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

Gate MeatSpace POST drill-cache fill behind explicit user consent

[._.]/ Adam Eivycce6ee2fa788
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a4be3d79cd..7623af577d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,6 @@
## AI Providers
+- **MeatSpace POST wordplay drills no longer cold-bootstrap LLM calls on server boot.** `initDrillCache()` fired at every server start and, on a fresh install (empty on-disk cache), silently kicked off a sequential 40-call backfill (4 drill types × up to 10 batches each) — visibly slow and surprising when the active provider was a TUI-driven CLI, since each call pastes into a real `claude`/`codex` session and waits. Boot now only loads the existing on-disk cache into memory (zero LLM calls); the bulk cache-fill only runs from a new explicit `POST /api/meatspace/post/drill-cache/fill` endpoint, gated behind a client-side consent modal (`CacheFillConsentModal` in `WordplayTrainer.jsx`) that names the provider about to be used and lets the user pick a different provider/model or skip straight to a single on-demand drill. Incremental top-ups after a cache has already been primed still run silently (`triggerReplenish` now no-ops on a cold/empty cache). See the new "AI Provider Usage Policy" section in `CLAUDE.md` — no PortOS feature should queue AI provider calls a user hasn't knowingly triggered, outside of automations the user explicitly scheduled.
- **[issue-1865] CLI provider runs now work on Windows** — npm-installed CLI providers (OpenCode, Codex, Claude Code) ship as `.cmd`/`.bat` shims on Windows; a bare command name like `opencode` never resolves there because `spawn()`'s default `shell:false` doesn't apply Windows' PATHEXT search at all. The Test-provider button surfaced this as "Resolved 'opencode' to ... but it could not be executed" — and that diagnostic was itself hitting a second bug: `where`'s first PATH match can be the extension-less POSIX shell-script stub npm ships alongside the real Windows wrapper (for Git Bash/WSL), which is never launchable natively. A new `resolveWindowsExecutable` (`server/lib/bufferedSpawn.js`) resolves a bare command to its actual `.exe`/`.cmd`/`.bat` path via a deliberately extension-aware filesystem search (skipping that stub). Critically, a resolved `.cmd`/`.bat` target still cannot be launched directly under `shell:false` even with the explicit extension — Node's CVE-2024-27980 patch makes `spawn()`/`execFile()` refuse batch files outright rather than safely auto-wrapping them — so a new `prepareWindowsSafeSpawn` wraps a batch target through Node's own documented-safe pattern, `cmd.exe /c <path> <args>` (a native `.exe` target is launched directly, unwrapped). Because `cmd.exe` is itself a normal native executable, Node's existing, already-tested non-shell argv escaping governs the result — correctly preserving spaces in each argument (including a multi-word vision-captioning prompt) — with none of `shell:true`'s DEP0190 hazard (`shell:true` with an args array does **not** escape arguments, it just space-joins them, so it was rejected as the fix here). This applies to the runner's spawn call, the vendored toolkit's built-in fallback, the autofixer/calendar-sync CLI runner, the vision-captioning CLI runner, and `testProvider()`'s version probe (fixing the Test button's literal reported scenario). Because a `.cmd`/`.bat` target routes through an intermediate `cmd.exe` process, a plain `SIGTERM` only kills that wrapper and orphans the real CLI process; every kill path for these processes (timeout, fallback-signal abort, Stop Run) now uses a `taskkill /T /F`-based process-tree kill on Windows (`killProcessTree`, extended to mark `.killed` synchronously and to skip non-`ChildProcess` killables like a node-pty TUI session, which has its own native teardown) and a plain `SIGTERM` elsewhere, unchanged. (#1865)
- **[claude-default-sonnet-5] Default Claude CLI/TUI providers now use `claude-sonnet-5` for the medium tier.** The seeded `claude-code`, `claude-code-tui`, and both `*-bedrock` providers ship the new sonnet tier (`claude-sonnet-5`, Bedrock `us.anthropic.claude-sonnet-5`) in place of `claude-sonnet-4-6`, and the Anthropic model-refresh dropdown lists it first. Migration 153 bumps existing installs' sonnet tier from `claude-sonnet-4-6` → `claude-sonnet-5` — rewriting the models list and swapping any tier pointer still on `claude-sonnet-4-6`, while leaving customized model lists and still-current pins (opus-4-8, haiku-4-5) untouched. The `claude-sonnet-5` context window (1M) is registered in both the server (`stageRunner.js`) and client (`utils/providers.js`) model maps. (`data.reference/providers.json`, `server/lib/aiToolkit/defaults/providers.sample.json`, `server/routes/scaffoldPortOS.js`)
diff --git a/CLAUDE.md b/CLAUDE.md
index 13255884e0..0b7feee940 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,6 +43,22 @@ The default database password `portos` (in `ecosystem.config.cjs`, `docker-compo
**Never run DB-backed tests against the real `portos` database.** There is ONE Postgres per install, shared by every git worktree (including CoS-agent worktrees). The `*.db.test.js` suites `DELETE FROM`/`INSERT` whole tables, so running them against `portos` corrupts the user's real universes/series/writers-room/catalog. They are gated to skip on a non-test DB and run only via `npm run test:db` (→ `portos_test`, provisioned by `npm run setup:db:test`). The gate in `server/lib/db.js` keys on `isTestRunner()` (`NODE_ENV==='test'` **OR** `process.env.VITEST`, not bare `NODE_ENV` — a wrapper that drops `NODE_ENV` must NOT be able to disarm it) and the `query()` backstop refuses ALL row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`) to a non-test DB under the runner. Do not weaken either to "just `NODE_ENV`" or "DELETE-only" — that's exactly the hole that wiped real data on 2026-06-13/14. See `server/lib/db.guards.test.js`.
+## AI Provider Usage Policy
+
+**No cold-bootstrap LLM calls.** PortOS must never queue up AI provider calls a user hasn't knowingly triggered. A new install (or a freshly merged feature) coming online should be silent on the LLM front until the user actually asks for AI-backed work. This rules out:
+
+- Firing LLM calls from server boot / `server/index.js` init sequences (cache warm-ups, pre-generation, startup backfills).
+- Any background job that silently expands from "generate the one thing the user asked for" into "generate a whole batch for later," without the user having opted into that batch.
+
+**Scheduled automations are the one sanctioned exception** — a cron-style task, autopilot, or CoS agent the user explicitly configured (see `taskSchedule.js`, `backupScheduler.js`, autopilot gates) is expected to call AI providers on its own schedule, because the user set it up and knows it's running. Anything else that touches an AI provider needs either a direct user action in the same request, or an explicit consent/config step first.
+
+**Pattern for background pre-generation (e.g. caches).** If a feature wants to pre-fill a cache of AI-generated content so future requests are instant:
+1. Boot-time init loads only what's already on disk — zero LLM calls.
+2. The bulk/cold fill only runs from an explicit user-triggered endpoint, gated behind a UI prompt that names the provider/model about to be used and lets the user change it (or decline and get a single on-demand generation instead).
+3. Incremental top-ups after the user has already engaged with the feature (e.g. replenishing one item after they consumed one from an already-primed cache) are fine to run silently — the user already consented once, and a small top-up doesn't route through a slow provider unannounced the way a from-zero batch does.
+
+See `server/services/meatspacePostDrillCache.js` (`initDrillCache` / `requestCacheFill` split) and `client/src/components/meatspace/post/WordplayTrainer.jsx` (`CacheFillConsentModal`) for the reference implementation — added after a fresh MeatSpace POST install triggered an unannounced 40-call sequential TUI backfill on first boot.
+
## Architecture
PortOS is a monorepo with Express.js server (always user-facing on `:5555`, HTTP or HTTPS) and React/Vite client (Vite dev server on `:5554` in `npm run dev`; in `npm start` the built client is served from `:5555` directly). PM2 manages app lifecycles. Data persists to JSON files in `./data/`.
diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsx
index d6f3e836e7..9d9b57050c 100644
--- a/client/src/components/meatspace/post/PostDrillConfig.jsx
+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';
import { ArrowLeft, Save, Brain } from 'lucide-react';
import { updatePostConfig, getProviders } from '../../../services/api';
import toast from '../../ui/Toast';
-import { filterSelectableModels, isApiProvider } from '../../../utils/providers';
+import { filterSelectableModels, enabledApiProviderFilter } from '../../../utils/providers';
const DRILL_META = {
'doubling-chain': {
@@ -114,7 +114,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {
const [saving, setSaving] = useState(false);
useEffect(() => {
- getProviders().then(p => setProviders((p || []).filter(pr => pr.enabled && isApiProvider(pr)))).catch(err => console.warn('⚠️ Failed to load providers: ' + err.message));
+ getProviders().then(p => setProviders((p?.providers || []).filter(enabledApiProviderFilter))).catch(err => console.warn('⚠️ Failed to load providers: ' + err.message));
}, []);
function toggleDrill(type) {
diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsx
index 94e53d8701..569fcd5205 100644
--- a/client/src/components/meatspace/post/WordplayTrainer.jsx
+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx
@@ -1,6 +1,13 @@
-import { useState, useRef, useCallback } from 'react';
-import { ArrowLeft, Link, Puzzle, BookOpen, Shuffle, CheckCircle, XCircle, ChevronRight } from 'lucide-react';
-import { generatePostDrill, scorePostLlmDrill } from '../../../services/api';
+import { useState, useRef, useCallback, useEffect } from 'react';
+import { ArrowLeft, Link, Puzzle, BookOpen, Shuffle, CheckCircle, XCircle, ChevronRight, Sparkles } from 'lucide-react';
+import {
+ generatePostDrill, scorePostLlmDrill, getPostDrillCacheStatus, fillPostDrillCache, updatePostConfig,
+} from '../../../services/api';
+import { enabledApiProviderFilter } from '../../../utils/providers';
+import useProviderModels from '../../../hooks/useProviderModels';
+import ProviderModelSelector from '../../ProviderModelSelector';
+import Modal from '../../ui/Modal';
+import toast from '../../ui/Toast';
import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar } from './WordplayDrillUI';
const GAME_MODES = [
@@ -42,7 +49,7 @@ const GAME_MODES = [
},
];
-export default function WordplayTrainer({ onBack, config }) {
+export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
const [selectedMode, setSelectedMode] = useState(null);
const [drill, setDrill] = useState(null);
const [loading, setLoading] = useState(false);
@@ -54,6 +61,23 @@ export default function WordplayTrainer({ onBack, config }) {
const inputRef = useRef(null);
const questionStartRef = useRef(Date.now());
+ // Cache-fill consent: PortOS never issues background LLM calls a user
+ // hasn't asked for. A mode whose drill cache is cold (0 cached) prompts
+ // for provider/model + explicit consent before any bulk generation runs.
+ // Modes primed this session (either filled or explicitly skipped) don't
+ // re-prompt even if the server-side count is still catching up.
+ const [cacheStatus, setCacheStatus] = useState(null);
+ const [primedModes, setPrimedModes] = useState(() => new Set());
+ const [pendingMode, setPendingMode] = useState(null);
+ const {
+ providers, selectedProviderId: fillProviderId, selectedModel: fillModel,
+ availableModels: fillModels, setSelectedProviderId: setFillProviderId, setSelectedModel: setFillModel,
+ } = useProviderModels({ filter: enabledApiProviderFilter, allowDefault: true, silent: true });
+
+ useEffect(() => {
+ getPostDrillCacheStatus().then(setCacheStatus).catch(() => setCacheStatus({}));
+ }, []);
+
const providerId = config?.llmDrills?.providerId || null;
const model = config?.llmDrills?.model || null;
@@ -61,7 +85,7 @@ export default function WordplayTrainer({ onBack, config }) {
const totalPrompts = prompts.length;
const currentPrompt = prompts[questionIndex];
- async function startMode(modeId) {
+ async function runMode(modeId, useProviderId, useModel) {
setSelectedMode(modeId);
setLoading(true);
setDrill(null);
@@ -71,7 +95,7 @@ export default function WordplayTrainer({ onBack, config }) {
setFeedback(null);
setResults([]);
- const generated = await generatePostDrill(modeId, { count: 5 }, providerId, model).catch(() => null);
+ const generated = await generatePostDrill(modeId, { count: 5 }, useProviderId, useModel).catch(() => null);
setLoading(false);
if (generated) {
setDrill(generated);
@@ -80,6 +104,50 @@ export default function WordplayTrainer({ onBack, config }) {
}
}
+ function startMode(modeId) {
+ // Default to cold when the status fetch hasn't resolved yet — never skip
+ // consent on an assumption the cache is already warm.
+ const isCold = cacheStatus?.[modeId]?.cold ?? true;
+ if (isCold && !primedModes.has(modeId)) {
+ setFillProviderId(config?.llmDrills?.providerId || '');
+ setFillModel(config?.llmDrills?.model || '');
+ setPendingMode(modeId);
+ return;
+ }
+ runMode(modeId, providerId, model);
+ }
+
+ // Both consent-modal resolutions dismiss the modal and mark the mode as
+ // primed (so it won't re-prompt this session) before diverging.
+ function closePendingMode() {
+ const modeId = pendingMode;
+ setPendingMode(null);
+ setPrimedModes(prev => new Set(prev).add(modeId));
+ return modeId;
+ }
+
+ function handleSkipFill() {
+ runMode(closePendingMode(), providerId, model);
+ }
+
+ function handleConfirmFill() {
+ const modeId = closePendingMode();
+ const chosenProviderId = fillProviderId || null;
+ const chosenModel = fillModel || null;
+ if (chosenProviderId !== providerId || chosenModel !== model) {
+ // Persist as the new default for scoring calls too, but don't gate the
+ // user-facing actions below on this round-trip — they already have the
+ // chosen provider/model as explicit params.
+ updatePostConfig({ llmDrills: { providerId: chosenProviderId, model: chosenModel } })
+ .then(updated => onConfigUpdate?.(updated))
+ .catch(() => {});
+ }
+ const providerLabel = providers.find(p => p.id === chosenProviderId)?.name || 'the default provider';
+ toast(`Filling ${modeId.replace(/-/g, ' ')} cache in the background using ${providerLabel}`);
+ fillPostDrillCache([modeId], chosenProviderId, chosenModel).catch(() => {});
+ runMode(modeId, chosenProviderId, chosenModel);
+ }
+
function handleBackToModes() {
setSelectedMode(null);
setDrill(null);
@@ -186,6 +254,20 @@ export default function WordplayTrainer({ onBack, config }) {
);
})}
</div>
+
+ <CacheFillConsentModal
+ pendingMode={pendingMode}
+ modeInfo={GAME_MODES.find(m => m.id === pendingMode)}
+ providers={providers}
+ fillProviderId={fillProviderId}
+ setFillProviderId={setFillProviderId}
+ fillModel={fillModel}
+ setFillModel={setFillModel}
+ fillModels={fillModels}
+ onCancel={() => setPendingMode(null)}
+ onSkip={handleSkipFill}
+ onConfirm={handleConfirmFill}
+ />
</div>
);
}
@@ -388,3 +470,55 @@ function ModeHeader({ modeInfo, onBack }) {
);
}
+// Cache for this mode is cold (never filled). PortOS never runs background
+// LLM calls without asking first — this is the ask. The user can pick a
+// provider/model and warm the cache, or skip it and just generate one drill
+// on demand (no background batch).
+function CacheFillConsentModal({
+ pendingMode, modeInfo, providers, fillProviderId, setFillProviderId,
+ fillModel, setFillModel, fillModels, onCancel, onSkip, onConfirm,
+}) {
+ return (
+ <Modal open={!!pendingMode} onClose={onCancel} size="sm" ariaLabel="Fill drill cache">
+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">
+ <div className="flex items-center gap-2">
+ <Sparkles size={18} className="text-port-accent-2" />
+ <h3 className="text-white font-medium">Warm up {modeInfo?.label || 'this'} drills?</h3>
+ </div>
+ <p className="text-sm text-gray-400">
+ This is the first time you're playing {modeInfo?.label || 'this mode'}. PortOS can use an AI
+ provider to pre-generate a batch of drills so future rounds load instantly. Pick a provider
+ and model, or skip and generate just one drill for this round.
+ </p>
+
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={fillProviderId}
+ selectedModel={fillModel}
+ availableModels={fillModels}
+ onProviderChange={setFillProviderId}
+ onModelChange={setFillModel}
+ emptyProviderOption="System Default"
+ emptyModelOption="Provider Default"
+ alwaysShowModel
+ />
+
+ <div className="flex gap-3 pt-1">
+ <button
+ onClick={onSkip}
+ className="flex-1 px-4 py-2 bg-port-card border border-port-border hover:border-port-accent text-white text-sm font-medium rounded-lg transition-colors"
+ >
+ Just Play Once
+ </button>
+ <button
+ onClick={onConfirm}
+ className="flex-1 px-4 py-2 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 text-sm font-medium rounded-lg transition-colors"
+ >
+ Fill Cache &amp; Play
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index b2704e733b..143c847e55 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -144,7 +144,7 @@ export default function PostTab({ tab = 'launcher', subtab }) {
/>
);
case 'wordplay':
- return <WordplayTrainer config={config} onBack={() => navigate('/post/launcher')} />;
+ return <WordplayTrainer config={config} onConfigUpdate={setConfig} onBack={() => navigate('/post/launcher')} />;
case 'morse':
return <MorseTrainer onBack={() => navigate('/post/launcher')} />;
case 'memory':
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index ac3c6770f7..ebafb1a2e3 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -193,6 +193,11 @@ export const scorePostLlmDrill = (type, drillData, responses, timeLimitMs, provi
method: 'POST',
body: JSON.stringify({ type, drillData, responses, timeLimitMs, ...(providerId && { providerId }), ...(model && { model }) })
});
+export const getPostDrillCacheStatus = () => request('/meatspace/post/drill-cache/status');
+export const fillPostDrillCache = (types, providerId, model) => request('/meatspace/post/drill-cache/fill', {
+ method: 'POST',
+ body: JSON.stringify({ ...(types && { types }), ...(providerId && { providerId }), ...(model && { model }) })
+});
// MeatSpace - POST Memory Builder
export const getMemoryItems = () => request('/meatspace/post/memory-items');
diff --git a/server/index.js b/server/index.js
index e097d6d14d..36f1e470c1 100644
--- a/server/index.js
+++ b/server/index.js
@@ -569,7 +569,8 @@ recoverStuckAutopilots().catch(err => console.error(`❌ Pipeline autopilot reco
startBrainScheduler();
// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
initBrainMemoryBridge();
-// Pre-fill POST drill cache in background
+// Load any on-disk POST drill cache into memory. Does NOT trigger LLM calls —
+// cache fill only happens on explicit user request (see meatspacePostRoutes.js).
initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: ${err.message}`));
// Initialize backup scheduler for daily data backups
startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 487f0d68e9..fdbcc92bff 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { CACHEABLE_TYPES } from '../services/meatspacePostDrillCache.js';
// =============================================================================
// POST (Power On Self Test) VALIDATION SCHEMAS
@@ -130,6 +131,13 @@ export const postLlmScoreRequestSchema = z.object({
model: z.string().optional()
});
+// Explicit, user-consented request to warm the wordplay drill cache
+export const postDrillCacheFillSchema = z.object({
+ types: z.array(z.enum(CACHEABLE_TYPES)).min(1).optional(),
+ providerId: z.string().optional(),
+ model: z.string().optional()
+});
+
// =============================================================================
// MEMORY BUILDER VALIDATION
// =============================================================================
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index 7e3a8ca8e6..867ffa9ba4 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -13,6 +13,7 @@ import {
postConfigUpdateSchema,
postDrillRequestSchema,
postLlmScoreRequestSchema,
+ postDrillCacheFillSchema,
memoryItemCreateSchema,
memoryItemUpdateSchema,
memoryPracticeSchema,
@@ -24,7 +25,7 @@ import {
import * as postService from '../services/meatspacePost.js';
import * as memoryService from '../services/meatspacePostMemory.js';
import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';
-import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';
+import { getCachedDrill, triggerReplenish, getCacheStats, requestCacheFill } from '../services/meatspacePostDrillCache.js';
import * as trainingService from '../services/meatspacePostTraining.js';
const router = Router();
@@ -115,7 +116,9 @@ router.post('/post/drill', asyncHandler(async (req, res) => {
if (!drill) {
throw new ServerError('Failed to generate LLM drill', { status: 500, code: 'LLM_DRILL_FAILED' });
}
- // Trigger background fill so next request is instant
+ // Top up the cache for next time — a no-op if the cache is currently cold
+ // (0 cached). Cold fill only happens via POST /post/drill-cache/fill,
+ // which requires the user to explicitly opt in and pick a provider/model.
triggerReplenish(data.type, data.providerId, data.model);
return res.json(drill);
}
@@ -149,6 +152,28 @@ router.post('/post/score-llm', asyncHandler(async (req, res) => {
res.json(result);
}));
+/**
+ * GET /api/meatspace/post/drill-cache/status
+ * Per-type cache counts for the wordplay drill cache, so the client can
+ * decide whether to prompt the user for a cache-fill (0 cached = cold).
+ */
+router.get('/post/drill-cache/status', asyncHandler(async (req, res) => {
+ res.json(getCacheStats());
+}));
+
+/**
+ * POST /api/meatspace/post/drill-cache/fill
+ * Explicit, user-initiated cache warm-up. This is the ONLY path that performs
+ * a cold fill (0 -> several cached drills per type) — the client must prompt
+ * the user and let them pick a provider/model before calling this, since it
+ * can issue several sequential LLM calls in the background.
+ */
+router.post('/post/drill-cache/fill', asyncHandler(async (req, res) => {
+ const data = validateRequest(postDrillCacheFillSchema, req.body);
+ const triggered = requestCacheFill(data.types, data.providerId, data.model);
+ res.json({ triggered });
+}));
+
// =============================================================================
// POST - Training Log
// =============================================================================
diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.js
index b9cca99473..5a6625602c 100644
--- a/server/services/meatspacePostDrillCache.js
+++ b/server/services/meatspacePostDrillCache.js
@@ -1,8 +1,11 @@
/**
* POST Drill Cache — Pre-generates wordplay drills so users don't wait.
*
- * On startup, fills cache to MIN_PER_TYPE. When a drill is consumed,
- * background replenishment kicks in. Cache persists to disk.
+ * On startup, only the on-disk cache is loaded — no LLM calls. A cold cache
+ * (0 cached) only fills via requestCacheFill(), which requires explicit user
+ * consent (see meatspacePostRoutes.js). Once a type has been warmed at least
+ * once, consuming a drill silently tops it back up in the background. Cache
+ * persists to disk. See "AI Provider Usage Policy" in CLAUDE.md.
*/
import { readFile } from 'fs/promises';
@@ -15,7 +18,7 @@ const MIN_PER_TYPE = 3;
const MAX_PER_TYPE = 10;
// Only cache LLM-generated drill types used in wordplay training
-const CACHEABLE_TYPES = [
+export const CACHEABLE_TYPES = [
'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist',
];
@@ -100,42 +103,63 @@ export function getCachedDrill(type) {
return result;
}
+// A type is "cold" when it has never been filled (0 cached). This is the one
+// place that defines cold vs. warm — triggerReplenish and getCacheStats both
+// read it, so a future change to the threshold (e.g. < MIN_PER_TYPE) can't
+// drift between the background-replenish guard and what the client is told.
+function isCacheCold(type) {
+ return !cache[type]?.length;
+}
+
/**
- * Trigger background replenishment after consuming a drill.
+ * Trigger background replenishment after consuming a drill. Only tops up a
+ * type that already has at least one cached drill — it does NOT perform the
+ * initial cold fill. Cold fill only happens via requestCacheFill(), which
+ * requires explicit user consent (see meatspacePostRoutes.js). Without this
+ * guard, the very first cache-miss after a fresh install would silently
+ * kick off a MAX_PER_TYPE-sized batch of LLM calls with no user awareness.
*/
export function triggerReplenish(type, providerId, model) {
if (!CACHEABLE_TYPES.includes(type)) return;
+ if (isCacheCold(type)) return;
replenishType(type, providerId, model);
debouncedSave();
}
/**
- * Get cache stats for debugging/status.
+ * Get cache stats for the drill-cache/status route: per-type count plus the
+ * same cold/warm classification triggerReplenish uses, so the client doesn't
+ * have to re-derive "cold" from a raw count.
*/
export function getCacheStats() {
const stats = {};
for (const type of CACHEABLE_TYPES) {
- stats[type] = cache[type]?.length || 0;
+ stats[type] = { count: cache[type]?.length || 0, cold: isCacheCold(type) };
}
return stats;
}
/**
- * Initialize cache: load from disk, start sequential background fill for low types.
+ * Explicitly requested cache fill — the only path allowed to perform a cold
+ * fill (0 -> MAX_PER_TYPE). Called from the drill-cache/fill route after the
+ * user has been prompted and picked a provider/model. See PortOS's
+ * no-cold-bootstrap-LLM-calls rule in CLAUDE.md.
+ */
+export function requestCacheFill(types, providerId, model) {
+ const requested = (types?.length ? types : CACHEABLE_TYPES).filter(t => CACHEABLE_TYPES.includes(t));
+ for (const type of requested) {
+ replenishType(type, providerId, model);
+ }
+ return requested;
+}
+
+/**
+ * Load the on-disk cache into memory at boot. Does NOT perform any LLM
+ * calls or start background fills — a fresh install boots with an empty
+ * cache and stays that way until the user opts in via requestCacheFill().
*/
-export async function initDrillCache(providerId, model) {
+export async function initDrillCache() {
await loadCache();
const stats = CACHEABLE_TYPES.map(t => `${t}:${cache[t]?.length || 0}`).join(' ');
console.log(`📦 POST drill cache loaded: ${stats}`);
-
- // Fill types sequentially (not in parallel) to avoid LLM API spam on startup
- const lowTypes = CACHEABLE_TYPES.filter(t => (cache[t]?.length || 0) < MIN_PER_TYPE);
- if (lowTypes.length > 0) {
- console.log(`📦 POST cache: queuing startup fill for ${lowTypes.length} types`);
- (async () => {
- for (const type of lowTypes) {
- await replenishType(type, providerId, model);
- }
- })().catch(err => console.error(`❌ POST drill cache startup fill failed: ${err.message}`));
- }
}