Skip to content

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

fix(issue-3302): preserve scoped Stacker safety state

[._.]/ Adam Eivy427ee988fefe
diff --git a/client/src/pages/StackerNews.jsx b/client/src/pages/StackerNews.jsx
index 4113e62d04..511d4bcef4 100644
--- a/client/src/pages/StackerNews.jsx
+++ b/client/src/pages/StackerNews.jsx
@@ -64,6 +64,7 @@ export default function StackerNews() {
const [territories, setTerritories] = useState([]);
const [items, setItems] = useState([]);
const [actions, setActions] = useState([]);
+ const [resourcesAccountId, setResourcesAccountId] = useState(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState('');
const [error, setError] = useState('');
@@ -90,6 +91,9 @@ export default function StackerNews() {
const models = useMemo(() => [...new Set(localModels.ollama)], [localModels.ollama]);
const accountFormDirty = selected ? !sameAccountForm(editAccount, savedAccount) : false;
const accountActionsDisabled = accountFormDirty || Boolean(busy);
+ const visibleTerritories = resourcesAccountId === accountId ? territories : [];
+ const visibleItems = resourcesAccountId === accountId ? items : [];
+ const visibleActions = resourcesAccountId === accountId ? actions : [];
const loadAccounts = useCallback(async () => {
const result = await api.getStackerNewsAccounts({ silent: true }).catch((err) => ({ error: err.message }));
@@ -101,8 +105,9 @@ export default function StackerNews() {
const loadSelected = useCallback(async () => {
const requestId = ++selectedLoadRef.current;
const requestedAccountId = accountId;
+ setResourcesAccountId(null);
+ setTerritories([]); setItems([]); setActions([]);
if (!accountId) {
- setTerritories([]); setItems([]); setActions([]);
return;
}
const [territoryResult, itemResult, actionResult] = await Promise.all([
@@ -116,6 +121,7 @@ export default function StackerNews() {
setTerritories(territoryResult.territories || []);
setItems(itemResult.items || []);
setActions(actionResult.actions || []);
+ setResourcesAccountId(requestedAccountId);
}, [accountId]);
useEffect(() => { loadAccounts(); }, [loadAccounts]);
@@ -158,18 +164,20 @@ export default function StackerNews() {
const saveAccount = (event) => {
event.preventDefault();
if (!selected) return;
- finish('save-account', api.updateStackerNewsAccount(selected.id, {
+ const savedAccountId = selected.id;
+ finish('save-account', api.updateStackerNewsAccount(savedAccountId, {
label: editAccount.label, username: editAccount.username, enabled: editAccount.enabled,
...(editAccount.clearApiKey ? { apiKey: '' } : editAccount.apiKey ? { apiKey: editAccount.apiKey } : {}),
monitoringEnabled: editAccount.monitoringEnabled, monitoringIntervalMinutes: Number(editAccount.monitoringIntervalMinutes),
analysisEnabled: editAccount.analysisEnabled, textModel: editAccount.textModel, visionModel: editAccount.visionModel,
rules: accountRules(editAccount),
}, { silent: true }), (result) => {
+ setAccounts((previous) => previous.map((candidate) => candidate.id === result.id ? result : candidate));
+ if (currentAccountIdRef.current !== savedAccountId) return;
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.');
});
};
@@ -255,7 +263,7 @@ export default function StackerNews() {
<h2 className="font-semibold text-white">Approval queue</h2>
<p className="mt-1 text-sm text-gray-400">Approval and execution are separate. Identity, content freshness, rules, budgets, and idempotency are rechecked at execution.</p>
<div className="mt-3 space-y-2">
- {actions.filter((action) => ['pending_review', 'approved'].includes(action.state)).map((action) => (
+ {visibleActions.filter((action) => ['pending_review', 'approved'].includes(action.state)).map((action) => (
<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>
@@ -265,12 +273,12 @@ export default function StackerNews() {
{action.state === 'approved' && <button className={`${buttonClass} mt-2`} disabled={busy === `execute-${action.id}`} onClick={() => executeAction(action)}>Execute reviewed action</button>}
</div>
))}
- {!actions.some((action) => ['pending_review', 'approved'].includes(action.state)) && <p className="text-sm text-gray-500">No actions are waiting.</p>}
+ {!visibleActions.some((action) => ['pending_review', 'approved'].includes(action.state)) && <p className="text-sm text-gray-500">No actions are waiting.</p>}
</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={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>
+ <div className="mt-3 space-y-2">{visibleItems.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>)}{!visibleItems.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>
);
@@ -280,7 +288,7 @@ export default function StackerNews() {
<section className="rounded border border-port-border bg-port-card p-4">
<h2 className="font-semibold text-white">Configured communities</h2>
<div className="mt-3 space-y-2">
- {territories.map((territory) => editingTerritoryId === territory.id ? (
+ {visibleTerritories.map((territory) => editingTerritoryId === territory.id ? (
<TerritoryForm key={territory.id} prefix={`edit-territory-${territory.id}`} title={`Edit ${territory.label || territory.slug}`} form={editTerritory} setForm={setEditTerritory} onSubmit={saveTerritory} busy={busy === `save-territory-${territory.id}`} onCancel={() => { setEditingTerritoryId(null); setEditTerritory(emptyTerritory); }} submitLabel="Save community" />
) : (
<div key={territory.id} className="rounded border border-port-border p-3">
@@ -293,7 +301,7 @@ export default function StackerNews() {
</div>
</div>
))}
- {!territories.length && <p className="text-sm text-gray-500">Add communities this account monitors or owns.</p>}
+ {!visibleTerritories.length && <p className="text-sm text-gray-500">Add communities this account monitors or owns.</p>}
</div>
</section>
<TerritoryForm prefix="new-territory" title="Add community" form={newTerritory} setForm={setNewTerritory} onSubmit={createTerritory} busy={busy === 'create-territory'} submitLabel="Add community" />
@@ -303,7 +311,7 @@ export default function StackerNews() {
const renderDrafts = () => {
const post = draft.kind.endsWith('_post');
const comment = draft.kind.endsWith('_comment');
- return <form className="mx-auto max-w-2xl rounded border border-port-border bg-port-card p-4" onSubmit={createAction}><h2 className="font-semibold text-white">Prepare a review-gated action</h2><p className="mt-1 text-sm text-gray-400">Wallet actions are browser handoffs only. Publishing uses the constrained API after separate approval.</p><div className="mt-3 space-y-3"><Field id="action-kind" label="Action"><select id="action-kind" className={fieldClass} value={draft.kind} onChange={(event) => setDraft({ ...draft, kind: event.target.value })}><option value="draft_comment">Local comment draft</option><option value="publish_comment">Publish comment after review</option><option value="draft_post">Local post draft</option><option value="publish_post">Publish post after review</option><option value="open_browser">Open fixed browser handoff</option></select></Field>{draft.kind === 'open_browser' && <Field id="action-destination" label="Handoff"><select id="action-destination" className={fieldClass} value={draft.destination} onChange={(event) => setDraft({ ...draft, destination: event.target.value })}><option value="item">Item (zap, downzap, boost, or manual interaction)</option><option value="territory_settings">Territory settings</option></select></Field>}{(comment || (draft.kind === 'open_browser' && draft.destination === 'item')) && <Field id="action-item" label="Source item"><select id="action-item" required className={fieldClass} value={draft.itemId} onChange={(event) => setDraft({ ...draft, itemId: event.target.value })}><option value="">Choose item</option>{items.map((item) => <option key={item.id} value={item.id}>{item.title || `${item.kind} by ${item.authorName}`}</option>)}</select></Field>}{(post || (draft.kind === 'open_browser' && draft.destination === 'territory_settings')) && <Field id="action-territory" label="Territory"><select id="action-territory" required className={fieldClass} value={draft.territoryId} onChange={(event) => setDraft({ ...draft, territoryId: event.target.value })}><option value="">Choose territory</option>{territories.map((territory) => <option key={territory.id} value={territory.id}>{territory.label || territory.slug}</option>)}</select></Field>}{post && <Field id="action-title" label="Title"><input id="action-title" required className={fieldClass} value={draft.title} onChange={(event) => setDraft({ ...draft, title: event.target.value })} /></Field>}{(post || comment) && <Field id="action-body" label="Draft text"><textarea id="action-body" required className={fieldClass} rows="6" value={draft.body} onChange={(event) => setDraft({ ...draft, body: event.target.value })} /></Field>}<button className={buttonClass} disabled={busy === 'create-action'}>Send to approval queue</button></div></form>;
+ return <form className="mx-auto max-w-2xl rounded border border-port-border bg-port-card p-4" onSubmit={createAction}><h2 className="font-semibold text-white">Prepare a review-gated action</h2><p className="mt-1 text-sm text-gray-400">Wallet actions are browser handoffs only. Publishing uses the constrained API after separate approval.</p><div className="mt-3 space-y-3"><Field id="action-kind" label="Action"><select id="action-kind" className={fieldClass} value={draft.kind} onChange={(event) => setDraft({ ...draft, kind: event.target.value })}><option value="draft_comment">Local comment draft</option><option value="publish_comment">Publish comment after review</option><option value="draft_post">Local post draft</option><option value="publish_post">Publish post after review</option><option value="open_browser">Open fixed browser handoff</option></select></Field>{draft.kind === 'open_browser' && <Field id="action-destination" label="Handoff"><select id="action-destination" className={fieldClass} value={draft.destination} onChange={(event) => setDraft({ ...draft, destination: event.target.value })}><option value="item">Item (zap, downzap, boost, or manual interaction)</option><option value="territory_settings">Territory settings</option></select></Field>}{(comment || (draft.kind === 'open_browser' && draft.destination === 'item')) && <Field id="action-item" label="Source item"><select id="action-item" required className={fieldClass} value={draft.itemId} onChange={(event) => setDraft({ ...draft, itemId: event.target.value })}><option value="">Choose item</option>{visibleItems.map((item) => <option key={item.id} value={item.id}>{item.title || `${item.kind} by ${item.authorName}`}</option>)}</select></Field>}{(post || (draft.kind === 'open_browser' && draft.destination === 'territory_settings')) && <Field id="action-territory" label="Territory"><select id="action-territory" required className={fieldClass} value={draft.territoryId} onChange={(event) => setDraft({ ...draft, territoryId: event.target.value })}><option value="">Choose territory</option>{visibleTerritories.map((territory) => <option key={territory.id} value={territory.id}>{territory.label || territory.slug}</option>)}</select></Field>}{post && <Field id="action-title" label="Title"><input id="action-title" required className={fieldClass} value={draft.title} onChange={(event) => setDraft({ ...draft, title: event.target.value })} /></Field>}{(post || comment) && <Field id="action-body" label="Draft text"><textarea id="action-body" required className={fieldClass} rows="6" value={draft.body} onChange={(event) => setDraft({ ...draft, body: event.target.value })} /></Field>}<button className={buttonClass} disabled={busy === 'create-action'}>Send to approval queue</button></div></form>;
};
const renderAccounts = () => (
@@ -316,7 +324,7 @@ export default function StackerNews() {
if (loading) return <PageSkeleton header="bar" label="Loading Stacker News" tabs={TABS.length} cards={3} />;
const notFound = accountId && !selected;
- return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={Newspaper} title="Stacker News" subtitle="Review-gated multi-account community stewardship" actions={selected && <span className="text-sm text-gray-400">@{selected.username}</span>} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/stacker-news')} ariaLabel="Stacker News 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>}{notFound && <div className="mb-3 rounded border border-port-error p-4 text-sm text-port-error">This Stacker News account was not found. <button className="underline" onClick={() => navigate('/stacker-news')}>Return to accounts.</button></div>}{activeTab === 'review' && selected && renderReview()}{activeTab === 'territory' && selected && renderTerritory()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'activity' && selected && <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Action ledger</h2><div className="mt-3 space-y-2">{actions.map((action) => <div key={action.id} className="rounded border border-port-border p-3 text-sm text-gray-300"><div>{action.kind.replaceAll('_', ' ')} · {action.state}</div>{action.error && <div className="mt-1 text-port-error">{action.error}</div>}{action.result?.handoffOpened && <div className="mt-1 text-gray-400">Fixed browser handoff opened.</div>}</div>)}{!actions.length && <p className="text-sm text-gray-500">No actions recorded.</p>}</div></section>}{activeTab === 'accounts' && renderAccounts()}</main></div>;
+ return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={Newspaper} title="Stacker News" subtitle="Review-gated multi-account community stewardship" actions={selected && <span className="text-sm text-gray-400">@{selected.username}</span>} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/stacker-news')} ariaLabel="Stacker News 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>}{notFound && <div className="mb-3 rounded border border-port-error p-4 text-sm text-port-error">This Stacker News account was not found. <button className="underline" onClick={() => navigate('/stacker-news')}>Return to accounts.</button></div>}{activeTab === 'review' && selected && renderReview()}{activeTab === 'territory' && selected && renderTerritory()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'activity' && selected && <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Action ledger</h2><div className="mt-3 space-y-2">{visibleActions.map((action) => <div key={action.id} className="rounded border border-port-border p-3 text-sm text-gray-300"><div>{action.kind.replaceAll('_', ' ')} · {action.state}</div>{action.error && <div className="mt-1 text-port-error">{action.error}</div>}{action.result?.handoffOpened && <div className="mt-1 text-gray-400">Fixed browser handoff opened.</div>}</div>)}{!visibleActions.length && <p className="text-sm text-gray-500">No actions recorded.</p>}</div></section>}{activeTab === 'accounts' && renderAccounts()}</main></div>;
}
function Field({ id, label, children }) {
diff --git a/client/src/pages/StackerNews.test.jsx b/client/src/pages/StackerNews.test.jsx
index 2225184ab3..ee397892b1 100644
--- a/client/src/pages/StackerNews.test.jsx
+++ b/client/src/pages/StackerNews.test.jsx
@@ -95,6 +95,20 @@ describe('StackerNews', () => {
expect(screen.getByText('Current community')).toBeInTheDocument();
});
+ it('hides executable actions immediately when account selection changes', async () => {
+ const user = userEvent.setup();
+ const nextActions = deferred();
+ api.getStackerNewsActions.mockImplementation((id) => id === 'a1'
+ ? Promise.resolve({ actions: [{ id: 'old-action', kind: 'publish_comment', state: 'approved', payload: { body: 'Old account action' }, reviewedTarget: { username: 'art_steward' }, policyVersion: 'v1' }] })
+ : nextActions.promise);
+ renderPage('/stacker-news/a1/review');
+ expect(await screen.findByRole('button', { name: 'Execute reviewed action' })).toBeInTheDocument();
+ await user.click(screen.getByRole('tab', { name: 'Accounts & Safety' }));
+ await user.click(await screen.findByRole('button', { name: /Personal/ }));
+ expect(screen.queryByRole('button', { name: 'Execute reviewed action' })).not.toBeInTheDocument();
+ await act(async () => nextActions.resolve({ actions: [] }));
+ });
+
it('gates server-side account actions on saved settings and the in-flight save', async () => {
const user = userEvent.setup();
const save = deferred();
@@ -121,6 +135,22 @@ describe('StackerNews', () => {
await waitFor(() => expect(api.updateStackerNewsAccount).toHaveBeenCalledWith('a1', expect.objectContaining({ apiKey: '' }), { silent: true }));
});
+ it('ignores an old account save completion after navigation', 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');
+ await user.click(screen.getByRole('button', { name: 'Save account' }));
+ await user.click(screen.getByRole('button', { name: /Personal/ }));
+ expect(await screen.findByDisplayValue('personal_stacker')).toBeInTheDocument();
+ await act(async () => save.resolve({ ...accounts[0], monitoringIntervalMinutes: 20 }));
+ expect(screen.getByDisplayValue('personal_stacker')).toBeInTheDocument();
+ expect(screen.getByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' })).toHaveValue(60);
+ });
+
it('edits and deletes configured communities through inline controls', async () => {
const user = userEvent.setup();
const territory = { id: 't1', accountId: 'a1', slug: 'art', label: 'Art', isOwned: false, monitoringEnabled: null, inheritAccountRules: true, rules: {} };
diff --git a/server/scripts/db-migrations/005-stacker-news-sparse-territory-budgets.js b/server/scripts/db-migrations/005-stacker-news-sparse-territory-budgets.js
new file mode 100644
index 0000000000..e426f36674
--- /dev/null
+++ b/server/scripts/db-migrations/005-stacker-news-sparse-territory-budgets.js
@@ -0,0 +1,11 @@
+/**
+ * Early preview builds expanded omitted territory budgets to the global
+ * defaults. Remove only that generated shape so account limits inherit again.
+ */
+export async function up(client) {
+ await client.query(
+ `UPDATE stacker_news_territories
+ SET rules=rules-'actionBudget',updated_at=NOW()
+ WHERE rules->'actionBudget'='{"maxPerHour":3,"maxPerDay":12,"minMinutesBetween":5}'::jsonb`,
+ );
+}
diff --git a/server/scripts/db-migrations/005-stacker-news-sparse-territory-budgets.test.js b/server/scripts/db-migrations/005-stacker-news-sparse-territory-budgets.test.js
new file mode 100644
index 0000000000..3f8ee19608
--- /dev/null
+++ b/server/scripts/db-migrations/005-stacker-news-sparse-territory-budgets.test.js
@@ -0,0 +1,11 @@
+import { describe, expect, it, vi } from 'vitest';
+import { up } from './005-stacker-news-sparse-territory-budgets.js';
+
+describe('Stacker News sparse territory budget migration', () => {
+ it('removes only the generated default budget shape', async () => {
+ const query = vi.fn(async () => ({ rows: [] }));
+ await up({ query });
+ expect(query.mock.calls[0][0]).toContain("rules=rules-'actionBudget'");
+ expect(query.mock.calls[0][0]).toContain('"maxPerDay":12');
+ });
+});
diff --git a/server/services/stackerNews.js b/server/services/stackerNews.js
index 93d34587df..bc874a2dc2 100644
--- a/server/services/stackerNews.js
+++ b/server/services/stackerNews.js
@@ -10,6 +10,7 @@ import {
combineStackerNewsModelResults,
evaluateStackerNewsPolicy,
hashStackerNewsRules,
+ normalizeStackerNewsRuleOverrides,
normalizeStackerNewsRules,
parseStackerNewsModelResult,
resolveStackerNewsRules,
@@ -202,7 +203,7 @@ export async function createTerritory({ accountId, slug, label = '', isOwned = f
const result = await query(
`INSERT INTO stacker_news_territories (id,account_id,slug,label,is_owned,monitoring_enabled,inherit_account_rules,rules)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`,
- [randomUUID(), accountId, slug, label, isOwned, monitoringEnabled, inheritAccountRules, normalizeStackerNewsRules(rules)],
+ [randomUUID(), accountId, slug, label, isOwned, monitoringEnabled, inheritAccountRules, normalizeStackerNewsRuleOverrides(rules)],
);
return territoryView(result.rows[0]);
}
@@ -211,13 +212,17 @@ export async function updateTerritory(id, updates) {
const previous = await query('SELECT * FROM stacker_news_territories WHERE id=$1', [id]);
const existing = previous.rows[0];
if (!existing) return null;
+ const nextSlug = updates.slug ?? existing.slug;
+ const slugChanged = nextSlug !== existing.slug;
const result = await query(
`UPDATE stacker_news_territories SET slug=$2,label=$3,is_owned=$4,monitoring_enabled=$5,
- inherit_account_rules=$6,rules=$7,updated_at=NOW() WHERE id=$1 RETURNING *`,
- [id, updates.slug ?? existing.slug, updates.label ?? existing.label, updates.isOwned ?? existing.is_owned,
+ inherit_account_rules=$6,rules=$7,remote_settings=$8,remote_refreshed_at=$9,updated_at=NOW() WHERE id=$1 RETURNING *`,
+ [id, nextSlug, updates.label ?? existing.label, updates.isOwned ?? existing.is_owned,
updates.monitoringEnabled === undefined ? existing.monitoring_enabled : updates.monitoringEnabled,
updates.inheritAccountRules ?? existing.inherit_account_rules,
- updates.rules === undefined ? existing.rules : normalizeStackerNewsRules(updates.rules)],
+ updates.rules === undefined ? existing.rules : normalizeStackerNewsRuleOverrides(updates.rules),
+ slugChanged ? {} : existing.remote_settings,
+ slugChanged ? null : existing.remote_refreshed_at],
);
return territoryView(result.rows[0]);
}
@@ -452,20 +457,25 @@ const eventInsert = (client, actionId, fromState, toState, note = '', metadata =
);
async function actionContext({ accountId, itemId, territoryId }) {
- const [account, itemResult, territoryResult] = await Promise.all([
+ const [account, itemResult] = await Promise.all([
getAccountRow(accountId),
itemId ? query('SELECT * FROM stacker_news_items WHERE id=$1 AND account_id=$2', [itemId, accountId]) : Promise.resolve({ rows: [] }),
- territoryId ? query('SELECT * FROM stacker_news_territories WHERE id=$1 AND account_id=$2', [territoryId, accountId]) : Promise.resolve({ rows: [] }),
]);
- return { account, item: itemResult.rows[0] || null, territory: territoryResult.rows[0] || null };
+ const item = itemResult.rows[0] || null;
+ if (item && territoryId && territoryId !== item.territory_id) throw new Error('Stacker News territory does not match the selected item');
+ const resolvedTerritoryId = territoryId || item?.territory_id || null;
+ const territoryResult = resolvedTerritoryId
+ ? await query('SELECT * FROM stacker_news_territories WHERE id=$1 AND account_id=$2', [resolvedTerritoryId, accountId])
+ : { rows: [] };
+ return { account, item, territory: territoryResult.rows[0] || null, resolvedTerritoryId };
}
export async function createAction({ accountId, itemId = null, territoryId = null, kind, destination = '', payload = {} }) {
if (!ACTION_KINDS.has(kind)) throw new Error('Unsupported Stacker News action kind');
- const { account, item, territory } = await actionContext({ accountId, itemId, territoryId });
+ const { account, item, territory, resolvedTerritoryId } = await actionContext({ accountId, itemId, territoryId });
if (!account) throw new Error('Stacker News account not found');
if (itemId && !item) throw new Error('Stacker News item not found for account');
- if (territoryId && !territory) throw new Error('Stacker News territory not found for account');
+ if (resolvedTerritoryId && !territory) throw new Error('Stacker News territory not found for account');
const rules = resolveStackerNewsRules(account.rules, territory?.rules, territory?.inherit_account_rules ?? true);
const rulesHash = hashStackerNewsRules(rules);
const sourceContentHash = item?.content_hash || '';
@@ -474,7 +484,7 @@ export async function createAction({ accountId, itemId = null, territoryId = nul
territorySlug: territory?.slug || '',
remoteItemId: item?.remote_id || '',
};
- const idempotencyKey = stableHash({ accountId, itemId, territoryId, kind, destination, payload, sourceContentHash, rulesHash, reviewedTarget });
+ const idempotencyKey = stableHash({ accountId, itemId, territoryId: resolvedTerritoryId, kind, destination, payload, sourceContentHash, rulesHash, reviewedTarget });
const id = randomUUID();
const row = await withTransaction(async (client) => {
const active = await client.query(
@@ -499,7 +509,7 @@ export async function createAction({ accountId, itemId = null, territoryId = nul
(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],
+ [id, accountId, itemId, resolvedTerritoryId, kind, destination, payload, sourceContentHash, rulesHash, POLICY_VERSION, idempotencyKey, reviewedTarget],
);
if (result.rows[0]) {
await eventInsert(client, id, null, 'pending_review', 'Created for human review');
diff --git a/server/services/stackerNewsActions.test.js b/server/services/stackerNewsActions.test.js
index 27e479b5bd..3756140961 100644
--- a/server/services/stackerNewsActions.test.js
+++ b/server/services/stackerNewsActions.test.js
@@ -2,7 +2,7 @@ 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' };
+const item = { id: 'item', account_id: 'account', territory_id: 'territory', remote_id: '42', content_hash: 'content-hash' };
let actionForExecution = null;
const query = vi.fn(async (sql) => {
@@ -47,6 +47,24 @@ describe('Stacker News reviewed actions', () => {
expect(transactionQuery.mock.calls.find(([sql]) => sql.includes('INSERT INTO stacker_news_actions'))[0]).toContain('reviewed_target');
});
+ it('derives an item action territory and rejects an explicit mismatch', async () => {
+ const action = await createAction({
+ accountId: account.id,
+ itemId: item.id,
+ kind: 'publish_comment',
+ payload: { body: 'Thanks for sharing.' },
+ });
+ expect(action.territoryId).toBe(territory.id);
+ expect(action.reviewedTarget.territorySlug).toBe('art');
+ await expect(createAction({
+ accountId: account.id,
+ itemId: item.id,
+ territoryId: 'different-territory',
+ kind: 'publish_comment',
+ payload: { body: 'Thanks for sharing.' },
+ })).rejects.toThrow('territory does not match');
+ });
+
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,
diff --git a/server/services/stackerNewsPolicy.js b/server/services/stackerNewsPolicy.js
index 67a7ba51ed..0514dbc952 100644
--- a/server/services/stackerNewsPolicy.js
+++ b/server/services/stackerNewsPolicy.js
@@ -34,6 +34,20 @@ export function normalizeStackerNewsRules(value = {}) {
};
}
+export function normalizeStackerNewsRuleOverrides(value = {}) {
+ const rules = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
+ const normalized = normalizeStackerNewsRules(rules);
+ const rawBudget = rules.actionBudget && typeof rules.actionBudget === 'object' && !Array.isArray(rules.actionBudget)
+ ? rules.actionBudget
+ : {};
+ return {
+ ...normalized,
+ actionBudget: Object.fromEntries(Object.keys(normalized.actionBudget)
+ .filter((key) => Number.isInteger(rawBudget[key]))
+ .map((key) => [key, normalized.actionBudget[key]])),
+ };
+}
+
export function resolveStackerNewsRules(accountRules, territoryRules, inheritAccountRules = true) {
const account = normalizeStackerNewsRules(accountRules);
const territory = normalizeStackerNewsRules(territoryRules);
diff --git a/server/services/stackerNewsPolicy.test.js b/server/services/stackerNewsPolicy.test.js
index 2696e0c8e0..5dfb7a967a 100644
--- a/server/services/stackerNewsPolicy.test.js
+++ b/server/services/stackerNewsPolicy.test.js
@@ -13,6 +13,15 @@ describe('Stacker News policy', () => {
expect(rules.actionBudget.maxPerDay).toBe(2);
});
+ it('preserves account budgets when a territory omitted budget overrides', () => {
+ const rules = resolveStackerNewsRules(
+ { actionBudget: { maxPerHour: 1, maxPerDay: 1, minMinutesBetween: 60 } },
+ { guidance: 'Community-specific guidance', actionBudget: {} },
+ true,
+ );
+ expect(rules.actionBudget).toEqual({ maxPerHour: 1, maxPerDay: 1, minMinutesBetween: 60 });
+ });
+
it('rejects unknown model fields and model-proposed action names', () => {
expect(() => parseStackerNewsModelResult({ classification: 'allowed', risk: 'low', summary: '', findings: [], suggestedAction: 'zap', tool: 'shell' })).toThrow();
});
diff --git a/server/services/stackerNewsTerritories.test.js b/server/services/stackerNewsTerritories.test.js
new file mode 100644
index 0000000000..f78705d0d1
--- /dev/null
+++ b/server/services/stackerNewsTerritories.test.js
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const existing = {
+ id: 'territory',
+ account_id: 'account',
+ slug: 'old-art',
+ label: 'Art',
+ is_owned: true,
+ monitoring_enabled: true,
+ inherit_account_rules: true,
+ rules: {},
+ remote_settings: { ownershipVerified: true, name: 'old-art' },
+ remote_refreshed_at: new Date(),
+};
+const query = vi.fn(async (sql, params) => {
+ if (sql.startsWith('SELECT * FROM stacker_news_territories')) return { rows: [existing] };
+ if (sql.startsWith('UPDATE stacker_news_territories')) return { rows: [{
+ ...existing,
+ slug: params[1],
+ remote_settings: params[7],
+ remote_refreshed_at: params[8],
+ }] };
+ return { rows: [] };
+});
+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 { updateTerritory } = await import('./stackerNews.js');
+
+describe('Stacker News territory ownership evidence', () => {
+ it('clears remote evidence when the configured slug changes', async () => {
+ const territory = await updateTerritory(existing.id, { slug: 'new-art' });
+ expect(territory.remoteSettings).toEqual({});
+ expect(territory.remoteRefreshedAt).toBeNull();
+ });
+});