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

feat: route Stacker News risk decisions through jev (#7681)

[._.]/ Adam Eivya1dc62340cf1
diff --git a/docs/features/messages-security.md b/docs/features/messages-security.md
index bb5c66d35e..eb1959657d 100644
--- a/docs/features/messages-security.md
+++ b/docs/features/messages-security.md
@@ -44,7 +44,7 @@ The GitHub role split does not change explicitly configured Jira or existing Git
**Measuring before you switch.** While a source is `off` and the scorer is installed, PortOS asks it each closed-set question after the chat model has answered, discards the answer, and folds the comparison into per-decision counters shown in **Models > LLMs > jev**. The counters are counts only — decision id, which bucket it landed in, and whether it agreed. No premise, message body, comment or diff is recorded, and neither side's verdict is kept.
- **Which decisions are routed.** The issue-watcher reply gate (`reply` / `none`), message triage (action and priority, as two independent decisions over one premise — one abstention retires the whole message), and the forge-maintenance disposition. A jev `reply` verdict still wakes the chat model to write the body; the gate only decides whether waking it is worth it. Stacker News is screened as the `stacker-news` source but is **not** jev-routed: its verdict is a classification, risk band and free-text findings, not a closed set an entailment head can answer.
+ **Which decisions are routed.** The issue-watcher reply gate (`reply` / `none`), message triage (action and priority, as two independent decisions over one premise — one abstention retires the whole message), the forge-maintenance disposition, and Stacker News classification/risk. Stacker News is an **escalation-only** gate: after phase-1 screening, jev may settle an item only when classification is `escalate` or risk is `high`; `allowed` / `low` remain shadow observations and the text and vision models still run, so their prose and `disallowedThemes` scan cannot be bypassed. The `allowed` classification option carries a `1.0` floor to encode that it is never acted on. A jev `reply` verdict still wakes the chat model to write the body; the gate only decides whether waking it is worth it.
3. **Validate and authorize effects in code.** Callers supply strict response contracts and check source identities and fresh state before acting. Issue replies and assignments use known issue/comment IDs; model prose never becomes a shell command. Maintenance analysis returns only fixed enums, not a freeform model summary that could repeat an attack. Issue maintenance separately receives screened requirements authored by a trusted account and a verified merge commit on the default branch; it can inspect that accepted code without importing outside PR descriptions. Message triage remains recommendations; replies remain drafts under the existing send-authorization flow.
PR review does not execute contributor tests or apply patches in its default stages. Read-only filesystem access and a disposable worktree are not equivalent to denying tools or isolating malicious code. A provider must expose an actual maintained recipe for the requested posture; unsupported stage pins must be corrected in schedule settings. A screening pass never grants broader permissions.
diff --git a/server/lib/jevDecisions.js b/server/lib/jevDecisions.js
index 5a07b8a493..c7d899a52f 100644
--- a/server/lib/jevDecisions.js
+++ b/server/lib/jevDecisions.js
@@ -20,8 +20,8 @@ import { JEV_DEFAULT_MIN_MARGIN, JEV_MAX_HYPOTHESIS_CHARS } from './jev.js';
* `source` is the INGRESS CHANNEL a decision's premise arrives on, and it is
* `null` for a decision that has none.
*
- * The four untrusted-content rungs each answer a question about text that
- * arrived from somewhere (`github-issue`, `email`, …), and their channel is
+ * The untrusted-content rungs each answer a question about text that arrived
+ * from somewhere (`github-issue`, `email`, …), and their channel is
* what `resolveUntrustedContentPolicy` keys the operator's per-source `jevMode`
* on. `scope-adherence` asks about the operator's OWN product documents
* instead, so there is no channel to name and no per-source policy to resolve —
@@ -109,6 +109,50 @@ export const JEV_DECISIONS = Object.freeze({
]),
}),
+ 'stacker-news-classification': Object.freeze({
+ source: 'stacker-news',
+ label: 'Stacker News classification',
+ minMargin: 0.25,
+ options: Object.freeze([
+ Object.freeze({
+ // The Stacker News caller never releases an item on this verdict alone;
+ // it remains a shadow observation so the model-backed prose checks keep
+ // their full context.
+ value: 'allowed',
+ hypothesis: 'This Stacker News item is ordinary community content that can proceed without moderation escalation.',
+ minMargin: 1.0,
+ }),
+ Object.freeze({
+ value: 'review',
+ hypothesis: 'This Stacker News item may be legitimate but needs human review before any community action.',
+ }),
+ Object.freeze({
+ value: 'escalate',
+ hypothesis: 'This Stacker News item contains hostile, unsafe, or policy-sensitive content that should be escalated before any automated action.',
+ }),
+ ]),
+ }),
+
+ 'stacker-news-risk': Object.freeze({
+ source: 'stacker-news',
+ label: 'Stacker News risk',
+ minMargin: 0.25,
+ options: Object.freeze([
+ Object.freeze({
+ value: 'low',
+ hypothesis: 'This Stacker News item presents low risk under the community rules.',
+ }),
+ Object.freeze({
+ value: 'medium',
+ hypothesis: 'This Stacker News item presents meaningful uncertainty or moderate risk under the community rules.',
+ }),
+ Object.freeze({
+ value: 'high',
+ hypothesis: 'This Stacker News item presents high risk under the community rules and should be escalated.',
+ }),
+ ]),
+ }),
+
'forge-maintenance-disposition': Object.freeze({
source: 'github-issue',
label: 'Forge maintenance discussion disposition',
diff --git a/server/lib/jevDecisions.test.js b/server/lib/jevDecisions.test.js
index cee8c4e943..45bb5557b5 100644
--- a/server/lib/jevDecisions.test.js
+++ b/server/lib/jevDecisions.test.js
@@ -12,6 +12,10 @@ import {
} from './jevDecisions.js';
import { UNTRUSTED_CONTENT_SOURCES, untrustedContentPolicySchema } from './untrustedContent.js';
+// Keep the contract assertion from making the broad jev test suite eagerly
+// instantiate the Stacker News service subtree.
+const { modelAnalysisSchema } = await import('../services/stackerNewsPolicy.js');
+
describe('shipped jev decisions', () => {
// A typo here is silent in production: the scorer rejects the request, the
// caller falls back, and the chat model keeps answering forever.
@@ -55,6 +59,7 @@ describe('shipped jev decisions', () => {
expect(jevMinMarginFor('message-triage', { optionValue: 'delete', policyMinMargin: 0 })).toBe(0.6);
expect(jevMinMarginFor('message-triage', { optionValue: 'archive', policyMinMargin: 0 })).toBe(JEV_DECISIONS['message-triage'].minMargin);
expect(jevMinMarginFor('message-triage', { optionValue: 'archive', policyMinMargin: 0.9 })).toBe(0.9);
+ expect(jevMinMarginFor('stacker-news-classification', { optionValue: 'allowed', policyMinMargin: 0 })).toBe(1);
expect(jevMinMarginFor('no-such-decision')).toBeNull();
// Every destructive-leaning option carries a floor above its decision's.
for (const [decisionId, optionValue] of [['message-triage', 'delete'], ['forge-maintenance-disposition', 'inspect-trusted-change']]) {
@@ -79,6 +84,8 @@ describe('shipped jev decisions', () => {
'issue-comment-reply': z.enum(['reply', 'none']),
'message-triage': z.enum(['reply', 'archive', 'delete', 'review']),
'message-priority': z.enum(['high', 'medium', 'low']),
+ 'stacker-news-classification': modelAnalysisSchema.shape.classification,
+ 'stacker-news-risk': modelAnalysisSchema.shape.risk,
'forge-maintenance-disposition': z.enum(['inspect-trusted-change', 'defer']),
'scope-adherence': z.enum(['aligned', 'unrelated', 'contradicts']),
};
diff --git a/server/services/stackerNews.js b/server/services/stackerNews.js
index efb2cec52a..cbba0807b5 100644
--- a/server/services/stackerNews.js
+++ b/server/services/stackerNews.js
@@ -446,7 +446,7 @@ export async function analyzeItem(itemId) {
// Deferred: `services/untrustedContent.js` pulls settings + providers, and
// `stackerNews.js` is reached by the routes and a dozen suites that never
// analyze anything. See "Import scoping" in server/AGENTS.md.
- const { screenUntrustedContent } = await import('./untrustedContent.js');
+ const { jevBatchGate, screenUntrustedContent } = await import('./untrustedContent.js');
const screening = await screenUntrustedContent({ content: fullContent, source: UNTRUSTED_CONTENT_SOURCE });
const deterministic = {
injectionRisk: injectionMatches.length ? 'high' : 'low', injectionMatches, sourceTrusted: false, contentLength: content.length,
@@ -464,6 +464,42 @@ export async function analyzeItem(itemId) {
return { item: itemView(item), analysisId: blockedId, stale: false, deterministic, text: null, vision: null, combinedModel: null, policy: blocked, errors: [] };
}
+ const jevGate = await jevBatchGate({
+ content: fullContent,
+ source: UNTRUSTED_CONTENT_SOURCE,
+ items: [{
+ key: item.id,
+ premise: () => fullContent,
+ decisionIds: ['stacker-news-classification', 'stacker-news-risk'],
+ }],
+ // A local allowed/low answer cannot replace the prose-bearing chat result:
+ // evaluateStackerNewsPolicy needs that prose to scan disallowedThemes. Only
+ // the restrictive side of either enum is safe to act on without it.
+ accept: (choices) => choices['stacker-news-classification'] === 'escalate'
+ || choices['stacker-news-risk'] === 'high',
+ });
+ const jevChoices = jevGate.decided.get(item.id);
+ if (jevChoices && !injectionMatches.length) {
+ const jevModel = {
+ classification: jevChoices['stacker-news-classification'],
+ risk: jevChoices['stacker-news-risk'],
+ summary: '',
+ findings: [],
+ suggestedAction: 'none',
+ };
+ await jevGate.measure();
+ const policy = evaluateStackerNewsPolicy({ deterministic, model: jevModel, rules });
+ await persistAnalysis({ item, stage: 'text', provider: 'jev', rulesHash, result: jevModel });
+ const analysisId = await persistAnalysis({ item, stage: 'policy', provider: 'deterministic', rulesHash, result: policy });
+ return { item: itemView(item), analysisId, stale: false, deterministic, text: jevModel, vision: null, combinedModel: jevModel, policy, errors: [] };
+ }
+ if (jevGate.skipped.some((entry) => entry.key === item.id) && !injectionMatches.length) {
+ const policy = { decision: 'review', reasons: ['jev_only_unsettled'], allowedAction: 'none' };
+ await jevGate.measure();
+ const analysisId = await persistAnalysis({ item, stage: 'policy', provider: 'jev', status: 'skipped', rulesHash, result: policy });
+ return { item: itemView(item), analysisId, stale: false, skipped: true, skipReason: 'jev_only_unsettled', deterministic, text: null, vision: null, combinedModel: null, policy, errors: [] };
+ }
+
let textResult = null;
let visionResult = null;
const errors = [];
@@ -500,6 +536,12 @@ 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 combinedModel = combineStackerNewsModelResults(textResult, visionResult);
+ await jevGate.measure(combinedModel ? {
+ [item.id]: {
+ 'stacker-news-classification': combinedModel.classification,
+ 'stacker-news-risk': combinedModel.risk,
+ },
+ } : undefined);
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, combinedModel, policy, errors };
diff --git a/server/services/stackerNewsScreening.test.js b/server/services/stackerNewsScreening.test.js
index b9d6f09900..00f2367aac 100644
--- a/server/services/stackerNewsScreening.test.js
+++ b/server/services/stackerNewsScreening.test.js
@@ -18,7 +18,7 @@ const query = vi.fn(async (sql, params) => {
if (sql.startsWith('SELECT * FROM stacker_news_territories')) return { rows: [] };
if (sql.startsWith('SELECT content_hash')) return { rows: [{ content_hash: item.content_hash }] };
if (sql.includes('INSERT INTO stacker_news_analyses')) {
- analysisRows.push({ id: params[0], stage: params[2], provider: params[3], result: params[9] });
+ analysisRows.push({ id: params[0], stage: params[2], provider: params[3], status: params[5], result: params[9] });
}
return { rows: [], rowCount: 1 };
});
@@ -26,13 +26,14 @@ const query = vi.fn(async (sql, params) => {
const fetchWithTimeout = vi.fn();
const fetchAndNormalizeStackerNewsImage = vi.fn();
const screenUntrustedContent = vi.fn();
+const jevBatchGate = vi.fn();
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(), executeStackerNewsBrowserRead: vi.fn(), stackerNewsCapabilities: {} }));
vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout }));
vi.mock('./stackerNewsMedia.js', () => ({ fetchAndNormalizeStackerNewsImage, hashRemoteMediaUrl: (url) => `hash:${url}` }));
-vi.mock('./untrustedContent.js', () => ({ screenUntrustedContent }));
+vi.mock('./untrustedContent.js', () => ({ jevBatchGate, screenUntrustedContent }));
const { analyzeItem } = await import('./stackerNews.js');
const { UNTRUSTED_CONTENT_INSTRUCTIONS } = await import('../lib/untrustedContent.js');
@@ -40,13 +41,18 @@ const { UNTRUSTED_CONTENT_INSTRUCTIONS } = await import('../lib/untrustedContent
const ollamaResponse = (body) => ({ ok: true, json: async () => ({ message: { content: JSON.stringify(body) } }) });
const allowed = { classification: 'allowed', risk: 'low', summary: 'Ordinary post', findings: [], suggestedAction: 'none' };
const stageResult = (stage) => analysisRows.find((row) => row.stage === stage)?.result;
+let gate;
beforeEach(() => {
analysisRows.length = 0;
+ account.rules = {};
query.mockClear();
fetchWithTimeout.mockReset();
fetchAndNormalizeStackerNewsImage.mockReset();
screenUntrustedContent.mockReset();
+ gate = { decided: new Map(), pending: [{ key: 'item' }], skipped: [], measure: vi.fn() };
+ jevBatchGate.mockReset();
+ jevBatchGate.mockResolvedValue(gate);
item = {
id: 'item', account_id: 'account', territory_id: null, content_hash: 'hash',
// Deliberately free of the local INJECTION_PATTERNS, so a skipped model call
@@ -66,6 +72,65 @@ describe('Stacker News phase-1 screening', () => {
expect(fetchAndNormalizeStackerNewsImage).not.toHaveBeenCalled();
});
+ it.each([
+ ['classification escalation', { classification: 'escalate', risk: 'low' }],
+ ['high risk', { classification: 'allowed', risk: 'high' }],
+ ])('uses jev %s without any text or vision calls', async (_label, choices) => {
+ screenUntrustedContent.mockResolvedValue({ ok: true, safe: true });
+ gate.decided.set('item', {
+ 'stacker-news-classification': choices.classification,
+ 'stacker-news-risk': choices.risk,
+ });
+ gate.pending = [];
+ gate.measure.mockResolvedValue(null);
+
+ const analysis = await analyzeItem('item');
+
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ expect(fetchAndNormalizeStackerNewsImage).not.toHaveBeenCalled();
+ expect(analysis.policy).toMatchObject({ decision: 'escalate', allowedAction: 'none' });
+ expect(analysis.text).toMatchObject({ ...choices, summary: '', findings: [], suggestedAction: 'none' });
+ const jevRows = analysisRows.filter((row) => row.provider === 'jev');
+ expect(jevRows).toHaveLength(1);
+ expect(jevRows[0]).toMatchObject({ stage: 'text', status: 'completed' });
+ expect(jevRows[0].result).toMatchObject({ ...choices, summary: '', findings: [] });
+ expect(gate.measure).toHaveBeenCalledWith();
+ });
+
+ it('falls through on an allowed/low jev verdict so model prose still scans disallowed themes', async () => {
+ screenUntrustedContent.mockResolvedValue({ ok: true, safe: true });
+ account.rules = { disallowedThemes: ['ordinary'] };
+ fetchAndNormalizeStackerNewsImage.mockResolvedValue({
+ base64: 'image-bytes', sourceUrlHash: 'hash', contentHash: 'image-hash', mimeType: 'image/png', width: 1, height: 1, byteLength: 11,
+ });
+ fetchWithTimeout.mockResolvedValue(ollamaResponse(allowed));
+
+ const analysis = await analyzeItem('item');
+
+ expect(fetchWithTimeout).toHaveBeenCalledTimes(2);
+ expect(fetchAndNormalizeStackerNewsImage).toHaveBeenCalledTimes(1);
+ expect(analysis.policy).toMatchObject({ decision: 'review', reasons: ['disallowed_theme:ordinary'] });
+ expect(gate.measure).toHaveBeenCalledWith({
+ item: { 'stacker-news-classification': 'allowed', 'stacker-news-risk': 'low' },
+ });
+ expect(analysisRows.some((row) => row.provider === 'jev')).toBe(false);
+ });
+
+ it('records a skip instead of releasing an abstention in jev only mode', async () => {
+ screenUntrustedContent.mockResolvedValue({ ok: true, safe: true });
+ gate.pending = [];
+ gate.skipped = [{ key: 'item' }];
+ gate.measure.mockResolvedValue(null);
+
+ const analysis = await analyzeItem('item');
+
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ expect(fetchAndNormalizeStackerNewsImage).not.toHaveBeenCalled();
+ expect(analysis).toMatchObject({ skipped: true, skipReason: 'jev_only_unsettled', policy: { decision: 'review', reasons: ['jev_only_unsettled'] } });
+ expect(analysisRows.find((row) => row.provider === 'jev')).toMatchObject({ stage: 'policy', status: 'skipped', result: { reasons: ['jev_only_unsettled'] } });
+ expect(gate.measure).toHaveBeenCalledWith();
+ });
+
it('persists the screening code and escalates instead of returning allowed', async () => {
screenUntrustedContent.mockResolvedValue({ ok: false, safe: false, code: 'untrusted-content-too-large', message: 'too large' });
const analysis = await analyzeItem('item');