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

fix: address claude review — reachable narrative opt-in, word-boundary matching, flat empty-week trend (#2157)

Adam Eivy7016bd40aed3
diff --git a/client/src/components/insights/GoalScorecardTab.jsx b/client/src/components/insights/GoalScorecardTab.jsx
index c28e82e984..1fbdce0b9a 100644
--- a/client/src/components/insights/GoalScorecardTab.jsx
+++ b/client/src/components/insights/GoalScorecardTab.jsx
@@ -7,6 +7,8 @@ import {
getGoalScorecardRules,
saveGoalScorecardRules,
getGoalScorecardSettings,
+ updateGoalScorecardSettings,
+ getProviders,
} from '../../services/api';
import { timeAgo } from '../../utils/formatters';
@@ -117,22 +119,37 @@ function RulesEditor({ onClose }) {
export default function GoalScorecardTab() {
const [data, setData] = useState(null);
const [settings, setSettings] = useState(null);
+ const [providers, setProviders] = useState([]);
const [loading, setLoading] = useState(true);
const [computing, setComputing] = useState(false);
const [generating, setGenerating] = useState(false);
+ const [savingSettings, setSavingSettings] = useState(false);
const [showRules, setShowRules] = useState(false);
const load = useCallback(() => {
- Promise.allSettled([getGoalScorecard(), getGoalScorecardSettings()])
- .then(([sc, st]) => {
+ Promise.allSettled([getGoalScorecard(), getGoalScorecardSettings(), getProviders({ silent: true })])
+ .then(([sc, st, pr]) => {
setData(sc.status === 'fulfilled' ? sc.value : null);
setSettings(st.status === 'fulfilled' ? st.value : null);
+ const p = pr.status === 'fulfilled' ? pr.value : null;
+ setProviders(p?.providers || (Array.isArray(p) ? p : []));
})
.finally(() => setLoading(false));
}, []);
useEffect(() => { load(); }, [load]);
+ // Persist a scorecard settings change (enable toggle / provider pick) — the
+ // narrative opt-in. Optimistic local update, reverts on failure.
+ const saveSettings = (partial) => {
+ setSavingSettings(true);
+ setSettings((prev) => ({ ...prev, ...partial }));
+ updateGoalScorecardSettings(partial)
+ .then((res) => setSettings(res))
+ .catch(() => load())
+ .finally(() => setSavingSettings(false));
+ };
+
const handleCompute = () => {
setComputing(true);
computeGoalScorecard()
@@ -181,7 +198,9 @@ export default function GoalScorecardTab() {
const { totals, goals = [], trend = [], trendDirection } = data;
const alignedPct = Math.round((totals?.alignedShare ?? 0) * 100);
- const narrativeEnabled = Boolean(settings?.enabled && settings?.provider);
+ // Enabling is the opt-in; a specific provider is optional (server falls back
+ // to the active provider), matching the cross-domain narrative.
+ const narrativeEnabled = Boolean(settings?.enabled);
const topGoalHours = goals.find((g) => g.alignedSeconds > 0)?.alignedHours ?? 0;
return (
@@ -278,17 +297,44 @@ export default function GoalScorecardTab() {
{/* Optional LLM narrative */}
<div className="bg-port-card border border-port-border rounded-lg p-4">
- <div className="flex items-center justify-between mb-2">
+ <div className="flex flex-wrap items-center justify-between gap-2 mb-2">
<h3 className="text-sm font-semibold text-white flex items-center gap-2"><Sparkles size={14} className="text-port-accent" /> Narrative</h3>
- <button
- onClick={handleNarrative}
- disabled={generating || !narrativeEnabled || totals?.totalSeconds === 0}
- title={narrativeEnabled ? '' : 'Enable a provider in scorecard settings to generate a narrative'}
- className="flex items-center gap-2 px-3 py-1.5 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
- >
- <RefreshCw size={14} className={generating ? 'animate-spin' : ''} />
- {generating ? 'Generating…' : data.narrative ? 'Regenerate' : 'Generate'}
- </button>
+ <div className="flex items-center gap-3">
+ <label className="flex items-center gap-1.5 text-xs text-gray-400 cursor-pointer" htmlFor="scorecard-narrative-enabled">
+ <input
+ id="scorecard-narrative-enabled"
+ type="checkbox"
+ checked={narrativeEnabled}
+ disabled={savingSettings}
+ onChange={(e) => saveSettings({ enabled: e.target.checked })}
+ className="accent-port-accent"
+ />
+ AI narrative
+ </label>
+ {narrativeEnabled && (
+ <select
+ aria-label="Narrative provider"
+ value={settings?.provider || ''}
+ disabled={savingSettings}
+ onChange={(e) => saveSettings({ provider: e.target.value || null })}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200 focus:border-port-accent/60 focus:outline-none"
+ >
+ <option value="">Active provider</option>
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>{p.name || p.id}</option>
+ ))}
+ </select>
+ )}
+ <button
+ onClick={handleNarrative}
+ disabled={generating || !narrativeEnabled || totals?.totalSeconds === 0}
+ title={narrativeEnabled ? '' : 'Enable AI narrative to generate a summary'}
+ className="flex items-center gap-2 px-3 py-1.5 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ >
+ <RefreshCw size={14} className={generating ? 'animate-spin' : ''} />
+ {generating ? 'Generating…' : data.narrative ? 'Regenerate' : 'Generate'}
+ </button>
+ </div>
</div>
{data.narrative ? (
<div className="prose prose-sm prose-invert max-w-none">
@@ -303,7 +349,7 @@ export default function GoalScorecardTab() {
<p className="text-xs text-gray-500">
{narrativeEnabled
? 'Generate an optional plain-language summary of this week’s goal alignment. The numeric scorecard above is always AI-free.'
- : 'Optional AI narrative is off. Enable a provider in scorecard settings to summarize the week in plain language. The numeric scorecard is always AI-free.'}
+ : 'Optional AI narrative is off. Toggle “AI narrative” above to summarize the week in plain language. The numeric scorecard is always AI-free.'}
</p>
)}
</div>
diff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.js
index 983554a0b8..b1becff2e8 100644
--- a/server/services/goalScorecard.js
+++ b/server/services/goalScorecard.js
@@ -31,7 +31,7 @@ import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
import { localDayRangeUtc, localDayKey, listEvents } from './humanActivity.js';
import * as journal from './brainJournal.js';
import { buildMarkers } from '../lib/markedSection.js';
-import { getProviderById } from './providers.js';
+import { getProviderById, getActiveProvider } from './providers.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');
@@ -184,11 +184,15 @@ function eventText(event) {
export function eventGoalMatches(event, rules = []) {
if (!event) return [];
const text = eventText(event);
+ // Whole-word set for single-token keywords so a short tag/category can't
+ // substring-match unrelated text ("go" in "going", "art" in "start"). Phrase
+ // keywords (containing a space) still substring-match against the full text.
+ const words = new Set(text.split(/[^a-z0-9]+/).filter(Boolean));
const personIds = new Set((event.participants || []).map((p) => p?.personId).filter(Boolean).map(String));
const subcal = event?.metadata?.subcalendarId != null ? String(event.metadata.subcalendarId) : null;
const matched = [];
for (const rule of rules) {
- const byKeyword = rule.keywords.some((k) => k && text.includes(k));
+ const byKeyword = rule.keywords.some((k) => k && (k.includes(' ') ? text.includes(k) : words.has(k)));
const byPerson = rule.personIds.some((id) => personIds.has(String(id)));
const byCalendar = subcal != null && rule.subcalendarIds.some((id) => String(id) === subcal);
if (byKeyword || byPerson || byCalendar) matched.push(rule.id);
@@ -307,7 +311,9 @@ export function computeScorecard({ weekStart, events = [], rules = [], timezone
const currentShare = totalSeconds > 0 ? alignedSeconds / totalSeconds : 0;
const priorMean = priorShares.length ? priorShares.reduce((a, b) => a + b, 0) / priorShares.length : null;
let direction = 'flat';
- if (priorMean != null) {
+ // A zero-activity week has no aligned share to compare — a blank week isn't a
+ // "decline" in goal alignment, so leave it neutral rather than reporting 'down'.
+ if (priorMean != null && totalSeconds > 0) {
if (currentShare > priorMean + 0.05) direction = 'up';
else if (currentShare < priorMean - 0.05) direction = 'down';
}
@@ -520,9 +526,11 @@ export async function refreshScorecardNarrative(providerId, model) {
const settings = await getSettings();
const resolvedProviderId = providerId || settings.provider;
- if (!resolvedProviderId) return { available: false, reason: 'no_provider' };
-
- const provider = await getProviderById(resolvedProviderId).catch(() => null);
+ // Prefer an explicit/configured provider; fall back to the active provider
+ // (mirrors the cross-domain narrative) so "enabled" alone is enough to run.
+ const provider = resolvedProviderId
+ ? await getProviderById(resolvedProviderId).catch(() => null)
+ : await getActiveProvider().catch(() => null);
if (!provider || provider.enabled === false) return { available: false, reason: 'no_provider' };
const selectedModel = model || settings.model || provider.defaultModel;
diff --git a/server/services/goalScorecard.test.js b/server/services/goalScorecard.test.js
index 2ea0e61ea7..c3ce986b1e 100644
--- a/server/services/goalScorecard.test.js
+++ b/server/services/goalScorecard.test.js
@@ -151,6 +151,22 @@ describe('eventGoalMatches', () => {
expect(eventGoalMatches(ev({ title: 'random chatter' }), rules)).toEqual([]);
});
+ it('matches single-token keywords on whole words, not substrings', () => {
+ // A short tag "art" must NOT match "start"/"artisan" via substring.
+ const artRules = buildMappingRules([
+ { id: 'art', title: 'Studio', category: 'creative', status: 'active', tags: ['art'] },
+ ]);
+ expect(eventGoalMatches(ev({ title: 'start the artisan run' }), artRules)).toEqual([]);
+ expect(eventGoalMatches(ev({ title: 'made some art today' }), artRules)).toEqual(['art']);
+ });
+
+ it('still substring-matches multi-word phrase keywords', () => {
+ const phraseRules = buildMappingRules([
+ { id: 'pull', title: 'Fitness', category: 'health', status: 'active', tags: ['pull ups'] },
+ ]);
+ expect(eventGoalMatches(ev({ title: 'did pull ups at the gym' }), phraseRules)).toEqual(['pull']);
+ });
+
it('can match multiple goals at once (de-duplicated)', () => {
const out = eventGoalMatches(ev({ title: 'musical robot jam', summary: 'humanoid' }), rules);
expect(out.sort()).toEqual(['music', 'robot']);
@@ -262,6 +278,16 @@ describe('computeScorecard (rollup math)', () => {
expect(empty.totals.alignedShare).toBe(0);
expect(empty.goals.every((g) => g.alignedSeconds === 0)).toBe(true);
});
+
+ it('reports flat (not down) for a zero-activity week even after active prior weeks', () => {
+ const trend = [
+ { weekStart: '2026-06-22', alignedSeconds: 50, unalignedSeconds: 50, totalSeconds: 100 }, // 50%
+ { weekStart: '2026-06-29', alignedSeconds: 60, unalignedSeconds: 40, totalSeconds: 100 }, // 60%
+ { weekStart: '2026-07-06', alignedSeconds: 0, unalignedSeconds: 0, totalSeconds: 0 },
+ ];
+ const sc = computeScorecard({ weekStart: '2026-07-06', events: [], rules, timezone: UTC, trend });
+ expect(sc.trendDirection).toBe('flat');
+ });
});
describe('formatScorecardDigestLine', () => {