feedkeeper 0.38.6 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feedkeeper",
3
- "version": "0.38.6",
3
+ "version": "0.40.0",
4
4
  "description": "A lightweight, self-hosted RSS reader and remote MCP server for your news, blogs, and AI workflows.",
5
5
  "keywords": [
6
6
  "rss",
@@ -44,6 +44,7 @@ const FEATURES = [
44
44
  "native-preferences.client-settings",
45
45
  "edition.overview",
46
46
  "edition.layout",
47
+ "edition.feedback",
47
48
  "search.fts",
48
49
  "account-capabilities",
49
50
  "account-profile",
@@ -22,6 +22,7 @@ import { buildOverview } from "../../mcp/digest.js";
22
22
  import { decodeCursor, encodeCursor } from "../../mcp/items.js";
23
23
  import { readingPositions, serializeItem, serializeSubscriptionDetail } from "./serialize.js";
24
24
  import { dismissEdition, editionCandidates, ensureEditionSchema, getEdition, getEditionState } from "../../native/editions.js";
25
+ import { getEditionFeedback, resetEditionFeedback, setEditionFeedback } from "../../native/editionFeedback.js";
25
26
  import { getNativePreferences, patchNativePreferences } from "../../native/preferences.js";
26
27
  import { NativeError } from "../../native/requests.js";
27
28
  import { capabilityDenial, hasUserCapability, requireCapability } from "../../auth/capabilities.js";
@@ -619,6 +620,31 @@ resourcesRouter.delete("/edition", (req, res) => {
619
620
  res.status(204).end();
620
621
  });
621
622
  });
623
+ resourcesRouter.get("/edition/feedback", (req, res) => {
624
+ res.setHeader("Cache-Control", "private, no-store");
625
+ const edition = getEdition(req.user.id);
626
+ const itemIds = edition ? edition.itemIds : undefined;
627
+ res.json(getEditionFeedback(req.user.id, itemIds));
628
+ });
629
+ const editionFeedbackSchema = z.object({
630
+ itemId: z.number().int().positive(),
631
+ vote: z.union([z.literal(-1), z.literal(0), z.literal(1)]),
632
+ }).strict();
633
+ resourcesRouter.post("/edition/feedback", requireCapability("editions"), (req, res) => {
634
+ const parsed = editionFeedbackSchema.safeParse(req.body);
635
+ if (!parsed.success)
636
+ return invalid(res, parsed.error.flatten());
637
+ nativeAction(res, () => {
638
+ const result = setEditionFeedback(req.user.id, parsed.data.itemId, parsed.data.vote);
639
+ res.json({ ok: true, ...result });
640
+ });
641
+ });
642
+ resourcesRouter.delete("/edition/feedback", requireCapability("editions"), (req, res) => {
643
+ nativeAction(res, () => {
644
+ resetEditionFeedback(req.user.id);
645
+ res.status(204).end();
646
+ });
647
+ });
622
648
  // ---- Universal Inbox ("Save to FeedKeeper") -------------------------------
623
649
  const saveInboxSchema = z
