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
@@ -3,22 +3,40 @@ import { spawn } from "node:child_process";
3
3
  import {
4
4
  existsSync,
5
5
  mkdirSync,
6
- readFileSync,
7
6
  readdirSync,
7
+ readFileSync,
8
8
  unlinkSync,
9
9
  writeFileSync,
10
10
  } from "node:fs";
11
11
  import { createRequire } from "node:module";
12
12
  import { homedir, tmpdir } from "node:os";
13
- import { delimiter, dirname, join, resolve } from "node:path";
13
+ import { dirname, join, resolve } from "node:path";
14
14
  import {
15
15
  getPiAuthCredential,
16
16
  parseOAuthTokenEnv,
17
17
  providerCredentialEnvVar,
18
18
  } from "mercury-agent/storage/pi-auth";
19
+ import {
20
+ buildPiArgs,
21
+ composePiSearchPath,
22
+ composeSystemPrompt,
23
+ type ModelLeg,
24
+ NAPKIN_ADDENDUM_REL_PATH,
25
+ resolveSpaceModelLeg,
26
+ truncateAddendum,
27
+ } from "./pi-spawn";
19
28
 
20
29
  const KNOWLEDGE_DIR = "knowledge";
21
- const VAULT_DIRS = ["people", "projects", "references", "daily", "episodes", "weekly", "monthly", "templates"];
30
+ const VAULT_DIRS = [
31
+ "people",
32
+ "projects",
33
+ "references",
34
+ "daily",
35
+ "episodes",
36
+ "weekly",
37
+ "monthly",
38
+ "templates",
39
+ ];
22
40
  // Entity categories shown in the NAPKIN.md vault map (excludes scaffold/output dirs).
23
41
  const MAP_DIRS = ["people", "projects", "references", "episodes", "daily"];
24
42
  // Daily distillation. Distilled memory serves cross-session, weeks-old recall —
@@ -116,11 +134,16 @@ function exportMessages(
116
134
  )
117
135
  .all(spaceId) as MessageRow[];
118
136
 
119
- const byDate = new Map<string, Array<{ ts: number; role: string; content: string }>>();
137
+ const byDate = new Map<
138
+ string,
139
+ Array<{ ts: number; role: string; content: string }>
140
+ >();
120
141
  for (const row of rows) {
121
142
  const date = formatDate(row.createdAt);
122
143
  if (!byDate.has(date)) byDate.set(date, []);
123
- byDate.get(date)!.push({ ts: row.createdAt, role: row.role, content: row.content });
144
+ byDate
145
+ .get(date)!
146
+ .push({ ts: row.createdAt, role: row.role, content: row.content });
124
147
  }
125
148
 
126
149
  const changed = new Set<string>();
