Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

chore: document/guard insights narrative LLM trigger contract (#2037)

Adam Eivyf5b1e1719394
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3a531ba3eb..bcc6fa112f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,3 +26,4 @@
- Migration 155 heals `data/prompts/stages/cd-treatment.md` installs that #1808's anchor-based migration 148 left stranded (#2042). Installs seeded before the `imageStrength` scene knob (older pre-#1808 template) got the `## Cast & ingredients` list but missed the per-scene `"cast": [{ "ingredientId": … }]` field, so the Creative Director cast-threading regression test stayed red on the runtime template and migration 148 (already applied) never re-ran. The new hash-driven prompt-replace upgrades those copies (and both pristine pre-#1808 shipped versions) to the current shipped reference, leaving hand-customized copies untouched. Also folds `cd-treatment.md` into `buildPromptDriftTables` so setup-data.js's drift warning classifies a stranded copy correctly.
- Replaced the last hardcoded `port-*` hex stragglers with design tokens (#2031). The Security page's audio-level meter used raw `#ef4444`/`#f59e0b`/`#22c55e` in an inline `backgroundColor`; these now resolve through `rgb(var(--port-error))`/`--port-warning`/`--port-success` so they track the theme. The Chief-of-Staff page's "CoS" wordmark gradient was duplicated inline three times and is now a single module-level `COS_TITLE_GRADIENT` constant. Visual output is unchanged.
- Fixed double error toasts across ~50 call sites that owned a custom `.catch` toast: they now pass `{ silent: true }` so the `apiCore.request()` default toast no longer fires alongside the component's own, per the "Silent vs. toasting API requests" convention (#2026). Also added the missing trailing `options = {}` passthrough to ~40 `api*.js` wrappers (CoS tasks/agents/jobs, Brain people/projects/ideas/admin/memories/buckets/inbox, GSD, memory approve/reject, app task-type overrides, feature-agent controls, browser/backup/system, MeatSpace POST drills, goals, messages) so callers can actually suppress the built-in toast. Sites whose `.catch` only reverts state (no toast) were intentionally left on the default single toast.
+- Audited the cross-domain insights engine against the no-cold-bootstrap LLM policy and documented the trigger contract at the two generation entry points (#2037). Verified the only functions that call an AI provider — `generateThemeAnalysis` (INS-02) and `refreshCrossDomainNarrative` (INS-04) — are reached solely from user-triggered POST endpoints (`/api/insights/themes/refresh`, `/api/insights/narrative/refresh`, both fired by an explicit "Refresh" click); the page-mount and cached-read paths (`getThemeAnalysis`/`getCrossDomainNarrative`) are disk-only, boot (`server/index.js`) mounts the router without generating, and no scheduler references insights. No violation found — added a contract comment block plus a regression test asserting the read paths never call a provider.
diff --git a/server/services/insightsService.js b/server/services/insightsService.js
index ce4d0fc8b9..823be8c4a5 100644
--- a/server/services/insightsService.js
+++ b/server/services/insightsService.js
@@ -216,6 +216,28 @@ export async function callProviderAISimple(provider, model, prompt, { temperatur
// =============================================================================
// EXPORTED FUNCTIONS
// =============================================================================
+//
+// LLM TRIGGER CONTRACT (no-cold-bootstrap policy — see CLAUDE.md "AI Provider
+// Usage Policy"). The insights source data (genome, blood tests, taste profile,
+// Apple Health) is sensitive, so provider calls must be *explicitly* user-driven:
+//
+// - generateThemeAnalysis (INS-02) and refreshCrossDomainNarrative (INS-04)
+// are the ONLY functions here that call an AI provider. Each is reached solely
+// from an explicit POST (`/api/insights/themes/refresh`,
+// `/api/insights/narrative/refresh`) that the user triggers by clicking
+// "Refresh" in the Insights UI (CrossDomainTab / TasteIdentityTab handleRefresh).
+// - The read paths getThemeAnalysis / getCrossDomainNarrative are disk-only
+// (readJSONFile → cached JSON, never a provider call), mirroring the
+// initDrillCache/requestCacheFill split in meatspacePostDrillCache.js. The
+// Insights page mounts by calling ONLY these read paths.
+// - getGenomeHealthCorrelations (INS-01) is pure rule-based (no LLM).
+//
+// Boot/init (server/index.js) mounts the router only — it must NEVER call a
+// generation function. No scheduler (taskSchedule / backupScheduler /
+// cosJobScheduler / automationScheduler) references insights. Do not add a
+// boot-time warm-up, a background refresh, or a page-mount auto-generate — any
+// new caller of the two generation functions must be a direct user action in the
+// same request (or an explicitly user-configured scheduled automation).
/**
* INS-01: Get genome-health correlations (pure rule-based, no LLM).
@@ -347,6 +369,10 @@ export async function getThemeAnalysis() {
* INS-02: Generate taste-identity themes via LLM and persist to disk.
* Reads taste profile sections, constructs prompt, parses JSON response.
*
+ * LLM CALL — user-triggered only. See the trigger-contract note above. Reached
+ * solely from POST /api/insights/themes/refresh (a user "Refresh" click). Never
+ * call from boot, a warm-up, or a page-mount effect.
+ *
* @param {string} [providerId] - Optional provider ID override
* @param {string} [model] - Optional model override
*/
@@ -430,6 +456,10 @@ export async function getCrossDomainNarrative() {
* Gathers genome, taste-identity, and Apple Health context; writes narrative
* to disk preserving previousText for client-side diff.
*
+ * LLM CALL — user-triggered only. See the trigger-contract note above. Reached
+ * solely from POST /api/insights/narrative/refresh (a user "Refresh" click).
+ * Never call from boot, a warm-up, or a page-mount effect.
+ *
* @param {string} [providerId] - Optional provider ID override
* @param {string} [model] - Optional model override
*/
diff --git a/server/services/insightsService.test.js b/server/services/insightsService.test.js
index 2a98d9faf1..4721783bd1 100644
--- a/server/services/insightsService.test.js
+++ b/server/services/insightsService.test.js
@@ -10,7 +10,11 @@ vi.mock('../lib/fetchWithTimeout.js', () => ({
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { mockJsonResponse, mockTextResponse } from '../lib/testHelper.js';
-import { callProviderAISimple } from './insightsService.js';
+import {
+ callProviderAISimple,
+ getThemeAnalysis,
+ getCrossDomainNarrative,
+} from './insightsService.js';
const PROVIDER = { type: 'api', endpoint: 'http://localhost:1234/v1' };
@@ -58,3 +62,26 @@ describe('insightsService.callProviderAISimple — non-JSON-body guard', () => {
expect(result.error).toMatch(/Provider returned 500: boom/);
});
});
+
+// Enforces the no-cold-bootstrap trigger contract documented at the generation
+// entry points: the cached-read paths the Insights page mounts with must be
+// disk-only and NEVER reach an AI provider. Only the user-triggered *refresh*
+// endpoints may generate. If a future edit makes a read path warm the cache via
+// the LLM, this fails.
+describe('insightsService read paths — disk-only, no provider call', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('getThemeAnalysis performs no provider call (returns not_generated when uncached)', async () => {
+ const result = await getThemeAnalysis();
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ expect(result.available === false || result.available === true).toBe(true);
+ });
+
+ it('getCrossDomainNarrative performs no provider call (returns not_generated when uncached)', async () => {
+ const result = await getCrossDomainNarrative();
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+ expect(result.available === false || result.available === true).toBe(true);
+ });
+});