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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add X account diagnostics to Comms
[._.]/ Adam Eivy33fba73e6de4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8598d31c97..1f68a3c29a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@- **[issue-3606] A Review Loop reviewer whose CLI isn't installed is now flagged up front.** Previously the only way to find out a configured reviewer (Claude, Antigravity, Codex, or Grok) couldn't actually run was to wait for the review loop itself to discover its command was missing — after PortOS had already opened the PR and spent an agent run. The Code Review Defaults panel, task form, schedule config, and `/do:next` run drawer now show a "not installed" badge next to any reviewer whose CLI binary isn't found on this machine. It's informational only — the reviewer stays selectable, since a federated peer machine (or a later install) may still be able to run it.## Added+- **X account diagnostics and review-gated compose handoffs.** Comms now has an X page that stores bounded public snapshots, checks profile/search visibility and post reach through the managed browser, captures visible metrics, and routes drafts through Review Hub before opening X for a final manual submission. It does not store X credentials, post automatically, or claim that ordinary low reach proves a shadowban.- **The claim-issue author gate has a "Me + collaborators" setting.** Until now the only way to let an agent work on a teammate's issue was "Any author", which also opens the queue to drive-by issues from strangers — so a repo with any real collaborators had to choose between ignoring their issues and claiming everyone's. The new option trusts you plus every account the forge already grants access to (GitHub collaborators, GitLab project members including group-inherited ones), which is the same set that could push the code anyway. It sits between "Filed by me only" (still the default) and "Any author" in the CoS → Schedule author-filter dropdown, in the per-app override, and in the `/do:next` run drawer, and applies to `claim-issue` and `claim-work` alike. Neither CLI's `--author` flag accepts more than one account, so the gate is applied to the issue listing rather than pushed into the query — both the work detector and the agent prompt resolve the trusted set first, then filter. If that lookup fails (a token without push access can't read the collaborator list), PortOS reports it and retries rather than quietly narrowing back to your own issues or widening to everybody — and because that failure repeats identically on every retry, both the run drawer and the "Run now" toast name the filter and the way out instead of the generic "try again shortly".## Documentationdiff --git a/client/src/App.jsx b/client/src/App.jsxindex 46c3f0c49d..0ac40a6cf5 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -31,6 +31,7 @@ const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetaconst CalendarPage = lazyWithReload(() => import('./pages/Calendar'));const Messages = lazyWithReload(() => import('./pages/Messages'));const StackerNews = lazyWithReload(() => import('./pages/StackerNews'));+const XPage = lazyWithReload(() => import('./pages/X'));const IMessage = lazyWithReload(() => import('./pages/IMessage'));const Tribe = lazyWithReload(() => import('./pages/Tribe'));const Timeline = lazyWithReload(() => import('./pages/Timeline'));@@ -317,6 +318,8 @@ export default function App() {<Route path="messages/:tab" element={<Messages />} /><Route path="stacker-news" element={<StackerNews />} /><Route path="stacker-news/:accountId/:tab" element={<StackerNews />} />+ <Route path="x" element={<XPage />} />+ <Route path="x/:accountId/:tab" element={<XPage />} />{/* Legacy /imessage → Comms Messages → iMessage tab */}<Route path="imessage" element={<Navigate to="/messages/imessage" replace />} /><Route path="imessage/:chatKey" element={<IMessage />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex b9cf2eff23..3a8ce70d82 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -96,7 +96,8 @@ import {PersonStanding,Box,Boxes,- Gamepad2+ Gamepad2,+ AtSign} from 'lucide-react';// `__APP_VERSION__` is a Vite build-time define (see vite.config.js). Biome does// not honour ESLint-style "global" block comments, so it is declared in@@ -217,6 +218,7 @@ const navItems = [{ to: '/messages/inbox', label: 'Inbox', icon: Inbox },{ to: '/stacker-news', label: 'Stacker News', icon: Newspaper },{ to: '/messages/sync', label: 'Sync', icon: RefreshCw },+ { to: '/x', label: 'X', icon: AtSign },],},{diff --git a/client/src/pages/X.jsx b/client/src/pages/X.jsxnew file mode 100644index 0000000000..ed715786f6--- /dev/null+++ b/client/src/pages/X.jsx@@ -0,0 +1,250 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useNavigate, useParams, useSearchParams } from 'react-router';+import { AtSign, BarChart3, Check, ExternalLink, FilePen, Plus, RefreshCw, ShieldAlert, X as XIcon } from 'lucide-react';+import * as api from '../services/api';+import Drawer from '../components/Drawer';+import PageHeader from '../components/PageHeader';+import PageSkeleton from '../components/ui/PageSkeleton';+import TabPills from '../components/ui/TabPills';+import { useValidTab } from '../hooks/useValidTab';++const TABS = [+ { id: 'health', label: 'Reach & health', icon: BarChart3 },+ { id: 'posts', label: 'Posts', icon: AtSign },+ { id: 'drafts', label: 'Drafts', icon: FilePen },+ { id: 'accounts', label: 'Accounts & safety', icon: ShieldAlert },+];+const emptyAccount = { label: '', username: '', enabled: true, notes: '' };+const fieldClass = 'w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white';+const buttonClass = 'rounded bg-port-accent px-3 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50';+const secondaryButton = 'rounded border border-port-border px-3 py-2 text-sm text-gray-200 disabled:cursor-not-allowed disabled:opacity-50';++const sameAccount = (left, right) => JSON.stringify(left) === JSON.stringify(right);+const formatCount = (value) => Number.isInteger(value) ? value.toLocaleString() : '—';+const formatDate = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : '—';+const stateLabel = (state) => ({ draft: 'Draft', pending_review: 'Awaiting review', approved: 'Approved', rejected: 'Rejected', opened: 'Opened in X' }[state] || state);+const normalizeHandle = (value) => String(value || '').trim().replace(/^@/, '');++function StatusBadge({ value, children }) {+ const classes = value === true+ ? 'border-port-success/40 bg-port-success/10 text-port-success'+ : value === false+ ? 'border-port-error/40 bg-port-error/10 text-port-error'+ : 'border-port-warning/40 bg-port-warning/10 text-port-warning';+ return <span className={`inline-flex items-center gap-1 rounded border px-2 py-1 text-xs ${classes}`}>{value === true ? <Check size={13} /> : value === false ? <XIcon size={13} /> : null}{children}</span>;+}++export default function XPage() {+ const navigate = useNavigate();+ const { accountId } = useParams();+ const activeRouteTab = useValidTab(TABS, 'health');+ const [searchParams, setSearchParams] = useSearchParams();+ const [accounts, setAccounts] = useState([]);+ const [posts, setPosts] = useState([]);+ const [drafts, setDrafts] = useState([]);+ const [resourcesAccountId, setResourcesAccountId] = useState(null);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState('');+ const [error, setError] = useState('');+ const [notice, setNotice] = useState('');+ const [accountForm, setAccountForm] = useState(emptyAccount);+ const [savedAccountForm, setSavedAccountForm] = useState(emptyAccount);+ const [accountFormError, setAccountFormError] = useState('');+ const [deleteAccountId, setDeleteAccountId] = useState(null);+ const [draftBody, setDraftBody] = useState('');+ const selectedLoadRef = useRef(0);+ const currentAccountIdRef = useRef(accountId);+ const selectedAccountIdRef = useRef(null);+ const savedAccountRef = useRef(emptyAccount);+ currentAccountIdRef.current = accountId;++ const selected = accounts.find((account) => account.id === accountId) || null;+ const activeTab = selected ? activeRouteTab : 'accounts';+ const accountPath = (id, tab = activeRouteTab) => `/x/${id}/${tab}`;+ const accountFormMode = searchParams.get('xAccount');+ const accountDrawerOpen = accountFormMode === 'new' || (accountFormMode === 'edit' && Boolean(selected));+ const accountFormDirty = accountFormMode === 'edit' && !sameAccount(accountForm, savedAccountForm);+ const visiblePosts = resourcesAccountId === accountId ? posts : [];+ const visibleDrafts = resourcesAccountId === accountId ? drafts : [];++ const openAccountForm = useCallback((mode) => {+ setAccountFormError('');+ setSearchParams((previous) => {+ const next = new URLSearchParams(previous);+ if (mode) next.set('xAccount', mode);+ else next.delete('xAccount');+ return next;+ }, { replace: true });+ }, [setSearchParams]);+ const closeAccountForm = useCallback(() => openAccountForm(null), [openAccountForm]);++ const loadAccounts = useCallback(async () => {+ const result = await api.getXAccounts({ silent: true }).catch((err) => ({ error: err.message, accounts: [] }));+ if (result.error) setError(result.error);+ setAccounts(result.accounts || []);+ setLoading(false);+ }, []);++ const loadSelected = useCallback(async () => {+ const requestId = ++selectedLoadRef.current;+ const requestedAccountId = accountId;+ setResourcesAccountId(null);+ setPosts([]);+ setDrafts([]);+ if (!accountId) return;+ const [postResult, draftResult] = await Promise.all([+ api.getXPosts(accountId, { silent: true }).catch((err) => ({ error: err.message, posts: [] })),+ api.getXDrafts(accountId, { silent: true }).catch((err) => ({ error: err.message, drafts: [] })),+ ]);+ if (selectedLoadRef.current !== requestId || currentAccountIdRef.current !== requestedAccountId) return;+ const failed = [postResult, draftResult].find((result) => result.error);+ if (failed) setError(failed.error);+ setPosts(postResult.posts || []);+ setDrafts(draftResult.drafts || []);+ setResourcesAccountId(requestedAccountId);+ }, [accountId]);++ useEffect(() => { loadAccounts(); }, [loadAccounts]);+ useEffect(() => { loadSelected(); }, [loadSelected]);+ useEffect(() => {+ if (!selected) {+ selectedAccountIdRef.current = null;+ return;+ }+ const next = { label: selected.label, username: selected.username, enabled: selected.enabled, notes: selected.notes || '' };+ const switched = selectedAccountIdRef.current !== selected.id;+ setAccountForm((current) => switched || sameAccount(current, savedAccountRef.current) ? next : current);+ setSavedAccountForm(next);+ savedAccountRef.current = next;+ selectedAccountIdRef.current = selected.id;+ }, [selected]);++ const finish = (key, promise, onSuccess) => {+ setBusy(key);+ setError('');+ setNotice('');+ promise.then(onSuccess, (err) => setError(err.message)).finally(() => setBusy(''));+ };++ const updateAccountForm = (key, value) => setAccountForm((previous) => ({ ...previous, [key]: value }));+ const saveAccount = (event) => {+ event.preventDefault();+ const label = accountForm.label.trim();+ const username = normalizeHandle(accountForm.username);+ if (!label || !username) {+ setAccountFormError('A local label and X username are required.');+ return;+ }+ setAccountFormError('');+ const payload = { label, username, enabled: accountForm.enabled, notes: accountForm.notes };+ if (accountFormMode === 'edit' && selected) {+ const savedId = selected.id;+ finish('save-account', api.updateXAccount(savedId, payload, { silent: true }), (result) => {+ setAccounts((previous) => previous.map((candidate) => candidate.id === result.id ? result : candidate));+ if (currentAccountIdRef.current === savedId) {+ const next = { label: result.label, username: result.username, enabled: result.enabled, notes: result.notes || '' };+ setAccountForm(next);+ setSavedAccountForm(next);+ savedAccountRef.current = next;+ }+ closeAccountForm();+ setNotice('X account settings saved.');+ });+ return;+ }+ finish('create-account', api.createXAccount(payload, { silent: true }), (result) => {+ setAccounts((previous) => [...previous, result]);+ setAccountForm(emptyAccount);+ closeAccountForm();+ navigate(accountPath(result.id, 'health'));+ setNotice('X account added.');+ });+ };++ const removeAccount = (id) => finish(`delete-account-${id}`, api.deleteXAccount(id, { silent: true }), () => {+ setAccounts((previous) => previous.filter((candidate) => candidate.id !== id));+ setDeleteAccountId(null);+ if (id === accountId) navigate('/x');+ setNotice('X account removed.');+ });++ const sync = () => selected && finish('sync', api.syncXAccount(selected.id, { silent: true }), (result) => {+ setAccounts((previous) => previous.map((candidate) => candidate.id === result.account.id ? result.account : candidate));+ setPosts(result.posts || []);+ setResourcesAccountId(selected.id);+ setNotice(`Diagnostic complete: ${result.ingested} public post(s) captured.`);+ });++ const openDestination = (kind) => selected && finish(`open-${kind}`, api.openXAccountDestination(selected.id, kind, { silent: true }), () => {+ setNotice('Opened the requested X page in the managed browser.');+ });++ const createDraft = (event) => {+ event.preventDefault();+ if (!selected || !draftBody.trim()) return;+ finish('create-draft', api.createXDraft({ accountId: selected.id, body: draftBody.trim() }, { silent: true }), (result) => {+ setDrafts((previous) => [result, ...previous]);+ setDraftBody('');+ setNotice('Draft saved locally. Submit it for review when you are ready.');+ });+ };++ const reviewDraft = (draft, state) => finish(`review-${draft.id}`, api.reviewXDraft(draft.id, { state }, { silent: true }), (result) => {+ setDrafts((previous) => previous.map((candidate) => candidate.id === result.id ? result : candidate));+ setNotice(state === 'pending_review' ? 'Draft submitted to Review Hub.' : `Draft ${state}.`);+ });++ const openDraft = (draft) => finish(`open-draft-${draft.id}`, api.openXDraft(draft.id, { silent: true }), (result) => {+ setDrafts((previous) => previous.map((candidate) => candidate.id === result.id ? result : candidate));+ setNotice('Opened the approved draft in X for a final manual check. Nothing was posted.');+ });++ const accountSwitcher = <div className="flex flex-wrap items-center gap-2">+ <label htmlFor="x-account-switcher" className="sr-only">X account in scope</label>+ <select id="x-account-switcher" className={`${fieldClass} w-auto min-w-48`} value={selected?.id || ''} onChange={(event) => navigate(event.target.value ? accountPath(event.target.value) : '/x')}>+ <option value="">Choose an X account</option>+ {accounts.map((account) => <option key={account.id} value={account.id}>@{account.username}</option>)}+ </select>+ <button type="button" className={secondaryButton} onClick={() => { setAccountForm(emptyAccount); openAccountForm('new'); }}><Plus size={15} className="mr-1 inline" />Add account</button>+ </div>;++ const renderHealth = () => {+ const snapshot = selected?.profileSnapshot || {};+ const profile = snapshot.profile || {};+ const checks = snapshot.diagnostics || {};+ const checkRows = [+ { label: 'Public profile reachable', value: checks.profilePublic, detail: 'The profile page returned the configured handle.' },+ { label: 'Exact account search', value: checks.appearsInPeopleSearch, detail: 'The handle appeared in X People search.' },+ { label: 'Recent posts in Latest search', value: checks.recentPostsInLatestSearch, detail: `${formatCount(checks.latestSearchPostCount)} matching original post(s) were returned.` },+ { label: 'Recommendation eligibility', value: null, detail: 'X does not expose a public yes/no recommendation-eligibility signal here.' },+ ];+ return <div className="space-y-4">+ <section className="rounded border border-port-border bg-port-card p-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div><h2 className="font-semibold text-white">Reach diagnostics for @{selected.username}</h2><p className="mt-1 text-sm text-gray-400">Read-only checks of the public profile, X search, and visible post metrics.</p></div>+ <div className="flex flex-wrap gap-2"><button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={sync}><RefreshCw size={15} className="mr-1 inline" />Run diagnostic</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('profile')}><ExternalLink size={15} className="mr-1 inline" />Open profile</button></div>+ </div>+ {!selected.profileSnapshot?.diagnostics && <div className="mt-4 rounded border border-port-warning/40 bg-port-warning/10 p-3 text-sm text-port-warning">No snapshot yet. Run a diagnostic to capture the evidence PortOS can verify.</div>}+ <div className="mt-4 grid gap-3 sm:grid-cols-4">+ {[['Followers', profile.followers], ['Following', profile.following], ['Lifetime posts', profile.postCount], ['Captured posts', visiblePosts.length]].map(([label, value]) => <div key={label} className="rounded border border-port-border p-3"><div className="text-xs uppercase tracking-wide text-gray-500">{label}</div><div className="mt-1 text-2xl font-semibold text-white">{formatCount(value)}</div></div>)}+ </div>+ <div className="mt-4 grid gap-2 md:grid-cols-2">+ {checkRows.map((check) => <div key={check.label} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2"><span className="text-sm text-gray-200">{check.label}</span><StatusBadge value={check.value}>{check.value === true ? 'Observed' : check.value === false ? 'Not observed' : 'Unknown'}</StatusBadge></div><p className="mt-2 text-xs text-gray-500">{check.detail}</p></div>)}+ </div>+ {selected.lastSyncAt && <p className="mt-3 text-xs text-gray-500">Last checked {formatDate(selected.lastSyncAt)}{selected.lastError ? ` · Last error: ${selected.lastError}` : ''}</p>}+ </section>+ <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">What this can and cannot conclude</h2><div className="mt-2 space-y-2 text-sm text-gray-300"><p>These checks rule out several hard visibility failures: the profile is public, the handle is searchable, and recent posts are returned in Latest search when a snapshot succeeds.</p><p>They cannot prove that X is recommending the account in Home or Explore. PortOS intentionally reports that as unknown instead of calling ordinary low reach a shadowban.</p><p className="text-gray-400">Automatic posting, follow/unfollow behavior, and background AI activity are off. Approved drafts only open X’s compose screen for a final human check.</p></div><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('people')}>Open account search</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('latest')}>Open Latest search</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('settings')}>Open X account settings</button></div></section>+ </div>;+ };++ const renderPosts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">Captured post reach</h2><p className="mt-1 text-sm text-gray-400">Public metrics from the last browser diagnostic; counts are impressions, not unique people.</p></div><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={sync}><RefreshCw size={15} className="mr-1 inline" />Refresh</button></div>{!visiblePosts.length ? <p className="mt-4 text-sm text-gray-500">No captured posts yet. Run a diagnostic from Reach & health.</p> : <div className="mt-4 space-y-2">{visiblePosts.map((post) => <article key={post.id} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-500"><span>{post.kind === 'reply' ? 'Reply' : 'Post'} · {formatDate(post.remoteCreatedAt)}</span><span>{post.sourceUrl ? <a className="text-port-accent hover:underline" href={post.sourceUrl} target="_blank" rel="noreferrer">Open on X</a> : null}</span></div><p className="mt-2 whitespace-pre-wrap text-sm text-gray-200">{post.body || '(no text captured)'}</p><div className="mt-3 flex flex-wrap gap-3 text-xs text-gray-400"><span><strong className="text-white">{formatCount(post.impressions)}</strong> impressions</span><span><strong className="text-white">{formatCount(post.engagements)}</strong> engagements</span><span>{formatCount(post.likes)} likes</span><span>{formatCount(post.reposts)} reposts</span><span>{formatCount(post.replies)} replies</span></div></article>)}</div>}</section>;++ const renderDrafts = () => <div className="space-y-4"><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Draft a post for review</h2><p className="mt-1 text-sm text-gray-400">Drafts stay local until you submit them to Review Hub. PortOS will never publish automatically.</p><form className="mt-3 space-y-3" onSubmit={createDraft}><label htmlFor="x-draft-body" className="sr-only">X draft text</label><textarea id="x-draft-body" className={fieldClass} rows="5" maxLength="4000" placeholder="Write something you actually want to say…" value={draftBody} onChange={(event) => setDraftBody(event.target.value)} /><div className="flex flex-wrap items-center justify-between gap-2"><span className="text-xs text-gray-500">{draftBody.length}/4000</span><button className={buttonClass} disabled={!draftBody.trim() || Boolean(busy)}>Save draft</button></div></form></section><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Draft queue</h2>{!visibleDrafts.length ? <p className="mt-3 text-sm text-gray-500">No drafts for @{selected.username}.</p> : <div className="mt-3 space-y-2">{visibleDrafts.map((draft) => <article key={draft.id} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2"><StatusBadge value={draft.state === 'approved' || draft.state === 'opened'}>{stateLabel(draft.state)}</StatusBadge><span className="text-xs text-gray-500">{formatDate(draft.updatedAt)}</span></div><p className="mt-3 whitespace-pre-wrap text-sm text-gray-200">{draft.body}</p><div className="mt-3 flex flex-wrap gap-2">{draft.state === 'draft' && <button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'pending_review')}>Submit for review</button>}{draft.state === 'pending_review' && <><button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'approved')}>Approve</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'rejected')}>Reject</button></>}{draft.state === 'approved' && <button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={() => openDraft(draft)}><ExternalLink size={15} className="mr-1 inline" />Open compose in X</button>}{draft.reviewNote && <span className="self-center text-xs text-gray-500">{draft.reviewNote}</span>}</div></article>)}</div>}</section></div>;++ const renderAccounts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">X accounts</h2><p className="mt-1 text-sm text-gray-400">Browser-only diagnostics and review-gated compose handoffs. No X credentials are stored.</p></div><button type="button" className={buttonClass} onClick={() => { setAccountForm(emptyAccount); openAccountForm('new'); }}><Plus size={15} className="mr-1 inline" />Add account</button></div>{!accounts.length ? <div className="mt-4 rounded border border-port-border p-4 text-sm text-gray-400">Add an X account to begin. Sync is manual, so nothing contacts X at boot.</div> : <div className="mt-4 grid gap-3 md:grid-cols-2">{accounts.map((account) => <article key={account.id} className="rounded border border-port-border p-4"><div className="flex items-start justify-between gap-2"><div><h3 className="font-semibold text-white">{account.label}</h3><p className="text-sm text-gray-400">@{account.username}</p></div><StatusBadge value={account.enabled}>{account.enabled ? 'Enabled' : 'Disabled'}</StatusBadge></div><p className="mt-3 text-xs text-gray-500">{account.lastSyncAt ? `Last diagnostic ${formatDate(account.lastSyncAt)}` : 'No diagnostic yet'}</p><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} onClick={() => { setAccountForm({ label: account.label, username: account.username, enabled: account.enabled, notes: account.notes || '' }); openAccountForm('edit'); }}>Edit</button><button type="button" className={secondaryButton} onClick={() => navigate(accountPath(account.id, 'health'))}>Open</button>{deleteAccountId === account.id ? <><button type="button" className="rounded border border-port-error px-3 py-2 text-sm text-port-error disabled:opacity-50" disabled={Boolean(busy)} onClick={() => removeAccount(account.id)}>Delete</button><button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(null)}>Cancel</button></> : <button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(account.id)}>Remove</button>}</div></article>)}</div>}</section>;++ const accountDrawer = <Drawer open={accountDrawerOpen} onClose={closeAccountForm} title={accountFormMode === 'edit' ? 'Edit X account' : 'Add X account'} subtitle="Read-only diagnostics with human-reviewed drafts" size="md"><form className="space-y-4" onSubmit={saveAccount}><label className="block text-sm text-gray-300" htmlFor="x-account-label">Local label<input id="x-account-label" className={`${fieldClass} mt-1`} required value={accountForm.label} onChange={(event) => updateAccountForm('label', event.target.value)} /></label><label className="block text-sm text-gray-300" htmlFor="x-account-username">X username<input id="x-account-username" className={`${fieldClass} mt-1`} required placeholder="example_user" value={accountForm.username} onChange={(event) => updateAccountForm('username', event.target.value)} /><span className="mt-1 block text-xs text-gray-500">Enter the handle without or with @. PortOS normalizes it.</span></label><label className="block text-sm text-gray-300" htmlFor="x-account-notes">Notes<textarea id="x-account-notes" className={`${fieldClass} mt-1`} rows="4" value={accountForm.notes} onChange={(event) => updateAccountForm('notes', event.target.value)} /></label><label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="x-account-enabled"><input id="x-account-enabled" type="checkbox" checked={accountForm.enabled} onChange={(event) => updateAccountForm('enabled', event.target.checked)} /> Allow diagnostics and compose handoffs</label><div className="rounded border border-port-border bg-port-bg p-3 text-xs text-gray-400">The managed browser reads public X pages. PortOS does not store your X password or API token, does not run background posting, and only opens an approved draft for final manual submission.</div>{accountFormError && <p className="text-sm text-port-error">{accountFormError}</p>}<div className="flex justify-end gap-2"><button type="button" className={secondaryButton} onClick={closeAccountForm}>Cancel</button><button className={buttonClass} disabled={Boolean(busy) || accountFormDirty && accountFormMode === 'edit' && !accountForm.label.trim()}>{accountFormMode === 'edit' ? 'Save account' : 'Add account'}</button></div></form></Drawer>;++ if (loading) return <PageSkeleton header="bar" label="Loading X" tabs={TABS.length} cards={3} />;+ return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={AtSign} title="X" subtitle="Account health, reach diagnostics, and review-gated drafts" actions={accountSwitcher} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/x')} ariaLabel="X sections" /><main className="flex-1 overflow-auto p-4">{error && <div className="mb-3 rounded border border-port-error p-3 text-sm text-port-error">{error}</div>}{notice && <div className="mb-3 rounded border border-port-border p-3 text-sm text-gray-200">{notice}</div>}{!selected && accounts.length > 0 && <div className="mb-3 rounded border border-port-warning/40 bg-port-warning/10 p-3 text-sm text-port-warning">Choose an X account to view diagnostics and drafts.</div>}{activeTab === 'health' && selected && renderHealth()}{activeTab === 'posts' && selected && renderPosts()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'accounts' && renderAccounts()}{accountDrawer}</main></div>;+}diff --git a/client/src/pages/X.test.jsx b/client/src/pages/X.test.jsxnew file mode 100644index 0000000000..ebb9e28366--- /dev/null+++ b/client/src/pages/X.test.jsx@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';++const api = {+ getXAccounts: vi.fn(),+ getXPosts: vi.fn(),+ getXDrafts: vi.fn(),+ createXAccount: vi.fn(),+ updateXAccount: vi.fn(),+ deleteXAccount: vi.fn(),+ syncXAccount: vi.fn(),+ openXAccountDestination: vi.fn(),+ createXDraft: vi.fn(),+ reviewXDraft: vi.fn(),+ openXDraft: vi.fn(),+};+vi.mock('../services/api', () => api);++const { default: XPage } = await import('./X.jsx');++const account = {+ id: '00000000-0000-4000-8000-000000000001',+ label: 'Personal X',+ username: 'example_user',+ enabled: true,+ notes: '',+ profileSnapshot: {+ profile: { followers: 1296, following: 1777, postCount: 7473 },+ diagnostics: {+ profilePublic: true,+ appearsInPeopleSearch: true,+ recentPostsInLatestSearch: true,+ latestSearchPostCount: 2,+ },+ },+ lastSyncAt: '2026-08-05T12:00:00.000Z',+ lastError: '',+};++function LocationProbe() {+ const location = useLocation();+ return <div data-testid="location">{`${location.pathname}${location.search}`}</div>;+}++function renderPage(path) {+ return render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/x" element={<XPage />} />+ <Route path="/x/:accountId/:tab" element={<XPage />} />+ </Routes>+ <LocationProbe />+ </MemoryRouter>,+ );+}++describe('X page', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getXAccounts.mockResolvedValue({ accounts: [account] });+ api.getXPosts.mockResolvedValue({ posts: [] });+ api.getXDrafts.mockResolvedValue({ drafts: [] });+ });++ it('deep-links to an account and reports verified reach checks without claiming recommendation status', async () => {+ renderPage(`/x/${account.id}/health`);+ expect(await screen.findByRole('heading', { name: 'Reach diagnostics for @example_user' })).toBeInTheDocument();+ expect(screen.getByText('Public profile reachable')).toBeInTheDocument();+ expect(screen.getByText('Exact account search')).toBeInTheDocument();+ expect(screen.getByText('Recommendation eligibility')).toBeInTheDocument();+ expect(screen.getByText('Unknown')).toBeInTheDocument();+ expect(screen.getByTestId('location')).toHaveTextContent(`/x/${account.id}/health`);+ });++ it('runs a manual diagnostic and keeps publishing out of the page workflow', async () => {+ const user = userEvent.setup();+ api.syncXAccount.mockResolvedValue({ account: { ...account, lastSyncAt: '2026-08-05T13:00:00.000Z' }, posts: [], ingested: 2 });+ renderPage(`/x/${account.id}/health`);+ await screen.findByRole('heading', { name: 'Reach diagnostics for @example_user' });+ await user.click(screen.getByRole('button', { name: 'Run diagnostic' }));+ await waitFor(() => expect(api.syncXAccount).toHaveBeenCalledWith(account.id, { silent: true }));+ expect(screen.queryByRole('button', { name: /publish/i })).not.toBeInTheDocument();+ expect(screen.getByText(/Diagnostic complete/)).toBeInTheDocument();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex ebae8b76d3..5c4955fd61 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -81,6 +81,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCalendar.js` | Calendar events. || `apiMessages.js` | Messages / notifications + iMessage manager (#2413). || `apiStackerNews.js` | Stacker News account, territory, review-action, and safe analysis APIs. |+| `apiX.js` | X account diagnostics, public post metrics, review-gated drafts, and manual browser handoffs. || `apiContacts.js` | macOS Contacts sync + identity resolve + Tribe enrich (#2415). || `apiSignal.js` | Signal Desktop ingestion status / setup-check / sync. || `apiSpotify.js` | Spotify OAuth + listening-history sync. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 11f68150e3..989be41e98 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -26,6 +26,7 @@ export * from './apiAccounts.js';export * from './apiSchedules.js';export * from './apiMessages.js';export * from './apiStackerNews.js';+export * from './apiX.js';export * from './apiContacts.js';export * from './apiSignal.js';export * from './apiSpotify.js';diff --git a/client/src/services/apiX.js b/client/src/services/apiX.jsnew file mode 100644index 0000000000..5927b4ca8f--- /dev/null+++ b/client/src/services/apiX.js@@ -0,0 +1,14 @@+import { request } from './apiCore.js';++export const getXAccounts = (options = {}) => request('/x/accounts', options);+export const getXAccount = (id, options = {}) => request(`/x/accounts/${id}`, options);+export const createXAccount = (data, options = {}) => request('/x/accounts', { method: 'POST', body: JSON.stringify(data), ...options });+export const updateXAccount = (id, data, options = {}) => request(`/x/accounts/${id}`, { method: 'PATCH', body: JSON.stringify(data), ...options });+export const deleteXAccount = (id, options = {}) => request(`/x/accounts/${id}`, { method: 'DELETE', ...options });+export const syncXAccount = (id, options = {}) => request(`/x/accounts/${id}/sync`, { method: 'POST', ...options });+export const openXAccountDestination = (id, kind, options = {}) => request(`/x/accounts/${id}/open`, { method: 'POST', body: JSON.stringify({ kind }), ...options });+export const getXPosts = (accountId, options = {}) => request(`/x/accounts/${accountId}/posts`, options);+export const getXDrafts = (accountId, options = {}) => request(`/x/accounts/${accountId}/drafts`, options);+export const createXDraft = (data, options = {}) => request('/x/drafts', { method: 'POST', body: JSON.stringify(data), ...options });+export const reviewXDraft = (id, data, options = {}) => request(`/x/drafts/${id}/review`, { method: 'POST', body: JSON.stringify(data), ...options });+export const openXDraft = (id, options = {}) => request(`/x/drafts/${id}/open`, { method: 'POST', ...options });diff --git a/server/index.js b/server/index.jsindex 3d4a317df5..c722277a28 100644--- a/server/index.js+++ b/server/index.js@@ -61,6 +61,7 @@ import mediaRoutes from './routes/media.js';import calendarRoutes from './routes/calendar.js';import messagesRoutes from './routes/messages.js';import stackerNewsRoutes from './routes/stackerNews.js';+import xRoutes from './routes/x.js';import genomeRoutes from './routes/genome.js';import digitalTwinRoutes from './routes/digital-twin/index.js';import modelPersonalityRoutes from './routes/model-personality.js';@@ -301,6 +302,7 @@ app.use('/api/media', mediaRoutes);app.use('/api/calendar', calendarRoutes);app.use('/api/messages', messagesRoutes);app.use('/api/stacker-news', stackerNewsRoutes);+app.use('/api/x', xRoutes);app.use('/api/digital-twin/social-accounts', socialAccountsRoutes);app.use('/api/meatspace/genome', genomeRoutes);app.use('/api/digital-twin/identity', identityRoutes);diff --git a/server/integrations/x/README.md b/server/integrations/x/README.mdnew file mode 100644index 0000000000..9d85e2ade3--- /dev/null+++ b/server/integrations/x/README.md@@ -0,0 +1,11 @@+# X integration++The X integration is intentionally browser-only and read-only for remote data.+It collects public profile metadata, recent post metrics, and the two visible+search checks used by the Comms → X page. Drafts stay in PortOS until a human+reviews them; an approved draft can open X's compose screen for a final manual+check, but PortOS never submits the post.++Remote page content is treated as untrusted data. The closed browser readers+accept only named operations and fixed-origin URLs, bound extracted text and+metrics, and normalize the result again before persistence.diff --git a/server/integrations/x/browserReader.js b/server/integrations/x/browserReader.jsnew file mode 100644index 0000000000..6002eb04bd--- /dev/null+++ b/server/integrations/x/browserReader.js@@ -0,0 +1,178 @@+// Read-only X transport over the managed browser. The browser expression is a+// closed DOM projection: it does not accept selectors, scripts, or URLs from a+// caller, and its result is normalized again before it reaches the database.+import { isPrivateAddress } from '../../lib/safeUrlFetch.js';+import { navigateToUrlPinned } from '../../services/browserService.js';+import { fixedXUrl, verifyFinalXPath } from '../../services/xBrowser.js';++const SETTLE_MS = 1_500;+const MAX_POSTS = 100;+const MAX_BODY_LENGTH = 40_000;+const MAX_BIO_LENGTH = 2_000;++const POST_HELPERS = String.raw`+ const parseCount = (value) => {+ const match = String(value || '').replace(/,/g, '').match(/(\d+(?:\.\d+)?)(?:\s*([KMB]))?/i);+ if (!match) return null;+ const multiplier = { K: 1_000, M: 1_000_000, B: 1_000_000_000 }[String(match[2] || '').toUpperCase()] || 1;+ return Math.round(Number(match[1]) * multiplier);+ };+ const labelledCount = (article, pattern) => {+ const node = [...article.querySelectorAll('button, a')].find((candidate) => pattern.test(candidate.getAttribute('aria-label') || ''));+ return parseCount(node?.getAttribute('aria-label') || '0') || 0;+ };+ const postRows = () => [...document.querySelectorAll('article')].map((article) => {+ const statusLink = [...article.querySelectorAll('a[href]')].find((node) => /\/status\/\d+/.test(node.getAttribute('href') || ''));+ const analyticsLink = [...article.querySelectorAll('a[href]')].find((node) => /\/analytics$/.test(node.getAttribute('href') || ''));+ const handleLink = [...article.querySelectorAll('a[href]')].find((node) => /^@[A-Za-z0-9_]{1,15}$/.test((node.textContent || '').trim()));+ const time = article.querySelector('time');+ const textNodes = [...article.querySelectorAll('[data-testid="tweetText"]')].map((node) => node.innerText || '').filter(Boolean);+ const body = (textNodes.length ? textNodes.join('\n') : article.innerText || '').slice(0, ${MAX_BODY_LENGTH});+ const analyticsLabel = analyticsLink?.getAttribute('aria-label') || analyticsLink?.textContent || '';+ return {+ remoteId: statusLink?.getAttribute('href')?.match(/\/status\/(\d+)/)?.[1] || '',+ sourceUrl: statusLink ? new URL(statusLink.getAttribute('href'), location.origin).href : '',+ authorHandle: (handleLink?.textContent || '').trim().replace(/^@/, ''),+ body,+ kind: /Replying to/i.test(article.innerText || '') ? 'reply' : 'post',+ remoteCreatedAt: time?.getAttribute('datetime') || null,+ impressions: parseCount(analyticsLabel),+ replies: labelledCount(article, /Replies?\. Reply/i),+ reposts: labelledCount(article, /reposts?\. Repost/i),+ likes: labelledCount(article, /Likes?\. Like/i),+ bookmarks: labelledCount(article, /Bookmarks?\. Bookmark/i),+ };+ }).filter((post) => post.remoteId);+`;++export const PROFILE_EXPRESSION = `(() => {+ ${POST_HELPERS}+ const pageText = document.body.innerText || '';+ const links = [...document.querySelectorAll('a[href]')];+ const handleLink = links.find((node) => /^@[A-Za-z0-9_]{1,15}$/.test((node.textContent || '').trim()));+ const followerLink = links.find((node) => /\/(?:followers|verified_followers)$/.test(node.getAttribute('href') || ''));+ const followingLink = links.find((node) => /\/following$/.test(node.getAttribute('href') || ''));+ const parseProfileCount = (value) => {+ const match = String(value || '').replace(/,/g, '').match(/(\d+(?:\.\d+)?)(?:\s*([KMB]))?/i);+ if (!match) return null;+ const multiplier = { K: 1_000, M: 1_000_000, B: 1_000_000_000 }[String(match[2] || '').toUpperCase()] || 1;+ return Math.round(Number(match[1]) * multiplier);+ };+ const heading = [...document.querySelectorAll('main h2')].map((node) => (node.innerText || '').trim()).find((value) => value && !/posts?$/i.test(value));+ return {+ profile: {+ displayName: (heading || '').replace(/\s+Verified account$/i, '').trim(),+ username: (handleLink?.textContent || '').trim().replace(/^@/, ''),+ bio: (document.querySelector('[data-testid="UserDescription"]')?.innerText || '').slice(0, ${MAX_BIO_LENGTH}),+ followers: parseProfileCount(followerLink?.textContent),+ following: parseProfileCount(followingLink?.textContent),+ postCount: parseProfileCount(pageText.match(/([\d,.]+)\s+posts?/i)?.[1]),+ url: location.href,+ },+ posts: postRows(),+ };+})()`;++export const SEARCH_EXPRESSION = `(() => {+ ${POST_HELPERS}+ return { posts: postRows(), url: location.href };+})()`;++export const PEOPLE_EXPRESSION = `(() => ({+ handles: [...document.querySelectorAll('a[href]')]+ .map((node) => (node.textContent || '').trim().match(/^@([A-Za-z0-9_]{1,15})$/i)?.[1] || '')+ .filter(Boolean)+ .slice(0, 200),+ url: location.href,+}))()`;++const boundedString = (value, max) => typeof value === 'string' ? value.replace(/\0/g, '').slice(0, max) : '';+const nullableCount = (value) => Number.isInteger(value) && value >= 0 ? value : null;+const normalizedHandle = (value) => boundedString(value, 15).replace(/^@/, '').toLowerCase();++const normalizePost = (post) => {+ const remoteId = boundedString(post?.remoteId, 80);+ if (!remoteId || !/^\d+$/.test(remoteId)) return null;+ const sourceUrl = boundedString(post?.sourceUrl, 2_000);+ const safeUrl = /^https:\/\/x\.com\/status\/\d+$/.test(sourceUrl) ? sourceUrl : '';+ const replies = nullableCount(post?.replies) ?? 0;+ const reposts = nullableCount(post?.reposts) ?? 0;+ const likes = nullableCount(post?.likes) ?? 0;+ const bookmarks = nullableCount(post?.bookmarks) ?? 0;+ return {+ remoteId,+ kind: post?.kind === 'reply' ? 'reply' : 'post',+ body: boundedString(post?.body, MAX_BODY_LENGTH),+ sourceUrl: safeUrl,+ authorHandle: normalizedHandle(post?.authorHandle),+ remoteCreatedAt: typeof post?.remoteCreatedAt === 'string' ? post.remoteCreatedAt.slice(0, 64) : null,+ impressions: nullableCount(post?.impressions),+ engagements: replies + reposts + likes + bookmarks,+ replies,+ reposts,+ likes,+ bookmarks,+ };+};++const normalizePosts = (posts) => [...new Map((Array.isArray(posts) ? posts : [])+ .map(normalizePost)+ .filter(Boolean)+ .map((post) => [post.remoteId, post])).values()].slice(0, MAX_POSTS);++async function readPage(url, expression, expectedPath) {+ const page = await navigateToUrlPinned(url, {+ verifyRemoteIp: (ip) => !isPrivateAddress(ip),+ settleMs: SETTLE_MS,+ evaluateExpression: expression,+ });+ verifyFinalXPath(url, page.url);+ if (!page.evalResult || typeof page.evalResult !== 'object') throw new Error('Could not read X data from the managed browser');+ const landedPath = new URL(page.url).pathname.replace(/\/+$/, '').toLowerCase();+ if (expectedPath && landedPath !== expectedPath.replace(/\/+$/, '').toLowerCase()) throw new Error('X returned an unexpected page');+ return page.evalResult;+}++export async function readProfile(username) {+ const requested = username.trim();+ const result = await readPage(fixedXUrl('profile', requested), PROFILE_EXPRESSION, `/${requested}`);+ const profile = result.profile || {};+ const posts = normalizePosts(result.posts);+ return {+ profile: {+ displayName: boundedString(profile.displayName, 200),+ username: normalizedHandle(profile.username),+ bio: boundedString(profile.bio, MAX_BIO_LENGTH),+ followers: nullableCount(profile.followers),+ following: nullableCount(profile.following),+ postCount: nullableCount(profile.postCount),+ url: fixedXUrl('profile', requested),+ },+ posts,+ };+}++export async function readLatest(username) {+ const result = await readPage(fixedXUrl('latest', username), SEARCH_EXPRESSION, '/search');+ return { posts: normalizePosts(result.posts) };+}++export async function readPeople(username) {+ const result = await readPage(fixedXUrl('people', username), PEOPLE_EXPRESSION, '/search');+ const handles = [...new Set((Array.isArray(result.handles) ? result.handles : []).map(normalizedHandle).filter(Boolean))];+ return { handles, exactMatch: handles.includes(username.trim().toLowerCase()) };+}++const BROWSER_READS = Object.freeze({+ profile: ({ username }) => readProfile(username),+ latest: ({ username }) => readLatest(username),+ people: ({ username }) => readPeople(username),+});++export async function executeXBrowserRead(name, input = {}) {+ const read = BROWSER_READS[name];+ if (!read) throw new Error(`Unsupported X browser read: ${name}`);+ return read(input);+}++export const xBrowserReads = Object.freeze(Object.keys(BROWSER_READS));diff --git a/server/integrations/x/browserReader.test.js b/server/integrations/x/browserReader.test.jsnew file mode 100644index 0000000000..376fb128f1--- /dev/null+++ b/server/integrations/x/browserReader.test.js@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const navigateToUrlPinned = vi.fn();+vi.mock('../../services/browserService.js', () => ({ navigateToUrlPinned }));++const { readLatest, readPeople, readProfile } = await import('./browserReader.js');++const page = (url, evalResult) => ({ id: 'page-1', url, evalResult });++describe('X browser read transport', () => {+ beforeEach(() => {+ navigateToUrlPinned.mockReset();+ });++ it('reads a public profile from the fixed X origin and bounds the normalized shape', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://x.com/Example_User', {+ profile: {+ displayName: 'Example User',+ username: 'Example_User',+ bio: 'A public bio',+ followers: 1296,+ following: 1777,+ postCount: 7473,+ },+ posts: [{+ remoteId: '123',+ authorHandle: 'Example_User',+ body: 'A public post',+ sourceUrl: 'https://x.com/status/123',+ impressions: 382,+ replies: 1,+ reposts: 2,+ likes: 3,+ bookmarks: 4,+ }],+ }));++ await expect(readProfile('Example_User')).resolves.toEqual({+ profile: {+ displayName: 'Example User',+ username: 'example_user',+ bio: 'A public bio',+ followers: 1296,+ following: 1777,+ postCount: 7473,+ url: 'https://x.com/Example_User',+ },+ posts: [expect.objectContaining({+ remoteId: '123',+ kind: 'post',+ engagements: 10,+ sourceUrl: 'https://x.com/status/123',+ })],+ });+ expect(navigateToUrlPinned).toHaveBeenCalledWith('https://x.com/Example_User', expect.objectContaining({+ evaluateExpression: expect.stringContaining('querySelectorAll'),+ }));+ });++ it('keeps account search and latest search as separate fixed, read-only operations', async () => {+ navigateToUrlPinned+ .mockResolvedValueOnce(page('https://x.com/search?q=example_user&src=typed_query&f=user', { handles: ['example_user', 'another_user'] }))+ .mockResolvedValueOnce(page('https://x.com/search?q=from%3Aexample_user+-filter%3Areplies&src=typed_query&f=live', {+ posts: [{ remoteId: '456', authorHandle: 'example_user', body: 'Latest post', sourceUrl: 'https://x.com/status/456' }],+ }));++ await expect(readPeople('example_user')).resolves.toEqual({ handles: ['example_user', 'another_user'], exactMatch: true });+ await expect(readLatest('example_user')).resolves.toEqual({ posts: [expect.objectContaining({ remoteId: '456', body: 'Latest post' })] });+ expect(navigateToUrlPinned.mock.calls[0][0]).toBe('https://x.com/search?q=example_user&src=typed_query&f=user');+ expect(navigateToUrlPinned.mock.calls[1][0]).toBe('https://x.com/search?q=from%3Aexample_user+-filter%3Areplies&src=typed_query&f=live');+ });++ it('rejects off-origin or wrong-page browser results', async () => {+ navigateToUrlPinned.mockResolvedValueOnce(page('https://example.com/example_user', { profile: {} }));+ await expect(readProfile('example_user')).rejects.toThrow('left the fixed origin');++ navigateToUrlPinned.mockResolvedValueOnce(page('https://x.com/other', { profile: {} }));+ await expect(readProfile('example_user')).rejects.toThrow('different page than the one requested');+ });+});diff --git a/server/integrations/x/index.js b/server/integrations/x/index.jsnew file mode 100644index 0000000000..f18f692f39--- /dev/null+++ b/server/integrations/x/index.js@@ -0,0 +1,7 @@+export {+ executeXBrowserRead,+ readLatest,+ readPeople,+ readProfile,+ xBrowserReads,+} from './browserReader.js';diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 6ec9e7243f..3db45927ad 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -31,13 +31,14 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| `lora.js` | `loraDdl` | LoRA training runs || `privacy.js` | `privacyDdl` | Privacy suite — vault, consents, orgs, brokers, change events || `stackerNews.js` | `stackerNewsDdl` | Stacker News accounts, territories, untrusted-content analyses, and review-gated actions |+| `x.js` | `xDdl` | X account diagnostics, public post metrics, and review-gated drafts || `audit.js` | `auditDdl`, `auditedTables`, `buildAuditTriggers()` | `record_audit` table/function + per-table audit triggers |### Composer (`index.js`)- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `commissions`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →- `universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` →+ `universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →`audit` DDL → audit triggers).`ensureSchemaImpl()` calls these two builders and runs each list throughdiff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex d6da0e0351..2f439cc89b 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -26,6 +26,7 @@ import { writersRoomDdl } from './writersRoom.js';import { loraDdl } from './lora.js';import { privacyDdl } from './privacy.js';import { stackerNewsDdl } from './stackerNews.js';+import { xDdl } from './x.js';import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';export {@@ -43,6 +44,7 @@ export {loraDdl,privacyDdl,stackerNewsDdl,+ xDdl,auditDdl,auditedTables,buildAuditTriggers,@@ -75,6 +77,7 @@ export function buildCatalogDdl() {...loraDdl,...privacyDdl,...stackerNewsDdl,+ ...xDdl,...auditDdl,...buildAuditTriggers(),];diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex ba057234f2..d66fb2907b 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -27,7 +27,7 @@ import {const DOMAIN_ARRAYS = ['coreDdl', 'tribeDdl', 'humanActivityDdl', 'commissionsDdl','catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl',- 'libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl',+ 'libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl','auditDdl',];@@ -61,6 +61,7 @@ describe('db/schema barrel + composer (#2832)', () => {...schema.loraDdl,...schema.privacyDdl,...schema.stackerNewsDdl,+ ...schema.xDdl,...schema.auditDdl,...buildAuditTriggers(),];diff --git a/server/lib/db/schema/x.js b/server/lib/db/schema/x.jsnew file mode 100644index 0000000000..36d28bd3c1--- /dev/null+++ b/server/lib/db/schema/x.js@@ -0,0 +1,52 @@+// X account diagnostics and review-gated draft handoffs. Reads use the managed+// browser and store only bounded public snapshots; PortOS never stores an X+// password or publishes automatically.+export const xDdl = [+ `CREATE TABLE IF NOT EXISTS x_accounts (+ id UUID PRIMARY KEY,+ label TEXT NOT NULL,+ username TEXT NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ notes TEXT NOT NULL DEFAULT '',+ profile_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,+ last_sync_at TIMESTAMPTZ,+ last_error TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (username)+ )`,+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_x_accounts_username_ci ON x_accounts (LOWER(username))`,+ `CREATE TABLE IF NOT EXISTS x_posts (+ id UUID PRIMARY KEY,+ account_id UUID NOT NULL REFERENCES x_accounts (id) ON DELETE CASCADE,+ remote_id TEXT NOT NULL,+ kind TEXT NOT NULL DEFAULT 'post' CHECK (kind IN ('post','reply')),+ body TEXT NOT NULL DEFAULT '',+ source_url TEXT NOT NULL DEFAULT '',+ remote_created_at TIMESTAMPTZ,+ impressions INTEGER,+ engagements INTEGER,+ replies INTEGER NOT NULL DEFAULT 0,+ reposts INTEGER NOT NULL DEFAULT 0,+ likes INTEGER NOT NULL DEFAULT 0,+ bookmarks INTEGER NOT NULL DEFAULT 0,+ content_hash TEXT NOT NULL,+ received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (account_id, remote_id)+ )`,+ `CREATE INDEX IF NOT EXISTS idx_x_posts_account_received ON x_posts (account_id, received_at DESC)`,+ `CREATE TABLE IF NOT EXISTS x_drafts (+ id UUID PRIMARY KEY,+ account_id UUID NOT NULL REFERENCES x_accounts (id) ON DELETE CASCADE,+ body TEXT NOT NULL,+ state TEXT NOT NULL DEFAULT 'draft' CHECK (state IN ('draft','pending_review','approved','rejected','opened')),+ review_note TEXT NOT NULL DEFAULT '',+ result JSONB NOT NULL DEFAULT '{}'::jsonb,+ approved_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_x_drafts_account_state ON x_drafts (account_id, state, created_at DESC)`,+];diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 0798db3665..5c6ec1adea 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -107,6 +107,7 @@ export const NAV_COMMANDS = [{ id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Comms', aliases: ['messages-config', 'comms-config'], keywords: ['comms'] },{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Comms', aliases: ['messages-sync', 'comms-sync'], keywords: ['comms'] },{ id: 'nav.stacker-news', path: '/stacker-news', label: 'Stacker News', section: 'Comms', aliases: ['stacker-news', 'stacker', 'sn'], keywords: ['comms', 'community', 'territory', 'moderation', 'stewardship'] },+ { id: 'nav.x', path: '/x', label: 'X', section: 'Comms', aliases: ['x', 'x-com', 'twitter', 'comms-x'], keywords: ['comms', 'social', 'reach', 'engagement', 'shadowban', 'diagnostics'] },{ id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily', 'import', 'backfill', 'whatsapp', 'spotify', 'discord', 'youtube'] },{ id: 'nav.tribe', path: '/tribe', label: 'Tribe', section: 'Brain', aliases: ['tribe', 'relationships', 'relationship-manager', 'people'], keywords: ['dunbar', 'friends', 'family', 'network', 'social graph', 'care cadence'] },diff --git a/server/routes/x.js b/server/routes/x.jsnew file mode 100644index 0000000000..87d353d26e--- /dev/null+++ b/server/routes/x.js@@ -0,0 +1,112 @@+import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as x from '../services/x.js';++const router = Router();+const uuid = z.string().uuid();+const username = z.preprocess((value) => typeof value === 'string' ? value.trim().replace(/^@/, '') : value, z.string().regex(/^[A-Za-z0-9_]{1,15}$/, 'must be an X username'));+const accountSchema = z.object({+ label: z.string().trim().min(1).max(120),+ username,+ enabled: z.boolean().optional(),+ notes: z.string().max(4_000).optional(),+}).strict();+const accountUpdateSchema = accountSchema.partial().strict();+const draftSchema = z.object({ accountId: uuid, body: z.string().trim().min(1).max(4_000) }).strict();+const reviewSchema = z.object({ state: z.enum(['pending_review', 'approved', 'rejected']), reviewNote: z.string().max(2_000).optional() }).strict();+const handoffSchema = z.object({ kind: z.enum(['profile', 'latest', 'people', 'settings']) }).strict();++const requireId = (value, label = 'ID') => {+ if (!uuid.safeParse(value).success) throw new ServerError(`Invalid ${label}`, { status: 400 });+};+const emitChanged = (req, accountId) => req.app.get('io')?.emit('x:changed', { accountId });++router.get('/capabilities', (_req, res) => res.json({+ readTransport: 'managed-browser',+ reads: ['profile', 'latest', 'people'],+ writes: ['draft', 'manual-compose-handoff'],+ automaticPublishing: false,+}));++router.get('/accounts', asyncHandler(async (_req, res) => res.json({ accounts: await x.listAccounts() })));++router.post('/accounts', asyncHandler(async (req, res) => {+ const account = await x.createAccount(validateRequest(accountSchema, req.body));+ emitChanged(req, account.id);+ res.status(201).json(account);+}));++router.get('/accounts/:id', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ const account = await x.getAccount(req.params.id);+ if (!account) throw new ServerError('X account not found', { status: 404 });+ res.json(account);+}));++router.patch('/accounts/:id', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ const account = await x.updateAccount(req.params.id, validateRequest(accountUpdateSchema, req.body));+ if (!account) throw new ServerError('X account not found', { status: 404 });+ emitChanged(req, account.id);+ res.json(account);+}));++router.delete('/accounts/:id', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ if (!await x.deleteAccount(req.params.id)) throw new ServerError('X account not found', { status: 404 });+ emitChanged(req, req.params.id);+ res.status(204).send();+}));++router.post('/accounts/:id/sync', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ const result = await x.syncAccount(req.params.id);+ if (!result) throw new ServerError('X account not found', { status: 404 });+ emitChanged(req, req.params.id);+ res.json(result);+}));++router.post('/accounts/:id/open', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ const { kind } = validateRequest(handoffSchema, req.body);+ const result = await x.openAccountDestination(req.params.id, kind);+ if (!result) throw new ServerError('X account not found', { status: 404 });+ res.json(result);+}));++router.get('/accounts/:id/posts', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ res.json({ posts: await x.listPosts(req.params.id) });+}));++router.get('/accounts/:id/drafts', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'account ID');+ res.json({ drafts: await x.listDrafts(req.params.id) });+}));++router.post('/drafts', asyncHandler(async (req, res) => {+ const draft = await x.createDraft(validateRequest(draftSchema, req.body));+ emitChanged(req, draft.accountId);+ res.status(201).json(draft);+}));++router.post('/drafts/:id/review', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'draft ID');+ const { state, reviewNote } = validateRequest(reviewSchema, req.body);+ const draft = await x.reviewDraft(req.params.id, state, reviewNote);+ if (!draft) throw new ServerError('X draft is not in a reviewable state', { status: 409 });+ emitChanged(req, draft.accountId);+ res.json(draft);+}));++router.post('/drafts/:id/open', asyncHandler(async (req, res) => {+ requireId(req.params.id, 'draft ID');+ const draft = await x.openApprovedDraft(req.params.id);+ if (!draft) throw new ServerError('X draft is not approved or was already opened', { status: 409 });+ emitChanged(req, draft.accountId);+ res.json(draft);+}));++export default router;diff --git a/server/routes/x.test.js b/server/routes/x.test.jsnew file mode 100644index 0000000000..9804cb49c6--- /dev/null+++ b/server/routes/x.test.js@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const x = vi.hoisted(() => ({+ createAccount: vi.fn(),+ deleteAccount: vi.fn(),+ getAccount: vi.fn(),+ listAccounts: vi.fn(),+ listDrafts: vi.fn(),+ listPosts: vi.fn(),+ openAccountDestination: vi.fn(),+ openApprovedDraft: vi.fn(),+ reviewDraft: vi.fn(),+ syncAccount: vi.fn(),+ updateAccount: vi.fn(),+ createDraft: vi.fn(),+}));+vi.mock('../services/x.js', () => x);++import xRoutes from './x.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/x', xRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('X routes', () => {+ let app;++ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ x.listAccounts.mockResolvedValue([]);+ });++ it('exposes the supervised read/write capabilities', async () => {+ const response = await request(app).get('/api/x/capabilities');+ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({+ readTransport: 'managed-browser',+ automaticPublishing: false,+ writes: ['draft', 'manual-compose-handoff'],+ });+ });++ it('normalizes an @ handle and does not accept an arbitrary username', async () => {+ x.createAccount.mockResolvedValue({ id: '00000000-0000-4000-8000-000000000001', username: 'example_user' });+ const created = await request(app).post('/api/x/accounts').send({ label: 'Example', username: '@Example_User' });+ expect(created.status).toBe(201);+ expect(x.createAccount).toHaveBeenCalledWith(expect.objectContaining({ username: 'Example_User' }));++ const rejected = await request(app).post('/api/x/accounts').send({ label: 'Bad', username: 'not valid' });+ expect(rejected.status).toBe(400);+ expect(x.createAccount).toHaveBeenCalledTimes(1);+ });++ it('keeps browser handoffs behind the named destination allowlist', async () => {+ x.openAccountDestination.mockResolvedValue({ pageId: 'page-1', url: 'https://x.com/example_user' });+ const response = await request(app)+ .post('/api/x/accounts/00000000-0000-4000-8000-000000000001/open')+ .send({ kind: 'profile' });+ expect(response.status).toBe(200);+ expect(x.openAccountDestination).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000001', 'profile');++ const rejected = await request(app)+ .post('/api/x/accounts/00000000-0000-4000-8000-000000000001/open')+ .send({ kind: 'javascript' });+ expect(rejected.status).toBe(400);+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 3d7f8d7791..13ba0e725f 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1402,6 +1402,56 @@ CREATE TABLE IF NOT EXISTS stacker_news_action_events ();CREATE INDEX IF NOT EXISTS idx_stacker_news_action_events_action ON stacker_news_action_events (action_id, created_at ASC);+-- X account diagnostics and review-gated drafts. Reads use the managed browser;+-- no X password or publishing credential is stored here.+CREATE TABLE IF NOT EXISTS x_accounts (+ id UUID PRIMARY KEY,+ label TEXT NOT NULL,+ username TEXT NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ notes TEXT NOT NULL DEFAULT '',+ profile_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,+ last_sync_at TIMESTAMPTZ,+ last_error TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (username)+);+CREATE UNIQUE INDEX IF NOT EXISTS idx_x_accounts_username_ci ON x_accounts (LOWER(username));+CREATE TABLE IF NOT EXISTS x_posts (+ id UUID PRIMARY KEY,+ account_id UUID NOT NULL REFERENCES x_accounts (id) ON DELETE CASCADE,+ remote_id TEXT NOT NULL,+ kind TEXT NOT NULL DEFAULT 'post' CHECK (kind IN ('post','reply')),+ body TEXT NOT NULL DEFAULT '',+ source_url TEXT NOT NULL DEFAULT '',+ remote_created_at TIMESTAMPTZ,+ impressions INTEGER,+ engagements INTEGER,+ replies INTEGER NOT NULL DEFAULT 0,+ reposts INTEGER NOT NULL DEFAULT 0,+ likes INTEGER NOT NULL DEFAULT 0,+ bookmarks INTEGER NOT NULL DEFAULT 0,+ content_hash TEXT NOT NULL,+ received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ UNIQUE (account_id, remote_id)+);+CREATE INDEX IF NOT EXISTS idx_x_posts_account_received ON x_posts (account_id, received_at DESC);+CREATE TABLE IF NOT EXISTS x_drafts (+ id UUID PRIMARY KEY,+ account_id UUID NOT NULL REFERENCES x_accounts (id) ON DELETE CASCADE,+ body TEXT NOT NULL,+ state TEXT NOT NULL DEFAULT 'draft' CHECK (state IN ('draft','pending_review','approved','rejected','opened')),+ review_note TEXT NOT NULL DEFAULT '',+ result JSONB NOT NULL DEFAULT '{}'::jsonb,+ approved_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_x_drafts_account_state ON x_drafts (account_id, state, created_at DESC);+-- Deletion audit log (incident #1248-follow-up). Append-only forensic trail of-- every tombstone / un-tombstone / hard-delete of user-authored records, written-- by a DB trigger so it captures deletions from ANY source (app, a test suite'sdiff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 8251440682..ca46b46773 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -32,6 +32,7 @@ import * as proactiveAlerts from './proactiveAlerts.js';import * as backup from './backup.js';import * as identity from './identity.js';import * as stackerNews from './stackerNews.js';+import * as x from './x.js';import { promoteLatestAssistantTurn } from './askPromote.js';import { ServerError } from '../lib/errorHandler.js';@@ -257,6 +258,25 @@ const PRODUCERS = [};},},+ {+ source: 'x',+ label: 'X drafts',+ drillTo: '/x',+ async gather() {+ return x.listPendingReviewActions({ limit: PER_SOURCE_LIMIT * 2 });+ },+ map(draft) {+ return {+ id: `x:${draft.id}`,+ title: 'X draft awaiting review',+ summary: draft.payload?.body?.slice(0, 200) || '(empty draft)',+ timestamp: draft.createdAt || null,+ severity: 'normal',+ drillTo: `/x/${draft.accountId}/drafts`,+ meta: { account: draft.accountLabel || `@${draft.username}` },+ };+ },+ },{source: 'health',label: 'Health anomalies',diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex cedff8fc27..6221c409aa 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -16,6 +16,7 @@ const askPromote = { promoteLatestAssistantTurn: vi.fn() };// active goals so existing cases see the brain/task-only target list.const identity = { getGoals: vi.fn() };const stackerNews = { listPendingReviewActions: vi.fn() };+const x = { listPendingReviewActions: vi.fn() };vi.mock('./brain.js', () => brain);vi.mock('./askConversations.js', () => askConversations);@@ -26,6 +27,7 @@ vi.mock('./backup.js', () => backup);vi.mock('./identity.js', () => identity);vi.mock('./askPromote.js', () => askPromote);vi.mock('./stackerNews.js', () => stackerNews);+vi.mock('./x.js', () => x);const { buildQueue, resolveQueueItem, promoteAskQueueItem, __resetAlertsCache } = await import('./reviewQueue.js');@@ -39,6 +41,7 @@ function resetEmpty() {backup.getState.mockResolvedValue({ status: 'ok', error: null });identity.getGoals.mockResolvedValue({ goals: [] });stackerNews.listPendingReviewActions.mockResolvedValue([]);+ x.listPendingReviewActions.mockResolvedValue([]);}describe('reviewQueue.buildQueue', () => {@@ -81,6 +84,16 @@ describe('reviewQueue.buildQueue', () => {});});+ it('surfaces X drafts with an account-specific drill-down', async () => {+ x.listPendingReviewActions.mockResolvedValue([{ id: 'x1', accountId: 'a1', accountLabel: 'Example X account', username: 'example_user', payload: { body: 'A thoughtful draft' }, createdAt: '2026-06-03T11:00:00.000Z' }]);+ const queue = await buildQueue();+ expect(queue.items.find((item) => item.source === 'x')).toMatchObject({+ id: 'x:x1',+ drillTo: '/x/a1/drafts',+ sourceLabel: 'X drafts',+ });+ });+it('only surfaces unpromoted ask conversations that have an assistant answer', async () => {askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'has content', promoted: false, turnCount: 2, assistantTurnCount: 1, updatedAt: '2026-06-03T10:00:00.000Z' },diff --git a/server/services/x.js b/server/services/x.jsnew file mode 100644index 0000000000..55c7bab48a--- /dev/null+++ b/server/services/x.js@@ -0,0 +1,283 @@+import { createHash, randomUUID } from 'crypto';+import { query, withTransaction } from '../lib/db.js';+import { executeXBrowserRead } from '../integrations/x/index.js';+import { openXHandoff } from './xBrowser.js';++const USERNAME_PATTERN = /^[A-Za-z0-9_]{1,15}$/;+const DRAFT_STATES = new Set(['draft', 'pending_review', 'approved', 'rejected', 'opened']);+const MAX_DRAFT_AGE_MS = 24 * 60 * 60 * 1000;+const syncLocks = new Map();++const normalizeUsername = (value) => {+ const username = String(value || '').trim().replace(/^@/, '');+ if (!USERNAME_PATTERN.test(username)) throw new Error('Invalid X username');+ return username.toLowerCase();+};+const safeUsername = (value) => {+ const username = String(value || '').trim().replace(/^@/, '').toLowerCase();+ return USERNAME_PATTERN.test(username) ? username : '';+};++const boundedText = (value, max) => typeof value === 'string' ? value.replace(/\0/g, '').slice(0, max) : '';+const stableHash = (value) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');+const safeDate = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;++const accountView = (row) => ({+ id: row.id,+ label: row.label,+ username: row.username,+ enabled: row.enabled,+ notes: row.notes || '',+ profileSnapshot: row.profile_snapshot || {},+ lastSyncAt: row.last_sync_at,+ lastError: row.last_error || '',+ createdAt: row.created_at,+ updatedAt: row.updated_at,+});++const postView = (row) => ({+ id: row.id,+ accountId: row.account_id,+ remoteId: row.remote_id,+ kind: row.kind,+ body: row.body,+ sourceUrl: row.source_url,+ remoteCreatedAt: row.remote_created_at,+ impressions: row.impressions,+ engagements: row.engagements,+ replies: row.replies,+ reposts: row.reposts,+ likes: row.likes,+ bookmarks: row.bookmarks,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+});++const draftView = (row) => ({+ id: row.id,+ accountId: row.account_id,+ accountLabel: row.account_label || '',+ username: row.username || '',+ body: row.body,+ state: row.state,+ reviewNote: row.review_note || '',+ result: row.result || {},+ approvedAt: row.approved_at,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+});++const accountSelect = 'SELECT * FROM x_accounts';++export async function listAccounts() {+ const result = await query(`${accountSelect} ORDER BY created_at ASC`);+ return result.rows.map(accountView);+}++export async function getAccount(id) {+ const result = await query(`${accountSelect} WHERE id=$1`, [id]);+ return result.rows[0] ? accountView(result.rows[0]) : null;+}++async function getAccountRow(id, client = { query }) {+ const result = await client.query('SELECT * FROM x_accounts WHERE id=$1', [id]);+ return result.rows[0] || null;+}++export async function createAccount({ label, username, enabled = true, notes = '' }) {+ const id = randomUUID();+ await query(+ `INSERT INTO x_accounts (id,label,username,enabled,notes)+ VALUES ($1,$2,$3,$4,$5)`,+ [id, boundedText(label, 120).trim(), normalizeUsername(username), enabled, boundedText(notes, 4_000)],+ );+ console.log(`🐦 Added X account ${id}`);+ return getAccount(id);+}++export async function updateAccount(id, updates) {+ const existing = await getAccountRow(id);+ if (!existing) return null;+ await query(+ `UPDATE x_accounts SET label=$2,username=$3,enabled=$4,notes=$5,updated_at=NOW() WHERE id=$1`,+ [id, boundedText(updates.label ?? existing.label, 120).trim(), normalizeUsername(updates.username ?? existing.username), updates.enabled ?? existing.enabled, boundedText(updates.notes ?? existing.notes, 4_000)],+ );+ return getAccount(id);+}++export async function deleteAccount(id) {+ const result = await query('DELETE FROM x_accounts WHERE id=$1', [id]);+ return result.rowCount > 0;+}++export function deriveXDiagnostics({ accountUsername, profile = {}, latest = {}, people = {} }) {+ const configured = normalizeUsername(accountUsername);+ const profileUsername = safeUsername(profile.username);+ const latestPosts = Array.isArray(latest.posts) ? latest.posts : [];+ const matchingPosts = latestPosts.filter((post) => safeUsername(post.authorHandle) === configured);+ return {+ profilePublic: Boolean(profileUsername && profileUsername === configured),+ profileHandleMatches: Boolean(profileUsername && profileUsername === configured),+ appearsInPeopleSearch: people.exactMatch === true || (Array.isArray(people.handles) && people.handles.map(safeUsername).includes(configured)),+ recentPostsInLatestSearch: matchingPosts.length > 0,+ latestSearchPostCount: matchingPosts.length,+ recommendationEligibility: 'unknown',+ checkedAt: new Date().toISOString(),+ };+}++const normalizeRemotePost = (post) => ({+ remoteId: boundedText(post?.remoteId, 80),+ kind: post?.kind === 'reply' ? 'reply' : 'post',+ body: boundedText(post?.body, 40_000),+ sourceUrl: boundedText(post?.sourceUrl, 2_000),+ remoteCreatedAt: safeDate(post?.remoteCreatedAt),+ impressions: Number.isInteger(post?.impressions) ? post.impressions : null,+ engagements: Number.isInteger(post?.engagements) ? post.engagements : null,+ replies: Number.isInteger(post?.replies) ? post.replies : 0,+ reposts: Number.isInteger(post?.reposts) ? post.reposts : 0,+ likes: Number.isInteger(post?.likes) ? post.likes : 0,+ bookmarks: Number.isInteger(post?.bookmarks) ? post.bookmarks : 0,+});++const mergePosts = (...lists) => [...new Map(lists.flat().map(normalizeRemotePost).filter((post) => /^\d+$/.test(post.remoteId)).map((post) => [post.remoteId, post])).values()].slice(0, 100);++async function syncAccountUnlocked(accountId) {+ const account = await getAccountRow(accountId);+ if (!account) return null;+ if (!account.enabled) throw new Error('Selected X account is disabled');++ const [profileResult, latestResult, peopleResult] = await Promise.all([+ executeXBrowserRead('profile', { username: account.username }),+ executeXBrowserRead('latest', { username: account.username }),+ executeXBrowserRead('people', { username: account.username }),+ ]);+ const profile = profileResult.profile || {};+ const latestPosts = Array.isArray(latestResult.posts) ? latestResult.posts : [];+ const people = peopleResult || {};+ const diagnostics = deriveXDiagnostics({ accountUsername: account.username, profile, latest: { posts: latestPosts }, people });+ const snapshot = {+ profile,+ diagnostics,+ peopleSearch: { exactMatch: people.exactMatch === true },+ latestSearch: { postCount: diagnostics.latestSearchPostCount },+ };+ const posts = mergePosts(profileResult.posts || [], latestPosts);++ await withTransaction(async (client) => {+ for (const post of posts) {+ await client.query(+ `INSERT INTO x_posts+ (id,account_id,remote_id,kind,body,source_url,remote_created_at,impressions,engagements,replies,reposts,likes,bookmarks,content_hash)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)+ ON CONFLICT (account_id,remote_id) DO UPDATE SET kind=EXCLUDED.kind,body=EXCLUDED.body,+ source_url=EXCLUDED.source_url,remote_created_at=EXCLUDED.remote_created_at,+ impressions=EXCLUDED.impressions,engagements=EXCLUDED.engagements,replies=EXCLUDED.replies,+ reposts=EXCLUDED.reposts,likes=EXCLUDED.likes,bookmarks=EXCLUDED.bookmarks,+ content_hash=EXCLUDED.content_hash,received_at=NOW(),updated_at=NOW()`,+ [randomUUID(), accountId, post.remoteId, post.kind, post.body, post.sourceUrl, post.remoteCreatedAt,+ post.impressions, post.engagements, post.replies, post.reposts, post.likes, post.bookmarks, stableHash(post.body)],+ );+ }+ await client.query(+ `UPDATE x_accounts SET profile_snapshot=$2,last_sync_at=NOW(),last_error='',updated_at=NOW() WHERE id=$1`,+ [accountId, snapshot],+ );+ });+ const [nextAccount, nextPosts] = await Promise.all([getAccount(accountId), listPosts(accountId)]);+ return { account: nextAccount, posts: nextPosts, ingested: posts.length, diagnostics };+}++export async function syncAccount(accountId) {+ if (syncLocks.has(accountId)) return syncLocks.get(accountId);+ const run = syncAccountUnlocked(accountId)+ .catch(async (error) => {+ await query('UPDATE x_accounts SET last_error=$2,updated_at=NOW() WHERE id=$1', [accountId, boundedText(error.message, 2_000)]).catch(() => {});+ throw error;+ })+ .finally(() => syncLocks.delete(accountId));+ syncLocks.set(accountId, run);+ return run;+}++export async function listPosts(accountId) {+ const result = await query('SELECT * FROM x_posts WHERE account_id=$1 ORDER BY COALESCE(remote_created_at,received_at) DESC LIMIT 100', [accountId]);+ return result.rows.map(postView);+}++export async function openAccountDestination(accountId, kind) {+ const account = await getAccountRow(accountId);+ if (!account) return null;+ if (!['profile', 'latest', 'people', 'settings'].includes(kind)) throw new Error('Unsupported X handoff destination');+ const value = kind === 'settings' ? '' : account.username;+ return openXHandoff({ kind, value });+}++export async function listDrafts(accountId) {+ const result = await query(+ `SELECT d.*, a.label AS account_label, a.username+ FROM x_drafts d JOIN x_accounts a ON a.id=d.account_id+ WHERE d.account_id=$1 ORDER BY d.created_at DESC LIMIT 100`,+ [accountId],+ );+ return result.rows.map(draftView);+}++export async function createDraft({ accountId, body }) {+ const account = await getAccountRow(accountId);+ if (!account) throw new Error('X account not found');+ const result = await query(+ 'INSERT INTO x_drafts (id,account_id,body) VALUES ($1,$2,$3) RETURNING *',+ [randomUUID(), accountId, boundedText(body, 4_000).trim()],+ );+ return draftView({ ...result.rows[0], account_label: account.label, username: account.username });+}++export async function listPendingReviewActions({ limit = 50 } = {}) {+ const result = await query(+ `SELECT d.*, a.label AS account_label, a.username+ FROM x_drafts d JOIN x_accounts a ON a.id=d.account_id+ WHERE d.state='pending_review' ORDER BY d.created_at ASC LIMIT $1`,+ [limit],+ );+ return result.rows.map((row) => ({ ...draftView(row), kind: 'draft_post', payload: { body: row.body } }));+}++export async function reviewDraft(id, state, reviewNote = '') {+ if (!DRAFT_STATES.has(state) || !['pending_review', 'approved', 'rejected'].includes(state)) throw new Error('Unsupported X draft review state');+ const current = await query('SELECT * FROM x_drafts WHERE id=$1', [id]);+ const existing = current.rows[0];+ if (!existing) return null;+ const allowed = existing.state === 'draft' && state === 'pending_review'+ || existing.state === 'pending_review' && ['approved', 'rejected'].includes(state);+ if (!allowed) return null;+ const result = await query(+ `UPDATE x_drafts SET state=$2,review_note=$3,approved_at=CASE WHEN $2='approved' THEN NOW() ELSE approved_at END,updated_at=NOW()+ WHERE id=$1 RETURNING *`,+ [id, state, boundedText(reviewNote, 2_000)],+ );+ const row = result.rows[0];+ const account = await getAccountRow(row.account_id);+ return draftView({ ...row, account_label: account?.label, username: account?.username });+}++export async function openApprovedDraft(id) {+ const result = await query(+ `SELECT d.*, a.label AS account_label, a.username, a.enabled+ FROM x_drafts d JOIN x_accounts a ON a.id=d.account_id WHERE d.id=$1`,+ [id],+ );+ const draft = result.rows[0];+ if (!draft || draft.state !== 'approved') return null;+ if (!draft.approved_at || Date.now() - new Date(draft.approved_at).getTime() > MAX_DRAFT_AGE_MS) throw new Error('X draft approval is stale; review a fresh draft');+ if (!draft.enabled) throw new Error('Selected X account is disabled');+ const handoff = await openXHandoff({ kind: 'compose', value: draft.body });+ const updated = await query(+ `UPDATE x_drafts SET state='opened',result=$2,updated_at=NOW() WHERE id=$1 AND state='approved' RETURNING *`,+ [id, { handoffOpened: true, url: handoff.url }],+ );+ const opened = updated.rows[0];+ return opened ? draftView({ ...opened, account_label: draft.account_label, username: draft.username }) : null;+}++export const xDraftStates = [...DRAFT_STATES];diff --git a/server/services/x.test.js b/server/services/x.test.jsnew file mode 100644index 0000000000..d19d8e142a--- /dev/null+++ b/server/services/x.test.js@@ -0,0 +1,30 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../lib/db.js', () => ({ query: vi.fn(), withTransaction: vi.fn() }));+vi.mock('../integrations/x/index.js', () => ({ executeXBrowserRead: vi.fn() }));+vi.mock('./xBrowser.js', () => ({ openXHandoff: vi.fn() }));++const { deriveXDiagnostics } = await import('./x.js');++describe('X diagnostics', () => {+ it('distinguishes observable public/search reach from unknown recommendation eligibility', () => {+ const result = deriveXDiagnostics({+ accountUsername: '@Example_User',+ profile: { username: 'example_user' },+ latest: { posts: [+ { authorHandle: 'example_user', remoteId: '1' },+ { authorHandle: 'other_user', remoteId: '2' },+ ] },+ people: { handles: ['other_user', 'Example_User'] },+ });++ expect(result).toMatchObject({+ profilePublic: true,+ profileHandleMatches: true,+ appearsInPeopleSearch: true,+ recentPostsInLatestSearch: true,+ latestSearchPostCount: 1,+ recommendationEligibility: 'unknown',+ });+ });+});diff --git a/server/services/xBrowser.js b/server/services/xBrowser.jsnew file mode 100644index 0000000000..db48cecb26--- /dev/null+++ b/server/services/xBrowser.js@@ -0,0 +1,64 @@+import { isPrivateAddress } from '../lib/safeUrlFetch.js';+import { navigateToUrlPinned } from './browserService.js';++const ORIGIN = 'https://x.com';+const USERNAME_PATTERN = /^[A-Za-z0-9_]{1,15}$/;++const assertUsername = (username) => {+ if (typeof username !== 'string' || !USERNAME_PATTERN.test(username.trim())) {+ throw new Error('Invalid X username');+ }+ return username.trim();+};++export const xBrowserOrigin = ORIGIN;++export const fixedXUrl = (kind, value = '') => {+ if (kind === 'profile') return `${ORIGIN}/${encodeURIComponent(assertUsername(value))}`;+ if (kind === 'latest') {+ const url = new URL(`${ORIGIN}/search`);+ url.searchParams.set('q', `from:${assertUsername(value)} -filter:replies`);+ url.searchParams.set('src', 'typed_query');+ url.searchParams.set('f', 'live');+ return url.toString();+ }+ if (kind === 'people') {+ const url = new URL(`${ORIGIN}/search`);+ url.searchParams.set('q', assertUsername(value));+ url.searchParams.set('src', 'typed_query');+ url.searchParams.set('f', 'user');+ return url.toString();+ }+ if (kind === 'settings') return `${ORIGIN}/settings/account`;+ if (kind === 'compose') {+ const url = new URL(`${ORIGIN}/compose/post`);+ url.searchParams.set('text', String(value).slice(0, 4_000));+ return url.toString();+ }+ throw new Error('Unsupported X browser destination');+};++export const verifyFinalXOrigin = (url) => {+ const parsed = new URL(url);+ if (parsed.origin !== ORIGIN) throw new Error('X browser navigation left the fixed origin');+};++export const verifyFinalXPath = (requestedUrl, finalUrl) => {+ verifyFinalXOrigin(finalUrl);+ const requested = new URL(requestedUrl);+ const final = new URL(finalUrl);+ if (requested.pathname.replace(/\/+$/, '').toLowerCase() !== final.pathname.replace(/\/+$/, '').toLowerCase()) {+ throw new Error('X browser navigation landed on a different page than the one requested');+ }+};++export async function openXHandoff({ kind, value = '' }) {+ const target = fixedXUrl(kind, value);+ const page = await navigateToUrlPinned(target, {+ verifyRemoteIp: (ip) => !isPrivateAddress(ip),+ settleMs: 500,+ closeAfterRead: false,+ });+ verifyFinalXPath(target, page.url);+ return { pageId: page.id, url: page.url };+}diff --git a/server/services/xBrowser.test.js b/server/services/xBrowser.test.jsnew file mode 100644index 0000000000..0a470146cd--- /dev/null+++ b/server/services/xBrowser.test.js@@ -0,0 +1,31 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const navigateToUrlPinned = vi.fn();+vi.mock('./browserService.js', () => ({ navigateToUrlPinned }));++const { fixedXUrl, openXHandoff, verifyFinalXPath } = await import('./xBrowser.js');++describe('X browser handoffs', () => {+ beforeEach(() => navigateToUrlPinned.mockReset());++ it('builds only the named fixed-origin destinations', () => {+ expect(fixedXUrl('profile', 'example_user')).toBe('https://x.com/example_user');+ expect(fixedXUrl('people', 'example_user')).toBe('https://x.com/search?q=example_user&src=typed_query&f=user');+ expect(fixedXUrl('latest', 'example_user')).toBe('https://x.com/search?q=from%3Aexample_user+-filter%3Areplies&src=typed_query&f=live');+ expect(fixedXUrl('compose', 'A bounded draft')).toContain('https://x.com/compose/post?text=A+bounded+draft');+ expect(() => fixedXUrl('profile', '../example')).toThrow('Invalid X username');+ expect(() => fixedXUrl('arbitrary', 'example_user')).toThrow('Unsupported X browser destination');+ });++ it('keeps a compose handoff open only after same-origin path verification', async () => {+ navigateToUrlPinned.mockResolvedValue({ id: 'page-1', url: 'https://x.com/compose/post?text=A+draft' });+ await expect(openXHandoff({ kind: 'compose', value: 'A draft' })).resolves.toMatchObject({+ pageId: 'page-1',+ url: 'https://x.com/compose/post?text=A+draft',+ });+ expect(navigateToUrlPinned).toHaveBeenCalledWith(expect.stringContaining('https://x.com/compose/post'), expect.objectContaining({ closeAfterRead: false }));++ expect(() => verifyFinalXPath('https://x.com/example_user', 'https://example.com/example_user')).toThrow('left the fixed origin');+ expect(() => verifyFinalXPath('https://x.com/example_user', 'https://x.com/another_user')).toThrow('different page than the one requested');+ });+});