@@ -128,7 +151,9 @@ function exportMessages(
128
151
  const filePath = join(messagesDir, `${date}.jsonl`);
129
152
  const newContent = `${messages.map((m) => JSON.stringify(m)).join("\n")}\n`;
130
153
 
131
- const oldHash = existsSync(filePath) ? md5(readFileSync(filePath, "utf-8")) : "";
154
+ const oldHash = existsSync(filePath)
155
+ ? md5(readFileSync(filePath, "utf-8"))
156
+ : "";
132
157
  writeFileSync(filePath, newContent);
133
158
  const newHash = md5(newContent);
134
159
 
@@ -141,16 +166,14 @@ function exportMessages(
141
166
  }
142
167
 
143
168
  /**
144
- * Build a child env whose PATH also contains directories where the `pi` CLI
145
- * may live. A global npm install only links the top-level package's bins
146
- * (mercury, mercury-ctl) — dependency bins like `pi` stay in node_modules/.bin.
147
- * We resolve that .bin dir from the package graph first, then fall back to
148
- * well-known global-bin dirs (~/.bun/bin, /usr/local/bin).
169
+ * Build a child env whose PATH puts Mercury's own `pi` dependency first —
170
+ * the version Mercury is pinned to and the agent image ships — then the
171
+ * inherited PATH, then the well-known global-bin dirs (~/.bun/bin,
172
+ * /usr/local/bin). See composePiSearchPath for why that order.
149
173
  */
150
174
  function envWithPiOnPath(): NodeJS.ProcessEnv {
151
175
  const isWindows = process.platform === "win32";
152
176
  const base = process.env.PATH ?? process.env.Path ?? "";
153
- const home = homedir();
154
177
 
155
178
  let piNodeModulesBin: string | undefined;
156
179
  try {
@@ -159,28 +182,70 @@ function envWithPiOnPath(): NodeJS.ProcessEnv {
159
182
  piNodeModulesBin = join(dirname(dirname(dirname(pkgJson))), ".bin");
160
183
  } catch {}
161
184
 
162
- const candidates = [
185
+ const path = composePiSearchPath({
186
+ base,
163
187
  piNodeModulesBin,
164
- join(home, ".bun", "bin"),
165
- isWindows
166
- ? join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "npm")
167
- : "/usr/local/bin",
168
- ].filter(Boolean) as string[];
169
- // PATH entries are case-insensitive on Windows, case-sensitive on POSIX.
170
- const normalize = (p: string) => (isWindows ? p.toLowerCase() : p);
171
- const existing = new Set(base.split(delimiter).map(normalize).filter(Boolean));
172
- const additions = candidates.filter((c) => c && !existing.has(normalize(c)));
173
- const path = [base, ...additions].filter(Boolean).join(delimiter);
188
+ home: homedir(),
189
+ isWindows,
190
+ appData: process.env.APPDATA,
191
+ });
174
192
  // On Windows also set `Path`: process.env keys are case-sensitive but the
175
193
  // Windows env is not, so a stale `Path` could otherwise shadow our `PATH`.
176
194
  return { ...process.env, PATH: path, ...(isWindows ? { Path: path } : {}) };
177
195
  }
178
196
 
197
+ /** The slice of the extension logger these helpers need. */
198
+ interface WarnLogger {
199
+ warn(message: string, fields?: Record<string, unknown>): void;
200
+ }
201
+
202
+ /**
203
+ * The space's own guidance for napkin, when it left any. Applies to every run
204
+ * over this vault — distillation and consolidation alike; see
205
+ * NAPKIN_ADDENDUM_REL_PATH.
206
+ *
207
+ * Absent is the normal case and is not worth a log line. Present-but-unreadable
208
+ * is: the space asked for guidance and is not getting it, and the run would
209
+ * otherwise proceed on the generic prompt with nothing to show for it.
210
+ */
211
+ function readVaultAddendum(
212
+ vaultDir: string,
213
+ log?: WarnLogger,
214
+ ): string | undefined {
215
+ const addendumPath = join(vaultDir, ...NAPKIN_ADDENDUM_REL_PATH.split("/"));
216
+ if (!existsSync(addendumPath)) return undefined;
217
+ let raw: string;
218
+ try {
219
+ raw = readFileSync(addendumPath, "utf-8");
220
+ } catch (err) {
221
+ log?.warn("Space guidance addendum unreadable — using the base prompt", {
222
+ path: addendumPath,
223
+ detail: err instanceof Error ? err.message : String(err),
224
+ });
225
+ return undefined;
226
+ }
227
+ const { text, truncated } = truncateAddendum(raw);
228
+ if (truncated) {
229
+ log?.warn("Space guidance addendum truncated", {
230
+ path: addendumPath,
231
+ bytes: Buffer.byteLength(raw, "utf8"),
232
+ });
233
+ }
234
+ return text;
235
+ }
236
+
237
+ /**
238
+ * One host-side pi run over a vault. The prompt file becomes the *entire*
239
+ * system prompt (`--system-prompt`) and the run is pinned to `leg` — both
240
+ * non-negotiable, see pi-spawn.ts for the two incidents behind them.
241
+ */
179
242
  function runPromptAgent(
180
243
  vaultDir: string,
181
244
  promptPath: string,
182
245
  instruction: string,
183
246
  extraEnv?: Record<string, string>,
247
+ leg?: ModelLeg,
248
+ log?: WarnLogger,
184
249
  ): Promise<{ ok: boolean; detail?: string }> {
185
250
  let promptText: string;
186
251
  try {
@@ -195,45 +260,52 @@ function runPromptAgent(
195
260
  }
196
261
 
197
262
  const promptFile = join(tmpdir(), `kb-distiller-${process.pid}.md`);
198
- writeFileSync(promptFile, promptText);
263
+ writeFileSync(
264
+ promptFile,
265
+ composeSystemPrompt(promptText, {
266
+ vaultDir,
267
+ date: todayDate(),
268
+ addendum: readVaultAddendum(vaultDir, log),
269
+ }),
270
+ );
199
271
 
200
272
  return new Promise((resolve) => {
201
273
  let stderr = "";
202
- const child = spawn(
203
- "pi",
204
- [
205
- "--print",
206
- "--no-session",
207
- "--tools",
208
- "read,bash,write",
209
- "--append-system-prompt",
210
- promptFile,
211
- instruction,
212
- ],
213
- {
214
- cwd: vaultDir,
215
- env: { ...envWithPiOnPath(), ...extraEnv },
216
- // Capture stderr (a background job has no console to inherit usefully):
217
- // the captured tail is what makes a non-zero exit diagnosable in logs.
218
- stdio: ["ignore", "inherit", "pipe"],
219
- },
220
- );
274
+ const child = spawn("pi", buildPiArgs({ promptFile, instruction, leg }), {
275
+ cwd: vaultDir,
276
+ env: { ...envWithPiOnPath(), ...extraEnv },
277
+ // Capture stderr (a background job has no console to inherit usefully):
278
+ // the captured tail is what makes a non-zero exit diagnosable in logs.
279
+ stdio: ["ignore", "inherit", "pipe"],
280
+ });
221
281
 
222
282
  child.stderr?.on("data", (chunk) => {
223
283
  stderr += chunk.toString();
224
284
  });
225
285
 
226
286
  child.on("close", (code) => {
227
- try { unlinkSync(promptFile); } catch {}
287
+ try {
288
+ unlinkSync(promptFile);
289
+ } catch {}
228
290
  if (code === 0) {
229
291
  resolve({ ok: true });
230
292
  return;
231
293
  }
232
- const tail = stderr.trim().split("\n").slice(-3).join(" | ").slice(0, 300);
233
- resolve({ ok: false, detail: `pi exited ${code}${tail ? `: ${tail}` : ""}` });
294
+ const tail = stderr
295
+ .trim()
296
+ .split("\n")
297
+ .slice(-3)
298
+ .join(" | ")
299
+ .slice(0, 300);
300
+ resolve({
301
+ ok: false,
302
+ detail: `pi exited ${code}${tail ? `: ${tail}` : ""}`,
303
+ });
234
304
  });
235
305
  child.on("error", (err) => {
236
- try { unlinkSync(promptFile); } catch {}
306
+ try {
307
+ unlinkSync(promptFile);
308
+ } catch {}
237
309
  resolve({ ok: false, detail: `spawn failed: ${err.message}` });
238
310
  });
239
311
  });
@@ -243,12 +315,16 @@ function runDistiller(
243
315
  vaultDir: string,
244
316
  dateFile: string,
245
317
  extraEnv?: Record<string, string>,
318
+ leg?: ModelLeg,
319
+ log?: WarnLogger,
246
320
  ): Promise<{ ok: boolean; detail?: string }> {
247
321
  return runPromptAgent(
248
322
  vaultDir,
249
323
  KB_DISTILLER_PROMPT_PATH,
250
324
  `Distill knowledge from: ${dateFile}`,
251
325
  extraEnv,
326
+ leg,
327
+ log,
252
328
  );
253
329
  }
254
330
 
@@ -336,10 +412,23 @@ export default function (mercury: {
336
412
  permission(opts: { defaultRoles: string[] }): void;
337
413
  skill(relativePath: string): void;
338
414
  on(event: string, handler: (event: any, ctx: any) => Promise<any>): void;
339
- job(name: string, def: { interval?: number; cron?: string; run: (ctx: any) => Promise<void> }): void;
340
- config(key: string, def: { description: string; default: string; validate?: (v: string) => boolean }): void;
415
+ job(
416
+ name: string,
417
+ def: { interval?: number; cron?: string; run: (ctx: any) => Promise<void> },
418
+ ): void;
419
+ config(
420
+ key: string,
421
+ def: {
422
+ description: string;
423
+ default: string;
424
+ validate?: (v: string) => boolean;
425
+ },
426
+ ): void;
341
427
  widget(def: { label: string; render: (ctx: any) => string }): void;
342
- store: { get(key: string): string | null; set(key: string, value: string): void };
428
+ store: {
429
+ get(key: string): string | null;
430
+ set(key: string, value: string): void;
431
+ };
343
432
  }) {
344
433
  mercury.cli({ name: "napkin", install: "bun add -g napkin-ai" });
345
434
  mercury.permission({ defaultRoles: ["admin", "member"] });
@@ -360,7 +449,8 @@ export default function (mercury: {
360
449
  });
361
450
 
362
451
  mercury.config("distill_backfill_days", {
363
- description: "How far back (in days) to look for unprocessed dates on first enable. Default: 90",
452
+ description:
453
+ "How far back (in days) to look for unprocessed dates on first enable. Default: 90",
364
454
  default: "90",
365
455
  validate: (v) => {
366
456
  const n = Number.parseInt(v, 10);
@@ -494,13 +584,70 @@ export default function (mercury: {
494
584
  return { ok: false, reason };
495
585
  }
496
586
 
587
+ // ---------------------------------------------------------------------------
588
+ // Per-space spawn plan: same model leg and same credential as the space's
589
+ // containers
590
+ // ---------------------------------------------------------------------------
591
+
592
+ /**
593
+ * One planner per job run. `legFor` is the leg the space's containers run
594
+ * on (its `model.active` pin, else the chain's first leg); `credentialFor`
595
+ * is the credential env for a provider, resolved **fresh for every pi
596
+ * spawn** — never cached across a run. A run can outlive the OAuth access
597
+ * token (the first real run did: 23 minutes in, every remaining spawn got
598
+ * 401), and `getPiAuthCredential` only refreshes when asked after expiry.
599
+ * Re-resolving is a file read while the token is valid and one refresh
600
+ * when it is not; concurrent refreshes are already coalesced in pi-auth.
601
+ */
602
+ function createSpacePiPlanner(
603
+ config: Parameters<typeof resolvePiAuthEnv>[0] & {
604
+ resolvedModelChain: readonly ModelLeg[];
605
+ },
606
+ getSpaceConfig: (spaceId: string, key: string) => string | null | undefined,
607
+ ) {
608
+ const chain = config.resolvedModelChain;
609
+ const defaultProvider = chain[0]?.provider ?? config.modelProvider;
610
+ return {
611
+ /** The provider every space falls back to — checked once up front. */
612
+ defaultProvider,
613
+ legFor(spaceId: string): ModelLeg | undefined {
614
+ return resolveSpaceModelLeg(
615
+ getSpaceConfig(spaceId, "model.active"),
616
+ chain,
617
+ );
618
+ },
619
+ credentialFor(leg: ModelLeg | undefined): Promise<PiAuthEnvResult> {
620
+ return resolvePiAuthEnv({
621
+ ...config,
622
+ modelProvider: leg?.provider ?? defaultProvider,
623
+ });
624
+ },
625
+ };
626
+ }
627
+
497
628
  // ---------------------------------------------------------------------------
498
629
  // KB Distillation job
499
630
  // ---------------------------------------------------------------------------
500
631
 
632
+ // The job runner's `running` flag is runner-wide, not per job: an hourly
633
+ // tick fires whether or not the previous run has finished. A backfill of a
634
+ // busy space takes longer than an hour (observed 2026-08-21: the 19:34 tick
635
+ // started a second distillation while the 18:34 one was still writing the
636
+ // same vault). One run at a time, per job; a tick that finds one in flight
637
+ // logs and returns — the next tick picks up whatever is still pending.
638
+ let distillInFlight = false;
639
+ let consolidateInFlight = false;
640
+
501
641
  mercury.job("distill", {
502
642
  interval: 3600_000, // check every hour
503
643
  async run(ctx) {
644
+ if (distillInFlight) {
645
+ ctx.log.info(
646
+ "Skipping KB distillation: previous run still in progress",
647
+ );
648
+ return;
649
+ }
650
+ distillInFlight = true;
504
651
  ctx.log.info("Running KB distillation");
505
652
 
506
653
  try {
@@ -512,18 +659,21 @@ export default function (mercury: {
512
659
  return;
513
660
  }
514
661
 
515
- const piAuth = await resolvePiAuthEnv(ctx.config);
516
- if (!piAuth.ok) {
662
+ const planner = createSpacePiPlanner(ctx.config, (spaceId, key) =>
663
+ ctx.db.getSpaceConfig(spaceId, key),
664
+ );
665
+ const defaultAuth = await planner.credentialFor(undefined);
666
+ if (!defaultAuth.ok) {
517
667
  // One clear host-level error instead of a failed pi spawn per
518
668
  // space per pending date; dates stay pending for the next run.
519
- ctx.log.error("Skipping distillation: no Anthropic credential", {
520
- reason: piAuth.reason,
669
+ ctx.log.error("Skipping distillation: no model credential", {
670
+ provider: planner.defaultProvider,
671
+ reason: defaultAuth.reason,
521
672
  });
522
673
  mercury.store.set("last-distill", new Date().toISOString());
523
674
  mercury.store.set("last-distill-status", "skipped: no credential");
524
675
  return;
525
676
  }
526
- const piAuthEnv = piAuth.env;
527
677
 
528
678
  const db = new Database(dbPath, { readonly: true });
529
679
 
@@ -550,7 +700,10 @@ export default function (mercury: {
550
700
  // null) — it does NOT surface the registered mercury.config default,
551
701
  // so the fallback here must mirror that default. An env var still
552
702
  // wins for operators who want to override globally.
553
- const spaceIntervalRaw = ctx.db.getSpaceConfig(spaceId, "napkin.distill_interval_ms");
703
+ const spaceIntervalRaw = ctx.db.getSpaceConfig(
704
+ spaceId,
705
+ "napkin.distill_interval_ms",
706
+ );
554
707
  const intervalMs = Number.parseInt(
555
708
  spaceIntervalRaw ??
556
709
  process.env.MERCURY_KB_DISTILL_INTERVAL_MS ??
@@ -572,7 +725,11 @@ export default function (mercury: {
572
725
  if (lastDistillAt) {
573
726
  const elapsed = Date.now() - new Date(lastDistillAt).getTime();
574
727
  if (elapsed < intervalMs) {
575
- ctx.log.debug("Skipping space — too soon", { spaceId, elapsed, intervalMs });
728
+ ctx.log.debug("Skipping space — too soon", {
729
+ spaceId,
730
+ elapsed,
731
+ intervalMs,
732
+ });
576
733
  continue;
577
734
  }
578
735
  } else {
@@ -584,7 +741,10 @@ export default function (mercury: {
584
741
  // completion times.
585
742
  const offset = hashSpaceId(spaceId) % intervalMs;
586
743
  const seed = Date.now() - (intervalMs - offset);
587
- mercury.store.set(`last_distill_at:${spaceId}`, new Date(seed).toISOString());
744
+ mercury.store.set(
745
+ `last_distill_at:${spaceId}`,
746
+ new Date(seed).toISOString(),
747
+ );
588
748
  ctx.log.debug("Staggering first distill for space", {
589
749
  spaceId,
590
750
  offsetMs: offset,
@@ -593,7 +753,10 @@ export default function (mercury: {
593
753
  }
594
754
 
595
755
  // --- Step 3: Backfill window ---
596
- const backfillDaysRaw = ctx.db.getSpaceConfig(spaceId, "napkin.distill_backfill_days");
756
+ const backfillDaysRaw = ctx.db.getSpaceConfig(
757
+ spaceId,
758
+ "napkin.distill_backfill_days",
759
+ );
597
760
  const backfillDays = Number.parseInt(backfillDaysRaw ?? "90", 10);
598
761
  const cutoffDate = formatDate(Date.now() - backfillDays * 86_400_000);
599
762
 
@@ -604,7 +767,9 @@ export default function (mercury: {
604
767
  try {
605
768
  distilledSet = new Set(JSON.parse(distilledRaw) as string[]);
606
769
  } catch {
607
- ctx.log.warn("Corrupted distilled set for space — resetting", { spaceId });
770
+ ctx.log.warn("Corrupted distilled set for space — resetting", {
771
+ spaceId,
772
+ });
608
773
  distilledSet = new Set();
609
774
  }
610
775
  } else {
@@ -660,22 +825,51 @@ export default function (mercury: {
660
825
  });
661
826
  }
662
827
  }
663
- mercury.store.set(`last_distill_at:${spaceId}`, new Date().toISOString());
828
+ mercury.store.set(
829
+ `last_distill_at:${spaceId}`,
830
+ new Date().toISOString(),
831
+ );
664
832
  continue;
665
833
  }
666
834
 
667
- ctx.log.info("Distilling space", { spaceId, dates: eligibleDates });
835
+ // --- Step 6: Distill each eligible date, on the space's own leg ---
836
+ const leg = planner.legFor(spaceId);
837
+ ctx.log.info("Distilling space", {
838
+ spaceId,
839
+ dates: eligibleDates,
840
+ provider: leg?.provider,
841
+ model: leg?.model,
842
+ });
668
843
 
669
- // --- Step 6: Distill each eligible date ---
670
844
  for (const date of eligibleDates) {
671
845
  const dateFile = join(messagesDir, `${date}.jsonl`);
672
- const result = await runDistiller(knowledgeDir, dateFile, piAuthEnv);
846
+ // Fresh credential per spawn — see createSpacePiPlanner.
847
+ const auth = await planner.credentialFor(leg);
848
+ if (!auth.ok) {
849
+ // Remaining dates stay pending for the next run.
850
+ ctx.log.error("Stopping space: credential unavailable", {
851
+ spaceId,
852
+ date,
853
+ reason: auth.reason,
854
+ });
855
+ break;
856
+ }
857
+ const result = await runDistiller(
858
+ knowledgeDir,
859
+ dateFile,
860
+ auth.env,
861
+ leg,
862
+ ctx.log,
863
+ );
673
864
  if (result.ok) {
674
865
  ctx.log.info("Distillation complete", { spaceId, date });
675
866
  // Only persist past dates to distilled set (today will always be re-checked)
676
867
  if (date !== today) {
677
868
  distilledSet.add(date);
678
- mercury.store.set(`distilled:${spaceId}`, JSON.stringify([...distilledSet]));
869
+ mercury.store.set(
870
+ `distilled:${spaceId}`,
871
+ JSON.stringify([...distilledSet]),
872
+ );
679
873
  }
680
874
  if (date === today) {
681
875
  distilledTodayCount++;
@@ -700,7 +894,10 @@ export default function (mercury: {
700
894
  });
701
895
  }
702
896
 
703
- mercury.store.set(`last_distill_at:${spaceId}`, new Date().toISOString());
897
+ mercury.store.set(
898
+ `last_distill_at:${spaceId}`,
899
+ new Date().toISOString(),
900
+ );
704
901
  }
705
902
 
706
903
  db.close();
@@ -709,8 +906,14 @@ export default function (mercury: {
709
906
  mercury.store.set("last-distill", now);
710
907
  mercury.store.set("last-distill-status", "success");
711
908
  mercury.store.set("last-distill-total-enabled", String(totalEnabled));
712
- mercury.store.set("last-distill-distilled-today", String(distilledTodayCount));
713
- ctx.log.info("KB distillation complete", { totalEnabled, distilledTodayCount });
909
+ mercury.store.set(
910
+ "last-distill-distilled-today",
911
+ String(distilledTodayCount),
912
+ );
913
+ ctx.log.info("KB distillation complete", {
914
+ totalEnabled,
915
+ distilledTodayCount,
916
+ });
714
917
  } catch (err) {
715
918
  mercury.store.set("last-distill", new Date().toISOString());
716
919
  mercury.store.set("last-distill-status", "failed");
@@ -718,6 +921,8 @@ export default function (mercury: {
718
921
  "KB distillation failed",
719
922
  err instanceof Error ? err : undefined,
720
923
  );
924
+ } finally {
925
+ distillInFlight = false;
721
926
  }
722
927
  },
723
928
  });
@@ -743,6 +948,11 @@ export default function (mercury: {
743
948
  mercury.job("consolidate", {
744
949
  interval: 3600_000,
745
950
  async run(ctx) {
951
+ if (consolidateInFlight) {
952
+ ctx.log.info("Skipping consolidation: previous run still in progress");
953
+ return;
954
+ }
955
+ consolidateInFlight = true;
746
956
  ctx.log.info("Running consolidation check");
747
957
 
748
958
  try {
@@ -751,14 +961,17 @@ export default function (mercury: {
751
961
  const dbPath = join(ctx.config.dataDir, "state.db");
752
962
  if (!existsSync(dbPath)) return;
753
963
 
754
- const piAuth = await resolvePiAuthEnv(ctx.config);
755
- if (!piAuth.ok) {
756
- ctx.log.error("Skipping consolidation: no Anthropic credential", {
757
- reason: piAuth.reason,
964
+ const planner = createSpacePiPlanner(ctx.config, (spaceId, key) =>
965
+ ctx.db.getSpaceConfig(spaceId, key),
966
+ );
967
+ const defaultAuth = await planner.credentialFor(undefined);
968
+ if (!defaultAuth.ok) {
969
+ ctx.log.error("Skipping consolidation: no model credential", {
970
+ provider: planner.defaultProvider,
971
+ reason: defaultAuth.reason,
758
972
  });
759
973
  return;
760
974
  }
761
- const piAuthEnv = piAuth.env;
762
975
 
763
976
  const db = new Database(dbPath, { readonly: true });
764
977
 
@@ -770,14 +983,32 @@ export default function (mercury: {
770
983
  const spaceWorkspace = join(spacesDir, spaceId);
771
984
  const knowledgeDir = join(spaceWorkspace, KNOWLEDGE_DIR);
772
985
  const dailyDir = join(knowledgeDir, "daily");
986
+ const leg = planner.legFor(spaceId);
987
+ // Fresh credential per spawn — see createSpacePiPlanner. A failure
988
+ // is logged once and stops this space's consolidation for the run.
989
+ const credentialOrLog = async (): Promise<
990
+ Record<string, string> | undefined
991
+ > => {
992
+ const auth = await planner.credentialFor(leg);
993
+ if (auth.ok) return auth.env;
994
+ ctx.log.error("Stopping space: credential unavailable", {
995
+ spaceId,
996
+ reason: auth.reason,
997
+ });
998
+ return undefined;
999
+ };
773
1000
  const weeklyDir = join(knowledgeDir, "weekly");
774
1001
  const monthlyDir = join(knowledgeDir, "monthly");
775
1002
 
776
1003
  if (!existsSync(knowledgeDir) || !existsSync(dailyDir)) continue;
777
1004
 
778
1005
  // --- Weekly consolidation ---
779
- const lastWeekly = mercury.store.get(`last_consolidation_weekly:${spaceId}`);
780
- const weeklyElapsed = lastWeekly ? Date.now() - new Date(lastWeekly).getTime() : Infinity;
1006
+ const lastWeekly = mercury.store.get(
1007
+ `last_consolidation_weekly:${spaceId}`,
1008
+ );
1009
+ const weeklyElapsed = lastWeekly
1010
+ ? Date.now() - new Date(lastWeekly).getTime()
1011
+ : Infinity;
781
1012
 
782
1013
  if (weeklyElapsed >= WEEKLY_INTERVAL_MS) {
783
1014
  let dailyFiles: string[];
@@ -815,19 +1046,24 @@ export default function (mercury: {
815
1046
 
816
1047
  for (const week of missingWeeks) {
817
1048
  const dates = datesByWeek.get(week)!;
818
- const dailyPaths = dates
819
- .map((d) => `daily/${d}.md`)
820
- .join(", ");
1049
+ const dailyPaths = dates.map((d) => `daily/${d}.md`).join(", ");
821
1050
  const instruction = `Consolidate week ${week} from daily files: ${dailyPaths}. End date of this week for lifecycle calculations: ${dates[dates.length - 1]}.`;
1051
+ const weekEnv = await credentialOrLog();
1052
+ if (!weekEnv) break;
822
1053
  ctx.log.info("Running weekly consolidation", { spaceId, week });
823
1054
  const result = await runPromptAgent(
824
1055
  knowledgeDir,
825
1056
  WEEKLY_CONSOLIDATION_PROMPT_PATH,
826
1057
  instruction,
827
- piAuthEnv,
1058
+ weekEnv,
1059
+ leg,
1060
+ ctx.log,
828
1061
  );
829
1062
  if (result.ok) {
830
- ctx.log.info("Weekly consolidation complete", { spaceId, week });
1063
+ ctx.log.info("Weekly consolidation complete", {
1064
+ spaceId,
1065
+ week,
1066
+ });
831
1067
  } else {
832
1068
  ctx.log.error("Weekly consolidation failed", {
833
1069
  spaceId,
@@ -844,8 +1080,12 @@ export default function (mercury: {
844
1080
  }
845
1081
 
846
1082
  // --- Monthly consolidation ---
847
- const lastMonthly = mercury.store.get(`last_consolidation_monthly:${spaceId}`);
848
- const monthlyElapsed = lastMonthly ? Date.now() - new Date(lastMonthly).getTime() : Infinity;
1083
+ const lastMonthly = mercury.store.get(
1084
+ `last_consolidation_monthly:${spaceId}`,
1085
+ );
1086
+ const monthlyElapsed = lastMonthly
1087
+ ? Date.now() - new Date(lastMonthly).getTime()
1088
+ : Infinity;
849
1089
 
850
1090
  if (monthlyElapsed >= MONTHLY_INTERVAL_MS) {
851
1091
  let weeklyFiles: string[];
@@ -888,6 +1128,8 @@ export default function (mercury: {
888
1128
  .map((f) => `weekly/${f}`)
889
1129
  .join(", ");
890
1130
  const instruction = `Consolidate month ${currentMonth} from weekly files: ${weeklyPaths}. Today's date: ${todayDate()}.`;
1131
+ const monthEnv = await credentialOrLog();
1132
+ if (!monthEnv) continue;
891
1133
  ctx.log.info("Running monthly consolidation", {
892
1134
  spaceId,
893
1135
  month: currentMonth,
@@ -896,7 +1138,9 @@ export default function (mercury: {
896
1138
  knowledgeDir,
897
1139
  MONTHLY_CONSOLIDATION_PROMPT_PATH,
898
1140
  instruction,
899
- piAuthEnv,
1141
+ monthEnv,
1142
+ leg,
1143
+ ctx.log,
900
1144
  );
901
1145
  if (result.ok) {
902
1146
  ctx.log.info("Monthly consolidation complete", {
@@ -927,6 +1171,8 @@ export default function (mercury: {
927
1171
  "Consolidation failed",
928
1172
  err instanceof Error ? err : undefined,
929
1173
  );
1174
+ } finally {
1175
+ consolidateInFlight = false;
930
1176
  }
931
1177
  },
932
1178
  });
@@ -940,8 +1186,10 @@ export default function (mercury: {
940
1186
  render: () => {
941
1187
  const lastDistill = mercury.store.get("last-distill") ?? "never";
942
1188
  const lastStatus = mercury.store.get("last-distill-status") ?? "—";
943
- const totalEnabled = mercury.store.get("last-distill-total-enabled") ?? "0";
944
- const distilledToday = mercury.store.get("last-distill-distilled-today") ?? "0";
1189
+ const totalEnabled =
1190
+ mercury.store.get("last-distill-total-enabled") ?? "0";
1191
+ const distilledToday =
1192
+ mercury.store.get("last-distill-distilled-today") ?? "0";
945
1193
  return `<div><strong>Last distill:</strong> ${lastDistill}<br><strong>Status:</strong> ${lastStatus}<br><strong>Spaces enabled:</strong> ${totalEnabled}<br><strong>Distilled today:</strong> ${distilledToday}</div>`;
946
1194
  },
947
1195
  });