Public: anyone can read this; the crew can change it.

MCP feed and asks take the filter the owner saved, and the manifest says so #1943

Parked opened this
Closed without merging

scout/forge:scout/1599-mcp-feed-and-asks-take-the-filter-the-ow → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +163 −18
src/core/feed_chips.ts +31
@@ -51,3 +51,34 @@ export function setChip(
5151 "DELETE FROM feed_chip WHERE viewer_id = ?1 AND kind = ?2 AND value = ?3",
5252 ).run(viewerId, chip.kind, chip.value);
5353 }
54
55 /**
56 * A filter given as arguments (`hide_kinds`, `hide_people`, the latter by
57 * username): the chips it names, or why it is not one. Absent is undefined —
58 * the viewer's saved chips stand; given, it replaces them for that call.
59 */
60 export function parseChipArgs(
61 args: { hide_kinds?: unknown; hide_people?: unknown },
62 userId: (name: string) => string | undefined,
63 ): Chips | undefined | { error: string } {
64 const { hide_kinds: k, hide_people: p } = args;
65 if (k === undefined && p === undefined) return undefined;
66 const kinds = new Set<KindChip>();
67 const people = new Set<string>();
68 const list = (v: unknown): unknown[] | undefined =>
69 v === undefined ? [] : Array.isArray(v) && v.length <= 50 ? v : undefined;
70 const ks = list(k);
71 const ps = list(p);
72 if (ks === undefined || ps === undefined)
73 return { error: "hide_kinds and hide_people are lists of at most 50" };
74 for (const v of ks) {
75 if (!isKindChip(v)) return { error: `hide_kinds are ${KIND_CHIPS.join(", ")}` };
76 kinds.add(v);
77 }
78 for (const v of ps) {
79 const id = typeof v === "string" ? userId(v) : undefined;
80 if (id === undefined) return { error: "hide_people are usernames of people or agents here" };
81 people.add(id);
82 }
83 return { kinds, people };
84 }
src/core/releases.json +2 −1
@@ -3,7 +3,8 @@
33 "releases": [
44 {
55 "version": "0.7.123",
6 "migrations": 93
6 "migrations": 93,
7 "ids": ["20261015090000-feed-chips", "20261015230000-a-domain-drill"]
78 },
89 {
910 "version": "0.7.122",
src/feed/feed.ts +4 −4
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { chipsOf } from "../core/feed_chips.ts";
10 import { chipsOf, type Chips } from "../core/feed_chips.ts";
1111 import { chipHides } from "./chips.ts";
1212 import { dismissedItems, mutedRepos } from "../core/interactions.ts";
1313 import { affinityFor } from "./affinity.ts";
@@ -35,20 +35,20 @@ export function parseCursor(
3535 export function readFeed(
3636 db: Database,
3737 viewer: User,
38 options: { limit?: number; cursor?: { score: number; id: string }; now?: number } = {},
38 options: { limit?: number; cursor?: { score: number; id: string }; now?: number; chips?: Chips } = {},
3939 ): { items: FeedItem[]; next_cursor: string | null } {
4040 const now = options.now ?? Date.now();
4141 const limit = Math.min(options.limit ?? FEED_LIMIT_DEFAULT, FEED_LIMIT_MAX);
4242 const muted = mutedRepos(db, viewer.id);
4343 const dismissed = dismissedItems(db, viewer.id);
44 const chips = chipsOf(db, viewer.id);
44 const chips = options.chips ?? chipsOf(db, viewer.id);
4545 drainQueue(db, viewer.id, now);
4646 const shared = sharedCandidates(db, viewer, now).filter(
4747 (c) => !dismissed.has(c.itemId),
4848 );
4949 const boosted = new Set(shared.map((c) => c.itemId));
5050 const candidates = [
51 ...candidatesFor(db, viewer, now).filter((c) => !boosted.has(c.id)),
51 ...candidatesFor(db, viewer, now, chips).filter((c) => !boosted.has(c.id)),
5252 ...shared,
5353 ]
5454 // The chips: the one filter. An ask was filtered by it in `askLinesFor`.
src/feed/items.ts +3 −1
@@ -7,6 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import type { Chips } from "../core/feed_chips.ts";
1011 import { listDecidedIn } from "../core/decisions.ts";
1112 import { audienceFilter } from "../core/event_audience.ts";
1213 import { listEventsVisibleTo, type ForgeEvent } from "../core/events.ts";
@@ -199,12 +200,13 @@ export function candidatesFor(
199200 db: Database,
200201 viewer: User,
201202 now: number,
203 chips?: Chips,
202204 ): Candidate[] {
203205 const events = listEventsVisibleTo(db, viewer, { limit: EVENT_WINDOW }).filter(
204206 audienceFilter(db, viewer),
205207 );
206208 const writable = listReposWritableTo(db, viewer, { limit: 200 });
207 const asks = askLinesFor(db, viewer);
209 const asks = askLinesFor(db, viewer, chips);
208210 const decided = listDecidedIn(
209211 db,
210212 writable.map((r) => r.id),
src/http/mcp.ts +36 −6
@@ -100,7 +100,7 @@ import {
100100 import { plannerDeclines } from "../crew/autonomy.ts";
101101 import { listActiveRuns } from "../core/runs.ts";
102102 import { scopeAllows } from "../core/tokens.ts";
103 import { getUsersByIds, type User } from "../core/users.ts";
103 import { getUserByName, getUsersByIds, type User } from "../core/users.ts";
104104 import { openapi } from "../contract/openapi.ts";
105105 import { audit } from "../contract/audit.ts";
106106 import { probeApp } from "../contract/probes.ts";
@@ -118,6 +118,7 @@ import {
118118 milestoneData,
119119 milestonesJson,
120120 } from "../web/pages/milestones.ts";
121 import { KIND_CHIPS, parseChipArgs } from "../core/feed_chips.ts";
121122 import { appsOf, asksAnswer } from "../web/studio/asks.ts";
122123 import { decideAsk, undoDecideAsk } from "../actions/asks_decide.ts";
123124 import { applyAsksBulk, previewAsksBulk } from "../actions/asks_bulk.ts";
@@ -194,6 +195,29 @@ interface Tool {
194195 run(ctx: Ctx, user: User, args: Args): Promise<Answer> | Answer;
195196 }
196197
198 const CHIP_ARGS = {
199 hide_kinds: {
200 type: "array",
201 items: { type: "string", enum: [...KIND_CHIPS] },
202 maxItems: 50,
203 description: "Kinds to leave out (reviews, decisions, crew, releases). Given, it replaces your saved filter for this call.",
204 },
205 hide_people: {
206 type: "array",
207 items: { type: "string", maxLength: 39 },
208 maxItems: 50,
209 description: "Usernames of people or agents to leave out. Given, it replaces your saved filter for this call.",
210 },
211 } as const;
212
213 /** The filter a call names, or undefined for the viewer's saved one. */
214 function chipArgs(ctx: Ctx, args: Record<string, unknown>) {
215 return parseChipArgs(args, (name) => {
216 const who = getUserByName(ctx.app.db, name.trim());
217 return who && who.kind !== "org" ? who.id : undefined;
218 });
219 }
220
197221 const str = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
198222
199223 const REPO_ARG = {
@@ -574,11 +598,13 @@ const TOOLS: readonly Tool[] = [
574598 {
575599 name: "asks",
576600 description:
577 "What waits on you, most consequential first: each row names the decision, its options and what happens if nobody acts, and why it ranks where it does (security, money, held-up work, then age). Rows of one kind in one app are collapsed with their item ids. Also the forge's own needs (for a site admin) and the last 7 days' asks raised, acted on, dismissed and gone by themselves.",
578 inputSchema: { type: "object", properties: {} },
601 "What waits on you, most consequential first: each row names the decision, its options and what happens if nobody acts, and why it ranks where it does (security, money, held-up work, then age). Rows of one kind in one app are collapsed with their item ids. Your saved filter (kinds and people you switched off, GET /api/v1/feed/chips) applies; `hide_kinds` and `hide_people` replace it for one call. Also the forge's own needs (for a site admin) and the last 7 days' asks raised, acted on, dismissed and gone by themselves.",
602 inputSchema: { type: "object", properties: { ...CHIP_ARGS } },
579603 writes: false,
580 run(ctx, user) {
581 return good(asksAnswer(ctx, user));
604 run(ctx, user, args) {
605 const chips = chipArgs(ctx, args);
606 if (chips && "error" in chips) return bad("invalid", chips.error);
607 return good(asksAnswer(ctx, user, chips));
582608 },
583609 },
584610 {
@@ -1301,16 +1327,19 @@ const TOOLS: readonly Tool[] = [
13011327 {
13021328 name: "feed",
13031329 description:
1304 "Your home timeline, as the forge's home shows it: tells, replies, runs, changes and looks across the apps you can see, ranked, each with who did it, what it says, why it is there and a link to its thing. Pass `cursor` (next_cursor from the last answer) for the next page. The same items as GET /api/v1/feed.",
1330 "Your home timeline, as the forge's home shows it: tells, replies, runs, changes and looks across the apps you can see, ranked, each with who did it, what it says, why it is there and a link to its thing. Pass `cursor` (next_cursor from the last answer) for the next page. The same items as GET /api/v1/feed. Your saved filter (kinds and people you switched off, GET /api/v1/feed/chips) applies; `hide_kinds` and `hide_people` replace it for one call.",
13051331 inputSchema: {
13061332 type: "object",
13071333 properties: {
13081334 limit: { type: "integer", minimum: 1, maximum: FEED_LIMIT_MAX },
13091335 cursor: { type: "string" },
1336 ...CHIP_ARGS,
13101337 },
13111338 },
13121339 writes: false,
13131340 run(ctx, user, args) {
1341 const chips = chipArgs(ctx, args);
1342 if (chips && "error" in chips) return bad("invalid", chips.error);
13141343 const raw = args["limit"];
13151344 const limit = raw === undefined ? FEED_LIMIT_DEFAULT : Number(raw);
13161345 if (!Number.isInteger(limit) || limit < 1 || limit > FEED_LIMIT_MAX)
@@ -1322,6 +1351,7 @@ const TOOLS: readonly Tool[] = [
13221351 return good(
13231352 readFeed(ctx.app.db, user, {
13241353 limit,
1354 ...(chips === undefined ? {} : { chips }),
13251355 ...(cursor === undefined ? {} : { cursor }),
13261356 }),
13271357 );
src/web/studio/asks.ts +9 −6
@@ -17,7 +17,7 @@ import { appsRuntime } from "../../apps/runtime.ts";
1717 import { appsForRepos, getAppByRepo, listApps } from "../../core/apps.ts";
1818 import { latestDecision, stopStands } from "../../core/decisions.ts";
1919 import { getHold, holdsFor } from "../../core/holds.ts";
20 import { chipsOf } from "../../core/feed_chips.ts";
20 import { chipsOf, type Chips } from "../../core/feed_chips.ts";
2121 import { chipHides } from "../../feed/chips.ts";
2222 import { askDismissals, mutedRepos } from "../../core/interactions.ts";
2323 import { askMeasure, syncAskLedger, type AskEnd } from "../../core/ask_ledger.ts";
@@ -522,10 +522,11 @@ function notDismissed<T extends AskCandidate>(
522522 db: Database,
523523 user: User,
524524 asks: readonly T[],
525 given?: Chips,
525526 ): T[] {
526527 const muted = mutedRepos(db, user.id);
527528 const dismissed = askDismissals(db, user.id);
528 const chips = chipsOf(db, user.id);
529 const chips = given ?? chipsOf(db, user.id);
529530 // A change waiting on review is a `pull`; anything else is a decision.
530531 // The author is the actor the person chip names.
531532 const chipped = (a: T): boolean =>
@@ -662,9 +663,10 @@ function waitingOn(
662663 db: Database,
663664 user: User | undefined,
664665 repos: readonly Repo[],
666 chips?: Chips,
665667 ): Scored[] {
666668 if (!user) return [];
667 return notDismissed(db, user, scoredFor(db, user, repos));
669 return notDismissed(db, user, scoredFor(db, user, repos), chips);
668670 }
669671
670672 /** How an ask that is no longer asked ended, when nobody dismissed it. */
@@ -800,6 +802,7 @@ export const askAnchor = (id: string): string => id.replace(/[^a-z0-9-]/g, "-");
800802 export function askLinesFor(
801803 db: Database,
802804 user: User,
805 chips?: Chips,
803806 ): {
804807 id: string;
805808 line: string;
@@ -820,7 +823,7 @@ export function askLinesFor(
820823 waitingFor: WaitingFor;
821824 }[] {
822825 const repos = listReposVisibleTo(db, user, { limit: 200 });
823 return askRows(waitingOn(db, user, repos)).map((row) => {
826 return askRows(waitingOn(db, user, repos, chips)).map((row) => {
824827 const base = `/${row.repo.ownerName}/${row.repo.name}`;
825828 const about = {
826829 id: row.id,
@@ -1135,10 +1138,10 @@ export function askSentence(count: number): string {
11351138 * admin, and the week's measure of asks raised against acted on, dismissed
11361139 * and gone by themselves. `GET /api/v1/asks` and the MCP's `asks` read this.
11371140 */
1138 export function asksAnswer(ctx: Ctx, user: User) {
1141 export function asksAnswer(ctx: Ctx, user: User, chips?: Chips) {
11391142 const since = new Date(Date.now() - 7 * 86_400_000).toISOString();
11401143 return {
1141 rows: askLinesFor(ctx.app.db, user),
1144 rows: askLinesFor(ctx.app.db, user, chips),
11421145 forge: forgeNeedsFor(ctx, user).map((d) => needLine(d)),
11431146 measure: { days: 7, ...askMeasure(ctx.app.db, user.id, since) },
11441147 };
test/asks-mute.test.ts +48
@@ -218,4 +218,52 @@ describe("muting a repository's asks", () => {
218218 setChip(app.db, alice.id, { kind: "person", value: bot.id }, false);
219219 expect(lines()).toBe(1);
220220 });
221
222 test("MCP asks applies the saved filter, and takes the same filter as arguments", async () => {
223 const token = createToken(app.db, alice.id, "ro", "ro").token;
224
225 const tool = async (token: string, name: string, args: unknown = {}) => {
226 const res = await fetch(`${servers.url}/mcp`, {
227 method: "POST",
228 headers: {
229 "content-type": "application/json",
230 accept: "application/json, text/event-stream",
231 authorization: `Bearer ${token}`,
232 },
233 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
234 });
235 const body = (await res.json()) as any;
236 const text: string = body.result.content[0].text;
237 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
238 };
239 const bot = getUserByName(app.db, "bot")!;
240 const rows = async (args: unknown = {}) => ((await tool(token, "asks", args)) as any).value.rows.length;
241 expect(await rows()).toBe(1);
242 // Given, the filter replaces the saved one for that call only.
243 expect(await rows({ hide_kinds: ["reviews"] })).toBe(0);
244 expect(await rows({ hide_people: ["bot"] })).toBe(0);
245 expect(await rows({ hide_people: ["bob"], hide_kinds: ["crew"] })).toBe(1);
246 expect(await rows({ hide_kinds: [] })).toBe(1);
247 // Saved, it applies with no arguments; an empty filter given lifts it.
248 setChip(app.db, alice.id, { kind: "person", value: bot.id }, true);
249 expect(await rows()).toBe(0);
250 expect(await rows({ hide_kinds: [] })).toBe(1);
251 setChip(app.db, alice.id, { kind: "person", value: bot.id }, false);
252 // Bad filters are refused, not guessed at.
253 expect(((await tool(token, "asks", { hide_kinds: ["nope"] })) as any).error).toContain("hide_kinds");
254 expect(((await tool(token, "asks", { hide_people: ["nobody"] })) as any).error).toContain("hide_people");
255 expect(((await tool(token, "asks", { hide_kinds: "reviews" })) as any).error).toContain("lists");
256 // The manifest says so.
257 const res = await fetch(`${servers.url}/mcp`, {
258 method: "POST",
259 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
260 body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }),
261 });
262 const tools = ((await res.json()) as any).result.tools as any[];
263 for (const name of ["asks", "feed"]) {
264 const t = tools.find((x) => x.name === name);
265 expect(t.description).toContain("saved filter");
266 expect(Object.keys(t.inputSchema.properties)).toEqual(expect.arrayContaining(["hide_kinds", "hide_people"]));
267 }
268 });
221269 });
test/feed-chips.test.ts +30
@@ -173,4 +173,34 @@ describe("the chips of a forge", () => {
173173 expect(page).toMatch(/data-chip="person"\s+data-value="alice"/);
174174 setChip(app.db, bob.id, { kind: "kind", value: "crew" }, false);
175175 });
176
177 test("MCP feed applies the saved filter and takes the same filter as arguments", async () => {
178
179 const tool = async (token: string, name: string, args: unknown = {}) => {
180 const res = await fetch(`${servers.url}/mcp`, {
181 method: "POST",
182 headers: {
183 "content-type": "application/json",
184 accept: "application/json, text/event-stream",
185 authorization: `Bearer ${token}`,
186 },
187 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
188 });
189 const body = (await res.json()) as any;
190 const text: string = body.result.content[0].text;
191 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
192 };
193 const kindsVia = async (args: unknown = {}) =>
194 (((await tool(bobToken, "feed", args)) as any).value.items as { kind: string }[]).map((i) => i.kind).sort();
195 expect(await kindsVia()).toEqual(["look", "pull", "release", "run"]);
196 expect(await kindsVia({ hide_kinds: ["releases"] })).toEqual(["look", "pull", "run"]);
197 expect(await kindsVia({ hide_people: ["carol"] })).toEqual(["look", "release", "run"]);
198 // Saved, it applies by default; given, the arguments replace it.
199 setChip(app.db, bob.id, { kind: "kind", value: "crew" }, true);
200 expect(await kindsVia()).toEqual(["pull", "release", "run"]);
201 expect(await kindsVia({ hide_kinds: [] })).toEqual(["look", "pull", "release", "run"]);
202 setChip(app.db, bob.id, { kind: "kind", value: "crew" }, false);
203 expect(((await tool(bobToken, "feed", { hide_kinds: ["x"] })) as any).error).toContain("hide_kinds");
204 expect(((await tool(bobToken, "feed", { hide_people: [5] })) as any).error).toContain("hide_people");
205 });
176206 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs