The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge main and bind ToolRegistry controllers (#8177)
Steven Enamakelea6b5337da59
diff --git a/.env.example b/.env.exampleindex da8c0fd733..c56f2cdf6a 100644--- a/.env.example+++ b/.env.example@@ -87,7 +87,7 @@ OPENHUMAN_CORE_BIN=# Set to 0 to block all side-effecting tool actions entirely.OPENHUMAN_MAX_ACTIONS_PER_HOUR=20# [optional] Default model to use-OPENHUMAN_MODEL=+OPENHUMAN_DEFAULT_MODEL=# [optional] Workspace directory (default: ~/.openhuman or ~/.openhuman-staging when OPENHUMAN_APP_ENV=staging)# Leave commented out to use the default. Setting to empty string is treated as unset.# OPENHUMAN_WORKSPACE=diff --git a/.gitignore b/.gitignoreindex 7159c17731..124cf904ff 100644--- a/.gitignore+++ b/.gitignore@@ -166,5 +166,10 @@ crates/openhuman-core/storage/*.dbcrates/openhuman-core/storage/*.db-walcrates/openhuman-core/storage/*.db-shm+# Local root-profile SQLite state is runtime data, never repository source.+/storage/storage.db+/storage/storage.db-shm+/storage/storage.db-wal+# Retired generated app schema snapshot; the runtime schema is registered in Rust./app/schema.jsondiff --git a/Cargo.lock b/Cargo.lockindex e00726f0e9..a6cb81f8ec 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5417,6 +5417,7 @@ dependencies = ["schemars","sentry","serde",+ "serde_ignored","serde_json","serde_path_to_error","sha2 0.10.9",@@ -5429,6 +5430,7 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyagents-hooks","tinyagents-live","tinyagents-orchestration",@@ -5537,6 +5539,7 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyagents-session","tinyagents-tasks","tinybus",@@ -5592,6 +5595,7 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyagents-hooks","tinyagents-session","tinybus",@@ -5610,6 +5614,7 @@ dependencies = ["url","uuid","wiremock",+ "zeroize",][[package]]@@ -5712,6 +5717,8 @@ dependencies = ["tinyinference-video","tinyinference-voice","tinyjevclient",+ "tinymemory-api",+ "tinymemory-integrations","tinytools","tinytools-jev","tokio",@@ -7568,6 +7575,16 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "serde_ignored"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798"+dependencies = [+ "serde",+ "serde_core",+]+[[package]]name = "serde_json"version = "1.0.151"@@ -8440,7 +8457,6 @@ dependencies = [name = "tinyagents-graph"version = "2.2.0"dependencies = [- "anyhow","async-trait","futures","serde",@@ -8463,7 +8479,6 @@ dependencies = ["base64 0.22.1","cap-std","chrono",- "chrono-tz","dirs 6.0.0","flate2","futures",@@ -8494,6 +8509,25 @@ dependencies = ["zip 2.4.2",]+[[package]]+name = "tinyagents-harness-tools"+version = "2.2.0"+dependencies = [+ "anyhow",+ "async-trait",+ "chrono",+ "chrono-tz",+ "serde",+ "serde_json",+ "tinyagents-harness",+ "tinyagents-orchestration",+ "tinyagents-tasks",+ "tinyinference-llm 0.4.1",+ "tinytools",+ "tokio",+ "tracing",+]+[[package]]name = "tinyagents-hooks"version = "2.2.0"@@ -8503,8 +8537,8 @@ dependencies = ["regex","serde","serde_json",- "tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyinference-llm 0.4.1","tinytools","tokio",@@ -8538,7 +8572,6 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",- "tinyagents-runtime","tinyagents-session","tinyagents-tasks","tinyinference-llm 0.4.1",diff --git a/app/src/components/settings/panels/SystemDiagnostics.doctor.test.tsx b/app/src/components/settings/panels/SystemDiagnostics.doctor.test.tsxnew file mode 100644index 0000000000..70c426384d--- /dev/null+++ b/app/src/components/settings/panels/SystemDiagnostics.doctor.test.tsx@@ -0,0 +1,92 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import SystemDiagnostics from './SystemDiagnostics';++const callCoreRpc = vi.fn();+vi.mock('../../../services/coreRpcClient', () => ({+ callCoreRpc: (...args: unknown[]) => callCoreRpc(...args),+}));++const report = {+ schema_version: 2,+ profile: 'desktop-default',+ config_source: 'profile',+ tier: 'connect',+ checks_run: ['config/file-integrity', 'runtime/core-ready'],+ checks_skipped: [],+ findings: [+ {+ check_id: 'config/file-integrity',+ severity: 'warn',+ message: 'The config file was recovered from its backup.',+ fix_hint: 'Review the backup and restore a valid config file.',+ duration_ms: 4,+ affects: ['settings.configuration'],+ },+ {+ check_id: 'runtime/core-ready',+ severity: 'pass',+ message: 'The core is ready.',+ fix_hint: 'No action required.',+ duration_ms: 1,+ affects: [],+ },+ ],+ summary: { pass: 1, info: 0, warn: 1, error: 0, skipped: 0 },+ ok: true,+};++function renderDiagnostics() {+ return render(+ <MemoryRouter>+ <SystemDiagnostics />+ </MemoryRouter>+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ callCoreRpc.mockResolvedValue({ result: report, logs: [] });+ vi.spyOn(window, 'confirm').mockReturnValue(true);+});++describe('<SystemDiagnostics /> doctor report', () => {+ it('renders v2 findings grouped by check category with the fix hint', async () => {+ renderDiagnostics();++ fireEvent.click(screen.getByRole('button', { name: 'Run doctor' }));++ await waitFor(() => {+ expect(callCoreRpc).toHaveBeenCalledWith(+ expect.objectContaining({ method: 'openhuman.doctor_report', params: { tier: 'connect' } })+ );+ });+ expect(await screen.findByText('config')).toBeInTheDocument();+ expect(screen.getByText('runtime')).toBeInTheDocument();+ expect(screen.getByText('The config file was recovered from its backup.')).toBeInTheDocument();+ expect(+ screen.getByText('Review the backup and restore a valid config file.')+ ).toBeInTheDocument();+ expect(screen.getByText('The core is ready.')).toBeInTheDocument();+ });++ it('requests the live tier only after the user confirms the token warning', async () => {+ vi.spyOn(window, 'confirm').mockReturnValue(false);+ renderDiagnostics();++ fireEvent.click(screen.getByRole('button', { name: 'Run live checks' }));+ expect(window.confirm).toHaveBeenCalled();+ expect(callCoreRpc).not.toHaveBeenCalled();++ vi.mocked(window.confirm).mockReturnValue(true);+ fireEvent.click(screen.getByRole('button', { name: 'Run live checks' }));++ await waitFor(() => {+ expect(callCoreRpc).toHaveBeenCalledWith(+ expect.objectContaining({ method: 'openhuman.doctor_report', params: { tier: 'live' } })+ );+ });+ });+});diff --git a/app/src/components/settings/panels/SystemDiagnostics.tsx b/app/src/components/settings/panels/SystemDiagnostics.tsxindex 63cc7f2786..9758844f07 100644--- a/app/src/components/settings/panels/SystemDiagnostics.tsx+++ b/app/src/components/settings/panels/SystemDiagnostics.tsx@@ -15,7 +15,15 @@ import { APP_ENVIRONMENT } from '../../../utils/config';// `safeInvoke` (aliased to `invoke`) turns the CEF synchronous IPC throw into a// rejected Promise so the `.catch(...)` handlers see a normal failure.import { safeInvoke as invoke, isTauri } from '../../../utils/tauriCommands/common';+import {+ type DoctorFinding,+ type DoctorReport,+ type DoctorSeverity,+ type DoctorTier,+ openhumanDoctorReport,+} from '../../../utils/tauriCommands/core';import Alert from '../../ui/Alert';+import Badge from '../../ui/Badge';import Button from '../../ui/Button';import Card from '../../ui/Card';import Field from '../../ui/Field';@@ -147,6 +155,114 @@ const RestartTourRow = () => {);};+type DoctorState =+ | { kind: 'idle' }+ | { kind: 'running' }+ | { kind: 'ready'; report: DoctorReport }+ | { kind: 'error' };++const severityBadge: Record<+ DoctorSeverity,+ 'success' | 'primary' | 'warning' | 'danger' | 'neutral'+> = { pass: 'success', info: 'primary', warn: 'warning', error: 'danger', skipped: 'neutral' };++function groupFindings(findings: DoctorFinding[]): [string, DoctorFinding[]][] {+ const groups = new Map<string, DoctorFinding[]>();+ for (const finding of findings) {+ // The v2 wire contract deliberately keeps check ids stable and carries no+ // display category. Their first path segment is the stable category key.+ const category = finding.check_id.split('/')[0] || finding.check_id;+ const group = groups.get(category) ?? [];+ group.push(finding);+ groups.set(category, group);+ }+ return Array.from(groups.entries());+}++const DoctorRow = () => {+ const { t } = useT();+ const [state, setState] = useState<DoctorState>({ kind: 'idle' });+ const textKey = 'devOptions.doctor';++ const run = async (tier: DoctorTier) => {+ if (tier === 'live' && !window.confirm(t(`${textKey}.liveWarning`))) return;+ setState({ kind: 'running' });+ try {+ const response = await openhumanDoctorReport(tier);+ setState({ kind: 'ready', report: response.result });+ } catch {+ // Core transport errors may include endpoint details; keep this surface+ // generic and never forward the raw error into analytics.+ setState({ kind: 'error' });+ }+ };++ const groups = state.kind === 'ready' ? groupFindings(state.report.findings) : [];++ return (+ <div className="space-y-3 p-4" data-testid="doctor-diagnostics">+ <div className="flex flex-wrap items-center gap-2">+ <Button+ variant="secondary"+ size="sm"+ analyticsId="settings-doctor-run"+ disabled={state.kind === 'running'}+ onClick={() => void run('connect')}>+ {state.kind === 'running' ? t('common.loading') : t(`${textKey}.run`)}+ </Button>+ <Button+ variant="secondary"+ size="sm"+ analyticsId="settings-doctor-run-live"+ disabled={state.kind === 'running'}+ onClick={() => void run('live')}>+ {t(`${textKey}.runLive`)}+ </Button>+ </div>++ <Alert variant="warning" density="compact" role={undefined}>+ <p>{t(`${textKey}.liveWarning`)}</p>+ </Alert>++ {state.kind === 'error' && (+ <Alert variant="destructive" density="compact" role="status" aria-live="polite">+ {t('misc.somethingWentWrong')}. {t('common.retry')}+ </Alert>+ )}++ {state.kind === 'ready' && (+ <div className="space-y-3" aria-live="polite">+ {groups.length === 0 && (+ <p className="text-sm text-content-muted">{t('common.noResults')}</p>+ )}+ {groups.map(([category, findings]) => (+ <section key={category} aria-label={category} className="space-y-2">+ <h4 className="text-sm font-semibold capitalize text-content">{category}</h4>+ <div className="space-y-2">+ {findings.map((finding, index) => (+ <div+ key={`${finding.check_id}:${finding.severity}:${index}`}+ className="rounded-lg border border-line-subtle p-3">+ <div className="flex flex-wrap items-start gap-2">+ <Badge variant={severityBadge[finding.severity]}>+ {t(`${textKey}.severity.${finding.severity}`)}+ </Badge>+ <span className="min-w-0 flex-1 text-sm text-content">{finding.message}</span>+ </div>+ <p className="mt-2 text-xs leading-relaxed text-content-muted">+ {finding.fix_hint}+ </p>+ </div>+ ))}+ </div>+ </section>+ ))}+ </div>+ )}+ </div>+ );+};+/** App logs, optional staging Sentry test, and the restart-tour action. */const SystemDiagnostics = () => {const { t } = useT();@@ -155,6 +271,7 @@ const SystemDiagnostics = () => {return (<><Card title={t('devOptions.titleDiagnostics')} data-testid="about-diagnostics">+ <DoctorRow /><LogsFolderRow /><RestartTourRow /></Card>diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex 59297a9d95..dc0c12eb83 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -654,6 +654,15 @@ const messages: TranslationMap = {'invites.title': 'الدعوات','invites.noInvites': 'لا توجد دعوات معلقة','devOptions.titleDiagnostics': 'المطور والتشخيص',+ 'devOptions.doctor.run': 'تشغيل الفحص',+ 'devOptions.doctor.runLive': 'تشغيل الفحوصات المباشرة',+ 'devOptions.doctor.liveWarning':+ 'قد تستهلك الفحوصات المباشرة رموزًا عند اختبار استدعاءات النماذج أو التضمين. هل تريد المتابعة؟',+ 'devOptions.doctor.severity.pass': 'ناجح',+ 'devOptions.doctor.severity.info': 'معلومات',+ 'devOptions.doctor.severity.warn': 'تحذير',+ 'devOptions.doctor.severity.error': 'خطأ',+ 'devOptions.doctor.severity.skipped': 'تم التخطي','devOptions.diagnostics': 'التشخيص','devOptions.toolPolicyDiagnosticsDesc':'قوائم جرد المواد، ووضع السياسات، والقوائم المسموح بها بx0xx، والوحدات الأخيرة',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 13eaeb8a15..2104b4e52e 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -664,6 +664,15 @@ const messages: TranslationMap = {'invites.title': 'আমন্ত্রণ','invites.noInvites': 'কোনো মুলতুবি আমন্ত্রণ নেই','devOptions.titleDiagnostics': 'ডেভেলপার ও ডায়াগনস্টিক্স',+ 'devOptions.doctor.run': 'ডায়াগনস্টিক চালান',+ 'devOptions.doctor.runLive': 'লাইভ পরীক্ষা চালান',+ 'devOptions.doctor.liveWarning':+ 'লাইভ পরীক্ষায় মডেল বা এমবেডিং কলের জন্য টোকেন খরচ হতে পারে। চালিয়ে যাবেন?',+ 'devOptions.doctor.severity.pass': 'সফল',+ 'devOptions.doctor.severity.info': 'তথ্য',+ 'devOptions.doctor.severity.warn': 'সতর্কতা',+ 'devOptions.doctor.severity.error': 'ত্রুটি',+ 'devOptions.doctor.severity.skipped': 'এড়িয়ে যাওয়া','devOptions.diagnostics': 'ডায়াগনস্টিক্স','devOptions.toolPolicyDiagnosticsDesc': 'টুল- মেকআপ, নীতি পোস্ট, xqxqxs, এবং সম্প্রতি ব্যবহৃত','devOptions.toolPolicyDiagnostics.loading': 'লোড করা হচ্ছে...',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex b309a37f9d..942a4d1d10 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -690,6 +690,15 @@ const messages: TranslationMap = {'invites.title': 'Lädt ein','invites.noInvites': 'Keine ausstehenden Einladungen','devOptions.titleDiagnostics': 'Entwickler & Diagnose',+ 'devOptions.doctor.run': 'Diagnose ausführen',+ 'devOptions.doctor.runLive': 'Live-Prüfungen ausführen',+ 'devOptions.doctor.liveWarning':+ 'Live-Prüfungen können bei Modell- oder Embedding-Aufrufen Tokens verbrauchen. Fortfahren?',+ 'devOptions.doctor.severity.pass': 'Bestanden',+ 'devOptions.doctor.severity.info': 'Info',+ 'devOptions.doctor.severity.warn': 'Warnung',+ 'devOptions.doctor.severity.error': 'Fehler',+ 'devOptions.doctor.severity.skipped': 'Übersprungen','devOptions.diagnostics': 'Diagnose','devOptions.toolPolicyDiagnosticsDesc':'Werkzeuginventar, Richtlinienstatus, MCP-Zulassungslisten und aktuelle Sperren',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex cf080574a8..dc04006ea1 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -734,6 +734,15 @@ const en: TranslationMap = {// Developer Options / Developer & Diagnostics'devOptions.titleDiagnostics': 'Developer & Diagnostics',+ 'devOptions.doctor.run': 'Run doctor',+ 'devOptions.doctor.runLive': 'Run live checks',+ 'devOptions.doctor.liveWarning':+ 'Live checks may spend tokens on model or embedding calls. Continue?',+ 'devOptions.doctor.severity.pass': 'Pass',+ 'devOptions.doctor.severity.info': 'Info',+ 'devOptions.doctor.severity.warn': 'Warning',+ 'devOptions.doctor.severity.error': 'Error',+ 'devOptions.doctor.severity.skipped': 'Skipped','devOptions.diagnostics': 'Diagnostics','devOptions.toolPolicyDiagnosticsDesc':'Tool inventory, policy posture, MCP allowlists, and recent blocks',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex f92bf6aa62..debe0ef973 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -687,6 +687,15 @@ const messages: TranslationMap = {'invites.title': 'Invitaciones','invites.noInvites': 'Sin invitaciones pendientes','devOptions.titleDiagnostics': 'Desarrollador y Diagnóstico',+ 'devOptions.doctor.run': 'Ejecutar diagnóstico',+ 'devOptions.doctor.runLive': 'Ejecutar comprobaciones en vivo',+ 'devOptions.doctor.liveWarning':+ 'Las comprobaciones en vivo pueden consumir tokens al probar modelos o embeddings. ¿Continuar?',+ 'devOptions.doctor.severity.pass': 'Correcto',+ 'devOptions.doctor.severity.info': 'Información',+ 'devOptions.doctor.severity.warn': 'Advertencia',+ 'devOptions.doctor.severity.error': 'Error',+ 'devOptions.doctor.severity.skipped': 'Omitido','devOptions.diagnostics': 'Diagnósticos','devOptions.toolPolicyDiagnosticsDesc':'Inventario de herramientas, postura política, listas permitidas de MCP y bloqueos recientes',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex 9084acede9..b658f3c2ed 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -690,6 +690,15 @@ const messages: TranslationMap = {'invites.title': 'Invitations','invites.noInvites': 'Aucune invitation en attente','devOptions.titleDiagnostics': 'Développeur et Diagnostics',+ 'devOptions.doctor.run': 'Lancer le diagnostic',+ 'devOptions.doctor.runLive': 'Lancer les vérifications en direct',+ 'devOptions.doctor.liveWarning':+ 'Les vérifications en direct peuvent consommer des jetons lors des appels de modèle ou d’intégration. Continuer ?',+ 'devOptions.doctor.severity.pass': 'Réussi',+ 'devOptions.doctor.severity.info': 'Info',+ 'devOptions.doctor.severity.warn': 'Avertissement',+ 'devOptions.doctor.severity.error': 'Erreur',+ 'devOptions.doctor.severity.skipped': 'Ignoré','devOptions.diagnostics': 'Diagnostic','devOptions.toolPolicyDiagnosticsDesc':'Inventaire des outils, posture de la politique, listes autorisées MCP et blocages récents',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex d3a488df59..c971054801 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -669,6 +669,15 @@ const messages: TranslationMap = {'invites.title': 'इनवाइट्स','invites.noInvites': 'कोई पेंडिंग इनवाइट नहीं','devOptions.titleDiagnostics': 'डेवलपर और डायग्नोस्टिक्स',+ 'devOptions.doctor.run': 'डायग्नोस्टिक्स चलाएँ',+ 'devOptions.doctor.runLive': 'लाइव जाँच चलाएँ',+ 'devOptions.doctor.liveWarning':+ 'लाइव जाँच मॉडल या एम्बेडिंग कॉल पर टोकन खर्च कर सकती है। जारी रखें?',+ 'devOptions.doctor.severity.pass': 'पास',+ 'devOptions.doctor.severity.info': 'जानकारी',+ 'devOptions.doctor.severity.warn': 'चेतावनी',+ 'devOptions.doctor.severity.error': 'त्रुटि',+ 'devOptions.doctor.severity.skipped': 'छोड़ा गया','devOptions.diagnostics': 'डायग्नोस्टिक्स','devOptions.toolPolicyDiagnosticsDesc':'उपकरण सूची, नीति मुद्रा, MCP अनुमतिसूची, और हाल के ब्लॉक',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 7c10258b7b..3f73261b6d 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -678,6 +678,15 @@ const messages: TranslationMap = {'invites.title': 'Undangan','invites.noInvites': 'Tidak ada undangan tertunda','devOptions.titleDiagnostics': 'Developer & Diagnostik',+ 'devOptions.doctor.run': 'Jalankan diagnosis',+ 'devOptions.doctor.runLive': 'Jalankan pemeriksaan langsung',+ 'devOptions.doctor.liveWarning':+ 'Pemeriksaan langsung dapat menggunakan token untuk panggilan model atau embedding. Lanjutkan?',+ 'devOptions.doctor.severity.pass': 'Lulus',+ 'devOptions.doctor.severity.info': 'Info',+ 'devOptions.doctor.severity.warn': 'Peringatan',+ 'devOptions.doctor.severity.error': 'Error',+ 'devOptions.doctor.severity.skipped': 'Dilewati','devOptions.diagnostics': 'Diagnostik','devOptions.toolPolicyDiagnosticsDesc':'Alat inventaris, postur kebijakan, allowzes MCP, dan blok terbaru',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 38550ad293..befa4fd757 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -685,6 +685,15 @@ const messages: TranslationMap = {'invites.title': 'Inviti','invites.noInvites': 'Nessun invito in sospeso','devOptions.titleDiagnostics': 'Sviluppatore e Diagnostica',+ 'devOptions.doctor.run': 'Esegui diagnostica',+ 'devOptions.doctor.runLive': 'Esegui controlli dal vivo',+ 'devOptions.doctor.liveWarning':+ 'I controlli dal vivo possono consumare token per le chiamate a modelli o embedding. Continuare?',+ 'devOptions.doctor.severity.pass': 'Superato',+ 'devOptions.doctor.severity.info': 'Info',+ 'devOptions.doctor.severity.warn': 'Avviso',+ 'devOptions.doctor.severity.error': 'Errore',+ 'devOptions.doctor.severity.skipped': 'Saltato','devOptions.diagnostics': 'Diagnostica','devOptions.toolPolicyDiagnosticsDesc':'Inventario degli strumenti, posizione della politica, allowlist MCP e blocchi recenti',diff --git a/app/src/lib/i18n/ja.ts b/app/src/lib/i18n/ja.tsindex 01a37383db..061594efbe 100644--- a/app/src/lib/i18n/ja.ts+++ b/app/src/lib/i18n/ja.ts@@ -713,6 +713,15 @@ const messages: TranslationMap = {// Developer Options / Developer & Diagnostics'devOptions.titleDiagnostics': '開発者向けと診断',+ 'devOptions.doctor.run': '診断を実行',+ 'devOptions.doctor.runLive': 'ライブチェックを実行',+ 'devOptions.doctor.liveWarning':+ 'ライブチェックではモデルまたは埋め込みの呼び出しにトークンを消費する場合があります。続行しますか?',+ 'devOptions.doctor.severity.pass': '合格',+ 'devOptions.doctor.severity.info': '情報',+ 'devOptions.doctor.severity.warn': '警告',+ 'devOptions.doctor.severity.error': 'エラー',+ 'devOptions.doctor.severity.skipped': 'スキップ','devOptions.diagnostics': '診断','devOptions.toolPolicyDiagnosticsDesc':'ツールインベントリ、ポリシー状態、MCP 許可リスト、および最近のブロック',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex c6c20fc62f..5bb13f9ba3 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -660,6 +660,15 @@ const messages: TranslationMap = {'invites.title': '초대','invites.noInvites': '대기 중인 초대가 없습니다','devOptions.titleDiagnostics': '개발자 및 진단',+ 'devOptions.doctor.run': '진단 실행',+ 'devOptions.doctor.runLive': '라이브 검사 실행',+ 'devOptions.doctor.liveWarning':+ '라이브 검사는 모델 또는 임베딩 호출에 토큰을 사용할 수 있습니다. 계속할까요?',+ 'devOptions.doctor.severity.pass': '통과',+ 'devOptions.doctor.severity.info': '정보',+ 'devOptions.doctor.severity.warn': '경고',+ 'devOptions.doctor.severity.error': '오류',+ 'devOptions.doctor.severity.skipped': '건너뜀','devOptions.diagnostics': '진단','devOptions.toolPolicyDiagnosticsDesc': '도구 인벤토리, 정책 상태, MCP 허용 목록 및 최근 차단','devOptions.toolPolicyDiagnostics.loading': '로딩 중…',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 360f4e900b..7e5720c49a 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -681,6 +681,15 @@ const messages: TranslationMap = {'invites.title': 'Zaproszenia','invites.noInvites': 'Brak oczekujących zaproszeń','devOptions.titleDiagnostics': 'Deweloper i Diagnostyka',+ 'devOptions.doctor.run': 'Uruchom diagnostykę',+ 'devOptions.doctor.runLive': 'Uruchom testy na żywo',+ 'devOptions.doctor.liveWarning':+ 'Testy na żywo mogą zużywać tokeny podczas wywołań modeli lub embeddingów. Kontynuować?',+ 'devOptions.doctor.severity.pass': 'Zaliczone',+ 'devOptions.doctor.severity.info': 'Informacje',+ 'devOptions.doctor.severity.warn': 'Ostrzeżenie',+ 'devOptions.doctor.severity.error': 'Błąd',+ 'devOptions.doctor.severity.skipped': 'Pominięto','devOptions.diagnostics': 'Diagnostyka','devOptions.toolPolicyDiagnosticsDesc':'Inwentarz narzędzi, postawa polityki, listy dozwolonych MCP i ostatnie blokady',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex 11d525f33e..ca25a79957 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -681,6 +681,15 @@ const messages: TranslationMap = {'invites.title': 'Convites','invites.noInvites': 'Nenhum convite pendente','devOptions.titleDiagnostics': 'Desenvolvedor e Diagnósticos',+ 'devOptions.doctor.run': 'Executar diagnóstico',+ 'devOptions.doctor.runLive': 'Executar verificações ao vivo',+ 'devOptions.doctor.liveWarning':+ 'As verificações ao vivo podem consumir tokens em chamadas de modelo ou embeddings. Continuar?',+ 'devOptions.doctor.severity.pass': 'Aprovado',+ 'devOptions.doctor.severity.info': 'Informações',+ 'devOptions.doctor.severity.warn': 'Aviso',+ 'devOptions.doctor.severity.error': 'Erro',+ 'devOptions.doctor.severity.skipped': 'Ignorado','devOptions.diagnostics': 'Diagnósticos','devOptions.toolPolicyDiagnosticsDesc':'Inventário de ferramentas, postura de políticas, listas de permissão MCP e bloqueios recentes',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 93a649a9cf..b1cfe2df39 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -677,6 +677,15 @@ const messages: TranslationMap = {'invites.title': 'Приглашения','invites.noInvites': 'Активных приглашений нет','devOptions.titleDiagnostics': 'Разработчик и Диагностика',+ 'devOptions.doctor.run': 'Запустить диагностику',+ 'devOptions.doctor.runLive': 'Запустить проверки в реальном времени',+ 'devOptions.doctor.liveWarning':+ 'Проверки в реальном времени могут расходовать токены при вызовах модели или эмбеддингов. Продолжить?',+ 'devOptions.doctor.severity.pass': 'Пройдено',+ 'devOptions.doctor.severity.info': 'Информация',+ 'devOptions.doctor.severity.warn': 'Предупреждение',+ 'devOptions.doctor.severity.error': 'Ошибка',+ 'devOptions.doctor.severity.skipped': 'Пропущено','devOptions.diagnostics': 'Диагностика','devOptions.toolPolicyDiagnosticsDesc':'Инвентаризация инструментов, положение политики, белые списки MCP и недавние блокировки',diff --git a/app/src/lib/i18n/tr.ts b/app/src/lib/i18n/tr.tsindex f5a6aee375..27de491ef8 100644--- a/app/src/lib/i18n/tr.ts+++ b/app/src/lib/i18n/tr.ts@@ -630,6 +630,15 @@ const messages: TranslationMap = {'invites.redeemPlaceholder': 'Davet kodu','invites.redeemSubmit': 'Kullan','devOptions.titleDiagnostics': 'Geliştirici ve tanılama',+ 'devOptions.doctor.run': 'Tanılamayı çalıştır',+ 'devOptions.doctor.runLive': 'Canlı denetimleri çalıştır',+ 'devOptions.doctor.liveWarning':+ 'Canlı denetimler model veya gömme çağrılarında token harcayabilir. Devam edilsin mi?',+ 'devOptions.doctor.severity.pass': 'Başarılı',+ 'devOptions.doctor.severity.info': 'Bilgi',+ 'devOptions.doctor.severity.warn': 'Uyarı',+ 'devOptions.doctor.severity.error': 'Hata',+ 'devOptions.doctor.severity.skipped': 'Atlandı','devOptions.diagnostics': 'Tanılama','devOptions.toolPolicyDiagnosticsDesc':'Araç envanteri, politika durumu, MCP izin listeleri ve son engellemeler',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 526067d11a..9fcfc18856 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -626,6 +626,14 @@ const messages: TranslationMap = {'invites.title': '邀请','invites.noInvites': '暂无待处理的邀请','devOptions.titleDiagnostics': '开发者与诊断',+ 'devOptions.doctor.run': '运行诊断',+ 'devOptions.doctor.runLive': '运行实时检查',+ 'devOptions.doctor.liveWarning': '实时检查可能会在模型或嵌入调用中消耗令牌。是否继续?',+ 'devOptions.doctor.severity.pass': '通过',+ 'devOptions.doctor.severity.info': '信息',+ 'devOptions.doctor.severity.warn': '警告',+ 'devOptions.doctor.severity.error': '错误',+ 'devOptions.doctor.severity.skipped': '已跳过','devOptions.diagnostics': '诊断','devOptions.toolPolicyDiagnosticsDesc': '工具清单、策略态势、MCP 允许列表和近期拦截','devOptions.toolPolicyDiagnostics.loading': '加载中…',diff --git a/app/src/utils/tauriCommands/core.ts b/app/src/utils/tauriCommands/core.tsindex ae9d4a05ff..3c54dcf521 100644--- a/app/src/utils/tauriCommands/core.ts+++ b/app/src/utils/tauriCommands/core.ts@@ -18,12 +18,33 @@ export interface CoreUpdateStatus {update_available: boolean;}-export type DoctorSeverity = 'Ok' | 'Warn' | 'Error';+export type DoctorTier = 'static' | 'connect' | 'live';+export type DoctorSeverity = 'pass' | 'info' | 'warn' | 'error' | 'skipped';export type ModelProbeOutcome = 'Ok' | 'Skipped' | 'AuthOrAccess' | 'Error';+export interface DoctorFinding {+ check_id: string;+ severity: DoctorSeverity;+ message: string;+ fix_hint: string;+ config_path?: string;+ value_source?: 'cli' | 'env' | 'dotenv' | 'file' | 'default';+ duration_ms: number;+ affects: string[];+}+export interface DoctorReport {- items: { severity: DoctorSeverity; category: string; message: string }[];- summary: { ok: number; warnings: number; errors: number };+ schema_version: 2;+ profile: string | null;+ config_source: 'profile' | 'tenant';+ profile_layout_version?: 1 | 2;+ config_resolution_source?: string;+ tier: DoctorTier;+ checks_run: string[];+ checks_skipped: string[];+ findings: DoctorFinding[];+ summary: { pass: number; info: number; warn: number; error: number; skipped: number };+ ok: boolean;}export interface ModelProbeReport {@@ -305,8 +326,13 @@ export async function setOnboardingCompleted(value: boolean): Promise<boolean> {return false;}-export async function openhumanDoctorReport(): Promise<CommandResponse<DoctorReport>> {- return await callCoreRpc<CommandResponse<DoctorReport>>({ method: 'openhuman.doctor_report' });+export async function openhumanDoctorReport(+ tier: DoctorTier = 'connect'+): Promise<CommandResponse<DoctorReport>> {+ return await callCoreRpc<CommandResponse<DoctorReport>>({+ method: 'openhuman.doctor_report',+ params: { tier },+ });}export async function openhumanDoctorModels(diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex bb835b62d9..2e6f3d3191 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -3707,6 +3707,7 @@ dependencies = ["schemars 1.2.2","sentry","serde",+ "serde_ignored","serde_json","serde_path_to_error","sha2 0.10.9",@@ -3719,6 +3720,7 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyagents-hooks","tinyagents-live","tinyagents-orchestration",@@ -3844,6 +3846,7 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyagents-hooks","tinyagents-session","tinybus",@@ -3923,6 +3926,8 @@ dependencies = ["tinyinference-video","tinyinference-voice","tinyjevclient",+ "tinymemory-api",+ "tinymemory-integrations","tinytools","tinytools-jev","tokio",@@ -5298,6 +5303,16 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "serde_ignored"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798"+dependencies = [+ "serde",+ "serde_core",+]+[[package]]name = "serde_json"version = "1.0.151"@@ -6415,7 +6430,6 @@ dependencies = [name = "tinyagents-graph"version = "2.2.0"dependencies = [- "anyhow","async-trait","futures","serde",@@ -6438,7 +6452,6 @@ dependencies = ["base64 0.22.1","cap-std","chrono",- "chrono-tz","dirs","flate2","futures",@@ -6469,6 +6482,25 @@ dependencies = ["zip 2.4.2",]+[[package]]+name = "tinyagents-harness-tools"+version = "2.2.0"+dependencies = [+ "anyhow",+ "async-trait",+ "chrono",+ "chrono-tz",+ "serde",+ "serde_json",+ "tinyagents-harness",+ "tinyagents-orchestration",+ "tinyagents-tasks",+ "tinyinference-llm",+ "tinytools",+ "tokio",+ "tracing",+]+[[package]]name = "tinyagents-hooks"version = "2.2.0"@@ -6478,8 +6510,8 @@ dependencies = ["regex","serde","serde_json",- "tinyagents-graph","tinyagents-harness",+ "tinyagents-harness-tools","tinyinference-llm","tinytools","tokio",@@ -6513,7 +6545,6 @@ dependencies = ["tinyagents-definition","tinyagents-graph","tinyagents-harness",- "tinyagents-runtime","tinyagents-session","tinyagents-tasks","tinyinference-llm",diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex 5fc40f30d3..429877a59f 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -453,6 +453,7 @@ sha2 = "0.10"tar = "0.4"tinyagents-graph = { path = "../../vendor/tinyagents/crates/tinyagents-graph", features = ["sqlite", "storage-drivers"] }tinyagents-harness = { path = "../../vendor/tinyagents/crates/tinyagents-harness", features = ["sqlite", "multimodal"] }+tinyagents-harness-tools = { path = "../../vendor/tinyagents/crates/tinyagents-harness-tools", default-features = false, features = ["goals"] }tinyagents-definition = { path = "../../vendor/tinyagents/crates/tinyagents-definition" }tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session" }tinydocs-bus = { path = "../../vendor/tinydocs/crates/tinydocs-bus" }@@ -540,6 +541,10 @@ linked-modules = ["modules", "dep:openhuman-modules-linked"][lints.rust]unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage)'] }+[[test]]+name = "doctor_e2e"+path = "../../tests/doctor_e2e.rs"+[[test]]name = "embeddings_opt_out"path = "../../tests/embeddings_opt_out.rs"diff --git a/crates/openhuman-cli/src/doctor/args.rs b/crates/openhuman-cli/src/doctor/args.rsnew file mode 100644index 0000000000..1ee2c9e3e7--- /dev/null+++ b/crates/openhuman-cli/src/doctor/args.rs@@ -0,0 +1,83 @@+use serde_json::{json, Value};++/// Parsed options for the host-owned doctor command.+pub(super) struct DoctorArgs {+ pub(super) json: bool,+ pub(super) lint: bool,+ pub(super) severity_min: String,+ pub(super) tier: String,+ pub(super) only: Vec<String>,+ pub(super) skip: Vec<String>,+ pub(super) profile: Option<String>,+}++impl DoctorArgs {+ /// Parameters accepted by `openhuman.doctor_report`.+ pub(super) fn rpc_params(&self) -> Value {+ json!({+ "tier": self.tier,+ "only": self.only,+ "skip": self.skip,+ "profile": self.profile+ })+ }+}++pub(super) fn parse_args(args: &[String]) -> Result<DoctorArgs, String> {+ let mut options = DoctorArgs {+ json: false,+ lint: false,+ severity_min: "error".into(),+ tier: "connect".into(),+ only: Vec::new(),+ skip: Vec::new(),+ profile: None,+ };++ let mut index = 0;+ while index < args.len() {+ match args[index].as_str() {+ "--json" => options.json = true,+ "--lint" => options.lint = true,+ "--live" => options.tier = "live".into(),+ "--severity-min" => {+ let value = argument_value(args, index, "--severity-min")?;+ if !matches!(value, "info" | "warn" | "error") {+ return Err(+ "invalid value for --severity-min: expected info, warn, or error"+ .to_owned(),+ );+ }+ options.severity_min = value.into();+ index += 1;+ }+ "--only" => {+ options+ .only+ .push(argument_value(args, index, "--only")?.into());+ index += 1;+ }+ "--skip" => {+ options+ .skip+ .push(argument_value(args, index, "--skip")?.into());+ index += 1;+ }+ "--profile" => {+ options.profile = Some(argument_value(args, index, "--profile")?.into());+ index += 1;+ }+ flag => return Err(format!("unknown doctor argument: {flag}")),+ }+ index += 1;+ }++ Ok(options)+}++fn argument_value<'a>(args: &'a [String], index: usize, flag: &str) -> Result<&'a str, String> {+ args.get(index + 1)+ .filter(|value| !value.starts_with('-') && !value.trim().is_empty())+ .map(String::as_str)+ .ok_or_else(|| format!("missing value for {flag}"))+}diff --git a/crates/openhuman-cli/src/doctor/args_tests.rs b/crates/openhuman-cli/src/doctor/args_tests.rsnew file mode 100644index 0000000000..a80c1ba393--- /dev/null+++ b/crates/openhuman-cli/src/doctor/args_tests.rs@@ -0,0 +1,183 @@+use serde_json::{json, Value};++use super::args::{parse_args, DoctorArgs};+use super::is_doctor_command;+use super::runner::exit_code;++fn args(values: &[&str]) -> DoctorArgs {+ let values = values+ .iter()+ .map(|value| (*value).to_owned())+ .collect::<Vec<_>>();+ parse_args(&values).expect("valid doctor arguments")+}++fn report(findings: Value) -> Value {+ json!({+ "schema_version": 2,+ "profile": null,+ "config_source": "profile",+ "tier": "connect",+ "checks_run": [],+ "checks_skipped": [],+ "findings": findings,+ "summary": { "pass": 0, "info": 0, "warn": 0, "error": 0, "skipped": 0 },+ "ok": true+ })+}++#[test]+fn defaults_to_connect_tier_and_error_lint_threshold() {+ let options = args(&[]);++ assert_eq!(options.tier, "connect");+ assert_eq!(options.severity_min, "error");+ assert!(!options.json);+ assert!(!options.lint);+ assert!(options.only.is_empty());+ assert!(options.skip.is_empty());+ assert!(options.profile.is_none());+}++#[test]+fn invalid_severity_and_unknown_flags_are_parse_errors() {+ let invalid_severity = ["--severity-min", "pass"].map(str::to_owned);+ let unknown_flag = ["--force"].map(str::to_owned);++ assert!(parse_args(&invalid_severity).is_err());+ assert!(parse_args(&unknown_flag).is_err());+}++#[test]+fn lint_defaults_to_error_threshold() {+ let options = args(&["--lint"]);+ let warnings = report(json!([{+ "check_id": "config/provenance",+ "severity": "warn",+ "message": "The setting came from an implicit source.",+ "fix_hint": "Set the intended source explicitly.",+ "duration_ms": 1,+ "affects": []+ }]));++ assert_eq!(exit_code(&options, Ok(&warnings)), 0);+}++#[test]+fn lint_error_exits_one() {+ let options = args(&["--lint"]);+ let errors = report(json!([{+ "check_id": "config/file-integrity",+ "severity": "error",+ "message": "The config file is invalid.",+ "fix_hint": "Repair the config file.",+ "duration_ms": 1,+ "affects": []+ }]));++ assert_eq!(exit_code(&options, Ok(&errors)), 1);+}++#[test]+fn lint_warning_exits_one_when_warn_is_the_minimum() {+ let options = args(&["--lint", "--severity-min", "warn"]);+ let warnings = report(json!([{+ "check_id": "config/provenance",+ "severity": "warn",+ "message": "The setting came from an implicit source.",+ "fix_hint": "Set the intended source explicitly.",+ "duration_ms": 1,+ "affects": []+ }]));++ assert_eq!(exit_code(&options, Ok(&warnings)), 1);+}++#[test]+fn lint_json_still_uses_the_requested_severity_threshold() {+ let options = args(&["--lint", "--json", "--severity-min", "warn"]);+ let warnings = report(json!([{+ "check_id": "config/provenance",+ "severity": "warn",+ "message": "The setting came from an implicit source.",+ "fix_hint": "Set the intended source explicitly.",+ "duration_ms": 1,+ "affects": []+ }]));++ assert_eq!(exit_code(&options, Ok(&warnings)), 1);+}++#[test]+fn runtime_failure_exits_two_before_a_report_exists() {+ let options = args(&["--lint"]);++ assert_eq!(exit_code(&options, Err(())), 2);+}++#[test]+fn unknown_only_selector_error_finding_fails_lint() {+ let options = args(&["--lint", "--only", "unknown/check"]);+ let selection_error = report(json!([{+ "check_id": "doctor/selection",+ "severity": "error",+ "message": "A requested check id is not registered.",+ "fix_hint": "Use a registered exact check id.",+ "duration_ms": 0,+ "affects": []+ }]));++ assert_eq!(exit_code(&options, Ok(&selection_error)), 1);+}++#[test]+fn json_without_lint_is_advisory_even_for_errors() {+ let options = args(&["--json"]);+ let errors = report(json!([{+ "check_id": "config/file-integrity",+ "severity": "error",+ "message": "The config file is invalid.",+ "fix_hint": "Repair the config file.",+ "duration_ms": 1,+ "affects": []+ }]));++ assert_eq!(exit_code(&options, Ok(&errors)), 0);+}++#[test]+fn live_profile_and_repeatable_selectors_map_to_rpc_options() {+ let options = args(&[+ "--live",+ "--profile",+ "desktop-default",+ "--only",+ "config/provenance",+ "--only",+ "workspace/layout",+ "--skip",+ "config/provenance",+ ]);++ assert_eq!(options.tier, "live");+ assert_eq!(options.profile.as_deref(), Some("desktop-default"));+ assert_eq!(options.only, ["config/provenance", "workspace/layout"]);+ assert_eq!(options.skip, ["config/provenance"]);+ assert_eq!(+ options.rpc_params(),+ json!({+ "tier": "live",+ "profile": "desktop-default",+ "only": ["config/provenance", "workspace/layout"],+ "skip": ["config/provenance"]+ })+ );+}++#[test]+fn legacy_doctor_namespace_commands_stay_with_the_core_dispatcher() {+ for command in ["report", "models"] {+ let invocation = vec!["doctor".to_owned(), command.to_owned()];+ assert!(!is_doctor_command(&invocation));+ }+}diff --git a/crates/openhuman-cli/src/doctor/invoke_tests.rs b/crates/openhuman-cli/src/doctor/invoke_tests.rsnew file mode 100644index 0000000000..0c70b7bd98--- /dev/null+++ b/crates/openhuman-cli/src/doctor/invoke_tests.rs@@ -0,0 +1,28 @@+use serde_json::json;++use super::runner::doctor_report_body;++#[test]+fn invoke_outcome_is_unwrapped_to_the_snake_case_report_body() {+ let invoke_result = json!({+ "result": {+ "schema_version": 2,+ "findings": [],+ "summary": { "pass": 0, "info": 0, "warn": 0, "error": 0, "skipped": 0 },+ "ok": true+ },+ "logs": ["doctor report generated"]+ });++ let report = doctor_report_body(&invoke_result).expect("report result is present");++ assert_eq!(report["schema_version"], 2);+ assert!(report.get("result").is_none());+}++#[test]+fn missing_invoke_result_is_a_runtime_failure() {+ let invoke_result = json!({ "logs": [] });++ assert!(doctor_report_body(&invoke_result).is_err());+}diff --git a/crates/openhuman-cli/src/doctor/mod.rs b/crates/openhuman-cli/src/doctor/mod.rsnew file mode 100644index 0000000000..1b91e4c8cc--- /dev/null+++ b/crates/openhuman-cli/src/doctor/mod.rs@@ -0,0 +1,26 @@+mod args;+mod render;+mod runner;++pub(crate) use runner::run;++/// Whether the top-level `doctor` invocation belongs to the v2 host command.+///+/// `doctor report` and `doctor models` remain owned by the legacy core+/// namespace dispatcher so their raw JSON behavior does not change.+pub(super) fn is_doctor_command(args: &[String]) -> bool {+ args.first().map(String::as_str) == Some("doctor")+ && !matches!(args.get(1).map(String::as_str), Some("report" | "models"))+}++#[cfg(test)]+#[path = "args_tests.rs"]+mod args_tests;++#[cfg(test)]+#[path = "invoke_tests.rs"]+mod invoke_tests;++#[cfg(test)]+#[path = "render_tests.rs"]+mod render_tests;diff --git a/crates/openhuman-cli/src/doctor/render.rs b/crates/openhuman-cli/src/doctor/render.rsnew file mode 100644index 0000000000..7973952a28--- /dev/null+++ b/crates/openhuman-cli/src/doctor/render.rs@@ -0,0 +1,123 @@+use serde_json::Value;++use super::args::DoctorArgs;++#[cfg(test)]+pub(super) fn render_table(report: &Value) -> String {+ render(report, None)+}++pub(super) fn render_table_for_args(report: &Value, options: &DoctorArgs) -> String {+ let minimum = options.lint.then_some(options.severity_min.as_str());+ render(report, minimum)+}++fn render(report: &Value, minimum: Option<&str>) -> String {+ let findings = report+ .get("findings")+ .and_then(Value::as_array)+ .map(Vec::as_slice)+ .unwrap_or_default();+ let mut groups: Vec<(String, Vec<&Value>)> = Vec::new();++ for finding in findings {+ let severity = finding+ .get("severity")+ .and_then(Value::as_str)+ .unwrap_or("info");+ if minimum.is_some_and(|minimum| !meets_threshold(severity, minimum)) {+ continue;+ }+ let id = finding+ .get("check_id")+ .and_then(Value::as_str)+ .unwrap_or("unknown/check");+ let category = id.split_once('/').map_or("other", |(area, _)| area);+ let index = groups+ .iter()+ .position(|(existing, _)| existing == category)+ .unwrap_or_else(|| {+ groups.push((category.to_owned(), Vec::new()));+ groups.len() - 1+ });+ groups[index].1.push(finding);+ }++ let mut output = String::new();+ render_profile_header(report, &mut output);+ for (category, findings) in groups {+ output.push_str(&category);+ output.push_str(":\n");+ for finding in findings {+ let severity = finding+ .get("severity")+ .and_then(Value::as_str)+ .unwrap_or("info");+ let id = finding+ .get("check_id")+ .and_then(Value::as_str)+ .unwrap_or("unknown/check");+ let message = finding+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or("No message was provided.");+ let fix_hint = finding+ .get("fix_hint")+ .and_then(Value::as_str)+ .unwrap_or("Review this check and rerun doctor.");+ output.push_str(&format!(+ " [{severity}] {id} {message}\n fix: {fix_hint}\n"+ ));+ }+ }++ let empty_summary = Value::Null;+ let summary = report.get("summary").unwrap_or(&empty_summary);+ output.push_str(&format!(+ "Summary: pass {}, info {}, warn {}, error {}, skipped {}\n",+ count(summary, "pass"),+ count(summary, "info"),+ count(summary, "warn"),+ count(summary, "error"),+ count(summary, "skipped"),+ ));+ output+}++fn render_profile_header(report: &Value, output: &mut String) {+ let profile = report.get("profile").and_then(Value::as_str);+ let source = report+ .get("config_resolution_source")+ .and_then(Value::as_str);+ let layout = report.get("profile_layout_version").and_then(Value::as_u64);+ if profile.is_none() && source.is_none() && layout.is_none() {+ return;+ }++ output.push_str("Profile: ");+ output.push_str(profile.unwrap_or("(none)"));+ if let Some(layout) = layout {+ output.push_str(&format!(" | layout v{layout}"));+ }+ if let Some(source) = source {+ output.push_str(&format!(" | config source: {source}"));+ }+ output.push('\n');+}++fn count(summary: &Value, severity: &str) -> u64 {+ summary.get(severity).and_then(Value::as_u64).unwrap_or(0)+}++fn meets_threshold(severity: &str, minimum: &str) -> bool {+ severity_rank(severity) >= severity_rank(minimum) && severity_rank(severity) > 0+}++fn severity_rank(severity: &str) -> u8 {+ match severity {+ "info" => 1,+ "warn" => 2,+ "error" => 3,+ _ => 0,+ }+}diff --git a/crates/openhuman-cli/src/doctor/render_tests.rs b/crates/openhuman-cli/src/doctor/render_tests.rsnew file mode 100644index 0000000000..356cf87c8e--- /dev/null+++ b/crates/openhuman-cli/src/doctor/render_tests.rs@@ -0,0 +1,68 @@+use serde_json::json;++use super::render::render_table;++#[test]+fn table_groups_by_check_category_and_renders_fix_hints() {+ let report = json!({+ "findings": [+ {+ "check_id": "config/provenance",+ "severity": "warn",+ "message": "The setting came from an implicit source.",+ "fix_hint": "Set the intended source explicitly.",+ "duration_ms": 1,+ "affects": []+ },+ {+ "check_id": "workspace/layout",+ "severity": "pass",+ "message": "The workspace layout is valid.",+ "fix_hint": "No action required.",+ "duration_ms": 1,+ "affects": []+ },+ {+ "check_id": "config/file-integrity",+ "severity": "error",+ "message": "The config file is invalid.",+ "fix_hint": "Repair the config file.",+ "duration_ms": 1,+ "affects": []+ }+ ],+ "summary": { "pass": 1, "info": 0, "warn": 1, "error": 1, "skipped": 0 },+ "ok": false+ });++ let rendered = render_table(&report);++ assert!(rendered.contains("config"));+ assert!(rendered.contains("workspace"));+ assert!(rendered.contains("[warn] config/provenance The setting came from an implicit source."));+ assert!(rendered.contains("[error] config/file-integrity The config file is invalid."));+ assert!(rendered.contains(" fix: Set the intended source explicitly."));+ assert!(rendered.contains(" fix: Repair the config file."));+ assert!(rendered.contains("Summary:"));+ let first_config = rendered.find("config/provenance").unwrap();+ let second_config = rendered.find("config/file-integrity").unwrap();+ let workspace = rendered.find("workspace/layout").unwrap();+ assert!(first_config < second_config && second_config < workspace);+}++#[test]+fn table_header_renders_report_profile_provenance_without_inference() {+ let report = json!({+ "profile": "desktop-default",+ "profile_layout_version": 2,+ "config_resolution_source": "active_user.toml",+ "findings": [],+ "summary": { "pass": 0, "info": 0, "warn": 0, "error": 0, "skipped": 0 },+ "ok": true+ });++ let rendered = render_table(&report);++ assert!(rendered+ .starts_with("Profile: desktop-default | layout v2 | config source: active_user.toml\n"));+}diff --git a/crates/openhuman-cli/src/doctor/runner.rs b/crates/openhuman-cli/src/doctor/runner.rsnew file mode 100644index 0000000000..df90170765--- /dev/null+++ b/crates/openhuman-cli/src/doctor/runner.rs@@ -0,0 +1,105 @@+use serde_json::Value;++use super::args::DoctorArgs;++pub(super) fn doctor_report_body(invoke_result: &Value) -> Result<&Value, String> {+ invoke_result+ .get("result")+ .filter(|result| result.is_object())+ .ok_or_else(|| "doctor RPC response did not include a report".into())+}++pub(super) fn exit_code(options: &DoctorArgs, report: Result<&Value, ()>) -> u8 {+ let Ok(report) = report else {+ return 2;+ };+ if !options.lint {+ return 0;+ }++ let minimum = severity_rank(&options.severity_min);+ let has_finding_at_threshold = report+ .get("findings")+ .and_then(Value::as_array)+ .is_some_and(|findings| {+ findings.iter().any(|finding| {+ let severity = finding+ .get("severity")+ .and_then(Value::as_str)+ .unwrap_or("");+ let rank = severity_rank(severity);+ rank > 0 && rank >= minimum+ })+ });+ u8::from(has_finding_at_threshold)+}++fn severity_rank(severity: &str) -> u8 {+ match severity {+ "info" => 1,+ "warn" => 2,+ "error" => 3,+ _ => 0,+ }+}++pub(crate) fn run(args: &[String]) -> u8 {+ let options = match super::args::parse_args(args) {+ Ok(options) => options,+ Err(error) => {+ eprintln!("doctor: {error}");+ return 2;+ }+ };++ let tokio = match openhuman_rpc::embed::process::tokio_runtime() {+ Ok(runtime) => runtime,+ Err(_) => {+ print_runtime_failure(options.json);+ return 2;+ }+ };+ let report = tokio.block_on(invoke_report(&options));+ drop(tokio);++ match report {+ Ok(report) => {+ if options.json {+ println!(+ "{}",+ serde_json::to_string_pretty(&report).unwrap_or_default()+ );+ } else {+ print!(+ "{}",+ super::render::render_table_for_args(&report, &options)+ );+ }+ exit_code(&options, Ok(&report))+ }+ Err(()) => {+ print_runtime_failure(options.json);+ exit_code(&options, Err(()))+ }+ }+}++async fn invoke_report(options: &DoctorArgs) -> Result<Value, ()> {+ let runtime = openhuman_rpc::host::doctor_runtime(options.profile.as_deref())+ .await+ .map_err(|_| ())?;+ let invoke_result = runtime+ .core_runtime()+ .invoke("openhuman.doctor_report", options.rpc_params())+ .await+ .map_err(|_| ())?;+ doctor_report_body(&invoke_result).cloned().map_err(|_| ())+}++fn print_runtime_failure(json: bool) {+ if json {+ println!("{{\"ok\":false}}");+ } else {+ eprintln!("doctor could not produce a report");+ }+}diff --git a/crates/openhuman-cli/src/main.rs b/crates/openhuman-cli/src/main.rsindex 810fc276c0..4f8b468c41 100644--- a/crates/openhuman-cli/src/main.rs+++ b/crates/openhuman-cli/src/main.rs@@ -1,16 +1,14 @@//! The `openhuman-core` binary.//!-//! A host like the desktop app and the TUI: it depends on `openhuman-rpc`-//! alone and boots through the shared host entry-//! [`openhuman_rpc::host::cli`], which connects the TinyHumans backend,-//! registers the server launcher and the `http_host` controllers, and runs-//! the core's command-line dispatcher. This file only owns what is specific-//! to the process: SIGPIPE, the early `.env`, and (with `crash-reporting`)-//! the Sentry client, built from embed's shared `before_send` chain.+//! The binary depends on `openhuman-rpc` alone. The doctor command is handled+//! in this CLI host before the generic namespace dispatcher; other commands+//! continue through [`openhuman_rpc::host::cli`]. This file owns process-level+//! details: SIGPIPE, the early `.env`, and (with `crash-reporting`) the shared+//! Sentry client.use openhuman_rpc::embed::process;-fn main() {+fn main() -> std::process::ExitCode {restore_default_sigpipe();// Load `.env` before Sentry so a DSN defined only in the dotenv file is@@ -33,9 +31,16 @@ fn main() {let _sentry_guard = init_sentry();let args: Vec<String> = std::env::args().skip(1).collect();- if let Err(err) = openhuman_rpc::host::cli(&args) {- eprintln!("{err}");- std::process::exit(1);+ if doctor::is_doctor_command(&args) {+ return std::process::ExitCode::from(doctor::run(&args[1..]));+ }++ match openhuman_rpc::host::cli(&args) {+ Ok(()) => std::process::ExitCode::SUCCESS,+ Err(err) => {+ eprintln!("{err}");+ std::process::ExitCode::from(1)+ }}}@@ -80,3 +85,5 @@ fn init_sentry() -> process::sentry::sdk::ClientInitGuard {#[cfg(all(test, feature = "crash-reporting"))]#[path = "main_tests.rs"]mod tests;++mod doctor;diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex a086ed9548..75347fdf81 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -104,7 +104,12 @@ tinyagents-hooks = { workspace = true, features = ["goals"] }tinyagents-harness = { path = "../../vendor/tinyagents/crates/tinyagents-harness", features = ["sqlite","multimodal",- "builtin-tools",+] }+tinyagents-harness-tools = { path = "../../vendor/tinyagents/crates/tinyagents-harness-tools", default-features = false, features = [+ "goals",+ "skills",+ "subagents",+ "todos",] }tinybox-bus = { path = "../../vendor/tinybox/crates/tinybox-bus", features = ["storage"] }tiny-artifacts = { path = "../../vendor/tiny-artifacts/crates/tiny-artifacts" }@@ -233,6 +238,7 @@ tinyskills-drivers = { path = "../../vendor/tinyskills/crates/tinyskills-driversserde = { version = "1", features = ["derive"] }serde_json = "1"serde_path_to_error = "0.1"+serde_ignored = "0.1"# (Removed `html2md` dep. dhat-rs profiling on real Gmail inboxes# showed `html2md::walk` and `html2md::tables::handle` allocating# ~894 MB peak heap on a 10 KB HTML input from Otter.ai-style emails@@ -336,7 +342,7 @@ aho-corasick = "1.1"walkdir = "2"hostname = "0.4.2"rustls = { version = "0.23", default-features = false, features = ["ring"] }-sysinfo = { version = "0.33", default-features = false, features = ["system"] }+sysinfo = { version = "0.33", default-features = false, features = ["system", "disk"] }# HTTP server framework for the domain-owned routes (`/v1`, dictation, the MCP# HTTP transport). Exclusive to the default-ON `http-server`# feature (#5048); the JSON-RPC server that mounts them lives indiff --git a/crates/openhuman-core/src/agent/README.md b/crates/openhuman-core/src/agent/README.mdindex 593499d85e..e5dc32d4b9 100644--- a/crates/openhuman-core/src/agent/README.md+++ b/crates/openhuman-core/src/agent/README.md@@ -297,7 +297,7 @@ Delegation and coordination:| `subagent_host/` | Runs a child agent: definition, model and tool narrowing, prompt, checkpoints, progress ([README](subagent_host/README.md)) || `orchestration/` | Spawn/steer/wait tools, teams, command center, workflow runs, worktrees, background delivery ([README](orchestration/README.md)) || `triage/` | Classifies `TriggerEnvelope`s and escalates ([README](triage/README.md)) |-| `goals/` | Host adapters around `tinyagents_graph::goals` and the `goal_*` tools ([README](goals/README.md)) |+| `goals/` | Host adapters around `tinyagents_harness_tools::goals` and the `goal_*` tools ([README](goals/README.md)) || `todos/` | Session-scoped todo list over the TinyAgents todo store ([README](todos/README.md)) || [`../plan_review/`](../plan_review/) | `request_plan_review` gate that parks a web-chat turn until the user decides || [`tools.rs`](./tools.rs), `tools/` | Loop control tools: `delegate`, `plan_exit`, `todo`, `run_workflow`/`await_workflow` (with `skills`) ([README](tools/README.md)) |diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rsindex 3874c4d366..7ad8a59b5b 100644--- a/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs+++ b/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs@@ -46,8 +46,9 @@ async fn turn_routes_a_bare_packed_tool_call_through_use_skill() {]));let ran = Arc::new(Mutex::new(None));let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(RecordingPackedTool(ran.clone()))];- crate::tools::toolpacks::append_pack_tools(&mut tools);-+ // The public registry helper only returns its tool vector. The session+ // builder must replace the canonical proxy with a session-owned handle.+ let _pack_registry_handle = crate::tools::toolpacks::append_pack_tools(&mut tools);let (mut agent, _tmp) = build_agent_with(provider, tools, Box::new(NativeDialect));assert!(!agent@@ -131,7 +132,7 @@ async fn turn_does_not_route_a_bare_call_the_session_would_refuse() {]));let ran = Arc::new(Mutex::new(false));let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(WritePackedTool(ran.clone()))];- crate::tools::toolpacks::append_pack_tools(&mut tools);+ let _pack_registry_handle = crate::tools::toolpacks::append_pack_tools(&mut tools);// The builder's default event channel is `internal`; cap it at read-only.let config = AgentConfig {channel_permissions: std::collections::HashMap::from([(diff --git a/crates/openhuman-core/src/agent/goals/mod.rs b/crates/openhuman-core/src/agent/goals/mod.rsindex 43e1ee379a..274facbe16 100644--- a/crates/openhuman-core/src/agent/goals/mod.rs+++ b/crates/openhuman-core/src/agent/goals/mod.rs@@ -1,4 +1,4 @@-//! Thin OpenHuman host adapters for [`tinyagents_graph::goals`].+//! Thin OpenHuman host adapters for [`tinyagents_harness_tools::goals`].//!//! Tinyagents owns the goal types, lifecycle, persistence, prompt rendering,//! graph continuation, and native harness tools. This module contains the@@ -9,7 +9,7 @@pub mod runtime;pub mod tools;-use tinyagents_graph::goals::ThreadGoal;+use tinyagents_harness_tools::goals::ThreadGoal;pub use tools::goal_tools;/// Serialize a [`ThreadGoal`] for the `goal` field on `ThreadGoalUpdated` /diff --git a/crates/openhuman-core/src/agent/goals/runtime.rs b/crates/openhuman-core/src/agent/goals/runtime.rsindex f2a2e2ce69..13106702fd 100644--- a/crates/openhuman-core/src/agent/goals/runtime.rs+++ b/crates/openhuman-core/src/agent/goals/runtime.rs@@ -10,9 +10,10 @@//! persistence and completed-turn accounting.use std::path::Path;+use std::time::Duration;-use tinyagents_graph::goals::budget as crate_budget;-use tinyagents_graph::goals::{ThreadGoal, ThreadGoalStatus};+use tinyagents_harness_tools::goals::budget as crate_budget;+use tinyagents_harness_tools::goals::{ThreadGoal, ThreadGoalStatus};use crate::core::bus::BUS;use crate::core::events::DomainEvent;@@ -21,7 +22,7 @@ use crate::core::events::DomainEvent;pub async fn load_for_thread(workspace_dir: &Path, thread_id: Option<&str>) -> Option<ThreadGoal> {let thread_id = normalized_thread(thread_id)?;let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::get(&store, &thread_id)+ match tinyagents_harness_tools::goals::store::get(&store, &thread_id).await.map_err(|e| e.to_string()){@@ -41,7 +42,7 @@ pub async fn resume_for_thread() -> Option<Option<ThreadGoal>> {let thread_id = normalized_thread(thread_id)?;let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::resume(&store, &thread_id)+ match tinyagents_harness_tools::goals::store::resume(&store, &thread_id).await.map_err(|e| e.to_string()){@@ -77,7 +78,7 @@ pub async fn complete_for_thread(workspace_dir: &Path, thread_id: Option<&str>)return;};let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::complete(&store, &thread_id)+ match tinyagents_harness_tools::goals::store::complete(&store, &thread_id).await.map_err(|e| e.to_string()){@@ -109,7 +110,7 @@ pub async fn clear_for_thread(workspace_dir: &Path, thread_id: Option<&str>) {return;};let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::clear(&store, &thread_id)+ match tinyagents_harness_tools::goals::store::clear(&store, &thread_id).await.map_err(|e| e.to_string()){@@ -134,7 +135,7 @@ fn turn_tokens(input: u64, output: u64) -> u64 {/// Account a finished turn's usage against an explicit thread's goal.////// The accounting rules are the crate's-/// ([`crate_budget::account_turn`](tinyagents_graph::goals::account_turn)):+/// ([`crate_budget::account_turn`](tinyagents_harness_tools::goals::account_turn)):/// only **active** goals are charged, so a paused/complete/budget-limited goal/// doesn't accrue usage from incidental chat. OpenHuman runs no autonomous/// goal continuation, so every accounted turn is user-initiated.@@ -154,7 +155,7 @@ pub async fn account_turn_against_goal(return;};let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- let prev = match tinyagents_graph::goals::store::get(&store, &thread_id)+ let prev = match tinyagents_harness_tools::goals::store::get(&store, &thread_id).await.map_err(|e| e.to_string()){@@ -168,7 +169,9 @@ pub async fn account_turn_against_goal(let prev_status = prev.status;let prev_tokens_used = prev.tokens_used;- match crate_budget::account_turn(&store, &thread_id, input, output, secs, true).await {+ match crate_budget::account_turn(&store, &thread_id, input, output, Duration::from_secs(secs))+ .await+ {Ok(Some(updated)) => {tracing::debug!(thread_id = %thread_id,diff --git a/crates/openhuman-core/src/agent/goals/runtime_tests.rs b/crates/openhuman-core/src/agent/goals/runtime_tests.rsindex b931b43fe2..fdeb27eb8f 100644--- a/crates/openhuman-core/src/agent/goals/runtime_tests.rs+++ b/crates/openhuman-core/src/agent/goals/runtime_tests.rs@@ -3,7 +3,7 @@ use super::*;async fn account_turn_charges_active_goal_and_trips_budget() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-acct","obj",@@ -12,7 +12,7 @@ async fn account_turn_charges_active_goal_and_trips_budget() {.await.unwrap();account_turn_against_goal(&dir, Some("t-acct"), 80, 40, 3).await; // 120 >= 100- let g = tinyagents_graph::goals::store::get(+ let g = tinyagents_harness_tools::goals::store::get(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-acct",)@@ -26,7 +26,7 @@ async fn account_turn_charges_active_goal_and_trips_budget() {async fn account_turn_skips_non_active_goal() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-paused","obj",@@ -34,14 +34,14 @@ async fn account_turn_skips_non_active_goal() {).await.unwrap();- tinyagents_graph::goals::store::pause(+ tinyagents_harness_tools::goals::store::pause(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-paused",).await.unwrap();account_turn_against_goal(&dir, Some("t-paused"), 500, 500, 1).await;- let g = tinyagents_graph::goals::store::get(+ let g = tinyagents_harness_tools::goals::store::get(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-paused",)@@ -57,7 +57,7 @@ async fn complete_for_thread_settles_active_goal() {// later turn stops re-injecting its `[active_goal]` block (#1725).let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-complete","obj",@@ -66,7 +66,7 @@ async fn complete_for_thread_settles_active_goal() {.await.unwrap();complete_for_thread(&dir, Some("t-complete")).await;- let g = tinyagents_graph::goals::store::get(+ let g = tinyagents_harness_tools::goals::store::get(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-complete",)@@ -90,7 +90,7 @@ async fn clear_for_thread_removes_the_goal_row() {// injects no goal block at all — the strongest anti-leak guarantee.let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-clear","obj",@@ -99,7 +99,7 @@ async fn clear_for_thread_removes_the_goal_row() {.await.unwrap();clear_for_thread(&dir, Some("t-clear")).await;- let g = tinyagents_graph::goals::store::get(+ let g = tinyagents_harness_tools::goals::store::get(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-clear",)@@ -119,7 +119,7 @@ async fn complete_and_clear_are_safe_without_a_goal_or_thread() {let dir = tmp.path().to_path_buf();complete_for_thread(&dir, Some("t-empty")).await;clear_for_thread(&dir, Some("t-empty")).await;- assert!(tinyagents_graph::goals::store::get(+ assert!(tinyagents_harness_tools::goals::store::get(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"t-empty")@@ -130,39 +130,3 @@ async fn complete_and_clear_are_safe_without_a_goal_or_thread() {complete_for_thread(&dir, None).await;clear_for_thread(&dir, None).await;}--#[tokio::test]-async fn account_turn_clears_suppression_without_losing_usage() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- let goal = tinyagents_graph::goals::store::set(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-suppressed",- "obj",- Some(1000),- )- .await- .unwrap();- tinyagents_graph::goals::store::set_continuation_suppressed_if(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-suppressed",- &goal.goal_id,- true,- )- .await- .unwrap();-- account_turn_against_goal(&dir, Some("t-suppressed"), 80, 40, 3).await;-- let updated = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-suppressed",- )- .await- .unwrap()- .unwrap();- assert_eq!(updated.goal_id, goal.goal_id);- assert!(!updated.continuation_suppressed);- assert_eq!(updated.tokens_used, 120);- assert_eq!(updated.time_used_seconds, 3);-}diff --git a/crates/openhuman-core/src/agent/goals/tools.rs b/crates/openhuman-core/src/agent/goals/tools.rsindex a1662808a7..a5308d2f2a 100644--- a/crates/openhuman-core/src/agent/goals/tools.rs+++ b/crates/openhuman-core/src/agent/goals/tools.rs@@ -1,7 +1,7 @@//! Host wiring for tinyagents' model-facing goal controls.//!//! `goal_get` / `goal_set` / `goal_complete` are owned by-//! [`tinyagents_graph::goals`] (`GoalTool`); ownership stays asymmetric+//! [`tinyagents_harness_tools::goals`] (`GoalTool`); ownership stays asymmetric//! (pause / resume / budget-limit are system-driven and have no model tool).//! This module only supplies what is OpenHuman's: the workspace-backed goal//! store and the `ThreadGoalUpdated` domain event the UI chip listens to.@@ -9,40 +9,50 @@use std::path::Path;use std::sync::Arc;-use tinyagents_graph::goals::{GoalTool, GoalToolKind, GoalUpdateHook};+use tinyagents_harness_tools::goals::{GoalObserver, GoalStore, GoalTool, GoalToolKind};use tinytools::Tool;use super::goal_to_value;-use tinyagents_graph::goals::ThreadGoal;+use tinyagents_harness_tools::goals::ThreadGoal;/// The model-facing goal tools for `workspace_dir`, each publishing/// `DomainEvent::ThreadGoalUpdated` after a write.pub fn goal_tools(workspace_dir: &Path) -> Vec<Box<dyn Tool>> {- let goal_store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- let hook: GoalUpdateHook = Arc::new(publish_goal_updated);+ let backing_store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;+ let goal_store = Arc::new(GoalStore::with_observer(+ backing_store,+ Arc::new(OpenHumanGoalObserver),+ ));GoalToolKind::MODEL_FACING.into_iter()- .map(|kind| {- Box::new(GoalTool::new(kind, goal_store.clone()).with_update_hook(hook.clone()))- as Box<dyn Tool>- })+ .map(|kind| Box::new(GoalTool::new(kind, goal_store.clone())) as Box<dyn Tool>).collect()}-/// Emit the live-update event so the UI chip refreshes immediately.-fn publish_goal_updated(goal: &ThreadGoal) {- tracing::debug!(- thread_id = %goal.thread_id,- goal_id = %goal.goal_id,- status = goal.status.as_str(),- "[thread_goals] tool wrote goal, publishing ThreadGoalUpdated"- );- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ThreadGoalUpdated {- thread_id: goal.thread_id.clone(),- goal_id: goal.goal_id.clone(),- status: goal.status.as_str().to_string(),- goal: Some(goal_to_value(goal)),- });+/// Emit live-update events so the UI chip refreshes after goal tool writes.+struct OpenHumanGoalObserver;++impl GoalObserver for OpenHumanGoalObserver {+ fn on_updated(&self, goal: &ThreadGoal) {+ tracing::debug!(+ thread_id = %goal.thread_id,+ goal_id = %goal.goal_id,+ status = goal.status.as_str(),+ "[thread_goals] tool wrote goal, publishing ThreadGoalUpdated"+ );+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ThreadGoalUpdated {+ thread_id: goal.thread_id.clone(),+ goal_id: goal.goal_id.clone(),+ status: goal.status.as_str().to_string(),+ goal: Some(goal_to_value(goal)),+ });+ }++ fn on_cleared(&self, thread_id: &str) {+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ThreadGoalCleared {+ thread_id: thread_id.to_string(),+ });+ }}#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/goals/tools_tests.rs b/crates/openhuman-core/src/agent/goals/tools_tests.rsindex 7188a585cc..eb1024e547 100644--- a/crates/openhuman-core/src/agent/goals/tools_tests.rs+++ b/crates/openhuman-core/src/agent/goals/tools_tests.rs@@ -40,7 +40,7 @@ async fn set_persists_to_the_workspace_store_and_answers_goal_and_text() {assert_eq!(payload["goal"]["tokenBudget"], 5000);assert!(payload["text"].as_str().unwrap().starts_with("Goal set."));- let stored = tinyagents_graph::goals::store::get(+ let stored = tinyagents_harness_tools::goals::store::get(&crate::storage::sessions::stores_or_ephemeral(tmp.path()).kv,"thread-host-tools",)diff --git a/crates/openhuman-core/src/agent/harness/graph_tests.rs b/crates/openhuman-core/src/agent/harness/graph_tests.rsindex 3153f27417..bb6cd8422d 100644--- a/crates/openhuman-core/src/agent/harness/graph_tests.rs+++ b/crates/openhuman-core/src/agent/harness/graph_tests.rs@@ -84,7 +84,7 @@ async fn channel_turn_runs_through_the_graph() {#[tokio::test]async fn channel_turn_pauses_on_ask_user_clarification() {let registry: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(- tinyagents_harness::tools::AskClarificationTool::new(),+ tinyagents_harness_tools::AskClarificationTool::new(),)]);let mut history = vec![TranscriptMessage::user("build me a workflow")];let scripted: Arc<dyn ChatModel<()>> = Arc::new(ScriptedModel::new(vec![diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rsindex 1d2b8b6df5..ab2cd2665e 100644--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs@@ -174,7 +174,7 @@ pub(crate) fn artifact_read_target(tool_name: &str,args: &Value,) -> Option<ArtifactRead> {- let wrapper = tinyagents_harness::tool::packs::USE_SKILL;+ let wrapper = tinyagents_harness_tools::skills::USE_SKILL;match store {Some(store) => store.read_target(tool_name, args, wrapper),None => tool_results::artifact_read_target(tool_name, args, READ_TOOL, wrapper),diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rsindex 2594f91231..fd281e6195 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs@@ -10,7 +10,7 @@ use super::super::delegate_graph::DelegateGraphDispatch;use crate::tools::delegate::DelegateToolDispatch;use tinyagents_harness::context::RunConfig;use tinyagents_harness::tool::ToolDispatch;-use tinyagents_harness::tools::AskClarificationTool;+use tinyagents_harness_tools::AskClarificationTool;struct DelegationRegistrationTool {name: &'static str,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_surface.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_surface.rsindex 8a446c3c69..658a160f24 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_surface.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_surface.rs@@ -109,7 +109,8 @@ async fn steer_reusable_session(message: String,) -> Result<(), String> {use tinyagents_harness::tool::ToolDispatch;- use tinyagents_orchestration::subagent::{SubAgentJobRegistry, SubAgentMessageTool};+ use tinyagents_harness_tools::subagents::SubAgentMessageTool;+ use tinyagents_orchestration::subagent::SubAgentJobRegistry;use tinytools::{ToolCallOptions, ToolTimeout};let context = &parent.data;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_continuation_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_continuation_tests.rsindex c5135023f9..9083bd2503 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_continuation_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_continuation_tests.rs@@ -12,7 +12,7 @@ async fn continue_subagent_resumes_paused_job_through_shared_driver() {seen: Mutex::new(Vec::new()),});let ask_tool: Box<dyn tinytools::Tool> =- Box::new(tinyagents_harness::tools::AskClarificationTool::new());+ Box::new(tinyagents_harness_tools::AskClarificationTool::new());let ask_spec = Arc::new(ask_tool.spec());let mut parent = parent_context(workspace.path(), provider.clone(), vec![]);parent.all_tools = Arc::new(vec![ask_tool]);@@ -126,7 +126,7 @@ async fn cancelling_a_paused_driver_through_rpc_settles_once_with_its_reason() {seen: Mutex::new(Vec::new()),});let ask_tool: Box<dyn tinytools::Tool> =- Box::new(tinyagents_harness::tools::AskClarificationTool::new());+ Box::new(tinyagents_harness_tools::AskClarificationTool::new());let ask_spec = Arc::new(ask_tool.spec());let mut parent = parent_context(workspace.path(), provider.clone(), vec![]);parent.workspace_dir = workspace.path().to_path_buf();diff --git a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_driver_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_driver_tests.rsindex 064f5e0cdb..691ec24ad2 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_driver_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_driver_tests.rs@@ -10,9 +10,8 @@ async fn force_fresh_cancels_old_driver_before_creating_a_new_session() {use crate::tools::toolpacks::ToolGroups;use tinyagents_harness::context::RunContext;use tinyagents_harness::tool::ToolDispatch;- use tinyagents_orchestration::subagent::{- SubAgentJobRegistry, SubAgentJobStatus, SubAgentJobsTool,- };+ use tinyagents_harness_tools::subagents::SubAgentJobsTool;+ use tinyagents_orchestration::subagent::{SubAgentJobRegistry, SubAgentJobStatus};struct GatedModel {calls: std::sync::atomic::AtomicUsize,@@ -206,7 +205,7 @@ async fn force_fresh_cancels_old_driver_before_creating_a_new_session() {Some("force-fresh-parent-thread".into()),);let wait = SubAgentJobsTool::new((*jobs).clone())- .with_fixed_action(tinyagents_orchestration::subagent::SubAgentJobAction::Await)+ .with_fixed_action(tinyagents_harness_tools::subagents::SubAgentJobAction::Await).with_identifier_fields("task_id", "subagent_session_id").with_sessions(Arc::new(session_port), |_| {"force-fresh-parent-session".to_owned()diff --git a/crates/openhuman-core/src/agent/prompts/mod_tests_builder_sections_tests.rs b/crates/openhuman-core/src/agent/prompts/mod_tests_builder_sections_tests.rsindex 01f46509fc..106952accc 100644--- a/crates/openhuman-core/src/agent/prompts/mod_tests_builder_sections_tests.rs+++ b/crates/openhuman-core/src/agent/prompts/mod_tests_builder_sections_tests.rs@@ -280,7 +280,7 @@ fn datetime_section_appends_resolve_time_rule_only_when_tool_present() {// With `resolve_time` in the agent's tool set, the time-discipline rule// is rendered under the date block (prevents the LLM hand-computing epoch// timestamps — the bug this tool exists to fix).- let timed = vec![Box::new(tinyagents_harness::tools::ResolveTimeTool::new()) as Box<dyn Tool>];+ let timed = vec![Box::new(tinyagents_harness_tools::ResolveTimeTool::new()) as Box<dyn Tool>];let with_prompt_tools = PromptTool::from_tools(&timed);let ctx_with = PromptContext {workspace_dir: Path::new("/tmp"),diff --git a/crates/openhuman-core/src/agent/registration.rs b/crates/openhuman-core/src/agent/registration.rsindex e5c0d3f4cd..a20450d201 100644--- a/crates/openhuman-core/src/agent/registration.rs+++ b/crates/openhuman-core/src/agent/registration.rs@@ -10,7 +10,7 @@ use crate::config::Config;#[cfg(feature = "skills")]use crate::skills::run_workflow::{AwaitWorkflowTool, RunWorkflowTool};use std::path::Path;-use tinyagents_harness::tools as harness_tools;+use tinyagents_harness_tools as harness_tools;use tinytools::Tool;use tinytools_std::filesystem::WorkspaceStateTool;@@ -40,8 +40,8 @@ pub(crate) fn dialogue_tools(action_dir: &Path, root_config: &Config) -> Vec<Box// durable `subagent_session_id` (preferred) or transient `task_id`.Box::new(ListSubagentsTool::new()),Box::new(SteerSubagentTool::new()),- Box::new(harness_tools::WaitTool::new()),- Box::new(harness_tools::WaitLoopTool::new()),+ Box::new(crate::agent::tools::WaitTool::new()),+ Box::new(crate::agent::tools::WaitLoopTool::new()),Box::new(WaitSubagentTool::new()),Box::new(CloseSubagentTool::new()),Box::new(ContinueSubagentTool::new()),diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rsindex 15106c3b4c..75bde0344a 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs@@ -13,9 +13,24 @@ impl SessionHostBuilder {/// setting up the context manager, and initializing the conversation history./// It ensures that all required fields (provider, tools, dispatcher, …) are present.pub fn build(self) -> Result<OpenHumanSessionHost> {+ let mut pack_registry_handle = self.pack_registry_handle.clone();let mut tools = self.tools.ok_or_else(|| anyhow::anyhow!("tools are required"))?;+ if pack_registry_handle.is_none()+ && tools+ .iter()+ .any(|tool| crate::tools::toolpacks::is_canonical_use_skill_tool(tool.as_ref()))+ {+ // Preserve the public `all_tools() -> Vec<_>` then `.tools(...)`+ // flow: callers that do not receive a handle still get a proxy+ // bound to this session's registry. Custom `use_skill` tools are+ // left untouched; they can supply a handle through the builder.+ tools.retain(|tool| {+ !crate::tools::toolpacks::is_canonical_use_skill_tool(tool.as_ref())+ });+ pack_registry_handle = Some(crate::tools::toolpacks::append_pack_tools(&mut tools));+ }// Advertise only the spawnable ids on the wire: see// `SpawnAsyncSubagentTool::scoped` for why the spec-view narrowing// alone did not reach a native-tool-calling provider.@@ -382,13 +397,12 @@ impl SessionHostBuilder {let tools = Arc::new(tools);let synthesized_tools = Arc::new(synthesized_tools);- // The pack tool lives inside this registry, so it can only be pointed- // at it once it exists. Re-bind after any later rebuild of this `Arc`.- crate::tools::toolpacks::bind_pack_registry(&tools);- // And at the delegates, which are NOT in that registry: every- // `delegate_*` is synthesised into its own `Arc`, so a packed delegate- // is unreachable through `use_skill` until this second binding runs.- crate::tools::toolpacks::bind_synthesized_pack_registry(&tools, &synthesized_tools);+ // The pack handle is host-owned and retained beside the registry;+ // rebind it after this Arc is built and after any future refresh.+ if let Some(handle) = pack_registry_handle.as_ref() {+ crate::tools::toolpacks::bind_pack_registry(handle, &tools);+ crate::tools::toolpacks::bind_synthesized_pack_registry(handle, &synthesized_tools);+ }Ok(OpenHumanSessionHost {runtime_session: None,@@ -401,6 +415,7 @@ impl SessionHostBuilder {})),turn_model_source,tools,+ pack_registry_handle,synthesized_tools,tool_specs: Arc::new(tool_specs),durable_tool_specs: Arc::new(durable_tool_specs),diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rsindex 238712fcd6..f860502917 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs@@ -112,7 +112,7 @@ fn use_skill_spec_from_registry() -> ToolSpec {crate::tools::toolpacks::append_pack_tools(&mut tools);let tool = tools.iter()- .find(|t| t.name() == tinyagents_harness::tool::packs::USE_SKILL)+ .find(|t| t.name() == tinyagents_harness_tools::skills::USE_SKILL).expect("append_pack_tools registers use_skill");ToolSpec {name: tool.name().to_string(),@@ -132,12 +132,12 @@ fn visible_specs_scope_use_skills_index_to_the_session() {let visible: std::collections::HashSet<String> = specs.iter().map(|s| s.name.clone()).collect();// Reachable: one workflows tool. Everything else in every other pack is// denied, exactly like the orchestrator against `system` / `audio`.- let session = session_allowing(&["run_workflow", tinyagents_harness::tool::packs::USE_SKILL]);+ let session = session_allowing(&["run_workflow", tinyagents_harness_tools::skills::USE_SKILL]);let out = visible_tool_specs_for_policy(&specs, &visible, &session);let load = out.iter()- .find(|s| s.name == tinyagents_harness::tool::packs::USE_SKILL)+ .find(|s| s.name == tinyagents_harness_tools::skills::USE_SKILL).expect("use_skill is still offered — workflows is reachable");assert!(@@ -169,7 +169,7 @@ fn visible_specs_drop_the_pack_tool_when_no_pack_is_reachable() {let specs: Vec<std::sync::Arc<ToolSpec>> =vec![std::sync::Arc::new(use_skill_spec_from_registry())];let visible: std::collections::HashSet<String> = specs.iter().map(|s| s.name.clone()).collect();- let session = session_allowing(&[tinyagents_harness::tool::packs::USE_SKILL]);+ let session = session_allowing(&[tinyagents_harness_tools::skills::USE_SKILL]);let out = visible_tool_specs_for_policy(&specs, &visible, &session);assert!(@@ -246,12 +246,12 @@ fn a_realistic_withheld_session_keeps_its_packs_advertised() {let names: Vec<&str> = out.iter().map(|s| s.name.as_str()).collect();assert!(- names.contains(&tinyagents_harness::tool::packs::USE_SKILL),+ names.contains(&tinyagents_harness_tools::skills::USE_SKILL),"use_skill must survive — the pack it opens is reachable: {names:?}");let load = out.iter()- .find(|s| s.name == tinyagents_harness::tool::packs::USE_SKILL)+ .find(|s| s.name == tinyagents_harness_tools::skills::USE_SKILL).expect("use_skill spec");assert!(load.description.contains("`goals`"),@@ -281,7 +281,7 @@ fn use_skill_survives_a_ceiling_that_excludes_it_when_a_pack_is_still_reachable(assert!(!session.allowed_tool_names- .contains(tinyagents_harness::tool::packs::USE_SKILL),+ .contains(tinyagents_harness_tools::skills::USE_SKILL),"precondition: use_skill itself is not in the allowlist");@@ -292,7 +292,7 @@ fn use_skill_survives_a_ceiling_that_excludes_it_when_a_pack_is_still_reachable(let out = visible_tool_specs_for_policy(&specs, &visible, &session);let load = out.iter()- .find(|s| s.name == tinyagents_harness::tool::packs::USE_SKILL)+ .find(|s| s.name == tinyagents_harness_tools::skills::USE_SKILL).expect("use_skill must survive even though it is not itself in allowed_tool_names — \its listing action is always ReadOnly and the workflows pack is reachable",diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rsindex 4795f071bb..70af683dd5 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rs@@ -62,7 +62,7 @@ fn the_three_spec_views_share_their_leaf_schemas() {// rewrite mutate in place would silently scope the durable set, and a// change that deep-copied everything again would still pass an// exclusion-only test.- let use_skill = tinyagents_harness::tool::packs::USE_SKILL;+ let use_skill = tinyagents_harness_tools::skills::USE_SKILL;let mut saw_scoped_use_skill = false;let mut saw_scoped_spawn = false;diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rsindex 3e5a999213..d5fd155425 100644--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs@@ -1,6 +1,6 @@//! `OpenHumanSessionHost::from_config` factory methods and internal `build_session_agent_inner` constructor.-use super::should_synthesize_delegation_tools;+use super::{factory_resolution::provider_role_for_definition, should_synthesize_delegation_tools};use crate::agent::prompts::SystemPromptBuilder;use crate::agent::session_host::types::OpenHumanSessionHost;use crate::agent_registry::host_definition::{@@ -19,6 +19,8 @@ use tinytools_agent::dialect::{CodeDialect, CodeStyle, NativeDialect, PFormatDialect, ToolCallFormat, ToolDialect, XmlDialect,};+#[path = "factory_tool_registry.rs"]+mod tool_registry;#[path = "factory_workflows.rs"]mod workflows;@@ -188,24 +190,23 @@ impl OpenHumanSessionHost {let tool_config: Arc<Config> = Arc::clone(&base_config);// Host-only (`host_only.rs`): no config-derived tool is even built.- let mut tools = if host_only {- Vec::new()- } else {- tools::ops::all_tools_with_runtime(- Arc::clone(&tool_config),- &security,- runtime,- audit,- &tool_config.browser,- &tool_config.http_request,- &tool_config.action_dir,- &tool_config.agents,- &tool_config,- workspace_descriptor- .as_ref()- .map(|descriptor| descriptor.root.as_path()),- )- };+ let (mut tools, pack_registry_handle) =+ tool_registry::make_tool_registry(host_only, || {+ tools::ops::all_tools_with_runtime_and_pack_handle(+ Arc::clone(&tool_config),+ &security,+ runtime,+ audit,+ &tool_config.browser,+ &tool_config.http_request,+ &tool_config.action_dir,+ &tool_config.agents,+ &tool_config,+ workspace_descriptor+ .as_ref()+ .map(|descriptor| descriptor.root.as_path()),+ )+ });// Filter tools by the user preference loaded above.if !enabled_tools.is_empty() {@@ -780,6 +781,7 @@ impl OpenHumanSessionHost {let mut builder = OpenHumanSessionHost::builder().crate_native_provider(ctx, provider_role, Arc::clone(&base_config)).tools(tools)+ .pack_registry_handle(pack_registry_handle).synthesized_tools(delegation_tools).visible_tool_names(visible).withheld_tool_names(withheld_tool_names)@@ -917,5 +919,3 @@ pub(super) fn resolve_target_definition(agent_id))}--use super::factory_resolution::provider_role_for_definition;diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory_tool_registry.rs b/crates/openhuman-core/src/agent/session_host/builder/factory_tool_registry.rsnew file mode 100644index 0000000000..e93b3529e2--- /dev/null+++ b/crates/openhuman-core/src/agent/session_host/builder/factory_tool_registry.rs@@ -0,0 +1,19 @@+use tinytools::Tool;++pub(super) fn make_tool_registry(+ host_only: bool,+ build: impl FnOnce() -> (+ Vec<Box<dyn Tool>>,+ tinyagents_harness_tools::skills::PackRegistryHandle,+ ),+) -> (+ Vec<Box<dyn Tool>>,+ Option<tinyagents_harness_tools::skills::PackRegistryHandle>,+) {+ if host_only {+ (Vec::new(), None)+ } else {+ let (tools, handle) = build();+ (tools, Some(handle))+ }+}diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rsindex cbecdc30bc..4ae675c953 100644--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs@@ -144,7 +144,7 @@ pub(super) fn visible_tool_specs_for_policy(// below already does the real per-tool narrowing via `is_callable`// (and drops the spec entirely when nothing survives), so this// filter only needs to gate *other* tools on the static ceiling.- spec.name == tinyagents_harness::tool::packs::USE_SKILL+ spec.name == tinyagents_harness_tools::skills::USE_SKILL|| tool_policy.is_allowed(&spec.name)}).cloned()@@ -161,7 +161,7 @@ pub(super) fn visible_tool_specs_for_policy(}return Some(spec);}- if spec.name == tinyagents_harness::tool::packs::USE_SKILL {+ if spec.name == tinyagents_harness_tools::skills::USE_SKILL {// `false` means no pack has a callable tool: an empty index and// an empty enum are not a tool, so drop it rather than ship one.// `Arc::make_mut`, not `&mut spec`: the three spec views share@@ -170,7 +170,7 @@ pub(super) fn visible_tool_specs_for_policy(// `durable_tool_specs` is meant to stay the unscoped truth.// This copies exactly the one spec being rewritten and leaves// the other ~48 visible schemas shared.- return tinyagents_harness::tool::packs::scope_use_skill_spec(+ return tinyagents_harness_tools::skills::scope_use_skill_spec(&crate::tools::toolpacks::CATALOG,Arc::make_mut(&mut spec),&is_callable,diff --git a/crates/openhuman-core/src/agent/session_host/builder/setters.rs b/crates/openhuman-core/src/agent/session_host/builder/setters.rsindex 448e2cb9ef..bb338b4db6 100644--- a/crates/openhuman-core/src/agent/session_host/builder/setters.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/setters.rs@@ -13,6 +13,7 @@ impl SessionHostBuilder {turn_model_source: None,runtime_config: None,tools: None,+ pack_registry_handle: None,synthesized_tools: None,visible_tool_names: None,withheld_tool_names: std::collections::HashSet::new(),@@ -95,6 +96,16 @@ impl SessionHostBuilder {self}+ /// Retains the host-owned pack handle used by the session's `use_skill`+ /// tool so registry refreshes can rebind its durable and synthesized views.+ pub fn pack_registry_handle(+ mut self,+ handle: Option<tinyagents_harness_tools::skills::PackRegistryHandle>,+ ) -> Self {+ self.pack_registry_handle = handle;+ self+ }+/// Sets the delegation tools synthesised for the session's initial/// connection set — see [`OpenHumanSessionHost::synthesized_tools`]. A name a durable/// tool already owns is dropped in [`Self::build`]. Defaults to none.diff --git a/crates/openhuman-core/src/agent/session_host/builder_config.rs b/crates/openhuman-core/src/agent/session_host/builder_config.rsindex 720bcb176b..e9aedea2d9 100644--- a/crates/openhuman-core/src/agent/session_host/builder_config.rs+++ b/crates/openhuman-core/src/agent/session_host/builder_config.rs@@ -17,6 +17,8 @@ pub struct SessionHostBuilder {/// Explicit host config for injected-model attachment staging and services.pub(super) runtime_config: Option<Arc<crate::config::Config>>,pub(super) tools: Option<Vec<Box<dyn Tool>>>,+ /// Host-owned handle shared with the durable `use_skill` tool.+ pub(super) pack_registry_handle: Option<tinyagents_harness_tools::skills::PackRegistryHandle>,/// Delegation tools synthesised for the session's initial connection set./// Held in [`OpenHumanSessionHost::synthesized_tools`], never inside [`OpenHumanSessionHost::tools`].pub(super) synthesized_tools: Option<Vec<Box<dyn Tool>>>,diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rsindex 450f13ee6c..18bdeb8a8b 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs@@ -1,10 +1,11 @@use std::sync::{Arc, Mutex};use async_trait::async_trait;+use tinyagents_harness::tool::ToolSnapshot;use tinyagents_runtime::{DriverFailure, DriverOutcome, DriverRequest, PrefixSnapshot, ResumeMode, SessionBuilder,- SessionDriver, SessionTerminal, SessionTurnRequest, ToolSnapshot, TranscriptCodec,- TranscriptTurnOptions, TurnOptions,+ SessionDriver, SessionTerminal, SessionTurnRequest, TranscriptCodec, TranscriptTurnOptions,+ TurnOptions,};use tinyagents_session::port::{InMemorySessionStores, SessionStoreProvider};use tinyagents_session::transcript::TranscriptMeta;@@ -286,7 +287,7 @@ async fn committed_goal_accounting_uses_direct_and_completed_child_usage() {);crate::core::runtime::CoreContext::scope(core, async {let goal_store = crate::storage::sessions::stores_or_ephemeral(workspace.path()).kv;- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&goal_store,"receipt-goal","finish migration",@@ -295,7 +296,7 @@ async fn committed_goal_accounting_uses_direct_and_completed_child_usage() {.await.unwrap();assert!(- tinyagents_graph::goals::store::get(&goal_store, "receipt-goal")+ tinyagents_harness_tools::goals::store::get(&goal_store, "receipt-goal").await.unwrap().is_some(),@@ -319,7 +320,7 @@ async fn committed_goal_accounting_uses_direct_and_completed_child_usage() {sidecar.subagents.push(child);account_committed_turn_against_goal(workspace.path(), Some("receipt-goal"), &sidecar).await;- let goal = tinyagents_graph::goals::store::get(&goal_store, "receipt-goal")+ let goal = tinyagents_harness_tools::goals::store::get(&goal_store, "receipt-goal").await.unwrap().unwrap();@@ -329,7 +330,7 @@ async fn committed_goal_accounting_uses_direct_and_completed_child_usage() {);assert_eq!(goal.status,- tinyagents_graph::goals::ThreadGoalStatus::BudgetLimited,+ tinyagents_harness_tools::goals::ThreadGoalStatus::BudgetLimited,"receipt-backed accounting advances continuation/budget state");})diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_usage_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_usage_tests.rsindex 9dd6e29d5b..dd3cf86088 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_usage_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_usage_tests.rs@@ -61,7 +61,7 @@ async fn committed_goal_accounting_saturates_direct_plus_inclusive_child_tokens();crate::core::runtime::CoreContext::scope(core, async {let goal_store = crate::storage::sessions::stores_or_ephemeral(workspace.path()).kv;- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&goal_store,"saturated-goal","complete safely",@@ -70,7 +70,7 @@ async fn committed_goal_accounting_saturates_direct_plus_inclusive_child_tokens(.await.unwrap();assert!(- tinyagents_graph::goals::store::get(&goal_store, "saturated-goal")+ tinyagents_harness_tools::goals::store::get(&goal_store, "saturated-goal").await.unwrap().is_some(),@@ -108,7 +108,7 @@ async fn committed_goal_accounting_saturates_direct_plus_inclusive_child_tokens().await;- let goal = tinyagents_graph::goals::store::get(&goal_store, "saturated-goal")+ let goal = tinyagents_harness_tools::goals::store::get(&goal_store, "saturated-goal").await.unwrap().unwrap();diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex ede5bf4bb1..139ee4d7d3 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -29,11 +29,12 @@ type ActiveTerminalSidecar = std::sync::Arc<use std::sync::Arc;use anyhow::Result;-use tinyagents_graph::goals::ThreadGoalStatus;use tinyagents_harness::multimodal::markers::extract_image_placeholders_in_text;+use tinyagents_harness::tool::ToolSnapshot;+use tinyagents_harness_tools::goals::ThreadGoalStatus;use tinyagents_runtime::{- CommitReceipt, ResumePreparation, SessionBuilder, SessionTerminal, ToolSnapshot,- TranscriptTarget, TurnPreparation,+ CommitReceipt, ResumePreparation, SessionBuilder, SessionTerminal, TranscriptTarget,+ TurnPreparation,};use tinyinference_llm::message::Message;@@ -91,6 +92,7 @@ struct OpenHumanTurnPrelude {crate::agent::tinyagents::host::OpenHumanRunContext,>,>,+ pack_registry_handle: Option<tinyagents_harness_tools::skills::PackRegistryHandle>,tool_dispatcher: Arc<dyn tinytools_agent::dialect::ToolDialect>,workspace_dir: std::path::PathBuf,action_dir: std::path::PathBuf,diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rsindex 1bf3127378..a18520dd1b 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs@@ -249,7 +249,7 @@ impl OpenHumanTurnPrelude {}};if let Some(goal) = &active_goal {- if let Some(block) = tinyagents_graph::goals::active_goal_context_block(goal) {+ if let Some(block) = tinyagents_harness_tools::goals::active_goal_context_block(goal) {context.push_str(&block);}if let Some(hook) = tinyagents_hooks::stop::GoalBudgetStopHook::for_goal(diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rsindex da29985467..10e7f72308 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rs@@ -12,6 +12,7 @@ impl OpenHumanSessionHost {prompt_builder: self.prompt_builder.clone(),context_config: self.context_config.clone(),tool_policy: self.tool_policy.clone(),+ pack_registry_handle: self.pack_registry_handle.clone(),tool_dispatcher: self.tool_dispatcher.clone(),workspace_dir: self.workspace_dir.clone(),action_dir: self.action_dir.clone(),diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rsindex d3e7ba8e47..b1a5adfbfd 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs@@ -2,7 +2,7 @@use std::sync::Arc;-use tinyagents_runtime::ToolSnapshot;+use tinyagents_harness::tool::ToolSnapshot;use tinytools::ToolSpec;#[cfg(feature = "flows")]diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rsindex 4597a8b31e..38c281f906 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs@@ -237,7 +237,9 @@ impl OpenHumanTurnPrelude {}}let synthesized_tools = Arc::new(synthesized);- crate::tools::toolpacks::bind_synthesized_pack_registry(&surface.tools, &synthesized_tools);+ if let Some(handle) = self.pack_registry_handle.as_ref() {+ crate::tools::toolpacks::bind_synthesized_pack_registry(handle, &synthesized_tools);+ }let all_tools = surface.tools.iter()diff --git a/crates/openhuman-core/src/agent/session_host/types.rs b/crates/openhuman-core/src/agent/session_host/types.rsindex d5526f63f3..41573ce2cd 100644--- a/crates/openhuman-core/src/agent/session_host/types.rs+++ b/crates/openhuman-core/src/agent/session_host/types.rs@@ -157,6 +157,8 @@ pub struct OpenHumanSessionHost {/// which *does* change mid-session, lives in [`Self::synthesized_tools`]/// instead. See that field for why.pub(super) tools: Arc<Vec<Box<dyn Tool>>>,+ /// Handle shared with the durable `use_skill` tool for safe registry rebinding.+ pub(super) pack_registry_handle: Option<tinyagents_harness_tools::skills::PackRegistryHandle>,/// The delegation tools synthesised for the current connection set —/// `delegate_<toolkit>` skill tools and archetype delegates, produced by/// [`crate::tools::orchestrator_tools::collect_orchestrator_tools`].diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rsindex afe165b068..d0bf54c9cc 100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs@@ -17,7 +17,6 @@ use tinyagents_orchestration::subagent::{SubagentPersistenceDisposition, SubagentPlanner, SubagentRequest, SubagentResume,SubagentRunResult, SubagentTaskKey, SubagentTerminalPersistenceDisposition,};-use tinyagents_runtime::ToolSnapshot;use tinyinference_llm::{message::Message,usage::{ChargedAmount, Usage, UsageTotals},@@ -365,7 +364,8 @@ async fn invoke_driver_tool_with_request(continuation: Option<(SubagentTaskKey, SubagentResume)>,) -> Result<(tinytools::ToolResult, OpenHumanDriverBundle), SubagentRunError> {use tinyagents_harness::tool::ToolDispatch;- use tinyagents_orchestration::subagent::{DriverSubAgentTool, SubAgentJobRegistry};+ use tinyagents_harness_tools::subagents::DriverSubAgentTool;+ use tinyagents_orchestration::subagent::SubAgentJobRegistry;use tinytools::{PermissionLevel, ToolCallOptions, ToolCategory, ToolScope, ToolTimeout};let task_id = host_requestdiff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rsindex 79910c0f33..558d22057a 100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rs@@ -1,4 +1,5 @@use super::*;+use tinyagents_harness::tool::ToolSnapshot;pub(crate) struct OpenHumanDriverBundle {pub(crate) driver:diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_driver_bridge_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_driver_bridge_tests.rsindex ba4079c714..a8860622f0 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests_driver_bridge_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_driver_bridge_tests.rs@@ -266,9 +266,10 @@ async fn closing_a_durable_driver_session_cancels_only_its_registered_child() {DurableSubagentSession, DurableSubagentStatus, OpenHumanTinySubagentSessionStore,SubagentSessionStore as HostSessionStore,};+ use tinyagents_harness_tools::subagents::{SubAgentJobAction, SubAgentJobsTool};use tinyagents_orchestration::subagent::{- SubAgentJobAction, SubAgentJobRegistry, SubAgentJobStatus, SubAgentJobsTool,- SubagentSessionStore as TinySessionStore, SubagentTaskKey,+ SubAgentJobRegistry, SubAgentJobStatus, SubagentSessionStore as TinySessionStore,+ SubagentTaskKey,};let scratch = tempfile::tempdir().expect("isolated driver close fixture");@@ -386,7 +387,7 @@ async fn closing_a_durable_driver_session_cancels_only_its_registered_child() {let message_store: std::sync::Arc<dyn TinySessionStore> = std::sync::Arc::new(port.clone());let message_dispatch: crate::agent::tinyagents::tool_registration::RegisteredToolDispatch =std::sync::Arc::new(- tinyagents_orchestration::subagent::SubAgentMessageTool::new(jobs.clone())+ tinyagents_harness_tools::subagents::SubAgentMessageTool::new(jobs.clone()).with_tool_name("steer_subagent").with_argument_fields("task_id", "subagent_session_id", "message", "__request_id").with_lane_field("mode")diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rsindex b5998cd11e..8edb8d195f 100644--- a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs@@ -8,8 +8,8 @@ use super::types::SubagentRunError;use crate::agent::prompts::PromptContext;use crate::agent_registry::host_definition::AgentDefinition;use tinyagents_definition::{PromptSource, ToolScope};+use tinyagents_harness::tool::ToolSnapshot;use tinyagents_orchestration::subagent::{restrict_tools_with_scope, SubagentRole};-use tinyagents_runtime::ToolSnapshot;use tinytools::Tool;// ── Prompt dialect selection ────────────────────────────────────────────diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rsindex 1ee0da0f19..0e36a4ceaa 100644--- a/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep_recovery_visibility_tests_tests.rs@@ -1,7 +1,7 @@use super::*;use crate::inference::tokenjuice::LEGACY_RETRIEVE_TOOL_NAME as RECOVERY_TOOL_NAME;use crate::tools::retrieve_tool_output_tool;-use tinyagents_harness::tools::CurrentTimeTool;+use tinyagents_harness_tools::CurrentTimeTool;fn tools() -> Vec<Box<dyn tinytools::Tool>> {vec | Host adapter over `tinyagents_harness::run_queue::SteeringForwarderGuard` (forwards `RunQueue` steer/collect messages into the harness `SteeringHandle`; abort-on-drop so drop-based cancellation always deregisters it, issue #4456): `QueuedMessage for QueuedTurn`, the `RunQueue*` domain-event sink and the steering-registry cleanup hook. || `summarize.rs` | `ModelSummarizer` / `FaultTolerantCachingSummarizer` plus a context-window-aware `SummarizationPolicy` driving the crate's `ContextCompressionMiddleware`. || [`embeddings.rs`](./embeddings.rs) | `ProviderEmbeddingModel`: cost-recording binding over the host-built `tinyinference_embeddings::EmbeddingModel`. |-| [`todos.rs`](./todos.rs) | `todos_store` / `scratch_todos_store` (the crate `Store` behind per-thread agent todos, `tinyagents_graph::todos`). |+| [`todos.rs`](./todos.rs) | `todos_store` / `scratch_todos_store` (the crate `Store` behind per-thread agent todos, `tinyagents_harness_tools::todos`). || [`config.rs`](./config.rs) | Maps OpenHuman's `Config` (including model pins) onto `tinyagents_harness::config` structs. || `*_tests.rs` | Sibling test suites for each file/part group above. |diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rsindex 78e5380ff4..d2d456e682 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs@@ -8,7 +8,7 @@//! and that pack's group is `Withheld`. No session (sub-agent, channel/CLI//! turns) means no routing, so the registration allowlist stays the boundary.-use tinyagents_harness::tool::packs::USE_SKILL;+use tinyagents_harness_tools::skills::USE_SKILL;use tinyagents_hooks::lifecycle::{PackedToolRouteMiddleware, PackedToolRouter};use tinytools::ToolPolicySession;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rsindex 7308c11c2c..a21b895cac 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs@@ -12,6 +12,7 @@ use tinyagents_harness::middleware::{DenialRenderer, MiddlewareToolOutcome, PolicyDecision, ToolCallPolicy, ToolHandler,ToolMiddleware, ToolPolicyGateMiddleware,};+use tinyagents_harness_tools::skills::PackRegistryHandle;use tinyinference_llm::tool::ToolCall as TaToolCall;use tinytools::ToolResult as TaToolResult;@@ -143,7 +144,7 @@ impl ToolPolicyMiddleware {#[cfg(test)]pub(crate) fn route_for_pack(&self,- pack: &tinyagents_harness::tool::packs::ToolPack,+ pack: &tinyagents_harness_tools::skills::ToolPack,) -> String {self.host.route_for_pack(pack)}@@ -151,9 +152,9 @@ impl ToolPolicyMiddleware {#[cfg(test)]pub(crate) fn no_such_pack_tool<'a>(&self,- pack: &'static tinyagents_harness::tool::packs::ToolPack,+ pack: &'static tinyagents_harness_tools::skills::ToolPack,tool: &'a str,- ) -> tinyagents_harness::tool::packs::NoSuchPackTool<'a> {+ ) -> tinyagents_harness_tools::skills::NoSuchPackTool<'a> {self.host.no_such_pack_tool(pack, tool)}}@@ -221,9 +222,9 @@ impl ToolPolicyHostState {/// the tools in it this session can call, or the pack's route when none.pub(crate) fn no_such_pack_tool<'a>(&self,- pack: &'static tinyagents_harness::tool::packs::ToolPack,+ pack: &'static tinyagents_harness_tools::skills::ToolPack,tool: &'a str,- ) -> tinyagents_harness::tool::packs::NoSuchPackTool<'a> {+ ) -> tinyagents_harness_tools::skills::NoSuchPackTool<'a> {let callable = pack.tools.iter()@@ -233,7 +234,7 @@ impl ToolPolicyHostState {&& !self.session.decision_for(name).blocks_execution()}).collect();- tinyagents_harness::tool::packs::NoSuchPackTool {+ tinyagents_harness_tools::skills::NoSuchPackTool {not_found_marker: tinytools::status::NOT_FOUND_MARKER,skill: pack.id,tool,@@ -245,9 +246,9 @@ impl ToolPolicyHostState {/// The route sentence for a pack, resolved against THIS session.pub(crate) fn route_for_pack(&self,- pack: &tinyagents_harness::tool::packs::ToolPack,+ pack: &tinyagents_harness_tools::skills::ToolPack,) -> String {- tinyagents_harness::tool::packs::route_sentence(+ tinyagents_harness_tools::skills::route_sentence(&self.callable_delegates_for(pack.owners),pack.owners,)@@ -264,23 +265,28 @@ impl ToolPolicyHostState {/// tool named, no `skill` argument, no pack handle), so the call falls/// through to the tool's own `execute` unchanged.pub(crate) fn render_skill_for_session(&self, call: &TaToolCall) -> Option<TaToolResult> {- if tinyagents_harness::tool::packs::named_tool(&call.arguments).is_some() {+ if tinyagents_harness_tools::skills::named_tool(&call.arguments).is_some() {return None;}let skill = call.arguments.get("skill").and_then(serde_json::Value::as_str)?;- let tool = self.resolve_tool(&call.name)?;- let handle = crate::tools::host_extensions::pack_registry_handle(tool.as_ref())?;+ self.resolve_tool(&call.name)?;+ let durable = self.tool_sets.first()?;+ let handle = PackRegistryHandle::default();+ handle.bind(Arc::downgrade(durable));+ if let Some(synthesized) = self.tool_sets.get(1) {+ handle.bind_synthesized(Arc::downgrade(synthesized));+ }let is_callable = |name: &str| !self.session.decision_for(name).blocks_execution();let route = crate::tools::toolpacks::pack(skill).map(|pack| self.route_for_pack(pack)).unwrap_or_default();- let rendered = tinyagents_harness::tool::packs::render_pack_filtered(+ let rendered = tinyagents_harness_tools::skills::render_pack_filtered(&crate::tools::toolpacks::CATALOG,skill,- handle,+ &handle,// The same predicate the gate applies to `use_skill`'s inner tool.// Two sources of truth for "can this session call it" is the bug.&is_callable,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_policy_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_policy_tests.rsindex ebcc88633e..212e7308f8 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_policy_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_policy_tests.rs@@ -12,7 +12,7 @@ use crate::agent::tinyagents::middleware::tool_policy::ToolPolicyMiddleware;use crate::agent::orchestration::tools::{ArchetypeDelegationTool, DelegationTarget};use crate::tools::toolpacks::{append_pack_tools, bind_pack_registry};-use tinyagents_harness::tool::packs::USE_SKILL;+use tinyagents_harness_tools::skills::USE_SKILL;use tinytools::{PermissionLevel, ToolResult};use tinytools::{TaskProfile, TaskRiskLevel, ToolCapability, ToolPolicyAction, ToolPolicyDecision,@@ -73,9 +73,9 @@ fn non_owner_middleware_at(allowed: PermissionLevel) -> ToolPolicyMiddleware {tool_description: "Build a workflow".to_string(),}),];- append_pack_tools(&mut tools);+ let pack_handle = append_pack_tools(&mut tools);let tools = Arc::new(tools);- bind_pack_registry(&tools);+ bind_pack_registry(&pack_handle, &tools);let session = ToolPolicySession {profile: TaskProfile {@@ -264,9 +264,9 @@ async fn a_use_skill_denial_names_a_delegate_this_session_can_call() {async fn a_session_without_the_delegate_is_not_told_to_call_it() {let mut tools: Vec<Box<dyn tinytools::Tool>> =vec![Box::new(RoutingFakeTool("propose_workflow"))];- append_pack_tools(&mut tools);+ let pack_handle = append_pack_tools(&mut tools);let tools = Arc::new(tools);- bind_pack_registry(&tools);+ bind_pack_registry(&pack_handle, &tools);let session = ToolPolicySession {profile: TaskProfile {@@ -326,9 +326,9 @@ async fn use_skill_reaches_a_withheld_packed_tool() {use tinytools::ToolPolicyEngine;let mut tools: Vec<Box<dyn tinytools::Tool>> = vec![Box::new(RoutingFakeTool("goal_set"))];- append_pack_tools(&mut tools);+ let pack_handle = append_pack_tools(&mut tools);let tools = Arc::new(tools);- bind_pack_registry(&tools);+ bind_pack_registry(&pack_handle, &tools);// The real harness shape: seed `visible` with everything, then withhold the// packed names for a non-owner.@@ -381,9 +381,9 @@ async fn a_prompt_hidden_delegate_is_not_offered_as_a_direct_route() {tool_description: "Build a workflow".to_string(),}),];- append_pack_tools(&mut tools);+ let pack_handle = append_pack_tools(&mut tools);let tools = Arc::new(tools);- bind_pack_registry(&tools);+ bind_pack_registry(&pack_handle, &tools);// `build_workflow` is itself a member of the `workflows` pack, so// `strip_packed_from_visible` withholds it for a non-owner — leaving thediff --git a/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/tool_registration.rsindex f2346db5de..d76b39519c 100644--- a/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs+++ b/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs@@ -7,11 +7,11 @@ use std::collections::HashSet;use std::sync::Arc;use async_trait::async_trait;-use tinyagents_graph::goals::GoalToolKind;-use tinyagents_harness::tool::packs::{PackSelection, UseSkillDispatch, USE_SKILL};use tinyagents_harness::tool::{CanonicalSharedToolAdapter, ToolDispatch, ToolExecScope, ToolExecution, ToolExecutionContext,};+use tinyagents_harness_tools::goals::GoalToolKind;+use tinyagents_harness_tools::skills::{PackSelection, UseSkillDispatch, USE_SKILL};use tinyagents_registry::{CapabilityRegistry, ComponentKind, RegistryDiagnostic};use tinyagents_runtime::turn_driver::{SharedToolSet, ToolSetBuilder};use tinyagents_runtime::{project_descriptors, ToolAdmission};@@ -353,7 +353,7 @@ fn dispatch_selector(tool_sets: Vec<SharedToolSet>) -> DispatchSelector {return typed_dispatch_for(name, adapter, delegation_target);}let selector: Arc<- tinyagents_harness::tool::packs::PackDispatchSelector<(), OpenHumanRunContext>,+ tinyagents_harness_tools::skills::PackDispatchSelector<(), OpenHumanRunContext>,> = Arc::new(select_packed_tool_dispatch);Some(Arc::new(UseSkillDispatch::new(adapter, selector)))})@@ -378,9 +378,10 @@ fn subagent_control_dispatches(tool_sets: &[SharedToolSet],run_context: &OpenHumanRunContext,) -> std::collections::HashMap<String, RegisteredToolDispatch> {- use tinyagents_orchestration::subagent::{- SubAgentJobAction, SubAgentJobRegistry, SubAgentJobsTool, SubAgentMessageTool,+ use tinyagents_harness_tools::subagents::{+ SubAgentJobAction, SubAgentJobsTool, SubAgentMessageTool,};+ use tinyagents_orchestration::subagent::SubAgentJobRegistry;let Some(parent) = run_context.parent.as_ref() else {return std::collections::HashMap::new();diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rsindex fe1325d4ae..e0ae55e71c 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs@@ -14,11 +14,12 @@ use anyhow::Result;use tinyagents_harness::runtime::AgentHarness;use tinyagents_harness::runtime::{AgentInvocation, AgentTurnRequest, InvocationRuntime};use tinyagents_harness::store::{InMemoryStore as ToolResultArtifactIndexStore, StoreRegistry};+use tinyagents_harness::tool::ToolSnapshot;use tinyagents_harness::turn_policy::effective_max_iterations;use tinyagents_runtime::turn_driver::{SubagentScope as DriverSubagentScope, TurnControls, TurnDriver, TurnScope,};-use tinyagents_runtime::{DriverRequest, ToolSnapshot};+use tinyagents_runtime::DriverRequest;use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;use crate::agent::tinyagents::host::OpenHumanRunContext;diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rsindex 5afdbad5cd..b5d87a7faa 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs@@ -480,7 +480,7 @@ pub(super) fn install_turn_middleware(match todo_store {Some(store) if verify_before_finish::applies(is_subagent, agent_id) => {harness.push_middleware(Arc::new(- tinyagents_graph::todos::TodoSequenceMiddleware::new(store),+ tinyagents_harness_tools::todos::TodoSequenceMiddleware::new(store),));}_ => tracing::debug!(diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rsindex 9b77423621..1536080c3d 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rs@@ -5,11 +5,12 @@ use super::*;use crate::agent::tinyagents::TurnModelSource;use crate::inference::turn_models::TurnModels;use async_trait::async_trait;+use tinyagents_harness::tool::ToolSnapshot;use tinyagents_harness::turn_policy::{DEFAULT_MODEL_CALL_TIMEOUT_SECS, LOCAL_MODEL_CALL_TIMEOUT_SECS,};use tinyagents_runtime::turn_driver::{SharedToolSet, TurnControls, TurnDriver};-use tinyagents_runtime::{DriverRequest, ToolSnapshot};+use tinyagents_runtime::DriverRequest;use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};use tinytools::{Tool, ToolResult};diff --git a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rsindex 4632efa8da..a51799f735 100644--- a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs@@ -22,8 +22,8 @@ use serde_json::json;use std::path::Path;use std::sync::Arc;use tinyagents_harness::context::RunConfig;-use tinyagents_harness::tool::packs::{PackRegistryHandle, UseSkillTool, USE_SKILL};use tinyagents_harness::CallId;+use tinyagents_harness_tools::skills::{PackRegistryHandle, UseSkillTool, USE_SKILL};use tinyinference_llm::message::Message;use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};use tinytools::{Tool, ToolCallOptions, ToolResult};@@ -154,7 +154,7 @@ fn build_use_skill_dispatch_with_target(let adapter = shared_tool_adapter(vec![durable.clone()],- tinyagents_harness::tool::packs::USE_SKILL,+ tinyagents_harness_tools::skills::USE_SKILL,).expect("use_skill resolves in the durable registry it was just placed in");let dispatch = dispatch_selector(vec![durable])(USE_SKILL, Arc::new(adapter) as Arc<dyn Tool>)diff --git a/crates/openhuman-core/src/agent/tools.rs b/crates/openhuman-core/src/agent/tools.rsindex 6342904a7b..fd9d05c7ac 100644--- a/crates/openhuman-core/src/agent/tools.rs+++ b/crates/openhuman-core/src/agent/tools.rs@@ -4,7 +4,7 @@//! memory, or the network. Wire names are//! given in parentheses where they differ from the type name://!-//! - `AskClarificationTool` (`ask_user_clarification`, from `tinyagents_harness::tools`) — returns the+//! - `AskClarificationTool` (`ask_user_clarification`, from `tinyagents_harness_tools`) — returns the//! question as its output; the turn actually pauses only because callers//! list this name in the harness seam's `early_exit_tools`.//! - [`DelegateTool`] — hands a subtask to a named agent with its own@@ -25,8 +25,10 @@ pub(crate) mod plan_exit;// with the `skills` gate so the tool list OMITS these rather than degrading// them to a disabled-error.mod todo;+mod wait;pub use plan_exit::PlanExitTool;-pub const PLAN_EXIT_MARKER: &str = tinyagents_harness::tool::plan_exit::PLAN_EXIT_MARKER;+pub const PLAN_EXIT_MARKER: &str = tinyagents_harness_tools::PLAN_EXIT_MARKER;pub use todo::TodoTool;pub(crate) use todo::TodoToolDispatch;+pub use wait::{WaitLoopTool, WaitTool};diff --git a/crates/openhuman-core/src/agent/tools/README.md b/crates/openhuman-core/src/agent/tools/README.mdindex 85aecc3da7..1c8ed63c0b 100644--- a/crates/openhuman-core/src/agent/tools/README.md+++ b/crates/openhuman-core/src/agent/tools/README.md@@ -10,7 +10,7 @@ crate should construct them directly.| Tool | File | Wire name (if different) || --- | --- | --- |-| `AskClarificationTool` | `tinyagents_harness::tools` | `ask_user_clarification` |+| `AskClarificationTool` | `tinyagents_harness_tools` | `ask_user_clarification` || `DelegateTool` | [`delegate.rs`](./delegate.rs) | `delegate` || `PlanExitTool` | [`plan_exit.rs`](./plan_exit.rs) | `plan_exit` || `RememberPreferenceTool` | `remember_preference.rs` | `remember_preference` |@@ -55,7 +55,7 @@ instead of registering them as disabled.- `crate::agent::orchestration` for the sub-agent spawn tools, which sit nextto these conceptually but live separately because they carry morelifecycle state.-- `tinyagents_graph::todos` for the todo store and tool behavior.+- `tinyagents_harness_tools::todos` for the todo store and tool behavior.## Further readingdiff --git a/crates/openhuman-core/src/agent/tools/plan_exit.rs b/crates/openhuman-core/src/agent/tools/plan_exit.rsindex 0238930736..e7cb7e96db 100644--- a/crates/openhuman-core/src/agent/tools/plan_exit.rs+++ b/crates/openhuman-core/src/agent/tools/plan_exit.rs@@ -25,8 +25,8 @@ fn mode_lookup(context: &dyn ToolRunContext) -> Option<RunModeHandle> {))}-fn owner_tool() -> tinyagents_harness::tool::plan_exit::PlanExitTool {- tinyagents_harness::tool::plan_exit::PlanExitTool::new(Arc::new(mode_lookup))+fn owner_tool() -> tinyagents_harness_tools::PlanExitTool {+ tinyagents_harness_tools::PlanExitTool::new(Arc::new(mode_lookup))}/// Public unit-shaped compatibility adapter around TinyAgents' tool engine.@@ -47,11 +47,11 @@ impl Default for PlanExitTool {#[async_trait]impl Tool for PlanExitTool {fn name(&self) -> &str {- tinyagents_harness::tool::plan_exit::PlanExitTool::NAME+ tinyagents_harness_tools::PlanExitTool::NAME}fn description(&self) -> &str {- tinyagents_harness::tool::plan_exit::PlanExitTool::DESCRIPTION+ tinyagents_harness_tools::PlanExitTool::DESCRIPTION}fn parameters_schema(&self) -> Value {diff --git a/crates/openhuman-core/src/agent/tools/todo.rs b/crates/openhuman-core/src/agent/tools/todo.rsindex be670b7553..6293186769 100644--- a/crates/openhuman-core/src/agent/tools/todo.rs+++ b/crates/openhuman-core/src/agent/tools/todo.rs@@ -21,13 +21,13 @@ use crate::agent::harness::fork_context::ParentExecutionContext;use async_trait::async_trait;use std::path::PathBuf;use std::sync::Arc;-use tinyagents_graph::todos::{self as graph_todos, store as todos_store};use tinyagents_harness::context::RunContext;use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};+use tinyagents_harness_tools::todos::{self as harness_todos, store as todos_store};use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};pub struct TodoTool {- inner: graph_todos::TodoTool,+ inner: harness_todos::TodoTool,workspace_dir: PathBuf,}@@ -123,7 +123,7 @@ impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Timpl TodoTool {pub fn new(workspace_dir: PathBuf) -> Self {Self {- inner: graph_todos::TodoTool::new(+ inner: harness_todos::TodoTool::new(crate::storage::sessions::stores_or_ephemeral(&workspace_dir).kv,),workspace_dir,@@ -198,22 +198,21 @@ impl TodoTool {.await}- /// If `scope`'s list is empty and `legacy_key` has a non-empty one,+ /// If `scope` has no stored list and `legacy_key` has a non-empty one,/// copy it forward under `scope`'s key so the rekey is transparent to an- /// in-flight session. Best-effort: any store error is logged and- /// swallowed — a failed migration just means the tool starts from an- /// empty list, same as any other first `todo` call.+ /// in-flight session. A persisted empty list is authoritative too: it+ /// records that the user cleared the migrated list and must not be treated+ /// as an absent target. Best-effort: store errors are logged and swallowed;+ /// the legacy value remains untouched unless the copy succeeds.async fn migrate_legacy_list_if_absent(&self, scope: &TodoScope, legacy_key: &str) {let store = crate::storage::sessions::stores_or_ephemeral(&self.workspace_dir).kv;- let current = match todos_store::list(&store, scope.key()).await {- Ok(snapshot) => snapshot,+ match todos_store::get(&store, scope.key()).await {+ Ok(Some(_)) => return,+ Ok(None) => {}Err(e) => {tracing::debug!(error = %e, "[tool][todo] legacy-migration: current list read failed");return;}- };- if !current.items.is_empty() {- return;}match todos_store::list(&store, legacy_key).await {Ok(legacy) if !legacy.items.is_empty() => {diff --git a/crates/openhuman-core/src/agent/tools/todo_tests.rs b/crates/openhuman-core/src/agent/tools/todo_tests.rsindex 208096300a..0c49cc062a 100644--- a/crates/openhuman-core/src/agent/tools/todo_tests.rs+++ b/crates/openhuman-core/src/agent/tools/todo_tests.rs@@ -1,6 +1,6 @@use super::*;use serde_json::{json, Value};-use tinyagents_graph::todos::{TodoItem, TodoStatus};+use tinyagents_harness_tools::todos::{TodoItem, TodoStatus};/// Serialize tests that share the process-global scratch store. Same lock/// process-global scratch store.@@ -30,7 +30,7 @@ fn test_workspace() -> std::path::PathBuf {}async fn reset_scratch(workspace_dir: &std::path::Path) {- tinyagents_graph::todos::store::clear(&todo_store(workspace_dir), "_scratch_")+ tinyagents_harness_tools::todos::store::clear(&todo_store(workspace_dir), "_scratch_").await.expect("clear scratch");}@@ -228,7 +228,7 @@ async fn a_legacy_session_keyed_list_is_migrated_forward_once() {id: parent.session_id.clone(),};let item = TodoItem::with_status("carried over", TodoStatus::InProgress);- tinyagents_graph::todos::store::replace(+ tinyagents_harness_tools::todos::store::replace(&todo_store(&workspace_dir),legacy_scope.key(),vec![item],@@ -240,7 +240,7 @@ async fn a_legacy_session_keyed_list_is_migrated_forward_once() {let read = tool.execute_with_parent_context(json!({}),- Some(parent),+ Some(parent.clone()),Some(&ThreadContext("thread-legacy")),).await@@ -254,11 +254,42 @@ async fn a_legacy_session_keyed_list_is_migrated_forward_once() {let thread_scope = TodoScope::Session {id: "thread-legacy".into(),};- let migrated =- tinyagents_graph::todos::store::list(&todo_store(&workspace_dir), thread_scope.key())- .await- .unwrap();+ let migrated = tinyagents_harness_tools::todos::store::list(+ &todo_store(&workspace_dir),+ thread_scope.key(),+ )+ .await+ .unwrap();assert_eq!(migrated.items.len(), 1);++ // Clearing the new thread-keyed list must remain authoritative. The empty+ // list is persisted, so a later read must not treat it as an absent target+ // and copy the still-present legacy row back into it.+ let cleared = tool+ .execute_with_parent_context(+ json!({ "todos": [] }),+ Some(parent.clone()),+ Some(&ThreadContext("thread-legacy")),+ )+ .await+ .unwrap();+ assert!(payload(&cleared)["todos"].as_array().unwrap().is_empty());++ let read_after_clear = tool+ .execute_with_parent_context(+ json!({}),+ Some(parent),+ Some(&ThreadContext("thread-legacy")),+ )+ .await+ .unwrap();+ assert!(+ payload(&read_after_clear)["todos"]+ .as_array()+ .unwrap()+ .is_empty(),+ "a cleared migrated list must not be resurrected from the legacy key"+ );}#[tokio::test]@@ -270,21 +301,26 @@ async fn sessions_do_not_see_each_other_and_a_list_survives_across_turns() {let b = TodoScope::Session {id: "sess-b".into(),};- tinyagents_graph::todos::store::clear(&todo_store(&workspace_dir), a.key())+ tinyagents_harness_tools::todos::store::clear(&todo_store(&workspace_dir), a.key()).await.unwrap();- tinyagents_graph::todos::store::clear(&todo_store(&workspace_dir), b.key())+ tinyagents_harness_tools::todos::store::clear(&todo_store(&workspace_dir), b.key()).await.unwrap();let item = TodoItem::with_status("only in a", TodoStatus::InProgress);- tinyagents_graph::todos::store::replace(&todo_store(&workspace_dir), a.key(), vec![item])- .await- .unwrap();+ tinyagents_harness_tools::todos::store::replace(+ &todo_store(&workspace_dir),+ a.key(),+ vec![item],+ )+ .await+ .unwrap();- let a_again = tinyagents_graph::todos::store::list(&todo_store(&workspace_dir), a.key())- .await- .unwrap();+ let a_again =+ tinyagents_harness_tools::todos::store::list(&todo_store(&workspace_dir), a.key())+ .await+ .unwrap();assert_eq!(a_again.items.len(),1,@@ -292,7 +328,7 @@ async fn sessions_do_not_see_each_other_and_a_list_survives_across_turns() {);assert_eq!(a_again.thread_id, "sess-a");assert!(- tinyagents_graph::todos::store::list(&todo_store(&workspace_dir), b.key())+ tinyagents_harness_tools::todos::store::list(&todo_store(&workspace_dir), b.key()).await.unwrap().itemsdiff --git a/crates/openhuman-core/src/agent/tools/wait.rs b/crates/openhuman-core/src/agent/tools/wait.rsnew file mode 100644index 0000000000..fc107e010d--- /dev/null+++ b/crates/openhuman-core/src/agent/tools/wait.rs@@ -0,0 +1,302 @@+//! Tool: `wait` / `wait_loop` - delayed callback ticks for the orchestrator.+//!+//! These tools intentionally do not own scheduling state. They sleep for a+//! bounded duration, then return the caller-provided message as a tool result so+//! the orchestrator can decide whether to act, poll async sub-agents, or call the+//! loop variant again.++use std::time::Duration;++use async_trait::async_trait;+use serde_json::json;+use tinytools::{PermissionLevel, Tool, ToolResult, ToolTimeout};++const DEFAULT_DURATION_SECS: u64 = 5;+const MAX_DURATION_SECS: u64 = 600;+const MILLIS_PER_SEC: u64 = 1_000;++/// One-shot delayed callback tool for the orchestrator.+pub struct WaitTool;+/// Repeatable delayed callback tool for orchestrator-controlled polling loops.+pub struct WaitLoopTool;++impl WaitTool {+ pub fn new() -> Self {+ Self+ }+}++impl Default for WaitTool {+ fn default() -> Self {+ Self::new()+ }+}++impl WaitLoopTool {+ pub fn new() -> Self {+ Self+ }+}++impl Default for WaitLoopTool {+ fn default() -> Self {+ Self::new()+ }+}++#[async_trait]+impl Tool for WaitTool {+ fn name(&self) -> &str {+ "wait"+ }++ fn description(&self) -> &str {+ "Wait for a bounded duration, then return the provided callback message \+ to the orchestrator. Use this to create a delayed tick before checking \+ async work or retrying a condition."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ wait_schema(false)+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Execute+ }++ fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {+ timeout_policy_for_wait(args)+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ execute_wait(args, false).await+ }+}++#[async_trait]+impl Tool for WaitLoopTool {+ fn name(&self) -> &str {+ "wait_loop"+ }++ fn description(&self) -> &str {+ "Wait for a bounded duration, then return the same callback message plus \+ a ready-to-call wait_loop instruction. Use this for deliberate polling \+ loops where the orchestrator decides after each tick whether to repeat."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ wait_schema(true)+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Execute+ }++ fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {+ timeout_policy_for_wait(args)+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ execute_wait(args, true).await+ }+}++/// Sleep for the requested duration, then return the callback tick payload.+async fn execute_wait(args: serde_json::Value, loop_mode: bool) -> anyhow::Result<ToolResult> {+ let request = match parse_wait_request(&args) {+ Ok(request) => request,+ Err(message) => return Ok(ToolResult::error(message)),+ };+ let tool_name = if loop_mode { "wait_loop" } else { "wait" };+ tracing::info!(+ "[wait] tool={} duration_ms={} iteration={} loop_key={} message_chars={}",+ tool_name,+ request.duration_ms,+ request.iteration,+ request.loop_key.as_deref().unwrap_or("none"),+ request.message.chars().count()+ );++ tokio::time::sleep(Duration::from_millis(request.duration_ms)).await;++ tracing::debug!(+ "[wait] elapsed tool={} duration_ms={} iteration={} loop_key={}",+ tool_name,+ request.duration_ms,+ request.iteration,+ request.loop_key.as_deref().unwrap_or("none")+ );++ Ok(ToolResult::success(format_wait_tick(&request, loop_mode)))+}++/// Build the JSON schema shared by `wait` and `wait_loop`.+fn wait_schema(loop_mode: bool) -> serde_json::Value {+ let mut properties = serde_json::Map::new();+ properties.insert(+ "message".to_string(),+ json!({+ "type": "string",+ "description": "Callback message to return to the orchestrator after the wait elapses."+ }),+ );+ properties.insert(+ "duration_secs".to_string(),+ json!({+ "type": "integer",+ "minimum": 1,+ "maximum": MAX_DURATION_SECS,+ "description": "Seconds to wait before returning the callback. Default 5. Ignored when duration_ms is supplied."+ }),+ );+ properties.insert(+ "duration_ms".to_string(),+ json!({+ "type": "integer",+ "minimum": 1,+ "maximum": MAX_DURATION_SECS * MILLIS_PER_SEC,+ "description": "Milliseconds to wait before returning the callback. Use only for short test-sized waits."+ }),+ );++ if loop_mode {+ properties.insert(+ "loop_key".to_string(),+ json!({+ "type": "string",+ "description": "Optional caller-defined key for the polling loop."+ }),+ );+ properties.insert(+ "iteration".to_string(),+ json!({+ "type": "integer",+ "minimum": 1,+ "description": "Current loop iteration. Defaults to 1; the returned instruction increments it."+ }),+ );+ }++ json!({+ "type": "object",+ "required": ["message"],+ "properties": serde_json::Value::Object(properties)+ })+}++/// Give the harness a deadline that covers the requested wait plus grace.+fn timeout_policy_for_wait(args: &serde_json::Value) -> ToolTimeout {+ let duration_ms = duration_ms_from_args(args).unwrap_or(DEFAULT_DURATION_SECS * MILLIS_PER_SEC);+ let rounded_secs = duration_ms.saturating_add(MILLIS_PER_SEC - 1) / MILLIS_PER_SEC;+ ToolTimeout::Millis(+ rounded_secs+ .saturating_add(1)+ .saturating_mul(MILLIS_PER_SEC),+ )+}++/// Extract and clamp the caller's requested wait duration in milliseconds.+fn duration_ms_from_args(args: &serde_json::Value) -> Option<u64> {+ if let Some(duration_ms) = args.get("duration_ms").and_then(|v| v.as_u64()) {+ return Some(duration_ms.clamp(1, MAX_DURATION_SECS * MILLIS_PER_SEC));+ }+ args.get("duration_secs")+ .and_then(|v| v.as_u64())+ .map(|secs| secs.clamp(1, MAX_DURATION_SECS) * MILLIS_PER_SEC)+}++/// Validate tool arguments and normalize them into an internal request.+fn parse_wait_request(args: &serde_json::Value) -> Result<WaitRequest, String> {+ let message = args+ .get("message")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .trim()+ .to_string();+ if message.is_empty() {+ return Err("wait: `message` is required".to_string());+ }++ let duration_ms = duration_ms_from_args(args).unwrap_or(DEFAULT_DURATION_SECS * MILLIS_PER_SEC);+ let iteration = args+ .get("iteration")+ .and_then(|v| v.as_u64())+ .unwrap_or(1)+ .max(1);+ let loop_key = args+ .get("loop_key")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string);++ Ok(WaitRequest {+ message,+ duration_ms,+ iteration,+ loop_key,+ })+}++/// Render the delayed callback as prose plus a machine-readable `[wait_tick]`.+fn format_wait_tick(request: &WaitRequest, loop_mode: bool) -> String {+ let seconds = request.duration_ms as f64 / MILLIS_PER_SEC as f64;+ let loop_instruction = loop_mode.then(|| {+ let mut arguments = json!({+ "message": request.message,+ "duration_ms": request.duration_ms,+ "iteration": request.iteration.saturating_add(1)+ });+ // The schema allows `loop_key` only as a string: omit it rather than+ // hand back a ready-to-call instruction carrying `null`.+ if let Some(loop_key) = &request.loop_key {+ arguments["loop_key"] = json!(loop_key);+ }+ json!({ "tool": "wait_loop", "arguments": arguments })+ });+ let payload = json!({+ "status": "elapsed",+ "message": request.message,+ "duration_ms": request.duration_ms,+ "durationMs": request.duration_ms,+ "duration_secs": seconds,+ "durationSecs": seconds,+ "loop": loop_mode,+ "loop_key": request.loop_key,+ "loopKey": request.loop_key,+ "iteration": request.iteration,+ "instructions": {+ "callback_message": request.message,+ "repeat": loop_instruction+ }+ });++ let prefix = if loop_mode {+ format!(+ "Loop tick {} elapsed after {}ms.",+ request.iteration, request.duration_ms+ )+ } else {+ format!("Wait elapsed after {}ms.", request.duration_ms)+ };++ format!(+ "{prefix}\n\n[wait_tick]\n{}\n[/wait_tick]\n\n{}",+ serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string()),+ request.message+ )+}++#[derive(Debug)]+/// Normalized wait arguments used by both wait tools.+struct WaitRequest {+ message: String,+ duration_ms: u64,+ iteration: u64,+ loop_key: Option<String>,+}++#[cfg(test)]+#[path = "wait_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tools/wait_tests.rs b/crates/openhuman-core/src/agent/tools/wait_tests.rsnew file mode 100644index 0000000000..434bb81f08--- /dev/null+++ b/crates/openhuman-core/src/agent/tools/wait_tests.rs@@ -0,0 +1,121 @@+use super::*;++#[test]+fn wait_schema_requires_message() {+ let schema = WaitTool::new().parameters_schema();+ let required = schema+ .get("required")+ .and_then(|v| v.as_array())+ .expect("required list");+ assert!(required.iter().any(|v| v.as_str() == Some("message")));+ assert!(schema["properties"].get("duration_secs").is_some());+ assert!(schema["properties"].get("duration_ms").is_some());+}++#[test]+fn wait_loop_schema_includes_loop_controls() {+ let schema = WaitLoopTool::new().parameters_schema();+ assert!(schema["properties"].get("loop_key").is_some());+ assert!(schema["properties"].get("iteration").is_some());+}++#[test]+fn parse_wait_request_clamps_duration_and_iteration() {+ let request = parse_wait_request(&json!({+ "message": "check subagents",+ "duration_secs": 9999,+ "iteration": 0+ }))+ .unwrap();+ assert_eq!(request.duration_ms, MAX_DURATION_SECS * MILLIS_PER_SEC);+ assert_eq!(request.iteration, 1);+}++#[test]+fn missing_message_is_rejected() {+ let err = parse_wait_request(&json!({ "duration_secs": 1 })).unwrap_err();+ assert!(err.contains("message"));+}++#[test]+fn wait_loop_tick_repeats_same_message() {+ let request = parse_wait_request(&json!({+ "message": "poll async workers",+ "duration_ms": 10,+ "loop_key": "workers",+ "iteration": 2+ }))+ .unwrap();+ let output = format_wait_tick(&request, true);++ assert!(output.contains("Loop tick 2 elapsed"));+ assert!(output.contains("\"tool\":\"wait_loop\""));+ assert!(output.contains("\"message\":\"poll async workers\""));+ assert!(output.contains("\"iteration\":3"));+}++#[test]+fn wait_loop_tick_at_max_iteration_does_not_overflow() {+ let request = parse_wait_request(&json!({+ "message": "poll",+ "duration_ms": 10,+ "iteration": u64::MAX+ }))+ .unwrap();+ let output = format_wait_tick(&request, true);+ assert!(output.contains(&format!("\"iteration\":{}", u64::MAX)));+}++#[test]+fn wait_loop_tick_omits_an_absent_loop_key() {+ let request = parse_wait_request(&json!({ "message": "poll", "duration_ms": 10 })).unwrap();+ let output = format_wait_tick(&request, true);+ let json = output+ .split("[wait_tick]\n")+ .nth(1)+ .and_then(|rest| rest.split("\n[/wait_tick]").next())+ .expect("wait_tick payload");+ let payload: serde_json::Value = serde_json::from_str(json).unwrap();+ let arguments = &payload["instructions"]["repeat"]["arguments"];+ assert!(arguments.is_object());+ assert!(+ arguments.get("loop_key").is_none(),+ "the repeat call must not carry a null loop_key: {arguments}"+ );+}++#[tokio::test]+async fn wait_execute_returns_callback_message() {+ let res = WaitTool::new()+ .execute(json!({+ "message": "time to check",+ "duration_ms": 1+ }))+ .await+ .unwrap();+ assert!(!res.is_error);+ assert!(res.output().contains("[wait_tick]"));+ assert!(res.output().contains("time to check"));+}++/// Wire shape is a contract with prompts and recorded transcripts: names and+/// schemas must stay byte-identical across moves.+#[test]+fn wire_schemas_are_stable() {+ assert_eq!(WaitTool::new().name(), "wait");+ assert_eq!(WaitLoopTool::new().name(), "wait_loop");+ let base = json!({+ "type": "object",+ "required": ["message"],+ "properties": {+ "message": {"type": "string", "description": "Callback message to return to the orchestrator after the wait elapses."},+ "duration_secs": {"type": "integer", "minimum": 1, "maximum": 600, "description": "Seconds to wait before returning the callback. Default 5. Ignored when duration_ms is supplied."},+ "duration_ms": {"type": "integer", "minimum": 1, "maximum": 600000, "description": "Milliseconds to wait before returning the callback. Use only for short test-sized waits."}+ }+ });+ assert_eq!(WaitTool::new().parameters_schema(), base);+ let mut looped = base.clone();+ looped["properties"]["loop_key"] = json!({"type": "string", "description": "Optional caller-defined key for the polling loop."});+ looped["properties"]["iteration"] = json!({"type": "integer", "minimum": 1, "description": "Current loop iteration. Defaults to 1; the returned instruction increments it."});+ assert_eq!(WaitLoopTool::new().parameters_schema(), looped);+}diff --git a/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs b/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rsindex 3596c2ddc3..3f76afb45a 100644--- a/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs+++ b/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs@@ -170,7 +170,7 @@ fn on_belt(def: &AgentDefinition, tool: &str) -> bool {/// whenever the pack table withheld something (`strip_packed_from_visible`).fn can_call(def: &AgentDefinition, tool: &str, universe: &BTreeSet<String>) -> bool {use crate::tools::toolpacks::ops::is_withheld_from;- if tool == tinyagents_harness::tool::packs::USE_SKILL {+ if tool == tinyagents_harness_tools::skills::USE_SKILL {return universe.iter().any(|n| on_belt(def, n) && is_withheld_from(&def.id, n));diff --git a/crates/openhuman-core/src/agent_registry/agents/orchestrator/prompt.rs b/crates/openhuman-core/src/agent_registry/agents/orchestrator/prompt.rsindex 96dc461d58..a1716e32a5 100644--- a/crates/openhuman-core/src/agent_registry/agents/orchestrator/prompt.rs+++ b/crates/openhuman-core/src/agent_registry/agents/orchestrator/prompt.rs@@ -39,7 +39,7 @@ pub fn build(ctx: &PromptContext<'_>) -> Result<String> {// A packed install route is already named under "Capabilities not in your// tool list"; the skills section names it only when it is on the belt.let skill_install = hand_off_route(ctx, "skill_setup")- .filter(|route| !route.contains(tinyagents_harness::tool::packs::USE_SKILL));+ .filter(|route| !route.contains(tinyagents_harness_tools::skills::USE_SKILL));// An empty visibility set is the builder's unfiltered sentinel. Preserve// the MCP route for those sessions while suppressing it in gated-off builds.// Registered is enough: the orchestrator defers the registry tools@@ -258,7 +258,7 @@ fn hand_off_route(ctx: &PromptContext<'_>, specialist: &str) -> Option<String> {// tool you do not have" failure this whole block exists to end (#6302).if !ctx.visible_tool_names- .contains(tinyagents_harness::tool::packs::USE_SKILL)+ .contains(tinyagents_harness_tools::skills::USE_SKILL){return None;}@@ -281,7 +281,7 @@ fn run_workflow_route(ctx: &PromptContext<'_>) -> Option<String> {// which case the policy gate would refuse the call this names.if !ctx.visible_tool_names- .contains(tinyagents_harness::tool::packs::USE_SKILL)+ .contains(tinyagents_harness_tools::skills::USE_SKILL)|| !belt_lists(ctx, RUN_WORKFLOW){return None;diff --git a/crates/openhuman-core/src/channels/commands.rs b/crates/openhuman-core/src/channels/commands.rsindex 3ad9eb378d..045abad104 100644--- a/crates/openhuman-core/src/channels/commands.rs+++ b/crates/openhuman-core/src/channels/commands.rs@@ -1,87 +1,6 @@-//! `doctor channels`: health checks for every configured real-time channel.-//!-//! OpenHuman hydrates credentials and applies its proxy policy. Provider-//! construction and bounded health checks execute in the TinyChannels module;-//! this adapter formats the observations.+//! Select configured listeners for startup orchestration and native doctor checks.-use super::runtime::hydrate_channel_credentials;use crate::config::Config;-use anyhow::Result;-use std::time::Duration;-use tinychannels_bus::{ChannelHealthState, HttpProxyPolicy};--/// Display label for a channel id (`telegram` → `Telegram`).-fn channel_label(channel: &str) -> String {- tinychannels_bus::controllers::find_channel_definition(channel)- .map(|definition| definition.display_name.to_string())- .unwrap_or_else(|| channel.to_string())-}--/// One report line for a channel's health state.-fn report_line(label: &str, state: ChannelHealthState) -> String {- match state {- ChannelHealthState::Healthy => format!(" ✅ {label:<9} healthy"),- ChannelHealthState::Unhealthy => format!(" ❌ {label:<9} unhealthy (auth/config/network)"),- ChannelHealthState::Timeout => format!(" ⏱️ {label:<9} timed out (>10s)"),- }-}--/// Run health checks for configured channels.-pub async fn doctor_channels(config: Config) -> Result<()> {- let configured = configured_providers(&config);- if configured.is_empty() {- println!("No real-time channels configured. Configure channels in the web UI.");- return Ok(());- }- let selectors = configured- .iter()- .map(|channel| format!("channel.{channel}"))- .filter(|service| config.proxy.should_apply_to_service(service))- .collect::<Vec<_>>();- let proxy = if selectors.is_empty() {- HttpProxyPolicy::default()- } else {- HttpProxyPolicy {- http_proxy: config.proxy.http_proxy.clone(),- https_proxy: config.proxy.https_proxy.clone(),- all_proxy: config.proxy.all_proxy.clone(),- no_proxy: config.proxy.normalized_no_proxy(),- service_selectors: selectors,- }- };- let client = crate::modules::client(config.clone())- .with_timeout(Duration::from_secs(configured.len() as u64 * 10 + 5));- let channels =- crate::modules::channel_health::check(&client, hydrate_channel_credentials(&config), proxy)- .await?;-- if channels.is_empty() {- println!("No real-time channels configured. Configure channels in the web UI.");- return Ok(());- }-- println!("🩺 OpenHuman Channel Doctor");- println!();-- let (mut healthy, mut unhealthy, mut timeout) = (0_u32, 0_u32, 0_u32);- for report in channels {- let state = report.state;- match state {- ChannelHealthState::Healthy => healthy += 1,- ChannelHealthState::Unhealthy => unhealthy += 1,- ChannelHealthState::Timeout => timeout += 1,- }- println!("{}", report_line(&channel_label(&report.channel), state));- }-- if config.channels_config.webhook.is_some() {- println!(" ℹ️ Webhook ensure your webhook endpoint is reachable");- }-- println!();- println!("Summary: {healthy} healthy, {unhealthy} unhealthy, {timeout} timed out");- Ok(())-}/// Selecting configured providers is host configuration orchestration. The/// module owns construction, platform support, health I/O and timeout handling.diff --git a/crates/openhuman-core/src/channels/commands_tests.rs b/crates/openhuman-core/src/channels/commands_tests.rsindex d71c1c33db..ab2b61cc66 100644--- a/crates/openhuman-core/src/channels/commands_tests.rs+++ b/crates/openhuman-core/src/channels/commands_tests.rs@@ -1,44 +1,32 @@use super::*;#[test]-fn report_lines_cover_every_state() {- assert_eq!(- report_line("Telegram", ChannelHealthState::Healthy),- " ✅ Telegram healthy"- );- assert!(report_line("Slack", ChannelHealthState::Unhealthy).contains("unhealthy"));- assert!(report_line("Slack", ChannelHealthState::Timeout).contains("timed out"));-}--#[test]-fn channel_labels_use_definition_display_names() {- assert_eq!(channel_label("telegram"), "Telegram");- assert_eq!(channel_label("not-a-channel"), "not-a-channel");-}--#[tokio::test]-async fn doctor_with_no_channels_is_ok() {- doctor_channels(Config::default()).await.unwrap();-}--#[tokio::test]-async fn doctor_with_configured_provider_requires_the_module() {+fn provider_selection_ignores_cli_and_relay_only_configuration() {let mut config = Config::default();- config.modules.enabled = false;+ config.channels_config.relay = Some(Default::default());+ assert!(configured_providers(&config).is_empty());config.channels_config.imessage = Some(tinychannels_bus::config::IMessageConfig {allowed_contacts: vec![],});- let error = doctor_channels(config).await.unwrap_err();- assert!(error.to_string().contains("module unavailable"), "{error}");+ assert_eq!(configured_providers(&config), vec!["imessage"]);}#[test]-fn doctor_provider_selection_ignores_cli_and_relay_only_configuration() {+fn listener_configuration_includes_channels_and_nonempty_relays_but_not_push_webhooks() {let mut config = Config::default();- config.channels_config.relay = Some(Default::default());- assert!(configured_providers(&config).is_empty());- config.channels_config.imessage = Some(tinychannels_bus::config::IMessageConfig {- allowed_contacts: vec![],+ config.channels_config.webhook = Some(tinychannels_bus::config::WebhookConfig {+ port: 0,+ secret: None,});- assert_eq!(configured_providers(&config), vec!["imessage"]);+ assert!(!has_listener_configuration(&config));++ config.channels_config.relay = Some(tinychannels_bus::config::RelayRuntimeConfig {+ url: "https://relay.example.invalid".into(),+ identities: vec![tinychannels_bus::config::RelayRuntimeIdentityConfig {+ platform: "discord".into(),+ bot_id: "doctor-test-bot".into(),+ }],+ ..Default::default()+ });+ assert!(has_listener_configuration(&config));}diff --git a/crates/openhuman-core/src/channels/credentials.rs b/crates/openhuman-core/src/channels/credentials.rsindex 40ea74140e..b9510c9e7d 100644--- a/crates/openhuman-core/src/channels/credentials.rs+++ b/crates/openhuman-core/src/channels/credentials.rs@@ -48,3 +48,52 @@ pub(crate) fn resolve_email_password(}email_cfg}++/// Read the email password for doctor inspection without opening the mutable+/// auth-profile store or probing the OS keychain.+pub(crate) fn resolve_email_password_read_only(+ mut email_cfg: tinychannels_bus::config::EmailConfig,+ config: &Config,+) -> tinychannels_bus::config::EmailConfig {+ if !email_cfg.password.is_empty() {+ return email_cfg;+ }+ let provider = crate::security::credentials::channel_credential_provider(+ "email",+ tinychannels_bus::controllers::ChannelAuthMode::ApiKey,+ );+ if let Ok(Some(profile)) =+ crate::security::credentials::AuthService::get_profile_read_only(config, &provider, None)+ {+ if profile.metadata.get("username").map(String::as_str) == Some(email_cfg.username.as_str())+ {+ if let Some(password) = profile.metadata.get("password") {+ email_cfg.password = password.clone();+ }+ }+ }+ email_cfg+}++/// Fill Yuanbao's app secret for doctor health inspection using only the+/// selected config's read-only credential snapshot.+pub(crate) fn resolve_yuanbao_app_secret_read_only(+ mut yb_cfg: tinychannels_bus::config::YuanbaoConfig,+ config: &Config,+) -> tinychannels_bus::config::YuanbaoConfig {+ if !yb_cfg.app_secret.is_empty() {+ return yb_cfg;+ }+ if let Ok(Some(profile)) = crate::security::credentials::AuthService::get_profile_read_only(+ config,+ "channel:yuanbao:api_key",+ None,+ ) {+ if profile.metadata.get("app_key").map(String::as_str) == Some(yb_cfg.app_key.as_str()) {+ if let Some(secret) = profile.metadata.get("app_secret") {+ yb_cfg.app_secret = secret.clone();+ }+ }+ }+ yb_cfg+}diff --git a/crates/openhuman-core/src/channels/mod.rs b/crates/openhuman-core/src/channels/mod.rsindex a132d16093..338508cb7a 100644--- a/crates/openhuman-core/src/channels/mod.rs+++ b/crates/openhuman-core/src/channels/mod.rs@@ -103,8 +103,6 @@ pub use yuanbao::YuanbaoChannel;#[cfg(all(feature = "channels", any(test, debug_assertions)))]pub use runtime::test_support;-#[cfg(feature = "channels")]-pub use commands::doctor_channels;#[cfg(feature = "channels")]// Channel system-prompt assembly lives in// `crate::channels::prompt` alongside the rest ofdiff --git a/crates/openhuman-core/src/channels/runtime/mod.rs b/crates/openhuman-core/src/channels/runtime/mod.rsindex 87b8ee69b1..5a500bef1b 100644--- a/crates/openhuman-core/src/channels/runtime/mod.rs+++ b/crates/openhuman-core/src/channels/runtime/mod.rs@@ -6,7 +6,6 @@ mod startup;#[cfg(test)]mod supervision;-pub(crate) use startup::hydrate_channel_credentials;pub(crate) use startup::prepare_runtime_limits;pub use startup::start_channels;pub(crate) use startup::start_channels_with_session;diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rsindex 2ddb66581a..4a2fb65c76 100644--- a/crates/openhuman-core/src/channels/runtime/startup.rs+++ b/crates/openhuman-core/src/channels/runtime/startup.rs@@ -50,7 +50,6 @@ pub(crate) async fn prepare_runtime_limits(}}-pub(crate) use credentials::hydrate_channel_credentials;pub use start_channels::start_channels;pub(crate) use start_channels::start_channels_with_session;pub(crate) use turn_parts::{build_channel_turn_parts, runtime_context, PromptToolDescs};diff --git a/crates/openhuman-core/src/config/README.md b/crates/openhuman-core/src/config/README.mdindex 3c9ea8f700..bf35f87f83 100644--- a/crates/openhuman-core/src/config/README.md+++ b/crates/openhuman-core/src/config/README.md@@ -108,7 +108,8 @@ process-global user's settings.Overrides are applied after parsing and never written back to disk.1. `Config::apply_env_overrides` ([`schema/load/env_overlay.rs`](./schema/load/env_overlay.rs) plus one submodule per section) reads- `OPENHUMAN_*` variables such as `OPENHUMAN_MODEL` and `OPENHUMAN_TOOL_DISPATCHER`. Only namespaced+ `OPENHUMAN_*` variables such as `OPENHUMAN_DEFAULT_MODEL` (with `OPENHUMAN_MODEL` kept as an alias)+ and `OPENHUMAN_TOOL_DISPATCHER`. Only namespacednames are honored. Tests call the pure `apply_env_overlay_with` with a map-backed `EnvLookup`([`schema/load/env.rs`](./schema/load/env.rs)) so they do not touch the process environment.2. The same call publishes process-wide state: the proxy settings go to `set_runtime_proxy_config`diff --git a/crates/openhuman-core/src/config/schema/cli_overrides/ops.rs b/crates/openhuman-core/src/config/schema/cli_overrides/ops.rsindex 975306f0b9..0d34d14334 100644--- a/crates/openhuman-core/src/config/schema/cli_overrides/ops.rs+++ b/crates/openhuman-core/src/config/schema/cli_overrides/ops.rs@@ -158,6 +158,9 @@ fn apply_overrides(config: &mut Config, overrides: &CliInferenceOverrides) {if provider_key == "openhuman" {if let Some(model) = model.as_ref() {config.default_model = Some(model.clone());+ config+ .load_provenance_mut()+ .record_cli_override("default_model");}}@@ -171,6 +174,15 @@ fn apply_overrides(config: &mut Config, overrides: &CliInferenceOverrides) {config.reasoning_provider = Some(route.clone());config.agentic_provider = Some(route.clone());config.coding_provider = Some(route);+ let provenance = config.load_provenance_mut();+ for field in [+ "chat_provider",+ "reasoning_provider",+ "agentic_provider",+ "coding_provider",+ ] {+ provenance.record_cli_override(field);+ }}fn split_provider_route(route: &str) -> (&str, Option<&str>) {diff --git a/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs b/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rsindex 1c7956c9f3..88bcc02794 100644--- a/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs+++ b/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs@@ -123,12 +123,30 @@ async fn reload_refreshes_the_snapshot_before_an_unrelated_save() {initial.config_path = config_path.clone();initial.workspace_dir = workspace_dir.clone();initial.chat_provider = Some("openai:old".into());+ initial.default_model = Some("file-default-model".into());initial.save().await.expect("save initial config");set_cli_inference_overrides(Some("ollama"), Some("qwen3:8b"));let mut first = Config::load_from_config_path(&config_path, &workspace_dir).await.expect("first load");+ assert_eq!(first.default_model.as_deref(), Some("file-default-model"));+ assert_eq!(+ first.load_provenance().field("default_model").source,+ crate::config::schema::load::ProvenanceSource::File+ );+ for field in [+ "chat_provider",+ "reasoning_provider",+ "agentic_provider",+ "coding_provider",+ ] {+ assert_eq!(+ first.load_provenance().field(field).source,+ crate::config::schema::load::ProvenanceSource::Cli,+ "CLI override should be recorded for {field}"+ );+ }first.chat_provider = Some("anthropic:explicit".into());first.save().await.expect("save explicit route change");diff --git a/crates/openhuman-core/src/config/schema/load/config_file_read.rs b/crates/openhuman-core/src/config/schema/load/config_file_read.rsindex f93ffa3b55..b016f95115 100644--- a/crates/openhuman-core/src/config/schema/load/config_file_read.rs+++ b/crates/openhuman-core/src/config/schema/load/config_file_read.rs@@ -4,6 +4,7 @@ use tokio::fs;use super::super::Config;use super::branches::default_config_boxed;+use super::{ConfigLoadFallback, ConfigParseError};pub(crate) async fn parse_config_with_recovery(config_path: &Path,@@ -18,7 +19,8 @@ pub(crate) async fn parse_config_with_recovery(/// pointer instead of an ~8 KB value per hop.pub(super) async fn parse_config_boxed(config_path: &Path, contents: &str) -> (Box<Config>, bool) {let parse_err = match parse_toml_off_worker(contents.to_string()).await {- Ok(config) => {+ Ok(mut config) => {+ config.load_diagnostics_mut().warn_unknown_keys_once();tracing::debug!(path = %config_path.display(),"[config] Config parsed successfully"@@ -27,6 +29,7 @@ pub(super) async fn parse_config_boxed(config_path: &Path, contents: &str) -> (B}Err(parse_err) => parse_err,};+ let parse_error = ConfigParseError::from_error(config_path.to_path_buf(), &parse_err);let backup_path = config_path.with_extension("toml.bak");if tokio::fs::try_exists(&backup_path).await.unwrap_or(false) {@@ -44,7 +47,12 @@ pub(super) async fn parse_config_boxed(config_path: &Path, contents: &str) -> (Bbackup = %backup_path.display(),"[config] Recovered config from backup");- return (bak_config, true);+ let mut config = *bak_config;+ let diagnostics = config.load_diagnostics_mut();+ diagnostics.parse_error = Some(parse_error);+ diagnostics.fallback = ConfigLoadFallback::Backup;+ diagnostics.warn_unknown_keys_once();+ return (Box::new(config), true);}Err(bak_err) => {tracing::warn!(@@ -72,7 +80,11 @@ pub(super) async fn parse_config_boxed(config_path: &Path, contents: &str) -> (B);}- (default_config_boxed(), true)+ let mut config = default_config_boxed();+ let diagnostics = config.load_diagnostics_mut();+ diagnostics.parse_error = Some(parse_error);+ diagnostics.fallback = ConfigLoadFallback::Defaults;+ (config, true)}/// Return the source text that should be inspected by migrations. A readable@@ -89,15 +101,17 @@ pub(super) async fn migration_source(config_path: &Path, contents: &str) -> Stri}}-pub(super) async fn parse_toml_off_worker(contents: String) -> Result<Box<Config>, String> {+pub(super) async fn parse_toml_off_worker(contents: String) -> Result<Box<Config>> {match tokio::task::spawn_blocking(move || {super::parse::config_from_toml_str(&contents).map(Box::new)}).await{Ok(Ok(config)) => Ok(config),- Ok(Err(parse_err)) => Err(parse_err.to_string()),- Err(join_err) => Err(format!("blocking-pool parse join failed: {join_err}")),+ Ok(Err(parse_error)) => Err(parse_error),+ Err(join_error) => {+ Err(anyhow::Error::new(join_error).context("blocking-pool config parser failed"))+ }}}diff --git a/crates/openhuman-core/src/config/schema/load/diagnostics.rs b/crates/openhuman-core/src/config/schema/load/diagnostics.rsnew file mode 100644index 0000000000..8c2a41fb40--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/diagnostics.rs@@ -0,0 +1,116 @@+//! Diagnostics collected while reading and migrating `config.toml`.++use std::path::PathBuf;++use super::super::Config;++/// Source used to recover after the configured file failed to parse.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub(crate) enum ConfigLoadFallback {+ /// The primary config parsed successfully, or no config existed.+ #[default]+ None,+ /// The primary config was invalid and its `.bak` file parsed successfully.+ Backup,+ /// Neither the primary config nor its backup could be used.+ Defaults,+}++/// The original config parse failure when the loader recovered from it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ConfigParseError {+ /// File whose contents failed to parse.+ pub(crate) path: PathBuf,+ /// Parse error including any TOML line or typed-field path.+ ///+ /// The parser's raw message can contain source context. Doctor findings+ /// should report a safe path/line/classification instead of copying this+ /// message verbatim.+ pub(crate) message: String,+ /// Safe dotted field path from the typed-deserialization error, if any.+ pub(crate) field_path: Option<String>,+ /// TOML syntax line, when the parser reports one.+ pub(crate) line: Option<usize>,+}++impl ConfigParseError {+ pub(crate) fn new(path: PathBuf, message: String) -> Self {+ Self {+ path,+ message,+ field_path: None,+ line: None,+ }+ }++ pub(crate) fn from_error(path: PathBuf, error: &anyhow::Error) -> Self {+ let typed = error.downcast_ref::<super::parse::ConfigParseFailure>();+ Self {+ path,+ message: error.to_string(),+ field_path: typed.and_then(|failure| failure.field_path.clone()),+ line: typed.and_then(|failure| failure.line),+ }+ }++ /// Operator-facing summary that excludes parser text and source values.+ pub(crate) fn safe_summary(&self) -> String {+ if let Some(field_path) = &self.field_path {+ format!("The config field `{field_path}` has an invalid value.")+ } else if let Some(line) = self.line {+ format!("The config file has invalid TOML syntax at line {line}.")+ } else {+ "The config file is invalid.".into()+ }+ }+}++/// Non-persisted information collected as a config is loaded.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct LoadDiagnostics {+ /// Dotted paths to keys not represented by the current config schema.+ pub(crate) unknown_keys: Vec<String>,+ /// Parse error that caused the loader to choose a fallback.+ pub(crate) parse_error: Option<ConfigParseError>,+ /// Fallback chosen after a parse failure.+ pub(crate) fallback: ConfigLoadFallback,+ /// Legacy config paths rewritten by an in-memory migration.+ pub(crate) migrated_keys: Vec<String>,+ unknown_keys_logged: bool,+}++impl LoadDiagnostics {+ pub(crate) fn warn_unknown_keys_once(&mut self) {+ if self.unknown_keys_logged || self.unknown_keys.is_empty() {+ return;+ }+ tracing::warn!(+ keys = %self.unknown_keys.join(","),+ "[config:load] unknown config keys ignored"+ );+ self.unknown_keys_logged = true;+ }++ pub(crate) fn record_migrated_key(&mut self, key: impl Into<String>) {+ let key = key.into();+ if !self.migrated_keys.contains(&key) {+ self.migrated_keys.push(key);+ }+ }+}++pub(super) fn record_non_utf8_recovery(+ config: &mut Config,+ path: &std::path::Path,+ fallback: ConfigLoadFallback,+) {+ let diagnostics = config.load_diagnostics_mut();+ if diagnostics.fallback != ConfigLoadFallback::None {+ return;+ }+ diagnostics.parse_error = Some(ConfigParseError::new(+ path.to_path_buf(),+ "config file could not be decoded as UTF-8".to_string(),+ ));+ diagnostics.fallback = fallback;+}diff --git a/crates/openhuman-core/src/config/schema/load/diagnostics_tests.rs b/crates/openhuman-core/src/config/schema/load/diagnostics_tests.rsnew file mode 100644index 0000000000..ca483c7ee6--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/diagnostics_tests.rs@@ -0,0 +1,104 @@+use super::*;++#[test]+fn parser_records_unknown_keys_with_their_full_path() {+ let config =+ config_from_toml_str("[memroy]\nengine = \"x\"\n[agent]\nmemroy = \"x\"\n").unwrap();++ assert_eq!(+ config.load_diagnostics().unknown_keys,+ ["agent.memroy", "memroy"]+ );+}++#[tokio::test]+async fn recovery_records_backup_source_and_original_parse_error() {+ let directory = tempfile::tempdir().unwrap();+ let config_path = directory.path().join("config.toml");+ let backup_path = directory.path().join("config.toml.bak");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).unwrap();+ std::fs::write(&config_path, "default_model = \"unterminated\n").unwrap();+ std::fs::write(&backup_path, "default_model = \"backup-model\"\n").unwrap();++ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .unwrap();++ let diagnostics = config.load_diagnostics();+ assert_eq!(diagnostics.fallback, ConfigLoadFallback::Backup);+ let parse_error = diagnostics.parse_error.as_ref().unwrap();+ assert_eq!(parse_error.path, config_path);+ assert!(+ parse_error.message.contains("line"),+ "{}",+ parse_error.message+ );+ assert_eq!(config.default_model.as_deref(), Some("backup-model"));+}++#[tokio::test]+async fn non_utf8_recovery_records_backup_source_and_config_path() {+ let directory = tempfile::tempdir().unwrap();+ let config_path = directory.path().join("config.toml");+ let backup_path = directory.path().join("config.toml.bak");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).unwrap();+ std::fs::write(&config_path, [0xff, 0xfe]).unwrap();+ std::fs::write(&backup_path, "default_model = \"backup-model\"\n").unwrap();++ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .unwrap();++ let diagnostics = config.load_diagnostics();+ assert_eq!(diagnostics.fallback, ConfigLoadFallback::Backup);+ let parse_error = diagnostics.parse_error.as_ref().unwrap();+ assert_eq!(parse_error.path, config_path);+ assert_eq!(+ parse_error.message,+ "config file could not be decoded as UTF-8"+ );+ assert_eq!(config.default_model.as_deref(), Some("backup-model"));+}++#[tokio::test]+async fn loader_records_legacy_inference_url_migration() {+ let directory = tempfile::tempdir().unwrap();+ let config_path = directory.path().join("config.toml");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).unwrap();+ std::fs::write(+ &config_path,+ "api_url = \"https://example.test/v1/chat/completions\"\n",+ )+ .unwrap();++ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .unwrap();++ assert!(config+ .load_diagnostics()+ .migrated_keys+ .iter()+ .any(|key| key == "api_url"));+ assert_eq!(+ config.inference_url.as_deref(),+ Some("https://example.test/v1/chat/completions")+ );+}++#[test]+fn default_config_has_empty_load_diagnostics() {+ let config = Config::default();++ assert!(config.load_diagnostics().unknown_keys.is_empty());+ assert!(config.load_diagnostics().parse_error.is_none());+ assert_eq!(config.load_diagnostics().fallback, ConfigLoadFallback::None);+ assert!(config.load_diagnostics().migrated_keys.is_empty());+ assert!(serde_json::to_value(&config)+ .unwrap()+ .get("load_diagnostics")+ .is_none());+}diff --git a/crates/openhuman-core/src/config/schema/load/dirs.rs b/crates/openhuman-core/src/config/schema/load/dirs.rsindex d756f1fb58..c95b98ffd8 100644--- a/crates/openhuman-core/src/config/schema/load/dirs.rs+++ b/crates/openhuman-core/src/config/schema/load/dirs.rs@@ -161,7 +161,7 @@ fn active_workspace_state_path(default_dir: &Path) -> PathBuf {default_dir.join(ACTIVE_WORKSPACE_STATE_FILE)}-async fn load_persisted_workspace_dirs(+pub(crate) async fn load_persisted_workspace_dirs(default_config_dir: &Path,) -> Result<Option<(PathBuf, PathBuf)>> {let state_path = active_workspace_state_path(default_config_dir);diff --git a/crates/openhuman-core/src/config/schema/load/env.rs b/crates/openhuman-core/src/config/schema/load/env.rsindex 09462cdfd4..c2fc947097 100644--- a/crates/openhuman-core/src/config/schema/load/env.rs+++ b/crates/openhuman-core/src/config/schema/load/env.rs@@ -15,6 +15,11 @@ pub(crate) trait EnvLookup {self.get(key).is_some()}+ /// Whether a present value was installed by the tracked dotenv load.+ fn is_from_dotenv(&self, _key: &str) -> bool {+ false+ }+/// Looks up the first non-`None` value across `keys`, preserving the/// precedence used by the manual `or_else` chains throughout this/// module (e.g. `OPENHUMAN_FOO` wins over the bare `FOO` alias).@@ -34,6 +39,10 @@ impl EnvLookup for ProcessEnv {fn contains(&self, key: &str) -> bool {std::env::var_os(key).is_some()}++ fn is_from_dotenv(&self, key: &str) -> bool {+ std::env::var_os(key).is_some() && super::dotenv_loaded_variable(key)+ }}/// Process env lookup that preserves every override except@@ -56,6 +65,10 @@ impl EnvLookup for ProcessEnvWithoutWorkspace {ProcessEnv.contains(key)}}++ fn is_from_dotenv(&self, key: &str) -> bool {+ key != "OPENHUMAN_WORKSPACE" && ProcessEnv.is_from_dotenv(key)+ }}/// Environment lookup for callers that must preserve the persisted configdiff --git a/crates/openhuman-core/src/config/schema/load/env_overlay.rs b/crates/openhuman-core/src/config/schema/load/env_overlay.rsindex 07ff3ad58f..edcfca9e54 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay.rs@@ -44,11 +44,46 @@ pub(super) fn classify_shell_hide_window(raw: &str) -> ShellHideWindowParse {}impl Config {+ pub(crate) fn record_env_override<E: super::env::EnvLookup + ?Sized>(+ &mut self,+ env: &E,+ field_path: &str,+ env_vars: &[&str],+ ) {+ if let Some(env_var) = env_vars.iter().copied().find(|name| env.contains(name)) {+ self.record_env_override_var(env, field_path, env_var);+ }+ }++ pub(crate) fn record_env_override_var<E: super::env::EnvLookup + ?Sized>(+ &mut self,+ env: &E,+ field_path: &str,+ env_var: &str,+ ) {+ let source = if env.is_from_dotenv(env_var) {+ super::ProvenanceSource::Dotenv+ } else {+ super::ProvenanceSource::Env+ };+ self.load_provenance_mut()+ .record_env_override(field_path, env_var, source);+ }+pub fn apply_env_overrides(&mut self) {use super::env::ProcessEnv;self.apply_env_overrides_from(&ProcessEnv);}+ /// Apply ordinary config environment overrides without replacing a+ /// profile's already-selected workspace directory or updating process+ /// proxy/keyring state. Used by read-only profile inspection.+ pub(crate) fn apply_profile_env_overrides(&mut self) {+ use super::env::ProcessEnvWithoutWorkspace;+ self.apply_env_overlay_with(&ProcessEnvWithoutWorkspace);+ super::super::cli_overrides::apply_cli_inference_overrides(self);+ }+pub(super) fn apply_env_overrides_from(&mut self,env: &(dyn super::env::EnvLookup + Send + Sync),@@ -80,16 +115,27 @@ impl Config {/// with a [`HashMapEnv`] (see tests) without requiring the/// `TEST_ENV_LOCK` or tainting sibling tests.pub(crate) fn apply_env_overlay_with<E: super::env::EnvLookup + ?Sized>(&mut self, env: &E) {- // Only the namespaced `OPENHUMAN_MODEL` is honoured. The bare `MODEL`- // env var used to be accepted as an alias but collides with vendor+ self.load_provenance_mut()+ .set_dotenv(super::current_dotenv_load());++ // `OPENHUMAN_DEFAULT_MODEL` is the explicit spelling; the historical+ // `OPENHUMAN_MODEL` remains accepted. The bare `MODEL` env var used to+ // be accepted as an alias but collides with vendor// asset-tag env vars (e.g. Dell OptiPlex sets `MODEL=7080`), which// silently clobbered the LLM model and 400'd every backend call// (Sentry OPENHUMAN-TAURI-J8).- if let Some(model) = env.get("OPENHUMAN_MODEL") {- let trimmed = model.trim();- if !trimmed.is_empty() {- self.default_model = Some(trimmed.to_string());- }+ let model = env+ .get("OPENHUMAN_DEFAULT_MODEL")+ .map(|value| ("OPENHUMAN_DEFAULT_MODEL", value))+ .filter(|(_, value)| !value.trim().is_empty())+ .or_else(|| {+ env.get("OPENHUMAN_MODEL")+ .map(|value| ("OPENHUMAN_MODEL", value))+ .filter(|(_, value)| !value.trim().is_empty())+ });+ if let Some((env_var, model)) = model {+ self.default_model = Some(model.trim().to_string());+ self.record_env_override_var(env, "default_model", env_var);}// One-launch override for the tool-call dialect experiment@@ -104,6 +150,11 @@ impl Config {"OPENHUMAN_TOOL_DISPATCHER overrides agent.tool_dispatcher");self.agent.tool_dispatcher = trimmed.to_string();+ self.record_env_override(+ env,+ "agent.tool_dispatcher",+ &["OPENHUMAN_TOOL_DISPATCHER"],+ );}}@@ -121,6 +172,11 @@ impl Config {agent.max_tool_iterations_override");self.agent.max_tool_iterations_override = Some(cap);+ self.record_env_override(+ env,+ "agent.max_tool_iterations_override",+ &["OPENHUMAN_AGENT_MAX_TOOL_ITERATIONS"],+ );}_ => tracing::warn!(value = trimmed,@@ -140,6 +196,7 @@ impl Config {"OPENHUMAN_COMPOSIO_MODE overrides composio.mode");self.composio.mode = trimmed.to_ascii_lowercase();+ self.record_env_override(env, "composio.mode", &["OPENHUMAN_COMPOSIO_MODE"]);}}@@ -155,6 +212,11 @@ impl Config {"OPENHUMAN_JEV_ROUTE overrides agent.tool_search.jev_route");self.agent.tool_search.jev_route = trimmed.to_ascii_lowercase();+ self.record_env_override(+ env,+ "agent.tool_search.jev_route",+ &["OPENHUMAN_JEV_ROUTE"],+ );}}if let Some(raw) = env.get("OPENHUMAN_JEV_BASE_URL") {@@ -162,6 +224,11 @@ impl Config {if !trimmed.is_empty() {tracing::debug!("OPENHUMAN_JEV_BASE_URL overrides agent.tool_search.jev_base_url");self.agent.tool_search.jev_base_url = Some(trimmed.to_string());+ self.record_env_override(+ env,+ "agent.tool_search.jev_base_url",+ &["OPENHUMAN_JEV_BASE_URL"],+ );}}@@ -170,6 +237,7 @@ impl Config {let (_, workspace_dir) =super::dirs::resolve_config_dir_for_workspace(&PathBuf::from(workspace));self.workspace_dir = workspace_dir;+ self.record_env_override(env, "workspace_dir", &["OPENHUMAN_WORKSPACE"]);}}@@ -177,6 +245,7 @@ impl Config {let trimmed = v.trim();if !trimmed.is_empty() {self.action_dir = PathBuf::from(trimmed);+ self.record_env_override(env, "action_dir", &["OPENHUMAN_ACTION_DIR"]);}}@@ -184,6 +253,11 @@ impl Config {if let Ok(temp) = temp_str.parse::<f64>() {if (0.0..=2.0).contains(&temp) {self.default_temperature = temp;+ self.record_env_override(+ env,+ "default_temperature",+ &["OPENHUMAN_TEMPERATURE"],+ );}}}@@ -192,7 +266,14 @@ impl Config {let trimmed = raw.trim();if !trimmed.is_empty() {match trimmed.parse::<u32>() {- Ok(limit) => self.autonomy.max_actions_per_hour = limit,+ Ok(limit) => {+ self.autonomy.max_actions_per_hour = limit;+ self.record_env_override(+ env,+ "autonomy.max_actions_per_hour",+ &["OPENHUMAN_MAX_ACTIONS_PER_HOUR"],+ );+ }Err(_) => tracing::warn!(value = %raw,"invalid OPENHUMAN_MAX_ACTIONS_PER_HOUR ignored; expected an unsigned integer"@@ -205,14 +286,29 @@ impl Config {let language = language.trim();if !language.is_empty() {self.output_language = Some(language.to_string());+ self.record_env_override(env, "output_language", &["OPENHUMAN_OUTPUT_LANGUAGE"]);}}if let Some(flag) = env.get_any(&["OPENHUMAN_REASONING_ENABLED", "REASONING_ENABLED"]) {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.runtime.reasoning_enabled = Some(true),- "0" | "false" | "no" | "off" => self.runtime.reasoning_enabled = Some(false),+ "1" | "true" | "yes" | "on" => {+ self.runtime.reasoning_enabled = Some(true);+ self.record_env_override(+ env,+ "runtime.reasoning_enabled",+ &["OPENHUMAN_REASONING_ENABLED", "REASONING_ENABLED"],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.runtime.reasoning_enabled = Some(false);+ self.record_env_override(+ env,+ "runtime.reasoning_enabled",+ &["OPENHUMAN_REASONING_ENABLED", "REASONING_ENABLED"],+ );+ }_ => {}}}@@ -231,6 +327,11 @@ impl Config {),ShellHideWindowParse::Set(value) => {self.shell.hide_window = value;+ self.record_env_override(+ env,+ "shell.hide_window",+ &["OPENHUMAN_SHELL_HIDE_WINDOW", "SHELL_HIDE_WINDOW"],+ );tracing::debug!(value = %flag,"[config][shell] OPENHUMAN_SHELL_HIDE_WINDOW applied: hide_window={value}"diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/components.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/components.rsindex 954013e802..357872e65f 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/components.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/components.rs@@ -26,6 +26,11 @@ impl Config {"[components] OPENHUMAN_DISABLE_CHANNEL_LISTENERS folds to channels=false");self.components.set("channels", false);+ self.record_env_override(+ env,+ "components.channels",+ &["OPENHUMAN_DISABLE_CHANNEL_LISTENERS"],+ );}for name in COMPONENT_NAMES {let key = format!("OPENHUMAN_COMPONENT_{}", name.to_ascii_uppercase());@@ -34,6 +39,7 @@ impl Config {Some(value) => {tracing::debug!("[components] env override {key}={value}");self.components.set(name, value);+ self.record_env_override_var(env, &format!("components.{name}"), &key);}None => tracing::warn!("[components] ignoring invalid {key} (use 0 or 1)"),}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/context.rsindex 648869190f..1c9e366a1f 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/context.rs@@ -8,30 +8,79 @@ impl Config {if let Some(flag) = env.get("OPENHUMAN_CONTEXT_ENABLED") {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.context.enabled = true,- "0" | "false" | "no" | "off" => self.context.enabled = false,+ "1" | "true" | "yes" | "on" => {+ self.context.enabled = true;+ self.record_env_override(+ env,+ "context.enabled",+ &["OPENHUMAN_CONTEXT_ENABLED"],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.context.enabled = false;+ self.record_env_override(+ env,+ "context.enabled",+ &["OPENHUMAN_CONTEXT_ENABLED"],+ );+ }_ => {}}}if let Some(flag) = env.get("OPENHUMAN_CONTEXT_MICROCOMPACT_ENABLED") {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.context.microcompact_enabled = true,- "0" | "false" | "no" | "off" => self.context.microcompact_enabled = false,+ "1" | "true" | "yes" | "on" => {+ self.context.microcompact_enabled = true;+ self.record_env_override(+ env,+ "context.microcompact_enabled",+ &["OPENHUMAN_CONTEXT_MICROCOMPACT_ENABLED"],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.context.microcompact_enabled = false;+ self.record_env_override(+ env,+ "context.microcompact_enabled",+ &["OPENHUMAN_CONTEXT_MICROCOMPACT_ENABLED"],+ );+ }_ => {}}}if let Some(flag) = env.get("OPENHUMAN_CONTEXT_AUTOCOMPACT_ENABLED") {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.context.autocompact_enabled = true,- "0" | "false" | "no" | "off" => self.context.autocompact_enabled = false,+ "1" | "true" | "yes" | "on" => {+ self.context.autocompact_enabled = true;+ self.record_env_override(+ env,+ "context.autocompact_enabled",+ &["OPENHUMAN_CONTEXT_AUTOCOMPACT_ENABLED"],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.context.autocompact_enabled = false;+ self.record_env_override(+ env,+ "context.autocompact_enabled",+ &["OPENHUMAN_CONTEXT_AUTOCOMPACT_ENABLED"],+ );+ }_ => {}}}if let Some(val) = env.get("OPENHUMAN_COMPACTION_STRATEGY") {match crate::config::CompactionStrategy::parse(&val) {- Some(strategy) => self.context.compaction_strategy = strategy,+ Some(strategy) => {+ self.context.compaction_strategy = strategy;+ self.record_env_override(+ env,+ "context.compaction_strategy",+ &["OPENHUMAN_COMPACTION_STRATEGY"],+ );+ }None if val.trim().is_empty() => {}None => tracing::warn!(value = %val.trim(),@@ -43,9 +92,23 @@ impl Config {// empty value clears an override set in `config.toml`.if let Some(val) = env.get("OPENHUMAN_COMPACTION_TRIGGER_TOKENS") {match val.trim() {- "" | "0" => self.context.compaction_trigger_tokens = None,+ "" | "0" => {+ self.context.compaction_trigger_tokens = None;+ self.record_env_override(+ env,+ "context.compaction_trigger_tokens",+ &["OPENHUMAN_COMPACTION_TRIGGER_TOKENS"],+ );+ }raw => match raw.parse::<u64>() {- Ok(tokens) => self.context.compaction_trigger_tokens = Some(tokens),+ Ok(tokens) => {+ self.context.compaction_trigger_tokens = Some(tokens);+ self.record_env_override(+ env,+ "context.compaction_trigger_tokens",+ &["OPENHUMAN_COMPACTION_TRIGGER_TOKENS"],+ );+ }Err(_) => tracing::warn!(value = raw,"[config] ignoring unparseable OPENHUMAN_COMPACTION_TRIGGER_TOKENS"@@ -56,6 +119,11 @@ impl Config {if let Some(val) = env.get("OPENHUMAN_CONTEXT_TOOL_RESULT_BUDGET_BYTES") {if let Ok(n) = val.trim().parse::<usize>() {self.context.tool_result_budget_bytes = n;+ self.record_env_override(+ env,+ "context.tool_result_budget_bytes",+ &["OPENHUMAN_CONTEXT_TOOL_RESULT_BUDGET_BYTES"],+ );}}// Switch for native tool-output compaction (Stage 1a). On by@@ -66,8 +134,28 @@ impl Config {.or_else(|| env.get("OPENHUMAN_CONTEXT_COMPACTION_ENABLED")){match flag.trim().to_ascii_lowercase().as_str() {- "1" | "true" | "yes" | "on" => self.context.compaction_enabled = true,- "0" | "false" | "no" | "off" => self.context.compaction_enabled = false,+ "1" | "true" | "yes" | "on" => {+ self.context.compaction_enabled = true;+ self.record_env_override(+ env,+ "context.compaction_enabled",+ &[+ "OPENHUMAN_COMPACTION",+ "OPENHUMAN_CONTEXT_COMPACTION_ENABLED",+ ],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.context.compaction_enabled = false;+ self.record_env_override(+ env,+ "context.compaction_enabled",+ &[+ "OPENHUMAN_COMPACTION",+ "OPENHUMAN_CONTEXT_COMPACTION_ENABLED",+ ],+ );+ }_ => {}}}@@ -75,6 +163,11 @@ impl Config {let model = model.trim();if !model.is_empty() {self.context.summarizer_model = Some(model.to_string());+ self.record_env_override(+ env,+ "context.summarizer_model",+ &["OPENHUMAN_CONTEXT_SUMMARIZER_MODEL"],+ );}}let context_default =diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rsindex d2f994e4ae..9cd6566bdc 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/embeddings.rs@@ -9,6 +9,11 @@ impl Config {if let Some(val) = env.get("OPENHUMAN_MEMORY_EMBED_RATE_LIMIT") {if let Ok(per_min) = val.trim().parse::<u32>() {self.memory.embedding_rate_limit_per_min = per_min;+ self.record_env_override(+ env,+ "memory.embedding_rate_limit_per_min",+ &["OPENHUMAN_MEMORY_EMBED_RATE_LIMIT"],+ );}}}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/modules.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/modules.rsindex 860d1aed5c..34e9ed0906 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/modules.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/modules.rs@@ -13,7 +13,10 @@ impl Config {pub(super) fn apply_modules_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {if let Some(raw) = env.get(MODULE_SOURCE_ENV) {match ModuleSourceMode::parse(&raw) {- Some(mode) => self.modules.source = mode,+ Some(mode) => {+ self.modules.source = mode;+ self.record_env_override(env, "modules.source", &[MODULE_SOURCE_ENV]);+ }None => tracing::warn!("[modules] ignoring invalid {MODULE_SOURCE_ENV} (valid: release, linked, source)"),@@ -30,6 +33,7 @@ impl Config {self.modules.overrides.push(ModuleOverride::with_source(record.id, mode));+ self.record_env_override_var(env, "modules.overrides[].source", &key);}}}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rsindex 8b0ad3ddef..5f45f0907c 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs@@ -14,14 +14,42 @@ impl Config {let dsn = dsn.trim();if !dsn.is_empty() {self.observability.sentry_dsn = Some(dsn.to_string());+ let env_var = if env.contains("OPENHUMAN_CORE_SENTRY_DSN") {+ Some("OPENHUMAN_CORE_SENTRY_DSN")+ } else if env.contains("OPENHUMAN_SENTRY_DSN") {+ Some("OPENHUMAN_SENTRY_DSN")+ } else if option_env!("OPENHUMAN_CORE_SENTRY_DSN").is_some() {+ Some("OPENHUMAN_CORE_SENTRY_DSN")+ } else if option_env!("OPENHUMAN_SENTRY_DSN").is_some() {+ Some("OPENHUMAN_SENTRY_DSN")+ } else {+ None+ };+ if let Some(env_var) = env_var {+ self.record_env_override_var(env, "observability.sentry_dsn", env_var);+ }}}if let Some(flag) = env.get("OPENHUMAN_ANALYTICS_ENABLED") {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.observability.analytics_enabled = true,- "0" | "false" | "no" | "off" => self.observability.analytics_enabled = false,+ "1" | "true" | "yes" | "on" => {+ self.observability.analytics_enabled = true;+ self.record_env_override(+ env,+ "observability.analytics_enabled",+ &["OPENHUMAN_ANALYTICS_ENABLED"],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.observability.analytics_enabled = false;+ self.record_env_override(+ env,+ "observability.analytics_enabled",+ &["OPENHUMAN_ANALYTICS_ENABLED"],+ );+ }_ => {}}}@@ -32,10 +60,20 @@ impl Config {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {"1" | "true" | "yes" | "on" => {- self.observability.agent_tracing.capture_content = true+ self.observability.agent_tracing.capture_content = true;+ self.record_env_override(+ env,+ "observability.agent_tracing.capture_content",+ &["OPENHUMAN_AGENT_TRACING_CAPTURE_CONTENT"],+ );}"0" | "false" | "no" | "off" => {- self.observability.agent_tracing.capture_content = false+ self.observability.agent_tracing.capture_content = false;+ self.record_env_override(+ env,+ "observability.agent_tracing.capture_content",+ &["OPENHUMAN_AGENT_TRACING_CAPTURE_CONTENT"],+ );}_ => {}}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rsindex c2c6cb0d6e..33e01a846e 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/proxy.rs@@ -15,23 +15,40 @@ impl Config {.and_then(parse_proxy_enabled);if let Some(enabled) = explicit_proxy_enabled {self.proxy.enabled = enabled;+ self.record_env_override(env, "proxy.enabled", &["OPENHUMAN_PROXY_ENABLED"]);}let mut proxy_url_overridden = false;if let Some(proxy_url) = env.get_any(&["OPENHUMAN_HTTP_PROXY", "HTTP_PROXY"]) {self.proxy.http_proxy = normalize_proxy_url_option(Some(&proxy_url));+ self.record_env_override(+ env,+ "proxy.http_proxy",+ &["OPENHUMAN_HTTP_PROXY", "HTTP_PROXY"],+ );proxy_url_overridden = true;}if let Some(proxy_url) = env.get_any(&["OPENHUMAN_HTTPS_PROXY", "HTTPS_PROXY"]) {self.proxy.https_proxy = normalize_proxy_url_option(Some(&proxy_url));+ self.record_env_override(+ env,+ "proxy.https_proxy",+ &["OPENHUMAN_HTTPS_PROXY", "HTTPS_PROXY"],+ );proxy_url_overridden = true;}if let Some(proxy_url) = env.get_any(&["OPENHUMAN_ALL_PROXY", "ALL_PROXY"]) {self.proxy.all_proxy = normalize_proxy_url_option(Some(&proxy_url));+ self.record_env_override(+ env,+ "proxy.all_proxy",+ &["OPENHUMAN_ALL_PROXY", "ALL_PROXY"],+ );proxy_url_overridden = true;}if let Some(no_proxy) = env.get_any(&["OPENHUMAN_NO_PROXY", "NO_PROXY"]) {self.proxy.no_proxy = normalize_no_proxy_list(vec![no_proxy]);+ self.record_env_override(env, "proxy.no_proxy", &["OPENHUMAN_NO_PROXY", "NO_PROXY"]);}if explicit_proxy_enabled.is_none()@@ -39,13 +56,28 @@ impl Config {&& self.proxy.has_any_proxy_url(){self.proxy.enabled = true;+ self.record_env_override(+ env,+ "proxy.enabled",+ &[+ "OPENHUMAN_HTTP_PROXY",+ "HTTP_PROXY",+ "OPENHUMAN_HTTPS_PROXY",+ "HTTPS_PROXY",+ "OPENHUMAN_ALL_PROXY",+ "ALL_PROXY",+ ],+ );}if let Some(scope_raw) = env.get("OPENHUMAN_PROXY_SCOPE") {let trimmed = scope_raw.trim();if !trimmed.is_empty() {match parse_proxy_scope(trimmed) {- Some(scope) => self.proxy.scope = scope,+ Some(scope) => {+ self.proxy.scope = scope;+ self.record_env_override(env, "proxy.scope", &["OPENHUMAN_PROXY_SCOPE"]);+ }None => {tracing::warn!("Invalid OPENHUMAN_PROXY_SCOPE value {:?} ignored", trimmed);}@@ -55,6 +87,7 @@ impl Config {if let Some(services_raw) = env.get("OPENHUMAN_PROXY_SERVICES") {self.proxy.services = normalize_service_list(vec![services_raw]);+ self.record_env_override(env, "proxy.services", &["OPENHUMAN_PROXY_SERVICES"]);}if let Err(error) = self.proxy.validate() {diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rsindex e02a73d369..12fdc0bd17 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs@@ -10,61 +10,121 @@ impl Config {if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ENABLED", &flag) {self.tokenjuice.router_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.router_enabled",+ &["OPENHUMAN_TOKENJUICE_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CCR_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CCR_ENABLED", &flag) {self.tokenjuice.ccr_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.ccr_enabled",+ &["OPENHUMAN_TOKENJUICE_CCR_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_REPL_HANDLE_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_REPL_HANDLE_ENABLED", &flag) {self.tokenjuice.repl_handle_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.repl_handle_enabled",+ &["OPENHUMAN_TOKENJUICE_REPL_HANDLE_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_REPL_SAVE_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_REPL_SAVE_ENABLED", &flag) {self.tokenjuice.repl_save_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.repl_save_enabled",+ &["OPENHUMAN_TOKENJUICE_REPL_SAVE_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED", &flag) {self.tokenjuice.ccr_disk_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.ccr_disk_enabled",+ &["OPENHUMAN_TOKENJUICE_CCR_DISK_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_SEARCH_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_SEARCH_ENABLED", &flag) {self.tokenjuice.search_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.search_enabled",+ &["OPENHUMAN_TOKENJUICE_SEARCH_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_CODE_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_CODE_ENABLED", &flag) {self.tokenjuice.code_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.code_enabled",+ &["OPENHUMAN_TOKENJUICE_CODE_ENABLED"],+ );}}if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_HTML_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_HTML_ENABLED", &flag) {self.tokenjuice.html_enabled = v;+ self.record_env_override(+ env,+ "tokenjuice.html_enabled",+ &["OPENHUMAN_TOKENJUICE_HTML_ENABLED"],+ );}}if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_MAX_CACHE_ENTRIES") {if let Ok(v) = s.trim().parse::<usize>() {self.tokenjuice.max_cache_entries = v;+ self.record_env_override(+ env,+ "tokenjuice.max_cache_entries",+ &["OPENHUMAN_TOKENJUICE_MAX_CACHE_ENTRIES"],+ );}}if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_MAX_CACHE_BYTES") {if let Ok(v) = s.trim().parse::<usize>() {self.tokenjuice.max_cache_bytes = v;+ self.record_env_override(+ env,+ "tokenjuice.max_cache_bytes",+ &["OPENHUMAN_TOKENJUICE_MAX_CACHE_BYTES"],+ );}}if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_CCR_TTL_SECS") {if let Ok(v) = s.trim().parse::<u64>() {self.tokenjuice.ccr_ttl_secs = Some(v);+ self.record_env_override(+ env,+ "tokenjuice.ccr_ttl_secs",+ &["OPENHUMAN_TOKENJUICE_CCR_TTL_SECS"],+ );}}if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_CCR_MIN_TOKENS") {if let Ok(v) = s.trim().parse::<usize>() {self.tokenjuice.ccr_min_tokens = v;+ self.record_env_override(+ env,+ "tokenjuice.ccr_min_tokens",+ &["OPENHUMAN_TOKENJUICE_CCR_MIN_TOKENS"],+ );}}}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rsindex ba46442263..a7b7cc9ce0 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs@@ -14,20 +14,45 @@ impl Config {if !key.is_empty() {self.seltz.api_key = Some(key);self.seltz.enabled = true;+ self.record_env_override(+ env,+ "seltz.api_key",+ &["OPENHUMAN_SELTZ_API_KEY", "SELTZ_API_KEY"],+ );+ self.record_env_override(+ env,+ "seltz.enabled",+ &["OPENHUMAN_SELTZ_API_KEY", "SELTZ_API_KEY"],+ );self.search.providers.insert("seltz".into(), SearchProviderSettings::direct());+ self.record_env_override(+ env,+ "search.providers.seltz",+ &["OPENHUMAN_SELTZ_API_KEY", "SELTZ_API_KEY"],+ );}}if let Some(url) = env.get_any(&["OPENHUMAN_SELTZ_API_URL", "SELTZ_API_URL"]) {if !url.is_empty() {self.seltz.api_url = Some(url);+ self.record_env_override(+ env,+ "seltz.api_url",+ &["OPENHUMAN_SELTZ_API_URL", "SELTZ_API_URL"],+ );}}if let Some(max) = env.get_any(&["OPENHUMAN_SELTZ_MAX_RESULTS", "SELTZ_MAX_RESULTS"]) {if let Ok(n) = max.parse::<usize>() {if (1..=20).contains(&n) {self.seltz.max_results = n;+ self.record_env_override(+ env,+ "seltz.max_results",+ &["OPENHUMAN_SELTZ_MAX_RESULTS", "SELTZ_MAX_RESULTS"],+ );}}}@@ -35,12 +60,27 @@ impl Config {if let Some(flag) = env.get_any(&["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"]) {if let Some(enabled) = parse_env_bool("OPENHUMAN_SEARXNG_ENABLED", &flag) {self.searxng.enabled = enabled;+ self.record_env_override(+ env,+ "searxng.enabled",+ &["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"],+ );if enabled {self.search.providers.insert("searxng".into(), SearchProviderSettings::direct());+ self.record_env_override(+ env,+ "search.providers.searxng",+ &["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"],+ );} else {self.search.providers.remove("searxng");+ self.record_env_override(+ env,+ "search.providers.searxng",+ &["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"],+ );}}}@@ -48,12 +88,22 @@ impl Config {let url = url.trim();if !url.is_empty() {self.searxng.base_url = url.to_string();+ self.record_env_override(+ env,+ "searxng.base_url",+ &["OPENHUMAN_SEARXNG_BASE_URL", "SEARXNG_BASE_URL"],+ );}}if let Some(max) = env.get_any(&["OPENHUMAN_SEARXNG_MAX_RESULTS", "SEARXNG_MAX_RESULTS"]) {if let Ok(n) = max.parse::<usize>() {if (1..=50).contains(&n) {self.searxng.max_results = n;+ self.record_env_override(+ env,+ "searxng.max_results",+ &["OPENHUMAN_SEARXNG_MAX_RESULTS", "SEARXNG_MAX_RESULTS"],+ );}}}@@ -64,6 +114,14 @@ impl Config {let language = language.trim();if !language.is_empty() {self.searxng.default_language = language.to_string();+ self.record_env_override(+ env,+ "searxng.default_language",+ &[+ "OPENHUMAN_SEARXNG_DEFAULT_LANGUAGE",+ "SEARXNG_DEFAULT_LANGUAGE",+ ],+ );}}if let Some(timeout_secs) = env.get_any(&[@@ -75,6 +133,16 @@ impl Config {if let Ok(timeout_secs) = timeout_secs.parse::<u64>() {if timeout_secs > 0 {self.searxng.timeout_secs = timeout_secs;+ self.record_env_override(+ env,+ "searxng.timeout_secs",+ &[+ "OPENHUMAN_SEARXNG_TIMEOUT_SECS",+ "OPENHUMAN_SEARXNG_TIMEOUT_SECONDS",+ "SEARXNG_TIMEOUT_SECS",+ "SEARXNG_TIMEOUT_SECONDS",+ ],+ );}}}@@ -82,12 +150,19 @@ impl Config {if let Some(flag) = env.get_any(&["OPENHUMAN_SEARCH_ENABLED"]) {if let Some(enabled) = parse_env_bool("OPENHUMAN_SEARCH_ENABLED", &flag) {self.search.enabled = Some(enabled);+ self.record_env_override(env, "search.enabled", &["OPENHUMAN_SEARCH_ENABLED"]);}}if let Some(engine) = env.get_any(&["OPENHUMAN_SEARCH_ENGINE", "SEARCH_ENGINE"]) {if !engine.trim().is_empty() {if let Err(error) = self.search.apply_legacy_engine(&engine) {log::warn!("[config][search] ignoring SEARCH_ENGINE: {error}");+ } else {+ self.record_env_override(+ env,+ "search.providers",+ &["OPENHUMAN_SEARCH_ENGINE", "SEARCH_ENGINE"],+ );}}}@@ -128,6 +203,7 @@ impl Config {);}self.search.providers = providers;+ self.record_env_override(env, "search.providers", &["OPENHUMAN_SEARCH_PROVIDERS"]);}// The dedicated provider toggles and credentials take precedence over// the provider-set shorthand, which replaces the map above.@@ -136,6 +212,11 @@ impl Config {self.search.providers.insert("seltz".into(), SearchProviderSettings::direct());+ self.record_env_override(+ env,+ "search.providers.seltz",+ &["OPENHUMAN_SELTZ_API_KEY", "SELTZ_API_KEY"],+ );}}if let Some(flag) = env.get_any(&["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"]) {@@ -144,26 +225,41 @@ impl Config {self.search.providers.insert("searxng".into(), SearchProviderSettings::direct());+ self.record_env_override(+ env,+ "search.providers.searxng",+ &["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"],+ );} else {self.search.providers.remove("searxng");+ self.record_env_override(+ env,+ "search.providers.searxng",+ &["OPENHUMAN_SEARXNG_ENABLED", "SEARXNG_ENABLED"],+ );}}}// `exa=direct,gemini=managed` — changes routes of listed providers.- let mut routes: Vec<(String, String)> = Vec::new();+ let mut routes: Vec<(String, String, &str)> = Vec::new();if let Some(value) = env.get_any(&["OPENHUMAN_SEARCH_ROUTES"]) {routes.extend(value.split(',').filter_map(|pair| {- pair.split_once('=')- .map(|(p, r)| (p.trim().to_ascii_lowercase(), r.trim().to_string()))+ pair.split_once('=').map(|(p, r)| {+ (+ p.trim().to_ascii_lowercase(),+ r.trim().to_string(),+ "OPENHUMAN_SEARCH_ROUTES",+ )+ })}));}if let Some(value) = env.get_any(&["OPENHUMAN_GEMINI_ROUTE"]) {log::warn!("[config][search] OPENHUMAN_GEMINI_ROUTE is deprecated; use OPENHUMAN_SEARCH_ROUTES=gemini=<route>");- routes.push(("gemini".into(), value));+ routes.push(("gemini".into(), value, "OPENHUMAN_GEMINI_ROUTE"));}- for (provider, route) in routes {+ for (provider, route, env_var) in routes {match ProviderRoute::parse(&route) {Some(route)if SEARCH_PROVIDERS.contains(&provider.as_str())@@ -174,6 +270,11 @@ impl Config {.get_mut(&provider).expect("checked above").route = route;+ self.record_env_override_var(+ env,+ &format!("search.providers.{provider}.route"),+ env_var,+ );}_ => log::warn!("[config][search] ignoring route '{provider}={route}'"),}@@ -196,11 +297,19 @@ impl Config {.filter(|p| SEARCH_PROVIDERS.contains(&p.as_str())).collect();self.search.roles.insert(role, order);+ self.record_env_override(env, "search.roles", &["OPENHUMAN_SEARCH_ROLES"]);}}if let Some(mode) = env.get_any(&["OPENHUMAN_SEARCH_PRESENTATION"]) {match PresentationMode::parse(&mode) {- Some(mode) => self.search.presentation = mode,+ Some(mode) => {+ self.search.presentation = mode;+ self.record_env_override(+ env,+ "search.presentation",+ &["OPENHUMAN_SEARCH_PRESENTATION"],+ );+ }None => {log::warn!("[config][search] ignoring OPENHUMAN_SEARCH_PRESENTATION='{mode}'")}@@ -214,42 +323,82 @@ impl Config {if let Some(key) = env.get_any(&["OPENHUMAN_PARALLEL_API_KEY", "PARALLEL_API_KEY"]) {if !key.trim().is_empty() {self.search.parallel.api_key = Some(key);+ self.record_env_override(+ env,+ "search.parallel.api_key",+ &["OPENHUMAN_PARALLEL_API_KEY", "PARALLEL_API_KEY"],+ );}}if let Some(key) = env.get_any(&["OPENHUMAN_GEMINI_API_KEY", "GEMINI_API_KEY"]) {if !key.trim().is_empty() {self.search.gemini.api_key = Some(key);+ self.record_env_override(+ env,+ "search.gemini.api_key",+ &["OPENHUMAN_GEMINI_API_KEY", "GEMINI_API_KEY"],+ );}}if let Some(key) = env.get_any(&["OPENHUMAN_BRAVE_API_KEY", "BRAVE_API_KEY"]) {if !key.trim().is_empty() {self.search.brave.api_key = Some(key);+ self.record_env_override(+ env,+ "search.brave.api_key",+ &["OPENHUMAN_BRAVE_API_KEY", "BRAVE_API_KEY"],+ );}}if let Some(key) = env.get_any(&["OPENHUMAN_QUERIT_API_KEY", "QUERIT_API_KEY"]) {if !key.trim().is_empty() {self.search.querit.api_key = Some(key);+ self.record_env_override(+ env,+ "search.querit.api_key",+ &["OPENHUMAN_QUERIT_API_KEY", "QUERIT_API_KEY"],+ );}}if let Some(key) = env.get_any(&["OPENHUMAN_EXA_API_KEY", "EXA_API_KEY"]) {if !key.trim().is_empty() {self.search.exa.api_key = Some(key);+ self.record_env_override(+ env,+ "search.exa.api_key",+ &["OPENHUMAN_EXA_API_KEY", "EXA_API_KEY"],+ );}}if let Some(key) = env.get_any(&["OPENHUMAN_TAVILY_API_KEY", "TAVILY_API_KEY"]) {if !key.trim().is_empty() {self.search.tavily.api_key = Some(key);+ self.record_env_override(+ env,+ "search.tavily.api_key",+ &["OPENHUMAN_TAVILY_API_KEY", "TAVILY_API_KEY"],+ );}}if let Some(key) = env.get_any(&["OPENHUMAN_TINYFISH_API_KEY", "TINYFISH_API_KEY"]) {if !key.trim().is_empty() {self.search.tinyfish.api_key = Some(key);+ self.record_env_override(+ env,+ "search.tinyfish.api_key",+ &["OPENHUMAN_TINYFISH_API_KEY", "TINYFISH_API_KEY"],+ );}}if let Some(max) = env.get_any(&["OPENHUMAN_SEARCH_MAX_RESULTS", "SEARCH_MAX_RESULTS"]) {if let Ok(n) = max.parse::<usize>() {if (1..=20).contains(&n) {self.search.max_results = n;+ self.record_env_override(+ env,+ "search.max_results",+ &["OPENHUMAN_SEARCH_MAX_RESULTS", "SEARCH_MAX_RESULTS"],+ );}}}@@ -257,6 +406,11 @@ impl Config {if let Ok(n) = t.parse::<u64>() {if n > 0 {self.search.timeout_secs = n;+ self.record_env_override(+ env,+ "search.timeout_secs",+ &["OPENHUMAN_SEARCH_TIMEOUT_SECS", "SEARCH_TIMEOUT_SECS"],+ );}}}@@ -274,6 +428,11 @@ impl Config {if let Ok(max_results) = max_results.parse::<usize>() {if (1..=10).contains(&max_results) {self.web_search.max_results = max_results;+ self.record_env_override(+ env,+ "web_search.max_results",+ &["OPENHUMAN_WEB_SEARCH_MAX_RESULTS", "WEB_SEARCH_MAX_RESULTS"],+ );}}}@@ -285,6 +444,14 @@ impl Config {if let Ok(timeout_secs) = timeout_secs.parse::<u64>() {if timeout_secs > 0 {self.web_search.timeout_secs = timeout_secs;+ self.record_env_override(+ env,+ "web_search.timeout_secs",+ &[+ "OPENHUMAN_WEB_SEARCH_TIMEOUT_SECS",+ "WEB_SEARCH_TIMEOUT_SECS",+ ],+ );}}}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/update.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/update.rsindex b5f5397573..32dd21d309 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/update.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/update.rs@@ -10,23 +10,52 @@ impl Config {if let Some(flag) = env.get("OPENHUMAN_AUTO_UPDATE_ENABLED") {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {- "1" | "true" | "yes" | "on" => self.update.enabled = true,- "0" | "false" | "no" | "off" => self.update.enabled = false,+ "1" | "true" | "yes" | "on" => {+ self.update.enabled = true;+ self.record_env_override(+ env,+ "update.enabled",+ &["OPENHUMAN_AUTO_UPDATE_ENABLED"],+ );+ }+ "0" | "false" | "no" | "off" => {+ self.update.enabled = false;+ self.record_env_override(+ env,+ "update.enabled",+ &["OPENHUMAN_AUTO_UPDATE_ENABLED"],+ );+ }_ => {}}}if let Some(val) = env.get("OPENHUMAN_AUTO_UPDATE_INTERVAL_MINUTES") {if let Ok(minutes) = val.trim().parse::<u32>() {self.update.interval_minutes = minutes;+ self.record_env_override(+ env,+ "update.interval_minutes",+ &["OPENHUMAN_AUTO_UPDATE_INTERVAL_MINUTES"],+ );}}if let Some(raw) = env.get("OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY") {match raw.trim().to_ascii_lowercase().as_str() {"self_replace" | "self-replace" | "self" => {self.update.restart_strategy = UpdateRestartStrategy::SelfReplace;+ self.record_env_override(+ env,+ "update.restart_strategy",+ &["OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY"],+ );}"supervisor" | "stage_only" | "stage-only" => {self.update.restart_strategy = UpdateRestartStrategy::Supervisor;+ self.record_env_override(+ env,+ "update.restart_strategy",+ &["OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY"],+ );}other => {tracing::warn!(@@ -42,6 +71,11 @@ impl Config {parse_env_bool("OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED", &flag){self.update.rpc_mutations_enabled = enabled;+ self.record_env_override(+ env,+ "update.rpc_mutations_enabled",+ &["OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED"],+ );}}}diff --git a/crates/openhuman-core/src/config/schema/load/impl_load.rs b/crates/openhuman-core/src/config/schema/load/impl_load.rsindex 93d599865c..83a1cf0215 100644--- a/crates/openhuman-core/src/config/schema/load/impl_load.rs+++ b/crates/openhuman-core/src/config/schema/load/impl_load.rs@@ -7,8 +7,7 @@ use super::dirs::{};use super::env::{EnvLookup, NoEnv, ProcessEnv, ProcessEnvWithoutWorkspace};use super::migrate::{- migrate_cloud_provider_slugs, migrate_components, migrate_legacy_inference_url,- migrate_legacy_memory_backend, migrate_search_settings,+ apply_loaded_config_migrations, migrate_components, migrate_legacy_memory_backend,};use super::secrets::{decrypt_config_secrets, decrypt_config_secrets_strict, encrypt_config_secrets,@@ -354,12 +353,8 @@ impl Config {config.workspace_dir = workspace_dir;config.action_dir = resolve_action_dir(&config.action_dir_override);config.recovered_from_corruption = config_was_corrupted;- migrate_legacy_inference_url(&mut config);let migration_raw = migration_source(&config_path, &raw).await;- migrate_legacy_memory_backend(&mut config, &migration_raw);- migrate_components(&mut config, &migration_raw);- migrate_cloud_provider_slugs(&mut config);- migrate_search_settings(&mut config);+ apply_loaded_config_migrations(&mut config, &migration_raw);config.apply_env_overrides_from(env);if config_was_corrupted {diff --git a/crates/openhuman-core/src/config/schema/load/migrate.rs b/crates/openhuman-core/src/config/schema/load/migrate.rsindex 663092378e..fbdcf74e3b 100644--- a/crates/openhuman-core/src/config/schema/load/migrate.rs+++ b/crates/openhuman-core/src/config/schema/load/migrate.rs@@ -1,5 +1,16 @@use super::super::Config;+/// Applies the in-memory migrations that normalize a parsed config before+/// environment overlays and persistent schema migrations. This helper does+/// not read config files or persist any of its changes.+pub(crate) fn apply_loaded_config_migrations(config: &mut Config, raw: &str) {+ migrate_legacy_inference_url(config);+ migrate_legacy_memory_backend(config, raw);+ migrate_components(config, raw);+ migrate_cloud_provider_slugs(config);+ migrate_search_settings(config);+}+pub(crate) fn migrate_legacy_inference_url(config: &mut Config) {if config.inference_url.is_some() {return;@@ -31,6 +42,7 @@ pub(crate) fn migrate_legacy_inference_url(config: &mut Config) {);config.inference_url = moved;config.api_url = None;+ config.load_diagnostics_mut().record_migrated_key("api_url");}/// Strip userinfo (basic-auth) and query string from a URL string for log@@ -68,6 +80,19 @@ pub fn redact_url_for_log(raw: &str) -> String {pub(crate) fn migrate_cloud_provider_slugs(config: &mut Config) {use super::super::cloud_providers::{builtin_cloud_provider, AuthStyle};+ let legacy_provider_labels = config+ .cloud_providers+ .iter()+ .any(|entry| entry.label.is_empty());+ let previous_routes = [+ config.reasoning_provider.clone(),+ config.agentic_provider.clone(),+ config.coding_provider.clone(),+ config.vision_provider.clone(),+ config.memory_provider.clone(),+ config.embeddings_provider.clone(),+ ];+for entry in &mut config.cloud_providers {if entry.label.is_empty() {entry.label = builtin_cloud_provider(&entry.slug)@@ -194,6 +219,50 @@ pub(crate) fn migrate_cloud_provider_slugs(config: &mut Config) {rewrite(&mut config.embeddings_provider);}+ if legacy_provider_labels {+ config+ .load_diagnostics_mut()+ .record_migrated_key("cloud_providers[].label");+ }+ let changed_routes: Vec<&str> = [+ (+ "reasoning_provider",+ &previous_routes[0],+ &config.reasoning_provider,+ ),+ (+ "agentic_provider",+ &previous_routes[1],+ &config.agentic_provider,+ ),+ (+ "coding_provider",+ &previous_routes[2],+ &config.coding_provider,+ ),+ (+ "vision_provider",+ &previous_routes[3],+ &config.vision_provider,+ ),+ (+ "memory_provider",+ &previous_routes[4],+ &config.memory_provider,+ ),+ (+ "embeddings_provider",+ &previous_routes[5],+ &config.embeddings_provider,+ ),+ ]+ .into_iter()+ .filter_map(|(key, before, after)| (before != after).then_some(key))+ .collect();+ for key in changed_routes {+ config.load_diagnostics_mut().record_migrated_key(key);+ }+fn normalize_provider_endpoint(url: &str) -> String {url.trim().trim_end_matches('/').to_ascii_lowercase()}@@ -218,6 +287,7 @@ pub(crate) fn migrate_search_settings(config: &mut Config) {tinyfish_api_key: config.integrations.tinyfish.api_key.clone(),};config.search.migrate_legacy(legacy);+ config.load_diagnostics_mut().record_migrated_key("search");}/// Migrates legacy v1 `[[memory_sources]]` into `[[memory.sources]]`, once:@@ -226,7 +296,13 @@ pub(crate) fn migrate_search_settings(config: &mut Config) {/// legacy list is cleared either way, so it is never written back.pub(crate) fn migrate_legacy_memory_sources(config: &mut Config) {let legacy = std::mem::take(&mut config.legacy_memory_sources);- if legacy.is_empty() || !config.memory.sources.is_empty() {+ if legacy.is_empty() {+ return;+ }+ config+ .load_diagnostics_mut()+ .record_migrated_key("memory_sources");+ if !config.memory.sources.is_empty() {return;}let migrated: Vec<_> = legacy@@ -264,6 +340,9 @@ pub(crate) fn migrate_legacy_memory_backend(config: &mut Config, raw: &str) {config.memory.engine.clear();config.memory.legacy_backend_unsupported = true;+ config+ .load_diagnostics_mut()+ .record_migrated_key("memory.backend");tracing::warn!("[config] legacy memory backend is unsupported; select an explicit v2 memory engine");@@ -381,6 +460,27 @@ pub(crate) fn migrate_components_with(config: &mut Config, raw: &str, tinymemes:.contains(&Some(false));disable(config, "sandbox", sandbox_off.then_some(false));if !moved.is_empty() {+ for component in &moved {+ let keys: &[&str] = match *component {+ "hosting" => &["hosting.enabled"],+ "search" => &["search.enabled"],+ "mcp" => &["mcp_client.enabled"],+ "connectors" => &["composio.mode"],+ "memory" => &["memory.engine"],+ "memes" => &["OPENHUMAN_TINYMEMES"],+ "juice" => &["tokenjuice.router_enabled"],+ "voice" => &[+ "dictation.enabled",+ "voice_server.auto_start",+ "voice_server.always_on_enabled",+ ],+ "sandbox" => &["sandbox.enabled", "security.sandbox.enabled"],+ _ => &[],+ };+ for key in keys {+ config.load_diagnostics_mut().record_migrated_key(*key);+ }+ }tracing::info!("[config][migrate] legacy switches moved to [components]: {}",moved.join(",")diff --git a/crates/openhuman-core/src/config/schema/load/mod.rs b/crates/openhuman-core/src/config/schema/load/mod.rsindex 2af2015d90..46dec5d55f 100644--- a/crates/openhuman-core/src/config/schema/load/mod.rs+++ b/crates/openhuman-core/src/config/schema/load/mod.rs@@ -5,6 +5,7 @@ mod branches;mod config_file_read;pub(crate) mod context_overlay;mod context_refresh;+mod diagnostics;mod dirs;pub(in crate::config::schema) mod env;mod env_overlay;@@ -12,10 +13,17 @@ mod impl_load;mod migrate;mod parse;mod parse_source;+mod provenance;mod saas_scope;mod secrets;pub(crate) mod source;+pub(crate) use diagnostics::{ConfigLoadFallback, ConfigParseError, LoadDiagnostics};++#[cfg(test)]+#[path = "diagnostics_tests.rs"]+mod diagnostics_tests;+pub use active_workspace::active_workspace_dir_cached;pub(crate) use active_workspace::invalidate_active_workspace;pub use dirs::{@@ -36,6 +44,11 @@ pub(super) use migrate::redact_url_for_log;// user-environment state). Exported so the classifier's tests can assert// against the real constant rather than a copied literal.pub(crate) use impl_load::CONFIG_OWNER_MISMATCH_MARKER;+pub(crate) use migrate::apply_loaded_config_migrations;+pub(crate) use provenance::{+ current_dotenv_load, dotenv_loaded_variable, set_current_dotenv_load, ConfigProvenance,+ DotenvLoadProvenance, ProvenanceSource, ValueProvenance,+};// Items needed by load_tests.rs (loaded as `mod tests` below).// Tests are a submodule of `load`, so `super::*` == this module's namespace.@@ -50,10 +63,11 @@ pub(crate) use dirs::read_active_user_id_checked;// workspace→config-dir mapping `config::load` uses, so a legacy `.../workspace`// override lands on the sibling `.openhuman` root that holds `auth-profiles.json`.pub(crate) use dirs::resolve_config_dir_for_workspace;-#[cfg(test)]pub(crate) use dirs::{- resolve_runtime_config_dirs, resolve_runtime_config_dirs_with, ConfigResolutionSource,+ load_persisted_workspace_dirs, read_active_user_id_checked_async, ConfigResolutionSource,};+#[cfg(test)]+pub(crate) use dirs::{resolve_runtime_config_dirs, resolve_runtime_config_dirs_with};// PathBuf and Config were in scope via `use super::*` in the original load.rs.#[cfg(test)]pub(crate) use super::Config;@@ -67,6 +81,10 @@ pub(crate) use parse::config_from_toml_str;#[cfg(test)]pub(crate) use std::path::PathBuf;+#[cfg(test)]+#[path = "provenance_tests.rs"]+mod provenance_tests;+pub(super) mod atomic_commit;#[cfg(unix)]diff --git a/crates/openhuman-core/src/config/schema/load/parse.rs b/crates/openhuman-core/src/config/schema/load/parse.rsindex 9f1693d41c..335c3c567b 100644--- a/crates/openhuman-core/src/config/schema/load/parse.rs+++ b/crates/openhuman-core/src/config/schema/load/parse.rs@@ -9,18 +9,110 @@//! `serde_path_to_error`, though not the line.use crate::config::Config;+use std::fmt;++/// A parser failure with safe location metadata and unchanged display text.+#[derive(Debug)]+pub(crate) struct ConfigParseFailure {+ pub(crate) field_path: Option<String>,+ pub(crate) line: Option<usize>,+ message: String,+ source: Option<Box<dyn std::error::Error + Send + Sync>>,+}++impl ConfigParseFailure {+ fn syntax(contents: &str, source: toml::de::Error) -> Self {+ let line = source.span().map(|span| {+ contents+ .as_bytes()+ .get(..span.start.min(contents.len()))+ .unwrap_or_default()+ .iter()+ .filter(|byte| **byte == b'\n')+ .count()+ + 1+ });+ let message = source.to_string();+ Self {+ field_path: None,+ line,+ message,+ source: Some(Box::new(source)),+ }+ }++ fn typed(field_path: String, source: serde_json::Error) -> Self {+ let message = format!("{field_path}: {source}");+ Self {+ field_path: Some(field_path),+ line: None,+ message,+ source: Some(Box::new(source)),+ }+ }+}++impl fmt::Display for ConfigParseFailure {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(&self.message)+ }+}++impl std::error::Error for ConfigParseFailure {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ self.source.as_deref().map(|error| error as _)+ }+}/// Parse a `config.toml` document into a [`Config`].#[inline(never)]pub(crate) fn config_from_toml_str(contents: &str) -> anyhow::Result<Config> {- let mut document: toml::Value = toml::from_str(contents)?;+ let mut document: toml::Value =+ toml::from_str(contents).map_err(|error| ConfigParseFailure::syntax(contents, error))?;+ let provenance_document = document.clone();+ let retired_provider_type = document+ .get("cloud_providers")+ .and_then(toml::Value::as_array)+ .is_some_and(|providers| {+ providers.iter().any(|provider| {+ provider+ .as_table()+ .is_some_and(|entry| entry.contains_key("type"))+ })+ })+ && document+ .get("schema_version")+ .and_then(toml::Value::as_integer)+ .unwrap_or(0)+ < 14;crate::config::migrations::retire_cloud_provider_type::rewrite_document(&mut document)?;reject_non_finite_floats(&document, &mut String::new())?;- let json = serde_json::to_value(document)?;- serde_path_to_error::deserialize(json).map_err(|err| {- let path = err.path().to_string();- anyhow::anyhow!("{path}: {}", err.into_inner())- })+ let json = serde_json::to_string(&document)?;+ let mut unknown_keys = Vec::new();+ let mut deserializer = serde_json::Deserializer::from_str(&json);+ let parsed = {+ let mut record_unknown = |path: serde_ignored::Path<'_>| {+ unknown_keys.push(path.to_string());+ };+ let deserializer = serde_ignored::Deserializer::new(&mut deserializer, &mut record_unknown);+ serde_path_to_error::deserialize(deserializer)+ };+ let mut config: Config = parsed.map_err(|error| {+ let path = error.path().to_string();+ ConfigParseFailure::typed(path, error.into_inner())+ })?;+ config+ .load_provenance_mut()+ .record_file_keys(&provenance_document);+ unknown_keys.sort();+ unknown_keys.dedup();+ config.load_diagnostics_mut().unknown_keys = unknown_keys;+ if retired_provider_type {+ config+ .load_diagnostics_mut()+ .record_migrated_key("cloud_providers[].type");+ }+ Ok(config)}/// JSON has no NaN or infinity: `serde_json::to_value` turns them into null,diff --git a/crates/openhuman-core/src/config/schema/load/parse_source.rs b/crates/openhuman-core/src/config/schema/load/parse_source.rsindex 840941b848..a0e109611b 100644--- a/crates/openhuman-core/src/config/schema/load/parse_source.rs+++ b/crates/openhuman-core/src/config/schema/load/parse_source.rs@@ -21,11 +21,12 @@ pub(super) async fn parse_source_contents(// fell back to the file (no document for the scope yet) returns file text,// which keeps the file's `.bak` recovery.if read.from_document {- let config = parse_toml_off_worker(contents.to_string())+ let mut config = parse_toml_off_worker(contents.to_string()).await.map_err(|error| {anyhow::anyhow!("the config document for this scope could not be parsed: {error}")})?;+ config.load_diagnostics_mut().warn_unknown_keys_once();*config.runtime_state.document_snapshot.lock().unwrap() =super::super::ConfigDocumentSnapshot {version: read.document_version,@@ -34,7 +35,12 @@ pub(super) async fn parse_source_contents(return Ok((config, false));}if read_was_recovered && contents.is_empty() {- let config = super::branches::default_config_boxed();+ let mut config = super::branches::default_config_boxed();+ super::diagnostics::record_non_utf8_recovery(+ &mut config,+ config_path,+ super::ConfigLoadFallback::Defaults,+ );*config.runtime_state.document_snapshot.lock().unwrap() =super::super::ConfigDocumentSnapshot {version: read.document_version,@@ -42,7 +48,15 @@ pub(super) async fn parse_source_contents(};return Ok((config, true));}- let (config, recovered) = Box::pin(parse_config_boxed(config_path, contents)).await;+ let (mut config, recovered) = Box::pin(parse_config_boxed(config_path, contents)).await;+ if read_was_recovered {+ let fallback = if contents.is_empty() {+ super::ConfigLoadFallback::Defaults+ } else {+ super::ConfigLoadFallback::Backup+ };+ super::diagnostics::record_non_utf8_recovery(&mut config, config_path, fallback);+ }*config.runtime_state.document_snapshot.lock().unwrap() =super::super::ConfigDocumentSnapshot {version: read.document_version,diff --git a/crates/openhuman-core/src/config/schema/load/provenance.rs b/crates/openhuman-core/src/config/schema/load/provenance.rsnew file mode 100644index 0000000000..58a5ad6d9b--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/provenance.rs@@ -0,0 +1,314 @@+//! Value-source metadata collected while a config document is loaded.++use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, HashSet};+use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};++/// The source that supplied a resolved config value.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum ProvenanceSource {+ /// The value came from a process-local CLI launch option.+ Cli,+ /// The value came from the process environment.+ Env,+ /// The value came from a `.env` file loaded for this process.+ Dotenv,+ /// The value was explicitly present in the persisted config document.+ File,+ /// The value came from the config schema's default.+ #[default]+ Default,+}++/// Source metadata for one logical config field. Config values are never kept.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub(crate) struct ValueProvenance {+ /// Origin of the resolved value.+ pub(crate) source: ProvenanceSource,+ /// Environment variable name when an environment source won.+ pub(crate) env_var: Option<String>,+ /// Whether the persisted file also explicitly contained this field.+ pub(crate) file_also_set: bool,+}++/// Metadata about the dotenv file considered by the CLI loader.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct DotenvLoadProvenance {+ /// File selected by dotenvy.+ pub(crate) path: PathBuf,+ /// Names present in the process environment, so dotenvy preserved them.+ pub(crate) skipped_vars: Vec<String>,+ /// Names supplied by the dotenv file.+ pub(crate) loaded_vars: Vec<String>,+}++impl DotenvLoadProvenance {+ /// Build dotenv metadata from variable names only; values are discarded.+ pub(crate) fn from_variables<I, K, P, PK>(path: PathBuf, variables: I, process_vars: P) -> Self+ where+ I: IntoIterator<Item = K>,+ K: AsRef<str>,+ P: IntoIterator<Item = PK>,+ PK: AsRef<str>,+ {+ let process_vars: HashSet<String> = process_vars+ .into_iter()+ .map(|name| name.as_ref().to_owned())+ .collect();+ let mut seen = HashSet::new();+ let mut skipped_vars = Vec::new();+ let mut loaded_vars = Vec::new();++ for name in variables {+ let name = name.as_ref();+ if !seen.insert(name.to_owned()) {+ continue;+ }+ if process_vars.contains(name) {+ skipped_vars.push(name.to_owned());+ } else {+ loaded_vars.push(name.to_owned());+ }+ }++ Self {+ path,+ skipped_vars,+ loaded_vars,+ }+ }++ /// Keep the original source classification when the same file is loaded+ /// again and its previously loaded variables are already in the process.+ pub(crate) fn preserve_previous_origin(+ &mut self,+ previous: Option<&Self>,+ process_vars: &HashSet<String>,+ ) {+ let Some(previous) = previous.filter(|previous| same_file(&self.path, &previous.path))+ else {+ return;+ };+ let current_vars: HashSet<String> = self+ .loaded_vars+ .iter()+ .chain(&self.skipped_vars)+ .cloned()+ .collect();++ for name in &previous.loaded_vars {+ if process_vars.contains(name) && current_vars.contains(name) {+ self.skipped_vars.retain(|current| current != name);+ push_unique(&mut self.loaded_vars, name);+ }+ }+ for name in &previous.skipped_vars {+ if process_vars.contains(name) && current_vars.contains(name) {+ self.loaded_vars.retain(|current| current != name);+ push_unique(&mut self.skipped_vars, name);+ }+ }+ }+}++fn same_file(left: &std::path::Path, right: &std::path::Path) -> bool {+ match (left.canonicalize(), right.canonicalize()) {+ (Ok(left), Ok(right)) => left == right,+ _ => left == right,+ }+}++fn push_unique(values: &mut Vec<String>, value: &str) {+ if !values.iter().any(|existing| existing == value) {+ values.push(value.to_owned());+ }+}++/// Provenance for a config snapshot. It stores paths and source labels only.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct ConfigProvenance {+ fields: BTreeMap<String, ValueProvenance>,+ pub(crate) dotenv: Option<DotenvLoadProvenance>,+}++impl ConfigProvenance {+ /// Mark explicit leaves in the parsed TOML document as file-sourced.+ pub(crate) fn record_file_keys(&mut self, document: &toml::Value) {+ record_toml_paths(document, &mut String::new(), &mut self.fields);+ }++ /// Make a source map directly from the persisted TOML tree.+ #[cfg(test)]+ pub(crate) fn from_file_document(document: &toml::Value) -> Self {+ let mut provenance = Self::default();+ provenance.record_file_keys(document);+ provenance+ }++ /// Record an environment override after its value has passed validation.+ pub(crate) fn record_env_override(+ &mut self,+ path: &str,+ env_var: &str,+ source: ProvenanceSource,+ ) {+ debug_assert!(matches!(+ source,+ ProvenanceSource::Env | ProvenanceSource::Dotenv+ ));+ let file_also_set = self+ .fields+ .get(path)+ .is_some_and(|entry| entry.source == ProvenanceSource::File || entry.file_also_set);+ self.fields.insert(+ path.to_owned(),+ ValueProvenance {+ source,+ env_var: Some(env_var.to_owned()),+ file_also_set,+ },+ );+ }++ pub(crate) fn record_cli_override(&mut self, path: &str) {+ let file_also_set = self+ .fields+ .get(path)+ .is_some_and(|entry| entry.source == ProvenanceSource::File || entry.file_also_set);+ self.fields.insert(+ path.to_owned(),+ ValueProvenance {+ source: ProvenanceSource::Cli,+ env_var: None,+ file_also_set,+ },+ );+ }++ /// Return source metadata for a field, defaulting to the schema default.+ pub(crate) fn field(&self, path: &str) -> super::ValueProvenance {+ self.fields.get(path).cloned().unwrap_or_default()+ }++ /// Iterate over recorded fields without exposing or retaining config values.+ pub(crate) fn fields(&self) -> impl Iterator<Item = (&str, &ValueProvenance)> {+ self.fields+ .iter()+ .map(|(path, provenance)| (path.as_str(), provenance))+ }++ /// Whether a logical config field or any of its descendants was supplied+ /// explicitly instead of coming from schema defaults.+ pub(crate) fn has_explicit_under(&self, path: &str) -> bool {+ self.fields.iter().any(|(candidate, provenance)| {+ let is_field_or_descendant = candidate == path+ || candidate+ .strip_prefix(path)+ .is_some_and(|suffix| suffix.starts_with('.') || suffix.starts_with("[]"));+ is_field_or_descendant && provenance.source != ProvenanceSource::Default+ })+ }++ pub(crate) fn set_dotenv(&mut self, dotenv: Option<DotenvLoadProvenance>) {+ self.dotenv = dotenv;+ }+}++fn record_toml_paths(+ value: &toml::Value,+ path: &mut String,+ fields: &mut BTreeMap<String, ValueProvenance>,+) {+ match value {+ toml::Value::Table(table) if !table.is_empty() => {+ if !path.is_empty() {+ fields.insert(+ path.clone(),+ ValueProvenance {+ source: ProvenanceSource::File,+ env_var: None,+ file_also_set: false,+ },+ );+ }+ for (key, child) in table {+ let original_len = path.len();+ if !path.is_empty() {+ path.push('.');+ }+ path.push_str(key);+ record_toml_paths(child, path, fields);+ path.truncate(original_len);+ }+ }+ toml::Value::Array(values) if values.iter().any(toml::Value::is_table) => {+ if !path.is_empty() {+ fields.insert(+ path.clone(),+ ValueProvenance {+ source: ProvenanceSource::File,+ env_var: None,+ file_also_set: false,+ },+ );+ }+ for child in values.iter().filter(|child| child.is_table()) {+ let original_len = path.len();+ path.push_str("[]");+ record_toml_paths(child, path, fields);+ path.truncate(original_len);+ }+ }+ _ => {+ if !path.is_empty() {+ fields.insert(+ path.clone(),+ ValueProvenance {+ source: ProvenanceSource::File,+ env_var: None,+ file_also_set: false,+ },+ );+ }+ }+ }+}++static CURRENT_DOTENV_LOAD: OnceLock<Mutex<Option<DotenvLoadProvenance>>> = OnceLock::new();++fn current_dotenv_slot() -> &'static Mutex<Option<DotenvLoadProvenance>> {+ CURRENT_DOTENV_LOAD.get_or_init(|| Mutex::new(None))+}++pub(crate) fn set_current_dotenv_load(load: Option<DotenvLoadProvenance>) {+ *current_dotenv_slot()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = load;+}++pub(crate) fn current_dotenv_load() -> Option<DotenvLoadProvenance> {+ current_dotenv_slot()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone()+}++pub(crate) fn dotenv_loaded_variable(name: &str) -> bool {+ current_dotenv_slot()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .is_some_and(|load| load.loaded_vars.iter().any(|loaded| loaded == name))+}++impl crate::config::schema::Config {+ pub(crate) fn load_provenance(&self) -> &ConfigProvenance {+ &self.runtime_state.provenance+ }++ pub(crate) fn load_provenance_mut(&mut self) -> &mut ConfigProvenance {+ &mut self.runtime_state.provenance+ }+}diff --git a/crates/openhuman-core/src/config/schema/load/provenance_tests.rs b/crates/openhuman-core/src/config/schema/load/provenance_tests.rsnew file mode 100644index 0000000000..7dbf215ec7--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/provenance_tests.rs@@ -0,0 +1,116 @@+use super::{ConfigProvenance, DotenvLoadProvenance, ProvenanceSource};+use std::path::PathBuf;++#[test]+fn environment_override_reports_source_and_whether_the_file_also_set_it() {+ let document: toml::Value = toml::from_str(r#"default_model = "file-model""#).unwrap();+ let mut provenance = ConfigProvenance::default();+ provenance.record_file_keys(&document);+ provenance.record_env_override(+ "default_model",+ "OPENHUMAN_DEFAULT_MODEL",+ ProvenanceSource::Env,+ );++ let entry = provenance.field("default_model");+ assert_eq!(entry.source, ProvenanceSource::Env);+ assert_eq!(entry.env_var.as_deref(), Some("OPENHUMAN_DEFAULT_MODEL"));+ assert!(entry.file_also_set);+ assert!(!format!("{provenance:?}").contains("file-model"));+}++#[test]+fn unoverridden_values_report_file_or_default_without_values() {+ let document: toml::Value = toml::from_str(+ r#"+default_model = "file-model"+[agent]+tool_dispatcher = "native"+"#,+ )+ .unwrap();+ let provenance = ConfigProvenance::from_file_document(&document);++ assert_eq!(+ provenance.field("default_model").source,+ ProvenanceSource::File+ );+ assert_eq!(+ provenance.field("agent.tool_dispatcher").source,+ ProvenanceSource::File+ );+ assert_eq!(+ provenance.field("output_language").source,+ ProvenanceSource::Default+ );+ assert!(!format!("{provenance:?}").contains("file-model"));+ assert!(!format!("{provenance:?}").contains("native"));+}++#[test]+fn explicit_subtree_lookup_matches_exact_and_descendant_paths_only() {+ let document: toml::Value =+ toml::from_str("[memory]\nengine = \"tinyhumans\"\n[search]\nenabled = true\n").unwrap();+ let provenance = ConfigProvenance::from_file_document(&document);++ assert!(provenance.has_explicit_under("memory"));+ assert!(provenance.has_explicit_under("memory.engine"));+ assert!(provenance.has_explicit_under("search.enabled"));+ assert!(!provenance.has_explicit_under("mem"));+ assert!(!provenance.has_explicit_under("memory_config"));+}++#[test]+fn every_serialized_config_field_has_file_or_default_source_when_no_env_is_applied() {+ let config = super::config_from_toml_str(+ r#"+default_model = "file-model"+[agent]+tool_dispatcher = "native"+"#,+ )+ .unwrap();+ let serialized = serde_json::to_value(&config).unwrap();+ assert_config_sources(&serialized, "", config.load_provenance());+}++fn assert_config_sources(value: &serde_json::Value, path: &str, provenance: &ConfigProvenance) {+ match value {+ serde_json::Value::Object(object) => {+ for (key, child) in object {+ let child_path = if path.is_empty() {+ key.clone()+ } else {+ format!("{path}.{key}")+ };+ assert_config_sources(child, &child_path, provenance);+ }+ }+ serde_json::Value::Array(items) if items.iter().any(serde_json::Value::is_object) => {+ for item in items {+ assert_config_sources(item, &format!("{path}[]"), provenance);+ }+ }+ _ => {+ let source = provenance.field(path).source;+ assert!(+ matches!(source, ProvenanceSource::File | ProvenanceSource::Default),+ "{path} reported unexpected source {source:?}"+ );+ }+ }+}++#[test]+fn dotenv_record_keeps_the_loaded_path_and_only_names_of_shadowed_variables() {+ let record = DotenvLoadProvenance::from_variables(+ PathBuf::from("/workspace/.env"),+ ["DOTENV_ONLY", "PROCESS_WINS"],+ ["PROCESS_WINS"],+ );++ assert_eq!(record.path, PathBuf::from("/workspace/.env"));+ assert_eq!(record.skipped_vars, ["PROCESS_WINS"]);+ assert_eq!(record.loaded_vars, ["DOTENV_ONLY"]);+ assert!(!format!("{record:?}").contains("secret"));+}diff --git a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rsindex d13daa0c16..ab91286d2c 100644--- a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs+++ b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs@@ -1,5 +1,50 @@use super::*;+#[test]+fn default_model_provenance_records_environment_precedence_without_values() {+ let mut cfg = config_from_toml_str(r#"default_model = "file-model""#).unwrap();+ cfg.apply_env_overlay_with(&HashMapEnv::new().with("OPENHUMAN_DEFAULT_MODEL", "env-model"));++ let entry = cfg.load_provenance().field("default_model");+ assert_eq!(entry.source, super::ProvenanceSource::Env);+ assert_eq!(entry.env_var.as_deref(), Some("OPENHUMAN_DEFAULT_MODEL"));+ assert!(entry.file_also_set);+ assert_eq!(cfg.default_model.as_deref(), Some("env-model"));+ assert!(!format!("{:?}", cfg.load_provenance()).contains("env-model"));+}++#[test]+fn blank_explicit_model_env_falls_back_to_legacy_alias_and_records_its_name() {+ for explicit_model in ["", " \t"] {+ let mut cfg = Config::default();+ cfg.apply_env_overlay_with(+ &HashMapEnv::new()+ .with("OPENHUMAN_DEFAULT_MODEL", explicit_model)+ .with("OPENHUMAN_MODEL", "legacy-model"),+ );++ assert_eq!(cfg.default_model.as_deref(), Some("legacy-model"));+ let provenance = cfg.load_provenance().field("default_model");+ assert_eq!(provenance.source, super::ProvenanceSource::Env);+ assert_eq!(provenance.env_var.as_deref(), Some("OPENHUMAN_MODEL"));+ }++ let mut cfg = Config::default();+ cfg.apply_env_overlay_with(+ &HashMapEnv::new()+ .with("OPENHUMAN_DEFAULT_MODEL", "canonical-model")+ .with("OPENHUMAN_MODEL", "legacy-model"),+ );+ assert_eq!(cfg.default_model.as_deref(), Some("canonical-model"));+ assert_eq!(+ cfg.load_provenance()+ .field("default_model")+ .env_var+ .as_deref(),+ Some("OPENHUMAN_DEFAULT_MODEL")+ );+}+#[test]fn env_overlay_model_only_honours_namespaced_var() {// Both set → OPENHUMAN_MODEL wins; bare MODEL is ignored even whendiff --git a/crates/openhuman-core/src/config/schema/types/config.rs b/crates/openhuman-core/src/config/schema/types/config.rsindex 678149760a..cd888492cf 100644--- a/crates/openhuman-core/src/config/schema/types/config.rs+++ b/crates/openhuman-core/src/config/schema/types/config.rs@@ -21,6 +21,11 @@ pub(crate) struct ConfigDocumentSnapshot {#[doc(hidden)]#[derive(Debug, Default)]pub struct ConfigRuntimeState {+ pub(crate) provenance: super::super::load::ConfigProvenance,+ pub(crate) load_diagnostics: super::super::load::LoadDiagnostics,+ pub(crate) doctor_profile_layout_version:+ Option<crate::config::schema::profile_layout::LayoutVersion>,+ pub(crate) doctor_profile_resolution_source: Option<String>,pub(crate) document_snapshot: std::sync::Mutex<ConfigDocumentSnapshot>,pub(crate) context_snapshot: Option<std::sync::Weak<std::sync::Mutex<Config>>>,pub(crate) context_overlay: std::sync::Mutex<@@ -31,6 +36,10 @@ pub struct ConfigRuntimeState {impl Clone for ConfigRuntimeState {fn clone(&self) -> Self {Self {+ provenance: self.provenance.clone(),+ load_diagnostics: self.load_diagnostics.clone(),+ doctor_profile_layout_version: self.doctor_profile_layout_version,+ doctor_profile_resolution_source: self.doctor_profile_resolution_source.clone(),document_snapshot: std::sync::Mutex::new(self.document_snapshot.lock().unwrap().clone(),),@@ -556,6 +565,41 @@ pub struct Config {pub model_registry: Vec<ModelRegistryEntry>,}+impl Config {+ /// Pins read-only doctor selection metadata to this in-memory snapshot.+ pub(crate) fn set_doctor_profile_metadata(+ &mut self,+ layout_version: Option<crate::config::schema::profile_layout::LayoutVersion>,+ resolution_source: Option<String>,+ ) {+ self.runtime_state.doctor_profile_layout_version = layout_version;+ self.runtime_state.doctor_profile_resolution_source = resolution_source;+ }++ /// Metadata recorded when this snapshot was selected for doctor inspection.+ pub(crate) fn doctor_profile_metadata(+ &self,+ ) -> (+ Option<crate::config::schema::profile_layout::LayoutVersion>,+ Option<String>,+ ) {+ (+ self.runtime_state.doctor_profile_layout_version,+ self.runtime_state.doctor_profile_resolution_source.clone(),+ )+ }++ /// Diagnostics captured while the loader parsed or migrated this snapshot.+ pub(crate) fn load_diagnostics(&self) -> &super::super::load::LoadDiagnostics {+ &self.runtime_state.load_diagnostics+ }++ /// Mutable access for the config loader while it assembles diagnostics.+ pub(crate) fn load_diagnostics_mut(&mut self) -> &mut super::super::load::LoadDiagnostics {+ &mut self.runtime_state.load_diagnostics+ }+}+/// Shared default so `#[serde(default)]` and `Config::default()` stay in sync.pub(crate) const DEFAULT_TEMPERATURE: f64 = 0.7;diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rsindex 1dc5d66c53..a1c6fabe77 100644--- a/crates/openhuman-core/src/core/all.rs+++ b/crates/openhuman-core/src/core/all.rs@@ -62,18 +62,18 @@ fn active_domain_set() -> Option<crate::core::runtime::DomainSet> {crate::core::runtime::context::CoreContext::current().map(|c| c.domains())}-/// Whether the given [`DomainGroup`] is enabled under the ambient-/// [`DomainSet`](crate::core::runtime::DomainSet). No active context ⇒ `true`-/// (full, no filter) so pre-boot unit tests and non-context callers see every-/// domain, exactly as before #4796.+/// Whether the given [`DomainGroup`] is enabled under the ambient [`DomainSet`].fn group_allowed(group: DomainGroup) -> bool {active_domain_set().map_or(group != DomainGroup::Operator, |s| s.allows(group))}-/// Whether `g` is live in the ambient scope: its family is enabled and, for a-/// SaaS user, the method is on the user surface (`profiles::surface`).+/// Whether `g` is live in the ambient scope.fn visible(g: &GroupedController) -> bool {- group_allowed(g.group) && on_surface(g)+ let doctor_report = g.controller.rpc_method_name() == "openhuman.doctor_report";+ // Only the shared report bypasses its group gate; surface checks still apply.+ let saas_doctor_report = crate::core::runtime::is_saas() && doctor_report;+ // That surface check denies missing scopes and unrelated Platform methods.+ (group_allowed(g.group) || saas_doctor_report) && on_surface(g)}fn on_surface(g: &GroupedController) -> bool {@@ -383,7 +383,7 @@ fn build_registered_controllers() -> Vec<GroupedController> {push_entries(&mut controllers,DomainGroup::Platform,- crate::platform::doctor::all_doctor_controller_entries(),+ crate::doctor::all_doctor_controller_entries(),);// User-authored hooks — inspect, reload, and test-fire `hooks.json` entries.push(@@ -556,10 +556,10 @@ fn build_registered_controllers() -> Vec<GroupedController> {crate::tools::all_tools_registered_controllers(),);// Unified read-only registry across MCP stdio tools and controller-backed tools- push(+ push_entries(&mut controllers,DomainGroup::Platform,- crate::tools::registry::all_tool_registry_registered_controllers(),+ crate::tools::registry::all_tool_registry_bound_controller_entries(),);// Memory v2 (`docs/specs/memory-v2.md`): engines, recall/fetch/learn/// forget, conversations, document sources, context.md and v1 import.diff --git a/crates/openhuman-core/src/core/all/namespaces.rs b/crates/openhuman-core/src/core/all/namespaces.rsindex e3cb222f9f..fddf73d447 100644--- a/crates/openhuman-core/src/core/all/namespaces.rs+++ b/crates/openhuman-core/src/core/all/namespaces.rs@@ -25,9 +25,9 @@ pub fn namespace_description(namespace: &str) -> Option<&'static str> {"Connectivity diagnostics for the local sidecar, listening port, and backend Socket.IO state.",),"cron" => Some("Manage scheduled jobs and run history."),- "inbound" => Some(- "Inbound event queues: depths and outcome counts, dead letters and redrive.",- ),+ "inbound" => {+ Some("Inbound event queues: depths and outcome counts, dead letters and redrive.")+ }"flows" => Some("Create, store, and run automation workflows."),"dashboard" => {Some("Operator-facing dashboard aggregations: per-model health comparison rows.")diff --git a/crates/openhuman-core/src/core/all_bound_controller_tests.rs b/crates/openhuman-core/src/core/all_bound_controller_tests.rsindex 32cbbd8cbc..158ad76c82 100644--- a/crates/openhuman-core/src/core/all_bound_controller_tests.rs+++ b/crates/openhuman-core/src/core/all_bound_controller_tests.rs@@ -35,6 +35,11 @@ fn staged_bound_methods() -> Vec<&'static str> {"socket.emit","socket.connect_with_session",]);+ methods.extend([+ "tool_registry.list",+ "tool_registry.get",+ "tool_registry.diagnostics",+ ]);#[cfg(feature = "voice")]methods.extend(["voice.status",@@ -714,3 +719,6 @@ mod registry_contract_tests;#[path = "all_keyring_consent_controller_tests.rs"]mod keyring_consent_controller_tests;++#[path = "all_tool_registry_controller_tests.rs"]+mod tool_registry_controller_tests;diff --git a/crates/openhuman-core/src/core/all_doctor_controller_tests.rs b/crates/openhuman-core/src/core/all_doctor_controller_tests.rsindex eb84f338a1..d11eeff8a1 100644--- a/crates/openhuman-core/src/core/all_doctor_controller_tests.rs+++ b/crates/openhuman-core/src/core/all_doctor_controller_tests.rs@@ -14,7 +14,7 @@ fn raw_doctor_platform_registry_matches_its_independent_contract() {registry(),internal_registry(),&contract,- &crate::platform::doctor::doctor_parameter_contracts(),+ &crate::doctor::doctor_parameter_contracts(),).expect("raw Doctor entries retain their ordered wire contracts");let entries: Vec<_> = registry()@@ -22,8 +22,32 @@ fn raw_doctor_platform_registry_matches_its_independent_contract() {.filter(|row| row.controller.schema.namespace == "doctor").collect();let use_cache = TypeSchema::Option(Box::new(TypeSchema::Bool));+ let report_inputs = [+ (+ "tier",+ TypeSchema::Option(Box::new(TypeSchema::Enum {+ variants: vec!["static", "connect", "live"],+ })),+ false,+ ),+ (+ "only",+ TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),+ false,+ ),+ (+ "skip",+ TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),+ false,+ ),+ (+ "profile",+ TypeSchema::Option(Box::new(TypeSchema::String)),+ false,+ ),+ ];assert_eq!(- crate::core::all::verify_wire_fields(&entries[0].controller.schema.inputs, &[]),+ crate::core::all::verify_wire_fields(&entries[0].controller.schema.inputs, &report_inputs,),Ok(()));assert_eq!(@@ -67,7 +91,7 @@ fn raw_doctor_decoders_ignore_unknown_fields_and_keep_boolean_types_strict() {("use_cache".into(), json!("not a boolean")),("nested_extra".into(), json!({"ignored":[1, false]})),]))- .expect("doctor.report ignores the entire parameter map");+ .expect("doctor.report ignores unknown fields and parses declared fields");let models = entries.iter()diff --git a/crates/openhuman-core/src/core/all_registry_tests.rs b/crates/openhuman-core/src/core/all_registry_tests.rsindex 180ad0d7f1..8d24e9038f 100644--- a/crates/openhuman-core/src/core/all_registry_tests.rs+++ b/crates/openhuman-core/src/core/all_registry_tests.rs@@ -1,5 +1,95 @@use super::*;+#[tokio::test]+async fn doctor_report_is_in_both_scoped_saas_dispatch_and_schema_surfaces() {+ use crate::core::runtime::{mode, ContextOverlay, CoreContext, DomainSet, Mode};++ const CHILD: &str = "OPENHUMAN_SAAS_DOCTOR_SURFACE_CHILD";+ let name = "doctor_report_is_in_both_scoped_saas_dispatch_and_schema_surfaces";+ let module = module_path!().split_once("::").expect("crate module").1;+ let exact = format!("{module}::{name}");+ if std::env::var(CHILD).as_deref() != Ok(exact.as_str()) {+ let output =+ std::process::Command::new(std::env::current_exe().expect("test executable path"))+ .args(["--exact", &exact, "--nocapture", "--test-threads=1"])+ .env(CHILD, &exact)+ .output()+ .expect("run isolated SaaS doctor-surface test");+ assert!(+ output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),+ "isolated test {exact} failed:\n{}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ return;+ }++ mode::lock_mode(Mode::Saas).expect("test process uses SaaS mode");+ let doctor = "openhuman.doctor_report";+ let doctor_models = "openhuman.doctor_models";+ let user_domains = crate::profiles::host::user_domains();+ let user_context = CoreContext::for_test(user_domains, None).derive_with(+ ContextOverlay::new(+ crate::config::Config::default(),+ user_domains,+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .profile("alice"),+ );++ let (unscoped_methods, unscoped_schemas) = (+ all_registered_controllers()+ .iter()+ .map(ControllerEntry::rpc_method_name)+ .collect::<Vec<_>>(),+ all_controller_schemas()+ .iter()+ .map(rpc_method_name)+ .collect::<Vec<_>>(),+ );+ let (operator_methods, operator_schemas) =+ CoreContext::scope(CoreContext::for_test(DomainSet::saas(), None), async {+ (+ all_registered_controllers()+ .iter()+ .map(ControllerEntry::rpc_method_name)+ .collect::<Vec<_>>(),+ all_controller_schemas()+ .iter()+ .map(rpc_method_name)+ .collect::<Vec<_>>(),+ )+ })+ .await;+ let (user_methods, user_schemas) = CoreContext::scope(user_context, async {+ (+ all_registered_controllers()+ .iter()+ .map(ControllerEntry::rpc_method_name)+ .collect::<Vec<_>>(),+ all_controller_schemas()+ .iter()+ .map(rpc_method_name)+ .collect::<Vec<_>>(),+ )+ })+ .await;++ assert!(!unscoped_methods.iter().any(|method| method == doctor));+ assert!(!unscoped_schemas.iter().any(|method| method == doctor));+ assert!(operator_methods.iter().any(|method| method == doctor));+ assert!(operator_schemas.iter().any(|method| method == doctor));+ assert!(user_methods.iter().any(|method| method == doctor));+ assert!(user_schemas.iter().any(|method| method == doctor));+ assert!(!operator_methods+ .iter()+ .any(|method| method == doctor_models));+ assert!(!user_methods.iter().any(|method| method == doctor_models));+ assert!(!user_methods+ .iter()+ .any(|method| method == "openhuman.config_get_config"));+}+#[tokio::test]async fn full_registration_is_byte_identical() {// With no ambient CoreContext (⇒ full, no filter), the publicdiff --git a/crates/openhuman-core/src/core/all_tool_registry_controller_tests.rs b/crates/openhuman-core/src/core/all_tool_registry_controller_tests.rsnew file mode 100644index 0000000000..3749e6e295--- /dev/null+++ b/crates/openhuman-core/src/core/all_tool_registry_controller_tests.rs@@ -0,0 +1,136 @@+use super::*;+use serde_json::{json, Map};++fn tool_registry_entries() -> Vec<ControllerEntry> {+ registry()+ .iter()+ .filter(|row| row.controller.schema.namespace == "tool_registry")+ .map(|row| row.controller.clone())+ .collect()+}++#[test]+fn raw_tool_registry_matches_its_independent_contract() {+ let contract = registry_test_support::BoundFamilyWireContract {+ namespaces: &["tool_registry"],+ group: DomainGroup::Platform,+ methods: &[+ ("tool_registry.list", "openhuman.tool_registry_list"),+ ("tool_registry.get", "openhuman.tool_registry_get"),+ (+ "tool_registry.diagnostics",+ "openhuman.tool_registry_diagnostics",+ ),+ ],+ };+ let fixtures = [+ ControllerParamContract {+ method: "tool_registry.list",+ required: &[],+ optional: &[],+ examples: vec![json!({})],+ },+ ControllerParamContract {+ method: "tool_registry.get",+ required: &["tool_id"],+ optional: &[],+ examples: vec![json!({"tool_id":" tools.web_search "})],+ },+ ControllerParamContract {+ method: "tool_registry.diagnostics",+ required: &[],+ optional: &[],+ examples: vec![json!({})],+ },+ ];+ registry_test_support::verify_family_contract(+ registry(),+ internal_registry(),+ &contract,+ &fixtures,+ )+ .expect("raw Tool Registry entries retain ordered bound wire contracts");++ let entries = tool_registry_entries();+ use TypeSchema::{Array, Json, String};+ let expected = [+ (vec![], vec![("tools", Array(Box::new(Json)), true)]),+ (vec![("tool_id", String, true)], vec![("tool", Json, true)]),+ (vec![], vec![("diagnostics", Json, true)]),+ ];+ assert_eq!(entries.len(), expected.len());+ for (entry, (inputs, outputs)) in entries.iter().zip(expected) {+ assert_eq!(+ crate::core::all::verify_wire_fields(&entry.schema.inputs, &inputs),+ Ok(()),+ "{} inputs",+ entry.schema.method_name()+ );+ assert_eq!(+ crate::core::all::verify_wire_fields(&entry.schema.outputs, &outputs),+ Ok(()),+ "{} outputs",+ entry.schema.method_name()+ );+ }+}++#[test]+fn raw_tool_registry_decoders_keep_ignored_maps_and_tool_id_errors() {+ let entries = tool_registry_entries();+ let list = entries+ .iter()+ .find(|entry| entry.schema.function == "list")+ .expect("raw list entry");+ let diagnostics = entries+ .iter()+ .find(|entry| entry.schema.function == "diagnostics")+ .expect("raw diagnostics entry");+ let ignored = Map::from_iter([("ignored".into(), json!({"nested": true}))]);+ list.decode_params(ignored.clone())+ .expect("list ignores its entire parameter map");+ diagnostics+ .decode_params(ignored)+ .expect("diagnostics ignores its entire parameter map");++ let get = entries+ .iter()+ .find(|entry| entry.schema.function == "get")+ .expect("raw get entry");+ get.decode_params(Map::from_iter([+ ("tool_id".into(), json!(" tools.web_search ")),+ ("ignored".into(), json!(true)),+ ]))+ .expect("get accepts a padded id and ignores extra fields");+ for params in [+ Map::new(),+ Map::from_iter([("tool_id".into(), json!(null))]),+ Map::from_iter([("tool_id".into(), json!(false))]),+ Map::from_iter([("tool_id".into(), json!(10))]),+ Map::from_iter([("tool_id".into(), json!([]))]),+ Map::from_iter([("tool_id".into(), json!({}))]),+ Map::from_iter([("tool_id".into(), json!(" "))]),+ ] {+ assert_eq!(+ get.decode_params(params).unwrap_err(),+ "tool_id must be a non-empty string"+ );+ }+}++#[test]+fn raw_tool_registry_get_rejects_invalid_id_before_lookup() {+ let get = tool_registry_entries()+ .into_iter()+ .find(|entry| entry.schema.function == "get")+ .expect("raw get entry");+ for params in [+ Map::new(),+ Map::from_iter([("tool_id".into(), json!(false))]),+ Map::from_iter([("tool_id".into(), json!(" "))]),+ ] {+ let error = futures::executor::block_on(get.invoke(DispatchCtx::unbound(), params))+ .expect_err("invalid id must stop before tool lookup");+ assert_eq!(error, "tool_id must be a non-empty string");+ }+}diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rsindex 2e0a94c9d8..6b6a0af35e 100644--- a/crates/openhuman-core/src/core/cli.rs+++ b/crates/openhuman-core/src/core/cli.rs@@ -9,10 +9,13 @@ use anyhow::Result;use serde_json::{Map, Value};use std::collections::BTreeMap;+use crate::config::schema::load::{set_current_dotenv_load, DotenvLoadProvenance};use crate::core::all;use crate::core::invoke::{default_state, invoke_method};use crate::core::params::parse_json_params;use crate::core::{ControllerSchema, TypeSchema};+use std::collections::HashSet;+use std::path::{Path, PathBuf};/// The ASCII banner displayed when the CLI starts.const CLI_BANNER: &str = r#"@@ -198,6 +201,16 @@ fn parse_launch_options(args: &[String]) -> Result<CliLaunchOptions> {Ok(parsed)}+/// Parse the same leading model/provider flags as the CLI and return the+/// remaining command arguments without applying those transient overrides.+///+/// Hosts that route an inspection command around the normal CLI boot path use+/// this to preserve the launch-argument grammar while keeping the selected+/// inspection configuration unchanged.+pub fn parse_cli_args_after_launch_options(args: &[String]) -> Result<Vec<String>> {+ parse_launch_options(args).map(|options| options.args)+}+fn run_moved_tui_diagnostic() -> Result<()> {anyhow::bail!("the terminal UI is now the separate `openhuman-tui` executable; \@@ -328,19 +341,65 @@ fn run_sentry_test_command(_args: &[String]) -> Result<()> {/// 2. If `OPENHUMAN_DOTENV_PATH` is set, that file is loaded./// 3. Otherwise, it searches for `.env` in the current working directory.pub fn load_dotenv_for_cli() -> Result<()> {+ let previous_dotenv_load = crate::config::schema::load::current_dotenv_load();+ let process_vars = std::env::vars_os()+ .map(|(name, _)| name.to_string_lossy().into_owned())+ .collect::<HashSet<_>>();match std::env::var("OPENHUMAN_DOTENV_PATH") {Ok(path) if !path.trim().is_empty() => {+ let path = PathBuf::from(&path);dotenvy::from_path(&path).map_err(|e| {- anyhow::anyhow!("failed to load dotenv from OPENHUMAN_DOTENV_PATH={path}: {e}")+ anyhow::anyhow!(+ "failed to load dotenv from OPENHUMAN_DOTENV_PATH={}: {e}",+ path.display()+ )})?;+ if let Ok(variables) = dotenv_variable_names(&path) {+ record_dotenv_load(+ path,+ variables,+ &process_vars,+ previous_dotenv_load.as_ref(),+ );+ }}_ => {- let _ = dotenvy::dotenv();+ if let Ok(path) = dotenvy::dotenv() {+ if let Ok(variables) = dotenv_variable_names(&path) {+ record_dotenv_load(+ path,+ variables,+ &process_vars,+ previous_dotenv_load.as_ref(),+ );+ }+ }}}Ok(())}+fn dotenv_variable_names(path: &Path) -> Result<Vec<String>> {+ dotenvy::from_path_iter(path)?+ .map(|entry| entry.map(|(name, _)| name).map_err(anyhow::Error::from))+ .collect()+}++fn record_dotenv_load(+ path: PathBuf,+ variables: Vec<String>,+ process_vars: &HashSet<String>,+ previous: Option<&DotenvLoadProvenance>,+) {+ let mut load = DotenvLoadProvenance::from_variables(+ path,+ variables,+ process_vars.iter().map(String::as_str),+ );+ load.preserve_previous_origin(previous, process_vars);+ set_current_dotenv_load(Some(load));+}+/// Handles the `call` subcommand to invoke a JSON-RPC method directly from the CLI.////// This is used for one-off commands and debugging, bypassing the HTTP transport@@ -501,7 +560,8 @@ fn run_namespace_command(Ok(())}-/// Parses command-line arguments into a JSON map based on a function's schema.+/// Parses namespace-style command-line arguments into a JSON map based on a+/// function's schema, without dispatching the command or starting a runtime.////// # Arguments///@@ -511,7 +571,7 @@ fn run_namespace_command(/// # Errors////// Returns an error if arguments are malformed, unknown, or fail validation.-fn parse_function_params(+pub fn parse_function_params(schema: &ControllerSchema,args: &[String],) -> Result<Map<String, Value>, String> {diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rsindex b8f57c7189..ad5498427c 100644--- a/crates/openhuman-core/src/core/cli_tests.rs+++ b/crates/openhuman-core/src/core/cli_tests.rs@@ -209,15 +209,60 @@ fn load_dotenv_for_cli_reads_cwd_dotenv_without_overwriting_existing_env() {let loaded_backend = std::env::var("BACKEND_URL").ok();let loaded_app_env = std::env::var("OPENHUMAN_APP_ENV").ok();+ let second_result = load_dotenv_for_cli();std::env::set_current_dir(&original_dir).expect("restore current dir");result.expect("dotenv load should succeed");+ second_result.expect("repeated dotenv load should succeed");assert_eq!(loaded_backend.as_deref(),Some("https://staging-api.example.test"));assert_eq!(loaded_app_env.as_deref(), Some("production"));++ let load = crate::config::schema::load::current_dotenv_load()+ .expect("successful dotenv load should record its provenance");+ assert_eq!(+ std::fs::canonicalize(&load.path).expect("recorded dotenv path exists"),+ std::fs::canonicalize(&env_path).expect("loaded dotenv path exists")+ );+ assert_eq!(load.loaded_vars, ["BACKEND_URL"]);+ assert_eq!(load.skipped_vars, ["OPENHUMAN_APP_ENV"]);+}++#[test]+fn load_dotenv_for_cli_keeps_valid_prefix_variables_when_later_line_is_malformed() {+ let _guard = env_lock();+ let tmp = tempdir().expect("tempdir");+ let env_path = tmp.path().join(".env");+ std::fs::write(+ &env_path,+ concat!(+ "OPENHUMAN_DOTENV_PREFIX_TEST=fake-prefix\n",+ "OPENHUMAN_DOTENV_PREEXISTING_TEST=file-value\n",+ "BROKEN=\"unterminated\n"+ ),+ )+ .expect("write malformed dotenv file");+ let _vars = EnvVarGuard::unset("OPENHUMAN_DOTENV_PREFIX_TEST")+ .with("OPENHUMAN_DOTENV_PREEXISTING_TEST", "process-value")+ .with("OPENHUMAN_DOTENV_PATH", env_path.as_os_str());++ let result = load_dotenv_for_cli();++ assert!(+ result.is_err(),+ "malformed dotenv should still return an error"+ );+ assert_eq!(+ std::env::var("OPENHUMAN_DOTENV_PREFIX_TEST").as_deref(),+ Ok("fake-prefix")+ );+ assert_eq!(+ std::env::var("OPENHUMAN_DOTENV_PREEXISTING_TEST").as_deref(),+ Ok("process-value")+ );}// --- `mcp` compile-time gate (#4799) ------------------------------------diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rsindex dc8be6a1d4..a01a51b351 100644--- a/crates/openhuman-core/src/core/runtime/builder.rs+++ b/crates/openhuman-core/src/core/runtime/builder.rs@@ -158,10 +158,27 @@ pub enum TokenSource {EnvOrFile,}+/// Startup work a core runtime performs before it can dispatch in-process RPC.+///+/// Normal runtimes load their workspace stores, bootstrap subscribers and+/// recover interrupted work. Inspection runtimes require a supplied config and+/// fixed bearer, then construct a real context without those persistent boot+/// effects. The selected RPC operation still decides which reads, network+/// probes and opt-in live writes it performs.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub enum CoreBootMode {+ /// Initialize workspace stores and runtime infrastructure as usual.+ #[default]+ Normal,+ /// Build a dispatchable context without startup persistence or services.+ Inspection,+}+/// Builder for a [`CoreRuntime`]. Construct with [`CoreBuilder::new`], then/// [`CoreBuilder::build`] to initialize the core.pub struct CoreBuilder {host_kind: HostKind,+ boot_mode: CoreBootMode,token: TokenSource,services: ServiceSet,domains: DomainSet,@@ -178,6 +195,7 @@ impl CoreBuilder {pub fn new(host_kind: HostKind) -> Self {Self {host_kind,+ boot_mode: CoreBootMode::Normal,token: TokenSource::EnvOrFile,services: ServiceSet::desktop(),domains: DomainSet::full(),@@ -189,6 +207,17 @@ impl CoreBuilder {}}+ /// Select normal startup or a side-effect-limited inspection context.+ ///+ /// [`CoreBootMode::Inspection`] requires [`Self::config`] and a+ /// [`TokenSource::Fixed`] bearer. It never discovers an ambient config,+ /// opens or installs a storage backend, initializes workspace stores,+ /// recovers prior work, or starts background services.+ pub fn boot_mode(mut self, mode: CoreBootMode) -> Self {+ self.boot_mode = mode;+ self+ }+/// Binds hook registrations (see [`crate::core::slots`]) to the context/// this builder creates, ahead of any process-wide registration. Fill an/// [`Extensions`](crate::core::slots::Extensions) with@@ -334,12 +363,28 @@ impl CoreBuilder {/// The init sequence itself is owned by [`CoreContext::init`] (Phase 2,/// Stage A).pub async fn build(self) -> anyhow::Result<CoreRuntime> {- let (ctx, has_operator_token, config) = CoreContext::init_with_config(+ if self.boot_mode == CoreBootMode::Inspection {+ anyhow::ensure!(+ self.config.is_some(),+ "inspection boot requires a caller-supplied config"+ );+ anyhow::ensure!(+ matches!(&self.token, TokenSource::Fixed(_)),+ "inspection boot requires a process-local fixed RPC bearer"+ );+ anyhow::ensure!(+ crate::storage::installed().is_none(),+ "inspection boot requires no installed storage backend"+ );+ }++ let (ctx, has_operator_token, config) = CoreContext::init_with_boot_mode(self.host_kind,&self.token,self.domains,self.tool_groups.clone(),self.config,+ self.boot_mode,).await?;ctx.extensions().merge_from(&self.extensions);@@ -352,8 +397,10 @@ impl CoreBuilder {// Retired scheduled jobs must be pruned before `build()` exposes// in-process RPC or agent turns. Running this from `serve()` is too// late for embedders that only build and invoke.- if let Some(cfg) = config.as_ref() {- crate::core::runtime::services::run_legacy_migrations(cfg).await;+ if self.boot_mode == CoreBootMode::Normal {+ if let Some(cfg) = config.as_ref() {+ crate::core::runtime::services::run_legacy_migrations(cfg).await;+ }}// Reap agent runs orphaned by a previous process (crash / restart /@@ -365,14 +412,20 @@ impl CoreBuilder {// status store has no executor to advance it and would be listed as// active forever. Best-effort — a store that cannot be read logs and// reaps nothing rather than failing the build.- if let Some(cfg) = config.as_ref() {- crate::agent::tinyagents::reaper::reap_orphaned_runs(&cfg.workspace_dir).await;+ if self.boot_mode == CoreBootMode::Normal {+ if let Some(cfg) = config.as_ref() {+ crate::agent::tinyagents::reaper::reap_orphaned_runs(&cfg.workspace_dir).await;+ }}Ok(CoreRuntime {ctx,config,- services: components.narrow_services(self.services),+ services: if self.boot_mode == CoreBootMode::Inspection {+ ServiceSet::none()+ } else {+ components.narrow_services(self.services)+ },has_operator_token,host: self.host,port: self.port,diff --git a/crates/openhuman-core/src/core/runtime/builder_tests.rs b/crates/openhuman-core/src/core/runtime/builder_tests.rsindex c6c59bb68c..7db953eb15 100644--- a/crates/openhuman-core/src/core/runtime/builder_tests.rs+++ b/crates/openhuman-core/src/core/runtime/builder_tests.rs@@ -1,5 +1,14 @@-use super::{DomainSet, ServiceSet};+use super::{CoreBootMode, CoreBuilder, DomainSet, ServiceSet};use crate::core::all::DomainGroup;+use crate::core::types::HostKind;++#[test]+fn core_builder_defaults_to_normal_boot_mode() {+ assert_eq!(+ CoreBuilder::new(HostKind::Library).boot_mode,+ CoreBootMode::Normal+ );+}#[test]fn domain_set_presets_have_expected_flags() {diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rsindex 8714008268..b30b55bb5f 100644--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@ -18,7 +18,6 @@use std::future::Future;use std::sync::{Arc, OnceLock, RwLock};-use crate::core::runtime::TokenSource;use crate::core::types::HostKind;#[path = "context_accessors.rs"]@@ -135,200 +134,10 @@ pub struct CoreContext {/// The workspace a context is bound to.struct WorkspaceBinding {workspace_dir: Option<std::path::PathBuf>,+ config_path: Option<std::path::PathBuf>,}impl CoreContext {- /// Run the core initialization sequence and return the context plus whether- /// an operator-supplied RPC bearer exists (for the public-bind safety check- /// in `openhuman_rpc::server::serve`) plus the loaded config, when boot reached- /// workspace-bound init. Order is load-bearing and mirrors the original- /// `run_server_inner` sequence:- ///- /// 1. register controllers, 2. master key, 3. seed RPC bearer,- /// 4. workspace stores ([`init_stores`]), 5. pure runtime registration.- ///- /// `preloaded_config` lets an embedder supply the [`Config`] outright- /// instead of having step 4 discover one from disk and the environment. See- /// [`init_with_config`](Self::init_with_config) for why that matters.- pub async fn init(- host_kind: HostKind,- token: &TokenSource,- domains: crate::core::runtime::DomainSet,- ) -> anyhow::Result<(Arc<CoreContext>, bool, Option<crate::config::Config>)> {- Self::init_with_config(host_kind, token, domains, Default::default(), None).await- }-- /// [`init`](Self::init) with an optional caller-supplied configuration.- ///- /// Passing `Some(config)` skips `Config::load_or_init()` entirely — the- /// config is used verbatim, exactly as loaded config would be. This is the- /// seam that lets a library embedder configure the core with struct fields- /// rather than by mutating the process environment before `build()`, which- /// is order-dependent, process-global, and invisible at the call site.- ///- /// Note it does not make the core hermetic on its own: `init_stores`, the- /// session database and the keyring still write beneath- /// `config.workspace_dir`. It decides *where*, not *whether*.- pub async fn init_with_config(- host_kind: HostKind,- token: &TokenSource,- mut domains: crate::core::runtime::DomainSet,- mut tool_groups: crate::tools::toolpacks::ToolGroups,- preloaded_config: Option<crate::config::Config>,- ) -> anyhow::Result<(Arc<CoreContext>, bool, Option<crate::config::Config>)> {- log::debug!(- "[core-context] init: host_kind={host_kind:?} domains={domains:?} \- tool_groups={tool_groups:?}"- );- crate::core::runtime::mode::admit_core(host_kind, DEFAULT_CONTEXT.get().is_some())- .map_err(|e| anyhow::anyhow!("[core-context] {e}"))?;- // 1. Ensure all controllers are registered before anything dispatches.- let _ = crate::core::all::all_registered_controllers();-- // 2. Load the master encryption key before any config/credential op that- // needs to decrypt secrets. No-op if already called (e.g. from- // run_core_from_args for the CLI).- if let Some(config) = &preloaded_config {- crate::security::secret_storage::init_workspace(&config.workspace_dir);- }- crate::security::secret_storage::init_master_key().map_err(anyhow::Error::msg)?;-- // 4. Seed the per-process RPC bearer. `Fixed` seeds the in-memory value- // directly (never touches the env); `EnvOrFile` reads- // OPENHUMAN_CORE_TOKEN or generates + writes {root}/core.token.- //- // `has_operator_token` records whether an OPERATOR-supplied bearer- // exists (in-memory handoff or env var). The self-generated core.token- // file does NOT count — remote clients cannot read it — so it must not- // satisfy the public-bind safety check in `serve`.- let has_operator_token = match token {- TokenSource::Fixed(token) => {- crate::core::auth::init_rpc_token_with_value(token)?;- !token.trim().is_empty()- }- TokenSource::EnvOrFile => {- // A caller-supplied config scopes the core's state, so a- // self-generated bearer must land beside it rather than under- // the operator's real `~/.openhuman` root — otherwise an- // "ephemeral" harness still writes a `core.token` into the- // operator's install. Fall back to the default root only when- // no config was supplied.- let token_dir = preloaded_config- .as_ref()- .map(|cfg| {- cfg.config_path- .parent()- .map(|p| p.to_path_buf())- .unwrap_or_else(|| cfg.config_path.clone())- })- .unwrap_or_else(|| {- crate::config::default_root_openhuman_dir().unwrap_or_else(|_| {- dirs::home_dir()- .unwrap_or_else(|| std::path::PathBuf::from("."))- .join(".openhuman")- })- });- crate::core::auth::init_rpc_token(&token_dir)?;- std::env::var(crate::core::auth::CORE_TOKEN_ENV_VAR)- .ok()- .filter(|s| !s.trim().is_empty())- .is_some()- }- };-- // 5. Resolve config once, then initialize workspace-bound stores- // (memory, attachments, people) with that exact workspace.- // Kept for the context: `preloaded_config` is consumed below, and the- // whole point is that handlers can reach it after boot.- let embedder_config = preloaded_config.clone();- let latest_embedder_config = embedder_config.clone().map(|config| {- let snapshot = Arc::new(std::sync::Mutex::new(config));- crate::config::Config::bind_context_snapshot(&snapshot);- snapshot- });- let loaded = match preloaded_config {- // A supplied config is authoritative: no disk read, no env overlay,- // and no `Err` arm to reach, because there was nothing to fail.- Some(cfg) => {- log::debug!("[core-context] init: using caller-supplied config (scoped workspace)");- Ok(cfg)- }- None => crate::config::Config::load_or_init().await,- };- // `[components]` can only narrow what the host chose.- let components = match &loaded {- Ok(cfg) => crate::core::runtime::ComponentSet::from_config(&cfg.components),- Err(_) => crate::core::runtime::ComponentSet::all(),- };- domains = components.narrow_domains(domains);- tool_groups = components.narrow_tool_groups(tool_groups);- log::debug!("[core-context] init: components={components:?} effective domains={domains:?}");- let config = match loaded {- Ok(cfg) => {- init_stores(&cfg, domains).await;- Some(cfg)- }- Err(e) => {- log::error!(- "[boot] workspace-bound store init SKIPPED — \- Config::load_or_init failed ({e:#}). Memory persistence is \- DISABLED for this run; no silent fallback to the default \- workspace (which would cause chunk loss / cross-workspace \- bleed-over). Fix config.toml or set OPENHUMAN_WORKSPACE to a \- writable path, then restart."- );- None- }- };- let workspace_dir = config.as_ref().map(|cfg| cfg.workspace_dir.clone());-- // Construct and publish the context before bootstrap. Host-installed- // session providers may resolve their cold-boot recovery workspace via- // CoreContext, which does not exist until this point.- let ctx = Arc::new(CoreContext {- host_kind,- workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {- workspace_dir: workspace_dir.clone(),- }))),- domains,- tool_groups,- autonomy_tier_source: if embedder_config.is_some() {- super::AutonomyTierSource::Captured- } else {- super::AutonomyTierSource::LiveConfig- },- autonomy_tier_ceiling: None,- components,- embedder_config,- latest_embedder_config,- user_skill_roots: true,- extensions: Default::default(),- turn_origin: None,- channel_thread: None,- session_agent: None,- profile: None,- agent: Default::default(),- bare: false,- });- let _ = DEFAULT_CONTEXT.set(ctx.clone());-- // 6. Long-lived runtime infrastructure: event bus, domain subscribers,- // ledgers, agent-definition registry, live security policy, approval- // gate, socket manager. Idempotent (Once-guarded internally). Selected- // background jobs start later, from CoreRuntime::start_services(), after a transport binds- // succeeds.- let runtime_config = config.clone();- super::bootstrap::bootstrap_core_runtime(- host_kind,- config,- domains,- &super::DispatchCtx::new(ctx.clone()),- )- .await;-- Ok((ctx, has_operator_token, runtime_config))- }-/// The host that constructed this context (Tauri shell / CLI / Docker).pub fn host_kind(&self) -> HostKind {self.host_kind@@ -369,7 +178,7 @@ impl CoreContext {/// process default; scoped readers observe its config and policy.pub fn derive_with(&self, overlay: ContextOverlay) -> Arc<CoreContext> {let parent_config = self.latest_embedder_config();- self.derive_with_parent_config_inner(parent_config.as_ref(), overlay)+ self.derive_with_parent_config_inner(parent_config.as_ref(), overlay, false)}/// Derive a child using the exact parent configuration it was built from.@@ -383,13 +192,14 @@ impl CoreContext {parent_config: &crate::config::Config,overlay: ContextOverlay,) -> Arc<CoreContext> {- self.derive_with_parent_config_inner(Some(parent_config), overlay)+ self.derive_with_parent_config_inner(Some(parent_config), overlay, false)}fn derive_with_parent_config_inner(&self,parent_config: Option<&crate::config::Config>,mut overlay: ContextOverlay,+ fresh_state: bool,) -> Arc<CoreContext> {// Clamped to what this context can already dispatch. A derived// overlay may only narrow: callers outside this crate (embed's@@ -399,6 +209,11 @@ impl CoreContext {// caller of `derive_with` cannot widen a restricted parent's domains// just by omitting that check.let domains = self.domains.intersect(&overlay.domains);+ let components = if fresh_state {+ crate::core::runtime::ComponentSet::from_config(&overlay.config.components)+ } else {+ self.components+ };if domains != overlay.domains {log::warn!("[core-context] derive: overlay requested domains={:?} wider than \@@ -416,9 +231,10 @@ impl CoreContext {overlay.tool_groups,overlay.user_skill_roots);- // A derived context over the parent's workspace shares the parent's- // binding handle, so a workspace rebind reaches it. One that carries- // another workspace keeps that override.+ // A derived context over the parent's workspace and config root shares+ // its current binding snapshot. A later parent rebind replaces the+ // parent's handle, leaving already-derived work on the prior binding.+ // Another workspace or config root gets its own binding from the start.let shared_binding = {let parent_handle = self.workspace_binding.read();let parent_handle = parent_handle@@ -428,16 +244,19 @@ impl CoreContext {let can_share = parent_handle.as_ref().is_some_and(|handle| {handle.read().ok().is_some_and(|parent| {parent.workspace_dir.as_deref() == Some(overlay.config.workspace_dir.as_path())+ && parent.config_path.as_deref()+ == Some(overlay.config.config_path.as_path())})});match (can_share, parent_handle.as_ref()) {(true, Some(handle)) => Arc::clone(handle),_ => Arc::new(RwLock::new(WorkspaceBinding {workspace_dir: Some(overlay.config.workspace_dir.clone()),+ config_path: Some(overlay.config.config_path.clone()),})),}};- let agent = self.agent.derive(&mut overlay);+ let agent = self.agent.derive(&mut overlay, fresh_state);config_access::record_context_config_overlay(self.profile(), parent_config, &mut overlay);overlay.config.runtime_state.context_snapshot = None;let latest_embedder_config = Some(Arc::new(std::sync::Mutex::new(overlay.config.clone())));@@ -449,6 +268,7 @@ impl CoreContext {workspace_binding: RwLock::new(shared_binding),domains,tool_groups: overlay.tool_groups,+ components,autonomy_tier_source: overlay.autonomy_tier_source.unwrap_or(self.autonomy_tier_source),@@ -456,7 +276,6 @@ impl CoreContext {self.autonomy_tier_ceiling,overlay.autonomy_tier_ceiling,),- components: self.components,embedder_config: Some(overlay.config),latest_embedder_config,user_skill_roots: overlay.user_skill_roots,@@ -492,6 +311,26 @@ impl CoreContext {})}+ /// The workspace and config path hint from one binding snapshot. The hint+ /// is captured during normal boot even when no embedder config was supplied.+ pub(crate) fn workspace_config_binding(+ &self,+ ) -> Result<(std::path::PathBuf, Option<std::path::PathBuf>), String> {+ let handle = self+ .workspace_binding+ .read()+ .map_err(|e| format!("workspace unavailable: context lock poisoned: {e}"))?;+ let binding = handle+ .read()+ .map_err(|e| format!("workspace unavailable: binding lock poisoned: {e}"))?;+ let workspace = binding.workspace_dir.clone().ok_or_else(|| {+ "workspace unavailable: Config::load_or_init failed during core boot; \+ fix config.toml or OPENHUMAN_WORKSPACE and restart"+ .to_string()+ })?;+ Ok((workspace, binding.config_path.clone()))+ }+/// The context for the current dispatch: the one scoped by/// [`CoreContext::scope`] if inside a scope, else the process/// [`DEFAULT_CONTEXT`]. Returns `None` only before any context is built@@ -513,6 +352,13 @@ impl CoreContext {/// passed to [`CoreContext::scope`] explicitly and are not the process/// default.pub fn rebind_default_workspace(workspace_dir: &std::path::Path) -> Result<(), String> {+ Self::rebind_default_workspace_with_config(workspace_dir, None)+ }++ pub(crate) fn rebind_default_workspace_with_config(+ workspace_dir: &std::path::Path,+ config_path: Option<&std::path::Path>,+ ) -> Result<(), String> {let Some(ctx) = DEFAULT_CONTEXT.get() else {log::debug!("[core-context] default context not initialized; skipped workspace rebind to {}",@@ -520,20 +366,25 @@ impl CoreContext {);return Ok(());};- ctx.rebind_workspace(workspace_dir)+ ctx.rebind_workspace(workspace_dir, config_path)}- fn rebind_workspace(&self, workspace_dir: &std::path::Path) -> Result<(), String> {+ pub(crate) fn rebind_workspace(+ &self,+ workspace_dir: &std::path::Path,+ config_path: Option<&std::path::Path>,+ ) -> Result<(), String> {let mut binding_handle = self.workspace_binding.write().map_err(|e| format!("workspace rebind failed: binding handle lock poisoned: {e}"))?;- let already = binding_handle- .read()- .map_err(|e| format!("workspace rebind failed: binding lock poisoned: {e}"))?- .workspace_dir- .as_deref()- == Some(workspace_dir);+ let already = {+ let binding = binding_handle+ .read()+ .map_err(|e| format!("workspace rebind failed: binding lock poisoned: {e}"))?;+ binding.workspace_dir.as_deref() == Some(workspace_dir)+ && binding.config_path.as_deref() == config_path+ };if already {log::debug!("[core-context] workspace {} already bound",@@ -547,6 +398,7 @@ impl CoreContext {);*binding_handle = Arc::new(RwLock::new(WorkspaceBinding {workspace_dir: Some(workspace_dir.to_path_buf()),+ config_path: config_path.map(std::path::Path::to_path_buf),}));Ok(())}@@ -604,112 +456,12 @@ impl CoreContext {/// workspace (Sentry OPENHUMAN-CORE-48), the workspace-bound init is skipped/// entirely; the server still comes up and the operator sees the loud error./// Per-`DomainGroup` gating decision for each workspace-bound store that-/// [`init_stores`] initializes. Extracted as a pure value so the store-gating-/// mapping (which store is owned by which `DomainGroup`) has a single source of-/// truth that `init_stores` consumes and tests assert directly — without-/// touching process-global store state or booting a runtime (#4796 DoD item 3).-///-/// The keyring-path log and the credentials Sentry bind in `init_stores` are-/// intentionally *not* represented here: they are unguarded core infra every-/// `DomainSet` needs.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub struct StoreInitPlan {- /// Reporting the memory engine binding (`memory::engine`) — gated on- /// [`DomainGroup::Memory`].- pub memory: bool,- /// `agent::multimodal` attachments sidecar dir — gated on [`DomainGroup::Agent`].- pub agent_attachments: bool,- /// legacy-workflow prune under `skills::registry` — gated on [`DomainGroup::Skills`].- pub skills_prune: bool,-}--impl StoreInitPlan {- /// The store-init plan for `domains`. Pure: no side effects, no globals.- pub fn for_domains(domains: crate::core::runtime::DomainSet) -> Self {- use crate::core::all::DomainGroup;- Self {- memory: domains.allows(DomainGroup::Memory),- agent_attachments: domains.allows(DomainGroup::Agent),- skills_prune: domains.allows(DomainGroup::Skills),- }- }-}+#[path = "context_store_init.rs"]+mod store_init;+pub use store_init::{init_stores, StoreInitPlan};-pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runtime::DomainSet) {- let plan = StoreInitPlan::for_domains(domains);-- let keyring_dir = crate::security::secret_storage::store::workspace_dir_for_file_backend();- // Keyring path log + credentials Sentry bind (below) are unguarded — they- // are core infra every DomainSet needs. Each workspace-bound store init is- // gated on its owning DomainGroup so an excluded domain's store stays- // uninitialized under `harness()`/`none()` (#4796 DoD item 3).- log::info!(- "[boot] paths: config={} workspace={} keyring_dir={} keyring_backend={} domains={:?}",- cfg.config_path.display(),- cfg.workspace_dir.display(),- keyring_dir.display(),- crate::security::secret_storage::backend_name(),- domains,- );- if plan.memory {- let binding = crate::memory::engine::resolve(cfg);- match &binding {- crate::memory::engine::Binding::On(bound) => {- log::info!("[boot] memory engine bound: id={}", bound.id)- }- crate::memory::engine::Binding::Off { reason, .. } => {- log::info!("[boot] memory is off: {reason}")- }- }- } else {- log::debug!("[boot] memory engine bind SKIPPED — Memory domain disabled");- }- // Install the on-disk image-attachment sidecar dir so inbound- // image markers persist under <workspace>/attachments/ instead- // of an in-memory FIFO (survives restarts + delegation hops).- // Also fires a best-effort stale-file sweep.- if plan.agent_attachments {- crate::agent::multimodal::init_attachments_dir(cfg.workspace_dir.join("attachments"));- log::info!(- "[boot] image attachments sidecar dir = {}",- cfg.workspace_dir.join("attachments").display()- );- } else {- log::debug!("[boot] image attachments sidecar dir SKIPPED — Agent domain disabled");- }- // (The WhatsApp data store moved to the Tauri shell; the core no longer- // initializes it here. The shell lazily opens it from its own workspace- // dir when the first ingest / query arrives.)- // Prune legacy bundled skills (dev-workflow / github-issue-crusher- // / pr-review-shepherd) that older builds seeded into- // <workspace>/skills/. OpenHuman no longer ships bundled defaults;- // this removes the stale dirs on upgrade. Idempotent.- if plan.skills_prune {- crate::skills::registry::prune_legacy_default_workflows(&cfg.workspace_dir);- } else {- log::debug!("[boot] skills legacy-workflow prune SKIPPED — Skills domain disabled");- }- // Boot-time Sentry user binding — issue #3135. If the user is- // already signed in (typical desktop restart), the auth-profile- // store has their `user_id` *now*, before any background loop- // (Composio sync tick, cron, etc.) fires its first event.- // Reading from the store here means subsequent events carry- // `user.id` even when no `app_state_snapshot` RPC has run yet.- match crate::security::credentials::session_support::build_session_state(cfg) {- Ok(state) => {- if let Some(uid) = state.user_id.as_deref() {- crate::security::credentials::sentry_scope::bind(uid);- }- // The host-supplied user payload survives restarts in the profile- // store; seed the identity slot from it so prompt composition sees- // the signed-in user before any host RPC runs.- crate::security::credentials::identity::set_current_user(state.user);- }- Err(e) => {- log::debug!("[boot] sentry scope user bind skipped — build_session_state failed: {e}")- }- }-}+#[path = "context_boot.rs"]+mod boot;#[path = "context_turn_origin.rs"]mod turn_origin_scope;@@ -720,6 +472,9 @@ mod for_agent_scope;#[path = "context_agent.rs"]mod agent_parts;+#[path = "context_inspection.rs"]+mod inspection;+#[path = "context_overlay.rs"]mod overlay;pub use overlay::{AutonomyTierSource, ContextOverlay};diff --git a/crates/openhuman-core/src/core/runtime/context_agent.rs b/crates/openhuman-core/src/core/runtime/context_agent.rsindex 8d198d0f0a..b487f72352 100644--- a/crates/openhuman-core/src/core/runtime/context_agent.rs+++ b/crates/openhuman-core/src/core/runtime/context_agent.rs@@ -32,7 +32,7 @@ impl Default for AgentParts {impl AgentParts {/// The parts of a context derived from one owning `self` with `overlay`./// An overlay that names an agent gets state slots of its own.- pub(super) fn derive(&self, overlay: &mut ContextOverlay) -> Self {+ pub(super) fn derive(&self, overlay: &mut ContextOverlay, fresh_state: bool) -> Self {Self {host_overrides: overlay.host_overrides@@ -44,7 +44,7 @@ impl AgentParts {.definitions.take().or_else(|| self.definitions.clone()),- state: if overlay.session_agent.is_some() || overlay.profile.is_some() {+ state: if fresh_state || overlay.session_agent.is_some() || overlay.profile.is_some() {Default::default()} else {Arc::clone(&self.state)diff --git a/crates/openhuman-core/src/core/runtime/context_boot.rs b/crates/openhuman-core/src/core/runtime/context_boot.rsnew file mode 100644index 0000000000..30f2bc55a3--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/context_boot.rs@@ -0,0 +1,247 @@+use super::*;+use crate::core::runtime::TokenSource;++impl CoreContext {+ /// Run the core initialization sequence and return the context plus whether+ /// an operator-supplied RPC bearer exists (for the public-bind safety check+ /// in `openhuman_rpc::server::serve`) plus the loaded config, when boot reached+ /// workspace-bound init. Order is load-bearing and mirrors the original+ /// `run_server_inner` sequence:+ ///+ /// 1. register controllers, 2. master key, 3. seed RPC bearer,+ /// 4. workspace stores ([`init_stores`]), 5. pure runtime registration.+ ///+ /// `preloaded_config` lets an embedder supply the [`Config`] outright+ /// instead of having step 4 discover one from disk and the environment. See+ /// [`init_with_config`](Self::init_with_config) for why that matters.+ pub async fn init(+ host_kind: HostKind,+ token: &TokenSource,+ domains: crate::core::runtime::DomainSet,+ ) -> anyhow::Result<(Arc<CoreContext>, bool, Option<crate::config::Config>)> {+ Self::init_with_config(host_kind, token, domains, Default::default(), None).await+ }++ /// [`init`](Self::init) with an optional caller-supplied configuration.+ ///+ /// Passing `Some(config)` skips `Config::load_or_init()` entirely — the+ /// config is used verbatim, exactly as loaded config would be. This is the+ /// seam that lets a library embedder configure the core with struct fields+ /// rather than by mutating the process environment before `build()`, which+ /// is order-dependent, process-global, and invisible at the call site.+ ///+ /// Note it does not make the core hermetic on its own: `init_stores`, the+ /// session database and the keyring still write beneath+ /// `config.workspace_dir`. It decides *where*, not *whether*.+ pub async fn init_with_config(+ host_kind: HostKind,+ token: &TokenSource,+ domains: crate::core::runtime::DomainSet,+ tool_groups: crate::tools::toolpacks::ToolGroups,+ preloaded_config: Option<crate::config::Config>,+ ) -> anyhow::Result<(Arc<CoreContext>, bool, Option<crate::config::Config>)> {+ Self::init_with_boot_mode(+ host_kind,+ token,+ domains,+ tool_groups,+ preloaded_config,+ crate::core::runtime::CoreBootMode::Normal,+ )+ .await+ }++ /// [`init_with_config`](Self::init_with_config) with an explicit startup+ /// policy. Inspection mode uses the supplied config but skips every+ /// persistent workspace/bootstrap effect while retaining a real dispatch+ /// context.+ pub(crate) async fn init_with_boot_mode(+ host_kind: HostKind,+ token: &TokenSource,+ mut domains: crate::core::runtime::DomainSet,+ mut tool_groups: crate::tools::toolpacks::ToolGroups,+ preloaded_config: Option<crate::config::Config>,+ boot_mode: crate::core::runtime::CoreBootMode,+ ) -> anyhow::Result<(Arc<CoreContext>, bool, Option<crate::config::Config>)> {+ if boot_mode == crate::core::runtime::CoreBootMode::Inspection {+ anyhow::ensure!(+ preloaded_config.is_some(),+ "inspection boot requires a caller-supplied config"+ );+ anyhow::ensure!(+ matches!(token, TokenSource::Fixed(_)),+ "inspection boot requires a process-local fixed RPC bearer"+ );+ }+ log::debug!(+ "[core-context] init: host_kind={host_kind:?} domains={domains:?} \+ tool_groups={tool_groups:?}"+ );+ crate::core::runtime::mode::admit_core(host_kind, DEFAULT_CONTEXT.get().is_some())+ .map_err(|e| anyhow::anyhow!("[core-context] {e}"))?;+ // 1. Ensure all controllers are registered before anything dispatches.+ let _ = crate::core::all::all_registered_controllers();++ // 2. Load the master encryption key before any config/credential op that+ // needs to decrypt secrets. No-op if already called (e.g. from+ // run_core_from_args for the CLI).+ if boot_mode == crate::core::runtime::CoreBootMode::Normal {+ if let Some(config) = &preloaded_config {+ crate::security::secret_storage::init_workspace(&config.workspace_dir);+ }+ crate::security::secret_storage::init_master_key().map_err(anyhow::Error::msg)?;+ }++ // 4. Seed the per-process RPC bearer. `Fixed` seeds the in-memory value+ // directly (never touches the env); `EnvOrFile` reads+ // OPENHUMAN_CORE_TOKEN or generates + writes {root}/core.token.+ //+ // `has_operator_token` records whether an OPERATOR-supplied bearer+ // exists (in-memory handoff or env var). The self-generated core.token+ // file does NOT count — remote clients cannot read it — so it must not+ // satisfy the public-bind safety check in `serve`.+ let has_operator_token = match token {+ TokenSource::Fixed(token) => {+ crate::core::auth::init_rpc_token_with_value(token)?;+ !token.trim().is_empty()+ }+ TokenSource::EnvOrFile => {+ // A caller-supplied config scopes the core's state, so a+ // self-generated bearer must land beside it rather than under+ // the operator's real `~/.openhuman` root — otherwise an+ // "ephemeral" harness still writes a `core.token` into the+ // operator's install. Fall back to the default root only when+ // no config was supplied.+ let token_dir = preloaded_config+ .as_ref()+ .map(|cfg| {+ cfg.config_path+ .parent()+ .map(|p| p.to_path_buf())+ .unwrap_or_else(|| cfg.config_path.clone())+ })+ .unwrap_or_else(|| {+ crate::config::default_root_openhuman_dir().unwrap_or_else(|_| {+ dirs::home_dir()+ .unwrap_or_else(|| std::path::PathBuf::from("."))+ .join(".openhuman")+ })+ });+ crate::core::auth::init_rpc_token(&token_dir)?;+ std::env::var(crate::core::auth::CORE_TOKEN_ENV_VAR)+ .ok()+ .filter(|s| !s.trim().is_empty())+ .is_some()+ }+ };++ // 5. Resolve config once, then initialize workspace-bound stores+ // (memory, attachments, people) with that exact workspace.+ // Kept for the context: `preloaded_config` is consumed below, and the+ // whole point is that handlers can reach it after boot.+ let embedder_config = preloaded_config.clone();+ let latest_embedder_config = embedder_config.clone().map(|config| {+ let snapshot = Arc::new(std::sync::Mutex::new(config));+ crate::config::Config::bind_context_snapshot(&snapshot);+ snapshot+ });+ let loaded = match preloaded_config {+ // A supplied config is authoritative: no disk read, no env overlay,+ // and no `Err` arm to reach, because there was nothing to fail.+ Some(cfg) => {+ log::debug!("[core-context] init: using caller-supplied config (scoped workspace)");+ Ok(cfg)+ }+ None => crate::config::Config::load_or_init().await,+ };+ // `[components]` can only narrow what the host chose.+ let components = match &loaded {+ Ok(cfg) => crate::core::runtime::ComponentSet::from_config(&cfg.components),+ Err(_) => crate::core::runtime::ComponentSet::all(),+ };+ domains = components.narrow_domains(domains);+ tool_groups = components.narrow_tool_groups(tool_groups);+ log::debug!("[core-context] init: components={components:?} effective domains={domains:?}");+ let config = match loaded {+ Ok(cfg) => {+ if boot_mode == crate::core::runtime::CoreBootMode::Normal {+ init_stores(&cfg, domains).await;+ }+ Some(cfg)+ }+ Err(e) => {+ log::error!(+ "[boot] workspace-bound store init SKIPPED — \+ Config::load_or_init failed ({e:#}). Memory persistence is \+ DISABLED for this run; no silent fallback to the default \+ workspace (which would cause chunk loss / cross-workspace \+ bleed-over). Fix config.toml or set OPENHUMAN_WORKSPACE to a \+ writable path, then restart."+ );+ None+ }+ };+ let workspace_dir = config.as_ref().map(|cfg| cfg.workspace_dir.clone());++ // Construct the runtime context before bootstrap. Inspection contexts+ // stay local and no-store; normal hosts still publish the process+ // default before their session provider can request it.+ let ctx = if boot_mode == crate::core::runtime::CoreBootMode::Inspection {+ super::CoreContext::for_runtime_inspection(+ config+ .clone()+ .expect("inspection boot validated its preloaded config"),+ host_kind,+ domains,+ tool_groups,+ )+ } else {+ let context = Arc::new(CoreContext {+ host_kind,+ workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {+ workspace_dir: workspace_dir.clone(),+ config_path: config.as_ref().map(|cfg| cfg.config_path.clone()),+ }))),+ domains,+ tool_groups,+ autonomy_tier_source: if embedder_config.is_some() {+ super::AutonomyTierSource::Captured+ } else {+ super::AutonomyTierSource::LiveConfig+ },+ autonomy_tier_ceiling: None,+ components,+ embedder_config,+ latest_embedder_config,+ user_skill_roots: true,+ extensions: Default::default(),+ turn_origin: None,+ channel_thread: None,+ session_agent: None,+ profile: None,+ agent: Default::default(),+ bare: false,+ });+ let _ = DEFAULT_CONTEXT.set(context.clone());+ context+ };++ // 6. Long-lived runtime infrastructure: event bus, domain subscribers,+ // ledgers, agent-definition registry, live security policy, approval+ // gate, socket manager. Idempotent (Once-guarded internally). Selected+ // background jobs start later, from CoreRuntime::start_services(), after a transport binds+ // succeeds.+ let runtime_config = config.clone();+ if boot_mode == crate::core::runtime::CoreBootMode::Normal {+ crate::core::runtime::bootstrap::bootstrap_core_runtime(+ host_kind,+ config,+ domains,+ &crate::core::runtime::DispatchCtx::new(ctx.clone()),+ )+ .await;+ }++ Ok((ctx, has_operator_token, runtime_config))+ }+}diff --git a/crates/openhuman-core/src/core/runtime/context_for_agent.rs b/crates/openhuman-core/src/core/runtime/context_for_agent.rsindex 897a962608..d2886abab7 100644--- a/crates/openhuman-core/src/core/runtime/context_for_agent.rs+++ b/crates/openhuman-core/src/core/runtime/context_for_agent.rs@@ -24,7 +24,7 @@ impl CoreContext {self.tool_groups.clone(),).session_agent(agent);- let parts = self.agent.derive(&mut overlay);+ let parts = self.agent.derive(&mut overlay, false);Arc::new(CoreContext {host_kind: self.host_kind,workspace_binding: RwLock::new(binding),diff --git a/crates/openhuman-core/src/core/runtime/context_inspection.rs b/crates/openhuman-core/src/core/runtime/context_inspection.rsnew file mode 100644index 0000000000..cd96010f9f--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/context_inspection.rs@@ -0,0 +1,64 @@+use super::*;++impl CoreContext {+ /// Derive a no-store context for read-only inspection under a selected+ /// config. It inherits host registrations and policies while owning fresh+ /// agent state slots; the parent's tenant and agent identities are retained.+ pub fn derive_for_inspection(&self, mut overlay: ContextOverlay) -> Arc<CoreContext> {+ let components =+ crate::core::runtime::ComponentSet::from_config(&overlay.config.components);+ overlay.domains = components.narrow_domains(overlay.domains);+ overlay.tool_groups = components.narrow_tool_groups(overlay.tool_groups);+ let parent_config = self.latest_embedder_config();+ self.derive_with_parent_config_inner(parent_config.as_ref(), overlay, true)+ }++ /// Construct a no-store inspection context before runtime boot. It carries+ /// the supplied config only for the scoped inspection and does not publish+ /// a process-default context or initialize stores.+ pub fn for_inspection(config: crate::config::Config) -> Arc<CoreContext> {+ Self::for_runtime_inspection(+ config,+ HostKind::Cli,+ crate::core::runtime::DomainSet::full(),+ Default::default(),+ )+ }++ /// Build an inspection runtime context while retaining the host's selected+ /// domains and tool groups. The builder merges its scoped extensions after+ /// this constructor returns.+ pub(super) fn for_runtime_inspection(+ config: crate::config::Config,+ host_kind: HostKind,+ domains: crate::core::runtime::DomainSet,+ tool_groups: crate::tools::toolpacks::ToolGroups,+ ) -> Arc<CoreContext> {+ let components = crate::core::runtime::ComponentSet::from_config(&config.components);+ let domains = components.narrow_domains(domains);+ let tool_groups = components.narrow_tool_groups(tool_groups);+ let latest_embedder_config = Some(Arc::new(std::sync::Mutex::new(config.clone())));+ Arc::new(CoreContext {+ host_kind,+ workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {+ workspace_dir: Some(config.workspace_dir.clone()),+ config_path: Some(config.config_path.clone()),+ }))),+ domains,+ tool_groups,+ autonomy_tier_source: super::AutonomyTierSource::Captured,+ autonomy_tier_ceiling: None,+ components,+ embedder_config: Some(config),+ latest_embedder_config,+ user_skill_roots: true,+ extensions: Default::default(),+ turn_origin: None,+ channel_thread: None,+ session_agent: None,+ profile: None,+ agent: Default::default(),+ bare: false,+ })+ }+}diff --git a/crates/openhuman-core/src/core/runtime/context_store_init.rs b/crates/openhuman-core/src/core/runtime/context_store_init.rsnew file mode 100644index 0000000000..9cea0b2ab1--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/context_store_init.rs@@ -0,0 +1,108 @@+//! Workspace-bound store initialization and its domain gating plan.++/// [`init_stores`] initializes. Extracted as a pure value so the store-gating+/// mapping (which store is owned by which `DomainGroup`) has a single source of+/// truth that `init_stores` consumes and tests assert directly — without+/// touching process-global store state or booting a runtime (#4796 DoD item 3).+///+/// The keyring-path log and the credentials Sentry bind in `init_stores` are+/// intentionally *not* represented here: they are unguarded core infra every+/// `DomainSet` needs.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct StoreInitPlan {+ /// Reporting the memory engine binding (`memory::engine`) — gated on+ /// [`DomainGroup::Memory`].+ pub memory: bool,+ /// `agent::multimodal` attachments sidecar dir — gated on [`DomainGroup::Agent`].+ pub agent_attachments: bool,+ /// legacy-workflow prune under `skills::registry` — gated on [`DomainGroup::Skills`].+ pub skills_prune: bool,+}++impl StoreInitPlan {+ /// The store-init plan for `domains`. Pure: no side effects, no globals.+ pub fn for_domains(domains: crate::core::runtime::DomainSet) -> Self {+ use crate::core::all::DomainGroup;+ Self {+ memory: domains.allows(DomainGroup::Memory),+ agent_attachments: domains.allows(DomainGroup::Agent),+ skills_prune: domains.allows(DomainGroup::Skills),+ }+ }+}++pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runtime::DomainSet) {+ let plan = StoreInitPlan::for_domains(domains);++ let keyring_dir = crate::security::secret_storage::store::workspace_dir_for_file_backend();+ // Keyring path log + credentials Sentry bind (below) are unguarded — they+ // are core infra every DomainSet needs. Each workspace-bound store init is+ // gated on its owning DomainGroup so an excluded domain's store stays+ // uninitialized under `harness()`/`none()` (#4796 DoD item 3).+ log::info!(+ "[boot] paths: config={} workspace={} keyring_dir={} keyring_backend={} domains={:?}",+ cfg.config_path.display(),+ cfg.workspace_dir.display(),+ keyring_dir.display(),+ crate::security::secret_storage::backend_name(),+ domains,+ );+ if plan.memory {+ let binding = crate::memory::engine::resolve(cfg);+ match &binding {+ crate::memory::engine::Binding::On(bound) => {+ log::info!("[boot] memory engine bound: id={}", bound.id)+ }+ crate::memory::engine::Binding::Off { reason, .. } => {+ log::info!("[boot] memory is off: {reason}")+ }+ }+ } else {+ log::debug!("[boot] memory engine bind SKIPPED — Memory domain disabled");+ }+ // Install the on-disk image-attachment sidecar dir so inbound+ // image markers persist under <workspace>/attachments/ instead+ // of an in-memory FIFO (survives restarts + delegation hops).+ // Also fires a best-effort stale-file sweep.+ if plan.agent_attachments {+ crate::agent::multimodal::init_attachments_dir(cfg.workspace_dir.join("attachments"));+ log::info!(+ "[boot] image attachments sidecar dir = {}",+ cfg.workspace_dir.join("attachments").display()+ );+ } else {+ log::debug!("[boot] image attachments sidecar dir SKIPPED — Agent domain disabled");+ }+ // (The WhatsApp data store moved to the Tauri shell; the core no longer+ // initializes it here. The shell lazily opens it from its own workspace+ // dir when the first ingest / query arrives.)+ // Prune legacy bundled skills (dev-workflow / github-issue-crusher+ // / pr-review-shepherd) that older builds seeded into+ // <workspace>/skills/. OpenHuman no longer ships bundled defaults;+ // this removes the stale dirs on upgrade. Idempotent.+ if plan.skills_prune {+ crate::skills::registry::prune_legacy_default_workflows(&cfg.workspace_dir);+ } else {+ log::debug!("[boot] skills legacy-workflow prune SKIPPED — Skills domain disabled");+ }+ // Boot-time Sentry user binding — issue #3135. If the user is+ // already signed in (typical desktop restart), the auth-profile+ // store has their `user_id` *now*, before any background loop+ // (Composio sync tick, cron, etc.) fires its first event.+ // Reading from the store here means subsequent events carry+ // `user.id` even when no `app_state_snapshot` RPC has run yet.+ match crate::security::credentials::session_support::build_session_state(cfg) {+ Ok(state) => {+ if let Some(uid) = state.user_id.as_deref() {+ crate::security::credentials::sentry_scope::bind(uid);+ }+ // The host-supplied user payload survives restarts in the profile+ // store; seed the identity slot from it so prompt composition sees+ // the signed-in user before any host RPC runs.+ crate::security::credentials::identity::set_current_user(state.user);+ }+ Err(e) => {+ log::debug!("[boot] sentry scope user bind skipped — build_session_state failed: {e}")+ }+ }+}diff --git a/crates/openhuman-core/src/core/runtime/context_test_support.rs b/crates/openhuman-core/src/core/runtime/context_test_support.rsindex 12d2a8f3c9..ad3eb8f29a 100644--- a/crates/openhuman-core/src/core/runtime/context_test_support.rs+++ b/crates/openhuman-core/src/core/runtime/context_test_support.rs@@ -17,6 +17,7 @@ impl CoreContext {host_kind: HostKind::Cli,workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {workspace_dir,+ config_path: None,}))),domains,tool_groups: Default::default(),@@ -81,6 +82,7 @@ impl CoreContext {host_kind: HostKind::Cli,workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {workspace_dir: Some(config.workspace_dir.clone()),+ config_path: Some(config.config_path.clone()),}))),domains,tool_groups: Default::default(),@@ -99,4 +101,19 @@ impl CoreContext {bare: false,})}++ /// Test-only constructor for a normal-boot binding with its resolved config+ /// path, without exposing an embedder config snapshot.+ pub(crate) fn for_test_with_boot_config_path(+ domains: crate::core::runtime::DomainSet,+ workspace_dir: std::path::PathBuf,+ config_path: std::path::PathBuf,+ ) -> Arc<CoreContext> {+ let mut ctx = Arc::try_unwrap(Self::for_test(domains, None)).ok().unwrap();+ ctx.workspace_binding = RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {+ workspace_dir: Some(workspace_dir),+ config_path: Some(config_path),+ })));+ Arc::new(ctx)+ }}diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rsindex 075d4e6df1..a6ced639c4 100644--- a/crates/openhuman-core/src/core/runtime/context_tests.rs+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs@@ -6,6 +6,7 @@ fn ctx(dir: &str) -> Arc<CoreContext> {host_kind: HostKind::Cli,workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {workspace_dir: Some(PathBuf::from(dir)),+ config_path: None,}))),domains: crate::core::runtime::DomainSet::full(),tool_groups: Default::default(),@@ -369,6 +370,7 @@ fn degraded_context_rejects_workspace_bound_stores() {host_kind: HostKind::Cli,workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {workspace_dir: None,+ config_path: None,}))),domains: crate::core::runtime::DomainSet::full(),tool_groups: Default::default(),@@ -403,3 +405,14 @@ fn degraded_context_rejects_workspace_bound_stores() {#[path = "context_turn_origin_tests.rs"]mod turn_origin_tests;+#[test]+fn inspection_context_uses_captured_autonomy_tier_without_a_ceiling() {+ let context = CoreContext::for_inspection(crate::config::Config::default());++ assert_eq!(+ context.autonomy_tier_source(),+ AutonomyTierSource::Captured,+ "inspection runs against its explicitly supplied config snapshot"+ );+ assert_eq!(context.autonomy_tier_ceiling(), None);+}diff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin.rsindex c4f85620cc..8d1be5d4da 100644--- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs@@ -36,6 +36,7 @@ impl CoreContext {host_kind: HostKind::Cli,workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {workspace_dir: None,+ config_path: None,}))),domains: crate::core::runtime::DomainSet::full(),tool_groups: Default::default(),diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rsindex 3b7acd4f84..c0eb42722e 100644--- a/crates/openhuman-core/src/core/runtime/mod.rs+++ b/crates/openhuman-core/src/core/runtime/mod.rs@@ -63,7 +63,7 @@ pub(crate) mod subscribers;pub mod tenant;pub use agent_scope::{agent_scope_dir, slot_for, AgentContextRegistry, AgentScopedState};-pub use builder::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};+pub use builder::{CoreBootMode, CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};pub use context::{AutonomyTierSource, ContextOverlay, CoreContext};pub use dispatch_ctx::DispatchCtx;pub use mode::{current_mode, is_saas, Mode};diff --git a/crates/openhuman-core/src/doctor/README.md b/crates/openhuman-core/src/doctor/README.mdnew file mode 100644index 0000000000..a479b63a19--- /dev/null+++ b/crates/openhuman-core/src/doctor/README.md@@ -0,0 +1,107 @@+# Doctor++The doctor domain runs configuration and runtime diagnostics and returns a+versioned `DoctorReport`. Checks have stable ids, a cost tier, a finding for+every result, and a fix hint. The core owns the report contract, check registry,+runner, core checks, and JSON-RPC controllers. Host-specific checks register+through the same source interface.++## Contract++`DoctorReport.schema_version` is `2`. A report carries the selected profile+and config source when known, the requested tier, ordered `checks_run` and+`checks_skipped` ids, findings, a severity summary, and `ok`. `ok` is false when+at least one finding has severity `error`; warnings and skipped checks do not+make it false.++Each `Finding` contains its check id, severity (`pass`, `info`, `warn`, `error`,+or `skipped`), safe message, required `fix_hint`, optional config path and+value source, elapsed milliseconds, and affected capability ids. Findings must+not include credentials, resolved config values, request bodies, or user text.+Use a safe error class and a useful recovery step when the original error may+contain sensitive data. A passing check uses “No action required.” as its hint.++## Tiers and selection++| Tier | Runs | Budget |+| --- | --- | --- |+| `static` | Local config and filesystem checks. | 5 seconds per check. |+| `connect` | Static checks and bounded, read-only connectivity probes. This is the default. | 10 seconds per check. |+| `live` | Static and connect checks plus probes that may incur inference cost or write disposable remote test data. | 60 seconds per check. |++The runner allows at most eight checks at once. Synchronous checks run on+Tokio's blocking pool; async checks stay on the runtime. A timeout or failed+worker becomes an error finding and does not stop sibling checks. Tier and+component gates produce `skipped` findings before a detector runs.++`only` and `skip` accept exact registered ids. When `only` is present, checks+outside that list do not appear in the report. `skip` removes checks from the+selected set. Unknown ids add one `doctor/selection` error finding without+echoing the supplied value. Check ids use lowercase slash-separated segments;+duplicate and malformed registrations are rejected before any detector runs.++## Registry and check sources++Built-in checks are composed in `checks/`, with profile checks in `profile.rs`.+Configuration-dependent checks are selected for the report's `DoctorCtx`.+Hosts contribute additional checks through `DoctorCheckSource`:++- `register_check_source` adds a source for the process.+- `register_check_source_in` scopes a source to a `CoreContext` extension set.+- `checks_for(&DoctorCtx)` lets a source choose checks from the effective+ config and profile; context-independent sources may use the default method.++Use a process source for checks independent of the active user or profile. Use+context-scoped registration and the supplied `DoctorCtx` for checks whose ids+or checks depend on that context. `registered_checks_for` combines built-ins,+context-dependent checks, and active host sources, then validates the complete+set before the runner starts.++## Profiles and hosted callers++The active config supplies the default report. A desktop host may select a+profile with `profile`; the doctor loads that profile read-only and reports+selection failures as findings. It does not activate or repair the profile. A+SaaS caller always uses its current tenant context and cannot use the profile+input to inspect another tenant. Hosts should route selected-profile requests+through `doctor_report_for_dispatch` or the explicit profile resolver so the+core uses the host's authorization and profile rules.++## Controller and tool surfaces++The `doctor.report` JSON-RPC controller accepts optional `tier`, exact-id+`only` and `skip` arrays, and `profile`. It returns the v2 report. The CLI host+is a separate consumer of this controller; CLI argument parsing, presentation,+and exit behavior belong in `crates/openhuman-cli`, not in this domain.++The `doctor_health` agent tool accepts optional `tier` and `only`. It defaults+to `connect` and returns the same report contract. Its description tells the+model that `live` may spend inference tokens and is only appropriate when the+user explicitly requested those probes; the tool has no separate user-intent+signal to enforce that policy at execution time.++The `doctor.models` controller and `doctor_models` tool are separate surfaces.+Keep their wire names stable. Catalog inspection uses a dedicated hook that+freezes selected credentials and never falls back to the ordinary mutable+catalog callback.++## Key files++| File | Role |+| --- | --- |+| [`contract.rs`](./contract.rs) | Tiers, check context and source traits, findings, and report types. |+| [`registry.rs`](./registry.rs) | Built-in and host source composition, registration, and id validation. |+| [`runner.rs`](./runner.rs) | Selection, tier/component skips, bounded execution, and report assembly. |+| [`checks/`](./checks/) | Configuration, inference, memory, storage, and context-selected checks. |+| [`profile.rs`](./profile.rs) | Read-only desktop profile loading and profile diagnostics. |+| [`ops.rs`](./ops.rs) | Core report entry points and host-facing profile selection. |+| [`schemas.rs`](./schemas.rs) | JSON-RPC controller schemas and handlers. |+| [`tools.rs`](./tools.rs) | `doctor_health` and `doctor_models` agent tools. |++## Tests++Tests live beside the implementation in `*_tests.rs` files. Use+`test_support::FakeCheck` and context-scoped check sources for runner and tool+tests. Keep tests independent of user skill roots and external services. The+registered-id inventory test under `tools_tests.rs` checks the user guide+against the check registry so documented ids track the code.diff --git a/crates/openhuman-core/src/doctor/checks/channels.rs b/crates/openhuman-core/src/doctor/checks/channels.rsnew file mode 100644index 0000000000..0a21079e46--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/channels.rs@@ -0,0 +1,320 @@+//! Read-only health checks for the configured TinyChannels providers.++use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;+use tinychannels_bus::{ChannelHealthReport, ChannelHealthState, ChannelsConfig, HttpProxyPolicy};++use crate::config::Config;+use crate::doctor::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};++#[cfg(all(feature = "modules", feature = "channels"))]+const MODULE_ID: &str = "tinychannels";+const PROVIDER_TIMEOUT: Duration = Duration::from_secs(10);++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum ChannelHealthFailure {+ Unavailable,+ Failed,+}++#[async_trait]+pub(super) trait ChannelHealthProbe: Send + Sync {+ async fn check(+ &self,+ config: &Config,+ provider: &str,+ proxy: HttpProxyPolicy,+ ) -> Result<Option<Vec<ChannelHealthReport>>, ChannelHealthFailure>;+}++struct ExistingModuleProbe;++#[async_trait]+impl ChannelHealthProbe for ExistingModuleProbe {+ async fn check(+ &self,+ config: &Config,+ provider: &str,+ proxy: HttpProxyPolicy,+ ) -> Result<Option<Vec<ChannelHealthReport>>, ChannelHealthFailure> {+ // Check readiness before reading credentials. `check_existing` repeats+ // this immediately before using the captured proxy, and never resolves+ // a module artifact or starts a runtime.+ if !module_is_ready(config) {+ return Ok(None);+ }++ #[cfg(all(feature = "modules", feature = "channels"))]+ let channels = health_config(config, provider);+ #[cfg(all(feature = "modules", feature = "channels"))]+ return crate::modules::channel_health::check_existing(+ config,+ channels,+ proxy,+ PROVIDER_TIMEOUT,+ )+ .await+ .map_err(|error| match error {+ crate::modules::channel_health::ExistingHealthError::Unavailable => {+ ChannelHealthFailure::Unavailable+ }+ crate::modules::channel_health::ExistingHealthError::Failed => {+ ChannelHealthFailure::Failed+ }+ });+ #[cfg(not(all(feature = "modules", feature = "channels")))]+ {+ let _ = (provider, proxy);+ Ok(None)+ }+ }+}++pub(super) fn for_context(ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ configured_provider_ids(ctx.config())+ .into_iter()+ .map(|provider| {+ Arc::new(ChannelHealthCheck::configured(+ provider,+ Arc::new(ExistingModuleProbe),+ )) as Arc<dyn DoctorCheck>+ })+ .collect()+}++pub(super) struct ChannelHealthCheck {+ id: String,+ provider: String,+ probe: Arc<dyn ChannelHealthProbe>,+}++impl ChannelHealthCheck {+ fn configured(provider: &str, probe: Arc<dyn ChannelHealthProbe>) -> Self {+ Self {+ id: format!("channels/{provider}"),+ provider: provider.to_owned(),+ probe,+ }+ }++ #[cfg(test)]+ fn with_probe(provider: &str, probe: Arc<dyn ChannelHealthProbe>) -> Self {+ Self::configured(provider, probe)+ }++ async fn finding(&self, config: &Config) -> Finding {+ let proxy = proxy_policy(config, &self.provider);+ match self.probe.check(config, &self.provider, proxy).await {+ Ok(None) | Err(ChannelHealthFailure::Unavailable) => Finding::skipped(+ &self.id,+ format!(+ "The {} channel module is not already serving for this run.",+ channel_label(&self.provider)+ ),+ "Start or reconnect the channel through its normal settings, then rerun doctor.",+ ),+ Err(ChannelHealthFailure::Failed) => Finding::error(+ &self.id,+ format!(+ "The {} channel health request failed.",+ channel_label(&self.provider)+ ),+ "Check the channel configuration and its local module status, then rerun doctor.",+ ),+ Ok(Some(reports)) => {+ let Some(report) = reports+ .iter()+ .find(|report| report.channel == self.provider)+ else {+ return Finding::error(+ &self.id,+ "The channel module did not report this configured provider.",+ "Reconnect the provider through channel settings, then rerun doctor.",+ );+ };+ let label = channel_label(&self.provider);+ match report.state {+ ChannelHealthState::Healthy => Finding::pass(&self.id, format!("{label} is healthy.")),+ ChannelHealthState::Unhealthy => Finding::error(+ &self.id,+ format!("{label} is unhealthy (auth/config/network)."),+ "Review the provider credentials and connection settings, then rerun doctor.",+ ),+ ChannelHealthState::Timeout => Finding::error(+ &self.id,+ format!("{label} health check timed out."),+ "Check the provider connection and network policy, then rerun doctor.",+ ),+ }+ }+ }+ }+}++#[async_trait]+impl DoctorCheck for ChannelHealthCheck {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ "channels"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Channels)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ vec![self.finding(ctx.config()).await]+ }+}++fn channel_label(channel: &str) -> String {+ tinychannels_bus::controllers::find_channel_definition(channel)+ .map(|definition| definition.display_name.to_string())+ .unwrap_or_else(|| channel.to_string())+}++fn module_is_ready(config: &Config) -> bool {+ #[cfg(all(feature = "modules", feature = "channels"))]+ {+ config.modules.enabled+ && crate::modules::runtime::existing_runtime().is_some()+ && crate::modules::ops::state_of(MODULE_ID) == crate::modules::types::ModuleState::Ready+ }+ #[cfg(not(all(feature = "modules", feature = "channels")))]+ {+ let _ = config;+ false+ }+}++fn proxy_policy(config: &Config, provider: &str) -> HttpProxyPolicy {+ let service = format!("channel.{provider}");+ let selectors = config+ .proxy+ .should_apply_to_service(&service)+ .then_some(service)+ .into_iter()+ .collect::<Vec<_>>();+ if selectors.is_empty() {+ HttpProxyPolicy::default()+ } else {+ HttpProxyPolicy {+ http_proxy: config.proxy.http_proxy.clone(),+ https_proxy: config.proxy.https_proxy.clone(),+ all_proxy: config.proxy.all_proxy.clone(),+ no_proxy: config.proxy.normalized_no_proxy(),+ service_selectors: selectors,+ }+ }+}++fn health_config(config: &Config, provider: &str) -> ChannelsConfig {+ let mut channels = config.channels_config.clone();+ #[cfg(feature = "channels")]+ {+ if provider == "email" {+ if let Some(email) = channels.email.take() {+ channels.email = Some(+ crate::channels::credentials::resolve_email_password_read_only(email, config),+ );+ }+ }+ if provider == "yuanbao" {+ if let Some(yuanbao) = channels.yuanbao.take() {+ channels.yuanbao = Some(+ crate::channels::credentials::resolve_yuanbao_app_secret_read_only(+ yuanbao, config,+ ),+ );+ }+ }+ }++ channels.cli = false;+ channels.webhook = None;+ channels.relay = None;+ channels.active_channel = None;+ channels.telegram = (provider == "telegram")+ .then(|| config.channels_config.telegram.clone())+ .flatten();+ channels.discord = (provider == "discord")+ .then(|| config.channels_config.discord.clone())+ .flatten();+ channels.slack = (provider == "slack")+ .then(|| config.channels_config.slack.clone())+ .flatten();+ channels.mattermost = (provider == "mattermost")+ .then(|| config.channels_config.mattermost.clone())+ .flatten();+ channels.imessage = (provider == "imessage")+ .then(|| config.channels_config.imessage.clone())+ .flatten();+ channels.matrix = (provider == "matrix")+ .then(|| config.channels_config.matrix.clone())+ .flatten();+ channels.signal = (provider == "signal")+ .then(|| config.channels_config.signal.clone())+ .flatten();+ channels.whatsapp = (provider == "whatsapp")+ .then(|| config.channels_config.whatsapp.clone())+ .flatten();+ channels.linq = (provider == "linq")+ .then(|| config.channels_config.linq.clone())+ .flatten();+ channels.email = (provider == "email")+ .then(|| channels.email.clone())+ .flatten();+ channels.irc = (provider == "irc")+ .then(|| config.channels_config.irc.clone())+ .flatten();+ channels.lark = (provider == "lark")+ .then(|| config.channels_config.lark.clone())+ .flatten();+ channels.dingtalk = (provider == "dingtalk")+ .then(|| config.channels_config.dingtalk.clone())+ .flatten();+ channels.qq = (provider == "qq")+ .then(|| config.channels_config.qq.clone())+ .flatten();+ channels.yuanbao = (provider == "yuanbao")+ .then(|| channels.yuanbao.clone())+ .flatten();+ channels+}++fn configured_provider_ids(config: &Config) -> Vec<&'static str> {+ let channels = &config.channels_config;+ [+ ("telegram", channels.telegram.is_some()),+ ("discord", channels.discord.is_some()),+ ("slack", channels.slack.is_some()),+ ("mattermost", channels.mattermost.is_some()),+ ("imessage", channels.imessage.is_some()),+ ("matrix", channels.matrix.is_some()),+ ("signal", channels.signal.is_some()),+ ("whatsapp", channels.whatsapp.is_some()),+ ("linq", channels.linq.is_some()),+ ("email", channels.email.is_some()),+ ("irc", channels.irc.is_some()),+ ("lark", channels.lark.is_some()),+ ("dingtalk", channels.dingtalk.is_some()),+ ("qq", channels.qq.is_some()),+ ("yuanbao", channels.yuanbao.is_some()),+ ]+ .into_iter()+ .filter_map(|(provider, configured)| configured.then_some(provider))+ .collect()+}++#[cfg(test)]+#[path = "channels_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/channels_tests.rs b/crates/openhuman-core/src/doctor/checks/channels_tests.rsnew file mode 100644index 0000000000..8925e93955--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/channels_tests.rs@@ -0,0 +1,260 @@+use super::*;+use crate::doctor::contract::{DoctorCtx, FindingSeverity};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use tinychannels_bus::{ChannelHealthReport, ChannelHealthState, HttpProxyPolicy};++struct FixedHealth {+ result: Result<Option<Vec<ChannelHealthReport>>, ChannelHealthFailure>,+ calls: Arc<AtomicUsize>,+ readiness_checks: Arc<AtomicUsize>,+ policy: std::sync::Mutex<Option<HttpProxyPolicy>>,+ workspace: std::sync::Mutex<Option<std::path::PathBuf>>,+}++#[async_trait::async_trait]+impl ChannelHealthProbe for FixedHealth {+ async fn check(+ &self,+ config: &crate::config::Config,+ _provider: &str,+ policy: HttpProxyPolicy,+ ) -> Result<Option<Vec<ChannelHealthReport>>, ChannelHealthFailure> {+ self.readiness_checks.fetch_add(1, Ordering::SeqCst);+ if matches!(&self.result, Ok(Some(_))) {+ self.calls.fetch_add(1, Ordering::SeqCst);+ }+ *self.workspace.lock().unwrap() = Some(config.workspace_dir.clone());+ *self.policy.lock().unwrap() = Some(policy);+ self.result.clone()+ }+}++fn config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config+}++fn telegram() -> tinychannels_bus::config::TelegramConfig {+ tinychannels_bus::config::TelegramConfig {+ bot_token: "doctor-test-token".into(),+ chat_id: None,+ allowed_users: vec![],+ stream_mode: Default::default(),+ draft_update_interval_ms: 1_000,+ silent_streaming: true,+ mention_only: false,+ }+}++#[tokio::test]+async fn a_health_timeout_is_an_error_for_the_configured_provider() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let mut config = config_in(scratch.path());+ config.channels_config.telegram = Some(telegram());+ config.proxy.enabled = true;+ config.proxy.scope = crate::config::schema::ProxyScope::Services;+ config.proxy.services = vec!["channel.telegram".into(), "provider.openai".into()];+ config.proxy.http_proxy = Some("http://proxy.example.invalid:3128".into());+ config.proxy.no_proxy = vec!["localhost".into(), ".example.test".into()];++ let calls = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(FixedHealth {+ result: Ok(Some(vec![ChannelHealthReport {+ channel: "telegram".into(),+ state: ChannelHealthState::Timeout,+ }])),+ calls: Arc::clone(&calls),+ readiness_checks: Arc::new(AtomicUsize::new(0)),+ policy: Default::default(),+ workspace: Default::default(),+ });+ let check = ChannelHealthCheck::with_probe("telegram", probe.clone());++ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .into_iter()+ .next()+ .expect("timeout produces a finding");++ assert_eq!(finding.check_id, "channels/telegram");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("timed out"));+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(probe.readiness_checks.load(Ordering::SeqCst), 1);+ assert_eq!(+ probe+ .policy+ .lock()+ .unwrap()+ .as_ref()+ .unwrap()+ .service_selectors,+ vec!["channel.telegram"]+ );+ assert_eq!(+ probe.policy.lock().unwrap().as_ref().unwrap().no_proxy,+ vec![".example.test", "localhost"]+ );+}++#[tokio::test]+async fn an_unavailable_module_is_skipped_without_opening_it() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let mut selected_b = config_in(scratch.path().join("b").as_path());+ selected_b.channels_config.telegram = Some(telegram());++ let calls = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(FixedHealth {+ result: Ok(None),+ calls: Arc::clone(&calls),+ readiness_checks: Arc::new(AtomicUsize::new(0)),+ policy: Default::default(),+ workspace: Default::default(),+ });+ let check = ChannelHealthCheck::with_probe("telegram", probe.clone());+ let finding = check+ .detect(&DoctorCtx::from_config(selected_b))+ .await+ .into_iter()+ .next()+ .expect("missing existing binding is represented");++ assert_eq!(finding.check_id, "channels/telegram");+ assert_eq!(finding.severity, FindingSeverity::Skipped);+ assert_eq!(+ finding.message,+ "The Telegram channel module is not already serving for this run."+ );+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ assert_eq!(probe.readiness_checks.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn a_ready_probe_receives_selected_config_not_ambient_config() {+ let ambient = tempfile::tempdir().expect("create ambient config fixture");+ let selected = tempfile::tempdir().expect("create selected config fixture");+ let mut config_a = config_in(ambient.path());+ config_a.channels_config.imessage = Some(tinychannels_bus::config::IMessageConfig {+ allowed_contacts: vec![],+ });+ let mut config_b = config_in(selected.path());+ config_b.channels_config.telegram = Some(telegram());+ config_b.proxy.enabled = true;+ config_b.proxy.scope = crate::config::schema::ProxyScope::Services;+ config_b.proxy.services = vec!["channel.telegram".into()];+ config_b.proxy.http_proxy = Some("http://selected-b.invalid:8080".into());+ config_b.proxy.no_proxy = vec!["b.internal".into()];++ let calls = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(FixedHealth {+ result: Ok(Some(vec![ChannelHealthReport {+ channel: "telegram".into(),+ state: ChannelHealthState::Healthy,+ }])),+ calls: Arc::clone(&calls),+ readiness_checks: Arc::new(AtomicUsize::new(0)),+ policy: Default::default(),+ workspace: Default::default(),+ });+ let check = ChannelHealthCheck::with_probe("telegram", probe.clone());+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let finding = crate::core::runtime::CoreContext::scope(ambient_context, async {+ let selected_context = DoctorCtx::from_config(config_b.clone()).with_components(+ crate::core::runtime::ComponentSet::from_config(&config_b.components),+ );+ check+ .detect(&selected_context)+ .await+ .into_iter()+ .next()+ .expect("healthy selected provider produces a finding")+ })+ .await;++ assert_eq!(finding.check_id, "channels/telegram");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(probe.readiness_checks.load(Ordering::SeqCst), 1);+ assert_eq!(+ *probe.workspace.lock().unwrap(),+ Some(config_b.workspace_dir.clone())+ );+ let policy = probe.policy.lock().unwrap().clone().unwrap();+ assert_eq!(+ policy.http_proxy.as_deref(),+ Some("http://selected-b.invalid:8080")+ );+ assert_eq!(policy.service_selectors, vec!["channel.telegram"]);+ assert_eq!(policy.no_proxy, vec!["b.internal"]);+}++#[test]+fn channel_labels_use_definition_display_names_and_fall_back_for_unknown_ids() {+ assert_eq!(channel_label("telegram"), "Telegram");+ assert_eq!(channel_label("not-a-channel"), "not-a-channel");+}++#[tokio::test]+async fn configured_channel_ids_come_from_selected_b_not_ambient_a() {+ let ambient = tempfile::tempdir().expect("create ambient config fixture");+ let selected = tempfile::tempdir().expect("create selected config fixture");+ let mut config_a = config_in(ambient.path());+ config_a.channels_config.imessage = Some(tinychannels_bus::config::IMessageConfig {+ allowed_contacts: vec![],+ });+ let mut config_b = config_in(selected.path());+ config_b.channels_config.telegram = Some(telegram());+ config_b.components.channels = false;+ let selected_components = crate::core::runtime::ComponentSet::from_config(&config_b.components);++ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let ids = crate::core::runtime::CoreContext::scope(ambient_context, async {+ let selected_ctx =+ DoctorCtx::from_config(config_b.clone()).with_components(selected_components);+ for_context(&selected_ctx)+ .iter()+ .map(|check| check.id().to_owned())+ .collect::<Vec<_>>()+ })+ .await;++ assert_eq!(ids, vec!["channels/telegram"]);+}++#[tokio::test]+async fn no_configured_channels_register_no_channel_checks() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let config = config_in(scratch.path());+ assert!(for_context(&DoctorCtx::from_config(config)).is_empty());+}++#[cfg(feature = "modules")]+#[tokio::test]+async fn disabled_module_configuration_skips_without_starting_or_loading_the_module() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let mut config = config_in(scratch.path());+ config.modules.enabled = false;+ config.channels_config.imessage = Some(tinychannels_bus::config::IMessageConfig {+ allowed_contacts: vec![],+ });+ let was_started = crate::modules::runtime::is_started();+ let result = ExistingModuleProbe+ .check(&config, "imessage", proxy_policy(&config, "imessage"))+ .await;++ assert_eq!(result.unwrap(), None);+ assert_eq!(crate::modules::runtime::is_started(), was_started);+}diff --git a/crates/openhuman-core/src/doctor/checks/config_file.rs b/crates/openhuman-core/src/doctor/checks/config_file.rsnew file mode 100644index 0000000000..d1f4a28fdf--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/config_file.rs@@ -0,0 +1,288 @@+//! Static checks for config parsing, ignored keys, and legacy-key migrations.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::Value;++use crate::config::schema::load::ConfigLoadFallback;+use crate::config::Config;+use crate::doctor::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};++const CATEGORY: &str = "configuration";++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![+ Arc::new(ConfigParseCheck),+ Arc::new(UnknownConfigKeyCheck),+ Arc::new(LegacyConfigKeyCheck),+ ]+}++struct ConfigParseCheck;++#[async_trait]+impl DoctorCheck for ConfigParseCheck {+ fn id(&self) -> &str {+ "config/parse"+ }++ fn category(&self) -> &str {+ CATEGORY+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let config = ctx.config();+ let diagnostics = config.load_diagnostics();+ let fallback = diagnostics.fallback;+ let recovered = config.recovered_from_corruption;+ let Some(mut finding) = crate::doctor::ops::config_parse_finding(config) else {+ if fallback == ConfigLoadFallback::None && !recovered {+ return Vec::new();+ }++ let message = match fallback {+ ConfigLoadFallback::None => {+ "The config loader recovered after detecting a corrupt config file.".to_owned()+ }+ ConfigLoadFallback::Backup => {+ "The config file was invalid, so the loader used its backup.".to_owned()+ }+ ConfigLoadFallback::Defaults => {+ "The config file and backup were invalid, so the loader used defaults."+ .to_owned()+ }+ };+ return vec![Finding::error(+ self.id(),+ message,+ "Repair config.toml and review any backup before relying on the loaded settings.",+ )];+ };++ finding.check_id = self.id().to_owned();+ match fallback {+ ConfigLoadFallback::None if recovered => {+ finding+ .message+ .push_str(" The loader recovered after detecting a corrupt config file.");+ finding.fix_hint =+ "Repair config.toml and review any backup before relying on the loaded settings."+ .to_owned();+ }+ ConfigLoadFallback::None => {}+ ConfigLoadFallback::Backup => {+ finding+ .message+ .push_str(" The loader recovered using the backup config.");+ finding.fix_hint =+ "Repair config.toml and review the backup before relying on the loaded settings."+ .to_owned();+ }+ ConfigLoadFallback::Defaults => {+ finding+ .message+ .push_str(" The loader used default settings after recovery failed.");+ finding.fix_hint =+ "Repair config.toml and review the backup before relying on the loaded settings."+ .to_owned();+ }+ }+ vec![finding]+ }+}++struct UnknownConfigKeyCheck;++#[async_trait]+impl DoctorCheck for UnknownConfigKeyCheck {+ fn id(&self) -> &str {+ "config/unknown-key"+ }++ fn category(&self) -> &str {+ CATEGORY+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let config = ctx.config();+ let unknown_keys = &config.load_diagnostics().unknown_keys;+ if unknown_keys.is_empty() {+ return Vec::new();+ }++ let schema = serde_json::to_value(Config::default()).ok();+ unknown_keys+ .iter()+ .map(|path| unknown_key_finding(path, schema.as_ref()))+ .collect()+ }+}++fn unknown_key_finding(path: &str, schema: Option<&Value>) -> Finding {+ let leaf = path.rsplit('.').next().unwrap_or(path);+ let suggestion = schema+ .and_then(|schema| known_sibling_keys(schema, path))+ .and_then(|candidates| closest_key(leaf, &candidates));++ let (message, fix_hint) = match suggestion {+ Some(suggestion) => (+ format!("Unknown config key `{leaf}` is ignored; did you mean `{suggestion}`?"),+ format!("Rename `{leaf}` to `{suggestion}` and rerun doctor."),+ ),+ None => (+ format!("Unknown config key `{leaf}` is ignored."),+ "Remove or rename the ignored key to a supported config field.".to_owned(),+ ),+ };+ let mut finding = Finding::new(+ "config/unknown-key",+ FindingSeverity::Warn,+ message,+ fix_hint,+ );+ finding.config_path = Some(path.to_owned());+ finding+}++fn known_sibling_keys(schema: &Value, path: &str) -> Option<Vec<String>> {+ let mut parts = path.split('.').collect::<Vec<_>>();+ let leaf = parts.pop()?;+ if leaf.is_empty() {+ return None;+ }++ let mut parent = schema;+ for part in parts {+ parent = descend_schema_path(parent, part)?;+ }+ let object = parent.as_object()?;+ Some(object.keys().cloned().collect())+}++fn descend_schema_path<'a>(mut value: &'a Value, part: &str) -> Option<&'a Value> {+ let bracket = part.find('[').unwrap_or(part.len());+ if bracket > 0 {+ value = value.as_object()?.get(&part[..bracket])?;+ }+ let mut remaining = &part[bracket..];+ while !remaining.is_empty() {+ let end = remaining.find(']')?;+ let index = remaining.get(1..end)?.parse::<usize>().ok()?;+ value = value.as_array()?.get(index)?;+ remaining = &remaining[end + 1..];+ if remaining.is_empty() {+ break;+ }+ if !remaining.starts_with('[') {+ return None;+ }+ }+ Some(value)+}++fn closest_key(unknown: &str, candidates: &[String]) -> Option<String> {+ let max_distance = (unknown.chars().count() / 3).max(1);+ candidates+ .iter()+ .map(|candidate| (edit_distance(unknown, candidate), candidate))+ .filter(|(distance, _)| *distance <= max_distance)+ .min_by(|(left_distance, left), (right_distance, right)| {+ left_distance+ .cmp(right_distance)+ .then_with(|| left.cmp(right))+ })+ .map(|(_, candidate)| candidate.clone())+}++/// Optimal-string-alignment distance, including adjacent transpositions.+fn edit_distance(left: &str, right: &str) -> usize {+ let left = left.chars().collect::<Vec<_>>();+ let right = right.chars().collect::<Vec<_>>();+ let mut distances = vec![vec![0; right.len() + 1]; left.len() + 1];+ for (index, row) in distances.iter_mut().enumerate() {+ row[0] = index;+ }+ for (index, distance) in distances[0].iter_mut().enumerate() {+ *distance = index;+ }++ for left_index in 1..=left.len() {+ for right_index in 1..=right.len() {+ let substitution = usize::from(left[left_index - 1] != right[right_index - 1]);+ distances[left_index][right_index] = (distances[left_index - 1][right_index] + 1)+ .min(distances[left_index][right_index - 1] + 1)+ .min(distances[left_index - 1][right_index - 1] + substitution);+ if left_index > 1+ && right_index > 1+ && left[left_index - 1] == right[right_index - 2]+ && left[left_index - 2] == right[right_index - 1]+ {+ distances[left_index][right_index] = distances[left_index][right_index]+ .min(distances[left_index - 2][right_index - 2] + 1);+ }+ }+ }+ distances[left.len()][right.len()]+}++struct LegacyConfigKeyCheck;++#[async_trait]+impl DoctorCheck for LegacyConfigKeyCheck {+ fn id(&self) -> &str {+ "config/legacy-key"+ }++ fn category(&self) -> &str {+ CATEGORY+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ ctx.config()+ .load_diagnostics()+ .migrated_keys+ .iter()+ .map(|key| {+ let replacement = replacement_key(key);+ let message = match replacement {+ Some(replacement) => {+ format!("Legacy config key `{key}` was migrated to `{replacement}`.")+ }+ None => format!(+ "Legacy config key `{key}` was migrated to the current config format."+ ),+ };+ let fix_hint = match replacement {+ Some(replacement) => {+ format!("Update the config to use `{replacement}` and remove `{key}`.")+ }+ None => "Update the config to the current format and remove the legacy key."+ .to_owned(),+ };+ let mut finding = Finding::new(self.id(), FindingSeverity::Info, message, fix_hint);+ finding.config_path = Some(key.clone());+ finding+ })+ .collect()+ }+}++fn replacement_key(key: &str) -> Option<&'static str> {+ match key {+ "api_url" => Some("inference_url"),+ _ => None,+ }+}diff --git a/crates/openhuman-core/src/doctor/checks/config_file_tests.rs b/crates/openhuman-core/src/doctor/checks/config_file_tests.rsnew file mode 100644index 0000000000..5ff9188ef8--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/config_file_tests.rs@@ -0,0 +1,103 @@+use crate::config::Config;+use crate::doctor::contract::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};+use crate::doctor::runner;++const PARSE: &str = "config/parse";+const UNKNOWN_KEY: &str = "config/unknown-key";+const LEGACY_KEY: &str = "config/legacy-key";++async fn load_config(contents: &str) -> (tempfile::TempDir, Config) {+ let directory = tempfile::tempdir().expect("temporary config directory");+ let config_path = directory.path().join("config.toml");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).expect("create workspace");+ std::fs::write(&config_path, contents).expect("write config");+ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .expect("load config");+ (directory, config)+}++async fn run_config_check(config: Config, check_id: &str) -> Vec<Finding> {+ runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("selected config doctor check runs")+ .findings+ .into_iter()+ .filter(|finding| finding.check_id == check_id)+ .collect()+}++fn finding(findings: &[Finding], severity: FindingSeverity) -> &Finding {+ findings+ .iter()+ .find(|finding| finding.severity == severity)+ .expect("expected finding severity")+}++#[tokio::test]+async fn unknown_keys_warn_with_a_suggestion_without_exposing_values() {+ let (_directory, config) = load_config("[memroy]\nengine = \"private-value\"\n").await;+ let findings = run_config_check(config, UNKNOWN_KEY).await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert_eq!(warning.config_path.as_deref(), Some("memroy"));+ assert!(warning.message.contains("memory"), "{}", warning.message);+ assert!(!warning.message.contains("private-value"));+}++#[tokio::test]+async fn typed_parse_error_reports_field_path_and_backup_fallback_safely() {+ let directory = tempfile::tempdir().expect("temporary config directory");+ let config_path = directory.path().join("config.toml");+ let backup_path = directory.path().join("config.toml.bak");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).expect("create workspace");+ std::fs::write(&config_path, "[memory]\nengine = 837465\n").expect("write invalid config");+ std::fs::write(&backup_path, "[memory]\nengine = \"backup-engine\"\n")+ .expect("write valid backup");+ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .expect("load config from backup");++ let findings = run_config_check(config, PARSE).await;++ let error = finding(&findings, FindingSeverity::Error);+ assert_eq!(error.config_path.as_deref(), Some("memory.engine"));+ assert!(+ error.message.to_ascii_lowercase().contains("backup"),+ "{}",+ error.message+ );+ assert!(!error.message.contains("837465"));+ assert!(!error+ .message+ .contains(&directory.path().display().to_string()));+}++#[tokio::test]+async fn legacy_keys_report_the_actual_source_key_as_info() {+ let (_directory, config) =+ load_config("api_url = \"https://example.test/v1/chat/completions\"\n").await;+ let findings = run_config_check(config, LEGACY_KEY).await;++ let info = finding(&findings, FindingSeverity::Info);+ assert_eq!(info.config_path.as_deref(), Some("api_url"));+ assert!(info.message.contains("inference_url"), "{}", info.message);+}++#[tokio::test]+async fn clean_default_config_passes_each_config_check() {+ for check_id in [PARSE, UNKNOWN_KEY, LEGACY_KEY] {+ let findings = run_config_check(Config::default(), check_id).await;+ assert_eq!(findings.len(), 1, "{check_id}");+ assert_eq!(findings[0].severity, FindingSeverity::Pass, "{check_id}");+ }+}diff --git a/crates/openhuman-core/src/doctor/checks/config_provenance.rs b/crates/openhuman-core/src/doctor/checks/config_provenance.rsnew file mode 100644index 0000000000..61e583dbe0--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/config_provenance.rs@@ -0,0 +1,132 @@+//! Checks that explain configuration overrides and their non-secret sources.++use async_trait::async_trait;++use crate::config::schema::load::ProvenanceSource;+use crate::config::schema::profile_layout::LayoutVersion;++use super::super::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};++const CATEGORY: &str = "configuration";++pub(super) struct EnvironmentOverrideCheck;++#[async_trait]+impl DoctorCheck for EnvironmentOverrideCheck {+ fn id(&self) -> &str {+ "config/env-override"+ }++ fn category(&self) -> &str {+ CATEGORY+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ ctx.config()+ .load_provenance()+ .fields()+ .filter_map(|(path, provenance)| {+ if !matches!(+ provenance.source,+ ProvenanceSource::Env | ProvenanceSource::Dotenv+ ) {+ return None;+ }+ let source = ctx.value_source_for(path)?;+ let env_var = provenance.env_var.as_deref()?;+ let severity = if provenance.file_also_set {+ FindingSeverity::Warn+ } else {+ FindingSeverity::Info+ };+ let message = if provenance.file_also_set {+ format!(+ "Environment variable `{env_var}` overrides a value explicitly set in the config file."+ )+ } else {+ format!(+ "Environment variable `{env_var}` supplies this value; the config file does not set it explicitly."+ )+ };+ let mut finding = Finding::new(+ self.id(),+ severity,+ message,+ "Choose one source for this setting and remove the shadowed override.",+ );+ finding.config_path = Some(path.to_owned());+ finding.value_source = Some(source);+ Some(finding)+ })+ .collect()+ }+}++pub(super) struct ConfigSourceCheck;++#[async_trait]+impl DoctorCheck for ConfigSourceCheck {+ fn id(&self) -> &str {+ "config/source"+ }++ fn category(&self) -> &str {+ CATEGORY+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let config = ctx.config();+ let provenance = config.load_provenance();+ let mut message = format!("Config file: {}.", config.config_path.display());++ if let Some(dotenv) = provenance.dotenv.as_ref() {+ message.push_str(&format!(" .env file: {}.", dotenv.path.display()));+ if !dotenv.skipped_vars.is_empty() {+ let mut shadowed_vars = dotenv.skipped_vars.clone();+ shadowed_vars.sort();+ shadowed_vars.dedup();+ message.push_str(&format!(+ " .env variables shadowed by the process environment: {}.",+ shadowed_vars.join(", ")+ ));+ }+ } else {+ message.push_str(" No .env file was loaded.");+ }++ if let Some(source) = ctx.profile_resolution_source() {+ message.push_str(&format!(" config_resolution_source: {source}."));+ }+ if let Some(version) = ctx.profile_layout_version() {+ let version = match version {+ LayoutVersion::V1 => 1,+ LayoutVersion::V2 => 2,+ };+ message.push_str(&format!(" profile_layout_version: {version}."));+ }++ let cli_override_active = provenance+ .fields()+ .any(|(_, field)| field.source == ProvenanceSource::Cli);+ message.push_str(&format!(+ " CLI `--model`/`--provider` inference override active: {cli_override_active}."+ ));++ let mut finding = Finding::new(+ self.id(),+ FindingSeverity::Info,+ message,+ "No action required; use these sources when diagnosing configuration precedence.",+ );+ finding.config_path = Some(config.config_path.display().to_string());+ vec![finding]+ }+}diff --git a/crates/openhuman-core/src/doctor/checks/config_provenance_tests.rs b/crates/openhuman-core/src/doctor/checks/config_provenance_tests.rsnew file mode 100644index 0000000000..537b774b8f--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/config_provenance_tests.rs@@ -0,0 +1,230 @@+use crate::config::schema::load::{DotenvLoadProvenance, ProvenanceSource};+use crate::config::Config;++use super::contract::{+ DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity, ValueSource,+};+use super::runner;++const ENV_OVERRIDE: &str = "config/env-override";+const CONFIG_SOURCE: &str = "config/source";++fn config_with_file_env_override() -> Config {+ let mut config = Config::default();+ config.default_model = Some("resolved-model-secret".to_owned());+ config.config_path = "/diagnostics/config.toml".into();+ let document = toml::from_str::<toml::Value>(r#"default_model = "file-model-secret""#)+ .expect("test config document parses");+ config.load_provenance_mut().record_file_keys(&document);+ config.load_provenance_mut().record_env_override(+ "default_model",+ "OPENHUMAN_DEFAULT_MODEL",+ ProvenanceSource::Env,+ );+ config+}++fn selected_findings<'a>(findings: &'a [Finding], check_id: &str) -> Vec<&'a Finding> {+ findings+ .iter()+ .filter(|finding| finding.check_id == check_id)+ .collect()+}++async fn run_config_check(config: Config, check_id: &str) -> Vec<Finding> {+ run_context_check(DoctorCtx::from_config(config), check_id)+ .await+ .findings+}++async fn run_context_check(ctx: DoctorCtx, check_id: &str) -> crate::doctor::DoctorReport {+ runner::run(+ &ctx,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("selected config doctor check runs")+}++#[tokio::test]+async fn environment_override_warns_when_the_file_explicitly_sets_the_field() {+ let findings = run_config_check(config_with_file_env_override(), ENV_OVERRIDE).await;+ let matching = selected_findings(&findings, ENV_OVERRIDE);++ assert_eq!(+ matching.len(),+ 1,+ "one finding identifies the overridden field"+ );+ assert_eq!(matching[0].severity, FindingSeverity::Warn);+ assert_eq!(matching[0].config_path.as_deref(), Some("default_model"));+ assert_eq!(matching[0].value_source, Some(ValueSource::Env));+ assert!(matching[0].message.contains("OPENHUMAN_DEFAULT_MODEL"));+ let serialized = serde_json::to_string(&matching).expect("finding serializes");+ assert!(!serialized.contains("resolved-model-secret"));+ assert!(!serialized.contains("file-model-secret"));+}++#[test]+fn context_value_source_maps_logical_paths_without_labeling_filesystem_paths() {+ let mut config = Config::default();+ let document = toml::from_str::<toml::Value>(r#"default_model = "file-model-secret""#)+ .expect("test config document parses");+ config.load_provenance_mut().record_file_keys(&document);+ config+ .load_provenance_mut()+ .record_cli_override("chat_provider");+ config.load_provenance_mut().record_env_override(+ "modules.overrides[].source",+ "OPENHUMAN_MODULE_SOURCE",+ ProvenanceSource::Dotenv,+ );+ let ctx = DoctorCtx::from_config(config);++ assert_eq!(+ ctx.value_source_for("modules.overrides[2].source"),+ Some(ValueSource::Dotenv)+ );+ assert_eq!(+ ctx.value_source_for("default_model"),+ Some(ValueSource::File)+ );+ assert_eq!(+ ctx.value_source_for("chat_provider"),+ Some(ValueSource::Cli)+ );+ assert_eq!(+ ctx.value_source_for("output_language"),+ Some(ValueSource::Default)+ );+ assert_eq!(ctx.value_source_for("/var/lib/openhuman/config.toml"), None);+ assert_eq!(ctx.value_source_for("config.toml"), None);+}++#[tokio::test]+async fn config_source_reports_the_active_user_directory_resolution_source() {+ let ctx = DoctorCtx::from_config(Config::default()).with_profile_metadata(+ Some(crate::config::schema::profile_layout::LayoutVersion::V2),+ Some("active_user.toml".to_owned()),+ );+ let report = run_context_check(ctx, CONFIG_SOURCE).await;+ let matching = selected_findings(&report.findings, CONFIG_SOURCE);++ assert_eq!(+ report.config_resolution_source.as_deref(),+ Some("active_user.toml")+ );+ assert_eq!(report.profile_layout_version, Some(2));+ assert!(matching.iter().any(|finding| {+ finding+ .message+ .contains("config_resolution_source: active_user.toml")+ && finding.message.contains("profile_layout_version: 2")+ }));+}++#[tokio::test]+async fn environment_override_is_info_when_the_file_does_not_set_the_field() {+ let mut config = Config::default();+ config.load_provenance_mut().record_env_override(+ "agent.tool_dispatcher",+ "OPENHUMAN_TOOL_DISPATCHER",+ ProvenanceSource::Env,+ );++ let findings = run_config_check(config, ENV_OVERRIDE).await;+ let matching = selected_findings(&findings, ENV_OVERRIDE);++ assert_eq!(matching.len(), 1);+ assert_eq!(matching[0].severity, FindingSeverity::Info);+ assert_eq!(+ matching[0].config_path.as_deref(),+ Some("agent.tool_dispatcher")+ );+ assert!(matching[0].message.contains("OPENHUMAN_TOOL_DISPATCHER"));+}++#[tokio::test]+async fn environment_override_check_enumerates_multiple_unrelated_fields() {+ let mut config = config_with_file_env_override();+ config.load_provenance_mut().record_env_override(+ "search.enabled",+ "OPENHUMAN_SEARCH_ENABLED",+ ProvenanceSource::Env,+ );++ let findings = run_config_check(config, ENV_OVERRIDE).await;+ let matching = selected_findings(&findings, ENV_OVERRIDE);+ let by_path = matching+ .iter()+ .map(|finding| {+ (+ finding+ .config_path+ .as_deref()+ .expect("field path is reported"),+ finding.severity,+ )+ })+ .collect::<std::collections::BTreeMap<_, _>>();++ assert_eq!(matching.len(), 2);+ assert_eq!(by_path.get("default_model"), Some(&FindingSeverity::Warn));+ assert_eq!(by_path.get("search.enabled"), Some(&FindingSeverity::Info));+}++#[tokio::test]+async fn dotenv_shadowing_and_paths_are_reported_without_values() {+ let mut config = config_with_file_env_override();+ config+ .load_provenance_mut()+ .set_dotenv(Some(DotenvLoadProvenance::from_variables(+ "/diagnostics/.env".into(),+ ["OPENHUMAN_DEFAULT_MODEL", "OPENHUMAN_OUTPUT_LANGUAGE"],+ ["OPENHUMAN_DEFAULT_MODEL"],+ )));++ let findings = run_config_check(config, CONFIG_SOURCE).await;+ let matching = selected_findings(&findings, CONFIG_SOURCE);++ assert!(+ !matching.is_empty(),+ "config/source describes the active configuration sources"+ );+ let serialized = serde_json::to_string(&matching).expect("finding serializes");+ assert!(serialized.contains("/diagnostics/config.toml"));+ assert!(serialized.contains("/diagnostics/.env"));+ assert!(serialized.contains("OPENHUMAN_DEFAULT_MODEL"));+ assert!(!serialized.contains("resolved-model-secret"));+ assert!(!serialized.contains("file-model-secret"));+}++#[tokio::test]+async fn config_source_reports_active_cli_model_and_provider_overrides() {+ let mut config = Config::default();+ config.config_path = "/diagnostics/config.toml".into();+ config.default_model = Some("private-model-secret".to_owned());+ config.chat_provider = Some("private-provider-secret".to_owned());+ {+ let provenance = config.load_provenance_mut();+ provenance.record_cli_override("default_model");+ provenance.record_cli_override("chat_provider");+ }++ let findings = run_config_check(config, CONFIG_SOURCE).await;+ let matching = selected_findings(&findings, CONFIG_SOURCE);++ assert!(+ !matching.is_empty(),+ "config/source describes the active configuration sources"+ );+ let serialized = serde_json::to_string(&matching).expect("finding serializes");+ assert!(serialized.contains("--model"));+ assert!(serialized.contains("--provider"));+ assert!(!serialized.contains("private-model-secret"));+ assert!(!serialized.contains("private-provider-secret"));+}diff --git a/crates/openhuman-core/src/doctor/checks/config_semantics.rs b/crates/openhuman-core/src/doctor/checks/config_semantics.rsnew file mode 100644index 0000000000..1058cc7043--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/config_semantics.rs@@ -0,0 +1,551 @@+//! Static checks for configuration values that disagree with one another.++use std::sync::Arc;++use async_trait::async_trait;++use crate::config::Config;+use crate::doctor::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};+use crate::storage::{StorageUrl, STORAGE_URL_VAR};+use tinystoragedrivers::{BlobConfig, StorageConfig};++const COMPONENTS_ID: &str = "components/referenced-but-disabled";+const MODULE_FALLBACK_ID: &str = "modules/source-fallback";+const MODULE_OVERRIDE_ID: &str = "modules/override-invalid";+const STORAGE_URL_ID: &str = "storage/url";+const ACTION_DIR_ID: &str = "workspace/action-dir";+const MASTER_KEY_ENV_ID: &str = "secrets/master-key-env";+const PROXY_ID: &str = "network/proxy";+const MEMORY_ROOT_ID: &str = "memory/root";++#[derive(Clone, Copy)]+enum CheckKind {+ Components,+ ModuleFallback,+ InvalidModuleOverride,+ StorageUrl,+ ActionDir,+ MasterKeyEnv,+ Proxy,+ MemoryRoot,+}++impl CheckKind {+ const fn id(self) -> &'static str {+ match self {+ Self::Components => COMPONENTS_ID,+ Self::ModuleFallback => MODULE_FALLBACK_ID,+ Self::InvalidModuleOverride => MODULE_OVERRIDE_ID,+ Self::StorageUrl => STORAGE_URL_ID,+ Self::ActionDir => ACTION_DIR_ID,+ Self::MasterKeyEnv => MASTER_KEY_ENV_ID,+ Self::Proxy => PROXY_ID,+ Self::MemoryRoot => MEMORY_ROOT_ID,+ }+ }++ const fn category(self) -> &'static str {+ match self {+ Self::Components => "components",+ Self::ModuleFallback | Self::InvalidModuleOverride => "modules",+ Self::StorageUrl => "storage",+ Self::ActionDir => "workspace",+ Self::MasterKeyEnv => "secrets",+ Self::Proxy => "network",+ Self::MemoryRoot => "memory",+ }+ }+}++struct ConfigSemanticsCheck(CheckKind);++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ [+ CheckKind::Components,+ CheckKind::ModuleFallback,+ CheckKind::InvalidModuleOverride,+ CheckKind::StorageUrl,+ CheckKind::ActionDir,+ CheckKind::MasterKeyEnv,+ CheckKind::Proxy,+ CheckKind::MemoryRoot,+ ]+ .into_iter()+ .map(|kind| Arc::new(ConfigSemanticsCheck(kind)) as Arc<dyn DoctorCheck>)+ .collect()+}++#[async_trait]+impl DoctorCheck for ConfigSemanticsCheck {+ fn id(&self) -> &str {+ self.0.id()+ }++ fn category(&self) -> &str {+ self.0.category()+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ fn is_blocking(&self) -> bool {+ true+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ self.detect_blocking(ctx).unwrap_or_default()+ }++ fn detect_blocking(&self, ctx: &DoctorCtx) -> Option<Vec<Finding>> {+ let findings = match self.0 {+ CheckKind::Components => referenced_but_disabled(ctx.config()),+ CheckKind::ModuleFallback => module_source_fallback(ctx.config()),+ CheckKind::InvalidModuleOverride => invalid_module_overrides(ctx.config()),+ CheckKind::StorageUrl => storage_url(ctx.config()),+ CheckKind::ActionDir => action_dir(ctx.config()),+ CheckKind::MasterKeyEnv => master_key_env(),+ CheckKind::Proxy => proxy(ctx.config()),+ CheckKind::MemoryRoot => memory_root(ctx.config()),+ };+ Some(findings)+ }+}++fn finding(+ check_id: &str,+ severity: FindingSeverity,+ message: impl Into<String>,+ fix_hint: impl Into<String>,+ config_path: Option<String>,+) -> Finding {+ let mut finding = Finding::new(check_id, severity, message, fix_hint);+ finding.config_path = config_path;+ finding+}++fn explicitly_configured(config: &Config, path: &str) -> bool {+ config.load_provenance().has_explicit_under(path)+}++fn referenced_but_disabled(config: &Config) -> Vec<Finding> {+ let mut references = Vec::new();+ let memory = &config.memory;+ let memory_engine = memory.engine.trim();+ let default_memory_engine = crate::config::schema::memory::DEFAULT_MEMORY_ENGINE;+ if !memory_engine.is_empty()+ && !memory_engine.eq_ignore_ascii_case("none")+ && (!memory_engine.eq_ignore_ascii_case(default_memory_engine)+ || explicitly_configured(config, "memory.engine"))+ {+ references.push(("memory", "memory.engine"));+ }+ if !memory.engines.is_empty() {+ references.push(("memory", "memory.engines"));+ }+ if memory.agent_id.as_deref().is_some_and(non_empty) {+ references.push(("memory", "memory.agent_id"));+ }+ if memory.root.as_deref().is_some_and(non_empty) {+ references.push(("memory", "memory.root"));+ }+ if !memory.sources.is_empty() {+ references.push(("memory", "memory.sources"));+ }+ if !memory.agents.is_empty() {+ references.push(("memory", "memory.agents"));+ }+ if memory.embedding_provider != crate::config::schema::memory::DEFAULT_EMBEDDING_PROVIDER+ || explicitly_configured(config, "memory.embedding_provider")+ {+ references.push(("memory", "memory.embedding_provider"));+ }+ if memory.embedding_model != crate::config::schema::memory::DEFAULT_EMBEDDING_MODEL+ || explicitly_configured(config, "memory.embedding_model")+ {+ references.push(("memory", "memory.embedding_model"));+ }+ if memory.embedding_dimensions != crate::config::schema::memory::DEFAULT_EMBEDDING_DIMENSIONS+ || explicitly_configured(config, "memory.embedding_dimensions")+ {+ references.push(("memory", "memory.embedding_dimensions"));+ }++ if !config.mcp_client.servers.is_empty() {+ references.push(("mcp", "mcp_client.servers"));+ }++ let channels = &config.channels_config;+ if channels.telegram.is_some()+ || channels.discord.is_some()+ || channels.slack.is_some()+ || channels.mattermost.is_some()+ || channels.webhook.is_some()+ || channels.imessage.is_some()+ || channels.matrix.is_some()+ || channels.signal.is_some()+ || channels.whatsapp.is_some()+ || channels.linq.is_some()+ || channels.email.is_some()+ || channels.irc.is_some()+ || channels.lark.is_some()+ || channels.dingtalk.is_some()+ || channels.qq.is_some()+ || channels.yuanbao.is_some()+ || channels.relay.is_some()+ {+ references.push(("channels", "channels_config"));+ }++ if !config.voice_providers.is_empty() {+ references.push(("voice", "voice_providers"));+ }+ if config.stt_provider.as_deref().is_some_and(non_empty) {+ references.push(("voice", "stt_provider"));+ }+ if config.tts_provider.as_deref().is_some_and(non_empty) {+ references.push(("voice", "tts_provider"));+ }+ if config.voice_server.stt_engine != crate::config::schema::SttEngine::default()+ || explicitly_configured(config, "voice_server.stt_engine")+ {+ references.push(("voice", "voice_server.stt_engine"));+ }++ if memory.sources.iter().any(|source| {+ matches!(+ source.kind,+ crate::config::schema::MemorySourceKind::File+ | crate::config::schema::MemorySourceKind::Folder+ )+ }) {+ references.push(("documents", "memory.sources"));+ }++ if config.search != crate::config::schema::SearchConfig::default()+ || explicitly_configured(config, "search")+ || config.seltz.enabled+ || config.searxng.enabled+ {+ references.push(("search", "search"));+ }++ if config.computer != crate::config::ComputerConfig::default()+ || explicitly_configured(config, "computer")+ || config.browser.enabled+ || !config.browser.allowed_domains.is_empty()+ || config+ .browser+ .session_name+ .as_deref()+ .is_some_and(non_empty)+ || config.browser.chrome_path.as_deref().is_some_and(non_empty)+ || config+ .browser+ .profile_path+ .as_deref()+ .is_some_and(non_empty)+ {+ references.push(("computer", "computer"));+ }++ if config.sandbox.enabled == Some(true)+ || !matches!(&config.sandbox.backend, crate::config::SandboxBackend::Auto)+ || explicitly_configured(config, "sandbox.backend")+ || !config.sandbox.firejail_args.is_empty()+ {+ references.push(("sandbox", "sandbox"));+ }++ if config.hosting.has_api_key()+ || config.hosting.team().is_some()+ || config.hosting.provider != crate::config::schema::HostingConfig::default().provider+ || explicitly_configured(config, "hosting.provider")+ {+ references.push(("hosting", "hosting"));+ }++ if config.memes != crate::config::schema::MemesConfig::default()+ || explicitly_configured(config, "memes")+ {+ references.push(("memes", "memes"));+ }++ if tokenjuice_is_custom(config) {+ references.push(("juice", "tokenjuice"));+ }++ if !config.capability_providers.is_empty() {+ references.push(("connectors", "capability_providers"));+ }+ if config.composio.mode != crate::config::schema::COMPOSIO_MODE_BACKEND+ || config.composio.api_key.is_some()+ || !config.composio.offered_toolkits_allow.is_empty()+ || !config.composio.offered_toolkits_deny.is_empty()+ || explicitly_configured(config, "composio")+ {+ references.push(("connectors", "composio"));+ }++ if config.inbound.queues_path.is_some()+ || config.inbound.pipeline_path.is_some()+ || config.inbound.queue_url.as_deref().is_some_and(non_empty)+ || config.inbound.triage_timeout_ms+ != crate::config::schema::InboundConfig::default().triage_timeout_ms+ || explicitly_configured(config, "inbound.triage_timeout_ms")+ {+ references.push(("eventqueues", "inbound"));+ }++ references+ .into_iter()+ .filter(|(component, _)| config.components.get(component) == Some(false))+ .map(|(component, path)| {+ finding(+ COMPONENTS_ID,+ FindingSeverity::Warn,+ format!("Configuration references the disabled {component} component."),+ format!("Enable the {component} component or remove the dependent configuration."),+ Some(path.to_owned()),+ )+ })+ .collect()+}++fn tokenjuice_is_custom(config: &Config) -> bool {+ let current = &config.tokenjuice;+ let default = crate::config::schema::TokenjuiceConfig::default();+ explicitly_configured(config, "tokenjuice")+ || current.router_enabled != default.router_enabled+ || current.ccr_enabled != default.ccr_enabled+ || current.repl_handle_enabled != default.repl_handle_enabled+ || current.repl_save_enabled != default.repl_save_enabled+ || current.ccr_disk_enabled != default.ccr_disk_enabled+ || current.max_cache_entries != default.max_cache_entries+ || current.max_cache_bytes != default.max_cache_bytes+ || current.ccr_ttl_secs != default.ccr_ttl_secs+ || current.min_bytes_to_compress != default.min_bytes_to_compress+ || current.ccr_min_tokens != default.ccr_min_tokens+ || current.search_enabled != default.search_enabled+ || current.code_enabled != default.code_enabled+ || current.html_enabled != default.html_enabled+}++fn non_empty(value: &str) -> bool {+ !value.trim().is_empty()+}++fn module_source_fallback(config: &Config) -> Vec<Finding> {+ module_statuses(config)+ .into_iter()+ .filter_map(|status| {+ if status.source != Some(crate::modules::ModuleSource::Release) {+ return None;+ }+ let requested = requested_module_source(config, &status.id)?;+ let detail = match requested {+ crate::config::schema::ModuleSourceMode::Source => {+ "no source-built artifact is available; the release will be served"+ }+ crate::config::schema::ModuleSourceMode::Linked => {+ "no linked factory is registered in this binary; the release will be served"+ }+ crate::config::schema::ModuleSourceMode::Release => return None,+ };+ Some(finding(+ MODULE_FALLBACK_ID,+ FindingSeverity::Warn,+ format!(+ "Module `{}` requested {} mode, but {detail}.",+ status.id,+ requested.as_str()+ ),+ "Build or install the requested module source, or set modules.source to release.",+ Some("modules.source".into()),+ ))+ })+ .collect()+}++fn module_statuses(config: &Config) -> Vec<crate::modules::ModuleStatus> {+ #[cfg(feature = "modules")]+ {+ crate::modules::ops::list(config)+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = config;+ Vec::new()+ }+}++fn requested_module_source(+ config: &Config,+ id: &str,+) -> Option<crate::config::schema::ModuleSourceMode> {+ if let Some(override_) = config+ .modules+ .overrides+ .iter()+ .find(|override_| override_.id == id && override_.validate().is_ok())+ {+ if override_.path.is_some() {+ return None;+ }+ if let Some(source) = override_.source {+ return Some(source);+ }+ }+ Some(config.modules.source)+}++fn invalid_module_overrides(config: &Config) -> Vec<Finding> {+ config+ .modules+ .overrides+ .iter()+ .enumerate()+ .filter(|(_, override_)| override_.validate().is_err())+ .map(|(index, _)| {+ finding(+ MODULE_OVERRIDE_ID,+ FindingSeverity::Warn,+ "A module override is invalid and will be ignored.",+ "Set exactly one of `path` or `source` for each module override.",+ Some(format!("modules.overrides[{index}]")),+ )+ })+ .collect()+}++fn storage_url(config: &Config) -> Vec<Finding> {+ let url = crate::storage::url_from(std::env::var(STORAGE_URL_VAR).ok(), config);+ let Some(url) = url else {+ return Vec::new();+ };++ let parsed = match StorageUrl::parse(&url) {+ Ok(parsed) => parsed,+ Err(error) if error.message().contains("s3 blob URL needs the s3 feature") => {+ return vec![storage_driver_error(STORAGE_URL_ID, "storage-s3")];+ }+ Err(_) => {+ return vec![finding(+ STORAGE_URL_ID,+ FindingSeverity::Error,+ "The configured storage URL is invalid.",+ "Use a supported storage URL scheme and a valid location.",+ Some("storage.url".into()),+ )];+ }+ };++ missing_storage_feature(&parsed).map_or_else(Vec::new, |feature| {+ vec![storage_driver_error(STORAGE_URL_ID, feature)]+ })+}++fn storage_driver_error(check_id: &str, feature: &'static str) -> Finding {+ finding(+ check_id,+ FindingSeverity::Error,+ format!(+ "The configured storage driver is unavailable because this build omits `{feature}`."+ ),+ format!("Use another storage scheme or enable the `{feature}` build feature."),+ Some("storage.url".into()),+ )+}++fn missing_storage_feature(config: &StorageConfig) -> Option<&'static str> {+ match config {+ StorageConfig::Memory | StorageConfig::File { .. } => None,+ // The dependency enables SQLite unconditionally, so this core marker+ // does not represent whether the normal opener can use the driver.+ StorageConfig::Sqlite { .. } => None,+ StorageConfig::MongoDb { .. } => {+ (!cfg!(feature = "storage-mongodb")).then_some("storage-mongodb")+ }+ StorageConfig::Composite { records, blobs } => {+ missing_storage_feature(records).or_else(|| missing_blob_feature(blobs))+ }+ _ => None,+ }+}++fn missing_blob_feature(config: &BlobConfig) -> Option<&'static str> {+ match config {+ BlobConfig::S3 { .. } => (!cfg!(feature = "storage-s3")).then_some("storage-s3"),+ BlobConfig::Backend(config) => missing_storage_feature(config),+ }+}++fn action_dir(config: &Config) -> Vec<Finding> {+ let writable = crate::storage::probe_directory_writable(&config.action_dir).is_ok();+ if writable {+ return Vec::new();+ }+ vec![finding(+ ACTION_DIR_ID,+ FindingSeverity::Error,+ "The configured action directory is missing or not writable.",+ "Create the directory or grant the process write access, then rerun doctor.",+ Some("action_dir".into()),+ )]+}++fn master_key_env() -> Vec<Finding> {+ use crate::security::secret_storage::encrypted_file_backend::{+ MASTER_KEY_ENV, MASTER_KEY_FILE_ENV,+ };++ let inline_is_configured = std::env::var_os(MASTER_KEY_ENV)+ .as_deref()+ .is_some_and(+ crate::security::secret_storage::encrypted_file_backend::key_source::env_source_is_configured,+ );+ let file_is_configured = std::env::var_os(MASTER_KEY_FILE_ENV)+ .as_deref()+ .is_some_and(+ crate::security::secret_storage::encrypted_file_backend::key_source::env_source_is_configured,+ );+ if inline_is_configured && file_is_configured {+ return vec![finding(+ MASTER_KEY_ENV_ID,+ FindingSeverity::Error,+ "Both master-key environment sources are configured.",+ "Keep only the intended master-key source configured, then rerun doctor.",+ None,+ )];+ }+ Vec::new()+}++fn proxy(config: &Config) -> Vec<Finding> {+ if config.proxy.validate().is_ok() {+ return Vec::new();+ }+ vec![finding(+ PROXY_ID,+ FindingSeverity::Error,+ "The proxy configuration is invalid.",+ "Correct the proxy URL or service selectors in the proxy configuration.",+ Some("proxy".into()),+ )]+}++fn memory_root(config: &Config) -> Vec<Finding> {+ let Some(root) = config.memory.root.as_deref() else {+ return Vec::new();+ };+ if tinymemory_tools::layout::identity::validate_root(root).is_ok() {+ return Vec::new();+ }+ vec![finding(+ MEMORY_ROOT_ID,+ FindingSeverity::Error,+ "The configured memory root is invalid.",+ "Set memory.root to a supported namespace root and rerun doctor.",+ Some("memory.root".into()),+ )]+}diff --git a/crates/openhuman-core/src/doctor/checks/config_semantics_tests.rs b/crates/openhuman-core/src/doctor/checks/config_semantics_tests.rsnew file mode 100644index 0000000000..3c39f4b390--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/config_semantics_tests.rs@@ -0,0 +1,419 @@+use crate::config::{test_env::EnvVarGuard, Config};+use crate::doctor::contract::{DoctorCtx, DoctorOptions, Finding, FindingSeverity};+use crate::doctor::runner;++async fn run_check(config: Config, check_id: &str) -> Vec<Finding> {+ let report = runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("built-in doctor checks should be registered");+ report+ .findings+ .into_iter()+ .filter(|finding| finding.check_id == check_id)+ .collect()+}++fn finding(findings: &[Finding], severity: FindingSeverity) -> &Finding {+ findings+ .iter()+ .find(|finding| finding.severity == severity)+ .expect("expected finding severity")+}++fn workspace_entries(root: &std::path::Path) -> Vec<std::path::PathBuf> {+ let mut entries = Vec::new();+ let mut pending = vec![root.to_owned()];+ while let Some(directory) = pending.pop() {+ for entry in std::fs::read_dir(directory).expect("read workspace snapshot") {+ let path = entry.expect("workspace entry").path();+ if path.is_dir() {+ pending.push(path.clone());+ }+ entries.push(path.strip_prefix(root).unwrap().to_owned());+ }+ }+ entries.sort();+ entries+}++fn record_file_provenance(config: &mut Config, source: &str) {+ let document = toml::from_str::<toml::Value>(source).expect("valid TOML fixture");+ config.load_provenance_mut().record_file_keys(&document);+}++#[tokio::test]+async fn disabled_memory_component_warns_when_an_engine_is_configured() {+ let mut config = Config::default();+ config.components.memory = false;+ config.memory.engine = "cortexdb".into();++ let findings = run_check(config, "components/referenced-but-disabled").await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert_eq!(warning.config_path.as_deref(), Some("memory.engine"));+ assert!(!warning.message.contains("cortexdb"));+}++#[tokio::test]+async fn disabled_memory_component_warns_when_the_default_engine_was_explicitly_set() {+ let mut config = Config::default();+ config.components.memory = false;+ config.memory.engine = crate::config::schema::memory::DEFAULT_MEMORY_ENGINE.into();+ record_file_provenance(+ &mut config,+ "[components]\nmemory = false\n[memory]\nengine = \"tinyhumans\"",+ );++ let findings = run_check(config, "components/referenced-but-disabled").await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert_eq!(warning.config_path.as_deref(), Some("memory.engine"));+}++#[tokio::test]+async fn disabled_memory_component_ignores_an_implicit_default_engine() {+ let mut config = Config::default();+ config.components.memory = false;+ record_file_provenance(&mut config, "[components]\nmemory = false");++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert!(!findings+ .iter()+ .any(|finding| finding.severity == FindingSeverity::Warn));+}++#[tokio::test]+async fn disabled_search_component_warns_for_an_explicit_default_valued_setting() {+ let mut config = Config::default();+ config.components.search = false;+ record_file_provenance(+ &mut config,+ "[components]\nsearch = false\n[search]\nenabled = true",+ );++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("search")+ );+}++#[tokio::test]+async fn disabled_memory_component_does_not_warn_for_explicit_none_engine() {+ let mut config = Config::default();+ config.components.memory = false;+ config.memory.engine = "none".into();+ record_file_provenance(+ &mut config,+ "[components]\nmemory = false\n[memory]\nengine = \"none\"",+ );++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert!(!findings+ .iter()+ .any(|finding| finding.severity == FindingSeverity::Warn));+}++#[tokio::test]+async fn disabled_mcp_component_warns_when_servers_are_configured() {+ let mut config = Config::default();+ config.components.mcp = false;+ let mut server = crate::config::McpServerConfig::default();+ server.name = "example".into();+ server.endpoint = "https://mcp.example.test/rpc".into();+ config.mcp_client.servers.push(server);++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("mcp_client.servers")+ );+}++#[tokio::test]+async fn disabled_channels_component_warns_when_a_provider_is_configured() {+ let mut config = Config::default();+ config.components.channels = false;+ config.channels_config.slack = Some(crate::config::SlackConfig {+ bot_token: "fixture-bot-token".into(),+ app_token: None,+ channel_id: None,+ allowed_users: Vec::new(),+ });++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("channels_config")+ );+}++#[tokio::test]+async fn disabled_voice_component_warns_when_a_provider_is_configured() {+ let mut config = Config::default();+ config.components.voice = false;+ let mut provider = crate::config::schema::voice_providers::VoiceProviderCreds::default();+ provider.slug = "test-provider".into();+ provider.endpoint = "https://voice.example.test".into();+ config.voice_providers.push(provider);++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("voice_providers")+ );+}++#[tokio::test]+async fn missing_storage_driver_is_reported_without_opening_the_backend() {+ let _environment = EnvVarGuard::locked_unset_async(crate::storage::STORAGE_URL_VAR).await;+ let mut config = Config::default();+ config.storage.url = Some("mongodb://app:[email protected]/openhuman".into());++ let findings = run_check(config, "storage/url").await;++ #[cfg(not(feature = "storage-mongodb"))]+ {+ let error = finding(&findings, FindingSeverity::Error);+ assert!(error.message.contains("storage-mongodb"));+ assert!(!error.message.contains("private"));+ assert!(!error.message.contains("db.internal"));+ }+ #[cfg(feature = "storage-mongodb")]+ assert!(findings+ .iter()+ .any(|finding| finding.severity == FindingSeverity::Pass));+}++#[cfg(not(feature = "storage-sqlite"))]+#[tokio::test]+async fn sqlite_is_not_reported_missing_when_only_the_core_marker_is_off() {+ let _environment = EnvVarGuard::locked_unset_async(crate::storage::STORAGE_URL_VAR).await;+ let mut config = Config::default();+ config.storage.url = Some("sqlite:/doctor-check-only/storage".into());++ let findings = run_check(config, "storage/url").await;++ assert!(findings+ .iter()+ .any(|finding| finding.severity == FindingSeverity::Pass));+}++#[tokio::test]+async fn malformed_storage_url_is_reported_without_echoing_it() {+ let _environment = EnvVarGuard::locked_unset_async(crate::storage::STORAGE_URL_VAR).await;+ let mut config = Config::default();+ config.storage.url = Some("custom://secret-value".into());++ let findings = run_check(config, "storage/url").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("secret-value"));+}++// This fixture relies on POSIX mode bits; Windows readonly attributes do not revoke write ACLs.+#[cfg(unix)]+#[tokio::test]+async fn action_directory_without_write_access_is_an_error() {+ let dir = tempfile::tempdir().expect("temporary action directory");+ let mut config = Config::default();+ config.action_dir = dir.path().to_owned();+ let original_permissions = std::fs::metadata(dir.path()).unwrap().permissions();+ let mut permissions = original_permissions.clone();+ permissions.set_readonly(true);+ std::fs::set_permissions(dir.path(), permissions).unwrap();++ let findings = run_check(config, "workspace/action-dir").await;+ std::fs::set_permissions(dir.path(), original_permissions).unwrap();++ assert_eq!(+ finding(&findings, FindingSeverity::Error)+ .config_path+ .as_deref(),+ Some("action_dir")+ );+ #[cfg(unix)]+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);+}++#[tokio::test]+async fn writable_action_directory_passes_and_removes_its_probe_file() {+ let dir = tempfile::tempdir().expect("temporary action directory");+ let mut config = Config::default();+ config.action_dir = dir.path().to_owned();++ let findings = run_check(config, "workspace/action-dir").await;++ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Pass);+ assert_eq!(findings[0].check_id, "workspace/action-dir");+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);+}++#[tokio::test]+async fn missing_action_directory_is_reported_without_creating_it() {+ let dir = tempfile::tempdir().expect("temporary parent directory");+ let action_dir = dir.path().join("missing");+ let mut config = Config::default();+ config.action_dir = action_dir.clone();++ let findings = run_check(config, "workspace/action-dir").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Error)+ .config_path+ .as_deref(),+ Some("action_dir")+ );+ assert!(!action_dir.exists());+}++#[tokio::test]+async fn both_master_key_environment_sources_are_reported_without_initializing_keys() {+ use crate::security::secret_storage::encrypted_file_backend::{+ MASTER_KEY_ENV, MASTER_KEY_FILE_ENV,+ };++ let _environment = EnvVarGuard::locked_unset_many_async(&[MASTER_KEY_ENV, MASTER_KEY_FILE_ENV])+ .await+ .with(MASTER_KEY_ENV, "do-not-read-inline");+ let workspace = tempfile::tempdir().expect("temporary workspace");+ let supplied_key_file = workspace.path().join("nested/operator.key");+ let _environment = _environment.with(MASTER_KEY_FILE_ENV, &supplied_key_file);+ let mut config = Config::default();+ config.workspace_dir = workspace.path().to_owned();+ let entries_before = workspace_entries(workspace.path());++ let findings = run_check(config, "secrets/master-key-env").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("do-not-read-inline"));+ assert!(!error+ .message+ .contains(&supplied_key_file.display().to_string()));+ assert_eq!(workspace_entries(workspace.path()), entries_before);+ assert!(!supplied_key_file.exists());+ assert!(!workspace.path().join("keyring/master.key").exists());+}++#[tokio::test]+async fn empty_master_key_environment_sources_are_treated_as_unset() {+ use crate::security::secret_storage::encrypted_file_backend::{+ MASTER_KEY_ENV, MASTER_KEY_FILE_ENV,+ };++ let _environment = EnvVarGuard::locked_unset_many_async(&[MASTER_KEY_ENV, MASTER_KEY_FILE_ENV])+ .await+ .with(MASTER_KEY_ENV, " \t ")+ .with(MASTER_KEY_FILE_ENV, "\r\n ");++ let findings = run_check(Config::default(), "secrets/master-key-env").await;++ assert!(findings+ .iter()+ .any(|finding| finding.severity == FindingSeverity::Pass));+}++#[tokio::test]+async fn invalid_module_override_is_reported_without_echoing_its_path() {+ use crate::config::schema::ModuleOverride;++ let mut config = Config::default();+ config.modules.overrides.push(ModuleOverride {+ id: "tinydocs".into(),+ path: Some("/private/libmodule.so".into()),+ source: Some(crate::config::schema::ModuleSourceMode::Source),+ });++ let findings = run_check(config, "modules/override-invalid").await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert!(!warning.message.contains("/private/libmodule.so"));+}++#[tokio::test]+async fn source_fallback_is_reported_without_loading_modules() {+ use crate::config::schema::ModuleSourceMode;++ let source_dir = tempfile::tempdir().expect("empty module source directory");+ let _environment = EnvVarGuard::locked_unset_many_async(&[+ "OPENHUMAN_MODULE_SOURCE",+ "OPENHUMAN_MODULE_SOURCE_DIR",+ ])+ .await+ .with("OPENHUMAN_MODULE_SOURCE_DIR", source_dir.path());+ let mut config = Config::default();+ config.modules.source = ModuleSourceMode::Source;++ let findings = run_check(config, "modules/source-fallback").await;++ assert!(findings.iter().any(|finding| {+ finding.severity == FindingSeverity::Warn+ && (finding.message.contains("no source-built artifact")+ || finding.message.contains("source fallback"))+ }));+}++#[tokio::test]+async fn invalid_proxy_settings_are_reported_without_echoing_credentials() {+ let mut config = Config::default();+ config.proxy.http_proxy = Some("http://user:private@[invalid".into());++ let findings = run_check(config, "network/proxy").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("private"));+}++#[tokio::test]+async fn invalid_memory_root_is_reported_without_echoing_the_value() {+ let mut config = Config::default();+ config.memory.root = Some("private-invalid-root".into());++ let findings = run_check(config, "memory/root").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("private-invalid-root"));+}++#[tokio::test]+async fn valid_memory_namespace_root_is_accepted() {+ let mut config = Config::default();+ config.memory.root = Some("project:q4/team:ops".into());++ let findings = run_check(config, "memory/root").await;++ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn memory_root_beyond_layout_depth_is_reported_without_echoing_it() {+ let mut config = Config::default();+ config.memory.root = Some("team:a/team:b/team:c/team:d/team:e/team:f/team:g/team:h".into());++ let findings = run_check(config, "memory/root").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("team:a"));+}diff --git a/crates/openhuman-core/src/doctor/checks/embeddings.rs b/crates/openhuman-core/src/doctor/checks/embeddings.rsnew file mode 100644index 0000000000..1f23c80fff--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/embeddings.rs@@ -0,0 +1,492 @@+//! Static validation for the selected embedding provider and vector settings.++use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;++use crate::config::Config;+use crate::doctor::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};++const CONFIG_ID: &str = "embeddings/config";+const CONFIGURED_MODEL_ID: &str = "embeddings/configured-model";++pub(super) struct EmbeddingConfigCheck;+pub(super) struct ConfiguredModelCheck;++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![+ Arc::new(EmbeddingConfigCheck),+ Arc::new(ConfiguredModelCheck),+ ]+}++#[async_trait]+impl DoctorCheck for EmbeddingConfigCheck {+ fn id(&self) -> &str {+ CONFIG_ID+ }++ fn category(&self) -> &str {+ "embedding configuration"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ tracing::debug!(target: "doctor", check = CONFIG_ID, event = "inspection_started");+ config(ctx.config())+ }+}++#[async_trait]+impl DoctorCheck for ConfiguredModelCheck {+ fn id(&self) -> &str {+ CONFIGURED_MODEL_ID+ }++ fn category(&self) -> &str {+ "embedding runtime"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ tracing::debug!(target: "doctor", check = CONFIGURED_MODEL_ID, event = "inspection_started");+ configured_model(ctx.config()).await+ }+}++async fn configured_model(config: &Config) -> Vec<Finding> {+ let local_model = config.workload_local_model("embeddings");+ let (provider, model, _) = tinyinference_embeddings::catalog::effective_embedding_settings(+ &config.memory.embedding_provider,+ &config.memory.embedding_model,+ config.memory.embedding_dimensions,+ local_model.as_deref(),+ );+ if provider != "ollama" {+ tracing::debug!(target: "doctor", check = CONFIGURED_MODEL_ID, event = "skipped_non_ollama");+ return vec![Finding::skipped(+ CONFIGURED_MODEL_ID,+ "The configured embedding provider does not use the local Ollama runtime.",+ "This readiness check applies only to Ollama; use the provider-specific diagnostics for other services.",+ )];+ }+ if model.trim().is_empty() {+ let mut finding = Finding::error(+ CONFIGURED_MODEL_ID,+ "No Ollama embedding model is configured.",+ "Select an embedding model for Ollama and rerun doctor.",+ );+ finding.config_path = Some("memory.embedding_model".to_owned());+ return vec![finding];+ }++ let base_url = tinyinference_local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );+ let tags_url = format!("{}/api/tags", base_url.trim_end_matches('/'));+ tracing::debug!(target: "doctor", check = CONFIGURED_MODEL_ID, event = "probe_started");++ let client = match reqwest::Client::builder()+ .timeout(Duration::from_secs(3))+ .build()+ {+ Ok(client) => client,+ Err(_) => {+ return vec![endpoint_error(+ "The local Ollama readiness client could not be initialized.",+ )];+ }+ };+ let response = match client.get(tags_url).send().await {+ Ok(response) => response,+ Err(_) => {+ tracing::debug!(target: "doctor", check = CONFIGURED_MODEL_ID, event = "unreachable");+ return vec![endpoint_error(+ "The configured Ollama runtime could not be reached.",+ )];+ }+ };+ if !response.status().is_success() {+ return vec![endpoint_error(+ "The configured Ollama runtime returned an unsuccessful tags response.",+ )];+ }++ let body = match response.text().await {+ Ok(body) => body,+ Err(_) => {+ return vec![Finding::new(+ CONFIGURED_MODEL_ID,+ FindingSeverity::Warn,+ "The Ollama tags response could not be read; model readiness could not be verified.",+ "Check the local Ollama runtime and rerun doctor.",+ )];+ }+ };+ let payload = match serde_json::from_str::<serde_json::Value>(&body) {+ Ok(payload) => payload,+ Err(_) => {+ return vec![Finding::new(+ CONFIGURED_MODEL_ID,+ FindingSeverity::Warn,+ "The Ollama tags response was not valid JSON; model readiness could not be verified.",+ "Check the local Ollama runtime and rerun doctor.",+ )];+ }+ };+ let Some(models) = payload.get("models").and_then(serde_json::Value::as_array) else {+ return vec![Finding::new(+ CONFIGURED_MODEL_ID,+ FindingSeverity::Warn,+ "The Ollama tags response has no models list; model readiness could not be verified.",+ "Check the local Ollama runtime and rerun doctor.",+ )];+ };++ let installed = models.iter().any(|entry| {+ entry+ .get("name")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|name| model_matches(name, &model))+ });+ if installed {+ tracing::debug!(target: "doctor", check = CONFIGURED_MODEL_ID, event = "model_available");+ vec![Finding::pass(+ CONFIGURED_MODEL_ID,+ "The configured embedding model is installed in the local Ollama runtime.",+ )]+ } else {+ let mut finding = Finding::error(+ CONFIGURED_MODEL_ID,+ "The configured embedding model is not installed in the local Ollama runtime.",+ "Pull the configured embedding model in Ollama, then rerun doctor.",+ );+ finding.config_path = Some("memory.embedding_model".to_owned());+ vec![finding]+ }+}++fn endpoint_error(message: &str) -> Finding {+ let mut finding = Finding::error(+ CONFIGURED_MODEL_ID,+ message,+ "Start the configured Ollama runtime and verify its local base URL, then rerun doctor.",+ );+ finding.config_path = Some("local_ai.base_url".to_owned());+ finding+}++fn model_matches(installed: &str, configured: &str) -> bool {+ if installed == configured {+ return true;+ }+ if installed.contains(':') && configured.contains(':') {+ return false;+ }+ model_base(installed) == model_base(configured)+}++fn model_base(model: &str) -> &str {+ model.split(':').next().unwrap_or_default()+}++fn config(config: &Config) -> Vec<Finding> {+ if config+ .embeddings_provider+ .as_deref()+ .is_some_and(|provider| provider.trim() == "none")+ {+ return Vec::new();+ }++ let local_model = config.workload_local_model("embeddings");+ let active_route_index = if local_model.is_none() {+ config+ .memory+ .embedding_model+ .trim()+ .strip_prefix("hint:")+ .and_then(|hint| {+ config+ .embedding_routes+ .iter()+ .enumerate()+ .find(|(_, route)| route.hint.trim() == hint.trim())+ .map(|(index, _)| index)+ })+ } else {+ None+ };+ let active_route = active_route_index.and_then(|index| config.embedding_routes.get(index));+ let active_hint = if local_model.is_none() {+ config+ .memory+ .embedding_model+ .trim()+ .strip_prefix("hint:")+ .map(str::trim)+ } else {+ None+ };+ let (effective_provider, effective_model, effective_dimensions) =+ tinyinference_embeddings::catalog::effective_embedding_settings(+ &config.memory.embedding_provider,+ &config.memory.embedding_model,+ config.memory.embedding_dimensions,+ local_model.as_deref(),+ );+ let (provider, model, dimensions, provider_path, model_path, dimensions_path) =+ if let Some(route) = active_route {+ let route_path = format!(+ "embedding_routes[{}]",+ active_route_index.expect("active route has an index")+ );+ (+ route.provider.clone(),+ route.model.clone(),+ route+ .dimensions+ .unwrap_or(config.memory.embedding_dimensions),+ format!("{route_path}.provider"),+ format!("{route_path}.model"),+ if route.dimensions.is_some() {+ format!("{route_path}.dimensions")+ } else {+ "memory.embedding_dimensions".to_owned()+ },+ )+ } else {+ (+ effective_provider,+ effective_model,+ effective_dimensions,+ "memory.embedding_provider".to_owned(),+ "memory.embedding_model".to_owned(),+ if local_model.is_some() {+ "embeddings_provider".to_owned()+ } else {+ "memory.embedding_dimensions".to_owned()+ },+ )+ };+ let provider_slug = normalized_provider_slug(&provider);+ let mut findings = Vec::new();++ if active_hint.is_some()+ && active_route.is_none()+ && !config+ .embedding_routes+ .iter()+ .any(|route| route.hint.trim() == active_hint.unwrap())+ {+ findings.push(invalid(+ "memory.embedding_model",+ "The selected embedding model hint has no matching route.",+ "Add the matching embedding route or select a concrete embedding model.",+ ));+ }++ if tinyinference_embeddings::catalog::find_provider(provider_slug).is_none() {+ findings.push(invalid(+ &provider_path,+ "The configured embedding provider is not supported by this build.",+ "Select a supported embedding provider and rerun doctor.",+ ));+ }++ if model.trim().is_empty() {+ findings.push(invalid(+ &model_path,+ "The configured embedding model is missing.",+ "Set an embedding model for the selected provider and rerun doctor.",+ ));+ }++ if dimensions == 0 {+ findings.push(invalid(+ &dimensions_path,+ "The selected embedding model has no usable vector dimensions.",+ "Choose a model with known dimensions or configure a positive vector width.",+ ));+ } else {+ if let Some(preset) =+ tinyinference_embeddings::catalog::find_model(provider_slug, model.trim())+ {+ if !preset.allowed_dimensions.contains(&dimensions) {+ findings.push(invalid(+ &dimensions_path,+ "The configured vector dimensions do not match the selected embedding model.",+ "Set a dimension supported by the selected embedding model and rerun doctor.",+ ));+ }+ }+ }++ if provider_slug == "custom" && !custom_endpoint_is_configured(config, &provider) {+ findings.push(invalid(+ "custom_embeddings.endpoint",+ "The custom embedding provider has no configured endpoint.",+ "Set and verify the custom embedding endpoint in Settings, then rerun doctor.",+ ));+ }++ for (index, route) in config.embedding_routes.iter().enumerate() {+ let path = format!("embedding_routes[{index}]");+ if route.hint.trim().is_empty() {+ findings.push(invalid(+ &format!("{path}.hint"),+ "An embedding route has no workload hint.",+ "Set a non-empty hint for this embedding route.",+ ));+ }+ if route.model.trim().is_empty() {+ findings.push(invalid(+ &format!("{path}.model"),+ "An embedding route has no model.",+ "Set a model for this embedding route.",+ ));+ }+ let route_dimensions = route+ .dimensions+ .unwrap_or(config.memory.embedding_dimensions);+ let route_dimensions_path = if route.dimensions.is_some() {+ format!("{path}.dimensions")+ } else {+ "memory.embedding_dimensions".to_owned()+ };+ if route_dimensions == 0 {+ findings.push(invalid(+ &route_dimensions_path,+ "An embedding route has a zero vector dimension.",+ "Set a positive dimension supported by the route's model.",+ ));+ }+ let route_provider = normalized_provider_slug(&route.provider);+ if tinyinference_embeddings::catalog::find_provider(route_provider).is_none() {+ findings.push(invalid(+ &format!("{path}.provider"),+ "An embedding route uses an unsupported provider.",+ "Select a supported embedding provider for this route.",+ ));+ }+ if route_provider == "custom" && !custom_endpoint_is_configured(config, &route.provider) {+ findings.push(invalid(+ &format!("{path}.provider"),+ "A custom embedding route has no configured endpoint.",+ "Set a custom endpoint for this embedding route.",+ ));+ }+ if let Some(preset) =+ tinyinference_embeddings::catalog::find_model(route_provider, route.model.trim())+ {+ if route_dimensions > 0 && !preset.allowed_dimensions.contains(&route_dimensions) {+ findings.push(invalid(+ &format!("{path}.dimensions"),+ "An embedding route's dimensions do not match its model.",+ "Set a dimension supported by the embedding route's model.",+ ));+ }+ }+ }++ if active_route.is_none() {+ if let Some(route) = config.embeddings_provider.as_deref() {+ if route.trim() != "none" {+ if let Some((route_provider, route_model)) = provider_route_parts(route) {+ if normalize_provider(route_provider) != normalize_provider(&provider) {+ findings.push(invalid(+ "embeddings_provider",+ "The embedding workload route and memory settings select different providers.",+ "Use the same embedding provider in both settings and rerun doctor.",+ ));+ } else if !route_model.is_empty()+ && route_model != model.trim()+ && !route.starts_with("custom:")+ {+ findings.push(invalid(+ "embeddings_provider",+ "The embedding workload route and memory settings select different models.",+ "Use the same embedding model in both settings and rerun doctor.",+ ));+ }+ }+ }+ }+ }++ let mut seen_paths = std::collections::HashSet::new();+ findings.retain(|finding| {+ finding+ .config_path+ .as_ref()+ .is_none_or(|path| seen_paths.insert(path.clone()))+ });+ findings+}++fn normalized_provider_slug(provider: &str) -> &str {+ match provider.trim() {+ "cloud" | "openhuman" => "managed",+ provider if provider.starts_with("custom:") => "custom",+ provider if provider.starts_with("ollama:") => "ollama",+ other => other,+ }+}++fn custom_endpoint_is_configured(config: &Config, provider: &str) -> bool {+ if let Some(endpoint) = provider.strip_prefix("custom:") {+ return valid_custom_endpoint(endpoint.trim());+ }+ provider.trim() == "custom"+ && config+ .custom_embeddings+ .as_ref()+ .is_some_and(|custom| valid_custom_endpoint(custom.endpoint.trim()))+}++fn valid_custom_endpoint(endpoint: &str) -> bool {+ reqwest::Url::parse(endpoint)+ .map(|url| matches!(url.scheme(), "http" | "https") && url.host_str().is_some())+ .unwrap_or(false)+}++fn normalize_provider(provider: &str) -> &str {+ match provider.trim() {+ "cloud" | "openhuman" => "managed",+ provider if provider.starts_with("custom:") => "custom",+ provider if provider.starts_with("ollama:") => "ollama",+ other => other,+ }+}++fn provider_route_parts(provider: &str) -> Option<(&str, &str)> {+ let provider = provider.trim();+ if let Some(endpoint) = provider.strip_prefix("custom:") {+ return Some(("custom", endpoint));+ }+ if let Some(model) = provider.strip_prefix("ollama:") {+ return Some(("ollama", model.trim()));+ }+ match provider.split_once(':') {+ Some((slug, model)) => Some((slug.trim(), model.trim())),+ None if !provider.is_empty() => Some((provider, "")),+ None => None,+ }+}++fn invalid(path: &str, message: &str, fix_hint: &str) -> Finding {+ let mut finding = Finding::error(CONFIG_ID, message, fix_hint);+ finding.config_path = Some(path.to_owned());+ finding+}++#[cfg(test)]+#[path = "embeddings_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/embeddings_live.rs b/crates/openhuman-core/src/doctor/checks/embeddings_live.rsnew file mode 100644index 0000000000..5c0113ea29--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/embeddings_live.rs@@ -0,0 +1,97 @@+//! The opt-in live embedding connectivity and vector-width check.++use async_trait::async_trait;++use crate::doctor::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};+use crate::inference::embedding_host::{probe_dimensions_for_inspection, InspectionEmbeddingError};++pub(super) struct EmbeddingsLiveCheck;++#[async_trait]+impl DoctorCheck for EmbeddingsLiveCheck {+ fn id(&self) -> &str {+ "embeddings/live"+ }++ fn category(&self) -> &str {+ "embeddings"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Live+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Memory)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let config = ctx.config();+ if config+ .memory+ .embedding_provider+ .trim()+ .eq_ignore_ascii_case("none")+ {+ return vec![Finding::skipped(+ self.id(),+ "Embedding generation is disabled in the selected configuration.",+ "Select an embedding provider before running the live embedding check.",+ )];+ }++ match probe_dimensions_for_inspection(config).await {+ Ok(dimensions)+ if dimensions.actual > 0 && dimensions.actual == dimensions.configured =>+ {+ vec![Finding::pass(+ self.id(),+ "The configured embedding provider returned the expected vector dimensions.",+ )]+ }+ Ok(dimensions) => {+ let message = if dimensions.actual == 0 {+ format!(+ "The embedding provider returned an empty vector (0 dimensions); the configuration requests {}.",+ dimensions.configured+ )+ } else {+ format!(+ "The embedding provider returned {} dimensions; the configuration requests {}.",+ dimensions.actual, dimensions.configured+ )+ };+ vec![Finding::error(+ self.id(),+ message,+ "Select a model that matches the configured vector dimensions, or update the configured dimensions.",+ )]+ }+ Err(error) => vec![finding_for_error(self.id(), error)],+ }+ }+}++fn finding_for_error(id: &str, error: InspectionEmbeddingError) -> Finding {+ match error {+ InspectionEmbeddingError::CredentialStoreUnavailable => Finding::error(+ id,+ "The selected embedding credential profile could not be read safely.",+ "Check the selected profile's embedding credential and rerun the live check.",+ ),+ InspectionEmbeddingError::ProviderUnavailable => Finding::error(+ id,+ "The selected embedding provider is unavailable for live inspection.",+ "Configure a supported embedding provider and rerun the live check.",+ ),+ InspectionEmbeddingError::ProbeFailed => Finding::error(+ id,+ "The configured embedding provider could not complete the live probe.",+ "Check the provider endpoint and model, then retry the live check.",+ ),+ }+}++#[cfg(test)]+#[path = "embeddings_live_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rs b/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rsnew file mode 100644index 0000000000..468e2fc79d--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/embeddings_live_tests.rs@@ -0,0 +1,118 @@+use super::EmbeddingsLiveCheck;+use crate::config::Config;+use crate::core::runtime::{CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::doctor::contract::{DoctorCheck, DoctorCtx, FindingSeverity};+use crate::inference::embedding_host::create_embedding_provider_for_inspection;+use crate::inference::provider::factory::PROVIDER_OPENHUMAN;+use axum::{extract::State, routing::post, Json, Router};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use tempfile::TempDir;++fn config_in(tmp: &TempDir, embedding_url: String) -> Config {+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace directory");+ let mut config = Config {+ workspace_dir: workspace.clone(),+ action_dir: workspace,+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ };+ config.memory.embedding_provider = "ollama".to_owned();+ config.memory.embedding_model = "nomic-embed-text".to_owned();+ config.memory.embedding_dimensions = 1536;+ config.local_ai.base_url = Some(embedding_url);+ config+}++async fn mock_ollama(dimensions: usize) -> (String, Arc<AtomicUsize>) {+ let calls = Arc::new(AtomicUsize::new(0));+ let app = Router::new()+ .route(+ "/api/embed",+ post(+ move |State(calls): State<Arc<AtomicUsize>>,+ Json(_body): Json<serde_json::Value>| async move {+ calls.fetch_add(1, Ordering::SeqCst);+ Json(serde_json::json!({+ "embeddings": [vec![0.1_f32; dimensions]],+ }))+ },+ ),+ )+ .with_state(Arc::clone(&calls));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local embedding mock");+ let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (endpoint, calls)+}++#[tokio::test]+async fn reports_actual_embedding_dimensions_when_the_provider_ignores_config() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let (endpoint, calls) = mock_ollama(768).await;+ let ctx = DoctorCtx::from_config(config_in(&tmp, endpoint));++ let findings = EmbeddingsLiveCheck.detect(&ctx).await;++ assert_eq!(+ calls.load(Ordering::SeqCst),+ 1,+ "the local embed mock is called once"+ );+ let finding = findings+ .iter()+ .find(|finding| finding.severity == FindingSeverity::Error)+ .expect("a provider dimension mismatch is an error");+ assert!(+ finding.message.contains("768") && finding.message.contains("1536"),+ "the finding names actual and configured dimensions: {}",+ finding.message+ );+}++#[tokio::test]+async fn managed_inspection_does_not_fall_back_to_the_mutable_provider_factory() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace directory");+ let config = Config {+ workspace_dir: workspace.clone(),+ action_dir: workspace,+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ };+ let calls = Arc::new(AtomicUsize::new(0));+ let provider_calls = Arc::clone(&calls);+ let extensions = Extensions::new();+ crate::inference::registry::register_embedding_in(&extensions, PROVIDER_OPENHUMAN, move |_| {+ provider_calls.fetch_add(1, Ordering::SeqCst);+ Ok(Box::new(tinyinference_embeddings::NoopEmbeddingModel)+ as Box<dyn tinyinference_embeddings::EmbeddingModel>)+ });+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);++ CoreContext::scope(context, async {+ let model = create_embedding_provider_for_inspection(+ &config,+ "managed",+ "managed-test-model",+ 768,+ "",+ None,+ )+ .expect("inspection factory returns its unavailable placeholder");+ assert!(model+ .embed(&["fixed doctor probe".to_owned()])+ .await+ .is_err());+ })+ .await;++ assert_eq!(calls.load(Ordering::SeqCst), 0);+}diff --git a/crates/openhuman-core/src/doctor/checks/embeddings_tests.rs b/crates/openhuman-core/src/doctor/checks/embeddings_tests.rsnew file mode 100644index 0000000000..2642cdc89e--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/embeddings_tests.rs@@ -0,0 +1,391 @@+use super::{model_matches, ConfiguredModelCheck};+use crate::config::Config;+use crate::doctor::runner;+use crate::doctor::{DoctorCheck, DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};++const EMBEDDINGS_CONFIG: &str = "embeddings/config";++async fn run_only(config: Config) -> Vec<Finding> {+ let context = DoctorCtx::from_config(config);+ runner::run(+ &context,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![EMBEDDINGS_CONFIG.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("the selected doctor check should run")+ .findings+}++fn finding(findings: &[Finding]) -> &Finding {+ findings+ .iter()+ .find(|finding| finding.check_id == EMBEDDINGS_CONFIG)+ .unwrap_or_else(|| panic!("expected finding from {EMBEDDINGS_CONFIG}: {findings:#?}"))+}++#[tokio::test]+async fn an_unknown_embedding_provider_reports_its_config_path() {+ let mut config = Config::default();+ config.memory.embedding_provider = "nope".to_owned();++ let findings = run_only(config).await;+ let result = finding(&findings);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(+ result.config_path.as_deref(),+ Some("memory.embedding_provider")+ );+}++#[tokio::test]+async fn missing_embedding_model_and_dimensions_are_reported() {+ let mut config = Config::default();+ config.memory.embedding_model.clear();+ config.memory.embedding_dimensions = 0;++ let findings = run_only(config).await;+ let paths = findings+ .iter()+ .filter(|result| result.check_id == EMBEDDINGS_CONFIG)+ .filter_map(|result| result.config_path.as_deref())+ .collect::<Vec<_>>();++ assert!(+ paths.contains(&"memory.embedding_model"),+ "missing model path in findings: {findings:#?}"+ );+ assert!(+ paths.contains(&"memory.embedding_dimensions"),+ "missing dimensions path in findings: {findings:#?}"+ );+ assert!(findings+ .iter()+ .filter(|result| result.check_id == EMBEDDINGS_CONFIG)+ .all(|result| result.severity == FindingSeverity::Error));+}++#[tokio::test]+async fn known_model_with_unsupported_dimensions_reports_the_dimension_path() {+ let mut config = Config::default();+ config.memory.embedding_provider = "openai".to_owned();+ config.memory.embedding_model = "text-embedding-3-small".to_owned();+ config.memory.embedding_dimensions = 1024;++ let findings = run_only(config).await;+ let result = finding(&findings);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(+ result.config_path.as_deref(),+ Some("memory.embedding_dimensions")+ );+}++#[tokio::test]+async fn active_embedding_route_dimensions_must_match_its_model() {+ use crate::config::EmbeddingRouteConfig;++ let mut config = Config::default();+ config.memory.embedding_model = "hint:recall".to_owned();+ config.memory.embedding_dimensions = 1024;+ config.embedding_routes = vec![EmbeddingRouteConfig {+ hint: "recall".to_owned(),+ provider: "openai".to_owned(),+ model: "text-embedding-3-small".to_owned(),+ dimensions: Some(1024),+ }];++ let findings = run_only(config).await;+ let paths = findings+ .iter()+ .filter(|result| result.check_id == EMBEDDINGS_CONFIG)+ .filter_map(|result| result.config_path.as_deref())+ .collect::<Vec<_>>();++ assert!(+ paths.contains(&"embedding_routes[0].dimensions"),+ "missing unsupported active route dimension finding: {findings:#?}"+ );+}++#[tokio::test]+async fn embedding_workload_model_must_match_memory_model() {+ let mut config = Config::default();+ config.memory.embedding_provider = "openai".to_owned();+ config.memory.embedding_model = "text-embedding-3-large".to_owned();+ config.memory.embedding_dimensions = 3072;+ config.embeddings_provider = Some("openai:text-embedding-3-small".to_owned());++ let findings = run_only(config).await;+ let result = finding(&findings);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("embeddings_provider"));+}++#[tokio::test]+async fn configured_ollama_model_uses_each_selected_config_base_url() {+ let (url_a, request_a) = fake_ollama(200, r#"{"models":[{"name":"bge-m3:latest"}]}"#).await;+ let (url_b, request_b) = fake_ollama(200, r#"{"models":[{"name":"nomic-embed-text"}]}"#).await;++ let mut config_a = Config::default();+ config_a.memory.embedding_provider = "ollama".to_owned();+ config_a.memory.embedding_model = "bge-m3".to_owned();+ config_a.local_ai.base_url = Some(url_a);+ let findings_a = ConfiguredModelCheck+ .detect(&DoctorCtx::from_config(config_a))+ .await;++ let mut config_b = Config::default();+ config_b.memory.embedding_provider = "ollama".to_owned();+ config_b.memory.embedding_model = "bge-m3".to_owned();+ config_b.local_ai.base_url = Some(url_b);+ let findings_b = ConfiguredModelCheck+ .detect(&DoctorCtx::from_config(config_b))+ .await;++ assert!(findings_a.iter().any(|finding| {+ finding.check_id == "embeddings/configured-model"+ && finding.severity == FindingSeverity::Pass+ }));+ assert!(findings_b.iter().any(|finding| {+ finding.check_id == "embeddings/configured-model"+ && finding.severity == FindingSeverity::Error+ }));+ assert!(request_a+ .await+ .expect("fake Ollama A request")+ .starts_with("GET /api/tags "));+ assert!(request_b+ .await+ .expect("fake Ollama B request")+ .starts_with("GET /api/tags "));+}++#[tokio::test]+async fn non_ollama_embedding_provider_is_skipped_instead_of_reported_healthy() {+ let mut config = Config::default();+ config.memory.embedding_provider = "openai".to_owned();+ config.memory.embedding_model = "text-embedding-3-small".to_owned();++ let findings = ConfiguredModelCheck+ .detect(&DoctorCtx::from_config(config))+ .await;++ assert!(findings.iter().any(|finding| {+ finding.check_id == "embeddings/configured-model"+ && finding.severity == FindingSeverity::Skipped+ }));+ assert!(findings+ .iter()+ .all(|finding| finding.severity != FindingSeverity::Pass));+}++#[tokio::test]+async fn a_custom_embedding_route_rejects_non_http_urls() {+ use crate::config::EmbeddingRouteConfig;++ let mut config = Config::default();+ config.memory.embedding_model = "hint:custom".to_owned();+ config.embedding_routes = vec![EmbeddingRouteConfig {+ hint: "custom".to_owned(),+ provider: "custom:file:///private/model".to_owned(),+ model: "private-model-name".to_owned(),+ dimensions: Some(768),+ }];++ let findings = run_only(config).await;++ assert!(findings.iter().any(|finding| {+ finding.check_id == EMBEDDINGS_CONFIG+ && finding.severity == FindingSeverity::Error+ && finding.config_path.as_deref() == Some("embedding_routes[0].provider")+ }));+ assert!(findings.iter().all(|finding| {+ !finding.message.contains("private-model-name")+ && !finding.message.contains("/private/model")+ }));+}++#[tokio::test]+async fn custom_embedding_route_accepts_a_well_formed_http_url() {+ use crate::config::EmbeddingRouteConfig;++ let mut config = Config::default();+ config.memory.embedding_model = "hint:custom".to_owned();+ config.embedding_routes = vec![EmbeddingRouteConfig {+ hint: "custom".to_owned(),+ provider: "custom:https://embedding.example.test/v1".to_owned(),+ model: "custom-model".to_owned(),+ dimensions: Some(768),+ }];++ let findings = run_only(config).await;++ assert!(!findings.iter().any(|finding| {+ finding.check_id == EMBEDDINGS_CONFIG+ && finding.config_path.as_deref() == Some("embedding_routes[0].provider")+ }));+}++#[tokio::test]+async fn the_disabled_embedding_provider_is_a_valid_route_value() {+ use crate::config::EmbeddingRouteConfig;++ let mut config = Config::default();+ config.memory.embedding_model = "hint:disabled".to_owned();+ config.embedding_routes = vec![EmbeddingRouteConfig {+ hint: "disabled".to_owned(),+ provider: "none".to_owned(),+ model: "unused".to_owned(),+ dimensions: Some(768),+ }];++ let findings = run_only(config).await;++ assert!(!findings.iter().any(|finding| {+ finding.check_id == EMBEDDINGS_CONFIG+ && finding.config_path.as_deref() == Some("embedding_routes[0].provider")+ }));+}++#[tokio::test]+async fn incomplete_embedding_routes_keep_their_field_specific_findings() {+ use crate::config::EmbeddingRouteConfig;++ let mut config = Config::default();+ config.embedding_routes = vec![EmbeddingRouteConfig {+ hint: String::new(),+ provider: "openai".to_owned(),+ model: String::new(),+ dimensions: Some(0),+ }];++ let findings = run_only(config).await;+ let paths = findings+ .iter()+ .filter(|finding| finding.check_id == EMBEDDINGS_CONFIG)+ .filter_map(|finding| finding.config_path.as_deref())+ .collect::<Vec<_>>();++ for path in [+ "embedding_routes[0].hint",+ "embedding_routes[0].model",+ "embedding_routes[0].dimensions",+ ] {+ assert!(+ paths.contains(&path),+ "missing {path} finding: {findings:#?}"+ );+ }+ assert!(findings.iter().all(|finding| {+ finding.check_id != EMBEDDINGS_CONFIG+ || (!finding.message.contains("private") && !finding.fix_hint.trim().is_empty())+ }));+}++#[tokio::test]+async fn an_unresolved_embedding_hint_is_reported_without_echoing_the_hint() {+ let mut config = Config::default();+ config.memory.embedding_model = "hint:private-workload-hint".to_owned();+ config.embedding_routes.clear();++ let findings = run_only(config).await;++ assert!(findings.iter().any(|finding| {+ finding.check_id == EMBEDDINGS_CONFIG+ && finding.severity == FindingSeverity::Error+ && finding.config_path.as_deref() == Some("memory.embedding_model")+ }));+ assert!(findings.iter().all(|finding| {+ !finding.message.contains("private-workload-hint")+ && !finding.fix_hint.contains("private-workload-hint")+ }));+}++#[tokio::test]+async fn custom_embedding_route_rejects_empty_and_malformed_urls() {+ use crate::config::EmbeddingRouteConfig;++ for provider in ["custom: ", "custom:not a url"] {+ let mut config = Config::default();+ config.memory.embedding_model = "hint:custom".to_owned();+ config.embedding_routes = vec![EmbeddingRouteConfig {+ hint: "custom".to_owned(),+ provider: provider.to_owned(),+ model: "custom-model".to_owned(),+ dimensions: Some(768),+ }];++ let findings = run_only(config).await;++ assert!(+ findings.iter().any(|finding| {+ finding.check_id == EMBEDDINGS_CONFIG+ && finding.severity == FindingSeverity::Error+ && finding.config_path.as_deref() == Some("embedding_routes[0].provider")+ }),+ "invalid endpoint was not reported: {findings:#?}"+ );+ }+}++#[test]+fn configured_ollama_model_matches_exact_and_tagged_names() {+ assert!(model_matches("bge-m3", "bge-m3"));+ assert!(model_matches("bge-m3:latest", "bge-m3"));+ assert!(model_matches("bge-m3", "bge-m3:latest"));+ assert!(model_matches("bge-m3:v1.0", "bge-m3"));+ assert!(!model_matches("nomic-embed-text:latest", "bge-m3"));+ assert!(!model_matches("bge-m3:latest", "nomic-embed-text"));+ assert!(!model_matches("bge-m3:latest", "bge-m3:v1.0"));+}++async fn fake_ollama(status: u16, body: &'static str) -> (String, tokio::task::JoinHandle<String>) {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local fake Ollama");+ let address = listener.local_addr().expect("fake Ollama address");+ let request = tokio::spawn(async move {+ let (mut stream, _) =+ tokio::time::timeout(std::time::Duration::from_secs(5), listener.accept())+ .await+ .expect("configured Ollama probe should reach the local fixture")+ .expect("accept local probe");+ let mut bytes = Vec::new();+ let mut buffer = [0_u8; 512];+ loop {+ let read = stream.read(&mut buffer).await.expect("read HTTP request");+ if read == 0 {+ break;+ }+ bytes.extend_from_slice(&buffer[..read]);+ if bytes.windows(4).any(|window| window == b"\r\n\r\n") {+ break;+ }+ }+ let reason = if status == 200 {+ "OK"+ } else {+ "Service Unavailable"+ };+ let response = format!(+ "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ stream+ .write_all(response.as_bytes())+ .await+ .expect("write fake Ollama response");+ String::from_utf8_lossy(&bytes).into_owned()+ });++ (format!("http://{address}"), request)+}diff --git a/crates/openhuman-core/src/doctor/checks/ids.rs b/crates/openhuman-core/src/doctor/checks/ids.rsnew file mode 100644index 0000000000..fb37d3a5a2--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/ids.rs@@ -0,0 +1,31 @@+//! Canonical segments for dynamically configured doctor check identifiers.++/// Encodes an arbitrary configured name as a valid check-id segment.+///+/// Native lowercase segments containing only lowercase letters, digits,+/// underscores, and dashes keep their configured spelling, except names that+/// start with the reserved `__x` escape namespace. Invalid names are encoded+/// as `__x_i_<hex UTF-8 bytes>`; valid names inside the reserved namespace are+/// encoded as `__x_v_<hex UTF-8 bytes>`. The separate markers make the mapping+/// collision-free, including for literal names that look like encoded ids.+pub(in crate::doctor) fn canonical_segment(value: &str) -> String {+ let native = !value.is_empty()+ && value.bytes().all(|byte| {+ byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-')+ });+ if native && !value.starts_with("__x") {+ return value.to_owned();+ }++ let kind = if native { 'v' } else { 'i' };+ let mut encoded = format!("__x_{kind}_");+ for byte in value.as_bytes() {+ use std::fmt::Write as _;+ let _ = write!(encoded, "{byte:02x}");+ }+ encoded+}++#[cfg(test)]+#[path = "ids_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/ids_tests.rs b/crates/openhuman-core/src/doctor/checks/ids_tests.rsnew file mode 100644index 0000000000..c428e26a64--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/ids_tests.rs@@ -0,0 +1,51 @@+use super::canonical_segment;++#[test]+fn valid_underscores_are_preserved() {+ assert_eq!(canonical_segment("server_name"), "server_name");+ assert_eq!(canonical_segment("server-name_2"), "server-name_2");+}++#[test]+fn invalid_names_use_the_reserved_escape_namespace() {+ assert_eq!(+ canonical_segment("Server A/α"),+ "__x_i_53657276657220412fceb1"+ );+ assert_eq!(canonical_segment(""), "__x_i_");+ assert_eq!(canonical_segment("__x"), "__x_v_5f5f78");+}++#[test]+fn literal_escape_looking_names_do_not_collide_with_encoded_names() {+ let encoded = canonical_segment("Server");+ let literal = canonical_segment("__x_i_536572766572");++ assert_eq!(encoded, "__x_i_536572766572");+ assert!(literal.starts_with("__x_v_"));+ assert_ne!(encoded, literal);+}++#[test]+fn distinct_configured_names_remain_distinct_after_encoding() {+ use std::collections::HashSet;++ let names = [+ "server_name",+ "Server_name",+ "server name",+ "server/name",+ "",+ "__x_i_736572766572",+ ];+ let ids = names+ .iter()+ .map(|name| canonical_segment(name))+ .collect::<HashSet<_>>();+ assert_eq!(ids.len(), names.len());+ assert!(ids.iter().all(|id| {+ id.bytes().all(|byte| {+ byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-')+ })+ }));+}diff --git a/crates/openhuman-core/src/doctor/checks/inference.rs b/crates/openhuman-core/src/doctor/checks/inference.rsnew file mode 100644index 0000000000..af7c87b6e7--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/inference.rs@@ -0,0 +1,520 @@+//! Static validation for chat-provider references, model construction, and temperatures.++use std::sync::Arc;++use async_trait::async_trait;++use crate::config::Config;+use crate::core::runtime::DispatchCtx;+use crate::doctor::{DoctorCheck, DoctorCtx, DoctorTier, Finding};+use crate::inference::provider::factory::create_chat_model_with_model_id_in_for_inspection;++const PROVIDER_REF_ID: &str = "inference/provider-ref";+const CONSTRUCT_ID: &str = "inference/construct";+const TEMPERATURE_ID: &str = "inference/temperature";++const CHAT_ROLE_PROVIDER_FIELDS: [(&str, &str); 6] = [+ ("chat", "chat_provider"),+ ("reasoning", "reasoning_provider"),+ ("agentic", "agentic_provider"),+ ("coding", "coding_provider"),+ ("vision", "vision_provider"),+ ("memory", "memory_provider"),+];++pub(super) struct ProviderRef;+pub(super) struct Construct;+pub(super) struct Temperature;++#[async_trait]+impl DoctorCheck for ProviderRef {+ fn id(&self) -> &str {+ PROVIDER_REF_ID+ }++ fn category(&self) -> &str {+ "inference configuration"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ provider_ref(ctx.config())+ }+}++#[async_trait]+impl DoctorCheck for Construct {+ fn id(&self) -> &str {+ CONSTRUCT_ID+ }++ fn category(&self) -> &str {+ "inference configuration"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ construct(ctx.config())+ }+}++#[async_trait]+impl DoctorCheck for Temperature {+ fn id(&self) -> &str {+ TEMPERATURE_ID+ }++ fn category(&self) -> &str {+ "inference configuration"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ temperature(ctx.config())+ }+}++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![+ Arc::new(ProviderRef),+ Arc::new(Construct),+ Arc::new(Temperature),+ ]+}++fn provider_ref(config: &Config) -> Vec<Finding> {+ let mut findings = Vec::new();++ for (role, path) in CHAT_ROLE_PROVIDER_FIELDS {+ let Some(provider) = role_provider(config, role)+ .map(str::trim)+ .filter(|provider| !provider.is_empty())+ else {+ continue;+ };+ let resolves = chat_provider_resolves(config, provider);+ if !resolves {+ findings.push(unresolved_provider(path));+ }+ }++ if let Some(provider) = config+ .embeddings_provider+ .as_deref()+ .map(str::trim)+ .filter(|provider| !provider.is_empty() && *provider != "none")+ {+ if !embedding_provider_resolves(config, provider) {+ findings.push(unresolved_provider("embeddings_provider"));+ }+ }++ if let Some(primary) = config+ .primary_cloud+ .as_deref()+ .map(str::trim)+ .filter(|primary| !primary.is_empty())+ {+ let configured = config+ .cloud_providers+ .iter()+ .any(|provider| provider.id == primary);+ let registered = crate::inference::registry::chat_model(primary).is_some()+ || crate::inference::registry::catalog(primary).is_some();+ if !configured && !registered {+ findings.push(unresolved_provider("primary_cloud"));+ }+ }++ for (index, route) in config.model_routes.iter().enumerate() {+ if let Some(provider) = provider_slug_from_model_route(&route.model) {+ if !chat_provider_slug_resolves(config, provider) {+ findings.push(unresolved_provider(&format!("model_routes[{index}].model")));+ }+ }+ }++ for (index, route) in config.embedding_routes.iter().enumerate() {+ if !embedding_provider_resolves(config, &route.provider) {+ findings.push(unresolved_provider(&format!(+ "embedding_routes[{index}].provider"+ )));+ }+ }++ for (provider, path) in [+ (config.stt_provider.as_deref(), "stt_provider"),+ (config.tts_provider.as_deref(), "tts_provider"),+ ] {+ if let Some(provider) = provider.map(str::trim).filter(|value| !value.is_empty()) {+ if !voice_provider_resolves(config, provider, path == "tts_provider") {+ findings.push(unresolved_provider(path));+ }+ }+ }++ for (provider, path, is_tts) in [+ (+ config.local_ai.stt_provider.as_str(),+ "local_ai.stt_provider",+ false,+ ),+ (+ config.local_ai.tts_provider.as_str(),+ "local_ai.tts_provider",+ true,+ ),+ ] {+ let provider = provider.trim();+ if !provider.is_empty()+ && !matches!(provider, "cloud" | "openhuman" | "backend")+ && !voice_provider_resolves(config, provider, is_tts)+ {+ findings.push(unresolved_provider(path));+ }+ }++ let (stt_provider, stt_path) = effective_stt_provider(config);+ if !voice_provider_resolves(config, &stt_provider, false) {+ findings.push(unresolved_provider(stt_path));+ }++ let (tts_provider, tts_path) = effective_tts_provider(config);+ if !voice_provider_resolves(config, &tts_provider, true) {+ findings.push(unresolved_provider(tts_path));+ }++ let mut seen_paths = std::collections::HashSet::new();+ findings.retain(|finding| {+ finding+ .config_path+ .as_ref()+ .is_none_or(|path| seen_paths.insert(path.clone()))+ });+ findings+}++fn role_provider<'a>(config: &'a Config, role: &str) -> Option<&'a str> {+ match role {+ "chat" => config.chat_provider.as_deref(),+ "reasoning" => config.reasoning_provider.as_deref(),+ "agentic" => config.agentic_provider.as_deref(),+ "coding" => config.coding_provider.as_deref(),+ "vision" => config.vision_provider.as_deref(),+ "memory" => config.memory_provider.as_deref(),+ "embeddings" => config.embeddings_provider.as_deref(),+ _ => None,+ }+}++fn provider_slug_from_model_route(route: &str) -> Option<&str> {+ let route = route.trim();+ let (slug, model) = route.split_once(':')?;+ if slug.trim().is_empty() || model.trim().is_empty() {+ return None;+ }+ Some(slug.trim())+}++fn chat_provider_resolves(config: &Config, provider: &str) -> bool {+ if provider.is_empty()+ || matches!(provider, "cloud" | "openhuman" | "managed")+ || provider == "claude_agent_sdk"+ || provider.starts_with("claude_agent_sdk:")+ || provider.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)+ || tinyinference_local::profile::is_local_provider_string(provider)+ || matches!(+ provider,+ "ollama" | "lmstudio" | "mlx" | "omlx" | "local-openai"+ )+ {+ return true;+ }+ let slug = provider+ .split_once(':')+ .map_or(provider, |(slug, _)| slug.trim());+ chat_provider_slug_resolves(config, slug)+}++fn chat_provider_slug_resolves(config: &Config, slug: &str) -> bool {+ config+ .cloud_providers+ .iter()+ .any(|provider| provider.slug == slug)+ || crate::inference::registry::chat_model(slug).is_some()+ || crate::inference::registry::catalog(slug).is_some()+}++fn embedding_provider_resolves(config: &Config, provider: &str) -> bool {+ let provider = provider.trim();+ if matches!(provider, "cloud" | "managed" | "openhuman" | "none")+ || matches!(provider, "ollama" | "openai" | "voyage" | "cohere")+ || tinyinference_local::profile::is_local_provider_string(provider)+ {+ return true;+ }+ if provider == "custom" || provider.starts_with("custom:") {+ return custom_embedding_endpoint_is_configured(config, provider);+ }+ let slug = provider+ .split_once(':')+ .map_or(provider, |(slug, _)| slug.trim());+ tinyinference_embeddings::catalog::find_provider(normalize_embedding_provider(slug)).is_some()+}++fn normalize_embedding_provider(provider: &str) -> &str {+ match provider {+ "cloud" | "openhuman" => "managed",+ other => other,+ }+}++fn custom_embedding_endpoint_is_configured(config: &Config, provider: &str) -> bool {+ provider+ .strip_prefix("custom:")+ .is_some_and(|endpoint| !endpoint.trim().is_empty())+ || config+ .custom_embeddings+ .as_ref()+ .is_some_and(|custom| !custom.endpoint.trim().is_empty())+}++fn is_voice_deferred(provider: &str) -> bool {+ matches!(+ provider.trim().to_ascii_lowercase().as_str(),+ "" | "cloud" | "openhuman" | "backend"+ )+}++fn effective_stt_provider(config: &Config) -> (String, &'static str) {+ if let Some(provider) = config+ .stt_provider+ .as_deref()+ .map(str::trim)+ .filter(|provider| !is_voice_deferred(provider))+ {+ return (provider.to_owned(), "stt_provider");+ }+ if !is_voice_deferred(&config.local_ai.stt_provider) {+ return (+ config.local_ai.stt_provider.trim().to_owned(),+ "local_ai.stt_provider",+ );+ }+ (+ config.voice_server.stt_engine.provider_string().to_owned(),+ "voice_server.stt_engine",+ )+}++fn effective_tts_provider(config: &Config) -> (String, &'static str) {+ if let Some(provider) = config+ .tts_provider+ .as_deref()+ .map(str::trim)+ .filter(|provider| !provider.is_empty())+ {+ return (provider.to_owned(), "tts_provider");+ }+ if !config.local_ai.tts_provider.trim().is_empty() {+ return (+ config.local_ai.tts_provider.trim().to_owned(),+ "local_ai.tts_provider",+ );+ }+ ("cloud".to_owned(), "tts_provider")+}++fn voice_provider_resolves(config: &Config, provider: &str, is_tts: bool) -> bool {+ let provider = provider.trim();+ if is_voice_deferred(provider) {+ return true;+ }+ if provider == "piper" {+ return is_tts;+ }+ let slug = provider+ .split_once(':')+ .map_or(provider, |(slug, _)| slug.trim());+ let configured = config.voice_providers.iter().any(|entry| {+ entry.slug == slug+ && if is_tts {+ entry.capability.supports_tts()+ } else {+ entry.capability.supports_stt()+ }+ });+ configured || registered_voice_provider(slug, is_tts)+}++#[cfg(feature = "voice")]+fn registered_voice_provider(slug: &str, is_tts: bool) -> bool {+ if is_tts {+ crate::voice::factory::registry::has_tts_provider(slug)+ } else {+ crate::voice::factory::registry::has_stt_provider(slug)+ }+}++#[cfg(not(feature = "voice"))]+fn registered_voice_provider(_slug: &str, _is_tts: bool) -> bool {+ false+}++fn unresolved_provider(path: &str) -> Finding {+ let mut finding = Finding::error(+ PROVIDER_REF_ID,+ "A configured provider reference does not resolve to an available provider.",+ "Select a configured provider or add the matching provider entry, then rerun doctor.",+ );+ finding.config_path = Some(path.to_owned());+ finding+}++fn construct(config: &Config) -> Vec<Finding> {+ let mut findings = Vec::new();+ let dispatch = DispatchCtx::ambient();++ for (role, path) in CHAT_ROLE_PROVIDER_FIELDS {+ let result = create_chat_model_with_model_id_in_for_inspection(+ &dispatch,+ role,+ config,+ config.default_temperature,+ );+ let Err(error) = result else {+ continue;+ };+ let class = construction_error_class(&error.to_string());+ let mut finding = Finding::error(+ CONSTRUCT_ID,+ format!("The configured {role} model could not be constructed: {class}."),+ format!("Correct `{path}` and configure the required credential, then rerun doctor."),+ );+ finding.config_path = Some(construction_config_path(config, path));+ findings.push(finding);+ }++ findings+}++fn construction_config_path(config: &Config, role_path: &str) -> String {+ if role_provider(config, role_path.trim_end_matches("_provider"))+ .is_some_and(|provider| !provider.trim().is_empty())+ {+ role_path.to_owned()+ } else if config+ .primary_cloud+ .as_deref()+ .is_some_and(|provider| !provider.trim().is_empty())+ {+ "primary_cloud".to_owned()+ } else {+ "default_model".to_owned()+ }+}++fn construction_error_class(error: &str) -> &'static str {+ let error = error.to_ascii_lowercase();+ if error.contains("requires refresh") || error.contains("expired") {+ "the stored credential requires refresh"+ } else if error.contains("credential") || error.contains("api key") {+ "a required credential is missing or unavailable"+ } else if error.contains("local-only") {+ "the configured privacy mode blocks this provider"+ } else if error.contains("backend_unavailable") || error.contains("managed inference needs") {+ "the managed provider is not available in this host"+ } else if error.contains("no model configured") || error.contains("empty model") {+ "the configured model is missing"+ } else if error.contains("no cloud provider") || error.contains("unrecognised provider") {+ "the configured provider route is invalid"+ } else {+ "the provider configuration is invalid"+ }+}++fn temperature(config: &Config) -> Vec<Finding> {+ let mut findings = Vec::new();+ add_temperature_finding(+ &mut findings,+ "default_temperature",+ config.default_temperature,+ );++ for (field, provider) in [+ ("chat_provider", config.chat_provider.as_deref()),+ ("reasoning_provider", config.reasoning_provider.as_deref()),+ ("agentic_provider", config.agentic_provider.as_deref()),+ ("coding_provider", config.coding_provider.as_deref()),+ ("vision_provider", config.vision_provider.as_deref()),+ ("memory_provider", config.memory_provider.as_deref()),+ ("embeddings_provider", config.embeddings_provider.as_deref()),+ ] {+ if let Some(provider) = provider {+ if let Some(temperature) = route_temperature(provider) {+ add_temperature_finding(&mut findings, field, temperature);+ }+ }+ }++ if let Some(default_model) = config.default_model.as_deref() {+ if let Some(temperature) = route_temperature(default_model) {+ add_temperature_finding(&mut findings, "default_model", temperature);+ }+ }++ for (index, route) in config.model_routes.iter().enumerate() {+ if let Some(temperature) = route_temperature(&route.model) {+ add_temperature_finding(+ &mut findings,+ &format!("model_routes[{index}].model"),+ temperature,+ );+ }+ }++ let mut agent_ids = config.agents.keys().collect::<Vec<_>>();+ agent_ids.sort();+ for (index, agent_id) in agent_ids.into_iter().enumerate() {+ if let Some(temperature) = config.agents[agent_id].temperature {+ add_temperature_finding(+ &mut findings,+ &format!("agents[{index}].temperature"),+ temperature,+ );+ }+ }++ findings+}++fn route_temperature(route: &str) -> Option<f64> {+ let (_, model) = route.trim().split_once(':')?;+ let (model, temperature) = model.rsplit_once('@')?;+ if model.trim().is_empty() {+ return None;+ }+ temperature.trim().parse::<f64>().ok()+}++fn add_temperature_finding(findings: &mut Vec<Finding>, path: &str, temperature: f64) {+ if temperature.is_finite() && (0.0..=2.0).contains(&temperature) {+ return;+ }+ let mut finding = Finding::error(+ TEMPERATURE_ID,+ "A configured inference temperature is outside the supported range 0.0 to 2.0.",+ format!("Set a supported temperature for `{path}` and rerun doctor."),+ );+ finding.config_path = Some(path.to_owned());+ findings.push(finding);+}diff --git a/crates/openhuman-core/src/doctor/checks/inference_catalog.rs b/crates/openhuman-core/src/doctor/checks/inference_catalog.rsnew file mode 100644index 0000000000..a8c75413aa--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/inference_catalog.rs@@ -0,0 +1,470 @@+//! Read-only, bounded provider catalog inspection for doctor.++use std::collections::HashMap;+use std::hash::{BuildHasher, Hash};+use std::sync::{Arc, LazyLock, Mutex};+use std::time::{Duration, Instant};++use async_trait::async_trait;++use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::core::{runtime::CoreContext, Outcome};+use crate::doctor::{+ contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity},+ core::{ModelProbeEntry, ModelProbeOutcome, ModelProbeReport, ModelProbeSummary},+};+use crate::inference::registry::{+ inspection_catalog, CatalogRequest, InspectionCatalogError, PreparedInspectionCatalog,+};++const CACHE_TTL: Duration = Duration::from_secs(60);+const PROVIDER_CATALOG_TIMEOUT: Duration = Duration::from_secs(10);+type CachedCatalog = (+ Instant,+ Result<(serde_json::Value, Vec<String>), InspectionCatalogError>,+);+static CATALOG_CACHE: LazyLock<Mutex<HashMap<u64, CachedCatalog>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));+static CACHE_HASHER: LazyLock<std::collections::hash_map::RandomState> =+ LazyLock::new(std::collections::hash_map::RandomState::new);++fn hash_key<T: Hash>(value: &T) -> u64 {+ CACHE_HASHER.hash_one(value)+}++fn scope_key(config: &crate::config::Config) -> String {+ let context = CoreContext::scoped();+ let scoped_workspace = context+ .as_ref()+ .and_then(|context| context.workspace_dir().ok())+ .unwrap_or_else(|| config.workspace_dir.clone());+ let tenant = context+ .as_ref()+ .and_then(|context| context.profile())+ .unwrap_or_default();+ format!(+ "{}\u{1f}{}\u{1f}{}\u{1f}{}",+ config.config_path.display(),+ config.workspace_dir.display(),+ scoped_workspace.display(),+ tenant,+ )+}++fn configured_entries(config: &crate::config::Config) -> Vec<CloudProviderCreds> {+ let mut entries = config.cloud_providers.clone();+ let selected = selected_models(config);+ // The managed route is a configured model source even though it is not a+ // BYOK row in cloud_providers.+ if selected+ .iter()+ .any(|(_, model)| model.starts_with("openhuman:") || model.starts_with("openrouter/"))+ && !entries.iter().any(|entry| entry.slug == "openhuman")+ {+ entries.push(CloudProviderCreds {+ id: "openhuman".into(),+ slug: "openhuman".into(),+ label: "OpenHuman".into(),+ endpoint: config.api_url.clone().unwrap_or_default(),+ auth_style: AuthStyle::OpenhumanJwt,+ default_model: None,+ });+ }+ entries+}++fn readonly_credential(+ config: &crate::config::Config,+ entry: &CloudProviderCreds,+) -> Option<String> {+ if entry.auth_style == AuthStyle::None || entry.auth_style == AuthStyle::OpenhumanJwt {+ return None;+ }+ let key = crate::inference::provider::factory::auth_key_for_slug(&entry.slug);+ let profile =+ crate::security::credentials::AuthService::get_profile_read_only(config, &key, None)+ .ok()??;+ let token = match profile.kind {+ crate::security::credentials::AuthProfileKind::Token => profile.token,+ crate::security::credentials::AuthProfileKind::OAuth => profile.token_set.and_then(|set| {+ (!set.is_expiring_within(Duration::from_secs(90))).then_some(set.access_token)+ }),+ };+ token.filter(|token| !token.trim().is_empty())+}++async fn prepare(+ config: &crate::config::Config,+ entry: &CloudProviderCreds,+) -> Result<PreparedInspectionCatalog, InspectionCatalogError> {+ if let Some(listing) = inspection_catalog(&entry.slug) {+ let client = crate::config::build_runtime_proxy_client_with_timeouts(+ "providers.list_models",+ 30,+ 10,+ );+ return listing(+ config.clone(),+ CatalogRequest {+ provider_key: String::new(),+ client,+ },+ )+ .await;+ }+ if entry.auth_style == AuthStyle::OpenhumanJwt {+ return Err(InspectionCatalogError::Unavailable);+ }+ let endpoint = entry.endpoint.trim_end_matches('/');+ let Ok(url) = reqwest::Url::parse(&format!("{endpoint}/models")) else {+ return Err(InspectionCatalogError::Unavailable);+ };+ if !matches!(url.scheme(), "http" | "https") {+ return Err(InspectionCatalogError::NoCatalog);+ }+ let token = readonly_credential(config, entry);+ let client = match config+ .cloud_provider_ca_certs+ .get(entry.slug.trim())+ .filter(|pem| !pem.is_empty())+ {+ Some(pem) => crate::util::tls::client_with_ca_bundle_with_timeouts(+ pem,+ "providers.list_models",+ 30,+ 10,+ )+ .map_err(|_| InspectionCatalogError::Unavailable)?,+ None => {+ crate::config::build_runtime_proxy_client_with_timeouts("providers.list_models", 30, 10)+ }+ };+ let provider = entry.slug.clone();+ let auth_style = entry.auth_style;+ let frozen_token = token.clone();+ let fetch_url = url.clone();+ let fetch = Box::pin(async move {+ let mut request = client.get(fetch_url);+ if let Some(token) = frozen_token.as_deref() {+ request = match auth_style {+ AuthStyle::Anthropic => request+ .header("x-api-key", token)+ .header("anthropic-version", "2023-06-01"),+ AuthStyle::Bearer => request.bearer_auth(token),+ AuthStyle::None | AuthStyle::OpenhumanJwt => request,+ };+ }+ let response = request.send().await.map_err(|error| {+ if error.is_timeout() {+ InspectionCatalogError::Failure+ } else {+ InspectionCatalogError::Unavailable+ }+ })?;+ let status = response.status();+ if status == reqwest::StatusCode::NOT_FOUND {+ return Err(InspectionCatalogError::NoCatalog);+ }+ if matches!(+ status,+ reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN+ ) {+ return Err(InspectionCatalogError::AuthOrAccess);+ }+ if !status.is_success() {+ return Err(InspectionCatalogError::Failure);+ }+ let body = response+ .json::<serde_json::Value>()+ .await+ .map_err(|_| InspectionCatalogError::Failure)?;+ let models = tinyinference_llm::catalog::parse_models_response(&body)+ .map_err(|_| InspectionCatalogError::Failure)?;+ Ok(Outcome::new(+ serde_json::json!({"models": models}),+ Vec::new(),+ ))+ });+ Ok(PreparedInspectionCatalog::new(+ &provider,+ url.as_str(),+ token.as_deref(),+ fetch,+ ))+}++async fn catalog_for(+ config: &crate::config::Config,+ entry: &CloudProviderCreds,+ use_cache: bool,+) -> Result<(serde_json::Value, Vec<String>), InspectionCatalogError> {+ match tokio::time::timeout(+ PROVIDER_CATALOG_TIMEOUT,+ catalog_for_with_timeout(config, entry, use_cache),+ )+ .await+ {+ Ok(result) => result,+ Err(_) => Err(InspectionCatalogError::Failure),+ }+}++async fn catalog_for_with_timeout(+ config: &crate::config::Config,+ entry: &CloudProviderCreds,+ use_cache: bool,+) -> Result<(serde_json::Value, Vec<String>), InspectionCatalogError> {+ let prepared = prepare(config, entry).await?;+ let cache_key = hash_key(&(scope_key(config), entry.slug.clone(), prepared.identity()));+ if use_cache {+ if let Some((at, result)) = CATALOG_CACHE+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get(&cache_key)+ {+ if at.elapsed() < CACHE_TTL {+ return result.clone();+ }+ }+ }+ let result = prepared+ .fetch()+ .await+ .map(|outcome| (outcome.value, outcome.logs));+ CATALOG_CACHE+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .insert(cache_key, (Instant::now(), result.clone()));+ result+}++pub async fn doctor_models(config: &crate::config::Config, use_cache: bool) -> ModelProbeReport {+ let mut entries = Vec::new();+ for provider in configured_entries(config) {+ let (outcome, message) = match catalog_for(config, &provider, use_cache).await {+ Ok((value, _)) => {+ let models = value+ .get("models")+ .and_then(serde_json::Value::as_array)+ .cloned()+ .unwrap_or_default();+ (+ ModelProbeOutcome::Ok,+ Some(format!("Catalog returned {} models.", models.len())),+ )+ }+ Err(InspectionCatalogError::AuthOrAccess) => (+ ModelProbeOutcome::AuthOrAccess,+ Some("Catalog access was rejected.".into()),+ ),+ Err(InspectionCatalogError::NoCatalog) => (+ ModelProbeOutcome::Skipped,+ Some("Provider does not expose a models catalog.".into()),+ ),+ Err(InspectionCatalogError::Unavailable) => (+ ModelProbeOutcome::Skipped,+ Some("A safe read-only catalog is unavailable.".into()),+ ),+ Err(InspectionCatalogError::Failure) => (+ ModelProbeOutcome::Error,+ Some("Catalog request failed.".into()),+ ),+ };+ entries.push(ModelProbeEntry {+ provider: provider.slug,+ outcome,+ message,+ });+ }+ ModelProbeReport {+ summary: ModelProbeSummary {+ ok: entries+ .iter()+ .filter(|e| e.outcome == ModelProbeOutcome::Ok)+ .count(),+ skipped: entries+ .iter()+ .filter(|e| e.outcome == ModelProbeOutcome::Skipped)+ .count(),+ auth_or_access: entries+ .iter()+ .filter(|e| e.outcome == ModelProbeOutcome::AuthOrAccess)+ .count(),+ errors: entries+ .iter()+ .filter(|e| e.outcome == ModelProbeOutcome::Error)+ .count(),+ },+ entries,+ }+}++pub(crate) struct ModelInCatalog;+#[async_trait]+impl DoctorCheck for ModelInCatalog {+ fn id(&self) -> &str {+ "inference/model-in-catalog"+ }+ fn category(&self) -> &str {+ "inference"+ }+ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }+ fn is_blocking(&self) -> bool {+ false+ }+ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let entries = configured_entries(ctx.config());+ if entries.is_empty() {+ return vec![Finding::skipped(+ self.id(),+ "No configured inference catalog is available.",+ "Configure a model provider and rerun doctor.",+ )];+ }+ let mut findings = Vec::new();+ for entry in entries {+ let catalog = match catalog_for(ctx.config(), &entry, true).await {+ Ok((value, _)) => value+ .get("models")+ .and_then(serde_json::Value::as_array)+ .cloned()+ .unwrap_or_default(),+ Err(InspectionCatalogError::NoCatalog) => {+ findings.push(Finding::skipped(+ self.id(),+ "Provider has no model catalog route.",+ "Choose a provider with a read-only models route.",+ ));+ continue;+ }+ Err(InspectionCatalogError::Unavailable) => {+ findings.push(Finding::skipped(+ self.id(),+ "Safe read-only model catalog is unavailable.",+ "Reconnect the provider or use doctor.models for details.",+ ));+ continue;+ }+ Err(InspectionCatalogError::AuthOrAccess) => {+ findings.push(Finding::new(+ self.id(),+ FindingSeverity::Warn,+ "Provider rejected catalog access.",+ "Check the selected provider credentials.",+ ));+ continue;+ }+ Err(InspectionCatalogError::Failure) => {+ findings.push(Finding::new(+ self.id(),+ FindingSeverity::Warn,+ "Provider catalog could not be read.",+ "Check provider availability and rerun doctor.",+ ));+ continue;+ }+ };+ let ids = catalog+ .iter()+ .filter_map(|model| model.get("id").and_then(serde_json::Value::as_str))+ .collect::<Vec<_>>();+ let selected = selected_models(ctx.config());+ for (path, model) in selected+ .iter()+ .filter(|(_, model)| {+ model.starts_with(&format!("{}:", entry.slug))+ || (entry.slug == "openhuman" && model.starts_with("openrouter/"))+ })+ .map(|(path, model)| {+ (+ path.as_str(),+ if model.starts_with("openrouter/") {+ model.as_str()+ } else {+ model+ .split_once(':')+ .map(|(_, model)| model)+ .unwrap_or(model.as_str())+ },+ )+ })+ {+ if !ids.contains(&model) {+ let mut finding = Finding::new(+ self.id(),+ FindingSeverity::Warn,+ format!(+ "Configured model at {path} is not present in the provider catalog."+ ),+ "Choose a model listed by the provider or update this route.",+ );+ finding.config_path = Some(path.to_owned());+ findings.push(finding);+ }+ }+ }+ findings+ }+}++fn selected_models(config: &crate::config::Config) -> Vec<(String, String)> {+ let mut models = Vec::new();+ if let Some(model) = &config.default_model {+ models.push(("default_model".to_owned(), model.clone()));+ }+ for (index, route) in config.model_routes.iter().enumerate() {+ models.push((format!("model_routes[{index}].model"), route.model.clone()));+ }+ models+}++pub(crate) struct AuthErrors;+#[async_trait]+impl DoctorCheck for AuthErrors {+ fn id(&self) -> &str {+ "inference/auth-errors"+ }+ fn category(&self) -> &str {+ "inference"+ }+ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }+ fn is_blocking(&self) -> bool {+ false+ }+ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let mut findings = Vec::new();+ let (errors, has_unscoped) = crate::inference::auth_error_registry::snapshot_for_scope(+ &ctx.config().workspace_dir,+ &ctx.config().config_path,+ ctx.profile(),+ );+ for error in errors {+ findings.push(Finding::new(+ self.id(),+ FindingSeverity::Error,+ format!(+ "Provider {} has a recorded authentication error.",+ error.provider+ ),+ "Update or reconnect this provider's credentials.",+ ));+ }+ if has_unscoped {+ findings.push(Finding::new(+ self.id(),+ FindingSeverity::Info,+ "A provider authentication error was recorded outside a known inspection scope.",+ "Rerun doctor after reproducing the issue in the selected profile.",+ ));+ }+ findings+ }+}++pub(crate) fn built_in_checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(ModelInCatalog), Arc::new(AuthErrors)]+}diff --git a/crates/openhuman-core/src/doctor/checks/inference_live.rs b/crates/openhuman-core/src/doctor/checks/inference_live.rsnew file mode 100644index 0000000000..3c223e081a--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/inference_live.rs@@ -0,0 +1,321 @@+//! Opt-in, one-shot model calls for configured chat inference roles.++use std::collections::HashMap;+use std::sync::Arc;+use std::time::{Duration, Instant};++use async_trait::async_trait;+use tinyinference_llm::message::Message;+use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse, ProviderError};+use tokio::sync::{Mutex, OnceCell};++use crate::config::Config;+use crate::core::runtime::DispatchCtx;+use crate::doctor::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};+use crate::inference::provider::factory::{+ create_chat_model_with_identity_in_for_inspection, InspectionRequestIdentity,+ PreparedInspectionChatModel,+};++const CATEGORY: &str = "live inference";+const CHAT_ROLES: &[&str] = &[+ "chat",+ "reasoning",+ "agentic",+ "burst",+ "coding",+ "vision",+ "memory",+ "summarization",+];+const LIVE_OUTPUT_LIMIT: u32 = 5;+const MODEL_TIMEOUT: Duration = Duration::from_secs(45);++/// Creates one report-local probe cache shared by the role-specific findings.+pub(super) fn for_context(_ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ let shared = Arc::new(LiveProbeCache::default());+ CHAT_ROLES+ .iter()+ .map(|role| {+ Arc::new(InferenceLiveCheck {+ id: format!("inference/live/{role}"),+ role,+ cache: Arc::clone(&shared),+ }) as Arc<dyn DoctorCheck>+ })+ .collect()+}++struct InferenceLiveCheck {+ id: String,+ role: &'static str,+ cache: Arc<LiveProbeCache>,+}++#[async_trait]+impl DoctorCheck for InferenceLiveCheck {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ CATEGORY+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Live+ }++ fn timeout(&self) -> Duration {+ DoctorTier::Live.timeout()+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let check_id = self.id();+ let selected_config = ctx.config().clone();+ let dispatch = inspection_dispatch_context(&selected_config);+ let core = dispatch+ .core()+ .expect("inspection dispatch always has a CoreContext")+ .clone();+ let built = match crate::core::runtime::CoreContext::scope(core, async {+ create_chat_model_with_identity_in_for_inspection(+ &dispatch,+ self.role,+ &selected_config,+ 0.0,+ )+ })+ .await+ {+ Ok(built) => built,+ Err(error) => {+ return vec![inspection_construction_error(+ check_id,+ self.role,+ ctx.config(),+ &error,+ )];+ }+ };++ vec![probe_prepared_model(&self.cache, built, check_id).await]+ }+}++pub(super) async fn probe_prepared_model(+ cache: &LiveProbeCache,+ built: PreparedInspectionChatModel,+ check_id: &str,+) -> Finding {+ if built.output_budget+ == crate::inference::provider::factory::InspectionOutputBudgetCapability::Unsupported+ {+ return Finding::skipped(+ check_id,+ "The Codex OAuth Responses API cannot enforce the required output-token limit; no completion request was sent.",+ "Use a provider route that supports a bounded output-token request to run this live check.",+ );+ }+ let slot = cache.slot(built.identity).await;+ let model = built.model;+ let model_id = built.model_id;+ slot.get_or_init(|| async move { invoke_once(model, model_id).await })+ .await+ .clone()+ .finding(check_id)+}++fn inspection_dispatch_context(config: &Config) -> DispatchCtx {+ match DispatchCtx::ambient().resolved() {+ Some(parent) => {+ let overlay = crate::core::runtime::ContextOverlay::new(+ config.clone(),+ parent.domains(),+ parent.tool_groups(),+ );+ DispatchCtx::new(parent.derive_for_inspection(overlay))+ }+ None => DispatchCtx::new(crate::core::runtime::CoreContext::for_inspection(+ config.clone(),+ )),+ }+}++#[derive(Default)]+pub(super) struct LiveProbeCache {+ calls: Mutex<HashMap<InspectionRequestIdentity, Arc<OnceCell<ProbeOutcome>>>>,+}++impl LiveProbeCache {+ async fn slot(&self, identity: InspectionRequestIdentity) -> Arc<OnceCell<ProbeOutcome>> {+ let mut calls = self.calls.lock().await;+ Arc::clone(+ calls+ .entry(identity)+ .or_insert_with(|| Arc::new(OnceCell::new())),+ )+ }+}++#[derive(Clone)]+struct ProbeOutcome {+ severity: FindingSeverity,+ message: String,+ fix_hint: String,+}++impl ProbeOutcome {+ fn finding(&self, id: &str) -> Finding {+ Finding::new(+ id,+ self.severity,+ self.message.clone(),+ self.fix_hint.clone(),+ )+ }+}++async fn invoke_once(model: Arc<dyn ChatModel<()>>, configured_model: String) -> ProbeOutcome {+ let request =+ ModelRequest::new(vec![Message::user("Reply OK")]).with_max_tokens(LIVE_OUTPUT_LIMIT);+ let started = Instant::now();+ let response = tokio::time::timeout(MODEL_TIMEOUT, model.invoke(&(), request)).await;+ let latency_ms = elapsed_ms(started.elapsed());+ match response {+ Ok(Ok(response)) => success_outcome(&response, &configured_model, latency_ms),+ Ok(Err(error)) => provider_error_outcome(&error),+ Err(_) => ProbeOutcome {+ severity: FindingSeverity::Error,+ message:+ "The configured inference provider did not answer before the live-check timeout."+ .into(),+ fix_hint: "Check the provider's availability and network connection, then rerun doctor with --live.".into(),+ },+ }+}++fn success_outcome(+ response: &ModelResponse,+ configured_model: &str,+ latency_ms: u64,+) -> ProbeOutcome {+ if response.text().trim().is_empty() {+ return ProbeOutcome {+ severity: FindingSeverity::Error,+ message: "The configured inference provider returned an empty completion.".into(),+ fix_hint:+ "Check that the configured model can return text, then rerun doctor with --live."+ .into(),+ };+ }+ let answered_model = response+ .raw+ .as_ref()+ .and_then(|raw| raw.get("model"))+ .and_then(serde_json::Value::as_str)+ .filter(|model| safe_model_id(model))+ .or_else(|| safe_model_id(configured_model).then_some(configured_model))+ .unwrap_or("configured model");+ ProbeOutcome {+ severity: FindingSeverity::Pass,+ message: format!(+ "Live completion succeeded in {latency_ms} ms using model `{answered_model}`."+ ),+ fix_hint: "No action required.".into(),+ }+}++fn provider_error_outcome(error: &tinyinference_llm::Error) -> ProbeOutcome {+ match error {+ tinyinference_llm::Error::Provider(provider_error) => {+ classify_provider_error(provider_error)+ }+ _ => ProbeOutcome {+ severity: FindingSeverity::Error,+ message: "The configured inference provider is unavailable for a live completion."+ .into(),+ fix_hint: "Check the configured provider, its local credential, and network availability, then rerun doctor with --live.".into(),+ },+ }+}++fn classify_provider_error(error: &ProviderError) -> ProbeOutcome {+ match error.status {+ Some(401 | 403) => ProbeOutcome {+ severity: FindingSeverity::Error,+ message: format!(+ "Inference authentication failed (HTTP {}).",+ error.status.unwrap()+ ),+ fix_hint: "Reconnect the configured provider or replace its API key, then rerun doctor with --live.".into(),+ },+ Some(429) => ProbeOutcome {+ severity: FindingSeverity::Error,+ message: "The configured inference provider reported a quota or rate limit (HTTP 429)."+ .into(),+ fix_hint: "Check the provider's quota or rate limit and retry when it allows another request.".into(),+ },+ Some(status) if status >= 500 => ProbeOutcome {+ severity: FindingSeverity::Error,+ message: format!("The configured inference provider is unavailable (HTTP {status})."),+ fix_hint: "Check the provider's service status and network connection, then rerun doctor with --live.".into(),+ },+ _ => ProbeOutcome {+ severity: FindingSeverity::Error,+ message: "The configured inference provider is unavailable for a live completion."+ .into(),+ fix_hint: "Check the configured model and provider endpoint, then rerun doctor with --live.".into(),+ },+ }+}++fn inspection_construction_error(+ id: &str,+ role: &str,+ config: &Config,+ error: &anyhow::Error,+) -> Finding {+ // The inspection factory's credential errors are deliberately safe,+ // typed failure text. Other construction errors may contain endpoint or+ // provider data, so never copy their text to the report.+ let detail = error.to_string().to_ascii_lowercase();+ let (message, fix_hint) = if detail.contains("credential") || detail.contains("session") {+ (+ "The configured inference credential is unavailable for a live completion.",+ "Reconnect the configured provider or provide an explicit API credential, then rerun doctor with --live.",+ )+ } else if is_external_cli_route(role, config) {+ (+ "This CLI-backed inference route has no explicit credential that can be frozen for inspection.",+ "Configure an explicit provider API key or choose a provider with a frozen inspection credential, then rerun doctor with --live.",+ )+ } else {+ (+ "The configured inference model could not be prepared for a live completion.",+ "Check the provider and model configuration, then rerun doctor with --live.",+ )+ };+ Finding::error(id, message, fix_hint)+}++fn is_external_cli_route(role: &str, config: &Config) -> bool {+ let provider = crate::inference::provider::factory::provider_for_role(role, config);+ let provider = provider.trim();+ provider == "claude_agent_sdk"+ || provider.starts_with("claude_agent_sdk:")+ || provider.starts_with("claude-code:")+}++fn safe_model_id(model: &str) -> bool {+ !model.is_empty()+ && model.len() <= 200+ && !model.contains("://")+ && model.bytes().all(|byte| {+ byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'/' | b':')+ })+}++fn elapsed_ms(duration: Duration) -> u64 {+ duration.as_millis().min(u64::MAX as u128) as u64+}diff --git a/crates/openhuman-core/src/doctor/checks/inference_live_budget_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_live_budget_tests.rsnew file mode 100644index 0000000000..3fc1ef3e59--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/inference_live_budget_tests.rs@@ -0,0 +1,92 @@+//! Output-budget capability tests for live inference checks.++use super::inference_live::{probe_prepared_model, LiveProbeCache};+use crate::doctor::FindingSeverity;+use crate::inference::provider::factory::{+ InspectionOutputBudgetCapability, InspectionRequestIdentity, PreparedInspectionChatModel,+};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};++struct InvocationCounter(Arc<AtomicUsize>);++#[async_trait::async_trait]+impl ChatModel<()> for InvocationCounter {+ async fn invoke(+ &self,+ _state: &(),+ _request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(ModelResponse::assistant("OK"))+ }+}++fn prepared(+ invocations: Arc<AtomicUsize>,+ output_budget: InspectionOutputBudgetCapability,+) -> PreparedInspectionChatModel {+ PreparedInspectionChatModel {+ model: Arc::new(InvocationCounter(Arc::clone(&invocations))),+ model_id: "gpt-codex".into(),+ identity: InspectionRequestIdentity::new(+ "https://chatgpt.com/backend-api/codex".into(),+ "dummy-frozen-codex-token".into(),+ "gpt-codex".into(),+ ),+ output_budget,+ }+}++#[tokio::test]+async fn unsupported_output_budget_is_skipped_without_invoking_the_model() {+ let invocations = Arc::new(AtomicUsize::new(0));+ let finding = probe_prepared_model(+ &LiveProbeCache::default(),+ prepared(+ Arc::clone(&invocations),+ InspectionOutputBudgetCapability::Unsupported,+ ),+ "inference/live/chat",+ )+ .await;+ let invocation_count = invocations.load(Ordering::SeqCst);++ assert!(+ finding.severity == FindingSeverity::Skipped && invocation_count == 0,+ "a route without an enforced output limit must skip before invoking; severity={:?}, invocations={invocation_count}",+ finding.severity+ );+}++#[tokio::test]+async fn unsupported_budget_is_not_hidden_by_a_cached_bounded_result() {+ let cache = LiveProbeCache::default();+ let bounded_invocations = Arc::new(AtomicUsize::new(0));+ let bounded = probe_prepared_model(+ &cache,+ prepared(+ Arc::clone(&bounded_invocations),+ InspectionOutputBudgetCapability::Bounded,+ ),+ "inference/live/chat",+ )+ .await;+ assert_eq!(bounded.severity, FindingSeverity::Pass);+ assert_eq!(bounded_invocations.load(Ordering::SeqCst), 1);++ let unsupported_invocations = Arc::new(AtomicUsize::new(0));+ let unsupported = probe_prepared_model(+ &cache,+ prepared(+ Arc::clone(&unsupported_invocations),+ InspectionOutputBudgetCapability::Unsupported,+ ),+ "inference/live/reasoning",+ )+ .await;++ assert_eq!(unsupported.severity, FindingSeverity::Skipped);+ assert_eq!(unsupported_invocations.load(Ordering::SeqCst), 0);+}diff --git a/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_live_tests.rsnew file mode 100644index 0000000000..aaa618de6a--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs@@ -0,0 +1,716 @@+//! Behaviour tests for the opt-in live inference checks.++use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::config::schema::ephemeral_route::{apply as apply_ephemeral_route, EphemeralRoute};+use crate::config::Config;+use crate::core::runtime::{CoreContext, DomainSet};+use crate::doctor::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};+use serde_json::{json, Value};+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++const CHECK_CHAT: &str = "inference/live/chat";+const TEST_BEARER: &str = "dummy-doctor-bearer";+const RESPONSE_SECRET: &str = "provider-response-must-not-leak";+const ENDPOINT_SECRET: &str = "endpoint-query-secret";++fn completion_path() -> String {+ format!("/openai/{ENDPOINT_SECRET}/chat/completions")+}++struct Fixture {+ config: Config,+ _temp: tempfile::TempDir,+}++fn isolated_config() -> Fixture {+ let temp = tempfile::tempdir().expect("temporary doctor fixture");+ let root = temp.path();+ let config = Config {+ workspace_dir: root.join("workspace"),+ action_dir: root.join("action"),+ config_path: root.join("config.toml"),+ ..Config::default()+ };+ Fixture {+ config,+ _temp: temp,+ }+}++fn config_for(server: &MockServer, model: &str) -> Fixture {+ let mut fixture = isolated_config();+ let mut config = Config {+ workspace_dir: fixture.config.workspace_dir.clone(),+ action_dir: fixture.config.action_dir.clone(),+ config_path: fixture.config.config_path.clone(),+ default_model: Some(model.to_string()),+ ..Config::default()+ };+ apply_ephemeral_route(+ &mut config,+ EphemeralRoute {+ endpoint: format!("{}/openai/{ENDPOINT_SECRET}", server.uri()),+ api_key: TEST_BEARER.to_string(),+ headers: Vec::new(),+ },+ );+ fixture.config = config;+ fixture+}++fn add_cloud_provider(config: &mut Config, slug: &str, endpoint: &str, model: &str) {+ config.cloud_providers.push(CloudProviderCreds {+ id: format!("provider-id-{slug}"),+ slug: slug.to_string(),+ label: "Doctor test provider".to_string(),+ endpoint: endpoint.to_string(),+ auth_style: AuthStyle::Bearer,+ default_model: Some(model.to_string()),+ });+}++fn cloud_route_fixture(+ server: &MockServer,+ providers: &[(&str, &str, &str, &str)],+ chat_slug: &str,+ reasoning_slug: &str,+) -> Fixture {+ let mut fixture = isolated_config();+ fixture.config.default_model = Some("provider/shared-model".into());+ let mut active_profiles = serde_json::Map::new();+ let mut profile_records = serde_json::Map::new();+ for (slug, endpoint_suffix, model, credential) in providers {+ add_cloud_provider(+ &mut fixture.config,+ slug,+ &format!("{}/{endpoint_suffix}/{ENDPOINT_SECRET}", server.uri()),+ model,+ );+ let provider = format!("provider:{slug}");+ let profile_id = format!("{provider}:default");+ active_profiles.insert(provider.clone(), Value::String(profile_id.clone()));+ profile_records.insert(+ profile_id,+ json!({+ "provider": provider,+ "profile_name": "default",+ "kind": "token",+ "token": credential,+ "metadata": {}+ }),+ );+ }+ let profile_path = fixture+ .config+ .config_path+ .parent()+ .expect("config fixture has a parent")+ .join("auth-profiles.json");+ std::fs::write(+ profile_path,+ serde_json::to_vec(&json!({+ "schema_version": 1,+ "active_profiles": active_profiles,+ "profiles": profile_records+ }))+ .expect("serialize dummy profile data"),+ )+ .expect("write dummy keys only inside this temp fixture");+ fixture.config.chat_provider = Some(format!("{chat_slug}:provider/shared-model"));+ fixture.config.reasoning_provider = Some(format!("{reasoning_slug}:provider/shared-model"));+ fixture+}++fn provider_completion_path(endpoint_suffix: &str) -> String {+ format!("/{endpoint_suffix}/{ENDPOINT_SECRET}/chat/completions")+}++fn completion_response(model: &str, content: &str) -> Value {+ json!({+ "id": "doctor-completion",+ "model": model,+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": content},+ "finish_reason": "stop"+ }],+ "usage": {"prompt_tokens": 2, "completion_tokens": 1, "total_tokens": 3}+ })+}++async fn run_live(fixture: Fixture, only: Vec<&str>) -> crate::doctor::DoctorReport {+ let expected_ids = only.iter().map(|id| id.to_string()).collect::<Vec<_>>();+ let Fixture { config, _temp } = fixture;+ let context = CoreContext::for_test_with_config(DomainSet::full(), config.clone());+ let report = CoreContext::scope(context, async move {+ let doctor_ctx = DoctorCtx::from_config(config);+ crate::doctor::runner::run(+ &doctor_ctx,+ DoctorOptions {+ tier: DoctorTier::Live,+ only: only.into_iter().map(str::to_string).collect(),+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("doctor report should be returned");+ for id in expected_ids {+ assert!(+ report.checks_run.contains(&id) || report.checks_skipped.contains(&id),+ "requested id {id} was not recognized: {:?}",+ report.findings+ );+ }+ assert!(+ !report.findings.iter().any(|finding| {+ finding.check_id == "doctor/selection" && finding.severity == FindingSeverity::Error+ }),+ "an unknown check id must never masquerade as a successful selected check"+ );+ drop(_temp);+ report+}++fn finding<'a>(report: &'a crate::doctor::DoctorReport, id: &str) -> &'a Finding {+ report+ .findings+ .iter()+ .find(|finding| finding.check_id == id)+ .unwrap_or_else(|| panic!("missing finding for {id}: {:?}", report.findings))+}++#[tokio::test]+async fn live_chat_sends_the_fixed_short_prompt_and_reports_only_safe_metadata() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(completion_path()))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(completion_response(+ "provider/answered-model",+ RESPONSE_SECRET,+ )),+ )+ .mount(&server)+ .await;++ let report = run_live(+ config_for(&server, "provider/configured-model"),+ vec![CHECK_CHAT],+ )+ .await;+ let result = finding(&report, CHECK_CHAT);+ assert_eq!(result.severity, FindingSeverity::Pass);+ let serialized = serde_json::to_value(&report).expect("report serializes");+ assert!(+ serialized["findings"]+ .as_array()+ .unwrap()+ .iter()+ .find(|item| item["check_id"] == CHECK_CHAT)+ .and_then(|item| item.get("duration_ms"))+ .is_some(),+ "live completion latency metadata is present"+ );+ assert!(+ result.message.contains("provider/answered-model")+ || result.message.contains("provider/configured-model"),+ "the finding includes only an available safe model identifier"+ );++ let requests = server+ .received_requests()+ .await+ .expect("mock records calls");+ assert_eq!(requests.len(), 1, "one completion is enough for this role");+ let body: Value = serde_json::from_slice(&requests[0].body).expect("request is JSON");+ assert_eq!(body["messages"].as_array().unwrap().len(), 1);+ assert_eq!(body["messages"][0]["content"], "Reply OK");+ assert!(body["max_tokens"]+ .as_u64()+ .is_some_and(|value| (1..=5).contains(&value)));+ assert_eq!(+ requests[0]+ .headers+ .get("authorization")+ .map(|value| value.to_str().unwrap()),+ Some("Bearer dummy-doctor-bearer")+ );++ let serialized = serde_json::to_string(&report).expect("report serializes");+ for secret in [TEST_BEARER, ENDPOINT_SECRET, RESPONSE_SECRET] {+ assert!(!serialized.contains(secret), "report leaked {secret}");+ }+}++#[tokio::test]+async fn live_probe_uses_selected_doctor_config_inside_another_ambient_context() {+ let ambient_server = MockServer::start().await;+ let selected_server = MockServer::start().await;+ for server in [&ambient_server, &selected_server] {+ Mock::given(method("POST"))+ .and(path(completion_path()))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(completion_response("provider/selected-model", "OK")),+ )+ .mount(server)+ .await;+ }+ let ambient = config_for(&ambient_server, "provider/ambient-model");+ let selected = config_for(&selected_server, "provider/selected-model");+ let context = CoreContext::for_test_with_config(DomainSet::full(), ambient.config);+ let report = CoreContext::scope(context, async move {+ crate::doctor::runner::run(+ &DoctorCtx::from_config(selected.config),+ DoctorOptions {+ tier: DoctorTier::Live,+ only: vec![CHECK_CHAT.into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("selected config live probe returns a report");+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+ assert_eq!(+ ambient_server+ .received_requests()+ .await+ .expect("ambient mock records calls")+ .len(),+ 0,+ "the ambient profile must not receive a selected-config probe"+ );+ assert_eq!(+ selected_server+ .received_requests()+ .await+ .expect("selected mock records calls")+ .len(),+ 1+ );+}++#[tokio::test]+async fn managed_chat_probe_uses_the_inspection_only_factory_callback() {+ use crate::inference::registry::{+ register_inspection_chat_model_in, ChatModelRequest, InspectionChatModelFactory,+ };+ use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+ };+ use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};++ struct CountingModel(Arc<AtomicUsize>);+ #[async_trait::async_trait]+ impl ChatModel<()> for CountingModel {+ async fn invoke(+ &self,+ _state: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ self.0.fetch_add(1, Ordering::SeqCst);+ assert_eq!(request.messages.len(), 1);+ assert_eq!(request.messages[0].text(), "Reply OK");+ assert!(request+ .max_tokens+ .is_some_and(|value| (1..=5).contains(&value)));+ Ok(ModelResponse::assistant("OK"))+ }+ }++ let extensions = crate::core::slots::Extensions::new();+ let calls = Arc::new(AtomicUsize::new(0));+ let model_calls = Arc::clone(&calls);+ let factory: InspectionChatModelFactory = Arc::new(move |request: &ChatModelRequest<'_>| {+ assert_eq!(request.role, "chat");+ Ok(crate::inference::registry::InspectionChatModelBuild {+ model: Arc::new(CountingModel(Arc::clone(&model_calls))) as Arc<dyn ChatModel<()>>,+ model_id: "managed-test-model".into(),+ endpoint: "https://managed.test/openai/v1".into(),+ credential: "frozen-managed-test-token".into(),+ })+ });+ register_inspection_chat_model_in(&extensions, "openhuman", factory);++ let mut fixture = isolated_config();+ let config = &mut fixture.config;+ config.chat_provider = Some("openhuman".into());+ config.default_model = Some("managed-test-model".into());+ let Fixture { config, _temp } = fixture;+ let context = CoreContext::for_test_with_extensions(+ DomainSet::full(),+ Some(config.workspace_dir.clone()),+ extensions,+ );+ let report = CoreContext::scope(context, async move {+ crate::doctor::runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Live,+ only: vec![CHECK_CHAT.into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("managed inspection callback completes");+ drop(_temp);++ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn live_chat_maps_auth_quota_and_unavailable_errors_without_provider_text() {+ let cases = [(401, "auth"), (429, "quota"), (503, "unavailable")];+ for (status, classification) in cases {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(completion_path()))+ .respond_with(ResponseTemplate::new(status).set_body_json(json!({+ "error": {"message": RESPONSE_SECRET, "code": "secret-provider-code"}+ })))+ .mount(&server)+ .await;++ let report = run_live(+ config_for(&server, "provider/configured-model"),+ vec![CHECK_CHAT],+ )+ .await;+ let result = finding(&report, CHECK_CHAT);+ assert_eq!(result.severity, FindingSeverity::Error, "HTTP {status}");+ assert!(+ result.message.to_ascii_lowercase().contains(classification),+ "{}",+ result.message+ );+ let serialized = serde_json::to_string(&report).expect("report serializes");+ for secret in [+ TEST_BEARER,+ ENDPOINT_SECRET,+ RESPONSE_SECRET,+ "secret-provider-code",+ ] {+ assert!(+ !serialized.contains(secret),+ "HTTP {status} leaked {secret}"+ );+ }+ }+}++#[tokio::test]+async fn identical_role_routes_share_one_completion_but_keep_each_role_finding() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(completion_path()))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(completion_response("provider/shared-model", "OK")),+ )+ .mount(&server)+ .await;+ let mut config = config_for(&server, "provider/shared-model");+ config.config.reasoning_provider = config.config.chat_provider.clone();++ let report = run_live(config, vec![CHECK_CHAT, "inference/live/reasoning"]).await;+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+ assert_eq!(+ finding(&report, "inference/live/reasoning").severity,+ FindingSeverity::Pass+ );+ assert_eq!(+ server+ .received_requests()+ .await+ .expect("mock records calls")+ .len(),+ 1,+ "matching endpoint, credential, and model are probed once"+ );+}++#[tokio::test]+async fn same_endpoint_and_credential_with_distinct_models_get_distinct_completions() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(completion_path()))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(completion_response("provider/answered-model", "OK")),+ )+ .mount(&server)+ .await;+ let mut fixture = config_for(&server, "provider/chat-model");+ fixture.config.reasoning_provider = Some("ephemeral-route:reasoning-model".into());++ let report = run_live(fixture, vec![CHECK_CHAT, "inference/live/reasoning"]).await;+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+ assert_eq!(+ finding(&report, "inference/live/reasoning").severity,+ FindingSeverity::Pass+ );+ assert_eq!(+ server+ .received_requests()+ .await+ .expect("mock records calls")+ .len(),+ 2,+ "a distinct resolved model needs its own completion"+ );+}++#[tokio::test]+async fn same_endpoint_and_model_with_distinct_credentials_get_distinct_completions() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(provider_completion_path("shared")))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(completion_response("provider/answered-model", "OK")),+ )+ .mount(&server)+ .await;+ let fixture = cloud_route_fixture(+ &server,+ &[+ (+ "route-one",+ "shared",+ "provider/shared-model",+ "dummy-key-one",+ ),+ (+ "route-two",+ "shared",+ "provider/shared-model",+ "dummy-key-two",+ ),+ ],+ "route-one",+ "route-two",+ );++ let report = run_live(fixture, vec![CHECK_CHAT, "inference/live/reasoning"]).await;+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+ assert_eq!(+ finding(&report, "inference/live/reasoning").severity,+ FindingSeverity::Pass+ );+ let requests = server+ .received_requests()+ .await+ .expect("mock records calls");+ assert_eq!(+ requests.len(),+ 2,+ "different frozen credentials cannot deduplicate"+ );+ let mut authorization = requests+ .iter()+ .map(|request| {+ request+ .headers+ .get("authorization")+ .expect("credential reaches local mock")+ .to_str()+ .unwrap()+ .to_string()+ })+ .collect::<Vec<_>>();+ authorization.sort();+ assert_eq!(+ authorization,+ vec!["Bearer dummy-key-one", "Bearer dummy-key-two"]+ );+}++#[tokio::test]+async fn distinct_endpoints_with_same_credential_and_model_get_distinct_completions() {+ let server = MockServer::start().await;+ for endpoint in ["first", "second"] {+ Mock::given(method("POST"))+ .and(path(provider_completion_path(endpoint)))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(completion_response("provider/answered-model", "OK")),+ )+ .mount(&server)+ .await;+ }+ let fixture = cloud_route_fixture(+ &server,+ &[+ (+ "route-one",+ "first",+ "provider/shared-model",+ "dummy-same-key",+ ),+ (+ "route-two",+ "second",+ "provider/shared-model",+ "dummy-same-key",+ ),+ ],+ "route-one",+ "route-two",+ );++ let report = run_live(fixture, vec![CHECK_CHAT, "inference/live/reasoning"]).await;+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+ assert_eq!(+ finding(&report, "inference/live/reasoning").severity,+ FindingSeverity::Pass+ );+ let requests = server+ .received_requests()+ .await+ .expect("mock records calls");+ assert_eq!(+ requests.len(),+ 2,+ "different endpoints need separate probes"+ );+ let mut paths = requests+ .iter()+ .map(|request| request.url.path().to_string())+ .collect::<Vec<_>>();+ paths.sort();+ assert_eq!(+ paths,+ vec![+ provider_completion_path("first"),+ provider_completion_path("second")+ ]+ );+}++#[tokio::test]+async fn distinct_provider_slugs_with_the_same_endpoint_credential_and_model_deduplicate() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path(provider_completion_path("shared")))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(completion_response("provider/answered-model", "OK")),+ )+ .mount(&server)+ .await;+ let fixture = cloud_route_fixture(+ &server,+ &[+ (+ "alias-one",+ "shared",+ "provider/shared-model",+ "dummy-same-key",+ ),+ (+ "alias-two",+ "shared",+ "provider/shared-model",+ "dummy-same-key",+ ),+ ],+ "alias-one",+ "alias-two",+ );++ let report = run_live(fixture, vec![CHECK_CHAT, "inference/live/reasoning"]).await;+ assert_eq!(finding(&report, CHECK_CHAT).severity, FindingSeverity::Pass);+ assert_eq!(+ finding(&report, "inference/live/reasoning").severity,+ FindingSeverity::Pass+ );+ assert_eq!(+ server+ .received_requests()+ .await+ .expect("mock records calls")+ .len(),+ 1,+ "provider ids and slugs are not part of the effective route identity"+ );+}++#[tokio::test]+async fn connect_tier_skips_live_chat_without_sending_a_completion() {+ let server = MockServer::start().await;+ let fixture = config_for(&server, "provider/model");+ let Fixture { config, _temp } = fixture;+ let context = CoreContext::for_test_with_config(DomainSet::full(), config.clone());+ let report = CoreContext::scope(context, async move {+ crate::doctor::runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Connect,+ only: vec![CHECK_CHAT.into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("connect tier returns report");+ drop(_temp);++ assert_eq!(report.checks_skipped, vec![CHECK_CHAT]);+ assert!(report.findings.iter().any(|result| {+ result.check_id == CHECK_CHAT && result.severity == FindingSeverity::Skipped+ }));+ assert!(!report.findings.iter().any(|result| {+ result.check_id == "doctor/selection" && result.severity == FindingSeverity::Error+ }));+ assert!(server+ .received_requests()+ .await+ .expect("mock records calls")+ .is_empty());+}++#[test]+fn configured_role_ids_are_registered_as_live_checks_for_that_config() {+ use crate::inference::provider::factory::provider_for_role;++ let mut fixture = isolated_config();+ let config = &mut fixture.config;+ config.default_model = Some("shared-model".into());+ config.chat_provider = Some("ephemeral-route:shared-model".into());+ config.reasoning_provider = Some("ephemeral-route:shared-model".into());+ config.vision_provider = Some("ephemeral-route:vision-model".into());+ config.memory_provider = Some("ephemeral-route:summary-model".into());+ let ctx = DoctorCtx::from_config(config.clone());+ let checks = crate::doctor::registry::registered_checks_for(&ctx)+ .expect("selected config supplies its own live role checks");+ let by_id = checks+ .iter()+ .map(|check| (check.id().to_owned(), check.tier()))+ .collect::<std::collections::HashMap<_, _>>();++ for role in [+ "chat",+ "reasoning",+ "agentic",+ "burst",+ "coding",+ "vision",+ "memory",+ "summarization",+ ] {+ let id = format!("inference/live/{role}");+ assert_eq!(by_id.get(&id), Some(&DoctorTier::Live), "missing {id}");+ assert!(!provider_for_role(role, config).is_empty());+ }+ assert!(!by_id.contains_key("inference/live/embeddings"));+}diff --git a/crates/openhuman-core/src/doctor/checks/inference_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_tests.rsnew file mode 100644index 0000000000..e7088fc6c5--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/inference_tests.rs@@ -0,0 +1,604 @@+use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::config::Config;+use crate::doctor::runner;+use crate::doctor::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};++const PROVIDER_REF: &str = "inference/provider-ref";+const CONSTRUCT: &str = "inference/construct";+const TEMPERATURE: &str = "inference/temperature";++async fn run_only(config: Config, check_id: &str) -> Vec<Finding> {+ let context = DoctorCtx::from_config(config);+ runner::run(+ &context,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("the selected doctor check should run")+ .findings+}++fn isolated_config(root: &std::path::Path) -> Config {+ let mut config = Config::default();+ config.config_path = root.join("config.toml");+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("action");+ config+}++fn filesystem_snapshot(root: &std::path::Path) -> Vec<(std::path::PathBuf, bool, Vec<u8>)> {+ fn visit(+ root: &std::path::Path,+ dir: &std::path::Path,+ snapshot: &mut Vec<(std::path::PathBuf, bool, Vec<u8>)>,+ ) {+ for entry in std::fs::read_dir(dir).expect("read temporary config fixture") {+ let entry = entry.expect("read fixture entry");+ let path = entry.path();+ let metadata = entry.metadata().expect("read fixture metadata");+ let is_dir = metadata.is_dir();+ let contents = if is_dir {+ Vec::new()+ } else {+ std::fs::read(&path).expect("read fixture file")+ };+ snapshot.push((+ path.strip_prefix(root)+ .expect("fixture path is under root")+ .to_path_buf(),+ is_dir,+ contents,+ ));+ if is_dir {+ visit(root, &path, snapshot);+ }+ }+ }++ let mut snapshot = Vec::new();+ visit(root, root, &mut snapshot);+ snapshot.sort_by(|left, right| left.0.cmp(&right.0));+ snapshot+}++fn finding<'a>(findings: &'a [Finding], check_id: &str) -> &'a Finding {+ findings+ .iter()+ .find(|finding| finding.check_id == check_id)+ .unwrap_or_else(|| panic!("expected finding from {check_id}: {findings:#?}"))+}++#[tokio::test]+async fn an_unregistered_chat_provider_reports_its_config_path() {+ let mut config = Config::default();+ config.chat_provider = Some("nope".to_owned());++ let findings = run_only(config, PROVIDER_REF).await;+ let result = finding(&findings, PROVIDER_REF);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("chat_provider"));+}++#[tokio::test]+async fn invalid_role_primary_cloud_and_route_references_report_each_path() {+ let mut config = Config::default();+ config.chat_provider = Some("missing-chat-provider:model".to_owned());+ config.reasoning_provider = Some("missing-chat-provider:model".to_owned());+ config.agentic_provider = Some("missing-agentic-provider:model".to_owned());+ config.coding_provider = Some("missing-coding-provider:model".to_owned());+ config.vision_provider = Some("missing-vision-provider:model".to_owned());+ config.memory_provider = Some("missing-memory-provider:model".to_owned());+ config.embeddings_provider = Some("missing-embedding-provider".to_owned());+ config.primary_cloud = Some("missing-primary-id".to_owned());+ config.stt_provider = Some("missing-stt-provider".to_owned());+ config.tts_provider = Some("missing-tts-provider".to_owned());+ config.model_routes = vec![crate::config::ModelRouteConfig {+ hint: "reasoning".to_owned(),+ model: "missing-route-provider:model".to_owned(),+ }];+ config.embedding_routes = vec![crate::config::EmbeddingRouteConfig {+ hint: "recall".to_owned(),+ provider: "missing-embedding-provider".to_owned(),+ model: "embedding-model".to_owned(),+ dimensions: Some(768),+ }];++ let findings = run_only(config, PROVIDER_REF).await;+ let paths = findings+ .iter()+ .filter(|result| result.check_id == PROVIDER_REF)+ .filter_map(|result| result.config_path.as_deref())+ .collect::<Vec<_>>();++ for expected in [+ "chat_provider",+ "reasoning_provider",+ "agentic_provider",+ "coding_provider",+ "vision_provider",+ "memory_provider",+ "embeddings_provider",+ "primary_cloud",+ "model_routes[0].model",+ "embedding_routes[0].provider",+ "stt_provider",+ "tts_provider",+ ] {+ assert!(+ paths.contains(&expected),+ "missing {expected} provider-reference finding: {findings:#?}"+ );+ }+}++#[cfg(feature = "voice")]+#[tokio::test]+async fn registered_voice_provider_ids_resolve_without_calling_the_factory() {+ let _registered = RegisterVoiceProviders;+ crate::voice::factory::registry::register_stt_provider(+ "doctor-fake-stt",+ |_, _| -> anyhow::Result<Box<dyn crate::voice::SttProvider>> {+ panic!("provider-reference checks must not invoke STT constructors")+ },+ );+ crate::voice::factory::registry::register_tts_provider(+ "doctor-fake-tts",+ |_, _| -> anyhow::Result<Box<dyn crate::voice::TtsProvider>> {+ panic!("provider-reference checks must not invoke TTS constructors")+ },+ );++ let mut config = Config::default();+ config.stt_provider = Some("doctor-fake-stt:small".to_owned());+ config.tts_provider = Some("doctor-fake-tts:voice".to_owned());++ let findings = run_only(config, PROVIDER_REF).await;++ assert!(+ findings+ .iter()+ .all(|result| result.check_id != PROVIDER_REF),+ "registered STT/TTS providers should resolve without constructing them: {findings:#?}"+ );+}++#[cfg(feature = "voice")]+struct RegisterVoiceProviders;++#[cfg(feature = "voice")]+impl Drop for RegisterVoiceProviders {+ fn drop(&mut self) {+ crate::voice::factory::registry::unregister_stt_provider("doctor-fake-stt");+ crate::voice::factory::registry::unregister_tts_provider("doctor-fake-tts");+ }+}++#[tokio::test]+async fn a_byok_cloud_fallback_without_a_key_reports_construction_failure() {+ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+ use crate::config::test_env::EnvVarGuard;++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let temp = tempfile::tempdir().expect("temporary configuration directory");+ let _env_guard = EnvVarGuard::locked_async()+ .await+ .with("HOME", temp.path())+ .with("OPENHUMAN_WORKSPACE", temp.path())+ .without("OPENHUMAN_ACTION_DIR")+ .without("OPENAI_API_KEY")+ .without("OPENHUMAN_CORE_TOKEN");++ let mut config = isolated_config(temp.path());+ config.chat_provider = Some("ollama:qwen2.5".to_owned());+ config.primary_cloud = Some("provider-doctor-test".to_owned());+ config.cloud_providers = vec![CloudProviderCreds {+ id: "provider-doctor-test".to_owned(),+ slug: "doctor-test".to_owned(),+ label: "Doctor test provider".to_owned(),+ endpoint: "https://doctor-test.invalid/v1".to_owned(),+ auth_style: AuthStyle::Bearer,+ default_model: Some("test-model".to_owned()),+ }];+ config.vision_provider = Some("cloud".to_owned());++ let before = filesystem_snapshot(temp.path());+ let findings = run_only(config, CONSTRUCT).await;+ assert_eq!(filesystem_snapshot(temp.path()), before);+ let result = findings+ .iter()+ .find(|finding| {+ finding.check_id == CONSTRUCT+ && finding.config_path.as_deref() == Some("vision_provider")+ })+ .expect("the configured vision fallback should report its own config path");++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("vision_provider"));+ assert!(result.message.to_ascii_lowercase().contains("credential"));+ assert!(!temp.path().join("auth-profiles.json").exists());+ assert!(!temp.path().join("auth-profiles.lock").exists());+}++#[tokio::test]+async fn inspection_reports_refresh_required_without_refreshing_or_publishing_session_expiry() {+ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+ use crate::config::test_env::EnvVarGuard;+ use crate::core::events::DomainEvent;+ use crate::core::runtime::DispatchCtx;+ use crate::inference::provider::factory::create_chat_model_with_model_id_in_for_inspection;+ use std::io::{Read, Write};+ use std::net::TcpListener;+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};++ struct LocalProxyTrap {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+ }++ impl Drop for LocalProxyTrap {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::SeqCst);+ if let Some(thread) = self.thread.take() {+ let _ = thread.join();+ }+ }+ }++ fn no_session_expiry_event(receiver: &mut tinybus::EventReceiver<DomainEvent>) -> bool {+ loop {+ match receiver.try_recv() {+ Ok(DomainEvent::SessionExpired { .. }) => return false,+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,+ Err(_) => return true,+ }+ }+ }++ fn drain_events(receiver: &mut tinybus::EventReceiver<DomainEvent>) {+ loop {+ match receiver.try_recv() {+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,+ Err(_) => return,+ }+ }+ }++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let temp = tempfile::tempdir().expect("temporary configuration directory");+ let proxy = TcpListener::bind(("127.0.0.1", 0)).expect("local proxy trap listener");+ proxy+ .set_nonblocking(true)+ .expect("nonblocking proxy listener");+ let proxy_url = format!("http://{}", proxy.local_addr().unwrap());+ let proxy_requests = Arc::new(AtomicUsize::new(0));+ let server_requests = Arc::clone(&proxy_requests);+ let stop = Arc::new(AtomicBool::new(false));+ let server_stop = Arc::clone(&stop);+ let proxy_thread = std::thread::spawn(move || {+ while !server_stop.load(Ordering::SeqCst) {+ match proxy.accept() {+ Ok((mut stream, _)) => {+ server_requests.fetch_add(1, Ordering::SeqCst);+ let mut request = [0_u8; 512];+ let _ = stream.read(&mut request);+ let _ = stream.write_all(+ b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",+ );+ }+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ Err(_) => break,+ }+ }+ });+ let _proxy_trap = LocalProxyTrap {+ stop,+ thread: Some(proxy_thread),+ };+ let _env_guard = EnvVarGuard::locked_async()+ .await+ .with("HOME", temp.path())+ .with("OPENHUMAN_WORKSPACE", temp.path())+ .without("OPENHUMAN_ACTION_DIR")+ .with("HTTPS_PROXY", &proxy_url)+ .with("https_proxy", &proxy_url)+ .with("ALL_PROXY", &proxy_url)+ .with("all_proxy", &proxy_url)+ .with("NO_PROXY", "")+ .with("no_proxy", "")+ .without("OPENAI_API_KEY")+ .without("OPENHUMAN_CORE_TOKEN");++ let mut config = isolated_config(temp.path());+ config.secrets.encrypt = false;+ config.chat_provider = Some("ollama:qwen2.5".to_owned());+ config.vision_provider = Some("openai:gpt-4o".to_owned());+ config.primary_cloud = Some("provider-openai".to_owned());+ config.cloud_providers = vec![CloudProviderCreds {+ id: "provider-openai".to_owned(),+ slug: "openai".to_owned(),+ label: "OpenAI".to_owned(),+ endpoint: "https://api.openai.invalid/v1".to_owned(),+ auth_style: AuthStyle::Bearer,+ default_model: Some("gpt-4o".to_owned()),+ }];+ config.resolved_endpoints.control_plane_url = Some("https://api.openhuman.invalid".to_owned());++ let profile_path = temp.path().join("auth-profiles.json");+ std::fs::write(+ &profile_path,+ serde_json::json!({+ "schema_version": 1,+ "active_profiles": {},+ "profiles": {+ "provider:openai:oauth": {+ "provider": "provider:openai",+ "profile_name": "oauth",+ "kind": "oauth",+ "access_token": "expired-openai-access-token",+ "refresh_token": "refresh-trap-token",+ "expires_at": "2000-01-01T00:00:00Z",+ "metadata": {}+ },+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": "expired-app-session-token",+ "metadata": { "session_expires_at": "2000-01-01T00:00:00Z" }+ }+ }+ })+ .to_string(),+ )+ .expect("write isolated read-only credential fixture");+ let before = filesystem_snapshot(temp.path());++ crate::core::bus::init().await.expect("event bus init");+ let mut events = crate::core::bus::BUS+ .get()+ .expect("event bus initialized")+ .receiver();+ drain_events(&mut events);+ let error = match create_chat_model_with_model_id_in_for_inspection(+ &DispatchCtx::unbound(),+ "vision",+ &config,+ config.default_temperature,+ ) {+ Err(error) => error,+ Ok(_) => panic!("an expired OAuth credential must not pass static inspection"),+ };+ let message = error.to_string();++ assert!(+ message.contains("OpenAI OAuth credential requires refresh"),+ "inspection should report the safe refresh classification: {message}"+ );+ assert!(!message.contains("expired-openai-access-token"));+ assert!(!message.contains("refresh-trap-token"));+ assert_eq!(proxy_requests.load(Ordering::SeqCst), 0);+ assert!(no_session_expiry_event(&mut events));+ assert_eq!(filesystem_snapshot(temp.path()), before);+ assert!(!temp.path().join("auth-profiles.lock").exists());+}++#[tokio::test]+async fn a_fully_configured_managed_default_constructs_cleanly() {+ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+ use crate::config::test_env::EnvVarGuard;+ use crate::inference::provider::factory::PROVIDER_OPENHUMAN;+ use crate::inference::registry::{register_inspection_chat_model, InspectionChatModelFactory};++ struct ManagedModel {+ generations: Arc<AtomicUsize>,+ }++ #[async_trait::async_trait]+ impl ChatModel<()> for ManagedModel {+ async fn invoke(+ &self,+ _state: &(),+ _request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ self.generations.fetch_add(1, Ordering::SeqCst);+ panic!("doctor's construction check must not generate a model response")+ }+ }++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let temp = tempfile::tempdir().expect("temporary configuration directory");+ let _env_guard = EnvVarGuard::locked_async()+ .await+ .with("HOME", temp.path())+ .with("OPENHUMAN_WORKSPACE", temp.path())+ .without("OPENHUMAN_ACTION_DIR")+ .without("OPENAI_API_KEY")+ .without("OPENHUMAN_CORE_TOKEN");+ let constructions = Arc::new(AtomicUsize::new(0));+ let generations = Arc::new(AtomicUsize::new(0));+ let build_constructions = Arc::clone(&constructions);+ let model_generations = Arc::clone(&generations);+ let inspection_factory: InspectionChatModelFactory = Arc::new(move |_| {+ build_constructions.fetch_add(1, Ordering::SeqCst);+ Ok(crate::inference::registry::InspectionChatModelBuild {+ model: Arc::new(ManagedModel {+ generations: Arc::clone(&model_generations),+ }) as Arc<dyn ChatModel<()>>,+ model_id: "managed-test-model".to_owned(),+ endpoint: "https://api.openhuman.invalid/openai/v1".to_owned(),+ credential: "doctor-test-session-token".to_owned(),+ })+ });+ register_inspection_chat_model(PROVIDER_OPENHUMAN, inspection_factory);+ let _registered_model = RegisterManagedModel;++ let mut config = isolated_config(temp.path());+ config.api_url = Some("https://api.openhuman.invalid".to_owned());+ config.api_key = Some("doctor-test-session-token".to_owned());+ config.primary_cloud = Some("provider-openhuman".to_owned());+ config.cloud_providers = vec![CloudProviderCreds {+ id: "provider-openhuman".to_owned(),+ slug: "openhuman".to_owned(),+ label: "OpenHuman".to_owned(),+ endpoint: "https://api.openhuman.invalid/v1".to_owned(),+ auth_style: AuthStyle::OpenhumanJwt,+ default_model: Some("managed-test-model".to_owned()),+ }];+ let before = filesystem_snapshot(temp.path());+ let findings = run_only(config, CONSTRUCT).await;+ assert_eq!(filesystem_snapshot(temp.path()), before);++ assert!(+ !findings.is_empty()+ && findings+ .iter()+ .all(|result| result.severity == FindingSeverity::Pass),+ "managed defaults should not report construction errors: {findings:#?}"+ );+ assert!(+ constructions.load(Ordering::SeqCst) > 0,+ "the managed provider factory must be consulted"+ );+ assert_eq!(generations.load(Ordering::SeqCst), 0);+ assert!(findings+ .iter()+ .all(|result| !result.message.contains("doctor-test-session-token")));+ assert!(!temp.path().join("auth-profiles.json").exists());+ assert!(!temp.path().join("auth-profiles.lock").exists());+}++#[tokio::test]+async fn missing_byok_model_is_reported_by_the_native_construct_check() {+ let workspace = tempfile::tempdir().expect("create isolated config fixture");+ let mut config = isolated_config(workspace.path());+ config.default_model = None;+ config.primary_cloud = None;+ config.chat_provider = Some("doctor-empty-model:".to_owned());+ config.reasoning_provider = None;+ config.agentic_provider = None;+ config.coding_provider = None;+ config.vision_provider = None;+ config.memory_provider = None;+ config.cloud_providers = vec![CloudProviderCreds {+ id: "doctor-empty-model-provider".to_owned(),+ slug: "doctor-empty-model".to_owned(),+ label: "Empty model fixture".to_owned(),+ endpoint: "https://provider.example.invalid/v1".to_owned(),+ auth_style: AuthStyle::Bearer,+ default_model: None,+ }];++ let findings = run_only(config, CONSTRUCT).await;+ let result = finding(&findings, CONSTRUCT);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("chat_provider"));+ assert!(result.message.contains("model is missing"));+ assert!(!result.message.contains("private"));+}++struct RegisterManagedModel;++impl Drop for RegisterManagedModel {+ fn drop(&mut self) {+ crate::inference::registry::unregister_inspection_chat_model(+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,+ );+ }+}++#[tokio::test]+async fn embedding_only_configuration_does_not_construct_a_chat_model_for_embeddings() {+ use crate::inference::registry::{register_inspection_chat_model, InspectionChatModelFactory};++ let _inference_guard = crate::inference::inference_test_guard_async().await;++ let roles = Arc::new(std::sync::Mutex::new(Vec::new()));+ let seen_roles = Arc::clone(&roles);+ let factory: InspectionChatModelFactory = Arc::new(move |request| {+ seen_roles.lock().unwrap().push(request.role.to_owned());+ anyhow::bail!("test construction marker")+ });+ register_inspection_chat_model(+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,+ factory,+ );+ let _registered_model = RegisterManagedModel;++ let mut config = Config::default();+ config.embeddings_provider = Some("custom".to_owned());+ config.primary_cloud = Some("openhuman".to_owned());+ let findings = run_only(config, CONSTRUCT).await;++ assert!(+ !roles+ .lock()+ .unwrap()+ .iter()+ .any(|role| role == "embeddings"),+ "embedding-only configuration must use embedding validation, never chat construction"+ );+ assert!(+ !findings.is_empty(),+ "the configured chat roles should still be inspected through their fake factory"+ );+}++#[tokio::test]+async fn an_out_of_range_temperature_reports_the_role_setting() {+ let mut config = Config::default();+ config.default_temperature = 3.5;++ let findings = run_only(config, TEMPERATURE).await;+ let result = finding(&findings, TEMPERATURE);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("default_temperature"));+}++#[tokio::test]+async fn invalid_role_and_agent_temperatures_report_their_config_paths() {+ let mut config = Config::default();+ config.chat_provider = Some("openai:[email protected]".to_owned());+ config.model_routes = vec![crate::config::ModelRouteConfig {+ hint: "reasoning".to_owned(),+ model: "openai:[email protected]".to_owned(),+ }];+ config.agents.insert(+ "delegate-test".to_owned(),+ crate::config::DelegateAgentConfig {+ model: "openrouter/example".to_owned(),+ system_prompt: None,+ temperature: Some(f64::NAN),+ max_depth: 3,+ },+ );++ let findings = run_only(config, TEMPERATURE).await;+ let paths = findings+ .iter()+ .filter(|result| result.check_id == TEMPERATURE)+ .filter_map(|result| result.config_path.as_deref())+ .collect::<Vec<_>>();++ for expected in [+ "chat_provider",+ "model_routes[0].model",+ "agents[0].temperature",+ ] {+ assert!(+ paths.contains(&expected),+ "missing {expected} temperature finding: {findings:#?}"+ );+ }+}diff --git a/crates/openhuman-core/src/doctor/checks/integrations.rs b/crates/openhuman-core/src/doctor/checks/integrations.rsnew file mode 100644index 0000000000..037c55a9d8--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/integrations.rs@@ -0,0 +1,111 @@+//! Read-only checks for configured Composio connectivity.++use std::sync::Arc;++use async_trait::async_trait;+use tinyconnectors_bus::{+ names::methods, ComposioConnectedIntegrationsMode, ComposioConnectedIntegrationsResponse,+ ComposioListConnectedIntegrationsRequest,+};++use crate::config::Config;+use crate::doctor::{ComponentId, DoctorCheck, DoctorTier, Finding};++#[async_trait]+trait ComposioProbe: Send + Sync {+ async fn list_existing(&self, config: &Config) -> Result<Option<()>, ()>;+}++struct ExistingConnectorProbe;++#[async_trait]+impl ComposioProbe for ExistingConnectorProbe {+ async fn list_existing(&self, config: &Config) -> Result<Option<()>, ()> {+ #[cfg(feature = "modules")]+ {+ let mode = if config.composio.host_credential.is_some()+ || config.composio.mode.trim() == crate::config::schema::COMPOSIO_MODE_DIRECT+ {+ ComposioConnectedIntegrationsMode::Direct+ } else if config.composio.mode.trim().is_empty()+ || config.composio.mode.trim() == crate::config::schema::COMPOSIO_MODE_BACKEND+ {+ ComposioConnectedIntegrationsMode::Backend+ } else {+ return Ok(None);+ };+ let response = crate::modules::connectors::call_existing_readonly::<+ _,+ ComposioConnectedIntegrationsResponse,+ >(+ config,+ methods::LIST_CONNECTED_INTEGRATIONS,+ ComposioListConnectedIntegrationsRequest { mode },+ )+ .await+ .map_err(|_| ())?;+ return Ok(response.map(|_| ()));+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = config;+ Ok(None)+ }+ }+}++pub(super) fn for_context() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(ComposioCheck {+ probe: Arc::new(ExistingConnectorProbe),+ })]+}++struct ComposioCheck {+ probe: Arc<dyn ComposioProbe>,+}++impl ComposioCheck {+ #[cfg(test)]+ fn with_probe(probe: Arc<dyn ComposioProbe>) -> Self {+ Self { probe }+ }+}++#[async_trait]+impl DoctorCheck for ComposioCheck {+ fn id(&self) -> &str {+ "integrations/composio"+ }+ fn category(&self) -> &str {+ "integrations"+ }+ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }+ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Connectors)+ }++ async fn detect(&self, ctx: &crate::doctor::DoctorCtx) -> Vec<Finding> {+ let finding = if ctx.config().composio.host_credential.is_none()+ && ctx.config().composio.mode.trim() == crate::config::schema::COMPOSIO_MODE_DISABLED+ {+ Finding::skipped(+ self.id(),+ "Composio is disabled in the selected configuration.",+ "Enable Composio in Integrations settings to inspect it.",+ )+ } else {+ match self.probe.list_existing(ctx.config()).await {+ Ok(Some(())) => Finding::pass(self.id(), "The existing Composio connector answered a read-only connection check."),+ Ok(None) => Finding::skipped(self.id(), "No matching ready Composio connector is available for the selected configuration.", "Open Integrations normally, then rerun doctor."),+ Err(()) => Finding::error(self.id(), "The ready Composio connector could not complete its read-only check.", "Check the Composio connection in Integrations, then rerun doctor."),+ }+ };+ vec![finding]+ }+}++#[cfg(test)]+#[path = "integrations_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/integrations_tests.rs b/crates/openhuman-core/src/doctor/checks/integrations_tests.rsnew file mode 100644index 0000000000..a21aedcd70--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/integrations_tests.rs@@ -0,0 +1,116 @@+use super::*;+use crate::doctor::contract::{DoctorCtx, FindingSeverity};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++struct ExistingList {+ expected_workspace: std::path::PathBuf,+ result: Result<Option<()>, ()>,+ calls: Arc<AtomicUsize>,+}++#[async_trait::async_trait]+impl ComposioProbe for ExistingList {+ async fn list_existing(&self, config: &crate::config::Config) -> Result<Option<()>, ()> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ assert_eq!(config.workspace_dir, self.expected_workspace);+ self.result+ }+}++fn config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config.composio.host_credential = Some(+ crate::config::schema::ComposioHostCredential::direct("doctor-fake-key")+ .entity_id("doctor-fake-entity"),+ );+ config+}++#[tokio::test]+async fn an_existing_composio_connection_list_passes_without_exposing_credentials() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let config = config_in(scratch.path());+ let calls = Arc::new(AtomicUsize::new(0));+ let check = ComposioCheck::with_probe(Arc::new(ExistingList {+ expected_workspace: config.workspace_dir.clone(),+ result: Ok(Some(())),+ calls: Arc::clone(&calls),+ }));++ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);+ assert_eq!(finding.check_id, "integrations/composio");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("doctor-fake-key"));+ assert!(!finding.message.contains("doctor-fake-entity"));+ assert_eq!(calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn selected_b_does_not_reuse_a_ready_or_cached_a_connection_list() {+ let ambient = tempfile::tempdir().expect("create ambient fixture");+ let selected = tempfile::tempdir().expect("create selected fixture");+ let config_a = config_in(ambient.path());+ let config_b = config_in(selected.path());+ let calls = Arc::new(AtomicUsize::new(0));+ let check = ComposioCheck::with_probe(Arc::new(ExistingList {+ expected_workspace: config_b.workspace_dir.clone(),+ result: Ok(None),+ calls: Arc::clone(&calls),+ }));+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let finding = crate::core::runtime::CoreContext::scope(ambient_context, async {+ check+ .detect(&DoctorCtx::from_config(config_b))+ .await+ .remove(0)+ })+ .await;++ assert_eq!(finding.check_id, "integrations/composio");+ assert_eq!(finding.severity, FindingSeverity::Skipped);+ assert_eq!(calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn an_existing_connector_failure_is_reported_without_raw_module_text() {+ let scratch = tempfile::tempdir().expect("create isolated fixture");+ let config = config_in(scratch.path());+ let calls = Arc::new(AtomicUsize::new(0));+ let check = ComposioCheck::with_probe(Arc::new(ExistingList {+ expected_workspace: config.workspace_dir.clone(),+ result: Err(()),+ calls: Arc::clone(&calls),+ }));+ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert_eq!(calls.load(Ordering::SeqCst), 1);+}++#[cfg(feature = "modules")]+#[tokio::test]+async fn the_default_probe_skips_a_disabled_connector_without_starting_the_runtime() {+ let scratch = tempfile::tempdir().expect("create isolated fixture");+ let mut config = config_in(scratch.path());+ config.modules.enabled = false;+ let started_before = crate::modules::runtime::is_started();++ let result = ExistingConnectorProbe.list_existing(&config).await;++ assert!(matches!(result, Ok(None)));+ assert_eq!(crate::modules::runtime::is_started(), started_before);+}diff --git a/crates/openhuman-core/src/doctor/checks/mcp.rs b/crates/openhuman-core/src/doctor/checks/mcp.rsnew file mode 100644index 0000000000..8117e06c41--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/mcp.rs@@ -0,0 +1,225 @@+//! Read-only checks over MCP clients that are already open.++use std::sync::Arc;++use async_trait::async_trait;++use crate::config::McpServerConfig;+use crate::doctor::contract::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};++use super::canonical_segment;++#[async_trait]+trait McpStatusProbe: Send + Sync {+ async fn statuses(+ &self,+ config: &crate::config::Config,+ ) -> Result<Option<Vec<tinymcp_bus::ConnStatus>>, McpStatusFailure>;+}++#[derive(Clone, Copy)]+enum McpStatusFailure {+ Unavailable,+ Failed,+}++struct ExistingClientProbe;++#[async_trait]+impl McpStatusProbe for ExistingClientProbe {+ async fn statuses(+ &self,+ config: &crate::config::Config,+ ) -> Result<Option<Vec<tinymcp_bus::ConnStatus>>, McpStatusFailure> {+ #[cfg(feature = "mcp")]+ {+ crate::mcp::module_client::McpConfiguredClient::existing_status_for_config(config)+ .await+ .map_err(|error| match error {+ tinybus::module::ModuleCallError::Unavailable => McpStatusFailure::Unavailable,+ _ => McpStatusFailure::Failed,+ })+ }+ #[cfg(not(feature = "mcp"))]+ {+ let _ = config;+ Err(McpStatusFailure::Unavailable)+ }+ }+}++pub(super) fn for_context(ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ checks_for_servers(+ &ctx.config().mcp_client.servers,+ Arc::new(ExistingClientProbe),+ )+ .into_iter()+ .map(|check| Arc::new(check) as Arc<dyn DoctorCheck>)+ .collect()+}++fn checks_for_servers(+ servers: &[McpServerConfig],+ probe: Arc<dyn McpStatusProbe>,+) -> Vec<McpServerCheck> {+ let mut indexes = std::collections::HashMap::<String, usize>::new();+ let mut checks: Vec<McpServerCheck> = Vec::new();+ for server in servers {+ let check = McpServerCheck::configured(server, Arc::clone(&probe));+ if let Some(index) = indexes.get(&check.id).copied() {+ checks[index].duplicate_definitions = true;+ } else {+ indexes.insert(check.id.clone(), checks.len());+ checks.push(check);+ }+ }+ checks+}++struct McpServerCheck {+ id: String,+ server_id: String,+ enabled: bool,+ duplicate_definitions: bool,+ probe: Arc<dyn McpStatusProbe>,+}++impl McpServerCheck {+ fn configured(server: &McpServerConfig, probe: Arc<dyn McpStatusProbe>) -> Self {+ Self {+ id: format!("mcp/{}", canonical_segment(&server.name)),+ server_id: server.name.clone(),+ enabled: server.enabled,+ duplicate_definitions: false,+ probe,+ }+ }++ #[cfg(test)]+ fn with_probe(server: &McpServerConfig, probe: Arc<dyn McpStatusProbe>) -> Self {+ Self {+ id: format!("mcp/{}", canonical_segment(&server.name)),+ server_id: server.name.clone(),+ enabled: server.enabled,+ duplicate_definitions: false,+ probe,+ }+ }++ async fn finding(&self, ctx: &DoctorCtx) -> Finding {+ if !ctx.config().components.mcp+ || !ctx.config().modules.enabled+ || !ctx.config().mcp_client.enabled+ {+ return Finding::skipped(+ &self.id,+ "MCP is disabled in the selected configuration.",+ "Enable MCP in the selected configuration to check server connections.",+ );+ }+ if self.duplicate_definitions {+ return Finding::error(+ &self.id,+ "Multiple MCP server definitions use a duplicate identifier; their connection state is ambiguous.",+ "Remove or rename duplicate entries in mcp_client.servers so each server name is unique.",+ );+ }+ if !self.enabled {+ return Finding::skipped(+ &self.id,+ "The configured MCP server is disabled.",+ "Enable the server in MCP settings to check its connection.",+ );+ }+ let statuses = match self.probe.statuses(ctx.config()).await {+ Ok(Some(statuses)) => statuses,+ Ok(None) | Err(McpStatusFailure::Unavailable) => {+ return Finding::skipped(+ &self.id,+ "No matching MCP runtime is already open for this configuration.",+ "Open the MCP runtime, then rerun doctor to inspect server connections.",+ );+ }+ Err(McpStatusFailure::Failed) => {+ return Finding::error(+ &self.id,+ "The already-open MCP runtime did not return server status.",+ "Review the MCP runtime and rerun doctor.",+ );+ }+ };+ let Some(status) = statuses+ .iter()+ .find(|status| status.server_id == self.server_id)+ else {+ return Finding::error(+ &self.id,+ "The configured MCP server has no status in the open runtime.",+ "Review the MCP server configuration and reconnect it, then rerun doctor.",+ );+ };++ match status.status {+ tinymcp_bus::ServerStatus::Connected => {+ Finding::pass(&self.id, "The configured MCP server is connected.")+ }+ tinymcp_bus::ServerStatus::Disabled => Finding::skipped(+ &self.id,+ "The MCP server is disabled in the open runtime.",+ "Enable the MCP server to check its connection.",+ ),+ tinymcp_bus::ServerStatus::Connecting => Finding::new(+ &self.id,+ crate::doctor::FindingSeverity::Info,+ "The MCP server connection is still in progress.",+ "Wait for the connection attempt to finish, then rerun doctor.",+ ),+ tinymcp_bus::ServerStatus::Disconnected+ | tinymcp_bus::ServerStatus::Unauthorized+ | tinymcp_bus::ServerStatus::Error => Finding::error(+ &self.id,+ format!(+ "The MCP server connection failed (status: {}).",+ status.status.as_str()+ ),+ "Review the MCP server connection and authentication settings, then reconnect it.",+ ),+ _ => Finding::error(+ &self.id,+ "The MCP server reported an unsupported connection state.",+ "Review the MCP server status and rerun doctor.",+ ),+ }+ }+}++#[async_trait]+impl DoctorCheck for McpServerCheck {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ "MCP servers"+ }++ fn tier(&self) -> DoctorTier {+ if self.duplicate_definitions {+ DoctorTier::Static+ } else {+ DoctorTier::Connect+ }+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Mcp)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ vec![self.finding(ctx).await]+ }+}++#[cfg(test)]+#[path = "mcp_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/mcp_tests.rs b/crates/openhuman-core/src/doctor/checks/mcp_tests.rsnew file mode 100644index 0000000000..7c20e0c726--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/mcp_tests.rs@@ -0,0 +1,188 @@+use super::*;+use crate::doctor::contract::{DoctorOptions, FindingSeverity};+use std::path::Path;+use std::sync::atomic::{AtomicUsize, Ordering};++struct FixedStatuses(Result<Option<Vec<tinymcp_bus::ConnStatus>>, McpStatusFailure>);++#[async_trait]+impl McpStatusProbe for FixedStatuses {+ async fn statuses(+ &self,+ _config: &crate::config::Config,+ ) -> Result<Option<Vec<tinymcp_bus::ConnStatus>>, McpStatusFailure> {+ self.0.clone()+ }+}++fn server(name: &str) -> McpServerConfig {+ McpServerConfig {+ server: tinymcp_bus::McpServerConfig {+ name: name.to_owned(),+ ..Default::default()+ },+ ..Default::default()+ }+}++fn config_in(root: &Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config+}++fn status(server_id: &str, status: tinymcp_bus::ServerStatus) -> tinymcp_bus::ConnStatus {+ tinymcp_bus::ConnStatus {+ server_id: server_id.to_owned(),+ qualified_name: "example/server".to_owned(),+ display_name: "fixture".to_owned(),+ status,+ tool_count: 0,+ last_error: Some("private endpoint response and token=secret".to_owned()),+ auth_hint: None,+ }+}++#[tokio::test]+async fn a_failed_existing_server_is_an_error_without_its_raw_error_text() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check = McpServerCheck::with_probe(+ &server("server-a"),+ Arc::new(FixedStatuses(Ok(Some(vec![status(+ "server-a",+ tinymcp_bus::ServerStatus::Error,+ )])))),+ );++ let finding = check+ .detect(&DoctorCtx::from_config(config_in(scratch.path())))+ .await+ .remove(0);++ assert_eq!(finding.check_id, "mcp/server-a");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("status: error"));+ assert!(!finding.message.contains("private endpoint"));+ assert!(!finding.message.contains("secret"));+}++#[tokio::test]+async fn an_absent_existing_client_is_skipped_without_bootstrapping_one() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check = McpServerCheck::with_probe(&server("server-a"), Arc::new(FixedStatuses(Ok(None))));++ let finding = check+ .detect(&DoctorCtx::from_config(config_in(scratch.path())))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Skipped);+ assert!(finding.message.contains("already open"));+}++#[tokio::test]+async fn an_existing_runtime_status_failure_is_reported_as_an_error() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check = McpServerCheck::with_probe(+ &server("server-a"),+ Arc::new(FixedStatuses(Err(McpStatusFailure::Failed))),+ );++ let finding = check+ .detect(&DoctorCtx::from_config(config_in(scratch.path())))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("did not return server status"));+}++#[tokio::test]+async fn disabled_mcp_component_skips_each_configured_server() {+ let workspace = tempfile::tempdir().expect("create isolated config fixture");+ let mut config = crate::config::Config::default();+ config.workspace_dir = workspace.path().join("workspace");+ config.action_dir = workspace.path().join("actions");+ config.config_path = workspace.path().join("config.toml");+ config.mcp_client.servers.push(server("server-a"));+ let mut components = crate::core::runtime::ComponentSet::all();+ components.mcp = false;+ let report = crate::doctor::runner::run(+ &DoctorCtx::from_config(config).with_components(components),+ DoctorOptions {+ only: vec!["mcp/server-a".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("disabled MCP component is represented as skipped");++ assert_eq!(report.checks_skipped, vec!["mcp/server-a".to_owned()]);+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "mcp/server-a" && finding.severity == FindingSeverity::Skipped+ }));+}++struct CountingProbe(Arc<AtomicUsize>);++#[async_trait]+impl McpStatusProbe for CountingProbe {+ async fn statuses(+ &self,+ _config: &crate::config::Config,+ ) -> Result<Option<Vec<tinymcp_bus::ConnStatus>>, McpStatusFailure> {+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(None)+ }+}++#[tokio::test]+async fn duplicate_mcp_definitions_report_one_error_without_probing_either_entry() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let calls = Arc::new(AtomicUsize::new(0));+ let servers = [+ server("server-a"),+ McpServerConfig {+ server: tinymcp_bus::McpServerConfig {+ name: "server-a".to_owned(),+ endpoint: "https://example.invalid/mcp".to_owned(),+ ..Default::default()+ },+ ..Default::default()+ },+ ];+ let checks = checks_for_servers(&servers, Arc::new(CountingProbe(Arc::clone(&calls))));++ assert_eq!(checks.len(), 1, "one exact id represents the ambiguity");+ let finding = checks[0]+ .detect(&DoctorCtx::from_config(config_in(scratch.path())))+ .await+ .remove(0);++ assert_eq!(finding.check_id, "mcp/server-a");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("Multiple MCP server definitions"));+ assert_eq!(calls.load(Ordering::SeqCst), 0);+}++#[test]+fn duplicate_mcp_definition_errors_are_available_at_the_static_tier() {+ let servers = [server("server-a"), server("server-a")];+ let checks = checks_for_servers(&servers, Arc::new(FixedStatuses(Ok(None))));++ assert_eq!(checks.len(), 1);+ assert_eq!(checks[0].tier(), DoctorTier::Static);+}++#[test]+fn arbitrary_server_names_produce_valid_noncolliding_ids() {+ let first =+ McpServerCheck::configured(&server("Server A/α"), Arc::new(FixedStatuses(Ok(None))));+ let second =+ McpServerCheck::configured(&server("server a/α"), Arc::new(FixedStatuses(Ok(None))));++ assert_eq!(first.id(), "mcp/__x_i_53657276657220412fceb1");+ assert_ne!(first.id(), second.id());+}diff --git a/crates/openhuman-core/src/doctor/checks/memory.rs b/crates/openhuman-core/src/doctor/checks/memory.rsnew file mode 100644index 0000000000..b7f65bec22--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/memory.rs@@ -0,0 +1,264 @@+//! Selected-configuration memory checks.++use std::sync::Arc;++use async_trait::async_trait;++use crate::doctor::contract::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};+use crate::memory::engine::EngineHealth;++const MEMORY_HEALTH_ID: &str = "memory/health";++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(BindingCheck), Arc::new(HealthCheck)]+}++struct BindingCheck;++#[async_trait]+impl DoctorCheck for BindingCheck {+ fn id(&self) -> &str {+ "memory/binding"+ }++ fn category(&self) -> &str {+ "memory"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Memory)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let config = ctx.config();+ if !config.components.memory {+ return vec![Finding::skipped(+ self.id(),+ "Memory is disabled in the selected configuration.",+ "Enable memory in the selected configuration to inspect its binding.",+ )];+ }+ let engine = config.memory.engine.trim();+ if engine.is_empty() {+ return vec![Finding::error(+ self.id(),+ "No memory engine is selected.",+ "Select an available memory engine and rerun doctor.",+ )];+ }+ if engine.eq_ignore_ascii_case(crate::memory::engine::DISABLED_ENGINE) {+ return vec![Finding::skipped(+ self.id(),+ "Memory is turned off in the selected configuration.",+ "Select a memory engine to enable memory.",+ )];+ }+ if !binding_supported(+ engine,+ crate::memory::engine_registry::lookup(engine).is_some(),+ ) {+ return vec![Finding::error(+ self.id(),+ "The selected memory engine is not available in this build.",+ "Select a registered memory engine and rerun doctor.",+ )];+ }+ vec![Finding::pass(+ self.id(),+ "A supported memory engine is selected in the effective configuration.",+ )]+ }+}++fn binding_supported(engine: &str, registered: bool) -> bool {+ engine == crate::memory::engine::CORTEXDB_ENGINE || registered+}++struct HealthCheck;++#[async_trait]+impl DoctorCheck for HealthCheck {+ fn id(&self) -> &str {+ MEMORY_HEALTH_ID+ }++ fn category(&self) -> &str {+ "memory"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Memory)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ if !ctx.config().components.memory {+ tracing::debug!(target: "doctor", check = MEMORY_HEALTH_ID, outcome = "component_disabled");+ return vec![Finding::skipped(+ self.id(),+ "Memory is disabled in the selected configuration.",+ "Enable memory in the selected configuration to check engine health.",+ )];+ }+ if ctx+ .config()+ .memory+ .engine+ .eq_ignore_ascii_case(crate::memory::engine::DISABLED_ENGINE)+ {+ tracing::debug!(target: "doctor", check = MEMORY_HEALTH_ID, outcome = "engine_disabled");+ return vec![Finding::skipped(+ self.id(),+ "Memory is turned off in the selected configuration.",+ "Select a memory engine to check its health.",+ )];+ }+ tracing::debug!(target: "doctor", check = MEMORY_HEALTH_ID, event = "probe_started");+ let memory = probe_selected_config(ctx.config()).await;+ let outcome = match &memory {+ EngineHealth::Ok => "healthy",+ EngineHealth::Degraded(_) => "degraded",+ EngineHealth::Down(_) => "down",+ };+ tracing::debug!(target: "doctor", check = MEMORY_HEALTH_ID, outcome);+ findings_for_health(memory)+ }+}++fn findings_for_health(health: EngineHealth) -> Vec<Finding> {+ match health {+ EngineHealth::Ok => vec![Finding::pass(+ MEMORY_HEALTH_ID,+ "The selected memory engine is healthy.",+ )],+ EngineHealth::Degraded(reason) => vec![Finding::new(+ MEMORY_HEALTH_ID,+ crate::doctor::FindingSeverity::Warn,+ safe_reason(&reason),+ "Check the memory engine configuration and connectivity.",+ )],+ EngineHealth::Down(reason) => vec![Finding::error(+ MEMORY_HEALTH_ID,+ safe_reason(&reason),+ "Check the memory engine configuration and connectivity.",+ )],+ }+}++fn safe_reason(reason: &str) -> String {+ let lower = reason.to_ascii_lowercase();+ if matches!(+ lower.as_str(),+ "engine is down"+ | "the configured memory service is unavailable"+ | "no usable credential is available for the selected backend."+ | "the selected backend endpoint is unavailable."+ | "backend attribution headers are unavailable."+ | "the selected memory engine configuration is invalid."+ | "cortexdb api key is not configured."+ | "cortexdb credentials could not be read."+ ) {+ return reason.to_owned();+ }+ if reason.contains("detail withheld") {+ if let Some(code) = reason.split("HTTP_").nth(1).and_then(|tail| {+ let digits = tail+ .chars()+ .take_while(char::is_ascii_digit)+ .collect::<String>();+ (digits.len() == 3).then_some(digits)+ }) {+ return format!("The memory service returned HTTP {code}.");+ }+ if reason.contains("UNAVAILABLE") {+ return "The memory service is temporarily unavailable.".to_owned();+ }+ if reason.contains("RATE_LIMITED") {+ return "The memory service is rate limited.".to_owned();+ }+ }+ "The selected memory engine reported an error; details are withheld.".to_owned()+}++async fn probe_selected_config(config: &crate::config::Config) -> EngineHealth {+ let engine_id = config.memory.engine.trim();+ #[cfg(test)]+ if let Some(health) = crate::memory::engine::doctor_test_health(config).await {+ return health;+ }+ match engine_id {+ crate::memory::engine::TINYHUMANS_ENGINE => {+ let Some(probe) = crate::memory::engine_registry::read_only_health_probe(engine_id)+ else {+ return unavailable("No read-only health probe is registered for this engine.");+ };+ probe(config.clone()).await+ }+ crate::memory::engine::CORTEXDB_ENGINE => cortexdb_health(config).await,+ crate::memory::engine::DISABLED_ENGINE => {+ unavailable("Memory is disabled in the selected configuration.")+ }+ other => {+ let Some(probe) = crate::memory::engine_registry::read_only_health_probe(other) else {+ return unavailable("No read-only health probe is registered for this engine.");+ };+ probe(config.clone()).await+ }+ }+}++async fn cortexdb_health(config: &crate::config::Config) -> EngineHealth {+ use crate::security::credentials::AuthService;+ use tinymemory_integrations::{EngineCredential, EngineSettings};++ let profile = match AuthService::get_profile_read_only(+ config,+ crate::config::schema::MEMORY_CORTEXDB_KEY_NAME,+ None,+ ) {+ Ok(Some(profile)) => profile,+ Ok(None) => return EngineHealth::Down("CortexDB API key is not configured.".to_owned()),+ Err(_) => return EngineHealth::Down("CortexDB credentials could not be read.".to_owned()),+ };+ let key = match profile.kind {+ crate::security::credentials::profiles::AuthProfileKind::Token => profile.token,+ crate::security::credentials::profiles::AuthProfileKind::OAuth => {+ profile.token_set.map(|tokens| tokens.access_token)+ }+ };+ let Some(key) = key.filter(|key| !key.trim().is_empty()) else {+ return EngineHealth::Down("CortexDB API key is not configured.".to_owned());+ };+ let endpoint = config+ .memory+ .endpoint_for(crate::memory::engine::CORTEXDB_ENGINE)+ .unwrap_or_else(|| tinymemory_integrations::cortex::CORTEX_API_ENDPOINT.to_owned());+ let settings = EngineSettings {+ endpoint: Some(endpoint),+ observed_actor: config.memory.observed_actor,+ ..EngineSettings::default()+ };+ match tinymemory_integrations::build_engine(+ crate::memory::engine::CORTEXDB_ENGINE,+ &settings,+ EngineCredential::Static(key),+ ) {+ Ok(engine) => engine.health().await,+ Err(_) => EngineHealth::Down("CortexDB engine configuration is invalid.".to_owned()),+ }+}++fn unavailable(reason: &str) -> EngineHealth {+ EngineHealth::Down(reason.to_owned())+}++#[cfg(test)]+#[path = "memory_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/memory_live.rs b/crates/openhuman-core/src/doctor/checks/memory_live.rsnew file mode 100644index 0000000000..8bd5ad5d02--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/memory_live.rs@@ -0,0 +1,347 @@+//! The opt-in store/fetch/forget roundtrip against the selected memory engine.++use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;+use tinymemory_api::{+ EngineDescriptor, Error as MemoryApiError, FetchMode, FetchRequest, ItemId, MemoryEngine,+ MemoryMeta, MetaFilter, Namespace, Reach, Segment, SegmentKind, StoreItem,+};++use crate::doctor::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};+use crate::memory::engine_registry::ReadOnlyEngineError;+use crate::memory::error::MemoryError;++const CHECK_ID: &str = "memory/roundtrip";+const OPERATION_TIMEOUT: Duration = Duration::from_secs(12);+const CLEANUP_TIMEOUT: Duration = Duration::from_secs(8);++pub(super) struct MemoryRoundtripCheck;++#[async_trait]+impl DoctorCheck for MemoryRoundtripCheck {+ fn id(&self) -> &str {+ CHECK_ID+ }++ fn category(&self) -> &str {+ "memory"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Live+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Memory)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let config = ctx.config();+ let engine = match crate::memory::engine::resolve_read_only_for_inspection(config).await {+ Ok(engine) => engine,+ Err(ReadOnlyEngineError::EngineDisabled | ReadOnlyEngineError::ComponentDisabled) => {+ return vec![Finding::skipped(+ CHECK_ID,+ "Memory is disabled in the selected configuration.",+ "Enable memory and select an engine before running the live roundtrip.",+ )];+ }+ Err(error) => return vec![finding_for_engine_error(error)],+ };++ let Some(fetch_mode) = probe_fetch_mode(engine.descriptor()) else {+ return vec![Finding::error(+ CHECK_ID,+ "The selected memory engine does not support a keyword or hybrid probe fetch.",+ "Select a memory engine that supports text-query fetch, store, and scoped forget.",+ )];+ };++ match roundtrip(engine, fetch_mode).await {+ Ok(()) => vec![Finding::pass(+ CHECK_ID,+ "The selected memory engine stored, fetched, and removed a temporary probe.",+ )],+ Err(finding) => vec![finding],+ }+ }+}++fn probe_fetch_mode(descriptor: &EngineDescriptor) -> Option<FetchMode> {+ [FetchMode::Hybrid, FetchMode::Keyword]+ .into_iter()+ .find(|mode| descriptor.supports(*mode))+}++struct ScopedScratchCleanup {+ engine: Arc<dyn MemoryEngine>,+ ids: Vec<ItemId>,+ reach: Reach,+ armed: bool,+}++impl ScopedScratchCleanup {+ fn new(engine: Arc<dyn MemoryEngine>, id: ItemId, namespace: Namespace) -> Self {+ Self {+ engine,+ ids: vec![id],+ reach: Reach::exact(namespace),+ armed: true,+ }+ }++ fn include_receipt_id(&mut self, id: ItemId) {+ if !self.ids.contains(&id) {+ self.ids.push(id);+ }+ }++ async fn cleanup(&mut self) -> bool {+ if !self.armed {+ return true;+ }+ let result = tokio::time::timeout(+ CLEANUP_TIMEOUT,+ self.engine+ .forget_within(self.ids.clone(), self.reach.clone()),+ )+ .await;+ if matches!(result, Ok(Ok(_))) {+ self.armed = false;+ true+ } else {+ false+ }+ }+}++impl Drop for ScopedScratchCleanup {+ fn drop(&mut self) {+ if !self.armed {+ return;+ }+ let Ok(runtime) = tokio::runtime::Handle::try_current() else {+ tracing::warn!(+ check_id = CHECK_ID,+ "scratch cleanup could not be scheduled"+ );+ return;+ };+ let engine = Arc::clone(&self.engine);+ let ids = self.ids.clone();+ let reach = self.reach.clone();+ runtime.spawn(async move {+ match tokio::time::timeout(CLEANUP_TIMEOUT, engine.forget_within(ids, reach)).await {+ Ok(Ok(_)) => {}+ Ok(Err(_)) | Err(_) => {+ tracing::warn!(+ check_id = CHECK_ID,+ "scratch cleanup failed after cancellation"+ );+ }+ }+ });+ }+}++async fn roundtrip(engine: Arc<dyn MemoryEngine>, fetch_mode: FetchMode) -> Result<(), Finding> {+ let nonce = uuid::Uuid::new_v4().simple().to_string();+ let namespace = Namespace::new(vec![Segment::new(+ SegmentKind::Service,+ format!("openhuman-doctor-{nonce}"),+ )+ .expect("generated service namespace is valid")])+ .expect("one service namespace segment is valid");+ let item = StoreItem::document(+ "OpenHuman doctor memory roundtrip probe",+ MemoryMeta {+ namespace: namespace.clone(),+ ..MemoryMeta::default()+ },+ );+ // StoreItem fingerprints are the stable idempotency id used by all+ // engines. Compute it before store so an accepted-but-timed-out write can+ // still be cleaned up.+ let scratch_id = ItemId::new(item.fingerprint());+ let mut cleanup =+ ScopedScratchCleanup::new(engine.clone(), scratch_id.clone(), namespace.clone());++ let receipt = match tokio::time::timeout(OPERATION_TIMEOUT, engine.store(item)).await {+ Ok(Ok(receipt)) => receipt,+ Ok(Err(error)) => {+ let cleaned = cleanup.cleanup().await;+ return Err(failure_finding(error, Operation::Store, cleaned));+ }+ Err(_) => {+ let cleaned = cleanup.cleanup().await;+ return Err(timeout_finding(Operation::Store, cleaned));+ }+ };+ let stored_id = receipt.id;+ cleanup.include_receipt_id(stored_id.clone());++ let request = FetchRequest {+ filter: MetaFilter {+ reach: Some(Reach::exact(namespace)),+ ..MetaFilter::default()+ },+ ..FetchRequest::new("OpenHuman doctor memory roundtrip probe", fetch_mode, 1)+ };+ match tokio::time::timeout(OPERATION_TIMEOUT, engine.fetch(request)).await {+ Ok(Ok(page)) if page.hits.iter().any(|hit| hit.id == stored_id) => {}+ Ok(Ok(_)) => {+ let cleaned = cleanup.cleanup().await;+ return Err(Finding::error(+ CHECK_ID,+ "The memory engine stored the probe but could not fetch it from its scratch scope.",+ cleanup_hint(+ "Check the selected memory engine's indexing and retry the live check.",+ cleaned,+ ),+ ));+ }+ Ok(Err(error)) => {+ let cleaned = cleanup.cleanup().await;+ return Err(failure_finding(error, Operation::Fetch, cleaned));+ }+ Err(_) => {+ let cleaned = cleanup.cleanup().await;+ return Err(timeout_finding(Operation::Fetch, cleaned));+ }+ }++ if cleanup.cleanup().await {+ Ok(())+ } else {+ Err(Finding::error(+ CHECK_ID,+ "The memory engine answered the roundtrip but the temporary probe could not be removed.",+ "Check the selected memory engine and remove the isolated doctor service item before rerunning.",+ ))+ }+}++#[derive(Clone, Copy)]+enum Operation {+ Store,+ Fetch,+}++fn failure_finding(error: MemoryApiError, operation: Operation, cleaned: bool) -> Finding {+ // Some memory transports preserve a typed 402 as `InsufficientCredits`,+ // while others normalize it to `Engine` and retain the stable marker in+ // the sanitized display string. Recover only the known account-wide+ // refusal markers; ordinary engine errors keep the generic classification.+ let error_text = error.to_string();+ let classified = MemoryError::refusal_from_skip_reason(&error_text)+ .unwrap_or_else(|| MemoryError::from(error));+ let (message, hint) = match classified {+ MemoryError::Unauthorized(_) => (+ "The selected memory engine rejected its credential.",+ "Sign in again or update the selected memory credential, then rerun the live check.",+ ),+ MemoryError::InsufficientCredits(_) => (+ "The selected memory service has insufficient credits for a live probe.",+ "Review the TinyHumans memory billing balance before rerunning the live check.",+ ),+ MemoryError::PlanRequired(_) => (+ "Memory is not included in the selected account's plan.",+ "Upgrade to a plan that includes memory or select a different memory engine in Settings.",+ ),+ MemoryError::Unavailable(_) => (+ "The selected memory service is temporarily unavailable.",+ "Check the memory service status and retry the live check later.",+ ),+ MemoryError::Off(_) => (+ "The selected memory engine is not enabled.",+ "Enable a memory engine in the selected configuration and rerun the check.",+ ),+ MemoryError::Unsupported(_) => (+ "The selected memory engine does not support the requested probe operation.",+ "Select a memory engine that supports store, fetch, and scoped forget.",+ ),+ MemoryError::InvalidRequest(_) => (+ "The memory engine refused the doctor probe request.",+ "Check the selected memory engine configuration and rerun the live check.",+ ),+ MemoryError::Engine(_) | MemoryError::ConfigConflict(_) => (+ "The selected memory engine reported an error; details are withheld.",+ "Check the selected memory engine configuration and retry the live check.",+ ),+ };+ let operation = match operation {+ Operation::Store => "store",+ Operation::Fetch => "fetch",+ };+ Finding::error(+ CHECK_ID,+ format!("The memory {operation} probe failed. {message}"),+ cleanup_hint(hint, cleaned),+ )+}++fn timeout_finding(operation: Operation, cleaned: bool) -> Finding {+ let (name, fix) = match operation {+ Operation::Store => (+ "store",+ "Check the memory service status and retry the live check.",+ ),+ Operation::Fetch => (+ "fetch",+ "Check the memory service status and retry the live check.",+ ),+ };+ Finding::error(+ CHECK_ID,+ format!("The memory {name} probe timed out."),+ cleanup_hint(fix, cleaned),+ )+}++fn cleanup_hint(hint: &str, cleaned: bool) -> String {+ if cleaned {+ hint.to_owned()+ } else {+ format!(+ "{hint} The doctor could not confirm scratch cleanup; inspect the isolated doctor service scope."+ )+ }+}++fn finding_for_engine_error(error: ReadOnlyEngineError) -> Finding {+ match error {+ ReadOnlyEngineError::CredentialsUnavailable => Finding::error(+ CHECK_ID,+ error.safe_message(),+ "Check the selected memory credential profile and sign in again if needed.",+ ),+ ReadOnlyEngineError::EndpointUnavailable => Finding::error(+ CHECK_ID,+ error.safe_message(),+ "Configure the selected memory engine endpoint and rerun the live check.",+ ),+ ReadOnlyEngineError::EngineDisabled | ReadOnlyEngineError::ComponentDisabled => {+ Finding::skipped(+ CHECK_ID,+ error.safe_message(),+ "Enable memory and select an engine before running the live roundtrip.",+ )+ }+ ReadOnlyEngineError::UnsupportedEngine => Finding::error(+ CHECK_ID,+ error.safe_message(),+ "Select a memory engine with an inspection-safe constructor.",+ ),+ ReadOnlyEngineError::InvalidConfiguration => Finding::error(+ CHECK_ID,+ error.safe_message(),+ "Review the selected memory engine settings and rerun the live check.",+ ),+ }+}++#[cfg(test)]+#[path = "memory_live_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/memory_live_tests.rs b/crates/openhuman-core/src/doctor/checks/memory_live_tests.rsnew file mode 100644index 0000000000..c1046bacf8--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/memory_live_tests.rs@@ -0,0 +1,596 @@+use super::{failure_finding, MemoryRoundtripCheck, Operation};+use crate::config::Config;+use crate::core::runtime::{CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::doctor::contract::{DoctorCheck, DoctorCtx, FindingSeverity};+use crate::memory::test_fixtures::stored;+use async_trait::async_trait;+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc, Mutex,+};+use tempfile::TempDir;+use tinymemory_api::conformance::ReferenceEngine;+use tinymemory_api::{+ EngineDescriptor, EngineHealth, Error as MemoryApiError, FetchMode, FetchPage, FetchRequest,+ ForgetReport, ForgetTarget, ItemId, ListPage, ListRequest, MemoryEngine, MemoryMeta,+ MetaFilter, Namespace, Reach, RecallAnswer, RecallRequest, StoreItem, StoreReceipt,+};++#[derive(Clone)]+enum Failure {+ None,+ Fetch,+ FetchUntilCancelled,+ StoreUntilCancelled,+ StoreAfterAccept(MemoryApiError),+}++#[derive(Default)]+struct Calls {+ steps: Vec<&'static str>,+ fetch_modes: Vec<FetchMode>,+ stored: Vec<(ItemId, Namespace)>,+ scoped_forgets: Vec<(Vec<ItemId>, Reach)>,+ unscoped_forgets: usize,+}++struct ProbeEngine {+ inner: ReferenceEngine,+ failure: Failure,+ calls: Mutex<Calls>,+ store_started: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,+ fetch_started: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,+ cleanup_finished: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,+}++impl ProbeEngine {+ fn new(failure: Failure) -> Self {+ Self {+ inner: ReferenceEngine::new(),+ failure,+ calls: Mutex::new(Calls::default()),+ store_started: Mutex::new(None),+ fetch_started: Mutex::new(None),+ cleanup_finished: Mutex::new(None),+ }+ }++ fn pending_fetch() -> (+ Self,+ tokio::sync::oneshot::Receiver<()>,+ tokio::sync::oneshot::Receiver<()>,+ ) {+ let (fetch_started_tx, fetch_started_rx) = tokio::sync::oneshot::channel();+ let (cleanup_finished_tx, cleanup_finished_rx) = tokio::sync::oneshot::channel();+ (+ Self {+ inner: ReferenceEngine::new(),+ failure: Failure::FetchUntilCancelled,+ calls: Mutex::new(Calls::default()),+ store_started: Mutex::new(None),+ fetch_started: Mutex::new(Some(fetch_started_tx)),+ cleanup_finished: Mutex::new(Some(cleanup_finished_tx)),+ },+ fetch_started_rx,+ cleanup_finished_rx,+ )+ }++ fn pending_store() -> (+ Self,+ tokio::sync::oneshot::Receiver<()>,+ tokio::sync::oneshot::Receiver<()>,+ ) {+ let (store_started_tx, store_started_rx) = tokio::sync::oneshot::channel();+ let (cleanup_finished_tx, cleanup_finished_rx) = tokio::sync::oneshot::channel();+ (+ Self {+ inner: ReferenceEngine::new(),+ failure: Failure::StoreUntilCancelled,+ calls: Mutex::new(Calls::default()),+ store_started: Mutex::new(Some(store_started_tx)),+ fetch_started: Mutex::new(None),+ cleanup_finished: Mutex::new(Some(cleanup_finished_tx)),+ },+ store_started_rx,+ cleanup_finished_rx,+ )+ }+}++#[async_trait]+impl MemoryEngine for ProbeEngine {+ fn descriptor(&self) -> &EngineDescriptor {+ self.inner.descriptor()+ }++ async fn health(&self) -> EngineHealth {+ self.inner.health().await+ }++ async fn recall(&self, request: RecallRequest) -> tinymemory_api::Result<RecallAnswer> {+ self.inner.recall(request).await+ }++ async fn fetch(&self, request: FetchRequest) -> tinymemory_api::Result<FetchPage> {+ {+ let mut calls = self.calls.lock().unwrap();+ calls.steps.push("fetch");+ calls.fetch_modes.push(request.mode);+ }+ if matches!(&self.failure, Failure::Fetch) {+ return Err(MemoryApiError::Unavailable("mock fetch failure".into()));+ }+ if matches!(&self.failure, Failure::FetchUntilCancelled) {+ if let Some(started) = self.fetch_started.lock().unwrap().take() {+ let _ = started.send(());+ }+ return std::future::pending().await;+ }+ self.inner.fetch(request).await+ }++ async fn store(&self, item: StoreItem) -> tinymemory_api::Result<StoreReceipt> {+ self.calls.lock().unwrap().steps.push("store");+ let id = ItemId::new(item.fingerprint());+ let namespace = item.meta().namespace.clone();+ let receipt = self.inner.store(item).await?;+ self.calls.lock().unwrap().stored.push((id, namespace));+ if matches!(&self.failure, Failure::StoreUntilCancelled) {+ if let Some(started) = self.store_started.lock().unwrap().take() {+ let _ = started.send(());+ }+ return std::future::pending().await;+ }+ if let Failure::StoreAfterAccept(error) = &self.failure {+ return Err(error.clone());+ }+ Ok(receipt)+ }++ async fn forget(&self, target: ForgetTarget) -> tinymemory_api::Result<ForgetReport> {+ self.calls.lock().unwrap().unscoped_forgets += 1;+ self.inner.forget(target).await+ }++ async fn forget_within(+ &self,+ ids: Vec<ItemId>,+ reach: Reach,+ ) -> tinymemory_api::Result<ForgetReport> {+ {+ let mut calls = self.calls.lock().unwrap();+ calls.steps.push("forget_within");+ calls.scoped_forgets.push((ids.clone(), reach.clone()));+ }+ let result = self.inner.forget_within(ids, reach).await;+ if let Some(finished) = self.cleanup_finished.lock().unwrap().take() {+ let _ = finished.send(());+ }+ result+ }++ async fn list(&self, request: ListRequest) -> tinymemory_api::Result<ListPage> {+ self.inner.list(request).await+ }+}++fn config_in(tmp: &TempDir) -> Config {+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace directory");+ Config {+ workspace_dir: workspace.clone(),+ action_dir: workspace,+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ }+}++async fn seed_real_memory(engine: &ProbeEngine) -> ItemId {+ let item = StoreItem::document("existing user memory", MemoryMeta::default());+ let id = ItemId::new(item.fingerprint());+ engine+ .inner+ .store(item)+ .await+ .expect("seed existing memory");+ id+}++async fn run_check(+ engine: &Arc<ProbeEngine>,+ tmp: &TempDir,+) -> Vec<crate::doctor::contract::Finding> {+ run_check_with_config(engine, config_in(tmp)).await+}++async fn run_check_with_config(+ engine: &Arc<ProbeEngine>,+ mut config: Config,+) -> Vec<crate::doctor::contract::Finding> {+ config.memory.engine = crate::memory::engine::TINYHUMANS_ENGINE.to_owned();+ let extensions = Extensions::new();+ let engine_for_factory: Arc<dyn MemoryEngine> = engine.clone();+ crate::memory::engine_registry::register_read_only_engine_factory_in(+ &extensions,+ crate::memory::engine::TINYHUMANS_ENGINE,+ Arc::new(move |_selected| {+ let engine = Arc::clone(&engine_for_factory);+ Box::pin(async move { Ok(engine) })+ }),+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ CoreContext::scope(context, async {+ MemoryRoundtripCheck+ .detect(&DoctorCtx::from_config(config))+ .await+ })+ .await+}++async fn assert_scratch_namespaces_are_empty(engine: &ProbeEngine, namespaces: &[Namespace]) {+ for namespace in namespaces {+ let items = stored(+ &engine.inner,+ MetaFilter {+ reach: Some(Reach::subtree(namespace.clone())),+ ..MetaFilter::default()+ },+ )+ .await;+ assert!(items.is_empty(), "scratch item remained in {namespace}");+ }+}++fn only_error(findings: &[crate::doctor::contract::Finding]) -> &crate::doctor::contract::Finding {+ findings+ .iter()+ .find(|finding| finding.severity == FindingSeverity::Error)+ .expect("the live memory failure is reported as an error")+}++#[tokio::test]+async fn fetch_failure_still_cleans_the_unique_service_scoped_item() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let config = config_in(&tmp);+ let engine = Arc::new(ProbeEngine::new(Failure::Fetch));+ let real_id = seed_real_memory(&engine).await;+ let findings = run_check_with_config(&engine, config).await;++ assert!(only_error(&findings).message.contains("fetch"));+ let namespaces = {+ let calls = engine.calls.lock().unwrap();+ assert_eq!(calls.steps, ["store", "fetch", "forget_within"]);+ assert_eq!(+ calls.unscoped_forgets, 0,+ "cleanup is confined to the probe scope"+ );+ assert_eq!(calls.stored.len(), 1);+ let (scratch_id, namespace) = &calls.stored[0];+ assert_ne!(scratch_id, &real_id);+ assert_ne!(scratch_id.as_str(), "doctor:probe");+ assert!(namespace+ .to_string()+ .starts_with("service:openhuman-doctor-"));+ assert!(!Reach::subtree(Namespace::ROOT).admits(namespace));+ assert_eq!(calls.scoped_forgets.len(), 1);+ assert_eq!(calls.scoped_forgets[0].0, vec![scratch_id.clone()]);+ assert_eq!(calls.scoped_forgets[0].1, Reach::exact(namespace.clone()));+ calls+ .stored+ .iter()+ .map(|(_, namespace)| namespace.clone())+ .collect::<Vec<_>>()+ };++ assert_scratch_namespaces_are_empty(&engine, &namespaces).await;+ let remaining = stored(&engine.inner, MetaFilter::default()).await;+ assert_eq!(+ remaining.len(),+ 1,+ "only the pre-existing user memory remains"+ );+ assert_eq!(remaining[0].id, real_id);+}++#[tokio::test]+async fn ambiguous_store_failure_attempts_scoped_cleanup_and_reports_a_billing_hint() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let config = config_in(&tmp);+ let engine = Arc::new(ProbeEngine::new(Failure::StoreAfterAccept(+ MemoryApiError::Engine(+ "[USER_INSUFFICIENT_CREDITS] mock account has insufficient credits (HTTP 402)".into(),+ ),+ )));+ let real_id = seed_real_memory(&engine).await;+ let findings = run_check_with_config(&engine, config).await;++ let finding = only_error(&findings);+ assert!(+ finding.fix_hint.to_ascii_lowercase().contains("credit")+ || finding.fix_hint.to_ascii_lowercase().contains("billing"),+ "insufficient credits needs an actionable billing hint: {}",+ finding.fix_hint+ );+ let namespaces = {+ let calls = engine.calls.lock().unwrap();+ assert_eq!(calls.steps, ["store", "forget_within"]);+ assert_eq!(calls.unscoped_forgets, 0);+ assert_eq!(calls.scoped_forgets.len(), 1);+ assert_eq!(calls.scoped_forgets[0].0, vec![calls.stored[0].0.clone()]);+ calls+ .stored+ .iter()+ .map(|(_, namespace)| namespace.clone())+ .collect::<Vec<_>>()+ };++ assert_scratch_namespaces_are_empty(&engine, &namespaces).await;+ let remaining = stored(&engine.inner, MetaFilter::default()).await;+ assert_eq!(+ remaining.len(),+ 1,+ "cleanup removes a possibly accepted write"+ );+ assert_eq!(remaining[0].id, real_id);+}++#[test]+fn plan_required_memory_failure_has_safe_plan_guidance_and_cleanup_warning() {+ let finding = failure_finding(+ MemoryApiError::Engine(+ "[MEMORY_PLAN_REQUIRED] memory API private-host.example: diagnostic details".into(),+ ),+ Operation::Store,+ false,+ );++ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding+ .message+ .contains("not included in the selected account's plan"));+ assert!(!finding.message.contains("MEMORY_PLAN_REQUIRED"));+ assert!(!finding.message.contains("private-host.example"));+ assert!(finding+ .fix_hint+ .contains("Upgrade to a plan that includes memory"));+ assert!(finding+ .fix_hint+ .contains("could not confirm scratch cleanup"));+}++#[tokio::test]+async fn unauthorized_and_unavailable_errors_have_safe_recovery_hints() {+ let cases = [+ (+ MemoryApiError::Unauthorized("secret token must not be echoed".into()),+ ["sign in", "auth", "credential"],+ ),+ (+ MemoryApiError::Unavailable("private endpoint detail must not be echoed".into()),+ ["retry", "available", "service"],+ ),+ ];++ for (error, hint_words) in cases {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let engine = Arc::new(ProbeEngine::new(Failure::StoreAfterAccept(error)));+ let findings = run_check(&engine, &tmp).await;+ let finding = only_error(&findings);+ let hint = finding.fix_hint.to_ascii_lowercase();+ assert!(+ hint_words.iter().any(|word| hint.contains(word)),+ "error needs a safe, relevant recovery hint: {}",+ finding.fix_hint+ );+ assert!(!finding.message.contains("secret token"));+ assert!(!finding.message.contains("private endpoint"));+ assert!(!finding.fix_hint.contains("secret token"));+ assert!(!finding.fix_hint.contains("private endpoint"));+ assert_eq!(engine.calls.lock().unwrap().unscoped_forgets, 0);+ }+}++#[tokio::test]+async fn each_successful_probe_uses_a_fresh_service_namespace_and_preserves_user_memory() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let config = config_in(&tmp);+ let engine = Arc::new(ProbeEngine::new(Failure::None));+ let real_id = seed_real_memory(&engine).await;++ for _ in 0..2 {+ let findings = run_check_with_config(&engine, config.clone()).await;+ assert!(+ findings+ .iter()+ .all(|finding| finding.severity != FindingSeverity::Error),+ "a successful store/fetch/forget roundtrip passes"+ );+ }++ let namespaces = {+ let calls = engine.calls.lock().unwrap();+ assert_eq!(+ calls.steps,+ [+ "store",+ "fetch",+ "forget_within",+ "store",+ "fetch",+ "forget_within"+ ]+ );+ assert_eq!(calls.fetch_modes, [FetchMode::Hybrid, FetchMode::Hybrid]);+ assert_eq!(calls.stored.len(), 2);+ assert_ne!(+ calls.stored[0].0, calls.stored[1].0,+ "probe IDs are unique per run"+ );+ assert_ne!(+ calls.stored[0].1, calls.stored[1].1,+ "probe namespaces are unique per run"+ );+ assert!(calls.stored.iter().all(|(_, namespace)| {+ namespace+ .to_string()+ .starts_with("service:openhuman-doctor-")+ && !Reach::subtree(Namespace::ROOT).admits(namespace)+ }));+ assert_eq!(calls.unscoped_forgets, 0);+ assert_eq!(calls.scoped_forgets.len(), 2);+ calls+ .stored+ .iter()+ .map(|(_, namespace)| namespace.clone())+ .collect::<Vec<_>>()+ };++ assert_scratch_namespaces_are_empty(&engine, &namespaces).await;+ let remaining = stored(&engine.inner, MetaFilter::default()).await;+ assert_eq!(remaining.len(), 1, "the scratch probes are gone");+ assert_eq!(remaining[0].id, real_id, "unrelated memory is preserved");+}++#[test]+fn probe_fetch_mode_prefers_hybrid_then_falls_back_to_keyword() {+ let engine = ReferenceEngine::new();+ let mut descriptor = engine.descriptor().clone();+ descriptor.fetch_modes = vec![FetchMode::Keyword, FetchMode::Hybrid];+ assert_eq!(+ super::probe_fetch_mode(&descriptor),+ Some(FetchMode::Hybrid)+ );++ descriptor.fetch_modes = vec![FetchMode::Keyword];+ assert_eq!(+ super::probe_fetch_mode(&descriptor),+ Some(FetchMode::Keyword)+ );++ descriptor.fetch_modes = vec![FetchMode::Vector];+ assert_eq!(super::probe_fetch_mode(&descriptor), None);+}++#[tokio::test]+async fn cancelling_a_pending_fetch_keeps_scoped_cleanup_owned_by_the_guard() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let config = config_in(&tmp);+ let (probe, fetch_started, cleanup_finished) = ProbeEngine::pending_fetch();+ let engine = Arc::new(probe);+ let real_id = seed_real_memory(&engine).await;++ let engine_for_task = Arc::clone(&engine);+ let task = tokio::spawn(async move { run_check_with_config(&engine_for_task, config).await });+ fetch_started+ .await+ .expect("the scratch item was stored and fetch began");+ task.abort();+ cleanup_finished+ .await+ .expect("detached cleanup finishes after the check is cancelled");++ let namespace = {+ let calls = engine.calls.lock().unwrap();+ assert_eq!(calls.steps, ["store", "fetch", "forget_within"]);+ assert_eq!(calls.unscoped_forgets, 0);+ assert_eq!(calls.scoped_forgets.len(), 1);+ let namespace = calls.stored[0].1.clone();+ assert_eq!(calls.scoped_forgets[0].1, Reach::exact(namespace.clone()));+ namespace+ };++ assert_scratch_namespaces_are_empty(&engine, &[namespace]).await;+ let remaining = stored(&engine.inner, MetaFilter::default()).await;+ assert_eq!(remaining.len(), 1);+ assert_eq!(remaining[0].id, real_id);+}++#[tokio::test]+async fn cancelling_an_ambiguous_store_cleans_up_using_the_precomputed_id() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let config = config_in(&tmp);+ let (probe, store_started, cleanup_finished) = ProbeEngine::pending_store();+ let engine = Arc::new(probe);+ let real_id = seed_real_memory(&engine).await;++ let engine_for_task = Arc::clone(&engine);+ let task = tokio::spawn(async move { run_check_with_config(&engine_for_task, config).await });+ store_started+ .await+ .expect("the store was accepted but its response is pending");+ task.abort();+ cleanup_finished+ .await+ .expect("detached cleanup finishes after the store is cancelled");++ let namespace = {+ let calls = engine.calls.lock().unwrap();+ assert_eq!(calls.steps, ["store", "forget_within"]);+ assert_eq!(calls.unscoped_forgets, 0);+ assert_eq!(calls.scoped_forgets.len(), 1);+ assert_eq!(calls.scoped_forgets[0].0, vec![calls.stored[0].0.clone()]);+ let namespace = calls.stored[0].1.clone();+ assert_eq!(calls.scoped_forgets[0].1, Reach::exact(namespace.clone()));+ namespace+ };++ assert_scratch_namespaces_are_empty(&engine, &[namespace]).await;+ let remaining = stored(&engine.inner, MetaFilter::default()).await;+ assert_eq!(remaining.len(), 1);+ assert_eq!(remaining[0].id, real_id);+}++#[tokio::test]+async fn inspection_binding_rejects_disabled_and_unregistered_engines_without_fallback() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let mut config = config_in(&tmp);+ config.components.memory = false;+ assert!(matches!(+ crate::memory::engine::resolve_read_only_for_inspection(&config).await,+ Err(crate::memory::engine_registry::ReadOnlyEngineError::ComponentDisabled)+ ));++ config.components.memory = true;+ config.memory.engine = format!("doctor-unregistered-{}", uuid::Uuid::new_v4().simple());+ assert!(matches!(+ crate::memory::engine::resolve_read_only_for_inspection(&config).await,+ Err(crate::memory::engine_registry::ReadOnlyEngineError::UnsupportedEngine)+ ));+}++#[tokio::test]+async fn inspection_engine_factories_are_called_for_each_live_probe_without_caching() {+ let tmp = TempDir::new().expect("temporary config and workspace");+ let mut config = config_in(&tmp);+ let engine_id = format!("doctor-uncached-{}", uuid::Uuid::new_v4().simple());+ config.memory.engine = engine_id.clone();+ let calls = Arc::new(AtomicUsize::new(0));+ let factory_calls = Arc::clone(&calls);+ let factory: crate::memory::engine_registry::ReadOnlyEngineFactory = Arc::new(move |_| {+ factory_calls.fetch_add(1, Ordering::SeqCst);+ let engine: Arc<dyn MemoryEngine> = Arc::new(ReferenceEngine::new());+ Box::pin(async move { Ok(engine) })+ });+ let extensions = Extensions::new();+ crate::memory::engine_registry::register_read_only_engine_factory_in(+ &extensions,+ engine_id,+ factory,+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);++ CoreContext::scope(context, async {+ let first = crate::memory::engine::resolve_read_only_for_inspection(&config)+ .await+ .expect("first selected-config inspection bind");+ let second = crate::memory::engine::resolve_read_only_for_inspection(&config)+ .await+ .expect("second selected-config inspection bind");+ assert!(!Arc::ptr_eq(&first, &second));+ })+ .await;++ assert_eq!(calls.load(Ordering::SeqCst), 2);+}diff --git a/crates/openhuman-core/src/doctor/checks/memory_tests.rs b/crates/openhuman-core/src/doctor/checks/memory_tests.rsnew file mode 100644index 0000000000..00c9f6954d--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/memory_tests.rs@@ -0,0 +1,127 @@+use super::*;+use crate::core::runtime::ComponentSet;+use crate::core::runtime::{CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::doctor::contract::{DoctorConfigSource, DoctorCtx, FindingSeverity};+use crate::memory::engine::{Binding, EngineHealth, DISABLED_ENGINE};+use crate::memory::engine_registry::{+ register_memory_engine_in, register_memory_health_probe_in, EngineEntry, EngineFuture,+ ReadOnlyHealthProbe,+};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++fn context(engine: &str) -> DoctorCtx {+ let mut config = crate::config::Config::default();+ config.memory.engine = engine.to_owned();+ DoctorCtx::from_config_with_components(config, ComponentSet::all())+ .with_profile("selected-b", DoctorConfigSource::Profile)+}++#[tokio::test]+async fn binding_uses_only_the_selected_config() {+ let finding = BindingCheck+ .detect(&context(crate::memory::engine::CORTEXDB_ENGINE))+ .await;+ assert_eq!(finding[0].check_id, "memory/binding");+ assert_eq!(finding[0].severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn binding_reports_disabled_memory_without_resolving_an_engine() {+ let finding = BindingCheck.detect(&context(DISABLED_ENGINE)).await;+ assert_eq!(finding[0].severity, FindingSeverity::Skipped);+}++#[tokio::test]+async fn health_is_skipped_when_memory_is_intentionally_disabled() {+ let finding = HealthCheck.detect(&context(DISABLED_ENGINE)).await;+ assert_eq!(finding[0].severity, FindingSeverity::Skipped);+}++#[tokio::test]+async fn selected_health_uses_the_read_only_probe_instead_of_the_cached_engine_builder() {+ let fixture = tempfile::tempdir().expect("memory health fixture");+ let engine_id = "doctor-read-only-health-test";+ let builder_calls = Arc::new(AtomicUsize::new(0));+ let builder_calls_in_closure = Arc::clone(&builder_calls);+ let extensions = Extensions::new();+ register_memory_engine_in(+ &extensions,+ engine_id,+ EngineEntry {+ build: Arc::new(move |_| {+ builder_calls_in_closure.fetch_add(1, Ordering::SeqCst);+ Binding::Off {+ engine: Some(engine_id.to_owned()),+ endpoint: None,+ reason: "normal cached builder must not run in doctor".to_owned(),+ }+ }),+ free_background: None,+ },+ );+ let probe_calls = Arc::new(AtomicUsize::new(0));+ let probe_calls_in_closure = Arc::clone(&probe_calls);+ let probe: ReadOnlyHealthProbe = Arc::new(move |_| {+ let calls = Arc::clone(&probe_calls_in_closure);+ Box::pin(async move {+ calls.fetch_add(1, Ordering::SeqCst);+ EngineHealth::Ok+ }) as EngineFuture<EngineHealth>+ });+ register_memory_health_probe_in(&extensions, engine_id, probe);++ let core = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let mut config = crate::config::Config::default();+ config.memory.engine = engine_id.to_owned();+ config.workspace_dir = fixture.path().join("workspace");+ let context = DoctorCtx::from_config_with_components(config, ComponentSet::all());+ let findings = CoreContext::scope(core, HealthCheck.detect(&context)).await;++ assert_eq!(builder_calls.load(Ordering::SeqCst), 0);+ assert_eq!(probe_calls.load(Ordering::SeqCst), 1);+ assert_eq!(findings[0].check_id, "memory/health");+ assert_eq!(findings[0].severity, FindingSeverity::Pass);+}++#[test]+fn health_reports_a_safe_engine_down_reason() {+ let finding = findings_for_health(EngineHealth::Down("engine is down".to_owned()));+ assert_eq!(finding[0].check_id, "memory/health");+ assert_eq!(finding[0].severity, FindingSeverity::Error);+ assert_eq!(finding[0].message, "engine is down");+}++#[test]+fn health_redacts_urls_and_credential_like_reasons() {+ let finding = findings_for_health(EngineHealth::Down(+ "request to https://user:[email protected] failed".to_owned(),+ ));+ assert!(!finding[0].message.contains("secret"));+}++#[test]+fn health_withholds_bare_secrets_and_local_paths() {+ for private_reason in ["sk-live-secret-value", "/Users/private/person/data.db"] {+ let finding = findings_for_health(EngineHealth::Down(private_reason.to_owned()));+ assert!(!finding[0].message.contains(private_reason));+ assert!(finding[0].message.contains("details are withheld"));+ }+}++#[test]+fn hosted_memory_binding_requires_a_registered_host_adapter() {+ assert!(!binding_supported(+ crate::memory::engine::TINYHUMANS_ENGINE,+ false+ ));+ assert!(binding_supported(+ crate::memory::engine::TINYHUMANS_ENGINE,+ true+ ));+ assert!(binding_supported(+ crate::memory::engine::CORTEXDB_ENGINE,+ false+ ));+}diff --git a/crates/openhuman-core/src/doctor/checks/mod.rs b/crates/openhuman-core/src/doctor/checks/mod.rsnew file mode 100644index 0000000000..4642ac5a8d--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/mod.rs@@ -0,0 +1,71 @@+//! Built-in doctor checks for configuration and native domain readiness.++mod channels;+mod config_file;+mod config_provenance;+mod config_semantics;+mod embeddings;+mod embeddings_live;+mod ids;+mod inference;+pub(crate) mod inference_catalog;+mod inference_live;+mod integrations;+mod mcp;+mod memory;+mod memory_live;+mod modules;+mod registry;+mod runtime;+mod runtime_settings;+mod sandbox;+mod search;+mod secrets;+mod skills;+mod storage;+mod voice;+mod wallet;+mod workspace;++use std::sync::Arc;++use super::contract::DoctorCheck;++pub(super) use ids::canonical_segment;+pub(super) use registry::for_context;++pub(super) fn builtins() -> Vec<Arc<dyn DoctorCheck>> {+ let mut checks = config_file::checks();+ checks.push(Arc::new(config_provenance::EnvironmentOverrideCheck));+ checks.push(Arc::new(config_provenance::ConfigSourceCheck));+ checks.extend(runtime_settings::checks());+ checks.extend(workspace::checks());+ checks.extend(runtime::checks());+ checks.push(Arc::new(inference::ProviderRef));+ checks.push(Arc::new(inference::Construct));+ checks.push(Arc::new(inference::Temperature));+ checks.extend(memory::checks());+ checks.push(Arc::new(memory_live::MemoryRoundtripCheck));+ checks.extend(storage::checks());+ checks.push(Arc::new(secrets::KeyringCheck));+ checks.extend(embeddings::checks());+ checks.push(Arc::new(embeddings_live::EmbeddingsLiveCheck));+ checks.extend(config_semantics::checks());+ checks+}++#[cfg(test)]+#[path = "config_semantics_tests.rs"]+mod config_semantics_tests;++#[cfg(test)]+#[path = "inference_live_tests.rs"]+mod inference_live_tests;++#[cfg(test)]+#[path = "inference_live_budget_tests.rs"]+mod inference_live_budget_tests;++#[cfg(test)]+#[path = "mod_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/mod_tests.rs b/crates/openhuman-core/src/doctor/checks/mod_tests.rsnew file mode 100644index 0000000000..655677c6c1--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/mod_tests.rs@@ -0,0 +1,41 @@+use super::*;+use crate::doctor::contract::DoctorTier;++#[test]+fn memory_storage_and_keyring_checks_are_registered_at_their_declared_tiers() {+ let checks = builtins();+ let tier = |id: &str| {+ checks+ .iter()+ .find(|check| check.id() == id)+ .map(|check| check.tier())+ };++ assert_eq!(tier("memory/binding"), Some(DoctorTier::Static));+ assert_eq!(tier("memory/health"), Some(DoctorTier::Connect));+ assert_eq!(tier("storage/connect"), Some(DoctorTier::Connect));+ assert_eq!(tier("storage/layout"), Some(DoctorTier::Static));+ assert_eq!(tier("secrets/keyring"), Some(DoctorTier::Connect));+}++#[test]+fn v1_check_replacements_are_registered_with_their_native_ids_and_tiers() {+ let checks = builtins();+ let tier = |id: &str| {+ checks+ .iter()+ .find(|check| check.id() == id)+ .map(|check| check.tier())+ };++ for (id, expected_tier) in [+ ("config/runtime-settings", DoctorTier::Static),+ ("workspace/writable", DoctorTier::Static),+ ("workspace/layout", DoctorTier::Static),+ ("runtime/environment", DoctorTier::Static),+ ("runtime/agent-sdk", DoctorTier::Connect),+ ("embeddings/configured-model", DoctorTier::Connect),+ ] {+ assert_eq!(tier(id), Some(expected_tier), "missing or mistiered {id}");+ }+}diff --git a/crates/openhuman-core/src/doctor/checks/modules.rs b/crates/openhuman-core/src/doctor/checks/modules.rsnew file mode 100644index 0000000000..da2d51e944--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/modules.rs@@ -0,0 +1,141 @@+//! Static module lifecycle and provenance checks.++use std::sync::Arc;++use async_trait::async_trait;++use crate::modules::types::{ModuleSource, ModuleState, ModuleStatus};++use super::super::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding};+use super::canonical_segment;++pub(super) fn for_context(ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ #[cfg(feature = "modules")]+ {+ crate::modules::ops::list(ctx.config())+ .into_iter()+ .map(|status| Arc::new(ModuleStatusCheck::new(status)) as Arc<dyn DoctorCheck>)+ .collect()+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = ctx;+ Vec::new()+ }+}++struct ModuleStatusCheck {+ id: String,+ status: ModuleStatus,+}++impl ModuleStatusCheck {+ fn new(status: ModuleStatus) -> Self {+ let id = format!("modules/{}", canonical_segment(&status.id));+ Self { id, status }+ }++ fn finding(&self) -> Finding {+ let source = self+ .status+ .source+ .map(module_source)+ .unwrap_or("unavailable");+ let detail = self.status.detail.as_deref().and_then(safe_module_detail);+ match self.status.state {+ ModuleState::Available | ModuleState::Ready => {+ let message = match detail {+ Some(detail) => format!("Module source is {source}; {detail}."),+ None => format!("Module is available from the {source} source."),+ };+ Finding::pass(&self.id, message)+ }+ ModuleState::Failed | ModuleState::Unsupported => Finding::error(+ &self.id,+ match detail {+ Some(detail) => format!(+ "Module from the {source} source is {}: {detail}.",+ module_state(self.status.state)+ ),+ None => format!(+ "Module from the {source} source is {}.",+ module_state(self.status.state)+ ),+ },+ "Review the module status and restart the core after correcting its installation.",+ ),+ ModuleState::Disabled => Finding::skipped(+ &self.id,+ "Module is disabled by configuration.",+ "Enable the module's owning component to make it available.",+ ),+ ModuleState::Loading => Finding::skipped(+ &self.id,+ "Module is still loading.",+ "Rerun doctor after the module finishes loading.",+ ),+ }+ }+}++/// Reduce module loader details to messages whose contents are known safe for+/// a doctor report. Loader failures can include artifact paths, URLs, and+/// transport diagnostics, so arbitrary detail strings must never reach users.+fn safe_module_detail(detail: &str) -> Option<&'static str> {+ let normalized = detail.trim().to_ascii_lowercase();+ if normalized.contains("digest mismatch") {+ return Some("artifact digest mismatch");+ }+ match normalized.as_str() {+ "no linked factory is registered in this binary; serving the release" => {+ Some("no linked factory is registered in this binary; serving the release")+ }+ "no source-built artifact is available; serving the release" => {+ Some("no source-built artifact is available; serving the release")+ }+ _ => None,+ }+}++#[async_trait]+impl DoctorCheck for ModuleStatusCheck {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ "modules"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ vec![self.finding()]+ }+}++fn module_source(source: ModuleSource) -> &'static str {+ match source {+ ModuleSource::Release => "release",+ ModuleSource::Linked => "linked",+ ModuleSource::Source => "source",+ ModuleSource::LocalFile => "local file",+ }+}++fn module_state(state: ModuleState) -> &'static str {+ match state {+ ModuleState::Available => "available",+ ModuleState::Loading => "loading",+ ModuleState::Ready => "ready",+ ModuleState::Failed => "failed",+ ModuleState::Unsupported => "unsupported",+ ModuleState::Disabled => "disabled",+ }+}++#[cfg(all(test, feature = "modules"))]+#[path = "modules_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/modules_tests.rs b/crates/openhuman-core/src/doctor/checks/modules_tests.rsnew file mode 100644index 0000000000..1d90a273ec--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/modules_tests.rs@@ -0,0 +1,93 @@+use super::*;+use crate::doctor::contract::FindingSeverity;++fn status(state: ModuleState, detail: Option<&str>) -> ModuleStatus {+ ModuleStatus {+ id: "tinydocs".to_owned(),+ description: "fixture module".to_owned(),+ version: "1".to_owned(),+ bus_name: "ai.tinyhumans.tinydocs".to_owned(),+ state,+ source: Some(ModuleSource::Release),+ detail: detail.map(str::to_owned),+ }+}++#[test]+fn failed_module_status_reports_its_load_reason_and_source() {+ let check = ModuleStatusCheck::new(status(ModuleState::Failed, Some("digest mismatch")));++ let finding = check.finding();++ assert_eq!(check.id(), "modules/tinydocs");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("digest mismatch"));+ assert!(finding.message.contains("release"));+}++#[test]+fn failed_module_status_does_not_expose_raw_detail_urls_paths_or_credentials() {+ let raw_url =+ "https://module-user:[email protected]/tiny?token=module-query-secret";+ let raw_path = "/Users/private-user/.openhuman/modules/tiny-module";+ let raw_token = "module-error-secret-value";+ let detail = format!("download failed from {raw_url} at {raw_path}; bearer={raw_token}");+ let check = ModuleStatusCheck::new(status(ModuleState::Failed, Some(&detail)));++ let finding = check.finding();++ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("release"));+ assert!(finding.message.contains("failed"));+ for private_value in [+ raw_url,+ raw_path,+ raw_token,+ "module-password",+ "module-query-secret",+ ] {+ assert!(+ !finding.message.contains(private_value),+ "module finding must not expose {private_value:?}: {}",+ finding.message+ );+ }+}++#[test]+fn module_statuses_map_to_their_contract_severities() {+ for state in [ModuleState::Available, ModuleState::Ready] {+ assert_eq!(+ ModuleStatusCheck::new(status(state, None))+ .finding()+ .severity,+ FindingSeverity::Pass+ );+ }+ for state in [ModuleState::Failed, ModuleState::Unsupported] {+ assert_eq!(+ ModuleStatusCheck::new(status(state, None))+ .finding()+ .severity,+ FindingSeverity::Error+ );+ }+ for state in [ModuleState::Disabled, ModuleState::Loading] {+ assert_eq!(+ ModuleStatusCheck::new(status(state, None))+ .finding()+ .severity,+ FindingSeverity::Skipped+ );+ }+}++#[test]+fn module_ids_are_encoded_as_valid_check_id_segments() {+ let check = ModuleStatusCheck::new(ModuleStatus {+ id: "Tiny Module/α".to_owned(),+ ..status(ModuleState::Ready, None)+ });++ assert_eq!(check.id(), "modules/__x_i_54696e79204d6f64756c652fceb1");+}diff --git a/crates/openhuman-core/src/doctor/checks/registry.rs b/crates/openhuman-core/src/doctor/checks/registry.rsnew file mode 100644index 0000000000..52f5fbd2df--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/registry.rs@@ -0,0 +1,20 @@+//! Composes native checks from the selected doctor configuration.++use std::sync::Arc;++use super::super::contract::{DoctorCheck, DoctorCtx};++/// Constructs checks from the configuration selected for this report.+pub(in crate::doctor) fn for_context(ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ let mut checks = super::modules::for_context(ctx);+ checks.extend(super::inference_live::for_context(ctx));+ checks.extend(super::mcp::for_context(ctx));+ checks.extend(super::skills::for_context(ctx));+ checks.extend(super::sandbox::for_context(ctx));+ checks.extend(super::channels::for_context(ctx));+ checks.extend(super::integrations::for_context());+ checks.extend(super::voice::for_context());+ checks.extend(super::search::for_context(ctx));+ checks.extend(super::wallet::for_context());+ checks+}diff --git a/crates/openhuman-core/src/doctor/checks/runtime.rs b/crates/openhuman-core/src/doctor/checks/runtime.rsnew file mode 100644index 0000000000..f6a14839e1--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/runtime.rs@@ -0,0 +1,260 @@+//! Static runtime prerequisites and the bounded Claude Agent SDK version probe.++use std::ffi::OsStr;+use std::process::Stdio;+use std::sync::Arc;++use async_trait::async_trait;++use crate::doctor::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity, ValueSource};++const ENVIRONMENT_ID: &str = "runtime/environment";+const AGENT_SDK_ID: &str = "runtime/agent-sdk";++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(EnvironmentCheck), Arc::new(AgentSdkCheck)]+}++struct EnvironmentCheck;++#[async_trait]+impl DoctorCheck for EnvironmentCheck {+ fn id(&self) -> &str {+ ENVIRONMENT_ID+ }++ fn category(&self) -> &str {+ "runtime environment"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));+ let findings = environment_findings(+ std::env::var_os("PATH").as_deref(),+ std::env::var_os("SHELL").as_deref(),+ home.as_deref(),+ std::env::var_os("PATHEXT").as_deref(),+ );+ for finding in &findings {+ tracing::debug!(+ target: "doctor",+ check = ENVIRONMENT_ID,+ config_path = finding.config_path.as_deref().unwrap_or(""),+ severity = ?finding.severity,+ "runtime environment prerequisite checked"+ );+ }+ findings+ }+}++fn environment_findings(+ path: Option<&OsStr>,+ shell: Option<&OsStr>,+ home: Option<&OsStr>,+ pathext: Option<&OsStr>,+) -> Vec<Finding> {+ let mut findings = Vec::with_capacity(4);+ for command in ["git", "curl"] {+ let available = command_on_path(command, path, pathext);+ findings.push(environment_finding(+ if available {+ FindingSeverity::Pass+ } else {+ FindingSeverity::Warn+ },+ if available {+ format!("The `{command}` executable is available on PATH.")+ } else {+ format!("The `{command}` executable is not available on PATH.")+ },+ if available {+ "No action required."+ } else {+ "Install the named local prerequisite and make it available on PATH."+ },+ &format!("PATH/{command}"),+ ));+ }++ let shell_present = shell.is_some_and(|value| !value.is_empty());+ findings.push(environment_finding(+ if shell_present {+ FindingSeverity::Pass+ } else {+ FindingSeverity::Warn+ },+ if shell_present {+ "A shell is configured in the process environment."+ } else {+ "The SHELL environment variable is not configured."+ },+ if shell_present {+ "No action required."+ } else {+ "Configure the SHELL environment variable for commands that need a shell."+ },+ "SHELL",+ ));++ let home_present = home.is_some_and(|value| !value.is_empty());+ findings.push(environment_finding(+ if home_present {+ FindingSeverity::Pass+ } else {+ FindingSeverity::Error+ },+ if home_present {+ "A home directory is configured in the process environment."+ } else {+ "Neither HOME nor USERPROFILE is configured."+ },+ if home_present {+ "No action required."+ } else {+ "Set HOME or USERPROFILE to the current user's home directory."+ },+ "HOME",+ ));+ findings+}++fn environment_finding(+ severity: FindingSeverity,+ message: impl Into<String>,+ fix_hint: impl Into<String>,+ config_path: &str,+) -> Finding {+ let mut finding = Finding::new(ENVIRONMENT_ID, severity, message, fix_hint);+ finding.config_path = Some(config_path.to_owned());+ finding.value_source = Some(ValueSource::Env);+ finding+}++/// Checks command availability with filesystem metadata only. Static doctor+/// checks never execute tools or shell code.+fn command_on_path(command: &str, path: Option<&OsStr>, pathext: Option<&OsStr>) -> bool {+ let Some(path) = path else {+ return false;+ };++ #[cfg(windows)]+ let extensions = pathext+ .and_then(OsStr::to_str)+ .filter(|value| !value.is_empty())+ .unwrap_or(".COM;.EXE;.BAT;.CMD")+ .split(';')+ .filter(|extension| !extension.is_empty())+ .collect::<Vec<_>>();++ #[cfg(not(windows))]+ let _ = pathext;++ std::env::split_paths(path).any(|directory| {+ #[cfg(windows)]+ {+ let direct = directory.join(command);+ direct.is_file()+ || extensions+ .iter()+ .any(|extension| directory.join(format!("{command}{extension}")).is_file())+ }++ #[cfg(unix)]+ {+ let executable = directory.join(command);+ std::fs::metadata(executable)+ .map(|metadata| {+ metadata.is_file() && {+ use std::os::unix::fs::PermissionsExt;+ metadata.permissions().mode() & 0o111 != 0+ }+ })+ .unwrap_or(false)+ }++ #[cfg(not(any(windows, unix)))]+ {+ directory.join(command).is_file()+ }+ })+}++struct AgentSdkCheck;++#[async_trait]+impl DoctorCheck for AgentSdkCheck {+ fn id(&self) -> &str {+ AGENT_SDK_ID+ }++ fn category(&self) -> &str {+ "Claude Agent SDK"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let sdk = &ctx.config().claude_agent_sdk;+ if !sdk.enabled {+ tracing::debug!(target: "doctor", check = AGENT_SDK_ID, outcome = "disabled");+ return vec![Finding::skipped(+ self.id(),+ "Claude Agent SDK is disabled in the selected configuration.",+ "Enable Claude Agent SDK in the selected configuration to check its CLI.",+ )];+ }+ if sdk.binary.trim().is_empty() {+ return vec![agent_sdk_warning()];+ }++ tracing::debug!(target: "doctor", check = AGENT_SDK_ID, outcome = "probe_started");+ let mut command = tokio::process::Command::new(&sdk.binary);+ command+ .arg("--version")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true);+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ command.as_std_mut().creation_flags(0x0800_0000); // CREATE_NO_WINDOW+ }++ match command.status().await {+ Ok(status) if status.success() => {+ tracing::debug!(target: "doctor", check = AGENT_SDK_ID, outcome = "available");+ vec![Finding::pass(+ self.id(),+ "The configured Claude Agent SDK CLI responded to `--version`.",+ )]+ }+ _ => {+ tracing::debug!(target: "doctor", check = AGENT_SDK_ID, outcome = "unavailable");+ vec![agent_sdk_warning()]+ }+ }+ }+}++fn agent_sdk_warning() -> Finding {+ let mut finding = Finding::new(+ AGENT_SDK_ID,+ FindingSeverity::Warn,+ "The configured Claude Agent SDK CLI is unavailable or did not respond successfully to `--version`.",+ "Install Claude Agent SDK or configure `claude_agent_sdk.binary`, then rerun doctor.",+ );+ finding.config_path = Some("claude_agent_sdk.binary".to_owned());+ finding+}++#[cfg(test)]+#[path = "runtime_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/runtime_settings.rs b/crates/openhuman-core/src/doctor/checks/runtime_settings.rsnew file mode 100644index 0000000000..815d062f37--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/runtime_settings.rs@@ -0,0 +1,139 @@+//! Remaining static runtime-setting warnings from the former aggregate config check.++use std::sync::Arc;++use async_trait::async_trait;++use crate::config::Config;+use crate::doctor::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};++const CHECK_ID: &str = "config/runtime-settings";++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(RuntimeSettingsCheck)]+}++struct RuntimeSettingsCheck;++#[async_trait]+impl DoctorCheck for RuntimeSettingsCheck {+ fn id(&self) -> &str {+ CHECK_ID+ }++ fn category(&self) -> &str {+ "runtime configuration"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ tracing::debug!(target: "doctor", check = CHECK_ID, event = "inspection_started");+ let findings = runtime_settings(ctx.config());+ tracing::debug!(+ target: "doctor",+ check = CHECK_ID,+ finding_count = findings.len(),+ "runtime settings inspected"+ );+ findings+ }+}++fn runtime_settings(config: &Config) -> Vec<Finding> {+ let mut findings = Vec::new();++ if !config.reliability.fallback_providers.is_empty() {+ findings.push(warning(+ "reliability.fallback_providers",+ "The configured fallback-provider list is ignored by the current runtime.",+ "Remove `reliability.fallback_providers` or configure supported provider routes.",+ ));+ }++ for (index, route) in config.model_routes.iter().enumerate() {+ let path = format!("model_routes[{index}]");+ if route.hint.trim().is_empty() {+ findings.push(warning(+ &format!("{path}.hint"),+ "A model route has no workload hint.",+ "Set a non-empty workload hint for this model route.",+ ));+ }+ if route.model.trim().is_empty() {+ findings.push(warning(+ &format!("{path}.model"),+ "A model route has no model configured.",+ "Set a model for this route or remove the unused route.",+ ));+ }+ }++ let mut agent_names = config.agents.keys().collect::<Vec<_>>();+ agent_names.sort();+ for (index, agent_name) in agent_names.into_iter().enumerate() {+ if config.agents[agent_name].model.trim().is_empty() {+ findings.push(warning(+ &format!("agents[{index}].model"),+ "A delegated agent has no model configured.",+ "Set a model for the delegated agent at the reported index.",+ ));+ }+ }++ if config.components.channels {+ if has_configured_channel(config) {+ findings.push(pass(+ "channels_config",+ "At least one messaging channel is configured.",+ ));+ } else {+ findings.push(warning(+ "channels_config",+ "No messaging channel is configured.",+ "Configure a messaging channel in Settings if this runtime should receive messages.",+ ));+ }+ }++ findings+}++fn has_configured_channel(config: &Config) -> bool {+ let channels = &config.channels_config;+ channels.telegram.is_some()+ || channels.discord.is_some()+ || channels.slack.is_some()+ || channels.mattermost.is_some()+ || channels.webhook.is_some()+ || channels.imessage.is_some()+ || channels.matrix.is_some()+ || channels.signal.is_some()+ || channels.whatsapp.is_some()+ || channels.linq.is_some()+ || channels.email.is_some()+ || channels.irc.is_some()+ || channels.lark.is_some()+ || channels.dingtalk.is_some()+ || channels.qq.is_some()+ || channels.yuanbao.is_some()+ || channels.relay.is_some()+}++fn warning(config_path: &str, message: &str, fix_hint: &str) -> Finding {+ let mut finding = Finding::new(CHECK_ID, FindingSeverity::Warn, message, fix_hint);+ finding.config_path = Some(config_path.to_owned());+ finding+}++fn pass(config_path: &str, message: &str) -> Finding {+ let mut finding = Finding::pass(CHECK_ID, message);+ finding.config_path = Some(config_path.to_owned());+ finding+}++#[cfg(test)]+#[path = "runtime_settings_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/runtime_settings_tests.rs b/crates/openhuman-core/src/doctor/checks/runtime_settings_tests.rsnew file mode 100644index 0000000000..69449b8d90--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/runtime_settings_tests.rs@@ -0,0 +1,95 @@+use crate::doctor::{DoctorCtx, DoctorOptions, DoctorTier, FindingSeverity};++const ID: &str = "config/runtime-settings";++async fn run_check(config: crate::config::Config) -> Vec<crate::doctor::Finding> {+ crate::doctor::runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![ID.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("runtime config check is registered")+ .findings+}++#[tokio::test]+async fn former_runtime_settings_findings_keep_their_paths_without_exposing_values() {+ use crate::config::{DelegateAgentConfig, ModelRouteConfig};++ let mut config = crate::config::Config::default();+ config.reliability.fallback_providers = vec!["private-model-name".to_owned()];+ config.model_routes = vec![+ ModelRouteConfig {+ hint: "private-route-name".to_owned(),+ model: String::new(),+ },+ ModelRouteConfig {+ hint: String::new(),+ model: "private-model-name".to_owned(),+ },+ ];+ let delegate = DelegateAgentConfig {+ model: String::new(),+ system_prompt: None,+ temperature: None,+ max_depth: 3,+ };+ config+ .agents+ .insert("private-agent-name".to_owned(), delegate);++ let findings = run_check(config).await;+ let paths = findings+ .iter()+ .filter(|finding| finding.check_id == ID)+ .filter_map(|finding| finding.config_path.as_deref())+ .collect::<Vec<_>>();++ for path in [+ "reliability.fallback_providers",+ "model_routes[0].model",+ "model_routes[1].hint",+ "agents[0].model",+ ] {+ assert!(+ paths.contains(&path),+ "missing {path} finding: {findings:#?}"+ );+ }+ assert!(findings+ .iter()+ .filter(|finding| finding.check_id == ID)+ .all(|finding| finding.severity == FindingSeverity::Warn+ && !finding.fix_hint.trim().is_empty()));+ assert!(findings.iter().all(|finding| {+ !finding.message.contains("private-model-name")+ && !finding.message.contains("private-route-name")+ && !finding.message.contains("private-agent-name")+ }));+ assert!(!findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"));+}++#[tokio::test]+async fn no_channel_warning_is_emitted_only_when_channels_are_enabled() {+ let mut enabled = crate::config::Config::default();+ enabled.components.channels = true;+ let findings = run_check(enabled).await;+ assert!(findings.iter().any(|finding| {+ finding.check_id == ID+ && finding.config_path.as_deref() == Some("channels_config")+ && finding.severity == FindingSeverity::Warn+ }));++ let mut disabled = crate::config::Config::default();+ disabled.components.channels = false;+ let findings = run_check(disabled).await;+ assert!(!findings.iter().any(|finding| {+ finding.check_id == ID && finding.config_path.as_deref() == Some("channels_config")+ }));+}diff --git a/crates/openhuman-core/src/doctor/checks/runtime_tests.rs b/crates/openhuman-core/src/doctor/checks/runtime_tests.rsnew file mode 100644index 0000000000..464d97cc62--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/runtime_tests.rs@@ -0,0 +1,187 @@+use super::*;++use crate::doctor::{DoctorCheck, DoctorCtx, FindingSeverity};++#[cfg(unix)]+#[test]+fn environment_check_resolves_git_and_curl_from_path_without_running_them() {+ use std::os::unix::fs::PermissionsExt;++ let fixture = tempfile::tempdir().expect("environment fixture");+ let bin = fixture.path().join("bin");+ std::fs::create_dir(&bin).expect("create fake bin directory");+ let marker = fixture.path().join("ran");+ for name in ["git", "curl"] {+ let path = bin.join(name);+ std::fs::write(+ &path,+ format!("#!/bin/sh\nprintf x > '{}'\n", marker.display()),+ )+ .expect("write executable fixture that would leave a marker if run");+ let mut permissions = std::fs::metadata(&path)+ .expect("executable metadata")+ .permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(path, permissions).expect("mark fixture executable");+ }++ let findings = environment_findings(+ Some(bin.as_os_str()),+ Some(std::ffi::OsStr::new("/bin/sh")),+ Some(std::ffi::OsStr::new("/isolated/home")),+ None,+ );++ assert!(findings.iter().any(|finding| {+ finding.check_id == "runtime/environment"+ && finding.severity == FindingSeverity::Pass+ && finding.config_path.as_deref() == Some("PATH/git")+ }));+ assert!(findings.iter().any(|finding| {+ finding.check_id == "runtime/environment"+ && finding.severity == FindingSeverity::Pass+ && finding.config_path.as_deref() == Some("PATH/curl")+ }));+ assert!(findings+ .iter()+ .all(|finding| !finding.message.contains("/isolated/home")));+ assert!(+ !marker.exists(),+ "static environment checks must not spawn tools"+ );+}++#[test]+fn environment_check_reports_missing_prerequisites_without_echoing_values() {+ let findings = environment_findings(None, None, None, None);++ assert!(findings.iter().any(|finding| {+ finding.config_path.as_deref() == Some("PATH/git")+ && finding.severity == FindingSeverity::Warn+ }));+ assert!(findings.iter().any(|finding| {+ finding.config_path.as_deref() == Some("PATH/curl")+ && finding.severity == FindingSeverity::Warn+ }));+ assert!(findings.iter().any(|finding| {+ finding.config_path.as_deref() == Some("SHELL") && finding.severity == FindingSeverity::Warn+ }));+ assert!(findings.iter().any(|finding| {+ finding.config_path.as_deref() == Some("HOME") && finding.severity == FindingSeverity::Error+ }));+ assert!(+ findings+ .iter()+ .all(|finding| !finding.message.contains("/Users/")+ && !finding.message.contains("secret"))+ );+}++#[cfg(unix)]+fn fake_cli(root: &std::path::Path, script: &str) -> std::path::PathBuf {+ use std::os::unix::fs::PermissionsExt;++ let path = root.join("claude-agent-sdk");+ std::fs::write(&path, format!("#!/bin/sh\n{script}\n")).expect("write isolated fake CLI");+ let mut permissions = std::fs::metadata(&path)+ .expect("fake CLI metadata")+ .permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&path, permissions).expect("mark fake CLI executable");+ path+}++#[cfg(unix)]+fn sdk_context(binary: std::path::PathBuf) -> DoctorCtx {+ let mut config = crate::config::Config::default();+ config.claude_agent_sdk.enabled = true;+ config.claude_agent_sdk.binary = binary.to_string_lossy().into_owned();+ DoctorCtx::from_config(config)+}++#[cfg(unix)]+#[tokio::test]+async fn agent_sdk_probe_reports_availability_without_echoing_command_output() {+ let fixture = tempfile::tempdir().expect("SDK fixture");+ let binary = fake_cli(+ fixture.path(),+ "printf 'claude 1.2.3\\n'; printf 'private-token\\n' >&2",+ );++ let findings = AgentSdkCheck.detect(&sdk_context(binary)).await;++ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].check_id, "runtime/agent-sdk");+ assert_eq!(findings[0].severity, FindingSeverity::Pass);+ assert!(!findings[0].message.contains("private-token"));+ assert!(!findings[0].message.contains("1.2.3"));+ assert!(!findings[0].fix_hint.trim().is_empty());+}++#[cfg(unix)]+#[tokio::test]+async fn agent_sdk_probe_reports_failure_without_echoing_stderr() {+ let fixture = tempfile::tempdir().expect("SDK fixture");+ let binary = fake_cli(+ fixture.path(),+ "printf 'private-error-token\\n' >&2; exit 7",+ );++ let findings = AgentSdkCheck.detect(&sdk_context(binary)).await;++ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Warn);+ assert!(!findings[0].message.contains("private-error-token"));+ assert!(!findings[0].fix_hint.trim().is_empty());+}++#[cfg(unix)]+#[tokio::test]+async fn disabled_agent_sdk_is_skipped_without_running_its_configured_binary() {+ let fixture = tempfile::tempdir().expect("SDK fixture");+ let marker = fixture.path().join("ran");+ let binary = fake_cli(+ fixture.path(),+ &format!("printf x > '{}'", marker.display()),+ );+ let mut config = crate::config::Config::default();+ config.claude_agent_sdk.enabled = false;+ config.claude_agent_sdk.binary = binary.to_string_lossy().into_owned();++ let findings = AgentSdkCheck.detect(&DoctorCtx::from_config(config)).await;++ assert_eq!(findings[0].severity, FindingSeverity::Skipped);+ assert!(+ !marker.exists(),+ "disabled SDK check must not spawn its CLI"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn static_tier_does_not_spawn_the_connect_tier_agent_sdk_cli() {+ use crate::doctor::{DoctorOptions, DoctorTier};++ let fixture = tempfile::tempdir().expect("SDK fixture");+ let marker = fixture.path().join("ran");+ let binary = fake_cli(+ fixture.path(),+ &format!("printf x > '{}'", marker.display()),+ );+ let report = crate::doctor::runner::run(+ &sdk_context(binary),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["runtime/agent-sdk".to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("above-tier SDK check is represented as skipped");++ assert_eq!(report.checks_skipped, vec!["runtime/agent-sdk".to_owned()]);+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "runtime/agent-sdk" && finding.severity == FindingSeverity::Skipped+ }));+ assert!(!marker.exists(), "static tier must not spawn the SDK CLI");+}diff --git a/crates/openhuman-core/src/doctor/checks/sandbox.rs b/crates/openhuman-core/src/doctor/checks/sandbox.rsnew file mode 100644index 0000000000..68fcb25894--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/sandbox.rs@@ -0,0 +1,186 @@+//! Bounded probes for explicitly configured sandbox backends.++use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;++use crate::config::SandboxBackend;+use crate::doctor::contract::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};++#[async_trait]+trait SandboxProbe: Send + Sync {+ async fn docker_available(&self) -> Result<bool, ()>;+ async fn landlock_status(&self) -> LandlockStatus;+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum LandlockStatus {+ Available,+ Unsupported,+ Unavailable,+ Failed,+}++struct HostSandboxProbe;++#[async_trait]+impl SandboxProbe for HostSandboxProbe {+ async fn docker_available(&self) -> Result<bool, ()> {+ use std::process::Stdio;++ let mut command = tokio::process::Command::new("docker");+ command+ .args(["info", "--format", "{{.ServerVersion}}"])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true);+ match tokio::time::timeout(Duration::from_secs(5), command.status()).await {+ Ok(Ok(status)) => Ok(status.success()),+ Ok(Err(_)) | Err(_) => Err(()),+ }+ }++ async fn landlock_status(&self) -> LandlockStatus {+ #[cfg(all(target_os = "linux", feature = "modules"))]+ {+ use crate::modules::runtime::{call_if_ready, ExistingModuleCallError};+ use crate::modules::tinybox::contract::names::JAIL_STATUS;+ use crate::modules::tinybox::contract::JailStatus;++ return match call_if_ready::<_, JailStatus>(+ crate::modules::tinybox::MODULE_ID,+ JAIL_STATUS,+ (),+ Duration::from_secs(5),+ )+ .await+ {+ Ok(Some(status)) => landlock_status_from_module(&status),+ Ok(None) | Err(ExistingModuleCallError::Unavailable) => LandlockStatus::Unavailable,+ Err(ExistingModuleCallError::Failed) => LandlockStatus::Failed,+ };+ }+ #[cfg(all(target_os = "linux", not(feature = "modules")))]+ {+ LandlockStatus::Unavailable+ }+ #[cfg(not(target_os = "linux"))]+ {+ LandlockStatus::Unsupported+ }+ }+}++#[cfg(all(target_os = "linux", feature = "modules"))]+fn landlock_status_from_module(+ status: &crate::modules::tinybox::contract::JailStatus,+) -> LandlockStatus {+ if status.backend == "landlock" && status.available && status.suitable_for_untrusted_code {+ LandlockStatus::Available+ } else {+ LandlockStatus::Unsupported+ }+}++pub(super) fn for_context(_ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(SandboxBackendCheck {+ probe: Arc::new(HostSandboxProbe),+ })]+}++struct SandboxBackendCheck {+ probe: Arc<dyn SandboxProbe>,+}++impl SandboxBackendCheck {+ #[cfg(test)]+ fn with_probe(probe: Arc<dyn SandboxProbe>) -> Self {+ Self { probe }+ }++ async fn finding(&self, ctx: &DoctorCtx) -> Finding {+ if !ctx.config().components.sandbox || ctx.config().sandbox.enabled == Some(false) {+ return Finding::skipped(+ "sandbox/backend",+ "Sandboxing is disabled in the selected configuration.",+ "Enable sandboxing in the selected configuration to check its backend.",+ );+ }+ match &ctx.config().sandbox.backend {+ SandboxBackend::Auto => Finding::pass(+ "sandbox/backend",+ "The sandbox backend is selected automatically by the runtime.",+ ),+ SandboxBackend::None => Finding::skipped(+ "sandbox/backend",+ "No sandbox backend is configured.",+ "Select a sandbox backend to check its availability.",+ ),+ SandboxBackend::Docker => match self.probe.docker_available().await {+ Ok(true) => Finding::pass(+ "sandbox/backend",+ "The configured Docker backend is available.",+ ),+ Ok(false) | Err(()) => Finding::error(+ "sandbox/backend",+ "The configured Docker backend is unavailable.",+ "Start Docker and confirm that the current user can reach its daemon.",+ ),+ },+ SandboxBackend::Landlock => match self.probe.landlock_status().await {+ LandlockStatus::Available => Finding::pass(+ "sandbox/backend",+ "The configured Landlock backend is available.",+ ),+ LandlockStatus::Unsupported => Finding::error(+ "sandbox/backend",+ "The configured Landlock backend is unavailable on this host.",+ "Use a Linux kernel and TinyBox build with Landlock support, or select another backend.",+ ),+ LandlockStatus::Unavailable => Finding::skipped(+ "sandbox/backend",+ "TinyBox is not already available to report its native jail capability.",+ "Open the sandbox runtime, then rerun doctor to inspect its backend.",+ ),+ LandlockStatus::Failed => Finding::error(+ "sandbox/backend",+ "The existing TinyBox runtime did not return native jail status.",+ "Review the sandbox runtime and rerun doctor.",+ ),+ },+ SandboxBackend::Firejail | SandboxBackend::Bubblewrap => Finding::error(+ "sandbox/backend",+ "The configured sandbox backend is not supported by this build.",+ "Select Docker, Landlock, automatic selection, or no backend.",+ ),+ }+ }+}++#[async_trait]+impl DoctorCheck for SandboxBackendCheck {+ fn id(&self) -> &str {+ "sandbox/backend"+ }++ fn category(&self) -> &str {+ "sandbox"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Sandbox)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ vec![self.finding(ctx).await]+ }+}++#[cfg(test)]+#[path = "sandbox_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs b/crates/openhuman-core/src/doctor/checks/sandbox_tests.rsnew file mode 100644index 0000000000..9e523ed77d--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/sandbox_tests.rs@@ -0,0 +1,187 @@+use super::*;+use crate::doctor::contract::FindingSeverity;+use std::path::Path;++struct DockerAvailability(bool);++#[async_trait]+impl SandboxProbe for DockerAvailability {+ async fn docker_available(&self) -> Result<bool, ()> {+ Ok(self.0)+ }++ async fn landlock_status(&self) -> LandlockStatus {+ LandlockStatus::Unavailable+ }+}++struct LandlockAvailability(LandlockStatus);++#[async_trait]+impl SandboxProbe for LandlockAvailability {+ async fn docker_available(&self) -> Result<bool, ()> {+ Ok(false)+ }++ async fn landlock_status(&self) -> LandlockStatus {+ self.0+ }+}++fn config(root: &Path, backend: SandboxBackend) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config.sandbox.backend = backend;+ config+}++#[tokio::test]+async fn configured_docker_without_a_daemon_is_an_error() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check = SandboxBackendCheck::with_probe(Arc::new(DockerAvailability(false)));+ let finding = check+ .detect(&DoctorCtx::from_config(config(+ scratch.path(),+ SandboxBackend::Docker,+ )))+ .await+ .remove(0);++ assert_eq!(finding.check_id, "sandbox/backend");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains("Docker backend is unavailable"));+}++#[tokio::test]+async fn available_docker_backend_passes() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check = SandboxBackendCheck::with_probe(Arc::new(DockerAvailability(true)));+ let finding = check+ .detect(&DoctorCtx::from_config(config(+ scratch.path(),+ SandboxBackend::Docker,+ )))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn no_probe_runs_when_sandboxing_is_disabled_in_config() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check = SandboxBackendCheck::with_probe(Arc::new(DockerAvailability(false)));+ let mut config = config(scratch.path(), SandboxBackend::Docker);+ config.sandbox.enabled = Some(false);+ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Skipped);+ assert!(finding.message.contains("disabled"));+}++#[tokio::test]+async fn an_existing_tinybox_landlock_status_is_mapped_to_the_configured_backend() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let check =+ SandboxBackendCheck::with_probe(Arc::new(LandlockAvailability(LandlockStatus::Available)));+ let finding = check+ .detect(&DoctorCtx::from_config(config(+ scratch.path(),+ SandboxBackend::Landlock,+ )))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn unsupported_and_unavailable_landlock_statuses_are_distinguished() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let unavailable = SandboxBackendCheck::with_probe(Arc::new(LandlockAvailability(+ LandlockStatus::Unavailable,+ )))+ .detect(&DoctorCtx::from_config(config(+ scratch.path(),+ SandboxBackend::Landlock,+ )))+ .await+ .remove(0);+ assert_eq!(unavailable.severity, FindingSeverity::Skipped);++ let unsupported = SandboxBackendCheck::with_probe(Arc::new(LandlockAvailability(+ LandlockStatus::Unsupported,+ )))+ .detect(&DoctorCtx::from_config(config(+ scratch.path(),+ SandboxBackend::Landlock,+ )))+ .await+ .remove(0);+ assert_eq!(unsupported.severity, FindingSeverity::Error);+}++#[cfg(all(target_os = "linux", feature = "modules"))]+#[test]+fn landlock_requires_a_matching_backend_and_the_untrusted_code_isolation_floor() {+ use crate::modules::tinybox::contract::JailStatus;++ let available_landlock = JailStatus {+ backend: "landlock".to_owned(),+ available: true,+ isolation: "kernel".to_owned(),+ suitable_for_untrusted_code: true,+ filesystem: "enforced".to_owned(),+ network: "enforced".to_owned(),+ subprocess: "enforced".to_owned(),+ };+ assert_eq!(+ landlock_status_from_module(&available_landlock),+ LandlockStatus::Available+ );++ let available_other_backend = JailStatus {+ backend: "seatbelt".to_owned(),+ ..available_landlock.clone()+ };+ assert_eq!(+ landlock_status_from_module(&available_other_backend),+ LandlockStatus::Unsupported,+ "another available jail does not satisfy an explicit Landlock selection"+ );++ let insufficient_landlock = JailStatus {+ suitable_for_untrusted_code: false,+ ..available_landlock+ };+ assert_eq!(+ landlock_status_from_module(&insufficient_landlock),+ LandlockStatus::Unsupported+ );+}++#[cfg(all(target_os = "linux", feature = "modules"))]+#[tokio::test]+async fn missing_tinybox_status_does_not_start_the_module_runtime() {+ if crate::util::module_test_process::run(+ module_path!(),+ "missing_tinybox_status_does_not_start_the_module_runtime",+ ) {+ return;+ }+ assert!(!crate::modules::runtime::is_started());++ let status = HostSandboxProbe.landlock_status().await;++ assert_eq!(status, LandlockStatus::Unavailable);+ assert!(!crate::modules::runtime::is_started());+ assert_eq!(+ crate::modules::ops::state_of(crate::modules::tinybox::MODULE_ID),+ crate::modules::types::ModuleState::Available+ );+}diff --git a/crates/openhuman-core/src/doctor/checks/search.rs b/crates/openhuman-core/src/doctor/checks/search.rsnew file mode 100644index 0000000000..d0838fb679--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/search.rs@@ -0,0 +1,197 @@+//! Provider readiness checks over the selected search config.++use std::sync::Arc;++use async_trait::async_trait;++use crate::config::{Config, SEARCH_PROVIDERS};+use crate::doctor::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};+use crate::search::providers::{ProviderStatus, ResolvedProvider};++#[async_trait]+pub(super) trait SearchProviderResolver: Send + Sync {+ async fn resolve(&self, config: &Config) -> Vec<ResolvedProvider>;+}++struct ReadOnlyProviderResolver;++#[async_trait]+impl SearchProviderResolver for ReadOnlyProviderResolver {+ async fn resolve(&self, config: &Config) -> Vec<ResolvedProvider> {+ let effective = config+ .profile_providers+ .as_ref()+ .map(|binding| binding.effective_search(config))+ .unwrap_or_else(|| config.clone());+ let managed_available = managed_credential_available(&effective);+ crate::search::providers::resolve_with(&effective, managed_available)+ }+}++pub(super) fn for_context(ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ let config = ctx.config();+ let effective = config+ .profile_providers+ .as_ref()+ .map(|binding| binding.effective_search(config))+ .unwrap_or_else(|| config.clone());+ effective+ .search+ .providers+ .keys()+ .filter(|id| SEARCH_PROVIDERS.contains(&id.as_str()))+ .map(|provider| {+ Arc::new(SearchProviderCheck::configured(+ provider,+ Arc::new(ReadOnlyProviderResolver),+ )) as Arc<dyn DoctorCheck>+ })+ .collect()+}++pub(super) struct SearchProviderCheck {+ id: String,+ provider: String,+ resolver: Arc<dyn SearchProviderResolver>,+}++impl SearchProviderCheck {+ fn configured(provider: &str, resolver: Arc<dyn SearchProviderResolver>) -> Self {+ Self {+ id: format!("search/{provider}"),+ provider: provider.to_owned(),+ resolver,+ }+ }++ pub(super) fn new(provider: &str) -> Self {+ Self::configured(provider, Arc::new(ReadOnlyProviderResolver))+ }++ #[cfg(test)]+ pub(super) fn with_resolver(provider: &str, resolver: Arc<dyn SearchProviderResolver>) -> Self {+ Self::configured(provider, resolver)+ }++ async fn finding(&self, config: &Config) -> Finding {+ let Some(provider) = self+ .resolver+ .resolve(config)+ .await+ .into_iter()+ .find(|provider| provider.id == self.provider)+ else {+ return Finding::error(+ &self.id,+ "The selected search provider is missing from the local provider catalog.",+ "Select a provider supported by this build and rerun doctor.",+ );+ };++ match provider.status(crate::search::is_active(config)) {+ ProviderStatus::Ready => Finding::pass(+ &self.id,+ format!("The {} search provider is ready.", self.provider),+ ),+ ProviderStatus::NeedsKey => Finding::new(+ &self.id,+ FindingSeverity::Warn,+ format!(+ "The {} search provider needs a direct API key.",+ self.provider+ ),+ format!("Set {} and rerun doctor.", direct_key_path(&self.provider)),+ ),+ ProviderStatus::SignInRequired => Finding::new(+ &self.id,+ FindingSeverity::Warn,+ format!(+ "The managed {} search route needs an active backend credential.",+ self.provider+ ),+ "Sign in to the selected backend, then rerun doctor.",+ ),+ ProviderStatus::Disabled => Finding::skipped(+ &self.id,+ format!(+ "The {} search provider is disabled in the selected config.",+ self.provider+ ),+ "Enable the provider in Search settings to inspect its readiness.",+ ),+ ProviderStatus::SearchOff => Finding::skipped(+ &self.id,+ "Search is disabled in the selected config.",+ "Enable Search in Components and rerun doctor.",+ ),+ }+ }+}++#[async_trait]+impl DoctorCheck for SearchProviderCheck {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ "search"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Search)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ vec![self.finding(ctx.config()).await]+ }+}++fn direct_key_path(provider: &str) -> String {+ match provider {+ "searxng" => "searxng.base_url".into(),+ "seltz" => "seltz.api_key".into(),+ _ => format!("search.{provider}.api_key"),+ }+}++/// Resolve managed credential presence with read-only profile snapshots only.+/// This deliberately avoids `resolve_backend_credential`, which may publish a+/// session-expiry event, and never opens an auth-store writer or refreshes a+/// token.+fn managed_credential_available(config: &Config) -> bool {+ use crate::security::credentials::{+ api_key,+ session_support::{+ check_session_backend, classify_session_token, is_local_session_token,+ SessionTokenCheck,+ },+ AuthService, APP_SESSION_PROVIDER,+ };++ if api_key::get_api_key_read_only(config)+ .ok()+ .flatten()+ .is_some_and(|key| !key.trim().is_empty())+ {+ return true;+ }+ let profile = AuthService::get_profile_read_only(config, APP_SESSION_PROVIDER, None)+ .ok()+ .flatten();+ if check_session_backend(config, profile.as_ref()).is_err() {+ return false;+ }+ matches!(+ classify_session_token(profile.as_ref(), chrono::Utc::now()),+ SessionTokenCheck::Live(token) if !is_local_session_token(&token)+ )+}++#[cfg(test)]+#[path = "search_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/search_tests.rs b/crates/openhuman-core/src/doctor/checks/search_tests.rsnew file mode 100644index 0000000000..2a3bab5da5--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/search_tests.rs@@ -0,0 +1,363 @@+use super::*;+use crate::config::{+ PresentationMode, ProviderRoute, SearchEngineCredentials, SearchProviderSettings,+};+use crate::doctor::contract::{DoctorCtx, FindingSeverity};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++struct FixedManagedResolver {+ managed_available: bool,+ calls: Arc<AtomicUsize>,+}++#[async_trait::async_trait]+impl SearchProviderResolver for FixedManagedResolver {+ async fn resolve(+ &self,+ config: &crate::config::Config,+ ) -> Vec<crate::search::providers::ResolvedProvider> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ crate::search::providers::resolve_with(config, self.managed_available)+ }+}++fn config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config.search.providers.insert(+ "brave".into(),+ SearchProviderSettings {+ enabled: true,+ route: ProviderRoute::Direct,+ },+ );+ config+}++fn backend_config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = config_in(root);+ config.resolved_endpoints.control_plane_url = Some("https://backend-b.example".into());+ config.secrets.encrypt = false;+ config+}++fn write_session_profile(root: &std::path::Path, expires_at: &str, issuer: &str) {+ let now = chrono::Utc::now().to_rfc3339();+ std::fs::write(+ root.join("auth-profiles.json"),+ serde_json::json!({+ "schema_version": 1,+ "updated_at": now,+ "active_profiles": {"app-session": "app-session:default"},+ "profiles": {+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": "doctor-fake-session-token",+ "metadata": {+ "session_issuing_backend": issuer,+ "session_expires_at": expires_at+ }+ }+ }+ })+ .to_string(),+ )+ .expect("write fake session profile");+}++fn write_api_key_profile(root: &std::path::Path) {+ let now = chrono::Utc::now().to_rfc3339();+ std::fs::write(+ root.join("auth-profiles.json"),+ serde_json::json!({+ "schema_version": 1,+ "updated_at": now,+ "active_profiles": {"api-key": "api-key:default"},+ "profiles": {+ "api-key:default": {+ "provider": "api-key",+ "profile_name": "default",+ "kind": "token",+ "token": "doctor-fake-managed-api-key",+ "metadata": {"kind": "tinyhumans-api-key"}+ }+ }+ })+ .to_string(),+ )+ .expect("write fake API key profile");+}++fn drain_session_expiry(+ receiver: &mut tinybus::EventReceiver<crate::core::events::DomainEvent>,+) -> bool {+ loop {+ match receiver.try_recv() {+ Ok(crate::core::events::DomainEvent::SessionExpired { .. }) => return true,+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,+ Err(_) => return false,+ }+ }+}++#[tokio::test]+async fn needs_key_is_a_warning_with_the_provider_config_key_in_its_hint() {+ let ambient = tempfile::tempdir().expect("create ambient config fixture");+ let selected = tempfile::tempdir().expect("create selected config fixture");+ let mut config_a = config_in(ambient.path());+ config_a.search.brave.api_key = Some("doctor-fake-key-a".into());+ let config_b = config_in(selected.path());+ let resolver_calls = Arc::new(AtomicUsize::new(0));+ let check = SearchProviderCheck::with_resolver(+ "brave",+ Arc::new(FixedManagedResolver {+ managed_available: false,+ calls: Arc::clone(&resolver_calls),+ }),+ );+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let finding = crate::core::runtime::CoreContext::scope(ambient_context, async {+ check+ .detect(&DoctorCtx::from_config(config_b))+ .await+ .into_iter()+ .next()+ .expect("NeedsKey produces a finding")+ })+ .await;++ assert_eq!(finding.check_id, "search/brave");+ assert_eq!(finding.severity, FindingSeverity::Warn);+ assert!(finding.fix_hint.contains("search.brave.api_key"));+ assert!(!finding.message.contains("doctor-fake-key-a"));+ assert_eq!(resolver_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn a_selected_direct_key_makes_the_provider_ready_without_any_network_call() {+ let scratch = tempfile::tempdir().expect("create isolated config fixture");+ let mut config = config_in(scratch.path());+ config.search.brave.api_key = Some("doctor-fake-key-b".into());+ let resolver_calls = Arc::new(AtomicUsize::new(0));+ let check = SearchProviderCheck::with_resolver(+ "brave",+ Arc::new(FixedManagedResolver {+ managed_available: false,+ calls: Arc::clone(&resolver_calls),+ }),+ );++ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .into_iter()+ .next()+ .expect("ready provider produces a finding");++ assert_eq!(finding.check_id, "search/brave");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("doctor-fake-key-b"));+ assert_eq!(resolver_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn a_live_selected_b_session_enables_managed_search_without_refreshing_it() {+ let ambient = tempfile::tempdir().expect("create ambient credential fixture");+ let selected = tempfile::tempdir().expect("create selected credential fixture");+ let now = chrono::Utc::now();+ write_session_profile(+ ambient.path(),+ &(now - chrono::Duration::hours(1)).to_rfc3339(),+ "https://backend-a.example",+ );+ write_session_profile(+ selected.path(),+ &(now + chrono::Duration::hours(1)).to_rfc3339(),+ "https://backend-b.example",+ );+ let config_a = backend_config_in(ambient.path());+ let mut config_b = backend_config_in(selected.path());+ config_b+ .search+ .providers+ .insert("exa".into(), SearchProviderSettings::managed());+ let selected_profile_path = selected.path().join("auth-profiles.json");+ let selected_profile_before = std::fs::read(&selected_profile_path).unwrap();+ let ambient_profile_path = ambient.path().join("auth-profiles.json");+ let ambient_profile_before = std::fs::read(&ambient_profile_path).unwrap();+ let check = SearchProviderCheck::new("exa");+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );++ let finding = crate::core::runtime::CoreContext::scope(ambient_context, async {+ check+ .detect(&DoctorCtx::from_config(config_b.clone()))+ .await+ .into_iter()+ .next()+ .expect("live selected-B managed provider produces a finding")+ })+ .await;++ assert_eq!(finding.check_id, "search/exa");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("doctor-fake-session-token"));+ assert_eq!(+ std::fs::read(&selected_profile_path).unwrap(),+ selected_profile_before+ );+ assert_eq!(+ std::fs::read(&ambient_profile_path).unwrap(),+ ambient_profile_before+ );+ assert!(!selected.path().join("auth-profiles.lock").exists());+ assert!(!ambient.path().join("auth-profiles.lock").exists());+ assert!(!config_b.workspace_dir.exists());+}++#[tokio::test]+async fn an_expired_or_wrong_backend_session_does_not_make_managed_search_ready() {+ let scratch = tempfile::tempdir().expect("create isolated credential fixture");+ let now = chrono::Utc::now();+ let mut config = backend_config_in(scratch.path());+ config+ .search+ .providers+ .insert("exa".into(), SearchProviderSettings::managed());+ let profile_path = scratch.path().join("auth-profiles.json");+ let check = SearchProviderCheck::new("exa");+ crate::core::bus::init()+ .await+ .expect("initialize event bus to observe forbidden expiry publication");+ let mut events = crate::core::bus::BUS+ .get()+ .expect("event bus initialized")+ .receiver();+ let missing = check+ .detect(&DoctorCtx::from_config(config.clone()))+ .await+ .into_iter()+ .next()+ .expect("missing managed credential produces an advisory finding");+ assert_ne!(missing.severity, FindingSeverity::Pass);+ assert!(!missing.message.contains("doctor-fake"));++ write_session_profile(+ scratch.path(),+ &(now - chrono::Duration::hours(1)).to_rfc3339(),+ "https://backend-b.example",+ );+ let expired_before = std::fs::read(&profile_path).unwrap();+ let expired = check+ .detect(&DoctorCtx::from_config(config.clone()))+ .await+ .into_iter()+ .next()+ .expect("expired managed credential produces an advisory finding");+ assert_ne!(expired.severity, FindingSeverity::Pass);+ assert!(!expired.message.contains("doctor-fake-session-token"));+ assert!(!expired.fix_hint.trim().is_empty());+ assert_eq!(std::fs::read(&profile_path).unwrap(), expired_before);+ assert!(!scratch.path().join("auth-profiles.lock").exists());+ assert!(!config.workspace_dir.exists());+ assert!(+ !drain_session_expiry(&mut events),+ "doctor checks expiry without publishing a session-expired event"+ );++ write_session_profile(+ scratch.path(),+ &(now + chrono::Duration::hours(1)).to_rfc3339(),+ "https://backend-a.example",+ );+ let mismatch_before = std::fs::read(&profile_path).unwrap();+ let mismatched = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .into_iter()+ .next()+ .expect("wrong-backend session produces an advisory finding");+ assert_ne!(mismatched.severity, FindingSeverity::Pass);+ assert!(!mismatched.message.contains("doctor-fake-session-token"));+ assert_eq!(std::fs::read(&profile_path).unwrap(), mismatch_before);+}++#[tokio::test]+async fn a_selected_api_key_is_a_valid_managed_credential() {+ let scratch = tempfile::tempdir().expect("create isolated credential fixture");+ write_api_key_profile(scratch.path());+ let mut config = backend_config_in(scratch.path());+ config+ .search+ .providers+ .insert("exa".into(), SearchProviderSettings::managed());+ let profile_path = scratch.path().join("auth-profiles.json");+ let bytes_before = std::fs::read(&profile_path).unwrap();+ let finding = SearchProviderCheck::new("exa")+ .detect(&DoctorCtx::from_config(config.clone()))+ .await+ .into_iter()+ .next()+ .expect("selected API key enables managed search");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("doctor-fake-managed-api-key"));+ assert_eq!(std::fs::read(&profile_path).unwrap(), bytes_before);+ assert!(!scratch.path().join("auth-profiles.lock").exists());+ assert!(!config.workspace_dir.exists());+}++#[tokio::test]+async fn profile_search_binding_is_resolved_without_operator_session_credentials() {+ let scratch = tempfile::tempdir().expect("create isolated profile fixture");+ let mut config = backend_config_in(scratch.path());+ config+ .search+ .providers+ .insert("exa".into(), SearchProviderSettings::managed());+ let mut saas = crate::core::runtime::SaasConfig::new(scratch.path());+ let mut search = crate::config::SearchConfig::default();+ search.presentation = PresentationMode::Roles;+ search.providers = std::collections::BTreeMap::from([+ ("exa".into(), SearchProviderSettings::direct()),+ ("gemini".into(), SearchProviderSettings::direct()),+ ]);+ search.roles = std::collections::BTreeMap::from([+ ("search".into(), vec!["exa".into(), "gemini".into()]),+ ("answer".into(), vec!["gemini".into()]),+ ("contents".into(), vec!["exa".into()]),+ ]);+ search.exa = SearchEngineCredentials {+ api_key: Some("doctor-profile-exa-key".into()),+ base_url: Some("http://127.0.0.1:1234".into()),+ };+ search.gemini = SearchEngineCredentials {+ api_key: Some("doctor-profile-gemini-key".into()),+ base_url: Some("http://127.0.0.1:2345".into()),+ };+ saas.search = Some(search);+ crate::profiles::provider_settings::ProfileProviderSettings::from_saas(&saas)+ .expect("valid direct profile binding")+ .bind(&mut config);+ let finding = SearchProviderCheck::new("exa")+ .detect(&DoctorCtx::from_config(config.clone()))+ .await+ .into_iter()+ .next()+ .expect("selected profile binding supplies the Exa direct key");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("doctor-profile-exa-key"));+ assert!(!finding.message.contains("doctor-profile-gemini-key"));+ assert!(!config.workspace_dir.exists());+}diff --git a/crates/openhuman-core/src/doctor/checks/secrets.rs b/crates/openhuman-core/src/doctor/checks/secrets.rsnew file mode 100644index 0000000000..1285b5313c--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/secrets.rs@@ -0,0 +1,79 @@+//! Safe diagnostics for the configured secret backend.++use async_trait::async_trait;++use crate::doctor::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding};++pub(super) struct KeyringCheck;++#[async_trait]+impl DoctorCheck for KeyringCheck {+ fn id(&self) -> &str {+ "secrets/keyring"+ }++ fn category(&self) -> &str {+ "secrets"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn is_blocking(&self) -> bool {+ true+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ self.detect_blocking(_ctx).unwrap_or_default()+ }++ fn detect_blocking(&self, _ctx: &DoctorCtx) -> Option<Vec<Finding>> {+ use std::io::IsTerminal;++ let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();+ let finding = keyring_with_probe(cfg!(target_os = "macos"), interactive, || {+ (+ crate::security::secret_storage::ops::backend_name(),+ crate::security::secret_storage::ops::is_available(),+ )+ });+ Some(vec![finding])+ }+}++fn keyring_with_probe(+ is_macos: bool,+ interactive: bool,+ probe: impl FnOnce() -> (String, bool),+) -> Finding {+ if !interactive {+ let message = if is_macos {+ "The macOS keyring probe was skipped because this session is non-interactive."+ } else {+ "The keyring probe was skipped because this session is non-interactive."+ };+ return Finding::skipped(+ "secrets/keyring",+ message,+ "Rerun doctor in an interactive terminal to check keyring availability.",+ );+ }+ let (backend, available) = probe();+ if available {+ Finding::pass(+ "secrets/keyring",+ format!("The configured {backend} secret backend is available."),+ )+ } else {+ Finding::error(+ "secrets/keyring",+ format!("The configured {backend} secret backend is unavailable."),+ "Check the selected secret backend and its access permissions.",+ )+ }+}++#[cfg(test)]+#[path = "secrets_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/secrets_tests.rs b/crates/openhuman-core/src/doctor/checks/secrets_tests.rsnew file mode 100644index 0000000000..d9cd847779--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/secrets_tests.rs@@ -0,0 +1,39 @@+//! Regression tests for keyring checks and their non-interactive probe gate.++use super::keyring_with_probe;+use crate::doctor::FindingSeverity;++#[test]+fn noninteractive_macos_keyring_check_skips_before_calling_the_probe() {+ let mut called = false;++ let finding = keyring_with_probe(true, false, || {+ called = true;+ ("host-keyring".to_owned(), true)+ });++ assert!(+ !called,+ "the OS keyring probe can display an interactive prompt"+ );+ assert_eq!(finding.check_id, "secrets/keyring");+ assert_eq!(finding.severity, FindingSeverity::Skipped);+}++#[test]+fn noninteractive_other_platforms_also_avoid_unclassified_keyring_probes() {+ let mut called = false;+ let finding = keyring_with_probe(false, false, || {+ called = true;+ ("os-keyring".to_owned(), true)+ });+ assert!(!called);+ assert_eq!(finding.severity, FindingSeverity::Skipped);+}++#[test]+fn interactive_keyring_check_reports_backend_and_availability() {+ let finding = keyring_with_probe(true, true, || ("encrypted_file".to_owned(), true));+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(finding.message.contains("encrypted_file"));+}diff --git a/crates/openhuman-core/src/doctor/checks/skills.rs b/crates/openhuman-core/src/doctor/checks/skills.rsnew file mode 100644index 0000000000..d80dd429f5--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/skills.rs@@ -0,0 +1,411 @@+//! Read-only discovery diagnostics and opt-in GitHub preflight checks.++#[cfg(feature = "skills")]+use std::path::PathBuf;+use std::sync::Arc;++use async_trait::async_trait;++use crate::doctor::contract::{ComponentId, DoctorCheck, DoctorCtx, DoctorTier, Finding};++pub(super) fn for_context(ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ #[cfg(feature = "skills")]+ let mut checks: Vec<Arc<dyn DoctorCheck>> = vec![Arc::new(SkillDiscoveryCheck)];+ #[cfg(not(feature = "skills"))]+ let checks: Vec<Arc<dyn DoctorCheck>> = vec![Arc::new(SkillDiscoveryCheck)];+ #[cfg(feature = "skills")]+ if let Some(required) = required_github_preflight(ctx.config()) {+ checks.push(Arc::new(GithubPreflightCheck {+ required: required.config,+ manifest_path: required.path,+ #[cfg(test)]+ probes: None,+ }));+ }+ #[cfg(not(feature = "skills"))]+ let _ = ctx;+ checks+}++struct SkillDiscoveryCheck;++#[async_trait]+impl DoctorCheck for SkillDiscoveryCheck {+ fn id(&self) -> &str {+ "skills/discovery"+ }++ fn category(&self) -> &str {+ "skills"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Skills)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ if !ctx.config().components.skills {+ return vec![Finding::skipped(+ self.id(),+ "Skills are disabled in the selected configuration.",+ "Enable skills in the selected configuration to inspect manifests.",+ )];+ }+ #[cfg(feature = "skills")]+ {+ let home = crate::skills::ops_discover::discovery_home_dir();+ let trusted =+ crate::skills::ops_discover::is_workspace_trusted(&ctx.config().workspace_dir);+ return crate::skills::ops_discover::discover_workflows(+ home.as_deref(),+ Some(&ctx.config().workspace_dir),+ trusted,+ )+ .into_iter()+ .filter(|skill| !skill.warnings.is_empty())+ .map(|skill| {+ let mut finding = Finding::new(+ self.id(),+ crate::doctor::FindingSeverity::Warn,+ "A discovered skill manifest has validation warnings.",+ "Review the skill manifest and rerun doctor.",+ );+ finding.config_path = skill+ .location+ .map(|path| path.to_string_lossy().into_owned());+ finding+ })+ .collect();+ }+ #[cfg(not(feature = "skills"))]+ {+ let _ = ctx;+ vec![Finding::skipped(+ self.id(),+ "Skill discovery is disabled in this build.",+ "Use a build with skills support to inspect skill manifests.",+ )]+ }+ }+}++#[cfg(feature = "skills")]+struct RequiredGithubPreflight {+ config: crate::skills::registry::WorkflowGithubConfig,+ path: PathBuf,+}++/// Finds a required GitHub gate using the same read-only discovery roots as+/// skills. This deliberately avoids `load_workflows`, which prunes legacy+/// bundles as part of its normal run-path preparation.+#[cfg(feature = "skills")]+fn required_github_preflight(config: &crate::config::Config) -> Option<RequiredGithubPreflight> {+ use crate::skills::registry::{IdentityMatch, WorkflowDefinition};++ let home = crate::skills::ops_discover::discovery_home_dir();+ let trusted = crate::skills::ops_discover::is_workspace_trusted(&config.workspace_dir);+ let discovered = crate::skills::ops_discover::discover_workflows(+ home.as_deref(),+ Some(&config.workspace_dir),+ trusted,+ );+ let mut required = Vec::new();+ for skill in discovered {+ let Some(document) = skill.location else {+ continue;+ };+ let Some(dir) = document.parent() else {+ continue;+ };+ let manifest = ["workflow.toml", "skill.toml"]+ .into_iter()+ .map(|name| dir.join(name))+ .find(|path| path.is_file());+ let Some(manifest) = manifest else {+ continue;+ };+ let Ok(text) = tinyskills::read_document(&manifest) else {+ continue;+ };+ let Ok(definition) = toml::from_str::<WorkflowDefinition>(&text) else {+ continue;+ };+ let Some(github) = definition.github.filter(|github| github.required) else {+ continue;+ };+ required.push(RequiredGithubPreflight {+ config: github,+ path: manifest,+ });+ }++ required.sort_by(|left, right| left.path.cmp(&right.path));+ // A single readiness check covers the shared local Git and GitHub+ // integration. Honor the most demanding declared identity policy.+ required+ .into_iter()+ .max_by_key(|entry| match entry.config.identity_match {+ IdentityMatch::None => 0,+ IdentityMatch::Any => 1,+ IdentityMatch::Strict => 2,+ })+}++#[cfg(feature = "skills")]+struct GithubPreflightCheck {+ required: crate::skills::registry::WorkflowGithubConfig,+ manifest_path: PathBuf,+ #[cfg(test)]+ probes: Option<Arc<dyn crate::skills::preflight::PreflightProbes>>,+}++#[cfg(feature = "skills")]+#[async_trait]+impl DoctorCheck for GithubPreflightCheck {+ fn id(&self) -> &str {+ "skills/github-preflight"+ }++ fn category(&self) -> &str {+ "skills"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Skills)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ if !ctx.config().components.skills {+ let mut finding = Finding::skipped(+ self.id(),+ "Skills are disabled in the selected configuration.",+ "Enable skills in the selected configuration to run GitHub preflight.",+ );+ finding.config_path = Some(self.manifest_path.to_string_lossy().into_owned());+ return vec![finding];+ }+ #[cfg(test)]+ let result = if let Some(probes) = &self.probes {+ crate::skills::preflight::run_github_preflight(Some(&self.required), probes.as_ref())+ .await+ } else {+ let probes = ExistingConnectorPreflightProbes {+ config: ctx.config(),+ };+ crate::skills::preflight::run_github_preflight(Some(&self.required), &probes).await+ };+ #[cfg(not(test))]+ let result = {+ let probes = ExistingConnectorPreflightProbes {+ config: ctx.config(),+ };+ crate::skills::preflight::run_github_preflight(Some(&self.required), &probes).await+ };++ let mut finding = match result {+ Ok(()) => Finding::pass(self.id(), "The required GitHub skill preflight is ready."),+ Err(crate::skills::preflight::GithubGateError::ComposioProbeUnavailable) => {+ Finding::skipped(+ self.id(),+ "The selected connector is unavailable for read-only inspection.",+ "Open the selected Composio connection in Connections, then rerun doctor.",+ )+ }+ Err(error) => Finding::error(+ self.id(),+ github_error_message(&error),+ "Review the GitHub connection and local Git setup, then rerun doctor.",+ ),+ };+ finding.config_path = Some(self.manifest_path.to_string_lossy().into_owned());+ vec![finding]+ }+}++#[cfg(feature = "skills")]+struct ExistingConnectorPreflightProbes<'a> {+ config: &'a crate::config::Config,+}++#[cfg(feature = "skills")]+#[async_trait]+impl crate::skills::preflight::PreflightProbes for ExistingConnectorPreflightProbes<'_> {+ async fn composio_toolkit_active(&self, _toolkit: &str) -> bool {+ false+ }++ async fn composio_identity(&self, _toolkit: &str) -> Option<String> {+ None+ }++ async fn composio_toolkit_status(+ &self,+ toolkit: &str,+ ) -> crate::skills::preflight::PreflightProbeStatus<bool> {+ existing_toolkit_status(self.config, toolkit).await+ }++ async fn composio_identity_status(+ &self,+ toolkit: &str,+ ) -> crate::skills::preflight::PreflightProbeStatus<Option<String>> {+ existing_identity_status(self.config, toolkit).await+ }++ async fn git_version(&self) -> Result<(), String> {+ crate::skills::preflight::LivePreflightProbes::new(self.config)+ .git_version()+ .await+ }++ async fn git_user_name(&self) -> String {+ crate::skills::preflight::LivePreflightProbes::new(self.config)+ .git_user_name()+ .await+ }++ async fn git_user_email(&self) -> String {+ crate::skills::preflight::LivePreflightProbes::new(self.config)+ .git_user_email()+ .await+ }+}++#[cfg(feature = "skills")]+async fn existing_toolkit_status(+ config: &crate::config::Config,+ toolkit: &str,+) -> crate::skills::preflight::PreflightProbeStatus<bool> {+ use crate::skills::preflight::PreflightProbeStatus;+ #[cfg(feature = "modules")]+ {+ use tinyconnectors_bus::{+ ComposioConnectedIntegrationsMode as Mode, ComposioConnectedIntegrationsResponse,+ ComposioListConnectedIntegrationsRequest,+ };++ let mode = if config.composio.host_credential.is_some() {+ Mode::Direct+ } else {+ match config.composio.mode.trim() {+ "" | crate::config::schema::COMPOSIO_MODE_BACKEND => Mode::Backend,+ crate::config::schema::COMPOSIO_MODE_DIRECT => Mode::Direct,+ _ => return PreflightProbeStatus::Unavailable,+ }+ };+ match crate::modules::connectors::call_existing_readonly::<+ _,+ ComposioConnectedIntegrationsResponse,+ >(+ config,+ crate::modules::connectors::methods::LIST_CONNECTED_INTEGRATIONS,+ ComposioListConnectedIntegrationsRequest { mode },+ )+ .await+ {+ Ok(Some(response)) => {+ PreflightProbeStatus::Available(response.integrations.iter().any(|integration| {+ integration.connected && integration.toolkit.eq_ignore_ascii_case(toolkit)+ }))+ }+ Ok(None) => PreflightProbeStatus::Unavailable,+ Err(crate::modules::connectors::ExistingCallError::Unavailable) => {+ PreflightProbeStatus::Unavailable+ }+ Err(crate::modules::connectors::ExistingCallError::Failed) => {+ PreflightProbeStatus::Failed+ }+ }+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = (config, toolkit);+ PreflightProbeStatus::Unavailable+ }+}++#[cfg(feature = "skills")]+async fn existing_identity_status(+ config: &crate::config::Config,+ toolkit: &str,+) -> crate::skills::preflight::PreflightProbeStatus<Option<String>> {+ use crate::skills::preflight::PreflightProbeStatus;+ #[cfg(feature = "modules")]+ {+ use crate::integrations::composio::types::{+ ComposioUserProfile, ComposioUserProfileRequest,+ };++ match crate::modules::connectors::call_existing_readonly::<_, ComposioUserProfile>(+ config,+ crate::modules::connectors::methods::GET_USER_PROFILE,+ ComposioUserProfileRequest {+ toolkit: toolkit.to_ascii_lowercase(),+ connection_id: None,+ },+ )+ .await+ {+ Ok(Some(profile)) => {+ let identity = profile+ .username+ .as_deref()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .map(str::to_owned);+ PreflightProbeStatus::Available(identity)+ }+ Ok(None) | Err(crate::modules::connectors::ExistingCallError::Unavailable) => {+ PreflightProbeStatus::Unavailable+ }+ Err(crate::modules::connectors::ExistingCallError::Failed) => {+ PreflightProbeStatus::Failed+ }+ }+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = (config, toolkit);+ PreflightProbeStatus::Unavailable+ }+}++#[cfg(feature = "skills")]+fn github_error_message(error: &crate::skills::preflight::GithubGateError) -> String {+ use crate::skills::preflight::GithubGateError;++ match error {+ GithubGateError::ComposioGithubMissing => {+ "The required GitHub integration is not connected.".to_owned()+ }+ GithubGateError::ComposioProbeUnavailable => {+ "The selected connector is not already available for read-only inspection.".to_owned()+ }+ GithubGateError::ComposioProbeFailed => {+ "The existing connector could not return GitHub connection status.".to_owned()+ }+ GithubGateError::GitBinaryMissing(_) => "Git is not available.".to_owned(),+ GithubGateError::GitUserNameMissing => "Local Git user.name is not configured.".to_owned(),+ GithubGateError::GitUserEmailMissing => {+ "Local Git user.email is not configured.".to_owned()+ }+ GithubGateError::IdentityMismatch { .. } => {+ "The connected GitHub identity does not match local Git identity.".to_owned()+ }+ GithubGateError::ComposioIdentityUnresolved => {+ "The connected GitHub identity could not be verified.".to_owned()+ }+ }+}++#[cfg(all(test, feature = "skills", feature = "modules"))]+#[path = "skills_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/skills_tests.rs b/crates/openhuman-core/src/doctor/checks/skills_tests.rsnew file mode 100644index 0000000000..765a559145--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/skills_tests.rs@@ -0,0 +1,287 @@+use super::*;+use crate::core::runtime::{CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::doctor::contract::FindingSeverity;+use crate::skills::preflight::PreflightProbes;+use std::path::Path;++fn config_in(root: &Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config+}++fn scoped(config: crate::config::Config) -> Arc<CoreContext> {+ CoreContext::for_test_with_extensions(DomainSet::full(), None, Extensions::new()).derive_with(+ crate::core::runtime::ContextOverlay::new(config, DomainSet::full(), Default::default())+ .without_user_skill_roots(),+ )+}++#[tokio::test]+async fn github_preflight_is_not_registered_when_no_skill_requires_it() {+ let scratch = tempfile::tempdir().expect("create isolated skill fixture");+ let config = config_in(scratch.path());+ let skill_dir = config.workspace_dir.join("skills/plain-skill");+ std::fs::create_dir_all(&skill_dir).expect("create skill directory");+ std::fs::write(skill_dir.join("SKILL.md"), "A plain skill.\n").expect("write skill document");++ let context = scoped(config.clone());+ let checks = CoreContext::scope(context, async {+ for_context(&DoctorCtx::from_config(config.clone()))+ })+ .await;++ assert!(checks.iter().any(|check| check.id() == "skills/discovery"));+ assert!(checks+ .iter()+ .all(|check| check.id() != "skills/github-preflight"));+}++#[derive(Default)]+struct MissingGithubProbe;++#[async_trait]+impl PreflightProbes for MissingGithubProbe {+ async fn composio_toolkit_active(&self, _toolkit: &str) -> bool {+ false+ }++ async fn composio_identity(&self, _toolkit: &str) -> Option<String> {+ None+ }++ async fn git_version(&self) -> Result<(), String> {+ Ok(())+ }++ async fn git_user_name(&self) -> String {+ "private local name".to_owned()+ }++ async fn git_user_email(&self) -> String {+ "[email protected]".to_owned()+ }+}++#[tokio::test]+async fn required_github_preflight_uses_fake_probes_and_redacts_error_details() {+ let scratch = tempfile::tempdir().expect("create isolated skill fixture");+ let config = config_in(scratch.path());+ let skill_dir = config.workspace_dir.join("skills/required-skill");+ std::fs::create_dir_all(&skill_dir).expect("create skill directory");+ std::fs::write(skill_dir.join("WORKFLOW.md"), "A workflow.\n")+ .expect("write workflow document");+ let manifest = skill_dir.join("workflow.toml");+ std::fs::write(+ &manifest,+ "id = \"required-skill\"\nwhen_to_use = \"Use the GitHub API\"\n\+ [github]\nrequired = true\nidentity_match = \"strict\"\n",+ )+ .expect("write GitHub gate config");++ let context = scoped(config.clone());+ let (required, checks) = CoreContext::scope(context, async {+ (+ required_github_preflight(&config),+ for_context(&DoctorCtx::from_config(config.clone())),+ )+ })+ .await;+ let required = required.expect("the workflow explicitly requires GitHub");+ assert_eq!(required.path, manifest);+ assert!(checks+ .iter()+ .any(|check| check.id() == "skills/github-preflight"));++ let check = GithubPreflightCheck {+ required: required.config,+ manifest_path: required.path,+ probes: Some(Arc::new(MissingGithubProbe)),+ };+ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding+ .message+ .contains("GitHub integration is not connected"));+ assert!(!finding.message.contains("private"));+ assert!(!finding.message.contains("example.test"));+ assert_eq!(+ finding.config_path.as_deref(),+ Some(manifest.to_string_lossy().as_ref())+ );+}++#[tokio::test]+async fn production_github_preflight_skips_expired_profile_without_mutating_credentials_or_loading_connectors(+) {+ let scratch = tempfile::tempdir().expect("create isolated preflight fixture");+ let config = config_in(scratch.path());+ let _env = crate::config::test_env::EnvVarGuard::locked_async()+ .await+ .with("HOME", scratch.path())+ .with("OPENHUMAN_WORKSPACE", config.workspace_dir.as_os_str())+ .without("OPENHUMAN_ACTION_DIR")+ .without("COMPOSIO_API_KEY")+ .with("OPENHUMAN_KEYRING_BACKEND", "file");++ let skill_dir = config.workspace_dir.join("skills/required-skill");+ std::fs::create_dir_all(&skill_dir).expect("create isolated skill directory");+ std::fs::write(+ skill_dir.join("WORKFLOW.md"),+ "A required GitHub workflow.\n",+ )+ .expect("write valid workflow document");+ let manifest = skill_dir.join("workflow.toml");+ std::fs::write(+ &manifest,+ "id = \"required-skill\"\nwhen_to_use = \"Use GitHub\"\n\+ [github]\nrequired = true\nidentity_match = \"none\"\n",+ )+ .expect("write required GitHub manifest");+ let profiles = scratch.path().join("auth-profiles.json");+ let raw_profile = serde_json::json!({+ "schema_version": 1,+ "active_profiles": {},+ "profiles": {+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": "expired-doctor-test-secret",+ "metadata": { "session_expires_at": "2000-01-01T00:00:00Z" }+ }+ }+ })+ .to_string();+ std::fs::write(&profiles, &raw_profile).expect("seed isolated expired profile");++ let loaded =+ crate::security::credentials::session_support::load_app_session_profile_read_only(&config)+ .expect("read-only profile fixture should parse");+ assert!(matches!(+ crate::security::credentials::session_support::classify_session_token(+ loaded.as_ref(),+ chrono::Utc::now()+ ),+ crate::security::credentials::session_support::SessionTokenCheck::Expired+ ));+ let connector_state_before = crate::modules::ops::state_of("tinyconnectors");++ let context = scoped(config.clone());+ let findings = CoreContext::scope(context, async {+ let required = required_github_preflight(&config).expect("manifest requires GitHub");+ GithubPreflightCheck {+ required: required.config,+ manifest_path: required.path,+ probes: None,+ }+ .detect(&DoctorCtx::from_config(config.clone()))+ .await+ })+ .await;++ assert_eq!(std::fs::read_to_string(&profiles).unwrap(), raw_profile);+ assert!(!scratch.path().join("auth-profiles.lock").exists());+ assert_eq!(+ crate::modules::ops::state_of("tinyconnectors"),+ connector_state_before,+ "doctor must not start or otherwise transition the connector module"+ );+ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Skipped);+ assert!(findings[0].message.contains("unavailable"));+ assert!(!scratch.path().join("modules").exists());+ assert!(!findings[0].message.contains("expired-doctor-test-secret"));+}++#[tokio::test]+async fn production_github_preflight_skips_malformed_profile_without_quarantining_or_loading_connectors(+) {+ let scratch = tempfile::tempdir().expect("create isolated preflight fixture");+ let config = config_in(scratch.path());+ let _env = crate::config::test_env::EnvVarGuard::locked_async()+ .await+ .with("HOME", scratch.path())+ .with("OPENHUMAN_WORKSPACE", config.workspace_dir.as_os_str())+ .without("OPENHUMAN_ACTION_DIR")+ .without("COMPOSIO_API_KEY")+ .with("OPENHUMAN_KEYRING_BACKEND", "file");++ let skill_dir = config.workspace_dir.join("skills/required-skill");+ std::fs::create_dir_all(&skill_dir).expect("create isolated skill directory");+ std::fs::write(+ skill_dir.join("WORKFLOW.md"),+ "A required GitHub workflow.\n",+ )+ .expect("write workflow document");+ let manifest = skill_dir.join("workflow.toml");+ std::fs::write(+ &manifest,+ "id = \"required-skill\"\nwhen_to_use = \"Use GitHub\"\n\+ [github]\nrequired = true\nidentity_match = \"none\"\n",+ )+ .expect("write required GitHub manifest");+ let profiles = scratch.path().join("auth-profiles.json");+ let malformed = b"{ malformed profile store";+ std::fs::write(&profiles, malformed).expect("seed malformed isolated profile store");++ let context = scoped(config.clone());+ let findings = CoreContext::scope(context, async {+ let required = required_github_preflight(&config).expect("manifest requires GitHub");+ GithubPreflightCheck {+ required: required.config,+ manifest_path: required.path,+ probes: None,+ }+ .detect(&DoctorCtx::from_config(config.clone()))+ .await+ })+ .await;++ assert_eq!(std::fs::read(&profiles).unwrap(), malformed);+ assert!(!scratch.path().join("auth-profiles.lock").exists());+ assert!(!scratch+ .path()+ .read_dir()+ .unwrap()+ .filter_map(Result::ok)+ .any(|entry| entry.file_name().to_string_lossy().contains("corrupt")));+ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Skipped);+ assert!(findings[0].message.contains("unavailable"));+ assert!(!scratch.path().join("modules").exists());+}++#[tokio::test]+async fn malformed_skill_manifest_reports_only_a_warning_and_its_path() {+ let scratch = tempfile::tempdir().expect("create isolated skill fixture");+ let config = config_in(scratch.path());+ let skill_dir = config.workspace_dir.join("skills/broken-skill");+ std::fs::create_dir_all(&skill_dir).expect("create skill directory");+ let manifest = skill_dir.join("SKILL.md");+ std::fs::write(&manifest, "---\nname: [broken\n---\nA test skill.\n")+ .expect("write malformed skill manifest");++ let context = scoped(config.clone());+ let findings = CoreContext::scope(context, async {+ SkillDiscoveryCheck+ .detect(&DoctorCtx::from_config(config))+ .await+ })+ .await;++ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Warn);+ assert_eq!(+ findings[0].config_path.as_deref(),+ Some(manifest.to_string_lossy().as_ref())+ );+ assert!(!findings[0].message.contains("broken"));+}diff --git a/crates/openhuman-core/src/doctor/checks/storage.rs b/crates/openhuman-core/src/doctor/checks/storage.rsnew file mode 100644index 0000000000..affbec1d73--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/storage.rs@@ -0,0 +1,201 @@+//! Storage connectivity and interrupted-layout checks.++use std::sync::Arc;++use async_trait::async_trait;+use tinystoragedrivers::StorageConfig;++use crate::doctor::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding};++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(StorageConnect), Arc::new(StorageLayout)]+}++struct StorageConnect;++#[async_trait]+impl DoctorCheck for StorageConnect {+ fn id(&self) -> &str {+ "storage/connect"+ }++ fn category(&self) -> &str {+ "storage"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let Some(url) = crate::storage::url_from(None, ctx.config()) else {+ return vec![Finding::skipped(+ self.id(),+ "Storage is not configured for this selected profile.",+ "Configure storage for the selected profile and rerun doctor.",+ )];+ };+ let parsed = match StorageConfig::parse(&url) {+ Ok(parsed) => parsed,+ Err(_) => {+ return vec![Finding::error(+ self.id(),+ "The selected storage configuration is invalid.",+ "Review the storage URL in the selected configuration.",+ )];+ }+ };+ inspect_storage_config(self.id(), parsed, 0).await+ }+}++async fn inspect_storage_config(check_id: &str, config: StorageConfig, depth: u8) -> Vec<Finding> {+ if depth > 2 {+ return vec![Finding::skipped(+ check_id,+ "The selected composite storage configuration is nested beyond the inspection limit.",+ "Simplify the storage configuration and rerun doctor.",+ )];+ }+ match config {+ StorageConfig::Sqlite { path } => {+ match tokio::task::spawn_blocking(move || sqlite_probe(&path)).await {+ Ok(true) => vec![Finding::pass(+ check_id,+ "The selected SQLite storage database is readable.",+ )],+ Ok(false) | Err(_) => vec![Finding::error(+ check_id,+ "The selected SQLite storage database could not be read.",+ "Check that the configured database exists, is readable, and is not busy.",+ )],+ }+ }+ StorageConfig::Memory => vec![Finding::pass(+ check_id,+ "The selected in-memory storage driver is available.",+ )],+ StorageConfig::File { dir } => {+ match tokio::task::spawn_blocking(move || file_probe(&dir)).await {+ Ok(true) => vec![Finding::pass(+ check_id,+ "The selected file storage directory exists and is readable.",+ )],+ Ok(false) | Err(_) => vec![Finding::error(+ check_id,+ "The selected file storage directory could not be read.",+ "Check that the configured directory exists and is readable.",+ )],+ }+ }+ StorageConfig::MongoDb { uri, database } => {+ #[cfg(feature = "storage-mongodb")]+ {+ match tinystoragedrivers::MongoStorage::connect(&uri, &database).await {+ Ok(_) => vec![Finding::pass(+ check_id,+ "The selected MongoDB server answered a read-only hello request.",+ )],+ Err(_) => vec![Finding::error(+ check_id,+ "The selected MongoDB server could not be reached.",+ "Check the selected MongoDB endpoint and credentials.",+ )],+ }+ }+ #[cfg(not(feature = "storage-mongodb"))]+ {+ let _ = (uri, database);+ vec![Finding::skipped(+ check_id,+ "MongoDB connectivity cannot be checked in this build.",+ "Use a build with MongoDB storage support to probe this backend.",+ )]+ }+ }+ StorageConfig::Composite { records, blobs } => {+ let mut findings =+ Box::pin(inspect_storage_config(check_id, *records, depth + 1)).await;+ findings.extend(match *blobs {+ tinystoragedrivers::BlobConfig::Backend(config) => {+ Box::pin(inspect_storage_config(check_id, config, depth + 1)).await+ }+ tinystoragedrivers::BlobConfig::S3 { .. } => vec![Finding::skipped(+ check_id,+ "The S3 blob backend has no bounded read-only connectivity probe.",+ "Check the configured S3 endpoint with its provider's read-only diagnostics.",+ )],+ });+ findings+ }+ #[allow(unreachable_patterns)]+ _ => vec![Finding::skipped(+ check_id,+ "The selected storage driver has no safe read-only connectivity probe.",+ "Use a storage driver with a read-only doctor probe or run its own connectivity check.",+ )],+ }+}++fn sqlite_probe(path: &std::path::Path) -> bool {+ tinystoragedrivers::sqlite::SqliteStorage::probe_read_only(path).is_ok()+}++fn file_probe(path: &std::path::Path) -> bool {+ std::fs::read_dir(path).is_ok()+}++struct StorageLayout;++#[async_trait]+impl DoctorCheck for StorageLayout {+ fn id(&self) -> &str {+ "storage/layout"+ }++ fn category(&self) -> &str {+ "storage"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ fn is_blocking(&self) -> bool {+ true+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ self.detect_blocking(ctx).unwrap_or_default()+ }++ fn detect_blocking(&self, ctx: &DoctorCtx) -> Option<Vec<Finding>> {+ let Some(target) = crate::storage::layout::Target::from_config(ctx.config()) else {+ return Some(vec![Finding::pass(+ self.id(),+ "The selected configuration has no desktop layout migration state.",+ )]);+ };+ match crate::storage::layout::state::LayoutState::load(&target.profile_dir) {+ Ok(Some(_state)) => Some(vec![Finding::new(+ self.id(),+ crate::doctor::FindingSeverity::Warn,+ "A storage layout migration is incomplete.",+ "Stop OpenHuman and resume the storage layout migration from Settings or the CLI.",+ )]),+ Ok(None) => Some(vec![Finding::pass(+ self.id(),+ "No interrupted storage layout migration was found.",+ )]),+ Err(_) => Some(vec![Finding::error(+ self.id(),+ "The storage layout migration state could not be read.",+ "Check permissions for the selected profile directory.",+ )]),+ }+ }+}++#[cfg(test)]+#[path = "storage_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/storage_tests.rs b/crates/openhuman-core/src/doctor/checks/storage_tests.rsnew file mode 100644index 0000000000..e35965537a--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/storage_tests.rs@@ -0,0 +1,81 @@+use super::*;+use crate::core::runtime::ComponentSet;+use crate::doctor::contract::{DoctorCtx, FindingSeverity};++fn context(root: &std::path::Path, url: String) -> DoctorCtx {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config.storage.url = Some(url);+ DoctorCtx::from_config_with_components(config, ComponentSet::all())+}++#[tokio::test]+async fn sqlite_connect_uses_read_only_probe_and_does_not_create_missing_paths() {+ let root = tempfile::tempdir().expect("temporary storage root");+ let missing = root.path().join("not-created/storage.db");+ let findings = StorageConnect+ .detect(&context(+ root.path(),+ format!("sqlite:{}", missing.display()),+ ))+ .await;+ assert_eq!(findings[0].severity, FindingSeverity::Error);+ assert!(!missing.exists());+ assert!(!missing.parent().expect("parent").exists());+}++#[tokio::test]+async fn corrupt_sqlite_is_an_error_without_echoing_its_location() {+ let root = tempfile::tempdir().expect("temporary storage root");+ let file = root.path().join("private-path.sqlite");+ std::fs::write(&file, b"not a database").expect("write corrupt fixture");+ let before = std::fs::read(&file).expect("read before probe");+ let findings = StorageConnect+ .detect(&context(root.path(), format!("sqlite:{}", file.display())))+ .await;+ assert_eq!(findings[0].severity, FindingSeverity::Error);+ assert!(!findings[0].message.contains("private-path"));+ assert_eq!(std::fs::read(file).expect("read after probe"), before);+}++#[tokio::test]+async fn file_storage_probe_reads_existing_directory_and_never_creates_it() {+ let root = tempfile::tempdir().expect("temporary storage root");+ let existing = root.path().join("file-storage");+ std::fs::create_dir(&existing).expect("create existing fixture root");+ let good = StorageConnect+ .detect(&context(+ root.path(),+ format!("file:{}", existing.display()),+ ))+ .await;+ assert_eq!(good[0].severity, FindingSeverity::Pass);++ let missing = root.path().join("private-storage-root");+ let bad = StorageConnect+ .detect(&context(root.path(), format!("file:{}", missing.display())))+ .await;+ assert_eq!(bad[0].severity, FindingSeverity::Error);+ assert!(!missing.exists());+ assert!(!bad[0].message.contains("private-storage-root"));+}++#[tokio::test]+async fn composite_storage_checks_supported_children_and_skips_unprobeable_s3() {+ let findings = inspect_storage_config(+ "storage/connect",+ StorageConfig::Composite {+ records: Box::new(StorageConfig::Memory),+ blobs: Box::new(tinystoragedrivers::BlobConfig::S3 {+ url: "s3://fixture-bucket".to_owned(),+ }),+ },+ 0,+ )+ .await;+ assert_eq!(findings.len(), 2);+ assert_eq!(findings[0].severity, FindingSeverity::Pass);+ assert_eq!(findings[1].severity, FindingSeverity::Skipped);+}diff --git a/crates/openhuman-core/src/doctor/checks/voice.rs b/crates/openhuman-core/src/doctor/checks/voice.rsnew file mode 100644index 0000000000..e7dd90ced4--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/voice.rs@@ -0,0 +1,277 @@+//! Read-only readiness checks for STT and TTS configuration.++use std::sync::Arc;++use async_trait::async_trait;++use crate::config::Config;+use crate::doctor::{ComponentId, DoctorCheck, DoctorTier, Finding};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum VoiceIssue {+ BuildDisabled,+ ProviderNotConfigured,+ ProviderUnsupported,+ CredentialMissing,+ PiperBinaryMissing,+ VoiceModelMissing,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) struct VoiceSnapshot {+ pub stt: Result<(), VoiceIssue>,+ pub tts: Result<(), VoiceIssue>,+}++#[async_trait]+pub(super) trait VoiceStatusProbe: Send + Sync {+ async fn inspect(&self, config: &Config) -> VoiceSnapshot;+}++struct ConfigVoiceProbe;++#[async_trait]+impl VoiceStatusProbe for ConfigVoiceProbe {+ async fn inspect(&self, config: &Config) -> VoiceSnapshot {+ VoiceSnapshot {+ stt: stt_readiness(config),+ tts: tts_readiness(config),+ }+ }+}++pub(super) fn for_context() -> Vec<Arc<dyn DoctorCheck>> {+ checks_with_probe(Arc::new(ConfigVoiceProbe))+ .into_iter()+ .map(|check| Arc::new(check) as Arc<dyn DoctorCheck>)+ .collect()+}++fn checks_with_probe(probe: Arc<dyn VoiceStatusProbe>) -> Vec<VoiceCheck> {+ vec![+ VoiceCheck::configured(VoiceKind::Stt, Arc::clone(&probe)),+ VoiceCheck::configured(VoiceKind::Tts, probe),+ ]+}++#[derive(Clone, Copy)]+enum VoiceKind {+ Stt,+ Tts,+}++struct VoiceCheck {+ id: &'static str,+ kind: VoiceKind,+ probe: Arc<dyn VoiceStatusProbe>,+}++impl VoiceCheck {+ fn configured(kind: VoiceKind, probe: Arc<dyn VoiceStatusProbe>) -> Self {+ let (id, _) = kind.parts();+ Self { id, kind, probe }+ }++ async fn finding(&self, config: &Config) -> Finding {+ let snapshot = self.probe.inspect(config).await;+ let (id, result) = match self.kind {+ VoiceKind::Stt => (self.id, snapshot.stt),+ VoiceKind::Tts => (self.id, snapshot.tts),+ };+ match result {+ Ok(()) => Finding::pass(id, "The configured voice provider is ready."),+ Err(VoiceIssue::BuildDisabled) => Finding::skipped(+ id,+ "Voice support is not included in this build.",+ "Use a build that includes the voice component to inspect speech providers.",+ ),+ Err(issue) => Finding::error(id, issue_message(issue), issue_hint(issue)),+ }+ }+}++impl VoiceKind {+ fn parts(self) -> (&'static str, &'static str) {+ match self {+ Self::Stt => ("voice/stt", "speech-to-text"),+ Self::Tts => ("voice/tts", "text-to-speech"),+ }+ }+}++#[async_trait]+impl DoctorCheck for VoiceCheck {+ fn id(&self) -> &str {+ self.id+ }++ fn category(&self) -> &str {+ match self.kind {+ VoiceKind::Stt => "speech-to-text",+ VoiceKind::Tts => "text-to-speech",+ }+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Voice)+ }++ async fn detect(&self, ctx: &crate::doctor::DoctorCtx) -> Vec<Finding> {+ vec![self.finding(ctx.config()).await]+ }+}++fn stt_readiness(config: &Config) -> Result<(), VoiceIssue> {+ #[cfg(not(feature = "voice"))]+ {+ let _ = config;+ Err(VoiceIssue::BuildDisabled)+ }+ #[cfg(feature = "voice")]+ {+ let provider = crate::voice::effective_stt_provider(config);+ let slug = provider+ .split_once(':')+ .map_or(provider.as_str(), |(slug, _)| slug);+ if is_hosted_slug(slug) {+ return crate::voice::factory::registry::has_stt_provider(slug)+ .then_some(())+ .ok_or(VoiceIssue::ProviderNotConfigured);+ }+ let entry = config+ .voice_providers+ .iter()+ .find(|entry| entry.slug == slug)+ .ok_or(VoiceIssue::ProviderNotConfigured)?;+ if !entry.capability.supports_stt() {+ return Err(VoiceIssue::ProviderUnsupported);+ }+ provider_credential_present_read_only(config, slug)+ .then_some(())+ .ok_or(VoiceIssue::CredentialMissing)+ }+}++fn tts_readiness(config: &Config) -> Result<(), VoiceIssue> {+ #[cfg(not(feature = "voice"))]+ {+ let _ = config;+ Err(VoiceIssue::BuildDisabled)+ }+ #[cfg(feature = "voice")]+ {+ let provider = crate::voice::factory::effective_tts_provider(config);+ let slug = provider+ .split_once(':')+ .map_or(provider.as_str(), |(slug, _)| slug);+ if slug == "piper" {+ let runtime = crate::inference::local_runtime_config(config);+ let binary =+ tinyinference_local::service::paths::resolve_piper_binary_with_config(&runtime);+ if binary.is_none() {+ return Err(VoiceIssue::PiperBinaryMissing);+ }+ return tinyinference_local::service::paths::resolve_tts_voice_path(&runtime)+ .map(|_| ())+ .map_err(|_| VoiceIssue::VoiceModelMissing);+ }+ if is_hosted_slug(slug) {+ return crate::voice::factory::registry::has_tts_provider(slug)+ .then_some(())+ .ok_or(VoiceIssue::ProviderNotConfigured);+ }+ let entry = config+ .voice_providers+ .iter()+ .find(|entry| entry.slug == slug)+ .ok_or(VoiceIssue::ProviderNotConfigured)?;+ if !entry.capability.supports_tts() {+ return Err(VoiceIssue::ProviderUnsupported);+ }+ provider_credential_present_read_only(config, slug)+ .then_some(())+ .ok_or(VoiceIssue::CredentialMissing)+ }+}++fn is_hosted_slug(slug: &str) -> bool {+ matches!(slug.trim(), "cloud" | "openhuman" | "backend")+}++fn provider_credential_present_read_only(config: &Config, slug: &str) -> bool {+ use crate::security::credentials::{profiles::AuthProfileKind, AuthService};++ let key = crate::inference::provider::factory::auth_key_for_slug(slug);+ for provider in [key.as_str(), slug] {+ if let Ok(Some(profile)) = AuthService::get_profile_read_only(config, provider, None) {+ let nonempty = match profile.kind {+ AuthProfileKind::Token => profile+ .token+ .as_deref()+ .is_some_and(|token| !token.trim().is_empty()),+ AuthProfileKind::OAuth => profile+ .token_set+ .as_ref()+ .is_some_and(|tokens| !tokens.access_token.trim().is_empty()),+ };+ if nonempty {+ return true;+ }+ }+ }++ if slug == "openai" {+ if let Ok(Some(profile)) = AuthService::get_profile_read_only(+ config,+ crate::security::credentials::openai_oauth::OPENAI_PROVIDER_KEY,+ Some(crate::security::credentials::openai_oauth::OPENAI_OAUTH_PROFILE_NAME),+ ) {+ if let Some(tokens) = profile.token_set {+ return !tokens.access_token.trim().is_empty()+ && !tokens.is_expiring_within(std::time::Duration::from_secs(120));+ }+ }+ }+ false+}++fn issue_message(issue: VoiceIssue) -> &'static str {+ match issue {+ VoiceIssue::BuildDisabled => "Voice support is not included in this build.",+ VoiceIssue::ProviderNotConfigured => {+ "No usable provider is registered for this voice route."+ }+ VoiceIssue::ProviderUnsupported => {+ "The selected voice provider does not support this operation."+ }+ VoiceIssue::CredentialMissing => "The selected voice provider has no saved credential.",+ VoiceIssue::PiperBinaryMissing => "The configured Piper executable was not found.",+ VoiceIssue::VoiceModelMissing => "The configured Piper voice model was not found.",+ }+}++fn issue_hint(issue: VoiceIssue) -> &'static str {+ match issue {+ VoiceIssue::BuildDisabled => "Use a build that includes the voice component.",+ VoiceIssue::ProviderNotConfigured | VoiceIssue::ProviderUnsupported => {+ "Select a supported speech provider in Voice settings."+ }+ VoiceIssue::CredentialMissing => {+ "Connect the selected speech provider or choose an available route."+ }+ VoiceIssue::PiperBinaryMissing => {+ "Install Piper through the normal setup path, then rerun doctor."+ }+ VoiceIssue::VoiceModelMissing => {+ "Install the selected Piper voice model, then rerun doctor."+ }+ }+}++#[cfg(test)]+#[path = "voice_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/voice_tests.rs b/crates/openhuman-core/src/doctor/checks/voice_tests.rsnew file mode 100644index 0000000000..c7001f4c3f--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/voice_tests.rs@@ -0,0 +1,101 @@+use super::*;+use crate::doctor::contract::{DoctorCtx, FindingSeverity};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++struct FixedVoiceStatus {+ snapshot: VoiceSnapshot,+ calls: Arc<AtomicUsize>,+ workspace: std::sync::Mutex<Option<std::path::PathBuf>>,+}++#[async_trait::async_trait]+impl VoiceStatusProbe for FixedVoiceStatus {+ async fn inspect(&self, config: &crate::config::Config) -> VoiceSnapshot {+ self.calls.fetch_add(1, Ordering::SeqCst);+ *self.workspace.lock().unwrap() = Some(config.workspace_dir.clone());+ self.snapshot+ }+}++fn config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config+}++#[tokio::test]+async fn stt_and_tts_configuration_findings_are_separate_and_sanitized() {+ let scratch = tempfile::tempdir().expect("create isolated fixture");+ let config = config_in(scratch.path());+ let calls = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(FixedVoiceStatus {+ snapshot: VoiceSnapshot {+ stt: Err(VoiceIssue::CredentialMissing),+ tts: Ok(()),+ },+ calls: Arc::clone(&calls),+ workspace: Default::default(),+ });+ let checks = checks_with_probe(probe);+ let ctx = DoctorCtx::from_config(config);+ let stt = checks[0].detect(&ctx).await.remove(0);+ let tts = checks[1].detect(&ctx).await.remove(0);+ assert_eq!(stt.check_id, "voice/stt");+ assert_eq!(stt.severity, FindingSeverity::Error);+ assert_eq!(tts.check_id, "voice/tts");+ assert_eq!(tts.severity, FindingSeverity::Pass);+ assert_eq!(+ stt.message,+ "The selected voice provider has no saved credential."+ );+ assert_eq!(+ stt.fix_hint,+ "Connect the selected speech provider or choose an available route."+ );+ assert_eq!(calls.load(Ordering::SeqCst), 2);+}++#[tokio::test]+async fn voice_checks_inspect_the_selected_config_without_starting_audio_runtime() {+ let ambient = tempfile::tempdir().expect("create ambient fixture");+ let selected = tempfile::tempdir().expect("create selected fixture");+ let config_a = config_in(ambient.path());+ let config_b = config_in(selected.path());+ let calls = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(FixedVoiceStatus {+ snapshot: VoiceSnapshot {+ stt: Ok(()),+ tts: Ok(()),+ },+ calls: Arc::clone(&calls),+ workspace: Default::default(),+ });+ let checks = checks_with_probe(probe.clone());+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let findings = crate::core::runtime::CoreContext::scope(ambient_context, async {+ let ctx = DoctorCtx::from_config(config_b.clone());+ let mut findings = Vec::new();+ for check in &checks {+ findings.extend(check.detect(&ctx).await);+ }+ findings+ })+ .await;+ assert_eq!(findings.len(), 2);+ assert!(findings+ .iter()+ .all(|finding| finding.severity == FindingSeverity::Pass));+ assert_eq!(calls.load(Ordering::SeqCst), 2);+ assert_eq!(+ *probe.workspace.lock().unwrap(),+ Some(config_b.workspace_dir)+ );+}diff --git a/crates/openhuman-core/src/doctor/checks/wallet.rs b/crates/openhuman-core/src/doctor/checks/wallet.rsnew file mode 100644index 0000000000..d5274cefea--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/wallet.rs@@ -0,0 +1,144 @@+//! Read-only inspection of an existing wallet state snapshot.++use std::sync::Arc;++use crate::doctor::{ComponentId, DoctorCheck, DoctorTier, Finding};+use async_trait::async_trait;++#[cfg(feature = "web3")]+use crate::config::Config;++#[cfg(feature = "web3")]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum WalletSnapshotFailure {+ Malformed,+ Unavailable,+}+#[cfg(feature = "web3")]+type SnapshotFailure = WalletSnapshotFailure;++#[cfg(feature = "web3")]+#[derive(Debug, Clone, Copy)]+struct WalletSnapshot {+ configured: bool,+}++#[cfg(feature = "web3")]+trait WalletSnapshotProbe: Send + Sync {+ fn read_existing(+ &self,+ config: &Config,+ ) -> Result<Option<WalletSnapshot>, WalletSnapshotFailure>;+}++#[cfg(feature = "web3")]+struct FileSnapshot;++#[cfg(feature = "web3")]+impl WalletSnapshotProbe for FileSnapshot {+ fn read_existing(+ &self,+ config: &Config,+ ) -> Result<Option<WalletSnapshot>, WalletSnapshotFailure> {+ use std::io::Read;++ const MAX_SNAPSHOT_BYTES: u64 = 1024 * 1024;+ let path = config.workspace_dir.join("state").join("wallet-state.json");+ let metadata = match std::fs::symlink_metadata(&path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(_) => return Err(SnapshotFailure::Unavailable),+ };+ if metadata.file_type().is_symlink() || !metadata.is_file() {+ return Err(SnapshotFailure::Unavailable);+ }+ if metadata.len() > MAX_SNAPSHOT_BYTES {+ return Err(SnapshotFailure::Malformed);+ }+ let mut contents = Vec::with_capacity(metadata.len() as usize);+ std::fs::File::open(path)+ .map_err(|_| SnapshotFailure::Unavailable)?+ .take(MAX_SNAPSHOT_BYTES + 1)+ .read_to_end(&mut contents)+ .map_err(|_| SnapshotFailure::Unavailable)?;+ if contents.len() as u64 > MAX_SNAPSHOT_BYTES {+ return Err(SnapshotFailure::Malformed);+ }+ let inspection = crate::web3::wallet::inspect_stored_wallet_state(&contents)+ .map_err(|_| SnapshotFailure::Malformed)?;+ let configured = inspection.consent_granted && inspection.account_count > 0;+ Ok(Some(WalletSnapshot { configured }))+ }+}++pub(super) fn for_context() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(WalletStatusCheck {+ #[cfg(feature = "web3")]+ probe: Arc::new(FileSnapshot),+ })]+}++struct WalletStatusCheck {+ #[cfg(feature = "web3")]+ probe: Arc<dyn WalletSnapshotProbe>,+}++impl WalletStatusCheck {+ #[cfg(all(test, feature = "web3"))]+ fn with_probe(probe: Arc<dyn WalletSnapshotProbe>) -> Self {+ Self { probe }+ }+}++#[async_trait]+impl DoctorCheck for WalletStatusCheck {+ fn id(&self) -> &str {+ "wallet/status"+ }+ fn category(&self) -> &str {+ "wallet"+ }+ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }+ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Wallet)+ }++ async fn detect(&self, ctx: &crate::doctor::DoctorCtx) -> Vec<Finding> {+ #[cfg(not(feature = "web3"))]+ let finding = Finding::skipped(+ self.id(),+ "Wallet support is not included in this build.",+ "Use a build with the wallet component enabled to inspect wallet state.",+ );+ #[cfg(feature = "web3")]+ let finding = match self.probe.read_existing(ctx.config()) {+ Ok(Some(WalletSnapshot { configured: true })) => {+ Finding::pass(self.id(), "An existing wallet snapshot is configured.")+ }+ Ok(Some(WalletSnapshot { configured: false })) | Ok(None) => Finding::skipped(+ self.id(),+ "No configured wallet snapshot exists in the selected workspace.",+ "Set up a wallet through the normal wallet flow, then rerun doctor.",+ ),+ Err(SnapshotFailure::Malformed) => Finding::error(+ self.id(),+ "The selected wallet snapshot is malformed.",+ "Review wallet settings before retrying; doctor leaves the snapshot untouched.",+ ),+ Err(SnapshotFailure::Unavailable) => Finding::error(+ self.id(),+ "The selected wallet snapshot could not be read.",+ "Check local workspace permissions, then rerun doctor.",+ ),+ };+ #[cfg(not(feature = "web3"))]+ let _ = ctx;+ vec![finding]+ }+}++#[cfg(test)]+#[path = "wallet_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/wallet_tests.rs b/crates/openhuman-core/src/doctor/checks/wallet_tests.rsnew file mode 100644index 0000000000..8f1824e35f--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/wallet_tests.rs@@ -0,0 +1,296 @@+use super::*;+use crate::doctor::contract::{DoctorCtx, FindingSeverity};+#[cfg(feature = "web3")]+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++#[cfg(feature = "web3")]+struct ReadOnlySnapshot {+ expected_workspace: std::path::PathBuf,+ snapshot: Result<Option<WalletSnapshot>, WalletSnapshotFailure>,+ reads: Arc<AtomicUsize>,+ keychain_queries: Arc<AtomicUsize>,+}++#[cfg(feature = "web3")]+impl WalletSnapshotProbe for ReadOnlySnapshot {+ fn read_existing(+ &self,+ config: &crate::config::Config,+ ) -> Result<Option<WalletSnapshot>, WalletSnapshotFailure> {+ self.reads.fetch_add(1, Ordering::SeqCst);+ assert_eq!(config.workspace_dir, self.expected_workspace);+ self.snapshot+ }+}++fn config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config+}++#[cfg(feature = "web3")]+fn stored_wallet_json(address: &str) -> String {+ serde_json::json!({+ "consentGranted": true,+ "source": "generated",+ "mnemonicWordCount": 12,+ "encryptedMnemonic": "enc2:doctor-fake-encrypted-mnemonic",+ "accounts": [{+ "chain": "evm",+ "address": address,+ "derivationPath": "m/44'/60'/0'/0/0"+ }],+ "updatedAtMs": 7+ })+ .to_string()+}++#[cfg(not(feature = "web3"))]+#[tokio::test]+async fn feature_off_wallet_facade_skips_without_reading_wallet_state() {+ let scratch = tempfile::tempdir().expect("create isolated wallet fixture");+ let config = config_in(scratch.path());+ let state_path = config.workspace_dir.join("state").join("wallet-state.json");+ std::fs::create_dir_all(state_path.parent().unwrap()).expect("create state fixture");+ let original = b"wallet snapshot remains untouched";+ std::fs::write(&state_path, original).expect("write state fixture");+ let check = WalletStatusCheck {};+ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);+ assert_eq!(finding.severity, FindingSeverity::Skipped);+ assert_eq!(std::fs::read(&state_path).unwrap(), original);+}++#[cfg(feature = "web3")]+#[tokio::test]+async fn a_valid_wallet_snapshot_is_inspected_without_keychain_access_or_rewrite() {+ let scratch = tempfile::tempdir().expect("create isolated wallet fixture");+ let config = config_in(scratch.path());+ let state_path = config.workspace_dir.join("state").join("wallet-state.json");+ std::fs::create_dir_all(state_path.parent().unwrap()).expect("create fixture state directory");+ let original = stored_wallet_json("0xdoctor-fixture-address");+ std::fs::write(&state_path, &original).expect("write fixture wallet state");++ let reads = Arc::new(AtomicUsize::new(0));+ let keychain_queries = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(ReadOnlySnapshot {+ expected_workspace: config.workspace_dir.clone(),+ snapshot: Ok(Some(WalletSnapshot { configured: true })),+ reads: Arc::clone(&reads),+ keychain_queries: Arc::clone(&keychain_queries),+ });+ let check = WalletStatusCheck::with_probe(probe.clone());++ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .into_iter()+ .next()+ .expect("existing wallet snapshot produces a finding");++ assert_eq!(finding.check_id, "wallet/status");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("0xdoctor-fixture-address"));+ assert!(!finding.message.contains("doctor-fake-encrypted-mnemonic"));+ assert_eq!(reads.load(Ordering::SeqCst), 1);+ assert_eq!(keychain_queries.load(Ordering::SeqCst), 0);+ assert_eq!(std::fs::read_to_string(&state_path).unwrap(), original);+}++#[cfg(feature = "web3")]+#[tokio::test]+async fn the_default_snapshot_reader_only_reads_selected_workspace_bytes() {+ let ambient = tempfile::tempdir().expect("create ambient wallet fixture");+ let selected = tempfile::tempdir().expect("create selected wallet fixture");+ let config_a = config_in(ambient.path());+ let config_b = config_in(selected.path());+ let state_a = config_a+ .workspace_dir+ .join("state")+ .join("wallet-state.json");+ let state_b = config_b+ .workspace_dir+ .join("state")+ .join("wallet-state.json");+ std::fs::create_dir_all(state_a.parent().unwrap()).expect("create ambient state");+ std::fs::create_dir_all(state_b.parent().unwrap()).expect("create selected state");+ std::fs::write(&state_a, stored_wallet_json("0xambient-address")).unwrap();+ let selected_bytes = stored_wallet_json("0xselected-address");+ std::fs::write(&state_b, &selected_bytes).unwrap();+ let check = WalletStatusCheck {+ probe: Arc::new(FileSnapshot),+ };+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let finding = crate::core::runtime::CoreContext::scope(ambient_context, async {+ check+ .detect(&DoctorCtx::from_config(config_b))+ .await+ .remove(0)+ })+ .await;++ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert!(!finding.message.contains("0xselected-address"));+ assert_eq!(std::fs::read_to_string(&state_b).unwrap(), selected_bytes);+ assert_eq!(+ std::fs::read_dir(state_b.parent().unwrap())+ .unwrap()+ .count(),+ 1+ );+}++#[cfg(feature = "web3")]+#[tokio::test]+async fn oversized_wallet_snapshot_is_rejected_without_rewriting_it() {+ let scratch = tempfile::tempdir().expect("create isolated wallet fixture");+ let config = config_in(scratch.path());+ let state_path = config.workspace_dir.join("state").join("wallet-state.json");+ std::fs::create_dir_all(state_path.parent().unwrap()).unwrap();+ let original = vec![b' '; 1024 * 1024 + 1];+ std::fs::write(&state_path, &original).unwrap();++ let check = WalletStatusCheck {+ probe: Arc::new(FileSnapshot),+ };+ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert_eq!(std::fs::read(&state_path).unwrap(), original);+ assert_eq!(+ std::fs::read_dir(state_path.parent().unwrap())+ .unwrap()+ .count(),+ 1+ );+}++#[cfg(feature = "web3")]+#[tokio::test]+async fn malformed_wallet_account_records_are_rejected_without_rewriting_state() {+ let scratch = tempfile::tempdir().expect("create isolated wallet fixture");+ let config = config_in(scratch.path());+ let state_path = config.workspace_dir.join("state").join("wallet-state.json");+ std::fs::create_dir_all(state_path.parent().unwrap()).unwrap();+ let original = serde_json::json!({+ "consentGranted": true,+ "source": "generated",+ "mnemonicWordCount": 12,+ "encryptedMnemonic": "enc2:doctor-fake-encrypted-mnemonic",+ "accounts": [null],+ "updatedAtMs": 7+ })+ .to_string();+ std::fs::write(&state_path, &original).unwrap();++ let check = WalletStatusCheck {+ probe: Arc::new(FileSnapshot),+ };+ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .remove(0);++ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(!finding.message.contains("doctor-fake-encrypted-mnemonic"));+ assert_eq!(std::fs::read_to_string(&state_path).unwrap(), original);+}++#[cfg(feature = "web3")]+#[tokio::test]+async fn malformed_selected_wallet_state_is_reported_without_quarantine_or_deletion() {+ let scratch = tempfile::tempdir().expect("create isolated wallet fixture");+ let config = config_in(scratch.path());+ let state_path = config.workspace_dir.join("state").join("wallet-state.json");+ std::fs::create_dir_all(state_path.parent().unwrap()).expect("create fixture state directory");+ let original = "{broken but private}\n";+ std::fs::write(&state_path, original).expect("write malformed fixture state");++ let reads = Arc::new(AtomicUsize::new(0));+ let keychain_queries = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(ReadOnlySnapshot {+ expected_workspace: config.workspace_dir.clone(),+ snapshot: Err(WalletSnapshotFailure::Malformed),+ reads,+ keychain_queries: Arc::clone(&keychain_queries),+ });+ let check = WalletStatusCheck::with_probe(probe);++ let finding = check+ .detect(&DoctorCtx::from_config(config))+ .await+ .into_iter()+ .next()+ .expect("malformed state produces a safe finding");++ assert_eq!(finding.check_id, "wallet/status");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(!finding.message.contains("broken but private"));+ assert_eq!(keychain_queries.load(Ordering::SeqCst), 0);+ assert_eq!(std::fs::read_to_string(&state_path).unwrap(), original);+ assert_eq!(+ std::fs::read_dir(state_path.parent().unwrap())+ .unwrap()+ .count(),+ 1,+ "the read-only check must not create a quarantine copy"+ );+}++#[cfg(feature = "web3")]+#[tokio::test]+async fn ambient_wallet_state_is_not_used_for_selected_b_workspace() {+ let ambient = tempfile::tempdir().expect("create ambient wallet fixture");+ let selected = tempfile::tempdir().expect("create selected wallet fixture");+ let config_a = config_in(ambient.path());+ let config_b = config_in(selected.path());+ let path_a = config_a+ .workspace_dir+ .join("state")+ .join("wallet-state.json");+ std::fs::create_dir_all(path_a.parent().unwrap()).expect("create ambient state directory");+ std::fs::write(&path_a, stored_wallet_json("0xambient-a-address"))+ .expect("write ambient wallet state");++ let reads = Arc::new(AtomicUsize::new(0));+ let keychain_queries = Arc::new(AtomicUsize::new(0));+ let probe = Arc::new(ReadOnlySnapshot {+ expected_workspace: config_b.workspace_dir.clone(),+ snapshot: Ok(None),+ reads: Arc::clone(&reads),+ keychain_queries: Arc::clone(&keychain_queries),+ });+ let check = WalletStatusCheck::with_probe(probe);+ let ambient_context = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let finding = crate::core::runtime::CoreContext::scope(ambient_context, async {+ check+ .detect(&DoctorCtx::from_config(config_b.clone()))+ .await+ .into_iter()+ .next()+ .expect("selected-B empty state is represented")+ })+ .await;++ assert_eq!(finding.check_id, "wallet/status");+ assert_eq!(finding.severity, FindingSeverity::Skipped);+ assert!(!finding.message.contains("0xambient-a-address"));+ assert_eq!(reads.load(Ordering::SeqCst), 1);+ assert_eq!(keychain_queries.load(Ordering::SeqCst), 0);+}diff --git a/crates/openhuman-core/src/doctor/checks/workspace.rs b/crates/openhuman-core/src/doctor/checks/workspace.rsnew file mode 100644index 0000000000..90c4b6e2d2--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/workspace.rs@@ -0,0 +1,149 @@+//! Read-only workspace checks and a bounded, disposable write probe.++use std::fs;+use std::path::Path;+use std::sync::Arc;++use async_trait::async_trait;++use crate::doctor::{DoctorCheck, DoctorCtx, DoctorTier, Finding, FindingSeverity};++const WRITABLE_ID: &str = "workspace/writable";+const LAYOUT_ID: &str = "workspace/layout";+const LOW_DISK_SPACE_MB: u64 = 512;++pub(super) fn checks() -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(WorkspaceWritable), Arc::new(WorkspaceLayout)]+}++struct WorkspaceWritable;++#[async_trait]+impl DoctorCheck for WorkspaceWritable {+ fn id(&self) -> &str {+ WRITABLE_ID+ }++ fn category(&self) -> &str {+ "workspace"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let workspace = &ctx.config().workspace_dir;+ if !workspace.is_dir() {+ return vec![workspace_error(+ "The configured workspace directory is missing or is not a directory.",+ )];+ }++ if crate::storage::probe_directory_writable(workspace).is_ok() {+ tracing::debug!(target: "doctor", check = WRITABLE_ID, outcome = "writable");+ Vec::new()+ } else {+ tracing::debug!(target: "doctor", check = WRITABLE_ID, outcome = "unwritable");+ vec![workspace_error(+ "The configured workspace directory is not writable.",+ )]+ }+ }+}++fn workspace_error(message: &str) -> Finding {+ let mut finding = Finding::error(+ WRITABLE_ID,+ message,+ "Grant write access to the workspace directory, then rerun doctor.",+ );+ finding.config_path = Some("workspace_dir".to_owned());+ tracing::debug!(target: "doctor", check = WRITABLE_ID, outcome = "error");+ finding+}++struct WorkspaceLayout;++#[async_trait]+impl DoctorCheck for WorkspaceLayout {+ fn id(&self) -> &str {+ LAYOUT_ID+ }++ fn category(&self) -> &str {+ "workspace"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let workspace = &ctx.config().workspace_dir;+ let disk_space_mb = available_disk_space_mb(workspace);+ let findings = layout_findings(workspace, disk_space_mb);+ tracing::debug!(+ target: "doctor",+ check = LAYOUT_ID,+ finding_count = findings.len(),+ "workspace layout inspected"+ );+ findings+ }+}++fn layout_findings(workspace: &Path, available_mb: Option<u64>) -> Vec<Finding> {+ if !workspace.is_dir() {+ return Vec::new();+ }++ let mut findings = Vec::new();+ let memory = workspace.join("memory");+ if !memory.is_dir() {+ findings.push(layout_warning(+ "The workspace memory directory is missing.",+ "Create the workspace `memory/` directory before using local memory features.",+ "workspace_dir/memory",+ ));+ }++ let system_prompt = workspace.join("SYSTEM.md");+ if !system_prompt.is_file() {+ findings.push(layout_warning(+ "The workspace SYSTEM.md file is missing.",+ "Add a SYSTEM.md file to the workspace if its agents need a workspace prompt.",+ "workspace_dir/SYSTEM.md",+ ));+ }++ if available_mb.is_some_and(|free| free < LOW_DISK_SPACE_MB) {+ findings.push(layout_warning(+ "The filesystem containing the workspace has less than 512 MB free.",+ "Free disk space on the filesystem that contains the workspace.",+ "workspace_dir",+ ));+ }+ findings+}++fn layout_warning(message: &str, fix_hint: &str, config_path: &str) -> Finding {+ let mut finding = Finding::new(LAYOUT_ID, FindingSeverity::Warn, message, fix_hint);+ finding.config_path = Some(config_path.to_owned());+ finding+}++fn available_disk_space_mb(path: &Path) -> Option<u64> {+ let canonical = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());+ let disks = sysinfo::Disks::new_with_refreshed_list();+ disks+ .list()+ .iter()+ .filter(|disk| canonical.starts_with(disk.mount_point()))+ .max_by_key(|disk| disk.mount_point().components().count())+ .map(|disk| disk.available_space() / (1024 * 1024))+}++#[cfg(test)]+#[path = "workspace_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/checks/workspace_tests.rs b/crates/openhuman-core/src/doctor/checks/workspace_tests.rsnew file mode 100644index 0000000000..1adb3011d0--- /dev/null+++ b/crates/openhuman-core/src/doctor/checks/workspace_tests.rs@@ -0,0 +1,280 @@+use super::*;++use crate::core::runtime::{CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::doctor::{DoctorCtx, DoctorOptions, DoctorTier, FindingSeverity};++fn config_in(root: &std::path::Path) -> crate::config::Config {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config+}++async fn run_only(config: crate::config::Config, id: &str) -> crate::doctor::DoctorReport {+ let core = CoreContext::for_test_with_extensions(DomainSet::full(), None, Extensions::new());+ CoreContext::scope(core, async move {+ crate::doctor::runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("selected workspace check should be in the report")+}++#[cfg(unix)]+const PRIVATE_WORKSPACE_MARKER: &str = "doctor-private-workspace-marker-8144";++#[cfg(unix)]+struct ReadOnlyWorkspace {+ _temp: tempfile::TempDir,+ workspace: std::path::PathBuf,+ original_mode: u32,+}++#[cfg(unix)]+impl ReadOnlyWorkspace {+ fn new() -> Self {+ use std::os::unix::fs::PermissionsExt;++ let temp = tempfile::tempdir().expect("read-only workspace fixture");+ let path = temp.path().join(PRIVATE_WORKSPACE_MARKER);+ std::fs::create_dir(&path).expect("create private workspace directory");+ let original_mode = std::fs::metadata(&path)+ .expect("workspace metadata")+ .permissions()+ .mode();+ let mut permissions = std::fs::metadata(&path)+ .expect("workspace metadata")+ .permissions();+ permissions.set_mode(original_mode & !0o222);+ std::fs::set_permissions(&path, permissions).expect("make workspace read-only");+ Self {+ _temp: temp,+ workspace: path,+ original_mode,+ }+ }++ fn path(&self) -> &std::path::Path {+ &self.workspace+ }+}++#[cfg(unix)]+impl Drop for ReadOnlyWorkspace {+ fn drop(&mut self) {+ use std::os::unix::fs::PermissionsExt;++ let mut permissions = std::fs::metadata(&self.workspace)+ .expect("workspace exists while restoring permissions")+ .permissions();+ permissions.set_mode(self.original_mode);+ std::fs::set_permissions(&self.workspace, permissions)+ .expect("restore permissions before temporary cleanup");+ }+}++#[cfg(unix)]+fn tree_snapshot(root: &std::path::Path) -> Vec<(std::path::PathBuf, Option<Vec<u8>>, u32)> {+ fn collect(+ root: &std::path::Path,+ path: &std::path::Path,+ entries: &mut Vec<(std::path::PathBuf, Option<Vec<u8>>, u32)>,+ ) {+ use std::os::unix::fs::PermissionsExt;++ let metadata = std::fs::symlink_metadata(path).expect("workspace entry metadata");+ let relative = path+ .strip_prefix(root)+ .expect("workspace entry stays under its root")+ .to_path_buf();+ let mode = metadata.permissions().mode();+ if metadata.file_type().is_dir() {+ entries.push((relative, None, mode));+ let mut children = std::fs::read_dir(path)+ .expect("read workspace directory")+ .map(|entry| entry.expect("workspace entry").path())+ .collect::<Vec<_>>();+ children.sort();+ for child in children {+ collect(root, &child, entries);+ }+ } else if metadata.file_type().is_file() {+ entries.push((+ relative,+ Some(std::fs::read(path).expect("read workspace file")),+ mode,+ ));+ } else if metadata.file_type().is_symlink() {+ entries.push((+ relative,+ Some(+ std::fs::read_link(path)+ .expect("read workspace symlink")+ .to_string_lossy()+ .as_bytes()+ .to_vec(),+ ),+ mode,+ ));+ }+ }++ let mut entries = Vec::new();+ collect(root, root, &mut entries);+ entries+}++#[cfg(unix)]+#[tokio::test]+async fn writable_probe_succeeds_and_leaves_the_selected_workspace_unchanged() {+ let fixture = tempfile::tempdir().expect("workspace fixture");+ let config = config_in(fixture.path());+ std::fs::create_dir_all(&config.workspace_dir).expect("create workspace");+ std::fs::write(config.workspace_dir.join("existing.txt"), b"fixture")+ .expect("write fixture file");+ let before = tree_snapshot(&config.workspace_dir);++ let report = run_only(config, "workspace/writable").await;++ assert!(report+ .checks_run+ .iter()+ .any(|id| id == "workspace/writable"));+ assert!(!report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"));+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "workspace/writable" && finding.severity == FindingSeverity::Pass+ }));+ assert_eq!(before, tree_snapshot(&fixture.path().join("workspace")));+}++#[cfg(unix)]+#[tokio::test]+async fn read_only_workspace_is_reported_by_the_native_writable_check() {+ let workspace = ReadOnlyWorkspace::new();+ assert!(workspace.path().is_dir(), "the selected workspace exists");+ assert!(+ crate::storage::probe_directory_writable(workspace.path()).is_err(),+ "the selected directory must reject probe-file creation"+ );+ let before = tree_snapshot(workspace.path());+ let mut config = crate::config::Config::default();+ config.workspace_dir = workspace.path().to_path_buf();++ let report = run_only(config, "workspace/writable").await;+ let after = tree_snapshot(workspace.path());++ assert_eq!(+ before, after,+ "the static probe must clean up its scratch file"+ );+ assert!(report+ .checks_run+ .iter()+ .any(|id| id == "workspace/writable"));+ assert!(!report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"));+ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "workspace/writable")+ .expect("native workspace check produces a finding");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert_eq!(finding.config_path.as_deref(), Some("workspace_dir"));+ let serialized = serde_json::to_string(&report).expect("serialize doctor report");+ assert!(+ !serialized.contains(PRIVATE_WORKSPACE_MARKER),+ "the report must not disclose the physical workspace path"+ );+ assert!(!finding.fix_hint.trim().is_empty());+}++#[tokio::test]+async fn missing_workspace_is_an_error_without_creating_it() {+ let fixture = tempfile::tempdir().expect("workspace fixture");+ let config = config_in(fixture.path());+ let workspace = config.workspace_dir.clone();++ let report = run_only(config, "workspace/writable").await;++ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "workspace/writable")+ .expect("missing workspace finding");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert_eq!(finding.config_path.as_deref(), Some("workspace_dir"));+ assert!(!workspace.exists(), "doctor must not create the workspace");+}++#[cfg(unix)]+#[test]+fn workspace_layout_reports_missing_entries_and_low_space_without_repairing_them() {+ let fixture = tempfile::tempdir().expect("workspace fixture");+ let workspace = fixture.path().join("workspace");+ std::fs::create_dir(&workspace).expect("create workspace");+ let before = tree_snapshot(&workspace);++ let findings = layout_findings(&workspace, Some(1));++ let paths = findings+ .iter()+ .filter(|finding| finding.check_id == "workspace/layout")+ .filter_map(|finding| finding.config_path.as_deref())+ .collect::<Vec<_>>();+ assert!(paths.contains(&"workspace_dir/memory"));+ assert!(paths.contains(&"workspace_dir/SYSTEM.md"));+ assert!(paths.contains(&"workspace_dir"));+ assert!(findings.iter().all(|finding| {+ finding.check_id == "workspace/layout"+ && finding.severity == FindingSeverity::Warn+ && !finding.fix_hint.trim().is_empty()+ }));+ assert_eq!(before, tree_snapshot(&workspace));+}++#[cfg(unix)]+#[test]+fn complete_workspace_layout_passes_at_the_disk_space_threshold() {+ let fixture = tempfile::tempdir().expect("workspace fixture");+ let workspace = fixture.path().join("workspace");+ std::fs::create_dir_all(workspace.join("memory")).expect("create memory directory");+ std::fs::write(workspace.join("SYSTEM.md"), "fixture prompt").expect("write workspace prompt");++ let findings = layout_findings(&workspace, Some(512));++ assert!(+ findings.is_empty(),+ "complete layout should be clean: {findings:#?}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn workspace_layout_finding_uses_the_registered_native_id() {+ let fixture = tempfile::tempdir().expect("workspace fixture");+ let config = config_in(fixture.path());+ std::fs::create_dir_all(&config.workspace_dir).expect("create workspace");++ let report = run_only(config, "workspace/layout").await;++ assert!(report.checks_run.iter().any(|id| id == "workspace/layout"));+ assert!(!report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"));+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "workspace/layout" && finding.severity == FindingSeverity::Warn+ }));+}diff --git a/crates/openhuman-core/src/doctor/config_file_tests.rs b/crates/openhuman-core/src/doctor/config_file_tests.rsnew file mode 100644index 0000000000..5ff9188ef8--- /dev/null+++ b/crates/openhuman-core/src/doctor/config_file_tests.rs@@ -0,0 +1,103 @@+use crate::config::Config;+use crate::doctor::contract::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};+use crate::doctor::runner;++const PARSE: &str = "config/parse";+const UNKNOWN_KEY: &str = "config/unknown-key";+const LEGACY_KEY: &str = "config/legacy-key";++async fn load_config(contents: &str) -> (tempfile::TempDir, Config) {+ let directory = tempfile::tempdir().expect("temporary config directory");+ let config_path = directory.path().join("config.toml");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).expect("create workspace");+ std::fs::write(&config_path, contents).expect("write config");+ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .expect("load config");+ (directory, config)+}++async fn run_config_check(config: Config, check_id: &str) -> Vec<Finding> {+ runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("selected config doctor check runs")+ .findings+ .into_iter()+ .filter(|finding| finding.check_id == check_id)+ .collect()+}++fn finding(findings: &[Finding], severity: FindingSeverity) -> &Finding {+ findings+ .iter()+ .find(|finding| finding.severity == severity)+ .expect("expected finding severity")+}++#[tokio::test]+async fn unknown_keys_warn_with_a_suggestion_without_exposing_values() {+ let (_directory, config) = load_config("[memroy]\nengine = \"private-value\"\n").await;+ let findings = run_config_check(config, UNKNOWN_KEY).await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert_eq!(warning.config_path.as_deref(), Some("memroy"));+ assert!(warning.message.contains("memory"), "{}", warning.message);+ assert!(!warning.message.contains("private-value"));+}++#[tokio::test]+async fn typed_parse_error_reports_field_path_and_backup_fallback_safely() {+ let directory = tempfile::tempdir().expect("temporary config directory");+ let config_path = directory.path().join("config.toml");+ let backup_path = directory.path().join("config.toml.bak");+ let workspace = directory.path().join("workspace");+ std::fs::create_dir(&workspace).expect("create workspace");+ std::fs::write(&config_path, "[memory]\nengine = 837465\n").expect("write invalid config");+ std::fs::write(&backup_path, "[memory]\nengine = \"backup-engine\"\n")+ .expect("write valid backup");+ let config = Config::load_from_config_path(&config_path, &workspace)+ .await+ .expect("load config from backup");++ let findings = run_config_check(config, PARSE).await;++ let error = finding(&findings, FindingSeverity::Error);+ assert_eq!(error.config_path.as_deref(), Some("memory.engine"));+ assert!(+ error.message.to_ascii_lowercase().contains("backup"),+ "{}",+ error.message+ );+ assert!(!error.message.contains("837465"));+ assert!(!error+ .message+ .contains(&directory.path().display().to_string()));+}++#[tokio::test]+async fn legacy_keys_report_the_actual_source_key_as_info() {+ let (_directory, config) =+ load_config("api_url = \"https://example.test/v1/chat/completions\"\n").await;+ let findings = run_config_check(config, LEGACY_KEY).await;++ let info = finding(&findings, FindingSeverity::Info);+ assert_eq!(info.config_path.as_deref(), Some("api_url"));+ assert!(info.message.contains("inference_url"), "{}", info.message);+}++#[tokio::test]+async fn clean_default_config_passes_each_config_check() {+ for check_id in [PARSE, UNKNOWN_KEY, LEGACY_KEY] {+ let findings = run_config_check(Config::default(), check_id).await;+ assert_eq!(findings.len(), 1, "{check_id}");+ assert_eq!(findings[0].severity, FindingSeverity::Pass, "{check_id}");+ }+}diff --git a/crates/openhuman-core/src/doctor/config_provenance_tests.rs b/crates/openhuman-core/src/doctor/config_provenance_tests.rsnew file mode 100644index 0000000000..dc5489f59a--- /dev/null+++ b/crates/openhuman-core/src/doctor/config_provenance_tests.rs@@ -0,0 +1,164 @@+use crate::config::schema::load::{DotenvLoadProvenance, ProvenanceSource};+use crate::config::Config;++use super::contract::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};+use super::runner;++const ENV_OVERRIDE: &str = "config/env-override";+const CONFIG_SOURCE: &str = "config/source";++fn config_with_file_env_override() -> Config {+ let mut config = Config::default();+ config.default_model = Some("resolved-model-secret".to_owned());+ config.config_path = "/diagnostics/config.toml".into();+ let document = toml::from_str::<toml::Value>(r#"default_model = "file-model-secret""#)+ .expect("test config document parses");+ config.load_provenance_mut().record_file_keys(&document);+ config.load_provenance_mut().record_env_override(+ "default_model",+ "OPENHUMAN_DEFAULT_MODEL",+ ProvenanceSource::Env,+ );+ config+}++fn selected_findings<'a>(findings: &'a [Finding], check_id: &str) -> Vec<&'a Finding> {+ findings+ .iter()+ .filter(|finding| finding.check_id == check_id)+ .collect()+}++async fn run_config_check(config: Config, check_id: &str) -> Vec<Finding> {+ runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("selected config doctor check runs")+ .findings+}++#[tokio::test]+async fn environment_override_warns_when_the_file_explicitly_sets_the_field() {+ let findings = run_config_check(config_with_file_env_override(), ENV_OVERRIDE).await;+ let matching = selected_findings(&findings, ENV_OVERRIDE);++ assert_eq!(+ matching.len(),+ 1,+ "one finding identifies the overridden field"+ );+ assert_eq!(matching[0].severity, FindingSeverity::Warn);+ assert_eq!(matching[0].config_path.as_deref(), Some("default_model"));+ assert!(matching[0].message.contains("OPENHUMAN_DEFAULT_MODEL"));+ let serialized = serde_json::to_string(&matching).expect("finding serializes");+ assert!(!serialized.contains("resolved-model-secret"));+ assert!(!serialized.contains("file-model-secret"));+}++#[tokio::test]+async fn environment_override_is_info_when_the_file_does_not_set_the_field() {+ let mut config = Config::default();+ config.load_provenance_mut().record_env_override(+ "agent.tool_dispatcher",+ "OPENHUMAN_TOOL_DISPATCHER",+ ProvenanceSource::Env,+ );++ let findings = run_config_check(config, ENV_OVERRIDE).await;+ let matching = selected_findings(&findings, ENV_OVERRIDE);++ assert_eq!(matching.len(), 1);+ assert_eq!(matching[0].severity, FindingSeverity::Info);+ assert_eq!(+ matching[0].config_path.as_deref(),+ Some("agent.tool_dispatcher")+ );+ assert!(matching[0].message.contains("OPENHUMAN_TOOL_DISPATCHER"));+}++#[tokio::test]+async fn environment_override_check_enumerates_multiple_unrelated_fields() {+ let mut config = config_with_file_env_override();+ config.load_provenance_mut().record_env_override(+ "search.enabled",+ "OPENHUMAN_SEARCH_ENABLED",+ ProvenanceSource::Env,+ );++ let findings = run_config_check(config, ENV_OVERRIDE).await;+ let matching = selected_findings(&findings, ENV_OVERRIDE);+ let by_path = matching+ .iter()+ .map(|finding| {+ (+ finding+ .config_path+ .as_deref()+ .expect("field path is reported"),+ finding.severity,+ )+ })+ .collect::<std::collections::BTreeMap<_, _>>();++ assert_eq!(matching.len(), 2);+ assert_eq!(by_path.get("default_model"), Some(&FindingSeverity::Warn));+ assert_eq!(by_path.get("search.enabled"), Some(&FindingSeverity::Info));+}++#[tokio::test]+async fn dotenv_shadowing_and_paths_are_reported_without_values() {+ let mut config = config_with_file_env_override();+ config+ .load_provenance_mut()+ .set_dotenv(Some(DotenvLoadProvenance::from_variables(+ "/diagnostics/.env".into(),+ ["OPENHUMAN_DEFAULT_MODEL", "OPENHUMAN_OUTPUT_LANGUAGE"],+ ["OPENHUMAN_DEFAULT_MODEL"],+ )));++ let findings = run_config_check(config, CONFIG_SOURCE).await;+ let matching = selected_findings(&findings, CONFIG_SOURCE);++ assert!(+ !matching.is_empty(),+ "config/source describes the active configuration sources"+ );+ let serialized = serde_json::to_string(&matching).expect("finding serializes");+ assert!(serialized.contains("/diagnostics/config.toml"));+ assert!(serialized.contains("/diagnostics/.env"));+ assert!(serialized.contains("OPENHUMAN_DEFAULT_MODEL"));+ assert!(!serialized.contains("resolved-model-secret"));+ assert!(!serialized.contains("file-model-secret"));+}++#[tokio::test]+async fn config_source_reports_active_cli_model_and_provider_overrides() {+ let mut config = Config::default();+ config.config_path = "/diagnostics/config.toml".into();+ config.default_model = Some("private-model-secret".to_owned());+ config.chat_provider = Some("private-provider-secret".to_owned());+ {+ let provenance = config.load_provenance_mut();+ provenance.record_cli_override("default_model");+ provenance.record_cli_override("chat_provider");+ }++ let findings = run_config_check(config, CONFIG_SOURCE).await;+ let matching = selected_findings(&findings, CONFIG_SOURCE);++ assert!(+ !matching.is_empty(),+ "config/source describes the active configuration sources"+ );+ let serialized = serde_json::to_string(&matching).expect("finding serializes");+ assert!(serialized.contains("--model"));+ assert!(serialized.contains("--provider"));+ assert!(!serialized.contains("private-model-secret"));+ assert!(!serialized.contains("private-provider-secret"));+}diff --git a/crates/openhuman-core/src/doctor/config_semantics_tests.rs b/crates/openhuman-core/src/doctor/config_semantics_tests.rsnew file mode 100644index 0000000000..2445d5bcb1--- /dev/null+++ b/crates/openhuman-core/src/doctor/config_semantics_tests.rs@@ -0,0 +1,281 @@+use crate::config::{test_env::EnvVarGuard, Config};+use crate::doctor::contract::{DoctorCtx, DoctorOptions, Finding, FindingSeverity};+use crate::doctor::runner;++async fn run_check(config: Config, check_id: &str) -> Vec<Finding> {+ let report = runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("built-in doctor checks should be registered");+ report+ .findings+ .into_iter()+ .filter(|finding| finding.check_id == check_id)+ .collect()+}++fn finding(findings: &[Finding], severity: FindingSeverity) -> &Finding {+ findings+ .iter()+ .find(|finding| finding.severity == severity)+ .expect("expected finding severity")+}++fn workspace_entries(root: &std::path::Path) -> Vec<std::path::PathBuf> {+ let mut entries = Vec::new();+ let mut pending = vec![root.to_owned()];+ while let Some(directory) = pending.pop() {+ for entry in std::fs::read_dir(directory).expect("read workspace snapshot") {+ let path = entry.expect("workspace entry").path();+ if path.is_dir() {+ pending.push(path.clone());+ }+ entries.push(path.strip_prefix(root).unwrap().to_owned());+ }+ }+ entries.sort();+ entries+}++#[tokio::test]+async fn disabled_memory_component_warns_when_an_engine_is_configured() {+ let mut config = Config::default();+ config.components.memory = false;+ config.memory.engine = "cortexdb".into();++ let findings = run_check(config, "components/referenced-but-disabled").await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert_eq!(warning.config_path.as_deref(), Some("memory.engine"));+ assert!(!warning.message.contains("cortexdb"));+}++#[tokio::test]+async fn disabled_mcp_component_warns_when_servers_are_configured() {+ let mut config = Config::default();+ config.components.mcp = false;+ let mut server = crate::config::McpServerConfig::default();+ server.name = "example".into();+ server.endpoint = "https://mcp.example.test/rpc".into();+ config.mcp_client.servers.push(server);++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("mcp_client.servers")+ );+}++#[tokio::test]+async fn disabled_channels_component_warns_when_a_provider_is_configured() {+ let mut config = Config::default();+ config.components.channels = false;+ config.channels_config.slack = Some(crate::config::SlackConfig {+ bot_token: "fixture-bot-token".into(),+ app_token: None,+ channel_id: None,+ allowed_users: Vec::new(),+ });++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("channels_config")+ );+}++#[tokio::test]+async fn disabled_voice_component_warns_when_a_provider_is_configured() {+ let mut config = Config::default();+ config.components.voice = false;+ let mut provider = crate::config::schema::voice_providers::VoiceProviderCreds::default();+ provider.slug = "test-provider".into();+ provider.endpoint = "https://voice.example.test".into();+ config.voice_providers.push(provider);++ let findings = run_check(config, "components/referenced-but-disabled").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Warn)+ .config_path+ .as_deref(),+ Some("voice_providers")+ );+}++#[tokio::test]+async fn missing_storage_driver_is_reported_without_opening_the_backend() {+ let _environment = EnvVarGuard::locked_unset_async(crate::storage::STORAGE_URL_VAR).await;+ let mut config = Config::default();+ config.storage.url = Some("mongodb://app:[email protected]/openhuman".into());++ let findings = run_check(config, "storage/url").await;++ #[cfg(not(feature = "storage-mongodb"))]+ {+ let error = finding(&findings, FindingSeverity::Error);+ assert!(error.message.contains("storage-mongodb"));+ assert!(!error.message.contains("private"));+ assert!(!error.message.contains("db.internal"));+ }+ #[cfg(feature = "storage-mongodb")]+ assert!(findings+ .iter()+ .any(|finding| finding.severity == FindingSeverity::Pass));+}++#[tokio::test]+async fn malformed_storage_url_is_reported_without_echoing_it() {+ let _environment = EnvVarGuard::locked_unset_async(crate::storage::STORAGE_URL_VAR).await;+ let mut config = Config::default();+ config.storage.url = Some("custom://secret-value".into());++ let findings = run_check(config, "storage/url").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("secret-value"));+}++// This fixture relies on POSIX mode bits; Windows readonly attributes do not revoke write ACLs.+#[cfg(unix)]+#[tokio::test]+async fn action_directory_without_write_access_is_an_error() {+ let dir = tempfile::tempdir().expect("temporary action directory");+ let mut config = Config::default();+ config.action_dir = dir.path().to_owned();+ let original_permissions = std::fs::metadata(dir.path()).unwrap().permissions();+ let mut permissions = original_permissions.clone();+ permissions.set_readonly(true);+ std::fs::set_permissions(dir.path(), permissions).unwrap();++ let findings = run_check(config, "workspace/action-dir").await;+ std::fs::set_permissions(dir.path(), original_permissions).unwrap();++ assert_eq!(+ finding(&findings, FindingSeverity::Error)+ .config_path+ .as_deref(),+ Some("action_dir")+ );+ #[cfg(unix)]+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);+}++#[tokio::test]+async fn missing_action_directory_is_reported_without_creating_it() {+ let dir = tempfile::tempdir().expect("temporary parent directory");+ let action_dir = dir.path().join("missing");+ let mut config = Config::default();+ config.action_dir = action_dir.clone();++ let findings = run_check(config, "workspace/action-dir").await;++ assert_eq!(+ finding(&findings, FindingSeverity::Error)+ .config_path+ .as_deref(),+ Some("action_dir")+ );+ assert!(!action_dir.exists());+}++#[tokio::test]+async fn both_master_key_environment_sources_are_reported_without_initializing_keys() {+ use crate::security::secret_storage::encrypted_file_backend::{+ MASTER_KEY_ENV, MASTER_KEY_FILE_ENV,+ };++ let _environment = EnvVarGuard::locked_unset_many_async(&[MASTER_KEY_ENV, MASTER_KEY_FILE_ENV])+ .await+ .with(MASTER_KEY_ENV, "do-not-read-inline");+ let workspace = tempfile::tempdir().expect("temporary workspace");+ let supplied_key_file = workspace.path().join("nested/operator.key");+ let _environment = _environment.with(MASTER_KEY_FILE_ENV, &supplied_key_file);+ let mut config = Config::default();+ config.workspace_dir = workspace.path().to_owned();+ let entries_before = workspace_entries(workspace.path());++ let findings = run_check(config, "secrets/master-key-env").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("do-not-read-inline"));+ assert!(!error+ .message+ .contains(&supplied_key_file.display().to_string()));+ assert_eq!(workspace_entries(workspace.path()), entries_before);+ assert!(!supplied_key_file.exists());+ assert!(!workspace.path().join("keyring/master.key").exists());+}++#[tokio::test]+async fn invalid_module_override_is_reported_without_echoing_its_path() {+ use crate::config::schema::ModuleOverride;++ let mut config = Config::default();+ config.modules.overrides.push(ModuleOverride {+ id: "tinydocs".into(),+ path: Some("/private/libmodule.so".into()),+ source: Some(crate::config::schema::ModuleSourceMode::Source),+ });++ let findings = run_check(config, "modules/override-invalid").await;++ let warning = finding(&findings, FindingSeverity::Warn);+ assert!(!warning.message.contains("/private/libmodule.so"));+}++#[tokio::test]+async fn source_fallback_is_reported_without_loading_modules() {+ use crate::config::schema::ModuleSourceMode;++ let source_dir = tempfile::tempdir().expect("empty module source directory");+ let _environment = EnvVarGuard::locked_unset_many_async(&[+ "OPENHUMAN_MODULE_SOURCE",+ "OPENHUMAN_MODULE_SOURCE_DIR",+ ])+ .await+ .with("OPENHUMAN_MODULE_SOURCE_DIR", source_dir.path());+ let mut config = Config::default();+ config.modules.source = ModuleSourceMode::Source;++ let findings = run_check(config, "modules/source-fallback").await;++ assert!(findings.iter().any(|finding| {+ finding.severity == FindingSeverity::Warn+ && (finding.message.contains("no source-built artifact")+ || finding.message.contains("source fallback"))+ }));+}++#[tokio::test]+async fn invalid_proxy_settings_are_reported_without_echoing_credentials() {+ let mut config = Config::default();+ config.proxy.http_proxy = Some("http://user:private@[invalid".into());++ let findings = run_check(config, "network/proxy").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("private"));+}++#[tokio::test]+async fn invalid_memory_root_is_reported_without_echoing_the_value() {+ let mut config = Config::default();+ config.memory.root = Some("private-invalid-root".into());++ let findings = run_check(config, "memory/root").await;++ let error = finding(&findings, FindingSeverity::Error);+ assert!(!error.message.contains("private-invalid-root"));+}diff --git a/crates/openhuman-core/src/doctor/connectivity_tests.rs b/crates/openhuman-core/src/doctor/connectivity_tests.rsnew file mode 100644index 0000000000..00894d9557--- /dev/null+++ b/crates/openhuman-core/src/doctor/connectivity_tests.rs@@ -0,0 +1,267 @@+use std::sync::Arc;++use async_trait::async_trait;++use super::contract::{DoctorCtx, DoctorOptions, FindingSeverity};+use super::runner;+use crate::config::schema::StorageConfig;+use crate::config::Config;++struct DownMemoryEngine {+ inner: tinymemory_api::conformance::ReferenceEngine,+ reason: String,+}++#[async_trait]+impl tinymemory_api::MemoryEngine for DownMemoryEngine {+ fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {+ self.inner.descriptor()+ }++ async fn health(&self) -> tinymemory_api::EngineHealth {+ tinymemory_api::EngineHealth::Down(self.reason.clone())+ }++ async fn recall(+ &self,+ request: tinymemory_api::RecallRequest,+ ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {+ self.inner.recall(request).await+ }++ async fn fetch(+ &self,+ request: tinymemory_api::FetchRequest,+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {+ self.inner.fetch(request).await+ }++ async fn store(+ &self,+ item: tinymemory_api::StoreItem,+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {+ self.inner.store(item).await+ }++ async fn forget(+ &self,+ target: tinymemory_api::ForgetTarget,+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {+ self.inner.forget(target).await+ }++ async fn list(+ &self,+ request: tinymemory_api::ListRequest,+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {+ self.inner.list(request).await+ }+}++fn snapshot_test_tree(+ root: &std::path::Path,+) -> std::collections::BTreeMap<std::path::PathBuf, Option<Vec<u8>>> {+ // SQLite read-only opens may update the derived `-shm` index or create+ // an empty `-wal`; the durable database and committed WAL remain pinned.+ fn walk(+ current: &std::path::Path,+ root: &std::path::Path,+ snapshot: &mut std::collections::BTreeMap<std::path::PathBuf, Option<Vec<u8>>>,+ ) {+ for entry in std::fs::read_dir(current).expect("read fixture directory") {+ let path = entry.expect("fixture entry").path();+ let relative = path+ .strip_prefix(root)+ .expect("fixture path is inside its root")+ .to_path_buf();+ let name = path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or_default();+ let is_sqlite_bookkeeping = name.ends_with("-shm")+ || (name.ends_with("-wal")+ && std::fs::metadata(&path).expect("fixture metadata").len() == 0);+ if is_sqlite_bookkeeping {+ continue;+ }+ if path.is_dir() {+ snapshot.insert(relative, None);+ walk(&path, root, snapshot);+ } else {+ snapshot.insert(+ relative,+ Some(std::fs::read(path).expect("read fixture file")),+ );+ }+ }+ }++ let mut snapshot = std::collections::BTreeMap::new();+ walk(root, root, &mut snapshot);+ snapshot+}++#[tokio::test]+async fn memory_health_check_reports_the_engine_down_reason() {+ let temp = tempfile::tempdir().expect("temp directory");+ let config = crate::memory::test_fixtures::config_in(&temp);+ let reason = "the configured memory service is unavailable";+ crate::memory::engine::install_test_engine(+ &config.workspace_dir,+ Arc::new(DownMemoryEngine {+ inner: tinymemory_api::conformance::ReferenceEngine::new(),+ reason: reason.to_owned(),+ }),+ );++ let report = runner::run(+ &DoctorCtx::from_config(config.clone()),+ DoctorOptions {+ only: vec!["memory/health".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("memory health result is represented in the report");+ crate::memory::engine::remove_test_engine(&config.workspace_dir);++ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "memory/health")+ .expect("the selected memory health check returns its own finding");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.contains(reason));+}++#[tokio::test]+async fn storage_connect_check_does_not_change_the_selected_sqlite_tree() {+ let temp = tempfile::tempdir().expect("temp directory");+ let workspace = temp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace");+ let database_dir = temp.path().join("selected-storage");+ let url = format!("sqlite:{}", database_dir.display());+ let backend = crate::storage::open(&url)+ .await+ .expect("create a local SQLite fixture using the normal setup path");+ drop(backend);+ let before = snapshot_test_tree(temp.path());+ let config = Config {+ action_dir: workspace.clone(),+ workspace_dir: workspace,+ storage: StorageConfig {+ url: Some(url),+ ..StorageConfig::default()+ },+ ..Config::default()+ };++ let report = runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ only: vec!["storage/connect".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("storage check is represented in the report");+ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "storage/connect")+ .expect("the selected storage check returns its own finding");+ assert_eq!(finding.severity, FindingSeverity::Pass);+ assert_eq!(before, snapshot_test_tree(temp.path()));+}++#[tokio::test]+async fn storage_connect_check_reports_corrupt_sqlite_without_changing_it() {+ let temp = tempfile::tempdir().expect("temp directory");+ let workspace = temp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace");+ let file = temp.path().join("corrupt.db");+ std::fs::write(&file, b"not a sqlite database").expect("write corrupt database fixture");+ let before = snapshot_test_tree(temp.path());+ let config = Config {+ action_dir: workspace.clone(),+ workspace_dir: workspace,+ storage: StorageConfig {+ url: Some(format!("sqlite:{}", file.display())),+ ..StorageConfig::default()+ },+ ..Config::default()+ };++ let report = runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ only: vec!["storage/connect".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("storage failure is represented in the report");+ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "storage/connect")+ .expect("the selected storage check returns its own finding");++ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(!finding.message.contains(file.to_string_lossy().as_ref()));+ assert_eq!(before, snapshot_test_tree(temp.path()));+}++#[tokio::test]+async fn storage_layout_check_warns_when_a_migration_is_pending() {+ let temp = tempfile::tempdir().expect("temp directory");+ let target = crate::storage::layout::Target::new(temp.path(), "u1");+ let workspace = target.workspace();+ std::fs::create_dir_all(&workspace).expect("create workspace");+ std::fs::create_dir_all(&target.profile_dir).expect("create profile directory");+ let config = Config {+ action_dir: workspace.clone(),+ config_path: target.profile_dir.join("config.toml"),+ workspace_dir: workspace,+ ..Config::default()+ };+ let state_path = target+ .profile_dir+ .join(crate::storage::layout::state::STATE_FILE);+ let error = crate::storage::layout::migrate(+ &target,+ &config,+ &crate::storage::layout::Options {+ crash_after: Some(crate::storage::layout::Step::Import),+ ..crate::storage::layout::Options::default()+ },+ )+ .await+ .expect_err("the fixture migration should stop after its import step");+ assert!(matches!(+ error,+ crate::storage::layout::LayoutError::InjectedCrash(crate::storage::layout::Step::Import)+ ));+ let before = std::fs::read(&state_path).expect("read migration state");++ let report = runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ only: vec!["storage/layout".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("layout check is represented in the report");++ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "storage/layout")+ .expect("the selected layout check returns its own finding");+ assert_eq!(finding.severity, FindingSeverity::Warn);+ assert_eq!(+ before,+ std::fs::read(state_path).expect("migration state remains readable")+ );+}diff --git a/crates/openhuman-core/src/doctor/contract.rs b/crates/openhuman-core/src/doctor/contract.rsnew file mode 100644index 0000000000..99a3048ba7--- /dev/null+++ b/crates/openhuman-core/src/doctor/contract.rs@@ -0,0 +1,484 @@+//! Public types for doctor checks and their versioned report.++use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;+use serde::{Deserialize, Serialize};++use crate::config::schema::load::ProvenanceSource;+use crate::config::schema::profile_layout::LayoutVersion;+use crate::config::Config;+use crate::core::runtime::{ComponentSet, CoreContext};++/// The maximum cost a caller permits for a doctor run.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DoctorTier {+ /// Local configuration and filesystem inspection.+ Static,+ /// Bounded, read-only connectivity checks. This is the default tier.+ Connect,+ /// Opt-in checks that can incur a cost or write disposable test data.+ Live,+}++impl DoctorTier {+ pub(crate) const fn timeout(self) -> Duration {+ match self {+ Self::Static => Duration::from_secs(5),+ Self::Connect => Duration::from_secs(10),+ Self::Live => Duration::from_secs(60),+ }+ }++ pub(crate) const fn includes(self, check_tier: Self) -> bool {+ match self {+ Self::Static => matches!(check_tier, Self::Static),+ Self::Connect => matches!(check_tier, Self::Static | Self::Connect),+ Self::Live => true,+ }+ }+}++/// A component whose disabled state prevents a check from running.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ComponentId {+ Flows,+ Tinyflows,+ Memes,+ Documents,+ Search,+ Mcp,+ Connectors,+ Hosting,+ Juice,+ Memory,+ Wallet,+ Computer,+ Sandbox,+ Channels,+ Skills,+ Voice,+ Eventqueues,+}++impl ComponentId {+ pub(crate) fn enabled(self, components: &ComponentSet) -> bool {+ match self {+ Self::Flows => components.flows,+ Self::Tinyflows => components.tinyflows,+ Self::Memes => components.memes,+ Self::Documents => components.documents,+ Self::Search => components.search,+ Self::Mcp => components.mcp,+ Self::Connectors => components.connectors,+ Self::Hosting => components.hosting,+ Self::Juice => components.juice,+ Self::Memory => components.memory,+ Self::Wallet => components.wallet,+ Self::Computer => components.computer,+ Self::Sandbox => components.sandbox,+ Self::Channels => components.channels,+ Self::Skills => components.skills,+ Self::Voice => components.voice,+ Self::Eventqueues => components.eventqueues,+ }+ }++ pub(crate) const fn as_str(self) -> &'static str {+ match self {+ Self::Flows => "flows",+ Self::Tinyflows => "tinyflows",+ Self::Memes => "memes",+ Self::Documents => "documents",+ Self::Search => "search",+ Self::Mcp => "mcp",+ Self::Connectors => "connectors",+ Self::Hosting => "hosting",+ Self::Juice => "juice",+ Self::Memory => "memory",+ Self::Wallet => "wallet",+ Self::Computer => "computer",+ Self::Sandbox => "sandbox",+ Self::Channels => "channels",+ Self::Skills => "skills",+ Self::Voice => "voice",+ Self::Eventqueues => "eventqueues",+ }+ }+}++/// Finding severity in the v2 wire contract.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum FindingSeverity {+ Pass,+ Info,+ Warn,+ Error,+ Skipped,+}++/// The non-secret origin of a resolved configuration value.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ValueSource {+ Cli,+ Env,+ Dotenv,+ File,+ Default,+}++/// The redacted source kind for the effective configuration.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DoctorConfigSource {+ Profile,+ Tenant,+}++/// Result of validating a selected desktop profile before other checks run.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum DoctorProfileStatus {+ Valid,+ Missing,+ UnknownLayoutMarker,+ InvalidConfig,+}++/// One operator-facing result from a check.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Finding {+ pub check_id: String,+ pub severity: FindingSeverity,+ pub message: String,+ pub fix_hint: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub config_path: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub value_source: Option<ValueSource>,+ pub duration_ms: u64,+ pub affects: Vec<String>,+}++impl Finding {+ pub fn new(+ check_id: impl Into<String>,+ severity: FindingSeverity,+ message: impl Into<String>,+ fix_hint: impl Into<String>,+ ) -> Self {+ Self {+ check_id: check_id.into(),+ severity,+ message: message.into(),+ fix_hint: fix_hint.into(),+ config_path: None,+ value_source: None,+ duration_ms: 0,+ affects: Vec::new(),+ }+ }++ pub fn pass(check_id: impl Into<String>, message: impl Into<String>) -> Self {+ Self::new(+ check_id,+ FindingSeverity::Pass,+ message,+ "No action required.",+ )+ }++ pub fn skipped(+ check_id: impl Into<String>,+ message: impl Into<String>,+ fix_hint: impl Into<String>,+ ) -> Self {+ Self::new(check_id, FindingSeverity::Skipped, message, fix_hint)+ }++ pub fn error(+ check_id: impl Into<String>,+ message: impl Into<String>,+ fix_hint: impl Into<String>,+ ) -> Self {+ Self::new(check_id, FindingSeverity::Error, message, fix_hint)+ }+}++/// Counts findings by v2 severity.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct DoctorSummary {+ pub pass: usize,+ pub info: usize,+ pub warn: usize,+ pub error: usize,+ pub skipped: usize,+}++impl DoctorSummary {+ pub(crate) fn from_findings(findings: &[Finding]) -> Self {+ let mut summary = Self::default();+ for finding in findings {+ match finding.severity {+ FindingSeverity::Pass => summary.pass += 1,+ FindingSeverity::Info => summary.info += 1,+ FindingSeverity::Warn => summary.warn += 1,+ FindingSeverity::Error => summary.error += 1,+ FindingSeverity::Skipped => summary.skipped += 1,+ }+ }+ summary+ }+}++/// Versioned, ordered report shared by RPC and every host surface.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct DoctorReport {+ pub schema_version: u8,+ pub profile: Option<String>,+ pub config_source: DoctorConfigSource,+ /// On-disk desktop profile layout, when the selected context has one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub profile_layout_version: Option<u8>,+ /// Stable source label that selected the config directory, when known.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub config_resolution_source: Option<String>,+ pub tier: DoctorTier,+ pub checks_run: Vec<String>,+ pub checks_skipped: Vec<String>,+ pub findings: Vec<Finding>,+ pub summary: DoctorSummary,+ pub ok: bool,+}++/// Inputs shared by selected checks in one doctor run.+#[derive(Debug, Clone)]+pub struct DoctorCtx {+ config: Arc<Config>,+ components: ComponentSet,+ profile: Option<String>,+ config_source: DoctorConfigSource,+ profile_layout_version: Option<LayoutVersion>,+ profile_resolution_source: Option<String>,+ profile_status: Option<DoctorProfileStatus>,+}++impl DoctorCtx {+ /// Creates a check context from the effective config and active core+ /// context. An unscoped local configuration reports `profile` as its+ /// source; a scoped SaaS context reports `tenant`.+ pub fn from_config(config: Config) -> Self {+ let (profile_layout_version, profile_resolution_source) = config.doctor_profile_metadata();+ let core = CoreContext::current();+ let profile = core+ .as_ref()+ .and_then(|context| context.profile().map(str::to_owned));+ let config_source = if profile.is_some() {+ DoctorConfigSource::Tenant+ } else {+ DoctorConfigSource::Profile+ };+ let components = core+ .as_ref()+ .map_or_else(ComponentSet::all, |context| context.components());+ Self {+ config: Arc::new(config),+ components,+ profile,+ config_source,+ profile_layout_version,+ profile_resolution_source,+ profile_status: None,+ }+ }++ /// Creates a context from a config and explicit component set without+ /// consulting the ambient [`CoreContext`]. Use this when the caller has+ /// already selected and loaded the profile context.+ pub fn from_config_with_components(config: Config, components: ComponentSet) -> Self {+ let (profile_layout_version, profile_resolution_source) = config.doctor_profile_metadata();+ Self {+ config: Arc::new(config),+ components,+ profile: None,+ config_source: DoctorConfigSource::Profile,+ profile_layout_version,+ profile_resolution_source,+ profile_status: None,+ }+ }++ /// Pins this run to an explicit profile or tenant id and source.+ pub fn with_profile(mut self, profile: impl Into<String>, source: DoctorConfigSource) -> Self {+ self.profile = Some(profile.into());+ self.config_source = source;+ self+ }++ /// Adds profile layout and directory-resolution provenance for the+ /// `config/source` check.+ pub fn with_profile_metadata(+ mut self,+ layout_version: Option<LayoutVersion>,+ resolution_source: Option<String>,+ ) -> Self {+ self.profile_layout_version = layout_version;+ self.profile_resolution_source = resolution_source;+ self+ }++ pub(crate) fn with_profile_status(mut self, status: DoctorProfileStatus) -> Self {+ self.profile_status = Some(status);+ self+ }++ pub fn with_components(mut self, components: ComponentSet) -> Self {+ self.components = components;+ self+ }++ /// The effective configuration inspected by this run.+ pub fn config(&self) -> &Config {+ &self.config+ }++ /// Returns the non-secret source for a logical config field path.+ ///+ /// Array indexes are normalized to the loader's `[]` notation. Filesystem+ /// paths are rejected because they identify a source location, not a+ /// resolved config value.+ pub(crate) fn value_source_for(&self, logical_path: &str) -> Option<ValueSource> {+ let path = normalize_logical_config_path(logical_path)?;+ let source = self.config.load_provenance().field(&path).source;+ Some(match source {+ ProvenanceSource::Cli => ValueSource::Cli,+ ProvenanceSource::Env => ValueSource::Env,+ ProvenanceSource::Dotenv => ValueSource::Dotenv,+ ProvenanceSource::File => ValueSource::File,+ ProvenanceSource::Default => ValueSource::Default,+ })+ }++ /// The component switches for this run.+ pub fn components(&self) -> ComponentSet {+ self.components+ }++ /// The effective profile or tenant id, when the active context has one.+ pub fn profile(&self) -> Option<&str> {+ self.profile.as_deref()+ }++ /// On-disk profile layout selected for this run, when applicable.+ pub fn profile_layout_version(&self) -> Option<LayoutVersion> {+ self.profile_layout_version+ }++ /// Directory-selection provenance for the effective profile, when known.+ pub fn profile_resolution_source(&self) -> Option<&str> {+ self.profile_resolution_source.as_deref()+ }++ pub(crate) fn config_source(&self) -> DoctorConfigSource {+ self.config_source+ }++ pub(crate) fn profile_status(&self) -> Option<DoctorProfileStatus> {+ self.profile_status+ }+}++fn normalize_logical_config_path(path: &str) -> Option<String> {+ if path.is_empty()+ || path.starts_with('.')+ || path.contains('/')+ || path.contains('\\')+ || path.ends_with(".toml")+ || path.ends_with(".env")+ {+ return None;+ }++ let mut normalized = String::with_capacity(path.len());+ let mut chars = path.chars().peekable();+ while let Some(character) = chars.next() {+ match character {+ '[' => {+ while chars.peek().is_some_and(char::is_ascii_digit) {+ chars.next();+ }+ if chars.next()? != ']' {+ return None;+ }+ normalized.push_str("[]");+ }+ ']' => return None,+ character+ if character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.') =>+ {+ normalized.push(character);+ }+ _ => return None,+ }+ }++ if normalized.starts_with('.') || normalized.ends_with('.') || normalized.contains("..") {+ return None;+ }+ Some(normalized)+}++/// Exact-id and tier filters for one report run.+#[derive(Debug, Clone)]+pub struct DoctorOptions {+ pub tier: DoctorTier,+ pub only: Vec<String>,+ pub skip: Vec<String>,+ /// Reserved for the profile loaders in #490/#491. The framework accepts+ /// the wire input; the host must resolve it before constructing `DoctorCtx`.+ pub profile: Option<String>,+}++impl Default for DoctorOptions {+ fn default() -> Self {+ Self {+ tier: DoctorTier::Connect,+ only: Vec::new(),+ skip: Vec::new(),+ profile: None,+ }+ }+}++/// A single registered doctor check.+#[async_trait]+pub trait DoctorCheck: Send + Sync {+ /// Stable lowercase `area/name` identifier.+ fn id(&self) -> &str;+ /// Display category for grouping in human-facing surfaces.+ fn category(&self) -> &str;+ /// Cost tier of this detector.+ fn tier(&self) -> DoctorTier;+ /// Component that must be enabled before detection can run.+ fn component_gate(&self) -> Option<ComponentId> {+ None+ }+ /// Per-check timeout. Defaults to the tier budget.+ fn timeout(&self) -> Duration {+ self.tier().timeout()+ }+ /// Whether this detector has a synchronous body that belongs on the+ /// blocking pool. Implement `detect_blocking` when this returns true.+ fn is_blocking(&self) -> bool {+ false+ }+ /// Run an asynchronous check.+ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding>;+ /// Run a blocking check on a Tokio blocking worker.+ fn detect_blocking(&self, _ctx: &DoctorCtx) -> Option<Vec<Finding>> {+ None+ }+}diff --git a/crates/openhuman-core/src/doctor/core.rs b/crates/openhuman-core/src/doctor/core.rsnew file mode 100644index 0000000000..7f61308a23--- /dev/null+++ b/crates/openhuman-core/src/doctor/core.rs@@ -0,0 +1,5 @@+//! Stable model-probe wire types retained for the `doctor_models` RPC stub.++mod types;++pub use types::{ModelProbeEntry, ModelProbeOutcome, ModelProbeReport, ModelProbeSummary};diff --git a/crates/openhuman-core/src/doctor/core/types.rs b/crates/openhuman-core/src/doctor/core/types.rsnew file mode 100644index 0000000000..cdc733b58b--- /dev/null+++ b/crates/openhuman-core/src/doctor/core/types.rs@@ -0,0 +1,32 @@+//! Stable wire types for the currently unavailable model-probe method.++use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum ModelProbeOutcome {+ Ok,+ Skipped,+ AuthOrAccess,+ Error,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ModelProbeEntry {+ pub provider: String,+ pub outcome: ModelProbeOutcome,+ pub message: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ModelProbeSummary {+ pub ok: usize,+ pub skipped: usize,+ pub auth_or_access: usize,+ pub errors: usize,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ModelProbeReport {+ pub entries: Vec<ModelProbeEntry>,+ pub summary: ModelProbeSummary,+}diff --git a/crates/openhuman-core/src/doctor/embeddings_config_tests.rs b/crates/openhuman-core/src/doctor/embeddings_config_tests.rsnew file mode 100644index 0000000000..11eafd5094--- /dev/null+++ b/crates/openhuman-core/src/doctor/embeddings_config_tests.rs@@ -0,0 +1,69 @@+use crate::config::Config;+use crate::doctor::runner;+use crate::doctor::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};++const EMBEDDINGS_CONFIG: &str = "embeddings/config";++async fn run_only(config: Config) -> Vec<Finding> {+ let context = DoctorCtx::from_config(config);+ runner::run(+ &context,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![EMBEDDINGS_CONFIG.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("the selected doctor check should run")+ .findings+}++fn finding(findings: &[Finding]) -> &Finding {+ findings+ .iter()+ .find(|finding| finding.check_id == EMBEDDINGS_CONFIG)+ .unwrap_or_else(|| panic!("expected finding from {EMBEDDINGS_CONFIG}: {findings:#?}"))+}++#[tokio::test]+async fn an_unknown_embedding_provider_reports_its_config_path() {+ let mut config = Config::default();+ config.memory.embedding_provider = "nope".to_owned();++ let findings = run_only(config).await;+ let result = finding(&findings);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(+ result.config_path.as_deref(),+ Some("memory.embedding_provider")+ );+}++#[tokio::test]+async fn missing_embedding_model_and_dimensions_are_reported() {+ let mut config = Config::default();+ config.memory.embedding_model.clear();+ config.memory.embedding_dimensions = 0;++ let findings = run_only(config).await;+ let paths = findings+ .iter()+ .filter(|result| result.check_id == EMBEDDINGS_CONFIG)+ .filter_map(|result| result.config_path.as_deref())+ .collect::<Vec<_>>();++ assert!(+ paths.contains(&"memory.embedding_model"),+ "missing model path in findings: {findings:#?}"+ );+ assert!(+ paths.contains(&"memory.embedding_dimensions"),+ "missing dimensions path in findings: {findings:#?}"+ );+ assert!(findings+ .iter()+ .filter(|result| result.check_id == EMBEDDINGS_CONFIG)+ .all(|result| result.severity == FindingSeverity::Error));+}diff --git a/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs b/crates/openhuman-core/src/doctor/inference_auth_error_tests.rsnew file mode 100644index 0000000000..4996597705--- /dev/null+++ b/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs@@ -0,0 +1,641 @@+use super::{ops::doctor_report_with_options, DoctorOptions, FindingSeverity};+use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::config::Config;+use crate::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};+use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ routing::get,+ Json, Router,+};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use std::time::Duration;++#[derive(Clone)]+struct CatalogServerState {+ status: StatusCode,+ body: serde_json::Value,+ delay: Duration,+ requests: Arc<AtomicUsize>,+ authorizations: Arc<std::sync::Mutex<Vec<Option<String>>>>,+}++async fn catalog_handler(State(state): State<CatalogServerState>, headers: HeaderMap) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ if !state.delay.is_zero() {+ tokio::time::sleep(state.delay).await;+ }+ state+ .authorizations+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .push(+ headers+ .get("authorization")+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned),+ );+ (state.status, Json(state.body)).into_response()+}++async fn missing_catalog_handler(State(state): State<CatalogServerState>) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ StatusCode::NOT_FOUND.into_response()+}++async fn spawn_catalog_server(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+) -> (String, CatalogServerState) {+ spawn_catalog_server_with_delay(status, body, has_models_route, Duration::ZERO).await+}++async fn spawn_catalog_server_with_delay(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+ delay: Duration,+) -> (String, CatalogServerState) {+ let state = CatalogServerState {+ status,+ body,+ delay,+ requests: Arc::new(AtomicUsize::new(0)),+ authorizations: Arc::new(std::sync::Mutex::new(Vec::new())),+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local catalog server");+ let address = listener.local_addr().expect("local server address");+ let app = if has_models_route {+ Router::new().route("/v1/models", get(catalog_handler))+ } else {+ Router::new()+ .route("/v1/health", get(catalog_handler))+ .fallback(get(missing_catalog_handler))+ };+ let app = app.with_state(state.clone());+ tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("serve local catalog");+ });+ (format!("http://{address}/v1"), state)+}++fn temporary_config() -> (tempfile::TempDir, Config) {+ let root = tempfile::tempdir().expect("temporary doctor fixture");+ let mut config = Config {+ config_path: root.path().join("config.toml"),+ workspace_dir: root.path().join("workspace"),+ action_dir: root.path().join("workspace"),+ ..Config::default()+ };+ config.cloud_providers = Vec::new();+ (root, config)+}++fn config_for_catalog(+ endpoint: String,+ provider_id: &str,+ slug: &str,+) -> (tempfile::TempDir, Config) {+ let (root, mut config) = temporary_config();+ config.secrets.encrypt = false;+ config.cloud_providers = vec![CloudProviderCreds {+ id: provider_id.to_owned(),+ slug: slug.to_owned(),+ label: "Doctor catalog fixture".to_owned(),+ endpoint,+ auth_style: AuthStyle::None,+ default_model: None,+ }];+ (root, config)+}++fn catalog_body(ids: &[&str]) -> serde_json::Value {+ serde_json::json!({+ "data": ids.iter().map(|id| serde_json::json!({ "id": id })).collect::<Vec<_>>()+ })+}++fn store_provider_key(config: &Config, slug: &str, token: &str) {+ AuthService::from_config(config)+ .store_provider_token(+ &crate::inference::provider::factory::auth_key_for_slug(slug),+ DEFAULT_AUTH_PROFILE_NAME,+ token,+ std::collections::HashMap::new(),+ true,+ )+ .expect("seed scoped provider credential");+}++fn auth_profiles_path(config: &Config) -> std::path::PathBuf {+ config+ .config_path+ .parent()+ .expect("fixture config parent")+ .join("auth-profiles.json")+}++fn profile_context(+ config: Config,+ profile_id: &str,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++fn workspace_context(config: Config) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ ))+}++fn profile_context_with_extensions(+ config: Config,+ profile_id: &str,+ extensions: crate::core::slots::Extensions,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++fn register_test_inspection_catalog(+ extensions: &crate::core::slots::Extensions,+ provider: &str,+ endpoint: String,+) -> Arc<AtomicUsize> {+ use crate::inference::registry::{+ register_inspection_catalog_in, InspectionCatalogError, InspectionCatalogListing,+ PreparedInspectionCatalog,+ };++ let requests = Arc::new(AtomicUsize::new(0));+ let request_count = Arc::clone(&requests);+ let provider_id = provider.to_owned();+ let listing: InspectionCatalogListing = Arc::new(move |config, request| {+ let endpoint = endpoint.clone();+ let provider_id = provider_id.clone();+ let request_count = Arc::clone(&request_count);+ Box::pin(async move {+ assert!(+ request.provider_key.is_empty(),+ "fixture uses the separate config credential identity"+ );+ let credential = config.api_key.clone();+ let cache_endpoint = endpoint.clone();+ let client = request.client.clone();+ let fetch_endpoint = endpoint.clone();+ let fetch_credential = credential.clone();+ let fetch_count = Arc::clone(&request_count);+ let fetch = Box::pin(async move {+ fetch_count.fetch_add(1, Ordering::SeqCst);+ let mut get = client.get(fetch_endpoint);+ if let Some(credential) = fetch_credential.as_deref() {+ get = get.bearer_auth(credential);+ }+ let response = get+ .send()+ .await+ .map_err(|_| InspectionCatalogError::Unavailable)?;+ let status = response.status();+ if status == StatusCode::NOT_FOUND {+ return Err(InspectionCatalogError::NoCatalog);+ }+ if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {+ return Err(InspectionCatalogError::AuthOrAccess);+ }+ if !status.is_success() {+ return Err(InspectionCatalogError::Failure);+ }+ let body = response+ .json::<serde_json::Value>()+ .await+ .map_err(|_| InspectionCatalogError::Failure)?;+ let models = body+ .get("data")+ .cloned()+ .unwrap_or_else(|| serde_json::json!([]));+ Ok(crate::core::Outcome::new(+ serde_json::json!({ "models": models }),+ Vec::new(),+ ))+ });+ Ok(PreparedInspectionCatalog::new(+ &provider_id,+ &cache_endpoint,+ credential.as_deref(),+ fetch,+ ))+ })+ });+ register_inspection_catalog_in(extensions, provider, listing);+ requests+}++async fn report_for_profile(+ config: &Config,+ profile_id: &str,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ report_for_context(config, profile_context(config.clone(), profile_id), options).await+}++async fn report_for_context(+ config: &Config,+ context: std::sync::Arc<crate::core::runtime::CoreContext>,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ crate::core::runtime::CoreContext::scope(context, async {+ doctor_report_with_options(config, options).await+ })+ .await+ .expect("doctor report for selected profile")+}++#[tokio::test]+async fn process_auth_error_is_not_attributed_across_desktop_workspaces() {+ let provider = "doctor-497-profile-scoped-auth-fixture";+ crate::inference::auth_error_registry::clear(provider);+ let (_temp_a, config_a) = temporary_config();+ let (_temp_b, config_b) = temporary_config();++ let first_episode =+ crate::core::runtime::CoreContext::scope(workspace_context(config_a.clone()), async {+ crate::inference::auth_error_registry::record(provider, 401)+ })+ .await;+ assert!(+ first_episode,+ "workspace A begins the process notification episode"+ );++ let report_b_without_failure = report_for_context(+ &config_b,+ workspace_context(config_b.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_b_without_failure+ .value+ .checks_run+ .iter()+ .any(|id| id == "inference/auth-errors"));+ assert!(report_b_without_failure+ .value+ .findings+ .iter()+ .all(|finding| {+ finding.check_id != "inference/auth-errors"+ || finding.severity != FindingSeverity::Error+ }));+ assert!(report_b_without_failure+ .value+ .findings+ .iter()+ .all(|finding| {+ !finding+ .message+ .contains(config_a.workspace_dir.to_string_lossy().as_ref())+ && !finding+ .message+ .contains(config_b.workspace_dir.to_string_lossy().as_ref())+ }));++ let report_a = report_for_context(+ &config_a,+ workspace_context(config_a.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_a.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors" && finding.severity == FindingSeverity::Error+ }));++ let second_profile_episode =+ crate::core::runtime::CoreContext::scope(workspace_context(config_b.clone()), async {+ crate::inference::auth_error_registry::record(provider, 403)+ })+ .await;+ assert!(+ !second_profile_episode,+ "per-workspace attribution must not re-arm the process notification latch"+ );+ let report_b_after_failure = report_for_context(+ &config_b,+ workspace_context(config_b.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_b_after_failure.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors" && finding.severity == FindingSeverity::Error+ }));+ let report_a_after_b_failure = report_for_context(+ &config_a,+ workspace_context(config_a.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_a_after_b_failure+ .value+ .findings+ .iter()+ .any(|finding| {+ finding.check_id == "inference/auth-errors"+ && finding.severity == FindingSeverity::Error+ }));+ assert_eq!(+ crate::inference::auth_error_registry::snapshot()+ .iter()+ .filter(|error| error.provider == provider)+ .count(),+ 1,+ "the existing process snapshot should remain one entry per provider"+ );+ crate::inference::auth_error_registry::clear(provider);+}++#[tokio::test]+async fn process_auth_error_is_not_attributed_across_config_roots_sharing_a_workspace() {+ let provider = "doctor-497-config-root-auth-fixture";+ crate::inference::auth_error_registry::clear(provider);+ let (_temp_a, config_a) = temporary_config();+ let (_temp_b, mut config_b) = temporary_config();+ config_b.workspace_dir = config_a.workspace_dir.clone();++ let first =+ crate::core::runtime::CoreContext::scope(workspace_context(config_a.clone()), async {+ crate::inference::auth_error_registry::record(provider, 401)+ })+ .await;+ assert!(first);++ let report_b = report_for_context(+ &config_b,+ workspace_context(config_b.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_b.value.findings.iter().all(|finding| {+ finding.check_id != "inference/auth-errors" || finding.severity != FindingSeverity::Error+ }));++ let report_a = report_for_context(+ &config_a,+ workspace_context(config_a.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_a.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors" && finding.severity == FindingSeverity::Error+ }));+ crate::inference::auth_error_registry::clear(provider);+}++#[tokio::test]+async fn normal_boot_workspace_without_embedder_config_keeps_auth_error_attribution() {+ let provider = "doctor-497-normal-boot-auth-fixture";+ crate::inference::auth_error_registry::clear(provider);+ let (_temp, config) = temporary_config();+ let context = crate::core::runtime::CoreContext::for_test_with_boot_config_path(+ crate::core::runtime::DomainSet::full(),+ config.workspace_dir.clone(),+ config.config_path.clone(),+ );+ assert!(+ crate::core::runtime::CoreContext::scope(context, async {+ assert!(crate::core::runtime::CoreContext::current_embedder_config().is_none());+ crate::inference::auth_error_registry::record(provider, 401)+ })+ .await+ );++ let report = report_for_context(+ &config,+ workspace_context(config.clone()),+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors" && finding.severity == FindingSeverity::Error+ }));+ crate::inference::auth_error_registry::clear(provider);+}++#[tokio::test]+async fn process_auth_error_is_attributed_to_the_matching_saas_profile() {+ let provider = "doctor-497-saas-auth-fixture";+ crate::inference::auth_error_registry::clear(provider);+ let (_temp, config) = temporary_config();++ let first_episode = crate::core::runtime::CoreContext::scope(+ profile_context(config.clone(), "tenant-a"),+ async { crate::inference::auth_error_registry::record(provider, 401) },+ )+ .await;+ assert!(first_episode);++ let report_b_without_failure = report_for_profile(+ &config,+ "tenant-b",+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_b_without_failure+ .value+ .checks_run+ .iter()+ .any(|id| id == "inference/auth-errors"));+ assert!(report_b_without_failure+ .value+ .findings+ .iter()+ .all(|finding| {+ finding.check_id != "inference/auth-errors"+ || finding.severity != FindingSeverity::Error+ }));+ assert!(report_b_without_failure+ .value+ .findings+ .iter()+ .all(|finding| {+ !finding.message.contains("tenant-a") && !finding.message.contains("tenant-b")+ }));++ let report_a = report_for_profile(+ &config,+ "tenant-a",+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_a.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors" && finding.severity == FindingSeverity::Error+ }));++ let second_profile_episode = crate::core::runtime::CoreContext::scope(+ profile_context(config.clone(), "tenant-b"),+ async { crate::inference::auth_error_registry::record(provider, 403) },+ )+ .await;+ assert!(!second_profile_episode);+ let report_b_after_failure = report_for_profile(+ &config,+ "tenant-b",+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_b_after_failure.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors" && finding.severity == FindingSeverity::Error+ }));+ let report_a_after_b_failure = report_for_profile(+ &config,+ "tenant-a",+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ assert!(report_a_after_b_failure+ .value+ .findings+ .iter()+ .any(|finding| {+ finding.check_id == "inference/auth-errors"+ && finding.severity == FindingSeverity::Error+ }));+ assert_eq!(+ crate::inference::auth_error_registry::snapshot()+ .iter()+ .filter(|error| error.provider == provider)+ .count(),+ 1+ );+ crate::inference::auth_error_registry::clear(provider);+}++#[tokio::test]+async fn an_unscoped_legacy_auth_error_is_reported_without_blame_to_profile_b() {+ let provider = "doctor-497-unscoped-auth-fixture";+ crate::inference::auth_error_registry::clear(provider);+ crate::inference::auth_error_registry::record(provider, 401);+ let (_temp, config) = temporary_config();++ let report = report_for_profile(+ &config,+ "tenant-b",+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;++ assert!(report+ .value+ .checks_run+ .iter()+ .any(|id| id == "inference/auth-errors"));+ assert!(report.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors"+ && finding.severity == FindingSeverity::Info+ && !finding.message.contains("tenant-b")+ }));+ assert!(report.value.findings.iter().all(|finding| {+ finding.check_id != "inference/auth-errors" || finding.severity != FindingSeverity::Error+ }));+ crate::inference::auth_error_registry::clear(provider);+}++#[tokio::test]+async fn recorded_provider_auth_errors_are_reported_as_errors() {+ let providers = ["doctor-497-auth-error-one", "doctor-497-auth-error-two"];+ for provider in providers {+ crate::inference::auth_error_registry::clear(provider);+ }+ let (_temp, config) = temporary_config();+ let recorded = crate::core::runtime::CoreContext::scope(+ profile_context(config.clone(), "doctor-auth-error-profile"),+ async {+ providers.map(|provider| crate::inference::auth_error_registry::record(provider, 401))+ },+ )+ .await;+ assert_eq!(recorded, [true, true]);+ let report = report_for_profile(+ &config,+ "doctor-auth-error-profile",+ DoctorOptions {+ only: vec!["inference/auth-errors".into()],+ ..DoctorOptions::default()+ },+ )+ .await;++ for provider in providers {+ assert!(report.value.findings.iter().any(|finding| {+ finding.check_id == "inference/auth-errors"+ && finding.severity == FindingSeverity::Error+ && finding.message.contains(provider)+ && !finding.message.contains("credentials rejected")+ }));+ crate::inference::auth_error_registry::clear(provider);+ }+}diff --git a/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs b/crates/openhuman-core/src/doctor/inference_catalog_test_support.rsnew file mode 100644index 0000000000..f3ea1698da--- /dev/null+++ b/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs@@ -0,0 +1,288 @@+use super::{ops::doctor_report_with_options, DoctorOptions};+use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::config::Config;+use crate::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};+use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ routing::get,+ Json, Router,+};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use std::time::Duration;++#[derive(Clone)]+pub(super) struct CatalogServerState {+ pub(super) status: StatusCode,+ pub(super) body: serde_json::Value,+ pub(super) delay: Duration,+ pub(super) requests: Arc<AtomicUsize>,+ pub(super) authorizations: Arc<std::sync::Mutex<Vec<Option<String>>>>,+}++pub(super) async fn catalog_handler(+ State(state): State<CatalogServerState>,+ headers: HeaderMap,+) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ if !state.delay.is_zero() {+ tokio::time::sleep(state.delay).await;+ }+ state+ .authorizations+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .push(+ headers+ .get("authorization")+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned),+ );+ (state.status, Json(state.body)).into_response()+}++pub(super) async fn missing_catalog_handler(State(state): State<CatalogServerState>) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ StatusCode::NOT_FOUND.into_response()+}++pub(super) async fn spawn_catalog_server(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+) -> (String, CatalogServerState) {+ spawn_catalog_server_with_delay(status, body, has_models_route, Duration::ZERO).await+}++pub(super) async fn spawn_catalog_server_with_delay(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+ delay: Duration,+) -> (String, CatalogServerState) {+ let state = CatalogServerState {+ status,+ body,+ delay,+ requests: Arc::new(AtomicUsize::new(0)),+ authorizations: Arc::new(std::sync::Mutex::new(Vec::new())),+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local catalog server");+ let address = listener.local_addr().expect("local server address");+ let app = if has_models_route {+ Router::new().route("/v1/models", get(catalog_handler))+ } else {+ Router::new()+ .route("/v1/health", get(catalog_handler))+ .fallback(get(missing_catalog_handler))+ };+ let app = app.with_state(state.clone());+ tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("serve local catalog");+ });+ (format!("http://{address}/v1"), state)+}++pub(super) fn temporary_config() -> (tempfile::TempDir, Config) {+ let root = tempfile::tempdir().expect("temporary doctor fixture");+ let mut config = Config {+ config_path: root.path().join("config.toml"),+ workspace_dir: root.path().join("workspace"),+ action_dir: root.path().join("workspace"),+ ..Config::default()+ };+ config.cloud_providers = Vec::new();+ config.default_model = None;+ config.model_routes.clear();+ (root, config)+}++pub(super) fn config_for_catalog(+ endpoint: String,+ provider_id: &str,+ slug: &str,+) -> (tempfile::TempDir, Config) {+ let (root, mut config) = temporary_config();+ config.secrets.encrypt = false;+ config.cloud_providers = vec![CloudProviderCreds {+ id: provider_id.to_owned(),+ slug: slug.to_owned(),+ label: "Doctor catalog fixture".to_owned(),+ endpoint,+ auth_style: AuthStyle::None,+ default_model: None,+ }];+ (root, config)+}++pub(super) fn catalog_body(ids: &[&str]) -> serde_json::Value {+ serde_json::json!({+ "data": ids.iter().map(|id| serde_json::json!({ "id": id })).collect::<Vec<_>>()+ })+}++pub(super) fn store_provider_key(config: &Config, slug: &str, token: &str) {+ AuthService::from_config(config)+ .store_provider_token(+ &crate::inference::provider::factory::auth_key_for_slug(slug),+ DEFAULT_AUTH_PROFILE_NAME,+ token,+ std::collections::HashMap::new(),+ true,+ )+ .expect("seed scoped provider credential");+}++pub(super) fn auth_profiles_path(config: &Config) -> std::path::PathBuf {+ config+ .config_path+ .parent()+ .expect("fixture config parent")+ .join("auth-profiles.json")+}++pub(super) fn profile_context(+ config: Config,+ profile_id: &str,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++pub(super) fn workspace_context(+ config: Config,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ ))+}++pub(super) fn profile_context_with_extensions(+ config: Config,+ profile_id: &str,+ extensions: crate::core::slots::Extensions,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++pub(super) fn register_test_inspection_catalog(+ extensions: &crate::core::slots::Extensions,+ provider: &str,+ endpoint: String,+) -> Arc<AtomicUsize> {+ use crate::inference::registry::{+ register_inspection_catalog_in, InspectionCatalogError, InspectionCatalogListing,+ PreparedInspectionCatalog,+ };++ let requests = Arc::new(AtomicUsize::new(0));+ let request_count = Arc::clone(&requests);+ let provider_id = provider.to_owned();+ let listing: InspectionCatalogListing = Arc::new(move |config, request| {+ let endpoint = endpoint.clone();+ let provider_id = provider_id.clone();+ let request_count = Arc::clone(&request_count);+ Box::pin(async move {+ assert!(+ request.provider_key.is_empty(),+ "fixture uses the separate config credential identity"+ );+ let credential = config.api_key.clone();+ let cache_endpoint = endpoint.clone();+ let client = request.client.clone();+ let fetch_endpoint = endpoint.clone();+ let fetch_credential = credential.clone();+ let fetch_count = Arc::clone(&request_count);+ let fetch = Box::pin(async move {+ fetch_count.fetch_add(1, Ordering::SeqCst);+ let mut get = client.get(fetch_endpoint);+ if let Some(credential) = fetch_credential.as_deref() {+ get = get.bearer_auth(credential);+ }+ let response = get+ .send()+ .await+ .map_err(|_| InspectionCatalogError::Unavailable)?;+ let status = response.status();+ if status == StatusCode::NOT_FOUND {+ return Err(InspectionCatalogError::NoCatalog);+ }+ if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {+ return Err(InspectionCatalogError::AuthOrAccess);+ }+ if !status.is_success() {+ return Err(InspectionCatalogError::Failure);+ }+ let body = response+ .json::<serde_json::Value>()+ .await+ .map_err(|_| InspectionCatalogError::Failure)?;+ let models = body+ .get("data")+ .cloned()+ .unwrap_or_else(|| serde_json::json!([]));+ Ok(crate::core::Outcome::new(+ serde_json::json!({ "models": models }),+ Vec::new(),+ ))+ });+ Ok(PreparedInspectionCatalog::new(+ &provider_id,+ &cache_endpoint,+ credential.as_deref(),+ fetch,+ ))+ })+ });+ register_inspection_catalog_in(extensions, provider, listing);+ requests+}++pub(super) async fn report_for_profile(+ config: &Config,+ profile_id: &str,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ report_for_context(config, profile_context(config.clone(), profile_id), options).await+}++pub(super) async fn report_for_context(+ config: &Config,+ context: std::sync::Arc<crate::core::runtime::CoreContext>,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ crate::core::runtime::CoreContext::scope(context, async {+ doctor_report_with_options(config, options).await+ })+ .await+ .expect("doctor report for selected profile")+}diff --git a/crates/openhuman-core/src/doctor/inference_catalog_tests.rs b/crates/openhuman-core/src/doctor/inference_catalog_tests.rsnew file mode 100644index 0000000000..4909d945ef--- /dev/null+++ b/crates/openhuman-core/src/doctor/inference_catalog_tests.rs@@ -0,0 +1,597 @@+use super::{+ ops::{doctor_models, doctor_report_with_options},+ DoctorOptions, FindingSeverity, ModelProbeOutcome,+};+use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::config::Config;+use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ routing::get,+ Json, Router,+};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use std::time::Duration;++#[derive(Clone)]+struct CatalogServerState {+ status: StatusCode,+ body: serde_json::Value,+ delay: Duration,+ requests: Arc<AtomicUsize>,+ authorizations: Arc<std::sync::Mutex<Vec<Option<String>>>>,+}++async fn catalog_handler(State(state): State<CatalogServerState>, headers: HeaderMap) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ if !state.delay.is_zero() {+ tokio::time::sleep(state.delay).await;+ }+ state+ .authorizations+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .push(+ headers+ .get("authorization")+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned),+ );+ (state.status, Json(state.body)).into_response()+}++async fn missing_catalog_handler(State(state): State<CatalogServerState>) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ StatusCode::NOT_FOUND.into_response()+}++async fn spawn_catalog_server(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+) -> (String, CatalogServerState) {+ spawn_catalog_server_with_delay(status, body, has_models_route, Duration::ZERO).await+}++async fn spawn_catalog_server_with_delay(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+ delay: Duration,+) -> (String, CatalogServerState) {+ let state = CatalogServerState {+ status,+ body,+ delay,+ requests: Arc::new(AtomicUsize::new(0)),+ authorizations: Arc::new(std::sync::Mutex::new(Vec::new())),+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local catalog server");+ let address = listener.local_addr().expect("local server address");+ let app = if has_models_route {+ Router::new().route("/v1/models", get(catalog_handler))+ } else {+ Router::new()+ .route("/v1/health", get(catalog_handler))+ .fallback(get(missing_catalog_handler))+ };+ let app = app.with_state(state.clone());+ tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("serve local catalog");+ });+ (format!("http://{address}/v1"), state)+}++fn temporary_config() -> (tempfile::TempDir, Config) {+ let root = tempfile::tempdir().expect("temporary doctor fixture");+ let mut config = Config {+ config_path: root.path().join("config.toml"),+ workspace_dir: root.path().join("workspace"),+ action_dir: root.path().join("workspace"),+ ..Config::default()+ };+ config.cloud_providers = Vec::new();+ config.default_model = None;+ config.model_routes.clear();+ (root, config)+}++fn config_for_catalog(+ endpoint: String,+ provider_id: &str,+ slug: &str,+) -> (tempfile::TempDir, Config) {+ let (root, mut config) = temporary_config();+ config.secrets.encrypt = false;+ config.cloud_providers = vec![CloudProviderCreds {+ id: provider_id.to_owned(),+ slug: slug.to_owned(),+ label: "Doctor catalog fixture".to_owned(),+ endpoint,+ auth_style: AuthStyle::None,+ default_model: None,+ }];+ (root, config)+}++fn catalog_body(ids: &[&str]) -> serde_json::Value {+ serde_json::json!({+ "data": ids.iter().map(|id| serde_json::json!({ "id": id })).collect::<Vec<_>>()+ })+}++fn store_provider_key(config: &Config, slug: &str, token: &str) {+ let provider = crate::inference::provider::factory::auth_key_for_slug(slug);+ let profile_id = format!("{provider}:default");+ let now = chrono::Utc::now().to_rfc3339();+ let mut active_profiles = std::collections::HashMap::new();+ active_profiles.insert(provider.clone(), profile_id.clone());+ let mut profiles = std::collections::HashMap::new();+ profiles.insert(+ profile_id,+ serde_json::json!({+ "provider": provider,+ "profile_name": "default",+ "kind": "token",+ "token": token,+ "metadata": {},+ "created_at": now,+ "updated_at": now,+ }),+ );+ let document = serde_json::json!({+ "schema_version": 1,+ "updated_at": now,+ "active_profiles": active_profiles,+ "profiles": profiles,+ });+ std::fs::write(+ auth_profiles_path(config),+ serde_json::to_vec(&document).unwrap(),+ )+ .expect("seed read-only provider credential fixture");+}++fn auth_profiles_path(config: &Config) -> std::path::PathBuf {+ config+ .config_path+ .parent()+ .expect("fixture config parent")+ .join("auth-profiles.json")+}++fn profile_context(+ config: Config,+ profile_id: &str,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++fn workspace_context(config: Config) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ ))+}++fn profile_context_with_extensions(+ config: Config,+ profile_id: &str,+ extensions: crate::core::slots::Extensions,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++fn register_test_inspection_catalog(+ extensions: &crate::core::slots::Extensions,+ provider: &str,+ endpoint: String,+) -> Arc<AtomicUsize> {+ use crate::inference::registry::{+ register_inspection_catalog_in, InspectionCatalogError, InspectionCatalogListing,+ PreparedInspectionCatalog,+ };++ let requests = Arc::new(AtomicUsize::new(0));+ let request_count = Arc::clone(&requests);+ let provider_id = provider.to_owned();+ let listing: InspectionCatalogListing = Arc::new(move |config, request| {+ let endpoint = endpoint.clone();+ let provider_id = provider_id.clone();+ let request_count = Arc::clone(&request_count);+ Box::pin(async move {+ assert!(+ request.provider_key.is_empty(),+ "fixture uses the separate config credential identity"+ );+ let credential = config.api_key.clone();+ let cache_endpoint = endpoint.clone();+ let client = request.client.clone();+ let fetch_endpoint = endpoint.clone();+ let fetch_credential = credential.clone();+ let fetch_count = Arc::clone(&request_count);+ let fetch = Box::pin(async move {+ fetch_count.fetch_add(1, Ordering::SeqCst);+ let mut get = client.get(fetch_endpoint);+ if let Some(credential) = fetch_credential.as_deref() {+ get = get.bearer_auth(credential);+ }+ let response = get+ .send()+ .await+ .map_err(|_| InspectionCatalogError::Unavailable)?;+ let status = response.status();+ if status == StatusCode::NOT_FOUND {+ return Err(InspectionCatalogError::NoCatalog);+ }+ if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {+ return Err(InspectionCatalogError::AuthOrAccess);+ }+ if !status.is_success() {+ return Err(InspectionCatalogError::Failure);+ }+ let body = response+ .json::<serde_json::Value>()+ .await+ .map_err(|_| InspectionCatalogError::Failure)?;+ let models = body+ .get("data")+ .cloned()+ .unwrap_or_else(|| serde_json::json!([]));+ Ok(crate::core::Outcome::new(+ serde_json::json!({ "models": models }),+ Vec::new(),+ ))+ });+ Ok(PreparedInspectionCatalog::new(+ &provider_id,+ &cache_endpoint,+ credential.as_deref(),+ fetch,+ ))+ })+ });+ register_inspection_catalog_in(extensions, provider, listing);+ requests+}++async fn report_for_profile(+ config: &Config,+ profile_id: &str,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ report_for_context(config, profile_context(config.clone(), profile_id), options).await+}++async fn report_for_context(+ config: &Config,+ context: std::sync::Arc<crate::core::runtime::CoreContext>,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ crate::core::runtime::CoreContext::scope(context, async {+ doctor_report_with_options(config, options).await+ })+ .await+ .expect("doctor report for selected profile")+}++#[tokio::test]+async fn doctor_models_lists_configured_catalogs_and_honors_use_cache() {+ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["present-model"]), true).await;+ let (_temp, config) = config_for_catalog(endpoint, "p_doctor_497_cache", "doctor-497-cache");++ let first = doctor_models(&config, true)+ .await+ .expect("a configured provider catalog should be inspectable");+ let second = doctor_models(&config, true)+ .await+ .expect("a cached catalog should remain available");+ assert_eq!(first.value.entries.len(), 1);+ assert_eq!(first.value.entries[0].provider, "doctor-497-cache");+ assert_eq!(first.value.entries[0].outcome, ModelProbeOutcome::Ok);+ assert_eq!(second.value.entries[0].outcome, ModelProbeOutcome::Ok);+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);++ doctor_models(&config, false)+ .await+ .expect("use_cache=false should refresh the provider catalog");+ assert_eq!(server.requests.load(Ordering::SeqCst), 2);+}++#[tokio::test]+async fn doctor_models_does_not_reuse_a_catalog_for_another_profiles_credential() {+ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["configured-model"]), true).await;+ let (_temp_a, mut config_a) = config_for_catalog(+ endpoint.clone(),+ "p_doctor_497_selected",+ "doctor-497-selected",+ );+ let (_temp_b, mut config_b) =+ config_for_catalog(endpoint, "p_doctor_497_selected", "doctor-497-selected");+ config_a.cloud_providers[0].auth_style = AuthStyle::Bearer;+ config_b.cloud_providers[0].auth_style = AuthStyle::Bearer;+ store_provider_key(&config_a, "doctor-497-selected", "fixture-token-profile-a");+ store_provider_key(&config_b, "doctor-497-selected", "fixture-token-profile-b");+ let auth_file_a_before = std::fs::read(auth_profiles_path(&config_a)).expect("profile A file");+ let auth_file_b_before = std::fs::read(auth_profiles_path(&config_b)).expect("profile B file");++ doctor_models(&config_a, true)+ .await+ .expect("first profile catalog should be available");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_a)).unwrap(),+ auth_file_a_before,+ "profile A credential bytes are unchanged after its probe"+ );+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_b)).unwrap(),+ auth_file_b_before,+ "profile B credential bytes are unchanged while A is probed"+ );+ doctor_models(&config_b, true)+ .await+ .expect("selected profile catalog should use its own credential");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_a)).unwrap(),+ auth_file_a_before,+ "profile A credential bytes are unchanged while B is probed"+ );+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_b)).unwrap(),+ auth_file_b_before,+ "profile B credential bytes are unchanged after its probe"+ );+ doctor_models(&config_b, true)+ .await+ .expect("the selected profile may reuse its own cached catalog");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_b)).unwrap(),+ auth_file_b_before,+ "profile B credential bytes are unchanged after its cache hit"+ );++ assert_eq!(server.requests.load(Ordering::SeqCst), 2);+ assert_eq!(+ *server+ .authorizations+ .lock()+ .unwrap_or_else(|error| error.into_inner()),+ vec![+ Some("Bearer fixture-token-profile-a".to_owned()),+ Some("Bearer fixture-token-profile-b".to_owned())+ ]+ );+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_a)).unwrap(),+ auth_file_a_before+ );+ assert_eq!(+ std::fs::read(auth_profiles_path(&config_b)).unwrap(),+ auth_file_b_before+ );+}++#[tokio::test]+async fn prepared_catalog_identity_changes_when_managed_credential_rotates_in_place() {+ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["managed-model"]), true).await;+ let (_temp, mut config_a) = temporary_config();+ config_a.api_key = Some("fixture-managed-credential-a".into());+ config_a.cloud_providers = vec![CloudProviderCreds {+ id: "openhuman".into(),+ slug: "openhuman".into(),+ label: "Managed catalog fixture".into(),+ endpoint: endpoint.clone(),+ auth_style: AuthStyle::OpenhumanJwt,+ default_model: None,+ }];+ let mut config_b = config_a.clone();+ config_b.api_key = Some("fixture-managed-credential-b".into());+ let extensions = crate::core::slots::Extensions::new();+ let prepared_fetches =+ register_test_inspection_catalog(&extensions, "openhuman", format!("{endpoint}/models"));+ let context = profile_context_with_extensions(config_b.clone(), "tenant-b", extensions);++ let (first, second, third) = crate::core::runtime::CoreContext::scope(context, async {+ let first = doctor_models(&config_a, true).await?;+ let second = doctor_models(&config_b, true).await?;+ let third = doctor_models(&config_b, true).await?;+ Ok::<_, String>((first, second, third))+ })+ .await+ .expect("selected profile scope");++ assert_eq!(first.value.entries[0].outcome, ModelProbeOutcome::Ok);+ assert_eq!(second.value.entries[0].outcome, ModelProbeOutcome::Ok);+ assert_eq!(third.value.entries[0].outcome, ModelProbeOutcome::Ok);+ for result in [&first, &second, &third] {+ assert!(result.value.entries.iter().all(|entry| {+ entry+ .message+ .as_deref()+ .is_none_or(|message| !message.contains("fixture-managed-credential-"))+ }));+ }+ assert_eq!(server.requests.load(Ordering::SeqCst), 2);+ assert_eq!(prepared_fetches.load(Ordering::SeqCst), 2);+ assert_eq!(+ *server+ .authorizations+ .lock()+ .unwrap_or_else(|error| error.into_inner()),+ vec![+ Some("Bearer fixture-managed-credential-a".to_owned()),+ Some("Bearer fixture-managed-credential-b".to_owned())+ ]+ );+}++#[tokio::test]+async fn a_slow_provider_times_out_without_blocking_the_other_catalog() {+ let per_provider_budget = Duration::from_secs(10);+ let (slow_endpoint, slow_server) = spawn_catalog_server_with_delay(+ StatusCode::OK,+ catalog_body(&["slow-model"]),+ true,+ per_provider_budget + Duration::from_secs(2),+ )+ .await;+ let (fast_endpoint, fast_server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["fast-model"]), true).await;+ let (_temp, mut config) = temporary_config();+ config.cloud_providers = vec![+ CloudProviderCreds {+ id: "p_doctor_497_slow".into(),+ slug: "doctor-497-slow".into(),+ label: "Slow catalog fixture".into(),+ endpoint: slow_endpoint,+ auth_style: AuthStyle::None,+ default_model: None,+ },+ CloudProviderCreds {+ id: "p_doctor_497_fast".into(),+ slug: "doctor-497-fast".into(),+ label: "Fast catalog fixture".into(),+ endpoint: fast_endpoint,+ auth_style: AuthStyle::None,+ default_model: None,+ },+ ];++ let report = tokio::time::timeout(+ per_provider_budget + Duration::from_secs(2),+ doctor_models(&config, false),+ )+ .await+ .expect("the per-provider timeout must bound the doctor request")+ .expect("a timed-out provider should be represented in the report");++ let slow = report+ .value+ .entries+ .iter()+ .find(|entry| entry.provider == "doctor-497-slow")+ .expect("slow provider result");+ let fast = report+ .value+ .entries+ .iter()+ .find(|entry| entry.provider == "doctor-497-fast")+ .expect("fast provider result");+ assert_eq!(slow.outcome, ModelProbeOutcome::Error);+ assert_eq!(fast.outcome, ModelProbeOutcome::Ok);+ assert_eq!(slow_server.requests.load(Ordering::SeqCst), 1);+ assert_eq!(fast_server.requests.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn doctor_models_uses_read_only_http_without_calling_the_mutable_catalog() {+ use crate::core::runtime::{CoreContext, DomainSet};+ use crate::core::slots::Extensions;+ use crate::core::Outcome;+ use crate::inference::registry::{register_catalog_in, CatalogEntry, CatalogListing};++ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["must-not-be-used"]), true).await;+ let (_temp, config) = config_for_catalog(+ endpoint,+ "p_doctor_497_no_safe_hook",+ "doctor-497-no-safe-hook",+ );+ let normal_calls = Arc::new(AtomicUsize::new(0));+ let call_counter = Arc::clone(&normal_calls);+ let ordinary_listing: CatalogListing = Arc::new(move |_, _| {+ let call_counter = Arc::clone(&call_counter);+ Box::pin(async move {+ call_counter.fetch_add(1, Ordering::SeqCst);+ Ok(Outcome::new(+ serde_json::json!({ "models": [{ "id": "must-not-be-used" }] }),+ Vec::new(),+ ))+ })+ });+ let extensions = Extensions::new();+ register_catalog_in(+ &extensions,+ "doctor-497-no-safe-hook",+ CatalogEntry {+ list: ordinary_listing,+ limits: None,+ },+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);++ let result = CoreContext::scope(context, async { doctor_models(&config, false).await }).await;++ assert_eq!(normal_calls.load(Ordering::SeqCst), 0);+ match result {+ Ok(report) => assert_eq!(report.value.entries[0].outcome, ModelProbeOutcome::Ok),+ Err(error) => panic!("read-only HTTP catalog should be available: {error}"),+ }+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn inference_connect_checks_are_registered_but_skipped_in_static_tier() {+ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["present-model"]), true).await;+ let (_temp, config) = config_for_catalog(endpoint, "p_doctor_497_static", "doctor-497-static");+ let provider = "doctor-497-static";+ crate::inference::auth_error_registry::clear(provider);+ crate::inference::auth_error_registry::record(provider, 401);++ let report = report_for_profile(+ &config,+ "doctor-497-static-profile",+ DoctorOptions {+ tier: super::DoctorTier::Static,+ only: vec![+ "inference/model-in-catalog".into(),+ "inference/auth-errors".into(),+ ],+ ..DoctorOptions::default()+ },+ )+ .await;+ crate::inference::auth_error_registry::clear(provider);++ for check_id in ["inference/model-in-catalog", "inference/auth-errors"] {+ assert!(report.value.checks_skipped.iter().any(|id| id == check_id));+ assert!(report.value.findings.iter().any(|finding| {+ finding.check_id == check_id && finding.severity == FindingSeverity::Skipped+ }));+ }+ assert!(report.value.ok);+ assert_eq!(server.requests.load(Ordering::SeqCst), 0);+}diff --git a/crates/openhuman-core/src/doctor/inference_config_tests.rs b/crates/openhuman-core/src/doctor/inference_config_tests.rsnew file mode 100644index 0000000000..f679392dde--- /dev/null+++ b/crates/openhuman-core/src/doctor/inference_config_tests.rs@@ -0,0 +1,240 @@+use crate::config::Config;+use crate::doctor::runner;+use crate::doctor::{DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};++const PROVIDER_REF: &str = "inference/provider-ref";+const CONSTRUCT: &str = "inference/construct";+const TEMPERATURE: &str = "inference/temperature";++async fn run_only(config: Config, check_id: &str) -> Vec<Finding> {+ let context = DoctorCtx::from_config(config);+ runner::run(+ &context,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec![check_id.to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("the selected doctor check should run")+ .findings+}++fn isolated_config(root: &std::path::Path) -> Config {+ let mut config = Config::default();+ config.config_path = root.join("config.toml");+ config.workspace_dir = root.join("workspace");+ config+}++fn filesystem_snapshot(root: &std::path::Path) -> Vec<(std::path::PathBuf, bool, Vec<u8>)> {+ fn visit(+ root: &std::path::Path,+ dir: &std::path::Path,+ snapshot: &mut Vec<(std::path::PathBuf, bool, Vec<u8>)>,+ ) {+ for entry in std::fs::read_dir(dir).expect("read temporary config fixture") {+ let entry = entry.expect("read fixture entry");+ let path = entry.path();+ let metadata = entry.metadata().expect("read fixture metadata");+ let is_dir = metadata.is_dir();+ let contents = if is_dir {+ Vec::new()+ } else {+ std::fs::read(&path).expect("read fixture file")+ };+ snapshot.push((+ path.strip_prefix(root)+ .expect("fixture path is under root")+ .to_path_buf(),+ is_dir,+ contents,+ ));+ if is_dir {+ visit(root, &path, snapshot);+ }+ }+ }++ let mut snapshot = Vec::new();+ visit(root, root, &mut snapshot);+ snapshot.sort_by(|left, right| left.0.cmp(&right.0));+ snapshot+}++fn finding<'a>(findings: &'a [Finding], check_id: &str) -> &'a Finding {+ findings+ .iter()+ .find(|finding| finding.check_id == check_id)+ .unwrap_or_else(|| panic!("expected finding from {check_id}: {findings:#?}"))+}++fn finding_for_path<'a>(findings: &'a [Finding], check_id: &str, config_path: &str) -> &'a Finding {+ findings+ .iter()+ .find(|finding| {+ finding.check_id == check_id && finding.config_path.as_deref() == Some(config_path)+ })+ .unwrap_or_else(|| panic!("expected {check_id} finding for {config_path}: {findings:#?}"))+}++#[tokio::test]+async fn an_unregistered_chat_provider_reports_its_config_path() {+ let mut config = Config::default();+ config.chat_provider = Some("nope".to_owned());++ let findings = run_only(config, PROVIDER_REF).await;+ let result = finding(&findings, PROVIDER_REF);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("chat_provider"));+}++#[tokio::test]+async fn a_byok_cloud_fallback_without_a_key_reports_construction_failure() {+ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+ use crate::config::test_env::EnvVarGuard;++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let temp = tempfile::tempdir().expect("temporary configuration directory");+ let _env_guard = EnvVarGuard::locked_async()+ .await+ .with("HOME", temp.path())+ .with("OPENHUMAN_WORKSPACE", temp.path())+ .without("OPENAI_API_KEY")+ .without("OPENHUMAN_CORE_TOKEN");++ let mut config = isolated_config(temp.path());+ config.chat_provider = Some("ollama:qwen2.5".to_owned());+ config.primary_cloud = Some("provider-doctor-test".to_owned());+ config.cloud_providers = vec![CloudProviderCreds {+ id: "provider-doctor-test".to_owned(),+ slug: "doctor-test".to_owned(),+ label: "Doctor test provider".to_owned(),+ endpoint: "https://doctor-test.invalid/v1".to_owned(),+ auth_style: AuthStyle::Bearer,+ default_model: Some("test-model".to_owned()),+ }];+ config.vision_provider = Some("cloud".to_owned());++ let before = filesystem_snapshot(temp.path());+ let findings = run_only(config, CONSTRUCT).await;+ assert_eq!(filesystem_snapshot(temp.path()), before);+ let result = finding_for_path(&findings, CONSTRUCT, "vision_provider");++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("vision_provider"));+ assert!(result.message.to_ascii_lowercase().contains("credential"));+ assert!(!temp.path().join("auth-profiles.json").exists());+ assert!(!temp.path().join("auth-profiles.lock").exists());+}++#[tokio::test]+async fn a_fully_configured_managed_default_constructs_cleanly() {+ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+ use crate::config::test_env::EnvVarGuard;+ use crate::inference::provider::factory::PROVIDER_OPENHUMAN;+ use crate::inference::registry::{register_inspection_chat_model, InspectionChatModelFactory};++ struct ManagedModel {+ generations: Arc<AtomicUsize>,+ }++ #[async_trait::async_trait]+ impl ChatModel<()> for ManagedModel {+ async fn invoke(+ &self,+ _state: &(),+ _request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ self.generations.fetch_add(1, Ordering::SeqCst);+ panic!("doctor's construction check must not generate a model response")+ }+ }++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let temp = tempfile::tempdir().expect("temporary configuration directory");+ let _env_guard = EnvVarGuard::locked_async()+ .await+ .with("HOME", temp.path())+ .with("OPENHUMAN_WORKSPACE", temp.path())+ .without("OPENAI_API_KEY")+ .without("OPENHUMAN_CORE_TOKEN");+ let constructions = Arc::new(AtomicUsize::new(0));+ let generations = Arc::new(AtomicUsize::new(0));+ let build_constructions = Arc::clone(&constructions);+ let model_generations = Arc::clone(&generations);+ let inspection_factory: InspectionChatModelFactory = Arc::new(move |_| {+ build_constructions.fetch_add(1, Ordering::SeqCst);+ Ok(crate::inference::registry::InspectionChatModelBuild {+ model: Arc::new(ManagedModel {+ generations: Arc::clone(&model_generations),+ }) as Arc<dyn ChatModel<()>>,+ model_id: "managed-test-model".to_owned(),+ endpoint: "https://api.openhuman.invalid/openai/v1".to_owned(),+ credential: "doctor-test-session-token".to_owned(),+ })+ });+ register_inspection_chat_model(PROVIDER_OPENHUMAN, inspection_factory);+ let _registered_model = RegisterManagedModel;++ let mut config = isolated_config(temp.path());+ config.api_url = Some("https://api.openhuman.invalid".to_owned());+ config.api_key = Some("doctor-test-session-token".to_owned());+ config.primary_cloud = Some("provider-openhuman".to_owned());+ config.cloud_providers = vec![CloudProviderCreds {+ id: "provider-openhuman".to_owned(),+ slug: "openhuman".to_owned(),+ label: "OpenHuman".to_owned(),+ endpoint: "https://api.openhuman.invalid/v1".to_owned(),+ auth_style: AuthStyle::OpenhumanJwt,+ default_model: Some("managed-test-model".to_owned()),+ }];+ let before = filesystem_snapshot(temp.path());+ let findings = run_only(config, CONSTRUCT).await;+ assert_eq!(filesystem_snapshot(temp.path()), before);++ assert!(+ !findings.is_empty()+ && findings+ .iter()+ .all(|result| result.severity == FindingSeverity::Pass),+ "managed defaults should not report construction errors: {findings:#?}"+ );+ assert!(+ constructions.load(Ordering::SeqCst) > 0,+ "the managed provider factory must be consulted"+ );+ assert_eq!(generations.load(Ordering::SeqCst), 0);+ assert!(findings+ .iter()+ .all(|result| !result.message.contains("doctor-test-session-token")));+ assert!(!temp.path().join("auth-profiles.json").exists());+ assert!(!temp.path().join("auth-profiles.lock").exists());+}++struct RegisterManagedModel;++impl Drop for RegisterManagedModel {+ fn drop(&mut self) {+ crate::inference::registry::unregister_inspection_chat_model(+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,+ );+ }+}++#[tokio::test]+async fn an_out_of_range_temperature_reports_the_role_setting() {+ let mut config = Config::default();+ config.default_temperature = 3.5;++ let findings = run_only(config, TEMPERATURE).await;+ let result = finding(&findings, TEMPERATURE);++ assert_eq!(result.severity, FindingSeverity::Error);+ assert_eq!(result.config_path.as_deref(), Some("default_temperature"));+}diff --git a/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs b/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rsnew file mode 100644index 0000000000..6d9b2a7e38--- /dev/null+++ b/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs@@ -0,0 +1,480 @@+use super::{+ ops::{doctor_models, doctor_report_with_options},+ DoctorOptions, FindingSeverity, ModelProbeOutcome,+};+use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+use crate::config::schema::ModelRouteConfig;+use crate::config::Config;+use crate::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};+use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ routing::get,+ Json, Router,+};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use std::time::Duration;++#[derive(Clone)]+struct CatalogServerState {+ status: StatusCode,+ body: serde_json::Value,+ delay: Duration,+ requests: Arc<AtomicUsize>,+ authorizations: Arc<std::sync::Mutex<Vec<Option<String>>>>,+}++async fn catalog_handler(State(state): State<CatalogServerState>, headers: HeaderMap) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ if !state.delay.is_zero() {+ tokio::time::sleep(state.delay).await;+ }+ state+ .authorizations+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .push(+ headers+ .get("authorization")+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned),+ );+ (state.status, Json(state.body)).into_response()+}++async fn missing_catalog_handler(State(state): State<CatalogServerState>) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ StatusCode::NOT_FOUND.into_response()+}++async fn spawn_catalog_server(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+) -> (String, CatalogServerState) {+ spawn_catalog_server_with_delay(status, body, has_models_route, Duration::ZERO).await+}++async fn spawn_catalog_server_with_delay(+ status: StatusCode,+ body: serde_json::Value,+ has_models_route: bool,+ delay: Duration,+) -> (String, CatalogServerState) {+ let state = CatalogServerState {+ status,+ body,+ delay,+ requests: Arc::new(AtomicUsize::new(0)),+ authorizations: Arc::new(std::sync::Mutex::new(Vec::new())),+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local catalog server");+ let address = listener.local_addr().expect("local server address");+ let app = if has_models_route {+ Router::new().route("/v1/models", get(catalog_handler))+ } else {+ Router::new()+ .route("/v1/health", get(catalog_handler))+ .fallback(get(missing_catalog_handler))+ };+ let app = app.with_state(state.clone());+ tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("serve local catalog");+ });+ (format!("http://{address}/v1"), state)+}++fn temporary_config() -> (tempfile::TempDir, Config) {+ let root = tempfile::tempdir().expect("temporary doctor fixture");+ let mut config = Config {+ config_path: root.path().join("config.toml"),+ workspace_dir: root.path().join("workspace"),+ action_dir: root.path().join("workspace"),+ ..Config::default()+ };+ config.cloud_providers = Vec::new();+ config.default_model = None;+ config.model_routes.clear();+ (root, config)+}++fn config_for_catalog(+ endpoint: String,+ provider_id: &str,+ slug: &str,+) -> (tempfile::TempDir, Config) {+ let (root, mut config) = temporary_config();+ config.secrets.encrypt = false;+ config.cloud_providers = vec![CloudProviderCreds {+ id: provider_id.to_owned(),+ slug: slug.to_owned(),+ label: "Doctor catalog fixture".to_owned(),+ endpoint,+ auth_style: AuthStyle::None,+ default_model: None,+ }];+ (root, config)+}++fn catalog_body(ids: &[&str]) -> serde_json::Value {+ serde_json::json!({+ "data": ids.iter().map(|id| serde_json::json!({ "id": id })).collect::<Vec<_>>()+ })+}++fn store_provider_key(config: &Config, slug: &str, token: &str) {+ AuthService::from_config(config)+ .store_provider_token(+ &crate::inference::provider::factory::auth_key_for_slug(slug),+ DEFAULT_AUTH_PROFILE_NAME,+ token,+ std::collections::HashMap::new(),+ true,+ )+ .expect("seed scoped provider credential");+}++fn auth_profiles_path(config: &Config) -> std::path::PathBuf {+ config+ .config_path+ .parent()+ .expect("fixture config parent")+ .join("auth-profiles.json")+}++fn profile_context(+ config: Config,+ profile_id: &str,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++fn workspace_context(config: Config) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test(DomainSet::full(), None).derive_with(ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ ))+}++fn profile_context_with_extensions(+ config: Config,+ profile_id: &str,+ extensions: crate::core::slots::Extensions,+) -> std::sync::Arc<crate::core::runtime::CoreContext> {+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++ CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions).derive_with(+ ContextOverlay::new(+ config,+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::default(),+ )+ .profile(profile_id),+ )+}++fn register_test_inspection_catalog(+ extensions: &crate::core::slots::Extensions,+ provider: &str,+ endpoint: String,+) -> Arc<AtomicUsize> {+ use crate::inference::registry::{+ register_inspection_catalog_in, InspectionCatalogError, InspectionCatalogListing,+ PreparedInspectionCatalog,+ };++ let requests = Arc::new(AtomicUsize::new(0));+ let request_count = Arc::clone(&requests);+ let provider_id = provider.to_owned();+ let listing: InspectionCatalogListing = Arc::new(move |config, request| {+ let endpoint = endpoint.clone();+ let provider_id = provider_id.clone();+ let request_count = Arc::clone(&request_count);+ Box::pin(async move {+ assert!(+ request.provider_key.is_empty(),+ "fixture uses the separate config credential identity"+ );+ let credential = config.api_key.clone();+ let cache_endpoint = endpoint.clone();+ let client = request.client.clone();+ let fetch_endpoint = endpoint.clone();+ let fetch_credential = credential.clone();+ let fetch_count = Arc::clone(&request_count);+ let fetch = Box::pin(async move {+ fetch_count.fetch_add(1, Ordering::SeqCst);+ let mut get = client.get(fetch_endpoint);+ if let Some(credential) = fetch_credential.as_deref() {+ get = get.bearer_auth(credential);+ }+ let response = get+ .send()+ .await+ .map_err(|_| InspectionCatalogError::Unavailable)?;+ let status = response.status();+ if status == StatusCode::NOT_FOUND {+ return Err(InspectionCatalogError::NoCatalog);+ }+ if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {+ return Err(InspectionCatalogError::AuthOrAccess);+ }+ if !status.is_success() {+ return Err(InspectionCatalogError::Failure);+ }+ let body = response+ .json::<serde_json::Value>()+ .await+ .map_err(|_| InspectionCatalogError::Failure)?;+ let models = body+ .get("data")+ .cloned()+ .unwrap_or_else(|| serde_json::json!([]));+ Ok(crate::core::Outcome::new(+ serde_json::json!({ "models": models }),+ Vec::new(),+ ))+ });+ Ok(PreparedInspectionCatalog::new(+ &provider_id,+ &cache_endpoint,+ credential.as_deref(),+ fetch,+ ))+ })+ });+ register_inspection_catalog_in(extensions, provider, listing);+ requests+}++async fn report_for_profile(+ config: &Config,+ profile_id: &str,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ report_for_context(config, profile_context(config.clone(), profile_id), options).await+}++async fn report_for_context(+ config: &Config,+ context: std::sync::Arc<crate::core::runtime::CoreContext>,+ options: DoctorOptions,+) -> crate::core::Outcome<super::DoctorReport> {+ crate::core::runtime::CoreContext::scope(context, async {+ doctor_report_with_options(config, options).await+ })+ .await+ .expect("doctor report for selected profile")+}++#[tokio::test]+async fn inference_connect_checks_are_registered_but_skipped_in_static_tier() {+ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["present-model"]), true).await;+ let (_temp, config) = config_for_catalog(endpoint, "p_doctor_497_static", "doctor-497-static");+ let provider = "doctor-497-static";+ crate::inference::auth_error_registry::clear(provider);+ crate::inference::auth_error_registry::record(provider, 401);++ let report = report_for_profile(+ &config,+ "doctor-497-static-profile",+ DoctorOptions {+ tier: super::DoctorTier::Static,+ only: vec![+ "inference/model-in-catalog".into(),+ "inference/auth-errors".into(),+ ],+ ..DoctorOptions::default()+ },+ )+ .await;+ crate::inference::auth_error_registry::clear(provider);++ for check_id in ["inference/model-in-catalog", "inference/auth-errors"] {+ assert!(report.value.checks_skipped.iter().any(|id| id == check_id));+ assert!(report.value.findings.iter().any(|finding| {+ finding.check_id == check_id && finding.severity == FindingSeverity::Skipped+ }));+ }+ assert!(report.value.ok);+ assert_eq!(server.requests.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn doctor_models_skips_a_provider_without_a_models_route() {+ let (endpoint, server) = spawn_catalog_server(StatusCode::OK, catalog_body(&[]), false).await;+ let (_temp, config) =+ config_for_catalog(endpoint, "p_doctor_497_no_models", "doctor-497-no-models");++ let endpoint_status = reqwest::get(format!("{}/models", config.cloud_providers[0].endpoint))+ .await+ .expect("mock provider should answer the missing catalog route");+ assert_eq!(endpoint_status.status(), StatusCode::NOT_FOUND);+ server.requests.store(0, Ordering::SeqCst);++ let report = doctor_models(&config, false)+ .await+ .expect("a provider without a model-listing route is an ordinary skipped check");++ assert_eq!(report.value.summary.skipped, 1);+ assert_eq!(report.value.summary.errors, 0);+ assert_eq!(report.value.entries[0].outcome, ModelProbeOutcome::Skipped);+ assert!(report.value.entries[0]+ .message+ .as_deref()+ .is_some_and(|message| message.to_ascii_lowercase().contains("models")));+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn model_in_catalog_check_skips_a_provider_without_a_models_route() {+ let (endpoint, server) = spawn_catalog_server(StatusCode::OK, catalog_body(&[]), false).await;+ let (_temp, config) = config_for_catalog(+ endpoint.clone(),+ "p_doctor_497_route_missing",+ "doctor-497-route-missing",+ );+ let extensions = crate::core::slots::Extensions::new();+ register_test_inspection_catalog(+ &extensions,+ "doctor-497-route-missing",+ format!("{endpoint}/models"),+ );+ let context =+ profile_context_with_extensions(config.clone(), "doctor-497-route-profile", extensions);++ let report = crate::core::runtime::CoreContext::scope(context, async {+ doctor_report_with_options(+ &config,+ DoctorOptions {+ only: vec!["inference/model-in-catalog".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("scoped doctor report");++ assert!(report+ .value+ .checks_run+ .iter()+ .any(|id| id == "inference/model-in-catalog"));+ assert!(report.value.findings.iter().any(|finding| {+ finding.check_id == "inference/model-in-catalog"+ && finding.severity == FindingSeverity::Skipped+ && (finding.message.to_ascii_lowercase().contains("models")+ || finding.message.to_ascii_lowercase().contains("catalog"))+ }));+ assert_eq!(report.value.summary.error, 0);+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn doctor_models_classifies_provider_401_as_auth_or_access() {+ let (endpoint, server) = spawn_catalog_server(+ StatusCode::UNAUTHORIZED,+ serde_json::json!({ "error": "credentials rejected" }),+ true,+ )+ .await;+ let (_temp, config) = config_for_catalog(+ endpoint,+ "p_doctor_497_unauthorized",+ "doctor-497-unauthorized",+ );++ let report = doctor_models(&config, false)+ .await+ .expect("provider authorization failures should be represented in the report");++ assert_eq!(report.value.summary.auth_or_access, 1);+ assert_eq!(report.value.summary.errors, 0);+ assert_eq!(+ report.value.entries[0].outcome,+ ModelProbeOutcome::AuthOrAccess+ );+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn missing_default_and_route_models_are_warned_by_the_inference_check() {+ let (endpoint, server) =+ spawn_catalog_server(StatusCode::OK, catalog_body(&["present-model"]), true).await;+ let (_temp, mut config) =+ config_for_catalog(endpoint, "p_doctor_497_missing", "doctor-497-missing");+ config.default_model = Some("doctor-497-missing:missing-default".into());+ config.model_routes.push(ModelRouteConfig {+ hint: "coding".into(),+ model: "doctor-497-missing:missing-route-model".into(),+ });+ let extensions = crate::core::slots::Extensions::new();+ let catalog_calls = register_test_inspection_catalog(+ &extensions,+ "doctor-497-missing",+ format!("{}/models", config.cloud_providers[0].endpoint),+ );+ let context = profile_context_with_extensions(config.clone(), "doctor-profile-b", extensions);+ let (catalog, report) = crate::core::runtime::CoreContext::scope(context, async {+ let catalog = doctor_models(&config, true).await?;+ let report = doctor_report_with_options(+ &config,+ DoctorOptions {+ only: vec!["inference/model-in-catalog".into()],+ ..DoctorOptions::default()+ },+ )+ .await?;+ Ok::<_, String>((catalog, report))+ })+ .await+ .expect("selected profile scope");++ assert_eq!(catalog.value.entries[0].outcome, ModelProbeOutcome::Ok);+ assert_eq!(report.value.profile.as_deref(), Some("doctor-profile-b"));+ assert!(report+ .value+ .checks_run+ .iter()+ .any(|id| id == "inference/model-in-catalog"));+ let missing_default = report.value.findings.iter().find(|finding| {+ finding.check_id == "inference/model-in-catalog"+ && finding.severity == FindingSeverity::Warn+ && finding.config_path.as_deref() == Some("default_model")+ && finding.message.contains("default_model")+ });+ assert!(missing_default.is_some(), "{:#?}", report.value.findings);+ let missing_route = report.value.findings.iter().find(|finding| {+ finding.check_id == "inference/model-in-catalog"+ && finding.severity == FindingSeverity::Warn+ && finding.config_path.as_deref() == Some("model_routes[0].model")+ });+ assert!(missing_route.is_some(), "{:#?}", report.value.findings);+ assert!(report.value.findings.iter().all(|finding| {+ !finding.message.contains("missing-default")+ && !finding.message.contains("missing-route-model")+ }));+ assert_eq!(catalog_calls.load(Ordering::SeqCst), 1);+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+}diff --git a/crates/openhuman-core/src/doctor/mod.rs b/crates/openhuman-core/src/doctor/mod.rsnew file mode 100644index 0000000000..73c67d3749--- /dev/null+++ b/crates/openhuman-core/src/doctor/mod.rs@@ -0,0 +1,87 @@+//! Native diagnostic checks for configuration, workspace, and runtime health.++pub(crate) mod checks;+mod contract;+mod core;+pub mod ops;+pub mod profile;+pub mod registry;+mod runner;+mod schemas;+pub mod tools;++pub use contract::{+ ComponentId, DoctorCheck, DoctorConfigSource, DoctorCtx, DoctorOptions, DoctorReport,+ DoctorSummary, DoctorTier, Finding, FindingSeverity, ValueSource,+};+pub use core::{ModelProbeEntry, ModelProbeOutcome, ModelProbeReport, ModelProbeSummary};+pub use ops::*;+pub use registry::{+ register_check_source, register_check_source_in, registered_checks_for, DoctorCheckSource,+};+pub(crate) use schemas::all_controller_entries as all_doctor_controller_entries;+#[cfg(test)]+pub(crate) use schemas::doctor_parameter_contracts;+pub use schemas::{+ all_controller_schemas as all_doctor_controller_schemas,+ all_registered_controllers as all_doctor_registered_controllers,+};++#[cfg(test)]+#[path = "config_file_tests.rs"]+mod config_file_red_tests;++#[cfg(test)]+#[path = "config_provenance_tests.rs"]+mod config_provenance_red_tests;++#[cfg(test)]+#[path = "config_semantics_tests.rs"]+mod config_semantics_red_tests;++#[cfg(test)]+#[path = "inference_config_tests.rs"]+mod inference_config_red_tests;++#[cfg(test)]+#[path = "embeddings_config_tests.rs"]+mod embeddings_config_red_tests;++#[cfg(test)]+#[path = "checks/config_file_tests.rs"]+mod config_file_tests;++#[cfg(test)]+#[path = "runner_tests.rs"]+mod runner_tests;++#[cfg(test)]+#[path = "connectivity_tests.rs"]+mod connectivity_tests;++#[cfg(test)]+#[path = "checks/config_provenance_tests.rs"]+mod config_provenance_tests;++#[cfg(test)]+#[path = "checks/inference_tests.rs"]+mod inference_config_tests;++#[cfg(test)]+#[path = "inference_catalog_tests.rs"]+mod inference_catalog_tests;++#[cfg(test)]+#[path = "inference_auth_error_tests.rs"]+mod inference_auth_error_tests;++#[cfg(test)]+#[path = "inference_model_catalog_tests.rs"]+mod inference_model_catalog_tests;++#[cfg(test)]+#[path = "inference_catalog_test_support.rs"]+mod inference_catalog_test_support;++#[cfg(test)]+pub(crate) mod test_support;diff --git a/crates/openhuman-core/src/doctor/ops.rs b/crates/openhuman-core/src/doctor/ops.rsnew file mode 100644index 0000000000..eeb33304ea--- /dev/null+++ b/crates/openhuman-core/src/doctor/ops.rs@@ -0,0 +1,322 @@+//! JSON-RPC / CLI controller surface for diagnostics.+//!+//! Resolve the selected profile and run the native doctor check registry.++use std::path::Path;++use super::contract::DoctorProfileStatus;+use super::profile::DesktopProfileSelection;+use crate::config::Config;+use crate::core::{+ runtime::{ComponentSet, CoreContext, DispatchCtx},+ Outcome,+};+use crate::doctor::{+ DoctorConfigSource, DoctorCtx, DoctorOptions, DoctorReport, DoctorSummary, DoctorTier, Finding,+ ModelProbeReport,+};++pub async fn doctor_report(config: &Config) -> Result<Outcome<DoctorReport>, String> {+ doctor_report_with_options(config, DoctorOptions::default()).await+}++pub async fn doctor_report_with_options(+ config: &Config,+ mut options: DoctorOptions,+) -> Result<Outcome<DoctorReport>, String> {+ if options.profile.is_none() {+ if let Some(outcome) = unusable_default_config_outcome(config, options.tier) {+ return Ok(outcome);+ }+ }+ if let Some(profile_id) = options.profile.take() {+ if crate::core::runtime::is_saas() {+ return Ok(profile_error_outcome(+ safe_profile_id(&profile_id),+ options.tier,+ super::profile::DesktopProfileError::Unavailable,+ ));+ }+ let Some(root) = super::profile::root_for_config(config)+ .or_else(|| crate::config::default_root_openhuman_dir().ok())+ else {+ return Ok(profile_error_outcome(+ safe_profile_id(&profile_id),+ options.tier,+ super::profile::DesktopProfileError::Missing,+ ));+ };+ return doctor_report_for_selected_profile(&root, &profile_id, options).await;+ }++ let mut ctx = DoctorCtx::from_config(config.clone());+ if ctx.profile().is_none() {+ if let Some(profile_id) = super::profile::id_for_config(config) {+ ctx = ctx.with_profile(profile_id, DoctorConfigSource::Profile);+ }+ }+ report_with_context(options, ctx).await+}++/// Runs a report under the dispatch's selected tenant context when present,+/// or resolves a desktop `--profile` request using the read-only loader.+pub async fn doctor_report_for_dispatch(+ dispatch: &DispatchCtx,+ mut options: DoctorOptions,+) -> Result<Outcome<DoctorReport>, String> {+ if crate::core::runtime::is_saas() {+ let target =+ crate::profiles::doctor::resolve_target(dispatch, options.profile.as_deref()).await?;+ if let Some(target) = target {+ options.profile = None;+ let components = ComponentSet::from_config(&target.config.components);+ let ctx = DoctorCtx::from_config_with_components(target.config.clone(), components)+ .with_profile(target.profile_id.as_str(), DoctorConfigSource::Tenant)+ .with_profile_metadata(None, Some("saas-tenant".into()));+ return CoreContext::scope(target.context, report_with_context(options, ctx)).await;+ }+ }++ if let Some(profile_id) = options.profile.take() {+ if crate::core::runtime::is_saas() {+ return Ok(profile_error_outcome(+ safe_profile_id(&profile_id),+ options.tier,+ super::profile::DesktopProfileError::Unavailable,+ ));+ }+ let root = dispatch+ .embedder_config()+ .as_ref()+ .and_then(super::profile::root_for_config)+ .or_else(super::profile::root_for_workspace_override)+ .or_else(|| crate::config::default_root_openhuman_dir().ok());+ let Some(root) = root else {+ return Ok(profile_error_outcome(+ safe_profile_id(&profile_id),+ options.tier,+ super::profile::DesktopProfileError::Missing,+ ));+ };+ return doctor_report_for_selected_profile(&root, &profile_id, options).await;+ }++ if crate::core::runtime::is_saas() {+ let config = dispatch.load_config().await?;+ return doctor_report_with_options(&config, options).await;+ }+ if let Some(config) = dispatch.embedder_config() {+ return doctor_report_with_options(&config, options).await;+ }++ // A doctor RPC is diagnostic, so resolve the desktop's effective config+ // through the read-only profile loader. `DispatchCtx::load_config()` falls+ // through to `Config::load_or_init()` when no embedder config exists; that+ // startup loader persists migrations and can rewrite config.toml during an+ // otherwise read-only report.+ let selection = desktop_selection_for_dispatch(dispatch).await?;+ doctor_report_for_desktop_selection(selection, options).await+}++/// Config resolution for non-SaaS doctor surfaces. Without an embedder-owned+/// snapshot, diagnostics use the read-only desktop profile loader instead of+/// `Config::load_or_init`, which can persist migrations.+pub(crate) async fn config_for_dispatch(dispatch: &DispatchCtx) -> Result<Config, String> {+ if crate::core::runtime::is_saas() {+ return dispatch.load_config().await;+ }+ if let Some(config) = dispatch.embedder_config() {+ return Ok(config);+ }+ Ok(desktop_selection_for_dispatch(dispatch).await?.config)+}++async fn desktop_selection_for_dispatch(+ dispatch: &DispatchCtx,+) -> Result<DesktopProfileSelection, String> {+ let process_root = dispatch.resolved().and_then(|context| {+ let (_, config_path) = context.workspace_config_binding().ok()?;+ super::profile::root_for_config_path(&config_path?)+ });+ let root = super::profile::root_for_workspace_override()+ .or(process_root)+ .or_else(|| crate::config::default_root_openhuman_dir().ok())+ .ok_or_else(|| "Could not resolve the desktop config root".to_owned())?;+ super::profile::resolve_desktop_profile_for_doctor(&root, None)+ .await+ .map_err(|error| error.message().to_owned())+}++/// Builds a desktop profile report from an explicit root and profile id.+/// This entry point does not load the active profile or initialize the core,+/// so hosts can use it before runtime bootstrap when they need a read-only+/// profile diagnostic.+pub async fn doctor_report_for_selected_profile(+ root: &Path,+ profile_id: &str,+ mut options: DoctorOptions,+) -> Result<Outcome<DoctorReport>, String> {+ options.profile = None;+ let selected = match super::profile::load_desktop_profile(root, profile_id).await {+ Ok(selected) => selected,+ Err(error) => {+ return Ok(profile_error_outcome(+ safe_profile_id(profile_id),+ options.tier,+ error,+ ));+ }+ };+ let components = ComponentSet::from_config(&selected.config.components);+ let inspection_profile_id = selected.id.clone();+ let ctx = DoctorCtx::from_config_with_components(selected.config.clone(), components)+ .with_profile(inspection_profile_id.clone(), DoctorConfigSource::Profile)+ .with_profile_metadata(Some(selected.layout.version), Some("--profile".into()))+ .with_profile_status(DoctorProfileStatus::Valid);+ let inspection_context =+ profile_inspection_context(&selected.config, Some(&inspection_profile_id));+ CoreContext::scope(inspection_context, report_with_context(options, ctx)).await+}++/// Runs a report from the effective desktop selection without consulting the+/// ambient core context. Hosts can resolve the config before boot and pass it+/// here to preserve profile identity and directory provenance.+pub async fn doctor_report_for_desktop_selection(+ selection: DesktopProfileSelection,+ options: DoctorOptions,+) -> Result<Outcome<DoctorReport>, String> {+ if let Some(outcome) = unusable_default_config_outcome(&selection.config, options.tier) {+ return Ok(outcome);+ }+ let components = ComponentSet::from_config(&selection.config.components);+ let inspection_profile_id = selection.profile_id.clone();+ let mut ctx = DoctorCtx::from_config_with_components(selection.config.clone(), components)+ .with_profile_metadata(selection.layout_version, Some(selection.resolution_source));+ if let Some(profile_id) = inspection_profile_id.clone() {+ ctx = ctx.with_profile(profile_id, DoctorConfigSource::Profile);+ }+ if let Some(status) = selection.profile_status {+ ctx = ctx.with_profile_status(status);+ }+ let inspection_context =+ profile_inspection_context(&selection.config, inspection_profile_id.as_deref());+ CoreContext::scope(inspection_context, report_with_context(options, ctx)).await+}++fn profile_inspection_context(+ config: &Config,+ _profile_id: Option<&str>,+) -> std::sync::Arc<CoreContext> {+ let Some(parent) = CoreContext::current() else {+ return CoreContext::for_inspection(config.clone());+ };+ let mut overlay = crate::core::runtime::ContextOverlay::new(+ config.clone(),+ parent.domains(),+ parent.tool_groups(),+ );+ if !parent.user_skill_roots() {+ overlay = overlay.without_user_skill_roots();+ }+ parent.derive_for_inspection(overlay)+}++/// Shared safe diagnostic for a config parse failure. Keeps parser output and+/// source values out of the doctor report while preserving a typed field path+/// or TOML line when the parser supplied one.+pub(crate) fn config_parse_finding(config: &Config) -> Option<Finding> {+ let error = config.load_diagnostics().parse_error.as_ref()?;+ let mut finding = Finding::error(+ "config/parse",+ error.safe_summary(),+ "Correct the reported config syntax or field type and rerun doctor.",+ );+ finding.config_path = error.field_path.clone();+ Some(finding)+}++fn unusable_default_config_outcome(+ config: &Config,+ tier: DoctorTier,+) -> Option<Outcome<DoctorReport>> {+ if config.load_diagnostics().fallback+ != crate::config::schema::load::ConfigLoadFallback::Defaults+ {+ return None;+ }+ let finding = config_parse_finding(config)?;+ let findings = vec![finding];+ let (layout_version, resolution_source) = config.doctor_profile_metadata();+ let report = DoctorReport {+ schema_version: 2,+ profile: super::profile::id_for_config(config),+ config_source: DoctorConfigSource::Profile,+ profile_layout_version: layout_version.map(|version| match version {+ crate::config::schema::profile_layout::LayoutVersion::V1 => 1,+ crate::config::schema::profile_layout::LayoutVersion::V2 => 2,+ }),+ config_resolution_source: resolution_source,+ tier,+ checks_run: vec!["config/parse".into()],+ checks_skipped: Vec::new(),+ summary: DoctorSummary::from_findings(&findings),+ findings,+ ok: false,+ };+ Some(Outcome::single_log(report, "doctor config parse failed"))+}++async fn report_with_context(+ options: DoctorOptions,+ ctx: DoctorCtx,+) -> Result<Outcome<DoctorReport>, String> {+ let report = super::runner::run(&ctx, options).await?;+ Ok(Outcome::single_log(report, "doctor report generated"))+}++fn profile_error_outcome(+ profile: Option<String>,+ tier: DoctorTier,+ error: super::profile::DesktopProfileError,+) -> Outcome<DoctorReport> {+ let findings = vec![Finding::error(+ "profile/exists",+ error.message(),+ "Select a supported desktop profile with a valid config and rerun doctor.",+ )];+ let summary = DoctorSummary::from_findings(&findings);+ Outcome::single_log(+ DoctorReport {+ schema_version: 2,+ profile,+ config_source: DoctorConfigSource::Profile,+ profile_layout_version: None,+ config_resolution_source: None,+ tier,+ checks_run: vec!["profile/exists".into()],+ checks_skipped: Vec::new(),+ findings,+ summary,+ ok: false,+ },+ "doctor profile selection failed",+ )+}++fn safe_profile_id(profile_id: &str) -> Option<String> {+ super::profile::is_profile_path_segment(profile_id).then(|| profile_id.to_owned())+}++pub async fn doctor_models(+ config: &Config,+ use_cache: bool,+) -> Result<Outcome<ModelProbeReport>, String> {+ Ok(Outcome::new(+ super::checks::inference_catalog::doctor_models(config, use_cache).await,+ Vec::new(),+ ))+}++#[cfg(test)]+#[path = "ops_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/ops_tests.rs b/crates/openhuman-core/src/doctor/ops_tests.rsnew file mode 100644index 0000000000..aafc293743--- /dev/null+++ b/crates/openhuman-core/src/doctor/ops_tests.rs@@ -0,0 +1,66 @@+use super::*;++use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++use crate::core::runtime::{CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::memory::engine::{Binding, EngineHealth};+use crate::memory::engine_registry::{+ register_memory_engine_in, register_memory_health_probe_in, EngineEntry, EngineFuture,+ ReadOnlyHealthProbe,+};++#[tokio::test]+async fn a_legacy_memory_selector_does_not_resolve_the_normal_engine() {+ let fixture = tempfile::tempdir().expect("doctor config fixture");+ let engine_id = "doctor-legacy-selector-test";+ let normal_builds = Arc::new(AtomicUsize::new(0));+ let normal_builds_in_closure = Arc::clone(&normal_builds);+ let extensions = Extensions::new();+ register_memory_engine_in(+ &extensions,+ engine_id,+ EngineEntry {+ build: Arc::new(move |_| {+ normal_builds_in_closure.fetch_add(1, Ordering::SeqCst);+ Binding::Off {+ engine: Some(engine_id.to_owned()),+ endpoint: None,+ reason: "test engine must not be resolved by doctor options".to_owned(),+ }+ }),+ free_background: None,+ },+ );+ let readonly_probes = Arc::new(AtomicUsize::new(0));+ let readonly_probes_in_closure = Arc::clone(&readonly_probes);+ let readonly_probe: ReadOnlyHealthProbe = Arc::new(move |_| {+ let probes = Arc::clone(&readonly_probes_in_closure);+ Box::pin(async move {+ probes.fetch_add(1, Ordering::SeqCst);+ EngineHealth::Ok+ }) as EngineFuture<EngineHealth>+ });+ register_memory_health_probe_in(&extensions, engine_id, readonly_probe);++ let core = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let mut config = Config::default();+ config.memory.engine = engine_id.to_owned();+ config.workspace_dir = fixture.path().join("workspace");+ config.action_dir = fixture.path().join("actions");+ config.config_path = fixture.path().join("config.toml");+ let context = DoctorCtx::from_config_with_components(config.clone(), ComponentSet::all());+ let options = DoctorOptions {+ tier: DoctorTier::Connect,+ only: vec!["memory/engine".to_owned()],+ ..DoctorOptions::default()+ };++ CoreContext::scope(core, report_with_context(options, context))+ .await+ .expect("a removed selector is reported in the doctor response");++ assert_eq!(normal_builds.load(Ordering::SeqCst), 0);+ assert_eq!(readonly_probes.load(Ordering::SeqCst), 0);+}diff --git a/crates/openhuman-core/src/doctor/profile.rs b/crates/openhuman-core/src/doctor/profile.rsnew file mode 100644index 0000000000..106596f3f6--- /dev/null+++ b/crates/openhuman-core/src/doctor/profile.rs@@ -0,0 +1,481 @@+//! Read-only loading and existence diagnostics for desktop profiles.++use std::path::{Component, Path, PathBuf};+use std::sync::Arc;++use async_trait::async_trait;++use crate::config::schema::load::ConfigResolutionSource;+use crate::config::schema::profile_layout::LayoutVersion;+use crate::config::Config;+use crate::doctor::contract::{DoctorCheck, DoctorCtx, DoctorProfileStatus, DoctorTier, Finding};+use crate::profiles::ProfileLayout;++/// A desktop profile config loaded without activating or repairing it.+#[derive(Debug, Clone)]+pub(crate) struct DesktopProfile {+ pub id: String,+ pub layout: ProfileLayout,+ pub config: Config,+}++/// The effective desktop config and provenance resolved without initializing+/// or repairing a profile.+#[derive(Debug, Clone)]+pub struct DesktopProfileSelection {+ /// Effective config loaded for the selected profile or current desktop.+ pub config: Config,+ /// Profile id when the selected config lives under `users/<id>`.+ pub profile_id: Option<String>,+ /// Profile layout when the config belongs to a desktop profile.+ pub layout_version: Option<LayoutVersion>,+ /// Source that chose the config directory, or `--profile` for an explicit id.+ pub resolution_source: String,+ pub(crate) profile_status: Option<DoctorProfileStatus>,+}++/// Safe failure categories for a selected desktop profile.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DesktopProfileError {+ InvalidId,+ Missing,+ UnknownLayoutMarker,+ InvalidConfig,+ Unavailable,+}++impl DesktopProfileError {+ pub fn message(self) -> &'static str {+ match self {+ Self::InvalidId => "The selected profile id is invalid.",+ Self::Missing => "The selected profile does not exist.",+ Self::UnknownLayoutMarker => "The selected profile has an unsupported layout marker.",+ Self::InvalidConfig => "The selected profile config is missing or invalid.",+ Self::Unavailable => "Profile selection is unavailable for this host.",+ }+ }+}++/// Resolves either an explicit desktop profile or the effective desktop+/// config using the normal directory precedence, without running+/// `ProfileLayout::resolve`, `Config::load_or_init`, or persistent migrations.+pub async fn resolve_desktop_profile_for_doctor(+ root: &Path,+ requested_profile: Option<&str>,+) -> Result<DesktopProfileSelection, DesktopProfileError> {+ if let Some(id) = requested_profile {+ let selected = load_desktop_profile(root, id).await?;+ let mut config = selected.config;+ config.set_doctor_profile_metadata(Some(selected.layout.version), Some("--profile".into()));+ return Ok(DesktopProfileSelection {+ config,+ profile_id: Some(selected.id),+ layout_version: Some(selected.layout.version),+ resolution_source: "--profile".into(),+ profile_status: Some(DoctorProfileStatus::Valid),+ });+ }++ let (config_dir, workspace_dir, source, profile_id, layout_version) =+ resolve_desktop_config_dirs_read_only(root).await?;+ let (mut config, config_exists) =+ load_config_read_only(&config_dir.join("config.toml"), &workspace_dir).await?;+ config.set_doctor_profile_metadata(layout_version, Some(source.as_str().into()));+ let profile_status = if profile_id.is_some() {+ if config.load_diagnostics().parse_error.is_some() {+ Some(DoctorProfileStatus::InvalidConfig)+ } else if config_exists {+ Some(DoctorProfileStatus::Valid)+ } else {+ match tokio::fs::symlink_metadata(&config_dir).await {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ Some(DoctorProfileStatus::Missing)+ }+ _ => Some(DoctorProfileStatus::InvalidConfig),+ }+ }+ } else {+ None+ };+ Ok(DesktopProfileSelection {+ config,+ profile_status,+ profile_id,+ layout_version,+ resolution_source: source.as_str().into(),+ })+}++/// Loads one profile beneath `root` without changing active-user state,+/// creating directories, writing a layout marker, or recovering from a+/// backup. It applies the same in-memory load transforms as the regular+/// snapshot loader but does not run persistent schema migrations. Process+/// environment config overrides still apply after the selected profile file+/// is parsed, except that the workspace override cannot replace the selected+/// profile's workspace.+pub(crate) async fn load_desktop_profile(+ root: &Path,+ id: &str,+) -> Result<DesktopProfile, DesktopProfileError> {+ if !is_profile_path_segment(id) {+ return Err(DesktopProfileError::InvalidId);+ }++ let dir = ProfileLayout::new(root, id).dir;+ let metadata = tokio::fs::metadata(&dir).await.map_err(|error| {+ if matches!(+ error.kind(),+ std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory+ ) {+ DesktopProfileError::Missing+ } else {+ DesktopProfileError::InvalidConfig+ }+ })?;+ if !metadata.is_dir() {+ return Err(DesktopProfileError::Missing);+ }++ let version = read_layout_version(&dir).await?;+ let layout = ProfileLayout::with_version(dir, version);+ let (config, config_exists) =+ load_config_read_only(&layout.config_path, &layout.workspace_dir).await?;+ if !config_exists {+ return Err(DesktopProfileError::InvalidConfig);+ }+ if config.load_diagnostics().parse_error.is_some() {+ return Err(DesktopProfileError::InvalidConfig);+ }++ Ok(DesktopProfile {+ id: id.to_owned(),+ layout,+ config,+ })+}++async fn load_config_read_only(+ config_path: &Path,+ workspace_dir: &Path,+) -> Result<(Config, bool), DesktopProfileError> {+ let config_text = match tokio::fs::metadata(config_path).await {+ Ok(metadata) if metadata.is_file() => Some(+ tokio::fs::read_to_string(config_path)+ .await+ .map_err(|_| DesktopProfileError::InvalidConfig)?,+ ),+ Ok(_) => return Err(DesktopProfileError::InvalidConfig),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(_) => return Err(DesktopProfileError::InvalidConfig),+ };++ let mut config = match config_text.as_deref() {+ Some(contents) => match crate::config::schema::config_from_toml_str(contents) {+ Ok(config) => config,+ Err(error) => invalid_config_snapshot(+ config_path,+ workspace_dir,+ crate::config::schema::load::ConfigParseError::from_error(+ config_path.to_path_buf(),+ &error,+ ),+ ),+ },+ None => Config::default(),+ };+ config.config_path = config_path.to_path_buf();+ config.workspace_dir = workspace_dir.to_path_buf();+ config.action_dir = crate::config::resolve_action_dir(&config.action_dir_override);+ if let Some(contents) = config_text.as_deref() {+ if config.load_diagnostics().parse_error.is_none() {+ crate::config::schema::load::apply_loaded_config_migrations(&mut config, contents);+ }+ }+ config.apply_profile_env_overrides();+ if config.load_diagnostics().parse_error.is_none() {+ crate::config::enrichers::run_enrichers(&mut config);+ }+ Ok((config, config_text.is_some()))+}++fn invalid_config_snapshot(+ config_path: &Path,+ workspace_dir: &Path,+ parse_error: crate::config::schema::load::ConfigParseError,+) -> Config {+ let mut config = Config {+ config_path: config_path.to_path_buf(),+ workspace_dir: workspace_dir.to_path_buf(),+ ..Config::default()+ };+ let diagnostics = config.load_diagnostics_mut();+ diagnostics.parse_error = Some(parse_error);+ diagnostics.fallback = crate::config::schema::load::ConfigLoadFallback::Defaults;+ config+}++async fn profile_paths_for_resolved_dirs(+ config_dir: PathBuf,+ workspace_dir: PathBuf,+) -> Result<(PathBuf, PathBuf, Option<String>, Option<LayoutVersion>), DesktopProfileError> {+ if let Some(profile_id) = profile_id_for_dir(&config_dir)? {+ let layout = read_profile_layout(config_dir).await?;+ return Ok((+ layout.dir.clone(),+ layout.workspace_dir.clone(),+ Some(profile_id),+ Some(layout.version),+ ));+ }+ if workspace_dir+ .file_name()+ .is_some_and(|name| name == crate::config::schema::profile_layout::PROFILE_FILES_DIR)+ {+ if let Some(profile_dir) = workspace_dir.parent() {+ if let Some(profile_id) = profile_id_for_dir(profile_dir)? {+ let layout = read_profile_layout(profile_dir.to_path_buf()).await?;+ return Ok((+ layout.dir.clone(),+ layout.workspace_dir.clone(),+ Some(profile_id),+ Some(layout.version),+ ));+ }+ }+ }+ if let Some(layout) = ProfileLayout::of_workspace(&workspace_dir) {+ let id = profile_id_for_dir(&layout.dir)?;+ return Ok((+ layout.dir.clone(),+ layout.workspace_dir.clone(),+ id,+ Some(layout.version),+ ));+ }+ Ok((config_dir, workspace_dir, None, None))+}++async fn resolve_desktop_config_dirs_read_only(+ root: &Path,+) -> Result<+ (+ PathBuf,+ PathBuf,+ ConfigResolutionSource,+ Option<String>,+ Option<LayoutVersion>,+ ),+ DesktopProfileError,+> {+ if let Some(workspace) = std::env::var_os("OPENHUMAN_WORKSPACE")+ .filter(|value| !value.is_empty())+ .map(PathBuf::from)+ {+ let (config_dir, workspace_dir) =+ crate::config::resolve_config_dir_for_workspace(&workspace);+ let (config_dir, workspace_dir, profile_id, layout_version) =+ profile_paths_for_resolved_dirs(config_dir, workspace_dir).await?;+ return Ok((+ config_dir,+ workspace_dir,+ ConfigResolutionSource::EnvWorkspace,+ profile_id,+ layout_version,+ ));+ }++ if let Some(profile_id) = crate::config::schema::load::read_active_user_id_checked_async(root)+ .await+ .map_err(|_| DesktopProfileError::InvalidConfig)?+ {+ if !is_profile_path_segment(&profile_id) {+ return Err(DesktopProfileError::InvalidId);+ }+ let dir = ProfileLayout::new(root, &profile_id).dir;+ let layout = read_profile_layout(dir).await?;+ return Ok((+ layout.dir.clone(),+ layout.workspace_dir.clone(),+ ConfigResolutionSource::ActiveUser,+ Some(profile_id),+ Some(layout.version),+ ));+ }++ if let Some((config_dir, workspace_dir)) =+ crate::config::schema::load::load_persisted_workspace_dirs(root)+ .await+ .map_err(|_| DesktopProfileError::InvalidConfig)?+ {+ let (config_dir, workspace_dir, profile_id, layout_version) =+ profile_paths_for_resolved_dirs(config_dir, workspace_dir).await?;+ return Ok((+ config_dir,+ workspace_dir,+ ConfigResolutionSource::ActiveWorkspaceMarker,+ profile_id,+ layout_version,+ ));+ }++ let layout = read_profile_layout(crate::config::pre_login_user_dir(root)).await?;+ Ok((+ layout.dir.clone(),+ layout.workspace_dir.clone(),+ ConfigResolutionSource::DefaultConfigDir,+ Some(crate::config::PRE_LOGIN_USER_ID.to_string()),+ Some(layout.version),+ ))+}++async fn read_profile_layout(dir: PathBuf) -> Result<ProfileLayout, DesktopProfileError> {+ match tokio::fs::metadata(&dir).await {+ Ok(metadata) if metadata.is_dir() => {}+ Ok(_) => return Err(DesktopProfileError::Missing),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(_) => return Err(DesktopProfileError::InvalidConfig),+ }+ let version = read_layout_version(&dir).await?;+ Ok(ProfileLayout::with_version(dir, version))+}++fn profile_id_for_dir(dir: &Path) -> Result<Option<String>, DesktopProfileError> {+ let Some(users_dir) = dir.parent() else {+ return Ok(None);+ };+ if !users_dir.file_name().is_some_and(|name| name == "users") {+ return Ok(None);+ }+ let Some(id) = dir.file_name().and_then(|name| name.to_str()) else {+ return Err(DesktopProfileError::InvalidId);+ };+ if !is_profile_path_segment(id) {+ return Err(DesktopProfileError::InvalidId);+ }+ Ok(Some(id.to_owned()))+}++/// Derives a selected profile's root from an already-resolved config path.+/// This does not consult the active-profile markers or environment.+pub(crate) fn root_for_config(config: &Config) -> Option<PathBuf> {+ root_for_config_path(&config.config_path)+}++pub(crate) fn root_for_config_path(config_path: &Path) -> Option<PathBuf> {+ let config_dir = config_path.parent()?;+ let users_dir = config_dir.parent()?;+ if users_dir.file_name().is_some_and(|name| name == "users") {+ return users_dir.parent().map(Path::to_path_buf);+ }+ Some(config_dir.to_path_buf())+}++/// Resolves the profile root implied by `OPENHUMAN_WORKSPACE` without loading+/// a config or consulting active-profile markers.+pub(crate) fn root_for_workspace_override() -> Option<PathBuf> {+ let workspace = std::env::var_os("OPENHUMAN_WORKSPACE")+ .filter(|value| !value.is_empty())+ .map(PathBuf::from)?;+ let (config_dir, _) = crate::config::resolve_config_dir_for_workspace(&workspace);+ let config = Config {+ config_path: config_dir.join("config.toml"),+ ..Config::default()+ };+ root_for_config(&config)+}++/// Profile id represented by a config path, if it is in `<root>/users/<id>`.+pub(crate) fn id_for_config(config: &Config) -> Option<String> {+ let config_dir = config.config_path.parent()?;+ let users_dir = config_dir.parent()?;+ if !users_dir.file_name().is_some_and(|name| name == "users") {+ return None;+ }+ let id = config_dir.file_name()?.to_str()?;+ is_profile_path_segment(id).then(|| id.to_owned())+}++pub(crate) fn is_profile_path_segment(id: &str) -> bool {+ if id.is_empty() || id.chars().any(char::is_control) || id.contains(['/', '\\']) {+ return false;+ }+ let mut components = Path::new(id).components();+ matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()+}++async fn read_layout_version(dir: &Path) -> Result<LayoutVersion, DesktopProfileError> {+ let marker = dir.join(".layout");+ match tokio::fs::read_to_string(&marker).await {+ Ok(value) if value.trim() == "2" => Ok(LayoutVersion::V2),+ Ok(_) => Err(DesktopProfileError::UnknownLayoutMarker),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ Ok(LayoutVersion::detect(dir))+ }+ Err(_) => Err(DesktopProfileError::UnknownLayoutMarker),+ }+}++pub(crate) fn built_in_checks() -> Vec<Arc<dyn DoctorCheck>> {+ let mut checks: Vec<Arc<dyn DoctorCheck>> = vec![Arc::new(ProfileExistsCheck)];+ checks.extend(crate::doctor::checks::inference_catalog::built_in_checks());+ checks+}++struct ProfileExistsCheck;++#[async_trait]+impl DoctorCheck for ProfileExistsCheck {+ fn id(&self) -> &str {+ "profile/exists"+ }++ fn category(&self) -> &str {+ "profile"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ if ctx.config_source() == super::contract::DoctorConfigSource::Tenant {+ return vec![Finding::skipped(+ self.id(),+ "Tenant profile readiness is reported by the hosted profile checks.",+ "No action required.",+ )];+ }+ match ctx.profile_status() {+ Some(DoctorProfileStatus::Valid) => {+ vec![Finding::pass(+ self.id(),+ "The selected profile exists and its config is valid.",+ )]+ }+ Some(DoctorProfileStatus::Missing) => vec![Finding::error(+ self.id(),+ DesktopProfileError::Missing.message(),+ "Select an existing desktop profile and rerun doctor.",+ )],+ Some(DoctorProfileStatus::UnknownLayoutMarker) => vec![Finding::error(+ self.id(),+ DesktopProfileError::UnknownLayoutMarker.message(),+ "Use a profile with a supported layout marker and rerun doctor.",+ )],+ Some(DoctorProfileStatus::InvalidConfig) => vec![Finding::error(+ self.id(),+ DesktopProfileError::InvalidConfig.message(),+ "Repair the selected profile config and rerun doctor.",+ )],+ None => vec![Finding::skipped(+ self.id(),+ "No desktop profile was selected for this run.",+ "Pass --profile <id> to validate a specific profile.",+ )],+ }+ }+}++#[cfg(test)]+#[path = "profile_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/doctor/profile_inspection_tests.rs b/crates/openhuman-core/src/doctor/profile_inspection_tests.rsnew file mode 100644index 0000000000..3d32d900fb--- /dev/null+++ b/crates/openhuman-core/src/doctor/profile_inspection_tests.rs@@ -0,0 +1,341 @@+use super::*;++#[tokio::test]+async fn selected_profile_reports_preserve_parent_check_sources_without_using_parent_state() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let account_a = ProfileLayout::new(root, "account-a");+ let account_b = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&account_a.dir).await.unwrap();+ tokio::fs::create_dir_all(&account_b.dir).await.unwrap();+ tokio::fs::write(+ &account_a.config_path,+ "api_url = \"https://account-a.example\"\n",+ )+ .await+ .unwrap();+ tokio::fs::write(+ &account_b.config_path,+ "api_url = \"https://account-b.example\"\n[components]\nmemory = false\n",+ )+ .await+ .unwrap();++ let mut account_a_config = Config {+ config_path: account_a.config_path.clone(),+ workspace_dir: account_a.workspace_dir.clone(),+ api_url: Some("https://account-a.example".into()),+ ..Config::default()+ };+ account_a_config.components.memory = true;+ let parent = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::kernel(),+ account_a_config.clone(),+ )+ .derive_with(+ crate::core::runtime::ContextOverlay::new(+ account_a_config,+ crate::core::runtime::DomainSet::kernel(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .without_user_skill_roots(),+ );++ let observed = Arc::new(Mutex::new(Vec::new()));+ let parent_state = parent.agent_state().slot::<InspectionStateSentinel>();+ crate::doctor::register_check_source_in(+ parent.extensions(),+ SelectedProfileContextSource {+ observed: observed.clone(),+ parent_state: Some(parent_state),+ },+ );+ let before = snapshot_tree(root);+ let explicit_outcome = crate::core::runtime::CoreContext::scope(parent.clone(), async {+ crate::doctor::ops::doctor_report_for_selected_profile(+ root,+ "account-b",+ selected_profile_context_options(),+ )+ .await+ })+ .await+ .unwrap();+ let selection = crate::core::runtime::CoreContext::scope(parent.clone(), async {+ resolve_desktop_profile_for_doctor(root, Some("account-b")).await+ })+ .await+ .unwrap();+ let selection_outcome = crate::core::runtime::CoreContext::scope(parent.clone(), async {+ crate::doctor::ops::doctor_report_for_desktop_selection(+ selection,+ selected_profile_context_options(),+ )+ .await+ })+ .await+ .unwrap();++ for report in [explicit_outcome.value, selection_outcome.value] {+ assert!(!report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"));+ assert!(report+ .checks_run+ .iter()+ .any(|id| id == "hosted/selected-profile-context"));+ assert_eq!(report.profile.as_deref(), Some("account-b"));+ }+ let observations = observed.lock().unwrap();+ assert_eq!(observations.len(), 2);+ for observation in observations.iter() {+ assert_eq!(observation.doctor_workspace, account_b.workspace_dir);+ assert_eq!(observation.doctor_config_path, account_b.config_path);+ assert_eq!(+ observation.doctor_api_url.as_deref(),+ Some("https://account-b.example")+ );+ assert_eq!(observation.ambient_workspace, account_b.workspace_dir);+ assert_eq!(observation.domains, {+ let mut domains = crate::core::runtime::DomainSet::kernel();+ domains.memory = false;+ domains+ });+ assert_eq!(+ observation.tool_groups,+ crate::tools::toolpacks::ToolGroups::none()+ );+ assert!(!observation.user_skill_roots);+ assert!(!observation.components.memory);+ assert!(!observation.ambient_components.memory);+ assert_eq!(observation.tenant_profile, None);+ assert!(!observation.state_shared_with_parent);+ }+ assert_eq!(before, snapshot_tree(root));+}++#[tokio::test]+async fn selected_profile_is_ambient_for_process_sources_without_a_parent_context() {+ const CHILD_MARKER: &str = "OPENHUMAN_DOCTOR_NO_PARENT_CHILD";+ if std::env::var_os(CHILD_MARKER).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "doctor::profile::tests::inspection::selected_profile_is_ambient_for_process_sources_without_a_parent_context",+ "--nocapture",+ ])+ .env(CHILD_MARKER, "1")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "isolated child failed: stdout={} stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ return;+ }++ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ assert!(crate::core::runtime::CoreContext::current().is_none());++ let temp = TempDir::new().unwrap();+ let layout = ProfileLayout::new(temp.path(), "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(+ &layout.config_path,+ "api_url = \"https://account-b.example\"\n[components]\nmemory = false\n",+ )+ .await+ .unwrap();++ let observed = Arc::new(Mutex::new(Vec::new()));+ let source_id = "doctor-selected-profile-process-context";+ crate::doctor::register_check_source(ProcessSelectedProfileContextSource(observed.clone()));+ let outcome = crate::doctor::ops::doctor_report_for_selected_profile(+ temp.path(),+ "account-b",+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["hosted/process-selected-profile-context".into()],+ ..DoctorOptions::default()+ },+ )+ .await;+ crate::doctor::registry::unregister_check_source(source_id);+ let report = outcome.unwrap().value;++ assert!(+ report+ .checks_run+ .iter()+ .any(|id| id == "hosted/process-selected-profile-context"),+ "checks_run={:?}, findings={:?}",+ report.checks_run,+ report.findings+ );+ let observations = observed.lock().unwrap();+ assert_eq!(observations.len(), 1);+ assert_eq!(+ observations[0].ambient_workspace.as_deref(),+ Some(layout.workspace_dir.as_path())+ );+ assert_eq!(observations[0].tenant_profile, None);+ assert_eq!(observations[0].ambient_memory_component, Some(false));+}++struct ProcessSelectedProfileContextSource(Arc<Mutex<Vec<ProcessSelectedProfileObservation>>>);++struct ProcessSelectedProfileObservation {+ ambient_workspace: Option<std::path::PathBuf>,+ tenant_profile: Option<String>,+ ambient_memory_component: Option<bool>,+}++struct ProcessSelectedProfileContextCheck(Arc<Mutex<Vec<ProcessSelectedProfileObservation>>>);++#[async_trait::async_trait]+impl DoctorCheck for ProcessSelectedProfileContextCheck {+ fn id(&self) -> &str {+ "hosted/process-selected-profile-context"+ }++ fn category(&self) -> &str {+ "hosted"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ let ambient_workspace = crate::core::runtime::CoreContext::current_embedder_config()+ .map(|config| config.workspace_dir);+ let tenant_profile = crate::core::runtime::current_tenant()+ .ok()+ .and_then(|tenant| tenant.profile);+ let ambient_memory_component =+ crate::core::runtime::CoreContext::current().map(|context| context.components().memory);+ self.0+ .lock()+ .unwrap()+ .push(ProcessSelectedProfileObservation {+ ambient_workspace,+ tenant_profile,+ ambient_memory_component,+ });+ vec![Finding::pass(+ self.id(),+ "The selected profile is ambient to host checks.",+ )]+ }+}++impl DoctorCheckSource for ProcessSelectedProfileContextSource {+ fn id(&self) -> &str {+ "doctor-selected-profile-process-context"+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(ProcessSelectedProfileContextCheck(self.0.clone()))]+ }+}++fn selected_profile_context_options() -> DoctorOptions {+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["hosted/selected-profile-context".into()],+ ..DoctorOptions::default()+ }+}++struct SelectedProfileContextObservation {+ doctor_workspace: std::path::PathBuf,+ doctor_config_path: std::path::PathBuf,+ doctor_api_url: Option<String>,+ ambient_workspace: std::path::PathBuf,+ domains: crate::core::runtime::DomainSet,+ tool_groups: crate::tools::toolpacks::ToolGroups,+ user_skill_roots: bool,+ components: crate::core::runtime::ComponentSet,+ ambient_components: crate::core::runtime::ComponentSet,+ tenant_profile: Option<String>,+ state_shared_with_parent: bool,+}++#[derive(Default)]+struct InspectionStateSentinel;++struct SelectedProfileContextCheck {+ observed: Arc<Mutex<Vec<SelectedProfileContextObservation>>>,+ parent_state: Option<Arc<InspectionStateSentinel>>,+}++#[async_trait::async_trait]+impl DoctorCheck for SelectedProfileContextCheck {+ fn id(&self) -> &str {+ "hosted/selected-profile-context"+ }++ fn category(&self) -> &str {+ "hosted"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let current = crate::core::runtime::CoreContext::current().unwrap();+ let ambient = crate::core::runtime::CoreContext::current_embedder_config().unwrap();+ let context_state = current.agent_state().slot::<InspectionStateSentinel>();+ let tenant_profile = crate::core::runtime::current_tenant()+ .ok()+ .and_then(|tenant| tenant.profile);+ self.observed+ .lock()+ .unwrap()+ .push(SelectedProfileContextObservation {+ doctor_workspace: ctx.config().workspace_dir.clone(),+ doctor_config_path: ctx.config().config_path.clone(),+ doctor_api_url: ctx.config().api_url.clone(),+ ambient_workspace: ambient.workspace_dir,+ domains: current.domains(),+ tool_groups: current.tool_groups(),+ user_skill_roots: current.user_skill_roots(),+ components: ctx.components(),+ ambient_components: current.components(),+ tenant_profile,+ state_shared_with_parent: self+ .parent_state+ .as_ref()+ .is_some_and(|parent| Arc::ptr_eq(parent, &context_state)),+ });+ vec![Finding::pass(+ self.id(),+ "The selected profile context and host check source are available.",+ )]+ }+}++struct SelectedProfileContextSource {+ observed: Arc<Mutex<Vec<SelectedProfileContextObservation>>>,+ parent_state: Option<Arc<InspectionStateSentinel>>,+}++impl DoctorCheckSource for SelectedProfileContextSource {+ fn id(&self) -> &str {+ "doctor-selected-profile-context"+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(SelectedProfileContextCheck {+ observed: self.observed.clone(),+ parent_state: self.parent_state.clone(),+ })]+ }+}diff --git a/crates/openhuman-core/src/doctor/profile_tests.rs b/crates/openhuman-core/src/doctor/profile_tests.rsnew file mode 100644index 0000000000..be08888d41--- /dev/null+++ b/crates/openhuman-core/src/doctor/profile_tests.rs@@ -0,0 +1,746 @@+use std::collections::{BTreeMap, HashMap};+use std::ffi::OsString;+use std::path::Path;+use std::sync::{Arc, Mutex};++use tempfile::TempDir;++use crate::config::Config;+use crate::doctor::profile::{+ load_desktop_profile, resolve_desktop_profile_for_doctor, DesktopProfileError,+};+use crate::doctor::{+ DoctorCheck, DoctorCheckSource, DoctorConfigSource, DoctorCtx, DoctorOptions, DoctorTier,+ Finding, FindingSeverity,+};+use crate::profiles::ProfileLayout;+use crate::security::credentials::{+ session_support::get_session_token, AuthService, APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+};++fn config_for(layout: &ProfileLayout) -> Config {+ Config {+ config_path: layout.config_path.clone(),+ workspace_dir: layout.workspace_dir.clone(),+ action_dir: layout.sandbox_dir.clone(),+ ..Config::default()+ }+}++struct WorkspaceOverrideGuard(Option<OsString>);++impl WorkspaceOverrideGuard {+ fn set(path: &std::path::Path) -> Self {+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");+ std::env::set_var("OPENHUMAN_WORKSPACE", path);+ Self(previous)+ }++ fn clear() -> Self {+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");+ std::env::remove_var("OPENHUMAN_WORKSPACE");+ Self(previous)+ }+}++impl Drop for WorkspaceOverrideGuard {+ fn drop(&mut self) {+ if let Some(previous) = self.0.take() {+ std::env::set_var("OPENHUMAN_WORKSPACE", previous);+ } else {+ std::env::remove_var("OPENHUMAN_WORKSPACE");+ }+ }+}++struct SecretBackendOverrideGuard;++impl Drop for SecretBackendOverrideGuard {+ fn drop(&mut self) {+ crate::security::secret_storage::clear_secret_backend();+ }+}++#[tokio::test]+async fn explicit_profile_reads_its_own_session_without_switching_active_user() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ tokio::fs::create_dir_all(root).await.unwrap();+ let active_user_path = root.join("active_user.toml");+ tokio::fs::write(&active_user_path, "user_id = \"account-a\"\n")+ .await+ .unwrap();++ let account_a = ProfileLayout::new(root, "account-a");+ tokio::fs::create_dir_all(&account_a.dir).await.unwrap();+ tokio::fs::write(+ &account_a.config_path,+ "default_model = \"account-a-model\"\n",+ )+ .await+ .unwrap();+ AuthService::from_config(&config_for(&account_a))+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ "account-a-session",+ HashMap::new(),+ true,+ )+ .unwrap();++ let account_b = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&account_b.dir).await.unwrap();+ tokio::fs::write(+ &account_b.config_path,+ "default_model = \"account-b-model\"\n",+ )+ .await+ .unwrap();++ let active_user_before = tokio::fs::read(&active_user_path).await.unwrap();+ let _workspace_override = WorkspaceOverrideGuard::set(&account_a.workspace_dir);+ let selected = load_desktop_profile(root, "account-b").await.unwrap();++ assert_eq!(selected.config.config_path, account_b.config_path);+ assert_eq!(selected.config.workspace_dir, account_b.workspace_dir);+ assert_eq!(selected.layout.version, account_b.version);+ assert_eq!(+ selected.config.default_model.as_deref(),+ Some("account-b-model")+ );+ assert_eq!(get_session_token(&selected.config).unwrap(), None);+ assert_eq!(+ get_session_token(&config_for(&account_a))+ .unwrap()+ .as_deref(),+ Some("account-a-session")+ );+ assert_eq!(+ tokio::fs::read(&active_user_path).await.unwrap(),+ active_user_before+ );+}++#[tokio::test]+async fn inspecting_selected_profile_credentials_does_not_quarantine_corrupt_auth_store(+) -> Result<(), String> {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ let temp = TempDir::new().unwrap();+ let layout = ProfileLayout::new(temp.path(), "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(&layout.config_path, "secrets.encrypt = false\n")+ .await+ .unwrap();+ let profiles_path = layout.dir.join("auth-profiles.json");+ let original = b"not valid auth profile json";+ tokio::fs::write(&profiles_path, original).await.unwrap();++ let selected = load_desktop_profile(temp.path(), "account-b")+ .await+ .unwrap();+ let result = crate::security::credentials::session_support::load_app_session_profile_read_only(+ &selected.config,+ );+ let after = tokio::fs::read(&profiles_path).await;+ if result.is_ok() {+ return Err("a corrupt credential store must be reported as unavailable".into());+ }+ let after = after.map_err(|_| "doctor removed the corrupt credential store".to_string())?;+ if after != original {+ return Err("doctor modified the corrupt credential store".into());+ }+ Ok(())+}++#[tokio::test]+async fn selected_profile_auth_snapshot_reads_its_backend_without_mutating_profile_files() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ #[cfg(target_os = "macos")]+ let temp = TempDir::new_in("/private/tmp").unwrap();+ #[cfg(not(target_os = "macos"))]+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let account_a = ProfileLayout::new(root, "account-a");+ let account_b = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&account_a.dir).await.unwrap();+ tokio::fs::create_dir_all(&account_b.dir).await.unwrap();+ tokio::fs::create_dir_all(&account_a.workspace_dir)+ .await+ .unwrap();+ tokio::fs::create_dir_all(&account_b.workspace_dir)+ .await+ .unwrap();+ tokio::fs::write(&account_b.config_path, "secrets.encrypt = true\n")+ .await+ .unwrap();+ let profiles_path = account_b.dir.join("auth-profiles.json");+ tokio::fs::write(+ &profiles_path,+ r#"{"schema_version":1,"active_profiles":{"app-session":"app-session:default"},"profiles":{"app-session:default":{"provider":"app-session","profile_name":"default","kind":"token","metadata":{"user_id":"account-b"}}}}"#,+ )+ .await+ .unwrap();++ let account_a_backend =+ crate::security::secret_storage::EncryptedFileBackend::new(&account_a.workspace_dir);+ let account_b_backend =+ crate::security::secret_storage::EncryptedFileBackend::new(&account_b.workspace_dir);+ use crate::security::secret_storage::SecretBackend;+ account_a_backend+ .set(+ &crate::security::secret_storage::ops::namespaced_key(+ "account-a",+ &crate::security::credentials::profiles::auth_profile_secret_key(+ "app-session:default",+ ),+ ),+ r#"{"token":"account-a-session"}"#,+ )+ .unwrap();+ account_b_backend+ .set(+ &crate::security::secret_storage::ops::namespaced_key(+ "account-b",+ &crate::security::credentials::profiles::auth_profile_secret_key(+ "app-session:default",+ ),+ ),+ r#"{"token":"account-b-session"}"#,+ )+ .unwrap();+ let _backend_override = SecretBackendOverrideGuard;+ crate::security::secret_storage::install_secret_backend(std::sync::Arc::new(account_a_backend));++ let selected = load_desktop_profile(root, "account-b").await.unwrap();+ let before = snapshot_tree(&account_b.dir);+ let profile =+ crate::security::credentials::session_support::load_app_session_profile_read_only(+ &selected.config,+ )+ .unwrap()+ .unwrap();+ let token =+ crate::security::credentials::session_support::session_token_from_profile(Some(&profile));+ let after = snapshot_tree(&account_b.dir);++ assert_eq!(token.as_deref(), Some("account-b-session"));+ assert_eq!(+ before, after,+ "doctor credential inspection must not mutate the selected profile"+ );+}++#[tokio::test]+async fn selected_profile_runs_its_context_scoped_endpoint_enricher() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(+ &layout.config_path,+ "api_url = \"https://account-b.example\"\n",+ )+ .await+ .unwrap();++ let context = crate::core::runtime::CoreContext::for_test(+ crate::core::runtime::DomainSet::full(),+ Some(layout.workspace_dir.clone()),+ );+ crate::config::register_enricher_in(+ context.extensions(),+ "doctor-selected-profile",+ |config| {+ if let Some(api_url) = &config.api_url {+ config.resolved_endpoints.control_plane_url = Some(api_url.clone());+ }+ },+ );+ let selected = crate::core::runtime::CoreContext::scope(context.clone(), async {+ resolve_desktop_profile_for_doctor(root, Some("account-b")).await+ })+ .await+ .unwrap();++ let mut profile = crate::security::credentials::profiles::AuthProfile::new_token(+ crate::security::credentials::APP_SESSION_PROVIDER,+ crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,+ "session-token".into(),+ );+ profile.metadata.insert(+ crate::security::credentials::session_support::SESSION_ISSUING_BACKEND_META.into(),+ "https://account-b.example".into(),+ );++ assert_eq!(+ selected+ .config+ .resolved_endpoints+ .control_plane_url+ .as_deref(),+ Some("https://account-b.example")+ );+ assert!(+ crate::security::credentials::session_support::check_session_backend(+ &selected.config,+ Some(&profile)+ )+ .is_ok()+ );+}++fn snapshot_tree(root: &Path) -> BTreeMap<std::path::PathBuf, Vec<u8>> {+ fn visit(root: &Path, directory: &Path, files: &mut BTreeMap<std::path::PathBuf, Vec<u8>>) {+ let entries = std::fs::read_dir(directory).unwrap();+ for entry in entries {+ let entry = entry.unwrap();+ let path = entry.path();+ if entry.file_type().unwrap().is_dir() {+ visit(root, &path, files);+ } else {+ files.insert(+ path.strip_prefix(root).unwrap().to_path_buf(),+ std::fs::read(path).unwrap(),+ );+ }+ }+ }++ let mut files = BTreeMap::new();+ visit(root, root, &mut files);+ files+}++#[tokio::test]+async fn invalid_explicit_profile_returns_one_safe_profile_exists_error() {+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(layout.dir.join(".layout"), "2\n")+ .await+ .unwrap();+ tokio::fs::write(&layout.config_path, "default_model = [\"private-value\"\n")+ .await+ .unwrap();+ let active_config = Config {+ config_path: root.join("users/account-a/config.toml"),+ ..Config::default()+ };++ let outcome = crate::doctor::ops::doctor_report_with_options(+ &active_config,+ DoctorOptions {+ tier: DoctorTier::Connect,+ profile: Some("account-b".into()),+ ..DoctorOptions::default()+ },+ )+ .await+ .unwrap();+ let report = outcome.value;++ assert_eq!(report.profile.as_deref(), Some("account-b"));+ assert_eq!(+ report.config_source,+ crate::doctor::DoctorConfigSource::Profile+ );+ assert_eq!(report.checks_run, ["profile/exists"]);+ assert!(report.checks_skipped.is_empty());+ assert_eq!(report.findings.len(), 1);+ assert_eq!(report.findings[0].check_id, "profile/exists");+ assert_eq!(+ report.findings[0].severity,+ crate::doctor::FindingSeverity::Error+ );+ assert!(!report.findings[0].message.contains("private-value"));+ assert_eq!(report.summary.error, 1);+ assert!(!report.ok);+}++#[tokio::test]+async fn malformed_default_profile_returns_only_a_safe_config_parse_error() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let active_user = root.join("active_user.toml");+ tokio::fs::write(&active_user, "user_id = \"account-b\"\n")+ .await+ .unwrap();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ let invalid_contents = b"default_temperature = \"private-value\"\n";+ tokio::fs::write(&layout.config_path, invalid_contents)+ .await+ .unwrap();+ let before = snapshot_tree(root);++ let selection = resolve_desktop_profile_for_doctor(root, None)+ .await+ .unwrap();+ let outcome = crate::doctor::ops::doctor_report_for_desktop_selection(+ selection,+ DoctorOptions {+ tier: DoctorTier::Static,+ ..DoctorOptions::default()+ },+ )+ .await+ .unwrap();++ assert_eq!(outcome.value.findings.len(), 1);+ assert_eq!(outcome.value.findings[0].check_id, "config/parse");+ assert_eq!(outcome.value.findings[0].severity, FindingSeverity::Error);+ assert_eq!(+ outcome.value.findings[0].config_path.as_deref(),+ Some("default_temperature")+ );+ assert!(!outcome.value.findings[0].message.contains("private-value"));+ assert_eq!(before, snapshot_tree(root));+}++#[tokio::test]+async fn explicit_dispatch_selection_does_not_load_the_ambient_config() {+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let active_config_path = root.join("users/account-a/config.toml");+ tokio::fs::create_dir_all(&active_config_path)+ .await+ .unwrap();+ let selected = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&selected.dir).await.unwrap();+ tokio::fs::write(+ &selected.config_path,+ "default_model = \"account-b-model\"\n",+ )+ .await+ .unwrap();+ let active_config = Config {+ config_path: active_config_path,+ workspace_dir: root.join("users/account-a/workspace"),+ ..Config::default()+ };+ let core = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ active_config,+ );+ let dispatch = crate::core::runtime::DispatchCtx::new(core);++ let outcome = crate::doctor::ops::doctor_report_for_dispatch(+ &dispatch,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["profile/exists".into()],+ profile: Some("account-b".into()),+ ..DoctorOptions::default()+ },+ )+ .await+ .unwrap();++ assert_eq!(outcome.value.profile.as_deref(), Some("account-b"));+ assert_eq!(outcome.value.checks_run, ["profile/exists"]);+ assert_eq!(outcome.value.findings[0].severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn selected_profile_context_pins_id_layout_source_and_components() {+ let temp = TempDir::new().unwrap();+ let layout = ProfileLayout::new(temp.path(), "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(&layout.config_path, "[components]\nmemory = false\n")+ .await+ .unwrap();+ let selected = resolve_desktop_profile_for_doctor(temp.path(), Some("account-b"))+ .await+ .unwrap();+ let components = crate::core::runtime::ComponentSet::from_config(&selected.config.components);+ let version = selected.layout_version;+ let profile_id = selected.profile_id.clone().unwrap();+ let resolution_source = selected.resolution_source.clone();+ let status = selected.profile_status;+ let mut ctx = DoctorCtx::from_config_with_components(selected.config, components)+ .with_profile_metadata(version, Some(resolution_source));+ ctx = ctx.with_profile(profile_id, DoctorConfigSource::Profile);+ if let Some(status) = status {+ ctx = ctx.with_profile_status(status);+ }++ assert_eq!(ctx.profile(), Some("account-b"));+ assert_eq!(ctx.config_source(), DoctorConfigSource::Profile);+ assert_eq!(ctx.profile_layout_version(), version);+ assert_eq!(ctx.profile_resolution_source(), Some("--profile"));+ assert!(!ctx.components().memory);++ let check = super::built_in_checks()+ .into_iter()+ .find(|check| check.id() == "profile/exists")+ .expect("profile existence check is registered among built-ins");+ let findings = check.detect(&ctx).await;+ assert_eq!(findings.len(), 1);+ assert_eq!(findings[0].severity, FindingSeverity::Pass);+}++#[tokio::test]+async fn report_serializes_active_profile_layout_and_resolution_source() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let active_user = root.join("active_user.toml");+ tokio::fs::write(&active_user, "user_id = \"account-b\"\n")+ .await+ .unwrap();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(layout.dir.join(".layout"), "2\n")+ .await+ .unwrap();+ tokio::fs::write(&layout.config_path, "[components]\nmemory = false\n")+ .await+ .unwrap();++ let selection = resolve_desktop_profile_for_doctor(root, None)+ .await+ .unwrap();+ let outcome = crate::doctor::ops::doctor_report_for_desktop_selection(+ selection,+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["profile/exists".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .unwrap();+ let json = serde_json::to_value(outcome.value).unwrap();++ assert_eq!(+ json.get("profile_layout_version")+ .and_then(serde_json::Value::as_u64),+ Some(2)+ );+ assert_eq!(+ json.get("config_resolution_source")+ .and_then(serde_json::Value::as_str),+ Some("active_user.toml")+ );+}++#[path = "profile_inspection_tests.rs"]+mod inspection;++#[tokio::test]+async fn selected_profile_applies_in_memory_legacy_migrations_without_saving_them() {+ let temp = TempDir::new().unwrap();+ let layout = ProfileLayout::new(temp.path(), "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ let contents = "api_url = \"https://custom.example/v1/chat/completions\"\n";+ tokio::fs::write(&layout.config_path, contents)+ .await+ .unwrap();++ let selected = load_desktop_profile(temp.path(), "account-b")+ .await+ .unwrap();++ assert_eq!(selected.config.api_url, None);+ assert_eq!(+ selected.config.inference_url.as_deref(),+ Some("https://custom.example/v1/chat/completions")+ );+ assert!(selected+ .config+ .load_diagnostics()+ .migrated_keys+ .contains(&"api_url".to_string()));+ assert_eq!(+ tokio::fs::read_to_string(&layout.config_path)+ .await+ .unwrap(),+ contents+ );+}++#[tokio::test]+async fn default_profile_resolution_reads_active_marker_without_initializing_layout() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let _workspace_override = WorkspaceOverrideGuard::clear();+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let marker = root.join("active_user.toml");+ tokio::fs::create_dir_all(root).await.unwrap();+ tokio::fs::write(&marker, "user_id = \"account-a\"\n")+ .await+ .unwrap();+ let layout = ProfileLayout::new(root, "account-a");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(&layout.config_path, "default_model = \"account-a-model\"\n")+ .await+ .unwrap();+ let marker_before = tokio::fs::read(&marker).await.unwrap();++ let selected = resolve_desktop_profile_for_doctor(root, None)+ .await+ .unwrap();++ assert_eq!(selected.profile_id.as_deref(), Some("account-a"));+ assert_eq!(selected.layout_version, Some(layout.version));+ assert_eq!(selected.resolution_source, "active_user.toml");+ assert_eq!(+ selected.config.default_model.as_deref(),+ Some("account-a-model")+ );+ assert!(!layout.dir.join(".layout").exists());+ assert_eq!(tokio::fs::read(&marker).await.unwrap(), marker_before);+}++#[tokio::test]+async fn default_profile_resolution_prefers_workspace_override_without_switching_user() {+ let _env_guard = crate::config::TEST_ENV_LOCK.lock().await;+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ tokio::fs::create_dir_all(root).await.unwrap();+ let active_user = root.join("active_user.toml");+ tokio::fs::write(&active_user, "user_id = \"account-a\"\n")+ .await+ .unwrap();+ let account_b = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&account_b.dir).await.unwrap();+ tokio::fs::write(account_b.dir.join(".layout"), "2\n")+ .await+ .unwrap();+ tokio::fs::write(+ &account_b.config_path,+ "default_model = \"account-b-model\"\n",+ )+ .await+ .unwrap();+ let marker_before = tokio::fs::read(&active_user).await.unwrap();+ let _workspace_override = WorkspaceOverrideGuard::set(&account_b.files_dir);++ let selected = resolve_desktop_profile_for_doctor(root, None)+ .await+ .unwrap();++ assert_eq!(selected.profile_id.as_deref(), Some("account-b"));+ assert_eq!(+ selected.layout_version,+ Some(crate::config::schema::profile_layout::LayoutVersion::V2)+ );+ assert_eq!(selected.resolution_source, "OPENHUMAN_WORKSPACE");+ assert_eq!(selected.config.workspace_dir, account_b.files_dir);+ assert_eq!(+ selected.config.default_model.as_deref(),+ Some("account-b-model")+ );+ assert_eq!(tokio::fs::read(&active_user).await.unwrap(), marker_before);+ assert_eq!(+ tokio::fs::read_to_string(account_b.dir.join(".layout"))+ .await+ .unwrap(),+ "2\n"+ );+}++#[tokio::test]+async fn missing_profile_is_reported_without_creating_or_switching_a_profile() {+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let active_user_path = root.join("active_user.toml");+ tokio::fs::create_dir_all(root).await.unwrap();+ tokio::fs::write(&active_user_path, "user_id = \"account-a\"\n")+ .await+ .unwrap();+ let marker_before = tokio::fs::read(&active_user_path).await.unwrap();++ let result = load_desktop_profile(root, "missing").await;++ assert!(matches!(result, Err(DesktopProfileError::Missing)));+ assert!(!root.join("users/missing").exists());+ assert_eq!(+ tokio::fs::read(&active_user_path).await.unwrap(),+ marker_before+ );+}++#[tokio::test]+async fn unknown_layout_marker_is_rejected_without_repairing_it() {+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(layout.dir.join(".layout"), "99\n")+ .await+ .unwrap();+ tokio::fs::write(&layout.config_path, "default_model = \"account-b-model\"\n")+ .await+ .unwrap();++ let result = load_desktop_profile(root, "account-b").await;++ assert!(matches!(+ result,+ Err(DesktopProfileError::UnknownLayoutMarker)+ ));+ assert_eq!(+ tokio::fs::read_to_string(layout.dir.join(".layout"))+ .await+ .unwrap(),+ "99\n"+ );+}++#[tokio::test]+async fn invalid_profile_config_is_rejected_without_persisting_recovery() {+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();+ tokio::fs::write(layout.dir.join(".layout"), "2\n")+ .await+ .unwrap();+ let invalid = "default_model = [\"unfinished\"\n";+ tokio::fs::write(&layout.config_path, invalid)+ .await+ .unwrap();+ tokio::fs::write(layout.config_path.with_extension("toml.bak"), "")+ .await+ .unwrap();++ let result = load_desktop_profile(root, "account-b").await;++ assert!(matches!(result, Err(DesktopProfileError::InvalidConfig)));+ assert_eq!(+ tokio::fs::read_to_string(&layout.config_path)+ .await+ .unwrap(),+ invalid+ );+ assert_eq!(+ tokio::fs::read_to_string(layout.config_path.with_extension("toml.bak"))+ .await+ .unwrap(),+ ""+ );+}++#[tokio::test]+async fn empty_profile_resolution_does_not_write_a_layout_marker() {+ let temp = TempDir::new().unwrap();+ let root = temp.path();+ let layout = ProfileLayout::new(root, "account-b");+ tokio::fs::create_dir_all(&layout.dir).await.unwrap();++ let _ = load_desktop_profile(root, "account-b").await;++ assert!(!layout.dir.join(".layout").exists());+}diff --git a/crates/openhuman-core/src/doctor/registry.rs b/crates/openhuman-core/src/doctor/registry.rsnew file mode 100644index 0000000000..d2b8c39fd4--- /dev/null+++ b/crates/openhuman-core/src/doctor/registry.rs@@ -0,0 +1,109 @@+//! Built-in checks and the generic host check-source registry.++use std::collections::HashSet;+use std::sync::Arc;++use crate::core::slots::{Extensions, HookSlot};++use super::contract::{DoctorCheck, DoctorCtx};++/// A host-owned group of checks. The core stores the source without knowing+/// which host or service supplies it.+pub trait DoctorCheckSource: Send + Sync {+ /// Stable source id, used for replacement and diagnostics.+ fn id(&self) -> &str;+ /// Checks contributed by this source.+ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>>;+ /// Checks contributed for the selected doctor configuration.+ ///+ /// Existing host sources remain context-free by default. Sources whose+ /// identifiers or check set depends on the effective configuration can+ /// override this method and must use `ctx`, not ambient process state.+ fn checks_for(&self, _ctx: &DoctorCtx) -> Vec<Arc<dyn DoctorCheck>> {+ self.checks()+ }+}++static CHECK_SOURCES: HookSlot<Arc<dyn DoctorCheckSource>> =+ HookSlot::new("doctor::registry::sources");++/// Registers a check source for the whole process.+pub fn register_check_source(source: impl DoctorCheckSource + 'static) {+ let source: Arc<dyn DoctorCheckSource> = Arc::new(source);+ let id = source.id().to_owned();+ CHECK_SOURCES.register(id, source);+}++/// Registers a check source for the context built from `extensions`.+pub fn register_check_source_in(extensions: &Extensions, source: impl DoctorCheckSource + 'static) {+ let source: Arc<dyn DoctorCheckSource> = Arc::new(source);+ let id = source.id().to_owned();+ CHECK_SOURCES.register_in(extensions, id, source);+}++/// Removes a process-wide source, primarily for isolated tests and hosts that+/// explicitly shut down a dynamically loaded check provider.+pub fn unregister_check_source(id: &str) -> bool {+ CHECK_SOURCES.unregister(id)+}++/// The checks available in the active context, with duplicate and malformed+/// ids rejected before a report starts.+pub fn registered_checks() -> Result<Vec<Arc<dyn DoctorCheck>>, String> {+ let mut checks = Vec::new();+ checks.extend(super::profile::built_in_checks());+ checks.extend(super::checks::builtins());+ for (_, source) in CHECK_SOURCES.entries() {+ checks.extend(source.checks());+ }++ validate_checks(checks)+}++/// The checks available for the selected doctor context, with duplicate and+/// malformed ids rejected before a report starts.+pub fn registered_checks_for(ctx: &DoctorCtx) -> Result<Vec<Arc<dyn DoctorCheck>>, String> {+ let mut checks = Vec::new();+ checks.extend(super::profile::built_in_checks());+ checks.extend(super::checks::builtins());+ checks.extend(super::checks::for_context(ctx));+ for (_, source) in CHECK_SOURCES.entries() {+ checks.extend(source.checks_for(ctx));+ }++ validate_checks(checks)+}++fn validate_checks(checks: Vec<Arc<dyn DoctorCheck>>) -> Result<Vec<Arc<dyn DoctorCheck>>, String> {+ let mut ids = HashSet::with_capacity(checks.len());+ for check in &checks {+ let id = check.id();+ if id == "doctor/selection" {+ return Err("doctor/selection is reserved by the runner".into());+ }+ if !valid_check_id(id) {+ return Err(format!(+ "doctor check id must use lowercase area/name form: {id}"+ ));+ }+ if !ids.insert(id.to_owned()) {+ return Err(format!("duplicate doctor check id: {id}"));+ }+ }+ Ok(checks)+}++fn valid_check_id(id: &str) -> bool {+ let mut segments = 0;+ for segment in id.split('/') {+ if segment.is_empty()+ || !segment.bytes().all(|byte| {+ byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')+ })+ {+ return false;+ }+ segments += 1;+ }+ segments >= 2+}diff --git a/crates/openhuman-core/src/doctor/runner.rs b/crates/openhuman-core/src/doctor/runner.rsnew file mode 100644index 0000000000..d4cbd1660f--- /dev/null+++ b/crates/openhuman-core/src/doctor/runner.rs@@ -0,0 +1,195 @@+//! Bounded async execution, filtering, and report assembly.++use std::collections::HashSet;+use std::sync::{Arc, LazyLock};+use std::time::Instant;++use futures::stream::{FuturesUnordered, StreamExt};+use tokio::sync::{OwnedSemaphorePermit, Semaphore};++use super::contract::{+ DoctorCheck, DoctorCtx, DoctorOptions, DoctorReport, DoctorSummary, Finding,+};+use super::registry;++const MAX_CONCURRENT_CHECKS: usize = 8;+static CHECK_SEMAPHORE: LazyLock<Arc<Semaphore>> =+ LazyLock::new(|| Arc::new(Semaphore::new(MAX_CONCURRENT_CHECKS)));++/// Runs registered checks using exact-id filters and stable report ordering.+pub(super) async fn run(ctx: &DoctorCtx, options: DoctorOptions) -> Result<DoctorReport, String> {+ let checks = registry::registered_checks_for(ctx)?;+ let check_ids = checks+ .iter()+ .map(|check| check.id().to_owned())+ .collect::<HashSet<_>>();+ let only = options.only.into_iter().collect::<HashSet<_>>();+ let skip = options.skip.into_iter().collect::<HashSet<_>>();+ let has_unknown_selector = only+ .iter()+ .chain(skip.iter())+ .any(|id| !check_ids.contains(id));+ let _reserved_profile_input = options.profile;++ let mut evaluated = Vec::new();+ let mut runnable = Vec::new();++ for (index, check) in checks.into_iter().enumerate() {+ let id = check.id().to_owned();+ if (!only.is_empty() && !only.contains(&id)) || skip.contains(&id) {+ continue;+ }++ if !options.tier.includes(check.tier()) {+ evaluated.push((+ index,+ id.clone(),+ vec![Finding::skipped(+ &id,+ format!(+ "The {} check is above the requested tier.",+ check.category()+ ),+ "Request a higher doctor tier and rerun the check.",+ )],+ true,+ ));+ continue;+ }++ if let Some(component) = check.component_gate() {+ if !component.enabled(&ctx.components()) {+ let name = component.as_str();+ evaluated.push((+ index,+ id.clone(),+ vec![Finding::skipped(+ &id,+ format!("The required {name} component is disabled."),+ format!("Enable the {name} component and rerun doctor."),+ )],+ true,+ ));+ continue;+ }+ }+ runnable.push((index, check));+ }++ let mut tasks = FuturesUnordered::new();+ for (index, check) in runnable {+ tasks.push(execute_one(index, check, ctx.clone()));+ }+ let mut outcomes = Vec::new();+ while let Some(outcome) = tasks.next().await {+ outcomes.push(outcome);+ }+ evaluated.append(&mut outcomes);+ evaluated.sort_by_key(|(index, _, _, _)| *index);++ let mut checks_run = Vec::new();+ let mut checks_skipped = Vec::new();+ let mut findings = Vec::new();+ for (_, id, mut check_findings, was_skipped) in evaluated {+ if was_skipped {+ checks_skipped.push(id);+ } else {+ checks_run.push(id);+ }+ findings.append(&mut check_findings);+ }++ if has_unknown_selector {+ findings.push(Finding::error(+ "doctor/selection",+ "One or more selected check ids are not registered.",+ "Use a registered exact check id from the doctor report.",+ ));+ }++ let summary = DoctorSummary::from_findings(&findings);+ let ok = summary.error == 0;+ Ok(DoctorReport {+ schema_version: 2,+ profile: ctx.profile().map(str::to_owned),+ config_source: ctx.config_source(),+ profile_layout_version: ctx.profile_layout_version().map(|version| match version {+ crate::config::schema::profile_layout::LayoutVersion::V1 => 1,+ crate::config::schema::profile_layout::LayoutVersion::V2 => 2,+ }),+ config_resolution_source: ctx.profile_resolution_source().map(str::to_owned),+ tier: options.tier,+ checks_run,+ checks_skipped,+ findings,+ summary,+ ok,+ })+}++async fn execute_one(+ index: usize,+ check: Arc<dyn DoctorCheck>,+ ctx: DoctorCtx,+) -> (usize, String, Vec<Finding>, bool) {+ let id = check.id().to_owned();+ let timeout = check.timeout();+ let started = Instant::now();+ let detection = detect(check, ctx);+ let result = tokio::time::timeout(timeout, detection).await;+ let duration_ms = elapsed_ms(started.elapsed());+ let mut findings = match result {+ Ok(Ok(mut findings)) => {+ if findings.is_empty() {+ findings.push(Finding::pass(&id, "The check completed without findings."));+ }+ findings+ }+ Ok(Err(_)) => vec![Finding::error(+ &id,+ "The check worker failed.",+ "Review the check's local dependencies and rerun doctor.",+ )],+ Err(_) => vec![Finding::error(+ &id,+ format!("The check timed out after {} ms.", timeout.as_millis()),+ "Review the check's dependencies and rerun doctor.",+ )],+ };+ for finding in &mut findings {+ finding.check_id.clone_from(&id);+ finding.duration_ms = duration_ms;+ if finding.fix_hint.trim().is_empty() {+ finding.fix_hint = "Review the check result and rerun doctor.".into();+ }+ }+ (index, id, findings, false)+}++async fn detect(check: Arc<dyn DoctorCheck>, ctx: DoctorCtx) -> Result<Vec<Finding>, ()> {+ // Include permit acquisition in the per-check budget, so queued work+ // cannot wait forever behind blocking probes that outlive a timeout.+ let permit: OwnedSemaphorePermit = Arc::clone(&CHECK_SEMAPHORE)+ .acquire_owned()+ .await+ .map_err(|_| ())?;+ if check.is_blocking() {+ tokio::task::spawn_blocking(move || {+ let result = check.detect_blocking(&ctx).ok_or(());+ // A blocking worker cannot be cancelled after it has started. It+ // retains the process-wide slot after its caller times out.+ drop(permit);+ result+ })+ .await+ .map_err(|_| ())?+ } else {+ let findings = check.detect(&ctx).await;+ drop(permit);+ Ok(findings)+ }+}++fn elapsed_ms(duration: std::time::Duration) -> u64 {+ duration.as_millis().min(u64::MAX as u128) as u64+}diff --git a/crates/openhuman-core/src/doctor/runner_tests.rs b/crates/openhuman-core/src/doctor/runner_tests.rsnew file mode 100644index 0000000000..182f879ff0--- /dev/null+++ b/crates/openhuman-core/src/doctor/runner_tests.rs@@ -0,0 +1,716 @@+use std::path::Path;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::Duration;++use crate::config::Config;+use crate::core::runtime::{ComponentSet, CoreContext, DomainSet};+use crate::core::slots::Extensions;+use async_trait::async_trait;++use super::contract::{+ DoctorCheck, DoctorConfigSource, DoctorCtx, DoctorOptions, DoctorTier, Finding, FindingSeverity,+};+use super::registry::{register_check_source_in, DoctorCheckSource};+use super::runner;+use super::test_support::{FakeCheck, FakeCheckSource};++fn isolated_config(root: &Path) -> Config {+ let mut config = Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.join("actions");+ config.config_path = root.join("config.toml");+ config+}++fn scoped_config_context(config: Config, extensions: Extensions) -> Arc<CoreContext> {+ CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions).derive_with(+ crate::core::runtime::ContextOverlay::new(config, DomainSet::full(), Default::default())+ .without_user_skill_roots(),+ )+}++#[test]+fn no_unwritten_daemon_state_check_is_registered() {+ let checks = super::registry::registered_checks().expect("built-in checks are valid");++ assert!(+ checks.iter().all(|check| check.id() != "runtime/daemon"),+ "the doctor must not advertise a daemon state check whose file is never written"+ );+}++struct BlockingProbe {+ id: String,+ timeout: Duration,+ active: Arc<AtomicUsize>,+ peak: Arc<AtomicUsize>,+}++#[async_trait]+impl DoctorCheck for BlockingProbe {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ "test"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn timeout(&self) -> Duration {+ self.timeout+ }++ fn is_blocking(&self) -> bool {+ true+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ Vec::new()+ }++ fn detect_blocking(&self, _ctx: &DoctorCtx) -> Option<Vec<Finding>> {+ let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;+ self.peak.fetch_max(active, Ordering::SeqCst);+ std::thread::sleep(Duration::from_millis(500));+ self.active.fetch_sub(1, Ordering::SeqCst);+ Some(vec![Finding::pass(+ &self.id,+ "The blocking fake check completed.",+ )])+ }+}++struct BlockingProbeSource(Vec<Arc<dyn DoctorCheck>>);++impl DoctorCheckSource for BlockingProbeSource {+ fn id(&self) -> &str {+ "doctor-blocking-probes"+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ self.0.clone()+ }+}++#[tokio::test]+async fn a_context_check_source_is_reported_with_its_check_id() {+ let extensions = Extensions::new();+ register_check_source_in(+ &extensions,+ FakeCheckSource::new(+ "doctor-runner-source",+ vec![FakeCheck::pass("hosted/ready")],+ ),+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(Config::default()),+ DoctorOptions {+ only: vec!["hosted/ready".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("registered check source runs");++ let config_source: DoctorConfigSource = report.config_source;+ assert_eq!(config_source, DoctorConfigSource::Profile);+ assert!(report.checks_run.iter().any(|id| id == "hosted/ready"));+ assert!(report+ .findings+ .iter()+ .any(|finding| finding.check_id == "hosted/ready"));+}++#[tokio::test]+async fn hierarchical_check_ids_are_registered_and_selected_exactly() {+ let extensions = Extensions::new();+ register_check_source_in(+ &extensions,+ FakeCheckSource::new(+ "doctor-hierarchical-id-source",+ vec![FakeCheck::pass("inference/live/role")],+ ),+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(Config::default()),+ DoctorOptions {+ tier: DoctorTier::Live,+ only: vec!["inference/live/role".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("hierarchical id is valid and selected as one exact id");++ assert_eq!(report.checks_run, vec!["inference/live/role".to_owned()]);+ assert!(report+ .findings+ .iter()+ .any(|finding| finding.check_id == "inference/live/role"));+}++#[tokio::test]+async fn a_timed_out_check_is_an_error_without_stopping_other_checks() {+ let extensions = Extensions::new();+ let slow = FakeCheck::pass("test/slow")+ .sleep_for(Duration::from_millis(100))+ .with_timeout(Duration::from_millis(10));+ register_check_source_in(+ &extensions,+ FakeCheckSource::new(+ "doctor-timeout-source",+ vec![slow, FakeCheck::pass("test/fast")],+ ),+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(Config::default()),+ DoctorOptions {+ only: vec!["test/slow".into(), "test/fast".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("timed out detector is returned as a finding");++ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "test/slow"+ && finding.severity == FindingSeverity::Error+ && finding.message.contains("timed out")+ }));+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "test/fast" && finding.severity == FindingSeverity::Pass+ }));+}++#[tokio::test]+async fn timed_out_blocking_checks_keep_the_concurrency_slot_until_the_worker_exits() {+ let active = Arc::new(AtomicUsize::new(0));+ let peak = Arc::new(AtomicUsize::new(0));+ let ids = (0..16)+ .map(|index| format!("test/blocking-{index}"))+ .collect::<Vec<_>>();+ let checks = ids+ .iter()+ .map(|id| {+ Arc::new(BlockingProbe {+ id: id.clone(),+ timeout: Duration::from_millis(20),+ active: Arc::clone(&active),+ peak: Arc::clone(&peak),+ }) as Arc<dyn DoctorCheck>+ })+ .collect();+ let extensions = Extensions::new();+ register_check_source_in(&extensions, BlockingProbeSource(checks));+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(Config::default()),+ DoctorOptions {+ only: ids,+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("all blocking checks return timed-out findings");++ assert!(+ active.load(Ordering::SeqCst) > 0,+ "the report should return while timed-out blocking workers are still finishing"+ );+ tokio::time::timeout(Duration::from_secs(3), async {+ while active.load(Ordering::SeqCst) != 0 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("blocking workers eventually finish");+ assert_eq!(report.summary.error, 16);+ assert!(peak.load(Ordering::SeqCst) <= 8);+}++#[tokio::test]+async fn memory_binding_and_health_checks_are_skipped_when_the_component_is_disabled() {+ let mut components = ComponentSet::all();+ components.memory = false;+ let context = DoctorCtx::from_config(Config::default()).with_components(components);+ let report = runner::run(+ &context,+ DoctorOptions {+ tier: DoctorTier::Connect,+ only: vec!["memory/binding".into(), "memory/health".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("component-gated check is represented as skipped");++ assert_eq!(+ report.checks_skipped,+ vec!["memory/binding".to_owned(), "memory/health".to_owned()]+ );+ for check_id in ["memory/binding", "memory/health"] {+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == check_id && finding.severity == FindingSeverity::Skipped+ }));+ }+}++#[tokio::test]+async fn checks_above_the_requested_tier_are_skipped() {+ let extensions = Extensions::new();+ register_check_source_in(+ &extensions,+ FakeCheckSource::new(+ "doctor-tier-source",+ vec![FakeCheck::pass("inference/role-completion").with_tier(DoctorTier::Live)],+ ),+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(Config::default()),+ DoctorOptions {+ tier: DoctorTier::Connect,+ only: vec!["inference/role-completion".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("above-tier check is represented as skipped");++ assert_eq!(+ report.checks_skipped,+ vec!["inference/role-completion".to_owned()]+ );+ assert_eq!(report.checks_run, Vec::<String>::new());+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "inference/role-completion"+ && finding.severity == FindingSeverity::Skipped+ && finding.duration_ms == 0+ }));+}++#[tokio::test]+async fn native_checks_use_the_selected_config_and_respect_its_component_gates() {+ let ambient_workspace = tempfile::tempdir().expect("ambient config workspace");+ let mut ambient_config = Config::default();+ ambient_config.workspace_dir = ambient_workspace.path().join("workspace");+ ambient_config.action_dir = ambient_workspace.path().join("projects");+ ambient_config.config_path = ambient_workspace.path().join("config.toml");+ ambient_config.channels_config.imessage = Some(tinychannels_bus::config::IMessageConfig {+ allowed_contacts: vec![],+ });++ let selected_workspace = tempfile::tempdir().expect("selected config workspace");+ let mut selected_config = Config::default();+ selected_config.workspace_dir = selected_workspace.path().join("workspace");+ selected_config.action_dir = selected_workspace.path().join("projects");+ selected_config.config_path = selected_workspace.path().join("config.toml");+ selected_config.channels_config.telegram = Some(tinychannels_bus::config::TelegramConfig {+ bot_token: "doctor-test-token".into(),+ chat_id: None,+ allowed_users: vec![],+ stream_mode: Default::default(),+ draft_update_interval_ms: 1_000,+ silent_streaming: true,+ mention_only: false,+ });+ selected_config.components.channels = false;+ selected_config.components.connectors = false;+ selected_config.components.voice = false;+ selected_config.components.search = false;+ selected_config.components.wallet = false;++ let ambient = CoreContext::for_test_with_config(DomainSet::full(), ambient_config);+ let selected_components = ComponentSet::from_config(&selected_config.components);+ let report = CoreContext::scope(ambient, async {+ let selected = DoctorCtx::from_config(selected_config).with_components(selected_components);+ runner::run(+ &selected,+ DoctorOptions {+ only: vec![+ "channels/telegram".into(),+ "integrations/composio".into(),+ "voice/stt".into(),+ "voice/tts".into(),+ "search/exa".into(),+ "wallet/status".into(),+ ],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("selected native checks are represented in the report");++ let expected_skipped = [+ "channels/telegram",+ "integrations/composio",+ "voice/stt",+ "voice/tts",+ "search/exa",+ "wallet/status",+ ];+ for check_id in expected_skipped {+ assert!(+ report.checks_skipped.iter().any(|id| id == check_id),+ "selected-config check {check_id} should be skipped: {report:#?}"+ );+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == check_id+ && finding.severity == FindingSeverity::Skipped+ && finding.message.contains("disabled")+ }));+ }+ assert!(!report.checks_run.iter().any(|id| id == "channels/imessage"));+ assert!(!report.findings.iter().any(|finding| {+ finding.check_id == "doctor/selection" && finding.severity == FindingSeverity::Error+ }));+}++#[tokio::test]+async fn connect_tier_skips_live_embedding_without_calling_the_provider() {+ use axum::{extract::State, routing::post, Json, Router};+ use std::sync::atomic::AtomicUsize;+ use tempfile::TempDir;+ use tinymemory_api::{conformance::ReferenceEngine, MemoryEngine};++ let tmp = TempDir::new().expect("temporary config and workspace");+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("workspace directory");+ let calls = Arc::new(AtomicUsize::new(0));+ let app =+ Router::new()+ .route(+ "/api/embed",+ post(+ |State(calls): State<Arc<AtomicUsize>>,+ Json(_body): Json<serde_json::Value>| async move {+ calls.fetch_add(1, Ordering::SeqCst);+ Json(serde_json::json!({ "embeddings": vec![vec![0.1_f32; 768]] }))+ },+ ),+ )+ .with_state(Arc::clone(&calls));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local embedding mock");+ let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let mut config = Config {+ workspace_dir: workspace.clone(),+ action_dir: workspace,+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ };+ config.memory.embedding_provider = "ollama".to_owned();+ config.memory.embedding_model = "nomic-embed-text".to_owned();+ config.memory.engine = crate::memory::engine::TINYHUMANS_ENGINE.to_owned();+ config.local_ai.base_url = Some(endpoint);+ let memory_factory_calls = Arc::new(AtomicUsize::new(0));+ let factory_calls = Arc::clone(&memory_factory_calls);+ let inspection_factory: crate::memory::engine_registry::ReadOnlyEngineFactory =+ Arc::new(move |_| {+ factory_calls.fetch_add(1, Ordering::SeqCst);+ let engine: Arc<dyn MemoryEngine> = Arc::new(ReferenceEngine::new());+ Box::pin(async move { Ok(engine) })+ });+ let extensions = Extensions::new();+ crate::memory::engine_registry::register_read_only_engine_factory_in(+ &extensions,+ crate::memory::engine::TINYHUMANS_ENGINE,+ inspection_factory,+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);++ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Connect,+ only: vec!["embeddings/live".to_owned(), "memory/roundtrip".to_owned()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("connect-only report")+ })+ .await;++ assert_eq!(+ calls.load(Ordering::SeqCst),+ 0,+ "live embedding was not invoked"+ );+ assert_eq!(+ memory_factory_calls.load(Ordering::SeqCst),+ 0,+ "live memory was not bound"+ );+ assert!(report+ .checks_skipped+ .contains(&"embeddings/live".to_owned()));+ assert!(report+ .checks_skipped+ .contains(&"memory/roundtrip".to_owned()));+}++#[tokio::test]+async fn only_filters_exact_ids_and_unknown_ids_get_a_selection_finding() {+ let extensions = Extensions::new();+ register_check_source_in(+ &extensions,+ FakeCheckSource::new(+ "doctor-selection-source",+ vec![+ FakeCheck::pass("config/temperature"),+ FakeCheck::pass("test/other"),+ ],+ ),+ );+ let context = CoreContext::for_test_with_extensions(DomainSet::full(), None, extensions);+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(Config::default()),+ DoctorOptions {+ only: vec![+ "config/temperature".into(),+ "test/other".into(),+ "missing/id".into(),+ ],+ skip: vec!["test/other".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("unknown selection is a report finding");++ assert_eq!(report.checks_run, vec!["config/temperature".to_owned()]);+ assert!(report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"+ && finding.severity == FindingSeverity::Error));+ assert_eq!(report.schema_version, 2);+ assert_eq!(report.summary.pass, 1);+ assert_eq!(report.summary.error, 1);+ assert!(!report.ok);+}++#[tokio::test]+async fn module_status_checks_are_registered_with_their_native_id() {+ let workspace = tempfile::tempdir().expect("create isolated doctor fixture");+ let report = runner::run(+ &DoctorCtx::from_config(isolated_config(workspace.path())),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["modules/tinymcp".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("module check is part of the doctor report");++ assert!(+ !report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"),+ "module check ids are exact registered ids, not unknown selectors: {:?}",+ report.findings+ );+ assert!(report.checks_run.iter().any(|id| id == "modules/tinymcp"));+ assert!(report+ .findings+ .iter()+ .any(|finding| finding.check_id == "modules/tinymcp"));+}++#[tokio::test]+async fn mcp_server_check_ids_come_from_the_selected_config() {+ let workspace_a = tempfile::tempdir().expect("create ambient config fixture");+ let workspace_b = tempfile::tempdir().expect("create selected config fixture");+ let mut config_a = isolated_config(workspace_a.path());+ let mut server_a = crate::config::McpServerConfig::default();+ server_a.name = "server-a".into();+ config_a.mcp_client.servers.push(server_a);+ let mut config_b = isolated_config(workspace_b.path());+ let mut server_b = crate::config::McpServerConfig::default();+ server_b.name = "server-b".into();+ config_b.mcp_client.servers.push(server_b);++ // The ambient context represents configuration A. The selected doctor+ // input is B, so its dynamic check id must be used for exact selection.+ let extensions_a = Extensions::new();+ register_check_source_in(+ &extensions_a,+ FakeCheckSource::new("doctor-mcp-config-a", vec![FakeCheck::pass("mcp/server-a")]),+ );+ let context_a = scoped_config_context(config_a, extensions_a);+ let report = CoreContext::scope(context_a, async {+ runner::run(+ &DoctorCtx::from_config(config_b),+ DoctorOptions {+ // Static ceiling proves the id is registered without probing+ // or starting any MCP server.+ tier: DoctorTier::Static,+ only: vec!["mcp/server-b".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("configured MCP check is represented in the report");++ assert!(+ !report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"),+ "the selected config's id must be registered: {:?}",+ report.findings+ );+ assert!(+ report.checks_skipped.iter().any(|id| id == "mcp/server-b")+ || report.checks_run.iter().any(|id| id == "mcp/server-b")+ );+ assert!(report+ .findings+ .iter()+ .any(|finding| finding.check_id == "mcp/server-b"));+ assert!(!report+ .findings+ .iter()+ .any(|finding| finding.check_id == "mcp/server-a"));+}++#[tokio::test]+async fn duplicate_mcp_names_report_an_ambiguous_definition() {+ let workspace = tempfile::tempdir().expect("create isolated MCP config fixture");+ let mut config = isolated_config(workspace.path());+ let mut first = crate::config::McpServerConfig::default();+ first.name = "server-a".into();+ first.command = "first-server".into();+ let mut second = crate::config::McpServerConfig::default();+ second.name = "server-a".into();+ second.endpoint = "https://example.invalid/mcp".into();+ config.mcp_client.servers.extend([first, second]);++ let report = runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ only: vec!["mcp/server-a".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("duplicate server names are reported under one valid id");++ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "mcp/server-a")+ .expect("one finding identifies the duplicate MCP server");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(finding.message.to_ascii_lowercase().contains("duplicate"));+ assert!(finding.fix_hint.contains("Remove"));+}++#[tokio::test]+async fn malformed_skill_discovery_reports_a_warning_with_its_path() {+ let workspace = tempfile::tempdir().expect("create isolated skill fixture");+ let config = isolated_config(workspace.path());+ let skill_dir = config.workspace_dir.join("skills").join("broken-skill");+ std::fs::create_dir_all(&skill_dir).expect("create skill fixture directory");+ let skill_path = skill_dir.join("SKILL.md");+ std::fs::write(+ &skill_path,+ "---\nname: [unterminated\n---\nA test skill.\n",+ )+ .expect("write malformed skill manifest");++ std::fs::create_dir_all(&config.workspace_dir).expect("create isolated workspace");+ let context = scoped_config_context(config.clone(), Extensions::new());+ let report = CoreContext::scope(context, async {+ runner::run(+ &DoctorCtx::from_config(config),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["skills/discovery".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ })+ .await+ .expect("skill discovery check is part of the doctor report");++ let finding = report+ .findings+ .iter()+ .find(|finding| finding.check_id == "skills/discovery")+ .expect("malformed skill produces a discovery finding");+ assert_eq!(finding.severity, FindingSeverity::Warn);+ let expected_path = skill_path.to_string_lossy();+ assert_eq!(finding.config_path.as_deref(), Some(expected_path.as_ref()));+ assert!(finding.message.to_ascii_lowercase().contains("manifest"));+}++#[tokio::test]+async fn sandbox_backend_check_is_registered_without_running_above_static_tier() {+ let workspace = tempfile::tempdir().expect("create isolated doctor fixture");+ let mut config = isolated_config(workspace.path());+ config.sandbox.backend = crate::config::SandboxBackend::Docker;+ let mut components = ComponentSet::all();+ components.sandbox = false;+ let report = runner::run(+ &DoctorCtx::from_config(config).with_components(components),+ DoctorOptions {+ tier: DoctorTier::Static,+ only: vec!["sandbox/backend".into()],+ ..DoctorOptions::default()+ },+ )+ .await+ .expect("sandbox check is represented without invoking Docker");++ assert!(+ !report+ .findings+ .iter()+ .any(|finding| finding.check_id == "doctor/selection"),+ "sandbox check id must be registered: {:?}",+ report.findings+ );+ assert_eq!(report.checks_skipped, vec!["sandbox/backend".to_owned()]);+ assert!(report.findings.iter().any(|finding| {+ finding.check_id == "sandbox/backend" && finding.severity == FindingSeverity::Skipped+ }));+}diff --git a/crates/openhuman-core/src/platform/doctor/schemas.rs b/crates/openhuman-core/src/doctor/schemas.rssimilarity index 56%rename from crates/openhuman-core/src/platform/doctor/schemas.rsrename to crates/openhuman-core/src/doctor/schemas.rsindex 5536484563..7de7dff1ad 100644--- a/crates/openhuman-core/src/platform/doctor/schemas.rs+++ b/crates/openhuman-core/src/doctor/schemas.rs@@ -3,11 +3,11 @@ use serde::de::DeserializeOwned;use serde_json::{Map, Value};use crate::config::Config;+use crate::core::Outcome;use crate::core::all::{BoundRegisteredController, ControllerEntry, ControllerFuture, ControllerTask,RegisteredController,};-use crate::core::Outcome;use crate::core::{ControllerSchema, FieldSchema, TypeSchema};pub fn all_controller_schemas() -> Vec<ControllerSchema> {@@ -45,7 +45,38 @@ pub fn schemas(function: &str) -> ControllerSchema {namespace: "doctor",function: "report",description: "Run diagnostics for workspace and runtime configuration.",- inputs: vec![],+ inputs: vec![+ FieldSchema {+ name: "tier",+ ty: TypeSchema::Option(Box::new(TypeSchema::Enum {+ variants: vec!["static", "connect", "live"],+ })),+ comment: "Maximum doctor check tier to run.",+ required: false,+ },+ FieldSchema {+ name: "only",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Exact check ids to include.",+ required: false,+ },+ FieldSchema {+ name: "skip",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Exact check ids to exclude.",+ required: false,+ },+ FieldSchema {+ name: "profile",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Profile id, resolved by the host when supported.",+ required: false,+ },+ ],outputs: vec![FieldSchema {name: "report",ty: TypeSchema::Ref("DoctorReport"),@@ -56,11 +87,11 @@ pub fn schemas(function: &str) -> ControllerSchema {"models" => ControllerSchema {namespace: "doctor",function: "models",- description: "Probe provider model availability and auth status.",+ description: "Read-only inference provider catalog inspection.",inputs: vec![FieldSchema {name: "use_cache",ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),- comment: "Reuse cached provider metadata when available.",+ comment: "Reuse a recent catalog result when available.",required: false,}],outputs: vec![FieldSchema {@@ -85,8 +116,8 @@ pub fn schemas(function: &str) -> ControllerSchema {}}-fn handle_report(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- report_controller().invoke(ctx, _params)+fn handle_report(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ report_controller().invoke(ctx, params)}fn handle_models(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {@@ -94,33 +125,44 @@ fn handle_models(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu}fn report_controller() -> BoundRegisteredController {- BoundRegisteredController::after_gate(schemas("report"), load_config, parse_report, run_report)+ BoundRegisteredController::typed(schemas("report"), parse_report, run_report)}fn models_controller() -> BoundRegisteredController {- BoundRegisteredController::after_gate(schemas("models"), load_config, parse_models, run_models)+ BoundRegisteredController::after_gate(+ schemas("models"),+ config_for_dispatch,+ parse_models,+ run_models,+ )}-fn load_config(ctx: DispatchCtx) -> ControllerTask<Config> {- Box::pin(async move { ctx.load_config().await })+fn config_for_dispatch(ctx: DispatchCtx) -> ControllerTask<Config> {+ Box::pin(async move { crate::doctor::ops::config_for_dispatch(&ctx).await })}-fn parse_report(_params: Map<String, Value>) -> Result<(), String> {- Ok(())+fn parse_report(params: Map<String, Value>) -> Result<crate::doctor::DoctorOptions, String> {+ Ok(crate::doctor::DoctorOptions {+ tier: read_optional::<crate::doctor::DoctorTier>(¶ms, "tier")?+ .unwrap_or(crate::doctor::DoctorTier::Connect),+ only: read_optional::<Vec<String>>(¶ms, "only")?.unwrap_or_default(),+ skip: read_optional::<Vec<String>>(¶ms, "skip")?.unwrap_or_default(),+ profile: read_optional::<String>(¶ms, "profile")?,+ })}fn parse_models(params: Map<String, Value>) -> Result<bool, String> {Ok(read_optional::<bool>(¶ms, "use_cache")?.unwrap_or(true))}-fn run_report(_ctx: DispatchCtx, config: Config, (): ()) -> ControllerFuture {- Box::pin(async move { to_json(crate::platform::doctor::rpc::doctor_report(&config).await?) })+fn run_report(ctx: DispatchCtx, options: crate::doctor::DoctorOptions) -> ControllerFuture {+ Box::pin(async move {+ to_json(crate::doctor::ops::doctor_report_for_dispatch(&ctx, options).await?)+ })}fn run_models(_ctx: DispatchCtx, config: Config, use_cache: bool) -> ControllerFuture {- Box::pin(async move {- to_json(crate::platform::doctor::rpc::doctor_models(&config, use_cache).await?)- })+ Box::pin(async move { to_json(crate::doctor::ops::doctor_models(&config, use_cache).await?) })}fn read_optional<T: DeserializeOwned>(diff --git a/crates/openhuman-core/src/platform/doctor/schemas_tests.rs b/crates/openhuman-core/src/doctor/schemas_tests.rssimilarity index 69%rename from crates/openhuman-core/src/platform/doctor/schemas_tests.rsrename to crates/openhuman-core/src/doctor/schemas_tests.rsindex b2afb4f8e9..9c9c5648d8 100644--- a/crates/openhuman-core/src/platform/doctor/schemas_tests.rs+++ b/crates/openhuman-core/src/doctor/schemas_tests.rs@@ -24,7 +24,11 @@ fn report_schema() {let s = schemas("report");assert_eq!(s.namespace, "doctor");assert_eq!(s.function, "report");- assert!(s.inputs.is_empty());+ assert_eq!(+ s.inputs.iter().map(|field| field.name).collect::<Vec<_>>(),+ ["tier", "only", "skip", "profile"]+ );+ assert!(s.inputs.iter().all(|field| !field.required));}#[test]@@ -69,7 +73,7 @@ fn model_parser_rejects_non_boolean_cache_flags() {}#[test]-fn report_parser_ignores_the_entire_parameter_map() {+fn report_parser_applies_defaults_and_ignores_unknown_fields() {let params = Map::from_iter([("use_cache".into(), Value::String("wrong type".into())),(@@ -77,7 +81,39 @@ fn report_parser_ignores_the_entire_parameter_map() {serde_json::json!({"ignored":[1, false]}),),]);- parse_report(params).expect("doctor.report ignores every supplied parameter");+ let options = parse_report(params).expect("unknown fields are ignored");+ assert_eq!(options.tier, crate::doctor::DoctorTier::Connect);+ assert!(options.only.is_empty());+ assert!(options.skip.is_empty());+ assert!(options.profile.is_none());+}++#[test]+fn report_parser_preserves_typed_options_and_null_defaults() {+ let params = Map::from_iter([+ ("tier".into(), serde_json::json!("live")),+ ("only".into(), serde_json::json!(["memory", "config"])),+ ("skip".into(), Value::Null),+ ("profile".into(), Value::Null),+ ]);+ let options = parse_report(params).unwrap();+ assert_eq!(options.tier, crate::doctor::DoctorTier::Live);+ assert_eq!(options.only, ["memory", "config"]);+ assert!(options.skip.is_empty());+ assert!(options.profile.is_none());+}++#[test]+fn report_parser_rejects_invalid_declared_options() {+ for (key, value) in [+ ("tier", serde_json::json!("unknown")),+ ("only", serde_json::json!("memory")),+ ("skip", serde_json::json!([false])),+ ("profile", serde_json::json!(false)),+ ] {+ let error = parse_report(Map::from_iter([(key.into(), value)])).unwrap_err();+ assert!(error.starts_with(&format!("invalid '{key}':")), "{error}");+ }}async fn runtime_doctor_entries() -> Vec<crate::core::all::ControllerEntry> {@@ -93,7 +129,7 @@ async fn runtime_doctor_entries() -> Vec<crate::core::all::ControllerEntry> {}#[tokio::test]-async fn doctor_controllers_load_config_before_parsing_and_parse_before_running() {+async fn report_options_parse_before_dispatch_config_and_models_gate_before_parsing() {use crate::config::test_env::EnvVarGuard;use crate::core::runtime::{CoreContext, DispatchCtx, DomainSet};use serde_json::json;@@ -112,13 +148,13 @@ async fn doctor_controllers_load_config_before_parsing_and_parse_before_running(let report_error = report.invoke(ctx.clone(),- Map::from_iter([("unexpected".into(), json!({"ignored":true}))]),+ Map::from_iter([("tier".into(), json!("invalid"))]),).await- .expect_err("invalid config stops diagnostics before the report runner");+ .expect_err("invalid options fail before the report resolves config");assert!(- report_error.contains("is a directory") || report_error.contains("not a file"),- "report config gate error: {report_error}"+ report_error.starts_with("invalid 'tier':"),+ "{report_error}");let models = entries@@ -130,9 +166,9 @@ async fn doctor_controllers_load_config_before_parsing_and_parse_before_running(.invoke(ctx, malformed.clone()).await.expect_err("config gate runs before model parameter parsing");- assert!(- gate_error.contains("is a directory") || gate_error.contains("not a file"),- "models config gate error: {gate_error}"+ assert_eq!(+ gate_error,+ "The selected profile config is missing or invalid.");assert!(!gate_error.starts_with("invalid 'use_cache':"));@@ -157,8 +193,14 @@ pub(crate) fn doctor_parameter_contracts() -> Vec<crate::core::all::ControllerPacrate::core::all::ControllerParamContract {method: "doctor.report",required: &[],- optional: &[],- examples: vec![json!({})],+ optional: &["tier", "only", "skip", "profile"],+ examples: vec![+ json!({}),+ json!({"tier":"static"}),+ json!({"only":["config"]}),+ json!({"skip":["memory"]}),+ json!({"profile":"work"}),+ ],},crate::core::all::ControllerParamContract {method: "doctor.models",diff --git a/crates/openhuman-core/src/doctor/test_support.rs b/crates/openhuman-core/src/doctor/test_support.rsnew file mode 100644index 0000000000..50e99aa51e--- /dev/null+++ b/crates/openhuman-core/src/doctor/test_support.rs@@ -0,0 +1,111 @@+//! Reusable fake checks and sources for doctor framework tests.++use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;++use super::contract::{DoctorCheck, DoctorCtx, DoctorTier, Finding};+use super::registry::DoctorCheckSource;++/// A configurable check used by framework and fan-out tests.+pub(crate) struct FakeCheck {+ id: String,+ findings: Vec<Finding>,+ delay: Duration,+ timeout: Option<Duration>,+ tier: DoctorTier,+ calls: Option<Arc<AtomicUsize>>,+}++impl FakeCheck {+ pub(crate) fn pass(id: impl Into<String>) -> Self {+ let id = id.into();+ Self {+ findings: vec![Finding::pass(&id, "The fake check passed.")],+ id,+ delay: Duration::ZERO,+ timeout: None,+ tier: DoctorTier::Connect,+ calls: None,+ }+ }++ pub(crate) fn sleep_for(mut self, delay: Duration) -> Self {+ self.delay = delay;+ self+ }++ pub(crate) fn with_timeout(mut self, timeout: Duration) -> Self {+ self.timeout = Some(timeout);+ self+ }++ pub(crate) fn with_tier(mut self, tier: DoctorTier) -> Self {+ self.tier = tier;+ self+ }++ pub(crate) fn with_call_counter(mut self, calls: Arc<AtomicUsize>) -> Self {+ self.calls = Some(calls);+ self+ }+}++#[async_trait]+impl DoctorCheck for FakeCheck {+ fn id(&self) -> &str {+ &self.id+ }++ fn category(&self) -> &str {+ "test"+ }++ fn tier(&self) -> DoctorTier {+ self.tier+ }++ fn timeout(&self) -> Duration {+ self.timeout.unwrap_or_else(|| self.tier.timeout())+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ if let Some(calls) = &self.calls {+ calls.fetch_add(1, Ordering::SeqCst);+ }+ if !self.delay.is_zero() {+ tokio::time::sleep(self.delay).await;+ }+ self.findings.clone()+ }+}++/// A source that contributes fake checks to a single registry scope.+pub(crate) struct FakeCheckSource {+ id: String,+ checks: Vec<Arc<dyn DoctorCheck>>,+}++impl FakeCheckSource {+ pub(crate) fn new(id: impl Into<String>, checks: Vec<FakeCheck>) -> Self {+ Self {+ id: id.into(),+ checks: checks+ .into_iter()+ .map(|check| Arc::new(check) as Arc<dyn DoctorCheck>)+ .collect(),+ }+ }+}++impl DoctorCheckSource for FakeCheckSource {+ fn id(&self) -> &str {+ &self.id+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ self.checks.clone()+ }+}diff --git a/crates/openhuman-core/src/platform/doctor/tools.rs b/crates/openhuman-core/src/doctor/tools.rssimilarity index 53%rename from crates/openhuman-core/src/platform/doctor/tools.rsrename to crates/openhuman-core/src/doctor/tools.rsindex b5b43e60d0..80a9936f1f 100644--- a/crates/openhuman-core/src/platform/doctor/tools.rs+++ b/crates/openhuman-core/src/doctor/tools.rs@@ -1,17 +1,19 @@//! LLM-callable wrappers over the `doctor` diagnostics domain.//!//! Read-only health diagnostics; both tools delegate to-//! [`crate::platform::doctor::ops`] and ship default-ON.+//! [`crate::doctor::ops`] and ship default-ON.use std::sync::Arc;use async_trait::async_trait;+use serde::Deserialize;use serde_json::json;use crate::config::Config;use tinytools::{Tool, ToolResult};use super::ops;+use super::{DoctorOptions, DoctorTier};macro_rules! emit {($outcome:expr, $name:literal) => {{@@ -25,6 +27,13 @@ pub struct DoctorHealthTool {config: Arc<Config>,}+#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+struct DoctorHealthArgs {+ tier: Option<DoctorTier>,+ only: Option<Vec<String>>,+}+impl DoctorHealthTool {pub fn new(config: Arc<Config>) -> Self {Self { config }@@ -42,18 +51,54 @@ impl Tool for DoctorHealthTool {}fn description(&self) -> &str {- "Run the full diagnostic battery (config, connectivity, dependencies, \- runtime) and return a structured report of checks with pass/warn/fail \- status. Use to diagnose why the assistant or a subsystem isn't working."+ "Run selected OpenHuman health checks and return a structured v2 report. \+ The default connect tier uses bounded, read-only checks. The live tier \+ can spend inference tokens and write disposable test data; run live only \+ when the user explicitly requested those billable probes. Use exact \+ registered check ids with `only` to narrow the report."}fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })+ json!({+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "tier": {+ "type": "string",+ "enum": ["static", "connect", "live"],+ "default": "connect",+ "description": "Maximum check tier. Live can spend inference tokens and write disposable test data; select it only when the user explicitly requested these billable probes."+ },+ "only": {+ "type": "array",+ "items": { "type": "string" },+ "description": "Optional exact registered check ids to run. Omit to include all checks up to the selected tier."+ }+ }+ })}- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ let args = if args.is_null() {+ DoctorHealthArgs::default()+ } else {+ serde_json::from_value::<DoctorHealthArgs>(args)?+ };+ let tier = args.tier.unwrap_or(DoctorTier::Connect);+ let only = args.only.unwrap_or_default();log::debug!("[tool][doctor] health invoked");- emit!(ops::doctor_report(&self.config).await, "doctor_health")+ emit!(+ ops::doctor_report_with_options(+ &self.config,+ DoctorOptions {+ tier,+ only,+ ..DoctorOptions::default()+ }+ )+ .await,+ "doctor_health"+ )}fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {@@ -83,15 +128,15 @@ impl Tool for DoctorModelsTool {}fn description(&self) -> &str {- "Probe configured AI models for availability and return a per-model \- report. Set `use_cache` false to force a fresh probe (default true)."+ "Check configured inference providers by listing their models catalogs. \+ This read-only check never generates a model response."}fn parameters_schema(&self) -> serde_json::Value {json!({"type": "object","properties": {- "use_cache": { "type": "boolean", "description": "Use cached probe results (default true)." }+ "use_cache": { "type": "boolean", "description": "Reuse a recent catalog result when available." }}})}diff --git a/crates/openhuman-core/src/doctor/tools_tests.rs b/crates/openhuman-core/src/doctor/tools_tests.rsnew file mode 100644index 0000000000..a761e4c28f--- /dev/null+++ b/crates/openhuman-core/src/doctor/tools_tests.rs@@ -0,0 +1,266 @@+use super::*;+use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};+use crate::core::slots::Extensions;+use crate::tools::toolpacks::ToolGroups;+use std::sync::atomic::{AtomicUsize, Ordering};+use tempfile::TempDir;+use tinytools::{PermissionLevel, ToolScope};+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++fn cfg() -> Arc<Config> {+ Arc::new(Config::default())+}++fn config_in(tmp: &TempDir) -> Config {+ let workspace = tmp.path().join("workspace");+ let action_dir = tmp.path().join("action");+ std::fs::create_dir_all(&workspace).expect("create test workspace");+ std::fs::create_dir_all(&action_dir).expect("create test action directory");++ Config {+ workspace_dir: workspace.clone(),+ action_dir,+ config_path: workspace.join("config.toml"),+ ..Config::default()+ }+}++fn scoped_context(config: &Config, extensions: Extensions) -> Arc<CoreContext> {+ let parent = CoreContext::for_test_with_extensions(+ DomainSet::full(),+ Some(config.workspace_dir.clone()),+ extensions,+ );+ parent.derive_with(+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none())+ .without_user_skill_roots(),+ )+}++#[test]+fn metadata() {+ assert_eq!(DoctorHealthTool::new(cfg()).name(), "doctor_health");+ assert_eq!(DoctorModelsTool::new(cfg()).name(), "doctor_models");+ assert_eq!(+ DoctorHealthTool::new(cfg()).permission_level(),+ PermissionLevel::ReadOnly+ );+ assert_eq!(DoctorHealthTool::new(cfg()).scope(), ToolScope::All);+}++#[test]+fn health_schema_exposes_only_optional_tier_and_exact_id_selection() {+ let tool = DoctorHealthTool::new(cfg());+ let schema = tool.parameters_schema();++ assert_eq!(schema["type"], "object");+ assert_eq!(+ schema["properties"]["tier"]["enum"],+ serde_json::json!(["static", "connect", "live"])+ );+ assert_eq!(schema["properties"]["tier"]["default"], "connect");+ assert_eq!(schema["properties"]["only"]["type"], "array");+ assert_eq!(schema["properties"]["only"]["items"]["type"], "string");+ assert!(+ schema["required"].is_null(),+ "both inputs should be optional"+ );++ let description = format!(+ "{} {}",+ tool.description(),+ schema["properties"]["tier"]["description"]+ .as_str()+ .expect("tier description")+ )+ .to_ascii_lowercase();+ assert!(description.contains("live"), "{description}");+ assert!(description.contains("token"), "{description}");+ assert!(+ description.contains("user explicitly requested"),+ "{description}"+ );+}++#[tokio::test]+async fn models_tool_returns_an_inspection_report_when_no_provider_is_configured() {+ DoctorModelsTool::new(cfg())+ .execute(serde_json::json!({ "use_cache": true }))+ .await+ .expect("doctor_models returns the actual empty inspection result");+}++#[tokio::test]+async fn health_tool_forwards_tier_and_only_to_the_scoped_check_registry() {+ let tmp = TempDir::new().expect("tempdir");+ let config = config_in(&tmp);+ let selected_calls = Arc::new(AtomicUsize::new(0));+ let unselected_calls = Arc::new(AtomicUsize::new(0));+ let extensions = Extensions::new();+ crate::doctor::register_check_source_in(+ &extensions,+ crate::doctor::test_support::FakeCheckSource::new(+ "doctor-health-tool-forwarding",+ vec![+ crate::doctor::test_support::FakeCheck::pass("test/selected")+ .with_tier(crate::doctor::DoctorTier::Static)+ .with_call_counter(Arc::clone(&selected_calls)),+ crate::doctor::test_support::FakeCheck::pass("test/unselected")+ .with_tier(crate::doctor::DoctorTier::Static)+ .with_call_counter(Arc::clone(&unselected_calls)),+ ],+ ),+ );+ let context = scoped_context(&config, extensions);+ let tool = DoctorHealthTool::new(Arc::new(config));++ let result = CoreContext::scope(+ context,+ tool.execute(serde_json::json!({+ "tier": "static",+ "only": ["test/selected"]+ })),+ )+ .await+ .expect("the scoped static check should return a report");+ let report: serde_json::Value =+ serde_json::from_str(&result.text()).expect("tool result is a JSON doctor report");++ assert_eq!(report["schema_version"], 2);+ assert_eq!(report["tier"], "static");+ assert_eq!(report["checks_run"], serde_json::json!(["test/selected"]));+ assert_eq!(selected_calls.load(Ordering::SeqCst), 1);+ assert_eq!(unselected_calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn health_tool_defaults_to_connect_when_tier_is_omitted() {+ let tmp = TempDir::new().expect("tempdir");+ let config = config_in(&tmp);+ let selected_calls = Arc::new(AtomicUsize::new(0));+ let extensions = Extensions::new();+ crate::doctor::register_check_source_in(+ &extensions,+ crate::doctor::test_support::FakeCheckSource::new(+ "doctor-health-tool-default-tier",+ vec![+ crate::doctor::test_support::FakeCheck::pass("test/default-connect")+ .with_tier(crate::doctor::DoctorTier::Connect)+ .with_call_counter(Arc::clone(&selected_calls)),+ ],+ ),+ );+ let context = scoped_context(&config, extensions);+ let tool = DoctorHealthTool::new(Arc::new(config));++ let result = CoreContext::scope(+ context,+ tool.execute(serde_json::json!({+ "only": ["test/default-connect"]+ })),+ )+ .await+ .expect("the selected connect check should return a report");+ let report: serde_json::Value =+ serde_json::from_str(&result.text()).expect("tool result is a JSON doctor report");++ assert_eq!(report["schema_version"], 2);+ assert_eq!(report["tier"], "connect");+ assert_eq!(+ report["checks_run"],+ serde_json::json!(["test/default-connect"])+ );+ assert_eq!(selected_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn models_tool_reports_each_configured_catalog_outcome() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/available/v1/models"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "data": [{ "id": "fixture-model" }]+ })))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/missing/v1/models"))+ .respond_with(ResponseTemplate::new(404))+ .mount(&server)+ .await;++ let tmp = TempDir::new().expect("tempdir");+ let mut config = config_in(&tmp);+ config.default_model = None;+ config.model_routes.clear();+ config.cloud_providers = vec![+ crate::config::schema::cloud_providers::CloudProviderCreds {+ id: "p_doctor_tool_models_available".into(),+ slug: "doctor-tool-models-available".into(),+ label: "Available test provider".into(),+ endpoint: format!("{}/available/v1", server.uri()),+ auth_style: crate::config::schema::cloud_providers::AuthStyle::None,+ default_model: None,+ },+ crate::config::schema::cloud_providers::CloudProviderCreds {+ id: "p_doctor_tool_models_missing".into(),+ slug: "doctor-tool-models-missing".into(),+ label: "Missing test provider".into(),+ endpoint: format!("{}/missing/v1", server.uri()),+ auth_style: crate::config::schema::cloud_providers::AuthStyle::None,+ default_model: None,+ },+ ];++ let result = DoctorModelsTool::new(Arc::new(config))+ .execute(serde_json::json!({ "use_cache": false }))+ .await+ .expect("catalog outcomes should be returned as a report");+ let report: serde_json::Value =+ serde_json::from_str(&result.text()).expect("tool result is a JSON model probe report");+ let entries = report["entries"].as_array().expect("provider entries");+ let available = entries+ .iter()+ .find(|entry| entry["provider"] == "doctor-tool-models-available")+ .expect("available provider entry");+ let missing = entries+ .iter()+ .find(|entry| entry["provider"] == "doctor-tool-models-missing")+ .expect("missing provider entry");++ assert_eq!(available["outcome"], "Ok");+ assert_eq!(available["message"], "Catalog returned 1 models.");+ assert_eq!(missing["outcome"], "Skipped");+ assert_eq!(+ missing["message"],+ "Provider does not expose a models catalog."+ );+ assert_eq!(report["summary"]["ok"], 1);+ assert_eq!(report["summary"]["skipped"], 1);+ assert_eq!(report["summary"]["errors"], 0);+}++#[test]+fn gitbook_inventory_lists_every_registered_doctor_check_id() {+ let docs_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../docs/gitbooks/en/guides/doctor.md");+ let docs = std::fs::read_to_string(&docs_path).unwrap_or_else(|error| {+ panic!(+ "doctor check inventory page should exist at {}: {error}",+ docs_path.display()+ )+ });+ let checks = crate::doctor::registry::registered_checks()+ .expect("registered doctor checks should have valid unique ids");++ for check in checks {+ let documented_id = format!("`{}`", check.id());+ assert!(+ docs.contains(&documented_id),+ "registered doctor check `{}` is missing from {}",+ check.id(),+ docs_path.display()+ );+ }+}diff --git a/crates/openhuman-core/src/inference/auth_error_registry.rs b/crates/openhuman-core/src/inference/auth_error_registry.rsindex 54ae542c3d..a6915dc64b 100644--- a/crates/openhuman-core/src/inference/auth_error_registry.rs+++ b/crates/openhuman-core/src/inference/auth_error_registry.rs@@ -19,7 +19,8 @@//! and an unguarded publish would re-flood the notification center the same//! way the raw error flooded Sentry.-use std::sync::OnceLock;+use std::collections::{HashMap, HashSet};+use std::sync::{Mutex, OnceLock};use std::time::{SystemTime, UNIX_EPOCH};use tinyinference_providers::auth_registry::ProviderAuthError;@@ -58,18 +59,31 @@ pub fn auth_error_message(provider: &str, status: u16) -> String {/// a 401 that repeats per-retry doesn't re-notify. An existing entry is/// refreshed (status / timestamp) and returns `false`.pub fn record(provider: &str, status: u16) -> bool {- registry().record(ProviderAuthError {+ let scope = current_scope();+ let changed = registry().record(ProviderAuthError {provider: provider.to_string(),status,message: auth_error_message(provider, status),timestamp_ms: now_ms(),- })+ });+ let mut origins = origins().lock().unwrap_or_else(|error| error.into_inner());+ let entry = origins.entry(provider.to_owned()).or_default();+ if let Some(scope) = scope {+ entry.scopes.insert(scope);+ } else {+ entry.unscoped = true;+ }+ changed}/// Clear any recorded auth error for `provider` (the user updated / removed/// the key, or a call newly succeeded). Returns `true` if an entry was/// removed. Re-arms the [`record`] latch so a fresh failure re-notifies.pub fn clear(provider: &str) -> bool {+ origins()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .remove(provider);registry().clear(provider)}@@ -79,11 +93,85 @@ pub fn snapshot() -> Vec<ProviderAuthError> {registry().snapshot()}+#[derive(Default)]+struct ErrorOrigins {+ scopes: HashSet<ScopeIdentity>,+ unscoped: bool,+}++#[derive(Clone, PartialEq, Eq, Hash)]+struct ScopeIdentity {+ workspace: std::path::PathBuf,+ config_path: Option<std::path::PathBuf>,+ tenant: String,+}++fn origins() -> &'static Mutex<HashMap<String, ErrorOrigins>> {+ static ORIGINS: OnceLock<Mutex<HashMap<String, ErrorOrigins>>> = OnceLock::new();+ ORIGINS.get_or_init(|| Mutex::new(HashMap::new()))+}++fn current_scope() -> Option<ScopeIdentity> {+ let context = crate::core::runtime::CoreContext::current()?;+ let (workspace, config_path) = context.workspace_config_binding().ok()?;+ Some(ScopeIdentity {+ workspace,+ config_path,+ tenant: context.profile().unwrap_or_default().to_owned(),+ })+}++/// Auth failures scoped to the current workspace/tenant. Known foreign+/// failures are omitted; unscoped legacy failures are reported separately so+/// callers can avoid attributing them to the selected profile.+pub fn snapshot_for_scope(+ workspace: &std::path::Path,+ config_path: &std::path::Path,+ tenant: Option<&str>,+) -> (Vec<ProviderAuthError>, bool) {+ let scope = ScopeIdentity {+ workspace: workspace.to_path_buf(),+ config_path: Some(config_path.to_path_buf()),+ tenant: tenant.unwrap_or_default().to_owned(),+ };+ let origins = origins().lock().unwrap_or_else(|error| error.into_inner());+ let mut has_unscoped = origins.values().any(|origin| origin.unscoped);+ let errors = registry()+ .snapshot()+ .into_iter()+ .filter(|error| {+ let Some(origin) = origins.get(&error.provider) else {+ return false;+ };+ let partial_match = origin.scopes.iter().any(|recorded| {+ recorded.config_path.is_none()+ && recorded.workspace == scope.workspace+ && recorded.tenant == scope.tenant+ });+ if partial_match {+ has_unscoped = true;+ }+ if origin.scopes.contains(&scope) {+ return true;+ }+ if !partial_match {+ return false;+ }+ false+ })+ .collect();+ (errors, has_unscoped)+}+/// Test-only: wipe the registry so a test can't be flaked by an entry an/// earlier test left behind (the map is process-global).#[cfg(any(test, debug_assertions))]pub fn reset_for_tests() {registry().clear_all();+ origins()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .clear();}#[cfg(test)]diff --git a/crates/openhuman-core/src/inference/auth_error_registry_tests.rs b/crates/openhuman-core/src/inference/auth_error_registry_tests.rsindex b267b88460..8395733d22 100644--- a/crates/openhuman-core/src/inference/auth_error_registry_tests.rs+++ b/crates/openhuman-core/src/inference/auth_error_registry_tests.rs@@ -7,6 +7,15 @@ use std::sync::Mutex;// exclusive registry.static TEST_LOCK: Mutex<()> = Mutex::new(());+fn with_test_lock(future: impl std::future::Future<Output = ()>) {+ let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("create current-thread test runtime")+ .block_on(future);+}+#[test]fn record_returns_true_only_on_first_episode() {let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());@@ -47,3 +56,181 @@ fn snapshot_is_sorted_and_carries_actionable_message() {assert!(snap[1].message.contains("Connections → API keys → LLM"));reset_for_tests();}++#[test]+fn a_workspace_only_origin_is_not_assigned_to_a_different_config_root() {+ with_test_lock(async {+ reset_for_tests();+ let workspace = tempfile::tempdir().expect("shared workspace");+ let config_root_a = tempfile::tempdir().expect("config root A");+ let config_root_b = tempfile::tempdir().expect("config root B");+ let config_path_b = config_root_b.path().join("config.toml");+ let context = crate::core::runtime::CoreContext::for_test(+ crate::core::runtime::DomainSet::full(),+ Some(workspace.path().to_path_buf()),+ );++ crate::core::runtime::CoreContext::scope(context, async {+ assert!(crate::core::runtime::CoreContext::current_embedder_config().is_none());+ assert!(record("workspace-only-provider", 401));+ })+ .await;++ let (selected_errors, has_unattributed_error) =+ snapshot_for_scope(workspace.path(), &config_path_b, None);+ assert!(+ selected_errors.is_empty(),+ "a workspace-only observation cannot be assigned to config root B"+ );+ assert!(+ has_unattributed_error,+ "the existing process error remains visible as unattributed"+ );++ // Keep both roots live through the assertion; their distinct paths are+ // the ambiguity this regression protects.+ assert_ne!(config_root_a.path(), config_root_b.path());+ reset_for_tests();+ });+}++#[test]+fn workspace_rebind_updates_or_clears_the_config_origin_hint_locally() {+ with_test_lock(async {+ reset_for_tests();+ let workspace = tempfile::tempdir().expect("shared workspace");+ let config_root_a = tempfile::tempdir().expect("config root A");+ let config_root_b = tempfile::tempdir().expect("config root B");+ let config_path_a = config_root_a.path().join("config.toml");+ let config_path_b = config_root_b.path().join("config.toml");+ let mut config_a = crate::config::Config::default();+ config_a.workspace_dir = workspace.path().to_path_buf();+ config_a.config_path = config_path_a.clone();+ let context_a = crate::core::runtime::CoreContext::for_test_with_config(+ crate::core::runtime::DomainSet::full(),+ config_a,+ );+ let derived_a = context_a.for_agent("in-flight-agent-a");++ crate::core::runtime::CoreContext::scope(context_a.clone(), async {+ assert!(record("config-a-provider", 401));+ })+ .await;+ context_a+ .rebind_workspace(workspace.path(), Some(&config_path_b))+ .expect("rebind config origin");+ crate::core::runtime::CoreContext::scope(context_a.clone(), async {+ assert!(record("config-b-provider", 403));+ })+ .await;+ crate::core::runtime::CoreContext::scope(derived_a, async {+ assert!(record("in-flight-config-a-provider", 401));+ })+ .await;++ let (errors_for_a, _) = snapshot_for_scope(workspace.path(), &config_path_a, None);+ let (errors_for_b, _) = snapshot_for_scope(workspace.path(), &config_path_b, None);+ assert_eq!(errors_for_a.len(), 2);+ assert_eq!(errors_for_b.len(), 1);++ context_a+ .rebind_workspace(workspace.path(), None)+ .expect("clear unknown config origin");+ crate::core::runtime::CoreContext::scope(context_a, async {+ assert!(record("unknown-config-provider", 401));+ })+ .await;+ let (errors_for_a, has_unattributed) =+ snapshot_for_scope(workspace.path(), &config_path_a, None);+ assert_eq!(errors_for_a.len(), 2);+ assert!(has_unattributed);+ reset_for_tests();+ });+}++#[test]+fn normal_boot_without_preloaded_config_uses_the_resolved_config_path() {+ const CHILD_MARKER: &str = "OPENHUMAN_AUTH_ORIGIN_NORMAL_BOOT_CHILD";+ if std::env::var_os(CHILD_MARKER).is_none() {+ let home = tempfile::tempdir().expect("isolated test home");+ let openhuman_dir = home.path().join(".openhuman");+ let config_dir = crate::config::pre_login_user_dir(&openhuman_dir);+ std::fs::create_dir_all(&config_dir).expect("create isolated config directory");+ std::fs::write(+ config_dir.join("config.toml"),+ "[storage]\nurl = \"memory\"\n\n[secrets]\nencrypt = false\n",+ )+ .expect("write isolated normal-boot config");++ let output = std::process::Command::new(+ std::env::current_exe().expect("test executable path"),+ )+ .args([+ "--exact",+ "inference::auth_error_registry::tests::normal_boot_without_preloaded_config_uses_the_resolved_config_path",+ "--nocapture",+ ])+ .env(CHILD_MARKER, "1")+ .env("HOME", home.path())+ .env("USERPROFILE", home.path())+ .env("OPENHUMAN_APP_ENV", "production")+ .env_remove("VITE_OPENHUMAN_APP_ENV")+ .env_remove("OPENHUMAN_WORKSPACE")+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY")+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")+ .output()+ .expect("spawn isolated normal-boot test process");+ assert!(+ output.status.success(),+ "isolated normal-boot child failed: stdout={} stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ return;+ }++ with_test_lock(async {+ reset_for_tests();+ assert!(crate::core::runtime::CoreContext::current().is_none());+ let token = crate::core::runtime::TokenSource::Fixed(std::sync::Arc::new(+ "auth-origin-test-token".to_owned(),+ ));+ let (context, _, config) = crate::core::runtime::CoreContext::init_with_boot_mode(+ crate::core::types::HostKind::Library,+ &token,+ crate::core::runtime::DomainSet::none(),+ crate::tools::toolpacks::ToolGroups::none(),+ None,+ crate::core::runtime::CoreBootMode::Normal,+ )+ .await+ .expect("normal boot with config discovery");+ let config = config.expect("normal boot config loaded from disk");+ let config_path_a = config.config_path.clone();+ let config_root_b = tempfile::tempdir().expect("selected config root B");+ let config_path_b = config_root_b.path().join("config.toml");+ assert_eq!(+ config_path_a,+ std::env::var_os("HOME")+ .map(std::path::PathBuf::from)+ .expect("isolated HOME")+ .join(".openhuman/users/local/config.toml")+ );++ crate::core::runtime::CoreContext::scope(context, async {+ assert!(crate::core::runtime::CoreContext::current_embedder_config().is_none());+ assert!(record("normal-boot-provider", 401));+ })+ .await;++ let (errors_for_a, unattributed_for_a) =+ snapshot_for_scope(&config.workspace_dir, &config_path_a, None);+ let (errors_for_b, unattributed_for_b) =+ snapshot_for_scope(&config.workspace_dir, &config_path_b, None);+ assert_eq!(errors_for_a.len(), 1);+ assert!(!unattributed_for_a);+ assert!(errors_for_b.is_empty());+ assert!(!unattributed_for_b);+ reset_for_tests();+ });+}diff --git a/crates/openhuman-core/src/inference/embedding_host/factory.rs b/crates/openhuman-core/src/inference/embedding_host/factory.rsindex 8fe9d1b98a..8c04c07fca 100644--- a/crates/openhuman-core/src/inference/embedding_host/factory.rs+++ b/crates/openhuman-core/src/inference/embedding_host/factory.rs@@ -48,6 +48,31 @@ fn managed_factory(config: &Config, chat: Option<ApprovalChatContext>) -> Manage})}+fn inspection_managed_factory(config: &Config) -> ManagedModelFactory {+ let config = config.clone();+ Arc::new(move |model, dimensions| {+ let Some(registered) = crate::inference::registry::inspection_embedding(PROVIDER_OPENHUMAN)+ else {+ log::debug!("[embeddings::factory] no inspection-safe managed embedder registered");+ return Ok(Box::new(UnavailableEmbeddingModel::new(model, dimensions)));+ };+ let (state_dir, secrets_encrypt) = credential_scope(Some(&config));+ registered(&EmbeddingRequest {+ config: Some(&config),+ model,+ dimensions,+ chat: None,+ state_dir,+ secrets_encrypt,+ })+ .map_err(|_| {+ tinyinference_embeddings::Error::Validation(+ "managed embedding inspection is unavailable".to_owned(),+ )+ })+ })+}+fn credential_resolver(config: &Config) -> CredentialResolver {let config = config.clone();Arc::new(move |provider| super::rpc::resolve_api_key(&config, provider))@@ -117,6 +142,40 @@ pub fn create_embedding_provider_with_config()}+/// Builds the selected provider through the shared TinyInference factory,+/// using only the supplied read-only credential snapshot for BYOK providers.+/// Managed embeddings use a separate inspection-safe factory and never fall+/// back to the ordinary mutable managed factory.+pub fn create_embedding_provider_for_inspection(+ config: &Config,+ provider: &str,+ model: &str,+ dimensions: usize,+ api_key: &str,+ custom_endpoint: Option<&str>,+) -> anyhow::Result<Box<dyn EmbeddingModel>> {+ let provider = custom_endpoint+ .filter(|_| provider == "custom")+ .map(|endpoint| format!("custom:{endpoint}"))+ .unwrap_or_else(|| provider.to_owned());+ let selected = settings(+ &provider,+ model,+ dimensions,+ tinyinference_local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ ),+ );+ let api_key = api_key.to_owned();+ let credentials: CredentialResolver = Arc::new(move |_| api_key.clone());+ let model = create_configured_embedding_model(+ &selected,+ &credentials,+ &inspection_managed_factory(config),+ )?;+ Ok(model)+}+/// [`create_embedding_provider_with_config`] for a call made in a chat turn:/// the managed (cloud) model discloses its egress to `chat`, the turn's thread/// and client, so the disclosure card reaches the chat that triggered it.diff --git a/crates/openhuman-core/src/inference/embedding_host/mod.rs b/crates/openhuman-core/src/inference/embedding_host/mod.rsindex ff86e620f8..d5b467fdba 100644--- a/crates/openhuman-core/src/inference/embedding_host/mod.rs+++ b/crates/openhuman-core/src/inference/embedding_host/mod.rs@@ -23,11 +23,12 @@ pub use cloud::{UnavailableEmbeddingModel, DEFAULT_CLOUD_EMBEDDING_DIMENSIONS, DEFAULT_CLOUD_EMBEDDING_MODEL,};pub use factory::{- create_embedding_provider_for_chat, create_embedding_provider_with_config,- create_embedding_provider_with_credentials, default_embedding_provider_for_chat,- default_embedding_provider_with_config,+ create_embedding_provider_for_chat, create_embedding_provider_for_inspection,+ create_embedding_provider_with_config, create_embedding_provider_with_credentials,+ default_embedding_provider_for_chat, default_embedding_provider_with_config,};pub use rpc::provider_from_config;+pub(crate) use rpc::{probe_dimensions_for_inspection, InspectionEmbeddingError};/// A shared embedding provider as this module's factories return it, nameable/// by hosts that hold one without depending on the embeddings crate.pub type SharedEmbeddingModel = std::sync::Arc<dyn tinyinference_embeddings::EmbeddingModel>;diff --git a/crates/openhuman-core/src/inference/embedding_host/rpc.rs b/crates/openhuman-core/src/inference/embedding_host/rpc.rsindex 5ceee0d365..63dd6116ae 100644--- a/crates/openhuman-core/src/inference/embedding_host/rpc.rs+++ b/crates/openhuman-core/src/inference/embedding_host/rpc.rs@@ -10,6 +10,7 @@ mod settings;pub use api_keys::{clear_api_key, set_api_key};pub use embed::{embed, test_connection};+pub(crate) use embed::{probe_dimensions_for_inspection, InspectionEmbeddingError};pub use settings::{get_settings, update_settings};#[cfg(test)]@@ -87,3 +88,19 @@ pub(crate) fn resolve_api_key(config: &Config, provider_name: &str) -> String {.flatten().unwrap_or_default()}++pub(crate) fn resolve_api_key_read_only(+ config: &Config,+ provider_name: &str,+) -> Result<String, crate::security::credentials::profiles::ReadOnlyAuthProfileError> {+ let slug = if provider_name.starts_with("custom:") {+ "custom"+ } else {+ provider_name+ };+ let cred_provider = format!("embeddings:{slug}");+ Ok(+ AuthService::get_provider_bearer_token_read_only(config, &cred_provider, None)?+ .unwrap_or_default(),+ )+}diff --git a/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs b/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rsindex 3aee247073..f2da1a3a49 100644--- a/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs+++ b/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs@@ -4,7 +4,9 @@ use crate::config::Config;use crate::core::Outcome;use super::{resolve_api_key, LOG_PREFIX};-use crate::inference::embedding_host::factory::create_embedding_provider_with_config;+use crate::inference::embedding_host::factory::{+ create_embedding_provider_for_inspection, create_embedding_provider_with_config,+};use tinyinference_embeddings::probe::probe_custom_embeddings;/// Generates embeddings for the given input texts using the currently@@ -145,3 +147,77 @@ pub async fn test_connection(}}}++/// The requested and actual vector widths from one read-only doctor probe.+pub(crate) struct InspectionEmbeddingDimensions {+ pub configured: usize,+ pub actual: usize,+}++/// Safe failure classes for the live doctor embedding probe.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum InspectionEmbeddingError {+ CredentialStoreUnavailable,+ ProviderUnavailable,+ ProbeFailed,+}++/// Embeds one fixed, non-user string through the same configured provider+/// factory, using read-only profile credentials and an inspection-safe managed+/// provider when the selected route is managed.+pub(crate) async fn probe_dimensions_for_inspection(+ config: &Config,+) -> Result<InspectionEmbeddingDimensions, InspectionEmbeddingError> {+ let provider_name = config.memory.embedding_provider.trim();+ let model = config.memory.embedding_model.trim();+ let configured = config.memory.embedding_dimensions;+ let api_key = super::resolve_api_key_read_only(config, provider_name)+ .map_err(|_| InspectionEmbeddingError::CredentialStoreUnavailable)?;+ let custom_endpoint = provider_name.strip_prefix("custom:").map(str::to_owned);+ let provider_slug = if custom_endpoint.is_some() {+ "custom"+ } else {+ provider_name+ };++ // Ollama's `/api/embed` endpoint does not accept a requested output width.+ // The normal provider constructor uses `configured` as a validation width,+ // which turns a doctor probe into an opaque failure before it can report+ // the actual vector width. Use TinyInference's single-request discovery+ // path for this inspection only; runtime embeddings keep their configured+ // width validation.+ let actual = if provider_slug == "ollama" {+ let base_url = tinyinference_local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );+ let input = ["OpenHuman doctor embedding probe".to_owned()];+ let (_, vectors) =+ tinyinference_embeddings::OllamaEmbeddingModel::embed_discovering_dimensions(+ &base_url,+ model,+ reqwest::Client::new(),+ &input,+ tinyinference_embeddings::RECOMMENDED_OLLAMA_CONTEXT_TOKENS,+ 1,+ )+ .await+ .map_err(|_| InspectionEmbeddingError::ProbeFailed)?;+ vectors.first().map_or(0, Vec::len)+ } else {+ let embedder = create_embedding_provider_for_inspection(+ config,+ provider_slug,+ model,+ configured,+ &api_key,+ custom_endpoint.as_deref(),+ )+ .map_err(|_| InspectionEmbeddingError::ProviderUnavailable)?;+ let vectors = embedder+ .embed(&["OpenHuman doctor embedding probe".to_owned()])+ .await+ .map_err(|_| InspectionEmbeddingError::ProbeFailed)?;+ vectors.first().map_or(0, Vec::len)+ };+ Ok(InspectionEmbeddingDimensions { configured, actual })+}diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rsindex 879540de47..c69285e687 100644--- a/crates/openhuman-core/src/inference/provider/factory.rs+++ b/crates/openhuman-core/src/inference/provider/factory.rs@@ -52,6 +52,8 @@ mod subprocess_providers;mod tiers;mod turn_model;+pub(crate) use chat_model::create_chat_model_with_identity_in_for_inspection;+pub(crate) use chat_model::create_chat_model_with_model_id_in_for_inspection;pub(crate) use chat_model::resolves_to_managed_backend;pub use chat_model::{create_chat_model_from_string, create_chat_model_from_string_with_model_id,@@ -79,13 +81,16 @@ pub(crate) use turn_model::{use access_gates::{emit_inference_egress, enforce_local_only_inference};use chat_model::{unresolved_chat_model_error, with_default_temperature};use cloud_slug::{- resolve_cloud_slug, try_create_cloud_slug_chat_model,+ resolve_cloud_slug, resolve_cloud_slug_with_access, try_create_cloud_slug_chat_model,+ try_create_cloud_slug_chat_model_for_inspection,+ try_create_cloud_slug_chat_model_for_inspection_with_identity,try_create_cloud_slug_chat_model_from_string,try_create_cloud_slug_chat_model_with_native_tools,};+use credentials::CredentialAccess;use local_runtime::{- try_create_local_runtime_chat_model, try_create_local_runtime_chat_model_from_string,- OptionalChatModelResult,+ try_create_local_runtime_chat_model, try_create_local_runtime_chat_model_for_inspection,+ try_create_local_runtime_chat_model_from_string, OptionalChatModelResult,};pub(crate) use managed_backend::{make_openhuman_backend_model_for_options, make_openhuman_backend_model_for_thread,@@ -94,7 +99,9 @@ use managed_backend::{managed_chat_model, resolve_managed_model};use primary_cloud::{legacy_inference_slug, resolve_primary_cloud_provider_string};use subprocess_providers::{prepare_claude_agent_sdk_chat_model, try_create_claude_agent_sdk_chat_model,+ try_create_claude_agent_sdk_chat_model_for_inspection,try_create_claude_agent_sdk_chat_model_from_string, try_create_claude_code_chat_model,+ try_create_claude_code_chat_model_for_inspection,try_create_claude_code_chat_model_from_string,};use tiers::{is_abstract_tier_model, managed_default_model};@@ -121,7 +128,9 @@ mod factory_tests;use crate::config::schema::cloud_providers::AuthStyle;use crate::config::Config;-use crate::inference::provider::openai_codex::resolve_openai_codex_routing;+use crate::inference::provider::openai_codex::{+ resolve_openai_codex_routing, resolve_openai_codex_routing_for_inspection,+};use crate::security::credentials::AuthService;use crate::security::egress::EgressLedger;use std::sync::Arc;@@ -133,6 +142,48 @@ use tinyinference_llm::providers::openai::codex::{};use tinyinference_llm::providers::openai::AuthStyle as CompatAuthStyle;+/// Opaque per-report identity for an inspection completion. It contains the+/// effective endpoint, exact frozen credential, and actual wire model, but+/// deliberately has no Debug/Display implementation.+#[derive(Clone, Eq, Hash, PartialEq)]+pub(crate) struct InspectionRequestIdentity {+ endpoint: String,+ credential: String,+ wire_model: String,+}++impl InspectionRequestIdentity {+ pub(crate) fn new(endpoint: String, credential: String, wire_model: String) -> Self {+ Self {+ endpoint,+ credential,+ wire_model,+ }+ }+}++/// Whether the resolved inspection route can enforce the requested output+/// token ceiling on the provider request.+#[derive(Debug, Clone, Copy, Eq, PartialEq)]+pub(crate) enum InspectionOutputBudgetCapability {+ /// The provider request enforces its requested output-token limit.+ Bounded,+ /// The provider route cannot express a bounded output-token request.+ Unsupported,+}++/// Result shape shared by inspection-only provider constructors.+type InspectionChatModelResult =+ Option<anyhow::Result<(Arc<dyn ChatModel<()>>, String, String, String)>>;++/// Prepared, frozen model plus its opaque deduplication identity.+pub(crate) struct PreparedInspectionChatModel {+ pub(crate) model: Arc<dyn ChatModel<()>>,+ pub(crate) model_id: String,+ pub(crate) identity: InspectionRequestIdentity,+ pub(crate) output_budget: InspectionOutputBudgetCapability,+}+/// Sentinel meaning "use the OpenHuman backend session JWT".pub const PROVIDER_OPENHUMAN: &str = "openhuman";/// Prefix for Ollama-local providers: `"ollama:<model>"`.diff --git a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs b/crates/openhuman-core/src/inference/provider/factory/chat_model.rsindex 269f6c2fbb..9c6a5bdf5d 100644--- a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs+++ b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs@@ -37,10 +37,130 @@ pub fn create_chat_model_with_model_id_in(Ok((with_default_temperature(model, temperature), model_id))}+/// Build a chat model for static inspection, sharing the runtime constructor+/// while resolving stored credentials through the read-only profile snapshot.+/// It never calls the model and never runs runtime session-expiry gates.+pub(crate) fn create_chat_model_with_model_id_in_for_inspection(+ ctx: &DispatchCtx,+ role: &str,+ config: &Config,+ temperature: f64,+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {+ let prepared =+ create_chat_model_with_identity_in_for_inspection(ctx, role, config, temperature)?;+ Ok((prepared.model, prepared.model_id))+}++/// Build a model for a live inspection call and preserve the exact resolved+/// endpoint, frozen credential, and wire-model identity used by that model.+pub(crate) fn create_chat_model_with_identity_in_for_inspection(+ _ctx: &DispatchCtx,+ role: &str,+ config: &Config,+ temperature: f64,+) -> anyhow::Result<PreparedInspectionChatModel> {+ let mut resolved = provider_for_role(role, config);+ if resolved.trim().is_empty() || resolved.trim() == "cloud" {+ resolved = resolve_primary_cloud_provider_string(config);+ }+ if resolves_to_managed_backend(role, config) {+ let build = managed_backend::managed_chat_model_build_for_inspection(role, config, None)?;+ return Ok(prepared_inspection_model(+ build.model,+ build.model_id.clone(),+ build.endpoint,+ build.credential,+ temperature,+ InspectionOutputBudgetCapability::Bounded,+ ));+ }+ if let Some(result) =+ try_create_claude_agent_sdk_chat_model_for_inspection(role, &resolved, config)+ {+ let (model, model_id, endpoint, credential) = result?;+ return Ok(prepared_inspection_model(+ model,+ model_id.clone(),+ endpoint,+ credential,+ temperature,+ InspectionOutputBudgetCapability::Bounded,+ ));+ }+ if let Some(result) = try_create_claude_code_chat_model_for_inspection(role, &resolved, config)+ {+ let (model, model_id, endpoint, credential) = result?;+ return Ok(prepared_inspection_model(+ model,+ model_id.clone(),+ endpoint,+ credential,+ temperature,+ InspectionOutputBudgetCapability::Bounded,+ ));+ }+ if let Some(result) = try_create_local_runtime_chat_model_for_inspection(role, config) {+ let (model, model_id, endpoint, credential) = result?;+ return Ok(prepared_inspection_model(+ model,+ model_id.clone(),+ endpoint,+ credential,+ temperature,+ InspectionOutputBudgetCapability::Bounded,+ ));+ }+ if let Some(result) =+ try_create_cloud_slug_chat_model_for_inspection_with_identity(role, config)+ {+ let (model, model_id, endpoint, credential, output_budget) = result?;+ return Ok(prepared_inspection_model(+ model,+ model_id.clone(),+ endpoint,+ credential,+ temperature,+ output_budget,+ ));+ }+ Err(unresolved_chat_model_error_with_access(+ role,+ &provider_for_role(role, config),+ config,+ &EgressLedger::none(),+ CredentialAccess::Inspection,+ ))+}++fn prepared_inspection_model(+ model: Arc<dyn ChatModel<()>>,+ model_id: String,+ endpoint: String,+ credential: String,+ temperature: f64,+ output_budget: InspectionOutputBudgetCapability,+) -> PreparedInspectionChatModel {+ PreparedInspectionChatModel {+ model: with_default_temperature(model, temperature),+ identity: InspectionRequestIdentity::new(endpoint, credential, model_id.clone()),+ model_id,+ output_budget,+ }+}+pub(super) fn create_chat_model_with_model_id_inner(ctx: &DispatchCtx,role: &str,config: &Config,+) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {+ create_chat_model_with_model_id_inner_and_access(ctx, role, config, CredentialAccess::Runtime)+}++fn create_chat_model_with_model_id_inner_and_access(+ ctx: &DispatchCtx,+ role: &str,+ config: &Config,+ credential_access: CredentialAccess,) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {if let Some(model) = ctx.host_overrides().and_then(|local| local.model_for(role)) {return Ok((@@ -73,7 +193,12 @@ pub(super) fn create_chat_model_with_model_id_inner(};if !test_override_active {if resolves_to_managed_backend(role, config) {- return make_openhuman_backend_model(role, config);+ return match credential_access {+ CredentialAccess::Runtime => make_openhuman_backend_model(role, config),+ CredentialAccess::Inspection => {+ super::managed_backend::managed_chat_model_for_inspection(role, config, None)+ }+ };}if let Some(result) =try_create_claude_agent_sdk_chat_model(role, config, &EgressLedger::none())@@ -98,16 +223,24 @@ pub(super) fn create_chat_model_with_model_id_inner(// codex-oauth or `/v1/responses` fallback) → crate-native `ChatModel`// (issue #4727 Phase 3, conservative subset). `openai`/codex, custom// proxy slugs, and the managed entry return `None` and fall through.- if let Some(result) = try_create_cloud_slug_chat_model(role, config, &EgressLedger::none())- {+ let cloud_slug = match credential_access {+ CredentialAccess::Runtime => {+ try_create_cloud_slug_chat_model(role, config, &EgressLedger::none())+ }+ CredentialAccess::Inspection => {+ try_create_cloud_slug_chat_model_for_inspection(role, config, &EgressLedger::none())+ }+ };+ if let Some(result) = cloud_slug {return result;}}- Err(unresolved_chat_model_error(+ Err(unresolved_chat_model_error_with_access(role,&provider_for_role(role, config),config,&EgressLedger::none(),+ credential_access,))}@@ -368,6 +501,22 @@ pub(super) fn unresolved_chat_model_error(provider: &str,config: &Config,egress: &EgressLedger,+) -> anyhow::Error {+ unresolved_chat_model_error_with_access(+ role,+ provider,+ config,+ egress,+ CredentialAccess::Runtime,+ )+}++pub(super) fn unresolved_chat_model_error_with_access(+ role: &str,+ provider: &str,+ config: &Config,+ egress: &EgressLedger,+ credential_access: CredentialAccess,) -> anyhow::Error {let p = provider.trim();@@ -391,17 +540,20 @@ pub(super) fn unresolved_chat_model_error(}if p.is_empty() || p == "cloud" {- return unresolved_chat_model_error(+ return unresolved_chat_model_error_with_access(role,&resolve_primary_cloud_provider_string(config),config,egress,+ credential_access,);}#[cfg(not(test))]- if let Err(error) = verify_session_active(config) {- return error;+ if credential_access == CredentialAccess::Runtime {+ if let Err(error) = verify_session_active(config) {+ return error;+ }}// Preserve the legacy chokepoint's disclosure ordering for invalid custom@@ -418,7 +570,13 @@ pub(super) fn unresolved_chat_model_error();}let (model, _) = split_model_and_temperature(model_with_temperature);- return match resolve_cloud_slug(role, slug.trim(), &model, config) {+ return match resolve_cloud_slug_with_access(+ role,+ slug.trim(),+ &model,+ config,+ credential_access,+ ) {Err(error) => error,Ok(_) => anyhow::anyhow!("[chat-factory] configured provider '{}' for role '{}' did not produce a crate-native chat model",diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rsindex 2c1258e477..c34ebe5914 100644--- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs+++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs@@ -9,6 +9,16 @@ use crate::inference::provider::factory::access_gates::verify_session_active;use crate::inference::provider::fallback_diagnostics;use tinyinference_llm::providers::anthropic::endpoint_is_anthropic_messages;+type CloudSlugInspectionChatModelResult = Option<+ anyhow::Result<(+ Arc<dyn ChatModel<()>>,+ String,+ String,+ String,+ InspectionOutputBudgetCapability,+ )>,+>;+/// Look up a `cloud_providers` entry by slug and build the provider./// The shared resolution for a `<slug>:<model>` cloud provider — the cloud/// `cloud_providers` entry, the effective model id (with `default_model`@@ -21,11 +31,31 @@ pub(super) struct CloudSlugResolution<'a> {pub(super) codex: tinyinference_llm::providers::openai::codex::OpenAiCodexRouting,}+pub(super) fn inspection_output_budget_capability(+ codex: &tinyinference_llm::providers::openai::codex::OpenAiCodexRouting,+) -> InspectionOutputBudgetCapability {+ if codex.using_oauth {+ InspectionOutputBudgetCapability::Unsupported+ } else {+ InspectionOutputBudgetCapability::Bounded+ }+}+pub(super) fn resolve_cloud_slug<'a>(role: &str,slug: &str,model: &str,config: &'a Config,+) -> anyhow::Result<CloudSlugResolution<'a>> {+ resolve_cloud_slug_with_access(role, slug, model, config, CredentialAccess::Runtime)+}++pub(super) fn resolve_cloud_slug_with_access<'a>(+ role: &str,+ slug: &str,+ model: &str,+ config: &'a Config,+ credential_access: CredentialAccess,) -> anyhow::Result<CloudSlugResolution<'a>> {let entry = config.cloud_providers.iter().find(|e| e.slug == slug);@@ -146,34 +176,60 @@ pub(super) fn resolve_cloud_slug<'a>(fallback_diagnostics::missing_provider_credentials_message(role, slug, local_chat)};- let key = lookup_key_for_slug(slug, config)- .map_err(|e| anyhow::anyhow!("{} (underlying error: {e})", missing_credentials()))?;+ let (key, bearer_is_oauth, oauth_account_id) = if credential_access+ == CredentialAccess::Inspection+ && entry.auth_style == AuthStyle::OpenhumanJwt+ {+ // The managed model constructor receives its credential later, on+ // invoke. Its hosted construction callback is config-only and offline.+ (String::new(), false, None)+ } else if credential_access == CredentialAccess::Inspection {+ let credential =+ super::credentials::lookup_key_for_slug_read_only(slug, config).map_err(|error| {+ anyhow::anyhow!("{} (underlying error: {error})", missing_credentials())+ })?;+ (credential.key, credential.is_oauth, credential.account_id)+ } else {+ let key = credential_access+ .lookup_key_for_slug(slug, config)+ .map_err(|error| {+ anyhow::anyhow!("{} (underlying error: {error})", missing_credentials())+ })?;+ let is_oauth = slug == "openai" && credential_access.openai_bearer_is_oauth(config);+ (key, is_oauth, None)+ };// A readable auth profile with no key for this slug returns `Ok("")`, which// would otherwise build a client with an empty bearer and surface as a raw// 401 from the provider several layers later — exactly the baffling error// this diagnostic exists to replace.//- // Scoped to the *implicit fallback* path deliberately. That is the case the- // diagnostic is for: a local-chat user whose background role landed on a- // BYOK slug they never configured. An explicitly routed provider keeps its- // existing behaviour and is allowed to build without a stored key — callers- // construct such models to probe or describe a provider before a key is- // saved, and failing that at construction time would be a behaviour change- // well beyond this diagnostic.+ // Runtime construction only rejects missing credentials on the implicit+ // fallback path: explicit routes may be constructed before a key is saved.+ // Inspection is stricter because doctor must report an unusable authenticated+ // route without invoking the model.//// Styles that carry no stored key (`OpenhumanJwt` injects a session JWT// downstream, `None` sends no auth header at all) are legitimately blank and// never trip this.- if implicit_fallback+ if (implicit_fallback || credential_access == CredentialAccess::Inspection)&& key.trim().is_empty()&& matches!(entry.auth_style, AuthStyle::Bearer | AuthStyle::Anthropic){anyhow::bail!("{}", missing_credentials());}- let bearer_is_oauth = slug == "openai" && openai_bearer_is_oauth(config);- let codex = resolve_openai_codex_routing(config, slug, &entry.endpoint, &key, bearer_is_oauth)- .map_err(anyhow::Error::msg)?;+ let codex = match credential_access {+ CredentialAccess::Runtime => {+ resolve_openai_codex_routing(config, slug, &entry.endpoint, &key, bearer_is_oauth)+ .map_err(anyhow::Error::msg)?+ }+ CredentialAccess::Inspection => resolve_openai_codex_routing_for_inspection(+ slug,+ &entry.endpoint,+ bearer_is_oauth,+ oauth_account_id,+ ),+ };Ok(CloudSlugResolution {entry,@@ -219,6 +275,70 @@ pub(super) fn try_create_cloud_slug_chat_model_with_native_tools(config: &Config,native_tool_calling: bool,egress: &EgressLedger,+) -> OptionalChatModelResult {+ try_create_cloud_slug_chat_model_with_native_tools_and_access(+ role,+ config,+ native_tool_calling,+ egress,+ CredentialAccess::Runtime,+ None,+ )+}++pub(super) fn try_create_cloud_slug_chat_model_for_inspection(+ role: &str,+ config: &Config,+ egress: &EgressLedger,+) -> OptionalChatModelResult {+ try_create_cloud_slug_chat_model_with_native_tools_and_access(+ role,+ config,+ true,+ egress,+ CredentialAccess::Inspection,+ None,+ )+}++pub(super) fn try_create_cloud_slug_chat_model_for_inspection_with_identity(+ role: &str,+ config: &Config,+) -> CloudSlugInspectionChatModelResult {+ let mut identity = None;+ let mut resolved = provider_for_role(role, config);+ if resolved.trim().is_empty() || resolved.trim() == "cloud" {+ resolved = resolve_primary_cloud_provider_string(config);+ }+ let result = try_create_cloud_slug_chat_model_from_string_with_native_tools_and_access(+ role,+ &resolved,+ config,+ true,+ &EgressLedger::none(),+ CredentialAccess::Inspection,+ Some(&mut identity),+ )?;+ Some(result.and_then(|(model, model_id)| {+ let (endpoint, credential, wire_model, output_budget) = identity.ok_or_else(|| {+ anyhow::anyhow!("inspection route did not expose its frozen wire identity")+ })?;+ if wire_model != model_id {+ anyhow::bail!("inspection route model identity did not match its constructed model");+ }+ Ok((model, model_id, endpoint, credential, output_budget))+ }))+}++fn try_create_cloud_slug_chat_model_with_native_tools_and_access(+ role: &str,+ config: &Config,+ native_tool_calling: bool,+ egress: &EgressLedger,+ credential_access: CredentialAccess,+ inspection_identity: Option<+ &mut Option<(String, String, String, InspectionOutputBudgetCapability)>,+ >,) -> OptionalChatModelResult {// Resolve the role's provider string, expanding the empty / "cloud" sentinel// to the primary cloud target.@@ -226,12 +346,14 @@ pub(super) fn try_create_cloud_slug_chat_model_with_native_tools(if resolved.trim().is_empty() || resolved.trim() == "cloud" {resolved = resolve_primary_cloud_provider_string(config);}- try_create_cloud_slug_chat_model_from_string_with_native_tools(+ try_create_cloud_slug_chat_model_from_string_with_native_tools_and_access(role,&resolved,config,native_tool_calling,egress,+ credential_access,+ inspection_identity,)}@@ -252,6 +374,28 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(config: &Config,native_tool_calling: bool,egress: &EgressLedger,+) -> OptionalChatModelResult {+ try_create_cloud_slug_chat_model_from_string_with_native_tools_and_access(+ role,+ provider,+ config,+ native_tool_calling,+ egress,+ CredentialAccess::Runtime,+ None,+ )+}++fn try_create_cloud_slug_chat_model_from_string_with_native_tools_and_access(+ role: &str,+ provider: &str,+ config: &Config,+ native_tool_calling: bool,+ egress: &EgressLedger,+ credential_access: CredentialAccess,+ mut inspection_identity: Option<+ &mut Option<(String, String, String, InspectionOutputBudgetCapability)>,+ >,) -> OptionalChatModelResult {let p = provider.trim().to_string();@@ -282,9 +426,11 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(if let Err(e) = enforce_local_only_inference(role, &p) {return Some(Err(e));}- #[cfg(not(test))]- if let Err(e) = verify_session_active(config) {- return Some(Err(e));+ if credential_access == CredentialAccess::Runtime {+ #[cfg(not(test))]+ if let Err(e) = verify_session_active(config) {+ return Some(Err(e));+ }}let CloudSlugResolution {@@ -292,7 +438,7 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(effective_model,key,codex,- } = match resolve_cloud_slug(role, &slug, &raw_model, config) {+ } = match resolve_cloud_slug_with_access(role, &slug, &raw_model, config, credential_access) {Ok(r) => r,Err(e) => return Some(Err(e)),};@@ -332,21 +478,45 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(}AuthStyle::Anthropic | AuthStyle::None => {}AuthStyle::OpenhumanJwt => {- #[cfg(not(test))]- if let Err(error) = verify_backend_session_active(config) {- return Some(Err(error));+ if credential_access == CredentialAccess::Runtime {+ #[cfg(not(test))]+ if let Err(error) = verify_backend_session_active(config) {+ return Some(Err(error));+ }}let model_override =(!effective_model.trim().is_empty()).then_some(effective_model.as_str());- return Some(managed_chat_model(- role,- config,- model_override,- None,- native_tool_calling,- None,- egress,- ));+ return Some(match credential_access {+ CredentialAccess::Runtime => managed_chat_model(+ role,+ config,+ model_override,+ None,+ native_tool_calling,+ None,+ egress,+ ),+ CredentialAccess::Inspection => {+ match super::managed_backend::managed_chat_model_build_for_inspection(+ role,+ config,+ model_override,+ ) {+ Ok(build) => {+ if let Some(identity) = inspection_identity.as_deref_mut() {+ *identity = Some((+ build.endpoint.clone(),+ build.credential.clone(),+ build.model_id.clone(),+ InspectionOutputBudgetCapability::Bounded,+ ));+ }+ Ok((build.model, build.model_id))+ }+ Err(error) => Err(error),+ }+ }+ });}AuthStyle::Bearer => {// The codex routing may re-target the endpoint (OAuth backend).@@ -415,5 +585,19 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(codex: codex_route,http,});+ if let Some(identity) = inspection_identity {+ let credential = if entry.auth_style == AuthStyle::None {+ String::new()+ } else {+ key.clone()+ };+ let output_budget = inspection_output_budget_capability(&codex);+ *identity = Some((+ codex.endpoint.clone(),+ credential,+ effective_model.clone(),+ output_budget,+ ));+ }Some(chat.map(|chat| (chat, effective_model)))}diff --git a/crates/openhuman-core/src/inference/provider/factory/credentials.rs b/crates/openhuman-core/src/inference/provider/factory/credentials.rsindex 1b252cc682..a7ea8f816f 100644--- a/crates/openhuman-core/src/inference/provider/factory/credentials.rs+++ b/crates/openhuman-core/src/inference/provider/factory/credentials.rs@@ -3,6 +3,195 @@use super::*;+type ReadOnlyProfileCredential = (+ String,+ bool,+ Option<chrono::DateTime<chrono::Utc>>,+ Option<String>,+);++/// Credential behavior used by shared model construction. Runtime callers keep+/// the established mutable auth-profile store path; doctor inspection uses the+/// selected profile's read-only snapshot and never refreshes credentials.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum CredentialAccess {+ Runtime,+ Inspection,+}++impl CredentialAccess {+ pub(super) fn lookup_key_for_slug(self, slug: &str, config: &Config) -> anyhow::Result<String> {+ match self {+ Self::Runtime => lookup_key_for_slug(slug, config),+ Self::Inspection => {+ lookup_key_for_slug_read_only(slug, config).map(|credential| credential.key)+ }+ }+ }++ pub(super) fn openai_bearer_is_oauth(self, config: &Config) -> bool {+ match self {+ Self::Runtime => openai_bearer_is_oauth(config),+ Self::Inspection => lookup_key_for_slug_read_only("openai", config)+ .map(|credential| credential.is_oauth)+ .unwrap_or(false),+ }+ }+}++pub(super) struct ReadOnlyCloudCredential {+ pub(super) key: String,+ pub(super) is_oauth: bool,+ pub(super) account_id: Option<String>,+}++pub(super) fn lookup_key_for_slug_read_only(+ slug: &str,+ config: &Config,+) -> anyhow::Result<ReadOnlyCloudCredential> {+ if slug == crate::config::schema::EPHEMERAL_ROUTE_SLUG {+ if let Some(route) = config.ephemeral_route.as_ref() {+ return Ok(ReadOnlyCloudCredential {+ key: route.api_key.trim().to_string(),+ is_oauth: false,+ account_id: None,+ });+ }+ }++ let auth_profile_key = auth_key_for_slug(slug);+ for provider in [auth_profile_key.as_str(), slug] {+ if let Some((key, is_oauth, expires_at, account_id)) =+ read_only_profile_credential(config, provider, None)?+ {+ if slug == "openai"+ && is_oauth+ && expires_at.is_some_and(|expires_at| {+ expires_at <= chrono::Utc::now() + chrono::Duration::minutes(2)+ })+ {+ anyhow::bail!("OpenAI OAuth credential requires refresh");+ }+ if !key.trim().is_empty() {+ return Ok(ReadOnlyCloudCredential {+ key,+ is_oauth,+ account_id,+ });+ }+ }+ }++ // The OAuth login is stored under a named profile rather than the+ // provider's active API-key profile. Its runtime lookup can refresh and+ // persist the token; doctor only reports when that refresh would be needed.+ if slug == "openai" {+ match read_only_profile_credential(+ config,+ crate::security::credentials::openai_oauth::OPENAI_PROVIDER_KEY,+ Some(crate::security::credentials::openai_oauth::OPENAI_OAUTH_PROFILE_NAME),+ )? {+ Some((key, true, expires_at, account_id)) if !key.trim().is_empty() => {+ if expires_at.is_some_and(|expires_at| {+ expires_at <= chrono::Utc::now() + chrono::Duration::minutes(2)+ }) {+ anyhow::bail!("OpenAI OAuth credential requires refresh");+ }+ return Ok(ReadOnlyCloudCredential {+ key,+ is_oauth: true,+ account_id,+ });+ }+ _ => {}+ }+ }++ // Preserve the narrowly scoped legacy config.toml fallback without+ // consulting the mutable auth-profile store.+ if legacy_inference_slug(config) == Some(slug) {+ if let Some(config_key) = config+ .api_key+ .as_deref()+ .map(str::trim)+ .filter(|key| !key.is_empty())+ {+ return Ok(ReadOnlyCloudCredential {+ key: config_key.to_string(),+ is_oauth: false,+ account_id: None,+ });+ }+ }++ Ok(ReadOnlyCloudCredential {+ key: String::new(),+ is_oauth: false,+ account_id: None,+ })+}++fn read_only_profile_credential(+ config: &Config,+ provider: &str,+ profile_override: Option<&str>,+) -> anyhow::Result<Option<ReadOnlyProfileCredential>> {+ let Some(profile) = crate::security::credentials::AuthService::get_profile_read_only(+ config,+ provider,+ profile_override,+ )+ .map_err(read_only_profile_error)?+ else {+ return Ok(None);+ };++ let (token, is_oauth, expires_at, account_id) = match profile.kind {+ crate::security::credentials::profiles::AuthProfileKind::Token => {+ (profile.token.unwrap_or_default(), false, None, None)+ }+ crate::security::credentials::profiles::AuthProfileKind::OAuth => {+ let access_token = profile+ .token_set+ .as_ref()+ .map(|tokens| tokens.access_token.trim().to_string())+ .unwrap_or_default();+ let account_id = profile+ .metadata+ .get("account_id")+ .map(String::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+ .or_else(|| {+ tinyinference_providers::oauth::openai_account_id_from_access_token(+ &access_token,+ )+ });+ (+ access_token,+ true,+ profile.token_set.and_then(|tokens| tokens.expires_at),+ account_id,+ )+ }+ };+ Ok(Some((token, is_oauth, expires_at, account_id)))+}++fn read_only_profile_error(+ error: crate::security::credentials::profiles::ReadOnlyAuthProfileError,+) -> anyhow::Error {+ match error {+ crate::security::credentials::profiles::ReadOnlyAuthProfileError::Unavailable => {+ anyhow::anyhow!("read-only credential profile is unavailable")+ }+ crate::security::credentials::profiles::ReadOnlyAuthProfileError::InvalidStore => {+ anyhow::anyhow!("read-only credential profile store is invalid")+ }+ }+}+/// Auth-profile storage key for a slug-keyed provider.////// New writes use `"provider:<slug>"`. Lookups also try the bare `<slug>`diff --git a/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs b/crates/openhuman-core/src/inference/provider/factory/local_runtime.rsindex 3aef45d5ac..2e82971887 100644--- a/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs+++ b/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs@@ -38,6 +38,44 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(provider: &str,config: &Config,egress: &EgressLedger,+) -> OptionalChatModelResult {+ try_create_local_runtime_chat_model_from_string_with_identity(+ role, provider, config, egress, false, None,+ )+}++pub(super) fn try_create_local_runtime_chat_model_for_inspection(+ role: &str,+ config: &Config,+) -> InspectionChatModelResult {+ let provider = provider_for_role(role, config);+ let mut identity = None;+ let result = try_create_local_runtime_chat_model_from_string_with_identity(+ role,+ &provider,+ config,+ &EgressLedger::none(),+ true,+ Some(&mut identity),+ )?;+ Some(result.and_then(|(model, model_id)| {+ let (endpoint, credential, wire_model) = identity.ok_or_else(|| {+ anyhow::anyhow!("inspection route did not expose its frozen wire identity")+ })?;+ if wire_model != model_id {+ anyhow::bail!("inspection route model identity did not match its constructed model");+ }+ Ok((model, model_id, endpoint, credential))+ }))+}++fn try_create_local_runtime_chat_model_from_string_with_identity(+ role: &str,+ provider: &str,+ config: &Config,+ egress: &EgressLedger,+ inspection: bool,+ inspection_identity: Option<&mut Option<(String, String, String)>>,) -> OptionalChatModelResult {use tinyinference_local::local_runtime::{resolve_local_runtime, LocalRuntimeAuth, LocalRuntimeInputs,@@ -58,8 +96,10 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(if let Err(e) = enforce_local_only_inference(role, &p) {return Some(Err(e));}- if let Err(e) = verify_provider_session(config, provider) {- return Some(Err(e));+ if !inspection {+ if let Err(e) = verify_provider_session(config, provider) {+ return Some(Err(e));+ }}// Egress spine (privacy epic S2, #4436): committed to a local runtime here@@ -81,6 +121,17 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(Ok(r) => r,Err(e) => return Some(Err(anyhow::anyhow!("{e}"))),};+ if let Some(identity) = inspection_identity {+ let credential = match &resolved.auth {+ LocalRuntimeAuth::None => String::new(),+ LocalRuntimeAuth::Bearer => resolved.api_key.clone(),+ };+ *identity = Some((+ resolved.endpoint.clone(),+ credential,+ resolved.model.clone(),+ ));+ }let auth = match resolved.auth {LocalRuntimeAuth::None => CompatAuthStyle::None,LocalRuntimeAuth::Bearer => CompatAuthStyle::Bearer,diff --git a/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs b/crates/openhuman-core/src/inference/provider/factory/managed_backend.rsindex 707a13fedb..388013b18f 100644--- a/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs+++ b/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs@@ -103,6 +103,40 @@ pub(super) fn managed_chat_model(})}+/// Build a managed model only through the host's explicitly inspection-safe+/// callback. This path never falls back to the runtime factory: doing so could+/// defer mutable credential access until invoke/stream.+pub(super) fn managed_chat_model_for_inspection(+ role: &str,+ config: &Config,+ model_override: Option<&str>,+) -> anyhow::Result<ManagedChatModel> {+ let build = managed_chat_model_build_for_inspection(role, config, model_override)?;+ Ok((build.model, build.model_id))+}++pub(super) fn managed_chat_model_build_for_inspection(+ role: &str,+ config: &Config,+ model_override: Option<&str>,+) -> anyhow::Result<crate::inference::registry::InspectionChatModelBuild> {+ enforce_local_only_inference(role, PROVIDER_OPENHUMAN)?;+ let Some(factory) = crate::inference::registry::inspection_chat_model(PROVIDER_OPENHUMAN)+ else {+ return Err(managed_unavailable_error());+ };+ let model = resolve_managed_model(role, config, model_override);+ (factory)(&crate::inference::registry::ChatModelRequest {+ role,+ config,+ model_override: Some(&model),+ default_model: None,+ native_tool_calling: true,+ thread_id: None,+ egress: &EgressLedger::none(),+ })+}+/// Construct a managed turn model with the explicit OpenHuman thread attached.pub(crate) fn make_openhuman_backend_model_for_thread(role: &str,diff --git a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rsindex e1b6581ef4..1198de014b 100644--- a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs+++ b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs@@ -33,6 +33,53 @@ pub(super) fn try_create_claude_agent_sdk_chat_model_from_string(Some(Ok((chat, model)))}+/// Creates a bounded one-shot CLI model only when the explicit environment+/// credential can be frozen and passed to the inspection-only wrapper.+pub(super) fn try_create_claude_agent_sdk_chat_model_for_inspection(+ role: &str,+ provider: &str,+ config: &Config,+) -> InspectionChatModelResult {+ let model = claude_agent_sdk_model_from_string(provider, config)?;+ Some((|| {+ enforce_local_only_inference(role, provider)?;+ let api_key = std::env::var("ANTHROPIC_API_KEY")+ .ok()+ .filter(|value| !value.is_empty());+ let auth_token = std::env::var("ANTHROPIC_AUTH_TOKEN")+ .ok()+ .filter(|value| !value.is_empty());+ let credential = api_key+ .as_deref()+ .or(auth_token.as_deref())+ .ok_or_else(|| anyhow::anyhow!("explicit Claude API credential is unavailable"))?+ .to_string();+ let base_url = std::env::var("ANTHROPIC_BASE_URL")+ .ok()+ .filter(|value| !value.is_empty());+ let endpoint = base_url+ .as_deref()+ .unwrap_or("https://api.anthropic.com")+ .trim_end_matches('/')+ .to_string();+ let auth =+ tinyagents_harness::providers::claude_agent_sdk::ClaudeAgentSdkInspectionAuth::new(+ api_key, auth_token, base_url,+ )?;+ let chat = ClaudeAgentSdkProvider::for_inspection(+ (&config.claude_agent_sdk).into(),+ model.clone(),+ auth,+ );+ Ok((+ Arc::new(chat) as Arc<dyn ChatModel<()>>,+ model.clone(),+ endpoint,+ credential,+ ))+ })())+}+pub(super) fn prepare_claude_agent_sdk_chat_model(role: &str,provider: &str,@@ -129,6 +176,25 @@ pub(super) fn try_create_claude_code_chat_model_from_string(Some(Ok((chat, configured_model)))}+/// Uses the same Claude CLI for a one-shot, tool-free inspection request. The+/// route is unavailable without an explicit API credential; the saved CLI+/// session is never read.+pub(super) fn try_create_claude_code_chat_model_for_inspection(+ role: &str,+ provider: &str,+ config: &Config,+) -> InspectionChatModelResult {+ let provider = provider.trim();+ let model_with_temp =+ provider.strip_prefix(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)?;+ let (configured_model, _) = split_model_and_temperature(model_with_temp);+ if configured_model.is_empty() {+ return Some(Err(anyhow::anyhow!("Claude CLI route has an empty model")));+ }+ let sdk_provider = format!("{CLAUDE_AGENT_SDK_PREFIX}{configured_model}");+ try_create_claude_agent_sdk_chat_model_for_inspection(role, &sdk_provider, config)+}+#[derive(Debug)]struct OpenHumanMcpEndpoint;diff --git a/crates/openhuman-core/src/inference/provider/factory_tests.rs b/crates/openhuman-core/src/inference/provider/factory_tests.rsindex 051672c51a..7a87fe318a 100644--- a/crates/openhuman-core/src/inference/provider/factory_tests.rs+++ b/crates/openhuman-core/src/inference/provider/factory_tests.rs@@ -3,8 +3,33 @@ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};use crate::config::Config;use crate::security::credentials::AuthService;use tempfile::TempDir;+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};use crate::inference::provider::factory::access_gates::host_requires_session;++#[test]+fn inspection_codex_oauth_metadata_marks_output_budget_unsupported() {+ use crate::inference::provider::factory::InspectionOutputBudgetCapability;+ use tinyinference_llm::providers::openai::codex::OpenAiCodexRouting;++ let codex = OpenAiCodexRouting {+ endpoint: "https://chatgpt.com/backend-api/codex".into(),+ using_oauth: true,+ account_id: Some("acct-test".into()),+ };+ assert_eq!(+ super::cloud_slug::inspection_output_budget_capability(&codex),+ InspectionOutputBudgetCapability::Unsupported+ );+ assert_eq!(+ super::cloud_slug::inspection_output_budget_capability(&OpenAiCodexRouting::standard(+ "https://api.openai.com/v1"+ )),+ InspectionOutputBudgetCapability::Bounded+ );+}+fn create_test_chat_model_from_string(role: &str,provider: &str,@@ -41,6 +66,62 @@ fn config_with_providers_in_tempdir(tmp: &TempDir, providers: Vec<CloudProviderCc}+#[test]+fn inspection_requires_credentials_for_explicit_authenticated_cloud_routes() {+ let tmp = TempDir::new().expect("temporary provider workspace");+ let mut provider = openai_entry("p_missing_key", "factory-missing-key-test");+ let mut config = config_with_providers_in_tempdir(&tmp, vec![provider.clone()]);+ config.chat_provider = Some("factory-missing-key-test:gpt-4o".to_string());++ let inspection = super::chat_model::create_chat_model_with_model_id_in_for_inspection(+ &crate::core::runtime::DispatchCtx::ambient(),+ "chat",+ &config,+ 0.0,+ );+ assert!(+ inspection.is_err(),+ "inspection must reject explicit Bearer routes without credentials"+ );++ let runtime = super::chat_model::create_chat_model_with_model_id_in(+ &crate::core::runtime::DispatchCtx::ambient(),+ "chat",+ &config,+ 0.0,+ );+ assert!(+ runtime.is_ok(),+ "runtime construction preserves explicit routes before a key is saved"+ );++ provider.auth_style = AuthStyle::Anthropic;+ config.cloud_providers = vec![provider.clone()];+ assert!(+ super::chat_model::create_chat_model_with_model_id_in_for_inspection(+ &crate::core::runtime::DispatchCtx::ambient(),+ "chat",+ &config,+ 0.0,+ )+ .is_err(),+ "inspection must reject explicit Anthropic routes without credentials"+ );++ provider.auth_style = AuthStyle::None;+ config.cloud_providers = vec![provider];+ assert!(+ super::chat_model::create_chat_model_with_model_id_in_for_inspection(+ &crate::core::runtime::DispatchCtx::ambient(),+ "chat",+ &config,+ 0.0,+ )+ .is_ok(),+ "unauthenticated proxy routes do not require a stored credential"+ );+}+fn oh_entry(id: &str) -> CloudProviderCreds {CloudProviderCreds {id: id.to_string(),@@ -130,6 +211,251 @@ fn store_byo_key(config: &Config, slug: &str, token: &str) {.expect("store provider token");}+#[tokio::test(flavor = "multi_thread")]+async fn inspection_construction_does_not_refresh_unselected_expired_codex_oauth_profile() {+ use crate::config::test_env::EnvVarGuard;+ use crate::security::credentials::openai_oauth::{+ OPENAI_OAUTH_PROFILE_NAME, OPENAI_PROVIDER_KEY,+ };+ use chrono::{Duration, Utc};++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let tmp = tempfile::tempdir().expect("temporary credentials fixture");+ let refresh_server = MockServer::start().await;+ let mut config = Config::default();+ config.config_path = tmp.path().join("config.toml");+ config.workspace_dir = tmp.path().join("workspace");+ config.action_dir = tmp.path().join("action");+ config.secrets.encrypt = false;++ let _env = EnvVarGuard::locked_async()+ .await+ .with("HOME", tmp.path())+ .with("OPENHUMAN_WORKSPACE", &config.workspace_dir)+ .with("OPENHUMAN_KEYRING_BACKEND", "file")+ .with(+ "OPENAI_CODEX_OAUTH_TOKEN_URL",+ format!("{}/token", refresh_server.uri()),+ );+ let expires_at = (Utc::now() - Duration::minutes(5)).to_rfc3339();+ let created_at = (Utc::now() - Duration::hours(1)).to_rfc3339();+ let updated_at = created_at.clone();+ let profiles_path = tmp.path().join("auth-profiles.json");+ std::fs::write(+ &profiles_path,+ serde_json::to_vec_pretty(&serde_json::json!({+ "schema_version": 1,+ "updated_at": created_at.clone(),+ "active_profiles": {+ (OPENAI_PROVIDER_KEY): format!("{OPENAI_PROVIDER_KEY}:default")+ },+ "profiles": {+ (format!("{OPENAI_PROVIDER_KEY}:default")): {+ "provider": OPENAI_PROVIDER_KEY,+ "profile_name": "default",+ "kind": "token",+ "token": "dummy-selected-api-key",+ "created_at": created_at.clone(),+ "updated_at": updated_at.clone(),+ "metadata": {}+ },+ (format!("{OPENAI_PROVIDER_KEY}:{OPENAI_OAUTH_PROFILE_NAME}")): {+ "provider": OPENAI_PROVIDER_KEY,+ "profile_name": OPENAI_OAUTH_PROFILE_NAME,+ "kind": "oauth",+ "access_token": "expired-oauth-access-token",+ "refresh_token": "dummy-refresh-token",+ "expires_at": expires_at,+ "token_type": "Bearer",+ "created_at": created_at.clone(),+ "updated_at": updated_at.clone(),+ "metadata": {}+ }+ }+ }))+ .expect("serialize raw auth-profile schema"),+ )+ .expect("write raw profile fixture without mutable auth APIs");++ let selected = AuthService::get_profile_read_only(&config, OPENAI_PROVIDER_KEY, None)+ .expect("selected profile is readable without mutable auth")+ .expect("selected API-key profile exists");+ assert_eq!(selected.profile_name, "default");+ assert_eq!(selected.token.as_deref(), Some("dummy-selected-api-key"));+ let oauth = AuthService::get_profile_read_only(+ &config,+ OPENAI_PROVIDER_KEY,+ Some(OPENAI_OAUTH_PROFILE_NAME),+ )+ .expect("named OAuth profile is readable without refreshing")+ .expect("expired OAuth profile exists");+ assert!(oauth+ .token_set+ .as_ref()+ .and_then(|token_set| token_set.expires_at)+ .is_some_and(|expires_at| expires_at < Utc::now()));+ let selected_codex_credential =+ super::credentials::lookup_key_for_slug_read_only("openai", &config)+ .expect("read selected OpenAI API-key credential");+ assert_eq!(selected_codex_credential.key, "dummy-selected-api-key");+ assert!(!selected_codex_credential.is_oauth);+ assert_eq!(selected_codex_credential.account_id, None);++ Mock::given(method("POST"))+ .and(path("/token"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "access_token": "refreshed-oauth-token-must-not-be-written",+ "refresh_token": "rotated-dummy-refresh-token",+ "expires_in": 3600,+ })))+ .mount(&refresh_server)+ .await;+ let snapshot =+ std::fs::read(&profiles_path).expect("snapshot raw credential file before inspection");++ let mut provider = openai_entry("p_openai_inspection", "openai");+ provider.endpoint = "https://api.openai.example.test/v1".into();+ config.cloud_providers = vec![provider];+ config.chat_provider = Some("openai:gpt-4o".into());+ let inspected = super::chat_model::create_chat_model_with_model_id_in_for_inspection(+ &crate::core::runtime::DispatchCtx::ambient(),+ "chat",+ &config,+ 0.0,+ );+ assert!(+ inspected.is_ok(),+ "the selected API-key profile is sufficient for model construction"+ );++ assert!(+ refresh_server+ .received_requests()+ .await+ .expect("refresh mock records requests")+ .is_empty(),+ "inspection construction must not refresh the unrelated expired OAuth profile"+ );+ assert_eq!(+ std::fs::read(tmp.path().join("auth-profiles.json"))+ .expect("read credential store after inspection"),+ snapshot,+ "inspection must leave all credential bytes unchanged"+ );+ let selected_after = AuthService::get_profile_read_only(&config, OPENAI_PROVIDER_KEY, None)+ .expect("selected profile remains readable")+ .expect("selected profile remains present");+ assert_eq!(selected_after.profile_name, "default");+ assert_eq!(+ selected_after.token.as_deref(),+ Some("dummy-selected-api-key")+ );+ let oauth_after = AuthService::get_profile_read_only(+ &config,+ OPENAI_PROVIDER_KEY,+ Some(OPENAI_OAUTH_PROFILE_NAME),+ )+ .expect("OAuth snapshot remains readable")+ .expect("OAuth snapshot remains present");+ assert_eq!(+ oauth_after+ .token_set+ .as_ref()+ .map(|token_set| token_set.access_token.as_str()),+ Some("expired-oauth-access-token"),+ "inspection must not replace an expired token with a refreshed one"+ );+ assert!(oauth_after+ .token_set+ .as_ref()+ .and_then(|token_set| token_set.expires_at)+ .is_some_and(|expires_at| expires_at < Utc::now()));+}++#[tokio::test(flavor = "multi_thread")]+async fn inspection_codex_metadata_matches_the_selected_oauth_profile() {+ use crate::config::test_env::EnvVarGuard;+ use chrono::{Duration, Utc};++ let _inference_guard = crate::inference::inference_test_guard_async().await;+ let temp = tempfile::tempdir().expect("temporary credentials fixture");+ let mut config = Config::default();+ config.config_path = temp.path().join("config.toml");+ config.workspace_dir = temp.path().join("workspace");+ config.action_dir = temp.path().join("action");+ config.secrets.encrypt = false;+ let _env = EnvVarGuard::locked_async()+ .await+ .with("HOME", temp.path())+ .with("OPENHUMAN_WORKSPACE", &config.workspace_dir)+ .with("OPENHUMAN_KEYRING_BACKEND", "file");++ let now = Utc::now();+ let created = (now - Duration::hours(1)).to_rfc3339();+ let expires = (now + Duration::hours(1)).to_rfc3339();+ let raw_profiles = serde_json::json!({+ "schema_version": 1,+ "updated_at": created,+ "active_profiles": {+ "provider:openai": "provider:openai:active-oauth"+ },+ "profiles": {+ "provider:openai:active-oauth": {+ "provider": "provider:openai",+ "profile_name": "active-oauth",+ "kind": "oauth",+ "access_token": "active-oauth-bearer",+ "refresh_token": "active-refresh-token",+ "expires_at": expires,+ "token_type": "Bearer",+ "metadata": {"account_id": "acct-active"},+ "created_at": created,+ "updated_at": created+ },+ "provider:openai:oauth": {+ "provider": "provider:openai",+ "profile_name": "oauth",+ "kind": "oauth",+ "access_token": "other-oauth-bearer",+ "refresh_token": "other-refresh-token",+ "expires_at": expires,+ "token_type": "Bearer",+ "metadata": {"account_id": "acct-unselected"},+ "created_at": created,+ "updated_at": created+ }+ }+ });+ let profiles_path = temp.path().join("auth-profiles.json");+ std::fs::write(+ &profiles_path,+ serde_json::to_vec_pretty(&raw_profiles).expect("serialize profile fixture"),+ )+ .expect("write read-only profile fixture");+ let before = std::fs::read(&profiles_path).expect("snapshot profile bytes");++ let selected = super::credentials::lookup_key_for_slug_read_only("openai", &config)+ .expect("read selected OAuth profile");+ assert_eq!(selected.key, "active-oauth-bearer");+ assert!(selected.is_oauth);+ assert_eq!(selected.account_id.as_deref(), Some("acct-active"));++ let routing =+ crate::inference::provider::openai_codex::resolve_openai_codex_routing_for_inspection(+ "openai",+ "https://api.openai.example.test/v1",+ selected.is_oauth,+ selected.account_id,+ );+ assert!(routing.using_oauth);+ assert_eq!(routing.account_id.as_deref(), Some("acct-active"));+ assert_eq!(+ std::fs::read(profiles_path).expect("profile bytes remain readable"),+ before,+ "inspection routing must not refresh or migrate profile data"+ );+}+// ── Motion B (#4727 Phase 3): wire-equivalent BYOK cloud-slug cutover ────────fn deepseek_entry(id: &str) -> CloudProviderCreds {diff --git a/crates/openhuman-core/src/inference/provider/openai_codex.rs b/crates/openhuman-core/src/inference/provider/openai_codex.rsindex 71def06181..fd147aa570 100644--- a/crates/openhuman-core/src/inference/provider/openai_codex.rs+++ b/crates/openhuman-core/src/inference/provider/openai_codex.rs@@ -43,3 +43,25 @@ pub(crate) fn resolve_openai_codex_routing(OpenAiCodexRouting::standard(endpoint)})}++/// Resolve Codex routing from the OAuth metadata that belongs to the exact+/// read-only credential selected for inspection. A plain API-key bearer must+/// not consult the separate saved OAuth profile at all.+pub(crate) fn resolve_openai_codex_routing_for_inspection(+ slug: &str,+ endpoint: &str,+ bearer_is_oauth: bool,+ account_id: Option<String>,+) -> OpenAiCodexRouting {+ if slug == "openai" && bearer_is_oauth {+ OpenAiCodexRouting {+ endpoint: OPENAI_CODEX_BACKEND_BASE_URL.to_string(),+ using_oauth: true,+ account_id: account_id+ .map(|value| value.trim().to_string())+ .filter(|value| !value.is_empty()),+ }+ } else {+ OpenAiCodexRouting::standard(endpoint)+ }+}diff --git a/crates/openhuman-core/src/inference/registry.rs b/crates/openhuman-core/src/inference/registry.rsindex 81659f3f7e..581c8f6508 100644--- a/crates/openhuman-core/src/inference/registry.rs+++ b/crates/openhuman-core/src/inference/registry.rs@@ -14,9 +14,11 @@//! The tables know nothing about what a provider talks to. With nothing//! registered every consult point behaves exactly as before.+use std::collections::hash_map::RandomState;use std::future::Future;+use std::hash::{BuildHasher, Hash, Hasher};use std::pin::Pin;-use std::sync::Arc;+use std::sync::{Arc, OnceLock};use tinyinference_embeddings::EmbeddingModel;use tinyinference_llm::model::discover::DiscoveryRequest;@@ -78,6 +80,63 @@ pub struct ChatModelEntry {static CHAT_MODELS: HookSlot<ChatModelEntry> = HookSlot::new("inference::chat_models");+/// A managed chat-model factory that is safe for inspection calls through+/// invoke/stream: it must use a frozen, read-only credential snapshot and+/// must not refresh or publish credential state.+pub type InspectionChatModelFactory = PreparedInspectionChatModelFactory;++/// An inspection-safe model and the resolved wire identity it invokes.+/// `credential` is retained only long enough for the core to build a+/// report-local deduplication key; it must never be logged or reported.+pub struct InspectionChatModelBuild {+ /// Frozen chat model that invokes the resolved route.+ pub model: Arc<dyn ChatModel<()>>,+ /// Safe provider model identifier selected for the route.+ pub model_id: String,+ /// Effective request endpoint used by the model.+ pub endpoint: String,+ /// Exact frozen bearer/key used by the model. Never expose in findings.+ pub credential: String,+}++/// Inspection-safe provider callback. Unlike the runtime callback this must+/// return the same frozen route identity used by the model invocation.+pub type PreparedInspectionChatModelFactory = Arc<+ dyn for<'a> Fn(&ChatModelRequest<'a>) -> anyhow::Result<InspectionChatModelBuild> + Send + Sync,+>;++static INSPECTION_CHAT_MODELS: HookSlot<InspectionChatModelFactory> =+ HookSlot::new("inference::inspection_chat_models");++/// Registers an inspection-safe managed model factory process-wide.+pub fn register_inspection_chat_model(+ provider_id: impl Into<String>,+ factory: PreparedInspectionChatModelFactory,+) {+ INSPECTION_CHAT_MODELS.register(provider_id, factory);+}++/// Registers an inspection-safe managed model factory for the context built+/// from `extensions`.+pub fn register_inspection_chat_model_in(+ extensions: &Extensions,+ provider_id: impl Into<String>,+ factory: PreparedInspectionChatModelFactory,+) {+ INSPECTION_CHAT_MODELS.register_in(extensions, provider_id, factory);+}++/// Removes the process-wide inspection-safe managed model factory.+pub fn unregister_inspection_chat_model(provider_id: &str) -> bool {+ INSPECTION_CHAT_MODELS.unregister(provider_id)+}++pub(crate) fn inspection_chat_model(+ provider_id: &str,+) -> Option<PreparedInspectionChatModelFactory> {+ INSPECTION_CHAT_MODELS.get(provider_id)+}+/// Registers the chat-model provider `provider_id` for the whole process.pub fn register_chat_model(provider_id: impl Into<String>, entry: ChatModelEntry) {CHAT_MODELS.register(provider_id, entry);@@ -143,6 +202,46 @@ pub type EmbeddingFactory = Arc<static EMBEDDINGS: HookSlot<EmbeddingFactory> = HookSlot::new("inference::embeddings");+/// A managed embedding factory safe for doctor inspection: it uses a frozen+/// credential snapshot and never refreshes or publishes credential state.+pub type InspectionEmbeddingFactory = EmbeddingFactory;++static INSPECTION_EMBEDDINGS: HookSlot<InspectionEmbeddingFactory> =+ HookSlot::new("inference::inspection-embeddings");++/// Registers a managed embedding factory for read-only credential inspection.+pub fn register_inspection_embedding<F>(provider_id: impl Into<String>, factory: F)+where+ F: for<'a> Fn(+ &EmbeddingRequest<'a>,+ ) -> tinyinference_embeddings::Result<Box<dyn EmbeddingModel>>+ + Send+ + Sync+ + 'static,+{+ INSPECTION_EMBEDDINGS.register(provider_id, Arc::new(factory));+}++/// Registers an inspection-safe embedding factory for one core context.+pub fn register_inspection_embedding_in<F>(+ extensions: &Extensions,+ provider_id: impl Into<String>,+ factory: F,+) where+ F: for<'a> Fn(+ &EmbeddingRequest<'a>,+ ) -> tinyinference_embeddings::Result<Box<dyn EmbeddingModel>>+ + Send+ + Sync+ + 'static,+{+ INSPECTION_EMBEDDINGS.register_in(extensions, provider_id, Arc::new(factory));+}++pub(crate) fn inspection_embedding(provider_id: &str) -> Option<InspectionEmbeddingFactory> {+ INSPECTION_EMBEDDINGS.get(provider_id)+}+/// Registers the embedding provider `provider_id` for the whole process.pub fn register_embedding<F>(provider_id: impl Into<String>, factory: F)where@@ -246,6 +345,117 @@ pub(crate) fn catalog(provider_id: &str) -> Option<CatalogEntry> {CATALOGS.get(provider_id)}+/// Safe outcomes from an inspection-only catalog request. Error response+/// bodies stay at the adapter boundary so Findings can never echo them.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InspectionCatalogError {+ /// The selected credential was rejected or lacks catalog access.+ AuthOrAccess,+ /// The provider does not expose a model-listing route.+ NoCatalog,+ /// The selected profile, endpoint, or read-only credential could not be+ /// inspected safely.+ Unavailable,+ /// The catalog request failed for another bounded, safe-to-summarize+ /// reason.+ Failure,+}++/// A catalog result is prepared before the doctor consults its cache. The+/// opaque identity captures the exact frozen credential and endpoint; the+/// lazy future captures those same values and is dropped on a cache hit.+///+/// Fields are intentionally private and this type does not implement+/// `Debug`, `Serialize`, or `Display`, so credential identities cannot leak+/// through reports or logs.+pub struct PreparedInspectionCatalog {+ identity: InspectionCatalogIdentity,+ fetch: BoxFuture<Result<Outcome<serde_json::Value>, InspectionCatalogError>>,+}++#[derive(Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) struct InspectionCatalogIdentity(u64);++impl PreparedInspectionCatalog {+ /// Creates a prepared request using a stable, process-keyed identity over+ /// the provider, effective listing URL, and credential snapshot. The+ /// fetch future must use the same credential snapshot passed here.+ pub fn new(+ provider_id: &str,+ effective_listing_url: &str,+ credential: Option<&str>,+ fetch: BoxFuture<Result<Outcome<serde_json::Value>, InspectionCatalogError>>,+ ) -> Self {+ let normalized_url = reqwest::Url::parse(effective_listing_url)+ .map(|url| url.to_string())+ .unwrap_or_else(|_| effective_listing_url.to_owned());+ let credential = credential+ .map(str::trim)+ .filter(|credential| !credential.is_empty());+ static IDENTITY_HASHER: OnceLock<RandomState> = OnceLock::new();+ let mut hasher = IDENTITY_HASHER.get_or_init(RandomState::new).build_hasher();+ provider_id.hash(&mut hasher);+ normalized_url.hash(&mut hasher);+ credential.hash(&mut hasher);+ Self {+ identity: InspectionCatalogIdentity(hasher.finish()),+ fetch,+ }+ }++ pub(crate) fn identity(&self) -> InspectionCatalogIdentity {+ self.identity+ }++ /// Runs the prepared request. Callers consult their cache before invoking+ /// this method; dropping the value leaves the network future unpolled.+ pub fn fetch(self) -> BoxFuture<Result<Outcome<serde_json::Value>, InspectionCatalogError>> {+ self.fetch+ }+}++/// An inspection-safe catalog preparer. It must read credentials without+/// refreshing, publishing expiry, or modifying profile state, then freeze the+/// credential into the returned request before the core checks its cache.+pub type InspectionCatalogListing = Arc<+ dyn Fn(+ Config,+ CatalogRequest,+ ) -> BoxFuture<Result<PreparedInspectionCatalog, InspectionCatalogError>>+ + Send+ + Sync,+>;++static INSPECTION_CATALOGS: HookSlot<InspectionCatalogListing> =+ HookSlot::new("inference::inspection_catalogs");++/// Registers an inspection-safe catalog preparer for the whole process.+pub fn register_inspection_catalog(+ provider_id: impl Into<String>,+ listing: InspectionCatalogListing,+) {+ INSPECTION_CATALOGS.register(provider_id, listing);+}++/// Registers an inspection-safe catalog preparer for a context built from+/// `extensions`.+pub fn register_inspection_catalog_in(+ extensions: &Extensions,+ provider_id: impl Into<String>,+ listing: InspectionCatalogListing,+) {+ INSPECTION_CATALOGS.register_in(extensions, provider_id, listing);+}++/// Removes a process-wide inspection-safe catalog preparer.+pub fn unregister_inspection_catalog(provider_id: &str) -> bool {+ INSPECTION_CATALOGS.unregister(provider_id)+}++pub(crate) fn inspection_catalog(provider_id: &str) -> Option<InspectionCatalogListing> {+ INSPECTION_CATALOGS.get(provider_id)+}+#[cfg(test)]#[path = "registry_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/integrations/prelude_integrations.rs b/crates/openhuman-core/src/integrations/prelude_integrations.rsindex 433d4c2f08..0151faf9bb 100644--- a/crates/openhuman-core/src/integrations/prelude_integrations.rs+++ b/crates/openhuman-core/src/integrations/prelude_integrations.rs@@ -5,7 +5,7 @@use std::sync::Arc;-use tinyagents_runtime::ToolSnapshot;+use tinyagents_harness::tool::ToolSnapshot;use super::OpenHumanTurnPrelude;diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rsindex 46f08c30eb..d2ad17c81d 100644--- a/crates/openhuman-core/src/lib.rs+++ b/crates/openhuman-core/src/lib.rs@@ -10,7 +10,7 @@//! below in the order they are declared (module declarations are kept//! alphabetical, with the `rpc` re-export sitting between `platform` and//! `runtime` — keep new modules sorted the same way): `agent`, `agent_registry`, `api`, `artifacts`, `attachments`,-//! `channels`, `config`, `core`, `cron`, `desktop`, `flows` (feature+//! `channels`, `config`, `core`, `cron`, `desktop`, `doctor`, `flows` (feature//! `flows`), `hooks`, `hosting` (feature `hosting`),//! `inference`, `integrations`,//! `mcp`, `media` (feature `media`), `memory`, `modules` (feature@@ -63,6 +63,7 @@ pub mod config;pub mod core;pub mod cron;pub mod desktop;+pub mod doctor;#[cfg(feature = "flows")]pub mod flows;pub mod hooks;@@ -107,7 +108,9 @@ pub use config::DaemonConfig;/// the Tauri shell, a CLI, a stdio MCP server, or a cloud/team server — via/// [`CoreBuilder`] → [`CoreRuntime`]. See `crates/openhuman-embed/README.md`/// and [`crate::core::runtime`] for the composition this builds on.-pub use core::runtime::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};+pub use core::runtime::{+ CoreBootMode, CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource,+};pub use core::types::HostKind;/// Runs the core logic based on the provided command-line arguments.diff --git a/crates/openhuman-core/src/mcp/module_client.rs b/crates/openhuman-core/src/mcp/module_client.rsindex 3c4a7b1b1e..0ed89824d0 100644--- a/crates/openhuman-core/src/mcp/module_client.rs+++ b/crates/openhuman-core/src/mcp/module_client.rs@@ -66,6 +66,20 @@ pub(crate) trait McpModulePort: Send + Sync {confidential: bool,) -> Result<Value, ModuleCallError>;+ /// Calls a child object through an already-pinned module owner.+ /// Implementations must not resolve, load, or pin a module when no owner is+ /// already available.+ async fn call_object_if_ready(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ let _ = (object_path, member, args, confidential);+ Err(ModuleCallError::Unavailable)+ }+async fn prepare_agent_tools(&self,request: PrepareAgentToolsRequest,diff --git a/crates/openhuman-core/src/mcp/module_client/lifecycle.rs b/crates/openhuman-core/src/mcp/module_client/lifecycle.rsindex a8c7ffa0e0..1c422d24ab 100644--- a/crates/openhuman-core/src/mcp/module_client/lifecycle.rs+++ b/crates/openhuman-core/src/mcp/module_client/lifecycle.rs@@ -51,6 +51,54 @@ impl McpConfiguredClient {table().snapshot()}+ /// Observes an already-open MCP client for this exact workspace and+ /// configuration. This path never creates a client or drives its+ /// lifecycle, so an absent or stale runtime is reported as `None`.+ pub(crate) async fn existing_status_for_config(+ config: &Config,+ ) -> Result<Option<Vec<tinymcp_bus::ConnStatus>>, ModuleCallError> {+ let data_dir = crate::core::runtime::agent_scope_dir(config);+ let key = client_key(&data_dir);+ let Some(client) = table()+ .snapshot()+ .into_iter()+ .find(|(candidate, _)| candidate == &key)+ .map(|(_, client)| client)+ else {+ return Ok(None);+ };+ client+ .existing_status_if_open(&super::super::host::client_config(config))+ .await+ }++ async fn existing_status_if_open(+ &self,+ selected_config: &McpClientConfig,+ ) -> Result<Option<Vec<tinymcp_bus::ConnStatus>>, ModuleCallError> {+ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {+ return Err(ModuleCallError::Unavailable);+ }+ let state = self.state.lock().await;+ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {+ return Err(ModuleCallError::Unavailable);+ }+ let Some(object) = state.open_object() else {+ return Ok(None);+ };+ if object.config != *selected_config {+ return Ok(None);+ }+ let args = serde_json::to_value(()).map_err(|_| ModuleCallError::ModuleFault)?;+ let reply = self+ .port+ .call_object_if_ready(&object.object_path, names::methods::STATUS, args, false)+ .await?;+ serde_json::from_value(reply)+ .map(Some)+ .map_err(|_| ModuleCallError::ModuleFault)+ }+/// Drain observations from the module-owned supervisor for an open child./// An object that is opening or closing is skipped and will be revisited/// on the next host poll.diff --git a/crates/openhuman-core/src/mcp/module_client/lifecycle_gate_tests.rs b/crates/openhuman-core/src/mcp/module_client/lifecycle_gate_tests.rsnew file mode 100644index 0000000000..f94748ffce--- /dev/null+++ b/crates/openhuman-core/src/mcp/module_client/lifecycle_gate_tests.rs@@ -0,0 +1,81 @@+use super::*;++/// A port that models TinyMCP's module-wide lifecycle gate: a second+/// `open_configured` while another workspace's transition is still pending is+/// refused instead of queued.+#[derive(Clone, Default)]+struct SingleTransitionPort {+ pending: Arc<std::sync::atomic::AtomicBool>,+}++#[async_trait]+impl McpModulePort for SingleTransitionPort {+ async fn open_configured(+ &self,+ data_dir: &str,+ _config: &McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {+ if self.pending.swap(true, std::sync::atomic::Ordering::SeqCst) {+ return Err(ModuleCallError::ModuleFault);+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ Ok(OpenConfiguredResponse {+ object_path: format!("/workspace{data_dir}"),+ transition_id: "open".to_owned(),+ })+ }++ async fn close(&self, _data_dir: &str) -> Result<Option<String>, ModuleCallError> {+ Ok(None)+ }++ async fn transition_status(+ &self,+ _transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ tokio::time::sleep(Duration::from_millis(5)).await;+ self.pending+ .store(false, std::sync::atomic::Ordering::SeqCst);+ Ok(TransitionStatus::Complete)+ }++ async fn call_object(+ &self,+ _object_path: &str,+ _member: &str,+ _args: Value,+ _confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ Ok(Value::Bool(true))+ }++ async fn prepare_agent_tools(+ &self,+ _request: PrepareAgentToolsRequest,+ ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {+ Ok(Vec::new())+ }++ async fn validate_server_arguments(+ &self,+ _request: ValidateServerArgumentsRequest,+ ) -> Result<ServerArgumentsValidation, ModuleCallError> {+ Err(ModuleCallError::IncompatibleContract)+ }+}++#[tokio::test]+async fn concurrent_workspaces_open_one_at_a_time_through_the_module_lifecycle_gate() {+ let port = SingleTransitionPort::default();+ let first = McpConfiguredClient::with_port("/private/a".to_owned(), Box::new(port.clone()));+ let second = McpConfiguredClient::with_port("/private/b".to_owned(), Box::new(port));+ let config = configured("server");++ let (a, b) = tokio::join!(+ first.call::<bool>(&config, "ConnectedOverview", ()),+ second.call::<bool>(&config, "ConnectedOverview", ()),+ );++ assert!(a.expect("first workspace opens"));+ assert!(b.expect("second workspace opens"));+}diff --git a/crates/openhuman-core/src/mcp/module_client_tests.rs b/crates/openhuman-core/src/mcp/module_client_tests.rsindex 94b58d88f9..0a97144bfb 100644--- a/crates/openhuman-core/src/mcp/module_client_tests.rs+++ b/crates/openhuman-core/src/mcp/module_client_tests.rs@@ -12,6 +12,8 @@ struct FakePort {prepared_requests: Arc<Mutex<Vec<PrepareAgentToolsRequest>>>,validation_requests: Arc<Mutex<Vec<ValidateServerArgumentsRequest>>>,transform_requests: Arc<Mutex<Vec<tinymcp_bus::TransformTextRequest>>>,+ statuses: Arc<Mutex<Vec<tinymcp_bus::ConnStatus>>>,+ fail_status: Arc<std::sync::atomic::AtomicBool>,open_started: Arc<Notify>,close_started: Arc<Notify>,release_close: Arc<Notify>,@@ -132,9 +134,30 @@ impl McpModulePort for FakePort {}]).map_err(|_| ModuleCallError::ModuleFault);}+ if member == names::methods::STATUS {+ if self+ .fail_status+ .swap(false, std::sync::atomic::Ordering::SeqCst)+ {+ return Err(ModuleCallError::TransportFailed);+ }+ return serde_json::to_value(self.statuses.lock().unwrap().clone())+ .map_err(|_| ModuleCallError::ModuleFault);+ }Ok(Value::Bool(true))}+ async fn call_object_if_ready(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ self.call_object(object_path, member, args, confidential)+ .await+ }+async fn prepare_agent_tools(&self,request: PrepareAgentToolsRequest,@@ -305,6 +328,142 @@ async fn static_server_summaries_use_the_confidential_module_member() {assert!(calls[0].3, "server metadata must use confidential delivery");}+#[tokio::test]+async fn doctor_status_reads_only_an_open_client_for_the_exact_config() {+ let scratch = tempfile::tempdir().expect("create isolated client workspace");+ let mut host_config = Config::default();+ host_config.workspace_dir = scratch.path().to_path_buf();+ let client_config = crate::mcp::host::client_config(&host_config);+ let port = FakePort::default();+ let opened = Arc::clone(&port.opened);+ let calls = Arc::clone(&port.calls);+ let expected = tinymcp_bus::ConnStatus {+ server_id: "docs".to_owned(),+ qualified_name: "example/docs".to_owned(),+ display_name: "Docs".to_owned(),+ status: tinymcp_bus::ServerStatus::Error,+ tool_count: 0,+ last_error: Some("private response body".to_owned()),+ auth_hint: None,+ };+ port.statuses.lock().unwrap().push(expected.clone());+ let client = McpConfiguredClient::install_test_port(&host_config, Box::new(port))+ .expect("install the test client without opening its module");+ let mut state = ConfiguredLifecycle::new();+ state.open_step(&client_config);+ state.open_replied(Ok(OpenConfiguredResponse {+ object_path: "/workspace/open".to_owned(),+ transition_id: "fixture-open".to_owned(),+ }));+ state.open_polled(TransitionStatus::Complete);+ *client.state.lock().await = state;++ let statuses = McpConfiguredClient::existing_status_for_config(&host_config)+ .await+ .expect("status call succeeds")+ .expect("the exact client is already open");++ assert_eq!(statuses, vec![expected]);+ assert!(+ opened.lock().unwrap().is_empty(),+ "doctor must not reopen MCP"+ );+ let calls = calls.lock().unwrap();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].1, names::methods::STATUS);+ assert!(+ !calls[0].3,+ "status contains no credentials and is read-only"+ );+}++#[tokio::test]+async fn doctor_status_skips_mismatched_retiring_and_absent_clients_without_opening() {+ let scratch = tempfile::tempdir().expect("create isolated client workspace");+ let mut selected = Config::default();+ selected.workspace_dir = scratch.path().to_path_buf();+ selected.mcp_client.servers.push(+ tinymcp_bus::McpServerConfig {+ name: "selected-b".into(),+ ..Default::default()+ }+ .into(),+ );+ let mut stale = selected.clone();+ stale.mcp_client.servers[0].name = "ambient-a".into();+ let port = FakePort::default();+ let opened = Arc::clone(&port.opened);+ let calls = Arc::clone(&port.calls);+ let client = McpConfiguredClient::install_test_port(&selected, Box::new(port.clone()))+ .expect("install the selected workspace client");+ let mut state = ConfiguredLifecycle::new();+ state.open_step(&crate::mcp::host::client_config(&stale));+ state.open_replied(Ok(OpenConfiguredResponse {+ object_path: "/workspace/ambient-a".to_owned(),+ transition_id: "fixture-open".to_owned(),+ }));+ state.open_polled(TransitionStatus::Complete);+ *client.state.lock().await = state;++ assert!(McpConfiguredClient::existing_status_for_config(&selected)+ .await+ .expect("stale configuration is not a transport error")+ .is_none());+ assert!(calls.lock().unwrap().is_empty());++ client.retiring.store(true, Ordering::Release);+ assert_eq!(+ McpConfiguredClient::existing_status_for_config(&selected).await,+ Err(ModuleCallError::Unavailable)+ );+ assert!(calls.lock().unwrap().is_empty());+ assert!(opened.lock().unwrap().is_empty());++ let absent_root = tempfile::tempdir().expect("create absent-client workspace");+ let mut absent = Config::default();+ absent.workspace_dir = absent_root.path().to_path_buf();+ assert!(McpConfiguredClient::existing_status_for_config(&absent)+ .await+ .expect("absent client is a safe unavailable result")+ .is_none());+ let absent_key = lifecycle::client_key(absent_root.path());+ assert!(McpConfiguredClient::open_clients()+ .iter()+ .all(|(path, _)| path != &absent_key));+}++#[tokio::test]+async fn existing_status_preserves_read_failures_without_reopening_the_client() {+ let scratch = tempfile::tempdir().expect("create isolated client workspace");+ let mut config = Config::default();+ config.workspace_dir = scratch.path().to_path_buf();+ let client_config = crate::mcp::host::client_config(&config);+ let port = FakePort::default();+ port.fail_status+ .store(true, std::sync::atomic::Ordering::SeqCst);+ let opened = Arc::clone(&port.opened);+ let calls = Arc::clone(&port.calls);+ let client = McpConfiguredClient::install_test_port(&config, Box::new(port))+ .expect("install fake existing client");+ let mut state = ConfiguredLifecycle::new();+ state.open_step(&client_config);+ state.open_replied(Ok(OpenConfiguredResponse {+ object_path: "/workspace/open".to_owned(),+ transition_id: "fixture-open".to_owned(),+ }));+ state.open_polled(TransitionStatus::Complete);+ *client.state.lock().await = state;++ assert_eq!(+ McpConfiguredClient::existing_status_for_config(&config).await,+ Err(ModuleCallError::TransportFailed)+ );+ assert!(opened.lock().unwrap().is_empty());+ let calls = calls.lock().unwrap();+ assert_eq!(calls.len(), 1);+ assert_eq!(calls[0].1, names::methods::STATUS);+}+#[tokio::test]async fn supervisor_drain_only_uses_an_open_object_and_keeps_the_bounded_limit() {let port = FakePort::default();@@ -533,85 +692,8 @@ async fn non_utf8_workspace_paths_are_rejected_before_opening() {#[path = "module_client/cleanup_tests.rs"]mod cleanup_tests;-/// A port that models TinyMCP's module-wide lifecycle gate: a second-/// `open_configured` while another workspace's transition is still pending is-/// refused instead of queued.-#[derive(Clone, Default)]-struct SingleTransitionPort {- pending: Arc<std::sync::atomic::AtomicBool>,-}--#[async_trait]-impl McpModulePort for SingleTransitionPort {- async fn open_configured(- &self,- data_dir: &str,- _config: &McpClientConfig,- ) -> Result<OpenConfiguredResponse, ModuleCallError> {- if self.pending.swap(true, std::sync::atomic::Ordering::SeqCst) {- return Err(ModuleCallError::ModuleFault);- }- tokio::time::sleep(Duration::from_millis(5)).await;- Ok(OpenConfiguredResponse {- object_path: format!("/workspace{data_dir}"),- transition_id: "open".to_owned(),- })- }-- async fn close(&self, _data_dir: &str) -> Result<Option<String>, ModuleCallError> {- Ok(None)- }-- async fn transition_status(- &self,- _transition_id: &str,- ) -> Result<TransitionStatus, ModuleCallError> {- tokio::time::sleep(Duration::from_millis(5)).await;- self.pending- .store(false, std::sync::atomic::Ordering::SeqCst);- Ok(TransitionStatus::Complete)- }-- async fn call_object(- &self,- _object_path: &str,- _member: &str,- _args: Value,- _confidential: bool,- ) -> Result<Value, ModuleCallError> {- Ok(Value::Bool(true))- }-- async fn prepare_agent_tools(- &self,- _request: PrepareAgentToolsRequest,- ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {- Ok(Vec::new())- }-- async fn validate_server_arguments(- &self,- _request: ValidateServerArgumentsRequest,- ) -> Result<ServerArgumentsValidation, ModuleCallError> {- Err(ModuleCallError::IncompatibleContract)- }-}--#[tokio::test]-async fn concurrent_workspaces_open_one_at_a_time_through_the_module_lifecycle_gate() {- let port = SingleTransitionPort::default();- let first = McpConfiguredClient::with_port("/private/a".to_owned(), Box::new(port.clone()));- let second = McpConfiguredClient::with_port("/private/b".to_owned(), Box::new(port));- let config = configured("server");-- let (a, b) = tokio::join!(- first.call::<bool>(&config, "ConnectedOverview", ()),- second.call::<bool>(&config, "ConnectedOverview", ()),- );-- assert!(a.expect("first workspace opens"));- assert!(b.expect("second workspace opens"));-}+#[path = "module_client/lifecycle_gate_tests.rs"]+mod lifecycle_gate_tests;#[path = "module_client_cleanup_tests.rs"]mod captured_cleanup_tests;diff --git a/crates/openhuman-core/src/mcp/module_port.rs b/crates/openhuman-core/src/mcp/module_port.rsindex 6a5201774d..d48d0cc079 100644--- a/crates/openhuman-core/src/mcp/module_port.rs+++ b/crates/openhuman-core/src/mcp/module_port.rs@@ -129,6 +129,30 @@ impl McpModulePort for TinyMcpPort {}}+ async fn call_object_if_ready(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ #[cfg(feature = "modules")]+ {+ let owner = self.pinned.get().ok_or(ModuleCallError::Unavailable)?;+ let object = owner.object_at(object_path)?;+ if confidential {+ object.call_confidential(member, args).await+ } else {+ object.call(member, args).await+ }+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = (object_path, member, args, confidential);+ Err(ModuleCallError::Unavailable)+ }+ }+async fn prepare_agent_tools(&self,request: PrepareAgentToolsRequest,@@ -161,3 +185,7 @@ impl McpModulePort for TinyMcpPort {.await}}++#[cfg(test)]+#[path = "module_port_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/module_port_tests.rs b/crates/openhuman-core/src/mcp/module_port_tests.rsnew file mode 100644index 0000000000..5965b84126--- /dev/null+++ b/crates/openhuman-core/src/mcp/module_port_tests.rs@@ -0,0 +1,23 @@+use super::*;+use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection};++#[tokio::test]+async fn ready_only_child_call_does_not_pin_or_load_an_unopened_module() {+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let caller = Connection::connect(bus.connect().await.expect("connect memory bus"))+ .await+ .expect("create memory-bus client");+ let root = crate::modules::ops::fixture_client(+ caller+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)+ .expect("create inert test proxy"),+ );+ let port = TinyMcpPort::new(root);++ let result = port+ .call_object_if_ready("/test/child", names::methods::STATUS, Value::Null, false)+ .await;++ assert_eq!(result, Err(ModuleCallError::Unavailable));+}diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rsindex 857e528445..be089f8cf2 100644--- a/crates/openhuman-core/src/memory/engine.rs+++ b/crates/openhuman-core/src/memory/engine.rs@@ -39,8 +39,8 @@ use std::sync::RwLock;use std::sync::{Arc, LazyLock};use sha2::{Digest, Sha256};-pub use tinymemory_api::Error as MemoryError;-use tinymemory_api::MemoryEngine;+pub use tinymemory_api::EngineHealth;+use tinymemory_api::{Error, MemoryEngine, Result};pub use tinymemory_integrations::cortex::CallbackBearerSource;pub use tinymemory_integrations::{BearerSource, Binding, BoundEngine, EngineBinder, EngineCredential, EngineSettings,@@ -50,7 +50,9 @@ use crate::config::schema::MEMORY_CORTEXDB_KEY_NAME;use crate::config::Config;use crate::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};-use tinymemory_api::{Error, Result};+use super::engine_registry::ReadOnlyEngineError;+pub use super::error::MemoryError;+use super::error::MemoryResult;/// Engine id of CortexDB behind the TinyHumans backend.pub use tinymemory_integrations::cortex::TINYHUMANS_ENGINE_ID as TINYHUMANS_ENGINE;@@ -71,6 +73,18 @@ static ENGINE_BINDER: LazyLock<EngineBinder> = LazyLock::new(EngineBinder::defaustatic TEST_ENGINES: LazyLock<RwLock<HashMap<std::path::PathBuf, Arc<dyn MemoryEngine>>>> =LazyLock::new(|| RwLock::new(HashMap::new()));+/// Test-only fixture lookup for native doctor probes; unlike [`resolve`],+/// this never falls through to ambient profile state or configured builders.+#[cfg(test)]+pub(crate) async fn doctor_test_health(config: &Config) -> Option<tinymemory_api::EngineHealth> {+ let engine = TEST_ENGINES+ .read()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .get(&config.workspace_dir)+ .cloned()?;+ Some(engine.health().await)+}+/// Binds `engine` for every config whose workspace is `workspace` (tests only).#[cfg(test)]pub(crate) fn install_test_engine(workspace: &std::path::Path, engine: Arc<dyn MemoryEngine>) {@@ -201,6 +215,78 @@ pub fn resolve(config: &Config) -> Binding {resolve_configured(config, root.as_deref())}+/// Builds an uncached engine for an explicitly requested live doctor check.+/// Credential/profile reads use the read-only inspection seams; this never+/// enters the active hosted context, normal engine cache, or mutable resolver.+pub async fn resolve_read_only_for_inspection(+ config: &Config,+) -> std::result::Result<Arc<dyn MemoryEngine>, ReadOnlyEngineError> {+ if !config.components.memory {+ return Err(ReadOnlyEngineError::ComponentDisabled);+ }+ let engine_id = config.memory.engine.trim();+ if engine_id.is_empty() || engine_id.eq_ignore_ascii_case(DISABLED_ENGINE) {+ return Err(ReadOnlyEngineError::EngineDisabled);+ }++ if let Some(factory) = super::engine_registry::read_only_engine_factory(engine_id) {+ return factory(config.clone()).await.map(guard_read_only_engine);+ }++ if engine_id != CORTEXDB_ENGINE {+ return Err(ReadOnlyEngineError::UnsupportedEngine);+ }++ let key =+ AuthService::get_provider_bearer_token_read_only(config, MEMORY_CORTEXDB_KEY_NAME, None)+ .map_err(|_| ReadOnlyEngineError::CredentialsUnavailable)?+ .ok_or(ReadOnlyEngineError::CredentialsUnavailable)?;+ let endpoint = cortexdb_endpoint(config);+ let root = inspection_layout_root(config)?;+ let settings = EngineSettings {+ endpoint: Some(endpoint),+ observed_actor: config.memory.observed_actor,+ ..EngineSettings::default()+ };+ let (settings, _) = rooted(+ settings,+ root.as_deref(),+ false,+ config.memory.legacy_user_segment_read,+ );+ let engine = tinymemory_integrations::build_engine(+ CORTEXDB_ENGINE,+ &settings,+ EngineCredential::Static(key),+ )+ .map_err(|_| ReadOnlyEngineError::InvalidConfiguration)?;+ Ok(guard_read_only_engine(engine))+}++/// Apply the same native scrub and timing decorators used for configured+/// engines without inserting this one-off inspection engine into the cache.+fn guard_read_only_engine(engine: Arc<dyn MemoryEngine>) -> Arc<dyn MemoryEngine> {+ ENGINE_BINDER+ .bind_external(+ engine,+ "doctor://inspection",+ crate::security::scrub::host_policy(),+ )+ .engine+}++fn inspection_layout_root(+ config: &Config,+) -> std::result::Result<Option<String>, ReadOnlyEngineError> {+ if config.memory.layout == crate::config::MemoryLayoutMode::V3 {+ super::scope::user_root(config)+ .map(Some)+ .ok_or(ReadOnlyEngineError::CredentialsUnavailable)+ } else {+ Ok(None)+ }+}+/// The engine the layout migration needs, for an explicit layout whatever/// `[memory] layout` says: `None` the legacy tree, `Some("org:<id>")` the/// person's v3 subtree, with the actor `user:<id>` as its owner. Same endpoint,@@ -212,7 +298,7 @@ pub fn resolve(config: &Config) -> Binding {/// Memory is off for `config`, or an embedding host's (or a test's)/// installed engine is bound, which has one layout of its own and cannot be/// bound below a scope root.-pub fn bind_with_root(config: &Config, root: Option<&str>) -> Result<BoundEngine> {+pub fn bind_with_root(config: &Config, root: Option<&str>) -> MemoryResult<BoundEngine> {if !config.components.memory {return Err(MemoryError::Off(COMPONENT_OFF_REASON.to_string()));}@@ -236,8 +322,8 @@ pub fn bind_with_root(config: &Config, root: Option<&str>) -> Result<BoundEngine.contains_key(&config.workspace_dir);if one_engine {return match root {- None => resolve(config).engine(),- Some(_) => Err(Error::Engine(+ None => resolve(config).engine().map_err(MemoryError::from),+ Some(_) => Err(MemoryError::Engine("the installed test engine cannot be bound below a scope root".to_string(),)),};@@ -252,7 +338,9 @@ pub fn bind_with_root(config: &Config, root: Option<&str>) -> Result<BoundEngine)? {return Ok(bound);}- resolve_configured(config, root).engine()+ resolve_configured(config, root)+ .engine()+ .map_err(MemoryError::from)}/// Whether the process-wide host engine may be used: never in SaaS, where one@@ -348,10 +436,7 @@ fn off(engine: Option<&str>, endpoint: Option<String>, reason: &str) -> Binding}fn resolve_cortexdb(config: &Config, root: Option<&str>) -> Binding {- let configured = config.memory.endpoint_for(CORTEXDB_ENGINE);- let endpoint = configured- .clone()- .unwrap_or_else(|| tinymemory_integrations::cortex::CORTEX_API_ENDPOINT.to_string());+ let endpoint = cortexdb_endpoint(config);let key = match read_cortexdb_key(config) {Ok(Some(key)) => key,Ok(None) => {@@ -394,6 +479,13 @@ fn resolve_cortexdb(config: &Config, root: Option<&str>) -> Binding {)}+fn cortexdb_endpoint(config: &Config) -> String {+ config+ .memory+ .endpoint_for(CORTEXDB_ENGINE)+ .unwrap_or_else(|| tinymemory_integrations::cortex::CORTEX_API_ENDPOINT.to_string())+}+pub fn build_cached(id: &str,settings: EngineSettings,diff --git a/crates/openhuman-core/src/memory/engine_registry.rs b/crates/openhuman-core/src/memory/engine_registry.rsindex 8d4dd2af3d..6a42a43d47 100644--- a/crates/openhuman-core/src/memory/engine_registry.rs+++ b/crates/openhuman-core/src/memory/engine_registry.rs@@ -28,6 +28,37 @@ use super::engine::{Binding, BoundEngine};use crate::config::Config;use crate::core::slots::{Extensions, HookSlot};+/// Safe failures while constructing an uncached memory engine for doctor live+/// checks. These variants intentionally carry no provider response text.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ReadOnlyEngineError {+ ComponentDisabled,+ EngineDisabled,+ UnsupportedEngine,+ CredentialsUnavailable,+ EndpointUnavailable,+ InvalidConfiguration,+}++impl ReadOnlyEngineError {+ /// A safe operator-facing summary with no credential or provider detail.+ #[must_use]+ pub const fn safe_message(self) -> &'static str {+ match self {+ Self::ComponentDisabled => "Memory is disabled in the selected configuration.",+ Self::EngineDisabled => "Memory is turned off in the selected configuration.",+ Self::UnsupportedEngine => {+ "The selected memory engine is not available for inspection."+ }+ Self::CredentialsUnavailable => {+ "No usable credential is available for the selected memory engine."+ }+ Self::EndpointUnavailable => "The selected memory engine endpoint is unavailable.",+ Self::InvalidConfiguration => "The selected memory engine configuration is invalid.",+ }+ }+}+/// A boxed `Send` future.pub type EngineFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;@@ -46,6 +77,22 @@ pub type EngineBuilder = Arc<dyn for<'a> Fn(&EngineRequest<'a>) -> Binding + Sen/// Whether background memory work is free for the bound engine and config.pub type FreeBackground = Arc<dyn Fn(Config, BoundEngine) -> EngineFuture<bool> + Send + Sync>;+/// A read-only connectivity probe for the selected engine configuration.+/// Unlike [`EngineBuilder`], this hook must not consult ambient profile state,+/// mutate credential state, initialize storage, or cache the engine.+pub type ReadOnlyHealthProbe =+ Arc<dyn Fn(Config) -> EngineFuture<tinymemory_api::EngineHealth> + Send + Sync>;++/// Builds an uncached engine from the explicitly selected config using a+/// frozen, read-only credential snapshot. The returned engine may perform+/// operations requested by an opt-in live doctor check; its construction must+/// not consult ambient profile state or mutate credential/config stores.+pub type ReadOnlyEngineFactory = Arc<+ dyn Fn(Config) -> EngineFuture<Result<Arc<dyn MemoryEngine>, ReadOnlyEngineError>>+ + Send+ + Sync,+>;+/// A registered memory engine.#[derive(Clone)]pub struct EngineEntry {@@ -56,6 +103,10 @@ pub struct EngineEntry {}static ENGINES: HookSlot<EngineEntry> = HookSlot::new("memory::engines");+static READ_ONLY_HEALTH_PROBES: HookSlot<ReadOnlyHealthProbe> =+ HookSlot::new("memory::read-only-health-probes");+static READ_ONLY_ENGINE_FACTORIES: HookSlot<ReadOnlyEngineFactory> =+ HookSlot::new("memory::read-only-engine-factories");/// Registers the memory engine `engine_id` for the whole process.pub fn register_memory_engine(engine_id: impl Into<String>, entry: EngineEntry) {@@ -72,6 +123,37 @@ pub fn register_memory_engine_in(ENGINES.register_in(extensions, engine_id, entry);}+/// Registers a read-only health probe for a configured memory engine.+pub fn register_memory_health_probe(engine_id: impl Into<String>, probe: ReadOnlyHealthProbe) {+ READ_ONLY_HEALTH_PROBES.register(engine_id, probe);+}++/// Registers a read-only health probe for a context built from `extensions`.+pub fn register_memory_health_probe_in(+ extensions: &Extensions,+ engine_id: impl Into<String>,+ probe: ReadOnlyHealthProbe,+) {+ READ_ONLY_HEALTH_PROBES.register_in(extensions, engine_id, probe);+}++/// Registers a read-only, uncached engine constructor for the selected config.+pub fn register_read_only_engine_factory(+ engine_id: impl Into<String>,+ factory: ReadOnlyEngineFactory,+) {+ READ_ONLY_ENGINE_FACTORIES.register(engine_id, factory);+}++/// Registers a read-only, uncached engine constructor for one core context.+pub fn register_read_only_engine_factory_in(+ extensions: &Extensions,+ engine_id: impl Into<String>,+ factory: ReadOnlyEngineFactory,+) {+ READ_ONLY_ENGINE_FACTORIES.register_in(extensions, engine_id, factory);+}+/// Removes the process-wide memory engine `engine_id`.pub fn unregister_memory_engine(engine_id: &str) -> bool {ENGINES.unregister(engine_id)@@ -82,6 +164,15 @@ pub(crate) fn lookup(engine_id: &str) -> Option<EngineEntry> {ENGINES.get(engine_id)}+/// The read-only health probe for `engine_id`, if the current context has one.+pub(crate) fn read_only_health_probe(engine_id: &str) -> Option<ReadOnlyHealthProbe> {+ READ_ONLY_HEALTH_PROBES.get(engine_id)+}++pub(crate) fn read_only_engine_factory(engine_id: &str) -> Option<ReadOnlyEngineFactory> {+ READ_ONLY_ENGINE_FACTORIES.get(engine_id)+}+/// Wraps `engine` as a [`BoundEngine`] with the same write scrubbing every/// configured engine gets. A registered builder returns/// `Binding::On(bound_engine(..))`.diff --git a/crates/openhuman-core/src/memory/engine_tests.rs b/crates/openhuman-core/src/memory/engine_tests.rsindex 4c01a4f6e7..3fd93e0557 100644--- a/crates/openhuman-core/src/memory/engine_tests.rs+++ b/crates/openhuman-core/src/memory/engine_tests.rs@@ -66,6 +66,40 @@ async fn assert_host_scrubbing();}+#[tokio::test]+async fn read_only_inspection_engines_use_the_native_host_scrub_policy() {+ let reference = Arc::new(tinymemory_api::conformance::ReferenceEngine::new());+ let guarded = guard_read_only_engine(reference.clone());+ let bound = BoundEngine {+ id: reference.descriptor().id.to_string(),+ endpoint: "doctor://inspection".to_owned(),+ engine: guarded,+ };++ assert_host_scrubbing(bound, &reference).await;+}++#[test]+fn read_only_inspection_uses_the_current_v3_user_root_only_for_v3_layout() {+ let mut config = crate::config::Config::default();+ config.config_path =+ "/home/operator/.openhuman/users/6512ab0f6512ab0f6512ab0f/config.toml".into();++ assert_eq!(inspection_layout_root(&config).unwrap(), None);++ config.memory.layout = crate::config::MemoryLayoutMode::V3;+ assert_eq!(+ inspection_layout_root(&config).unwrap().as_deref(),+ Some("org:6512ab0f6512ab0f6512ab0f")+ );++ config.config_path = "/home/operator/.openhuman/config.toml".into();+ assert_eq!(+ inspection_layout_root(&config),+ Err(ReadOnlyEngineError::CredentialsUnavailable)+ );+}+#[tokio::test]async fn installed_host_engine_binding_uses_the_host_scrub_policy() {const CHILD_FLAG: &str = "OPENHUMAN_MEMORY_HOST_POLICY_CHILD";@@ -507,7 +541,10 @@ fn a_disabled_memory_component_binds_no_engine() {assert!(off_reason(resolve(&config)).contains("components"));assert!(!is_on(&config));assert!(switched_off(&config));- assert!(matches!(bind_with_root(&config, None), Err(Error::Off(_))));+ assert!(matches!(+ bind_with_root(&config, None),+ Err(MemoryError::Off(_))+ ));}#[test]diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rsindex 5cda1cac79..5e3ed848c5 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs@@ -14,6 +14,7 @@ use super::state::StateKvMigrationStore;use crate::config::{Config, MemoryLayoutMode};use crate::memory::engine::{self, CORTEXDB_ENGINE};use crate::memory::scope;+use crate::memory::MemoryError;use tinymemory_api::{Error, Result};/// The app's [`lm::LayoutHost`], bound to one account's config.@@ -73,8 +74,8 @@ impl lm::LayoutHost for AppHost {let bind = || -> Result<Engines> {let root = signed_in_root(config)?;Ok(Engines {- legacy: engine::bind_with_root(config, None)?.engine,- tree: engine::bind_with_root(config, Some(&root))?.engine,+ legacy: bind_engine(config, None)?.engine,+ tree: bind_engine(config, Some(&root))?.engine,})};bind().map_err(to_module)@@ -144,7 +145,7 @@ pub(super) fn claim(config: &Config) -> Result<Option<FsLegacyClaim>> {.and_then(std::path::Path::parent).and_then(std::path::Path::parent).ok_or_else(signed_out)?;- let endpoint = engine::bind_with_root(config, None)?.endpoint;+ let endpoint = bind_engine(config, None)?.endpoint;Ok(Some(FsLegacyClaim::new(app_dir, &endpoint, &owner)))}@@ -156,6 +157,26 @@ fn signed_out() -> Error {Error::Off("sign in to move memory into its own layout".to_string())}+fn bind_engine(config: &Config, root: Option<&str>) -> Result<engine::BoundEngine> {+ engine::bind_with_root(config, root).map_err(memory_error_to_engine)+}++fn memory_error_to_engine(error: MemoryError) -> Error {+ match error {+ MemoryError::Off(message) => Error::Off(message),+ MemoryError::Unsupported(message) => Error::Unsupported(message),+ MemoryError::InvalidRequest(message) => Error::InvalidRequest(message),+ MemoryError::Unauthorized(message) => Error::Unauthorized(message),+ MemoryError::InsufficientCredits(message) => Error::InsufficientCredits(message),+ // TinyMemory has no plan-specific API variant. Preserve the stable+ // marker so the host can recover OpenHuman's PLAN_REQUIRED category.+ MemoryError::PlanRequired(message) => Error::Engine(message),+ MemoryError::Unavailable(message) => Error::Unavailable(message),+ MemoryError::Engine(message) => Error::Engine(message),+ MemoryError::ConfigConflict(error) => Error::Conflict(error.message),+ }+}+#[cfg(test)]#[path = "app_host_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rsindex 36724271af..39d4d61011 100644--- a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs@@ -13,6 +13,28 @@ use tinymemory_tools::layout_migration::{const ACCOUNT: &str = "0123456789abcdef01234567";+#[test]+fn memory_bind_errors_keep_their_engine_categories_at_the_migration_boundary() {+ assert_eq!(+ memory_error_to_engine(crate::memory::MemoryError::Off("memory is disabled".into())),+ tinymemory_api::Error::Off("memory is disabled".into())+ );+ assert_eq!(+ memory_error_to_engine(crate::memory::MemoryError::Unavailable("offline".into())),+ tinymemory_api::Error::Unavailable("offline".into())+ );+ assert_eq!(+ memory_error_to_engine(crate::memory::MemoryError::ConfigConflict(+ crate::core::StructuredRpcError {+ message: "configuration changed".into(),+ data: None,+ expected_user_state: true,+ }+ )),+ tinymemory_api::Error::Conflict("configuration changed".into())+ );+}+/// A config that lives where a signed-in account's does.fn signed_in(tmp: &tempfile::TempDir) -> Config {let mut config = crate::memory::test_fixtures::config_in(tmp);@@ -196,6 +218,14 @@ fn errors_keep_their_wire_codes_across_the_module_boundary() {let back = from_module(to_module(credit_error));assert!(matches!(back, Error::InsufficientCredits(_)));assert!(back.is_account_wide());++ let plan_error = crate::memory::MemoryError::PlanRequired(+ "[MEMORY_PLAN_REQUIRED] memory API memory/scopes (HTTP 403)".into(),+ );+ let module_error = to_module(memory_error_to_engine(plan_error));+ let back = crate::memory::MemoryError::from(from_module(module_error));+ assert_eq!(back.code(), crate::memory::error::PLAN_REQUIRED);+ assert!(back.is_account_wide());}#[test]diff --git a/crates/openhuman-core/src/modules/channel_health.rs b/crates/openhuman-core/src/modules/channel_health.rsindex 9668cb08ca..686af9aa41 100644--- a/crates/openhuman-core/src/modules/channel_health.rs+++ b/crates/openhuman-core/src/modules/channel_health.rs@@ -1,7 +1,16 @@-//! Thin confidential adapter for TinyChannels' provider health checks.+//! Confidential, existing-module-only adapter for TinyChannels health checks.+use std::time::Duration;+use tinybus::module::{ModuleCallError, ModuleClient};use tinychannels_bus::{ChannelHealthReport, ChannelsConfig, HttpProxyPolicy};+/// A safe failure class for one already-serving TinyChannels health probe.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ExistingHealthError {+ Unavailable,+ Failed,+}+pub(crate) async fn check(client: &ModuleClient,config: ChannelsConfig,@@ -16,6 +25,72 @@ pub(crate) async fn check(.await}+/// Ask an already-serving TinyChannels module to inspect the supplied config.+///+/// This path never constructs a `ModuleClient`, resolves an artifact, starts+/// the module runtime, or opens a provider listener. The selected provider+/// configuration and proxy policy are passed in the confidential health-call+/// arguments, so a module first loaded under another config cannot substitute+/// its ambient provider credentials.+pub(crate) async fn check_existing(+ config: &crate::config::Config,+ channels: ChannelsConfig,+ proxy_policy: HttpProxyPolicy,+ timeout: Duration,+) -> Result<Option<Vec<ChannelHealthReport>>, ExistingHealthError> {+ #[cfg(feature = "modules")]+ {+ use crate::modules::types::ModuleState;++ if !config.modules.enabled+ || crate::modules::ops::state_of("tinychannels") != ModuleState::Ready+ {+ return Ok(None);+ }+ let Some(runtime) = crate::modules::runtime::existing_runtime() else {+ return Ok(None);+ };+ let Some(record) = crate::modules::registry::find("tinychannels") else {+ return Err(ExistingHealthError::Unavailable);+ };+ let proxy = runtime+ .proxy(record.bus_name, record.object_path)+ .map_err(|_| ExistingHealthError::Unavailable)?+ .with_timeout(timeout);+ return call_existing_proxy(&proxy, channels, proxy_policy, timeout)+ .await+ .map(Some);+ }++ #[cfg(not(feature = "modules"))]+ {+ let _ = (config, channels, proxy_policy, timeout);+ Ok(None)+ }+}++async fn call_existing_proxy(+ proxy: &tinybus::Proxy,+ channels: ChannelsConfig,+ proxy_policy: HttpProxyPolicy,+ timeout: Duration,+) -> Result<Vec<ChannelHealthReport>, ExistingHealthError> {+ tokio::time::timeout(+ timeout,+ proxy.clone().with_timeout(timeout).call_confidential(+ tinychannels_bus::methods::CHECK_CHANNEL_HEALTH,+ (+ channels,+ proxy_policy,+ timeout.as_millis().min(u64::MAX as u128) as u64,+ ),+ ),+ )+ .await+ .map_err(|_| ExistingHealthError::Failed)?+ .map_err(|_| ExistingHealthError::Failed)+}+#[cfg(all(test, feature = "modules"))]#[path = "channel_health_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/modules/channel_health_tests.rs b/crates/openhuman-core/src/modules/channel_health_tests.rsindex 010ece0b42..0cde9b1752 100644--- a/crates/openhuman-core/src/modules/channel_health_tests.rs+++ b/crates/openhuman-core/src/modules/channel_health_tests.rs@@ -1,4 +1,183 @@use super::*;+use tinychannels_bus::ChannelHealthState;++#[cfg(feature = "modules")]+type ObservedHealth = (bool, Vec<String>, u64);++#[cfg(feature = "modules")]+#[derive(Clone)]+struct HealthResponseState {+ delay: std::time::Duration,+ fail: bool,+ observed: std::sync::Arc<std::sync::Mutex<Option<ObservedHealth>>>,+}++#[cfg(feature = "modules")]+#[derive(Clone)]+struct HealthResponder(HealthResponseState);++#[cfg(feature = "modules")]+#[async_trait::async_trait]+impl tinybus::service::Interface for HealthResponder {+ fn name(&self) -> tinybus::InterfaceName {+ tinybus::InterfaceName::new("test.ChannelHealth").unwrap()+ }++ fn members(&self) -> Vec<tinybus::MemberName> {+ vec![tinybus::MemberName::new("CheckChannelHealth").unwrap()]+ }++ async fn call(+ &self,+ member: &tinybus::MemberName,+ args: serde_json::Value,+ ) -> tinybus::Result<serde_json::Value> {+ if member.as_str() != "CheckChannelHealth" {+ return Err(tinybus::Error::failed("unknown fixture member"));+ }+ let selectors = args[1]["service_selectors"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(serde_json::Value::as_str)+ .map(str::to_owned)+ .collect();+ *self.0.observed.lock().unwrap() = Some((+ args[0]["telegram"].is_object(),+ selectors,+ args[2].as_u64().unwrap_or_default(),+ ));+ tokio::time::sleep(self.0.delay).await;+ if self.0.fail {+ return Err(tinybus::Error::failed("fixture secret must be discarded"));+ }+ serde_json::to_value(vec![ChannelHealthReport {+ channel: "telegram".into(),+ state: ChannelHealthState::Healthy,+ }])+ .map_err(|_| tinybus::Error::failed("fixture response encoding failed"))+ }+}++#[cfg(feature = "modules")]+async fn health_proxy(state: HealthResponseState) -> tinybus::Proxy {+ use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};++ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let service = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ service+ .serve_at(+ ObjectPath::new("/test/ChannelHealth").unwrap(),+ HealthResponder(state),+ )+ .await+ .unwrap();+ service.request_name("test.ChannelHealth").await.unwrap();+ caller+ .proxy(+ "test.ChannelHealth",+ "/test/ChannelHealth",+ "test.ChannelHealth",+ )+ .unwrap()+}++#[cfg(feature = "modules")]+fn health_inputs() -> (ChannelsConfig, HttpProxyPolicy) {+ (+ ChannelsConfig {+ telegram: Some(tinychannels_bus::config::TelegramConfig {+ bot_token: "selected-b-test-token".into(),+ chat_id: None,+ allowed_users: Vec::new(),+ stream_mode: Default::default(),+ draft_update_interval_ms: 1_000,+ silent_streaming: true,+ mention_only: false,+ }),+ ..Default::default()+ },+ HttpProxyPolicy {+ service_selectors: vec!["channel.telegram".into()],+ ..Default::default()+ },+ )+}++#[cfg(feature = "modules")]+#[tokio::test]+async fn existing_health_adapter_passes_only_the_selected_provider_and_policy() {+ let observed = std::sync::Arc::new(std::sync::Mutex::new(None));+ let proxy = health_proxy(HealthResponseState {+ delay: std::time::Duration::ZERO,+ fail: false,+ observed: observed.clone(),+ })+ .await;+ let (channels, policy) = health_inputs();++ let reports = call_existing_proxy(+ &proxy,+ channels,+ policy,+ std::time::Duration::from_millis(100),+ )+ .await+ .expect("existing read-only member returns its health report");++ assert_eq!(reports[0].channel, "telegram");+ assert_eq!(reports[0].state, ChannelHealthState::Healthy);+ assert_eq!(+ observed.lock().unwrap().as_ref().unwrap(),+ &(true, vec!["channel.telegram".into()], 100)+ );+}++#[cfg(feature = "modules")]+#[tokio::test]+async fn existing_health_adapter_sanitizes_failure_and_bounds_timeout() {+ let observed = std::sync::Arc::new(std::sync::Mutex::new(None));+ let proxy = health_proxy(HealthResponseState {+ delay: std::time::Duration::from_millis(100),+ fail: false,+ observed: observed.clone(),+ })+ .await;+ let (channels, policy) = health_inputs();+ let failure = call_existing_proxy(+ &proxy,+ channels,+ policy,+ std::time::Duration::from_millis(10),+ )+ .await+ .expect_err("late provider must time out");+ assert_eq!(failure, ExistingHealthError::Failed);++ let failing_proxy = health_proxy(HealthResponseState {+ delay: std::time::Duration::ZERO,+ fail: true,+ observed: std::sync::Arc::new(std::sync::Mutex::new(None)),+ })+ .await;+ let (channels, policy) = health_inputs();+ let failure = call_existing_proxy(+ &failing_proxy,+ channels,+ policy,+ std::time::Duration::from_millis(100),+ )+ .await+ .expect_err("module error is reduced to a safe failure class");+ assert_eq!(failure, ExistingHealthError::Failed);+ assert_ne!(format!("{failure:?}"), "fixture secret must be discarded");+}#[cfg(feature = "modules")]#[tokio::test]diff --git a/crates/openhuman-core/src/modules/connectors.rs b/crates/openhuman-core/src/modules/connectors.rsindex ca8eb9f9ec..a0dc9489fe 100644--- a/crates/openhuman-core/src/modules/connectors.rs+++ b/crates/openhuman-core/src/modules/connectors.rs@@ -68,6 +68,19 @@ pub type ProxyTargetResolver = Arc<dyn Fn(&Config) -> Result<ProxyTarget, Stringstatic MODULE_PROXY_TARGETS: HookSlot<ProxyTargetResolver> =HookSlot::new("modules::connectors::proxy_targets");+#[path = "connectors/inspection.rs"]+mod inspection;++pub(crate) use inspection::{call_existing_readonly, ExistingCallError};++pub(crate) fn note_module_config_for_load(config: &Config, module_config: &serde_json::Value) {+ inspection::note_module_config_for_load(config, module_config);+}++pub(crate) fn note_load_resolution_ready() {+ inspection::note_load_resolution_ready();+}+/// Registers `resolve` as the proxy target for `mode` (`"backend"` is the one/// mode the proxy route serves). Nothing registered => the mode has no route.pub fn register_proxy_target<F>(mode: impl Into<String>, resolve: F)@@ -307,6 +320,7 @@ static ROUTE_TURN: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());/// user's session no longer owns, and "your account is broken" is a bad way to/// tell someone they are signed out.async fn ensure_routed(config: &Config, proxy: &Proxy) -> Result<(), String> {+ let _inspection_guard = inspection::route_lock().lock().await;let mut route =module_config(config).unwrap_or_else(|_| serde_json::json!({ "route": "none" }));// `state_dir` is load-time only: the trigger archive opens once, and moving@@ -335,6 +349,7 @@ async fn ensure_routed(config: &Config, proxy: &Proxy) -> Result<(), String> {return Ok(());}+ let inspection_binding = inspection::configured_binding_for_route(config, &route);proxy.call_confidential::<serde_json::Value>(methods::CONFIGURE, (route,)).await@@ -345,6 +360,7 @@ async fn ensure_routed(config: &Config, proxy: &Proxy) -> Result<(), String> {*last_route().lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(current);+ inspection::record_configured_route(inspection_binding);Ok(())}diff --git a/crates/openhuman-core/src/modules/connectors/inspection.rs b/crates/openhuman-core/src/modules/connectors/inspection.rsnew file mode 100644index 0000000000..39ef887687--- /dev/null+++ b/crates/openhuman-core/src/modules/connectors/inspection.rs@@ -0,0 +1,421 @@+//! Bounded inspection calls to an already-ready connector runtime.++use serde::de::DeserializeOwned;+use serde::Serialize;+use sha2::{Digest, Sha256};+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use crate::config::Config;+use crate::modules::types::ModuleState;++const INSPECTION_TIMEOUT: Duration = Duration::from_secs(10);++#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) struct ConfiguredBinding {+ load_scope: [u8; 32],+ route_scope: [u8; 32],+ credential: [u8; 32],+}++fn loaded_scope() -> &'static Mutex<Option<[u8; 32]>> {+ static SCOPE: OnceLock<Mutex<Option<[u8; 32]>>> = OnceLock::new();+ SCOPE.get_or_init(|| Mutex::new(None))+}++fn pending_load_scope() -> &'static Mutex<Option<[u8; 32]>> {+ static SCOPE: OnceLock<Mutex<Option<[u8; 32]>>> = OnceLock::new();+ SCOPE.get_or_init(|| Mutex::new(None))+}++/// Safe result boundary for the existing-only connector call.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ExistingCallError {+ /// The runtime is absent or its accepted config belongs to another scope.+ Unavailable,+ /// A matching ready runtime returned a failed or malformed response.+ Failed,+}++trait ExistingRuntimeAccess {+ fn is_ready(&self) -> bool;+ fn proxy(&self) -> Result<tinybus::Proxy, ExistingCallError>;+}++struct ProcessRuntimeAccess;++impl ExistingRuntimeAccess for ProcessRuntimeAccess {+ fn is_ready(&self) -> bool {+ super::ops::state_of(super::MODULE_ID) == ModuleState::Ready+ && super::super::runtime::existing_runtime().is_some()+ }++ fn proxy(&self) -> Result<tinybus::Proxy, ExistingCallError> {+ let runtime =+ super::super::runtime::existing_runtime().ok_or(ExistingCallError::Unavailable)?;+ let record =+ super::registry::find(super::MODULE_ID).ok_or(ExistingCallError::Unavailable)?;+ runtime+ .proxy(record.bus_name, record.object_path)+ .map_err(|_| ExistingCallError::Unavailable)+ }+}++fn route_gate() -> &'static tokio::sync::Mutex<()> {+ static GATE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+ &GATE+}++fn configured_binding() -> &'static Mutex<Option<ConfiguredBinding>> {+ static BINDING: OnceLock<Mutex<Option<ConfiguredBinding>>> = OnceLock::new();+ BINDING.get_or_init(|| Mutex::new(None))+}++pub(super) fn route_lock() -> &'static tokio::sync::Mutex<()> {+ route_gate()+}++/// Capture the scope only after the module accepted its CONFIGURE request.+/// The ordinary route fingerprint intentionally omits state_dir and toolkit+/// policy; this separate identity prevents those omissions from authorizing a+/// doctor read against a different workspace or configuration.+pub(super) fn configured_binding_for_route(+ config: &Config,+ route: &serde_json::Value,+) -> Option<ConfiguredBinding> {+ let selected = selected_credential(config)?;+ let accepted_secret = route+ .get("auth_token")+ .or_else(|| route.get("api_key"))?+ .as_str()?;+ if selected.1 != accepted_secret {+ return None;+ }+ let load_scope = loaded_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .copied()?;+ Some(ConfiguredBinding {+ load_scope,+ route_scope: route_scope_fingerprint(config)?,+ credential: credential_fingerprint(&selected.0, &selected.1),+ })+}++pub(super) fn record_configured_route(binding: Option<ConfiguredBinding>) {+ *configured_binding()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = binding;+}++#[cfg(test)]+pub(super) fn record_configured_route_for_test(config: &Config, route: &serde_json::Value) {+ let binding = (|| {+ let selected = selected_credential(config)?;+ let accepted_secret = route+ .get("auth_token")+ .or_else(|| route.get("api_key"))?+ .as_str()?;+ if selected.1 != accepted_secret {+ return None;+ }+ let load_scope = loaded_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .copied()?;+ Some(ConfiguredBinding {+ load_scope,+ route_scope: route_scope_fingerprint(config)?,+ credential: credential_fingerprint(&selected.0, &selected.1),+ })+ })();+ record_configured_route(binding);+}++/// Call a read-only member only when the currently serving module was already+/// configured for this exact selected scope and credential. This function+/// never starts the module runtime, loads the module, reconciles its route, or+/// imports legacy connector data. `None` means inspection is unavailable.+pub(crate) async fn call_existing_readonly<Request, Reply>(+ config: &Config,+ member: &str,+ request: Request,+) -> Result<Option<Reply>, ExistingCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ let _route_guard = route_gate().lock().await;+ call_existing_readonly_with_runtime(config, member, request, &ProcessRuntimeAccess).await+}++async fn call_existing_readonly_with_runtime<Request, Reply, Runtime>(+ config: &Config,+ member: &str,+ request: Request,+ runtime: &Runtime,+) -> Result<Option<Reply>, ExistingCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+ Runtime: ExistingRuntimeAccess,+{+ if !config.modules.enabled || !config.components.connectors || !runtime.is_ready() {+ return Ok(None);+ }+ let Some(expected) = binding_for_config(config) else {+ return Ok(None);+ };+ if *configured_binding()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ != Some(expected)+ {+ return Ok(None);+ }+ let proxy = runtime.proxy()?.with_timeout(INSPECTION_TIMEOUT);+ call_bound_proxy(config, &proxy, member, request).await+}++async fn call_bound_proxy<Request, Reply>(+ config: &Config,+ proxy: &tinybus::Proxy,+ member: &str,+ request: Request,+) -> Result<Option<Reply>, ExistingCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ if !binding_matches_config(config) {+ return Ok(None);+ }+ call_proxy_readonly(proxy, member, request).await.map(Some)+}++async fn call_proxy_readonly<Request, Reply>(+ proxy: &tinybus::Proxy,+ member: &str,+ request: Request,+) -> Result<Reply, ExistingCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ call_proxy_readonly_with_timeout(proxy, member, request, INSPECTION_TIMEOUT).await+}++async fn call_proxy_readonly_with_timeout<Request, Reply>(+ proxy: &tinybus::Proxy,+ member: &str,+ request: Request,+ timeout: Duration,+) -> Result<Reply, ExistingCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ match tokio::time::timeout(+ timeout,+ proxy+ .clone()+ .with_timeout(timeout)+ .call_confidential::<Reply>(member, (request,)),+ )+ .await+ {+ Ok(Ok(reply)) => Ok(reply),+ Ok(Err(_)) | Err(_) => Err(ExistingCallError::Failed),+ }+}++fn selected_credential(config: &Config) -> Option<(String, String)> {+ if let Some(pinned) = config.composio.host_credential.as_ref() {+ return Some(("host-pinned-direct".to_owned(), pinned.api_key().to_owned()));+ }++ match config.composio.mode.trim() {+ "" | crate::config::schema::COMPOSIO_MODE_BACKEND => {+ let api_key =+ crate::security::credentials::api_key::get_api_key_read_only(config).ok()?;+ if let Some(api_key) = api_key.filter(|key| !key.trim().is_empty()) {+ return Some(("backend-api-key".to_owned(), api_key.trim().to_owned()));+ }+ let profile =+ crate::security::credentials::session_support::load_app_session_profile_read_only(+ config,+ )+ .ok()?;+ crate::security::credentials::session_support::check_session_backend(+ config,+ profile.as_ref(),+ )+ .ok()?;+ let token = match crate::security::credentials::session_support::classify_session_token(+ profile.as_ref(),+ chrono::Utc::now(),+ ) {+ crate::security::credentials::session_support::SessionTokenCheck::Live(token)+ if !crate::security::credentials::session_support::is_local_session_token(+ token.trim(),+ ) =>+ {+ token+ }+ _ => return None,+ };+ Some(("backend-session".to_owned(), token))+ }+ crate::config::schema::COMPOSIO_MODE_DIRECT => {+ let profile = crate::security::credentials::AuthService::get_profile_read_only(+ config,+ crate::security::credentials::COMPOSIO_DIRECT_PROVIDER,+ None,+ )+ .ok()?;+ let stored = profile.and_then(|profile| match profile.kind {+ crate::security::credentials::profiles::AuthProfileKind::Token => profile.token,+ crate::security::credentials::profiles::AuthProfileKind::OAuth => {+ profile.token_set.map(|tokens| tokens.access_token)+ }+ });+ stored+ .or_else(|| config.composio.api_key.clone())+ .map(|key| ("direct-composio-key".to_owned(), key.trim().to_owned()))+ .filter(|(_, key)| !key.is_empty())+ }+ _ => None,+ }+}++fn binding_for_config(config: &Config) -> Option<ConfiguredBinding> {+ let actual_load_scope = loaded_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .copied()?;+ if Some(actual_load_scope) != load_scope_fingerprint(config) {+ return None;+ }+ let selected = selected_credential(config)?;+ binding_for_selected(config, &selected)+}++fn binding_for_selected(config: &Config, selected: &(String, String)) -> Option<ConfiguredBinding> {+ Some(ConfiguredBinding {+ load_scope: loaded_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .copied()?,+ route_scope: route_scope_fingerprint(config)?,+ credential: credential_fingerprint(&selected.0, &selected.1),+ })+}++/// Capture the scope the resolver passed to the module's load configuration.+/// Search-path modules do not invoke this provider and therefore remain+/// unscoped for inspection rather than inheriting the first caller's config.+pub(super) fn note_module_config_for_load(config: &Config, module_config: &serde_json::Value) {+ let expected_state_dir = serde_json::to_value(config.workspace_dir.join("state")).ok();+ let expected_policy = super::offered_toolkits(config);+ let captures_selected_scope = module_config.get("state_dir") == expected_state_dir.as_ref()+ && module_config.get("offered_toolkits") == Some(&expected_policy);+ let candidate = captures_selected_scope+ .then(|| load_scope_fingerprint(config))+ .flatten();+ *pending_load_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = candidate;+}++/// Promote the resolver's captured candidate only after ensure_loaded returned+/// success and the process-wide resolution table reports Ready.+pub(super) fn note_load_resolution_ready() {+ if super::ops::state_of(super::MODULE_ID) != ModuleState::Ready {+ return;+ }+ let candidate = pending_load_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take();+ if let Some(candidate) = candidate {+ *loaded_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(candidate);+ }+}++fn binding_matches_config(config: &Config) -> bool {+ let Some(expected) = binding_for_config(config) else {+ return false;+ };+ *configured_binding()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ == Some(expected)+}++fn load_scope_fingerprint(config: &Config) -> Option<[u8; 32]> {+ let scope = serde_json::json!({+ "config_path": config.config_path,+ "workspace_dir": config.workspace_dir,+ "state_dir": config.workspace_dir.join("state"),+ "components_connectors": config.components.connectors,+ "modules_enabled": config.modules.enabled,+ "offered_toolkits": super::offered_toolkits(config),+ });+ Some(Sha256::digest(serde_json::to_vec(&scope).ok()?).into())+}++#[cfg(test)]+fn seed_loaded_scope_for_test(config: &Config) {+ *loaded_scope()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = load_scope_fingerprint(config);+}++fn route_scope_fingerprint(config: &Config) -> Option<[u8; 32]> {+ let config_json = serde_json::to_value(config).ok()?;+ let env = [+ "BACKEND_URL",+ "VITE_BACKEND_URL",+ "OPENHUMAN_APP_ENV",+ "VITE_APP_ENV",+ "OPENHUMAN_COMPOSIO_DIRECT_BASE_V2",+ "OPENHUMAN_COMPOSIO_DIRECT_BASE_V3",+ "TZ",+ ]+ .into_iter()+ .map(|key| (key, std::env::var(key).ok()))+ .collect::<std::collections::BTreeMap<_, _>>();+ let context = serde_json::json!({+ "config": config_json,+ "config_path": config.config_path,+ "workspace_dir": config.workspace_dir,+ "state_dir": config.workspace_dir.join("state"),+ "offered_toolkits": super::offered_toolkits(config),+ "host_credential": config.composio.host_credential.as_ref().map(|credential| {+ serde_json::json!({+ "entity_id": credential.entity(),+ "base_urls": credential.direct_base_urls().map(|urls| [&urls.v2, &urls.v3]),+ })+ }),+ "env": env,+ });+ Some(Sha256::digest(serde_json::to_vec(&context).ok()?).into())+}++fn credential_fingerprint(kind: &str, secret: &str) -> [u8; 32] {+ let mut hash = Sha256::new();+ hash.update(kind.as_bytes());+ hash.update([0]);+ hash.update(secret.as_bytes());+ hash.finalize().into()+}++#[cfg(test)]+#[path = "inspection_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/modules/connectors/inspection_tests.rs b/crates/openhuman-core/src/modules/connectors/inspection_tests.rsnew file mode 100644index 0000000000..176c063d72--- /dev/null+++ b/crates/openhuman-core/src/modules/connectors/inspection_tests.rs@@ -0,0 +1,535 @@+use super::*;+use std::sync::{Arc, Mutex};+use tinybus::service::Interface;+use tinybus::transport::memory::MemoryBus;++const DESTINATION: &str = "ai.tinyhumans.openhuman.DoctorConnectorFixture";+const OBJECT_PATH: &str = "/ai/tinyhumans/openhuman/DoctorConnectorFixture";+const INTERFACE: &str = "ai.tinyhumans.openhuman.DoctorConnectorFixture";++struct ReadOnlyFixture {+ calls: Arc<Mutex<Vec<(String, serde_json::Value)>>>,+ reply: serde_json::Value,+ delay: std::time::Duration,+}++struct FixtureReadyRuntime {+ proxy: tinybus::Proxy,+ proxy_requests: Arc<std::sync::atomic::AtomicUsize>,+}++impl ExistingRuntimeAccess for FixtureReadyRuntime {+ fn is_ready(&self) -> bool {+ true+ }++ fn proxy(&self) -> Result<tinybus::Proxy, ExistingCallError> {+ self.proxy_requests+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Ok(self.proxy.clone())+ }+}++#[async_trait::async_trait]+impl Interface for ReadOnlyFixture {+ fn name(&self) -> tinybus::InterfaceName {+ tinybus::InterfaceName::new(INTERFACE).unwrap()+ }++ fn members(&self) -> Vec<tinybus::MemberName> {+ vec![tinybus::MemberName::new("ListConnectedIntegrations").unwrap()]+ }++ async fn call(+ &self,+ member: &tinybus::MemberName,+ args: serde_json::Value,+ ) -> tinybus::Result<serde_json::Value> {+ tokio::time::sleep(self.delay).await;+ self.calls+ .lock()+ .unwrap()+ .push((member.as_str().to_owned(), args));+ Ok(self.reply.clone())+ }+}++struct LinkedFixtureModule {+ tx: std::sync::mpsc::SyncSender<Vec<u8>>,+}++unsafe extern "C" fn linked_fixture_deliver(+ ctx: *mut std::ffi::c_void,+ ptr: *const u8,+ len: usize,+) -> i32 {+ if ctx.is_null() || ptr.is_null() {+ return tinybus::module::abi::TB_BAD_ARGUMENT;+ }+ let module = unsafe { &*ctx.cast::<LinkedFixtureModule>() };+ let bytes = unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec();+ match module.tx.try_send(bytes) {+ Ok(()) => tinybus::module::abi::TB_OK,+ Err(std::sync::mpsc::TrySendError::Full(_)) => tinybus::module::abi::TB_BACKPRESSURE,+ Err(std::sync::mpsc::TrySendError::Disconnected(_)) => tinybus::module::abi::TB_CLOSED,+ }+}++unsafe extern "C" fn linked_fixture_shutdown(ctx: *mut std::ffi::c_void, _: u64) -> i32 {+ if !ctx.is_null() {+ drop(unsafe { Box::from_raw(ctx.cast::<LinkedFixtureModule>()) });+ }+ tinybus::module::abi::TB_OK+}++unsafe extern "C" fn linked_fixture_reinitialize(+ _: *mut std::ffi::c_void,+ _: *const u8,+ _: usize,+) -> i32 {+ tinybus::module::abi::TB_BAD_ARGUMENT+}++unsafe extern "C" fn linked_fixture_init(+ host: *const tinybus::module::abi::TbHostVtable,+ out: *mut tinybus::module::abi::TbModuleVtable,+) -> i32 {+ if host.is_null() || out.is_null() {+ return tinybus::module::abi::TB_BAD_ARGUMENT;+ }+ let host = unsafe { *host };+ let config = if host.config.len == 0 {+ serde_json::Value::Null+ } else {+ let bytes = unsafe { std::slice::from_raw_parts(host.config.ptr, host.config.len) };+ match serde_json::from_slice::<serde_json::Value>(bytes) {+ Ok(config) => config,+ Err(_) => return tinybus::module::abi::TB_BAD_ARGUMENT,+ }+ };+ let reply = config+ .get("reply")+ .cloned()+ .unwrap_or(serde_json::Value::Null);+ let host_ctx = host.host_ctx as usize;+ let send = host.send;+ let ready = host.ready;+ let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(8);+ std::thread::spawn(move || {+ unsafe { ready(host_ctx as *mut std::ffi::c_void) };+ while let Ok(bytes) = rx.recv() {+ let Ok(message) = serde_json::from_slice::<tinybus::Message>(&bytes) else {+ continue;+ };+ if message.header.kind != tinybus::MessageKind::MethodCall {+ continue;+ }+ let member = message+ .header+ .member+ .as_ref()+ .map(ToString::to_string)+ .unwrap_or_default();+ let body = serde_json::json!({+ "response": reply,+ "observed_member": member,+ "observed_body": message.body,+ });+ let response = tinybus::Message::method_return(&message.header, body);+ let Ok(bytes) = serde_json::to_vec(&response) else {+ continue;+ };+ let _ = unsafe {+ send(+ host_ctx as *mut std::ffi::c_void,+ bytes.as_ptr(),+ bytes.len(),+ )+ };+ }+ });+ unsafe {+ *out = tinybus::module::abi::TbModuleVtable {+ size: std::mem::size_of::<tinybus::module::abi::TbModuleVtable>() as u32,+ _reserved: 0,+ module_ctx: Box::into_raw(Box::new(LinkedFixtureModule { tx })).cast(),+ deliver: linked_fixture_deliver,+ shutdown: linked_fixture_shutdown,+ reinitialize: Some(linked_fixture_reinitialize),+ };+ }+ tinybus::module::abi::TB_OK+}++fn linked_fixture_manifest() -> tinybus::module::manifest::ModuleManifest {+ use tinybus::module::manifest::{+ ModuleIdentity, ModuleManifest, PanicPolicy, ProvidedInterface, MANIFEST_SCHEMA,+ };+ use tinybus::name::{BusName, InterfaceName, MemberName, ObjectPath};+ use tinybus::version::{InterfaceVersion, Version};++ ModuleManifest {+ schema: MANIFEST_SCHEMA,+ module: ModuleIdentity {+ name: "doctor-connector-fixture".to_owned(),+ version: Version::new(1, 0, 0),+ description: "Test-only attested connector fixture".to_owned(),+ homepage: None,+ license: String::new(),+ },+ bus_name: BusName::new(DESTINATION).unwrap(),+ object_path: ObjectPath::new(OBJECT_PATH).unwrap(),+ provides: vec![ProvidedInterface {+ version: InterfaceVersion::provided(+ InterfaceName::new(INTERFACE).unwrap(),+ Version::new(1, 0, 0),+ ),+ methods: vec![MemberName::new("ListConnectedIntegrations").unwrap()],+ signals: Vec::new(),+ }],+ requires: Vec::new(),+ environment: Vec::new(),+ capabilities: Vec::new(),+ lazy_init: false,+ worker_threads: 1,+ on_panic: PanicPolicy::Detach,+ }+}++#[tokio::test]+async fn a_matching_config_binding_is_pinned_to_workspace_policy_and_credential() {+ let _guard = route_lock().lock().await;+ let scratch = tempfile::tempdir().expect("create isolated binding fixture");+ let mut selected = Config {+ config_path: scratch.path().join("config.toml"),+ workspace_dir: scratch.path().join("workspace-a"),+ ..Config::default()+ };+ selected.composio.mode = crate::config::schema::COMPOSIO_MODE_DIRECT.to_owned();+ selected.composio.api_key = Some("doctor-binding-key-a".to_owned());+ selected.composio.offered_toolkits_allow = vec!["github".to_owned()];+ seed_loaded_scope_for_test(&selected);+ let route = serde_json::json!({+ "route": "direct",+ "api_key": "doctor-binding-key-a",+ "entity_id": "default",+ "state_dir": selected.workspace_dir.join("state"),+ "offered_toolkits": super::super::offered_toolkits(&selected),+ });++ record_configured_route_for_test(&selected, &route);+ assert!(binding_matches_config(&selected));++ let mut other_workspace = selected.clone();+ other_workspace.workspace_dir = scratch.path().join("workspace-b");+ assert!(!binding_matches_config(&other_workspace));++ let mut other_credential = selected.clone();+ other_credential.composio.api_key = Some("doctor-binding-key-b".to_owned());+ assert!(!binding_matches_config(&other_credential));++ let mut other_policy = selected.clone();+ other_policy+ .composio+ .offered_toolkits_allow+ .push("slack".to_owned());+ assert!(!binding_matches_config(&other_policy));++ let mut reconfigured_b = selected.clone();+ reconfigured_b.workspace_dir = scratch.path().join("workspace-b");+ reconfigured_b.composio.api_key = Some("doctor-binding-key-b".to_owned());+ let route_b = serde_json::json!({+ "route": "direct",+ "api_key": "doctor-binding-key-b",+ "entity_id": "default",+ "state_dir": reconfigured_b.workspace_dir.join("state"),+ "offered_toolkits": super::super::offered_toolkits(&reconfigured_b),+ });+ record_configured_route_for_test(&reconfigured_b, &route_b);+ assert!(+ !binding_matches_config(&reconfigured_b),+ "reconfiguring a module loaded under A cannot relabel its state/policy as B"+ );++ *configured_binding()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = None;+}++#[tokio::test]+async fn a_session_from_another_issuer_is_not_a_matching_connector_credential() {+ let scratch = tempfile::tempdir().expect("create isolated issuer fixture");+ let mut config = Config::default();+ config.config_path = scratch.path().join("config.toml");+ config.workspace_dir = scratch.path().join("workspace");+ config.secrets.encrypt = false;+ config.resolved_endpoints.control_plane_url = Some("https://account-b.example".to_owned());+ let profiles = scratch.path().join("auth-profiles.json");+ let raw = serde_json::json!({+ "schema_version": 1,+ "active_profiles": {},+ "profiles": {+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": "issuer-mismatch-test-token",+ "metadata": { "session_issuing_backend": "https://account-a.example" }+ }+ }+ })+ .to_string();+ std::fs::write(&profiles, &raw).expect("seed selected issuer profile");++ assert!(selected_credential(&config).is_none());+ assert_eq!(std::fs::read_to_string(&profiles).unwrap(), raw);+ assert!(!scratch.path().join("auth-profiles.lock").exists());+}++#[tokio::test]+async fn a_ready_connector_never_probes_after_the_selected_session_expires() {+ let _route_guard = route_lock().lock().await;+ let scratch = tempfile::tempdir().expect("create isolated expired-session fixture");+ let mut config = Config::default();+ config.config_path = scratch.path().join("config.toml");+ config.workspace_dir = scratch.path().join("workspace");+ config.secrets.encrypt = false;+ let profiles = scratch.path().join("auth-profiles.json");+ let raw = serde_json::json!({+ "schema_version": 1,+ "active_profiles": {},+ "profiles": {+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": "expired-connector-test-token",+ "metadata": { "session_expires_at": "2000-01-01T00:00:00Z" }+ }+ }+ })+ .to_string();+ std::fs::write(&profiles, &raw).expect("seed isolated expired credential");+ seed_loaded_scope_for_test(&config);++ let bus = MemoryBus::new();+ tinybus::broker::Broker::new().spawn(bus.clone());+ let client = tinybus::Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let proxy = client.proxy(DESTINATION, OBJECT_PATH, INTERFACE).unwrap();+ let proxy_requests = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let runtime = FixtureReadyRuntime {+ proxy,+ proxy_requests: Arc::clone(&proxy_requests),+ };++ let result = call_existing_readonly_with_runtime::<_, serde_json::Value, _>(+ &config,+ "ListConnectedIntegrations",+ (),+ &runtime,+ )+ .await+ .expect("expired credentials make the inspection unavailable");++ assert!(result.is_none());+ assert_eq!(proxy_requests.load(std::sync::atomic::Ordering::SeqCst), 0);+ assert_eq!(std::fs::read_to_string(&profiles).unwrap(), raw);+ assert!(!scratch.path().join("auth-profiles.lock").exists());+ *configured_binding().lock().unwrap() = None;+ *loaded_scope().lock().unwrap() = None;+}++#[tokio::test]+async fn load_scope_is_captured_only_when_the_module_receives_selected_paths_and_policy() {+ let _guard = route_lock().lock().await;+ let scratch = tempfile::tempdir().expect("create isolated load-scope fixture");+ let mut config = Config::default();+ config.config_path = scratch.path().join("config.toml");+ config.workspace_dir = scratch.path().join("workspace-a");+ config.composio.offered_toolkits_allow = vec!["github".to_owned()];+ let policy = super::super::offered_toolkits(&config);++ note_module_config_for_load(&config, &serde_json::json!({ "offered_toolkits": policy }));+ assert!(+ pending_load_scope().lock().unwrap().is_none(),+ "capability-only fallback does not attest a workspace"+ );++ let module_config = serde_json::json!({+ "route": "proxy",+ "state_dir": config.workspace_dir.join("state"),+ "offered_toolkits": super::super::offered_toolkits(&config),+ });+ note_module_config_for_load(&config, &module_config);+ assert_eq!(+ *pending_load_scope().lock().unwrap(),+ load_scope_fingerprint(&config)+ );+ *pending_load_scope().lock().unwrap() = None;+}++#[tokio::test]+async fn existing_readonly_call_returns_a_matching_ready_response_with_a_bound() {+ let _route_guard = route_lock().lock().await;+ let scratch = tempfile::tempdir().expect("create selected connector workspace");+ let mut config = Config::default();+ config.config_path = scratch.path().join("config.toml");+ config.workspace_dir = scratch.path().join("workspace");+ config.composio.mode = crate::config::schema::COMPOSIO_MODE_DIRECT.to_owned();+ config.composio.api_key = Some("doctor-boundary-fixture-key".to_owned());+ seed_loaded_scope_for_test(&config);+ let accepted_route = serde_json::json!({+ "route": "direct",+ "api_key": "doctor-boundary-fixture-key",+ "entity_id": "default",+ "state_dir": config.workspace_dir.join("state"),+ "offered_toolkits": super::super::offered_toolkits(&config),+ });+ record_configured_route_for_test(&config, &accepted_route);++ let bus = MemoryBus::new();+ let broker = tinybus::broker::Broker::new();+ let broker_task = broker.clone().spawn(bus.clone());+ let host = tinybus::module::ModuleHost::new(broker);+ host.attach_linked_with_config(+ tinybus::module::LinkedModule {+ descriptor: tinybus::module::abi::TbAbiDescriptor::current(+ "doctor-connector-fixture",+ "1.0.0",+ ),+ manifest: linked_fixture_manifest(),+ init: linked_fixture_init,+ },+ serde_json::json!({+ "reply": { "integrations": [{ "toolkit": "github", "connected": true }] }+ }),+ )+ .expect("admit the fixture through the trusted linked-module host");+ let client = tinybus::Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let reply = serde_json::json!({ "integrations": [{ "toolkit": "github", "connected": true }] });+ let proxy = client.proxy(DESTINATION, OBJECT_PATH, INTERFACE).unwrap();+ let proxy_requests = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let runtime = FixtureReadyRuntime {+ proxy,+ proxy_requests: Arc::clone(&proxy_requests),+ };++ let request = serde_json::json!({ "mode": "backend" });+ let response = call_existing_readonly_with_runtime::<_, serde_json::Value, _>(+ &config,+ "ListConnectedIntegrations",+ request.clone(),+ &runtime,+ )+ .await+ .expect("read-only fixture responds")+ .expect("the exactly matching ready binding is probeable");++ assert_eq!(response["response"], reply);+ assert_eq!(response["observed_member"], "ListConnectedIntegrations");+ assert_eq!(+ response["observed_body"],+ serde_json::json!([request.clone()])+ );+ let mut other_workspace = config.clone();+ other_workspace.workspace_dir = scratch.path().join("workspace-b");+ assert!(+ call_existing_readonly_with_runtime::<_, serde_json::Value, _>(+ &other_workspace,+ "ListConnectedIntegrations",+ request.clone(),+ &runtime,+ )+ .await+ .expect("mismatched binding is unavailable")+ .is_none()+ );+ assert_eq!(proxy_requests.load(std::sync::atomic::Ordering::SeqCst), 1);+ *configured_binding()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = None;+ drop(host);+ broker_task.abort();+}++#[tokio::test]+async fn existing_proxy_failures_are_sanitized_and_time_bounded() {+ let bus = MemoryBus::new();+ tinybus::broker::Broker::new().spawn(bus.clone());+ let service = tinybus::Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let client = tinybus::Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ service.request_name(DESTINATION).await.unwrap();+ let calls = Arc::new(Mutex::new(Vec::new()));+ service+ .serve_at(+ tinybus::ObjectPath::new(OBJECT_PATH).unwrap(),+ ReadOnlyFixture {+ calls,+ reply: serde_json::json!({ "private": "raw connector error fixture" }),+ delay: std::time::Duration::from_millis(40),+ },+ )+ .await+ .unwrap();+ let proxy = client.proxy(DESTINATION, OBJECT_PATH, INTERFACE).unwrap();++ let error = call_proxy_readonly_with_timeout::<_, String>(+ &proxy,+ "ListConnectedIntegrations",+ (),+ std::time::Duration::from_millis(1),+ )+ .await+ .expect_err("a slow connector status call must time out");++ assert_eq!(error, ExistingCallError::Failed);+ assert!(!format!("{error:?}").contains("raw connector error fixture"));++ let malformed = call_proxy_readonly_with_timeout::<_, String>(+ &proxy,+ "ListConnectedIntegrations",+ (),+ std::time::Duration::from_secs(1),+ )+ .await+ .expect_err("a malformed response must be surfaced as a safe failure");+ assert_eq!(malformed, ExistingCallError::Failed);+ assert!(!format!("{malformed:?}").contains("raw connector error fixture"));+}++#[tokio::test]+async fn an_absent_connector_does_not_start_runtime_or_load_the_module() {+ if crate::util::module_test_process::run(+ module_path!(),+ "an_absent_connector_does_not_start_runtime_or_load_the_module",+ ) {+ return;+ }+ assert!(!crate::modules::runtime::is_started());+ let scratch = tempfile::tempdir().expect("create isolated missing connector config");+ let mut config = Config::default();+ config.config_path = scratch.path().join("config.toml");+ config.workspace_dir = scratch.path().join("workspace");+ config.composio.mode = crate::config::schema::COMPOSIO_MODE_BACKEND.to_owned();+ let before = crate::modules::ops::state_of(super::super::MODULE_ID);++ let result =+ call_existing_readonly::<_, serde_json::Value>(&config, "ListConnectedIntegrations", ())+ .await+ .expect("absence is an unavailable observation, not a call error");++ assert!(result.is_none());+ assert_eq!(+ crate::modules::ops::state_of(super::super::MODULE_ID),+ before+ );+ assert!(!crate::modules::runtime::is_started());+}diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rsindex 38a16f9b03..9ecac130f0 100644--- a/crates/openhuman-core/src/modules/ops.rs+++ b/crates/openhuman-core/src/modules/ops.rs@@ -145,6 +145,7 @@ pub fn resolver(config: &Config) -> Resolver {}}let gate_config = Arc::clone(&shared);+ let module_config_source = Arc::clone(&shared);Resolver::new(ResolverInputs {enabled: config.modules.enabled,install_dir: install_dir(config),@@ -158,7 +159,13 @@ pub fn resolver(config: &Config) -> Resolver {records: registry::release_records(),terminal_marker: tinytools::status::MODULE_FAULT_MARKER.to_string(),runtime: Arc::new(|| Box::pin(runtime::runtime())),- module_config: Arc::new(move |id| module_config(&shared, id)),+ module_config: Arc::new(move |id| {+ let value = module_config(&module_config_source, id);+ if id == super::connectors::MODULE_ID {+ super::connectors::note_module_config_for_load(&module_config_source, &value);+ }+ value+ }),reporter: report::reporter(),})}@@ -269,7 +276,11 @@ pub async fn ensure_loaded_within(id: &str,within: Option<Duration>,) -> Result<(), LoadError> {- resolver(config).ensure_loaded_within(id, within).await+ let result = resolver(config).ensure_loaded_within(id, within).await;+ if id == super::connectors::MODULE_ID && result.is_ok() {+ super::connectors::note_load_resolution_ready();+ }+ result}/// The state of `id` as the resolution table reports it, without touching it.diff --git a/crates/openhuman-core/src/modules/runtime.rs b/crates/openhuman-core/src/modules/runtime.rsindex 4a720139f3..7ba4bcc648 100644--- a/crates/openhuman-core/src/modules/runtime.rs+++ b/crates/openhuman-core/src/modules/runtime.rs@@ -34,7 +34,10 @@//! shutdown path because there is nothing a shutdown could reclaim.use std::sync::OnceLock;+use std::time::Duration;+use serde::de::DeserializeOwned;+use serde::Serialize;use tinybus::module::{ModuleRuntime, RuntimeNames};/// The module bus, built once on first use.@@ -137,6 +140,56 @@ pub fn is_started() -> bool {RUNTIME.get().is_some_and(Result::is_ok)}+/// Returns the current runtime only when it was already started and its host+/// callbacks are serving. Unlike [`runtime`], this accessor never starts a+/// runtime or installs callbacks.+pub(crate) fn existing_runtime() -> Option<&'static ModuleRuntime> {+ let runtime = RUNTIME.get()?.as_ref().ok()?;+ CALLBACKS.get()?.as_ref().ok()?;+ Some(runtime)+}++/// A safe, sanitized result for a call through the already-serving module bus.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ExistingModuleCallError {+ Unavailable,+ Failed,+}++/// Call a read-only capability on a module that is already ready. This never+/// starts the module runtime, loads a module, or retries through a ModuleClient.+pub(crate) async fn call_if_ready<Request, Reply>(+ id: &str,+ member: &str,+ request: Request,+ timeout: Duration,+) -> Result<Option<Reply>, ExistingModuleCallError>+where+ Request: Serialize + Send,+ Reply: DeserializeOwned,+{+ if super::ops::state_of(id) != super::types::ModuleState::Ready {+ return Ok(None);+ }+ let Some(runtime) = existing_runtime() else {+ return Ok(None);+ };+ let record = super::registry::find(id).ok_or(ExistingModuleCallError::Unavailable)?;+ let proxy = runtime+ .proxy(record.bus_name, record.object_path)+ .map_err(|_| ExistingModuleCallError::Unavailable)?+ .with_timeout(timeout);+ match tokio::time::timeout(+ timeout,+ proxy.call_confidential::<Reply>(member, (request,)),+ )+ .await+ {+ Ok(Ok(reply)) => Ok(Some(reply)),+ Ok(Err(_)) | Err(_) => Err(ExistingModuleCallError::Failed),+ }+}+/// Whether `id` is admitted and currently serving on an already-started/// module runtime. This is a read-only snapshot; it never starts the runtime.#[must_use]diff --git a/crates/openhuman-core/src/platform/README.md b/crates/openhuman-core/src/platform/README.mdindex deda72ce02..249bb89c1f 100644--- a/crates/openhuman-core/src/platform/README.md+++ b/crates/openhuman-core/src/platform/README.md@@ -50,9 +50,8 @@ The event-driven pieces:(`WebhookIncomingRequest`, `ComposioTriggerReceived`,`ChannelInboundMessage`, device tunnel events) for other domains to handle.-Some members read state other domains own instead of keeping their own.-[`doctor`](./doctor) reads the daemon state file `service` writes and the memory engine-status from `memory`. [`connectivity`](./connectivity) reads the `SocketManager` state to tell+The top-level [`doctor`](../doctor) domain reads the daemon state file+`service` writes and the memory engine status from `memory`. [`connectivity`](./connectivity) reads the `SocketManager` state to tellthe frontend which of its connection channels is broken.## Layout@@ -62,7 +61,6 @@ the frontend which of its connection channels is broken.| [`about_app/`](about_app/README.md) | The user-facing capability catalog: what each feature does, where it is in the UI, its maturity, and its privacy disclosure. A compile-time static table with list, lookup, and search. Update it when user-visible capabilities change. || [`connectivity/`](connectivity/README.md) | `connectivity_diag` (backend socket state, loop liveness, core PID and port, a loopback port probe) and the listen-port picker the core uses to bind its HTTP listener, including stale-listener takeover and the Windows excluded-port fallback. || [`cost/`](cost/README.md) | Token usage and USD cost: an append-only `costs.jsonl` ledger, day and month aggregates, the 7-day dashboard, the static pricing and context-window catalog (`catalog.rs`), and managed vs BYOK route classification (`route.rs`). |-| [`doctor/`](doctor/README.md) | Self-checks over config, workspace, the daemon state file, the environment, the memory engine, and the embedding model, aggregated into a severity-tagged `DoctorReport`. Powers `openhuman doctor` and the Settings health view. || [`health/`](health/README.md) | The in-process component health registry, the `HealthVerdict` behind `GET /health`, and static system info. || [`proc_metrics/`](proc_metrics/README.md) | Cross-platform RSS and peak-RSS sampling for this process and its tree. Used by the `rss-bench` and `library-profile` bins in openhuman-benchmarks (`profile/`). No RPC. || [`service/`](service/README.md) | Installs the core as a per-user OS service (LaunchAgent, systemd user unit, Windows scheduled task), self-restart and graceful shutdown over the bus, daemon-host tray preferences, and a file-backed mock for E2E (`OPENHUMAN_SERVICE_MOCK`). |@@ -79,7 +77,6 @@ There is no type shared across the family. The ones contributors touch most:- `CostTracker` and `cost::init_global` / `try_global` / `rebind_global`([`cost/global.rs`](./cost/global.rs)). The tracker is bound to one workspace, and signing in orout rebinds it so usage lands in the right user's ledger.-- `DoctorReport` ([`doctor/core/types.rs`](./doctor/core/types.rs)).- `SocketManager` and `token_provider_from_config` ([`socket/`](./socket/)).- `pick_listen_port_for_host` and its variants ([`connectivity/`](./connectivity/)), used by theRPC host when binding.@@ -94,14 +91,13 @@ Method names are `openhuman.<namespace>_<function>`.| [`about_app`](./about_app) | `list`, `lookup`, `search` || `connectivity` | `diag` || [`cost`](./cost) | `get_dashboard`, `get_daily_history`, `get_summary`, `get_usage_log` |-| [`doctor`](./doctor) | `report`, `models` || `health` | `snapshot`, `system_info` || `service` | `install`, `start`, `stop`, `status`, `uninstall`, `restart`, `shutdown`, `daemon_host_get`, `daemon_host_set` || `socket` | `connect`, `connect_with_session`, `disconnect`, `emit`, `state` || [`update`](./update) | `version`, `check`, `apply`, `run` |Agent tools from this family (registered in `tools/ops.rs`):-`health_snapshot`, `health_system_info`, `doctor_health`, `doctor_models`,+`health_snapshot`, `health_system_info`,`cost_get_dashboard`, `cost_get_daily_history`, `cost_get_summary`,`service_restart`, `service_shutdown`, and `daemon_host_prefs_set`. Thelifecycle mutators ship off by default through the user tool filter.diff --git a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rsindex de32ca4096..76c0a037ed 100644--- a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs+++ b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs@@ -560,6 +560,16 @@ Capability {status: CapabilityStatus::Beta,privacy: LOCAL_RAW,},+Capability {+ id: "intelligence.doctor_health",+ name: "Health Diagnostics",+ domain: "doctor",+ category: CapabilityCategory::Intelligence,+ description: "Inspect OpenHuman configuration and runtime health with a structured diagnostic report of checks and repair hints. The default tier uses local and bounded read-only checks; live probes that can spend inference tokens require an explicit request.",+ how_to: "Ask the assistant to run doctor_health when diagnosing a configuration or runtime problem",+ status: CapabilityStatus::Beta,+ privacy: DIAGNOSTICS_TO_BACKEND,+ },Capability {id: "intelligence.orchestrator_worker_thread",name: "Worker Thread Delegation",diff --git a/crates/openhuman-core/src/platform/about_app/catalog_tests.rs b/crates/openhuman-core/src/platform/about_app/catalog_tests.rsindex e073c52f80..4f4d9609c1 100644--- a/crates/openhuman-core/src/platform/about_app/catalog_tests.rs+++ b/crates/openhuman-core/src/platform/about_app/catalog_tests.rs@@ -7,6 +7,20 @@ fn lookup_returns_expected_capability() {assert_eq!(capability.status, CapabilityStatus::Beta);}+#[test]+fn doctor_health_is_advertised_as_an_intelligence_capability() {+ let capability = lookup("intelligence.doctor_health")+ .expect("the doctor health diagnostic is a user-facing capability");++ assert_eq!(capability.domain, "doctor");+ assert_eq!(capability.category, CapabilityCategory::Intelligence);+ assert!(capability+ .description+ .to_ascii_lowercase()+ .contains("diagnostic"));+ assert!(capability.how_to.contains("doctor_health"));+}+/// The removed desktop push-to-talk server must not be advertised, while the/// mobile and live voice capabilities remain discoverable.#[test]diff --git a/crates/openhuman-core/src/platform/doctor/README.md b/crates/openhuman-core/src/platform/doctor/README.mddeleted file mode 100644index 9ad49af99a..0000000000--- a/crates/openhuman-core/src/platform/doctor/README.md+++ /dev/null@@ -1,95 +0,0 @@-# doctor--Diagnostic / self-check domain for OpenHuman. Runs a synchronous battery of probes against the live `Config`, the workspace directory, the daemon state file, the local environment, the embedding provider (Ollama), and the Claude Agent SDK binary, then aggregates the findings into a severity-tagged `DoctorReport`. Exposed to CLI and JSON-RPC as `doctor.report` and `doctor.models`. This is what powers `openhuman doctor` / the Settings health surface.--## Responsibilities--- Validate config semantics: config file presence, `api_url` (with fallback resolution), app session JWT / sign-in state, `default_model`, temperature range (0.0 to 2.0), legacy `reliability.fallback_providers`, model & embedding route entries (empty hints/models, invalid embedding providers, `dimensions=0`), `memory.embedding_model` `hint:` cross-reference, at least one channel configured, and delegate-agent models.-- Check workspace integrity: directory existence, write probe (create/write/delete a temp probe file), `memory/` dir, `SYSTEM.md` prompt, and best-effort free disk space (warns under 512 MB; uses `df -m` on Unix, PowerShell `Get-PSDrive` on Windows).-- Inspect daemon state file: presence, JSON validity, heartbeat freshness (stale > 30s = error), scheduler component health (stale > 120s), and per-channel component freshness (stale > 300s).-- Probe environment commands: `git --version`, `curl --version`, `$SHELL`, and `$HOME`/`$USERPROFILE`.-- Probe the memory engine (`memory_agent_checks::check_memory_engine`): report `ok`, `degraded`, `down` or `off` (memory is off with no usable engine) from the `MemoryEngineCheck` the async caller takes from the memory domain's status before the blocking hop.-- Probe embedding-model health: if provider is `ollama`, do a 3s blocking HTTP GET to `<base_url>/api/tags` and verify the configured model is installed; non-ollama providers report OK without a local probe.-- Probe the Claude Agent SDK: if enabled, run `<binary> --version`.-- Probe provider model availability via `run_models` (currently a stub: see Notes).--## Key files--| File | Role |-| --- | --- |-| `crates/openhuman-core/src/platform/doctor/mod.rs` | Module docstring + exports. Declares [`core`](./core), `ops`, `schemas`; re-exports `core::*`, `ops::*` (also aliased `pub use ops as rpc`), and the schema controller pair. |-| `crates/openhuman-core/src/platform/doctor/core.rs` | All diagnostic logic + types. `run()` entry point and every `check_*` probe; `run_models()`; severity helpers; OS-specific disk/command helpers. |-| `crates/openhuman-core/src/platform/doctor/ops.rs` | Async JSON-RPC/CLI controller surface (`doctor_report`, `doctor_models`) wrapping the sync `core` logic in `spawn_blocking` and returning `Outcome<T>`. |-| `crates/openhuman-core/src/platform/doctor/schemas.rs` | Controller schemas + registry (`all_controller_schemas`, `all_registered_controllers`, `handle_report`/`handle_models`). |-| `crates/openhuman-core/src/platform/doctor/core_tests.rs` | Test suite for [`core.rs`](./core.rs) (via `#[path = "core_tests.rs"] mod tests`). |--## Public surface--From [`mod.rs`](./mod.rs) re-exports (`core::*`):--- Types: `Severity` (`Ok`/`Warn`/`Error`), `DiagnosticItem`, `DoctorSummary`, `DoctorReport`, `ModelProbeOutcome`, `ModelProbeEntry`, `ModelProbeSummary`, `ModelProbeReport`.-- Functions: `run(&Config, MemoryChunkCount) -> Result<DoctorReport>` (blocking-only: keep no `.await` inside; async probes are resolved by the caller and passed in), `run_models(&Config, use_cache) -> Result<ModelProbeReport>`.-- Type alias: `MemoryChunkCount = Result<u64, String>`: the hoisted chunk-count probe.--From `ops` (also re-exported as `doctor::rpc`):--- `doctor_report(&Config) -> Result<Outcome<DoctorReport>, String>`-- `doctor_models(&Config, use_cache: bool) -> Result<Outcome<ModelProbeReport>, String>`--Schema pair re-exported as `all_doctor_controller_schemas` / `all_doctor_registered_controllers`.--## RPC / controllers--Namespace `doctor`, two functions:--| Method | Inputs | Output |-| --- | --- | --- |-| `doctor.report` | none | `DoctorReport` ("Run diagnostics for workspace and runtime configuration.") |-| `doctor.models` | `use_cache: Option<bool>` (default `true`) | `ModelProbeReport` ("Probe provider model availability and auth status.") |--Both handlers load config via `config_rpc::load_config_with_timeout()` and return `Outcome::single_log(...)`. Wired into the global registry in `crates/openhuman-core/src/core/all.rs` (controllers, schemas, and the namespace description "Run diagnostics for workspace and runtime health.").--## Agent tools--None. This domain owns no agent tools (no [`tools.rs`](./tools.rs)).--## Events--None. No `bus.rs` / event-bus subscribers or publishers.--## Persistence--None of its own (no `store.rs`). It only **reads** existing state owned by other domains: the daemon state file (`service::daemon::state_file_path`), the memory engine's status (passed in as `MemoryEngineCheck`), config files, and `<workspace>/SYSTEM.md` / `<workspace>/memory/`. Its only writes are an ephemeral workspace probe file that is immediately deleted.--## Dependencies--- `crate::config::{Config, rpc}`: reads the live config for all probes; `config_rpc::load_config_with_timeout` in the handlers.-- `crate::platform::service::daemon`: `state_file_path` for the daemon heartbeat/component snapshot.-- `crate::memory::status`: the memory engine's status (`ok`/`degraded`/`down`/`off`), taken by `ops` before the blocking hop and passed to `run` as a `MemoryEngineCheck`.-- `crate::inference::embedding_host::effective_embedding_settings`: resolves the intended embedding provider/model.-- `crate::inference::{provider, local}`: `provider::list_providers` (model targets) and `local::ollama_base_url` (embedding probe).-- `config.resolved_endpoints` (filled by the host's config enricher) for the inference base URL; `crate::security::credentials::jwt::get_session_token` for sign-in state.-- `crate::core::all::{ControllerFuture, RegisteredController}`, `crate::core::{ControllerSchema, FieldSchema, TypeSchema}`: controller/schema plumbing.-- `crate::rpc::RpcOutcome`: handler return contract.-- External: `reqwest` (blocking client + URL parse), `serde`/`serde_json`, `chrono`, `anyhow`.--## Used by--- `crates/openhuman-core/src/core/all.rs`: registers the doctor controllers/schemas into the global RPC + CLI registry (the only in-tree consumer).--## Notes / gotchas--- `run()` is **strictly blocking** by contract (file system, sqlite, blocking HTTP). `reqwest::blocking::Client` panics inside a tokio runtime, so `ops::doctor_report` runs the whole thing in `tokio::task::spawn_blocking`. Do not add `.await` inside `core::run`.-- An async probe therefore arrives as an **argument**, resolved in `ops` before the blocking hop: `MemoryEngineCheck` is the first of them. Do not reach for `Handle::block_on` inside [`core`](./core): it panics on a current-thread runtime and deadlocks the multi-thread one whose worker it is already occupying.-- An engine that is down is reported as an error and memory being off as a warning, so the doctor names what is wrong instead of showing an empty store.-- `run_models` / `doctor.models` is effectively a **stub**: it enumerates providers from `inference::provider::list_providers` but marks every entry `Skipped` with message "model catalog refresh removed" (catalog refresh was removed). It never actually probes auth/availability despite the schema description.-- The embedding probe is capped at a 3s timeout to avoid stalling on a slow Ollama daemon; non-ollama providers short-circuit to OK.-- `model_matches` treats `name` vs `name:tag` as a match only when at most one side is tagged; two differently-tagged names are not considered equal.-- Severity rollup: `DoctorSummary` counts `Ok`/`Warn`/`Error` items; checks are intentionally lenient (missing optional dirs/tools → `Warn`, not `Error`).-- OS-specific helpers (`available_disk_space_mb`, `check_command_available`, `check_claude_agent_sdk`) set `CREATE_NO_WINDOW` on Windows to avoid console flashes.--## Further reading--- [Parent module (`platform`)](../README.md)-- [Platform and availability](../../../../../docs/gitbooks/en/features/platform.md)-- [Recover a failed installation](../../../../../docs/gitbooks/en/guides/recover-failed-installation.md)diff --git a/crates/openhuman-core/src/platform/doctor/core.rs b/crates/openhuman-core/src/platform/doctor/core.rsdeleted file mode 100644index fe49541c7f..0000000000--- a/crates/openhuman-core/src/platform/doctor/core.rs+++ /dev/null@@ -1,29 +0,0 @@-//! The doctor report: config, workspace, daemon, environment, memory, and-//! agent-SDK diagnostic checks, plus the model-probe report.-//!-//! Split by responsibility rather than by line count — see `core/*.rs`. This-//! file only wires the submodules together and re-exports the public API.--#[cfg(test)]-#[path = "core_tests.rs"]-mod tests;--mod config_checks;-mod daemon_env_checks;-mod memory_agent_checks;-mod run;-mod types;-mod workspace_checks;--pub use run::{run, run_models, MemoryEngineCheck};-pub use types::{- DiagnosticItem, DoctorReport, DoctorSummary, ModelProbeEntry, ModelProbeOutcome,- ModelProbeReport, ModelProbeSummary, Severity,-};--#[cfg(test)]-use config_checks::{check_config_semantics, embedding_provider_validation_error};-#[cfg(test)]-use daemon_env_checks::truncate_for_display;-#[cfg(test)]-use memory_agent_checks::model_matches;diff --git a/crates/openhuman-core/src/platform/doctor/core/config_checks.rs b/crates/openhuman-core/src/platform/doctor/core/config_checks.rsdeleted file mode 100644index fb8dc73e1b..0000000000--- a/crates/openhuman-core/src/platform/doctor/core/config_checks.rs+++ /dev/null@@ -1,225 +0,0 @@-//! Config semantic validation: [`check_config_semantics`] and its embedding-//! provider URL check.--use crate::config::Config;--use super::types::DiagnosticItem;--pub(super) fn check_config_semantics(config: &Config, items: &mut Vec<DiagnosticItem>) {- let cat = "config";-- // Config file exists- if config.config_path.exists() {- items.push(DiagnosticItem::ok(- cat,- format!("config file: {}", config.config_path.display()),- ));- } else {- items.push(DiagnosticItem::error(- cat,- format!("config file not found: {}", config.config_path.display()),- ));- }-- // Backend API URL- if let Some(url) = config- .api_url- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty())- {- items.push(DiagnosticItem::ok(cat, format!("api_url: {url}")));- } else {- let resolved = config- .resolved_endpoints- .inference_or_configured(&config.api_url)- .unwrap_or_else(|| "no hosted backend".to_string());- items.push(DiagnosticItem::ok(- cat,- format!("api_url: (unset) resolved to {resolved}"),- ));- }-- match crate::security::credentials::jwt::get_session_token(config) {- Ok(Some(token)) if !token.trim().is_empty() => {- items.push(DiagnosticItem::ok(cat, "signed in with app session JWT"));- }- Ok(_) => {- items.push(DiagnosticItem::warn(- cat,- "no app session JWT — not signed in",- ));- }- Err(err) => {- items.push(DiagnosticItem::error(- cat,- format!("failed to read app session JWT: {err}"),- ));- }- }-- // Model configured- if config.default_model.is_some() {- items.push(DiagnosticItem::ok(- cat,- format!(- "default model: {}",- config.default_model.as_deref().unwrap_or("?")- ),- ));- } else {- items.push(DiagnosticItem::warn(cat, "no default_model configured"));- }-- // Temperature range- if config.default_temperature >= 0.0 && config.default_temperature <= 2.0 {- items.push(DiagnosticItem::ok(- cat,- format!(- "temperature {:.1} (valid range 0.0-2.0)",- config.default_temperature- ),- ));- } else {- items.push(DiagnosticItem::error(- cat,- format!(- "temperature {:.1} is out of range (expected 0.0-2.0)",- config.default_temperature- ),- ));- }-- // Reliability: fallback providers (legacy; ignored at runtime)- if !config.reliability.fallback_providers.is_empty() {- items.push(DiagnosticItem::warn(- cat,- "reliability.fallback_providers is set but ignored (single backend)",- ));- }-- // Model routes validation- for route in &config.model_routes {- if route.hint.is_empty() {- items.push(DiagnosticItem::warn(cat, "model route with empty hint"));- }- if route.model.is_empty() {- items.push(DiagnosticItem::warn(- cat,- format!("model route \"{}\" has empty model", route.hint),- ));- }- }-- // Embedding routes validation- for route in &config.embedding_routes {- if route.hint.trim().is_empty() {- items.push(DiagnosticItem::warn(cat, "embedding route with empty hint"));- }- if let Some(reason) = embedding_provider_validation_error(&route.provider) {- items.push(DiagnosticItem::warn(- cat,- format!(- "embedding route \"{}\" uses invalid provider \"{}\": {}",- route.hint, route.provider, reason- ),- ));- }- if route.model.trim().is_empty() {- items.push(DiagnosticItem::warn(- cat,- format!("embedding route \"{}\" has empty model", route.hint),- ));- }- if route.dimensions.is_some_and(|value| value == 0) {- items.push(DiagnosticItem::warn(- cat,- format!(- "embedding route \"{}\" has invalid dimensions=0",- route.hint- ),- ));- }- }-- if let Some(hint) = config- .memory- .embedding_model- .strip_prefix("hint:")- .map(str::trim)- .filter(|value| !value.is_empty())- {- if !config- .embedding_routes- .iter()- .any(|route| route.hint.trim() == hint)- {- items.push(DiagnosticItem::warn(- cat,- format!(- "memory.embedding_model uses hint \"{hint}\" but no matching [[embedding_routes]] entry exists"- ),- ));- }- }-- // Channel: at least one configured- let cc = &config.channels_config;- let has_channel = cc.telegram.is_some()- || cc.discord.is_some()- || cc.slack.is_some()- || cc.imessage.is_some()- || cc.matrix.is_some()- || cc.whatsapp.is_some()- || cc.email.is_some()- || cc.irc.is_some()- || cc.lark.is_some()- || cc.webhook.is_some();-- if has_channel {- items.push(DiagnosticItem::ok(cat, "at least one channel configured"));- } else {- items.push(DiagnosticItem::warn(- cat,- "no channels configured - configure one in the UI",- ));- }-- // Delegate agents- let mut agent_names: Vec<_> = config.agents.keys().collect();- agent_names.sort();- for name in agent_names {- let agent = config.agents.get(name).unwrap();- if agent.model.trim().is_empty() {- items.push(DiagnosticItem::warn(- cat,- format!("delegate agent \"{name}\" has empty model"),- ));- }- }-}--pub(super) fn embedding_provider_validation_error(name: &str) -> Option<String> {- let normalized = name.trim();- if normalized.eq_ignore_ascii_case("none") || normalized.eq_ignore_ascii_case("openai") {- return None;- }-- let Some(url) = normalized.strip_prefix("custom:") else {- return Some("supported values: none, openai, custom:<url>".into());- };-- let url = url.trim();- if url.is_empty() {- return Some("custom provider requires a non-empty URL after 'custom:'".into());- }-- match reqwest::Url::parse(url) {- Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => None,- Ok(parsed) => Some(format!(- "custom provider URL must use http/https, got '{}'",- parsed.scheme()- )),- Err(err) => Some(format!("invalid custom provider URL: {err}")),- }-}diff --git a/crates/openhuman-core/src/platform/doctor/core/daemon_env_checks.rs b/crates/openhuman-core/src/platform/doctor/core/daemon_env_checks.rsdeleted file mode 100644index af47235e87..0000000000--- a/crates/openhuman-core/src/platform/doctor/core/daemon_env_checks.rs+++ /dev/null@@ -1,259 +0,0 @@-//! Daemon liveness, environment, and command-availability checks.--use chrono::{DateTime, Utc};--use crate::config::Config;--use super::types::DiagnosticItem;--const DAEMON_STALE_SECONDS: i64 = 30;-const SCHEDULER_STALE_SECONDS: i64 = 120;-const CHANNEL_STALE_SECONDS: i64 = 300;-pub(super) const COMMAND_VERSION_PREVIEW_CHARS: usize = 60;--pub(super) fn check_daemon_state(config: &Config, items: &mut Vec<DiagnosticItem>) {- let cat = "daemon";- let state_file = crate::platform::service::daemon::state_file_path(config);-- if !state_file.exists() {- items.push(DiagnosticItem::error(- cat,- format!(- "state file not found: {} - is the daemon running?",- state_file.display()- ),- ));- return;- }-- let raw = match std::fs::read_to_string(&state_file) {- Ok(r) => r,- Err(e) => {- items.push(DiagnosticItem::error(- cat,- format!("cannot read state file: {e}"),- ));- return;- }- };-- let snapshot: serde_json::Value = match serde_json::from_str(&raw) {- Ok(v) => v,- Err(e) => {- items.push(DiagnosticItem::error(- cat,- format!("invalid state JSON: {e}"),- ));- return;- }- };-- // Daemon heartbeat freshness- let updated_at = snapshot- .get("updated_at")- .and_then(serde_json::Value::as_str)- .unwrap_or("");-- if let Ok(ts) = DateTime::parse_from_rfc3339(updated_at) {- let age = Utc::now()- .signed_duration_since(ts.with_timezone(&Utc))- .num_seconds();- if age <= DAEMON_STALE_SECONDS {- items.push(DiagnosticItem::ok(- cat,- format!("heartbeat fresh ({age}s ago)"),- ));- } else {- items.push(DiagnosticItem::error(- cat,- format!("heartbeat stale ({age}s ago)"),- ));- }- } else {- items.push(DiagnosticItem::error(- cat,- format!("invalid daemon timestamp: {updated_at}"),- ));- }-- // Components- if let Some(components) = snapshot- .get("components")- .and_then(serde_json::Value::as_object)- {- // Scheduler- if let Some(scheduler) = components.get("scheduler") {- let scheduler_ok = scheduler- .get("status")- .and_then(serde_json::Value::as_str)- .is_some_and(|s| s == "ok");- let scheduler_age = scheduler- .get("last_ok")- .and_then(serde_json::Value::as_str)- .and_then(parse_rfc3339)- .map_or(i64::MAX, |dt| {- Utc::now().signed_duration_since(dt).num_seconds()- });-- if scheduler_ok && scheduler_age <= SCHEDULER_STALE_SECONDS {- items.push(DiagnosticItem::ok(- cat,- format!("scheduler healthy (last ok {scheduler_age}s ago)"),- ));- } else {- items.push(DiagnosticItem::error(- cat,- format!("scheduler unhealthy (ok={scheduler_ok}, age={scheduler_age}s)"),- ));- }- } else {- items.push(DiagnosticItem::warn(- cat,- "scheduler component not tracked yet",- ));- }-- // Channels- let mut channel_count = 0u32;- let mut stale = 0u32;- for (name, component) in components {- if !name.starts_with("channel:") {- continue;- }- channel_count += 1;- let status_ok = component- .get("status")- .and_then(serde_json::Value::as_str)- .is_some_and(|s| s == "ok");- let age = component- .get("last_ok")- .and_then(serde_json::Value::as_str)- .and_then(parse_rfc3339)- .map_or(i64::MAX, |dt| {- Utc::now().signed_duration_since(dt).num_seconds()- });-- if status_ok && age <= CHANNEL_STALE_SECONDS {- items.push(DiagnosticItem::ok(- cat,- format!("{name} fresh ({age}s ago)"),- ));- } else {- stale += 1;- items.push(DiagnosticItem::error(- cat,- format!("{name} stale (ok={status_ok}, age={age}s)"),- ));- }- }-- if channel_count == 0 {- items.push(DiagnosticItem::warn(- cat,- "no channel components tracked yet",- ));- } else if stale > 0 {- items.push(DiagnosticItem::warn(- cat,- format!("{channel_count} channels, {stale} stale"),- ));- }- }-}--// ── Environment checks ───────────────────────────────────────────--pub(super) fn check_environment(items: &mut Vec<DiagnosticItem>) {- let cat = "environment";-- // git- check_command_available("git", &["--version"], cat, items);-- // Shell- let shell = std::env::var("SHELL").unwrap_or_default();- if shell.is_empty() {- items.push(DiagnosticItem::warn(cat, "$SHELL not set"));- } else {- items.push(DiagnosticItem::ok(cat, format!("shell: {shell}")));- }-- // HOME- if std::env::var("HOME").is_ok() || std::env::var("USERPROFILE").is_ok() {- items.push(DiagnosticItem::ok(cat, "home directory env set"));- } else {- items.push(DiagnosticItem::error(- cat,- "neither $HOME nor $USERPROFILE is set",- ));- }-- // Optional tools- check_command_available("curl", &["--version"], cat, items);-}--fn check_command_available(- cmd: &str,- args: &[&str],- cat: &'static str,- items: &mut Vec<DiagnosticItem>,-) {- let mut child_cmd = std::process::Command::new(cmd);- child_cmd- .args(args)- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped());- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- child_cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW- }- match child_cmd.output() {- Ok(output) if output.status.success() => {- let version = String::from_utf8_lossy(&output.stdout)- .lines()- .next()- .unwrap_or("(unknown)")- .to_string();- items.push(DiagnosticItem::ok(cat, format!("{cmd}: {version}")));- }- Ok(output) => {- let preview = String::from_utf8_lossy(&output.stderr)- .lines()- .next()- .unwrap_or("(failed)")- .to_string();- items.push(DiagnosticItem::warn(- cat,- format!("{cmd} not available ({preview})"),- ));- }- Err(err) => {- items.push(DiagnosticItem::warn(- cat,- format!("{cmd} not available ({err})"),- ));- }- }-}--pub(super) fn truncate_for_display(text: &str, max_len: usize) -> String {- if text.chars().count() <= max_len {- return text.to_string();- }-- let mut out = String::new();- for (idx, ch) in text.chars().enumerate() {- if idx >= max_len {- break;- }- out.push(ch);- }- out.push_str("...");- out-}--fn parse_rfc3339(input: &str) -> Option<DateTime<Utc>> {- DateTime::parse_from_rfc3339(input)- .ok()- .map(|dt| dt.with_timezone(&Utc))-}diff --git a/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rs b/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rsdeleted file mode 100644index 66d5c6717d..0000000000--- a/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rs+++ /dev/null@@ -1,290 +0,0 @@-//! Memory-engine, embedding-model, and Claude Agent SDK checks.--use crate::config::Config;--use super::daemon_env_checks::{truncate_for_display, COMMAND_VERSION_PREVIEW_CHARS};-use super::run::MemoryEngineCheck;-use super::types::DiagnosticItem;--/// Report the memory engine: which one is bound and whether it answers, or-/// why memory is off. Off is a warning, not an error: a signed-out user with-/// no CortexDB key has memory off by design.-pub(super) fn check_memory_engine(memory: &MemoryEngineCheck, items: &mut Vec<DiagnosticItem>) {- let cat = "memory_engine";- log::debug!(- "[doctor] check_memory_engine: engine={:?} status={}",- memory.engine,- memory.status- );- let engine = memory.engine.as_deref().unwrap_or("none");- let reason = memory.reason.as_deref().unwrap_or("no reason given");- items.push(match memory.status.as_str() {- "ok" => DiagnosticItem::ok(cat, format!("memory engine '{engine}' is serving")),- "degraded" => DiagnosticItem::warn(- cat,- format!("memory engine '{engine}' is degraded: {reason}"),- ),- "off" => DiagnosticItem::warn(cat, format!("memory is off: {reason}")),- _ => DiagnosticItem::error(cat, format!("memory engine '{engine}' is down: {reason}")),- });-}--// ── Embedding model health ───────────────────────────────────────--/// Probe the configured embedding provider and model.-///-/// - If the intended provider is not `"ollama"` (e.g. cloud): `Ok` — no-/// local daemon is involved and nothing to diagnose here.-/// - If Ollama is configured but the daemon at `<base_url>/api/tags` is-/// unreachable: `Error` with the pull command as the fix hint.-/// - If the daemon is reachable but the configured embedding model is not-/// listed in `/api/tags`: `Error` with `ollama pull <model>` guidance.-/// - If both daemon and model are healthy: `Ok`.-///-/// This check is synchronous (uses a small blocking HTTP call) so it fits-/// the existing `run()` contract. The timeout is capped at 3 s to avoid-/// stalling `openhuman doctor` on a very slow Ollama daemon.-pub(super) fn check_embedding_model_health(config: &Config, items: &mut Vec<DiagnosticItem>) {- let cat = "embedding_model";-- // Resolve the effective (intended, non-probed) embedding settings.- let local_embedding_model = config.workload_local_model("embeddings");- let (provider, model, _dims) = tinyinference_embeddings::catalog::effective_embedding_settings(- &config.memory.embedding_provider,- &config.memory.embedding_model,- config.memory.embedding_dimensions,- local_embedding_model.as_deref(),- );-- log::debug!("[doctor] check_embedding_model_health: provider={provider} model={model}");-- if provider != "ollama" {- // Cloud or custom provider — no local daemon to probe.- items.push(DiagnosticItem::ok(- cat,- format!("embedding provider: {provider} (model: {model}) — no local daemon required"),- ));- return;- }-- // Ollama path: probe reachability then model availability.- let base_url = tinyinference_local::ollama::ollama_base_url();- let tags_url = format!("{}/api/tags", base_url.trim_end_matches('/'));-- log::debug!("[doctor] probing ollama at {tags_url} for embedding model {model}");-- let client = match reqwest::blocking::Client::builder()- .timeout(std::time::Duration::from_secs(3))- .build()- {- Ok(c) => c,- Err(e) => {- items.push(DiagnosticItem::warn(- cat,- format!("could not build HTTP client for Ollama probe: {e}"),- ));- return;- }- };-- let resp = match client.get(&tags_url).send() {- Ok(r) => r,- Err(e) => {- items.push(DiagnosticItem::error(- cat,- format!(- "Ollama daemon unreachable at {base_url} — embedding model `{model}` cannot be used. \- Start Ollama, then run: ollama pull {model} (error: {e})"- ),- ));- return;- }- };-- if !resp.status().is_success() {- items.push(DiagnosticItem::error(- cat,- format!(- "Ollama /api/tags returned {} at {base_url} — cannot verify embedding model `{model}`. \- Start Ollama and run: ollama pull {model}",- resp.status()- ),- ));- return;- }-- // Parse the tags response and look for the configured model.- let body = match resp.text() {- Ok(t) => t,- Err(e) => {- items.push(DiagnosticItem::warn(- cat,- format!("Ollama /api/tags response could not be read: {e}"),- ));- return;- }- };-- // Parse the JSON and extract the `models` array. If the response is- // malformed or the schema changed (missing `models` key), report that- // explicitly instead of falling through to "model NOT installed".- let models_array = match serde_json::from_str::<serde_json::Value>(&body) {- Ok(v) => match v.get("models").and_then(|m| m.as_array()) {- Some(arr) => arr.clone(),- None => {- items.push(DiagnosticItem::warn(- cat,- format!(- "Ollama /api/tags response is missing the `models` key — \- cannot verify embedding model `{model}`. Ollama API may have changed."- ),- ));- return;- }- },- Err(e) => {- items.push(DiagnosticItem::warn(- cat,- format!(- "Ollama /api/tags returned invalid JSON — \- cannot verify embedding model `{model}`: {e}"- ),- ));- return;- }- };-- let model_found = models_array.iter().any(|entry| {- entry- .get("name")- .and_then(serde_json::Value::as_str)- .map(|name| model_matches(name, &model))- .unwrap_or(false)- });-- if model_found {- items.push(DiagnosticItem::ok(- cat,- format!("embedding model `{model}` is installed and reachable at {base_url}"),- ));- } else {- items.push(DiagnosticItem::error(- cat,- format!(- "embedding model `{model}` is NOT installed on Ollama at {base_url}. \- Run: ollama pull {model} (OpenHuman does not download models; pull it \- in your own Ollama)"- ),- ));- }-}--// ── Claude Agent SDK check ───────────────────────────────────────--pub(super) fn check_claude_agent_sdk(config: &Config, items: &mut Vec<DiagnosticItem>) {- let sdk = &config.claude_agent_sdk;- if !sdk.enabled {- return;- }-- tracing::debug!("probe:claude_agent_sdk:entry binary={}", sdk.binary);-- // Probe the configured binary by running `<binary> --version`.- let mut cmd = std::process::Command::new(&sdk.binary);- cmd.arg("--version")- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped());- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW- }-- tracing::debug!(- "probe:claude_agent_sdk:exec binary={} cmd=--version",- sdk.binary- );-- match cmd.output() {- Ok(output) if output.status.success() => {- let version = String::from_utf8_lossy(&output.stdout)- .lines()- .next()- .unwrap_or("(unknown version)")- .to_string();- tracing::info!(- "probe:claude_agent_sdk:ok binary={} version={}",- sdk.binary,- version- );- items.push(DiagnosticItem::ok(- "claude_agent_sdk",- format!("claude CLI found (binary='{}'): {version}", sdk.binary),- ));- tracing::debug!(- "probe:claude_agent_sdk:exit binary={} result=ok",- sdk.binary- );- }- Ok(output) => {- let stderr = String::from_utf8_lossy(&output.stderr);- let preview = stderr.lines().next().unwrap_or("(no stderr)");- tracing::warn!(- "probe:claude_agent_sdk:warn binary={} status={:?} stderr={}",- sdk.binary,- output.status,- truncate_for_display(preview, COMMAND_VERSION_PREVIEW_CHARS)- );- items.push(DiagnosticItem::warn(- "claude_agent_sdk",- format!(- "claude CLI execution failed (binary='{}', status={}). {}",- sdk.binary,- output.status,- truncate_for_display(preview, COMMAND_VERSION_PREVIEW_CHARS)- ),- ));- tracing::debug!(- "probe:claude_agent_sdk:exit binary={} result=warn",- sdk.binary- );- }- Err(err) => {- tracing::warn!(- "probe:claude_agent_sdk:warn binary={} err={}",- sdk.binary,- err- );- items.push(DiagnosticItem::warn(- "claude_agent_sdk",- format!(- "claude CLI not found or not executable (configured binary='{}'): {}. \- Install from https://claude.ai/code or set claude_agent_sdk.binary in config.",- sdk.binary, err- ),- ));- tracing::debug!(- "probe:claude_agent_sdk:exit binary={} result=warn",- sdk.binary- );- }- }-}--// ── Helpers ──────────────────────────────────────────────────────--pub(super) fn model_matches(installed: &str, configured: &str) -> bool {- if installed == configured {- return true;- }-- if installed.contains(':') && configured.contains(':') {- return false;- }-- model_base(installed) == model_base(configured)-}--fn model_base(model: &str) -> &str {- model.split(':').next().unwrap()-}diff --git a/crates/openhuman-core/src/platform/doctor/core/run.rs b/crates/openhuman-core/src/platform/doctor/core/run.rsdeleted file mode 100644index 4dc2e8e95b..0000000000--- a/crates/openhuman-core/src/platform/doctor/core/run.rs+++ /dev/null@@ -1,100 +0,0 @@-//! [`run`] and [`run_models`]: the doctor report's public entry points.--use anyhow::Result;--use crate::config::Config;--use super::config_checks::check_config_semantics;-use super::daemon_env_checks::{check_daemon_state, check_environment};-use super::memory_agent_checks::{- check_claude_agent_sdk, check_embedding_model_health, check_memory_engine,-};-use super::types::{- DiagnosticItem, DoctorReport, DoctorSummary, ModelProbeEntry, ModelProbeOutcome,- ModelProbeReport, ModelProbeSummary, Severity,-};-use super::workspace_checks::check_workspace;--/// The memory engine's status, taken by the async caller (engine health is-/// an HTTP call and [`run`] is blocking by contract).-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct MemoryEngineCheck {- /// The configured engine id.- pub engine: Option<String>,- /// `ok` | `degraded` | `down` | `off`.- pub status: String,- /// Why the status is not `ok`.- pub reason: Option<String>,-}--/// Build the full doctor report.-///-/// `ops::doctor_report` runs this in `tokio::task::spawn_blocking` because the-/// checks are synchronous and may touch the file system, sqlite, or local HTTP-/// endpoints. Keep this function blocking-only; add async probes in the caller-/// (as `memory` is) instead of introducing `.await` here.-pub fn run(config: &Config, memory: MemoryEngineCheck) -> Result<DoctorReport> {- let mut items: Vec<DiagnosticItem> = Vec::new();-- check_config_semantics(config, &mut items);- check_workspace(config, &mut items);- check_daemon_state(config, &mut items);- check_environment(&mut items);- check_memory_engine(&memory, &mut items);- check_embedding_model_health(config, &mut items);- check_claude_agent_sdk(config, &mut items);-- let errors = items- .iter()- .filter(|i| i.severity == Severity::Error)- .count();- let warnings = items- .iter()- .filter(|i| i.severity == Severity::Warn)- .count();- let ok = items.iter().filter(|i| i.severity == Severity::Ok).count();-- Ok(DoctorReport {- items,- summary: DoctorSummary {- ok,- warnings,- errors,- },- })-}--fn doctor_model_targets() -> Vec<String> {- crate::inference::provider::list_providers()- .into_iter()- .map(|provider| provider.name.to_string())- .collect()-}--pub fn run_models(_config: &Config, _use_cache: bool) -> Result<ModelProbeReport> {- let targets = doctor_model_targets();-- if targets.is_empty() {- anyhow::bail!("No providers available for model probing");- }-- let skipped_count = targets.len();- let entries = targets- .into_iter()- .map(|provider| ModelProbeEntry {- provider,- outcome: ModelProbeOutcome::Skipped,- message: Some("model catalog refresh removed".to_string()),- })- .collect();-- Ok(ModelProbeReport {- entries,- summary: ModelProbeSummary {- ok: 0,- skipped: skipped_count,- auth_or_access: 0,- errors: 0,- },- })-}diff --git a/crates/openhuman-core/src/platform/doctor/core/types.rs b/crates/openhuman-core/src/platform/doctor/core/types.rsdeleted file mode 100644index 4d95b3e4be..0000000000--- a/crates/openhuman-core/src/platform/doctor/core/types.rs+++ /dev/null@@ -1,85 +0,0 @@-//! The doctor report's data shapes: diagnostic severities, entries, and the-//! model-probe report types.--use serde::{Deserialize, Serialize};--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum Severity {- Ok,- Warn,- Error,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct DiagnosticItem {- pub severity: Severity,- pub category: String,- pub message: String,-}--impl DiagnosticItem {- pub(crate) fn ok(category: impl Into<String>, msg: impl Into<String>) -> Self {- Self {- severity: Severity::Ok,- category: category.into(),- message: msg.into(),- }- }- pub(crate) fn warn(category: impl Into<String>, msg: impl Into<String>) -> Self {- Self {- severity: Severity::Warn,- category: category.into(),- message: msg.into(),- }- }- pub(crate) fn error(category: impl Into<String>, msg: impl Into<String>) -> Self {- Self {- severity: Severity::Error,- category: category.into(),- message: msg.into(),- }- }-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct DoctorSummary {- pub ok: usize,- pub warnings: usize,- pub errors: usize,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct DoctorReport {- pub items: Vec<DiagnosticItem>,- pub summary: DoctorSummary,-}--// ── Public entry point ───────────────────────────────────────────-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum ModelProbeOutcome {- Ok,- Skipped,- AuthOrAccess,- Error,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ModelProbeEntry {- pub provider: String,- pub outcome: ModelProbeOutcome,- pub message: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ModelProbeSummary {- pub ok: usize,- pub skipped: usize,- pub auth_or_access: usize,- pub errors: usize,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ModelProbeReport {- pub entries: Vec<ModelProbeEntry>,- pub summary: ModelProbeSummary,-}diff --git a/crates/openhuman-core/src/platform/doctor/core/workspace_checks.rs b/crates/openhuman-core/src/platform/doctor/core/workspace_checks.rsdeleted file mode 100644index 7f83e7ca2f..0000000000--- a/crates/openhuman-core/src/platform/doctor/core/workspace_checks.rs+++ /dev/null@@ -1,176 +0,0 @@-//! Workspace integrity: [`check_workspace`] and its disk-space and probe-path-//! helpers.--use std::io::Write;-use std::path::Path;--use crate::config::Config;--use super::types::DiagnosticItem;--pub(super) fn check_workspace(config: &Config, items: &mut Vec<DiagnosticItem>) {- let cat = "workspace";- let ws = &config.workspace_dir;-- if ws.exists() {- items.push(DiagnosticItem::ok(- cat,- format!("directory exists: {}", ws.display()),- ));- } else {- items.push(DiagnosticItem::error(- cat,- format!("directory missing: {}", ws.display()),- ));- return;- }-- // Writable check- let probe = workspace_probe_path(ws);- match std::fs::OpenOptions::new()- .write(true)- .create_new(true)- .open(&probe)- {- Ok(mut probe_file) => {- let write_result = probe_file.write_all(b"probe");- drop(probe_file);- let _ = std::fs::remove_file(&probe);- match write_result {- Ok(()) => items.push(DiagnosticItem::ok(cat, "directory is writable")),- Err(e) => items.push(DiagnosticItem::error(- cat,- format!("directory write probe failed: {e}"),- )),- }- }- Err(e) => {- items.push(DiagnosticItem::error(- cat,- format!("directory is not writable: {e}"),- ));- }- }-- // Minimal workspace folders- let mem_dir = ws.join("memory");- if mem_dir.exists() {- items.push(DiagnosticItem::ok(- cat,- format!("memory directory: {}", mem_dir.display()),- ));- } else {- items.push(DiagnosticItem::warn(- cat,- format!("memory directory missing: {}", mem_dir.display()),- ));- }-- // Check for config templates or docs- let prompt = ws.join("SYSTEM.md");- if prompt.exists() {- items.push(DiagnosticItem::ok(- cat,- format!("SYSTEM prompt: {}", prompt.display()),- ));- } else {- items.push(DiagnosticItem::warn(- cat,- format!("SYSTEM prompt missing: {}", prompt.display()),- ));- }-- // Disk space warning (best-effort)- if let Some(avail_mb) = available_disk_space_mb(ws) {- if avail_mb < 512 {- items.push(DiagnosticItem::warn(- cat,- format!("low disk space: {avail_mb} MB free"),- ));- } else {- items.push(DiagnosticItem::ok(- cat,- format!("disk space OK: {avail_mb} MB free"),- ));- }- }-}--fn available_disk_space_mb(path: &Path) -> Option<u64> {- #[cfg(target_os = "windows")]- {- available_disk_space_mb_windows(path)- }-- #[cfg(not(target_os = "windows"))]- {- let output = std::process::Command::new("df")- .arg("-m")- .arg(path)- .output()- .ok()?;- if !output.status.success() {- return None;- }- let stdout = String::from_utf8_lossy(&output.stdout);- parse_df_available_mb(&stdout)- }-}--#[cfg(not(target_os = "windows"))]-fn parse_df_available_mb(stdout: &str) -> Option<u64> {- let line = stdout.lines().rev().find(|line| !line.trim().is_empty())?;- let avail = line.split_whitespace().nth(3)?;- avail.parse::<u64>().ok()-}--#[cfg(target_os = "windows")]-fn available_disk_space_mb_windows(path: &Path) -> Option<u64> {- use std::path::{Component, Prefix};-- let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());- let letter = canonical.components().find_map(|c| match c {- Component::Prefix(pc) => match pc.kind() {- Prefix::Disk(b) | Prefix::VerbatimDisk(b) => Some((b as char).to_ascii_uppercase()),- _ => None,- },- _ => None,- })?;-- // PowerShell is ubiquitous on supported Windows; `Get-PSDrive` needs no admin- // and returns free bytes as a single integer line.- let script = format!("(Get-PSDrive -Name {letter} -ErrorAction Stop).Free");- let mut cmd = std::process::Command::new("powershell");- cmd.args([- "-NoProfile",- "-NonInteractive",- "-ExecutionPolicy",- "Bypass",- "-Command",- &script,- ]);- {- use std::os::windows::process::CommandExt;- cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW- }- let output = cmd.output().ok()?;- if !output.status.success() {- return None;- }- let bytes: u64 = String::from_utf8_lossy(&output.stdout)- .trim()- .parse()- .ok()?;- Some(bytes / (1024 * 1024))-}--fn workspace_probe_path(workspace_dir: &Path) -> std::path::PathBuf {- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map_or(0, |duration| duration.as_nanos());- workspace_dir.join(format!(- ".openhuman_doctor_probe_{}_{}",- std::process::id(),- nanos- ))-}diff --git a/crates/openhuman-core/src/platform/doctor/core_tests.rs b/crates/openhuman-core/src/platform/doctor/core_tests.rsdeleted file mode 100644index 5740871f7f..0000000000--- a/crates/openhuman-core/src/platform/doctor/core_tests.rs+++ /dev/null@@ -1,76 +0,0 @@-use super::*;-use tempfile::TempDir;--use crate::config::Config;-fn test_config_in(tmp: &TempDir) -> Config {- let mut cfg = Config::default();- cfg.workspace_dir = tmp.path().to_path_buf();- cfg-}--#[test]-fn config_validation_warns_no_channels() {- let config = Config::default();- let mut items = vec![];- check_config_semantics(&config, &mut items);- let ch_item = items.iter().find(|i| i.message.contains("channel"));- assert!(ch_item.is_some());- assert_eq!(ch_item.unwrap().severity, Severity::Warn);-}--#[test]-fn truncate_for_display_short() {- let s = "hello";- assert_eq!(truncate_for_display(s, 10), s);-}--#[test]-fn truncate_for_display_long() {- let s = "abcdefghijklmnopqrstuvwxyz";- let truncated = truncate_for_display(s, 5);- assert!(truncated.starts_with("abcde"));- assert!(truncated.ends_with("..."));-}--#[test]-fn embedding_provider_validation_accepts_standard_values() {- assert_eq!(embedding_provider_validation_error("none"), None);- assert_eq!(embedding_provider_validation_error("openai"), None);- assert_eq!(- embedding_provider_validation_error("custom:https://example.com"),- None- );-}--#[test]-fn embedding_provider_validation_rejects_empty_custom_url() {- let err = embedding_provider_validation_error("custom: ").expect("should fail");- assert!(err.contains("non-empty URL"), "{err}");-}--#[test]-fn embedding_provider_validation_rejects_non_http_scheme() {- let err = embedding_provider_validation_error("custom:file:///tmp/model").expect("should fail");- assert!(err.contains("http/https"), "{err}");-}--#[test]-fn embedding_provider_validation_rejects_malformed_url() {- let err = embedding_provider_validation_error("custom:not a url").expect("should fail");- assert!(err.contains("invalid custom provider URL"), "{err}");-}--#[test]-fn model_matches_accepts_exact_and_tagged_variants() {- assert!(model_matches("bge-m3", "bge-m3"));- assert!(model_matches("bge-m3:latest", "bge-m3"));- assert!(model_matches("bge-m3", "bge-m3:latest"));- assert!(model_matches("bge-m3:v1.0", "bge-m3"));-}--#[test]-fn model_matches_rejects_different_base_models() {- assert!(!model_matches("nomic-embed-text:latest", "bge-m3"));- assert!(!model_matches("bge-m3:latest", "nomic-embed-text"));- assert!(!model_matches("bge-m3:latest", "bge-m3:v1.0"));-}diff --git a/crates/openhuman-core/src/platform/doctor/mod.rs b/crates/openhuman-core/src/platform/doctor/mod.rsdeleted file mode 100644index 51c75297d6..0000000000--- a/crates/openhuman-core/src/platform/doctor/mod.rs+++ /dev/null@@ -1,18 +0,0 @@-//! Diagnostic checks for OpenHuman configuration, workspace health, and daemon state.--mod core;-pub mod ops;-mod schemas;-pub mod tools;--pub use core::*;-pub use ops as rpc;-pub use ops::*;-pub(crate) use schemas::all_controller_entries as all_doctor_controller_entries;-pub use schemas::{- all_controller_schemas as all_doctor_controller_schemas,- all_registered_controllers as all_doctor_registered_controllers,-};--#[cfg(test)]-pub(crate) use schemas::doctor_parameter_contracts;diff --git a/crates/openhuman-core/src/platform/doctor/ops.rs b/crates/openhuman-core/src/platform/doctor/ops.rsdeleted file mode 100644index 280b83e8c2..0000000000--- a/crates/openhuman-core/src/platform/doctor/ops.rs+++ /dev/null@@ -1,47 +0,0 @@-//! JSON-RPC / CLI controller surface for diagnostics.-//!-//! Also the home of the async probes [`doctor::run`] cannot take itself. It is-//! blocking by contract (see its docs), so anything that has to be `await`ed-//! is resolved here and passed down as a value.--use crate::config::Config;-use crate::core::Outcome;-use crate::platform::doctor::{self, DoctorReport, MemoryEngineCheck, ModelProbeReport};--pub async fn doctor_report(config: &Config) -> Result<Outcome<DoctorReport>, String> {- // Awaited before the blocking hop, not inside it: `doctor::run` may not- // `.await`. See `MemoryEngineCheck`.- let memory = memory_engine_check(config).await;-- // `doctor::run` calls `check_embedding_model_health` which uses- // `reqwest::blocking::Client` — that panics inside a tokio runtime.- // Move the entire sync `run()` onto a blocking thread.- let config_clone = config.clone();- let report = tokio::task::spawn_blocking(move || doctor::run(&config_clone, memory))- .await- .map_err(|e| format!("doctor task join error: {e}"))?- .map_err(|e| e.to_string())?;- Ok(Outcome::single_log(report, "doctor report generated"))-}--/// The memory engine's status for the doctor report.-async fn memory_engine_check(config: &Config) -> MemoryEngineCheck {- let view = crate::memory::ops::engine_get(config).await;- let status = serde_json::to_value(view.status)- .ok()- .and_then(|value| value.as_str().map(str::to_string))- .unwrap_or_else(|| "down".to_string());- MemoryEngineCheck {- engine: view.engine,- status,- reason: view.reason,- }-}--pub async fn doctor_models(- config: &Config,- use_cache: bool,-) -> Result<Outcome<ModelProbeReport>, String> {- let report = doctor::run_models(config, use_cache).map_err(|e| e.to_string())?;- Ok(Outcome::single_log(report, "model probes completed"))-}diff --git a/crates/openhuman-core/src/platform/doctor/tools_tests.rs b/crates/openhuman-core/src/platform/doctor/tools_tests.rsdeleted file mode 100644index bbdca43eb7..0000000000--- a/crates/openhuman-core/src/platform/doctor/tools_tests.rs+++ /dev/null@@ -1,17 +0,0 @@-use super::*;-use tinytools::{PermissionLevel, ToolScope};--fn cfg() -> Arc<Config> {- Arc::new(Config::default())-}--#[test]-fn metadata() {- assert_eq!(DoctorHealthTool::new(cfg()).name(), "doctor_health");- assert_eq!(DoctorModelsTool::new(cfg()).name(), "doctor_models");- assert_eq!(- DoctorHealthTool::new(cfg()).permission_level(),- PermissionLevel::ReadOnly- );- assert_eq!(DoctorHealthTool::new(cfg()).scope(), ToolScope::All);-}diff --git a/crates/openhuman-core/src/platform/mod.rs b/crates/openhuman-core/src/platform/mod.rsindex b93c8105bb..c612c4db49 100644--- a/crates/openhuman-core/src/platform/mod.rs+++ b/crates/openhuman-core/src/platform/mod.rs@@ -7,7 +7,6 @@pub mod about_app;pub mod connectivity;pub mod cost;-pub mod doctor;pub mod health;pub mod llm_gate;pub mod proc_metrics;diff --git a/crates/openhuman-core/src/platform/service/README.md b/crates/openhuman-core/src/platform/service/README.mdindex 277ed89467..3f9042a09c 100644--- a/crates/openhuman-core/src/platform/service/README.md+++ b/crates/openhuman-core/src/platform/service/README.md@@ -10,7 +10,6 @@ Service-management domain for the OpenHuman core daemon. It installs/uninstalls- Resolve the daemon executable to launch (env override `OPENHUMAN_CORE_BIN`, else sibling `openhuman-core[-*]` next to the current exe; macOS also searches `../Resources`).- Persist and read daemon-host UI preferences (`show_tray`) next to the main config.- Provide a deterministic, file-backed **mock** service backend for E2E tests (`OPENHUMAN_SERVICE_MOCK`).-- Expose `daemon_state.json` path helper consumed by doctor/health reporting.## Key files@@ -27,7 +26,6 @@ Service-management domain for the OpenHuman core daemon. It installs/uninstalls| `crates/openhuman-core/src/platform/service/macos.rs` | LaunchAgent (`com.openhuman.core.plist`) install/start/stop/status/uninstall via `launchctl`; migrates legacy labels. || `crates/openhuman-core/src/platform/service/linux.rs` | systemd user-unit install/lifecycle via `systemctl --user`. || `crates/openhuman-core/src/platform/service/windows.rs` | Scheduled-task install/lifecycle via `schtasks`. |-| `crates/openhuman-core/src/platform/service/daemon.rs` | `state_file_path(config)` → `<config_dir>/daemon_state.json`, used by doctor/health. || `crates/openhuman-core/src/platform/service/daemon_host.rs` | `DaemonHostConfig { show_tray }` + async `load_for_config_dir` / `save_for_config_dir` (JSON next to config, `daemon_host_config.json`). || `crates/openhuman-core/src/platform/service/mock.rs` | File-backed deterministic mock backend gated on `OPENHUMAN_SERVICE_MOCK`; supports forced failures and an `agent_running` flag (`mock_agent_running`). || `crates/openhuman-core/src/platform/service/mock_tests.rs` | Sibling test suite for [`mock.rs`](./mock.rs). |@@ -42,7 +40,7 @@ From [`mod.rs`](./mod.rs) re-exports:- `restart::{apply_startup_restart_delay_from_env, RestartStatus}` (and `restart::trigger_self_restart_now` via the `restart` module path).- `shutdown::ShutdownStatus`.- `schemas::all_service_controller_schemas` / `all_service_registered_controllers`.-- `daemon::state_file_path`, `daemon_host::{DaemonHostConfig, …}` (via their `pub mod` paths).+- `daemon_host::{DaemonHostConfig, …}` (via its `pub mod` path).## RPC / controllers@@ -79,7 +77,6 @@ Both subscribers are registered idempotently from `crates/openhuman-core/src/cor## Persistence- Daemon-host prefs: `daemon_host_config.json` next to the main config (`DaemonHostConfig { show_tray }`, default `true`); read/written async by [`daemon_host.rs`](./daemon_host.rs).-- Daemon state path: `daemon_state.json` next to config (`daemon::state_file_path`), consumed by doctor/health (not written here).- Service unit files: written by the per-OS impls (macOS plist in `~/Library/LaunchAgents`, Linux systemd user unit, Windows scheduled task).- Mock state: `service-mock-state.json` (overridable via `OPENHUMAN_SERVICE_MOCK_STATE_FILE`) tracking `installed`/`running`/`agent_running`/forced `failures`, only when the mock is enabled.@@ -95,7 +92,6 @@ Both subscribers are registered idempotently from `crates/openhuman-core/src/cor- `crates/openhuman-core/src/core/all.rs`: registers the service controllers (`all_service_registered_controllers`).- `crates/openhuman-core/src/core/runtime/subscribers.rs`: registers the restart/shutdown event-bus subscribers at startup.-- `crates/openhuman-core/src/platform/doctor/core.rs`: reads `service::daemon::state_file_path`.- `crates/openhuman-core/src/platform/update/ops.rs` (`rpc::service_restart` after a self-replace), `crates/openhuman-core/src/config/ops/loader/runtime_flags.rs` (`mock::mock_agent_running`), `crates/openhuman-core/src/desktop/app_state/ops/{types,runtime_snapshot}.rs` (`ServiceState`/`ServiceStatus`, `status`): call into `crate::platform::service`.- `crates/openhuman-core/src/tools/mod.rs`: re-exports `platform::service::tools::*`.- `lib.rs`: module wiring.@@ -110,7 +106,6 @@ Both subscribers are registered idempotently from `crates/openhuman-core/src/cor- `OPENHUMAN_SERVICE_MOCK` short-circuits **every** lifecycle dispatcher to the file-backed mock: used for deterministic E2E; it can also inject forced per-operation failures.- Windows command spawns set `CREATE_NO_WINDOW` (`common::no_window`) so polled `schtasks /Query` calls don't flash a console.- Lifecycle RPCs are deliberately **not** unit-tested (they mutate real OS state or kill the process); RPC-adapter coverage lives in `tests/json_rpc_e2e.rs`. `daemon_host_get`/`set` and the restart/shutdown publish paths are unit-tested.-- `daemon.rs::state_file_path` and `common.rs::state_file_path` (mock) both compute paths next to config but for different files (`daemon_state.json` vs the mock state file).## Further readingdiff --git a/crates/openhuman-core/src/platform/service/daemon.rs b/crates/openhuman-core/src/platform/service/daemon.rsdeleted file mode 100644index 3b4b0ef2a5..0000000000--- a/crates/openhuman-core/src/platform/service/daemon.rs+++ /dev/null@@ -1,11 +0,0 @@-use crate::config::Config;-use std::path::PathBuf;--/// Shared daemon state file path used by health/doctor reporting.-pub fn state_file_path(config: &Config) -> PathBuf {- config- .config_path- .parent()- .map_or_else(|| PathBuf::from("."), PathBuf::from)- .join("daemon_state.json")-}diff --git a/crates/openhuman-core/src/platform/service/mod.rs b/crates/openhuman-core/src/platform/service/mod.rsindex 19b6cd8308..638ecc812f 100644--- a/crates/openhuman-core/src/platform/service/mod.rs+++ b/crates/openhuman-core/src/platform/service/mod.rs@@ -2,7 +2,6 @@pub mod bus;mod core;-pub mod daemon;pub mod daemon_host;pub mod ops;mod restart;diff --git a/crates/openhuman-core/src/platform/socket/manager.rs b/crates/openhuman-core/src/platform/socket/manager.rsindex 51380a5172..4393522156 100644--- a/crates/openhuman-core/src/platform/socket/manager.rs+++ b/crates/openhuman-core/src/platform/socket/manager.rs@@ -87,6 +87,25 @@ pub(super) struct SharedState {pub(super) loop_stopped_on_failure: AtomicBool,}+impl SharedState {+ /// Publish an identity and its status as one readable snapshot.+ ///+ /// Readers take `connection_identity` before `status` and hold the+ /// identity guard through the status read. Keep both writes under that+ /// same identity lock so they cannot observe a new owner with its+ /// predecessor's status.+ pub(super) fn set_connection_snapshot(+ &self,+ identity: Option<(String, String)>,+ status: ConnectionStatus,+ ) {+ let mut current_identity = self.connection_identity.write();+ let mut current_status = self.status.write();+ *current_identity = identity;+ *current_status = status;+ }+}+/// The connection's readiness flag, guarded by a lock so a reader can hold the/// flag `true` across the send it authorises.///@@ -294,6 +313,7 @@ impl SocketManager {/// was handed at spawn — a provider that refreshes the session mid-loop/// keeps matching instead of forcing a pointless reconnect.pub fn is_live_for(&self, url: &str, token: &str) -> bool {+ let identity = self.shared.connection_identity.read();let status = *self.shared.status.read();let serving = match status {ConnectionStatus::Connected => true,@@ -301,14 +321,48 @@ impl SocketManager {_ => false,};serving- && self- .shared- .connection_identity- .read()+ && identity.as_ref().is_some_and(|(u, t)| u == url && t == token)}+ /// Return the stored status only when it belongs to exactly `url` and+ /// `token`, including terminal and reconnecting states.+ ///+ /// Diagnostics that inspect a selected profile use this instead of+ /// `get_state()`, whose process-global status may describe another+ /// account. Unlike [`Self::is_live_for`], this preserves an owner's+ /// `Error`, `Reconnecting`, and `Disconnected` status for readiness+ /// reporting; no matching identity returns `None`.+ pub fn status_for(&self, url: &str, token: &str) -> Option<ConnectionStatus> {+ self.status_for_with_observer(url, token, || {})+ }++ fn status_for_with_observer(+ &self,+ url: &str,+ token: &str,+ after_status_snapshot: impl FnOnce(),+ ) -> Option<ConnectionStatus> {+ let identity = self.shared.connection_identity.read();+ let status = *self.shared.status.read();+ after_status_snapshot();+ identity+ .as_ref()+ .is_some_and(|(active_url, active_token)| active_url == url && active_token == token)+ .then_some(status)+ }++ #[cfg(test)]+ fn status_for_with_snapshot_observer(+ &self,+ url: &str,+ token: &str,+ after_status_snapshot: impl FnOnce(),+ ) -> Option<ConnectionStatus> {+ self.status_for_with_observer(url, token, after_status_snapshot)+ }+// -----------------------------------------------------------------------// Connection lifecycle// -----------------------------------------------------------------------@@ -405,11 +459,11 @@ impl SocketManager {// agree, or the guard could match on a credential this connection never// used. `ws_loop` rewrites it before every attempt, so a token refreshed// mid-session replaces this seed rather than going stale behind it.- *self.shared.connection_identity.write() = Some((url.to_string(), token));+ self.shared+ .set_connection_snapshot(Some((url.to_string(), token)), ConnectionStatus::Connecting);log::info!("[socket] Connecting to {}", url);- *self.shared.status.write() = ConnectionStatus::Connecting;*self.shared.error.write() = None;emit_state_change(&self.shared);@@ -472,10 +526,10 @@ impl SocketManager {self.shared.loop_stopped_on_failure.store(false, Ordering::Release);- *self.shared.status.write() = ConnectionStatus::Disconnected;+ self.shared+ .set_connection_snapshot(None, ConnectionStatus::Disconnected);*self.shared.socket_id.write() = None;*self.shared.error.write() = None;- *self.shared.connection_identity.write() = None;emit_state_change(&self.shared);log::debug!("[socket] Disconnected");Ok(())diff --git a/crates/openhuman-core/src/platform/socket/manager_tests.rs b/crates/openhuman-core/src/platform/socket/manager_tests.rsindex c60a133d5a..8c4f08b99a 100644--- a/crates/openhuman-core/src/platform/socket/manager_tests.rs+++ b/crates/openhuman-core/src/platform/socket/manager_tests.rs@@ -39,6 +39,70 @@ fn is_connected_tracks_status_transitions() {assert!(!mgr.is_connected());}+#[test]+fn status_for_preserves_owner_status_but_rejects_foreign_and_retired_identities() {+ let manager = SocketManager::new();+ let url = "https://backend-b.example/socket.io";+ let token = "session-b";+ *manager.shared.connection_identity.write() = Some((url.to_owned(), token.to_owned()));++ for status in [+ ConnectionStatus::Disconnected,+ ConnectionStatus::Connecting,+ ConnectionStatus::Connected,+ ConnectionStatus::Reconnecting,+ ConnectionStatus::Error,+ ] {+ *manager.shared.status.write() = status;+ assert_eq!(manager.status_for(url, token), Some(status));+ assert_eq!(+ manager.status_for("https://backend-a.example/socket.io", token),+ None+ );+ assert_eq!(manager.status_for(url, "session-a"), None);+ }++ *manager.shared.connection_identity.write() = None;+ assert_eq!(manager.status_for(url, token), None);+}++#[test]+fn status_for_does_not_pair_a_stale_status_with_a_new_owner() {+ let manager = SocketManager::new();+ let url_a = "https://backend-a.example/socket.io";+ let token_a = "session-a";+ let url_b = "https://backend-b.example/socket.io";+ let token_b = "session-b";+ *manager.shared.connection_identity.write() = Some((url_a.to_owned(), token_a.to_owned()));+ *manager.shared.status.write() = ConnectionStatus::Connected;+ let mut transitioned_in_observer = false;++ let status = manager.status_for_with_snapshot_observer(url_b, token_b, || {+ if let Some(mut owner) = manager.shared.connection_identity.try_write() {+ // Model disconnect(A) followed by the start of connect(B) in the+ // gap between reading status and attributing it to an identity.+ *owner = Some((url_b.to_owned(), token_b.to_owned()));+ *manager.shared.status.write() = ConnectionStatus::Disconnected;+ transitioned_in_observer = true;+ }+ });++ assert_eq!(+ status, None,+ "A's Connected state must not be reported for B"+ );+ if !transitioned_in_observer {+ // The fixed implementation holds the read guard through the injected+ // interleaving point, so complete B's simulated start after the query.+ *manager.shared.status.write() = ConnectionStatus::Disconnected;+ *manager.shared.connection_identity.write() = Some((url_b.to_owned(), token_b.to_owned()));+ }+ assert_eq!(+ manager.status_for(url_b, token_b),+ Some(ConnectionStatus::Disconnected)+ );+}+#[test]fn get_state_reflects_stored_sid_and_status() {let mgr = SocketManager::new();diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rsindex b57738b087..783d2ec3b3 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs@@ -161,8 +161,10 @@ pub(crate) async fn ws_loop(// would otherwise leave `SocketManager::is_live_for` comparing against// the token this loop was spawned with and tearing down a healthy socket// on the next connect (#6181).- *shared.connection_identity.write() = Some((url.clone(), token.clone()));- *shared.status.write() = ConnectionStatus::Connecting;+ shared.set_connection_snapshot(+ Some((url.clone(), token.clone())),+ ConnectionStatus::Connecting,+ );emit_state_change(&shared);// Taken before the attempt so a stalled first dial counts toward thediff --git a/crates/openhuman-core/src/profiles/doctor.rs b/crates/openhuman-core/src/profiles/doctor.rsnew file mode 100644index 0000000000..71f22da0ba--- /dev/null+++ b/crates/openhuman-core/src/profiles/doctor.rs@@ -0,0 +1,238 @@+//! SaaS profile selection and read-only inputs for doctor.++use std::future::Future;+use std::sync::Arc;++use async_trait::async_trait;++use crate::config::Config;+use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx};+use crate::doctor::{DoctorCheck, DoctorCheckSource, DoctorCtx, DoctorTier, Finding};+use crate::tools::toolpacks::ToolGroups;++use super::host::{self, ProfileHost};+use super::types::ProfileId;++/// The SaaS caller that has already passed the existing dispatch scope guard.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum DoctorCaller {+ Operator,+ Tenant(ProfileId),+}++/// A selected tenant's forced config and no-store diagnostic context.+#[derive(Clone)]+pub(crate) struct TenantDoctorTarget {+ pub profile_id: ProfileId,+ pub config: Config,+ pub context: Arc<CoreContext>,+}++impl std::fmt::Debug for TenantDoctorTarget {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("TenantDoctorTarget")+ .field("profile_id", &self.profile_id)+ .finish_non_exhaustive()+ }+}++/// The safe result of reading the tenant registry and lease for diagnostics.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum DoctorProfileState {+ Unprovisioned,+ Ready,+ HeldElsewhere,+ Unavailable,+}++/// Authorizes a requested tenant before invoking the sole loader for profile+/// registry, config, credential, or lease data.+pub(crate) async fn resolve_with_loader<T, F, Fut>(+ caller: Option<DoctorCaller>,+ requested: Option<&str>,+ load: F,+) -> Result<Option<T>, String>+where+ F: FnOnce(ProfileId) -> Fut,+ Fut: Future<Output = Result<T, String>>,+{+ let selected = match caller {+ None => return Err("doctor requires an authorized SaaS scope".into()),+ Some(DoctorCaller::Operator) => requested.map(parse_requested_profile).transpose()?,+ Some(DoctorCaller::Tenant(own_profile)) => {+ if let Some(requested) = requested {+ let requested = parse_requested_profile(requested)?;+ if requested != own_profile {+ return Err("a tenant may only run doctor for its own profile".into());+ }+ }+ Some(own_profile)+ }+ };++ match selected {+ Some(profile_id) => load(profile_id).await.map(Some),+ None => Ok(None),+ }+}++/// Resolves the optional SaaS doctor target. The report handler calls this+/// before loading config; an operator without `profile` keeps the normal+/// operator config path, while a tenant always targets its own profile.+pub(crate) async fn resolve_target(+ dispatch: &DispatchCtx,+ requested: Option<&str>,+) -> Result<Option<TenantDoctorTarget>, String> {+ if !crate::core::runtime::is_saas() {+ return Ok(None);+ }++ let tenant = dispatch.tenant().ok();+ let caller = match (super::surface::current_scope(), tenant) {+ (super::surface::Scope::Operator, Some(tenant)) if tenant.profile.is_none() => {+ Some(DoctorCaller::Operator)+ }+ (super::surface::Scope::User, Some(tenant)) => tenant+ .profile+ .and_then(|profile| ProfileId::parse(&profile).ok().map(DoctorCaller::Tenant)),+ _ => None,+ };++ resolve_with_loader(caller, requested, |profile_id| async move {+ let host =+ host::host().ok_or_else(|| "SaaS profile inspection is unavailable".to_string())?;+ host.target_for_doctor(&profile_id)+ })+ .await+}++fn parse_requested_profile(raw: &str) -> Result<ProfileId, String> {+ ProfileId::parse(raw).map_err(|_| "profile id is invalid".to_string())+}++/// Builds the tenant config and a diagnostic-only context without opening a+/// profile, taking its lease, or creating its workspace.+impl ProfileHost {+ pub(crate) fn target_for_doctor(+ &self,+ profile_id: &ProfileId,+ ) -> Result<TenantDoctorTarget, String> {+ let config = self.serving_config(&self.layout_of(profile_id), profile_id)?;+ let overlay = ContextOverlay::new(+ config.clone(),+ super::host::user_domains(),+ ToolGroups::none(),+ )+ .without_user_skill_roots()+ .profile(profile_id.as_str());+ let context = self.operator.derive_for_inspection(overlay);+ Ok(TenantDoctorTarget {+ profile_id: profile_id.clone(),+ config,+ context,+ })+ }++ /// Reads provision and lease readiness without creating collections or+ /// taking over a profile's lease.+ pub(crate) async fn inspect_for_doctor(&self, profile_id: &ProfileId) -> DoctorProfileState {+ match self.registry.get_readonly(profile_id).await {+ Ok(Some(_)) => {}+ Ok(None) => return DoctorProfileState::Unprovisioned,+ Err(_) => return DoctorProfileState::Unavailable,+ }++ let now = super::lease::now_ms();+ match self.leases.holder_readonly(profile_id.as_str()).await {+ Ok(Some(record)) if record.is_live(now) && record.owner != self.node => {+ DoctorProfileState::HeldElsewhere+ }+ Ok(_) => DoctorProfileState::Ready,+ Err(_) => DoctorProfileState::Unavailable,+ }+ }+}++/// Emits the safe operator-facing result for `profile/provisioned`.+pub(crate) fn profile_provisioned_finding(state: DoctorProfileState) -> Finding {+ match state {+ DoctorProfileState::Ready => Finding::pass(+ "profile/provisioned",+ "The tenant profile is provisioned and available on this node.",+ ),+ DoctorProfileState::Unprovisioned => Finding::error(+ "profile/provisioned",+ "The tenant profile is not provisioned.",+ "Provision the tenant profile through the normal profile management flow, then rerun doctor.",+ ),+ DoctorProfileState::HeldElsewhere => Finding::error(+ "profile/provisioned",+ "The tenant profile is currently held by another node.",+ "Run doctor on the node holding this profile, or retry after its lease is released.",+ ),+ DoctorProfileState::Unavailable => Finding::error(+ "profile/provisioned",+ "The tenant profile registry or lease could not be verified safely.",+ "Check profile storage and complete any required storage migration before rerunning doctor.",+ ),+ }+}++struct ProfileProvisionedCheck {+ host: Arc<ProfileHost>,+}++#[async_trait]+impl DoctorCheck for ProfileProvisionedCheck {+ fn id(&self) -> &str {+ "profile/provisioned"+ }++ fn category(&self) -> &str {+ "Profile"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let Some(profile) = ctx.profile() else {+ return vec![Finding::skipped(+ self.id(),+ "No tenant profile was selected for this report.",+ "Pass a tenant profile id to inspect SaaS profile readiness.",+ )];+ };+ let state = match ProfileId::parse(profile) {+ Ok(profile_id) => self.host.inspect_for_doctor(&profile_id).await,+ Err(_) => DoctorProfileState::Unavailable,+ };+ vec![profile_provisioned_finding(state)]+ }+}++struct ProfileDoctorCheckSource {+ host: Arc<ProfileHost>,+}++impl DoctorCheckSource for ProfileDoctorCheckSource {+ fn id(&self) -> &str {+ "profiles-doctor"+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(ProfileProvisionedCheck {+ host: Arc::clone(&self.host),+ })]+ }+}++pub(crate) fn register_check_source(host: Arc<ProfileHost>) {+ crate::doctor::register_check_source(ProfileDoctorCheckSource { host });+}++#[cfg(test)]+#[path = "doctor_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/profiles/doctor_tests.rs b/crates/openhuman-core/src/profiles/doctor_tests.rsnew file mode 100644index 0000000000..29d01380ea--- /dev/null+++ b/crates/openhuman-core/src/profiles/doctor_tests.rs@@ -0,0 +1,339 @@+//! SaaS doctor selection fixtures. This module is included by+//! `profiles::doctor` when the tenant resolver lands.++use super::{profile_provisioned_finding, resolve_with_loader, DoctorCaller, DoctorProfileState};+use crate::config::Config;+use crate::core::runtime::ComponentSet;+use crate::doctor::FindingSeverity;+use crate::doctor::{DoctorConfigSource, DoctorCtx};+use crate::doctor::{DoctorOptions, DoctorTier};+use crate::profiles::ProfileId;+use std::future::Ready;+use std::sync::{Arc, Mutex};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ReadKind {+ Registry,+ Config,+ Credential,+ Lease,+}++#[derive(Default)]+struct ReadSpy(Mutex<Vec<(ReadKind, ProfileId)>>);++impl ReadSpy {+ fn record_selected_profile(&self, id: &ProfileId) {+ let mut reads = self.0.lock().unwrap();+ for kind in [+ ReadKind::Registry,+ ReadKind::Config,+ ReadKind::Credential,+ ReadKind::Lease,+ ] {+ reads.push((kind, id.clone()));+ }+ }++ fn snapshot(&self) -> Vec<(ReadKind, ProfileId)> {+ self.0.lock().unwrap().clone()+ }+}++fn spy_loader(spy: Arc<ReadSpy>) -> impl FnOnce(ProfileId) -> Ready<Result<ProfileId, String>> {+ move |id| {+ spy.record_selected_profile(&id);+ std::future::ready(Ok(id))+ }+}++fn profile(raw: &str) -> ProfileId {+ ProfileId::parse(raw).unwrap()+}++#[test]+fn selected_tenant_context_reports_tenant_source_and_profile() {+ let id = profile("alice");+ let ctx = DoctorCtx::from_config_with_components(Config::default(), ComponentSet::all())+ .with_profile(id.as_str(), DoctorConfigSource::Tenant);++ assert_eq!(ctx.profile(), Some(id.as_str()));+ assert_eq!(ctx.config_source(), DoctorConfigSource::Tenant);+}++#[tokio::test]+async fn a_tenant_foreign_profile_is_rejected_before_any_tenant_read() {+ let alice = profile("alice");+ let bob = profile("bob");+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(+ Some(DoctorCaller::Tenant(alice)),+ Some(bob.as_str()),+ spy_loader(Arc::clone(&reads)),+ )+ .await;++ assert!(result.is_err(), "a tenant cannot inspect another profile");+ assert!(+ reads.snapshot().is_empty(),+ "authorization must precede registry, config, credential, and lease reads"+ );+}++#[tokio::test]+async fn an_unscoped_saas_call_cannot_become_an_operator_profile_read() {+ let bob = profile("bob");+ let reads = Arc::new(ReadSpy::default());++ let result =+ resolve_with_loader(None, Some(bob.as_str()), spy_loader(Arc::clone(&reads))).await;++ assert!(result.is_err(), "missing task scope must fail closed");+ assert!(reads.snapshot().is_empty());+}++#[tokio::test]+async fn a_tenant_without_a_requested_id_loads_only_its_own_profile() {+ let alice = profile("alice");+ let bob = profile("bob");+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(+ Some(DoctorCaller::Tenant(alice.clone())),+ None,+ spy_loader(Arc::clone(&reads)),+ )+ .await+ .unwrap();++ assert_eq!(result, Some(alice.clone()));+ assert_eq!(+ reads.snapshot(),+ [+ (ReadKind::Registry, alice.clone()),+ (ReadKind::Config, alice.clone()),+ (ReadKind::Credential, alice.clone()),+ (ReadKind::Lease, alice),+ ]+ );+ assert!(!reads.snapshot().iter().any(|(_, id)| id == &bob));+}++#[tokio::test]+async fn a_tenant_may_explicitly_select_its_own_profile() {+ let alice = profile("alice");+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(+ Some(DoctorCaller::Tenant(alice.clone())),+ Some(alice.as_str()),+ spy_loader(Arc::clone(&reads)),+ )+ .await+ .unwrap();++ assert_eq!(result, Some(alice.clone()));+ assert!(reads.snapshot().iter().all(|(_, id)| id == &alice));+}++#[tokio::test]+async fn an_operator_can_select_any_profile_after_scope_is_verified() {+ let bob = profile("bob");+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(+ Some(DoctorCaller::Operator),+ Some(bob.as_str()),+ spy_loader(Arc::clone(&reads)),+ )+ .await+ .unwrap();++ assert_eq!(result, Some(bob.clone()));+ assert_eq!(+ reads.snapshot(),+ [+ (ReadKind::Registry, bob.clone()),+ (ReadKind::Config, bob.clone()),+ (ReadKind::Credential, bob.clone()),+ (ReadKind::Lease, bob),+ ]+ );+}++#[tokio::test]+async fn a_valid_but_unprovisioned_operator_target_reaches_the_profile_check() {+ let id = profile("not-provisioned");+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(Some(DoctorCaller::Operator), Some(id.as_str()), {+ let reads = Arc::clone(&reads);+ move |selected| {+ reads.record_selected_profile(&selected);+ std::future::ready(Ok(false))+ }+ })+ .await+ .unwrap();++ assert_eq!(+ result,+ Some(false),+ "the selected check reports provision status"+ );+ assert!(reads.snapshot().iter().all(|(_, selected)| selected == &id));+}++#[tokio::test]+async fn an_operator_without_a_selected_profile_does_not_load_a_tenant() {+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(+ Some(DoctorCaller::Operator),+ None,+ spy_loader(Arc::clone(&reads)),+ )+ .await+ .unwrap();++ assert!(+ result.is_none(),+ "the operator keeps its own normal config path"+ );+ assert!(reads.snapshot().is_empty());+}++#[tokio::test]+async fn malformed_profile_ids_are_rejected_before_tenant_reads() {+ let reads = Arc::new(ReadSpy::default());++ let result = resolve_with_loader(+ Some(DoctorCaller::Operator),+ Some("../bob"),+ spy_loader(Arc::clone(&reads)),+ )+ .await;++ assert!(result.is_err());+ assert!(reads.snapshot().is_empty());+}++#[test]+fn an_unprovisioned_profile_is_a_safe_profile_provisioned_error() {+ let finding = profile_provisioned_finding(DoctorProfileState::Unprovisioned);++ assert_eq!(finding.check_id, "profile/provisioned");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(!finding.message.contains("secret"));+ assert!(!finding.message.contains("token"));+ assert!(!finding.fix_hint.contains("secret"));+}++#[tokio::test]+async fn dispatch_report_runs_registered_provisioned_check_without_creating_state() {+ const CHILD: &str = "OPENHUMAN_SAAS_DOCTOR_UNPROVISIONED_CHILD";+ let name = "dispatch_report_runs_registered_provisioned_check_without_creating_state";+ let module = module_path!().split_once("::").expect("crate module").1;+ let exact = format!("{module}::{name}");+ if std::env::var(CHILD).as_deref() != Ok(exact.as_str()) {+ let output = std::process::Command::new(std::env::current_exe().expect("test executable"))+ .args(["--exact", &exact, "--nocapture", "--test-threads=1"])+ .env(CHILD, &exact)+ .output()+ .expect("run isolated SaaS profile doctor test");+ assert!(+ output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),+ "isolated test {exact} failed:\n{}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ return;+ }++ use crate::core::runtime::{mode, CoreContext, DomainSet, Mode, SaasConfig};+ use crate::storage::{CollectionSpec, MemoryStorage, Scope, StorageBackend};++ mode::lock_mode(Mode::Saas).expect("isolated test process uses SaaS mode");+ let temp = tempfile::tempdir().unwrap();+ let backend: Arc<dyn StorageBackend> = Arc::new(MemoryStorage::new());+ let operator = CoreContext::for_test(DomainSet::saas(), None);+ let host = crate::profiles::ProfileHost::with_backend(+ SaasConfig::new(temp.path()),+ Arc::clone(&operator),+ Some(Arc::clone(&backend)),+ )+ .unwrap();+ let id = ProfileId::parse("not-provisioned").unwrap();+ let layout = host.layout_of(&id);+ let cluster = backend+ .for_scope(&Scope::new(crate::storage::lease::CLUSTER_SCOPE).unwrap())+ .unwrap();+ let registry_spec = CollectionSpec::new(crate::profiles::registry::REGISTRY_COLLECTION);+ let lease_spec = CollectionSpec::new(crate::storage::lease::LEASE_COLLECTION);+ assert!(cluster+ .documents()+ .validate_collection_spec(®istry_spec)+ .await+ .is_err());+ assert!(cluster+ .documents()+ .validate_collection_spec(&lease_spec)+ .await+ .is_err());+ crate::profiles::host::install(Arc::new(host));++ let options = DoctorOptions {+ tier: DoctorTier::Connect,+ only: vec!["profile/provisioned".into()],+ skip: Vec::new(),+ profile: Some(id.as_str().into()),+ };+ let dispatch = crate::core::runtime::DispatchCtx::new(Arc::clone(&operator));+ let outcome = CoreContext::scope(operator, async {+ crate::doctor::ops::doctor_report_for_dispatch(&dispatch, options).await+ })+ .await+ .unwrap();++ assert_eq!(outcome.value.profile.as_deref(), Some(id.as_str()));+ assert_eq!(outcome.value.config_source, DoctorConfigSource::Tenant);+ assert!(outcome+ .value+ .checks_run+ .iter()+ .any(|check| check == "profile/provisioned"));+ assert!(!outcome.value.ok);+ let finding = outcome+ .value+ .findings+ .iter()+ .find(|finding| finding.check_id == "profile/provisioned")+ .expect("registered profile/provisioned check result");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(+ !layout.dir.exists(),+ "doctor must not create profile directories"+ );+ assert!(cluster+ .documents()+ .validate_collection_spec(®istry_spec)+ .await+ .is_err());+ assert!(cluster+ .documents()+ .validate_collection_spec(&lease_spec)+ .await+ .is_err());+}++#[test]+fn a_profile_held_by_another_node_is_reported_without_holder_details() {+ let finding = profile_provisioned_finding(DoctorProfileState::HeldElsewhere);++ assert_eq!(finding.check_id, "profile/provisioned");+ assert_eq!(finding.severity, FindingSeverity::Error);+ assert!(!finding.message.contains("node-a"));+ assert!(!finding.message.contains("https://"));+ assert!(!finding.fix_hint.contains("token"));+}diff --git a/crates/openhuman-core/src/profiles/host.rs b/crates/openhuman-core/src/profiles/host.rsindex bfee511279..0e2e75624a 100644--- a/crates/openhuman-core/src/profiles/host.rs+++ b/crates/openhuman-core/src/profiles/host.rs@@ -197,7 +197,11 @@ impl ProfileHost {/// [`Self::forced_config`] plus the operator's direct providers, for any/// config that serves chat, relay or cron turns.- fn serving_config(&self, layout: &ProfileLayout, id: &ProfileId) -> Result<Config, String> {+ pub(super) fn serving_config(+ &self,+ layout: &ProfileLayout,+ id: &ProfileId,+ ) -> Result<Config, String> {let mut config = self.forced_config(layout, id);super::provider_settings::ProfileProviderSettings::from_saas(&self.saas).map_err(|error| error.to_string())?@@ -634,8 +638,11 @@ static HOST: OnceLock<Arc<ProfileHost>> = OnceLock::new();/// Install the process's profile host. A SaaS boot does this once; later calls/// are ignored.pub fn install(host: Arc<ProfileHost>) {- if HOST.set(host).is_err() {- log::warn!("[profiles] profile host already installed; keeping the first");+ match HOST.set(Arc::clone(&host)) {+ Ok(()) => super::doctor::register_check_source(host),+ Err(_) => {+ log::warn!("[profiles] profile host already installed; keeping the first");+ }}}diff --git a/crates/openhuman-core/src/profiles/host_fence_tests.rs b/crates/openhuman-core/src/profiles/host_fence_tests.rsnew file mode 100644index 0000000000..76b535e0b1--- /dev/null+++ b/crates/openhuman-core/src/profiles/host_fence_tests.rs@@ -0,0 +1,174 @@+use super::*;++#[tokio::test]+async fn provisioning_with_a_new_root_replaces_a_dead_higher_epoch_fence() {+ const CHILD: &str = "OPENHUMAN_PROFILE_DEAD_HIGHER_FENCE_CHILD";+ if std::env::var_os(CHILD).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "profiles::host::tests::fence_tests::provisioning_with_a_new_root_replaces_a_dead_higher_epoch_fence",+ "--nocapture",+ ])+ .env(CHILD, "1")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "isolated profile fence child failed:\n{}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("running 1 test"),+ "child selected no test: {stdout}"+ );+ assert!(stdout.contains("test profiles::host::tests::fence_tests::provisioning_with_a_new_root_replaces_a_dead_higher_epoch_fence"), "expected child test did not run: {stdout}");+ assert!(+ stdout.contains("test result: ok. 1 passed"),+ "child did not pass exactly one test: {stdout}"+ );+ return;+ }++ let first_root = tempfile::tempdir().unwrap();+ let second_root = tempfile::tempdir().unwrap();+ let id = profile(&format!("cron-fence-{}", uuid::Uuid::new_v4().simple()));+ let registry = crate::storage::fence::registry();+ let backend: Arc<dyn crate::storage::StorageBackend> =+ Arc::new(crate::storage::fenced_backend::FencedBackend::new(+ Arc::new(crate::storage::MemoryStorage::new()),+ Arc::clone(®istry),+ ));+ let _storage = RestoreInstalledStorage(crate::storage::install(backend));++ let mut first_saas = SaasConfig::new(first_root.path());+ first_saas.cron.agent_jobs_only = true;+ first_saas.cron.max_active_jobs = 1;+ let first = ProfileHost::new(first_saas, CoreContext::for_test(DomainSet::full(), None));+ first.provision(&id).await.unwrap();+ let opened = first.open(&id).await.unwrap();+ let old_epoch = opened.lease_fence().epoch();+ let _retire_stale_fence = RetireProfileFence {+ registry: Arc::clone(®istry),+ profile_id: id.as_str().to_string(),+ epoch: old_epoch,+ };+ drop(opened);+ drop(first);++ let mut second_saas = SaasConfig::new(second_root.path());+ second_saas.cron.agent_jobs_only = true;+ second_saas.cron.max_active_jobs = 1;+ let second = ProfileHost::new(second_saas, CoreContext::for_test(DomainSet::full(), None));+ let provisioned = second.provision(&id).await;+ assert!(+ provisioned.unwrap(),+ "the new root must be able to register its own profile fence"+ );+}++#[tokio::test]+async fn opening_replaces_a_dropped_hosts_fence_before_cron_reconciliation() {+ const CHILD: &str = "OPENHUMAN_PROFILE_REOPEN_DROPPED_FENCE_CHILD";+ if std::env::var_os(CHILD).is_none() {+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "profiles::host::tests::fence_tests::opening_replaces_a_dropped_hosts_fence_before_cron_reconciliation",+ "--nocapture",+ ])+ .env(CHILD, "1")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "isolated profile reopen child failed:\n{}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("running 1 test"),+ "child selected no test: {stdout}"+ );+ assert!(stdout.contains("test profiles::host::tests::fence_tests::opening_replaces_a_dropped_hosts_fence_before_cron_reconciliation"), "expected child test did not run: {stdout}");+ assert!(+ stdout.contains("test result: ok. 1 passed"),+ "child did not pass exactly one test: {stdout}"+ );+ return;+ }++ let tmp = tempfile::tempdir().unwrap();+ let id = profile(&format!("cron-fence-{}", uuid::Uuid::new_v4().simple()));+ let registry = crate::storage::fence::registry();+ let backend: Arc<dyn crate::storage::StorageBackend> =+ Arc::new(crate::storage::fenced_backend::FencedBackend::new(+ Arc::new(crate::storage::MemoryStorage::new()),+ Arc::clone(®istry),+ ));+ let _storage = RestoreInstalledStorage(crate::storage::install(backend));++ let mut first_saas = SaasConfig::new(tmp.path());+ first_saas.cron.agent_jobs_only = true;+ first_saas.cron.max_active_jobs = 1;+ let first = ProfileHost::new(first_saas, CoreContext::for_test(DomainSet::full(), None));+ first.provision(&id).await.unwrap();+ let opened = first.open(&id).await.unwrap();+ let old_epoch = opened.lease_fence().epoch();+ let _retire_stale_fence = RetireProfileFence {+ registry: Arc::clone(®istry),+ profile_id: id.as_str().to_string(),+ epoch: old_epoch,+ };+ drop(opened);+ drop(first);++ let mut second_saas = SaasConfig::new(tmp.path());+ second_saas.cron.agent_jobs_only = true;+ second_saas.cron.max_active_jobs = 1;+ let second = ProfileHost::new(second_saas, CoreContext::for_test(DomainSet::full(), None));+ assert!(!second.provision(&id).await.unwrap());+ let reopened = second.open(&id).await;+ assert!(+ reopened.is_ok(),+ "the later lease in this root must replace the dropped host's profile fence"+ );+}++#[tokio::test]+async fn disabling_profile_cron_limits_clears_the_persisted_store_cap() {+ let tmp = tempfile::tempdir().unwrap();+ let id = profile("cron-cap-toggle-off");+ let mut saas = SaasConfig::new(tmp.path());+ saas.cron.agent_jobs_only = true;+ saas.cron.max_active_jobs = 1;+ let enforced = ProfileHost::new(saas, CoreContext::for_test(DomainSet::full(), None));+ enforced.provision(&id).await.unwrap();+ let config = enforced.provisioned_config(&id).await.unwrap();+ let scope = crate::cron::documents_port::DocScope::for_scope(+ &config,+ crate::storage::scope_for_profile(id.as_str()),+ );+ crate::cron::client::store_in::<crate::cron::CronJob>(&config, &scope, raw_profile_agent_add())+ .await+ .unwrap();++ let unenforced = ProfileHost::new(+ SaasConfig::new(tmp.path()),+ CoreContext::for_test(DomainSet::full(), None),+ );+ unenforced.provision(&id).await.unwrap();+ let _profile = unenforced.open(&id).await.unwrap();+ let config = unenforced.provisioned_config(&id).await.unwrap();+ let scope = crate::cron::documents_port::DocScope::for_scope(+ &config,+ crate::storage::scope_for_profile(id.as_str()),+ );++ crate::cron::client::store_in::<crate::cron::CronJob>(&config, &scope, raw_profile_agent_add())+ .await+ .expect("disabling operator policy should clear its persisted cap");+}diff --git a/crates/openhuman-core/src/profiles/host_tests.rs b/crates/openhuman-core/src/profiles/host_tests.rsindex b4e6c481f9..db6c6000b4 100644--- a/crates/openhuman-core/src/profiles/host_tests.rs+++ b/crates/openhuman-core/src/profiles/host_tests.rs@@ -1,5 +1,235 @@use super::*;use crate::core::runtime::DispatchCtx;+use crate::profiles::doctor::DoctorProfileState;+use crate::storage::{CollectionSpec, MemoryStorage, Scope, StorageBackend};+use std::collections::BTreeMap;++fn snapshot_tree(root: &std::path::Path) -> BTreeMap<std::path::PathBuf, Vec<u8>> {+ fn visit(+ root: &std::path::Path,+ current: &std::path::Path,+ snapshot: &mut BTreeMap<std::path::PathBuf, Vec<u8>>,+ ) {+ let Ok(entries) = std::fs::read_dir(current) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ let relative = path.strip_prefix(root).unwrap().to_path_buf();+ if entry.file_type().is_ok_and(|kind| kind.is_dir()) {+ snapshot.insert(relative.join("."), Vec::new());+ visit(root, &path, snapshot);+ } else if let Ok(contents) = std::fs::read(&path) {+ snapshot.insert(relative, contents);+ }+ }+ }++ let mut snapshot = BTreeMap::new();+ visit(root, root, &mut snapshot);+ snapshot+}++#[tokio::test]+async fn inspecting_an_unprovisioned_profile_does_not_run_storage_migrations() {+ let tmp = tempfile::tempdir().unwrap();+ let backend: Arc<dyn StorageBackend> = Arc::new(MemoryStorage::new());+ let saas = SaasConfig::new(tmp.path());+ let host = ProfileHost::with_backend(+ saas,+ CoreContext::for_test(DomainSet::full(), None),+ Some(Arc::clone(&backend)),+ )+ .unwrap();+ let cluster = backend+ .for_scope(&Scope::new(crate::storage::lease::CLUSTER_SCOPE).unwrap())+ .unwrap();+ let registry_spec = CollectionSpec::new(crate::profiles::registry::REGISTRY_COLLECTION);+ let lease_spec = CollectionSpec::new(crate::storage::lease::LEASE_COLLECTION);+ let docs = cluster.documents();+ let id = profile("alice");+ let layout = host.layout_of(&id);+ let default_context = CoreContext::default_context();++ assert!(docs.validate_collection_spec(®istry_spec).await.is_err());+ assert!(docs.validate_collection_spec(&lease_spec).await.is_err());+ assert_eq!(+ host.inspect_for_doctor(&id).await,+ DoctorProfileState::Unprovisioned+ );+ let target = host.target_for_doctor(&id).unwrap();+ assert_eq!(target.profile_id, id);+ assert_eq!(target.context.profile(), Some(id.as_str()));+ assert_eq!(target.config.config_path, layout.config_path);+ assert_eq!(host.open_count(), 0, "inspection must not open or lease it");+ assert!(+ !layout.dir.exists(),+ "inspection must not create profile dirs"+ );+ let default_context_after = CoreContext::default_context();+ match (default_context.as_ref(), default_context_after.as_ref()) {+ (None, None) => {}+ (Some(before), Some(after)) => assert!(Arc::ptr_eq(before, after)),+ _ => panic!("doctor inspection must not publish a process default context"),+ }+ let lease_key =+ tinystoragedrivers::Key::of([crate::storage::lease::LEASE_OWNER, id.as_str()]).unwrap();+ assert!(+ docs.get(crate::storage::lease::LEASE_COLLECTION, lease_key.as_str())+ .await+ .unwrap()+ .is_none(),+ "inspection must not claim a lease"+ );++ assert!(+ docs.validate_collection_spec(®istry_spec).await.is_err(),+ "a profile check must not create or migrate the registry schema"+ );+ assert!(+ docs.validate_collection_spec(&lease_spec).await.is_err(),+ "a profile check must not create or migrate the lease schema"+ );+}++#[tokio::test]+async fn selected_doctor_context_keeps_config_storage_credentials_and_provider_binding_per_profile()+{+ let tmp = tempfile::tempdir().unwrap();+ let mut saas = SaasConfig::new(tmp.path());+ saas.max_tool_iterations = Some(7);+ saas.cron.min_interval_secs = 900;+ let host = ProfileHost::new(saas, CoreContext::for_test(DomainSet::full(), None));+ let a = ProfileId::for_user(+ &format!("doctor-a-{}", uuid::Uuid::new_v4().simple()),+ crate::profiles::ProfileIdMode::Raw,+ )+ .unwrap();+ let b = ProfileId::for_user(+ &format!("doctor-b-{}", uuid::Uuid::new_v4().simple()),+ crate::profiles::ProfileIdMode::Raw,+ )+ .unwrap();+ host.provision(&a).await.unwrap();+ host.provision(&b).await.unwrap();+ let target_a = host.target_for_doctor(&a).unwrap();+ let target_b = host.target_for_doctor(&b).unwrap();++ let profile_store = target_b+ .config+ .config_path+ .parent()+ .unwrap()+ .join("auth-profiles.json");+ std::fs::write(+ &profile_store,+ r#"{"schema_version":1,"active_profiles":{"api-key":"api-key:default"},"profiles":{"api-key:default":{"provider":"api-key","profile_name":"default","kind":"token","token":"doctor-b-only-test-key","metadata":{"kind":"tinyhumans-api-key"}}}}"#,+ )+ .expect("seed profile B's temporary read-only API-key fixture");++ let before_reads = snapshot_tree(tmp.path());+ let a_observed = CoreContext::scope(Arc::clone(&target_a.context), async {+ let selected_context = CoreContext::current().expect("selected profile context");+ let config = selected_context+ .embedder_config()+ .expect("selected profile config");+ (+ config.config_path.clone(),+ crate::storage::current_scope().unwrap(),+ crate::security::credentials::api_key::get_api_key_read_only(config).unwrap(),+ crate::security::credentials::session_support::load_app_session_profile_read_only(+ config,+ )+ .unwrap(),+ crate::profiles::provider_settings::ProfileProviderSettings::in_ctx(+ &DispatchCtx::ambient(),+ )+ .is_some(),+ )+ })+ .await;+ let b_observed = CoreContext::scope(Arc::clone(&target_b.context), async {+ let selected_context = CoreContext::current().expect("selected profile context");+ let config = selected_context+ .embedder_config()+ .expect("selected profile config");+ (+ config.config_path.clone(),+ crate::storage::current_scope().unwrap(),+ crate::security::credentials::api_key::get_api_key_read_only(config).unwrap(),+ crate::security::credentials::session_support::load_app_session_profile_read_only(+ config,+ )+ .unwrap(),+ crate::profiles::provider_settings::ProfileProviderSettings::in_ctx(+ &DispatchCtx::ambient(),+ )+ .is_some(),+ )+ })+ .await;++ assert_eq!(a_observed.0, target_a.config.config_path);+ assert_eq!(b_observed.0, target_b.config.config_path);+ assert_ne!(a_observed.0, b_observed.0);+ assert_eq!(a_observed.1, crate::storage::scope_for_profile(a.as_str()));+ assert_eq!(b_observed.1, crate::storage::scope_for_profile(b.as_str()));+ assert!(a_observed.2.is_none(), "A must not observe B's API key");+ assert!(a_observed.3.is_none(), "A must not observe B's session");+ assert_eq!(b_observed.2.as_deref(), Some("doctor-b-only-test-key"));+ assert!(b_observed.3.is_none(), "B has no app-session profile");+ assert!(+ a_observed.4 && b_observed.4,+ "each forced config resolves provider settings"+ );+ assert_eq!(target_a.config.agent.max_tool_iterations_override, Some(7));+ assert_eq!(target_b.config.cron.min_interval_secs, 900);+ let storage = MemoryStorage::new();+ assert!(storage.for_scope(&a_observed.1).is_ok());+ assert!(storage.for_scope(&b_observed.1).is_ok());+ assert_eq!(+ host.open_count(),+ 0,+ "doctor inspection does not open profiles"+ );+ assert_eq!(before_reads, snapshot_tree(tmp.path()));+}++#[tokio::test]+async fn doctor_inspection_reports_an_existing_lease_without_taking_it() {+ let tmp = tempfile::tempdir().unwrap();+ let operator = CoreContext::for_test(DomainSet::full(), None);+ let make_host = |node: &str| {+ let mut saas = SaasConfig::new(tmp.path());+ saas.node_id = Some(node.into());+ ProfileHost::new(saas, Arc::clone(&operator))+ };+ let (owner, inspector, third) = (+ make_host("node-a"),+ make_host("node-b"),+ make_host("node-c"),+ );+ let id = ProfileId::for_user(+ &format!("doctor-held-{}", uuid::Uuid::new_v4().simple()),+ crate::profiles::ProfileIdMode::Raw,+ )+ .unwrap();+ owner.provision(&id).await.unwrap();+ let opened = owner.open(&id).await.unwrap();++ assert_eq!(+ inspector.inspect_for_doctor(&id).await,+ DoctorProfileState::HeldElsewhere+ );+ assert_eq!(inspector.open_count(), 0);++ match third.open(&id).await {+ Err(OpenError::HeldElsewhere(record)) => assert_eq!(record.owner, "node-a"),+ other => panic!("inspection must leave the existing lease with node-a; got {other:?}"),+ }++ drop(opened);+}fn host(tmp: &tempfile::TempDir, max_open: usize, idle_secs: u64) -> ProfileHost {let mut saas = SaasConfig::new(tmp.path());@@ -507,175 +737,5 @@ async fn opening_an_existing_profile_adopts_the_enforced_cron_cap() {.contains("Failed to insert cron agent job"));}-#[tokio::test]-async fn provisioning_with_a_new_root_replaces_a_dead_higher_epoch_fence() {- const CHILD: &str = "OPENHUMAN_PROFILE_DEAD_HIGHER_FENCE_CHILD";- if std::env::var_os(CHILD).is_none() {- let output = std::process::Command::new(std::env::current_exe().unwrap())- .args([- "--exact",- "profiles::host::tests::provisioning_with_a_new_root_replaces_a_dead_higher_epoch_fence",- "--nocapture",- ])- .env(CHILD, "1")- .output()- .unwrap();- assert!(- output.status.success(),- "isolated profile fence child failed:\n{}\n{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- let stdout = String::from_utf8_lossy(&output.stdout);- assert!(- stdout.contains("running 1 test"),- "child selected no test: {stdout}"- );- assert!(stdout.contains("test profiles::host::tests::provisioning_with_a_new_root_replaces_a_dead_higher_epoch_fence"), "expected child test did not run: {stdout}");- assert!(- stdout.contains("test result: ok. 1 passed"),- "child did not pass exactly one test: {stdout}"- );- return;- }-- let first_root = tempfile::tempdir().unwrap();- let second_root = tempfile::tempdir().unwrap();- let id = profile(&format!("cron-fence-{}", uuid::Uuid::new_v4().simple()));- let registry = crate::storage::fence::registry();- let backend: Arc<dyn crate::storage::StorageBackend> =- Arc::new(crate::storage::fenced_backend::FencedBackend::new(- Arc::new(crate::storage::MemoryStorage::new()),- Arc::clone(®istry),- ));- let _storage = RestoreInstalledStorage(crate::storage::install(backend));-- let mut first_saas = SaasConfig::new(first_root.path());- first_saas.cron.agent_jobs_only = true;- first_saas.cron.max_active_jobs = 1;- let first = ProfileHost::new(first_saas, CoreContext::for_test(DomainSet::full(), None));- first.provision(&id).await.unwrap();- let opened = first.open(&id).await.unwrap();- let old_epoch = opened.lease_fence().epoch();- let _retire_stale_fence = RetireProfileFence {- registry: Arc::clone(®istry),- profile_id: id.as_str().to_string(),- epoch: old_epoch,- };- drop(opened);- drop(first);-- let mut second_saas = SaasConfig::new(second_root.path());- second_saas.cron.agent_jobs_only = true;- second_saas.cron.max_active_jobs = 1;- let second = ProfileHost::new(second_saas, CoreContext::for_test(DomainSet::full(), None));- let provisioned = second.provision(&id).await;- assert!(- provisioned.unwrap(),- "the new root must be able to register its own profile fence"- );-}--#[tokio::test]-async fn opening_replaces_a_dropped_hosts_fence_before_cron_reconciliation() {- const CHILD: &str = "OPENHUMAN_PROFILE_REOPEN_DROPPED_FENCE_CHILD";- if std::env::var_os(CHILD).is_none() {- let output = std::process::Command::new(std::env::current_exe().unwrap())- .args([- "--exact",- "profiles::host::tests::opening_replaces_a_dropped_hosts_fence_before_cron_reconciliation",- "--nocapture",- ])- .env(CHILD, "1")- .output()- .unwrap();- assert!(- output.status.success(),- "isolated profile reopen child failed:\n{}\n{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- let stdout = String::from_utf8_lossy(&output.stdout);- assert!(- stdout.contains("running 1 test"),- "child selected no test: {stdout}"- );- assert!(stdout.contains("test profiles::host::tests::opening_replaces_a_dropped_hosts_fence_before_cron_reconciliation"), "expected child test did not run: {stdout}");- assert!(- stdout.contains("test result: ok. 1 passed"),- "child did not pass exactly one test: {stdout}"- );- return;- }-- let tmp = tempfile::tempdir().unwrap();- let id = profile(&format!("cron-fence-{}", uuid::Uuid::new_v4().simple()));- let registry = crate::storage::fence::registry();- let backend: Arc<dyn crate::storage::StorageBackend> =- Arc::new(crate::storage::fenced_backend::FencedBackend::new(- Arc::new(crate::storage::MemoryStorage::new()),- Arc::clone(®istry),- ));- let _storage = RestoreInstalledStorage(crate::storage::install(backend));-- let mut first_saas = SaasConfig::new(tmp.path());- first_saas.cron.agent_jobs_only = true;- first_saas.cron.max_active_jobs = 1;- let first = ProfileHost::new(first_saas, CoreContext::for_test(DomainSet::full(), None));- first.provision(&id).await.unwrap();- let opened = first.open(&id).await.unwrap();- let old_epoch = opened.lease_fence().epoch();- let _retire_stale_fence = RetireProfileFence {- registry: Arc::clone(®istry),- profile_id: id.as_str().to_string(),- epoch: old_epoch,- };- drop(opened);- drop(first);-- let mut second_saas = SaasConfig::new(tmp.path());- second_saas.cron.agent_jobs_only = true;- second_saas.cron.max_active_jobs = 1;- let second = ProfileHost::new(second_saas, CoreContext::for_test(DomainSet::full(), None));- assert!(!second.provision(&id).await.unwrap());- let reopened = second.open(&id).await;- assert!(- reopened.is_ok(),- "the later lease in this root must replace the dropped host's profile fence"- );-}--#[tokio::test]-async fn disabling_profile_cron_limits_clears_the_persisted_store_cap() {- let tmp = tempfile::tempdir().unwrap();- let id = profile("cron-cap-toggle-off");- let mut saas = SaasConfig::new(tmp.path());- saas.cron.agent_jobs_only = true;- saas.cron.max_active_jobs = 1;- let enforced = ProfileHost::new(saas, CoreContext::for_test(DomainSet::full(), None));- enforced.provision(&id).await.unwrap();- let config = enforced.provisioned_config(&id).await.unwrap();- let scope = crate::cron::documents_port::DocScope::for_scope(- &config,- crate::storage::scope_for_profile(id.as_str()),- );- crate::cron::client::store_in::<crate::cron::CronJob>(&config, &scope, raw_profile_agent_add())- .await- .unwrap();-- let unenforced = ProfileHost::new(- SaasConfig::new(tmp.path()),- CoreContext::for_test(DomainSet::full(), None),- );- unenforced.provision(&id).await.unwrap();- let _profile = unenforced.open(&id).await.unwrap();- let config = unenforced.provisioned_config(&id).await.unwrap();- let scope = crate::cron::documents_port::DocScope::for_scope(- &config,- crate::storage::scope_for_profile(id.as_str()),- );-- crate::cron::client::store_in::<crate::cron::CronJob>(&config, &scope, raw_profile_agent_add())- .await- .expect("disabling operator policy should clear its persisted cap");-}+#[path = "host_fence_tests.rs"]+mod fence_tests;diff --git a/crates/openhuman-core/src/profiles/lease_tests.rs b/crates/openhuman-core/src/profiles/lease_tests.rsindex e651f74600..4c76e45e1f 100644--- a/crates/openhuman-core/src/profiles/lease_tests.rs+++ b/crates/openhuman-core/src/profiles/lease_tests.rs@@ -293,6 +293,10 @@ impl LeaseStore for PausingRenewals {async fn holder(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError> {self.inner.holder(key).await}++ async fn holder_readonly(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError> {+ self.inner.holder_readonly(key).await+ }}/// An operator release that lands while the heartbeat is renewing the samediff --git a/crates/openhuman-core/src/profiles/lifecycle_tests.rs b/crates/openhuman-core/src/profiles/lifecycle_tests.rsindex 8ffec0a9ad..07efc48862 100644--- a/crates/openhuman-core/src/profiles/lifecycle_tests.rs+++ b/crates/openhuman-core/src/profiles/lifecycle_tests.rs@@ -88,6 +88,10 @@ impl LeaseStore for PausingLeases {async fn holder(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError> {self.inner.holder(key).await}++ async fn holder_readonly(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError> {+ self.inner.holder_readonly(key).await+ }}#[tokio::test]diff --git a/crates/openhuman-core/src/profiles/mod.rs b/crates/openhuman-core/src/profiles/mod.rsindex ec50e2a64c..cd1cbb0fc1 100644--- a/crates/openhuman-core/src/profiles/mod.rs+++ b/crates/openhuman-core/src/profiles/mod.rs@@ -27,6 +27,7 @@ pub mod background;pub mod capabilities;pub mod credentials;pub mod cron;+pub(crate) mod doctor;pub mod fence;pub mod gateway;pub mod host;diff --git a/crates/openhuman-core/src/profiles/registry.rs b/crates/openhuman-core/src/profiles/registry.rsindex e25431c70a..d8cac4e6ef 100644--- a/crates/openhuman-core/src/profiles/registry.rs+++ b/crates/openhuman-core/src/profiles/registry.rs@@ -141,6 +141,44 @@ impl ProfileRegistry {read_meta(&ProfileLayout::new(root, id))}+ /// Reads a profile record without declaring collections or running the+ /// lazy legacy migration used by normal lifecycle operations.+ ///+ /// A legacy registry collection is reported as requiring explicit+ /// migration rather than being changed by a diagnostic read.+ pub(crate) async fn get_readonly(&self, id: &ProfileId) -> Result<Option<ProfileMeta>, String> {+ let Self::Documents { docs, .. } = self else {+ let Self::Files { root } = self else {+ unreachable!("a registry is documents or files");+ };+ return read_meta(&ProfileLayout::new(root, id));+ };++ if collection_is_declared(+ docs.as_ref(),+ super::storage_schema::LEGACY_REGISTRY_COLLECTION,+ )+ .await?+ {+ return Err("profile registry requires explicit storage migration".into());+ }+ if !collection_is_declared(docs.as_ref(), REGISTRY_COLLECTION).await? {+ return Ok(None);+ }++ let key = key_of(id.as_str()).map_err(|_| "profile registry key is invalid".to_string())?;+ let Some(stored) = docs+ .get(REGISTRY_COLLECTION, &key)+ .await+ .map_err(|_| "profile registry could not be read".to_string())?+ else {+ return Ok(None);+ };+ meta_of(&stored)+ .map(Some)+ .map_err(|_| "profile registry record is invalid".to_string())+ }+/// Records `meta` unless its profile is already recorded. Returns whether/// it was new.///@@ -251,6 +289,20 @@ impl ProfileRegistry {}}+async fn collection_is_declared(+ docs: &dyn DocumentStore,+ collection: &str,+) -> Result<bool, String> {+ match docs+ .validate_collection_spec(&CollectionSpec::new(collection))+ .await+ {+ Ok(()) => Ok(true),+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),+ Err(_) => Err("profile registry schema could not be inspected".into()),+ }+}+fn read_meta(layout: &ProfileLayout) -> Result<Option<ProfileMeta>, String> {let raw = match std::fs::read_to_string(&layout.meta_path) {Ok(raw) => raw,diff --git a/crates/openhuman-core/src/profiles/registry_tests.rs b/crates/openhuman-core/src/profiles/registry_tests.rsindex 6efc244308..97f78fbe29 100644--- a/crates/openhuman-core/src/profiles/registry_tests.rs+++ b/crates/openhuman-core/src/profiles/registry_tests.rs@@ -1,5 +1,6 @@use super::*;-use crate::storage::MemoryStorage;+use crate::storage::{CollectionSpec, MemoryStorage, Scope, StorageBackend};+use tinystoragedrivers::Precondition;fn meta(id: &str, created_at: u64) -> ProfileMeta {ProfileMeta {@@ -77,3 +78,91 @@ async fn an_empty_root_lists_nothing() {.unwrap().is_empty());}++#[tokio::test]+async fn doctor_lookup_of_an_unknown_profile_does_not_declare_cluster_schema() {+ let storage = MemoryStorage::new();+ let registry = ProfileRegistry::cluster(&storage).unwrap();+ let docs = storage+ .for_scope(&Scope::new(crate::storage::lease::CLUSTER_SCOPE).unwrap())+ .unwrap();+ let registry_spec = CollectionSpec::new(REGISTRY_COLLECTION);+ let lease_spec = CollectionSpec::new(crate::storage::lease::LEASE_COLLECTION);++ assert!(registry+ .get_readonly(&ProfileId::parse("alice").unwrap())+ .await+ .unwrap()+ .is_none());++ assert!(docs+ .documents()+ .validate_collection_spec(®istry_spec)+ .await+ .is_err());+ assert!(docs+ .documents()+ .validate_collection_spec(&lease_spec)+ .await+ .is_err());+}++#[tokio::test]+async fn doctor_lookup_does_not_migrate_legacy_profile_or_lease_records() {+ let storage = MemoryStorage::new();+ let registry = ProfileRegistry::cluster(&storage).unwrap();+ let scoped = storage+ .for_scope(&Scope::new(crate::storage::lease::CLUSTER_SCOPE).unwrap())+ .unwrap();+ let docs = scoped.documents();+ let alice_key = crate::storage::schema_support::key_of("alice").unwrap();+ docs.ensure_collection(&CollectionSpec::new("profiles"))+ .await+ .unwrap();+ docs.put(+ "profiles",+ &alice_key,+ serde_json::json!({ "profile_id": "alice", "created_at": 1, "layout_version": 2 }),+ Precondition::Absent,+ )+ .await+ .unwrap();+ docs.ensure_collection(&CollectionSpec::new("leases"))+ .await+ .unwrap();+ docs.put(+ "leases",+ "alice",+ serde_json::json!({+ "owner": "node-a",+ "endpoint": null,+ "epoch": 3,+ "expires_at_ms": u64::MAX,+ "released": false+ }),+ Precondition::Absent,+ )+ .await+ .unwrap();++ let result = registry+ .get_readonly(&ProfileId::parse("alice").unwrap())+ .await;+ assert!(+ result.is_err() || result.unwrap().is_some(),+ "a legacy provisioned profile must not be misreported as unprovisioned"+ );++ assert!(docs.get("profiles", &alice_key).await.unwrap().is_some());+ assert!(docs.get("leases", "alice").await.unwrap().is_some());+ assert!(docs+ .validate_collection_spec(&CollectionSpec::new(REGISTRY_COLLECTION))+ .await+ .is_err());+ assert!(docs+ .validate_collection_spec(&CollectionSpec::new(+ crate::storage::lease::LEASE_COLLECTION+ ))+ .await+ .is_err());+}diff --git a/crates/openhuman-core/src/profiles/schemas.rs b/crates/openhuman-core/src/profiles/schemas.rsindex 9fe5cc0386..a553e1954d 100644--- a/crates/openhuman-core/src/profiles/schemas.rs+++ b/crates/openhuman-core/src/profiles/schemas.rs@@ -101,7 +101,10 @@ pub fn profiles_schemas(function: &str) -> ControllerSchema {description: "Create the profile that serves a gateway user, if it does not exist.",inputs: vec![string_field("user_id", "The gateway's id for the user.")],outputs: vec![- string_field("profile_id", "The user's profile id: the user id itself when it fits the raw charset (raw mode), else h-<sha256 prefix>."),+ string_field(+ "profile_id",+ "The user's profile id: the user id itself when it fits the raw charset (raw mode), else h-<sha256 prefix>.",+ ),bool_field("created", "False when the profile already existed."),],},@@ -141,7 +144,10 @@ pub fn profiles_schemas(function: &str) -> ControllerSchema {required: true,},bool_field("open", "Whether it is loaded right now."),- bool_field("has_credential", "Whether a backend credential is installed."),+ bool_field(+ "has_credential",+ "Whether a backend credential is installed.",+ ),],},"set_credential" => ControllerSchema {diff --git a/crates/openhuman-core/src/profiles/surface.rs b/crates/openhuman-core/src/profiles/surface.rsindex 305640363a..cc83e969ed 100644--- a/crates/openhuman-core/src/profiles/surface.rs+++ b/crates/openhuman-core/src/profiles/surface.rs@@ -13,6 +13,11 @@use crate::core::runtime::is_saas;+/// Diagnostic reports are safe in both the operator plane and a user's own+/// profile scope. Selection of another profile is authorized in the report+/// handler before it reads profile state.+const SHARED_SAAS_METHODS: &[&str] = &["openhuman.doctor_report"];+/// Every RPC method a user may dispatch. Grows as each family's per-user/// isolation lands; a method is listed only once nothing it touches is/// shared between users.@@ -107,11 +112,12 @@ pub fn current_scope() -> Scope {////// A SaaS task with no scope sees nothing: missing scope fails closed.pub fn visible_in(saas: bool, scope: Scope, method: &str, operator_plane: bool) -> bool {+ let shared = SHARED_SAAS_METHODS.contains(&method);match (saas, scope) {(false, _) => true,(true, Scope::None) => false,- (true, Scope::Operator) => operator_plane,- (true, Scope::User) => !operator_plane && USER_METHODS.contains(&method),+ (true, Scope::Operator) => operator_plane || shared,+ (true, Scope::User) => !operator_plane && (USER_METHODS.contains(&method) || shared),}}diff --git a/crates/openhuman-core/src/profiles/surface_tests.rs b/crates/openhuman-core/src/profiles/surface_tests.rsindex 48a4118c06..41b5387152 100644--- a/crates/openhuman-core/src/profiles/surface_tests.rs+++ b/crates/openhuman-core/src/profiles/surface_tests.rs@@ -41,6 +41,20 @@ fn the_saas_planes_never_overlap() {));}+#[test]+fn doctor_report_is_available_to_both_authorized_saas_scopes() {+ let doctor = "openhuman.doctor_report";+ assert!(visible_in(true, Scope::Operator, doctor, false));+ assert!(visible_in(true, Scope::User, doctor, false));+ assert!(!visible_in(true, Scope::None, doctor, false));+ assert!(!visible_in(+ true,+ Scope::User,+ "openhuman.config_get_config",+ false+ ));+}+#[test]fn chat_is_open_but_other_channel_methods_are_not() {assert!(visible_in(diff --git a/crates/openhuman-core/src/security/credentials/api_key.rs b/crates/openhuman-core/src/security/credentials/api_key.rsindex 9313064c34..bde68e7fdf 100644--- a/crates/openhuman-core/src/security/credentials/api_key.rs+++ b/crates/openhuman-core/src/security/credentials/api_key.rs@@ -79,6 +79,17 @@ pub fn get_api_key(config: &Config) -> Result<Option<String>> {)}+/// Reads the selected profile's API key for doctor checks without using the+/// ordinary mutable auth-profile store.+pub fn get_api_key_read_only(+ config: &Config,+) -> Result<Option<String>, super::profiles::ReadOnlyAuthProfileError> {+ let Some(profile) = AuthService::get_profile_read_only(config, API_KEY_PROVIDER, None)? else {+ return Ok(None);+ };+ Ok(api_key_from_profile(profile))+}+/// [`get_api_key`] against an explicit credential state directory — for/// callers that hold `ProviderRuntimeOptions` rather than a `Config`.///@@ -93,19 +104,23 @@ pub fn get_api_key_in(state_dir: &Path, encrypt: bool) -> Result<Option<String>>let Some(profile) = service.get_profile(API_KEY_PROVIDER, None)? else {return Ok(None);};+ Ok(api_key_from_profile(profile))+}++fn api_key_from_profile(profile: AuthProfile) -> Option<String> {if profile.metadata.get(API_KEY_KIND_META).map(String::as_str) != Some(API_KEY_KIND) {log::debug!("[credentials][api-key] provider profile {:?} exists but lacks the {API_KEY_KIND_META}={API_KEY_KIND} \marker — treating as absent, not a TinyHumans api key",API_KEY_PROVIDER);- return Ok(None);+ return None;}let credential = match profile.kind {super::profiles::AuthProfileKind::Token => profile.token,super::profiles::AuthProfileKind::OAuth => profile.token_set.map(|t| t.access_token),};- Ok(credential.filter(|t| !t.trim().is_empty()))+ credential.filter(|t| !t.trim().is_empty())}/// Whether an API key is stored. Errors reading the store count as "no key"diff --git a/crates/openhuman-core/src/security/credentials/core.rs b/crates/openhuman-core/src/security/credentials/core.rsindex f7314347d5..b5fe0e59e6 100644--- a/crates/openhuman-core/src/security/credentials/core.rs+++ b/crates/openhuman-core/src/security/credentials/core.rs@@ -19,6 +19,35 @@ pub struct AuthService {}impl AuthService {+ /// Reads one profile for doctor inspection without constructing the+ /// mutable auth store or consulting process-global credential storage.+ pub fn get_profile_read_only(+ config: &Config,+ provider: &str,+ profile_override: Option<&str>,+ ) -> Result<Option<AuthProfile>, super::profiles::ReadOnlyAuthProfileError> {+ super::profiles::load_profile_read_only(config, provider, profile_override)+ }++ /// Reads the selected profile's bearer without opening the mutable+ /// auth-profile store. Doctor inspection uses this for BYOK providers.+ pub fn get_provider_bearer_token_read_only(+ config: &Config,+ provider: &str,+ profile_override: Option<&str>,+ ) -> Result<Option<String>, super::profiles::ReadOnlyAuthProfileError> {+ let Some(profile) = Self::get_profile_read_only(config, provider, profile_override)? else {+ return Ok(None);+ };+ let credential = match profile.kind {+ super::profiles::AuthProfileKind::Token => profile.token,+ super::profiles::AuthProfileKind::OAuth => {+ profile.token_set.map(|tokens| tokens.access_token)+ }+ };+ Ok(credential.filter(|token| !token.trim().is_empty()))+ }+pub fn from_config(config: &Config) -> Self {let state_dir = state_dir_from_config(config);Self::new(&state_dir, config.secrets.encrypt)diff --git a/crates/openhuman-core/src/security/credentials/mod.rs b/crates/openhuman-core/src/security/credentials/mod.rsindex 30fe16ae91..17890b8200 100644--- a/crates/openhuman-core/src/security/credentials/mod.rs+++ b/crates/openhuman-core/src/security/credentials/mod.rs@@ -24,6 +24,7 @@ pub use http_creds::{pub use jwt::user_id_from_profile_payload;pub use ops as rpc;pub use ops::*;+pub use profiles::{AuthProfile, AuthProfileKind, TokenSet};// Direct-mode (BYO Composio API key) credential helpers.pub use ops::{clear_composio_api_key, get_composio_api_key, store_composio_api_key, COMPOSIO_DIRECT_PROVIDER,diff --git a/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests_bearer_token_tests.rs b/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests_bearer_token_tests.rsindex 4a67ecc2ad..28dbc423b1 100644--- a/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests_bearer_token_tests.rs+++ b/crates/openhuman-core/src/security/credentials/openai_oauth/flow_tests_bearer_token_tests.rs@@ -133,7 +133,7 @@ async fn lookup_openai_bearer_token_does_not_persist_blank_refreshed_access_toke.mount(&server).await;- let _env_guard = EnvVarGuard::set(+ let _env_guard = EnvVarGuard::locked_async().await.with("OPENAI_CODEX_OAUTH_TOKEN_URL",format!("{}/token", server.uri()),);diff --git a/crates/openhuman-core/src/security/credentials/openai_oauth/store.rs b/crates/openhuman-core/src/security/credentials/openai_oauth/store.rsindex 105c24b424..c70527aa94 100644--- a/crates/openhuman-core/src/security/credentials/openai_oauth/store.rs+++ b/crates/openhuman-core/src/security/credentials/openai_oauth/store.rs@@ -197,6 +197,14 @@ fn auth_profiles_store(config: &Config) -> AuthProfilesStore {fn try_refresh_oauth_token(refresh: &str) -> Result<OAuthTokenSet, String> {let cfg = openai_codex_config("http://127.0.0.1:1455/auth/callback");+ #[cfg(test)]+ let cfg = if let Some(token_url) = local_refresh_url_override() {+ let mut cfg = cfg;+ cfg.token_url = token_url;+ cfg+ } else {+ cfg+ };let refresh = refresh.to_string();if let Ok(handle) = tokio::runtime::Handle::try_current() {// `block_in_place` lets the multi-thread runtime move other tasks off this@@ -210,6 +218,18 @@ fn try_refresh_oauth_token(refresh: &str) -> Result<OAuthTokenSet, String> {Err("tokio runtime required to refresh openai oauth token".to_string())}+/// Local-only endpoint override for OAuth refresh tests. Production builds do+/// not read this variable, and tests cannot redirect refresh credentials away+/// from loopback.+#[cfg(test)]+fn local_refresh_url_override() -> Option<String> {+ let endpoint = std::env::var("OPENAI_CODEX_OAUTH_TOKEN_URL").ok()?;+ let parsed = reqwest::Url::parse(&endpoint).ok()?;+ let host = parsed.host_str()?;+ (parsed.scheme() == "http" && matches!(host, "localhost" | "127.0.0.1" | "::1"))+ .then(|| endpoint.clone())+}+/// Look up the OpenAI bearer token sourced from the OAuth (ChatGPT/// subscription) flow. Returns `Ok(None)` when no OAuth profile is present or/// when the access token is empty. API-key fallback for the `openai` slug isdiff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env.rsindex b5e900fdd1..701af9d342 100644--- a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env.rs@@ -36,7 +36,9 @@ pub fn seed_api_key_from_env(config: &Config) {return;};if api_key::has_api_key(config) {- log::debug!("[auth][boot] {BACKEND_API_KEY_ENV} set but an api key is already stored; keeping the stored one");+ log::debug!(+ "[auth][boot] {BACKEND_API_KEY_ENV} set but an api key is already stored; keeping the stored one"+ );return;}match api_key::store_api_key(config, &key) {@@ -55,7 +57,9 @@ pub async fn seed_session_from_env(ctx: &DispatchCtx, config: &Config) {return;};if matches!(get_session_token(config), Ok(Some(_))) {- log::debug!("[auth][boot] {BACKEND_SESSION_TOKEN_ENV} set but a session is already stored; keeping the stored one");+ log::debug!(+ "[auth][boot] {BACKEND_SESSION_TOKEN_ENV} set but a session is already stored; keeping the stored one"+ );return;}let request = SetCredentialRequest {diff --git a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs b/crates/openhuman-core/src/security/credentials/ops/user_scope.rsindex 304f86a1ec..b01b7d560e 100644--- a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs@@ -148,8 +148,11 @@ pub(super) fn rebind_after_credential_change());}crate::cron::seed::prune_retired_jobs(config).map_err(|error| error.to_string())?;- crate::core::runtime::context::CoreContext::rebind_default_workspace(&config.workspace_dir)- .map_err(|error| error.to_string())?;+ crate::core::runtime::context::CoreContext::rebind_default_workspace_with_config(+ &config.workspace_dir,+ Some(&config.config_path),+ )+ .map_err(|error| error.to_string())?;if let Err(error) = crate::cron::system_jobs::ensure_memory_jobs(config) {logs.push(format!("memory cron jobs not seeded: {error}"));}diff --git a/crates/openhuman-core/src/security/credentials/profiles.rs b/crates/openhuman-core/src/security/credentials/profiles.rsindex b57a1d7328..0f7534ba8b 100644--- a/crates/openhuman-core/src/security/credentials/profiles.rs+++ b/crates/openhuman-core/src/security/credentials/profiles.rs@@ -22,8 +22,18 @@ mod keychain;mod lock;mod migration;mod persistence;+mod readonly;pub(crate) use persistence::STORAGE_SECRET_NAME as PROFILES_SECRET_NAME;mod store_core;+pub use readonly::ReadOnlyAuthProfileError;++pub(crate) fn load_profile_read_only(+ config: &crate::config::Config,+ provider: &str,+ profile_override: Option<&str>,+) -> Result<Option<AuthProfile>, ReadOnlyAuthProfileError> {+ readonly::load_profile(config, provider, profile_override)+}const CURRENT_SCHEMA_VERSION: u32 = 1;@@ -209,6 +219,11 @@ impl Default for AuthProfilesData {/// Full key format (as handled by the keyring module): `"{user_id}:auth:{profile_id}"`.const KEYCHAIN_AUTH_PREFIX: &str = "auth:";+/// The logical key used for an auth profile's secret payload.+pub(crate) fn auth_profile_secret_key(profile_id: &str) -> String {+ format!("{KEYCHAIN_AUTH_PREFIX}{profile_id}")+}+/// Derive a stable keychain user-id from a state directory path.////// For a typical path like `/home/alice/.openhuman/users/uid-123` thisdiff --git a/crates/openhuman-core/src/security/credentials/profiles/keychain.rs b/crates/openhuman-core/src/security/credentials/profiles/keychain.rsindex f39829874c..271a01af16 100644--- a/crates/openhuman-core/src/security/credentials/profiles/keychain.rs+++ b/crates/openhuman-core/src/security/credentials/profiles/keychain.rs@@ -2,12 +2,12 @@use anyhow::Context;-use super::{AuthProfile, AuthProfilesStore, KeychainSecrets, KEYCHAIN_AUTH_PREFIX};+use super::{AuthProfile, AuthProfilesStore, KeychainSecrets};impl AuthProfilesStore {/// Build a keychain key for an auth profile's combined secret payload.pub(super) fn keychain_key_for_profile(&self, profile_id: &str) -> String {- format!("{KEYCHAIN_AUTH_PREFIX}{profile_id}")+ super::auth_profile_secret_key(profile_id)}/// Store auth secrets for a profile in the OS keychain.diff --git a/crates/openhuman-core/src/security/credentials/profiles/readonly.rs b/crates/openhuman-core/src/security/credentials/profiles/readonly.rsnew file mode 100644index 0000000000..e37b61d4ad--- /dev/null+++ b/crates/openhuman-core/src/security/credentials/profiles/readonly.rs@@ -0,0 +1,221 @@+//! Non-mutating auth-profile snapshots for doctor checks.++use zeroize::Zeroizing;++use crate::config::Config;+use crate::security::secret_storage::{EncryptedFileBackend, SecretStore};++use super::{+ normalize_profile_id_provider, parse_datetime_with_fallback, parse_optional_datetime,+ parse_profile_kind, profile_id, AuthProfile, AuthProfileKind, KeychainSecrets,+ PersistedAuthProfile, PersistedAuthProfiles, TokenSet, CURRENT_SCHEMA_VERSION,+ PROFILES_FILENAME,+};+use crate::security::credentials::default_profile_id;++/// Safe failure categories for a read-only auth-profile snapshot.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ReadOnlyAuthProfileError {+ /// The selected backend, encryption key, or stored record cannot be read safely.+ Unavailable,+ /// The selected profile's persisted auth document is malformed or unsupported.+ InvalidStore,+}++/// Reads one selected profile from its config directory and profile-scoped+/// encrypted-file backend, without locks, migrations, writes, or global+/// storage/backend lookups.+pub(super) fn load_profile(+ config: &Config,+ provider: &str,+ profile_override: Option<&str>,+) -> Result<Option<AuthProfile>, ReadOnlyAuthProfileError> {+ let state_dir = config+ .config_path+ .parent()+ .ok_or(ReadOnlyAuthProfileError::Unavailable)?;+ let path = state_dir.join(PROFILES_FILENAME);+ let bytes = match std::fs::read(&path) {+ Ok(bytes) => bytes,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(_) => return Err(ReadOnlyAuthProfileError::Unavailable),+ };+ let persisted: PersistedAuthProfiles =+ serde_json::from_slice(&bytes).map_err(|_| ReadOnlyAuthProfileError::InvalidStore)?;+ if persisted.schema_version > CURRENT_SCHEMA_VERSION {+ return Err(ReadOnlyAuthProfileError::InvalidStore);+ }++ let provider = provider.trim().to_ascii_lowercase();+ let Some(id) = selected_profile_id(&persisted, &provider, profile_override) else {+ return Ok(None);+ };+ let profile = persisted+ .profiles+ .get(&id)+ .ok_or(ReadOnlyAuthProfileError::InvalidStore)?;++ let user_id = super::user_id_from_state_dir(state_dir);+ let profile_secret =+ read_profile_secret(config, &user_id, &super::auth_profile_secret_key(&id));+ let secrets = match profile_secret {+ Ok(Some(payload)) => Some(+ serde_json::from_str::<KeychainSecrets>(&payload)+ .map_err(|_| ReadOnlyAuthProfileError::InvalidStore)?,+ ),+ Ok(None) => None,+ Err(_) if has_json_secret_fields(profile) => None,+ Err(error) => return Err(error),+ };++ let encrypted_json = has_encrypted_json_fields(profile);+ let key = if encrypted_json {+ Some(Zeroizing::new(+ read_profile_secret(config, &user_id, "secretstore.master_key")?+ .ok_or(ReadOnlyAuthProfileError::Unavailable)?,+ ))+ } else {+ None+ };+ let store = SecretStore::new(state_dir, config.secrets.encrypt);+ let decrypt = |value: Option<&str>| -> Result<Option<String>, ReadOnlyAuthProfileError> {+ value+ .map(|value| {+ if let Some(key) = key.as_deref() {+ SecretStore::decrypt_with_existing_key(value, key)+ .map_err(|_| ReadOnlyAuthProfileError::Unavailable)+ } else if value.starts_with("enc:") || value.starts_with("enc2:") {+ Err(ReadOnlyAuthProfileError::Unavailable)+ } else {+ store+ .decrypt(value)+ .map_err(|_| ReadOnlyAuthProfileError::Unavailable)+ }+ })+ .transpose()+ };++ let kind =+ parse_profile_kind(&profile.kind).map_err(|_| ReadOnlyAuthProfileError::InvalidStore)?;+ let (access_token, refresh_token, id_token, token) = if let Some(secrets) = secrets {+ (+ secrets.access_token,+ secrets.refresh_token,+ secrets.id_token,+ secrets.token,+ )+ } else {+ (+ decrypt(profile.access_token.as_deref())?,+ decrypt(profile.refresh_token.as_deref())?,+ decrypt(profile.id_token.as_deref())?,+ decrypt(profile.token.as_deref())?,+ )+ };++ let token_set = match kind {+ AuthProfileKind::OAuth => Some(TokenSet {+ access_token: access_token.ok_or(ReadOnlyAuthProfileError::InvalidStore)?,+ refresh_token,+ id_token,+ expires_at: parse_optional_datetime(profile.expires_at.as_deref())+ .map_err(|_| ReadOnlyAuthProfileError::InvalidStore)?,+ token_type: profile.token_type.clone(),+ scope: profile.scope.clone(),+ }),+ AuthProfileKind::Token => None,+ };++ Ok(Some(AuthProfile {+ id,+ provider: profile.provider.clone(),+ profile_name: profile.profile_name.clone(),+ kind,+ account_id: profile.account_id.clone(),+ workspace_id: profile.workspace_id.clone(),+ token_set,+ token,+ metadata: profile.metadata.clone(),+ created_at: parse_datetime_with_fallback(&profile.created_at),+ updated_at: parse_datetime_with_fallback(&profile.updated_at),+ }))+}++fn selected_profile_id(+ persisted: &PersistedAuthProfiles,+ provider: &str,+ profile_override: Option<&str>,+) -> Option<String> {+ let provider_key = if provider.starts_with("provider:") {+ provider.to_owned()+ } else {+ format!("provider:{provider}")+ };+ if let Some(profile_override) = profile_override {+ let requested = if profile_override.contains(':') {+ profile_override.to_owned()+ } else {+ profile_id(provider, profile_override)+ };+ return [requested.clone(), format!("provider:{requested}")]+ .into_iter()+ .find(|id| persisted.profiles.contains_key(id));+ }++ if let Some(active) = persisted+ .active_profiles+ .get(provider)+ .or_else(|| persisted.active_profiles.get(&provider_key))+ {+ let normalized = normalize_profile_id_provider(active);+ if persisted.profiles.contains_key(active) {+ return Some(active.clone());+ }+ if persisted.profiles.contains_key(&normalized) {+ return Some(normalized);+ }+ }+ let default = default_profile_id(provider);+ if persisted.profiles.contains_key(&default) {+ return Some(default);+ }+ let namespaced_default = default_profile_id(&provider_key);+ if persisted.profiles.contains_key(&namespaced_default) {+ return Some(namespaced_default);+ }+ persisted.profiles.iter().find_map(|(id, profile)| {+ (profile.provider.eq_ignore_ascii_case(provider)+ || profile.provider.eq_ignore_ascii_case(&provider_key))+ .then(|| id.clone())+ })+}++fn read_profile_secret(+ config: &Config,+ user_id: &str,+ logical_key: &str,+) -> Result<Option<String>, ReadOnlyAuthProfileError> {+ let key = crate::security::secret_storage::ops::namespaced_key(user_id, logical_key);+ EncryptedFileBackend::new(&config.workspace_dir)+ .get_profile_read_only(&key)+ .map_err(|_| ReadOnlyAuthProfileError::Unavailable)+}++fn has_json_secret_fields(profile: &PersistedAuthProfile) -> bool {+ profile.access_token.is_some()+ || profile.refresh_token.is_some()+ || profile.id_token.is_some()+ || profile.token.is_some()+}++fn has_encrypted_json_fields(profile: &PersistedAuthProfile) -> bool {+ [+ &profile.access_token,+ &profile.refresh_token,+ &profile.id_token,+ &profile.token,+ ]+ .into_iter()+ .flatten()+ .any(|value| value.starts_with("enc:") || value.starts_with("enc2:"))+}diff --git a/crates/openhuman-core/src/security/credentials/schemas.rs b/crates/openhuman-core/src/security/credentials/schemas.rsindex e352eb5a80..4ad0426342 100644--- a/crates/openhuman-core/src/security/credentials/schemas.rs+++ b/crates/openhuman-core/src/security/credentials/schemas.rs@@ -112,7 +112,10 @@ pub fn schemas(function: &str) -> ControllerSchema {// Accepted spelling for callers that still send the historical// `auth_store_session` shape through the legacy alias.optional_string("user_id", "Alias of `userId`."),- optional_string("issuingBackend", "Backend origin used by the host to validate this session; binds future credential use to that deployment."),+ optional_string(+ "issuingBackend",+ "Backend origin used by the host to validate this session; binds future credential use to that deployment.",+ ),optional_json("user","User payload (the host's /auth/me answer, or the local user).",diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rsindex de1feeca41..13ee5b5934 100644--- a/crates/openhuman-core/src/security/credentials/session_support.rs+++ b/crates/openhuman-core/src/security/credentials/session_support.rs@@ -264,7 +264,9 @@ pub fn normalize_session_backend(raw: &str) -> Result<String, String> {Ok(parsed.as_str().trim_end_matches('/').to_string())}-fn check_session_backend(config: &Config, profile: Option<&AuthProfile>) -> Result<(), String> {+/// Purely verifies that a stored session belongs to the selected config's+/// control-plane endpoint. It does not publish expiry events or mutate auth state.+pub fn check_session_backend(config: &Config, profile: Option<&AuthProfile>) -> Result<(), String> {let Some(profile) = profile else {return Ok(());};@@ -561,6 +563,14 @@ pub fn load_app_session_profile(config: &Config) -> Result<Option<AuthProfile>,.map_err(|e| e.to_string())}+/// Reads the selected app-session profile for doctor checks without opening+/// the ordinary mutable auth-profile store.+pub fn load_app_session_profile_read_only(+ config: &Config,+) -> Result<Option<AuthProfile>, super::profiles::ReadOnlyAuthProfileError> {+ AuthService::get_profile_read_only(config, APP_SESSION_PROVIDER, None)+}+pub fn session_state_from_profile(profile: Option<&AuthProfile>) -> AuthStateResponse {let Some(profile) = profile else {return AuthStateResponse {diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rsindex aa32f0414e..d33a01afc8 100644--- a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs@@ -364,6 +364,24 @@ impl EncryptedFileBackend {}}+ /// Read one namespaced secret from this explicit profile store without+ /// initializing global keyring state, importing legacy files, or+ /// quarantining corrupt data. Returns an error when no read-only key is+ /// available, so callers can report the result as unavailable rather+ /// than treating it as a missing credential.+ pub fn get_profile_read_only(+ &self,+ namespaced_key: &str,+ ) -> Result<Option<String>, SecretStorageError> {+ let key =+ key_source::profile_master_key_read_only(&self.workspace_dir)?.ok_or_else(|| {+ SecretStorageError::Backend(+ "profile master key unavailable for read-only secret lookup".into(),+ )+ })?;+ self.get_with_key_read_only(&key, namespaced_key)+ }+fn key(&self) -> Option<Zeroizing<[u8; KEY_LEN]>> {#[cfg(test)]{@@ -624,6 +642,19 @@ impl EncryptedFileBackend {adapter::utf8(namespaced_key, value)}+ fn get_with_key_read_only(+ &self,+ key: &[u8; KEY_LEN],+ namespaced_key: &str,+ ) -> Result<Option<String>, SecretStorageError> {+ use tinystoragedrivers::secrets::SecretStore as _;+ let name = namespaced_key.to_string();+ let store = self.store(key);+ let value = crate::storage::block_on(async move { store.get(&name).await })+ .map_err(adapter::backend_error)?;+ adapter::utf8(namespaced_key, value)+ }+/// [`SecretBackend::set`] under an explicit master key.pub(super) fn set_with_key(&self,diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rsindex b2d2863c56..4664c84ce4 100644--- a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rs+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rs@@ -2,6 +2,16 @@use super::*;+/// Whether an environment source is configured according to the same+/// whitespace handling used before key parsing. Invalid Unicode is present+/// and must remain an error, so it counts as configured here.+pub(crate) fn env_source_is_configured(value: &std::ffi::OsStr) -> bool {+ match value.to_str() {+ Some(value) => !value.trim().is_empty(),+ None => true,+ }+}+/// Only `NotPresent` means unset. Invalid Unicode must not fall through to the/// next source, where a new key could orphan the encrypted secrets.pub(super) fn env_value(@@ -25,8 +35,12 @@ pub(super) fn master_key_from_env(file: Option<&str>,read_file: impl FnOnce(&Path) -> Result<String, String>,) -> Result<Option<([u8; KEY_LEN], String)>, String> {- let inline = inline.map(str::trim).filter(|value| !value.is_empty());- let file = file.map(str::trim).filter(|value| !value.is_empty());+ let inline = inline+ .filter(|value| env_source_is_configured(std::ffi::OsStr::new(value)))+ .map(str::trim);+ let file = file+ .filter(|value| env_source_is_configured(std::ffi::OsStr::new(value)))+ .map(str::trim);match (inline, file) {(None, None) => Ok(None),(Some(_), Some(_)) => Err(format!(@@ -126,6 +140,61 @@ pub(super) fn workspace_master_key(}}+/// Resolves a key for a profile-scoped diagnostic read without creating or+/// changing key state. Explicit operator key variables retain their normal+/// precedence; otherwise only an existing key file beneath `workspace` is+/// considered. Host key sources are excluded because they can prompt or mint.+pub(super) fn profile_master_key_read_only(+ workspace: &Path,+) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError> {+ let inline = env_value(MASTER_KEY_ENV, std::env::var(MASTER_KEY_ENV))+ .map_err(SecretStorageError::Backend)?;+ let file = env_value(MASTER_KEY_FILE_ENV, std::env::var(MASTER_KEY_FILE_ENV))+ .map_err(SecretStorageError::Backend)?;+ if let Some((key, _)) = master_key_from_env(+ inline.as_deref(),+ file.as_deref(),+ super::read_master_key_file,+ )+ .map_err(SecretStorageError::Backend)?+ {+ return Ok(Some(Zeroizing::new(key)));+ }++ let path = workspace.join("keyring/master.key");+ let metadata = match std::fs::symlink_metadata(&path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(_) => {+ return Err(SecretStorageError::Backend(+ "cannot inspect profile master key".into(),+ ));+ }+ };+ if !metadata.file_type().is_file() {+ return Err(SecretStorageError::Backend(+ "profile master key must be a regular file".into(),+ ));+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if metadata.permissions().mode() & 0o077 != 0 {+ return Err(SecretStorageError::Backend(+ "profile master key requires permissions 0600".into(),+ ));+ }+ }+ let text = Zeroizing::new(+ std::fs::read_to_string(&path)+ .map_err(|_| SecretStorageError::Backend("cannot read profile master key".into()))?,+ );+ parse_master_key_hex(text.trim())+ .map(Zeroizing::new)+ .map(Some)+ .map_err(SecretStorageError::Backend)+}+#[cfg(test)]#[path = "key_source_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rsindex c1af887e97..c78fb21284 100644--- a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs@@ -24,6 +24,97 @@ fn write_secret(backend: &EncryptedFileBackend, key: &[u8; KEY_LEN], value: &strbackend.set_with_key(key, "user:token", value).unwrap();}+fn write_profile_key(workspace: &Path, key: &[u8; KEY_LEN]) {+ let path = workspace.join("keyring/master.key");+ let encoded = crypto::hex_encode(key);+ file_store::write_atomic(&path, encoded.as_bytes()).unwrap();+}++#[test]+fn profile_read_only_secret_lookup_uses_only_the_selected_store() {+ let account_a = secrets_tempdir();+ let account_b = secrets_tempdir();+ let key_a = [0x42; KEY_LEN];+ let key_b = [0x24; KEY_LEN];+ write_profile_key(account_a.path(), &key_a);+ write_profile_key(account_b.path(), &key_b);++ let store_a = EncryptedFileBackend::new(account_a.path());+ let store_b = EncryptedFileBackend::new(account_b.path());+ store_a+ .set_with_key(&key_a, "account:session", "account-a-session")+ .unwrap();+ store_b+ .set_with_key(&key_b, "account:other", "account-b-other")+ .unwrap();+ let legacy = account_b.path().join(LEGACY_DEV_KEYCHAIN);+ std::fs::write(+ &legacy,+ serde_json::to_vec(&HashMap::from([(+ "account:session".to_string(),+ "ambient-session".to_string(),+ )]))+ .unwrap(),+ )+ .unwrap();++ assert_eq!(+ store_b.get_profile_read_only("account:session").unwrap(),+ None+ );+ assert_eq!(+ store_a+ .get_profile_read_only("account:session")+ .unwrap()+ .as_deref(),+ Some("account-a-session")+ );+ assert!(+ legacy.exists(),+ "read-only lookup must not import legacy data"+ );+}++#[test]+fn profile_read_only_secret_lookup_does_not_create_a_missing_key() {+ let _env = crate::config::test_env::EnvVarGuard::locked_unset_many(&[+ MASTER_KEY_ENV,+ MASTER_KEY_FILE_ENV,+ ]);+ let workspace = secrets_tempdir();+ let backend = EncryptedFileBackend::new(workspace.path());++ let error = backend+ .get_profile_read_only("account:session")+ .unwrap_err();++ assert!(error.to_string().contains("master key unavailable"));+ assert!(!workspace.path().join("keyring/master.key").exists());+}++#[test]+fn profile_read_only_secret_lookup_preserves_corrupt_store_bytes() {+ let workspace = secrets_tempdir();+ let key = [0x42; KEY_LEN];+ write_profile_key(workspace.path(), &key);+ let backend = EncryptedFileBackend::new(workspace.path());+ std::fs::write(&backend.path, b"corrupt encrypted store").unwrap();++ assert!(backend.get_profile_read_only("user:token").is_err());++ assert_eq!(+ std::fs::read(&backend.path).unwrap(),+ b"corrupt encrypted store"+ );+ assert!(!std::fs::read_dir(workspace.path())+ .unwrap()+ .flatten()+ .any(|entry| entry+ .file_name()+ .to_string_lossy()+ .starts_with("secrets.enc.corrupt.")));+}+#[test]fn legacy_plaintext_is_removed_only_after_verified_encrypted_migration() {let dir = secrets_tempdir();diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_store.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_store.rsindex 7f3531c4a3..1989140130 100644--- a/crates/openhuman-core/src/security/secret_storage/encrypted_store.rs+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_store.rs@@ -94,6 +94,28 @@ impl SecretStore {}}+ /// Decrypt one existing `enc2:` value using an explicitly supplied key.+ /// This does not consult or initialize the process keyring and does not+ /// migrate legacy `enc:` values.+ pub(crate) fn decrypt_with_existing_key(value: &str, key: &str) -> Result<String> {+ let Some(hex_str) = value.strip_prefix("enc2:") else {+ if value.starts_with("enc:") {+ anyhow::bail!("legacy encrypted value is unavailable to read-only inspection");+ }+ return Ok(value.to_string());+ };++ let key_bytes = decode_key_hex(key.trim())?;+ let key: [u8; KEY_LEN] = key_bytes+ .as_slice()+ .try_into()+ .map_err(|_| anyhow::anyhow!("invalid secret key length"))?;+ let key = Zeroizing::new(key);+ let blob = crypto::hex_decode(hex_str).map_err(anyhow::Error::msg)?;+ let plaintext = crypto::chacha20_decrypt(&key, &blob).map_err(anyhow::Error::msg)?;+ String::from_utf8(plaintext).context("decrypted secret is not valid UTF-8")+ }+/// Decrypt a secret and return a migrated `enc2:` value if the input used legacy `enc:` format.////// Returns `(plaintext, Some(new_enc2_value))` if migration occurred, ordiff --git a/crates/openhuman-core/src/skills/preflight.rs b/crates/openhuman-core/src/skills/preflight.rsindex e1df7e464b..810defe8c3 100644--- a/crates/openhuman-core/src/skills/preflight.rs+++ b/crates/openhuman-core/src/skills/preflight.rs@@ -51,6 +51,11 @@ const GIT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);pub enum GithubGateError {/// No active Composio connection found whose `toolkit == "github"`.ComposioGithubMissing,+ /// The doctor could not find a connector runtime already serving this+ /// selected configuration. Workflow execution still uses the live probes.+ ComposioProbeUnavailable,+ /// A matching existing connector returned a failed or malformed response.+ ComposioProbeFailed,/// `git --version` failed (binary missing, non-zero exit, …). The/// payload carries the underlying error message for the run log.GitBinaryMissing(String),@@ -83,6 +88,12 @@ impl GithubGateError {OAuth → GitHub) and re-run.".to_string()}+ GithubGateError::ComposioProbeUnavailable => {+ "GitHub preflight could not inspect a matching ready connector. Rerun after the selected connector is available.".to_string()+ }+ GithubGateError::ComposioProbeFailed => {+ "GitHub preflight could not read connection status from the existing connector. Rerun doctor and review the connector status.".to_string()+ }GithubGateError::GitBinaryMissing(err) => format!("GitHub preflight failed: local `git` is not available ({err}). \Install Git and make sure it's on PATH, then re-run."@@ -124,6 +135,8 @@ impl GithubGateError {pub fn tag(&self) -> &'static str {match self {GithubGateError::ComposioGithubMissing => "composio_github_missing",+ GithubGateError::ComposioProbeUnavailable => "composio_probe_unavailable",+ GithubGateError::ComposioProbeFailed => "composio_probe_failed",GithubGateError::GitBinaryMissing(_) => "git_binary_missing",GithubGateError::GitUserNameMissing => "git_user_name_missing",GithubGateError::GitUserEmailMissing => "git_user_email_missing",@@ -147,6 +160,21 @@ pub trait PreflightProbes: Send + Sync {/// registered, profile lookup failed, empty username).async fn composio_identity(&self, toolkit: &str) -> Option<String>;+ /// Detailed inspection result. Implementations used by doctor override+ /// this to distinguish a missing ready runtime from a real negative result.+ async fn composio_toolkit_status(&self, toolkit: &str) -> PreflightProbeStatus<bool> {+ PreflightProbeStatus::Available(self.composio_toolkit_active(toolkit).await)+ }++ /// Detailed identity result for doctor. Legacy workflow probes retain their+ /// established `Option` behavior through this default.+ async fn composio_identity_status(+ &self,+ toolkit: &str,+ ) -> PreflightProbeStatus<Option<String>> {+ PreflightProbeStatus::Available(self.composio_identity(toolkit).await)+ }+/// `git --version` outcome. `Ok(())` when git is on PATH and exits/// zero; `Err(message)` otherwise.async fn git_version(&self) -> Result<(), String>;@@ -160,6 +188,15 @@ pub trait PreflightProbes: Send + Sync {async fn git_user_email(&self) -> String;}+/// Read-only probe outcome used by doctor to report unavailable runtimes+/// separately from a live connector's negative or failed result.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PreflightProbeStatus<T> {+ Available(T),+ Unavailable,+ Failed,+}+/// Production probes — hits real Composio (via/// `composio::connection_identity` //// `composio::fetch_connected_integrations`) and the local `git`@@ -238,7 +275,7 @@ async fn git_config_value(key: &str) -> String {////// The gate is a no-op (immediate `Ok(())`) when the `[github]` block/// is absent (`cfg: None`) or `required = false`.-pub async fn run_github_preflight<P: PreflightProbes>(+pub async fn run_github_preflight<P: PreflightProbes + ?Sized>(cfg: Option<&WorkflowGithubConfig>,probes: &P,) -> Result<(), GithubGateError> {@@ -252,9 +289,16 @@ pub async fn run_github_preflight<P: PreflightProbes>(}// (1) Composio GitHub integration must be connected.- if !probes.composio_toolkit_active("github").await {- tracing::warn!("[workflows:preflight] github gate fail: composio_github_missing");- return Err(GithubGateError::ComposioGithubMissing);+ match probes.composio_toolkit_status("github").await {+ PreflightProbeStatus::Available(true) => {}+ PreflightProbeStatus::Available(false) => {+ tracing::warn!("[workflows:preflight] github gate fail: composio_github_missing");+ return Err(GithubGateError::ComposioGithubMissing);+ }+ PreflightProbeStatus::Unavailable => {+ return Err(GithubGateError::ComposioProbeUnavailable);+ }+ PreflightProbeStatus::Failed => return Err(GithubGateError::ComposioProbeFailed),}// (2) git binary present.@@ -287,28 +331,32 @@ pub async fn run_github_preflight<P: PreflightProbes>(IdentityMatch::Any => {// "any" still requires the Composio side to surface an// identity — confirms the connection is genuinely usable.- match probes.composio_identity("github").await {- Some(_) => {+ match probes.composio_identity_status("github").await {+ PreflightProbeStatus::Available(Some(_)) => {tracing::debug!("[workflows:preflight] github gate pass (identity_match=any)");Ok(())}- None => {- tracing::warn!(- "[workflows:preflight] github gate fail: composio_identity_unresolved (identity_match=any)"- );+ PreflightProbeStatus::Available(None) => {+ tracing::warn!("[workflows:preflight] github gate fail: composio_identity_unresolved (identity_match=any)");Err(GithubGateError::ComposioIdentityUnresolved)}+ PreflightProbeStatus::Unavailable => Err(GithubGateError::ComposioProbeUnavailable),+ PreflightProbeStatus::Failed => Err(GithubGateError::ComposioProbeFailed),}}IdentityMatch::Strict => {- let composio_name = match probes.composio_identity("github").await {- Some(n) => n,- None => {+ let composio_name = match probes.composio_identity_status("github").await {+ PreflightProbeStatus::Available(Some(n)) => n,+ PreflightProbeStatus::Available(None) => {tracing::warn!("[workflows:preflight] github gate fail: composio_identity_unresolved (identity_match=strict)");return Err(GithubGateError::ComposioIdentityUnresolved);}+ PreflightProbeStatus::Unavailable => {+ return Err(GithubGateError::ComposioProbeUnavailable);+ }+ PreflightProbeStatus::Failed => return Err(GithubGateError::ComposioProbeFailed),};if composio_name.trim().eq_ignore_ascii_case(git_name.trim()) {tracing::debug!(diff --git a/crates/openhuman-core/src/storage/fenced_backend_tests.rs b/crates/openhuman-core/src/storage/fenced_backend_tests.rsindex 78a73dc688..20ceafbacc 100644--- a/crates/openhuman-core/src/storage/fenced_backend_tests.rs+++ b/crates/openhuman-core/src/storage/fenced_backend_tests.rs@@ -243,6 +243,16 @@ impl LeaseStore for PausedAfterCheck {Ok(record)}+ async fn holder_readonly(+ &self,+ key: &str,+ ) -> std::result::Result<+ Option<crate::storage::lease::LeaseRecord>,+ crate::storage::lease::LeaseError,+ > {+ self.inner.holder_readonly(key).await+ }+fn driver_fence(&self, key: &str, node: &str, epoch: u64) -> Option<tinystoragedrivers::Fence> {self.inner.driver_fence(key, node, epoch)}diff --git a/crates/openhuman-core/src/storage/inspection.rs b/crates/openhuman-core/src/storage/inspection.rsnew file mode 100644index 0000000000..211d4bf9e2--- /dev/null+++ b/crates/openhuman-core/src/storage/inspection.rs@@ -0,0 +1,15 @@+//! Local filesystem probes used by static diagnostics.++use std::io::Write;+use std::path::Path;++/// Creates, writes, and immediately removes a bounded temporary file in a+/// directory to verify the process can actually write there.+pub(crate) fn probe_directory_writable(directory: &Path) -> std::io::Result<()> {+ let mut file = tempfile::Builder::new()+ .prefix(".openhuman-doctor-")+ .tempfile_in(directory)?;+ file.as_file_mut().write_all(b"openhuman-write-probe")?;+ file.close()?;+ Ok(())+}diff --git a/crates/openhuman-core/src/storage/lease.rs b/crates/openhuman-core/src/storage/lease.rsindex b2149ea51b..fc2f04655b 100644--- a/crates/openhuman-core/src/storage/lease.rs+++ b/crates/openhuman-core/src/storage/lease.rs@@ -171,6 +171,15 @@ pub trait LeaseStore: Send + Sync {/// [`LeaseError::Storage`].async fn holder(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError>;+ /// Reads the stored holder without declaring schema or creating local+ /// lease files. Implementations that cannot guarantee a read-only lookup+ /// fail closed.+ async fn holder_readonly(&self, _key: &str) -> Result<Option<LeaseRecord>, LeaseError> {+ Err(LeaseError::Storage(StorageError::backend(+ "lease store does not support read-only holder inspection",+ )))+ }+/// The fence a storage driver enforces for `node`'s grant on `key` at/// `epoch`, when the record lives in the storage ports at all: the/// record must still name `node` at `epoch`, unreleased. The driver thendiff --git a/crates/openhuman-core/src/storage/lease_documents.rs b/crates/openhuman-core/src/storage/lease_documents.rsindex a30493416d..1b8f5bb533 100644--- a/crates/openhuman-core/src/storage/lease_documents.rs+++ b/crates/openhuman-core/src/storage/lease_documents.rs@@ -22,7 +22,8 @@ use std::time::Duration;use async_trait::async_trait;use tinystoragedrivers::primitives::{self, Acquire, Acquisition};use tinystoragedrivers::{- CollectionSpec, DocumentStore, Fence, Filter, Key, Leases, Scope, StorageBackend, Version,+ CollectionSpec, DocumentStore, ErrorKind, Fence, Filter, Key, Leases, Scope, StorageBackend,+ Version,};use super::lease::{@@ -344,6 +345,38 @@ impl LeaseStore for DocumentLeases {.map(record_of))}+ async fn holder_readonly(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError> {+ validate_key(key)?;+ match self+ .docs+ .validate_collection_spec(&CollectionSpec::new(LEASE_COLLECTION))+ .await+ {+ Ok(()) => {}+ Err(error) if error.kind() == ErrorKind::NotFound => {+ match self+ .docs+ .validate_collection_spec(&CollectionSpec::new("leases"))+ .await+ {+ Ok(()) => {+ return Err(LeaseError::Storage(StorageError::backend(+ "legacy profile leases require explicit storage migration",+ )));+ }+ Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(LeaseError::Storage(error)),+ }+ }+ Err(error) => return Err(LeaseError::Storage(error)),+ }+ self.leases_at(0)+ .inspect(LEASE_OWNER, key)+ .await+ .map(|record| record.map(record_of))+ .map_err(LeaseError::from)+ }+fn driver_fence(&self, key: &str, node: &str, epoch: u64) -> Option<Fence> {let scope = self.scope.clone()?;let id = Key::of([LEASE_OWNER, key]).ok()?;diff --git a/crates/openhuman-core/src/storage/lease_documents_tests.rs b/crates/openhuman-core/src/storage/lease_documents_tests.rsindex 9334cd277b..694f147bea 100644--- a/crates/openhuman-core/src/storage/lease_documents_tests.rs+++ b/crates/openhuman-core/src/storage/lease_documents_tests.rs@@ -3,7 +3,7 @@ use super::*;use std::time::Duration;use crate::storage::MemoryStorage;-use tinystoragedrivers::Precondition;+use tinystoragedrivers::{CollectionSpec, Precondition, Scope};const TTL: Duration = Duration::from_millis(1_000);@@ -11,6 +11,31 @@ fn node(storage: &MemoryStorage, id: &str) -> DocumentLeases {DocumentLeases::cluster(storage, id, Some(format!("http://{id}")), TTL).unwrap()}+#[tokio::test]+async fn doctor_holder_inspection_does_not_declare_the_lease_collection() {+ let storage = MemoryStorage::new();+ let leases = node(&storage, "a");+ let documents = storage+ .for_scope(&Scope::new(CLUSTER_SCOPE).unwrap())+ .unwrap();+ let spec = CollectionSpec::new(LEASE_COLLECTION);++ assert!(documents+ .documents()+ .validate_collection_spec(&spec)+ .await+ .is_err());+ assert!(leases.holder_readonly("alice").await.unwrap().is_none());+ assert!(+ documents+ .documents()+ .validate_collection_spec(&spec)+ .await+ .is_err(),+ "a doctor-style holder inspection must not create storage schema"+ );+}+#[tokio::test]async fn acquire_contend_expire_and_take_over() {let storage = MemoryStorage::new();diff --git a/crates/openhuman-core/src/storage/lease_local.rs b/crates/openhuman-core/src/storage/lease_local.rsindex 18ea7f9f69..0ae5ac188d 100644--- a/crates/openhuman-core/src/storage/lease_local.rs+++ b/crates/openhuman-core/src/storage/lease_local.rs@@ -306,6 +306,34 @@ impl LeaseStore for LocalLeases {}Ok(Some(record))}++ async fn holder_readonly(&self, key: &str) -> Result<Option<LeaseRecord>, LeaseError> {+ validate_key(key)?;+ if let Some(holding) = self.held().get(key) {+ return Ok(Some(holding.record.clone()));+ }+ let Some(mut record) = self.read_record(key)? else {+ return Ok(None);+ };+ if !record.released {+ let path = local_dir(&self.root, key).join(LOCK_FILE);+ match OpenOptions::new().read(true).open(&path) {+ Ok(file) => match file.try_lock_exclusive() {+ Ok(()) => {+ let _ = FileExt::unlock(&file);+ record.expires_at_ms = 0;+ }+ Err(error) if is_contended(&error) => {}+ Err(error) => return Err(io_error("open", &path, &error).into()),+ },+ Err(error) if error.kind() == io::ErrorKind::NotFound => {+ record.expires_at_ms = 0;+ }+ Err(error) => return Err(io_error("open", &path, &error).into()),+ }+ }+ Ok(Some(record))+ }}#[cfg(test)]diff --git a/crates/openhuman-core/src/storage/lease_local_tests.rs b/crates/openhuman-core/src/storage/lease_local_tests.rsindex 68368b2e31..7d026226ab 100644--- a/crates/openhuman-core/src/storage/lease_local_tests.rs+++ b/crates/openhuman-core/src/storage/lease_local_tests.rs@@ -1,5 +1,39 @@use super::*;+#[tokio::test]+async fn doctor_holder_inspection_does_not_create_a_lock_file() {+ let dir = tempfile::tempdir().unwrap();+ let key_dir = local_dir(dir.path(), "k");+ fs::create_dir_all(&key_dir).unwrap();+ fs::write(+ key_dir.join(RECORD_FILE),+ serde_json::to_vec(&LeaseRecord {+ owner: "previous-node".into(),+ endpoint: None,+ epoch: 1,+ expires_at_ms: u64::MAX,+ released: false,+ })+ .unwrap(),+ )+ .unwrap();+ let lock_path = key_dir.join(LOCK_FILE);+ assert!(!lock_path.exists());++ let observer = LocalLeases::new(dir.path(), "doctor");+ let record = observer.holder_readonly("k").await.unwrap().unwrap();++ assert_eq!(record.owner, "previous-node");+ assert!(+ !record.is_live(0),+ "the absent lock means no holder is live"+ );+ assert!(+ !lock_path.exists(),+ "a read-only holder inspection must not create the lock file"+ );+}+#[tokio::test]async fn a_second_instance_on_one_root_is_held_out() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rsindex bfa7c6a363..ea71c53a5d 100644--- a/crates/openhuman-core/src/storage/mod.rs+++ b/crates/openhuman-core/src/storage/mod.rs@@ -34,6 +34,7 @@ pub mod fenced_backend;mod host_importers;pub mod import;pub mod import_state;+mod inspection;pub mod journal_maintenance;pub mod layout;pub mod lease;@@ -43,6 +44,7 @@ pub mod local;pub mod rebind;pub mod schema;pub mod schema_support;+pub(crate) use inspection::probe_directory_writable;pub mod scope;pub mod scope_move;pub mod secrets;diff --git a/crates/openhuman-core/src/threads/ops/live_state.rs b/crates/openhuman-core/src/threads/ops/live_state.rsindex 751985c96c..ca6e3d2690 100644--- a/crates/openhuman-core/src/threads/ops/live_state.rs+++ b/crates/openhuman-core/src/threads/ops/live_state.rs@@ -30,7 +30,7 @@ pub struct ThreadGoalGetResponse {/// thread has never written one.#[derive(Debug, Clone, serde::Serialize)]pub struct ThreadTodosGetResponse {- pub todos: Vec<tinyagents_graph::todos::TodoItem>,+ pub todos: Vec<tinyagents_harness_tools::todos::TodoItem>,}/// `threads.goal_get` — read a thread's current goal without waiting for the@@ -62,7 +62,7 @@ pub async fn todos_get(return Err("thread_id is required".to_string());}let store = crate::storage::sessions::stores_or_ephemeral(&dir).kv;- let todos = match tinyagents_graph::todos::store::list(&store, thread_id).await {+ let todos = match tinyagents_harness_tools::todos::store::list(&store, thread_id).await {Ok(snapshot) => snapshot.items,Err(e) => {log::debug!("[threads] todos_get thread_id={thread_id} list failed: {e}");diff --git a/crates/openhuman-core/src/threads/ops/live_state_tests.rs b/crates/openhuman-core/src/threads/ops/live_state_tests.rsindex fdacf4f6e9..50d7dff5cb 100644--- a/crates/openhuman-core/src/threads/ops/live_state_tests.rs+++ b/crates/openhuman-core/src/threads/ops/live_state_tests.rs@@ -8,7 +8,7 @@use super::*;use crate::config::TEST_ENV_LOCK;-use tinyagents_graph::todos::{TodoItem, TodoStatus};+use tinyagents_harness_tools::todos::{TodoItem, TodoStatus};#[test]fn thread_live_state_request_parses_thread_id() {@@ -63,7 +63,7 @@ async fn goal_get_reads_back_a_stored_goal() {.await.unwrap().workspace_dir;- tinyagents_graph::goals::store::set(+ tinyagents_harness_tools::goals::store::set(&crate::storage::sessions::stores_or_ephemeral(&dir).kv,"thread-goal-live","ship it",@@ -102,7 +102,7 @@ async fn todos_get_reads_back_what_the_todo_tool_wrote() {assert!(empty_json["data"]["todos"].as_array().unwrap().is_empty());let store = crate::storage::sessions::stores_or_ephemeral(&dir).kv;- tinyagents_graph::todos::store::replace(+ tinyagents_harness_tools::todos::store::replace(&store,"thread-todos-live",vec![TodoItem::with_status("write tests", TodoStatus::InProgress)],diff --git a/crates/openhuman-core/src/tools/README.md b/crates/openhuman-core/src/tools/README.mdindex 2b0e61ef99..f961ba4dbf 100644--- a/crates/openhuman-core/src/tools/README.md+++ b/crates/openhuman-core/src/tools/README.md@@ -141,7 +141,7 @@ Where the built-in tools come from:| `file_read`, `file_write`, `edit`, `apply_patch`, `grep`, `glob`, `list`, `read_diff`, `csv_export`, `git_operations`, `run_linter`, `run_tests`, `image_info`, `read_workspace_state` | `tinytools_std::filesystem`, gated by [`impl/filesystem/gate.rs`](./impl/filesystem/gate.rs) || `detect_tools`, `curl`, `pushover` | `tinytools_std` || `http_request`, `web_fetch` | `tinytools_std::network`, wired with host limits, TinyJuice extraction and the x402 handler in [`impl/network/host.rs`](./impl/network/host.rs) |-| `current_time`, `resolve_time`, `ask_user_clarification`, `wait`, `wait_loop` | `tinyagents_harness::tools` |+| `current_time`, `resolve_time`, `ask_user_clarification`, `wait`, `wait_loop` | `tinyagents_harness_tools` || `shell`, `install_tool`, `schedule`, `proxy_config`, `lsp`, `update_check`, `update_apply`, `retrieve_tool_output` | [`impl/system/`](./impl/system/) || `gitbooks_search`, `gitbooks_get_page`, `gmail_unsubscribe`, `mcp_list_servers`, `mcp_list_tools`, `mcp_call_tool`, `mcp_<server>_<tool>` | [`impl/network/`](./impl/network/) (MCP tools behind `mcp`) || `browser`, `browser_open` | [`impl/browser/`](./impl/browser/) (behind `modules`) |diff --git a/crates/openhuman-core/src/tools/host_extensions.rs b/crates/openhuman-core/src/tools/host_extensions.rsindex 1c4a958efe..43ee310484 100644--- a/crates/openhuman-core/src/tools/host_extensions.rs+++ b/crates/openhuman-core/src/tools/host_extensions.rs@@ -5,22 +5,10 @@//! host implementation details, not portable tool-trait APIs.use crate::agent::orchestration::tools::DelegationTarget;-use tinyagents_harness::tool::packs::{PackRegistryHandle, PackToolExtension};#[cfg(test)]use tinytools::{PermissionLevel, ToolCategory, ToolResult, ToolScope};use tinytools::{Tool, ToolRunContext};-/// Reads a tool's pack-registry handle from its erased host extension.-pub fn pack_registry_handle(tool: &dyn Tool) -> Option<&PackRegistryHandle> {- tool.host_extension()- .and_then(|any| any.downcast_ref::<PackToolExtension>())- .map(PackToolExtension::registry_handle)- .or_else(|| {- tool.host_extension()- .and_then(|any| any.downcast_ref::<PackRegistryHandle>())- })-}-/// Reads the target agent a synthesized `delegate_*` tool routes to.pub fn delegation_target(tool: &dyn Tool) -> Option<&str> {tool.host_extension()diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex d217f6f98d..b1e45023d0 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -7,7 +7,7 @@ use crate::security::{AuditLogger, SecurityPolicy};use crate::tools::delegate::DelegateTool;use std::collections::HashMap;use std::sync::Arc;-use tinyagents_harness::tools::{CurrentTimeTool, ResolveTimeTool};+use tinyagents_harness_tools::{CurrentTimeTool, ResolveTimeTool};use tinytools::Tool;use tinytools_std::detect_tools::DetectToolsTool;use tinytools_std::filesystem::{@@ -86,6 +86,42 @@ pub fn all_tools_with_runtime(root_config: &crate::config::Config,approval_workspace_root: Option<&std::path::Path>,) -> Vec<Box<dyn Tool>> {+ all_tools_with_runtime_and_pack_handle(+ config,+ security,+ runtime,+ audit,+ browser_config,+ http_config,+ action_dir,+ agents,+ root_config,+ approval_workspace_root,+ )+ .0+}++/// Build the full tool registry and return its pack handle alongside it.+///+/// The handle belongs to the session that owns the registry; callers retain it+/// so later registry refreshes can rebind `use_skill` without inspecting the+/// tool's generic dispatch extension.+#[allow(clippy::implicit_hasher, clippy::too_many_arguments)]+pub fn all_tools_with_runtime_and_pack_handle(+ config: Arc<Config>,+ security: &Arc<SecurityPolicy>,+ runtime: Arc<dyn RuntimeAdapter>,+ audit: Arc<AuditLogger>,+ browser_config: &crate::config::BrowserConfig,+ http_config: &crate::config::HttpRequestConfig,+ action_dir: &std::path::Path,+ agents: &HashMap<String, DelegateAgentConfig>,+ root_config: &crate::config::Config,+ approval_workspace_root: Option<&std::path::Path>,+) -> (+ Vec<Box<dyn Tool>>,+ tinyagents_harness_tools::skills::PackRegistryHandle,+) {let shell: Box<dyn Tool> = Box::new(ShellTool::with_config(security.clone(),Arc::clone(&runtime),@@ -182,9 +218,7 @@ pub fn all_tools_with_runtime(// lifecycle. doctor/health/cost/dashboard/security reads are default-ON.// service_status / daemon_host_prefs_get default-ON; the lifecycle// mutators ship default-OFF via `tools::user_filter` (service_lifecycle).- tools.extend(crate::platform::doctor::tools::registered_tools(- config.clone(),- ));+ tools.extend(crate::doctor::tools::registered_tools(config.clone()));tools.extend(crate::platform::health::tools::registered_tools());tools.extend(crate::platform::cost::tools::registered_tools(config.clone(),@@ -572,13 +606,13 @@ pub fn all_tools_with_runtime(// cover the `delegate_*` tools synthesised later by// `orchestrator_tools::collect_orchestrator_tools` — which never pass// through this function.- crate::tools::toolpacks::append_pack_tools(&mut tools);+ let pack_registry = crate::tools::toolpacks::append_pack_tools(&mut tools);// The lookup half of `ToolExposure::Deferred` is not registered here: the// tinyagents harness advertises its intrinsic `tool_search` bridge// (a found tool is then called by its own name) whenever a run has a// deferred tool (`tool::discover`), ranked by whatever `agent::tinyagents::discovery` installed. A host-registered// `tool_search` would shadow that bridge.- tools+ (tools, pack_registry)}#[path = "ops_tool_groups.rs"]diff --git a/crates/openhuman-core/src/tools/registry/mod.rs b/crates/openhuman-core/src/tools/registry/mod.rsindex 472c488d20..454f3fc3fd 100644--- a/crates/openhuman-core/src/tools/registry/mod.rs+++ b/crates/openhuman-core/src/tools/registry/mod.rs@@ -11,6 +11,7 @@ pub use providers::{normalize_capability_provider_id, CapabilityProviderMetadata, CapabilityProviderRegistry,CapabilityProviderRegistryError,};+pub(crate) use schemas::all_bound_controller_entries as all_tool_registry_bound_controller_entries;pub use schemas::{all_controller_schemas as all_tool_registry_controller_schemas,all_registered_controllers as all_tool_registry_registered_controllers,diff --git a/crates/openhuman-core/src/tools/registry/schemas.rs b/crates/openhuman-core/src/tools/registry/schemas.rsindex c5ac81fd45..e2f75d8867 100644--- a/crates/openhuman-core/src/tools/registry/schemas.rs+++ b/crates/openhuman-core/src/tools/registry/schemas.rs@@ -1,7 +1,9 @@use crate::core::runtime::DispatchCtx;use serde_json::{Map, Value};-use crate::core::all::{ControllerFuture, RegisteredController};+use crate::core::all::{+ BoundRegisteredController, ControllerEntry, ControllerFuture, RegisteredController,+};use crate::core::Outcome;use crate::core::{ControllerSchema, FieldSchema, TypeSchema};@@ -28,6 +30,27 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {]}+/// Bound runtime entries for the `tool_registry` namespace.+pub(crate) fn all_bound_controller_entries() -> Vec<ControllerEntry> {+ vec![+ ControllerEntry::bound(BoundRegisteredController::typed(+ schemas("list"),+ parse_list,+ run_list,+ )),+ ControllerEntry::bound(BoundRegisteredController::typed(+ schemas("get"),+ parse_get,+ run_get,+ )),+ ControllerEntry::bound(BoundRegisteredController::typed(+ schemas("diagnostics"),+ parse_diagnostics,+ run_diagnostics,+ )),+ ]+}+/// Return the schema for one `tool_registry` function.pub fn schemas(function: &str) -> ControllerSchema {match function {@@ -122,6 +145,46 @@ fn handle_diagnostics(_ctx: DispatchCtx, params: Map<String, Value>) -> Controll})}+fn parse_list(_params: Map<String, Value>) -> Result<(), String> {+ Ok(())+}++fn parse_get(params: Map<String, Value>) -> Result<String, String> {+ required_tool_id(¶ms).map(str::to_owned)+}++fn parse_diagnostics(_params: Map<String, Value>) -> Result<(), String> {+ Ok(())+}++fn run_list(ctx: DispatchCtx, (): ()) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[tool_registry] rpc list requested");+ to_json(crate::tools::registry::ops::list_tools(&ctx))+ })+}++fn run_get(ctx: DispatchCtx, tool_id: String) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[tool_registry] rpc get requested tool_id={tool_id}");+ to_json(crate::tools::registry::ops::get_tool(&ctx, &tool_id)?)+ })+}++fn run_diagnostics(_ctx: DispatchCtx, (): ()) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[tool_registry] rpc diagnostics requested");+ let result = crate::tools::registry::ops::diagnostics()+ .await+ .and_then(to_json);+ log::debug!(+ "[tool_registry] rpc diagnostics completed success={}",+ result.is_ok()+ );+ result+ })+}+fn required_tool_id(params: &Map<String, Value>) -> Result<&str, String> {params.get("tool_id")diff --git a/crates/openhuman-core/src/tools/registry/schemas_tests.rs b/crates/openhuman-core/src/tools/registry/schemas_tests.rsindex def6a1b9a6..25bebf0fb6 100644--- a/crates/openhuman-core/src/tools/registry/schemas_tests.rs+++ b/crates/openhuman-core/src/tools/registry/schemas_tests.rs@@ -39,6 +39,14 @@ fn diagnostics_schema_has_no_inputs() {assert_eq!(schema.outputs[0].name, "diagnostics");}+#[test]+fn required_tool_id_trims_padded_ids_before_lookup() {+ let mut params = Map::new();+ params.insert("tool_id".to_string(), json!(" tools.web_search "));++ assert_eq!(parse_get(params).unwrap(), "tools.web_search");+}+#[test]fn required_tool_id_rejects_wrong_type() {let mut params = Map::new();diff --git a/crates/openhuman-core/src/tools/toolpacks/README.md b/crates/openhuman-core/src/tools/toolpacks/README.mdindex 4e89e358a5..6bda5c15dd 100644--- a/crates/openhuman-core/src/tools/toolpacks/README.md+++ b/crates/openhuman-core/src/tools/toolpacks/README.md@@ -35,7 +35,7 @@ constructed and executable but unadvertised: the agent sees one small tool,session-scoped listing (`render_pack_filtered` + `route_sentence`) isproduced by the tinyagents policy middleware, which is the only layer thatholds the session (see below).-- `tinyagents_harness::tool::packs::PackRegistryHandle` is the late-bound, non-owning (`Weak`) view the+- `tinyagents_harness_tools::skills::PackRegistryHandle` is the late-bound, non-owning (`Weak`) view theproxy dispatches through. It holds two registries: the durable tool `Arc`and the agent's `synthesized_tools` `Arc`, where every `delegate_*` toollives. Each must be rebound after its `Arc` is replaced, or packed@@ -43,7 +43,7 @@ constructed and executable but unadvertised: the agent sees one small tool,on `Tool::host_extension` and is read back by`tools::host_extensions::pack_registry_handle`. The proxy itself(`UseSkillTool`, `PackCatalog`, `ToolPack`, the listing/scoping renderers) lives in- `tinyagents_harness::tool::packs`; this module keeps the pack table+ `tinyagents_harness_tools::skills`; this module keeps the pack table(`registry::PACKS`, handed over as `registry::CATALOG`), the group posture and theregistry binding.- `ops::strip_packed_from_visible` does the actual compression: it removes adiff --git a/crates/openhuman-core/src/tools/toolpacks/mod.rs b/crates/openhuman-core/src/tools/toolpacks/mod.rsindex 9f70b5caa9..5412c326cf 100644--- a/crates/openhuman-core/src/tools/toolpacks/mod.rs+++ b/crates/openhuman-core/src/tools/toolpacks/mod.rs@@ -7,7 +7,7 @@//! idle in most conversations.//!//! A pack keeps its tools constructed and executable but unadvertised. The-//! agent sees one small tool instead: `tinyagents_harness::tool::packs::UseSkillTool` renders a pack's+//! agent sees one small tool instead: `tinyagents_harness_tools::skills::UseSkillTool` renders a pack's//! schemas into the conversation when called with a `skill` alone, and executes//! one of them when also given a `tool`, forwarding permission level and//! execution context to the real tool so nothing is laundered through the@@ -27,6 +27,7 @@ pub mod ops;pub mod registry;pub use groups::{set_process_default, GroupMode, ToolGroups, GROUP_COUNT};+pub(crate) use ops::is_canonical_use_skill_tool;pub use ops::{append_pack_tools, bind_pack_registry, bind_synthesized_pack_registry, close_handed_off_packs,closed_by_direct_handoff, strip_packed_from_visible,diff --git a/crates/openhuman-core/src/tools/toolpacks/ops.rs b/crates/openhuman-core/src/tools/toolpacks/ops.rsindex 2e42a6a17e..b7990c04cf 100644--- a/crates/openhuman-core/src/tools/toolpacks/ops.rs+++ b/crates/openhuman-core/src/tools/toolpacks/ops.rs@@ -4,18 +4,38 @@ use std::collections::HashSet;use std::sync::{Arc, Weak};use super::registry;-use tinyagents_harness::tool::packs::{PackRegistryHandle, UseSkillTool, USE_SKILL};+use tinyagents_harness_tools::skills::{PackRegistryHandle, UseSkillTool, USE_SKILL};use tinytools::Tool;-/// Append `use_skill` to a freshly built registry.-///-/// It starts unbound; [`bind_pack_registry`] gives it its view of the registry-/// once that is behind an `Arc`.-pub fn append_pack_tools(tools: &mut Vec<Box<dyn Tool>>) {+/// Append `use_skill` to a freshly built registry and return the handle its+/// owner must retain for later rebinding.+pub fn append_pack_tools(tools: &mut Vec<Box<dyn Tool>>) -> PackRegistryHandle {+ let handle = PackRegistryHandle::default();tools.push(Box::new(UseSkillTool::new(- PackRegistryHandle::default(),+ handle.clone(),registry::CATALOG,)));+ handle+}++/// Whether `tool` is the canonical OpenHuman `use_skill` proxy built from the+/// compiled pack catalog. Public callers of `all_tools()` cannot carry the+/// handle separately, so the session builder uses this signature to replace+/// only that proxy with a session-owned handle before binding it.+pub(crate) fn is_canonical_use_skill_tool(tool: &dyn Tool) -> bool {+ if tool.name() != USE_SKILL+ || tool+ .host_extension()+ .and_then(|extension| {+ extension.downcast_ref::<tinyagents_harness::tool::ToolCallBinding>()+ })+ .is_none()+ {+ return false;+ }+ let canonical = UseSkillTool::new(PackRegistryHandle::default(), registry::CATALOG);+ tool.description() == canonical.description()+ && tool.parameters_schema() == canonical.parameters_schema()}/// Point the pack tool at the durable registry it lives in.@@ -28,10 +48,13 @@ pub fn append_pack_tools(tools: &mut Vec<Box<dyn Tool>>) {/// This is only half the registry. Every `delegate_*` tool lives in the agent's/// separate `synthesized_tools` `Arc`, so a packed delegate is reachable only/// once [`bind_synthesized_pack_registry`] has run too.-pub fn bind_pack_registry(tools: &Arc<Vec<Box<dyn Tool>>>) {+pub fn bind_pack_registry(handle: &PackRegistryHandle, tools: &Arc<Vec<Box<dyn Tool>>>) {let weak: Weak<Vec<Box<dyn Tool>>> = Arc::downgrade(tools);- let bound = for_each_pack_tool(tools, |handle| handle.bind(weak.clone()));- tracing::debug!(bound, "[toolpacks] bound pack tool to durable registry");+ handle.bind(weak);+ tracing::debug!(+ tools = tools.len(),+ "[toolpacks] bound pack tool to durable registry"+ );}/// Point the pack tool at the synthesised delegate set.@@ -45,36 +68,17 @@ pub fn bind_pack_registry(tools: &Arc<Vec<Box<dyn Tool>>>) {/// at which point every packed delegate reports "no tool in skill" instead of/// running.pub fn bind_synthesized_pack_registry(- durable: &Arc<Vec<Box<dyn Tool>>>,+ handle: &PackRegistryHandle,synthesized: &Arc<Vec<Box<dyn Tool>>>,) {let weak: Weak<Vec<Box<dyn Tool>>> = Arc::downgrade(synthesized);- let bound = for_each_pack_tool(durable, |handle| handle.bind_synthesized(weak.clone()));+ handle.bind_synthesized(weak);tracing::debug!(- bound,delegates = synthesized.len(),"[toolpacks] bound pack tool to synthesised delegate set");}-/// Apply `edit` to every pack tool's handle in `tools`, returning how many.-fn for_each_pack_tool(- tools: &Arc<Vec<Box<dyn Tool>>>,- mut edit: impl FnMut(&PackRegistryHandle),-) -> usize {- let mut bound = 0usize;- for tool in tools.iter() {- if tool.name() != USE_SKILL {- continue;- }- if let Some(handle) = crate::tools::host_extensions::pack_registry_handle(tool.as_ref()) {- edit(handle);- bound += 1;- }- }- bound-}-/// Remove packed tool names from an agent's advertised set.////// This is the whole compression: the tools stay registered and executable, butdiff --git a/crates/openhuman-core/src/tools/toolpacks/registry.rs b/crates/openhuman-core/src/tools/toolpacks/registry.rsindex bab39d2be3..d4bfd7167c 100644--- a/crates/openhuman-core/src/tools/toolpacks/registry.rs+++ b/crates/openhuman-core/src/tools/toolpacks/registry.rs@@ -4,7 +4,7 @@//! could edit would let a caller move a dangerous tool out of the advertised//! surface (or back into it) without review. Adding a pack is a source change.-use tinyagents_harness::tool::packs::{PackCatalog, ToolPack};+use tinyagents_harness_tools::skills::{PackCatalog, ToolPack};/// Every pack this build knows about.///@@ -410,7 +410,7 @@ pub(crate) const DELIBERATELY_UNPACKED_FLEET_TOOLS: &[&str] = &[];/// The lookup surface over [`PACKS`] handed to the generic `use_skill` tool-/// (`tinyagents_harness::tool::packs`). `NOT_FOUND_MARKER` is the host's status+/// (`tinyagents_harness_tools::skills`). `NOT_FOUND_MARKER` is the host's status/// vocabulary, so a "no such skill / tool" result classifies as `NotFound`.pub const CATALOG: PackCatalog = PackCatalog::new(PACKS, tinytools::status::NOT_FOUND_MARKER);diff --git a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rsindex 96457af298..eafc62d59d 100644--- a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs+++ b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs@@ -11,7 +11,8 @@ use async_trait::async_trait;use serde_json::{json, Value};use super::*;-use tinyagents_harness::tool::packs::USE_SKILL;+use tinyagents_harness_tools::skills::PackRegistryHandle;+use tinyagents_harness_tools::skills::USE_SKILL;use tinytools::{PermissionLevel, Tool, ToolResult, ToolTimeout};struct FakeTool {@@ -47,7 +48,7 @@ impl Tool for FakeTool {}/// A registry holding several real packed tools plus the two pack tools, bound.-fn registry_with_all(names: &[&'static str]) -> Arc<Vec<Box<dyn Tool>>> {+fn registry_with_all(names: &[&'static str]) -> (Arc<Vec<Box<dyn Tool>>>, PackRegistryHandle) {let mut tools: Vec<Box<dyn Tool>> = names.iter().map(|name| {@@ -59,24 +60,27 @@ fn registry_with_all(names: &[&'static str]) -> Arc<Vec<Box<dyn Tool>>> {}) as Box<dyn Tool>}).collect();- append_pack_tools(&mut tools);+ let handle = append_pack_tools(&mut tools);let tools = Arc::new(tools);- bind_pack_registry(&tools);- tools+ bind_pack_registry(&handle, &tools);+ (tools, handle)}/// A registry holding one real packed tool plus the two pack tools, bound.-fn registry_with(name: &'static str, level: PermissionLevel) -> Arc<Vec<Box<dyn Tool>>> {+fn registry_with(+ name: &'static str,+ level: PermissionLevel,+) -> (Arc<Vec<Box<dyn Tool>>>, PackRegistryHandle) {let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(FakeTool {name,level,external: false,timeout: ToolTimeout::Inherit,})];- append_pack_tools(&mut tools);+ let handle = append_pack_tools(&mut tools);let tools = Arc::new(tools);- bind_pack_registry(&tools);- tools+ bind_pack_registry(&handle, &tools);+ (tools, handle)}fn find<'a>(tools: &'a [Box<dyn Tool>], name: &str) -> &'a dyn Tool {@@ -96,9 +100,12 @@ type ToolRegistry = Arc<Vec<Box<dyn Tool>>>;/// This is not a contrived shape. Every `delegate_*` tool is synthesised into/// `OpenHumanSessionHost::synthesized_tools`, a different `Arc` from the durable registry/// (#6145), and seven delegates were already packed.-fn split_registries(name: &'static str, level: PermissionLevel) -> (ToolRegistry, ToolRegistry) {+fn split_registries(+ name: &'static str,+ level: PermissionLevel,+) -> (ToolRegistry, ToolRegistry, PackRegistryHandle) {let mut durable: Vec<Box<dyn Tool>> = Vec::new();- append_pack_tools(&mut durable);+ let handle = append_pack_tools(&mut durable);let durable = Arc::new(durable);let synthesized: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(FakeTool {name,@@ -106,9 +113,9 @@ fn split_registries(name: &'static str, level: PermissionLevel) -> (ToolRegistryexternal: false,timeout: ToolTimeout::Inherit,})]);- bind_pack_registry(&durable);- bind_synthesized_pack_registry(&durable, &synthesized);- (durable, synthesized)+ bind_pack_registry(&handle, &durable);+ bind_synthesized_pack_registry(&handle, &synthesized);+ (durable, synthesized, handle)}/// A packed **delegate** must be reachable, not merely withheld.@@ -121,7 +128,8 @@ fn split_registries(name: &'static str, level: PermissionLevel) -> (ToolRegistry/// model then cannot call is strictly worse than never packing it.#[tokio::test]async fn a_packed_delegate_in_the_synthesised_set_is_reachable() {- let (durable, _synthesized) = split_registries("manage_tasks", PermissionLevel::ReadOnly);+ let (durable, _synthesized, _handle) =+ split_registries("manage_tasks", PermissionLevel::ReadOnly);let use_skill = find(&durable, USE_SKILL);// Disclosure half: the schema must render even though the tool is in thediff --git a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_guides_tests.rs b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_guides_tests.rsindex 422e337f9d..4c6f6a01f9 100644--- a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_guides_tests.rs+++ b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_guides_tests.rs@@ -86,7 +86,7 @@ fn every_guided_pack_tool_is_named_in_its_guide_or_by_family() {#[tokio::test]async fn loading_a_skill_prints_its_guide_before_the_tool_schemas() {let web3 = pack("web3").unwrap();- let tools = registry_with_all(&["wallet_status", "web3_swap_quote"]);+ let (tools, _handle) = registry_with_all(&["wallet_status", "web3_swap_quote"]);let result = find(&tools, USE_SKILL).execute(json!({"skill": "web3"})).awaitdiff --git a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_scoping_and_visibility_tests.rs b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_scoping_and_visibility_tests.rsindex 2923575f2d..34f4c011b7 100644--- a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_scoping_and_visibility_tests.rs+++ b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests_scoping_and_visibility_tests.rs@@ -2,13 +2,13 @@//! execution distinction the whole pack mechanism rests on.use super::*;-use tinyagents_harness::tool::packs::{route_sentence, USE_SKILL};+use tinyagents_harness_tools::skills::{route_sentence, USE_SKILL};// ── the index must agree with the gate too ──────────────────────────────────/// A spec shaped like the one `UseSkillTool` publishes.fn use_skill_spec() -> tinytools::ToolSpec {- let tools = registry_with_all(&["build_workflow"]);+ let (tools, _handle) = registry_with_all(&["build_workflow"]);let tool = find(&tools, USE_SKILL);tinytools::ToolSpec {name: tool.name().to_string(),@@ -32,7 +32,7 @@ fn the_index_drops_a_pack_this_session_can_call_nothing_in() {// Only the workflows pack is reachable.let workflows = pack("workflows").expect("workflows pack");let kept =- tinyagents_harness::tool::packs::scope_use_skill_spec(&CATALOG, &mut spec, &|name| {+ tinyagents_harness_tools::skills::scope_use_skill_spec(&CATALOG, &mut spec, &|name| {workflows.tools.contains(&name)});assert!(@@ -60,7 +60,7 @@ fn the_index_drops_a_pack_this_session_can_call_nothing_in() {fn the_skill_enum_offers_only_reachable_packs() {let mut spec = use_skill_spec();let workflows = pack("workflows").expect("workflows pack");- tinyagents_harness::tool::packs::scope_use_skill_spec(&CATALOG, &mut spec, &|name| {+ tinyagents_harness_tools::skills::scope_use_skill_spec(&CATALOG, &mut spec, &|name| {workflows.tools.contains(&name)});@@ -85,7 +85,7 @@ fn the_skill_enum_offers_only_reachable_packs() {fn a_session_that_can_reach_no_pack_loses_use_skill() {let mut spec = use_skill_spec();assert!(- !tinyagents_harness::tool::packs::scope_use_skill_spec(&CATALOG, &mut spec, &|_| false),+ !tinyagents_harness_tools::skills::scope_use_skill_spec(&CATALOG, &mut spec, &|_| false),"with nothing reachable, use_skill must be dropped, not emptied");}@@ -97,7 +97,7 @@ fn scoping_the_index_only_ever_shrinks_it() {let mut spec = use_skill_spec();let before = spec.description.len();let workflows = pack("workflows").expect("workflows pack");- tinyagents_harness::tool::packs::scope_use_skill_spec(&CATALOG, &mut spec, &|name| {+ tinyagents_harness_tools::skills::scope_use_skill_spec(&CATALOG, &mut spec, &|name| {workflows.tools.contains(&name)});assert!(@@ -119,7 +119,7 @@ fn scoping_the_index_only_ever_shrinks_it() {fn a_withheld_packed_tool_is_hidden_but_not_denied() {use tinytools::{ToolPolicyAction, ToolPolicyEngine};- let tools = registry_with_all(&["goal_set", "build_workflow"]);+ let (tools, _handle) = registry_with_all(&["goal_set", "build_workflow"]);// The real shape: the harness seeds `visible` with everything, then// `strip_packed_from_visible` removes the packed names for a non-owner.let mut visible: HashSet<String> = tools.iter().map(|t| t.name().to_string()).collect();@@ -197,7 +197,7 @@ fn rebinding_a_pack_handle_repoints_it_at_the_new_registry() {let name = pack("web3").unwrap().tools[0];// The agent's first tool `Arc`, with the packed tool marked Dangerous.- let first = registry_with(name, PermissionLevel::Dangerous);+ let (first, handle) = registry_with(name, PermissionLevel::Dangerous);let use_skill = find(&first, USE_SKILL);let args = json!({"skill": "web3", "tool": name});assert_eq!(@@ -214,13 +214,11 @@ fn rebinding_a_pack_handle_repoints_it_at_the_new_registry() {external: false,timeout: ToolTimeout::Inherit,})];- append_pack_tools(&mut rebuilt);+ let _rebuilt_handle = append_pack_tools(&mut rebuilt);let rebuilt = Arc::new(rebuilt);// Re-point the ORIGINAL handle at it, which is what a rebuild does.- crate::tools::host_extensions::pack_registry_handle(use_skill)- .expect("use_skill exposes a pack registry handle")- .bind(Arc::downgrade(&rebuilt));+ handle.bind(Arc::downgrade(&rebuilt));assert_eq!(use_skill.permission_level_with_args(&args),@@ -240,14 +238,12 @@ fn rebinding_a_pack_handle_repoints_it_at_the_new_registry() {/// not mention a tool that gate will refuse.#[test]fn a_non_owner_listing_omits_the_tools_the_gate_will_refuse() {- let tools = registry_with_all(&["build_workflow", "propose_workflow"]);- let handle = crate::tools::host_extensions::pack_registry_handle(find(&tools, USE_SKILL))- .expect("use_skill carries the pack handle");+ let (_tools, handle) = registry_with_all(&["build_workflow", "propose_workflow"]);- let rendered = tinyagents_harness::tool::packs::render_pack_filtered(+ let rendered = tinyagents_harness_tools::skills::render_pack_filtered(&CATALOG,"workflows",- handle,+ &handle,&|name: &str| name != "propose_workflow","",)@@ -267,15 +263,13 @@ fn a_non_owner_listing_omits_the_tools_the_gate_will_refuse() {/// way out. A bare "no tools available" is the dead end the model retried into.#[test]fn a_listing_with_nothing_callable_names_the_route_out() {- let tools = registry_with_all(&["build_workflow", "propose_workflow"]);- let handle = crate::tools::host_extensions::pack_registry_handle(find(&tools, USE_SKILL))- .expect("use_skill carries the pack handle");+ let (_tools, handle) = registry_with_all(&["build_workflow", "propose_workflow"]);let route = route_sentence(&["build_workflow".to_string()], &["workflow_builder"]);- let err = tinyagents_harness::tool::packs::render_pack_filtered(+ let err = tinyagents_harness_tools::skills::render_pack_filtered(&CATALOG,"workflows",- handle,+ &handle,&|_| false,&route,)@@ -340,7 +334,7 @@ fn a_direct_hand_off_closes_its_owners_pack_and_nothing_else() {delegate("hand_off_to_skill_setup", "skill_setup"),delegate("create_image", "image_agent"),];- let raw = registry_with_all(&[+ let (raw, _handle) = registry_with_all(&["skill_registry_install","media_generate_image","wallet_status",@@ -402,7 +396,7 @@ fn a_packed_hand_off_leaves_its_owners_pack_open() {agent_id: DelegationTarget("skill_setup".to_string()),tool_description: String::new(),});- let raw = registry_with_all(&["skill_registry_install"]);+ let (raw, _handle) = registry_with_all(&["skill_registry_install"]);let tools: Vec<&dyn tinytools::Tool> = raw.iter().map(|t| t.as_ref())@@ -440,7 +434,7 @@ fn a_named_scope_session_closes_the_pack_its_visible_list_never_mentions() {agent_id: DelegationTarget("skill_setup".to_string()),tool_description: String::new(),});- let raw = registry_with_all(&["skill_registry_install"]);+ let (raw, _handle) = registry_with_all(&["skill_registry_install"]);let tools: Vec<&dyn tinytools::Tool> = raw.iter().map(|t| t.as_ref())@@ -508,7 +502,7 @@ fn the_orchestrators_only_file_creator_is_never_closed() {}) as Box<dyn tinytools::Tool>}).collect();- let raw = registry_with_all(&["file_write", "file_read"]);+ let (raw, _handle) = registry_with_all(&["file_write", "file_read"]);let tools: Vec<&dyn tinytools::Tool> = raw.iter().map(|t| t.as_ref())diff --git a/crates/openhuman-core/src/tools/traits_tests.rs b/crates/openhuman-core/src/tools/traits_tests.rsindex 208c762223..c4a8418255 100644--- a/crates/openhuman-core/src/tools/traits_tests.rs+++ b/crates/openhuman-core/src/tools/traits_tests.rs@@ -47,9 +47,9 @@ async fn a_tool_written_against_this_path_satisfies_the_shared_trait() {}#[test]-fn a_tool_carrying_no_host_extension_yields_none() {+fn a_tool_carrying_no_host_extension_has_no_delegation_target() {let tool = DummyTool;- assert!(pack_registry_handle(&tool).is_none());+ assert!(delegation_target(&tool).is_none());}#[test]diff --git a/crates/openhuman-core/src/voice/factory/registry.rs b/crates/openhuman-core/src/voice/factory/registry.rsindex b6fd8382d3..417132d07c 100644--- a/crates/openhuman-core/src/voice/factory/registry.rs+++ b/crates/openhuman-core/src/voice/factory/registry.rs@@ -73,10 +73,22 @@ pub(super) fn stt_factory(slug: &str) -> Option<SttProviderFactory> {STT_PROVIDERS.get(slug)}+/// Whether an STT provider factory is registered without constructing a+/// provider or invoking its constructor.+pub(crate) fn has_stt_provider(slug: &str) -> bool {+ STT_PROVIDERS.get(slug).is_some()+}+pub(super) fn tts_factory(slug: &str) -> Option<TtsProviderFactory> {TTS_PROVIDERS.get(slug)}+/// Whether a TTS provider factory is registered without constructing a+/// provider or invoking its constructor.+pub(crate) fn has_tts_provider(slug: &str) -> bool {+ TTS_PROVIDERS.get(slug).is_some()+}+#[cfg(test)]#[path = "registry_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/web3/wallet/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rsindex 3ed66332f2..f01fda038d 100644--- a/crates/openhuman-core/src/web3/wallet/mod.rs+++ b/crates/openhuman-core/src/web3/wallet/mod.rs@@ -62,8 +62,6 @@ pub use execution::{ProviderStatus, SupportedAsset, TxLookupInfo, TxReceiptInfo, TxState, TxStatusInfo,};#[cfg(feature = "web3")]-pub(crate) use ops::secret_material;-#[cfg(feature = "web3")]pub use ops::{derive_recovery_material, generate_recovery_phrase, reveal_recovery_phrase, setup, status,validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation,@@ -71,6 +69,8 @@ pub use ops::{WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE,};#[cfg(feature = "web3")]+pub(crate) use ops::{inspect_stored_wallet_state, secret_material};+#[cfg(feature = "web3")]pub use schemas::{all_controller_schemas, all_registered_controllers, all_wallet_controller_schemas,all_wallet_registered_controllers, schemas, wallet_schemas,diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rsindex 06efd62f4c..d2255c8c29 100644--- a/crates/openhuman-core/src/web3/wallet/ops.rs+++ b/crates/openhuman-core/src/web3/wallet/ops.rs@@ -9,7 +9,7 @@ mod types;use crate::core::runtime::DispatchCtx;use types::StoredWalletState;-pub(crate) use types::WalletSecretMaterial;+pub(crate) use types::{inspect_stored_wallet_state, WalletSecretMaterial};pub use types::{GeneratedRecoveryPhrase, RecoveryPhraseValidation, RevealRecoveryPhraseResult, WalletAccount,WalletChain, WalletRecoveryMaterial, WalletSetupParams, WalletSetupSource, WalletStatus,diff --git a/crates/openhuman-core/src/web3/wallet/ops/types.rs b/crates/openhuman-core/src/web3/wallet/ops/types.rsindex aeba7f7822..623463a889 100644--- a/crates/openhuman-core/src/web3/wallet/ops/types.rs+++ b/crates/openhuman-core/src/web3/wallet/ops/types.rs@@ -116,6 +116,25 @@ pub(super) struct StoredWalletState {pub updated_at_ms: u64,}+/// Non-secret projection for read-only inspection of a stored wallet snapshot.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct StoredWalletInspection {+ pub consent_granted: bool,+ pub account_count: usize,+}++/// Deserialize using the canonical persisted wallet schema and expose only+/// the fields needed by health checks.+pub(crate) fn inspect_stored_wallet_state(+ bytes: &[u8],+) -> Result<StoredWalletInspection, serde_json::Error> {+ let state: StoredWalletState = serde_json::from_slice(bytes)?;+ Ok(StoredWalletInspection {+ consent_granted: state.consent_granted,+ account_count: state.accounts.len(),+ })+}+#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct WalletSecretMaterial {pub encrypted_mnemonic: String,diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.tomlindex b9a17d2673..2bd03fd021 100644--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@ -79,6 +79,7 @@ tinymcp-bus = { path = "../../vendor/tinymcp/crates/tinymcp-bus" }# the core's so one copy resolves.tinyagents-hooks = { workspace = true }tinyagents-harness = { path = "../../vendor/tinyagents/crates/tinyagents-harness", default-features = false }+tinyagents-harness-tools = { path = "../../vendor/tinyagents/crates/tinyagents-harness-tools", default-features = false, features = ["todos"] }tinyagents-definition = { path = "../../vendor/tinyagents/crates/tinyagents-definition" }tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session" }# Native persisted todo codec exposed by the existing session-store contract.@@ -102,6 +103,7 @@ uuid = { version = "1", features = ["v4"] }async-trait = "0.1"tinymemory-api = { path = "../../vendor/tinymemory/crates/tinymemory-api", features = ["conformance"] }dirs = "6"+zeroize = "1"# `cron_tests` builds core `CronJob`s, whose schedule types live in the# tinyflows bus contract.tinyflows-bus = { path = "../../vendor/tinyflows/crates/tinyflows-bus" }diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rsindex 28aff07f59..16d77d1446 100644--- a/crates/openhuman-embed/src/host_internals.rs+++ b/crates/openhuman-embed/src/host_internals.rs@@ -106,6 +106,23 @@ pub mod core {}}+/// The generic doctor hook for checks contributed by a layered host.+pub mod doctor {+ /// The read-only desktop profile resolver used by the RPC host's one-shot+ /// doctor boot.+ pub mod profile {+ pub use openhuman_core::doctor::profile::{+ resolve_desktop_profile_for_doctor, DesktopProfileError, DesktopProfileSelection,+ };+ }++ pub use openhuman_core::doctor::registry::registered_checks;+ pub use openhuman_core::doctor::{+ register_check_source, register_check_source_in, ComponentId, DoctorCheck,+ DoctorCheckSource, DoctorConfigSource, DoctorCtx, DoctorTier, Finding, FindingSeverity,+ };+}+/// tinyhumans (every hosted controller loads its config) and rpc (server).pub mod config {pub use openhuman_core::config::{@@ -233,16 +250,18 @@ pub mod security {}pub mod session_support {pub use openhuman_core::security::credentials::session_support::{- build_session_state, classify_session_token, current_session_is_local,- get_session_token, is_local_session_token, load_app_session_profile,- publish_local_session_expiry, resolve_backend_credential, BackendCredential,- SessionTokenCheck, LOCAL_SESSION_BACKEND_UNAVAILABLE,+ build_session_state, check_session_backend, classify_session_token,+ current_session_is_local, get_session_token, is_local_session_token,+ load_app_session_profile, load_app_session_profile_read_only,+ publish_local_session_expiry, resolve_backend_credential, session_token_for_config,+ BackendCredential, SessionTokenCheck, LOCAL_SESSION_BACKEND_UNAVAILABLE,LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE, SESSION_EXPIRES_AT_META,+ SESSION_ISSUING_BACKEND_META,};}pub mod api_key {pub use openhuman_core::security::credentials::api_key::{- get_api_key_in, store_api_key, store_api_key_in,+ get_api_key, get_api_key_in, get_api_key_read_only, store_api_key, store_api_key_in,};}}@@ -362,22 +381,31 @@ pub mod inference_registry {pub use openhuman_core::inference::provider::openhuman_backend_model::REASONING_OFF_METADATA_KEY;pub use openhuman_core::inference::registry::{register_catalog, register_catalog_in, register_chat_model, register_chat_model_in,- register_embedding, register_embedding_in, unregister_catalog, unregister_chat_model,- unregister_embedding, BoxFuture, CatalogEntry, CatalogLimits, CatalogListing,- CatalogRequest, ChatModelEntry, ChatModelFactory, ChatModelRequest, EmbeddingFactory,- EmbeddingRequest, ReadinessProbe,+ register_embedding, register_embedding_in, register_inspection_catalog,+ register_inspection_catalog_in, register_inspection_chat_model,+ register_inspection_chat_model_in, register_inspection_embedding,+ register_inspection_embedding_in, unregister_catalog, unregister_chat_model,+ unregister_embedding, unregister_inspection_catalog, unregister_inspection_chat_model,+ BoxFuture, CatalogEntry, CatalogLimits, CatalogListing, CatalogRequest, ChatModelEntry,+ ChatModelFactory, ChatModelRequest, EmbeddingFactory, EmbeddingRequest,+ InspectionCatalogError, InspectionCatalogListing, InspectionChatModelBuild,+ InspectionChatModelFactory, InspectionEmbeddingFactory, PreparedInspectionCatalog,+ PreparedInspectionChatModelFactory, ReadinessProbe,};}/// Memory engines by id, and the free-background-work predicate.pub mod memory_engines {pub use openhuman_core::memory::engine::{- build_cached, rooted, BearerSource, Binding, BoundEngine, EngineCredential, EngineSettings,- TINYHUMANS_ENGINE,+ build_cached, rooted, BearerSource, Binding, BoundEngine, EngineCredential, EngineHealth,+ EngineSettings, TINYHUMANS_ENGINE,};pub use openhuman_core::memory::engine_registry::{- bound_engine, register_memory_engine, register_memory_engine_in, unregister_memory_engine,- EngineBuilder, EngineEntry, EngineFuture, EngineRequest, FreeBackground,+ bound_engine, register_memory_engine, register_memory_engine_in,+ register_memory_health_probe, register_memory_health_probe_in,+ register_read_only_engine_factory, register_read_only_engine_factory_in,+ unregister_memory_engine, EngineBuilder, EngineEntry, EngineFuture, EngineRequest,+ FreeBackground, ReadOnlyEngineError, ReadOnlyEngineFactory, ReadOnlyHealthProbe,};}@@ -447,6 +475,12 @@ pub mod platform {pub mod health {pub use openhuman_core::platform::health::{snapshot, verdict};}++ /// tinyhumans: read-only view of the live Socket.IO connection state.+ pub mod socket {+ pub use openhuman_core::platform::socket::global_socket_manager;+ pub use openhuman_core::platform::socket::models::ConnectionStatus;+ }}pub mod storage {diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex 92611549cf..58597f5684 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -89,7 +89,8 @@ pub use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};pub use openhuman_core::agent::tinyagents::host::LastTurnUsage;pub use openhuman_core::agent::{HostAttachment, HostTools, HostTurnTools, TurnContext};pub use openhuman_core::{- CoreBuilder, CoreRuntime, DaemonConfig, DomainSet, HostKind, ServiceSet, TokenSource,+ CoreBootMode, CoreBuilder, CoreRuntime, DaemonConfig, DomainSet, HostKind, ServiceSet,+ TokenSource,};/// Declarative execution requirements for host-owned tools, from the core's vendored contract.pub use tinytools::ToolPolicy;@@ -122,6 +123,12 @@ pub mod channels;pub mod chat_surface;pub mod complete;pub mod config;+/// Pure command-line argument parsers shared by host-owned command facades.+pub mod cli {+ pub use openhuman_core::core::cli::{+ parse_cli_args_after_launch_options, parse_function_params,+ };+}mod core_agent;pub mod cron;pub mod embeddings;@@ -238,10 +245,10 @@ pub mod seams {/// is held to. The persisted record types are the harness's own serde codecs,/// so hosts can encode and decode stored state without duplicating wire shapes.pub mod session_store {- pub use tinyagents_graph::todos::TodoList;pub use tinyagents_harness::events::{AgentEvent, HarnessRunStatus};pub use tinyagents_harness::ids::ExecutionStatus;pub use tinyagents_harness::observability::AgentObservation;+ pub use tinyagents_harness_tools::todos::TodoList;pub use tinyagents_session::port::{AgentStores, SessionStoreProvider};pub use tinyagents_session::port::{AppendStore, InMemorySessionStores, InMemoryTranscriptLocator, InMemoryTurnStates, Store,diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rsindex 305e6a59c6..c9f4db4373 100644--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@ -4,7 +4,7 @@ use std::path::Path;use std::sync::Arc;use openhuman_core::config::Config;-use openhuman_core::core::runtime::CoreBuilder;+use openhuman_core::core::runtime::{CoreBootMode, CoreBuilder, ServiceSet, TokenSource};use openhuman_core::core::types::HostKind;use tinyagents_session::port::SessionStoreProvider;@@ -79,18 +79,48 @@ impl RuntimeBuilder {/// Refuse combinations the chosen [`ConfigSource`] cannot honour.pub(super) fn validate(&self) -> Result<(), RuntimeError> {self.validate_modules()?;- if self.agent_defaults.skills.root.is_some() && !cfg!(feature = "skills") {+ let inspection = self.boot_mode == CoreBootMode::Inspection;+ if inspection {+ if self.config_source != ConfigSource::Resolved+ || self.config.is_none()+ || !matches!(self.workspace, Workspace::Inherit)+ || !matches!(&self.token, TokenSource::Fixed(_))+ {+ return Err(RuntimeError::Invalid(+ "inspection boot requires an inherited workspace, caller-supplied resolved config, and fixed bearer".into(),+ ));+ }+ if self.workspace_dir.is_some()+ || self.action_dir.is_some()+ || self.api_key.is_some()+ || self.session.is_some()+ || self.session_store.is_some()+ || self.seams.storage.is_some()+ {+ return Err(RuntimeError::Invalid(+ "inspection boot does not accept path overrides, credentials, sessions, or storage providers".into(),+ ));+ }+ if openhuman_core::storage::installed().is_some() {+ return Err(RuntimeError::Invalid(+ "inspection boot requires no installed storage backend".into(),+ ));+ }+ }+ if !inspection && self.agent_defaults.skills.root.is_some() && !cfg!(feature = "skills") {return Err(RuntimeError::Invalid("copying runtime skill bundles requires Cargo feature `openhuman-embed/skills`".into(),));}- validate_storage_feature(self.seams.storage.as_ref())?;- if self.seams.storage.is_none() {- if let Some(config) = &self.config {- if let Some(url) = openhuman_core::storage::explicit_url(config) {- validate_storage_feature(Some(&super::StorageSource::Url(url)))?;+ if !inspection {+ validate_storage_feature(self.seams.storage.as_ref())?;+ if self.seams.storage.is_none() {+ if let Some(config) = &self.config {+ if let Some(url) = openhuman_core::storage::explicit_url(config) {+ validate_storage_feature(Some(&super::StorageSource::Url(url)))?;+ }}}}@@ -101,7 +131,8 @@ impl RuntimeBuilder {if self.api_key.as_ref().is_some_and(ApiKey::is_blank) {return Err(RuntimeError::BlankApiKey);}- if matches!(self.workspace, Workspace::Stateless)+ if !inspection+ && matches!(self.workspace, Workspace::Stateless)&& self.session_store.is_none()&& self.seams.storage.is_none()&& self@@ -140,6 +171,7 @@ impl RuntimeBuilder {async fn build_inner(mut self) -> Result<Runtime, RuntimeError> {self.validate()?;+ let inspection = self.boot_mode == CoreBootMode::Inspection;let discovered = self.config_source == ConfigSource::Discovered;let inherit = self.workspace.is_operator_owned();let resolved = ResolvedWorkspace::resolve(&self.workspace, self.action_dir.as_deref())@@ -164,31 +196,38 @@ impl RuntimeBuilder {config.as_ref().unwrap_or(&Config::default()),);let mut host_seams = std::mem::take(&mut self.seams);- if host_seams.storage.is_none() {- if let Some(config) = &config {- if let Some(url) = openhuman_core::storage::explicit_url(config) {- host_seams.storage = Some(super::StorageSource::Url(url));+ if !inspection {+ if host_seams.storage.is_none() {+ if let Some(config) = &config {+ if let Some(url) = openhuman_core::storage::explicit_url(config) {+ host_seams.storage = Some(super::StorageSource::Url(url));+ }}}+ // A stateless workspace keeps nothing durable on disk: with no host+ // backend, the documents the core keeps beside the session store (run+ // status, cron, flows) go to memory instead of the workspace-default+ // SQLite under `<workspace>/storage`. Installed process-wide like any+ // storage seam, and removed with the runtime.+ if host_seams.storage.is_none() && matches!(self.workspace, Workspace::Stateless) {+ host_seams.storage = Some(super::StorageSource::Url("memory".into()));+ }+ validate_storage_feature(host_seams.storage.as_ref())?;+ host_seams+ .open_storage()+ .await+ .map_err(RuntimeError::Invalid)?;}- // A stateless workspace keeps nothing durable on disk: with no host- // backend, the documents the core keeps beside the session store (run- // status, cron, flows) go to memory instead of the workspace-default- // SQLite under `<workspace>/storage`. Installed process-wide like any- // storage seam, and removed with the runtime.- if host_seams.storage.is_none() && matches!(self.workspace, Workspace::Stateless) {- host_seams.storage = Some(super::StorageSource::Url("memory".into()));- }- validate_storage_feature(host_seams.storage.as_ref())?;- host_seams- .open_storage()- .await- .map_err(RuntimeError::Invalid)?;- let storage_backend = match &host_seams.storage {- Some(super::StorageSource::Backend(backend)) => Some(backend.clone()),- _ => None,+ let storage_backend = if inspection {+ None+ } else {+ match &host_seams.storage {+ Some(super::StorageSource::Backend(backend)) => Some(backend.clone()),+ _ => None,+ }};- if self.session_store.is_none() {+ let core_extensions = host_seams.core_extensions.clone();+ if !inspection && self.session_store.is_none() {if let Some(backend) = &storage_backend {let stores = openhuman_core::storage::sessions::TenantSessionStores::new(backend.clone(),@@ -223,19 +262,31 @@ impl RuntimeBuilder {let domains = self.domains.unwrap_or_else(default_domains);let tool_groups = self.tool_groups.clone().unwrap_or_default();- let services = self.services.unwrap_or_else(default_services);+ let services = if inspection {+ ServiceSet::none()+ } else {+ self.services.unwrap_or_else(default_services)+ };- if let Some(engine) = self.memory_engine.clone() {- openhuman_core::memory::engine::install_host_engine(engine);+ if !inspection {+ if let Some(engine) = self.memory_engine.clone() {+ openhuman_core::memory::engine::install_host_engine(engine);+ }}- if let Some(delivery) = self.cron_delivery.clone() {- log::debug!("[embed][runtime] host cron delivery installed");- openhuman_core::cron::host_delivery::install(delivery);+ if !inspection {+ if let Some(delivery) = self.cron_delivery.clone() {+ log::debug!("[embed][runtime] host cron delivery installed");+ openhuman_core::cron::host_delivery::install(delivery);+ }}// Install only after all fallible workspace/config resolution has// completed; core boot performs recovery against this provider.- let installed_session_store = self.session_store.clone();+ let installed_session_store = if inspection {+ None+ } else {+ self.session_store.clone()+ };let previous_session_store = installed_session_store.clone().and_then(openhuman_core::storage::sessions::install);@@ -256,9 +307,11 @@ impl RuntimeBuilder {);let mut builder = CoreBuilder::new(host_kind)+ .boot_mode(self.boot_mode).domains(domains).tool_groups(tool_groups.clone()).services(services)+ .extensions(core_extensions).token(std::mem::replace(&mut self.token,openhuman_core::core::runtime::TokenSource::EnvOrFile,@@ -277,7 +330,11 @@ impl RuntimeBuilder {RuntimeError::Build(error)})?;let core = Core::from_runtime(Arc::new(runtime));- let storage_backend = storage_backend.or_else(openhuman_core::storage::installed);+ let storage_backend = if inspection {+ None+ } else {+ storage_backend.or_else(openhuman_core::storage::installed)+ };if !storage_info.configured {if let Some(backend) = &storage_backend {storage_info = super::StorageInfo {diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rsindex b1fd9908c3..2238b650ab 100644--- a/crates/openhuman-embed/src/runtime/builder.rs+++ b/crates/openhuman-embed/src/runtime/builder.rs@@ -15,7 +15,7 @@ use std::path::PathBuf;use std::sync::Arc;use openhuman_core::config::Config;-use openhuman_core::core::runtime::{DomainSet, ServiceSet, TokenSource};+use openhuman_core::core::runtime::{CoreBootMode, DomainSet, ServiceSet, TokenSource};use openhuman_core::core::types::HostKind;use openhuman_core::tools::toolpacks::ToolGroups;use tinyagents_session::port::SessionStoreProvider;@@ -81,6 +81,7 @@ pub struct RuntimeBuilder {pub(super) workspace_dir: Option<PathBuf>,pub(super) action_dir: Option<PathBuf>,pub(super) config_source: ConfigSource,+ pub(super) boot_mode: CoreBootMode,pub(super) provider: Provider,pub(super) access: Access,pub(super) services: Option<ServiceSet>,@@ -127,6 +128,7 @@ impl RuntimeBuilder {workspace_dir: None,action_dir: None,config_source: ConfigSource::Resolved,+ boot_mode: CoreBootMode::Normal,provider: Provider::inherit(),access: Access::default(),services: None,@@ -337,6 +339,18 @@ impl RuntimeBuilder {self}+ /// Choose normal host startup or a side-effect-limited inspection build.+ ///+ /// Inspection requires an inherited workspace, a supplied resolved+ /// config, and a fixed in-memory bearer. It does not discover ambient+ /// config, open persistent storage, install session stores, bootstrap+ /// workspace state, or start background services. The runtime still has+ /// a real `CoreContext` and can dispatch in-process RPC.+ pub fn boot_mode(mut self, mode: CoreBootMode) -> Self {+ self.boot_mode = mode;+ self+ }+/// The TinyHumans API key — the runtime's only credential.////// Installed into the runtime's credential store before the core boots.diff --git a/crates/openhuman-embed/src/runtime/builder_tests.rs b/crates/openhuman-embed/src/runtime/builder_tests.rsindex 0f7a3225fd..a41ee73f38 100644--- a/crates/openhuman-embed/src/runtime/builder_tests.rs+++ b/crates/openhuman-embed/src/runtime/builder_tests.rs@@ -113,6 +113,14 @@ fn token_defaults_to_env_or_file_and_is_overridable() {assert!(matches!(&fixed.token, TokenSource::Fixed(t) if t.as_str() == "bearer"));}+#[test]+fn runtime_builder_defaults_to_normal_core_boot() {+ assert_eq!(+ RuntimeBuilder::new().boot_mode,+ openhuman_core::core::runtime::CoreBootMode::Normal+ );+}+#[test]fn listen_records_host_and_port_for_the_transport() {let builder = RuntimeBuilder::new();diff --git a/crates/openhuman-embed/src/runtime/seams.rs b/crates/openhuman-embed/src/runtime/seams.rsindex fa4303400e..a0fcfbcd8f 100644--- a/crates/openhuman-embed/src/runtime/seams.rs+++ b/crates/openhuman-embed/src/runtime/seams.rs@@ -34,6 +34,7 @@ use openhuman_core::agent::tinyagents::discovery::{};use openhuman_core::core::all::{register_controller_extension, ControllerExtension};use openhuman_core::core::server_launcher::{install_server_launcher, ServerLauncher};+use openhuman_core::core::slots::Extensions;use openhuman_core::security::SecurityPolicy;use openhuman_core::storage::StorageBackend;use tinytools::ToolRanker;@@ -83,6 +84,7 @@ impl From<Arc<dyn StorageBackend>> for StorageSource {#[derive(Default)]pub(crate) struct HostSeams {pub(crate) controller_extensions: Vec<ControllerExtension>,+ pub(crate) core_extensions: Extensions,pub(crate) tool_ranker: Option<Arc<dyn ToolRanker>>,pub(crate) post_turn_hooks: Vec<Arc<dyn LearningSink>>,pub(crate) tool_hooks: Vec<Arc<dyn ToolHook<OpenHumanRunContext>>>,@@ -407,6 +409,17 @@ impl Drop for InstalledSeams {}impl RuntimeBuilder {+ /// Configure context-scoped core hooks before this runtime is built.+ ///+ /// The callback receives the same extension set that is attached to the+ /// runtime's `CoreContext`; registrations remain isolated from other core+ /// contexts in the process. This is intended for layered host crates.+ #[doc(hidden)]+ pub fn configure_core_extensions(self, configure: impl FnOnce(&Extensions)) -> Self {+ configure(&self.seams.core_extensions);+ self+ }+/// Contribute controllers to the core's registry, as the TinyHumans layer/// does for its hosted RPC proxies. May be called more than once.///diff --git a/crates/openhuman-embed/tests/inspection_boot.rs b/crates/openhuman-embed/tests/inspection_boot.rsnew file mode 100644index 0000000000..69de6c6448--- /dev/null+++ b/crates/openhuman-embed/tests/inspection_boot.rs@@ -0,0 +1,264 @@+use std::collections::{BTreeMap, BTreeSet};+use std::ffi::OsString;+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++use openhuman_core::config::Config;+use openhuman_core::doctor::{+ register_check_source_in, DoctorCheck, DoctorCheckSource, DoctorCtx, DoctorTier, Finding,+};+use openhuman_core::security::secret_storage::{+ clear_master_key_source, clear_secret_backend, install_master_key_source,+ install_secret_backend, EncryptedFileBackend, MasterKeySource, SecretStorageError,+};+use openhuman_embed::{+ ConfigSource, CoreBootMode, DomainSet, RuntimeBuilder, ServiceSet, TokenSource, Workspace,+};+use serde_json::json;+use zeroize::Zeroizing;++#[derive(Debug, Clone, PartialEq, Eq)]+enum SnapshotEntry {+ Directory,+ File(Vec<u8>),+ Symlink(PathBuf),+ Other,+}++fn snapshot(root: &Path) -> BTreeMap<PathBuf, SnapshotEntry> {+ fn visit(root: &Path, dir: &Path, entries: &mut BTreeMap<PathBuf, SnapshotEntry>) {+ for entry in fs::read_dir(dir).expect("read snapshot directory") {+ let entry = entry.expect("read snapshot entry");+ let path = entry.path();+ let relative = path.strip_prefix(root).unwrap().to_path_buf();+ let file_type = entry.file_type().expect("inspect snapshot entry");+ if file_type.is_dir() {+ entries.insert(relative, SnapshotEntry::Directory);+ visit(root, &path, entries);+ } else if file_type.is_file() {+ entries.insert(+ relative,+ SnapshotEntry::File(fs::read(&path).expect("read snapshot file")),+ );+ } else if file_type.is_symlink() {+ entries.insert(+ relative,+ SnapshotEntry::Symlink(fs::read_link(&path).expect("read symlink")),+ );+ } else {+ entries.insert(relative, SnapshotEntry::Other);+ }+ }+ }++ let mut entries = BTreeMap::new();+ visit(root, root, &mut entries);+ entries+}++struct Environment(Vec<(&'static str, Option<OsString>)>);++impl Environment {+ fn isolated(root: &Path, storage_url: &str) -> Self {+ let overrides = [+ ("OPENHUMAN_WORKSPACE", None),+ (+ "OPENHUMAN_PROJECTS_DIR",+ Some(root.join("projects").into_os_string()),+ ),+ (+ "OPENHUMAN_ACTION_DIR",+ Some(root.join("action").into_os_string()),+ ),+ ("OPENHUMAN_STORAGE_URL", Some(OsString::from(storage_url))),+ (+ "OPENHUMAN_KEYRING_BACKEND",+ Some(OsString::from("encrypted_file")),+ ),+ ("OPENHUMAN_KEYRING_MASTER_KEY", None),+ ("OPENHUMAN_KEYRING_MASTER_KEY_FILE", None),+ ];+ let saved = overrides+ .iter()+ .map(|(key, value)| {+ let previous = std::env::var_os(key);+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ (*key, previous)+ })+ .collect();+ Self(saved)+ }+}++impl Drop for Environment {+ fn drop(&mut self) {+ for (key, value) in self.0.drain(..) {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }+}++struct SecretBackendReset;++impl Drop for SecretBackendReset {+ fn drop(&mut self) {+ clear_master_key_source();+ clear_secret_backend();+ }+}++struct InspectionCheck;++#[async_trait::async_trait]+impl DoctorCheck for InspectionCheck {+ fn id(&self) -> &str {+ "inspection/probe"+ }++ fn category(&self) -> &str {+ "inspection"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ async fn detect(&self, _ctx: &DoctorCtx) -> Vec<Finding> {+ vec![Finding::pass(self.id(), "Inspection context is available.")]+ }+}++struct InspectionSource;++impl DoctorCheckSource for InspectionSource {+ fn id(&self) -> &str {+ "inspection-source"+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ vec![Arc::new(InspectionCheck)]+ }+}++struct CountingMasterKeySource(Arc<AtomicUsize>);++impl MasterKeySource for CountingMasterKeySource {+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError> {+ Ok(None)+ }++ fn store(&self, _key: &[u8; 32]) -> Result<(), SecretStorageError> {+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+}++#[test]+fn preloaded_runtime_can_invoke_doctor_without_startup_writes() {+ let runtime = openhuman_embed::process::tokio_runtime().expect("tuned Tokio runtime");+ let task = runtime.spawn(preloaded_runtime_report());+ runtime+ .block_on(task)+ .expect("inspection test task completes");+}++async fn preloaded_runtime_report() {+ let root = tempfile::tempdir().expect("inspection root");+ let workspace = root.path().join("workspace");+ let action = root.path().join("action");+ let storage_file = root.path().join("configured.sqlite");+ let storage_url = format!("sqlite:{}", storage_file.display());+ let _environment = Environment::isolated(root.path(), &storage_url);++ let legacy_skill = workspace.join("skills/dev-workflow/keep.txt");+ fs::create_dir_all(legacy_skill.parent().unwrap()).expect("legacy skill fixture");+ fs::write(&legacy_skill, b"preserve this directory").expect("legacy skill sentinel");++ let mut config = Config {+ config_path: root.path().join("config.toml"),+ workspace_dir: workspace,+ action_dir: action,+ ..Config::default()+ };+ config.storage.url = Some(storage_url);++ let key_writes = Arc::new(AtomicUsize::new(0));+ install_secret_backend(Arc::new(EncryptedFileBackend::new(&config.workspace_dir)));+ install_master_key_source(Arc::new(CountingMasterKeySource(Arc::clone(&key_writes))));+ let _secret_backend = SecretBackendReset;++ let before = snapshot(root.path());+ assert!(openhuman_core::storage::installed().is_none());+ let runtime = RuntimeBuilder::new()+ .workspace(Workspace::Inherit)+ .config_source(ConfigSource::Resolved)+ .config(config)+ .boot_mode(CoreBootMode::Inspection)+ .token(TokenSource::Fixed(Arc::new(+ "inspection-test-token".to_owned(),+ )))+ .domains(DomainSet::full())+ .services(ServiceSet::none())+ .build()+ .await+ .expect("build preloaded inspection runtime");++ assert!(+ openhuman_core::core::runtime::CoreContext::current().is_none(),+ "inspection runtime must not publish a process-default context"+ );+ let backend_opened = openhuman_core::storage::installed().is_some();+ let key_store_writes = key_writes.load(Ordering::SeqCst);+ register_check_source_in(+ runtime.core_runtime().context().extensions(),+ InspectionSource,+ );+ let response = runtime+ .core_runtime()+ .invoke(+ "openhuman.doctor_report",+ json!({+ "tier": "static",+ "only": ["inspection/probe"]+ }),+ )+ .await+ .expect("invoke doctor report in-process");+ assert!(+ openhuman_core::core::runtime::CoreContext::current().is_none(),+ "in-process inspection dispatch must leave no ambient context behind"+ );+ let report = response+ .get("result")+ .expect("unwrap the CLI-compatible outcome envelope");+ assert_eq!(report["schema_version"], 2);+ assert!(report["findings"]+ .as_array()+ .unwrap()+ .iter()+ .any(|finding| finding["check_id"] == "inspection/probe"));++ drop(runtime);+ let after = snapshot(root.path());+ let changed_paths = before+ .keys()+ .chain(after.keys())+ .cloned()+ .collect::<BTreeSet<_>>()+ .into_iter()+ .filter(|path| before.get(path) != after.get(path))+ .collect::<Vec<_>>();+ assert!(+ !backend_opened && key_store_writes == 0 && changed_paths.is_empty(),+ "inspection startup side effects: backend_opened={backend_opened}, \+ key_store_writes={key_store_writes}, changed_paths={changed_paths:?}"+ );+}diff --git a/crates/openhuman-rpc/src/host.rs b/crates/openhuman-rpc/src/host.rsindex 84c031221a..a91422338c 100644--- a/crates/openhuman-rpc/src/host.rs+++ b/crates/openhuman-rpc/src/host.rs@@ -37,7 +37,9 @@use std::sync::Arc;#[cfg(feature = "server")]-use openhuman_tinyhumans::embed::{ServiceSet, TokenSource};+use openhuman_tinyhumans::embed::{+ ConfigSource, CoreBootMode, RuntimeConfig, ServiceSet, TokenSource, Workspace,+};use openhuman_tinyhumans::RuntimeBuilder;#[cfg(feature = "server")]use tokio_util::sync::CancellationToken;@@ -48,6 +50,10 @@ pub use crate::server::EmbeddedReadySignal;#[path = "host/secret_storage.rs"]mod secret_storage;+#[cfg(feature = "server")]+#[path = "host/doctor_cli.rs"]+mod doctor_cli;+/// The CLI host's builder: the `cli` preset with this crate's server as the/// `run` / `serve` launcher and the `http_host.*` controllers registered.#[cfg(feature = "server")]@@ -57,6 +63,78 @@ pub fn cli_builder() -> RuntimeBuilder {.controller_extension(crate::http_host::extension())}+/// Prepare the CLI host for a one-shot in-process command without booting a+/// runtime or installing the server's storage-backed session store.+///+/// Config loading depends on the TinyHumans enricher and persistent hosts need+/// the encrypted-file secret backend installed before a report reads config.+#[cfg(feature = "server")]+pub fn prepare_cli_host() {+ openhuman_tinyhumans::register_hooks();+ prepare_cli_environment();+}++/// Build a side-effect-limited runtime for the CLI's one-shot doctor command.+///+/// The effective desktop config is selected before the core boots. The normal+/// doctor RPC then runs through `CoreRuntime::invoke`, preserving the shared+/// report path and context-scoped TinyHumans checks. An invalid explicit+/// profile uses a safe in-memory config pinned to the root so the RPC can+/// return its single `profile/exists` finding without loading ambient config.+#[cfg(feature = "server")]+pub async fn doctor_runtime(+ requested_profile: Option<&str>,+) -> anyhow::Result<openhuman_tinyhumans::embed::Runtime> {+ prepare_cli_host();+ let root = crate::embed::config::default_root_openhuman_dir()?;+ let config = match crate::core_host::doctor::profile::resolve_desktop_profile_for_doctor(+ &root,+ requested_profile,+ )+ .await+ {+ Ok(selection) => selection.config,+ Err(_) if requested_profile.is_some() => doctor_fallback_config(&root),+ Err(error) => anyhow::bail!("doctor profile selection failed: {}", error.message()),+ };++ Ok(doctor_builder(config).build().await?)+}++#[cfg(feature = "server")]+fn doctor_builder(config: RuntimeConfig) -> RuntimeBuilder {+ let bearer = Arc::new(uuid::Uuid::new_v4().simple().to_string());+ cli_builder()+ .workspace(Workspace::Inherit)+ .config_source(ConfigSource::Resolved)+ .config(config)+ .boot_mode(CoreBootMode::Inspection)+ .services(ServiceSet::none())+ .token(TokenSource::Fixed(bearer))+}++#[cfg(feature = "server")]+fn doctor_fallback_config(root: &std::path::Path) -> RuntimeConfig {+ RuntimeConfig {+ config_path: root.join("config.toml"),+ workspace_dir: root.join("workspace"),+ action_dir: root.join("action"),+ ..RuntimeConfig::default()+ }+}++#[cfg(feature = "server")]+fn prepare_cli_environment() {+ // The preflight reads URLs before normal CLI dispatch loads `.env` itself.+ if let Err(error) = crate::core_host::core::cli::load_dotenv_for_cli() {+ log::warn!(+ "[rpc:host] cli: early dotenv load failed ({error}); a host setting supplied only \+ in that file will not be seen"+ );+ }+ secret_storage::install();+}+/// Parse the side-effect-free embedding capability command.#[cfg(any(feature = "server", test))]fn embed_info(args: &[String]) -> anyhow::Result<Option<crate::embed::RuntimeInfo>> {@@ -83,6 +161,9 @@ fn embed_info(args: &[String]) -> anyhow::Result<Option<crate::embed::RuntimeInfpub fn cli(args: &[String]) -> anyhow::Result<()> {// Config reads below (and in the dispatcher) need the enricher.openhuman_tinyhumans::register_hooks();+ if let Some(result) = doctor_cli::try_run(args) {+ return result;+ }// Introspection belongs above the core: never introduce a core -> embed dependency.if let Some(info) = embed_info(args)? {println!("{}", serde_json::to_string_pretty(&info)?);@@ -94,15 +175,7 @@ pub fn cli(args: &[String]) -> anyhow::Result<()> {args.first().map(String::as_str).unwrap_or("<none>"),args.len());- // The preflight reads the URL before the dispatcher loads `.env`- // itself, so a URL supplied through the dotenv file must be loaded now.- if let Err(error) = crate::core_host::core::cli::load_dotenv_for_cli() {- log::warn!(- "[rpc:host] cli: early dotenv load failed ({error}); a host setting supplied only \- in that file will not be seen"- );- }- secret_storage::install();+ prepare_cli_environment();let mut builder = cli_builder();if cli_command_uses_storage(args, |namespace| {// `subsystems` only renders status; it never touches stored state.@@ -164,6 +237,7 @@ fn cli_command_uses_storage(args: &[String], has_cli_handler: impl Fn(&str) -> blet tail: Vec<&str> = rest.collect();match command {"run" | "serve" | "tui" | "chat" | "sentry-test" => false,+ "doctor" if matches!(tail.first().copied(), Some("report" | "models")) => false,// The MCP server speaks stdio when given no function and runs agent// sessions, so it needs the backend."mcp" | "mcp-server" => !tail.iter().any(|a| is_help(a)),diff --git a/crates/openhuman-rpc/src/host/doctor_cli.rs b/crates/openhuman-rpc/src/host/doctor_cli.rsnew file mode 100644index 0000000000..b45d9740a4--- /dev/null+++ b/crates/openhuman-rpc/src/host/doctor_cli.rs@@ -0,0 +1,104 @@+//! Read-only execution for the legacy `doctor report` and `doctor models` CLI+//! namespace methods.++use anyhow::{anyhow, Result};+use serde_json::{Map, Value};++#[derive(Debug, PartialEq)]+struct Invocation {+ method: String,+ params: Map<String, Value>,+}++/// Run one legacy doctor namespace command in the inspection runtime.+///+/// `None` leaves unrelated commands and help requests to the general CLI+/// dispatcher. A matching inspection invocation returns its raw controller+/// JSON shape, without opening the persistent session store or entering the+/// normal CLI boot path.+pub(super) fn try_run(args: &[String]) -> Option<Result<()>> {+ match parse(args) {+ Ok(Some(invocation)) => Some(invoke(invocation)),+ Ok(None) => None,+ Err(error) => Some(Err(error)),+ }+}++fn parse(args: &[String]) -> Result<Option<Invocation>> {+ if !args+ .first()+ .is_some_and(|arg| is_doctor_or_launch_option(arg))+ {+ return Ok(None);+ }++ // This pure parser is shared with the CLI dispatcher. The inspection path+ // accepts the familiar leading flags but deliberately does not apply their+ // transient model/provider overrides to the selected profile.+ let command = match crate::embed::cli::parse_cli_args_after_launch_options(args) {+ Ok(command) => command,+ Err(_) => return Ok(None),+ };+ if command.first().map(String::as_str) != Some("doctor") {+ return Ok(None);+ }++ let Some(function) = command.get(1).map(String::as_str) else {+ return Ok(None);+ };+ if !matches!(function, "report" | "models") {+ return Ok(None);+ }+ // Core's namespace dispatcher prints these function-help forms before it+ // parses parameters. Let that path retain its existing help text.+ if command+ .get(2)+ .is_some_and(|arg| matches!(arg.as_str(), "-h" | "--help" | "help"))+ {+ return Ok(None);+ }++ let method = format!("openhuman.doctor_{function}");+ let schema = crate::embed::schema_for_rpc_method(&method)+ .ok_or_else(|| anyhow!("unregistered doctor controller '{function}'"))?;+ let params = crate::embed::cli::parse_function_params(&schema, &command[2..])+ .map_err(anyhow::Error::msg)?;+ Ok(Some(Invocation { method, params }))+}++fn is_doctor_or_launch_option(arg: &str) -> bool {+ matches!(+ arg,+ "doctor" | "--model" | "--model-id" | "-m" | "--provider" | "--provider-id" | "-p"+ ) || arg.starts_with("--model=")+ || arg.starts_with("--model-id=")+ || arg.starts_with("--provider=")+ || arg.starts_with("--provider-id=")+}++fn invoke(invocation: Invocation) -> Result<()> {+ let selected_profile = invocation+ .params+ .get("profile")+ .and_then(Value::as_str)+ .map(str::to_owned);+ let tokio = crate::embed::process::tokio_runtime()?;+ let runtime = tokio.block_on(super::doctor_runtime(selected_profile.as_deref()))?;+ let result = tokio+ .block_on(+ runtime+ .core_runtime()+ .invoke(&invocation.method, Value::Object(invocation.params)),+ )+ .map_err(anyhow::Error::msg)?;+ println!("{}", format_json(&result)?);+ Ok(())+}++fn format_json(value: &Value) -> Result<String> {+ Ok(serde_json::to_string_pretty(value)?)+}++#[cfg(test)]+#[path = "doctor_cli_tests.rs"]+mod tests;diff --git a/crates/openhuman-rpc/src/host/doctor_cli_tests.rs b/crates/openhuman-rpc/src/host/doctor_cli_tests.rsnew file mode 100644index 0000000000..03d1493676--- /dev/null+++ b/crates/openhuman-rpc/src/host/doctor_cli_tests.rs@@ -0,0 +1,97 @@+use super::*;+use serde_json::{json, Value};++fn args(values: &[&str]) -> Vec<String> {+ values.iter().map(|value| (*value).to_owned()).collect()+}++#[test]+fn report_reuses_launch_and_schema_parameter_parsing_without_global_overrides() {+ let invocation = parse(&args(&[+ "--model",+ "transient-model",+ "--provider=transient-provider",+ "doctor",+ "report",+ "--tier",+ "static",+ "--only",+ r#"["config/parse"]"#,+ "--profile",+ "selected-profile",+ ]))+ .expect("valid legacy report arguments")+ .expect("legacy report is routed through inspection");++ assert_eq!(invocation.method, "openhuman.doctor_report");+ assert_eq!(+ Value::Object(invocation.params),+ json!({+ "tier": "static",+ "only": ["config/parse"],+ "profile": "selected-profile"+ })+ );+}++#[test]+fn models_parses_legacy_bool_argument_and_keeps_raw_method() {+ let invocation = parse(&args(&[+ "-m",+ "ignored-model-override",+ "-p",+ "ignored-provider-override",+ "doctor",+ "models",+ "--use-cache",+ "false",+ ]))+ .expect("valid legacy models arguments")+ .expect("legacy models is routed through inspection");++ assert_eq!(invocation.method, "openhuman.doctor_models");+ assert_eq!(+ Value::Object(invocation.params),+ json!({"use_cache": false})+ );+}++#[test]+fn help_and_other_namespaces_remain_with_the_general_cli_dispatcher() {+ for invocation in [+ args(&["doctor", "report", "--help"]),+ args(&["doctor", "models", "help"]),+ args(&["doctor", "unknown"]),+ args(&["cron", "list"]),+ args(&["--model", "example", "cron", "list"]),+ ] {+ assert_eq!(parse(&invocation).unwrap(), None, "{invocation:?}");+ }+}++#[test]+fn legacy_doctor_parameter_errors_use_the_registered_schema() {+ let error = parse(&args(&["doctor", "report", "--unknown", "value"]))+ .expect_err("unknown controller parameters are refused");+ assert!(error.to_string().contains("unknown param 'unknown'"));+}++#[test]+fn raw_json_printer_preserves_both_outcome_and_bare_controller_shapes() {+ let report = json!({+ "result": {"schema_version": 2, "findings": []},+ "logs": ["doctor report generated"]+ });+ let models = json!({"entries": [], "summary": {"ok": 0, "skipped": 0}});++ assert_eq!(+ serde_json::from_str::<Value>(&format_json(&report).expect("format report JSON"))+ .expect("parse report JSON"),+ report+ );+ assert_eq!(+ serde_json::from_str::<Value>(&format_json(&models).expect("format models JSON"))+ .expect("parse models JSON"),+ models+ );+}diff --git a/crates/openhuman-rpc/src/host_tests.rs b/crates/openhuman-rpc/src/host_tests.rsindex 2f0e76d37b..90161e46c0 100644--- a/crates/openhuman-rpc/src/host_tests.rs+++ b/crates/openhuman-rpc/src/host_tests.rs@@ -19,6 +19,40 @@ fn cli_builder_is_the_cli_preset_with_server_and_http_host() {assert_eq!(summary.controller_extensions, vec![DomainGroup::Platform]);}+#[cfg(feature = "server")]+#[test]+fn doctor_builder_is_preloaded_inspection_with_no_services_or_storage() {+ let root = tempfile::tempdir().expect("temp root");+ let config = doctor_fallback_config(root.path());+ let summary = doctor_builder(config).into_embed().summary();++ assert!(matches!(+ summary.workspace,+ openhuman_tinyhumans::embed::Workspace::Inherit+ ));+ assert_eq!(+ summary.config_source,+ openhuman_tinyhumans::embed::ConfigSource::Resolved+ );+ assert_eq!(summary.services, Some(ServiceSet::none()));+ assert!(summary.fixed_token);+ assert!(!summary.has_api_key);+ assert!(!summary.has_session_store);+ assert!(!summary.has_memory_engine);+ assert!(summary.has_server_launcher);+}++#[cfg(feature = "server")]+#[test]+fn invalid_profile_fallback_config_is_pinned_to_the_selected_root() {+ let root = tempfile::tempdir().expect("temp root");+ let config = doctor_fallback_config(root.path());++ assert_eq!(config.config_path, root.path().join("config.toml"));+ assert_eq!(config.workspace_dir, root.path().join("workspace"));+ assert_eq!(config.action_dir, root.path().join("action"));+}+#[cfg(feature = "server")]#[test]fn desktop_builder_carries_bearer_listener_and_services() {@@ -165,6 +199,27 @@ fn cli_storage_is_opened_for_one_shot_commands_only() {assert!(uses(&["--model", "help", "cron", "list"]));}+#[test]+#[cfg(feature = "server")]+fn legacy_doctor_namespace_commands_do_not_preopen_storage() {+ let args = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::<Vec<_>>();+ let uses = |parts: &[&str]| cli_command_uses_storage(&args(parts), |_| true);++ for invocation in [+ &["doctor", "report"][..],+ &["doctor", "report", "--tier", "static"][..],+ &["--model", "x", "doctor", "report", "--only", "config/parse"][..],+ &["doctor", "models"][..],+ &["doctor", "models", "--use-cache", "false"][..],+ &["--provider=x", "doctor", "models", "--use-cache", "true"][..],+ ] {+ assert!(+ !uses(invocation),+ "legacy doctor inspection must not open storage before namespace dispatch: {invocation:?}"+ );+ }+}+#[test]fn embed_info_is_versioned_and_rejects_unknown_flags() {let info = embed_info(&["embed".into(), "info".into(), "--json".into()])diff --git a/crates/openhuman-rpc/src/lib.rs b/crates/openhuman-rpc/src/lib.rsindex 17fcaed4f1..96fb2c8120 100644--- a/crates/openhuman-rpc/src/lib.rs+++ b/crates/openhuman-rpc/src/lib.rs@@ -53,9 +53,9 @@ pub mod tinyhumans {pub mod embed {pub use openhuman_tinyhumans::embed::modules;pub use openhuman_tinyhumans::embed::{- artifacts, chat_surface, config, process, schema_for_rpc_method, secret_storage,- CoreRuntime, PickListenPortError, RuntimeBuilder, RuntimeInfo, ServiceSet,- HTTP_SERVER_COMPILED_IN, VOICE_COMPILED_IN,+ artifacts, chat_surface, cli, config, process, schema_for_rpc_method, secret_storage,+ CoreBootMode, CoreRuntime, PickListenPortError, Runtime, RuntimeBuilder, RuntimeConfig,+ RuntimeInfo, ServiceSet, TokenSource, HTTP_SERVER_COMPILED_IN, VOICE_COMPILED_IN,};}diff --git a/crates/openhuman-tinyhumans/Cargo.toml b/crates/openhuman-tinyhumans/Cargo.tomlindex 7aa13d5cb4..c4b04bce6b 100644--- a/crates/openhuman-tinyhumans/Cargo.toml+++ b/crates/openhuman-tinyhumans/Cargo.toml@@ -92,6 +92,10 @@ tinyinference-providers = { path = "../../vendor/tinyagents/vendor/tinyinferencetinyinference-llm = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }tinyinference-embeddings = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-embeddings" }tinyinference-core = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core" }+# The hosted memory engine uses the same TinyMemory contract and integration+# implementation as the core, keeping the vendor crates unified in one graph.+tinymemory-api = { path = "../../vendor/tinymemory/crates/tinymemory-api", features = ["local-safety"] }+tinymemory-integrations = { path = "../../vendor/tinymemory/crates/tinymemory-integrations", default-features = false, features = ["cortex", "brain", "sources-network", "safety", "legacy-import"] }# Managed media generation (`integrations::media`): the OpenRouter image and# video generators, over the same vendored crates the core's harness uses.tinyinference-image = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-image", optional = true }diff --git a/crates/openhuman-tinyhumans/src/doctor/hosted_checks_tests.rs b/crates/openhuman-tinyhumans/src/doctor/hosted_checks_tests.rsnew file mode 100644index 0000000000..916bf9a1cc--- /dev/null+++ b/crates/openhuman-tinyhumans/src/doctor/hosted_checks_tests.rs@@ -0,0 +1,599 @@+use super::*;+use crate::session::test_support::{EXPIRED_JWT, LIVE_JWT};+use openhuman_embed::__host::config::Config;+use openhuman_embed::__host::core::runtime::CoreContext;+use openhuman_embed::__host::doctor::{registered_checks, ComponentId, DoctorCheck};+use openhuman_embed::{CoreBuilder, DomainSet, HostKind, ServiceSet};+use serde_json::json;+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;+use tempfile::TempDir;+use wiremock::matchers::{header, method, path, query_param};+use wiremock::{Mock, MockServer, ResponseTemplate};++fn context(tmp: &TempDir, api_url: &str) -> DoctorCtx {+ let state_dir = tmp.path().join("workspace");+ context_at(&state_dir, &state_dir, api_url)+}++fn config_at(state_dir: &Path, workspace_dir: &Path, api_url: &str) -> Config {+ let mut config = Config {+ workspace_dir: workspace_dir.to_path_buf(),+ action_dir: workspace_dir.to_path_buf(),+ config_path: state_dir.join("config.toml"),+ api_url: Some(api_url.to_owned()),+ ..Config::default()+ };+ config.resolved_endpoints.control_plane_url = Some(api_url.to_owned());+ config+}++fn context_at(state_dir: &Path, workspace_dir: &Path, api_url: &str) -> DoctorCtx {+ DoctorCtx::from_config(config_at(state_dir, workspace_dir, api_url))+}++fn write_raw_session_profile(+ ctx: &DoctorCtx,+ token: &str,+ metadata: serde_json::Map<String, serde_json::Value>,+) -> (PathBuf, Vec<u8>) {+ let state_dir = ctx.config().config_path.parent().expect("config state dir");+ std::fs::create_dir_all(state_dir).expect("create temp config state dir");+ let path = state_dir.join("auth-profiles.json");+ let bytes = serde_json::to_vec(&json!({+ "schema_version": 1,+ "updated_at": "2026-01-01T00:00:00Z",+ "active_profiles": {},+ "profiles": {+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": token,+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-01T00:00:00Z",+ "metadata": metadata,+ }+ }+ }))+ .expect("serialize schema-1 auth profile");+ std::fs::write(&path, &bytes).expect("write schema-1 auth profile");+ (path, bytes)+}++fn metadata(+ entries: impl IntoIterator<Item = (&'static str, String)>,+) -> serde_json::Map<String, serde_json::Value> {+ entries+ .into_iter()+ .map(|(key, value)| (key.to_owned(), serde_json::Value::String(value)))+ .collect()+}++fn workspace_snapshot(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {+ fn visit(root: &Path, dir: &Path, snapshot: &mut BTreeMap<PathBuf, Vec<u8>>) {+ for entry in std::fs::read_dir(dir).expect("read temp workspace") {+ let entry = entry.expect("workspace entry");+ let path = entry.path();+ if entry.file_type().expect("workspace entry type").is_dir() {+ visit(root, &path, snapshot);+ } else {+ snapshot.insert(+ path.strip_prefix(root)+ .expect("workspace-relative path")+ .to_path_buf(),+ std::fs::read(path).expect("read workspace file"),+ );+ }+ }+ }+ let mut snapshot = BTreeMap::new();+ if root.exists() {+ visit(root, root, &mut snapshot);+ }+ snapshot+}++async fn registered_ids(runtime: &openhuman_embed::CoreRuntime) -> Vec<String> {+ CoreContext::scope(runtime.context().clone(), async {+ registered_checks()+ .expect("registered checks")+ .iter()+ .map(|check| check.id().to_owned())+ .collect::<Vec<_>>()+ })+ .await+}++fn check(source: &HostedDoctorCheckSource, id: &str) -> Arc<dyn DoctorCheck> {+ source+ .checks()+ .into_iter()+ .find(|check| check.id() == id)+ .unwrap_or_else(|| panic!("missing hosted doctor check {id}"))+}++async fn findings(source: &HostedDoctorCheckSource, ctx: &DoctorCtx) -> Vec<Finding> {+ let checks = source.checks();+ let mut findings = Vec::with_capacity(checks.len());+ for check in checks {+ findings.extend(check.detect(ctx).await);+ }+ findings+}++async fn run_isolated_probe(scenario: &str, root: &Path, api_url: &str) -> serde_json::Value {+ let workspace = root.join("workspace");+ let output = tokio::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "doctor::tests::hosted_probe_child",+ "--nocapture",+ ])+ .env("OPENHUMAN_DOCTOR_PROBE_CHILD_SCENARIO", scenario)+ .env("OPENHUMAN_DOCTOR_PROBE_CHILD_ROOT", root)+ .env("OPENHUMAN_DOCTOR_PROBE_CHILD_API_URL", api_url)+ .env("OPENHUMAN_WORKSPACE", &workspace)+ .env("OPENHUMAN_KEYRING_BACKEND", "encrypted_file")+ .env("OPENHUMAN_KEYRING_MASTER_KEY", "11".repeat(32))+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")+ .output()+ .await+ .expect("run isolated doctor child test");+ assert!(+ output.status.success(),+ "child test failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ serde_json::from_slice(&std::fs::read(root.join("child-result.json")).expect("child report"))+ .expect("parse child report")+}++#[tokio::test]+async fn hosted_probe_child() {+ let Some(scenario) = std::env::var_os("OPENHUMAN_DOCTOR_PROBE_CHILD_SCENARIO") else {+ return;+ };+ let scenario = scenario.to_string_lossy();+ let root =+ PathBuf::from(std::env::var_os("OPENHUMAN_DOCTOR_PROBE_CHILD_ROOT").expect("child root"));+ openhuman_embed::process::init_master_key().expect("initialize isolated test key source");+ openhuman_embed::__host::core::bus::init()+ .await+ .expect("initialize isolated child bus");+ let mut events = openhuman_embed::__host::core::bus::BUS+ .get()+ .expect("initialized bus")+ .receiver();+ let workspace = root.join("workspace");+ let api_url = std::env::var("OPENHUMAN_DOCTOR_PROBE_CHILD_API_URL").expect("child api url");+ let ctx = context_at(&workspace, &workspace, &api_url);+ let (active_url, active_token, active_status) = match scenario.as_ref() {+ "socket-mismatch" => (+ "https://profile-a.example/socket.io".to_owned(),+ "session-a".to_owned(),+ ConnectionStatus::Connected,+ ),+ "socket-owner-error" => (+ api_url.clone(),+ LIVE_JWT.to_string(),+ ConnectionStatus::Error,+ ),+ "socket-owner-reconnecting" => (+ api_url.clone(),+ LIVE_JWT.to_string(),+ ConnectionStatus::Reconnecting,+ ),+ _ => (+ api_url.clone(),+ LIVE_JWT.to_string(),+ ConnectionStatus::Connected,+ ),+ };+ let source = HostedDoctorCheckSource::with_socket_state_reader(move |url, token| {+ (url == active_url && token == active_token).then_some(active_status)+ });+ let before = (scenario == "expired").then(|| workspace_snapshot(&workspace));++ let report = match scenario.as_ref() {+ "healthy" => {+ let results = findings(&source, &ctx).await;+ json!({+ "findings": results.iter().map(|finding| json!({+ "check_id": finding.check_id,+ "severity": format!("{:?}", finding.severity),+ "message": finding.message,+ })).collect::<Vec<_>>(),+ })+ }+ "outage" => {+ let results = [+ "backend/reachable",+ "backend/identity",+ "inference/managed-catalog",+ ]+ .into_iter()+ .map(|id| check(&source, id));+ let mut findings = Vec::new();+ for probe in results {+ findings.extend(probe.detect(&ctx).await);+ }+ json!({+ "findings": findings.iter().map(|finding| json!({+ "check_id": finding.check_id,+ "severity": format!("{:?}", finding.severity),+ "message": finding.message,+ })).collect::<Vec<_>>(),+ })+ }+ "issuer-mismatch" => {+ let results = [+ "backend/credential",+ "backend/identity",+ "inference/managed-catalog",+ ]+ .into_iter()+ .map(|id| check(&source, id));+ let mut findings = Vec::new();+ for probe in results {+ findings.extend(probe.detect(&ctx).await);+ }+ json!({+ "findings": findings.iter().map(|finding| json!({+ "check_id": finding.check_id,+ "severity": format!("{:?}", finding.severity),+ "message": finding.message,+ })).collect::<Vec<_>>(),+ })+ }+ "socket-mismatch" | "socket-owner-error" | "socket-owner-reconnecting" => {+ let finding = check(&source, "backend/socket").detect(&ctx).await;+ json!({+ "severity": format!("{:?}", finding[0].severity),+ "message": finding[0].message,+ })+ }+ "scoped-context" => {+ let config = config_at(&root, &workspace, &api_url);+ let hosted = crate::RuntimeBuilder::new()+ .workspace(crate::embed::Workspace::Dir(workspace.clone()))+ .services(crate::embed::ServiceSet::none())+ .domains(crate::embed::DomainSet::none())+ .config(config.clone())+ .build()+ .await+ .expect("TinyHumans runtime context");+ let core_only = CoreBuilder::new(HostKind::Library)+ .services(ServiceSet::none())+ .domains(DomainSet::none())+ .config(config)+ .build()+ .await+ .expect("plain core context");+ json!({+ "hosted_ids": registered_ids(hosted.core_runtime()).await,+ "core_ids": registered_ids(&core_only).await,+ })+ }+ "expired" => {+ let finding = check(&source, "backend/credential").detect(&ctx).await;+ let mut session_expired_published = false;+ while let Ok(event) = events.try_recv() {+ if matches!(+ event,+ openhuman_embed::__host::core::events::DomainEvent::SessionExpired { .. }+ ) {+ session_expired_published = true;+ }+ }+ json!({+ "severity": format!("{:?}", finding[0].severity),+ "message": finding[0].message,+ "profile_store_unchanged": before.unwrap() == workspace_snapshot(&workspace),+ "session_expired_published": session_expired_published,+ })+ }+ _ => panic!("unknown child scenario"),+ };+ std::fs::write(+ root.join("child-result.json"),+ serde_json::to_vec(&report).unwrap(),+ )+ .expect("write child result outside profile workspace");+}++#[tokio::test]+async fn healthy_backend_passes_hosted_checks_and_uses_sdk_attribution() {+ let _registry = crate::registry_test_lock_async().await;+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/"))+ .and(header("x-sdk-name", "openhuman"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/auth/me"))+ .and(header("x-sdk-name", "openhuman"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(json!({"success": true, "data": {"user": {"id": "private-user"}}})),+ )+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/openai/v1/models"))+ .and(query_param("catalog", "openrouter"))+ .and(header("x-sdk-name", "openhuman"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"data": []})))+ .expect(1)+ .mount(&server)+ .await;++ let tmp = TempDir::new().unwrap();+ let ctx = context(&tmp, &server.uri());+ write_raw_session_profile(+ &ctx,+ &LIVE_JWT,+ metadata([("session_issuing_backend", server.uri())]),+ );+ let report = run_isolated_probe("healthy", tmp.path(), &server.uri()).await;+ let findings = report["findings"].as_array().unwrap();+ assert_eq!(findings.len(), 6);+ assert!(findings.iter().all(|finding| finding["severity"] == "Pass"));+ assert!(findings.iter().all(|finding| {+ !finding["message"]+ .as_str()+ .unwrap()+ .contains("private-user")+ }));+ let requests = server.received_requests().await.unwrap();+ assert!(requests.iter().any(|request| request.url.path() == "/"));+ assert!(requests+ .iter()+ .any(|request| request.url.path() == "/auth/me"));+ assert!(requests+ .iter()+ .any(|request| request.url.path() == "/openai/v1/models"));+ assert!(requests+ .iter()+ .all(|request| request.headers.get("x-sdk-name").is_some()));+}++#[tokio::test]+async fn backend_outage_skips_authenticated_hosted_probes_without_leaking_response_data() {+ let _registry = crate::registry_test_lock_async().await;+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/"))+ .respond_with(+ ResponseTemplate::new(503).set_body_string("token=private-token user=private-user"),+ )+ .mount(&server)+ .await;++ let tmp = TempDir::new().unwrap();+ let ctx = context(&tmp, &server.uri());+ write_raw_session_profile(+ &ctx,+ &LIVE_JWT,+ metadata([("session_issuing_backend", server.uri())]),+ );+ let report = run_isolated_probe("outage", tmp.path(), &server.uri()).await;+ let findings = report["findings"].as_array().unwrap();+ assert_eq!(findings.len(), 3);+ assert_eq!(findings[0]["severity"], "Error");+ assert_eq!(findings[1]["severity"], "Skipped");+ assert_eq!(findings[2]["severity"], "Skipped");+ assert!(findings.iter().all(|finding| {+ !finding["message"]+ .as_str()+ .unwrap()+ .contains("private-token")+ }));+ assert!(findings.iter().all(|finding| {+ !finding["message"]+ .as_str()+ .unwrap()+ .contains("private-user")+ }));+ let requests = server.received_requests().await.unwrap();+ assert!(requests.iter().all(|request| request.url.path() == "/"));+ assert!(requests+ .iter()+ .all(|request| !request.headers.contains_key("authorization")));+}++#[tokio::test]+async fn expired_session_probe_preserves_profile_and_does_not_publish_expiry() {+ let _registry = crate::registry_test_lock_async().await;+ let tmp = TempDir::new().unwrap();+ let workspace = tmp.path().join("workspace");+ let ctx = context_at(&workspace, &workspace, "http://127.0.0.1:9");+ write_raw_session_profile(+ &ctx,+ &EXPIRED_JWT,+ metadata([+ ("session_issuing_backend", "http://127.0.0.1:9".to_owned()),+ ("session_expires_at", "2001-01-01T00:00:00Z".to_owned()),+ ]),+ );++ let report = run_isolated_probe("expired", tmp.path(), "http://127.0.0.1:9").await;+ assert_eq!(report["severity"], "Error");+ assert!(report["message"]+ .as_str()+ .unwrap()+ .contains("SESSION_EXPIRED"));+ assert_eq!(report["profile_store_unchanged"], true);+ assert_eq!(report["session_expired_published"], false);+ assert!(!report["message"].as_str().unwrap().contains(&*EXPIRED_JWT));+}++#[tokio::test]+async fn foreign_socket_connection_is_skipped_for_selected_profile() {+ let tmp = TempDir::new().unwrap();+ let api_url = "https://selected-b.example";+ let ctx = context(&tmp, api_url);+ write_raw_session_profile(+ &ctx,+ &LIVE_JWT,+ metadata([("session_issuing_backend", api_url.to_owned())]),+ );+ let report = run_isolated_probe("socket-mismatch", tmp.path(), api_url).await;+ assert_eq!(report["severity"], "Skipped");+ assert!(!report["message"].as_str().unwrap().contains(&*LIVE_JWT));+}++#[tokio::test]+async fn socket_error_for_selected_profile_remains_an_error() {+ let tmp = TempDir::new().unwrap();+ let api_url = "https://selected-b.example";+ let ctx = context(&tmp, api_url);+ write_raw_session_profile(+ &ctx,+ &LIVE_JWT,+ metadata([("session_issuing_backend", api_url.to_owned())]),+ );+ let report = run_isolated_probe("socket-owner-error", tmp.path(), api_url).await;+ assert_eq!(report["severity"], "Error");+}++#[tokio::test]+async fn reconnecting_socket_status_is_preserved_for_its_owner() {+ let tmp = TempDir::new().unwrap();+ let api_url = "https://selected-b.example";+ let ctx = context(&tmp, api_url);+ write_raw_session_profile(+ &ctx,+ &LIVE_JWT,+ metadata([("session_issuing_backend", api_url.to_owned())]),+ );+ let report = run_isolated_probe("socket-owner-reconnecting", tmp.path(), api_url).await;+ assert_eq!(report["severity"], "Warn");+}++#[tokio::test]+async fn mismatched_issuing_backend_is_rejected_before_authenticated_probes() {+ let _registry = crate::registry_test_lock_async().await;+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/"))+ .and(header("x-sdk-name", "openhuman"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/auth/me"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"user": "private-user"})))+ .expect(0)+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/openai/v1/models"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({"data": []})))+ .expect(0)+ .mount(&server)+ .await;++ let tmp = TempDir::new().unwrap();+ let ctx = context(&tmp, &server.uri());+ write_raw_session_profile(+ &ctx,+ &LIVE_JWT,+ metadata([(+ "session_issuing_backend",+ "https://issuer-a.example".to_owned(),+ )]),+ );+ let report = run_isolated_probe("issuer-mismatch", tmp.path(), &server.uri()).await;+ let findings = report["findings"].as_array().unwrap();+ assert_eq!(findings[0]["severity"], "Error");+ assert!(findings[0]["message"]+ .as_str()+ .unwrap()+ .contains("SESSION_BACKEND_MISMATCH"));+ assert_eq!(findings[1]["severity"], "Skipped");+ assert_eq!(findings[2]["severity"], "Skipped");+ for finding in findings {+ assert!(!finding["message"].as_str().unwrap().contains(&*LIVE_JWT));+ assert!(!finding["message"]+ .as_str()+ .unwrap()+ .contains("issuer-a.example"));+ assert!(!finding["message"]+ .as_str()+ .unwrap()+ .contains("private-user"));+ }++ let requests = server.received_requests().await.unwrap();+ assert!(!requests+ .iter()+ .any(|request| request.url.path() == "/auth/me"));+ assert!(!requests+ .iter()+ .any(|request| request.url.path() == "/openai/v1/models"));+ assert!(requests.iter().all(|request| request.url.path() == "/"));+ assert!(requests+ .iter()+ .all(|request| !request.headers.contains_key("authorization")));+ server.verify().await;+}++#[test]+fn backend_credential_check_runs_in_the_connect_tier() {+ assert_eq!(+ check(&HostedDoctorCheckSource::default(), "backend/credential").tier(),+ DoctorTier::Connect+ );+}++#[test]+fn every_hosted_check_is_gated_by_the_hosting_component() {+ let checks = HostedDoctorCheckSource::default().checks();+ let expected_ids = [+ "backend/reachable",+ "backend/credential",+ "backend/identity",+ "backend/socket",+ "backend/api-url",+ "inference/managed-catalog",+ ];++ assert_eq!(+ checks.iter().map(|check| check.id()).collect::<Vec<_>>(),+ expected_ids+ );+ for check in checks {+ assert_eq!(+ check.component_gate(),+ Some(ComponentId::Hosting),+ "{} must require the Hosting component",+ check.id()+ );+ }+}++#[tokio::test]+async fn tinyhumans_runtime_registration_is_context_scoped() {+ let tmp = TempDir::new().unwrap();+ let api_url = "https://scope-test.example";+ let report = run_isolated_probe("scoped-context", tmp.path(), api_url).await;+ let hosted_ids = report["hosted_ids"].as_array().unwrap();+ let core_ids = report["core_ids"].as_array().unwrap();++ for id in [+ "backend/reachable",+ "backend/credential",+ "backend/identity",+ "backend/socket",+ "backend/api-url",+ "inference/managed-catalog",+ ] {+ assert!(hosted_ids.iter().any(|registered| registered == id), "{id}");+ assert!(!core_ids.iter().any(|registered| registered == id), "{id}");+ }+}diff --git a/crates/openhuman-tinyhumans/src/doctor/mod.rs b/crates/openhuman-tinyhumans/src/doctor/mod.rsnew file mode 100644index 0000000000..c0f9c4ae4d--- /dev/null+++ b/crates/openhuman-tinyhumans/src/doctor/mod.rs@@ -0,0 +1,495 @@+//! Read-only doctor checks for the TinyHumans-hosted backend.++use std::sync::Arc;++use async_trait::async_trait;+use openhuman_embed::__host::config::Config;+use openhuman_embed::__host::doctor::{+ register_check_source, register_check_source_in, ComponentId, DoctorCheck, DoctorCheckSource,+ DoctorCtx, DoctorTier, Finding, FindingSeverity,+};+use openhuman_embed::__host::platform::socket::{global_socket_manager, ConnectionStatus};+use openhuman_embed::__host::security::credentials::api_key::get_api_key_read_only;+use openhuman_embed::__host::security::credentials::session_support::{+ classify_session_token, is_local_session_token, load_app_session_profile_read_only,+ session_token_for_config, BackendCredential, SessionTokenCheck,+};+use tinyhumans_sdk::{Error as SdkError, TinyHumansClient};++use crate::backend::product::product_identity_headers;+use crate::backend::url::{+ effective_backend_api_url, looks_like_inference_provider_endpoint, looks_like_local_ai_endpoint,+};+use crate::client::shared_transport;+use crate::hosted::client::{CredentialKind, HostedClient};+use crate::transport::{BackendTransport, TransportProfile};++const SOURCE_ID: &str = "tinyhumans";+const HEALTH_FIX: &str = "Check the configured backend URL and network access, then rerun doctor.";+const AUTH_FIX: &str = "Sign in again through the supported auth flow, then rerun doctor.";+const CATALOG_FIX: &str = "Check managed inference access for this profile, then rerun doctor.";++type SocketStateReader = Arc<dyn Fn(&str, &str) -> Option<ConnectionStatus> + Send + Sync>;++/// The stateless group of TinyHumans checks registered by this crate.+pub(crate) struct HostedDoctorCheckSource {+ socket_state: SocketStateReader,+}++impl Default for HostedDoctorCheckSource {+ fn default() -> Self {+ Self {+ socket_state: Arc::new(|url, token| {+ global_socket_manager().and_then(|manager| manager.status_for(url, token))+ }),+ }+ }+}++impl HostedDoctorCheckSource {+ #[cfg(test)]+ fn with_socket_state_reader(+ reader: impl Fn(&str, &str) -> Option<ConnectionStatus> + Send + Sync + 'static,+ ) -> Self {+ Self {+ socket_state: Arc::new(reader),+ }+ }+}++impl DoctorCheckSource for HostedDoctorCheckSource {+ fn id(&self) -> &str {+ SOURCE_ID+ }++ fn checks(&self) -> Vec<Arc<dyn DoctorCheck>> {+ vec![+ Arc::new(BackendReachable),+ Arc::new(BackendCredentialCheck),+ Arc::new(BackendIdentity),+ Arc::new(BackendSocket(Arc::clone(&self.socket_state))),+ Arc::new(BackendApiUrl),+ Arc::new(ManagedCatalog),+ ]+ }+}++pub(crate) fn register(registration: crate::register::DoctorRegistration<'_>) {+ let source = HostedDoctorCheckSource::default();+ match registration {+ crate::register::DoctorRegistration::Process => register_check_source(source),+ crate::register::DoctorRegistration::Context(extensions) => {+ register_check_source_in(extensions, source)+ }+ }+}++struct BackendReachable;++#[async_trait]+impl DoctorCheck for BackendReachable {+ fn id(&self) -> &str {+ "backend/reachable"+ }++ fn category(&self) -> &str {+ "Backend"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Hosting)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ vec![match health_check(ctx.config()).await {+ Ok(()) => Finding::pass(self.id(), "The hosted backend is reachable."),+ Err(HealthFailure::Status(status)) => Finding::error(+ self.id(),+ format!("The hosted backend health check returned HTTP {status}."),+ HEALTH_FIX,+ ),+ Err(HealthFailure::Transport) => Finding::error(+ self.id(),+ "The hosted backend health check could not complete.",+ HEALTH_FIX,+ ),+ }]+ }+}++struct BackendCredentialCheck;++#[async_trait]+impl DoctorCheck for BackendCredentialCheck {+ fn id(&self) -> &str {+ "backend/credential"+ }++ fn category(&self) -> &str {+ "Backend"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Hosting)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ vec![match doctor_credential(ctx.config()) {+ CredentialState::Usable(_) => {+ Finding::pass(self.id(), "A usable hosted credential is configured.")+ }+ CredentialState::Expired => Finding::error(+ self.id(),+ "SESSION_EXPIRED: the backend session has expired.",+ AUTH_FIX,+ ),+ CredentialState::Local => Finding::skipped(+ self.id(),+ "This profile uses a local-only session without hosted backend access.",+ "Sign in with a TinyHumans account to run hosted checks.",+ ),+ CredentialState::Absent => Finding::skipped(+ self.id(),+ "No usable hosted credential is configured.",+ "Sign in with a TinyHumans account to run hosted checks.",+ ),+ CredentialState::BackendMismatch => Finding::error(+ self.id(),+ "SESSION_BACKEND_MISMATCH: the stored session belongs to a different backend.",+ "Restore the backend that issued this session or sign in to the configured backend.",+ ),+ CredentialState::Unreadable => Finding::error(+ self.id(),+ "The stored hosted credential could not be read safely.",+ AUTH_FIX,+ ),+ }]+ }+}++struct BackendIdentity;++#[async_trait]+impl DoctorCheck for BackendIdentity {+ fn id(&self) -> &str {+ "backend/identity"+ }++ fn category(&self) -> &str {+ "Backend"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Hosting)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let credential = match doctor_credential(ctx.config()) {+ CredentialState::Usable(credential) => credential,+ _ => return vec![credential_skipped(self.id())],+ };+ if health_check(ctx.config()).await.is_err() {+ return vec![backend_dependent_skipped(self.id())];+ }++ let client = hosted_client(ctx.config(), credential);+ vec![match client.sdk().auth().me().await {+ Ok(_) => Finding::pass(self.id(), "The backend accepted the configured identity."),+ Err(error) => auth_finding(self.id(), client.kind(), error, AUTH_FIX),+ }]+ }+}++struct BackendSocket(SocketStateReader);++#[async_trait]+impl DoctorCheck for BackendSocket {+ fn id(&self) -> &str {+ "backend/socket"+ }++ fn category(&self) -> &str {+ "Backend"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Hosting)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let Some(url) = ctx.config().resolved_endpoints.control_plane_url.as_deref() else {+ return vec![Finding::skipped(+ self.id(),+ "The selected profile has no resolved backend socket endpoint.",+ "Configure the hosted backend before checking its socket connection.",+ )];+ };+ let CredentialState::Usable(BackendCredential::Session(token)) =+ doctor_credential(ctx.config())+ else {+ return vec![Finding::skipped(+ self.id(),+ "The selected profile has no usable session for a backend socket check.",+ "Sign in with a TinyHumans account to run this check.",+ )];+ };+ let Some(status) = (self.0)(url, &token) else {+ return vec![Finding::skipped(+ self.id(),+ "No socket connection is active for the selected profile.",+ "Enable the socket service for this profile, then rerun doctor.",+ )];+ };++ let finding = match status {+ ConnectionStatus::Connected => {+ Finding::pass(self.id(), "The backend socket is connected.")+ }+ ConnectionStatus::Connecting => Finding::new(+ self.id(),+ FindingSeverity::Info,+ "The backend socket is connecting.",+ "No action required while the connection starts.",+ ),+ ConnectionStatus::Reconnecting => Finding::new(+ self.id(),+ FindingSeverity::Warn,+ "The backend socket is reconnecting.",+ HEALTH_FIX,+ ),+ ConnectionStatus::Disconnected => Finding::new(+ self.id(),+ FindingSeverity::Warn,+ "The backend socket is disconnected.",+ HEALTH_FIX,+ ),+ ConnectionStatus::Error => Finding::error(+ self.id(),+ "The backend socket reported a connection error.",+ HEALTH_FIX,+ ),+ };+ vec![finding]+ }+}++struct BackendApiUrl;++#[async_trait]+impl DoctorCheck for BackendApiUrl {+ fn id(&self) -> &str {+ "backend/api-url"+ }++ fn category(&self) -> &str {+ "Backend"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Static+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Hosting)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let configured = ctx.config().api_url.as_deref().unwrap_or_default().trim();+ if !configured.is_empty() {+ let Ok(parsed) = url::Url::parse(configured) else {+ return vec![Finding::error(+ self.id(),+ "The configured backend API URL is invalid.",+ "Set api_url to an absolute HTTP or HTTPS backend URL.",+ )];+ };+ if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {+ return vec![Finding::error(+ self.id(),+ "The configured backend API URL must use HTTP or HTTPS and include a host.",+ "Set api_url to an absolute HTTP or HTTPS backend URL.",+ )];+ }+ if looks_like_local_ai_endpoint(configured)+ || looks_like_inference_provider_endpoint(configured)+ {+ return vec![Finding::new(+ self.id(),+ FindingSeverity::Warn,+ "The configured api_url looks like an inference endpoint; hosted requests use the backend default.",+ "Set api_url to the hosted backend URL and configure model inference with inference_url.",+ )];+ }+ }++ let resolved = effective_backend_api_url(&ctx.config().api_url);+ match url::Url::parse(&resolved) {+ Ok(parsed)+ if matches!(parsed.scheme(), "http" | "https") && parsed.host_str().is_some() =>+ {+ vec![Finding::pass(+ self.id(),+ "The hosted backend API URL is valid.",+ )]+ }+ _ => vec![Finding::error(+ self.id(),+ "The hosted backend API URL could not be resolved.",+ "Set api_url to an absolute HTTP or HTTPS backend URL.",+ )],+ }+ }+}++struct ManagedCatalog;++#[async_trait]+impl DoctorCheck for ManagedCatalog {+ fn id(&self) -> &str {+ "inference/managed-catalog"+ }++ fn category(&self) -> &str {+ "Inference"+ }++ fn tier(&self) -> DoctorTier {+ DoctorTier::Connect+ }++ fn component_gate(&self) -> Option<ComponentId> {+ Some(ComponentId::Hosting)+ }++ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding> {+ let credential = match doctor_credential(ctx.config()) {+ CredentialState::Usable(credential) => credential,+ _ => return vec![credential_skipped(self.id())],+ };+ if health_check(ctx.config()).await.is_err() {+ return vec![backend_dependent_skipped(self.id())];+ }++ let client = hosted_client(ctx.config(), credential);+ let query = [("catalog", Some("openrouter".to_owned()))];+ vec![match client.sdk().inference().list_models(&query).await {+ Ok(_) => Finding::pass(self.id(), "The managed inference catalog is reachable."),+ Err(error) => auth_finding(self.id(), client.kind(), error, CATALOG_FIX),+ }]+ }+}++enum CredentialState {+ Usable(BackendCredential),+ Expired,+ Local,+ Absent,+ BackendMismatch,+ Unreadable,+}++fn doctor_credential(config: &Config) -> CredentialState {+ match get_api_key_read_only(config) {+ Ok(Some(key)) => return CredentialState::Usable(BackendCredential::ApiKey(key)),+ Ok(None) => {}+ Err(_) => return CredentialState::Unreadable,+ }++ let profile = match load_app_session_profile_read_only(config) {+ Ok(profile) => profile,+ Err(_) => return CredentialState::Unreadable,+ };+ let token = match session_token_for_config(config, profile.as_ref()) {+ Ok(Some(token)) => token,+ Ok(None) => return CredentialState::Absent,+ Err(error) if error.starts_with("SESSION_BACKEND_MISMATCH:") => {+ return CredentialState::BackendMismatch;+ }+ Err(_) => return CredentialState::Unreadable,+ };+ match classify_session_token(profile.as_ref(), chrono::Utc::now()) {+ SessionTokenCheck::Absent => CredentialState::Absent,+ SessionTokenCheck::Expired => CredentialState::Expired,+ SessionTokenCheck::Live(_) if is_local_session_token(&token) => CredentialState::Local,+ SessionTokenCheck::Live(_) => CredentialState::Usable(BackendCredential::Session(token)),+ }+}++fn hosted_client(config: &Config, credential: BackendCredential) -> HostedClient {+ HostedClient::with_credential(&effective_backend_api_url(&config.api_url), credential)+}++fn credential_skipped(id: &str) -> Finding {+ Finding::skipped(+ id,+ "A usable hosted credential is required for this check.",+ "Sign in with a TinyHumans account to run hosted checks.",+ )+}++fn backend_dependent_skipped(id: &str) -> Finding {+ Finding::skipped(+ id,+ "This hosted check was skipped because the backend is unreachable.",+ HEALTH_FIX,+ )+}++fn auth_finding(id: &str, kind: CredentialKind, error: SdkError, fix_hint: &str) -> Finding {+ match error {+ SdkError::Status { status: 401, .. } if kind == CredentialKind::Session => Finding::error(+ id,+ "SESSION_EXPIRED: the backend rejected the session.",+ AUTH_FIX,+ ),+ SdkError::Status { status: 401, .. } if kind == CredentialKind::ApiKey => Finding::error(+ id,+ "API_KEY_REJECTED: the backend rejected the configured API key.",+ AUTH_FIX,+ ),+ SdkError::Status { status, .. } => Finding::error(+ id,+ format!("The hosted request returned HTTP {status}."),+ fix_hint,+ ),+ _ => Finding::error(id, "The hosted request could not complete.", fix_hint),+ }+}++enum HealthFailure {+ Status(u16),+ Transport,+}++async fn health_check(config: &Config) -> Result<(), HealthFailure> {+ let url = effective_backend_api_url(&config.api_url);+ let transport = shared_transport().map_err(|_| HealthFailure::Transport)?;+ let client = TinyHumansClient::new(url)+ .with_http_client(transport.http_client(TransportProfile::Api))+ .with_default_headers(product_identity_headers());+ match client.health().check().await {+ Ok(_) => Ok(()),+ Err(SdkError::Status { status, .. }) => Err(HealthFailure::Status(status)),+ Err(_) => Err(HealthFailure::Transport),+ }+}++#[cfg(test)]+#[path = "hosted_checks_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/inference/managed_calls.rs b/crates/openhuman-tinyhumans/src/inference/managed_calls.rsindex 54c88a970f..c5f8fab14e 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_calls.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_calls.rs@@ -51,10 +51,17 @@ pub(super) fn log_managed_provider_error(pe: &ProviderError, operation: &str) {/// Gives a failure reported inside a stream the same handling as a failed/// `stream()` call: logged, and an expired session starts re-authentication.+#[cfg(test)]pub(super) fn observe_in_band_failure(item: &ModelStreamItem) {+ observe_in_band_failure_with_session_publish(item, true);+}++fn observe_in_band_failure_with_session_publish(item: &ModelStreamItem, publish: bool) {if let ModelStreamItem::ProviderFailed(pe) = item {log_managed_provider_error(pe, "stream (in-band)");- maybe_publish_provider_session_expired(pe, "stream");+ if publish {+ maybe_publish_provider_session_expired(pe, "stream");+ }}}@@ -108,6 +115,7 @@ impl ChatModel<()> for OpenHumanBackendModel {state: &(),request: ModelRequest,) -> tinyinference_llm::Result<ModelResponse> {+ let publish_session_expiry = !self.is_inspection_safe();let model = self.build_wire_model()?;let response = match model.invoke(@@ -119,7 +127,9 @@ impl ChatModel<()> for OpenHumanBackendModel {Ok(response) => response,Err(e) => {log_managed_dispatch_error(&e, "invoke");- maybe_publish_session_expired(&e, "invoke");+ if publish_session_expiry {+ maybe_publish_session_expired(&e, "invoke");+ }return Err(e);}};@@ -131,6 +141,7 @@ impl ChatModel<()> for OpenHumanBackendModel {state: &(),request: ModelRequest,) -> tinyinference_llm::Result<ModelStream> {+ let publish_session_expiry = !self.is_inspection_safe();let model = self.build_wire_model()?;// The backend sends its charge on an `openhuman-metadata` frame before// `[DONE]`; the crate's SSE parser keeps that envelope on the terminal@@ -145,8 +156,8 @@ impl ChatModel<()> for OpenHumanBackendModel {{// A failure can also arrive *inside* an HTTP 200 stream as an SSE// `{"error":…}` payload; it never reaches the `Err` arm (#6724).- Ok(stream) => Ok(stream.map_items(|item| {- observe_in_band_failure(&item);+ Ok(stream) => Ok(stream.map_items(move |item| {+ observe_in_band_failure_with_session_publish(&item, publish_session_expiry);match item {tinyinference_llm::model::ModelStreamItem::Completed(response) => {tinyinference_llm::model::ModelStreamItem::Completed(project_managed_usage(@@ -158,7 +169,9 @@ impl ChatModel<()> for OpenHumanBackendModel {})),Err(e) => {log_managed_dispatch_error(&e, "stream");- maybe_publish_session_expired(&e, "stream");+ if publish_session_expiry {+ maybe_publish_session_expired(&e, "stream");+ }Err(e)}}diff --git a/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs b/crates/openhuman-tinyhumans/src/inference/managed_catalog.rsindex 5b9478951a..02a1869e11 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs@@ -10,7 +10,8 @@use openhuman_embed::__host::config::Config;use openhuman_embed::__host::core::Outcome;use openhuman_embed::__host::inference_registry::{- BoxFuture, CatalogEntry, CatalogLimits, CatalogListing, CatalogRequest,+ BoxFuture, CatalogEntry, CatalogLimits, CatalogListing, CatalogRequest, InspectionCatalogError,+ InspectionCatalogListing, PreparedInspectionCatalog,};use openhuman_embed::__host::security::credentials::session_support::{classify_session_token, load_app_session_profile, publish_local_session_expiry,@@ -21,6 +22,7 @@ use std::sync::Arc;use tinyinference_llm::catalog::{append_query_param, parse_models_response};use tinyinference_llm::model::discover::DiscoveryRequest;+use super::PROVIDER_OPENHUMAN;use crate::backend::headers::attribution_headers;use crate::backend::url::{effective_api_url, effective_backend_api_url};use crate::client::endpoint::{@@ -46,6 +48,98 @@ pub(super) fn entry() -> CatalogEntry {}}+/// Inspection-only variant: freezes a read-only session credential before+/// the core consults its cache. This deliberately does not call `list_models`+/// or any mutable session/catalog path.+pub(super) fn inspection_entry() -> InspectionCatalogListing {+ Arc::new(|config, request| {+ Box::pin(async move {+ use openhuman_embed::__host::security::credentials::session_support::{+ check_session_backend, classify_session_token, load_app_session_profile_read_only,+ SessionTokenCheck,+ };++ let profile = load_app_session_profile_read_only(&config)+ .map_err(|_| InspectionCatalogError::Unavailable)?;+ check_session_backend(&config, profile.as_ref())+ .map_err(|_| InspectionCatalogError::Unavailable)?;+ let session = match classify_session_token(profile.as_ref(), chrono::Utc::now()) {+ SessionTokenCheck::Live(token) => Some(token),+ SessionTokenCheck::Absent | SessionTokenCheck::Expired => None,+ };+ let provider_key = request.provider_key.trim();+ let api_key = if provider_key.is_empty() {+ openhuman_embed::__host::security::credentials::api_key::get_api_key_read_only(+ &config,+ )+ .map_err(|_| InspectionCatalogError::Unavailable)?+ } else {+ Some(provider_key.to_owned())+ };+ let credential = session+ .filter(|_| is_safe_endpoint_for_managed_bearer(&catalog_url(&config)))+ .or_else(|| {+ api_key.filter(|_| is_managed_endpoint_for_api_key(&catalog_url(&config)))+ });+ let url = catalog_url(&config);+ if credential.is_none() {+ return Err(InspectionCatalogError::Unavailable);+ }+ let client = request.client;+ let frozen = credential.clone();+ let fetch_url = url.clone();+ let fetch = Box::pin(async move {+ let mut get = client.get(&fetch_url);+ if let Some(token) = frozen.as_deref() {+ get = get.header("Authorization", format!("Bearer {token}"));+ if let Ok(headers) = attribution_headers() {+ get = get.headers(headers);+ }+ }+ let response = get.send().await.map_err(|error| {+ if error.is_timeout() {+ InspectionCatalogError::Failure+ } else {+ InspectionCatalogError::Unavailable+ }+ })?;+ let status = response.status();+ if status == reqwest::StatusCode::NOT_FOUND {+ return Err(InspectionCatalogError::NoCatalog);+ }+ if matches!(+ status,+ reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN+ ) {+ return Err(InspectionCatalogError::AuthOrAccess);+ }+ if !status.is_success() {+ return Err(InspectionCatalogError::Failure);+ }+ let body = response+ .json::<serde_json::Value>()+ .await+ .map_err(|_| InspectionCatalogError::Failure)?;+ if body.get("error").is_some() {+ return Err(InspectionCatalogError::Failure);+ }+ let models =+ parse_models_response(&body).map_err(|_| InspectionCatalogError::Failure)?;+ Ok(Outcome::new(+ serde_json::json!({"models": models}),+ Vec::new(),+ ))+ });+ Ok(PreparedInspectionCatalog::new(+ PROVIDER_OPENHUMAN,+ &url,+ credential.as_deref(),+ fetch,+ ))+ })+ })+}+fn empty_catalog(reason: &str) -> Result<Outcome<serde_json::Value>, String> {Ok(Outcome::new(serde_json::json!({ "models": Vec::<serde_json::Value>::new() }),diff --git a/crates/openhuman-tinyhumans/src/inference/managed_catalog_inspection_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_catalog_inspection_tests.rsnew file mode 100644index 0000000000..eee4d681ab--- /dev/null+++ b/crates/openhuman-tinyhumans/src/inference/managed_catalog_inspection_tests.rs@@ -0,0 +1,414 @@+use super::super::inspection_entry;+use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ routing::get,+ Json, Router,+};+use openhuman_embed::__host::config::Config;+use openhuman_embed::__host::inference_registry::{+ CatalogRequest, InspectionCatalogError, PreparedInspectionCatalog,+};+use openhuman_embed::__host::security::credentials::session_support::{+ SESSION_EXPIRES_AT_META, SESSION_ISSUING_BACKEND_META,+};+use openhuman_embed::__host::security::credentials::{+ APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,+};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++fn with_backend_env_test_lock(future: impl std::future::Future<Output = ()>) {+ let _env_lock = crate::backend::url::backend_env_test_lock();+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("create current-thread test runtime")+ .block_on(future);+}++#[derive(Clone)]+struct MockManagedCatalog {+ status: StatusCode,+ requests: Arc<AtomicUsize>,+ authorization: Arc<std::sync::Mutex<Vec<Option<String>>>>,+}++async fn catalog_handler(State(state): State<MockManagedCatalog>, headers: HeaderMap) -> Response {+ state.requests.fetch_add(1, Ordering::SeqCst);+ state+ .authorization+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .push(+ headers+ .get("authorization")+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned),+ );+ if state.status.is_success() {+ Json(serde_json::json!({+ "data": [{ "id": "managed-fixture-model", "owned_by": "openrouter" }]+ }))+ .into_response()+ } else {+ (+ state.status,+ Json(serde_json::json!({ "error": "managed fixture rejected the request" })),+ )+ .into_response()+ }+}++async fn spawn_managed_backend(status: StatusCode) -> (String, MockManagedCatalog) {+ let state = MockManagedCatalog {+ status,+ requests: Arc::new(AtomicUsize::new(0)),+ authorization: Arc::new(std::sync::Mutex::new(Vec::new())),+ };+ let app = Router::new()+ .route("/openai/v1/models", get(catalog_handler))+ .with_state(state.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind local managed-backend fixture");+ let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());+ tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("serve local managed-backend fixture");+ });+ (base, state)+}++struct BackendEnvSnapshot {+ backend_url: Option<std::ffi::OsString>,+ vite_backend_url: Option<std::ffi::OsString>,+}++impl BackendEnvSnapshot {+ fn set(base: &str) -> Self {+ let snapshot = Self {+ backend_url: std::env::var_os("BACKEND_URL"),+ vite_backend_url: std::env::var_os("VITE_BACKEND_URL"),+ };+ std::env::set_var("BACKEND_URL", base);+ std::env::remove_var("VITE_BACKEND_URL");+ snapshot+ }+}++impl Drop for BackendEnvSnapshot {+ fn drop(&mut self) {+ match self.backend_url.take() {+ Some(value) => std::env::set_var("BACKEND_URL", value),+ None => std::env::remove_var("BACKEND_URL"),+ }+ match self.vite_backend_url.take() {+ Some(value) => std::env::set_var("VITE_BACKEND_URL", value),+ None => std::env::remove_var("VITE_BACKEND_URL"),+ }+ }+}++fn temporary_config(base: &str) -> (tempfile::TempDir, Config) {+ let root = tempfile::tempdir().expect("temporary managed-catalog fixture");+ let mut config = Config {+ config_path: root.path().join("config.toml"),+ workspace_dir: root.path().join("workspace"),+ action_dir: root.path().join("workspace"),+ ..Config::default()+ };+ config.api_url = None;+ config.secrets.encrypt = false;+ config.resolved_endpoints.control_plane_url = Some(base.to_owned());+ (root, config)+}++fn store_session(+ config: &Config,+ token: &str,+ issuer: &str,+ expires_at: chrono::DateTime<chrono::Utc>,+) {+ let mut metadata = std::collections::HashMap::new();+ metadata.insert(SESSION_ISSUING_BACKEND_META.to_owned(), issuer.to_owned());+ metadata.insert(SESSION_EXPIRES_AT_META.to_owned(), expires_at.to_rfc3339());+ let profile_id = format!("{APP_SESSION_PROVIDER}:{DEFAULT_AUTH_PROFILE_NAME}");+ let now = chrono::Utc::now().to_rfc3339();+ let mut active_profiles = std::collections::HashMap::new();+ active_profiles.insert(APP_SESSION_PROVIDER, profile_id.clone());+ let mut profiles = std::collections::HashMap::new();+ profiles.insert(+ profile_id,+ serde_json::json!({+ "provider": APP_SESSION_PROVIDER,+ "profile_name": DEFAULT_AUTH_PROFILE_NAME,+ "kind": "token",+ "token": token,+ "metadata": metadata,+ "created_at": now,+ "updated_at": now,+ }),+ );+ let document = serde_json::json!({+ "schema_version": 1,+ "updated_at": now,+ "active_profiles": active_profiles,+ "profiles": profiles,+ });+ std::fs::write(+ auth_profiles_path(config),+ serde_json::to_vec(&document).unwrap(),+ )+ .expect("seed read-only session profile fixture");+}++fn auth_profiles_path(config: &Config) -> std::path::PathBuf {+ config+ .config_path+ .parent()+ .expect("fixture config parent")+ .join("auth-profiles.json")+}++async fn prepare_managed_catalog(+ config: Config,+) -> Result<PreparedInspectionCatalog, InspectionCatalogError> {+ let inspect = inspection_entry();+ inspect(+ config,+ CatalogRequest {+ provider_key: String::new(),+ client: reqwest::Client::new(),+ },+ )+ .await+}++async fn inspect_managed_catalog(+ config: Config,+) -> Result<openhuman_embed::__host::core::Outcome<serde_json::Value>, InspectionCatalogError> {+ prepare_managed_catalog(config).await?.fetch().await+}++#[test]+fn managed_inspection_catalog_lists_models_with_a_read_only_session() {+ with_backend_env_test_lock(async {+ let _registry = crate::registry_test_lock_async().await;+ let (base, server) = spawn_managed_backend(StatusCode::OK).await;+ let _env = BackendEnvSnapshot::set(&base);+ let (_temp, config) = temporary_config(&base);+ store_session(+ &config,+ "fixture-managed-session",+ &base,+ chrono::Utc::now() + chrono::Duration::hours(1),+ );+ let auth_file_before = std::fs::read(auth_profiles_path(&config)).expect("session fixture");++ let result = inspect_managed_catalog(config.clone())+ .await+ .expect("managed inspection should list the catalog");++ assert_eq!(result.value["models"][0]["id"], "managed-fixture-model");+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+ assert_eq!(+ *server+ .authorization+ .lock()+ .unwrap_or_else(|error| error.into_inner()),+ vec![Some("Bearer fixture-managed-session".to_owned())]+ );+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_before+ );+ });+}++#[test]+fn managed_inspection_catalog_classifies_a_401_without_mutating_credentials() {+ with_backend_env_test_lock(async {+ let _registry = crate::registry_test_lock_async().await;+ let (base, server) = spawn_managed_backend(StatusCode::UNAUTHORIZED).await;+ let _env = BackendEnvSnapshot::set(&base);+ let (_temp, config) = temporary_config(&base);+ store_session(+ &config,+ "fixture-managed-session",+ &base,+ chrono::Utc::now() + chrono::Duration::hours(1),+ );+ let auth_file_before = std::fs::read(auth_profiles_path(&config)).expect("session fixture");++ let error = inspect_managed_catalog(config.clone())+ .await+ .expect_err("a managed-catalog 401 is an auth/access result");++ assert!(matches!(error, InspectionCatalogError::AuthOrAccess));+ assert_eq!(server.requests.load(Ordering::SeqCst), 1);+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_before+ );+ });+}++#[test]+fn a_prepared_managed_fetch_uses_the_frozen_session_after_rotation() {+ with_backend_env_test_lock(async {+ let _registry = crate::registry_test_lock_async().await;+ let (base, server) = spawn_managed_backend(StatusCode::OK).await;+ let _env = BackendEnvSnapshot::set(&base);+ let (_temp, config) = temporary_config(&base);+ store_session(+ &config,+ "fixture-session-before-rotation",+ &base,+ chrono::Utc::now() + chrono::Duration::hours(1),+ );+ let auth_file_a_before =+ std::fs::read(auth_profiles_path(&config)).expect("session A fixture");++ let prepared_a = prepare_managed_catalog(config.clone())+ .await+ .expect("read-only prepare should capture session A");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_a_before,+ "preparing A must not rewrite auth state"+ );+ store_session(+ &config,+ "fixture-session-after-rotation",+ &base,+ chrono::Utc::now() + chrono::Duration::hours(1),+ );+ let auth_file_after_rotation =+ std::fs::read(auth_profiles_path(&config)).expect("rotated session fixture");++ prepared_a+ .fetch()+ .await+ .expect("the prepared request must use its captured session");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_after_rotation,+ "fetching frozen A must not change the newly stored B credential"+ );+ let prepared_b = prepare_managed_catalog(config.clone())+ .await+ .expect("a new prepare should see session B");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_after_rotation,+ "preparing B must not rewrite auth state"+ );+ prepared_b+ .fetch()+ .await+ .expect("the second prepared request should use session B");+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_after_rotation,+ "fetching frozen B must not rewrite auth state"+ );++ assert_eq!(server.requests.load(Ordering::SeqCst), 2);+ assert_eq!(+ *server+ .authorization+ .lock()+ .unwrap_or_else(|error| error.into_inner()),+ vec![+ Some("Bearer fixture-session-before-rotation".to_owned()),+ Some("Bearer fixture-session-after-rotation".to_owned())+ ]+ );+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_after_rotation+ );+ });+}++#[test]+fn a_session_from_another_backend_is_never_sent_to_the_managed_catalog() {+ with_backend_env_test_lock(async {+ let _registry = crate::registry_test_lock_async().await;+ let (base, server) = spawn_managed_backend(StatusCode::OK).await;+ let _env = BackendEnvSnapshot::set(&base);+ let (_temp, config) = temporary_config(&base);+ store_session(+ &config,+ "fixture-session-issued-elsewhere",+ "http://issuer-a.example",+ chrono::Utc::now() + chrono::Duration::hours(1),+ );+ let auth_file_before = std::fs::read(auth_profiles_path(&config)).expect("session fixture");++ let result = inspect_managed_catalog(config.clone()).await;++ assert!(+ result.is_err(),+ "a foreign session must not pass inspection"+ );+ assert_eq!(server.requests.load(Ordering::SeqCst), 0);+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_before+ );+ });+}++#[test]+fn an_expired_session_is_skipped_without_broadcast_or_store_mutation() {+ use openhuman_embed::__host::core::events::DomainEvent;++ with_backend_env_test_lock(async {+ let _registry = crate::registry_test_lock_async().await;+ openhuman_embed::__host::core::bus::init()+ .await+ .expect("event bus init");+ let mut events = openhuman_embed::__host::core::bus::BUS+ .get()+ .expect("event bus initialized")+ .receiver();+ while events.try_recv().is_ok() {}++ let (base, server) = spawn_managed_backend(StatusCode::OK).await;+ let _env = BackendEnvSnapshot::set(&base);+ let (_temp, config) = temporary_config(&base);+ store_session(+ &config,+ "fixture-expired-session",+ &base,+ chrono::Utc::now() - chrono::Duration::hours(1),+ );+ let auth_file_before = std::fs::read(auth_profiles_path(&config)).expect("session fixture");++ let result = inspect_managed_catalog(config.clone()).await;++ assert!(matches!(result, Err(InspectionCatalogError::Unavailable)));+ assert_eq!(server.requests.load(Ordering::SeqCst), 0);+ assert_eq!(+ std::fs::read(auth_profiles_path(&config)).unwrap(),+ auth_file_before+ );+ let published_expiry = std::iter::from_fn(|| events.try_recv().ok()).any(|event| {+ matches!(+ event,+ DomainEvent::SessionExpired { source, .. }+ if source == "credentials.local_expiry_precheck"+ )+ });+ assert!(+ !published_expiry,+ "inspection must not broadcast local expiry"+ );+ });+}diff --git a/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rsindex 89cac0c621..f8fab61a70 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs@@ -93,3 +93,7 @@ fn with_neither_credential_the_catalog_is_empty() {ListingAuth::Empty("session expired"));}++#[cfg(test)]+#[path = "managed_catalog_inspection_tests.rs"]+mod inspection_tests;diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rsindex 37566b30b0..3ff3f7e4cf 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs@@ -39,6 +39,31 @@ impl ManagedEmbeddingModel {)}+ /// Builds an inspection model with a frozen bearer from the selected+ /// profile. The normal credential store is never consulted at embed time.+ pub fn from_request_for_inspection(+ request: &EmbeddingRequest<'_>,+ ) -> tinyinference_embeddings::Result<Self> {+ let config = request.config.ok_or_else(|| {+ tinyinference_embeddings::Error::Validation(+ "selected managed embedding config is unavailable".to_owned(),+ )+ })?;+ let bearer =+ super::managed_session::managed_bearer_for_inspection(config).map_err(|_| {+ tinyinference_embeddings::Error::Validation(+ "selected managed embedding credential is unavailable".to_owned(),+ )+ })?;+ Ok(Self::new_with_bearer(+ config.api_url.clone(),+ bearer,+ request.model,+ request.dimensions,+ None,+ ))+ }+/// Builds the embedder against `api_url` (or the default backend) with/// credentials read from `state_dir`.pub fn new(@@ -98,6 +123,31 @@ impl ManagedEmbeddingModel {}}+ fn new_with_bearer(+ api_url: Option<String>,+ bearer_value: String,+ model: &str,+ dimensions: usize,+ chat: Option<ApprovalChatContext>,+ ) -> Self {+ let base_url = format!(+ "{}/openai/v1",+ effective_api_url(&api_url).trim_end_matches('/')+ );+ let bearer: BearerResolver = Arc::new(move || Ok(bearer_value.clone()));+ let model = model.to_owned();+ Self {+ inner: Arc::new(CloudEmbeddingModel::new(+ base_url,+ model.clone(),+ dimensions,+ bearer,+ )),+ model,+ chat,+ }+ }+/// This embedder with its egress disclosures routed to `chat` (the turn's/// thread and client); `None` leaves them unrouted. Shares the transport,/// so it is cheap to do per turn.diff --git a/crates/openhuman-tinyhumans/src/inference/managed_model.rs b/crates/openhuman-tinyhumans/src/inference/managed_model.rsindex a51443a0df..a553c17d73 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_model.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_model.rs@@ -57,6 +57,9 @@ pub struct OpenHumanBackendModel {/// the managed backend model: BYOK and third-party models must never see/// this backend-only extension.pub(super) thread_id: Option<String>,+ /// Frozen bearer for inspection-only calls. When set, invocation never+ /// consults mutable credential storage or publishes session state.+ pub(super) inspection_bearer: Option<String>,}impl OpenHumanBackendModel {@@ -86,6 +89,7 @@ impl OpenHumanBackendModel {..ModelProfile::default()},thread_id: None,+ inspection_bearer: None,}}@@ -100,6 +104,17 @@ impl OpenHumanBackendModel {self}+ /// Pin a credential from the read-only inspection snapshot for subsequent+ /// calls. This model must not be used as a runtime model.+ pub fn with_inspection_bearer(mut self, bearer: String) -> Self {+ self.inspection_bearer = Some(bearer);+ self+ }++ pub(super) fn is_inspection_safe(&self) -> bool {+ self.inspection_bearer.is_some()+ }+/// Force prompt-guided tool calling for toolsets that exceed the managed/// backend's native grammar ceiling.pub fn with_native_tool_calling(mut self, enabled: bool) -> Self {@@ -119,6 +134,9 @@ impl OpenHumanBackendModel {}pub(super) fn resolve_bearer(&self) -> anyhow::Result<String> {+ if let Some(bearer) = self.inspection_bearer.as_ref() {+ return Ok(bearer.clone());+ }use openhuman_embed::__host::security::credentials::session_support::classify_session_token;// A stored API key (library runtime) is the bearer outright: thediff --git a/crates/openhuman-tinyhumans/src/inference/managed_session.rs b/crates/openhuman-tinyhumans/src/inference/managed_session.rsindex b563440c72..3ef8969937 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_session.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_session.rs@@ -5,6 +5,45 @@use tinyinference_llm::model::ProviderError;use tinyinference_llm::Error as TiError;+/// Resolve the managed backend bearer from a read-only selected-profile+/// snapshot. Inspection never refreshes credentials or publishes expiry.+pub(super) fn managed_bearer_for_inspection(+ config: &openhuman_embed::__host::config::Config,+) -> anyhow::Result<String> {+ use openhuman_embed::__host::security::credentials::session_support::{+ check_session_backend, classify_session_token, is_local_session_token,+ load_app_session_profile_read_only, SessionTokenCheck,+ };++ if let Some(key) =+ openhuman_embed::__host::security::credentials::api_key::get_api_key_read_only(config)+ .map_err(|_| anyhow::anyhow!("managed API key profile is unavailable or invalid"))?+ {+ let endpoint = format!(+ "{}/openai/v1",+ crate::backend::url::effective_api_url(&config.api_url).trim_end_matches('/')+ );+ anyhow::ensure!(+ crate::client::endpoint::is_managed_endpoint_for_api_key(&endpoint),+ "managed API key endpoint is not an approved managed endpoint"+ );+ return Ok(key);+ }++ let profile = load_app_session_profile_read_only(config)+ .map_err(|_| anyhow::anyhow!("managed session profile is unavailable or invalid"))?;+ check_session_backend(config, profile.as_ref())+ .map_err(|_| anyhow::anyhow!("managed session belongs to a different backend"))?;+ match classify_session_token(profile.as_ref(), chrono::Utc::now()) {+ SessionTokenCheck::Live(token) if !is_local_session_token(&token) => Ok(token),+ SessionTokenCheck::Expired => anyhow::bail!("managed session is expired"),+ SessionTokenCheck::Live(_) => {+ anyhow::bail!("offline local session cannot call managed inference")+ }+ SessionTokenCheck::Absent => anyhow::bail!("managed session credential is unavailable"),+ }+}+/// The bearer a classified app-session token yields for managed inference.////// Separate from `OpenHumanBackendModel::resolve_bearer` so the decision isdiff --git a/crates/openhuman-tinyhumans/src/inference/managed_session_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_session_tests.rsindex 9af136e855..e4dcd46bed 100644--- a/crates/openhuman-tinyhumans/src/inference/managed_session_tests.rs+++ b/crates/openhuman-tinyhumans/src/inference/managed_session_tests.rs@@ -49,12 +49,16 @@ fn a_signed_in_session_still_authenticates_managed_inference() {use tinyinference_llm::model::{ModelStreamItem, ProviderError};+static SESSION_EXPIRY_EVENT_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+/// #6724 (review): a 401 reported *inside* a stream must start re-auth just/// like a failed `stream()` call does.#[tokio::test]async fn an_in_band_401_publishes_session_expired() {use openhuman_embed::__host::core::events::DomainEvent;+ let _lock = SESSION_EXPIRY_EVENT_TEST_LOCK.lock().await;+openhuman_embed::__host::core::bus::init().await.expect("bus init");@@ -91,3 +95,215 @@ async fn an_in_band_401_publishes_session_expired() {"an in-band 401 must publish SessionExpired");}++#[tokio::test]+async fn inspection_invoke_and_in_band_401_do_not_mutate_credentials_or_publish_expiry() {+ const CHILD_MARKER: &str = "OPENHUMAN_INSPECTION_401_ISOLATED_CHILD";+ if std::env::var_os(CHILD_MARKER).is_none() {+ let exact = "inference::managed_session::tests::inspection_invoke_and_in_band_401_do_not_mutate_credentials_or_publish_expiry";+ let output = std::process::Command::new(+ std::env::current_exe().expect("resolve current test executable"),+ )+ .args(["--exact", exact, "--nocapture", "--test-threads=1"])+ .env(CHILD_MARKER, "1")+ .stdin(std::process::Stdio::null())+ .output()+ .expect("run inspection 401 test in an isolated process");+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ output.status.success()+ && stdout.contains("test result: ok. 1 passed; 0 failed; 0 ignored"),+ "isolated inspection 401 test must run exactly once and pass (status {})",+ output.status+ );+ return;+ }++ use axum::response::IntoResponse;+ use openhuman_embed::__host::config::Config;+ use openhuman_embed::__host::core::events::DomainEvent;+ use openhuman_embed::__host::egress::EgressLedger;+ use openhuman_embed::__host::inference_registry::ChatModelRequest;+ use tinyinference_llm::message::Message;+ use tinyinference_llm::model::ModelRequest;++ let _lock = SESSION_EXPIRY_EVENT_TEST_LOCK.lock().await;+ let temp = tempfile::tempdir().expect("temporary selected credential workspace");+ let invoke_addr = spawn_inspection_401_server(false).await;+ let stream_addr = spawn_inspection_401_server(true).await;+ let config = Config {+ workspace_dir: temp.path().to_owned(),+ action_dir: temp.path().to_owned(),+ config_path: temp.path().join("config.toml"),+ api_url: Some(format!("http://{invoke_addr}")),+ secrets: {+ let mut secrets = Config::default().secrets;+ secrets.encrypt = false;+ secrets+ },+ ..Config::default()+ };+ let auth_profile_path = temp.path().join("auth-profiles.json");+ // Keep the fixture in the selected profile's portable JSON store. The+ // ordinary AuthService may choose a machine-global secret backend, while+ // the inspection adapter intentionally reads only this workspace.+ std::fs::write(+ &auth_profile_path,+ r#"{"schema_version":1,"active_profiles":{"app-session":"app-session:default"},"profiles":{"app-session:default":{"provider":"app-session","profile_name":"default","kind":"token","token":"inspection-session-token"}}}"#,+ )+ .expect("seed selected app-session profile in the temporary workspace");+ let profile_before = std::fs::read(&auth_profile_path).expect("read seeded auth profile");+ let store_before = credential_store_snapshot(temp.path());++ openhuman_embed::__host::core::bus::init()+ .await+ .expect("event bus init");+ let mut events = openhuman_embed::__host::core::bus::BUS+ .get()+ .expect("event bus initialized")+ .receiver();+ drain_session_events(&mut events);++ let egress = EgressLedger::none();+ let build_inspection_model = |api_url: &str| {+ let mut model_config = config.clone();+ model_config.api_url = Some(format!("http://{api_url}"));+ let request = ChatModelRequest {+ role: "chat",+ config: &model_config,+ model_override: Some("reasoning-v1"),+ default_model: None,+ native_tool_calling: true,+ thread_id: None,+ egress: &egress,+ };+ let model = super::super::build_chat_model_for_inspection(&request)+ .expect("real TinyHumans inspection adapter should read the selected profile");+ (model_config, model.model)+ };++ let (_invoke_config, invoke_model) = build_inspection_model(&invoke_addr);+ let invoke_error = invoke_model+ .invoke(&(), ModelRequest::new(vec![Message::user("probe")]))+ .await+ .expect_err("mock 401 should surface as a provider failure");+ assert!(matches!(+ invoke_error,+ tinyinference_llm::Error::Provider(_)+ ));+ assert_eq!(+ std::fs::read(&auth_profile_path).expect("read auth profile after invoke"),+ profile_before,+ "inspection invoke must not clear, rewrite, or quarantine the selected profile"+ );+ assert_eq!(credential_store_snapshot(temp.path()), store_before);+ assert_no_session_expired(&mut events);++ let (_stream_config, stream_model) = build_inspection_model(&stream_addr);+ let stream = stream_model+ .stream(&(), ModelRequest::new(vec![Message::user("probe")]))+ .await+ .expect("HTTP 200 stream can report an in-band provider error");+ use futures::StreamExt;+ let items = stream.collect::<Vec<_>>().await;+ assert!(+ items.iter().any(|item| matches!(+ item,+ ModelStreamItem::ProviderFailed(ProviderError {+ status: Some(401),+ ..+ })+ )),+ "mock SSE should produce an in-band 401: {items:#?}"+ );+ assert_eq!(+ std::fs::read(&auth_profile_path).expect("read auth profile after stream"),+ profile_before,+ "inspection stream must not clear, rewrite, or quarantine the selected profile"+ );+ assert_eq!(credential_store_snapshot(temp.path()), store_before);+ assert!(!temp.path().join("auth-profiles.lock").exists());+ assert_no_session_expired(&mut events);++ async fn spawn_inspection_401_server(in_band: bool) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind loopback mock");+ let addr = listener.local_addr().expect("mock address");+ let app = axum::Router::new().route(+ "/openai/v1/chat/completions",+ axum::routing::post(move || async move {+ if in_band {+ (+ axum::http::StatusCode::OK,+ [(axum::http::header::CONTENT_TYPE, "text/event-stream")],+ "data: {\"error\":{\"code\":401,\"message\":\"Invalid token\"}}\n\ndata: [DONE]\n\n",+ )+ .into_response()+ } else {+ (+ axum::http::StatusCode::UNAUTHORIZED,+ axum::Json(serde_json::json!({+ "error": { "message": "Invalid token", "type": "auth_error" }+ })),+ )+ .into_response()+ }+ }),+ );+ tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("serve loopback mock");+ });+ addr.to_string()+ }++ fn drain_session_events(receiver: &mut tinybus::events::EventReceiver<DomainEvent>) {+ loop {+ match receiver.try_recv() {+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,+ Err(_) => return,+ }+ }+ }++ fn assert_no_session_expired(receiver: &mut tinybus::events::EventReceiver<DomainEvent>) {+ loop {+ match receiver.try_recv() {+ Ok(DomainEvent::SessionExpired { source, reason }) => {+ panic!("inspection call published SessionExpired ({source}): {reason}")+ }+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,+ Err(_) => return,+ }+ }+ }++ fn credential_store_snapshot(root: &std::path::Path) -> Vec<(std::path::PathBuf, Vec<u8>)> {+ fn visit(+ root: &std::path::Path,+ dir: &std::path::Path,+ out: &mut Vec<(std::path::PathBuf, Vec<u8>)>,+ ) {+ for entry in std::fs::read_dir(dir).expect("read credential fixture directory") {+ let path = entry.expect("read credential fixture entry").path();+ if path.is_dir() {+ visit(root, &path, out);+ } else {+ out.push((+ path.strip_prefix(root)+ .expect("fixture file under root")+ .to_path_buf(),+ std::fs::read(&path).expect("read credential fixture bytes"),+ ));+ }+ }+ }++ let mut files = Vec::new();+ visit(root, root, &mut files);+ files.sort_by(|left, right| left.0.cmp(&right.0));+ files+ }+}diff --git a/crates/openhuman-tinyhumans/src/inference/mod.rs b/crates/openhuman-tinyhumans/src/inference/mod.rsindex afdef923c0..a0098765dc 100644--- a/crates/openhuman-tinyhumans/src/inference/mod.rs+++ b/crates/openhuman-tinyhumans/src/inference/mod.rs@@ -25,8 +25,9 @@ use std::sync::Arc;use openhuman_embed::__host::config::{Config, MODEL_MANAGED_DEFAULT};use openhuman_embed::__host::inference_registry::{- register_catalog, register_chat_model, register_embedding, BoxFuture, ChatModelEntry,- ChatModelFactory, ChatModelRequest, ReadinessProbe, PROVIDER_OPENHUMAN,+ register_catalog, register_chat_model, register_embedding, register_inspection_chat_model,+ register_inspection_embedding, BoxFuture, ChatModelEntry, ChatModelFactory, ChatModelRequest,+ InspectionChatModelBuild, ReadinessProbe, PROVIDER_OPENHUMAN,};use tinyinference_llm::model::ChatModel;@@ -77,6 +78,45 @@ pub(crate) fn build_chat_model(Ok((Arc::new(model), pinned))}+/// Builds a managed model around a frozen read-only credential snapshot for+/// inspection calls; invoke and stream never consult mutable auth state.+fn build_chat_model_for_inspection(+ request: &ChatModelRequest<'_>,+) -> anyhow::Result<InspectionChatModelBuild> {+ let pinned = request+ .model_override+ .map(str::trim)+ .filter(|model| !model.is_empty())+ .unwrap_or(MODEL_MANAGED_DEFAULT)+ .to_string();+ let default_model = request+ .default_model+ .map(str::trim)+ .filter(|model| !model.is_empty())+ .map(str::to_string)+ .unwrap_or_else(|| pinned.clone());+ let options = managed_options(request.config);+ let bearer = managed_session::managed_bearer_for_inspection(request.config)?;+ let endpoint = format!(+ "{}/openai/v1",+ crate::backend::url::effective_api_url(&request.config.api_url).trim_end_matches('/')+ );+ let model = OpenHumanBackendModel::new(+ request.config.api_url.as_deref(),+ &options,+ default_model.clone(),+ )+ .with_native_tool_calling(request.native_tool_calling)+ .with_thread_id(request.thread_id)+ .with_inspection_bearer(bearer.clone());+ Ok(InspectionChatModelBuild {+ model: Arc::new(model),+ model_id: default_model,+ endpoint,+ credential: bearer,+ })+}+fn readiness_probe() -> ReadinessProbe {Arc::new(|role: String, model: String, config: Config| -> BoxFuture<Result<(), String>> {@@ -101,10 +141,22 @@ pub(crate) fn register(_options: &InstallOptions) {probe: Some(readiness_probe()),},);+ register_inspection_chat_model(+ PROVIDER_OPENHUMAN,+ Arc::new(build_chat_model_for_inspection),+ );register_embedding(PROVIDER_OPENHUMAN, |request| {Ok(Box::new(ManagedEmbeddingModel::from_request(request)))});+ register_inspection_embedding(PROVIDER_OPENHUMAN, |request| {+ ManagedEmbeddingModel::from_request_for_inspection(request)+ .map(|model| Box::new(model) as Box<dyn tinyinference_embeddings::EmbeddingModel>)+ });register_catalog(PROVIDER_OPENHUMAN, managed_catalog::entry());+ openhuman_embed::__host::inference_registry::register_inspection_catalog(+ PROVIDER_OPENHUMAN,+ managed_catalog::inspection_entry(),+ );log::debug!("[tinyhumans] inference: registered the managed chat model, embeddings and catalog");diff --git a/crates/openhuman-tinyhumans/src/install.rs b/crates/openhuman-tinyhumans/src/install.rsindex 875ca9051c..a6529e6c06 100644--- a/crates/openhuman-tinyhumans/src/install.rs+++ b/crates/openhuman-tinyhumans/src/install.rs@@ -118,7 +118,10 @@ impl std::fmt::Debug for Wiring {////// A new identity drops the cached transport, because a transport captures/// its attribution headers once; [`connect_transport`] then rebuilds it.-fn prepare(options: &InstallOptions) -> (Option<ControllerExtension>, Option<Arc<dyn ToolRanker>>) {+fn prepare(+ options: &InstallOptions,+ doctor_registration: crate::register::DoctorRegistration<'_>,+) -> (Option<ControllerExtension>, Option<Arc<dyn ToolRanker>>) {if let Some(identity) = options.product_identity.clone() {log::debug!("[tinyhumans] install: product identity {}",@@ -131,7 +134,7 @@ fn prepare(options: &InstallOptions) -> (Option<ControllerExtension>, Option<Arc}// Plug every area into the core's generic registries (idempotent).- crate::register::register_all(options);+ crate::register::register_all(options, doctor_registration);let controllers = options.hosted_controllers.then(crate::hosted::extension);@@ -164,8 +167,14 @@ fn connect_transport() -> Result<Arc<SdkBackendTransport>, InstallError> {/// Resolve everything a TinyHumans connection wires in and connect the/// transport. The builder's path; [`install`] runs the same two steps with/// the registry and ranker applied in between, in its historical order.-pub(crate) fn wiring(options: &InstallOptions) -> Result<Wiring, InstallError> {- let (controllers, ranker) = prepare(options);+pub(crate) fn wiring(+ options: &InstallOptions,+ extensions: &openhuman_embed::__host::core::slots::Extensions,+) -> Result<Wiring, InstallError> {+ let (controllers, ranker) = prepare(+ options,+ crate::register::DoctorRegistration::Context(extensions),+ );// Connecting builds the process transport; only tests read it back.#[cfg_attr(not(test), allow(unused_variables))]let transport = connect_transport()?;@@ -189,7 +198,7 @@ pub(crate) fn wiring(options: &InstallOptions) -> Result<Wiring, InstallError> {/// The core holds no transport of its own; the returned handle is the one/// every hosted caller in this crate sends through.pub fn install(options: InstallOptions) -> Result<Arc<SdkBackendTransport>, InstallError> {- let (controllers, ranker) = prepare(&options);+ let (controllers, ranker) = prepare(&options, crate::register::DoctorRegistration::Process);if let Some(extension) = controllers {// Idempotent in the core: an identical re-registration is a no-op.diff --git a/crates/openhuman-tinyhumans/src/install_tests.rs b/crates/openhuman-tinyhumans/src/install_tests.rsindex 96bef7758d..452e81b472 100644--- a/crates/openhuman-tinyhumans/src/install_tests.rs+++ b/crates/openhuman-tinyhumans/src/install_tests.rs@@ -4,13 +4,18 @@use super::*;#[cfg(feature = "jev")]use openhuman_embed::__host::agent::tinyagents::discovery::installed_tool_ranker;+use openhuman_embed::__host::core::slots::Extensions;use openhuman_embed::seams::DomainGroup;+fn test_wiring(options: &InstallOptions) -> Result<Wiring, InstallError> {+ wiring(options, &Extensions::new())+}+#[test]fn default_wiring_carries_hosted_controllers_and_the_jev_ranker() {let _registry = crate::registry_test_lock();- let wired = wiring(&InstallOptions::default()).expect("wiring");+ let wired = test_wiring(&InstallOptions::default()).expect("wiring");assert_eq!(wired.controllers.as_ref().map(|ext| ext.group),Some(DomainGroup::Hosted)@@ -28,7 +33,7 @@ fn default_wiring_carries_hosted_controllers_and_the_jev_ranker() {fn options_turn_controllers_and_ranker_off() {let _registry = crate::registry_test_lock();- let wired = wiring(+ let wired = test_wiring(&InstallOptions::default().hosted_controllers(false).tool_ranker(false),@@ -44,8 +49,8 @@ fn wiring_reuses_the_process_transport() {// A product-identity change drops the cached transport; hold its lock.let _guard = crate::backend::product::product_identity_test_lock();- let first = wiring(&InstallOptions::default()).expect("first");- let second = wiring(&InstallOptions::default()).expect("second");+ let first = test_wiring(&InstallOptions::default()).expect("first");+ let second = test_wiring(&InstallOptions::default()).expect("second");assert!(Arc::ptr_eq(&first.transport, &second.transport));}@@ -64,6 +69,6 @@ fn install_registers_hosted_controllers_and_installs_the_ranker() {#[cfg(feature = "jev")]assert!(installed_tool_ranker().is_some());// The same transport the builder path binds.- let wired = wiring(&InstallOptions::default()).expect("wiring");+ let wired = test_wiring(&InstallOptions::default()).expect("wiring");assert!(Arc::ptr_eq(&transport, &wired.transport));}diff --git a/crates/openhuman-tinyhumans/src/lib.rs b/crates/openhuman-tinyhumans/src/lib.rsindex 883b7b109b..ca22f7c9e6 100644--- a/crates/openhuman-tinyhumans/src/lib.rs+++ b/crates/openhuman-tinyhumans/src/lib.rs@@ -52,10 +52,10 @@ pub mod embed {// Runtime, builder and the knobs the hosts configure it with.pub use openhuman_embed::{Access, Agent, AgentDefaults, AgentDefinitionSpec, AgentSpec, ApiKey, ConfigSource,- ConfigurationInfo, CoreError, CoreRuntime, DefaultsInfo, DefinitionBase, DomainSet,- Harness, HarnessBuilder, HostKind, LearningSettings, ModelDefaults, Provider, Runtime,- RuntimeBuilder, RuntimeDefaults, RuntimeError, RuntimeInfo, RuntimeModule, ServiceSet,- SkillsPolicy, StorageInfo, TokenSource, WeightClass, Workspace,+ ConfigurationInfo, CoreBootMode, CoreError, CoreRuntime, DefaultsInfo, DefinitionBase,+ DomainSet, Harness, HarnessBuilder, HostKind, LearningSettings, ModelDefaults, Provider,+ Runtime, RuntimeBuilder, RuntimeConfig, RuntimeDefaults, RuntimeError, RuntimeInfo,+ RuntimeModule, ServiceSet, SkillsPolicy, StorageInfo, TokenSource, WeightClass, Workspace,};// Process-level facts a host reads.pub use openhuman_embed::{@@ -64,7 +64,7 @@ pub mod embed {// The curated facades (each is an explicit list inside embed).pub use openhuman_embed::modules;pub use openhuman_embed::{- artifacts, chat_surface, config, identity, memory, process, seams, secret_storage,+ artifacts, chat_surface, cli, config, identity, memory, process, seams, secret_storage,session_store,};}@@ -77,6 +77,7 @@ pub use openhuman_embed::__host;pub mod backend;pub(crate) mod channels;pub mod client;+pub(crate) mod doctor;pub mod hosted;pub(crate) mod inference;mod install;diff --git a/crates/openhuman-tinyhumans/src/memory/engine.rs b/crates/openhuman-tinyhumans/src/memory/engine.rsindex 9bbe7f1cce..93a14890a8 100644--- a/crates/openhuman-tinyhumans/src/memory/engine.rs+++ b/crates/openhuman-tinyhumans/src/memory/engine.rs@@ -18,13 +18,78 @@ use async_trait::async_trait;use openhuman_embed::__host::config::Config;use openhuman_embed::__host::memory_engines::{build_cached, rooted, BearerSource, Binding, EngineCredential, EngineRequest, EngineSettings,- TINYHUMANS_ENGINE,+ ReadOnlyEngineError, TINYHUMANS_ENGINE,};use openhuman_embed::__host::security::credentials::session_support::resolve_backend_credential;use crate::backend::headers::attribution_headers;use crate::backend::url::effective_backend_api_url;+/// Constructs an uncached TinyHumans engine for bounded, read-only inspection+/// of an explicitly selected config. #502 may reuse this for its live probe;+/// ordinary [`bind`] remains on its existing mutable credential/cache path.+pub(crate) fn build_read_only_engine(+ config: &Config,+) -> Result<Arc<dyn tinymemory_api::MemoryEngine>, ReadOnlyEngineError> {+ let (credential, is_api_key) =+ match openhuman_embed::__host::security::credentials::api_key::get_api_key_read_only(config)+ {+ Ok(Some(key)) => (key, true),+ Ok(None) => (+ read_only_session_token(config)?+ .ok_or(ReadOnlyEngineError::CredentialsUnavailable)?,+ false,+ ),+ Err(_) => return Err(ReadOnlyEngineError::CredentialsUnavailable),+ };+ let endpoint = endpoint_for(config);+ crate::client::endpoint::validate_credential_endpoint(&endpoint, is_api_key)+ .map_err(|_| ReadOnlyEngineError::EndpointUnavailable)?;+ let headers = crate::backend::headers::attribution_headers()+ .map_err(|_| ReadOnlyEngineError::InvalidConfiguration)?+ .iter()+ .filter_map(|(name, value)| {+ value+ .to_str()+ .ok()+ .map(|value| (name.as_str().to_owned(), value.to_owned()))+ })+ .collect();+ let settings = EngineSettings {+ endpoint: Some(endpoint),+ headers,+ tenant_root: true,+ ..EngineSettings::default()+ };+ tinymemory_integrations::build_engine(+ TINYHUMANS_ENGINE,+ &settings,+ EngineCredential::Static(credential),+ )+ .map_err(|_| ReadOnlyEngineError::InvalidConfiguration)+}++fn read_only_session_token(config: &Config) -> Result<Option<String>, ReadOnlyEngineError> {+ use openhuman_embed::__host::security::credentials::session_support::{+ check_session_backend, classify_session_token, is_local_session_token,+ load_app_session_profile_read_only, SessionTokenCheck,+ };++ let profile = load_app_session_profile_read_only(config)+ .map_err(|_| ReadOnlyEngineError::CredentialsUnavailable)?;+ let Some(profile) = profile else {+ return Ok(None);+ };+ check_session_backend(config, Some(&profile))+ .map_err(|_| ReadOnlyEngineError::CredentialsUnavailable)?;+ match classify_session_token(Some(&profile), chrono::Utc::now()) {+ SessionTokenCheck::Live(token) if !is_local_session_token(&token) => Ok(Some(token)),+ SessionTokenCheck::Live(_) | SessionTokenCheck::Absent | SessionTokenCheck::Expired => {+ Ok(None)+ }+ }+}+fn off(endpoint: Option<String>, reason: &str) -> Binding {Binding::Off {engine: Some(TINYHUMANS_ENGINE.to_string()),diff --git a/crates/openhuman-tinyhumans/src/memory/mod.rs b/crates/openhuman-tinyhumans/src/memory/mod.rsindex a76ba3f3dc..b1c1b3f066 100644--- a/crates/openhuman-tinyhumans/src/memory/mod.rs+++ b/crates/openhuman-tinyhumans/src/memory/mod.rs@@ -17,7 +17,8 @@ pub(crate) mod billing;pub(crate) mod engine;use openhuman_embed::__host::memory_engines::{- register_memory_engine, EngineEntry, TINYHUMANS_ENGINE,+ register_memory_engine, register_memory_health_probe, register_read_only_engine_factory,+ EngineEntry, EngineHealth, ReadOnlyEngineFactory, TINYHUMANS_ENGINE,};use std::sync::Arc;@@ -34,9 +35,27 @@ pub(crate) fn register(_options: &InstallOptions) {})),},);+ let read_only_factory: ReadOnlyEngineFactory =+ Arc::new(|config| Box::pin(async move { engine::build_read_only_engine(&config) }));+ register_read_only_engine_factory(TINYHUMANS_ENGINE, read_only_factory);+ register_memory_health_probe(TINYHUMANS_ENGINE, Arc::new(read_only_health_probe));log::debug!("[tinyhumans] memory: hosted engine registered as '{TINYHUMANS_ENGINE}'");}+/// Builds a throwaway engine for a read-only health request. It reads the+/// selected config's credential profile directly and never enters the normal+/// engine cache or publishes session-expiry state.+fn read_only_health_probe(+ config: openhuman_embed::__host::config::Config,+) -> openhuman_embed::__host::memory_engines::EngineFuture<EngineHealth> {+ Box::pin(async move {+ match engine::build_read_only_engine(&config) {+ Ok(engine) => engine.health().await,+ Err(reason) => EngineHealth::Down(reason.safe_message().to_owned()),+ }+ })+}+#[cfg(test)]#[path = "mod_tests.rs"]mod tests;diff --git a/crates/openhuman-tinyhumans/src/memory/mod_tests.rs b/crates/openhuman-tinyhumans/src/memory/mod_tests.rsindex 4544b2636a..26eee280ee 100644--- a/crates/openhuman-tinyhumans/src/memory/mod_tests.rs+++ b/crates/openhuman-tinyhumans/src/memory/mod_tests.rs@@ -176,6 +176,153 @@ async fn host_bearer_rejects_a_local_session_token() {));}+async fn health_server(status: u16) -> wiremock::MockServer {+ use wiremock::matchers::{method, path};+ let server = wiremock::MockServer::start().await;+ wiremock::Mock::given(method("GET"))+ .and(path("/memory/scopes"))+ .respond_with(+ wiremock::ResponseTemplate::new(status).set_body_json(json!({+ "success": true,+ "data": { "items": [] }+ })),+ )+ .mount(&server)+ .await;+ server+}++fn store_session_with_metadata(+ config: &openhuman_embed::__host::config::Config,+ token: &str,+ metadata: std::collections::HashMap<String, String>,+) {+ AuthService::from_config(config)+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ token,+ metadata,+ true,+ )+ .expect("store selected session fixture");+}++fn persistent_tree(+ path: &std::path::Path,+) -> std::collections::BTreeMap<std::path::PathBuf, Vec<u8>> {+ fn visit(+ root: &std::path::Path,+ at: &std::path::Path,+ out: &mut std::collections::BTreeMap<std::path::PathBuf, Vec<u8>>,+ ) {+ for entry in std::fs::read_dir(at).expect("read fixture tree") {+ let entry = entry.expect("read fixture entry");+ let path = entry.path();+ if path.is_dir() {+ visit(root, &path, out);+ } else {+ out.insert(+ path.strip_prefix(root)+ .expect("relative fixture path")+ .to_path_buf(),+ std::fs::read(path).expect("read fixture file"),+ );+ }+ }+ }+ let mut out = std::collections::BTreeMap::new();+ if path.exists() {+ visit(path, path, &mut out);+ }+ out+}++#[tokio::test]+async fn readonly_health_uses_the_selected_config_credential_and_endpoint() {+ let _registry = crate::registry_test_lock();+ let server_a = health_server(500).await;+ let server_b = health_server(200).await;+ let tmp_a = tempfile::tempdir().unwrap();+ let tmp_b = tempfile::tempdir().unwrap();+ let config_a = config_with_endpoint(&tmp_a, &server_a.uri());+ let config_b = config_with_endpoint(&tmp_b, &server_b.uri());+ store_key(&config_a, "selected-a-token");+ store_key(&config_b, "selected-b-token");+ let before_a = persistent_tree(config_a.config_path.parent().unwrap());+ let before_b = persistent_tree(config_b.config_path.parent().unwrap());++ let health = read_only_health_probe(config_b.clone()).await;++ assert_eq!(health, EngineHealth::Ok);+ assert!(server_a.received_requests().await.unwrap().is_empty());+ let requests = server_b.received_requests().await.unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(+ requests[0]+ .headers+ .get("authorization")+ .unwrap()+ .to_str()+ .unwrap(),+ "Bearer selected-b-token"+ );+ assert_eq!(+ persistent_tree(config_a.config_path.parent().unwrap()),+ before_a+ );+ assert_eq!(+ persistent_tree(config_b.config_path.parent().unwrap()),+ before_b+ );+}++#[tokio::test]+async fn readonly_health_reports_down_without_exposing_backend_error_text() {+ let server = health_server(500).await;+ let tmp = tempfile::tempdir().unwrap();+ let config = config_with_endpoint(&tmp, &server.uri());+ store_key(&config, "health-down-token");++ let health = read_only_health_probe(config).await;++ assert!(matches!(health, EngineHealth::Down(_)));+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}++#[tokio::test]+async fn expired_or_wrong_issuer_session_skips_network_and_preserves_credentials() {+ let server = health_server(200).await;+ for (token, metadata) in [+ (+ "expired-session",+ std::collections::HashMap::from([(+ openhuman_embed::__host::security::credentials::session_support::SESSION_EXPIRES_AT_META.to_owned(),+ (chrono::Utc::now() - chrono::Duration::minutes(2)).to_rfc3339(),+ )]),+ ),+ (+ "wrong-issuer-session",+ std::collections::HashMap::from([(+ "session_issuing_backend".to_owned(),+ "https://other-backend.example.test".to_owned(),+ )]),+ ),+ ] {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = config_with_endpoint(&tmp, &server.uri());+ config.resolved_endpoints.control_plane_url = Some("https://selected-backend.example.test".into());+ store_session_with_metadata(&config, token, metadata);+ let before = persistent_tree(config.config_path.parent().unwrap());++ let health = read_only_health_probe(config.clone()).await;++ assert!(matches!(health, EngineHealth::Down(_)));+ assert_eq!(persistent_tree(config.config_path.parent().unwrap()), before);+ }+ assert!(server.received_requests().await.unwrap().is_empty());+}+#[test]fn registering_twice_leaves_one_engine() {let _registry = crate::registry_test_lock();diff --git a/crates/openhuman-tinyhumans/src/register.rs b/crates/openhuman-tinyhumans/src/register.rsindex 74d08650f9..2b3274b108 100644--- a/crates/openhuman-tinyhumans/src/register.rs+++ b/crates/openhuman-tinyhumans/src/register.rs@@ -9,12 +9,21 @@//! second `install` is harmless.use crate::install::InstallOptions;+use openhuman_embed::__host::core::slots::Extensions;++/// Where registrations contributed during setup should be visible.+pub(crate) enum DoctorRegistration<'a> {+ /// Compatibility hosts install the TinyHumans layer for the whole process.+ Process,+ /// RuntimeBuilder hosts bind checks to the CoreContext they create.+ Context(&'a Extensions),+}#[cfg(feature = "voice")]use crate::voice;use crate::{channels, client, inference, integrations, memory};/// Registers every area's hooks with the core.-pub(crate) fn register_all(options: &InstallOptions) {+pub(crate) fn register_all(options: &InstallOptions, doctor_registration: DoctorRegistration<'_>) {log::debug!("[tinyhumans] register_all: registering core hooks");client::register(options);integrations::register(options);@@ -23,6 +32,7 @@ pub(crate) fn register_all(options: &InstallOptions) {inference::register(options);channels::register(options);memory::register(options);+ crate::doctor::register(doctor_registration);}#[cfg(test)]diff --git a/crates/openhuman-tinyhumans/src/register_tests.rs b/crates/openhuman-tinyhumans/src/register_tests.rsindex e6196e6524..b4c59b4211 100644--- a/crates/openhuman-tinyhumans/src/register_tests.rs+++ b/crates/openhuman-tinyhumans/src/register_tests.rs@@ -5,6 +5,6 @@ fn register_all_is_idempotent() {let _registry = crate::registry_test_lock();let options = InstallOptions::default();- register_all(&options);- register_all(&options);+ register_all(&options, DoctorRegistration::Process);+ register_all(&options, DoctorRegistration::Process);}diff --git a/crates/openhuman-tinyhumans/src/runtime.rs b/crates/openhuman-tinyhumans/src/runtime.rsindex 8932135f66..68af0be7df 100644--- a/crates/openhuman-tinyhumans/src/runtime.rs+++ b/crates/openhuman-tinyhumans/src/runtime.rs@@ -30,8 +30,8 @@ use openhuman_embed::seams::{use tinytools::ToolRanker;use openhuman_embed::{- Access, ApiKey, ConfigSource, DomainSet, HostKind, Provider, Runtime, RuntimeConfig,- ServiceSet, Session, SessionStoreProvider, TokenSource, ToolGroups, Workspace,+ Access, ApiKey, ConfigSource, CoreBootMode, DomainSet, HostKind, Provider, Runtime,+ RuntimeConfig, ServiceSet, Session, SessionStoreProvider, TokenSource, ToolGroups, Workspace,};use crate::install::{wiring, InstallError, InstallOptions};@@ -138,6 +138,10 @@ impl RuntimeBuilder {/// See [`openhuman_embed::RuntimeBuilder::config_source`].config_source(source: ConfigSource));+ forward!(+ /// See [`openhuman_embed::RuntimeBuilder::boot_mode`].+ boot_mode(mode: CoreBootMode)+ );forward!(/// See [`openhuman_embed::RuntimeBuilder::provider`].provider(provider: Provider)@@ -263,9 +267,14 @@ impl RuntimeBuilder {/// controller extension and the Jev ranker as the tool ranker. For entry/// points that take an embed builder rather than this one.pub fn connect(self) -> Result<openhuman_embed::RuntimeBuilder, InstallError> {- let wiring = wiring(&self.install)?;+ let Self { inner, install } = self;+ let mut wiring_result = None;+ let inner = inner.configure_core_extensions(|extensions| {+ wiring_result = Some(wiring(&install, extensions));+ });+ let wiring = wiring_result.expect("core extensions are configured synchronously")?;log::debug!("[tinyhumans] connecting embed builder: {wiring:?}");- let mut inner = self.inner;+ let mut inner = inner;if let Some(extension) = wiring.controllers {inner = inner.controller_extension(extension);}diff --git a/crates/openhuman-tinyhumans/src/runtime_tests.rs b/crates/openhuman-tinyhumans/src/runtime_tests.rsindex 498ab9ecdf..1219eebe27 100644--- a/crates/openhuman-tinyhumans/src/runtime_tests.rs+++ b/crates/openhuman-tinyhumans/src/runtime_tests.rs@@ -4,6 +4,7 @@use super::*;use crate::transport::BackendTransport;+use openhuman_embed::__host::core::slots::Extensions;use openhuman_embed::seams::DomainGroup;use openhuman_embed::BuilderSummary;@@ -68,7 +69,7 @@ fn product_identity_is_set_on_connect() {let builder = RuntimeBuilder::new().product_identity(identity.clone());// Not applied until the builder connects.assert_ne!(crate::product_identity(), identity);- let wired = wiring(&builder.install).expect("wiring");+ let wired = wiring(&builder.install, &Extensions::new()).expect("wiring");assert_eq!(crate::product_identity(), identity);assert_eq!(wired.transport.product_identity(), "opencompany");@@ -78,6 +79,7 @@ fn product_identity_is_set_on_connect() {.hosted_controllers(false).tool_ranker(false).product_identity(crate::ProductIdentity::default()),+ &Extensions::new(),).expect("restore");assert_eq!(diff --git a/crates/openhuman-tinyhumans/src/transport/memory_bearer_tests.rs b/crates/openhuman-tinyhumans/src/transport/memory_bearer_tests.rsindex a47e8869ef..d336f8c717 100644--- a/crates/openhuman-tinyhumans/src/transport/memory_bearer_tests.rs+++ b/crates/openhuman-tinyhumans/src/transport/memory_bearer_tests.rs@@ -42,8 +42,6 @@ async fn memory_bearer_rejects_the_host_local_session() {assert!(matches!(source.bearer().await,- Err(openhuman_embed::__host::memory::MemoryError::Unauthorized(- _- ))+ Err(tinymemory_api::Error::Unauthorized(_))));}diff --git a/crates/openhuman-tinyhumans/src/transport/mod.rs b/crates/openhuman-tinyhumans/src/transport/mod.rsindex 73886d56e4..75886f5dd7 100644--- a/crates/openhuman-tinyhumans/src/transport/mod.rs+++ b/crates/openhuman-tinyhumans/src/transport/mod.rs@@ -7,7 +7,7 @@ use std::sync::Arc;use async_trait::async_trait;use openhuman_embed::__host::config::Config;-use openhuman_embed::__host::memory::{CallbackBearerSource, MemoryError};+use openhuman_embed::__host::memory::CallbackBearerSource;use openhuman_embed::__host::memory_engines::BearerSource;use openhuman_embed::__host::security::credentials::session_support::{resolve_backend_credential, BackendCredential,@@ -133,7 +133,7 @@ impl BackendTransport for SdkBackendTransport {.map(BackendCredential::into_secret).map_err(|error| {log::debug!("[tinyhumans-transport] memory bearer unavailable: {error}");- MemoryError::Unauthorized(+ tinymemory_api::Error::Unauthorized("the backend credential is unavailable".to_string(),)})diff --git a/docs/gitbooks/en/SUMMARY.md b/docs/gitbooks/en/SUMMARY.mdindex e20b2e0820..2ee4e11a7d 100644--- a/docs/gitbooks/en/SUMMARY.md+++ b/docs/gitbooks/en/SUMMARY.md@@ -19,6 +19,7 @@- [Move OpenHuman to a new PC](guides/move-to-new-pc.md)- [Organize my project folders](guides/organize-project-folders.md)- [Create a doctor-specific assistant](guides/doctor-assistant.md)+ - [Run health diagnostics](guides/doctor.md)- [Create a safe companion for a child](guides/child-safe-companion.md)## Featuresdiff --git a/docs/gitbooks/en/developing/embed/api-index.json b/docs/gitbooks/en/developing/embed/api-index.jsonindex a1fc595a20..ab1705f2cd 100644--- a/docs/gitbooks/en/developing/embed/api-index.json+++ b/docs/gitbooks/en/developing/embed/api-index.json@@ -37,6 +37,7 @@"ConfigurationInfo","ControllerSchema","CoreAgent",+ "CoreBootMode","CoreBuilder","CoreError","CoreRuntime",@@ -154,6 +155,7 @@"cancellation","channels","chat_surface",+ "cli","complete","config","cron",@@ -184,151 +186,163 @@"name": "access","signature": "pub fn access(mut self, access: Access) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 370+ "line": 384},{"name": "action_dir","signature": "pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 327+ "line": 329},{"name": "agent_defaults","signature": "pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 157+ "line": 159},{"name": "api_key","signature": "pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 347+ "line": 361},{"name": "autonomy","signature": "pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 192+ "line": 194},{"name": "backend_url","signature": "pub fn backend_url(mut self, url: impl Into<String>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 357+ "line": 371+ },+ {+ "name": "boot_mode",+ "signature": "pub fn boot_mode(mut self, mode: CoreBootMode) -> Self",+ "source": "crates/openhuman-embed/src/runtime/builder.rs",+ "line": 349},{"name": "config","signature": "pub fn config(mut self, config: Config) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 487+ "line": 501},{"name": "config_source","signature": "pub fn config_source(mut self, source: ConfigSource) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 335+ "line": 337+ },+ {+ "name": "configure_core_extensions",+ "signature": "pub fn configure_core_extensions(self, configure: impl FnOnce(&Extensions)) -> Self",+ "source": "crates/openhuman-embed/src/runtime/seams.rs",+ "line": 418},{"name": "controller_extension","signature": "pub fn controller_extension(mut self, extension: ControllerExtension) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 417+ "line": 430},{"name": "cron","signature": "pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 217+ "line": 219},{"name": "cron_delivery","signature": "pub fn cron_delivery( mut self, delivery: Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>, ) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 261+ "line": 263},{"name": "cron_job_handler","signature": "pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc<dyn crate::cron::JobKindHandler>, ) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 275+ "line": 277},{"name": "defer_services","signature": "pub fn defer_services(mut self) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 405+ "line": 419},{"name": "definition_base","signature": "pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 176+ "line": 178},{"name": "domains","signature": "pub fn domains(mut self, domains: DomainSet) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 417+ "line": 431},{"name": "host_kind","signature": "pub fn host_kind(mut self, host_kind: HostKind) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 434+ "line": 448},{"name": "learning","signature": "pub fn learning(mut self, value: super::LearningSettings) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 212+ "line": 214},{"name": "listen","signature": "pub fn listen(self, host: impl Into<String>, port: u16) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 456+ "line": 470},{"name": "listen_host","signature": "pub fn listen_host(mut self, host: impl Into<String>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 461+ "line": 475},{"name": "listen_port","signature": "pub fn listen_port(mut self, port: u16) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 467+ "line": 481},{"name": "live_policy","signature": "pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 466+ "line": 479},{"name": "max_agents","signature": "pub fn max_agents(mut self, limit: usize) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 290+ "line": 292},{"name": "mcp_baseline","signature": "pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 187+ "line": 189},{"name": "memory_engine","signature": "pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 231+ "line": 233},{"name": "model_defaults","signature": "pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 166+ "line": 168},{"name": "modules",@@ -340,109 +354,109 @@"name": "post_turn_hook","signature": "pub fn post_turn_hook(mut self, hook: Arc<dyn LearningSink>) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 432+ "line": 445},{"name": "privacy","signature": "pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 202+ "line": 204},{"name": "provider","signature": "pub fn provider(mut self, provider: Provider) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 363+ "line": 377},{"name": "sandbox","signature": "pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 171+ "line": 173},{"name": "secrets","signature": "pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 207+ "line": 209},{"name": "server_launcher","signature": "pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 446+ "line": 459},{"name": "services","signature": "pub fn services(mut self, services: ServiceSet) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 389+ "line": 403},{"name": "session","signature": "pub fn session(mut self, session: Session) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 477+ "line": 491},{"name": "session_store","signature": "pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 246+ "line": 248},{"name": "skills","signature": "pub fn skills(mut self, policy: super::SkillsPolicy) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 181+ "line": 183},{"name": "storage","signature": "pub fn storage(mut self, source: impl Into<StorageSource>) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 459+ "line": 472},{"name": "token","signature": "pub fn token(mut self, token: TokenSource) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 444+ "line": 458},{"name": "tool_groups","signature": "pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 426+ "line": 440},{"name": "tool_hook","signature": "pub fn tool_hook(mut self, hook: Arc<dyn ToolHook<OpenHumanRunContext>>) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 439+ "line": 452},{"name": "tool_ranker","signature": "pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self","source": "crates/openhuman-embed/src/runtime/seams.rs",- "line": 424+ "line": 437},{"name": "tool_rules","signature": "pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 197+ "line": 199},{"name": "workspace","signature": "pub fn workspace(mut self, workspace: Workspace) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 300+ "line": 302},{"name": "workspace_dir","signature": "pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self","source": "crates/openhuman-embed/src/runtime/builder.rs",- "line": 314+ "line": 316}],"capabilities": {diff --git a/docs/gitbooks/en/developing/embed/api-index.md b/docs/gitbooks/en/developing/embed/api-index.mdindex 8cbf38d923..bd5ee7923a 100644--- a/docs/gitbooks/en/developing/embed/api-index.md+++ b/docs/gitbooks/en/developing/embed/api-index.md@@ -40,6 +40,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe- [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)+- [`CoreBootMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)@@ -157,6 +158,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe- [`cancellation`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`chat_surface`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)+- [`cli`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`complete`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)diff --git a/docs/gitbooks/en/developing/embed/builder-setters.md b/docs/gitbooks/en/developing/embed/builder-setters.mdindex aec4d2e3ce..a2d31b5d16 100644--- a/docs/gitbooks/en/developing/embed/builder-setters.md+++ b/docs/gitbooks/en/developing/embed/builder-setters.md@@ -4,47 +4,49 @@Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.-- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L370): `pub fn access(mut self, access: Access) -> Self`-- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L327): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`-- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L157): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`-- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L347): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`-- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L192): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`-- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L357): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`-- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L487): `pub fn config(mut self, config: Config) -> Self`-- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L335): `pub fn config_source(mut self, source: ConfigSource) -> Self`-- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L417): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`-- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L217): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`-- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L261): `pub fn cron_delivery( mut self, delivery: Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>, ) -> Self`-- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L275): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc<dyn crate::cron::JobKindHandler>, ) -> Self`-- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L405): `pub fn defer_services(mut self) -> Self`-- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L176): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`-- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L417): `pub fn domains(mut self, domains: DomainSet) -> Self`-- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L434): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`-- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L212): `pub fn learning(mut self, value: super::LearningSettings) -> Self`-- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L456): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`-- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L461): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`-- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L467): `pub fn listen_port(mut self, port: u16) -> Self`-- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L466): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`-- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L290): `pub fn max_agents(mut self, limit: usize) -> Self`-- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L187): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`-- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L231): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`-- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L166): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`+- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L384): `pub fn access(mut self, access: Access) -> Self`+- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L329): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`+- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L159): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`+- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L361): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`+- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L194): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`+- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L371): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`+- [`boot_mode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L349): `pub fn boot_mode(mut self, mode: CoreBootMode) -> Self`+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L501): `pub fn config(mut self, config: Config) -> Self`+- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L337): `pub fn config_source(mut self, source: ConfigSource) -> Self`+- [`configure_core_extensions`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L418): `pub fn configure_core_extensions(self, configure: impl FnOnce(&Extensions)) -> Self`+- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L430): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L219): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`+- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L263): `pub fn cron_delivery( mut self, delivery: Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>, ) -> Self`+- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L277): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc<dyn crate::cron::JobKindHandler>, ) -> Self`+- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L419): `pub fn defer_services(mut self) -> Self`+- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L178): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`+- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L431): `pub fn domains(mut self, domains: DomainSet) -> Self`+- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L448): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`+- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L214): `pub fn learning(mut self, value: super::LearningSettings) -> Self`+- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L470): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`+- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L475): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`+- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L481): `pub fn listen_port(mut self, port: u16) -> Self`+- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L479): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`+- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L292): `pub fn max_agents(mut self, limit: usize) -> Self`+- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L189): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`+- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L233): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`+- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L168): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L155): `pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self`-- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L432): `pub fn post_turn_hook(mut self, hook: Arc<dyn LearningSink>) -> Self`-- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L202): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`-- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L363): `pub fn provider(mut self, provider: Provider) -> Self`-- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L171): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`-- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L207): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`-- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L446): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`-- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L389): `pub fn services(mut self, services: ServiceSet) -> Self`-- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L477): `pub fn session(mut self, session: Session) -> Self`-- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L246): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`-- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L181): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`-- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L459): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`-- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L444): `pub fn token(mut self, token: TokenSource) -> Self`-- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L426): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`-- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L439): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook<OpenHumanRunContext>>) -> Self`-- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L424): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`-- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L197): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`-- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L300): `pub fn workspace(mut self, workspace: Workspace) -> Self`-- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L314): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`+- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L445): `pub fn post_turn_hook(mut self, hook: Arc<dyn LearningSink>) -> Self`+- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L204): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`+- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L377): `pub fn provider(mut self, provider: Provider) -> Self`+- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L173): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`+- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L209): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`+- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L459): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`+- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L403): `pub fn services(mut self, services: ServiceSet) -> Self`+- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L491): `pub fn session(mut self, session: Session) -> Self`+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L248): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`+- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L183): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`+- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L472): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`+- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L458): `pub fn token(mut self, token: TokenSource) -> Self`+- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L440): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`+- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L452): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook<OpenHumanRunContext>>) -> Self`+- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L437): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`+- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L199): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`+- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L302): `pub fn workspace(mut self, workspace: Workspace) -> Self`+- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L316): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`diff --git a/docs/gitbooks/en/guides/doctor.md b/docs/gitbooks/en/guides/doctor.mdnew file mode 100644index 0000000000..4458329e99--- /dev/null+++ b/docs/gitbooks/en/guides/doctor.md@@ -0,0 +1,199 @@+---+description: >-+ Run OpenHuman diagnostics, choose a check tier, and use the report to fix+ configuration and runtime problems.+icon: activity+---++# Diagnose OpenHuman with doctor++The doctor command checks the selected OpenHuman configuration and runtime. It+returns stable check ids, a result for each check, and a repair hint. It does+not repair settings or change the active profile.++## Run a report++Open a terminal where `openhuman-core` is installed and run:++```bash+openhuman-core doctor+```++The default `connect` tier checks local configuration and workspace state, then+runs bounded, read-only checks for configured services. Use `--live` only to+opt into live checks:++```bash+openhuman-core doctor --live+```++The CLI uses `connect` by default. Its `--live` option selects live checks;+the `static` tier is available through JSON-RPC and the agent tool.++Use `--only` and `--skip` to select exact check ids. Repeat either option to+select more than one check:++```bash+openhuman-core doctor --only config/parse --only workspace/writable+openhuman-core doctor --skip embeddings/configured-model+```++An unknown id appears as a `doctor/selection` error in the report. Valid ids+in the same request still run. The full inventory and fix hints are below.++## Tiers and cost++| Tier | What it runs |+| --------- | -------------------------------------------------------------------------------------------------------------------------- |+| `static` | Local config and filesystem checks. Some checks briefly create and remove a bounded temporary file to verify access. |+| `connect` | Static checks plus bounded, read-only checks against configured local services and network endpoints. This is the default. |+| `live` | Connect checks plus one-shot inference and embedding requests and a disposable memory store/fetch/forget roundtrip. |++{% hint style="warning" %}+Live checks may spend inference or memory-service credits. Run `--live` only+when you intend to make those requests. The memory roundtrip stores an isolated+temporary item and attempts to remove it afterward; the report says when it+cannot confirm cleanup. A local SQLite memory engine may update derived+`-shm` or empty `-wal` sidecar state during database access.+{% endhint %}++Each chat inference probe sends the short `Reply OK` prompt with a provider-+enforced output limit of at most five tokens. Roles that resolve to the same+endpoint, credential, and wire model share one completion while keeping separate+findings. A route that cannot enforce an output limit in its request is skipped+without a model call. OpenAI Codex OAuth uses a Responses API request that has+no output-token limit field, so its `inference/live/<role>` check is skipped;+that skip does not indicate that Codex is healthy.++The agent tool follows the same rule: ask the assistant to run `doctor_health`+for ordinary diagnostics. It should request the live tier only when you+explicitly ask for billable probes.++## Output modes and exit codes++The command supports a human-readable table, JSON output, and lint mode:++```bash+openhuman-core doctor --json+openhuman-core doctor --lint+openhuman-core doctor --lint --severity-min warn --json+```++| Mode | Result |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------- |+| Default | Prints a table grouped by check category and a summary. Returns `0` after a report is produced. |+| `--json` | Prints the v2 report as JSON and returns `0` after a report is produced, regardless of findings. |+| `--lint` | Returns `0` when no finding meets the minimum severity, `1` when one or more do, or `2` if the report could not be produced. |+| `--lint --json` | Prints the report as JSON and keeps lint's `0`, `1`, or `2` exit behavior. |++`--severity-min` accepts `info`, `warn`, or `error` and defaults to `error`.+Pass and skipped findings never meet the threshold. For example, to fail CI on+warnings as well as errors:++```bash+openhuman-core doctor --lint --severity-min warn+```++## Select a profile++On desktop, `--profile <id>` checks a profile without activating it or+switching the current user:++```bash+openhuman-core doctor --profile work+```++Profile loading is read-only. A missing profile or an unsupported layout is+reported with a finding and a fix hint. In a SaaS host, diagnostics use the+current tenant's forced configuration; a profile option cannot select another+tenant.++## Read the report++The report uses schema version `2`. It includes the selected profile and config+source when known, requested tier, check ids run or skipped, findings, a+severity summary, and `ok`. `ok` is false when a finding has severity `error`;+warnings remain advisory. In lint mode, the separate severity threshold+determines the exit code.++Each finding has a short message and a `fix_hint`. The report may name a config+path and whether a value came from the command line, environment, `.env`, file,+or default. It does not include credentials or resolved config values. The+`config/source` finding may identify the loaded config and `.env` file paths so+you can diagnose where a setting came from.++The doctor does not have a `--fix` mode. Apply a repair yourself, then rerun+the reported check or the full report.++## Check inventory++The ids below are registered checks. Dynamic ids include the configured module,+server, provider, or inference role in the final path segment. Each finding+includes a more specific hint for the setting or service it checked.++| Check id | Tier | What it checks | Next step when it reports a problem |+| ------------------------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `config/parse` | static | Config parsing and recovery from an invalid file or backup. | Repair `config.toml`; inspect and restore a valid backup if recovery occurred. |+| `config/unknown-key` | static | Config keys ignored because they are not supported. | Rename the key to the suggested supported field. |+| `config/legacy-key` | static | Legacy config keys migrated during load. | Update the config to the current key name. |+| `config/env-override` | static | Values supplied by environment variables or `.env` that shadow file values. | Choose one source and remove the shadowed override. |+| `config/source` | static | Config and `.env` paths and value-source information. | Use the reported source to diagnose precedence. |+| `inference/provider-ref` | static | References to unavailable inference providers. | Select a registered provider and correct the reported config field. |+| `inference/construct` | static | Whether each configured model route can be constructed with its required credential. | Correct provider settings and configure its required credential. |+| `inference/temperature` | static | Supported temperature settings on configured model routes. | Set a supported temperature for the reported route. |+| `embeddings/config` | static | Embedding provider, model, route, and vector dimensions. | Configure a provider, model, and dimension that agree. |+| `components/referenced-but-disabled` | static | Config that refers to a disabled component. | Enable the component or remove the dependent config. |+| `config/runtime-settings` | static | Ignored fallback providers and incomplete model, delegate, or enabled-channel settings. | Use the path-specific hint to complete, remove, or enable the named setting. |+| `modules/source-fallback` | static | Module source selection that fell back from the intended source. | Configure the intended module source explicitly. |+| `modules/override-invalid` | static | Invalid module overrides. | Correct or remove the reported override. |+| `storage/url` | static | Whether the configured storage URL uses a driver available in this build. | Use a supported URL scheme and include its driver. |+| `workspace/action-dir` | static | Whether the agent action directory is usable. | Create the directory or grant the process access. |+| `workspace/writable` | static | Whether the selected workspace permits a bounded write probe. | Grant write access to the workspace directory. |+| `workspace/layout` | static | Required workspace entries and available disk space. | Create the named entry or free disk space. |+| `runtime/environment` | static | Required local environment, including `HOME`, `SHELL`, `git`, and `curl`. | Install or configure the named local prerequisite. |+| `runtime/agent-sdk` | connect | The configured Claude Agent SDK command and version. | Install or configure the SDK command, then rerun doctor. |+| `secrets/master-key-env` | static | Whether both master-key environment variables are set. | Keep only the intended master-key source configured. |+| `network/proxy` | static | Whether the configured network proxy is valid. | Correct the proxy setting reported by the check. |+| `memory/root` | static | Whether the configured memory root is valid. | Correct the reported memory-root path. |+| `profile/exists` | static | Whether a selected desktop profile exists and has a supported layout and valid config. | Select an existing profile with a supported layout and valid config. |+| `profile/provisioned` | connect | Whether the selected tenant profile is provisioned and ready. | Provision the tenant profile before running doctor again. |+| `memory/binding` | static | The selected memory engine and its configuration. | Select an available memory driver. |+| `memory/health` | connect | Whether the selected memory engine is healthy. | Restore the memory driver's availability and rerun the check. |+| `memory/roundtrip` | live | Whether a disposable memory item can be stored, fetched, and removed. | Check the selected engine; inspect the isolated doctor scope if cleanup was not confirmed. |+| `storage/connect` | connect | Read-only access to the configured storage driver. A missing SQLite database is not created; an existing database and WAL data remain intact, though SQLite may create derived `-shm` or empty `-wal` sidecars. | Check that the configured storage exists and is readable; connect to remote storage if it is unavailable. |+| `storage/layout` | static | An interrupted profile storage-layout migration. | Stop OpenHuman and resume the migration through Settings or the CLI. |+| `secrets/keyring` | connect | Whether the configured keyring can be inspected safely. Non-interactive macOS checks may be skipped. | Run interactively or configure an available keyring backend. |+| `embeddings/configured-model` | connect | Whether the configured Ollama embedding model is available. Other providers are skipped by this check. | Start the configured Ollama service or correct its URL and model. |+| `modules/<id>` | connect | Status of each configured module. Disabled modules are skipped. | Repair or enable the module and verify its configured digest. |+| `mcp/<server>` | connect | Connectivity for each configured MCP server. | Start the server or correct its connection settings. |+| `skills/discovery` | static | Whether installed skill manifests can be read. | Repair the manifest at the reported path. |+| `skills/github-preflight` | connect | GitHub access required by an installed skill. | Resolve the reported GitHub access or repository issue. |+| `sandbox/backend` | connect | Whether the configured Docker sandbox backend is available. | Install or start Docker, or choose an available sandbox backend. |+| `channels/<provider>` | connect | Health of each configured messaging provider. | Restore the provider connection and rerun the check. |+| `integrations/composio` | connect | Composio availability for the selected profile. | Reconnect Composio or correct its endpoint configuration. |+| `voice/stt` | connect | Readiness of the configured speech-to-text provider. | Enable voice or configure a supported speech-to-text provider. |+| `voice/tts` | connect | Readiness of the configured text-to-speech provider. | Enable voice or configure a supported text-to-speech provider. |+| `search/<provider>` | connect | Readiness of each configured search provider. | Configure the provider key named in the finding. |+| `wallet/status` | connect | Readiness of the configured wallet component. | Configure the wallet safely or disable the unused wallet feature. |+| `backend/api-url` | static | Whether the hosted backend URL is valid for the selected profile. | Set a valid backend API URL for this profile. |+| `backend/reachable` | connect | Whether the hosted backend responds to its health check. | Check the configured backend URL and network access. |+| `backend/credential` | connect | Whether the selected profile has a usable hosted credential. | Sign in again through the supported auth flow. |+| `backend/identity` | connect | Whether the backend accepts the selected identity. | Check the tenant identity and access through the supported auth flow. |+| `backend/socket` | connect | Current backend socket connection state. | Check socket availability and the profile's network policy. |+| `inference/managed-catalog` | connect | Whether the hosted managed inference catalog is reachable. | Check managed inference access for this profile. |+| `inference/model-in-catalog` | connect | Whether configured models appear in their provider catalogs. Providers without a read-only catalog are skipped. | Choose a listed model or verify catalog support for the provider. |+| `inference/auth-errors` | connect | Authentication errors recorded for inference providers. | Update or reconnect the provider credentials. |+| `inference/live/<role>` | live | Whether each configured inference role can return a short, capped completion. Routes that cannot enforce the output cap are skipped; identical routes share one request. | A skipped check made no model call and does not confirm provider health. For attempted requests, check the provider, model, credential, quota, and network connection named by the finding. |+| `embeddings/live` | live | Whether the selected embedding provider returns the configured vector width. | Check provider access and align the configured model and dimensions. |++## Common interpretation++- A `pass` means the check completed successfully. A `warn` calls out a problem+ that does not make the report's `ok` field false. An `error` means a check+ found a failure. A `skipped` result explains why a check did not run.+- A check above the selected tier, behind a disabled component, or using an+ inference route that cannot enforce the output cap is skipped; a skipped check+ is not evidence that the service is healthy.+- `doctor.models` is a separate read-only provider-catalog report. It distinguishes+ available catalogs, providers without a catalog, access failures, and request+ errors; it does not make inference requests.diff --git a/docs/gitbooks/zh/SUMMARY.md b/docs/gitbooks/zh/SUMMARY.mdindex c100b5289f..d6d95f77a3 100644--- a/docs/gitbooks/zh/SUMMARY.md+++ b/docs/gitbooks/zh/SUMMARY.md@@ -9,3 +9,7 @@kind: translationtranslation: tr_lvOVh```++## 指南++- [运行 OpenHuman 健康诊断](guides/doctor.md)diff --git a/docs/gitbooks/zh/guides/doctor.md b/docs/gitbooks/zh/guides/doctor.mdnew file mode 100644index 0000000000..202982727f--- /dev/null+++ b/docs/gitbooks/zh/guides/doctor.md@@ -0,0 +1,178 @@+---+description: >-+ 运行 OpenHuman 诊断,选择检查级别,并根据报告修复配置和运行问题。+icon: activity+---++# 使用 doctor 诊断 OpenHuman++doctor 命令会检查所选 OpenHuman 配置和运行环境,并返回稳定的检查 ID、+检查结果和修复提示。它不会自动修复设置,也不会切换当前配置档案。++## 运行报告++在安装了 `openhuman-core` 的终端中运行:++```bash+openhuman-core doctor+```++默认的 `connect` 级别会检查本地配置和工作区,然后对已配置的服务执行有时限、+只读的检查。使用 `--live` 可选择加入实时检查:++```bash+openhuman-core doctor --live+```++CLI 默认使用 `connect`。CLI 的 `--live` 会启用实时检查;JSON-RPC 和 agent 工具+还可以选择 `static` 级别。++使用 `--only` 和 `--skip` 按精确检查 ID 选择项目。每个选项都可以重复使用:++```bash+openhuman-core doctor --only config/parse --only workspace/writable+openhuman-core doctor --skip embeddings/configured-model+```++未知 ID 会在报告中显示为 `doctor/selection` 错误。同一请求中有效的 ID 仍会运行。+完整清单和修复提示见下文。++## 检查级别与费用++| 级别 | 检查内容 |+| --------- | -------------------------------------------------------------------------------------- |+| `static` | 本地配置和文件系统检查。部分检查会短暂创建并删除有大小限制的临时文件,以确认访问权限。 |+| `connect` | `static` 检查,以及对已配置本地服务和网络端点进行有时限、只读检查。这是默认级别。 |+| `live` | `connect` 检查,以及一次性推理和嵌入请求、一次临时记忆存储/读取/删除测试。 |++{% hint style="warning" %}+实时检查可能消耗推理或记忆服务额度。只有在你准备好发出这些请求时才使用+`--live`。记忆往返测试会存入一个隔离的临时条目,并在完成后尝试删除;如果无法+确认已清理,报告会说明这一点。本地 SQLite 记忆引擎访问数据库时,可能会更新+派生的 `-shm` 或空 `-wal` 辅助文件状态。+{% endhint %}++每个推理探测都会发送简短的 `Reply OK` 提示,并要求提供方在请求层将输出限制为最多+5 个 token。解析到相同端点、凭据和实际模型的角色会共用一次补全请求,但仍各自生成+检查结果。如果路由无法在请求层强制输出上限,doctor 会跳过该路由且不会调用模型。+OpenAI Codex OAuth 使用的 Responses API 请求没有输出 token 上限字段,因此对应的+`inference/live/<role>` 会跳过;这不表示 Codex 已通过健康检查。++agent 工具也遵循此规则:日常诊断可要求助手运行 `doctor_health`。只有当你明确+要求执行可能计费的实时探测时,助手才应选择 live 级别。++## 输出模式和退出码++命令支持人类可读表格、JSON 输出和 lint 模式:++```bash+openhuman-core doctor --json+openhuman-core doctor --lint+openhuman-core doctor --lint --severity-min warn --json+```++| 模式 | 结果 |+| --------------- | -------------------------------------------------------------------------------------- |+| 默认模式 | 按检查类别分组输出表格和摘要。成功生成报告后返回 `0`。 |+| `--json` | 输出 v2 JSON 报告。成功生成报告后始终返回 `0`,不受检查结果影响。 |+| `--lint` | 没有达到最低严重级别的结果时返回 `0`;有一个或多个时返回 `1`;无法生成报告时返回 `2`。 |+| `--lint --json` | 输出 JSON,同时保留 lint 的 `0`、`1` 或 `2` 退出码规则。 |++`--severity-min` 可设为 `info`、`warn` 或 `error`,默认是 `error`。`pass` 和+`skipped` 不会达到阈值。若希望 CI 对警告和错误都失败:++```bash+openhuman-core doctor --lint --severity-min warn+```++## 选择配置档案++在桌面端,`--profile <id>` 会检查指定配置档案,而不会激活它或切换当前用户:++```bash+openhuman-core doctor --profile work+```++配置档案以只读方式加载。档案不存在或布局不受支持时,报告会给出对应结果和修复+提示。SaaS 主机始终使用当前租户的强制配置;配置档案选项不能用于选择其他租户。++## 阅读报告++报告使用 schema 版本 `2`。其中包括已知的配置档案和配置来源、请求的级别、已运行+或跳过的检查 ID、发现项、严重程度摘要以及 `ok`。只有当某项严重程度为 `error`+时,`ok` 才为 false;警告仍是提示。在 lint 模式中,退出码由单独的严重程度阈值决定。++每项发现都有简短说明和 `fix_hint`。报告可以注明配置路径,以及值来自命令行、环境+变量、`.env`、配置文件或默认值。报告不会包含凭据或解析后的配置值。`config/source`+可能会列出加载的配置文件和 `.env` 路径,帮助你查明设置来源。++doctor 没有 `--fix` 模式。请自行应用修复,然后重新运行相关检查或完整报告。++## 检查清单++以下是已注册的检查 ID。动态 ID 的最后一段会包含配置中的模块、服务器、提供方或+推理角色。报告会针对所检查的具体设置或服务提供更具体的提示。++| 检查 ID | 级别 | 检查内容 | 出现问题时的下一步 |+| ------------------------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| `config/parse` | static | 配置解析,以及无效文件或备份的恢复状态。 | 修复 `config.toml`;如发生恢复,请检查并还原有效备份。 |+| `config/unknown-key` | static | 因不受支持而被忽略的配置键。 | 按建议改为受支持的字段名。 |+| `config/legacy-key` | static | 加载时迁移的旧配置键。 | 将配置改为当前键名。 |+| `config/env-override` | static | 环境变量或 `.env` 中覆盖文件值的设置。 | 选择一个来源,并移除被覆盖的设置。 |+| `config/source` | static | 配置和 `.env` 路径及值来源。 | 根据报告的来源排查优先级。 |+| `inference/provider-ref` | static | 引用了不可用推理提供方的设置。 | 选择已注册的提供方,并修正报告的配置字段。 |+| `inference/construct` | static | 配置的模型路由是否能使用所需凭据创建。 | 修正提供方设置并配置所需凭据。 |+| `inference/temperature` | static | 模型路由上的温度设置是否受支持。 | 为报告中的路由设置受支持的温度。 |+| `embeddings/config` | static | 嵌入提供方、模型、路由和向量维度。 | 配置相互匹配的提供方、模型和维度。 |+| `components/referenced-but-disabled` | static | 配置引用了已禁用的组件。 | 启用组件或移除依赖它的配置。 |+| `config/runtime-settings` | static | 被忽略的回退提供方,以及不完整的模型、委托代理或已启用频道设置。 | 按提示完成、移除或启用对应字段。 |+| `modules/source-fallback` | static | 模块来源是否从预期来源回退。 | 明确配置预期使用的模块来源。 |+| `modules/override-invalid` | static | 无效的模块覆盖设置。 | 修正或移除报告的覆盖项。 |+| `storage/url` | static | 配置的存储 URL 是否使用此构建支持的驱动。 | 使用受支持的 URL 方案并启用对应驱动。 |+| `workspace/action-dir` | static | agent 操作目录是否可用。 | 创建该目录或授予进程所需访问权限。 |+| `workspace/writable` | static | 所选工作区是否允许受限写入测试。 | 授予工作区写入权限。 |+| `workspace/layout` | static | 工作区必需文件和可用磁盘空间。 | 创建报告中缺失的项目或释放磁盘空间。 |+| `runtime/environment` | static | `HOME`、`SHELL`、`git` 和 `curl` 等本地环境。 | 安装或配置报告中指出的本地依赖。 |+| `runtime/agent-sdk` | connect | 已配置的 Claude Agent SDK 命令及版本。 | 安装或配置 SDK 命令,然后重新运行 doctor。 |+| `secrets/master-key-env` | static | 是否同时设置了两个主密钥环境变量。 | 只保留预期的主密钥来源。 |+| `network/proxy` | static | 已配置的网络代理是否有效。 | 修正检查指出的代理设置。 |+| `memory/root` | static | 已配置的记忆根目录是否有效。 | 修正报告中的记忆根目录路径。 |+| `profile/exists` | static | 桌面配置档案是否存在,布局是否受支持且配置有效。 | 选择具有受支持布局和有效配置的现有档案。 |+| `profile/provisioned` | connect | 所选租户档案是否已配置并可用。 | 先配置租户档案,再重新运行 doctor。 |+| `memory/binding` | static | 所选记忆引擎及其配置。 | 选择可用的记忆驱动。 |+| `memory/health` | connect | 所选记忆引擎是否健康。 | 恢复记忆驱动的可用性并重新运行检查。 |+| `memory/roundtrip` | live | 临时记忆条目能否存储、读取和删除。 | 检查所选引擎;若未确认清理,请查看隔离的 doctor 服务范围。 |+| `storage/connect` | connect | 对配置存储驱动的只读访问。不会创建缺失的 SQLite 数据库;现有数据库及 WAL 数据保持不变,但 SQLite 可能创建派生的 `-shm` 或空 `-wal` 辅助文件。 | 检查存储是否存在且可读;远程存储不可用时检查连接。 |+| `storage/layout` | static | 是否有未完成的配置档案存储布局迁移。 | 停止 OpenHuman,通过 Settings 或 CLI 继续迁移。 |+| `secrets/keyring` | connect | 是否能安全检查已配置的密钥环。非交互 macOS 检查可能跳过。 | 在交互环境运行,或配置可用的密钥环后端。 |+| `embeddings/configured-model` | connect | 配置的 Ollama 嵌入模型是否可用。其他提供方会被此项跳过。 | 启动配置的 Ollama 服务,或修正 URL 和模型。 |+| `modules/<id>` | connect | 每个已配置模块的状态。禁用的模块会跳过。 | 修复或启用模块,并检查其配置摘要。 |+| `mcp/<server>` | connect | 每个已配置 MCP 服务器的连接状态。 | 启动服务器或修正连接设置。 |+| `skills/discovery` | static | 已安装的 skill 清单是否可读。 | 修复报告路径上的清单文件。 |+| `skills/github-preflight` | connect | skill 所需的 GitHub 访问。 | 解决报告中的 GitHub 访问或仓库问题。 |+| `sandbox/backend` | connect | 配置的 Docker 沙箱后端是否可用。 | 安装或启动 Docker,或选择可用的沙箱后端。 |+| `channels/<provider>` | connect | 每个已配置消息提供方的健康状态。 | 恢复提供方连接并重新运行检查。 |+| `integrations/composio` | connect | 所选配置档案中的 Composio 是否可用。 | 重新连接 Composio 或修正端点设置。 |+| `voice/stt` | connect | 已配置语音转文字提供方是否就绪。 | 启用语音或配置受支持的语音转文字提供方。 |+| `voice/tts` | connect | 已配置文字转语音提供方是否就绪。 | 启用语音或配置受支持的文字转语音提供方。 |+| `search/<provider>` | connect | 每个已配置搜索提供方是否就绪。 | 配置发现项中指出的提供方密钥。 |+| `wallet/status` | connect | 已配置钱包组件是否就绪。 | 安全配置钱包,或禁用不使用的钱包功能。 |+| `backend/api-url` | static | 所选档案的托管后端 URL 是否有效。 | 为该档案设置有效的后端 API URL。 |+| `backend/reachable` | connect | 托管后端是否响应健康检查。 | 检查配置的后端 URL 和网络访问。 |+| `backend/credential` | connect | 所选档案是否有可用的托管凭据。 | 通过受支持的认证流程重新登录。 |+| `backend/identity` | connect | 后端是否接受所选身份。 | 检查租户身份和访问权限。 |+| `backend/socket` | connect | 当前后端 socket 连接状态。 | 检查 socket 服务和该档案的网络策略。 |+| `inference/managed-catalog` | connect | 托管推理目录是否可访问。 | 检查该档案的托管推理访问权限。 |+| `inference/model-in-catalog` | connect | 配置的模型是否出现在其提供方目录中。不支持只读目录的提供方会跳过。 | 选择目录中的模型,或确认提供方支持目录查询。 |+| `inference/auth-errors` | connect | 记录的推理提供方认证错误。 | 更新或重新连接提供方凭据。 |+| `inference/live/<role>` | live | 每个配置推理角色是否能返回受上限约束的简短补全。无法在请求层强制输出上限的路由会跳过;相同路由共用一次请求。 | 跳过表示没有调用模型,也不表示提供方健康。对于已尝试的请求,按提示检查提供方、模型、凭据、额度和网络连接。 |+| `embeddings/live` | live | 所选嵌入提供方返回的向量宽度是否符合配置。 | 检查提供方访问,并使模型与配置维度一致。 |++## 常见结果++- `pass` 表示检查成功。`warn` 表示需要留意的问题,但不会令报告的 `ok` 变为+ false。`error` 表示检查发现失败。`skipped` 会说明检查未运行的原因。+- 高于所选级别、受禁用组件影响,或使用无法强制输出上限的推理路由时,检查会被跳过。+ 跳过不能说明服务健康。+- `doctor.models` 是单独的只读提供方目录报告,会区分可用目录、提供方不支持目录、+ 访问失败和请求错误;它不会发送模型补全请求。diff --git a/docs/specs/doctor.md b/docs/specs/doctor.mdnew file mode 100644index 0000000000..c6e165fd66--- /dev/null+++ b/docs/specs/doctor.md@@ -0,0 +1,357 @@+# Doctor v2 contract++This is the maintainer contract for the OpenHuman doctor framework and the+checks delivered by the doctor epic. It defines stable check ids and report+semantics for the `doctor` domain. The core owns checks,+the registry, runner, and RPC surface; `openhuman-cli` owns command parsing,+rendering, and process exit codes; `openhuman-tinyhumans` owns hosted checks.++The intended user outcome is a report that says whether the selected+configuration is ready to run, what was inspected, and what an operator can do+about each finding. Doctor does not persist configuration or application-state+changes; local filesystem write probes use temporary files and clean them up.+This contract borrows OpenClaw's stable check identifiers,+structured findings, advisory JSON mode, and threshold-based lint behavior.+Wire fields remain snake case to match the existing RPC contract. This contract+does not adopt OpenClaw's repair operation: this epic adds no repair command.++## Goals and non-goals++The doctor validates configuration semantics and provenance, profile-specific+runtime readiness, configured local and hosted components, and outbound+connections. Checks are selectable by stable id and have an explicit cost tier.+The report is a versioned JSON API shared by RPC, CLI, the agent tool, and the+Settings diagnostics surface.++This epic does not add `--fix`, prompts, config rewrites, migrations, token+generation, or other repair side effects. A finding always has a human-readable+`fix_hint`, but that hint is guidance for a later explicit operator action.+Checks do not make billable inference or embedding calls, or write scratch+memory, unless the caller opts into the `live` tier.++## Check contract++The Rust API and serialized JSON use snake case. A check is registered with a+stable id, category, cost tier, and optional component gate. Its detector is+asynchronous and returns findings for that check:++```rust+DoctorCheck {+ id: "<area>/<name>[/<qualifier>...]",+ category: "<display category>",+ tier: DoctorTier::Static | DoctorTier::Connect | DoctorTier::Live,+ component_gate: Option<ComponentId>,+ async fn detect(&self, ctx: &DoctorCtx) -> Vec<Finding>,+}+```++Ids are lowercase ASCII segments separated by `/`, with at least an area and+name (`area/name`). Each segment is nonempty and contains only lowercase ASCII+letters, digits, `_`, or `-`. Additional segments are allowed for checks+scoped to a role or provider, such as+`inference/live/chat`. They are API identifiers used by `--only`, `--skip`, the+RPC filters, and downstream consumers. Once released, an id is never renamed+or reused for different behavior; a replacement gets a new id and the old one+remains recognizable for at least one schema lifetime. IDs are matched+exactly. Prefixes, globs, and category names are not selectors.++`static` checks may read and probe the local filesystem, but do not open network+connections. Temporary local write probes must be cleaned up. `connect` checks+may make bounded, read-only network requests and are the default; they do not+make billable calls or persist state. `live` checks may make billable model or+embedding calls and may write disposable scratch memory; they run only when+explicitly requested. A requested tier is a ceiling: `static` runs static+checks, `connect` runs static and connect checks, and `live` runs all three+tiers.++The runner applies the active `ComponentSet` gate before calling a detector.+A gated-off component produces a `skipped` finding and is listed in+`checks_skipped`. Checks above the requested tier are also listed as skipped.+An id omitted by `--only` or named by a valid `--skip` is filtered out and is+not reported as a failed check. The runner uses bounded concurrency (at most+eight checks at once), a timeout for every detector (5 seconds for static,+10 seconds for connect, 60 seconds for live), and a stable registry order in+the report regardless of completion order. Timeout and detector failures are+`error` findings; one failure does not prevent other selected checks from+finishing. A timed-out detector is cancelled where the async operation supports+cancellation.++Detectors may return an empty vector when the check is clean. The runner turns+an empty result into one `pass` finding so `checks_run` and severity totals+still distinguish a successful check from an unobserved one. Detectors that+find multiple conditions emit one finding for each condition. This permits a+clean config check to return no findings, as required by the config leaves.++### Finding++```json+{+ "check_id": "config/unknown-key",+ "severity": "warn",+ "message": "Unknown config key `memroy`; did you mean `memory`?",+ "fix_hint": "Rename the key to `memory` and rerun doctor.",+ "config_path": "memroy",+ "value_source": "file",+ "duration_ms": 4,+ "affects": ["settings.configure_ai"]+}+```++| Field | Contract |+| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `check_id` | Required stable id of the check that produced the finding. |+| `severity` | `pass`, `info`, `warn`, `error`, or `skipped`. |+| `message` | Short operator-facing result, with no secret or config value. |+| `fix_hint` | Required next step. Use “No action required.” for `pass`; explain how to rerun or enable a skipped check. |+| `config_path` | Optional config key path or source file path. `config/source` may name the loaded config and `.env` paths; other checks normally use a logical config key path. |+| `value_source` | Optional `cli`, `env`, `dotenv`, `file`, or `default`, when a finding concerns a resolved value. |+| `duration_ms` | Elapsed detector time, repeated consistently on findings from one check. A check skipped before execution reports `0`. |+| `affects` | Zero or more stable `about_app` capability ids, such as `channels.connect_platform` or `local_ai.configure_provider`. |++The report must not contain credentials, tokens, secret material, raw config+values, request or response bodies, or user-authored content. Redact endpoint+credentials and query parameters before forming messages. A detector that+cannot safely summarize an error reports its class and a safe recovery hint,+not the original error string. `value_source` records provenance only; it+never carries the value.++## Report schema v2++The RPC method remains `openhuman.doctor_report`; the existing `doctor_models`+method and `doctor_health` / `doctor_models` tool names also remain stable.+`doctor_report` accepts `{ "tier", "only", "skip", "profile" }` and returns:++```json+{+ "schema_version": 2,+ "profile": "desktop-default",+ "config_source": "profile",+ "profile_layout_version": 2,+ "config_resolution_source": "active_user.toml",+ "tier": "connect",+ "checks_run": ["config/parse"],+ "checks_skipped": ["inference/live/chat"],+ "findings": [+ {+ "check_id": "config/parse",+ "severity": "pass",+ "message": "The config file parsed successfully.",+ "fix_hint": "No action required.",+ "duration_ms": 4,+ "affects": []+ },+ {+ "check_id": "inference/live/chat",+ "severity": "skipped",+ "message": "This live check was not requested.",+ "fix_hint": "Rerun doctor with --live to run this check.",+ "duration_ms": 0,+ "affects": []+ }+ ],+ "summary": { "pass": 1, "info": 0, "warn": 0, "error": 0, "skipped": 1 },+ "ok": true+}+```++`checks_run` and `checks_skipped` are ordered arrays of check ids. A check+selected by the caller but gated off or above the requested tier is in+`checks_skipped`; checks outside an `only` selection and checks named by `skip`+are absent. `summary` counts findings by severity. `ok` is false exactly when+the report contains an `error`; warnings remain advisory, and a skipped check+does not by itself make the report unhealthy. The CLI's lint threshold is+separate from this field.++`profile` is the effective profile id, when the host has one, and `null`+otherwise. `config_source` is always the source kind (`profile` or `tenant`),+not a tenant credential or filesystem path. `profile_layout_version` is `1`+or `2` when a desktop profile layout was selected; `config_resolution_source`+is the stable directory-selection label, such as `OPENHUMAN_WORKSPACE`,+`active_workspace.toml`, `active_user.toml`, `default`, or `--profile`. These+optional fields are omitted when unknown and for SaaS tenant contexts. The+`config/source` info finding+reports the loaded config and `.env` paths, directory resolution source,+profile layout version when applicable, and whether CLI `--model` or+`--provider` overrides are active. It does not report config values or+credentials. It also reports `.env` variables shadowed by existing process+environment values without including their values.++The selection validator is a reserved runner check, `doctor/selection`. An+unknown id supplied to either `only` or `skip` adds an `error` finding under+`doctor/selection`, with a hint to use a registered exact id. Do not echo an+unknown selector into the message. Valid selected checks still run. The+reserved check is not itself selectable and does not count as a detector in+`checks_run`.++## Tier and selection inputs++The RPC accepts optional `tier`, `only`, `skip`, and `profile` fields. An+omitted tier means `connect`; omitted lists are empty. `only` and `skip` are+repeatable at the CLI and contain exact ids. If `only` is present, only those+registered checks run; `skip` then removes checks from that set. Duplicate ids+are collapsed. An unregistered id is a report finding rather than a transport+error, so callers receive useful results for the valid ids in the same request.++`--live` selects the `live` ceiling. It does not change the tier of each check+or imply repair. The doctor does not infer consent to billable work from a+profile setting.++## CLI contract++The command is implemented only in `crates/openhuman-cli`; the core contains+no CLI parser or renderer. It calls `openhuman.doctor_report` through the+`openhuman-rpc` facade and maps options to the RPC parameters above.++| Invocation | Output and exit behavior |+| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |+| `openhuman-core doctor` | Human-readable table; exit `0` after a report is produced. |+| `openhuman-core doctor --json` | JSON report; advisory mode exits `0` after a report is produced, regardless of findings. |+| `openhuman-core doctor --lint` | Human-readable findings; exit `0` if none meet the threshold, `1` if any do, `2` if parsing or execution fails before a report is produced. |+| `openhuman-core doctor --lint --json` | Same threshold and exit behavior as lint, with JSON output. |++`--severity-min` accepts `info`, `warn`, or `error` and defaults to `error`.+The threshold controls both printed findings and the lint result. `pass` and+`skipped` never meet it. `--only <id>` and `--skip <id>` may be repeated;+`--live` selects the live tier, and `--profile <id>` selects the effective+profile where the host permits it. In SaaS, an authenticated tenant always uses+its forced config and storage scope. An operator may use `--profile <id>` to+target another tenant; a tenant caller may target only itself. The host checks+that permission before doctor reads config or credentials. Argument syntax+errors exit `2` before+the RPC call.++The CLI does not add fields to the RPC report. Human output is a rendering of+the same findings and includes the severity, check id, message, and fix hint.+JSON uses the same report in every surface.++## Profile semantics++On desktop, a requested profile id resolves through `ProfileLayout`. Doctor+loads that profile's configuration and credentials for inspection without+changing the active profile, writing profile state, or changing process-wide+configuration. With no explicit id, it uses the currently selected profile.+The report's `profile` is the effective id and `config_source` is `profile`.++In SaaS, doctor runs against a forced tenant configuration and storage scope.+Without `profile`, the context is the authenticated tenant. An operator may+select another tenant by id; an ordinary tenant caller may select only itself.+The host authorizes this before doctor reads any config or credential. The+report uses `config_source: "tenant"` and includes no tenant secret.+Profile-scoped reads use the selected context rather than process-global+lookup helpers.++## Check registration and hosted checks++Built-in checks register in the core registry. The core exposes both+process-default `register_check_source(source)` and per-`CoreContext`+`register_check_source_in` registration through `CoreBuilder::extensions`, so a+host can supply checks without a dependency from core back to that host.+`openhuman-tinyhumans` registers its backend, identity, socket, API URL, and+managed-inference checks through this seam. Profile-aware or tenant-aware+sources use context-scoped registration; context-independent sources may use+the process-default registration. At report start, malformed or duplicate ids+are rejected before any selected detector executes. Hosted ids use the same+lowercase slash-separated segment grammar and are unique across sources. A+source may register zero checks when its host capability is absent.++The doctor stays in the existing `DomainGroup::Platform` registration group.+Its Rust module lives at the top-level `doctor` domain without adding a new+runtime domain group. `subsystems.status` remains a separate+wire projection: it reports driver bindings, health, and capabilities, while+doctor findings include stable check ids, severity, guidance, provenance, and+timing. A doctor check may consume subsystem status as evidence, but it does+not reuse `SubsystemStatus` as a finding.++## Check inventory++The paths below are the implementation-owned probe locations under+`crates/openhuman-core/src/doctor/` (and `crates/openhuman-tinyhumans/src/doctor/`+for hosted checks). Function names are stable implementation targets. The+implementation leaves add final source-line links when their functions land;+this contract is written before those files exist. IDs and any severity/status+called out by a leaf's Scope or Acceptance criteria are normative. Where a leaf+does not specify a severity, its implementation must choose one consistent with+the finding and cover it in that leaf's tests.++| Check id | Tier | Probe function | Owning leaf | Required severity or status | Minimum fix hint |+| ------------------------------------ | ------- | --------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| `config/parse` | static | `doctor/checks/config.rs::parse` | #492 | `error` on parse failure or corruption recovery, including `.bak` fallback. | Repair `config.toml`; review and restore a valid backup if recovery occurred. |+| `config/unknown-key` | static | `doctor/checks/config.rs::unknown_key` | #492 | `warn` per ignored key, with a did-you-mean suggestion where available. | Rename the key to the suggested supported field. |+| `config/legacy-key` | static | `doctor/checks/config.rs::legacy_key` | #492 | `info` per migrated legacy key. | Update the config to the current key name. |+| `config/env-override` | static | `doctor/checks/config.rs::env_override` | #493 | `warn` if env overrides an explicit file value; otherwise `info`. | Set the intended value in one source and remove the shadowed override. |+| `config/source` | static | `doctor/checks/config.rs::source` | #493 | `info`. | No action required; use the reported source when diagnosing precedence. |+| `config/runtime-settings` | static | `doctor/checks/runtime_settings.rs::runtime_settings` | #506 | `warn` for ignored fallback providers, incomplete model routes or delegate models, or no channel when channels are enabled. | Remove ignored settings or complete the reported configuration path. |+| `inference/provider-ref` | static | `doctor/checks/inference.rs::provider_ref` | #494 | `error` for unresolved provider references. | Select a registered provider and fix the reported config path. |+| `inference/construct` | static | `doctor/checks/inference.rs::construct` | #494 | `error` when a configured role cannot be constructed, including missing BYOK credentials. | Correct provider settings and configure its required credential. |+| `inference/temperature` | static | `doctor/checks/inference.rs::temperature` | #494 | Finding for invalid settings; severity is not specified by the leaf. | Set a supported temperature for the configured role. |+| `embeddings/config` | static | `doctor/checks/embeddings.rs::config` | #494 | Finding for invalid or inconsistent settings; severity is not specified by the leaf. | Configure a provider, model, and dimension that agree. |+| `components/referenced-but-disabled` | static | `doctor/checks/components.rs::referenced_but_disabled` | #495 | `warn` when config references a disabled component. | Enable the component or remove dependent configuration. |+| `modules/source-fallback` | static | `doctor/checks/modules.rs::source_fallback` | #495 | Leaf-defined; include the source fallback detail. | Configure the intended module source explicitly. |+| `modules/override-invalid` | static | `doctor/checks/modules.rs::override_invalid` | #495 | Leaf-defined for an invalid override. | Correct or remove the invalid module override. |+| `storage/url` | static | `doctor/checks/storage.rs::url` | #495 | `error` when the storage scheme's driver is unavailable in this build. | Use a supported URL scheme and enable its driver. |+| `workspace/action-dir` | static | `doctor/checks/workspace.rs::action_dir` | #495 | `error` when the configured action directory is not writable. | Create the directory or grant the process write access. |+| `secrets/master-key-env` | static | `doctor/checks/secrets.rs::master_key_env` | #495 | `error` when both master-key environment variables are set. | Keep only the intended master-key source configured. |+| `network/proxy` | static | `doctor/checks/network.rs::proxy` | #495 | Leaf-defined by the existing proxy validator. | Correct the proxy configuration reported by the validator. |+| `memory/root` | static | `doctor/checks/memory.rs::root` | #495 | Leaf-defined by the existing memory-root validator. | Correct the memory root path reported by the validator. |+| `profile/exists` | static | `doctor/profile.rs::exists` | #490 | `error` for a missing profile, unknown layout marker, or invalid profile config. | Select an existing profile with a supported layout and valid config. |+| `profile/provisioned` | connect | `doctor/profile.rs::provisioned` | #491 | `error` for an unprovisioned tenant profile. | Provision the tenant profile before running doctor. |+| `workspace/writable` | static | `doctor/checks/workspace.rs::writable` | #506 | `error` when the workspace write probe fails. | Grant write access to the workspace directory. |+| `workspace/layout` | static | `doctor/checks/workspace.rs::layout` | #506 | Leaf-defined for missing `memory/`, `SYSTEM.md`, or low disk space. | Create or repair the reported workspace entry or free disk space. |+| `runtime/environment` | static | `doctor/checks/runtime.rs::environment` | #506 | Leaf-defined for git, curl, shell, or home environment checks. | Install or configure the named local prerequisite. |+| `runtime/agent-sdk` | connect | `doctor/checks/runtime.rs::agent_sdk` | #506 | Leaf-defined for the Claude Agent SDK version probe. | Install or configure the agent SDK binary, then rerun doctor. |+| `memory/binding` | static | `doctor/checks/memory.rs::binding` | #498 | Leaf-defined for the selected memory binding. | Select an available memory driver. |+| `memory/health` | connect | `doctor/checks/memory.rs::health` | #498 | `error` when the bound engine is down. | Restore the memory driver's availability and rerun doctor. |+| `storage/connect` | connect | `doctor/checks/storage.rs::connect` | #498 | `error` when the read-only open fails; never migrate. | Make the configured storage reachable and retry the check. |+| `storage/layout` | connect | `doctor/checks/storage.rs::layout` | #498 | `warn` when a storage layout migration is pending. | Apply the documented migration using the normal storage upgrade path. |+| `secrets/keyring` | connect | `doctor/checks/secrets.rs::keyring` | #498 | `skipped` for a non-interactive macOS keychain probe. | Run interactively or configure an available keyring backend. |+| `embeddings/configured-model` | connect | `doctor/checks/embeddings.rs::configured_model` | #509 | Non-Ollama providers are `skipped`; probe the configured Ollama URL. | Start the configured service or correct its base URL and model. |+| `modules/<id>` | connect | `doctor/checks/modules.rs::module_status` | #499 | Failed/Unsupported=`error`; Disabled=`skipped`; Available/Ready=`pass`. | Repair or enable the named module source and verify its digest pin. |+| `mcp/<server>` | connect | `doctor/checks/mcp.rs::server_status` | #499 | `error` when a configured server fails to connect; `skipped` when `components.mcp` is disabled. | Start the server or correct its connection settings. |+| `skills/discovery` | static | `doctor/checks/skills.rs::discovery` | #499 | `warn` for a malformed skill manifest. | Repair the manifest at the reported path. |+| `skills/github-preflight` | connect | `doctor/checks/skills.rs::github_preflight` | #499 | Runs only when a skill requires it; failure severity is leaf-defined. | Resolve the reported GitHub access or repository issue. |+| `sandbox/backend` | connect | `doctor/checks/sandbox.rs::backend` | #499 | `error` when the configured Docker backend is unavailable. | Install or start Docker, or select an available sandbox backend. |+| `channels/<provider>` | connect | `doctor/checks/channels.rs::provider_health` | #500 | `error` on provider health timeout; `skipped` when its component is disabled. | Restore the channel provider connection and retry. |+| `integrations/composio` | connect | `doctor/checks/integrations.rs::composio` | #500 | `skipped` when its component is disabled; otherwise leaf-defined. | Reconnect Composio or correct its endpoint configuration. |+| `voice/stt` | connect | `doctor/checks/voice.rs::stt` | #500 | `skipped` when `components.voice` is disabled; otherwise leaf-defined. | Enable voice or configure an available speech-to-text provider. |+| `voice/tts` | connect | `doctor/checks/voice.rs::tts` | #500 | `skipped` when `components.voice` is disabled; otherwise leaf-defined. | Enable voice or configure an available text-to-speech provider. |+| `search/<provider>` | connect | `doctor/checks/search.rs::provider_status` | #500 | `warn` when provider status is `NeedsKey`; `skipped` when its component is disabled. | Configure the provider key named in the finding. |+| `wallet/status` | connect | `doctor/checks/wallet.rs::status` | #500 | `skipped` when its component is disabled; otherwise leaf-defined. | Configure the wallet safely or disable the unused wallet feature. |+| `backend/reachable` | connect | `openhuman-tinyhumans/src/doctor/backend.rs::reachable` | #496 | `error` when backend is down; dependent hosted checks are `skipped`. | Check the configured backend URL and network access. |+| `backend/credential` | connect | `openhuman-tinyhumans/src/doctor/backend.rs::credential` | #496 | `error` for an expired JWT (`SESSION_EXPIRED`). | Sign in again through the supported auth flow. |+| `backend/identity` | connect | `openhuman-tinyhumans/src/doctor/backend.rs::identity` | #496 | Healthy result passes; failure severity is leaf-defined. | Check tenant identity and access through the supported auth flow. |+| `backend/socket` | connect | `openhuman-tinyhumans/src/doctor/backend.rs::socket` | #496 | Healthy result passes; failure severity is leaf-defined. | Check backend socket availability and network policy. |+| `backend/api-url` | static | `openhuman-tinyhumans/src/doctor/backend.rs::api_url` | #496 | Healthy result passes; failure severity is leaf-defined. | Set a valid backend API URL for this profile. |+| `inference/managed-catalog` | connect | `openhuman-tinyhumans/src/doctor/inference.rs::managed_catalog` | #496 | Healthy result passes; failure severity is leaf-defined. | Check the managed inference catalog and tenant access. |+| `inference/model-in-catalog` | connect | `doctor/checks/inference.rs::model_in_catalog` | #497 | `warn` when a configured model is absent; `skipped` if provider has no `/models` route. | Select a listed model or verify provider catalog support. |+| `inference/auth-errors` | connect | `doctor/checks/inference.rs::auth_errors` | #497 | `error` per provider in the auth error snapshot. | Resolve provider authentication or access. |+| `inference/live/<role>` | live | `doctor/checks/inference_live.rs::role_completion` | #501 | `error` for a provider 401; other failures are categorized as auth/quota/unavailable. | Check the role's provider access and model configuration. |+| `embeddings/live` | live | `doctor/checks/embeddings_live.rs::embed` | #502 | `error` on embed failure or configured/actual dimension mismatch. | Check embedding access and configured vector dimensions. |+| `memory/roundtrip` | live | `doctor/checks/memory_live.rs::roundtrip` | #502 | `error` on roundtrip failure, including insufficient credits. | Check memory-driver write/fetch/delete access and billing. |++The IDs above are normative names from the leaves' Scope and Acceptance+criteria. Dynamic segments use the canonical identifier supplied by their+owner; they are safe single path segments, never arbitrary display text.+`config/temperature` appears only in #488's selector test and is a `FakeCheck`+fixture id, not a built-in inventory entry. The former daemon-state check has+no v2 id: #325 deletes it because its state file is never written.++For #491 tenant checks, `profile/provisioned` covers provision and lease+readiness, while `backend/credential`, `inference/provider-ref`, and+`storage/connect` report credential, provider-settings, and storage-scope+readiness within the forced tenant context. A tenant caller cannot use+`profile` to inspect another tenant; an authorized operator may select one.+Authorization is checked before doctor reads config or credentials.++`memory/roundtrip` uses doctor-scoped disposable content and must always forget+it, including after a fetch failure. If cleanup fails, the report names the+cleanup failure without including test content. Static checks may use bounded+temporary local write probes, but must not persist configuration or repair+application state. Connect checks may add read-only network probes but do not+make billable calls or write remote state.++## Implementation references++- Existing doctor being replaced: `crates/openhuman-core/src/doctor/`+- Existing subsystem status projection: `crates/openhuman-core/src/core/subsystem/status.rs`+- Capability ids: `crates/openhuman-core/src/platform/about_app/`+- OpenClaw reference: [structured health-check contract](https://github.com/openclaw/openclaw/blob/main/docs/cli/doctor/health-contract.md), [lint mode and selectors](https://github.com/openclaw/openclaw/blob/main/docs/cli/doctor/lint.md), and [running doctor](https://github.com/openclaw/openclaw/blob/main/docs/cli/doctor/running.md)diff --git a/llms-full.txt b/llms-full.txtindex 70feae7d0f..389920cb8f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2823,50 +2823,52 @@ This matrix comes from the default-feature compiled capability-report example. RPublic consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.-- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L370): `pub fn access(mut self, access: Access) -> Self`-- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L327): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`-- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L157): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`-- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L347): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`-- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L192): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`-- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L357): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`-- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L487): `pub fn config(mut self, config: Config) -> Self`-- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L335): `pub fn config_source(mut self, source: ConfigSource) -> Self`-- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L417): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`-- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L217): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`-- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L261): `pub fn cron_delivery( mut self, delivery: Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>, ) -> Self`-- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L275): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc<dyn crate::cron::JobKindHandler>, ) -> Self`-- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L405): `pub fn defer_services(mut self) -> Self`-- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L176): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`-- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L417): `pub fn domains(mut self, domains: DomainSet) -> Self`-- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L434): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`-- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L212): `pub fn learning(mut self, value: super::LearningSettings) -> Self`-- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L456): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`-- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L461): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`-- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L467): `pub fn listen_port(mut self, port: u16) -> Self`-- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L466): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`-- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L290): `pub fn max_agents(mut self, limit: usize) -> Self`-- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L187): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`-- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L231): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`-- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L166): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`+- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L384): `pub fn access(mut self, access: Access) -> Self`+- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L329): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`+- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L159): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`+- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L361): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`+- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L194): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`+- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L371): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`+- [`boot_mode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L349): `pub fn boot_mode(mut self, mode: CoreBootMode) -> Self`+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L501): `pub fn config(mut self, config: Config) -> Self`+- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L337): `pub fn config_source(mut self, source: ConfigSource) -> Self`+- [`configure_core_extensions`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L418): `pub fn configure_core_extensions(self, configure: impl FnOnce(&Extensions)) -> Self`+- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L430): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L219): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`+- [`cron_delivery`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L263): `pub fn cron_delivery( mut self, delivery: Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>, ) -> Self`+- [`cron_job_handler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L277): `pub fn cron_job_handler( mut self, kind: crate::cron::JobKind, handler: Arc<dyn crate::cron::JobKindHandler>, ) -> Self`+- [`defer_services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L419): `pub fn defer_services(mut self) -> Self`+- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L178): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`+- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L431): `pub fn domains(mut self, domains: DomainSet) -> Self`+- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L448): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`+- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L214): `pub fn learning(mut self, value: super::LearningSettings) -> Self`+- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L470): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`+- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L475): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`+- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L481): `pub fn listen_port(mut self, port: u16) -> Self`+- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L479): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`+- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L292): `pub fn max_agents(mut self, limit: usize) -> Self`+- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L189): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`+- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L233): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`+- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L168): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L155): `pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self`-- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L432): `pub fn post_turn_hook(mut self, hook: Arc<dyn LearningSink>) -> Self`-- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L202): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`-- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L363): `pub fn provider(mut self, provider: Provider) -> Self`-- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L171): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`-- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L207): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`-- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L446): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`-- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L389): `pub fn services(mut self, services: ServiceSet) -> Self`-- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L477): `pub fn session(mut self, session: Session) -> Self`-- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L246): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`-- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L181): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`-- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L459): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`-- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L444): `pub fn token(mut self, token: TokenSource) -> Self`-- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L426): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`-- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L439): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook<OpenHumanRunContext>>) -> Self`-- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L424): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`-- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L197): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`-- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L300): `pub fn workspace(mut self, workspace: Workspace) -> Self`-- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L314): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`+- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L445): `pub fn post_turn_hook(mut self, hook: Arc<dyn LearningSink>) -> Self`+- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L204): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`+- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L377): `pub fn provider(mut self, provider: Provider) -> Self`+- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L173): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`+- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L209): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`+- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L459): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`+- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L403): `pub fn services(mut self, services: ServiceSet) -> Self`+- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L491): `pub fn session(mut self, session: Session) -> Self`+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L248): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`+- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L183): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`+- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L472): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`+- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L458): `pub fn token(mut self, token: TokenSource) -> Self`+- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L440): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`+- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L452): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook<OpenHumanRunContext>>) -> Self`+- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L437): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`+- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L199): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`+- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L302): `pub fn workspace(mut self, workspace: Workspace) -> Self`+- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L316): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`<!-- Source: docs/gitbooks/en/developing/embed/api-index.md --># API index@@ -2911,6 +2913,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe- [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)+- [`CoreBootMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`CoreRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)@@ -3028,6 +3031,7 @@ Generate the complete local Rust API reference with `cargo doc -p openhuman-embe- [`cancellation`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`chat_surface`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)+- [`cli`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`complete`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.jsonindex ef8f2453a1..676e91bd21 100644--- a/scripts/ci/saas-ambient-baseline.json+++ b/scripts/ci/saas-ambient-baseline.json@@ -589,7 +589,7 @@},{"rule": "bare-spawn",- "path": "crates/openhuman-core/src/platform/doctor/ops.rs",+ "path": "crates/openhuman-core/src/doctor/ops.rs","line": 20,"text": "let report = tokio::task::spawn_blocking(move || doctor::run(&config_clone, memory))","occurrence": 1diff --git a/scripts/ci/storage-bypass-baseline.json b/scripts/ci/storage-bypass-baseline.jsonindex aebdf01f0d..e67eeefd59 100644--- a/scripts/ci/storage-bypass-baseline.json+++ b/scripts/ci/storage-bypass-baseline.json@@ -160,13 +160,6 @@"text": "tokio::fs::write(&file_path, audio_bytes)","occurrence": 1},- {- "rule": "json-write",- "path": "crates/openhuman-core/src/platform/doctor/core/workspace_checks.rs",- "line": 30,- "text": "match std::fs::OpenOptions::new()",- "occurrence": 1- },{"rule": "json-write","path": "crates/openhuman-core/src/platform/service/daemon_host.rs",diff --git a/scripts/mock-api/routes/integrations.mjs b/scripts/mock-api/routes/integrations.mjsindex 923eed065f..59af55233a 100644--- a/scripts/mock-api/routes/integrations.mjs+++ b/scripts/mock-api/routes/integrations.mjs@@ -226,14 +226,19 @@ export function handleIntegrations(ctx) {? parsedBody.input: [parsedBody?.input ?? ""];// Honor the OpenAI `dimensions` parameter when present (the embeddings- // client sends it for `text-embedding-3-*` models). The save-time- // verification probe validates `vector.len() == configured dims`, so the- // returned vector must match the requested size; default to 4 for callers- // that don't request a specific size.+ // client sends it for `text-embedding-3-*` models). Managed embeddings+ // don't send that parameter, so tests can set `embeddingDimensions` to the+ // managed model's fixed width. Keep the historical 4-wide default for+ // callers without either value.+ const configuredDims = Number(mockBehavior.embeddingDimensions);+ const fallbackDims =+ Number.isInteger(configuredDims) && configuredDims > 0+ ? configuredDims+ : 4;const requestedDims =Number.isInteger(parsedBody?.dimensions) && parsedBody.dimensions > 0? parsedBody.dimensions- : 4;+ : fallbackDims;const data = inputs.map((input, index) => {const text = String(input ?? "");// Keep the vector deterministic so callers that cache / comparediff --git a/tests/doctor_e2e.rs b/tests/doctor_e2e.rsnew file mode 100644index 0000000000..52da23c835--- /dev/null+++ b/tests/doctor_e2e.rs@@ -0,0 +1,685 @@+//! Doctor JSON-RPC and CLI end-to-end coverage against the shared local mock.+//!+//! The test starts its own copy of `scripts/mock-api-server.mjs` when no+//! verified loopback mock was supplied by `scripts/test-rust-with-mock.sh`.+//! This keeps the same target hermetic under the direct CI Lite coverage runner.++#[path = "support/tinyhumans_boot.rs"]+mod tinyhumans_boot;++use std::collections::BTreeMap;+use std::ffi::{OsStr, OsString};+use std::fs;+use std::net::TcpListener;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Output, Stdio};+use std::sync::OnceLock;+use std::time::{Duration, Instant};++use axum::http::header::AUTHORIZATION;+use serde_json::{json, Value};+use tempfile::TempDir;+use tokio::sync::MutexGuard;++const MOCK_TOKEN_HEADER: &str = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0";+const MOCK_TOKEN_PAYLOAD: &str = "eyJzdWIiOiJ1c2VyLTEyMyIsInVzZXJJZCI6InVzZXItMTIzIiwidGdVc2VySWQiOiJ1c2VyLTEyMyIsImV4cCI6NDEwMjQ0NDgwMH0";+const EXPIRED_TOKEN_PAYLOAD: &str =+ "eyJzdWIiOiJ1c2VyLTEyMyIsInVzZXJJZCI6InVzZXItMTIzIiwidGdVc2VySWQiOiJ1c2VyLTEyMyIsImV4cCI6MX0";+const MOCK_USER_ID: &str = "user-123";+const RPC_TOKEN: &str = "doctor-e2e-in-process-rpc-token";+const MOCK_BACKEND_PLACEHOLDER: &str = "__MOCK_BACKEND_URL__";++static RPC_AUTH_INIT: OnceLock<()> = OnceLock::new();+static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++/// A loopback server for one serialized fixture.+struct MockBackend {+ origin: String,+ child: Option<Child>,+}++impl MockBackend {+ async fn start(inherited_backend_url: Option<&str>) -> Self {+ let inherited_origin = inherited_backend_url.and_then(loopback_origin);+ if let Some(origin) = inherited_origin {+ if is_shared_mock(&origin).await {+ return Self {+ origin,+ child: None,+ };+ }+ }++ let port = TcpListener::bind("127.0.0.1:0")+ .expect("reserve a loopback mock port")+ .local_addr()+ .expect("mock listener address")+ .port();+ let script = Path::new(env!("OPENHUMAN_REPOSITORY_ROOT"))+ .join("scripts/mock-api-server.mjs")+ .canonicalize()+ .expect("shared mock server script exists");+ let child = Command::new("node")+ .arg(script)+ .arg("--port")+ .arg(port.to_string())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("start the shared Node mock (node must be on PATH)");+ let mut mock = Self {+ origin: format!("http://127.0.0.1:{port}"),+ child: Some(child),+ };+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ if is_shared_mock(&mock.origin).await {+ return mock;+ }+ if mock+ .child+ .as_mut()+ .and_then(|process| process.try_wait().ok())+ .flatten()+ .is_some()+ {+ panic!("the shared mock server exited before becoming healthy");+ }+ assert!(+ Instant::now() < deadline,+ "the shared mock did not become healthy on loopback"+ );+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }++ async fn reset(&self) {+ let response = reqwest::Client::new()+ .post(format!("{}/__admin/reset", self.origin))+ .json(&json!({}))+ .send()+ .await+ .expect("reset shared mock state");+ assert!(response.status().is_success(), "mock reset succeeded");+ }++ async fn set_behavior(&self, behavior: Value, replace: bool) {+ let response = reqwest::Client::new()+ .post(format!("{}/__admin/behavior", self.origin))+ .json(&json!({+ "behavior": behavior,+ "mode": if replace { "replace" } else { "merge" },+ }))+ .send()+ .await+ .expect("configure shared mock behavior");+ assert!(response.status().is_success(), "mock behavior accepted");+ }++ async fn request_paths(&self) -> Vec<(String, String)> {+ let body: Value = reqwest::get(format!("{}/__admin/requests", self.origin))+ .await+ .expect("read shared mock request log")+ .json()+ .await+ .expect("mock request log is JSON");+ body["data"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|row| {+ Some((+ row["method"].as_str()?.to_owned(),+ row["url"].as_str()?.split('?').next()?.to_owned(),+ ))+ })+ .collect()+ }++ async fn memory_scopes(&self) -> Vec<Value> {+ let response = reqwest::Client::new()+ .get(format!("{}/memory/scopes", self.origin))+ .bearer_auth(mock_token())+ .send()+ .await+ .expect("inspect mock memory after doctor cleanup");+ assert!(+ response.status().is_success(),+ "mock memory scopes succeeded"+ );+ let body: Value = response.json().await.expect("mock memory scopes are JSON");+ body.pointer("/data/items")+ .and_then(Value::as_array)+ .cloned()+ .expect("mock memory scopes contain an item list")+ }+}++impl Drop for MockBackend {+ fn drop(&mut self) {+ if let Some(mut process) = self.child.take() {+ let _ = process.kill();+ let _ = process.wait();+ }+ }+}++fn loopback_origin(raw: &str) -> Option<String> {+ let mut url = reqwest::Url::parse(raw).ok()?;+ if url.scheme() != "http"+ || !url.username().is_empty()+ || url.password().is_some()+ || url.query().is_some()+ || url.fragment().is_some()+ || !matches!(url.path(), "" | "/")+ || !matches!(url.host_str()?, "127.0.0.1" | "localhost" | "::1")+ {+ return None;+ }+ url.set_path("");+ Some(url.as_str().trim_end_matches('/').to_owned())+}++fn mock_token() -> String {+ format!("{MOCK_TOKEN_HEADER}.{MOCK_TOKEN_PAYLOAD}.e2e")+}++fn expired_mock_token() -> String {+ format!("{MOCK_TOKEN_HEADER}.{EXPIRED_TOKEN_PAYLOAD}.e2e")+}++async fn is_shared_mock(origin: &str) -> bool {+ let client = match reqwest::Client::builder()+ .timeout(Duration::from_secs(1))+ .build()+ {+ Ok(client) => client,+ Err(_) => return false,+ };+ let Ok(response) = client.get(format!("{origin}/__admin/health")).send().await else {+ return false;+ };+ if !response.status().is_success() {+ return false;+ }+ response+ .json::<Value>()+ .await+ .is_ok_and(|body| body["ok"] == true && body["port"].as_u64().is_some())+}++/// Removes inherited OpenHuman/backend credentials and config overrides for+/// the duration of one serialized case, then restores the parent environment.+struct IsolatedEnvironment {+ previous: Vec<(OsString, OsString)>,+ managed: Vec<OsString>,+}++impl IsolatedEnvironment {+ fn install(home: &Path, action_dir: &Path, backend_url: &str) -> Self {+ let mut previous = Vec::new();+ let mut managed = [+ "HOME",+ "USERPROFILE",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_STATE_HOME",+ "APPDATA",+ "LOCALAPPDATA",+ "BACKEND_URL",+ "VITE_BACKEND_URL",+ "OPENHUMAN_ACTION_DIR",+ "OPENHUMAN_KEYRING_BACKEND",+ ]+ .into_iter()+ .map(OsString::from)+ .collect::<Vec<_>>();+ let inherited = std::env::vars_os().collect::<Vec<_>>();+ for (key, value) in inherited {+ if is_isolated_environment_key(&key) || managed.contains(&key) {+ if !managed.contains(&key) {+ managed.push(key.clone());+ }+ previous.push((key.clone(), value));+ // SAFETY: Fixture holds ENV_LOCK from setup through Drop and+ // all test functions use Tokio's current-thread runtime. No+ // peer test task can read or mutate this process environment+ // during the mutation; the CLI child receives its own env.+ unsafe { std::env::remove_var(key) };+ }+ }++ // SAFETY: same serialized, current-thread fixture guarantee as above.+ unsafe {+ std::env::set_var("HOME", home);+ std::env::set_var("USERPROFILE", home);+ std::env::set_var("XDG_CONFIG_HOME", home.join(".config"));+ std::env::set_var("XDG_DATA_HOME", home.join(".local/share"));+ std::env::set_var("XDG_CACHE_HOME", home.join(".cache"));+ std::env::set_var("XDG_STATE_HOME", home.join(".local/state"));+ std::env::set_var("APPDATA", home.join("AppData/Roaming"));+ std::env::set_var("LOCALAPPDATA", home.join("AppData/Local"));+ std::env::set_var("BACKEND_URL", backend_url);+ std::env::set_var("VITE_BACKEND_URL", backend_url);+ std::env::set_var("OPENHUMAN_ACTION_DIR", action_dir);+ std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");+ }+ Self { previous, managed }+ }+}++fn is_isolated_environment_key(key: &OsStr) -> bool {+ let key = key.to_string_lossy();+ key == "HOME"+ || key == "USERPROFILE"+ || key.starts_with("OPENHUMAN_")+ || key.starts_with("BACKEND_")+ || key == "VITE_BACKEND_URL"+}++impl Drop for IsolatedEnvironment {+ fn drop(&mut self) {+ // SAFETY: Fixture still owns ENV_LOCK while this guard is dropped, so+ // no concurrent test task reads or mutates the process environment.+ unsafe {+ for key in &self.managed {+ std::env::remove_var(key);+ }+ for (key, value) in &self.previous {+ std::env::set_var(key, value);+ }+ }+ }+}++struct Fixture {+ _home: TempDir,+ mock: MockBackend,+ rpc_base: String,+ rpc_task: tokio::task::JoinHandle<Result<(), std::io::Error>>,+ _environment: IsolatedEnvironment,+ _environment_lock: MutexGuard<'static, ()>,+}++impl Fixture {+ async fn new(config: &str) -> Self {+ let environment_lock = ENV_LOCK.lock().await;+ let inherited_backend_url = std::env::var("BACKEND_URL").ok();+ let mock = MockBackend::start(inherited_backend_url.as_deref()).await;+ let home = tempfile::tempdir().expect("fixture home");+ let action_dir = home.path().join("action");+ fs::create_dir_all(&action_dir).expect("create fixture action directory");+ let environment = IsolatedEnvironment::install(home.path(), &action_dir, &mock.origin);+ write_profile(home.path(), MOCK_USER_ID, &mock.origin, config, true);++ tinyhumans_boot::boot();+ ensure_rpc_auth();+ mock.reset().await;+ mock.set_behavior(healthy_mock_behavior(), true).await;++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind in-process JSON-RPC listener");+ let address = listener.local_addr().expect("RPC listener address");+ let router = openhuman_rpc::server::build_core_http_router(false);+ let rpc_task = tokio::spawn(async move { axum::serve(listener, router).await });++ Self {+ _home: home,+ mock,+ rpc_base: format!("http://{address}"),+ rpc_task,+ _environment: environment,+ _environment_lock: environment_lock,+ }+ }++ async fn report(&self, params: Value) -> Value {+ let before = snapshot_tree(self._home.path());+ let response = reqwest::Client::new()+ .post(format!("{}/rpc", self.rpc_base))+ .header(AUTHORIZATION, format!("Bearer {RPC_TOKEN}"))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "openhuman.doctor_report",+ "params": params,+ }))+ .send()+ .await+ .expect("call doctor JSON-RPC");+ assert!(+ response.status().is_success(),+ "doctor RPC transport status"+ );+ let envelope: Value = response.json().await.expect("doctor RPC JSON");+ assert!(envelope.get("error").is_none(), "doctor RPC succeeded");+ let result = envelope+ .get("result")+ .unwrap_or_else(|| panic!("doctor RPC has result: {envelope}"));+ let report = if result.get("logs").is_some() {+ result+ .get("result")+ .unwrap_or_else(|| panic!("doctor outcome has report: {result}"))+ } else {+ result+ }+ .clone();+ let serialized = serde_json::to_string(&report).expect("serialize doctor report");+ assert!(+ !serialized.contains(&mock_token()),+ "the report does not contain the synthetic session token"+ );+ assert_unchanged(&before, &snapshot_tree(self._home.path()));+ report+ }++ async fn models(&self, params: Value) -> Value {+ let before = snapshot_tree(self._home.path());+ let response = reqwest::Client::new()+ .post(format!("{}/rpc", self.rpc_base))+ .header(AUTHORIZATION, format!("Bearer {RPC_TOKEN}"))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "openhuman.doctor_models",+ "params": params,+ }))+ .send()+ .await+ .expect("call doctor models JSON-RPC");+ assert!(+ response.status().is_success(),+ "doctor models transport status"+ );+ let envelope: Value = response.json().await.expect("doctor models JSON");+ assert!(+ envelope.get("error").is_none(),+ "doctor models RPC succeeded"+ );+ let result = envelope+ .get("result")+ .unwrap_or_else(|| panic!("doctor models RPC has result: {envelope}"));+ let models = if result.get("logs").is_some() {+ result+ .get("result")+ .unwrap_or_else(|| panic!("doctor models outcome has report: {result}"))+ } else {+ result+ }+ .clone();+ assert!(+ !serde_json::to_string(&models)+ .expect("serialize doctor models report")+ .contains(&mock_token()),+ "the report does not contain the synthetic session token"+ );+ assert_unchanged(&before, &snapshot_tree(self._home.path()));+ models+ }++ fn run_cli(&self, args: &[&str]) -> Output {+ let mut command = Command::new(env!("CARGO_BIN_EXE_openhuman-core"));+ command+ .args(args)+ .current_dir(self._home.path())+ .env_clear()+ .env("HOME", self._home.path())+ .env("USERPROFILE", self._home.path())+ .env("BACKEND_URL", &self.mock.origin)+ .env("VITE_BACKEND_URL", &self.mock.origin)+ .env("OPENHUMAN_ACTION_DIR", self._home.path().join("action"))+ .env("OPENHUMAN_KEYRING_BACKEND", "file");++ for name in ["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP", "TMPDIR"] {+ if let Some(value) = std::env::var_os(name) {+ command.env(name, value);+ }+ }+ command.output().expect("run openhuman-core doctor CLI")+ }+}++impl Drop for Fixture {+ fn drop(&mut self) {+ self.rpc_task.abort();+ }+}++fn healthy_mock_behavior() -> Value {+ json!({+ "httpFaultRules": serde_json::to_string(&json!([+ {"method": "GET", "path": "/", "status": 200, "body": {"status": "ok"}}+ ])).expect("encode mock health response"),+ "llmStreamScript": serde_json::to_string(&json!([+ {"text": "OK"},+ {"finish": "stop"}+ ])).expect("encode mock completion script"),+ })+}++fn write_profile(home: &Path, profile_id: &str, backend_url: &str, config: &str, activate: bool) {+ let root = home.join(".openhuman");+ let profile_dir = root.join("users").join(profile_id);+ let files_dir = profile_dir.join("files");+ let sandbox_dir = profile_dir.join("sandbox");+ fs::create_dir_all(&files_dir).expect("create profile files directory");+ fs::create_dir_all(&sandbox_dir).expect("create profile sandbox directory");+ if activate {+ fs::write(+ root.join("active_user.toml"),+ format!("user_id = \"{profile_id}\"\n"),+ )+ .expect("write active user fixture");+ }+ fs::write(profile_dir.join(".layout"), "2\n").expect("mark profile layout v2");++ let content = config.replace(MOCK_BACKEND_PLACEHOLDER, backend_url);+ fs::write(profile_dir.join("config.toml"), content).expect("write doctor config fixture");+ let auth_profiles = json!({+ "schema_version": 1,+ "active_profiles": {"app-session": "app-session:default"},+ "profiles": {+ "app-session:default": {+ "provider": "app-session",+ "profile_name": "default",+ "kind": "token",+ "token": mock_token(),+ "metadata": {"user_id": MOCK_USER_ID},+ "created_at": "2025-01-01T00:00:00Z",+ "updated_at": "2025-01-01T00:00:00Z"+ }+ }+ });+ fs::write(+ profile_dir.join("auth-profiles.json"),+ serde_json::to_vec(&auth_profiles).expect("serialize synthetic auth profile"),+ )+ .expect("write synthetic auth profile");+}++fn write_expired_session(home: &Path) {+ let path = home+ .join(".openhuman/users")+ .join(MOCK_USER_ID)+ .join("auth-profiles.json");+ let mut profiles: Value =+ serde_json::from_slice(&fs::read(&path).expect("read synthetic auth profile"))+ .expect("synthetic auth profile is JSON");+ profiles["profiles"]["app-session:default"]["token"] = json!(expired_mock_token());+ profiles["profiles"]["app-session:default"]["metadata"]["session_expires_at"] =+ json!("2000-01-01T00:00:00Z");+ fs::write(+ path,+ serde_json::to_vec(&profiles).expect("serialize expired auth profile"),+ )+ .expect("write expired synthetic auth profile");+}++async fn assert_expired_session_is_seeded(home: &Path) {+ let before = snapshot_tree(home);+ let config = openhuman_core::doctor::profile::resolve_desktop_profile_for_doctor(+ &home.join(".openhuman"),+ Some(MOCK_USER_ID),+ )+ .await+ .expect("resolve isolated doctor profile read-only")+ .config;+ let profile =+ openhuman_core::security::credentials::session_support::load_app_session_profile_read_only(+ &config,+ )+ .expect("read session profile without mutation")+ .expect("synthetic session profile exists");+ let token = openhuman_core::security::credentials::session_support::session_token_from_profile(+ Some(&profile),+ )+ .expect("session profile carries a token");+ let now = chrono::Utc::now();+ assert!(+ openhuman_core::security::credentials::jwt::decode_jwt_exp(&token)+ .expect("synthetic JWT has an expiration")+ < now,+ "fixture JWT itself is expired"+ );+ assert_eq!(+ openhuman_core::security::credentials::session_support::classify_session_token(+ Some(&profile),+ now,+ ),+ openhuman_core::security::credentials::session_support::SessionTokenCheck::Expired,+ "the read-only session classifier sees an expired profile before doctor runs"+ );+ assert_unchanged(&before, &snapshot_tree(home));+}++fn snapshot_tree(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {+ fn visit(root: &Path, current: &Path, snapshot: &mut BTreeMap<PathBuf, Vec<u8>>) {+ let Ok(entries) = fs::read_dir(current) else {+ return;+ };+ let mut entries = entries+ .map(|entry| entry.expect("read fixture directory entry").path())+ .collect::<Vec<_>>();+ entries.sort();+ for path in entries {+ let relative = path+ .strip_prefix(root)+ .expect("path remains under fixture root");+ let metadata = fs::symlink_metadata(&path).expect("fixture path metadata");+ if metadata.file_type().is_symlink() {+ let target = fs::read_link(&path).expect("read fixture symlink");+ snapshot.insert(+ relative.to_path_buf(),+ target.as_os_str().as_encoded_bytes().to_vec(),+ );+ } else if metadata.is_dir() {+ snapshot.insert(relative.to_path_buf(), b"directory".to_vec());+ visit(root, &path, snapshot);+ } else {+ snapshot.insert(+ relative.to_path_buf(),+ fs::read(path).expect("read fixture file"),+ );+ }+ }+ }++ let mut snapshot = BTreeMap::new();+ visit(root, root, &mut snapshot);+ snapshot+}++fn assert_unchanged(before: &BTreeMap<PathBuf, Vec<u8>>, after: &BTreeMap<PathBuf, Vec<u8>>) {+ if before != after {+ let changed = before+ .keys()+ .chain(after.keys())+ .collect::<std::collections::BTreeSet<_>>()+ .into_iter()+ .filter(|path| before.get(*path) != after.get(*path))+ .cloned()+ .collect::<Vec<_>>();+ panic!("doctor changed fixture files: {changed:?}");+ }+}++fn finding<'a>(report: &'a Value, check_id: &str) -> &'a Value {+ report["findings"]+ .as_array()+ .into_iter()+ .flatten()+ .find(|finding| finding["check_id"] == check_id)+ .unwrap_or_else(|| panic!("doctor report includes {check_id}"))+}++fn assert_finding(report: &Value, check_id: &str, severity: &str) {+ let selected = finding(report, check_id);+ assert_eq!(+ selected["severity"],+ severity,+ "{check_id}: {}",+ selected["message"]+ .as_str()+ .unwrap_or("<no safe finding message>")+ );+}++fn fixture(name: &str) -> &'static str {+ match name {+ "healthy" => include_str!("fixtures/doctor/healthy.toml"),+ "unknown-key" => include_str!("fixtures/doctor/unknown-key.toml"),+ "unknown-provider" => include_str!("fixtures/doctor/unknown-provider.toml"),+ "byok-no-key" => include_str!("fixtures/doctor/byok-no-key.toml"),+ "disabled-component-reference" => {+ include_str!("fixtures/doctor/disabled-component-reference.toml")+ }+ "storage-missing-driver" => {+ include_str!("fixtures/doctor/storage-missing-driver.toml")+ }+ _ => panic!("unknown doctor fixture"),+ }+}++async fn fixture_named(name: &str) -> Fixture {+ Fixture::new(fixture(name)).await+}++fn assert_cli_report(output: &Output, expected_code: i32, check_id: Option<&str>) -> Value {+ assert_eq!(+ output.status.code(),+ Some(expected_code),+ "doctor CLI exit code; stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let report: Value = serde_json::from_slice(&output.stdout)+ .unwrap_or_else(|error| panic!("doctor CLI stdout is JSON ({error})"));+ assert_eq!(report["schema_version"], 2);+ if let Some(check_id) = check_id {+ assert!(report["findings"]+ .as_array()+ .unwrap()+ .iter()+ .any(|item| { item["check_id"] == check_id }));+ }+ report+}++fn ensure_rpc_auth() {+ RPC_AUTH_INIT.get_or_init(|| {+ openhuman_core::core::auth::init_rpc_token_with_value(RPC_TOKEN)+ .expect("initialize in-memory RPC bearer for doctor E2E");+ });+}++#[tokio::test(flavor = "current_thread")]+async fn models_rpc_inspects_the_selected_profile_without_writing_it() {+ let fixture = fixture_named("healthy").await;+ let models = fixture.models(json!({ "use_cache": false })).await;+ assert!(models["summary"].is_object());+ assert!(models["entries"].is_array());+}++#[path = "doctor_e2e/cases.rs"]+mod cases;diff --git a/tests/doctor_e2e/cases.rs b/tests/doctor_e2e/cases.rsnew file mode 100644index 0000000000..9bedd4817b--- /dev/null+++ b/tests/doctor_e2e/cases.rs@@ -0,0 +1,388 @@+use super::*;++#[tokio::test(flavor = "current_thread")]+async fn healthy_report_is_v2_and_does_not_write_profile_state() {+ let fixture = fixture_named("healthy").await;+ let report = fixture.report(json!({"tier": "static"})).await;++ assert_eq!(report["schema_version"], 2);+ assert_eq!(report["ok"], true);+ assert_eq!(report["summary"]["error"], 0);+ assert_eq!(report["tier"], "static");++ let product_requests = fixture+ .mock+ .request_paths()+ .await+ .into_iter()+ .filter(|(_, path)| path != "/" && !path.starts_with("/__admin/"))+ .collect::<Vec<_>>();+ assert!(+ product_requests.is_empty(),+ "static doctor made no product backend requests: {product_requests:?}"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn unknown_config_key_reports_its_stable_check_id() {+ let fixture = fixture_named("unknown-key").await;+ let report = fixture+ .report(json!({"tier": "static", "only": ["config/unknown-key"]}))+ .await;++ assert_finding(&report, "config/unknown-key", "warn");+}++#[tokio::test(flavor = "current_thread")]+async fn unknown_provider_reports_its_stable_check_id() {+ let fixture = fixture_named("unknown-provider").await;+ let report = fixture+ .report(json!({"tier": "static", "only": ["inference/provider-ref"]}))+ .await;++ assert_finding(&report, "inference/provider-ref", "error");+}++#[tokio::test(flavor = "current_thread")]+async fn byok_provider_without_a_key_reports_construction_failure() {+ let fixture = fixture_named("byok-no-key").await;+ let report = fixture+ .report(json!({"tier": "static", "only": ["inference/construct"]}))+ .await;++ assert_finding(&report, "inference/construct", "error");+}++#[tokio::test(flavor = "current_thread")]+async fn unavailable_backend_reports_reachability_failure() {+ let fixture = fixture_named("healthy").await;+ fixture+ .mock+ .set_behavior(+ json!({+ "httpFaultRules": serde_json::to_string(&json!([+ {"method": "GET", "path": "/", "status": 503, "body": {"error": "offline"}}+ ])).unwrap()+ }),+ true,+ )+ .await;+ let report = fixture+ .report(json!({"tier": "connect", "only": ["backend/reachable"]}))+ .await;++ assert_finding(&report, "backend/reachable", "error");+}++#[tokio::test(flavor = "current_thread")]+async fn expired_jwt_reports_credential_failure() {+ let fixture = fixture_named("healthy").await;+ write_expired_session(fixture._home.path());+ assert_expired_session_is_seeded(fixture._home.path()).await;+ let report = fixture+ .report(json!({"tier": "connect", "only": ["backend/credential"]}))+ .await;++ assert_finding(&report, "backend/credential", "error");+}++#[tokio::test(flavor = "current_thread")]+async fn disabled_memory_with_a_cortexdb_reference_is_reported() {+ let fixture = fixture_named("disabled-component-reference").await;+ let report = fixture+ .report(json!({+ "tier": "static",+ "only": ["components/referenced-but-disabled"]+ }))+ .await;++ assert_finding(&report, "components/referenced-but-disabled", "warn");+}++#[tokio::test(flavor = "current_thread")]+async fn mongodb_storage_url_reports_the_unavailable_driver() {+ let fixture = fixture_named("storage-missing-driver").await;+ let report = fixture+ .report(json!({"tier": "static", "only": ["storage/url"]}))+ .await;++ assert_finding(&report, "storage/url", "error");+}++#[tokio::test(flavor = "current_thread")]+async fn missing_profile_is_a_reported_rpc_finding_without_creating_it() {+ let fixture = fixture_named("healthy").await;+ let missing = fixture._home.path().join(".openhuman/users/doctor-missing");+ let report = fixture+ .report(json!({+ "tier": "static",+ "only": ["profile/exists"],+ "profile": "doctor-missing"+ }))+ .await;++ assert_finding(&report, "profile/exists", "error");+ assert!(+ !missing.exists(),+ "profile inspection does not create a profile"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn cli_explicit_valid_profile_uses_its_config_without_activating_or_writing_it() {+ const ALTERNATE_PROFILE: &str = "doctor-alternate";+ let healthy_fixture = fixture_named("healthy").await;+ let root = healthy_fixture._home.path().join(".openhuman");+ let active_user_path = root.join("active_user.toml");+ let active_user_before = fs::read_to_string(&active_user_path).expect("active user fixture");+ let alternate_dir = root.join("users").join(ALTERNATE_PROFILE);+ write_profile(+ healthy_fixture._home.path(),+ ALTERNATE_PROFILE,+ &healthy_fixture.mock.origin,+ fixture("unknown-key"),+ false,+ );+ let before = snapshot_tree(healthy_fixture._home.path());++ let output = healthy_fixture.run_cli(&[+ "doctor",+ "--lint",+ "--json",+ "--severity-min",+ "warn",+ "--only",+ "config/unknown-key",+ "--profile",+ ALTERNATE_PROFILE,+ ]);+ let report = assert_cli_report(&output, 1, Some("config/unknown-key"));++ assert_eq!(report["profile"], ALTERNATE_PROFILE);+ assert_eq!(report["config_source"], "profile");+ assert_eq!(report["config_resolution_source"], "--profile");+ assert_eq!(report["profile_layout_version"], 2);+ let unknown_key = finding(&report, "config/unknown-key");+ assert_eq!(unknown_key["severity"], "warn");+ assert_eq!(unknown_key["config_path"], "memroy");+ assert!(unknown_key["message"]+ .as_str()+ .is_some_and(|message| message.contains("memroy")));++ assert_eq!(+ fs::read_to_string(&active_user_path).expect("active user remains readable"),+ active_user_before,+ "explicit profile inspection does not activate the alternate profile"+ );+ assert!(alternate_dir.is_dir(), "selected profile remains present");+ assert_unchanged(&before, &snapshot_tree(healthy_fixture._home.path()));++ let legacy_output = healthy_fixture.run_cli(&[+ "doctor",+ "report",+ "--tier",+ "static",+ "--only",+ r#"["config/unknown-key"]"#,+ "--profile",+ ALTERNATE_PROFILE,+ ]);+ assert_eq!(legacy_output.status.code(), Some(0));+ let legacy: Value = serde_json::from_slice(&legacy_output.stdout)+ .expect("legacy report keeps its JSON outcome shape");+ assert_eq!(legacy["result"]["profile"], ALTERNATE_PROFILE);+ assert_eq!(legacy["result"]["config_resolution_source"], "--profile");+ assert_eq!(legacy["result"]["findings"][0]["config_path"], "memroy");+ assert_unchanged(&before, &snapshot_tree(healthy_fixture._home.path()));+}++#[tokio::test(flavor = "current_thread")]+async fn legacy_doctor_report_and_models_keep_json_without_boot_storage_writes() {+ let fixture = fixture_named("healthy").await;+ let home = fixture._home.path();+ let config_path = home+ .join(".openhuman/users")+ .join(MOCK_USER_ID)+ .join("config.toml");+ let mut config: toml::Value =+ toml::from_str(&fs::read_to_string(&config_path).expect("active profile config"))+ .expect("valid healthy config fixture");+ let storage_path = home.join("legacy-doctor-storage");+ config+ .get_mut("storage")+ .and_then(toml::Value::as_table_mut)+ .expect("fixture has a storage table")+ .insert(+ "url".into(),+ toml::Value::String(format!("sqlite:{}", storage_path.display())),+ );+ fs::write(+ &config_path,+ toml::to_string(&config).expect("serialize config"),+ )+ .expect("point legacy CLI fixture at a file-backed storage URL");+ let before = snapshot_tree(home);++ let report_output = fixture.run_cli(&[+ "doctor",+ "report",+ "--tier",+ "static",+ "--only",+ r#"["config/parse"]"#,+ ]);+ assert_eq!(report_output.status.code(), Some(0));+ let report: Value =+ serde_json::from_slice(&report_output.stdout).expect("legacy report remains raw JSON");+ assert!(+ report["logs"].is_array(),+ "report keeps its legacy outcome envelope"+ );+ assert_eq!(report["result"]["tier"], "static");+ assert!(report["result"]["checks_run"]+ .as_array()+ .is_some_and(|checks| checks.iter().any(|check| check == "config/parse")));+ assert_unchanged(&before, &snapshot_tree(home));++ let models_output = fixture.run_cli(&["doctor", "models", "--use-cache", "false"]);+ assert_eq!(models_output.status.code(), Some(0));+ let models: Value =+ serde_json::from_slice(&models_output.stdout).expect("legacy models remains raw JSON");+ assert!(models["summary"].is_object());+ assert!(models["entries"].is_array());+ assert_unchanged(&before, &snapshot_tree(home));+ assert!(+ !storage_path.exists(),+ "legacy inspection must not create the configured session database"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn legacy_doctor_function_help_stays_on_the_existing_namespace_printer() {+ let fixture = fixture_named("healthy").await;+ let before = snapshot_tree(fixture._home.path());++ let report_help = fixture.run_cli(&["doctor", "report", "--help"]);+ assert_eq!(report_help.status.code(), Some(0));+ assert!(String::from_utf8_lossy(&report_help.stdout).contains("--tier"));++ let models_help = fixture.run_cli(&["doctor", "models", "--help"]);+ assert_eq!(models_help.status.code(), Some(0));+ assert!(String::from_utf8_lossy(&models_help.stdout).contains("--use_cache"));+ assert_unchanged(&before, &snapshot_tree(fixture._home.path()));+}++#[tokio::test(flavor = "current_thread")]+async fn connect_tier_skips_billable_live_probes() {+ let fixture = fixture_named("healthy").await;+ let report = fixture.report(json!({"tier": "connect"})).await;+ assert_eq!(report["schema_version"], 2);+ assert_eq!(report["tier"], "connect");+ assert_eq!(+ report["summary"]["error"], 0,+ "healthy Connect checks should not fail: {:?}",+ report["findings"]+ );+ assert_eq!(report["ok"], true, "healthy Connect report should pass");+ for check_id in ["inference/live/chat", "embeddings/live", "memory/roundtrip"] {+ assert_finding(&report, check_id, "skipped");+ }++ let billable = fixture+ .mock+ .request_paths()+ .await+ .into_iter()+ .filter(|(method, path)| {+ method == "POST"+ && matches!(+ path.as_str(),+ "/openai/v1/chat/completions"+ | "/openai/v1/embeddings"+ | "/memory/experience"+ | "/memory/recall"+ | "/memory/answer"+ )+ })+ .collect::<Vec<_>>();+ assert!(+ billable.is_empty(),+ "connect tier made no billable requests"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn live_completion_embedding_and_memory_roundtrip_pass_and_clean_up() {+ let fixture = fixture_named("healthy").await;+ let mut behavior = healthy_mock_behavior();+ behavior["embeddingDimensions"] = json!(1024);+ fixture.mock.set_behavior(behavior, false).await;+ let report = fixture+ .report(json!({+ "tier": "live",+ "only": [+ "inference/live/chat",+ "embeddings/live",+ "memory/roundtrip"+ ]+ }))+ .await;++ for check_id in ["inference/live/chat", "embeddings/live", "memory/roundtrip"] {+ assert_finding(&report, check_id, "pass");+ }+ let paths = fixture.mock.request_paths().await;+ for expected in [+ ("POST", "/openai/v1/chat/completions"),+ ("POST", "/openai/v1/embeddings"),+ ("POST", "/memory/experience"),+ ("POST", "/memory/recall"),+ ("GET", "/memory/events"),+ ("POST", "/memory/forget"),+ ] {+ assert!(+ paths+ .iter()+ .any(|(method, path)| { method == expected.0 && path == expected.1 }),+ "live doctor made the expected local mock request"+ );+ }+ assert!(+ fixture.mock.memory_scopes().await.is_empty(),+ "live memory probe leaves no scratch scope"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn cli_lint_uses_report_threshold_and_argument_error_exit_codes() {+ let fixture = fixture_named("healthy").await;+ let before = snapshot_tree(fixture._home.path());+ let healthy = fixture.run_cli(&["doctor", "--lint", "--json", "--only", "config/parse"]);+ let report = assert_cli_report(&healthy, 0, Some("config/parse"));+ assert_eq!(report["ok"], true);++ let missing_profile = fixture.run_cli(&[+ "doctor",+ "--lint",+ "--json",+ "--only",+ "profile/exists",+ "--profile",+ "doctor-missing",+ ]);+ assert_cli_report(&missing_profile, 1, Some("profile/exists"));+ assert!(+ !fixture+ ._home+ .path()+ .join(".openhuman/users/doctor-missing")+ .exists(),+ "CLI profile inspection does not create a profile"+ );++ let invalid_arguments = fixture.run_cli(&["doctor", "--lint", "--severity-min", "pass"]);+ assert_eq!(invalid_arguments.status.code(), Some(2));+ assert!(String::from_utf8_lossy(&invalid_arguments.stderr)+ .contains("invalid value for --severity-min"));+ assert_unchanged(&before, &snapshot_tree(fixture._home.path()));+}diff --git a/tests/fixtures/doctor/byok-no-key.toml b/tests/fixtures/doctor/byok-no-key.tomlnew file mode 100644index 0000000000..d81827dfeb--- /dev/null+++ b/tests/fixtures/doctor/byok-no-key.toml@@ -0,0 +1,17 @@+api_url = "__MOCK_BACKEND_URL__"+default_model = "gpt-4o-mini"+default_temperature = 0.2+chat_provider = "openai:gpt-4o-mini"++[secrets]+encrypt = false++[[cloud_providers]]+id = "p_doctor_openai"+slug = "openai"+label = "OpenAI"+endpoint = "https://example.invalid/v1"+auth_style = "bearer"++[storage]+url = "memory"diff --git a/tests/fixtures/doctor/disabled-component-reference.toml b/tests/fixtures/doctor/disabled-component-reference.tomlnew file mode 100644index 0000000000..5dac4a690e--- /dev/null+++ b/tests/fixtures/doctor/disabled-component-reference.toml@@ -0,0 +1,15 @@+api_url = "__MOCK_BACKEND_URL__"+default_model = "e2e-mock-model"+default_temperature = 0.2++[secrets]+encrypt = false++[components]+memory = false++[memory]+engine = "cortexdb"++[storage]+url = "memory"diff --git a/tests/fixtures/doctor/healthy.toml b/tests/fixtures/doctor/healthy.tomlnew file mode 100644index 0000000000..407cc41a1d--- /dev/null+++ b/tests/fixtures/doctor/healthy.toml@@ -0,0 +1,19 @@+api_url = "__MOCK_BACKEND_URL__"+default_model = "e2e-mock-model"+default_temperature = 0.2+chat_onboarding_completed = true++[secrets]+encrypt = false++[local_ai]+enabled = false++[memory]+engine = "tinyhumans"+embedding_provider = "cloud"+embedding_model = "embedding-v1"+embedding_dimensions = 1024++[storage]+url = "memory"diff --git a/tests/fixtures/doctor/storage-missing-driver.toml b/tests/fixtures/doctor/storage-missing-driver.tomlnew file mode 100644index 0000000000..18997e8cba--- /dev/null+++ b/tests/fixtures/doctor/storage-missing-driver.toml@@ -0,0 +1,9 @@+api_url = "__MOCK_BACKEND_URL__"+default_model = "e2e-mock-model"+default_temperature = 0.2++[secrets]+encrypt = false++[storage]+url = "mongodb://127.0.0.1/doctor"diff --git a/tests/fixtures/doctor/unknown-key.toml b/tests/fixtures/doctor/unknown-key.tomlnew file mode 100644index 0000000000..a853e98358--- /dev/null+++ b/tests/fixtures/doctor/unknown-key.toml@@ -0,0 +1,10 @@+api_url = "__MOCK_BACKEND_URL__"+default_model = "e2e-mock-model"+default_temperature = 0.2+memroy = true++[secrets]+encrypt = false++[storage]+url = "memory"diff --git a/tests/fixtures/doctor/unknown-provider.toml b/tests/fixtures/doctor/unknown-provider.tomlnew file mode 100644index 0000000000..76027262b4--- /dev/null+++ b/tests/fixtures/doctor/unknown-provider.toml@@ -0,0 +1,10 @@+api_url = "__MOCK_BACKEND_URL__"+default_model = "e2e-mock-model"+default_temperature = 0.2+chat_provider = "nope"++[secrets]+encrypt = false++[storage]+url = "memory"diff --git a/tests/in_process/agent_turn_overrides_e2e.rs b/tests/in_process/agent_turn_overrides_e2e.rsindex 994960a4a7..5383d53ac2 100644--- a/tests/in_process/agent_turn_overrides_e2e.rs+++ b/tests/in_process/agent_turn_overrides_e2e.rs@@ -223,7 +223,7 @@ async fn seed_goal(objective: &str,) -> Result<(), String> {let store = openhuman_core::storage::sessions::stores_or_ephemeral(workspace).kv;- tinyagents_graph::goals::store::set(&store, thread_id, objective, None)+ tinyagents_harness_tools::goals::store::set(&store, thread_id, objective, None).await.map(|_| ()).map_err(|error| error.to_string())diff --git a/tests/raw_coverage/host_extension_rpc_e2e.rs b/tests/raw_coverage/host_extension_rpc_e2e.rsindex 8f7950404e..346a73ab6d 100644--- a/tests/raw_coverage/host_extension_rpc_e2e.rs+++ b/tests/raw_coverage/host_extension_rpc_e2e.rs@@ -1,71 +1,27 @@-//! Raw integration coverage for the erased host-extension seam #5841 created.+//! Raw integration coverage for the public host-owned tool-pack binding API.//!-//! #5841 moved the `Tool` vocabulary into the shared `tinytools` crate. Two-//! trait methods named host-only types and could not go with it, so they now-//! ride `Tool::host_extension` / `Tool::host_call_extension` as-//! `dyn Any`, read back through typed free functions in-//! `openhuman::tools::traits`.-//!-//! That trade is invisible to the compiler in one direction. A producer that-//! stores a different concrete type still builds; the `downcast_ref` in the-//! reader simply returns `None`, and every consumer treats `None` as "this-//! tool has no such context".-//!-//! Every assertion that existed on this seam — in the e2e lane-//! (`tools_approval_channels_raw_coverage_e2e.rs`) and in the unit lane-//! (`tools/traits_tests.rs`) — asserts `is_none()`. The failure mode and the-//! only tested state were the same value. These tests assert the `Some` side.+//! The TinyAgents tool's generic `ToolCallBinding` extension intentionally no+//! longer exposes its private registry handle. OpenHuman therefore retains the+//! handle returned by `append_pack_tools` and binds it to the session registry.use std::sync::Arc;use serde_json::json;-use openhuman_core::tools::host_extensions::pack_registry_handle;-use openhuman_core::tools::toolpacks::registry::{CATALOG, PACKS};-use tinyagents_harness::tool::packs::{PackRegistryHandle, UseSkillTool};+use openhuman_core::tools::toolpacks::registry::PACKS;+use openhuman_core::tools::toolpacks::{append_pack_tools, bind_pack_registry};use tinytools::Tool;-/// A production pack tool's registry handle survives the round trip through-/// `dyn Any` **as the same handle**, not merely as some handle.-///-/// `UseSkillTool` is the only real producer in the tree. If its-/// `host_extension` ever stored something other than a `PackRegistryHandle`,-/// this is the only place that would notice: `toolpacks::ops` reads the handle-/// back through the same free function and, on `None`, silently skips the pack-/// registry rather than failing.-///-/// `is_some()` alone is too weak to catch the interesting half of that. A-/// producer that handed back a *different* `PackRegistryHandle` — a fresh-/// `default()`, or a second instance — satisfies `is_some()` while-/// `toolpacks::ops` reads an unbound registry and skips the pack exactly as if-/// the downcast had failed. `PackRegistryHandle` is `Clone + Default` with a-/// private `Arc<OnceLock<_>>` and no `PartialEq`, so identity is not directly-/// comparable; it is observable, because two handles share one `OnceLock` only-/// if they are the same handle. So bind through the **recovered** handle and-/// observe the effect on the **tool**, which reads its own.-///-/// `render_pack` distinguishes the two states by message, which is what makes-/// this a real discriminator rather than a smoke test:-///-/// * handle unbound ⇒ "The skill registry is not available in this session"-/// * handle bound, registry empty ⇒ "Skill `…` has no tools available"-///-/// An empty registry is deliberate: the second message proves the binding was-/// observed without needing to construct a real packed tool.#[tokio::test]-async fn a_pack_tools_registry_handle_reads_back_as_the_same_handle() {- let tool = UseSkillTool::new(PackRegistryHandle::default(), CATALOG);-- let recovered = pack_registry_handle(&tool).expect(- "a pack tool must yield its PackRegistryHandle through the erased \- host extension; None here is the silent-downcast failure that makes \- toolpacks::ops skip the registry",- );-- // Kept alive for the whole test: the handle stores a `Weak`, so dropping- // this would make the binding unobservable and the assertion vacuous.- let registry: Arc<Vec<Box<dyn Tool>>> = Arc::new(Vec::new());- recovered.bind(Arc::downgrade(®istry));+async fn the_public_pack_builder_returns_the_handle_its_tool_uses() {+ let mut tools: Vec<Box<dyn Tool>> = Vec::new();+ let handle = append_pack_tools(&mut tools);+ let registry = Arc::new(tools);+ bind_pack_registry(&handle, ®istry);+ let tool = registry+ .iter()+ .find(|tool| tool.name() == "use_skill")+ .expect("pack tool registered");let skill = PACKS.first()@@ -80,15 +36,10 @@ async fn a_pack_tools_registry_handle_reads_back_as_the_same_handle() {assert!(!rendered.contains("registry is not available"),- "binding through the recovered handle did not reach the tool's own \- handle, so the erased extension yielded a different \- PackRegistryHandle than the one supplied — the failure `is_some()` \- cannot see. Rendered: {rendered}"+ "binding the returned handle did not reach the tool's registry: {rendered}");assert!(rendered.contains("has no tools available"),- "the tool should have got as far as walking the (empty) bound \- registry; a different message means this test is no longer \- discriminating between bound and unbound. Rendered: {rendered}"+ "the tool should have reached the bound empty registry: {rendered}");}diff --git a/tests/raw_coverage/notification_platform_e2e.rs b/tests/raw_coverage/notification_platform_e2e.rsindex 68caa21660..fc8dcf09a2 100644--- a/tests/raw_coverage/notification_platform_e2e.rs+++ b/tests/raw_coverage/notification_platform_e2e.rs@@ -23,10 +23,10 @@ use std::sync::{Arc, OnceLock};use std::time::Duration;use axum::extract::State;-use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};+use axum::http::{HeaderMap, StatusCode, header::AUTHORIZATION};use axum::routing::get;use axum::{Json, Router};-use serde_json::{json, Value};+use serde_json::{Value, json};use tempfile::tempdir;use openhuman_core::config::rpc::load_config_with_timeout;@@ -51,7 +51,8 @@ fn platform_e2e_env_lock() -> tokio::sync::MutexGuard<'static, ()> {async fn platform_e2e_env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))- .lock().await+ .lock()+ .await}const TEST_JWT: &str = "e2e-notification-platform-jwt";@@ -904,8 +905,8 @@ async fn health_snapshot_and_system_info_report_this_process() {// ── doctor ───────────────────────────────────────────────────────────────────-/// `doctor_report` returns a self-consistent diagnostics report, and `doctor_models` reports one-/// entry per registered provider.+/// `doctor_report` returns a self-consistent v2 report, and `doctor_models` returns its catalog+/// inspection result.////// Covers: `openhuman.doctor_report`, `openhuman.doctor_models`.#[tokio::test]@@ -916,77 +917,97 @@ async fn doctor_report_and_models_are_internally_consistent() {let report = post_json_rpc(&h.rpc_base, 9301, "openhuman.doctor_report", json!({})).await;let result = peel(assert_no_jsonrpc_error(&report, "doctor_report"));- let items = result- .get("items")+ assert_eq!(+ result.get("schema_version").and_then(Value::as_u64),+ Some(2),+ "doctor_report must return the v2 schema: {result}"+ );+ let findings = result+ .get("findings").and_then(Value::as_array)- .unwrap_or_else(|| panic!("doctor_report must return items: {result}"));+ .unwrap_or_else(|| panic!("doctor_report must return findings: {result}"));assert!(- !items.is_empty(),+ !findings.is_empty(),"the doctor always runs at least the config and workspace checks: {result}");- for item in items {+ for finding in findings {assert!(matches!(- item.get("severity").and_then(Value::as_str),- Some("Ok" | "Warn" | "Error")+ finding.get("severity").and_then(Value::as_str),+ Some("pass" | "info" | "warn" | "error" | "skipped")),- "every item carries one of the three severities: {item}"+ "every finding carries a v2 severity: {finding}");assert!(- item.get("category")+ finding+ .get("check_id").and_then(Value::as_str)- .map(|c| !c.is_empty())+ .map(|id| !id.is_empty()).unwrap_or(false),- "every item is attributed to a category: {item}"+ "every finding is attributed to a stable check id: {finding}");assert!(- item.get("message")+ finding+ .get("message").and_then(Value::as_str).map(|m| !m.is_empty()).unwrap_or(false),- "every item carries a human-readable message: {item}"+ "every finding carries a human-readable message: {finding}"+ );+ assert!(+ finding+ .get("fix_hint")+ .and_then(Value::as_str)+ .map(|hint| !hint.is_empty())+ .unwrap_or(false),+ "every finding carries a fix hint: {finding}");}assert!(- items+ findings.iter()- .any(|i| i.get("category").and_then(Value::as_str) == Some("config")),+ .any(|finding| finding.get("check_id").and_then(Value::as_str)+ == Some("config/semantics")),"the config check always runs: {result}");assert!(- items+ findings.iter()- .any(|i| i.get("category").and_then(Value::as_str) == Some("workspace")),+ .any(|finding| finding.get("check_id").and_then(Value::as_str)+ == Some("workspace/layout")),"the workspace check always runs: {result}");+ assert!(+ findings.iter().all(+ |finding| finding.get("check_id").and_then(Value::as_str) != Some("runtime/daemon")+ ),+ "the report must not include a check backed by an unwritten daemon state file: {result}"+ );- // The summary is derived from the items — if the tally drifts, this is what catches it.+ // The summary is derived from the findings — if the tally drifts, this catches it.let summary = result.get("summary").unwrap_or_else(|| panic!("doctor_report must return a summary: {result}"));let count_of = |severity: &str| {- items+ findings.iter()- .filter(|i| i.get("severity").and_then(Value::as_str) == Some(severity))+ .filter(|finding| finding.get("severity").and_then(Value::as_str) == Some(severity)).count() as u64};+ for severity in ["pass", "info", "warn", "error", "skipped"] {+ assert_eq!(+ summary.get(severity).and_then(Value::as_u64),+ Some(count_of(severity)),+ "summary.{severity} must equal the number of matching findings: {result}"+ );+ }assert_eq!(- summary.get("ok").and_then(Value::as_u64),- Some(count_of("Ok")),- "summary.ok must equal the number of Ok items: {result}"- );- assert_eq!(- summary.get("warnings").and_then(Value::as_u64),- Some(count_of("Warn")),- "summary.warnings must equal the number of Warn items: {result}"- );- assert_eq!(- summary.get("errors").and_then(Value::as_u64),- Some(count_of("Error")),- "summary.errors must equal the number of Error items: {result}"+ result.get("ok").and_then(Value::as_bool),+ Some(count_of("error") == 0),+ "doctor_report.ok must be false exactly when a finding is an error: {result}");- // ── models: one entry per registered inference provider, summary consistent with them.+ // ── models: a successful empty report is the honest result when no provider is configured.let models = post_json_rpc(&h.rpc_base,9302,@@ -994,48 +1015,19 @@ async fn doctor_report_and_models_are_internally_consistent() {json!({ "use_cache": false }),).await;- let result = peel(assert_no_jsonrpc_error(&models, "doctor_models"));- let entries = result- .get("entries")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("doctor_models must return entries: {result}"));- assert!(- !entries.is_empty(),- "the provider registry is never empty, and an empty target list is a hard error: {result}"+ let model_result = assert_no_jsonrpc_error(&models, "doctor_models");+ assert_eq!(+ model_result+ .get("entries")+ .and_then(Value::as_array)+ .map(Vec::len),+ Some(0));- for entry in entries {- assert!(- entry- .get("provider")- .and_then(Value::as_str)- .map(|p| !p.is_empty())- .unwrap_or(false),- "every probe entry names its provider: {entry}"- );- assert!(- matches!(- entry.get("outcome").and_then(Value::as_str),- Some("Ok" | "Skipped" | "AuthOrAccess" | "Error")- ),- "every probe entry carries a known outcome: {entry}"- );- }- let summary = result- .get("summary")- .unwrap_or_else(|| panic!("doctor_models must return a summary: {result}"));- let total: u64 = ["ok", "skipped", "auth_or_access", "errors"]- .iter()- .map(|k| {- summary- .get(*k)- .and_then(Value::as_u64)- .unwrap_or_else(|| panic!("summary must carry {k}: {result}"))- })- .sum();assert_eq!(- total,- entries.len() as u64,- "the summary buckets must add up to the number of entries: {result}"+ model_result+ .pointer("/summary/errors")+ .and_then(Value::as_u64),+ Some(0));// `use_cache` is optional and defaults to true; a non-bool must be rejected, not coerced.diff --git a/vendor/tinyagents b/vendor/tinyagentsindex f49bd62d41..eced73fff0 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit f49bd62d418bb132f934a6117f1e4c2ace278c4c+Subproject commit eced73fff096ba9f39514e6d7f587e6e34d3a63adiff --git a/vendor/tinystoragedrivers b/vendor/tinystoragedriversindex 0c6dcfce57..0b32b65c81 160000--- a/vendor/tinystoragedrivers+++ b/vendor/tinystoragedrivers@@ -1 +1 @@-Subproject commit 0c6dcfce57201fadd830431f36fd759c3baa897a+Subproject commit 0b32b65c81a3e1e32fc1c0f77e5634ce707f4161