624
650
  .object({
@@ -0,0 +1,12 @@
1
+ -- Reader feedback (up/down votes) on curated edition articles for future edition personalization.
2
+ CREATE TABLE IF NOT EXISTS edition_feedback (
3
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
4
+ item_id INTEGER NOT NULL,
5
+ feed_id INTEGER NOT NULL,
6
+ vote INTEGER NOT NULL CHECK (vote IN (-1, 1)),
7
+ keywords_json TEXT NOT NULL CHECK (json_valid(keywords_json)),
8
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
9
+ PRIMARY KEY (user_id, item_id)
10
+ );
11
+
12
+ CREATE INDEX IF NOT EXISTS idx_edition_feedback_user_updated ON edition_feedback(user_id, updated_at DESC);
@@ -14,6 +14,7 @@ import { pollFeed } from "../feeds/poller.js";
14
14
  import { discoverFeeds } from "../feeds/discovery.js";
15
15
  import { APP_VERSION } from "../version.js";
16
16
  import { dismissEdition, editionCandidates, getEditionState, publishCuratedEdition, publishEditionFields } from "../native/editions.js";
17
+ import { getFeedbackProfile } from "../native/editionFeedback.js";
17
18
  import { getNativePreferences } from "../native/preferences.js";
18
19
  import { NativeError } from "../native/requests.js";
19
20
  import { capabilityDenial, hasUserCapability } from "../auth/capabilities.js";
@@ -602,12 +603,17 @@ export function createMcpServerForUser(userId, scope) {
602
603
  }, async () => textResult(getEditionState(userId)));
603
604
  server.registerTool("get_edition_candidates", {
604
605
  title: "Get candidate articles for newspaper curation",
605
- description: "Use this tool ONLY when preparing to curate a newspaper edition with publish_edition. Returns a bounded shortlist of unread articles from the last 7 days scored for editorial curation, user reading preferences, and current revision. Do NOT use for general reading or browsing (use get_digest or get_new_items instead).",
606
+ description: "Use this tool ONLY when preparing to curate a newspaper edition with publish_edition. Returns a bounded shortlist of unread articles from the last 7 days scored for editorial curation, user reading preferences, learned reader feedback signals (liked/disliked sources and topics), and current revision. Do NOT use for general reading or browsing (use get_digest or get_new_items instead).",
606
607
  annotations: readOnlyAnnotations,
607
608
  inputSchema: {
608
609
  limit: z.number().int().min(1).max(200).default(100).describe("Maximum number of candidate articles to evaluate (1 to 200, default: 100)"),
609
610
  },
610
- }, async ({ limit }) => capabilityAction("editions", () => ({ preferences: getNativePreferences(userId), current: getEditionState(userId), candidates: editionCandidates(userId, new Date(), limit) })));
611
+ }, async ({ limit }) => capabilityAction("editions", () => ({
612
+ preferences: getNativePreferences(userId),
613
+ readerPreferences: getFeedbackProfile(userId),
614
+ current: getEditionState(userId),
615
+ candidates: editionCandidates(userId, new Date(), limit),
616
+ })));
611
617
  if (scope === "write")
612
618
  server.registerTool("publish_edition", {
613
619
  title: "Publish curated newspaper edition",
@@ -0,0 +1,164 @@
1
+ import { db } from "../db/index.js";
2
+ import { canAccessItem } from "../feeds/repository.js";
3
+ import { normalizedTitle, significantTitleWords } from "./editionSelection.js";
4
+ import { NativeError } from "./requests.js";
5
+ const DECAY_HALF_LIFE_MS = 30 * 86_400_000;
6
+ const MIN_SIGNAL_WEIGHT = 0.35;
7
+ const MAX_PROFILE_ITEMS = 8;
8
+ function clamp(value, min, max) {
9
+ return Math.max(min, Math.min(max, value));
10
+ }
11
+ function decayedWeight(vote, updatedAt, nowMs) {
12
+ const timestamp = Date.parse(updatedAt);
13
+ if (!Number.isFinite(timestamp))
14
+ return vote;
15
+ const ageMs = Math.max(0, nowMs - timestamp);
16
+ return vote * Math.pow(0.5, ageMs / DECAY_HALF_LIFE_MS);
17
+ }
18
+ function parseKeywords(json) {
19
+ try {
20
+ const parsed = JSON.parse(json);
21
+ if (!Array.isArray(parsed))
22
+ return [];
23
+ return parsed.filter((entry) => typeof entry === "string" && entry.length > 0);
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ }
29
+ export function extractFeedbackKeywords(title) {
30
+ return [...significantTitleWords(normalizedTitle(title))].slice(0, 16);
31
+ }
32
+ /**
33
+ * Stores or clears an explicit reader vote (+1 / -1 / 0) for an article.
34
+ * Feed and extracted title keywords are stored denormalized so retention cleanup preserves taste signals.
35
+ */
36
+ export function setEditionFeedback(userId, itemId, vote, now = new Date()) {
37
+ if (vote === 0) {
38
+ db.prepare("DELETE FROM edition_feedback WHERE user_id = ? AND item_id = ?").run(userId, itemId);
39
+ const countRow = db.prepare("SELECT COUNT(*) AS count FROM edition_feedback WHERE user_id = ?").get(userId);
40
+ return { itemId, vote: 0, totalCount: countRow?.count ?? 0 };
41
+ }
42
+ if (!canAccessItem(userId, itemId)) {
43
+ throw new NativeError("item_not_found", 404);
44
+ }
45
+ const item = db.prepare("SELECT feed_id, title FROM items WHERE id = ?").get(itemId);
46
+ if (!item) {
47
+ throw new NativeError("item_not_found", 404);
48
+ }
49
+ const keywords = extractFeedbackKeywords(item.title);
50
+ const updatedAt = now.toISOString();
51
+ db.prepare(`INSERT INTO edition_feedback (user_id, item_id, feed_id, vote, keywords_json, updated_at)
52
+ VALUES (?, ?, ?, ?, ?, ?)
53
+ ON CONFLICT (user_id, item_id) DO UPDATE SET
54
+ feed_id = excluded.feed_id,
55
+ vote = excluded.vote,
56
+ keywords_json = excluded.keywords_json,
57
+ updated_at = excluded.updated_at`).run(userId, itemId, item.feed_id, vote, JSON.stringify(keywords), updatedAt);
58
+ const countRow = db.prepare("SELECT COUNT(*) AS count FROM edition_feedback WHERE user_id = ?").get(userId);
59
+ return { itemId, vote, totalCount: countRow?.count ?? 0 };
60
+ }
61
+ /** Returns stored votes for the given item IDs (or all recent votes if omitted) plus total feedback count. */
62
+ export function getEditionFeedback(userId, itemIds) {
63
+ const totalCount = db.prepare("SELECT COUNT(*) AS count FROM edition_feedback WHERE user_id = ?").get(userId)?.count ?? 0;
64
+ let rows;
65
+ if (itemIds && itemIds.length > 0) {
66
+ const placeholders = itemIds.map(() => "?").join(", ");
67
+ rows = db.prepare(`SELECT item_id, vote FROM edition_feedback WHERE user_id = ? AND item_id IN (${placeholders})`).all(userId, ...itemIds);
68
+ }
69
+ else if (itemIds && itemIds.length === 0) {
70
+ rows = [];
71
+ }
72
+ else {
73
+ rows = db.prepare("SELECT item_id, vote FROM edition_feedback WHERE user_id = ? ORDER BY updated_at DESC LIMIT 200").all(userId);
74
+ }
75
+ const votes = {};
76
+ for (const row of rows) {
77
+ votes[String(row.item_id)] = row.vote;
78
+ }
79
+ return { votes, totalCount };
80
+ }
81
+ export function resetEditionFeedback(userId) {
82
+ db.prepare("DELETE FROM edition_feedback WHERE user_id = ?").run(userId);
83
+ }
84
+ function aggregateSignals(userId, now = new Date()) {
85
+ const rows = db.prepare("SELECT item_id, feed_id, vote, keywords_json, updated_at FROM edition_feedback WHERE user_id = ? ORDER BY updated_at DESC LIMIT 500").all(userId);
86
+ const nowMs = now.getTime();
87
+ const sourceWeights = new Map();
88
+ const keywordWeights = new Map();
89
+ for (const row of rows) {
90
+ const weight = decayedWeight(row.vote, row.updated_at, nowMs);
91
+ sourceWeights.set(row.feed_id, (sourceWeights.get(row.feed_id) ?? 0) + weight);
92
+ for (const keyword of parseKeywords(row.keywords_json)) {
93
+ keywordWeights.set(keyword, (keywordWeights.get(keyword) ?? 0) + weight);
94
+ }
95
+ }
96
+ return { totalVotes: rows.length, sourceWeights, keywordWeights };
97
+ }
98
+ /**
99
+ * Builds a bounded scoring multiplier function for candidate articles based on past reader feedback.
100
+ * Soft bounds prevent echo chambers: disliked sources/topics are damped rather than blocked.
101
+ */
102
+ export function createEditionFeedbackScorer(userId, now = new Date()) {
103
+ const { totalVotes, sourceWeights, keywordWeights } = aggregateSignals(userId, now);
104
+ if (totalVotes === 0)
105
+ return () => 1;
106
+ return (feedId, title) => {
107
+ const sourceNet = sourceWeights.get(feedId) ?? 0;
108
+ const sourceFactor = clamp(1 + sourceNet * 0.15, 0.55, 1.55);
109
+ const keywords = extractFeedbackKeywords(title);
110
+ let keywordNet = 0;
111
+ for (const keyword of keywords) {
112
+ keywordNet += keywordWeights.get(keyword) ?? 0;
113
+ }
114
+ const keywordFactor = clamp(1 + keywordNet * 0.18, 0.65, 1.45);
115
+ return clamp(sourceFactor * keywordFactor, 0.45, 1.85);
116
+ };
117
+ }
118
+ /** Summarizes reader feedback signals for external MCP curators and FeedKeeper Cloud. */
119
+ export function getFeedbackProfile(userId, now = new Date()) {
120
+ const { totalVotes, sourceWeights, keywordWeights } = aggregateSignals(userId, now);
121
+ if (totalVotes === 0) {
122
+ return { totalVotes: 0, likedSources: [], dislikedSources: [], likedTopics: [], dislikedTopics: [] };
123
+ }
124
+ const sourceNames = new Map();
125
+ const feedIds = [...sourceWeights.keys()];
126
+ if (feedIds.length > 0) {
127
+ const placeholders = feedIds.map(() => "?").join(", ");
128
+ const rows = db.prepare(`SELECT f.id, NULLIF(TRIM(s.label), '') AS label, f.title
129
+ FROM feeds f
130
+ LEFT JOIN subscriptions s ON s.feed_id = f.id AND s.user_id = ?
131
+ WHERE f.id IN (${placeholders})`).all(userId, ...feedIds);
132
+ for (const row of rows) {
133
+ const name = row.label ?? row.title;
134
+ if (name)
135
+ sourceNames.set(row.id, name);
136
+ }
137
+ }
138
+ const rankedSources = [...sourceWeights.entries()]
139
+ .map(([feedId, weight]) => ({ name: sourceNames.get(feedId), weight }))
140
+ .filter((entry) => Boolean(entry.name));
141
+ const likedSources = rankedSources
142
+ .filter((entry) => entry.weight >= MIN_SIGNAL_WEIGHT)
143
+ .sort((a, b) => b.weight - a.weight)
144
+ .slice(0, MAX_PROFILE_ITEMS)
145
+ .map((entry) => entry.name);
146
+ const dislikedSources = rankedSources
147
+ .filter((entry) => entry.weight <= -MIN_SIGNAL_WEIGHT)
148
+ .sort((a, b) => a.weight - b.weight)
149
+ .slice(0, MAX_PROFILE_ITEMS)
150
+ .map((entry) => entry.name);
151
+ const rankedTopics = [...keywordWeights.entries()].filter(([, weight]) => Math.abs(weight) >= MIN_SIGNAL_WEIGHT);
152
+ const likedTopics = rankedTopics
153
+ .filter(([, weight]) => weight > 0)
154
+ .sort((a, b) => b[1] - a[1])
155
+ .slice(0, MAX_PROFILE_ITEMS)
156
+ .map(([keyword]) => keyword);
157
+ const dislikedTopics = rankedTopics
158
+ .filter(([, weight]) => weight < 0)
159
+ .sort((a, b) => a[1] - b[1])
160
+ .slice(0, MAX_PROFILE_ITEMS)
161
+ .map(([keyword]) => keyword);
162
+ return { totalVotes, likedSources, dislikedSources, likedTopics, dislikedTopics };
163
+ }
164
+ //# sourceMappingURL=editionFeedback.js.map
@@ -19,7 +19,7 @@ export function canonicalArticleUrl(value) {
19
19
  return null;
20
20
  }
21
21
  }
22
- function normalizedTitle(value) {
22
+ export function normalizedTitle(value) {
23
23
  return (value ?? "").normalize("NFKD").replace(/\p{M}/gu, "").toLocaleLowerCase("en")
24
24
  .replace(/[^\p{L}\p{N}]+/gu, " ").trim();
25
25
  }
@@ -35,7 +35,7 @@ const TITLE_STOPWORDS = new Set([
35
35
  "ist", "mit", "nach", "nicht", "noch", "nur", "oder", "sich", "sie", "sind", "so", "über", "uber", "um", "und",
36
36
  "uns", "unter", "vom", "von", "vor", "war", "was", "werden", "wie", "will", "wird", "wurde", "zu", "zum", "zur",
37
37
  ]);
38
- function significantTitleWords(normalized) {
38
+ export function significantTitleWords(normalized) {
39
39
  if (!normalized)
40
40
  return new Set();
41
41
  const tokens = normalized.split(" ").filter((word) => word.length >= 2 && !TITLE_STOPWORDS.has(word));
@@ -8,6 +8,7 @@ import { getNativePreferences } from "./preferences.js";
8
8
  import { checkEditionLayout, editionLayoutSchema } from "./editionLayout.js";
9
9
  import { NativeError, nativeRequest } from "./requests.js";
10
10
  import { hasEditionText } from "./editionContent.js";
11
+ import { createEditionFeedbackScorer } from "./editionFeedback.js";
11
12
  export const overviewSchema = z.array(z.object({
12
13
  heading: z.string().trim().min(1).max(160),
13
14
  segments: z.array(z.object({
@@ -235,13 +236,15 @@ export function editionCandidates(userId, now = new Date(), limit = 200) {
235
236
  JOIN items full_item ON full_item.id = r.id
236
237
  WHERE r.source_rank <= 40 ORDER BY r.source_rank, r.published DESC, r.id DESC LIMIT 4000`)
237
238
  .all(userId, userId, userId, new Date(now.getTime() - 7 * 86_400_000).toISOString(), now.toISOString());
239
+ const feedbackScore = createEditionFeedbackScorer(userId, now);
238
240
  const scored = rows.filter((row) => (row.folder_id === null ? prefs.showUnfiled : !prefs.hiddenFolderIds.includes(row.folder_id)) && hasEditionText(row))
239
241
  .map((row) => ({
240
242
  id: row.id, sourceName: row.source_name, folderName: row.folder_name, subscriptionId: row.feed_id, folderId: row.folder_id,
241
243
  title: row.title, url: row.link, publishedAt: row.published, snippet: decodeEntities(row.content_snippet) ?? null, imageUrl: row.image_url,
242
244
  readingMinutes: Math.max(1, Math.ceil(row.content_chars / 1400)), previouslySelected: previous.has(row.id),
243
245
  score: Math.pow(0.5, Math.max(0, now.getTime() - Date.parse(row.published)) / (18 * 3_600_000)) *
244
- (row.folder_id !== null && prefs.preferredFolderIds.includes(row.folder_id) ? 1.4 : 1),
246
+ (row.folder_id !== null && prefs.preferredFolderIds.includes(row.folder_id) ? 1.4 : 1) *
247
+ feedbackScore(row.feed_id, row.title),
245
248
  }));
246
249
  // Candidate requests expose a shortlist in which every source has a fair chance, not only the busiest one.
247
250
  if (limit < AUTOMATIC_EDITION_LIMIT) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feedkeeper/server",
3
- "version": "0.38.6",
3
+ "version": "0.40.0",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }