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,344 @@
1
+ /**
2
+ * The two container hooks: handing the daily article everything the watcher
3
+ * saw, and moving the cursor once the article has actually been written.
4
+ *
5
+ * The governing rule, inherited from `longview/hook.ts`: **a failure here never
6
+ * costs the run.** Every path out of `handleBeforeContainer` either returns a
7
+ * block to append or returns `undefined`, which leaves the article running
8
+ * exactly as it does today. The digest is an input, not a dependency.
9
+ *
10
+ * Skips are logged at debug rather than returned silently. A hook that declines
11
+ * with no trace is indistinguishable from a broken one, which is what made
12
+ * `docs/debug/moderate/07-2026/2026-07-17-profile-member-permissions-silently-disable-extensions.md`
13
+ * cost an hour that one log line would have saved.
14
+ */
15
+
16
+ import { type GetConfig, readSpaceConfig } from "./config.js";
17
+ import {
18
+ formatItemLines,
19
+ formatLocal,
20
+ resolveTimezone,
21
+ type StoredItem,
22
+ } from "./items.js";
23
+ import {
24
+ bufferKey,
25
+ lastDigestKey,
26
+ type WatchLogger,
27
+ type WatchStore,
28
+ } from "./watch.js";
29
+
30
+ /** Marker a task prompt carries to ask for the digest. */
31
+ export const MARKER_DIGEST = "[feed-watch:digest]";
32
+
33
+ /** Marker the extension's own one-shot verify prompts carry. */
34
+ export const MARKER_VERIFY = "[feed-watch:verify]";
35
+
36
+ /** Path of the human-readable digest log inside a space workspace. */
37
+ export const DIGEST_FILE = "knowledge/feed-digest.md";
38
+
39
+ /** How many past windows the workspace file keeps. */
40
+ export const DIGEST_FILE_WINDOWS = 30;
41
+
42
+ /**
43
+ * Where `before_container` records the instant the window it handed the agent
44
+ * closed at, for `after_container` to promote into the real cursor.
45
+ *
46
+ * Without it the cursor advances to *its own* `now`, minutes later, and every
47
+ * item the 3-minute poller picked up while the article was being written is
48
+ * skipped: not in the block the agent saw, and not in the next one either. A
49
+ * hole, where the whole design prefers an overlap.
50
+ */
51
+ export const pendingDigestKey = (spaceId: string) => `digest_until:${spaceId}`;
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // Building the block
55
+ // ---------------------------------------------------------------------------
56
+
57
+ export interface Digest {
58
+ /** The `<feed_watch_digest>` block, ready to append to a prompt. */
59
+ block: string;
60
+ /** ISO cursor this window starts at, or null when there was none. */
61
+ since: string | null;
62
+ /** ISO instant the window ends at. */
63
+ until: string;
64
+ items: StoredItem[];
65
+ }
66
+
67
+ /**
68
+ * Collect everything buffered since the cursor.
69
+ *
70
+ * Returns `undefined` only when the watcher has never stored anything for this
71
+ * space — there is no honest window to report. An *empty* window is a real
72
+ * result and gets a block with `items="0"`: the article has to be able to tell
73
+ * "the watcher saw nothing" apart from "the watcher was not running", and those
74
+ * two produce very different articles.
75
+ */
76
+ export function buildDigest(
77
+ store: WatchStore,
78
+ spaceId: string,
79
+ now: number,
80
+ zone: string,
81
+ log: WatchLogger,
82
+ /**
83
+ * Close the window at this instant instead of `now`. The `after_container`
84
+ * pass uses it to rebuild the *same* window the prompt carried, minutes after
85
+ * the fact — see `handleAfterContainer`.
86
+ */
87
+ untilOverride?: string,
88
+ ): Digest | undefined {
89
+ const raw = store.get(bufferKey(spaceId));
90
+ if (raw === null) return undefined;
91
+
92
+ let buffer: StoredItem[];
93
+ try {
94
+ buffer = JSON.parse(raw) as StoredItem[];
95
+ } catch (err) {
96
+ log.warn("feed-watch: unreadable buffer, no digest for this run", {
97
+ spaceId,
98
+ error: err instanceof Error ? err.message : String(err),
99
+ });
100
+ return undefined;
101
+ }
102
+
103
+ const until = untilOverride ?? new Date(now).toISOString();
104
+ const untilMs = Date.parse(until);
105
+ const since = store.get(lastDigestKey(spaceId));
106
+ const cursorMs = since ? Date.parse(since) : Number.NaN;
107
+ const items = buffer.filter((i) => {
108
+ const seen = Date.parse(i.seenAt);
109
+ if (Number.isFinite(cursorMs) && seen <= cursorMs) return false;
110
+ // Upper bound matters only on the rebuild: nothing can be seen after `now`
111
+ // on the way in, but plenty can arrive while an article is being written.
112
+ return !Number.isFinite(untilMs) || seen <= untilMs;
113
+ });
114
+
115
+ const header = `<feed_watch_digest since="${since ?? ""}" until="${until}" items="${items.length}">`;
116
+ const lines = items.length > 0 ? `\n${formatItemLines(items, zone)}` : "";
117
+ const block =
118
+ `${header}${lines}\n</feed_watch_digest>\n` +
119
+ "These are the only items observed by the feed watcher in this window. " +
120
+ "Prefer them over anything remembered from earlier conversation; an item " +
121
+ "not listed here and not verifiable today from a source dated today is " +
122
+ "not news.";
123
+
124
+ return { block, since, until, items };
125
+ }
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // before_container
129
+ // ---------------------------------------------------------------------------
130
+
131
+ export interface DigestEventLike {
132
+ spaceId: string;
133
+ prompt: string;
134
+ workspace: string;
135
+ }
136
+
137
+ export interface DigestDeps {
138
+ getConfig: GetConfig;
139
+ store: WatchStore;
140
+ log: WatchLogger;
141
+ defaultTimezone?: string;
142
+ /** Injectable clock, so a test does not have to reason about wall time. */
143
+ now?: () => number;
144
+ }
145
+
146
+ /**
147
+ * Append the digest to a prompt that asked for it.
148
+ *
149
+ * Three ways to decline, all logged at debug and all leaving the run untouched:
150
+ * the prompt did not ask, the space is switched off, or the watcher has no
151
+ * buffer yet.
152
+ */
153
+ export function handleBeforeContainer(
154
+ event: DigestEventLike,
155
+ deps: DigestDeps,
156
+ ): { promptAppend: string } | undefined {
157
+ try {
158
+ if (!event.prompt.includes(MARKER_DIGEST)) return undefined;
159
+
160
+ const cfg = readSpaceConfig(deps.getConfig, event.spaceId, deps.log);
161
+ if (!cfg.enabled) {
162
+ deps.log.debug("feed-watch: digest asked for in a space that is off", {
163
+ spaceId: event.spaceId,
164
+ });
165
+ return undefined;
166
+ }
167
+
168
+ const now = deps.now?.() ?? Date.now();
169
+ const zone = resolveTimezone(cfg.timezone, deps.defaultTimezone, deps.log);
170
+ const digest = buildDigest(deps.store, event.spaceId, now, zone, deps.log);
171
+ if (!digest) {
172
+ deps.log.debug("feed-watch: no buffer yet, digest omitted", {
173
+ spaceId: event.spaceId,
174
+ });
175
+ return undefined;
176
+ }
177
+
178
+ // Remember exactly where this window closed. `after_container` promotes it
179
+ // into the cursor, so the cursor can never move past an item the agent was
180
+ // not shown.
181
+ deps.store.set(pendingDigestKey(event.spaceId), digest.until);
182
+
183
+ deps.log.info("feed-watch: digest appended", {
184
+ spaceId: event.spaceId,
185
+ items: digest.items.length,
186
+ since: digest.since,
187
+ until: digest.until,
188
+ });
189
+ return { promptAppend: digest.block };
190
+ } catch (err) {
191
+ // The article is worth more than the digest. Whatever went wrong here, the
192
+ // run proceeds with the prompt it already had.
193
+ deps.log.warn("feed-watch: digest hook failed, run continues without it", {
194
+ spaceId: event.spaceId,
195
+ error: err instanceof Error ? err.message : String(err),
196
+ });
197
+ return undefined;
198
+ }
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // after_container
203
+ // ---------------------------------------------------------------------------
204
+
205
+ /** Read/write access to the workspace digest file, injected for testability. */
206
+ export interface DigestFileIO {
207
+ read(workspace: string): string | null;
208
+ write(workspace: string, content: string): void;
209
+ }
210
+
211
+ export interface AfterDigestEventLike extends DigestEventLike {
212
+ error?: unknown;
213
+ }
214
+
215
+ export interface AfterDigestDeps extends DigestDeps {
216
+ file: DigestFileIO;
217
+ }
218
+
219
+ /**
220
+ * Advance the cursor and append the window to `knowledge/feed-digest.md`.
221
+ *
222
+ * The cursor moves only on a run that finished without error. A failed article
223
+ * re-includes the window next time, and an overlap is strictly better than a
224
+ * hole: the agent seeing an item twice costs a line, whereas skipping the
225
+ * window loses whatever happened in it for good.
226
+ *
227
+ * The file write is a convenience index, never the source of truth — it is
228
+ * attempted after the cursor moves and its failure is logged and swallowed.
229
+ */
230
+ export function handleAfterContainer(
231
+ event: AfterDigestEventLike,
232
+ deps: AfterDigestDeps,
233
+ ): void {
234
+ try {
235
+ if (!event.prompt.includes(MARKER_DIGEST)) return;
236
+ if (event.error) {
237
+ deps.log.debug(
238
+ "feed-watch: run failed, digest cursor left where it was",
239
+ {
240
+ spaceId: event.spaceId,
241
+ },
242
+ );
243
+ return;
244
+ }
245
+
246
+ // The instant the window the agent actually saw closed at. Its absence
247
+ // means `before_container` never appended one — a space enabled between the
248
+ // two hooks, or a prompt that carried the marker while the buffer was
249
+ // empty. Nothing was shown, so nothing is consumed.
250
+ const shownUntil = deps.store.get(pendingDigestKey(event.spaceId));
251
+ if (!shownUntil) {
252
+ deps.log.debug("feed-watch: no digest was appended to this run", {
253
+ spaceId: event.spaceId,
254
+ });
255
+ return;
256
+ }
257
+
258
+ const cfg = readSpaceConfig(deps.getConfig, event.spaceId, deps.log);
259
+ if (!cfg.enabled) return;
260
+
261
+ const now = deps.now?.() ?? Date.now();
262
+ const zone = resolveTimezone(cfg.timezone, deps.defaultTimezone, deps.log);
263
+
264
+ // Rebuild the window the prompt carried — while `lastDigestKey` still
265
+ // holds the *old* cursor, since that is the window's lower bound. Only
266
+ // then advance it.
267
+ const digest = buildDigest(
268
+ deps.store,
269
+ event.spaceId,
270
+ now,
271
+ zone,
272
+ deps.log,
273
+ shownUntil,
274
+ );
275
+
276
+ // Advance and clear unconditionally. Writing the workspace file is
277
+ // best-effort; consuming the window is not, and a buffer that has become
278
+ // unreadable since the prompt was built must not leave the mark behind for
279
+ // tomorrow's article to promote a second time.
280
+ deps.store.set(lastDigestKey(event.spaceId), shownUntil);
281
+ deps.store.delete(pendingDigestKey(event.spaceId));
282
+
283
+ deps.log.info("feed-watch: digest cursor advanced", {
284
+ spaceId: event.spaceId,
285
+ until: shownUntil,
286
+ items: digest?.items.length ?? null,
287
+ });
288
+ if (digest) appendWindow(event.workspace, digest, zone, deps);
289
+ } catch (err) {
290
+ deps.log.warn("feed-watch: after-run digest bookkeeping failed", {
291
+ spaceId: event.spaceId,
292
+ error: err instanceof Error ? err.message : String(err),
293
+ });
294
+ }
295
+ }
296
+
297
+ /** Render one window as a section and prepend it to the workspace file. */
298
+ export function renderDigestSection(
299
+ digest: Digest,
300
+ zone: string,
301
+ now: number,
302
+ ): string {
303
+ const stamp = formatLocal(now, zone);
304
+ const sinceLabel = digest.since
305
+ ? formatLocal(Date.parse(digest.since), zone)
306
+ : "the beginning";
307
+ const body =
308
+ digest.items.length > 0
309
+ ? formatItemLines(digest.items, zone)
310
+ : "- (nothing matched in this window)";
311
+ return `## ${stamp} — ${digest.items.length} items since ${sinceLabel}\n${body}\n`;
312
+ }
313
+
314
+ function appendWindow(
315
+ workspace: string,
316
+ digest: Digest,
317
+ zone: string,
318
+ deps: AfterDigestDeps,
319
+ ): void {
320
+ const now = deps.now?.() ?? Date.now();
321
+ try {
322
+ const existing = deps.file.read(workspace) ?? "";
323
+ const section = renderDigestSection(digest, zone, now);
324
+ // Newest first, so the agent grepping this file reads today at the top.
325
+ const sections = [section, ...splitSections(existing)].slice(
326
+ 0,
327
+ DIGEST_FILE_WINDOWS,
328
+ );
329
+ deps.file.write(workspace, sections.join("\n"));
330
+ } catch (err) {
331
+ // Read-only workspace, full disk, whatever it is — the reply has already
332
+ // been sent and the cursor has already moved. Losing the index is cheap.
333
+ deps.log.warn("feed-watch: could not write the digest file", {
334
+ workspace,
335
+ error: err instanceof Error ? err.message : String(err),
336
+ });
337
+ }
338
+ }
339
+
340
+ /** Split an existing file into its `## ` sections, dropping any preamble. */
341
+ export function splitSections(content: string): string[] {
342
+ const parts = content.split(/^(?=## )/m).map((s) => s.trim());
343
+ return parts.filter((s) => s.startsWith("## ")).map((s) => `${s}\n`);
344
+ }
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Fetching and parsing feeds — the only part of feed-watch that touches the
3
+ * network, and the only part that has to cope with whatever an outlet emits.
4
+ *
5
+ * Deliberately dependency-free. `fast-xml-parser` is present in the tree only
6
+ * as a transitive override, and pulling a real XML parser in for four fields
7
+ * would make this extension the reason a dependency has to stay pinned. The
8
+ * shapes we care about — RSS 2.0 `<item>` and Atom `<entry>` — are flat enough
9
+ * that tag extraction over the raw text is honest, and every fixture in
10
+ * `tests/fixtures/feed-watch/` is a real body from a source the space polls.
11
+ *
12
+ * The governing rule: **a malformed feed yields zero items, never a throw that
13
+ * escapes parsing.** One outlet serving broken XML must not stop the other ten.
14
+ */
15
+
16
+ import { createHash } from "node:crypto";
17
+
18
+ /** One entry from a feed, normalized across RSS and Atom. */
19
+ export interface FeedItem {
20
+ /** Stable identity: guid → link → sha1(title). Used for dedupe across polls. */
21
+ id: string;
22
+ title: string;
23
+ /** Empty string when the feed omits it — an item with no link is still news. */
24
+ link: string;
25
+ /** Outlet name: `<source>` → feed `<title>` → link host. */
26
+ source: string;
27
+ /** ISO 8601, or null when the feed carries no date. */
28
+ publishedAt: string | null;
29
+ /** Description / summary text, stripped of markup. Matched alongside the title. */
30
+ description: string;
31
+ }
32
+
33
+ /** Hard caps. A feed is untrusted input: it is bounded before it is parsed. */
34
+ export const MAX_ITEMS_PER_FEED = 100;
35
+ export const MAX_BODY_BYTES = 512 * 1024;
36
+ export const FETCH_TIMEOUT_MS = 5_000;
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Text extraction
40
+ // ---------------------------------------------------------------------------
41
+
42
+ const NAMED_ENTITIES: Record<string, string> = {
43
+ amp: "&",
44
+ lt: "<",
45
+ gt: ">",
46
+ quot: '"',
47
+ apos: "'",
48
+ nbsp: " ",
49
+ };
50
+
51
+ /**
52
+ * Decode the entity forms feeds actually use.
53
+ *
54
+ * Applied twice in one place — Google News double-escapes an HTML anchor
55
+ * inside `<description>` — so it has to be safe to repeat: a bare `&` is left
56
+ * alone, and an unknown entity is returned verbatim rather than dropped.
57
+ */
58
+ export function decodeEntities(text: string): string {
59
+ return text.replace(
60
+ /&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g,
61
+ (whole, body: string) => {
62
+ const named = NAMED_ENTITIES[body.toLowerCase()];
63
+ if (named !== undefined) return named;
64
+ if (body.startsWith("#x") || body.startsWith("#X")) {
65
+ const code = Number.parseInt(body.slice(2), 16);
66
+ return Number.isFinite(code) ? safeCodePoint(code, whole) : whole;
67
+ }
68
+ if (body.startsWith("#")) {
69
+ const code = Number.parseInt(body.slice(1), 10);
70
+ return Number.isFinite(code) ? safeCodePoint(code, whole) : whole;
71
+ }
72
+ return whole;
73
+ },
74
+ );
75
+ }
76
+
77
+ /** `String.fromCodePoint` throws on out-of-range values; a feed can carry one. */
78
+ function safeCodePoint(code: number, fallback: string): string {
79
+ if (code < 0 || code > 0x10ffff) return fallback;
80
+ try {
81
+ return String.fromCodePoint(code);
82
+ } catch {
83
+ // Lone surrogate or similar. The entity is not decodable; keep the source
84
+ // text so the title still reads, rather than losing the character.
85
+ return fallback;
86
+ }
87
+ }
88
+
89
+ /** Strip tags and collapse whitespace — feed descriptions carry markup. */
90
+ export function stripMarkup(text: string): string {
91
+ return decodeEntities(decodeEntities(text).replace(/<[^>]*>/g, " "))
92
+ .replace(/\s+/g, " ")
93
+ .trim();
94
+ }
95
+
96
+ /**
97
+ * Read one child tag's text out of a block.
98
+ *
99
+ * CDATA wins over entity decoding — a CDATA section is literal by definition,
100
+ * so `&amp;` inside one is five characters the outlet meant to write.
101
+ */
102
+ export function extractTag(block: string, name: string): string | null {
103
+ const re = new RegExp(
104
+ `<${name}(?:\\s[^>]*)?\\s*(?:/>|>([\\s\\S]*?)</${name}\\s*>)`,
105
+ "i",
106
+ );
107
+ const m = re.exec(block);
108
+ if (!m) return null;
109
+ const raw = m[1];
110
+ if (raw === undefined) return "";
111
+ const cdata = /^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/.exec(raw);
112
+ if (cdata) return (cdata[1] ?? "").trim();
113
+ return decodeEntities(raw).trim();
114
+ }
115
+
116
+ /**
117
+ * Atom `<link>` carries its target in `href`, and an entry may list several
118
+ * (`alternate`, `self`, `replies`). `alternate` is the article; absent any
119
+ * `rel` the first one is, which is what a bare `<link>` means.
120
+ */
121
+ function atomLink(block: string): string {
122
+ const links = [...block.matchAll(/<link\b[^>]*>/gi)].map((m) => m[0]);
123
+ const alternate = links.find((l) => /rel\s*=\s*"alternate"/i.test(l));
124
+ const chosen =
125
+ alternate ?? links.find((l) => !/rel\s*=\s*"/i.test(l)) ?? links[0];
126
+ if (!chosen) return "";
127
+ const href = /href\s*=\s*"([^"]*)"/i.exec(chosen);
128
+ return href?.[1] ? decodeEntities(href[1]).trim() : "";
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Dates
133
+ // ---------------------------------------------------------------------------
134
+
135
+ /**
136
+ * RFC-822 (`Fri, 21 Aug 2026 11:27:00 +0300`) and ISO both parse with `Date`.
137
+ *
138
+ * Anything else becomes `null` rather than an invalid date that would later
139
+ * format as `Invalid Date` on a prompt line the agent is told to trust.
140
+ */
141
+ export function parseDate(raw: string | null): string | null {
142
+ if (!raw) return null;
143
+ const ms = Date.parse(raw.trim());
144
+ if (!Number.isFinite(ms)) return null;
145
+ return new Date(ms).toISOString();
146
+ }
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // Identity
150
+ // ---------------------------------------------------------------------------
151
+
152
+ /**
153
+ * `guid` is what an outlet means by "the same story". Falling back to `link`
154
+ * and then to a hash of the title keeps an id stable across polls for feeds
155
+ * that omit it — without one, every poll would re-report the whole feed.
156
+ */
157
+ export function itemId(
158
+ guid: string | null,
159
+ link: string,
160
+ title: string,
161
+ ): string {
162
+ const g = guid?.trim();
163
+ if (g) return g;
164
+ const l = link.trim();
165
+ if (l) return l;
166
+ return `sha1:${createHash("sha1").update(title, "utf8").digest("hex")}`;
167
+ }
168
+
169
+ /** Host of a URL, or "" — used as the last-resort outlet name. */
170
+ export function hostOf(url: string): string {
171
+ try {
172
+ return new URL(url).host.replace(/^www\./, "");
173
+ } catch {
174
+ // Not a URL (a bare guid, or an outlet emitting a relative path). The
175
+ // caller falls through to the feed title; there is nothing to report.
176
+ return "";
177
+ }
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // Parsing
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /**
185
+ * Parse an RSS 2.0 or Atom body into items. Never throws: an unrecognised or
186
+ * truncated body simply yields `[]`.
187
+ */
188
+ export function parseFeed(xml: string, fallbackSource = ""): FeedItem[] {
189
+ const firstEntry = xml.search(/<(?:item|entry)\b/i);
190
+ // The feed's own `<title>` is the outlet name, but only the one *before* the
191
+ // first item — reading the whole body would pick up the first headline.
192
+ const header = firstEntry > 0 ? xml.slice(0, firstEntry) : "";
193
+ const feedName = extractTag(header, "title") || fallbackSource;
194
+
195
+ const blocks = [
196
+ ...xml.matchAll(/<item\b[^>]*>[\s\S]*?<\/item\s*>/gi),
197
+ ...xml.matchAll(/<entry\b[^>]*>[\s\S]*?<\/entry\s*>/gi),
198
+ ]
199
+ .map((m) => m[0])
200
+ .slice(0, MAX_ITEMS_PER_FEED);
201
+
202
+ const items: FeedItem[] = [];
203
+ for (const block of blocks) {
204
+ const title = extractTag(block, "title");
205
+ // A titleless entry is unmatchable and unreportable — the agent would be
206
+ // handed a line with nothing in it.
207
+ if (!title) continue;
208
+
209
+ const isAtom = /<\/entry\s*>\s*$/i.test(block);
210
+ const link = isAtom ? atomLink(block) : (extractTag(block, "link") ?? "");
211
+ const guid =
212
+ extractTag(block, "guid") ?? (isAtom ? extractTag(block, "id") : null);
213
+ const published = parseDate(
214
+ extractTag(block, "pubDate") ??
215
+ extractTag(block, "published") ??
216
+ extractTag(block, "updated") ??
217
+ extractTag(block, "dc:date"),
218
+ );
219
+ // `<source>` is what Google News uses to name the real outlet behind an
220
+ // opaque redirect link — the only outlet name that survives the redirect.
221
+ const source =
222
+ extractTag(block, "source") || feedName || hostOf(link) || fallbackSource;
223
+ const description = stripMarkup(
224
+ extractTag(block, "description") ??
225
+ extractTag(block, "summary") ??
226
+ extractTag(block, "content") ??
227
+ "",
228
+ );
229
+
230
+ items.push({
231
+ id: itemId(guid, link, title),
232
+ title: stripMarkup(title),
233
+ link,
234
+ source: stripMarkup(source),
235
+ publishedAt: published,
236
+ description,
237
+ });
238
+ }
239
+ return items;
240
+ }
241
+
242
+ // ---------------------------------------------------------------------------
243
+ // Google News query URLs
244
+ // ---------------------------------------------------------------------------
245
+
246
+ export interface GnewsOptions {
247
+ hl?: string;
248
+ gl?: string;
249
+ ceid?: string;
250
+ }
251
+
252
+ /**
253
+ * Build one Google-News RSS search URL for a term.
254
+ *
255
+ * `when:1d` is appended because the whole point of the watcher is *new* news;
256
+ * without it the query returns the same month-old features on every poll, and
257
+ * every one of them is an item a verify run has to open and reject.
258
+ */
259
+ export function gnewsUrl(term: string, opts: GnewsOptions = {}): string {
260
+ const hl = opts.hl ?? "en";
261
+ const gl = opts.gl ?? "US";
262
+ const ceid = opts.ceid ?? `${gl}:${hl.split("-")[0]}`;
263
+ const q = encodeURIComponent(`${term.trim()} when:1d`);
264
+ return `https://news.google.com/rss/search?q=${q}&hl=${encodeURIComponent(hl)}&gl=${encodeURIComponent(gl)}&ceid=${encodeURIComponent(ceid)}`;
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Fetching
269
+ // ---------------------------------------------------------------------------
270
+
271
+ export type FetchImpl = (
272
+ url: string,
273
+ init?: { signal?: AbortSignal; headers?: Record<string, string> },
274
+ ) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;
275
+
276
+ /**
277
+ * Fetch and parse one feed.
278
+ *
279
+ * Throws on HTTP failure, timeout or an oversize body so the caller can record
280
+ * the failure against that source and back off; it never throws for *content*
281
+ * reasons — a body that parses to nothing returns `[]`.
282
+ */
283
+ export async function fetchFeed(
284
+ url: string,
285
+ opts: {
286
+ fetchImpl: FetchImpl;
287
+ timeoutMs?: number;
288
+ maxBytes?: number;
289
+ fallbackSource?: string;
290
+ /**
291
+ * Called when a cap bit. The caller decides how loudly to say so — this
292
+ * module has no logger and should not grow one, but a source quietly
293
+ * losing half its items is exactly the kind of thing that must not be
294
+ * silent.
295
+ */
296
+ onTruncate?: (
297
+ kind: "bytes" | "items",
298
+ detail: Record<string, number>,
299
+ ) => void;
300
+ },
301
+ ): Promise<FeedItem[]> {
302
+ const controller = new AbortController();
303
+ const timer = setTimeout(
304
+ () => controller.abort(),
305
+ opts.timeoutMs ?? FETCH_TIMEOUT_MS,
306
+ );
307
+ try {
308
+ const res = await opts.fetchImpl(url, {
309
+ signal: controller.signal,
310
+ headers: { "user-agent": "mercury-feed-watch/1.0" },
311
+ });
312
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
313
+ const body = await res.text();
314
+ const max = opts.maxBytes ?? MAX_BODY_BYTES;
315
+
316
+ // Measured in bytes, not UTF-16 units: a Hebrew feed is two bytes per
317
+ // character, so a code-unit cap would let through twice what it claims.
318
+ //
319
+ // **Truncated, not rejected.** Throwing here would reach the caller as a
320
+ // *source failure* — backoff, then a retry that fails identically, and a
321
+ // warning only on the first tick of the streak. A feed that grew past the
322
+ // cap would drop out of the watchlist permanently behind one log line, and
323
+ // two of the configured sources are already within 2× of it. Cutting the
324
+ // body keeps the newest items flowing; a trailing partial `<item>` has no
325
+ // closing tag and is dropped by the parser rather than half-read.
326
+ const bytes = Buffer.byteLength(body, "utf8");
327
+ let text = body;
328
+ if (bytes > max) {
329
+ text = Buffer.from(body, "utf8").subarray(0, max).toString("utf8");
330
+ opts.onTruncate?.("bytes", { bytes, max });
331
+ }
332
+
333
+ const items = parseFeed(text, opts.fallbackSource ?? hostOf(url));
334
+ if (items.length === MAX_ITEMS_PER_FEED) {
335
+ opts.onTruncate?.("items", { kept: MAX_ITEMS_PER_FEED });
336
+ }
337
+ return items;
338
+ } finally {
339
+ clearTimeout(timer);
340
+ }
341
+ }