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
fix(issue-3302): harden reviewed Stacker actions
[._.]/ Adam Eivy67390d1cd427
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 94c8f03a6c..e7f63ad743 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -92,4 +92,4 @@## Stacker News stewardship-- **[issue-3302] Safe Stacker News community stewardship** — Add independent account rules and schedules, ownership-aware territory monitoring, constrained GraphQL reads and reviewed publishing, local text/vision analysis with safe image normalization, fixed-origin identity-verified browser handoffs, Review Hub approvals, and an auditable action ledger in Comms.+- **[issue-3302] Safe Stacker News community stewardship** — Add independent account rules and schedules, ownership-aware territory monitoring, constrained GraphQL reads and reviewed publishing, conservative local text/vision analysis with safe image normalization, fixed-origin identity-verified browser handoffs, target-bound Review Hub approvals, and an auditable action ledger in Comms.diff --git a/client/src/pages/StackerNews.jsx b/client/src/pages/StackerNews.jsxindex b405a27c12..015160435f 100644--- a/client/src/pages/StackerNews.jsx+++ b/client/src/pages/StackerNews.jsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useNavigate, useParams } from 'react-router-dom';import { Newspaper, Plus, RefreshCw, ShieldCheck, ShieldAlert } from 'lucide-react';import * as api from '../services/api';@@ -23,6 +23,16 @@ const buttonClass = 'rounded bg-port-accent px-3 py-2 text-sm font-medium text-wconst secondaryButton = 'rounded border border-port-border px-3 py-2 text-sm text-gray-200 disabled:opacity-50';const splitList = (value) => value.split(',').map((entry) => entry.trim()).filter(Boolean);const accountRules = (form) => ({ guidance: form.guidance, tone: form.tone, allowedThemes: splitList(form.allowedThemes), disallowedThemes: splitList(form.disallowedThemes), escalationCues: splitList(form.escalationCues), desiredEngagement: splitList(form.desiredEngagement), actionBudget: { maxPerHour: Number(form.maxPerHour), maxPerDay: Number(form.maxPerDay), minMinutesBetween: Number(form.minMinutesBetween) } });+const accountToForm = (account) => ({+ label: account.label, username: account.username, apiKey: '', enabled: account.enabled,+ monitoringEnabled: account.monitoringEnabled, monitoringIntervalMinutes: account.monitoringIntervalMinutes,+ analysisEnabled: account.analysisEnabled, textModel: account.textModel, visionModel: account.visionModel,+ guidance: account.rules?.guidance || '', tone: account.rules?.tone || '', allowedThemes: (account.rules?.allowedThemes || []).join(', '),+ disallowedThemes: (account.rules?.disallowedThemes || []).join(', '), escalationCues: (account.rules?.escalationCues || []).join(', '),+ desiredEngagement: (account.rules?.desiredEngagement || []).join(', '), maxPerHour: account.rules?.actionBudget?.maxPerHour ?? 3,+ maxPerDay: account.rules?.actionBudget?.maxPerDay ?? 12, minMinutesBetween: account.rules?.actionBudget?.minMinutesBetween ?? 5,+});+const sameAccountForm = (left, right) => JSON.stringify(left) === JSON.stringify(right);export default function StackerNews() {const navigate = useNavigate();@@ -39,15 +49,23 @@ export default function StackerNews() {const [notice, setNotice] = useState('');const [newAccount, setNewAccount] = useState(emptyAccount);const [editAccount, setEditAccount] = useState(emptyAccount);+ const [savedAccount, setSavedAccount] = useState(emptyAccount);const [newTerritory, setNewTerritory] = useState(emptyTerritory);const [draft, setDraft] = useState(emptyDraft);const [analysisResults, setAnalysisResults] = useState({});const [feedbackDrafts, setFeedbackDrafts] = 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 ? tab : 'accounts';const accountPath = (id, nextTab = tab) => `/stacker-news/${id}/${nextTab}`;const models = useMemo(() => [...new Set(localModels.ollama)], [localModels.ollama]);+ const accountFormDirty = selected ? !sameAccountForm(editAccount, savedAccount) : false;+ const accountActionsDisabled = accountFormDirty || Boolean(busy);const loadAccounts = useCallback(async () => {const result = await api.getStackerNewsAccounts({ silent: true }).catch((err) => ({ error: err.message }));@@ -57,6 +75,8 @@ export default function StackerNews() {}, []);const loadSelected = useCallback(async () => {+ const requestId = ++selectedLoadRef.current;+ const requestedAccountId = accountId;if (!accountId) {setTerritories([]); setItems([]); setActions([]);return;@@ -66,6 +86,7 @@ export default function StackerNews() {api.getStackerNewsItems(accountId, { silent: true }).catch((err) => ({ error: err.message, items: [] })),api.getStackerNewsActions(accountId, { silent: true }).catch((err) => ({ error: err.message, actions: [] })),]);+ if (selectedLoadRef.current !== requestId || currentAccountIdRef.current !== requestedAccountId) return;const failed = [territoryResult, itemResult, actionResult].find((result) => result.error);if (failed) setError(failed.error);setTerritories(territoryResult.territories || []);@@ -76,16 +97,16 @@ export default function StackerNews() {useEffect(() => { loadAccounts(); }, [loadAccounts]);useEffect(() => { loadSelected(); }, [loadSelected]);useEffect(() => {- if (!selected) return;- setEditAccount({- label: selected.label, username: selected.username, apiKey: '', enabled: selected.enabled,- monitoringEnabled: selected.monitoringEnabled, monitoringIntervalMinutes: selected.monitoringIntervalMinutes,- analysisEnabled: selected.analysisEnabled, textModel: selected.textModel, visionModel: selected.visionModel,- guidance: selected.rules?.guidance || '', tone: selected.rules?.tone || '', allowedThemes: (selected.rules?.allowedThemes || []).join(', '),- disallowedThemes: (selected.rules?.disallowedThemes || []).join(', '), escalationCues: (selected.rules?.escalationCues || []).join(', '),- desiredEngagement: (selected.rules?.desiredEngagement || []).join(', '), maxPerHour: selected.rules?.actionBudget?.maxPerHour ?? 3,- maxPerDay: selected.rules?.actionBudget?.maxPerDay ?? 12, minMinutesBetween: selected.rules?.actionBudget?.minMinutesBetween ?? 5,- });+ if (!selected) {+ selectedAccountIdRef.current = null;+ return;+ }+ const nextSaved = accountToForm(selected);+ const switchedAccounts = selectedAccountIdRef.current !== selected.id;+ setEditAccount((current) => switchedAccounts || sameAccountForm(current, savedAccountRef.current) ? nextSaved : current);+ selectedAccountIdRef.current = selected.id;+ savedAccountRef.current = nextSaved;+ setSavedAccount(nextSaved);}, [selected]);const finish = (key, promise, onSuccess) => {@@ -115,6 +136,10 @@ export default function StackerNews() {analysisEnabled: editAccount.analysisEnabled, textModel: editAccount.textModel, visionModel: editAccount.visionModel,rules: accountRules(editAccount),}, { silent: true }), (result) => {+ const nextSaved = accountToForm(result);+ savedAccountRef.current = nextSaved;+ setSavedAccount(nextSaved);+ setEditAccount(nextSaved);setAccounts((previous) => previous.map((candidate) => candidate.id === result.id ? result : candidate));setNotice('Account rules and schedule saved.');});@@ -194,6 +219,7 @@ export default function StackerNews() {<div key={action.id} className="rounded border border-port-border p-3 text-sm"><div className="flex items-center justify-between gap-2"><span className="font-medium text-white">{action.kind.replaceAll('_', ' ')}</span><span className="text-xs text-gray-400">{action.state.replaceAll('_', ' ')}</span></div><div className="mt-1 whitespace-pre-wrap text-gray-400">{action.payload?.title || action.payload?.body || `Fixed ${action.destination || 'local'} action`}</div>+ <div className="mt-1 text-xs text-gray-400">Reviewed target: @{action.reviewedTarget?.username || selected.username}{action.reviewedTarget?.territorySlug ? ` · ${action.reviewedTarget.territorySlug}` : ''}{action.reviewedTarget?.remoteItemId ? ` · item ${action.reviewedTarget.remoteItemId}` : ''}</div><div className="mt-1 font-mono text-[11px] text-gray-500">content {action.sourceContentHash?.slice(0, 10) || 'n/a'} · rules {action.rulesHash?.slice(0, 10) || 'n/a'} · {action.policyVersion}</div>{action.state === 'pending_review' && <div className="mt-2 flex gap-2"><button className={buttonClass} disabled={busy === `review-${action.id}`} onClick={() => reviewAction(action, 'approved')}>Approve</button><button className={secondaryButton} onClick={() => reviewAction(action, 'rejected')}>Reject</button></div>}{action.state === 'approved' && <button className={`${buttonClass} mt-2`} disabled={busy === `execute-${action.id}`} onClick={() => executeAction(action)}>Execute reviewed action</button>}@@ -203,7 +229,7 @@ export default function StackerNews() {</div></section><section className="rounded border border-port-border bg-port-card p-4">- <div className="flex flex-wrap items-center justify-between gap-2"><div><h2 className="font-semibold text-white">Monitored content</h2><p className="text-sm text-gray-400">Remote text and images remain untrusted data.</p></div><button className={secondaryButton} disabled={busy === 'sync'} onClick={syncNow}>Sync now</button></div>+ <div className="flex flex-wrap items-center justify-between gap-2"><div><h2 className="font-semibold text-white">Monitored content</h2><p className="text-sm text-gray-400">Remote text and images remain untrusted data.</p></div><button className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button></div><div className="mt-3 space-y-2">{items.map((item) => <div key={item.id} className="rounded border border-port-border p-3"><div className="text-sm font-medium text-white">{item.title || `${item.kind} by @${item.authorName}`}</div><div className="mt-1 line-clamp-3 text-sm text-gray-400">{item.body}</div>{analysisResults[item.id] && <div className="mt-2 rounded bg-port-bg p-2 text-xs text-gray-300">Policy: {analysisResults[item.id].stale ? 'stale' : analysisResults[item.id].policy?.decision || 'review'}{analysisResults[item.id].policy?.reasons?.length ? ` · ${analysisResults[item.id].policy.reasons.join(', ')}` : ''}<div className="mt-2 flex gap-2"><input aria-label={`Feedback for ${item.title || item.id}`} className={fieldClass} placeholder="Moderator feedback" value={feedbackDrafts[item.id] || ''} onChange={(event) => setFeedbackDrafts((previous) => ({ ...previous, [item.id]: event.target.value }))} /><button className={secondaryButton} disabled={!analysisResults[item.id].analysisId || busy === `feedback-${item.id}`} onClick={() => saveFeedback(item)}>Save feedback</button></div></div>}<button className={`${secondaryButton} mt-2`} disabled={busy === `analyze-${item.id}`} onClick={() => analyze(item)}>Run local analysis</button></div>)}{!items.length && <p className="text-sm text-gray-500">No stored content. Add a territory, then sync explicitly or enable a schedule.</p>}</div></section></div>@@ -225,7 +251,7 @@ export default function StackerNews() {const renderAccounts = () => (<div className="grid gap-3 xl:grid-cols-3"><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Accounts</h2><div className="mt-3 space-y-2">{accounts.map((account) => <button key={account.id} className={`block w-full rounded border p-3 text-left ${account.id === selected?.id ? 'border-port-accent' : 'border-port-border'}`} onClick={() => navigate(accountPath(account.id, 'accounts'))}><div className="flex justify-between gap-2"><span className="font-medium text-white">{account.label}</span><span className="text-xs text-gray-400">{account.apiKeyConfigured ? 'Key protected' : 'No key'}</span></div><div className="mt-1 text-sm text-gray-400">@{account.username} · {account.monitoringEnabled ? `every ${account.monitoringIntervalMinutes}m` : 'monitoring off'}</div></button>)}{!accounts.length && <p className="text-sm text-gray-500">No accounts configured.</p>}</div></section>- {selected ? <AccountForm title="Selected account" submitLabel="Save account" form={editAccount} setForm={setEditAccount} models={models} onSubmit={saveAccount} busy={busy === 'save-account'} extra={<div className="flex flex-wrap gap-2"><button type="button" className={secondaryButton} disabled={busy === 'verify'} onClick={checkConnection}>Check API identity</button><button type="button" className={secondaryButton} disabled={busy === 'browser'} onClick={checkBrowser}>Check browser identity</button><button type="button" className={secondaryButton} disabled={busy === 'sync'} onClick={syncNow}>Sync now</button></div>} /> : <div className="rounded border border-port-border bg-port-card p-4 text-sm text-gray-400">Choose an account to edit its independent rules, models, and monitoring schedule.</div>}+ {selected ? <AccountForm title="Selected account" submitLabel="Save account" form={editAccount} setForm={setEditAccount} models={models} onSubmit={saveAccount} busy={busy === 'save-account'} extra={<div className="flex flex-wrap gap-2"><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkConnection}>Check API identity</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkBrowser}>Check browser identity</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button></div>} /> : <div className="rounded border border-port-border bg-port-card p-4 text-sm text-gray-400">Choose an account to edit its independent rules, models, and monitoring schedule.</div>}<AccountForm title="Add account" submitLabel="Add protected account" form={newAccount} setForm={setNewAccount} models={models} onSubmit={createAccount} busy={busy === 'create-account'} showCredential /></div>);diff --git a/client/src/pages/StackerNews.test.jsx b/client/src/pages/StackerNews.test.jsxindex f3de556b32..4a5406e6bb 100644--- a/client/src/pages/StackerNews.test.jsx+++ b/client/src/pages/StackerNews.test.jsx@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { render, screen, waitFor } from '@testing-library/react';+import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter, Route, Routes } from 'react-router-dom';@@ -32,6 +32,12 @@ function renderPage(path) {return render(<MemoryRouter initialEntries={[path]}><Routes><Route path="/stacker-news" element={<StackerNews />} /><Route path="/stacker-news/:accountId/:tab" element={<StackerNews />} /></Routes></MemoryRouter>);}+function deferred() {+ let resolve;+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };+}+describe('StackerNews', () => {beforeEach(() => {vi.clearAllMocks();@@ -70,4 +76,37 @@ describe('StackerNews', () => {renderPage('/stacker-news/missing/review');expect(await screen.findByText(/account was not found/i)).toBeInTheDocument();});++ it('discards resource responses for an account that is no longer selected', async () => {+ const user = userEvent.setup();+ const oldTerritories = deferred();+ api.getStackerNewsTerritories.mockImplementation((id) => id === 'a1'+ ? oldTerritories.promise+ : Promise.resolve({ territories: [{ id: 't2', accountId: 'a2', slug: 'current-community', label: 'Current community', rules: {} }] }));+ renderPage('/stacker-news/a1/accounts');+ await screen.findByRole('button', { name: /Personal/ });+ await user.click(screen.getByRole('button', { name: /Personal/ }));+ await user.click(screen.getByRole('tab', { name: 'Territory' }));+ expect(await screen.findByText('Current community')).toBeInTheDocument();+ await act(async () => oldTerritories.resolve({ territories: [{ id: 't1', accountId: 'a1', slug: 'old-community', label: 'Old community', rules: {} }] }));+ expect(screen.queryByText('Old community')).not.toBeInTheDocument();+ expect(screen.getByText('Current community')).toBeInTheDocument();+ });++ it('gates server-side account actions on saved settings and the in-flight save', async () => {+ const user = userEvent.setup();+ const save = deferred();+ api.updateStackerNewsAccount.mockReturnValue(save.promise);+ renderPage('/stacker-news/a1/accounts');+ const interval = await screen.findByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' });+ await user.clear(interval);+ await user.type(interval, '20');+ expect(screen.getByRole('button', { name: 'Check API identity' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Check browser identity' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Sync now' })).toBeDisabled();+ await user.click(screen.getByRole('button', { name: 'Save account' }));+ expect(screen.getByRole('button', { name: 'Sync now' })).toBeDisabled();+ await act(async () => save.resolve({ ...accounts[0], monitoringIntervalMinutes: 20 }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Sync now' })).toBeEnabled());+ });});diff --git a/docs/features/stacker-news.md b/docs/features/stacker-news.mdindex 06e245f98f..55a372b0c5 100644--- a/docs/features/stacker-news.md+++ b/docs/features/stacker-news.md@@ -17,12 +17,15 @@ accounts its user explicitly adds.- Posts, comments, URLs, images, and browser content are untrusted. Text isbounded and screened for instruction-shaped content before optional localanalysis. A prompt-injection match prevents text and images from reaching an- Ollama model.+ Ollama model. The complete bounded title and body are hashed even though the+ model copy is shorter, so edits outside the model window still invalidate an+ analysis or approval.- Remote images use the strict public-network fetch posture, a five-megabytedownload cap, MIME and pixel limits, and a single-frame Sharp decode. SVG andother active formats are rejected. Ollama receives only an in-memory,re-encoded PNG; raw remote bytes are never persisted.-- Ollama text and vision results must match a strict JSON schema. Results record+- Ollama text and vision results must match a strict JSON schema and are merged+ conservatively, preserving the highest risk from either stage. Results recordtheir source-content hash, effective-rules hash, model, stage, provider, andpolicy version. If content changes during analysis, the result is stale andcannot drive an action.@@ -35,6 +38,9 @@ Every proposed action enters `pending_review`. Approval and execution areseparate user actions. Immediately before execution PortOS rechecks the selectedaccount identity, source-content hash, effective rule hash, action age, actionbudgets, territory ownership evidence, state transition, and idempotency key.+The reviewed username, territory slug, and remote item ID are snapshotted and+must still match, so editing account or territory configuration cannot redirect+an already-approved action. Terminal actions may be submitted as a fresh review.Every transition is appended to the action ledger. Pending actions also appearin Review Hub and drill back to the correct account.diff --git a/server/lib/db/schema/stackerNews.js b/server/lib/db/schema/stackerNews.jsindex 7e98aae138..92eef3941f 100644--- a/server/lib/db/schema/stackerNews.js+++ b/server/lib/db/schema/stackerNews.js@@ -121,6 +121,7 @@ export const stackerNewsDdl = [rules_hash TEXT NOT NULL DEFAULT '',policy_version TEXT NOT NULL DEFAULT 'v1',idempotency_key TEXT NOT NULL,+ reviewed_target JSONB NOT NULL DEFAULT '{}'::jsonb,review_note TEXT NOT NULL DEFAULT '',result JSONB NOT NULL DEFAULT '{}'::jsonb,error TEXT NOT NULL DEFAULT '',@@ -134,10 +135,12 @@ export const stackerNewsDdl = [`ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS rules_hash TEXT NOT NULL DEFAULT ''`,`ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS policy_version TEXT NOT NULL DEFAULT 'v1'`,`ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS idempotency_key TEXT`,+ `ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS reviewed_target JSONB NOT NULL DEFAULT '{}'::jsonb`,`ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS result JSONB NOT NULL DEFAULT '{}'::jsonb`,`ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS error TEXT NOT NULL DEFAULT ''`,`ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS approved_at TIMESTAMPTZ`,- `CREATE UNIQUE INDEX IF NOT EXISTS idx_stacker_news_actions_idempotency_key ON stacker_news_actions (idempotency_key)`,+ `DROP INDEX IF EXISTS idx_stacker_news_actions_idempotency_key`,+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_stacker_news_actions_active_idempotency_key ON stacker_news_actions (idempotency_key) WHERE state IN ('pending_review','approved','executing')`,`CREATE INDEX IF NOT EXISTS idx_stacker_news_actions_account_state ON stacker_news_actions (account_id, state, created_at DESC)`,`CREATE TABLE IF NOT EXISTS stacker_news_action_events (id UUID PRIMARY KEY,diff --git a/server/scripts/db-migrations/003-stacker-news-reviewed-targets.js b/server/scripts/db-migrations/003-stacker-news-reviewed-targets.jsnew file mode 100644index 0000000000..f55e7ea768--- /dev/null+++ b/server/scripts/db-migrations/003-stacker-news-reviewed-targets.js@@ -0,0 +1,21 @@+/**+ * Bind every review to the external account and destination that the moderator+ * actually saw, while allowing terminal actions to be submitted for a new review.+ */+export async function up(client) {+ await client.query("ALTER TABLE stacker_news_actions ADD COLUMN IF NOT EXISTS reviewed_target JSONB NOT NULL DEFAULT '{}'::jsonb");+ await client.query(+ `UPDATE stacker_news_actions a+ SET reviewed_target=jsonb_build_object(+ 'username', ac.username,+ 'territorySlug', COALESCE((SELECT t.slug FROM stacker_news_territories t WHERE t.id=a.territory_id), ''),+ 'remoteItemId', COALESCE((SELECT i.remote_id FROM stacker_news_items i WHERE i.id=a.item_id), '')+ )+ FROM stacker_news_accounts ac+ WHERE ac.id=a.account_id AND a.reviewed_target='{}'::jsonb`,+ );+ await client.query('DROP INDEX IF EXISTS idx_stacker_news_actions_idempotency_key');+ await client.query(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_stacker_news_actions_active_idempotency_key ON stacker_news_actions (idempotency_key) WHERE state IN ('pending_review','approved','executing')",+ );+}diff --git a/server/scripts/db-migrations/003-stacker-news-reviewed-targets.test.js b/server/scripts/db-migrations/003-stacker-news-reviewed-targets.test.jsnew file mode 100644index 0000000000..5a5669707e--- /dev/null+++ b/server/scripts/db-migrations/003-stacker-news-reviewed-targets.test.js@@ -0,0 +1,13 @@+import { describe, expect, it, vi } from 'vitest';+import { up } from './003-stacker-news-reviewed-targets.js';++describe('Stacker News reviewed-target migration', () => {+ it('backfills target snapshots and limits idempotency to active actions', async () => {+ const query = vi.fn(async () => ({ rows: [] }));+ await up({ query });+ const statements = query.mock.calls.map(([sql]) => sql);+ expect(statements.some((sql) => sql.includes("'username', ac.username"))).toBe(true);+ expect(statements).toContain('DROP INDEX IF EXISTS idx_stacker_news_actions_idempotency_key');+ expect(statements.at(-1)).toContain("WHERE state IN ('pending_review','approved','executing')");+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 6a67b6d1c6..3a57a8d1bd 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1377,6 +1377,7 @@ CREATE TABLE IF NOT EXISTS stacker_news_actions (rules_hash TEXT NOT NULL DEFAULT '',policy_version TEXT NOT NULL DEFAULT 'v1',idempotency_key TEXT NOT NULL,+ reviewed_target JSONB NOT NULL DEFAULT '{}'::jsonb,review_note TEXT NOT NULL DEFAULT '',result JSONB NOT NULL DEFAULT '{}'::jsonb,error TEXT NOT NULL DEFAULT '',@@ -1385,7 +1386,8 @@ CREATE TABLE IF NOT EXISTS stacker_news_actions (created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW());-CREATE UNIQUE INDEX IF NOT EXISTS idx_stacker_news_actions_idempotency_key ON stacker_news_actions (idempotency_key);+DROP INDEX IF EXISTS idx_stacker_news_actions_idempotency_key;+CREATE UNIQUE INDEX IF NOT EXISTS idx_stacker_news_actions_active_idempotency_key ON stacker_news_actions (idempotency_key) WHERE state IN ('pending_review','approved','executing');CREATE INDEX IF NOT EXISTS idx_stacker_news_actions_account_state ON stacker_news_actions (account_id, state, created_at DESC);CREATE TABLE IF NOT EXISTS stacker_news_action_events (id UUID PRIMARY KEY,diff --git a/server/services/stackerNews.js b/server/services/stackerNews.jsindex 90ee698137..835a6aa16e 100644--- a/server/services/stackerNews.js+++ b/server/services/stackerNews.js@@ -7,6 +7,7 @@ import { fetchAndNormalizeStackerNewsImage, hashRemoteMediaUrl } from './stackerimport { getStackerNewsBrowserIdentity, openStackerNewsHandoff } from './stackerNewsBrowser.js';import {POLICY_VERSION,+ combineStackerNewsModelResults,evaluateStackerNewsPolicy,hashStackerNewsRules,normalizeStackerNewsRules,@@ -29,7 +30,15 @@ const ACTION_MAX_AGE_MS = 24 * 60 * 60 * 1000;const syncLocks = new Map();const stableHash = (value) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');-const normalizedText = ({ title = '', body = '' }) => `${title}\n${body}`.replace(/\0/g, '').slice(0, MAX_ANALYSIS_CHARS);+const boundedContent = ({ title = '', body = '' }) => ({+ title: String(title).replace(/\0/g, '').slice(0, 2_000),+ body: String(body).replace(/\0/g, '').slice(0, 40_000),+});+const normalizedText = (value) => {+ const { title, body } = boundedContent(value);+ return `${title}\n${body}`;+};+const analysisText = (value) => normalizedText(value).slice(0, MAX_ANALYSIS_CHARS);const markdownImages = (body = '') => [...body.matchAll(/!\[[^\]]*\]\((https?:\/\/[^\s)]+)(?:\s+"[^"]*")?\)/gi)].map((match) => match[1]).slice(0, 12);const accountView = (row) => ({@@ -96,6 +105,7 @@ const actionView = (row) => ({sourceContentHash: row.source_content_hash,rulesHash: row.rules_hash,policyVersion: row.policy_version,+ reviewedTarget: row.reviewed_target || {},reviewNote: row.review_note,result: row.result || {},error: row.error || '',@@ -245,7 +255,8 @@ export async function ingestItem({accountId, territoryId = null, remoteId, kind, authorName = '', title = '', body = '', sourceUrl = '', imageUrls = [],remoteCreatedAt = null, remoteUpdatedAt = null,}) {- const contentHash = stableHash(normalizedText({ title, body }));+ const content = boundedContent({ title, body });+ const contentHash = stableHash(normalizedText(content));const result = await query(`INSERT INTO stacker_news_items(id,account_id,territory_id,remote_id,kind,author_name,title,body,source_url,image_urls,content_hash,remote_created_at,remote_updated_at)@@ -254,7 +265,7 @@ export async function ingestItem({author_name=EXCLUDED.author_name,title=EXCLUDED.title,body=EXCLUDED.body,source_url=EXCLUDED.source_url,image_urls=EXCLUDED.image_urls,content_hash=EXCLUDED.content_hash,remote_created_at=EXCLUDED.remote_created_at,remote_updated_at=EXCLUDED.remote_updated_at,received_at=NOW(),updated_at=NOW() RETURNING *`,- [randomUUID(), accountId, territoryId, String(remoteId), kind, authorName, title, body, sourceUrl, imageUrls, contentHash, remoteCreatedAt, remoteUpdatedAt],+ [randomUUID(), accountId, territoryId, String(remoteId), kind, authorName, content.title, content.body, sourceUrl, imageUrls, contentHash, remoteCreatedAt, remoteUpdatedAt],);return itemView(result.rows[0]);}@@ -304,7 +315,7 @@ export async function analyzeItem(itemId) {const territory = territoryResult.rows[0];const rules = resolveStackerNewsRules(account.rules, territory?.rules, territory?.inherit_account_rules ?? true);const rulesHash = hashStackerNewsRules(rules);- const { normalized: content, injectionMatches } = inspectUntrustedContent(normalizedText(item));+ const { normalized: content, injectionMatches } = inspectUntrustedContent(analysisText(item));const deterministic = { injectionRisk: injectionMatches.length ? 'high' : 'low', injectionMatches, sourceTrusted: false, contentLength: content.length };await persistAnalysis({ item, stage: 'ingress', provider: 'deterministic', rulesHash, result: deterministic });@@ -343,9 +354,10 @@ export async function analyzeItem(itemId) {const fresh = await query('SELECT content_hash FROM stacker_news_items WHERE id=$1', [item.id]);if (fresh.rows[0]?.content_hash !== item.content_hash) return { item: itemView(item), stale: true, deterministic, errors };- const policy = evaluateStackerNewsPolicy({ deterministic, model: visionResult || textResult, rules });+ const combinedModel = combineStackerNewsModelResults(textResult, visionResult);+ const policy = evaluateStackerNewsPolicy({ deterministic, model: combinedModel, rules });const analysisId = await persistAnalysis({ item, stage: 'policy', provider: 'deterministic', rulesHash, result: policy });- return { item: itemView(item), analysisId, stale: false, deterministic, text: textResult, vision: visionResult, policy, errors };+ return { item: itemView(item), analysisId, stale: false, deterministic, text: textResult, vision: visionResult, combinedModel, policy, errors };}export async function listAnalyses(itemId) {@@ -455,18 +467,49 @@ export async function createAction({ accountId, itemId = null, territoryId = nulconst rules = resolveStackerNewsRules(account.rules, territory?.rules, territory?.inherit_account_rules ?? true);const rulesHash = hashStackerNewsRules(rules);const sourceContentHash = item?.content_hash || '';- const idempotencyKey = stableHash({ accountId, itemId, territoryId, kind, destination, payload, sourceContentHash, rulesHash });+ const reviewedTarget = {+ username: account.username,+ territorySlug: territory?.slug || '',+ remoteItemId: item?.remote_id || '',+ };+ const idempotencyKey = stableHash({ accountId, itemId, territoryId, kind, destination, payload, sourceContentHash, rulesHash, reviewedTarget });const id = randomUUID();const row = await withTransaction(async (client) => {+ const active = await client.query(+ `SELECT * FROM stacker_news_actions+ WHERE idempotency_key=$1 AND state IN ('pending_review','approved','executing')+ ORDER BY created_at DESC LIMIT 1`,+ [idempotencyKey],+ );+ const existing = active.rows[0];+ const approvalExpired = existing?.state === 'approved'+ && (!existing.approved_at || Date.now() - new Date(existing.approved_at).getTime() > ACTION_MAX_AGE_MS);+ if (existing && !approvalExpired) return existing;+ if (approvalExpired) {+ await client.query(+ "UPDATE stacker_news_actions SET state='rejected',error='Approval expired before execution',updated_at=NOW() WHERE id=$1 AND state='approved'",+ [existing.id],+ );+ await eventInsert(client, existing.id, 'approved', 'rejected', 'Approval expired; a fresh review was requested');+ }const result = await client.query(`INSERT INTO stacker_news_actions- (id,account_id,item_id,territory_id,kind,state,destination,payload,source_content_hash,rules_hash,policy_version,idempotency_key)- VALUES ($1,$2,$3,$4,$5,'pending_review',$6,$7,$8,$9,$10,$11)- ON CONFLICT (idempotency_key) DO UPDATE SET updated_at=stacker_news_actions.updated_at RETURNING *`,- [id, accountId, itemId, territoryId, kind, destination, payload, sourceContentHash, rulesHash, POLICY_VERSION, idempotencyKey],+ (id,account_id,item_id,territory_id,kind,state,destination,payload,source_content_hash,rules_hash,policy_version,idempotency_key,reviewed_target)+ VALUES ($1,$2,$3,$4,$5,'pending_review',$6,$7,$8,$9,$10,$11,$12)+ ON CONFLICT (idempotency_key) WHERE state IN ('pending_review','approved','executing') DO NOTHING RETURNING *`,+ [id, accountId, itemId, territoryId, kind, destination, payload, sourceContentHash, rulesHash, POLICY_VERSION, idempotencyKey, reviewedTarget],+ );+ if (result.rows[0]) {+ await eventInsert(client, id, null, 'pending_review', 'Created for human review');+ return result.rows[0];+ }+ const conflicted = await client.query(+ `SELECT * FROM stacker_news_actions+ WHERE idempotency_key=$1 AND state IN ('pending_review','approved','executing')+ ORDER BY created_at DESC LIMIT 1`,+ [idempotencyKey],);- if (result.rows[0].id === id) await eventInsert(client, id, null, 'pending_review', 'Created for human review');- return result.rows[0];+ return conflicted.rows[0];});return actionView(row);}@@ -556,7 +599,14 @@ export async function executeApprovedAction(id) {territoryId: action.territory_id,});if (!account?.enabled) throw new Error('Selected Stacker News account is disabled');+ const currentTarget = {+ username: account.username,+ territorySlug: territory?.slug || '',+ remoteItemId: item?.remote_id || '',+ };+ if (stableHash(currentTarget) !== stableHash(action.reviewed_target || {})) throw new Error('External account or destination changed after review');if (item && item.content_hash !== action.source_content_hash) throw new Error('Source content changed after review');+ if (action.policy_version !== POLICY_VERSION) throw new Error('Policy version changed after review');const rules = resolveStackerNewsRules(account.rules, territory?.rules, territory?.inherit_account_rules ?? true);if (hashStackerNewsRules(rules) !== action.rules_hash) throw new Error('Community rules changed after review');if (!['draft_post', 'draft_comment'].includes(action.kind)) await assertActionBudget(account.id, rules.actionBudget);diff --git a/server/services/stackerNewsActions.test.js b/server/services/stackerNewsActions.test.jsnew file mode 100644index 0000000000..27e479b5bd--- /dev/null+++ b/server/services/stackerNewsActions.test.js@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest';++const account = { id: 'account', username: 'example_user', enabled: true, rules: {}, policy_version: 'v1' };+const territory = { id: 'territory', account_id: 'account', slug: 'art', rules: {}, inherit_account_rules: true, is_owned: false, remote_settings: {} };+const item = { id: 'item', account_id: 'account', remote_id: '42', content_hash: 'content-hash' };+let actionForExecution = null;++const query = vi.fn(async (sql) => {+ if (sql === 'SELECT * FROM stacker_news_actions WHERE id=$1') return { rows: actionForExecution ? [actionForExecution] : [] };+ if (sql.startsWith('SELECT * FROM stacker_news_accounts')) return { rows: [account] };+ if (sql.startsWith('SELECT * FROM stacker_news_items')) return { rows: [item] };+ if (sql.startsWith('SELECT * FROM stacker_news_territories')) return { rows: [territory] };+ return { rows: [] };+});++const transactionQuery = vi.fn(async (sql, params) => {+ if (sql.includes('WHERE idempotency_key=$1')) return { rows: [] };+ if (sql.includes('INSERT INTO stacker_news_actions')) {+ return {+ rows: [{+ id: params[0], account_id: params[1], item_id: params[2], territory_id: params[3], kind: params[4],+ state: 'pending_review', destination: params[5], payload: params[6], source_content_hash: params[7],+ rules_hash: params[8], policy_version: params[9], idempotency_key: params[10], reviewed_target: params[11],+ }],+ };+ }+ return { rows: [], rowCount: 1 };+});+const withTransaction = vi.fn(async (callback) => callback({ query: transactionQuery }));++vi.mock('../lib/db.js', () => ({ query, withTransaction }));+vi.mock('../lib/vaultCrypto.js', () => ({ decryptValue: vi.fn(), encryptValue: vi.fn(), ensureVaultKey: vi.fn() }));+vi.mock('../integrations/stackerNews/index.js', () => ({ executeStackerNewsOperation: vi.fn(), stackerNewsCapabilities: {} }));++const { createAction, executeApprovedAction } = await import('./stackerNews.js');++describe('Stacker News reviewed actions', () => {+ it('persists the reviewed external account and destination', async () => {+ const action = await createAction({+ accountId: account.id,+ itemId: item.id,+ territoryId: territory.id,+ kind: 'publish_comment',+ payload: { body: 'Thanks for sharing.' },+ });+ expect(action.reviewedTarget).toEqual({ username: 'example_user', territorySlug: 'art', remoteItemId: '42' });+ expect(transactionQuery.mock.calls.find(([sql]) => sql.includes('INSERT INTO stacker_news_actions'))[0]).toContain('reviewed_target');+ });++ it('refuses execution when the reviewed identity no longer matches', async () => {+ actionForExecution = {+ id: 'action', account_id: account.id, item_id: item.id, territory_id: territory.id,+ kind: 'publish_comment', state: 'approved', approved_at: new Date(), payload: { body: 'Hello' },+ reviewed_target: { username: 'previous_user', territorySlug: 'art', remoteItemId: '42' },+ source_content_hash: item.content_hash, rules_hash: '', policy_version: 'v1',+ };+ await expect(executeApprovedAction('action')).rejects.toThrow('External account or destination changed after review');+ });+});diff --git a/server/services/stackerNewsContent.test.js b/server/services/stackerNewsContent.test.jsnew file mode 100644index 0000000000..c633315806--- /dev/null+++ b/server/services/stackerNewsContent.test.js@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest';++const query = vi.fn(async (sql, params) => {+ if (!sql.includes('INSERT INTO stacker_news_items')) return { rows: [] };+ return {+ rows: [{+ id: params[0], account_id: params[1], territory_id: params[2], remote_id: params[3], kind: params[4],+ author_name: params[5], title: params[6], body: params[7], source_url: params[8], image_urls: params[9],+ content_hash: params[10], remote_created_at: params[11], remote_updated_at: params[12],+ }],+ };+});++vi.mock('../lib/db.js', () => ({ query, withTransaction: vi.fn() }));+vi.mock('../lib/vaultCrypto.js', () => ({ decryptValue: vi.fn(), encryptValue: vi.fn(), ensureVaultKey: vi.fn() }));+vi.mock('../integrations/stackerNews/index.js', () => ({ executeStackerNewsOperation: vi.fn(), stackerNewsCapabilities: {} }));++const { ingestItem } = await import('./stackerNews.js');++describe('Stacker News content snapshots', () => {+ it('hashes the complete bounded body while model input remains separately capped', async () => {+ const prefix = 'a'.repeat(8_100);+ const first = await ingestItem({ accountId: 'account', remoteId: '1', kind: 'post', body: `${prefix}first-tail` });+ const second = await ingestItem({ accountId: 'account', remoteId: '2', kind: 'post', body: `${prefix}second-tail` });+ expect(first.contentHash).not.toBe(second.contentHash);+ expect(first.body).toHaveLength(prefix.length + 'first-tail'.length);+ });++ it('bounds remotely sourced content before persistence and hashing', async () => {+ const item = await ingestItem({ accountId: 'account', remoteId: '3', kind: 'post', title: 't'.repeat(2_100), body: 'b'.repeat(41_000) });+ expect(item.title).toHaveLength(2_000);+ expect(item.body).toHaveLength(40_000);+ });+});diff --git a/server/services/stackerNewsPolicy.js b/server/services/stackerNewsPolicy.jsindex d3521bd605..67a7ba51ed 100644--- a/server/services/stackerNewsPolicy.js+++ b/server/services/stackerNewsPolicy.js@@ -67,6 +67,28 @@ export function parseStackerNewsModelResult(raw) {return modelAnalysisSchema.parse(parsed);}+export function combineStackerNewsModelResults(...results) {+ const available = results.flat().filter(Boolean).map((result) => modelAnalysisSchema.parse(result));+ if (!available.length) return null;+ if (available.length === 1) return available[0];+ const classificationRank = { allowed: 0, review: 1, escalate: 2 };+ const riskRank = { low: 0, medium: 1, high: 2 };+ const classification = available.reduce((worst, result) => (+ classificationRank[result.classification] > classificationRank[worst] ? result.classification : worst+ ), 'allowed');+ const risk = available.reduce((worst, result) => (+ riskRank[result.risk] > riskRank[worst] ? result.risk : worst+ ), 'low');+ const suggestedActions = new Set(available.map((result) => result.suggestedAction));+ return {+ classification,+ risk,+ summary: available.map((result) => result.summary).filter(Boolean).join(' | ').slice(0, 1_200),+ findings: [...new Set(available.flatMap((result) => result.findings))].slice(0, 12),+ suggestedAction: suggestedActions.size === 1 ? available[0].suggestedAction : 'none',+ };+}+export function evaluateStackerNewsPolicy({ deterministic, model, rules }) {if (deterministic.injectionMatches?.length) return { decision: 'escalate', reasons: ['prompt_injection_pattern'], allowedAction: 'none' };if (model?.classification === 'escalate' || model?.risk === 'high') return { decision: 'escalate', reasons: ['model_high_risk'], allowedAction: 'none' };diff --git a/server/services/stackerNewsPolicy.test.js b/server/services/stackerNewsPolicy.test.jsindex f9d119c143..2696e0c8e0 100644--- a/server/services/stackerNewsPolicy.test.js+++ b/server/services/stackerNewsPolicy.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { evaluateStackerNewsPolicy, parseStackerNewsModelResult, resolveStackerNewsRules } from './stackerNewsPolicy.js';+import { combineStackerNewsModelResults, evaluateStackerNewsPolicy, parseStackerNewsModelResult, resolveStackerNewsRules } from './stackerNewsPolicy.js';describe('Stacker News policy', () => {it('inherits account rules while allowing explicit territory scalar and budget overrides', () => {@@ -20,4 +20,13 @@ describe('Stacker News policy', () => {it('keeps prompt-injection decisions deterministic', () => {expect(evaluateStackerNewsPolicy({ deterministic: { injectionMatches: ['ignore'] }, model: null, rules: {} })).toMatchObject({ decision: 'escalate', allowedAction: 'none' });});++ it('combines text and vision results conservatively', () => {+ const combined = combineStackerNewsModelResults(+ { classification: 'escalate', risk: 'high', summary: 'Text concern', findings: ['credential request'], suggestedAction: 'none' },+ { classification: 'allowed', risk: 'low', summary: 'Image is ordinary', findings: [], suggestedAction: 'draft_comment' },+ );+ expect(combined).toMatchObject({ classification: 'escalate', risk: 'high', suggestedAction: 'none' });+ expect(evaluateStackerNewsPolicy({ deterministic: { injectionMatches: [] }, model: combined, rules: {} })).toMatchObject({ decision: 'escalate' });+ });});