mercury-agent 0.16.0 → 0.16.2

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.
Files changed (80) hide show
  1. package/README.md +6 -0
  2. package/container/Dockerfile +6 -1
  3. package/container/Dockerfile.base +6 -1
  4. package/docs/README.md +50 -0
  5. package/docs/authoring-profiles.md +8 -0
  6. package/docs/behavior-layers.md +193 -0
  7. package/docs/extensions.md +2 -0
  8. package/docs/goals/football-reporter-profile/decisions.md +479 -0
  9. package/docs/goals/football-reporter-profile/goal.md +91 -0
  10. package/docs/goals/football-reporter-profile/roadmap.md +196 -0
  11. package/docs/goals/whatsapp-bot-hardening/README.md +43 -0
  12. package/docs/goals/whatsapp-bot-hardening/archive/ambient-group-context.md +211 -0
  13. package/docs/goals/whatsapp-bot-hardening/archive/command-routing-consistency.md +210 -0
  14. package/docs/goals/whatsapp-bot-hardening/archive/destructive-command-guards.md +218 -0
  15. package/docs/goals/whatsapp-bot-hardening/archive/docs-extension.md +182 -0
  16. package/docs/goals/whatsapp-bot-hardening/archive/handoff-2026-08-09.md +588 -0
  17. package/docs/goals/whatsapp-bot-hardening/archive/media-size-and-silent-drop.md +178 -0
  18. package/docs/goals/whatsapp-bot-hardening/archive/member-memory.md +199 -0
  19. package/docs/goals/whatsapp-bot-hardening/archive/message-author-attribution.md +211 -0
  20. package/docs/goals/whatsapp-bot-hardening/archive/run-from-source-switchover.md +212 -0
  21. package/docs/goals/whatsapp-bot-hardening/archive/setup-plan-2026-08-06.md +1117 -0
  22. package/docs/goals/whatsapp-bot-hardening/decisions.md +200 -0
  23. package/docs/goals/whatsapp-bot-hardening/goal.md +75 -0
  24. package/docs/goals/whatsapp-bot-hardening/open-threads.md +396 -0
  25. package/docs/goals/whatsapp-bot-hardening/roadmap.md +245 -0
  26. package/docs/memory.md +30 -0
  27. package/docs/profile-guide.md +483 -0
  28. package/docs/refactor/.gitkeep +0 -0
  29. package/docs/refactor/archive/.gitkeep +0 -0
  30. package/docs/refactor/audits/.gitkeep +0 -0
  31. package/docs/refactor/backlog/.gitkeep +0 -0
  32. package/docs/skills-guide.md +154 -0
  33. package/examples/extensions/README.md +1 -0
  34. package/examples/extensions/feed-watch/config.ts +354 -0
  35. package/examples/extensions/feed-watch/digest.ts +344 -0
  36. package/examples/extensions/feed-watch/feeds.ts +341 -0
  37. package/examples/extensions/feed-watch/index.ts +302 -0
  38. package/examples/extensions/feed-watch/items.ts +171 -0
  39. package/examples/extensions/feed-watch/match.ts +107 -0
  40. package/examples/extensions/feed-watch/prompts/verify.md +35 -0
  41. package/examples/extensions/feed-watch/skill/SKILL.md +128 -0
  42. package/examples/extensions/feed-watch/watch.ts +548 -0
  43. package/examples/extensions/longview/hook.ts +179 -16
  44. package/examples/extensions/longview/index.ts +13 -2
  45. package/examples/extensions/longview/prompts/summarize.md +3 -2
  46. package/examples/extensions/longview/render/telegraph-nodes.ts +21 -1
  47. package/examples/extensions/longview/summarize.ts +57 -14
  48. package/examples/extensions/napkin/index.ts +334 -86
  49. package/examples/extensions/napkin/pi-spawn.ts +196 -0
  50. package/examples/extensions/pinchtab/index.ts +37 -4
  51. package/examples/extensions/pinchtab/lib/session-injector.ts +31 -9
  52. package/examples/extensions/pinchtab/skill/SKILL.md +29 -0
  53. package/examples/profiles/_template/AGENTS.md +138 -0
  54. package/examples/profiles/_template/README.md +65 -0
  55. package/examples/profiles/_template/config.yaml +57 -0
  56. package/examples/profiles/_template/tasks/daily.md +32 -0
  57. package/examples/profiles/football-reporter/AGENTS.md +219 -0
  58. package/examples/profiles/football-reporter/README.md +138 -0
  59. package/examples/profiles/football-reporter/config.yaml +174 -0
  60. package/examples/profiles/football-reporter/seed/MEMORY.md +42 -0
  61. package/examples/profiles/football-reporter/seed/episodes/barcelona-2026-27.md +25 -0
  62. package/examples/profiles/football-reporter/seed/episodes/beitar-jerusalem-2026-27.md +25 -0
  63. package/examples/profiles/football-reporter/seed/episodes/maccabi-haifa-2026-27.md +24 -0
  64. package/examples/profiles/football-reporter/seed/episodes/man-united-2026-27.md +26 -0
  65. package/examples/profiles/football-reporter/seed/episodes/real-madrid-2026-27.md +25 -0
  66. package/examples/profiles/football-reporter/seed/napkin-distill.md +55 -0
  67. package/examples/profiles/football-reporter/tasks/daily-article.md +142 -0
  68. package/package.json +8 -5
  69. package/src/adapters/whatsapp.ts +75 -13
  70. package/src/bridges/whatsapp.ts +6 -4
  71. package/src/cli/mrctl.ts +9 -1
  72. package/src/core/handler.ts +51 -6
  73. package/src/core/routes/dashboard.ts +106 -5
  74. package/src/core/routes/tasks.ts +28 -0
  75. package/src/core/runtime.ts +63 -2
  76. package/src/core/task-scheduler.ts +103 -12
  77. package/src/extensions/catalog.ts +9 -0
  78. package/src/profile/space-profile.ts +780 -0
  79. package/src/storage/db.ts +215 -0
  80. package/src/types.ts +56 -0
@@ -0,0 +1,302 @@
1
+ /**
2
+ * feed-watch — a host-side feed poller that replaces discovery-by-LLM.
3
+ *
4
+ * A space used to learn about news by paying a container to wake on a clock,
5
+ * browse, and guess whether anything had happened. This extension polls RSS and
6
+ * Google-News queries on the host, matches headlines against a per-space
7
+ * watchlist, and — only when something actually matched — opens a one-shot task
8
+ * carrying the concrete, dated, sourced items. It also hands the daily article
9
+ * everything seen since the last one.
10
+ *
11
+ * **No model runs on the host side of this.** The job fetches, parses, matches
12
+ * and creates tasks; it never calls a provider, never composes prose, and never
13
+ * sends to a chat. Every message a group receives is written by an agent run
14
+ * that was handed real items.
15
+ *
16
+ * **Off by default, per space.** `feed-watch.enabled` is `"false"` until an
17
+ * admin says otherwise, and a disabled space fetches nothing and stores nothing.
18
+ *
19
+ * This file is wiring only. Every decision lives in the pure modules beside it,
20
+ * which is what lets `tests/feed-watch-*.test.ts` cover the state machine
21
+ * without a runtime, a network or a clock.
22
+ */
23
+
24
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ import { dirname, join } from "node:path";
26
+ import { CONFIG_KEYS } from "./config.js";
27
+ import {
28
+ DIGEST_FILE,
29
+ type DigestFileIO,
30
+ handleAfterContainer,
31
+ handleBeforeContainer,
32
+ } from "./digest.js";
33
+ import { type FetchImpl, fetchFeed } from "./feeds.js";
34
+ import {
35
+ type FetchTarget,
36
+ type PollDeps,
37
+ pollSpace,
38
+ TASK_NAME,
39
+ type WatchLogger,
40
+ type WatchStore,
41
+ } from "./watch.js";
42
+
43
+ /** How often the poller wakes. Interval jobs also run once at startup. */
44
+ export const POLL_INTERVAL_MS = 180_000;
45
+
46
+ // Ships alongside this extension, so `import.meta.dir` is the installed
47
+ // extension directory — the same arrangement longview uses for its prompt.
48
+ const VERIFY_PROMPT_PATH = join(import.meta.dir, "prompts", "verify.md");
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // The slice of the host API this extension uses
52
+ // ---------------------------------------------------------------------------
53
+
54
+ interface ExtensionDb {
55
+ listSpaces(): Array<{ id: string }>;
56
+ createTask(
57
+ spaceId: string,
58
+ schedule: { at: string },
59
+ prompt: string,
60
+ nextRunAt: number,
61
+ createdBy: string,
62
+ silent?: boolean,
63
+ timezone?: string,
64
+ name?: string,
65
+ ): number;
66
+ listTasks(spaceId: string): Array<{ name?: string | null }>;
67
+ getSpaceConfigUpdatedBy(spaceId: string, key: string): string | null;
68
+ }
69
+
70
+ interface ExtensionContext {
71
+ db: ExtensionDb;
72
+ config: { defaultTimezone?: string };
73
+ // Mirrors `Logger` in `src/logger.ts`: every level takes a message and one
74
+ // optional `extra`. An extension declares its own structural type and the
75
+ // loader hands it an untyped object, so nothing would catch a third argument
76
+ // — it would just be dropped, taking the spaceId of a failing poll with it.
77
+ log: WatchLogger & {
78
+ error(message: string, extra?: unknown): void;
79
+ };
80
+ getConfig(spaceId: string, key: string): string | null;
81
+ }
82
+
83
+ /** The event fields both container hooks read. */
84
+ interface ContainerEvent {
85
+ spaceId: string;
86
+ prompt: string;
87
+ workspace: string;
88
+ error?: unknown;
89
+ }
90
+
91
+ interface HookResult {
92
+ promptAppend?: string;
93
+ }
94
+
95
+ interface MercuryApi {
96
+ config(
97
+ key: string,
98
+ def: {
99
+ description: string;
100
+ default: string;
101
+ validate?: (value: string) => boolean;
102
+ },
103
+ ): void;
104
+ job(
105
+ name: string,
106
+ def: { interval: number; run: (ctx: ExtensionContext) => Promise<void> },
107
+ ): void;
108
+ on(
109
+ event: "before_container" | "after_container",
110
+ handler: (
111
+ event: ContainerEvent,
112
+ ctx: ExtensionContext,
113
+ ) => Promise<HookResult | undefined>,
114
+ ): void;
115
+ skill(relativePath: string): void;
116
+ store: WatchStore;
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // Setup
121
+ // ---------------------------------------------------------------------------
122
+
123
+ export default function (mercury: MercuryApi) {
124
+ const store = mercury.store;
125
+
126
+ // A missing prompt template is a broken install, not a degraded one: every
127
+ // run this extension opens is built from it. Fail at load, loudly, rather
128
+ // than three days later with an empty verify prompt in a live group.
129
+ const verifyTemplate = readFileSync(VERIFY_PROMPT_PATH, "utf8");
130
+
131
+ // ── Config ───────────────────────────────────────────────────────────────
132
+ for (const def of CONFIG_KEYS) {
133
+ mercury.config(def.key, {
134
+ description: def.description,
135
+ default: def.default,
136
+ validate: def.validate,
137
+ });
138
+ }
139
+
140
+ mercury.skill("./skill");
141
+
142
+ // ── The poll job ─────────────────────────────────────────────────────────
143
+
144
+ /**
145
+ * A tick that finds the previous one still running returns immediately.
146
+ * Ten sources at a five-second timeout can outlast a three-minute interval,
147
+ * and two concurrent ticks would race on every store key.
148
+ */
149
+ let inFlight = false;
150
+
151
+ /**
152
+ * Sources already reported as hitting a cap. A feed that is permanently over
153
+ * the byte limit would otherwise warn every three minutes forever; the fact
154
+ * is worth saying once per process, not 480 times a day.
155
+ */
156
+ const truncationWarned = new Set<string>();
157
+
158
+ function buildDeps(ctx: ExtensionContext): Omit<PollDeps, "log"> & {
159
+ log: WatchLogger;
160
+ } {
161
+ return {
162
+ getConfig: (spaceId, key) => ctx.getConfig(spaceId, key),
163
+ store,
164
+ fetchFeed: (target: FetchTarget) =>
165
+ fetchFeed(target.url, {
166
+ fetchImpl: globalThis.fetch as unknown as FetchImpl,
167
+ fallbackSource: target.fallbackSource,
168
+ onTruncate: (kind, detail) => {
169
+ const key = `${target.key}:${kind}`;
170
+ if (truncationWarned.has(key)) return;
171
+ truncationWarned.add(key);
172
+ ctx.log.warn("feed-watch: source hit a cap, older items dropped", {
173
+ source: target.key,
174
+ kind,
175
+ ...detail,
176
+ });
177
+ },
178
+ }),
179
+ createTask: (spaceId, prompt, runAs) =>
180
+ ctx.db.createTask(
181
+ spaceId,
182
+ { at: new Date().toISOString() },
183
+ prompt,
184
+ Date.now(),
185
+ runAs,
186
+ // Not silent: a verify run that finds something posts it. A run that
187
+ // finds nothing replies NO_UPDATE, which the core's no-op guard
188
+ // already drops before it reaches anyone.
189
+ false,
190
+ undefined,
191
+ TASK_NAME,
192
+ ),
193
+ listTasks: (spaceId) => ctx.db.listTasks(spaceId),
194
+ configUpdatedBy: (spaceId, key) =>
195
+ ctx.db.getSpaceConfigUpdatedBy(spaceId, key),
196
+ verifyTemplate,
197
+ log: ctx.log,
198
+ defaultTimezone: ctx.config.defaultTimezone,
199
+ pollIntervalMs: POLL_INTERVAL_MS,
200
+ };
201
+ }
202
+
203
+ mercury.job("poll", {
204
+ interval: POLL_INTERVAL_MS,
205
+ run: async (ctx) => {
206
+ if (inFlight) {
207
+ ctx.log.debug("feed-watch: previous poll still running, skipping tick");
208
+ return;
209
+ }
210
+ inFlight = true;
211
+ const started = Date.now();
212
+ const tally = {
213
+ spaces: 0,
214
+ watching: 0,
215
+ fetched: 0,
216
+ failed: 0,
217
+ backedOff: 0,
218
+ matched: 0,
219
+ opened: 0,
220
+ errors: 0,
221
+ deferred: [] as string[],
222
+ };
223
+ try {
224
+ const deps = buildDeps(ctx);
225
+ for (const space of ctx.db.listSpaces()) {
226
+ tally.spaces++;
227
+ try {
228
+ const result = await pollSpace(deps, space.id, Date.now());
229
+ if (result.skipped === "disabled") continue;
230
+ tally.watching++;
231
+ tally.fetched += result.fetched;
232
+ tally.failed += result.failed;
233
+ tally.backedOff += result.backedOff;
234
+ tally.matched += result.matched;
235
+ if (result.created) tally.opened++;
236
+ if (result.deferred) tally.deferred.push(result.deferred);
237
+ } catch (err) {
238
+ // One space's failure must not cost the others their poll. The
239
+ // loop is sequential precisely so this catch can be per-space.
240
+ tally.errors++;
241
+ ctx.log.error("feed-watch: poll failed for a space", {
242
+ spaceId: space.id,
243
+ error: err instanceof Error ? err.message : String(err),
244
+ });
245
+ }
246
+ }
247
+ } finally {
248
+ inFlight = false;
249
+ // One line per tick, so a healthy poll leaves positive evidence.
250
+ // `pollSpace` logs the notable transitions on its own, but a tick where
251
+ // nothing happened logs nothing at all — and "nothing happened" and
252
+ // "the job stopped running" are the two states an operator most needs
253
+ // to tell apart.
254
+ ctx.log.debug("feed-watch: poll tick", {
255
+ ...tally,
256
+ durationMs: Date.now() - started,
257
+ });
258
+ }
259
+ },
260
+ });
261
+
262
+ // ── Digest hooks ─────────────────────────────────────────────────────────
263
+
264
+ const file: DigestFileIO = {
265
+ read: (workspace) => {
266
+ try {
267
+ return readFileSync(join(workspace, DIGEST_FILE), "utf8");
268
+ } catch {
269
+ // Absent on the first write, and that is the normal case. Anything
270
+ // else (permissions, a directory in its place) surfaces on the write
271
+ // below, where it is logged.
272
+ return null;
273
+ }
274
+ },
275
+ write: (workspace, content) => {
276
+ const path = join(workspace, DIGEST_FILE);
277
+ mkdirSync(dirname(path), { recursive: true });
278
+ writeFileSync(path, content, "utf8");
279
+ },
280
+ };
281
+
282
+ mercury.on("before_container", async (event, ctx) => {
283
+ return handleBeforeContainer(event, {
284
+ getConfig: (spaceId, key) => ctx.getConfig(spaceId, key),
285
+ store,
286
+ log: ctx.log,
287
+ defaultTimezone: ctx.config.defaultTimezone,
288
+ });
289
+ });
290
+
291
+ mercury.on("after_container", async (event, ctx) => {
292
+ handleAfterContainer(event, {
293
+ getConfig: (spaceId, key) => ctx.getConfig(spaceId, key),
294
+ store,
295
+ log: ctx.log,
296
+ defaultTimezone: ctx.config.defaultTimezone,
297
+ file,
298
+ });
299
+ // Nothing to mutate: the reply is the agent's, unchanged.
300
+ return undefined;
301
+ });
302
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The buffered-item shape and the one line format both consumers render it in.
3
+ *
4
+ * The verify prompt and the daily digest hand the agent the *same* line, on
5
+ * purpose: whatever the watcher saw, it says the same way every time, so a run
6
+ * that has learned to read one has learned to read the other. That is why this
7
+ * lives apart from `watch.ts` and `digest.ts` rather than in whichever of them
8
+ * happened to need it first.
9
+ */
10
+
11
+ import type { FeedItem } from "./feeds.js";
12
+
13
+ /** A matched item as it is held in the buffer, with the watch metadata added. */
14
+ export interface StoredItem {
15
+ id: string;
16
+ title: string;
17
+ link: string;
18
+ source: string;
19
+ /** ISO from the feed, or null when the outlet published no date. */
20
+ publishedAt: string | null;
21
+ /** ISO, when the watcher first saw it. Always present — this is our clock. */
22
+ seenAt: string;
23
+ /** Which watch terms hit. */
24
+ terms: string[];
25
+ /** Normalized-title hash, for collapsing the same headline across outlets. */
26
+ fp: string;
27
+ }
28
+
29
+ /** Attach watch metadata to a parsed feed item. */
30
+ export function toStoredItem(
31
+ item: FeedItem,
32
+ opts: { terms: string[]; fp: string; seenAt: string },
33
+ ): StoredItem {
34
+ return {
35
+ id: item.id,
36
+ title: item.title,
37
+ link: item.link,
38
+ source: item.source,
39
+ publishedAt: item.publishedAt,
40
+ seenAt: opts.seenAt,
41
+ terms: opts.terms,
42
+ fp: opts.fp,
43
+ };
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Time
48
+ // ---------------------------------------------------------------------------
49
+
50
+ /**
51
+ * Pick the zone to render and compare local times in.
52
+ *
53
+ * Order: the space's own key, the deployment default, UTC. An unusable value
54
+ * degrades to the next option with a warning rather than throwing — a bad zone
55
+ * must not take the watcher down, and a silent fallback is what makes "quiet
56
+ * hours never fire" impossible to diagnose.
57
+ */
58
+ export function resolveTimezone(
59
+ spaceZone: string,
60
+ defaultZone: string | undefined,
61
+ log?: { warn(message: string, meta?: Record<string, unknown>): void },
62
+ ): string {
63
+ for (const candidate of [spaceZone, defaultZone]) {
64
+ const zone = candidate?.trim();
65
+ if (!zone) continue;
66
+ if (isUsableZone(zone)) return zone;
67
+ log?.warn("feed-watch: unusable timezone, falling back", { zone });
68
+ }
69
+ return "UTC";
70
+ }
71
+
72
+ function isUsableZone(zone: string): boolean {
73
+ try {
74
+ new Intl.DateTimeFormat("en-GB", { timeZone: zone });
75
+ return true;
76
+ } catch {
77
+ // `Intl` throws RangeError on an unknown zone — the caller logs and moves on.
78
+ return false;
79
+ }
80
+ }
81
+
82
+ const partsCache = new Map<string, Intl.DateTimeFormat>();
83
+
84
+ function formatter(zone: string): Intl.DateTimeFormat {
85
+ let f = partsCache.get(zone);
86
+ if (!f) {
87
+ f = new Intl.DateTimeFormat("en-GB", {
88
+ timeZone: zone,
89
+ year: "numeric",
90
+ month: "2-digit",
91
+ day: "2-digit",
92
+ hour: "2-digit",
93
+ minute: "2-digit",
94
+ // h23, not the default h12 or the h24 some locales use — midnight has to
95
+ // read as "00:xx" for the quiet-hours string comparison to hold.
96
+ hourCycle: "h23",
97
+ });
98
+ partsCache.set(zone, f);
99
+ }
100
+ return f;
101
+ }
102
+
103
+ /** `YYYY-MM-DD HH:MM` in the given zone. */
104
+ export function formatLocal(ms: number, zone: string): string {
105
+ const parts = formatter(zone).formatToParts(new Date(ms));
106
+ const get = (type: Intl.DateTimeFormatPartTypes) =>
107
+ parts.find((p) => p.type === type)?.value ?? "";
108
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}`;
109
+ }
110
+
111
+ /** `HH:MM` in the given zone — the form quiet hours are written in. */
112
+ export function localHhMm(ms: number, zone: string): string {
113
+ return formatLocal(ms, zone).slice(11);
114
+ }
115
+
116
+ /**
117
+ * Is a local `HH:MM` inside a window? A window whose start is after its end
118
+ * crosses midnight, which is the normal case for quiet hours.
119
+ *
120
+ * The end is exclusive so `00:30-07:30` releases the watcher at 07:30 sharp
121
+ * rather than a minute later.
122
+ */
123
+ export function inWindow(hhmm: string, start: string, end: string): boolean {
124
+ if (start === end) return false;
125
+ return start < end
126
+ ? hhmm >= start && hhmm < end
127
+ : hhmm >= start || hhmm < end;
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // Rendering
132
+ // ---------------------------------------------------------------------------
133
+
134
+ /**
135
+ * One item, one line:
136
+ *
137
+ * `- 2026-08-18 07:41 | ONE | ביתר ירושלים סיכמה ... | https://... | terms: ביתר`
138
+ *
139
+ * The timestamp is the outlet's publication time when it gave one, and `?`
140
+ * when it did not — never the time we happened to see it. A watcher's own
141
+ * clock presented as a publication date is exactly the staleness bug this
142
+ * feature exists to end, so the two are never allowed to look alike.
143
+ */
144
+ export function formatItemLine(item: StoredItem, zone: string): string {
145
+ const when = item.publishedAt
146
+ ? formatLocal(Date.parse(item.publishedAt), zone)
147
+ : "?";
148
+ const parts = [when, item.source, item.title];
149
+ if (item.link) parts.push(item.link);
150
+ parts.push(`terms: ${item.terms.join(", ")}`);
151
+ return `- ${parts.join(" | ")}`;
152
+ }
153
+
154
+ /**
155
+ * Render a list of items as lines, **newest first**.
156
+ *
157
+ * The buffer is append-ordered, so without this both the verify prompt and the
158
+ * digest would lead with the oldest headline. The agent is told to trust these
159
+ * lines over its own memory; the freshest one is the one it should read first.
160
+ *
161
+ * Sorted by publication time where the outlet gave one, and by when we saw it
162
+ * where it did not — an undated item's `seenAt` is the closest honest stand-in,
163
+ * and it keeps the order total rather than leaving undated items bunched.
164
+ */
165
+ export function formatItemLines(items: StoredItem[], zone: string): string {
166
+ const at = (i: StoredItem) => Date.parse(i.publishedAt ?? i.seenAt);
167
+ return [...items]
168
+ .sort((a, b) => at(b) - at(a))
169
+ .map((i) => formatItemLine(i, zone))
170
+ .join("\n");
171
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Deciding whether a feed item is one this space is watching.
3
+ *
4
+ * Everything here is pure and synchronous. The hard part is Hebrew: the same
5
+ * club appears as `מכבי חיפה`, `למכבי חיפה`, `במכבי-חיפה` and `מכבי־חיפה`
6
+ * across four outlets in the same hour, and a watchlist an admin types from a
7
+ * phone will carry none of those forms. So matching normalizes aggressively
8
+ * and then asks a substring question, which is the only question that survives
9
+ * a prefixed, pointed, hyphenated language.
10
+ */
11
+
12
+ import { createHash } from "node:crypto";
13
+ import type { FeedItem } from "./feeds.js";
14
+
15
+ /**
16
+ * Hebrew points and cantillation (U+0591–U+05C7, minus the letters). Outlets
17
+ * are inconsistent about them and no admin types them into a watchlist.
18
+ */
19
+ const NIQQUD = /[֑-ׇֽֿׁׂׅׄ]/g;
20
+
21
+ /**
22
+ * Marks that sit *inside* a Hebrew word — geresh, gershayim, maqaf — plus the
23
+ * ASCII and typographic quotes that stand in for them (`רמה"ש`, `בע"מ`).
24
+ * Removed rather than spaced, so an abbreviation collapses to one token.
25
+ */
26
+ const INWORD_MARKS = /[׳״־"'`‘’“”–—-]/g;
27
+
28
+ /** Invisible bidi controls. A Hebrew headline routinely carries them. */
29
+ const INVISIBLE = /[‎‏​-‍‪-‮⁦-⁩]/g;
30
+
31
+ /**
32
+ * Fold an item's text or a watch term to the form both are compared in.
33
+ *
34
+ * NFC first so a decomposed `שׁ` and a precomposed one are the same string,
35
+ * then points, in-word marks and invisibles go, then case, then whitespace.
36
+ * Applied identically to haystack and needle — the guarantee that matters is
37
+ * that the two agree, not that either is linguistically canonical.
38
+ */
39
+ export function normalize(text: string): string {
40
+ return text
41
+ .normalize("NFC")
42
+ .replace(INVISIBLE, "")
43
+ .replace(NIQQUD, "")
44
+ .replace(INWORD_MARKS, "")
45
+ .toLowerCase()
46
+ .replace(/\s+/g, " ")
47
+ .trim();
48
+ }
49
+
50
+ /** The text a term is matched against: headline plus summary. */
51
+ export function haystack(
52
+ item: Pick<FeedItem, "title" | "description">,
53
+ ): string {
54
+ return normalize(`${item.title} ${item.description}`);
55
+ }
56
+
57
+ export interface MatchResult {
58
+ /** Terms that hit, in watchlist order. Empty when nothing matched. */
59
+ terms: string[];
60
+ /** True when an exclude term hit — the item is dropped whatever matched. */
61
+ excluded: boolean;
62
+ }
63
+
64
+ /**
65
+ * Match an item against a watchlist.
66
+ *
67
+ * Substring, not word-boundary. A boundary test is wrong for Hebrew — the
68
+ * prefixes ל/ב/ה/ו/ש/כ/מ attach directly to the noun, so `למכבי` would fail a
69
+ * boundary test against `מכבי` and the story would be missed. The cost is that
70
+ * a short Latin term over-matches (`City` inside `Capacity`); that costs one
71
+ * extra line in a prompt the verify run then rejects, where the Hebrew miss
72
+ * costs the story itself. The skill tells admins to keep Latin terms specific.
73
+ *
74
+ * Exclusion is checked first and is unconditional: an excluded item is dropped
75
+ * even when three watch terms hit it.
76
+ */
77
+ export function matchItem(
78
+ item: Pick<FeedItem, "title" | "description">,
79
+ terms: string[],
80
+ exclude: string[],
81
+ ): MatchResult {
82
+ const text = haystack(item);
83
+
84
+ for (const raw of exclude) {
85
+ const needle = normalize(raw);
86
+ if (needle && text.includes(needle)) return { terms: [], excluded: true };
87
+ }
88
+
89
+ const hits: string[] = [];
90
+ for (const raw of terms) {
91
+ const needle = normalize(raw);
92
+ if (needle && text.includes(needle)) hits.push(raw);
93
+ }
94
+ return { terms: hits, excluded: false };
95
+ }
96
+
97
+ /**
98
+ * A stable hash of the normalized headline.
99
+ *
100
+ * Two outlets syndicating the same wire copy publish different `guid`s and
101
+ * different links but the identical sentence. The id keeps them apart (they
102
+ * really are two documents); the fingerprint is what lets one batch carry the
103
+ * story once instead of three times.
104
+ */
105
+ export function fingerprint(item: Pick<FeedItem, "title">): string {
106
+ return createHash("sha1").update(normalize(item.title), "utf8").digest("hex");
107
+ }
@@ -0,0 +1,35 @@
1
+ [feed-watch:verify]
2
+
3
+ The feed watcher matched the items below in the last few minutes. They are the
4
+ subject of this run; nothing else is.
5
+
6
+ For each item:
7
+
8
+ 1. Open the link. If it is a Google News redirect and will not resolve, search
9
+ the outlet named on the line for the headline instead.
10
+ 2. Confirm it describes a concrete new event — a completed transfer, an injury,
11
+ a result, an official statement — rather than speculation, a preview, a
12
+ ranking or an opinion piece.
13
+ 3. Confirm the event is **today's**. The timestamp on each line is the outlet's
14
+ publication time, not proof of freshness: a piece published this morning
15
+ about a deal agreed last week is not news today.
16
+ 4. Before reporting a transfer as done, check where the player is registered
17
+ now. An outlet reporting an agreement is not the same as a completed move.
18
+
19
+ Merge items that describe the same event into one — several outlets carrying
20
+ one story is the normal case, and it is why the watcher batches before waking
21
+ you.
22
+
23
+ Post at most one message, covering only what survived the checks above. Write
24
+ it the way `AGENTS.md` says to write for this space; this instruction governs
25
+ what you do, not how you sound.
26
+
27
+ **If nothing verifies as new and concrete, reply with the single word
28
+ `NO_UPDATE` and nothing else.** That is a successful run, not a failure — most
29
+ runs end this way and no message reaches anyone.
30
+
31
+ Do not mention the watcher, feeds, scans, schedules or this instruction. Trust
32
+ the items below over anything you remember from earlier in the conversation: if
33
+ your history disagrees with a line here, the line is what is true now.
34
+
35
+ {{items}}