Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(avatar): 支持 WEB 侧画像版本切换,并将手动蒸馏改为后台执行且与自动调度共用租约

xukang83d4c2d6a08e
diff --git a/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.css b/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.css
index 917caeb977..ae6a081a28 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.css
+++ b/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.css
@@ -664,22 +664,164 @@
color: #7a7a7a;
}
-.pc-iml__distill {
+.pc-iml__distill-block {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin-top: 16px;
+ padding-top: 16px;
+ border-top: 1px solid #eee;
+}
+
+.pc-iml__distill-head {
display: flex;
align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+}
+
+.pc-iml__distill-title {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ color: #191919;
+}
+
+.pc-iml__distill-badges {
+ display: flex;
gap: 8px;
- padding: 8px 12px;
+ flex-wrap: wrap;
+}
+
+.pc-iml__distill-presets {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 4px;
+}
+
+.pc-iml__distill-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ margin-top: 4px;
+}
+
+.pc-iml__profiles-block {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin-top: 16px;
+ padding-top: 16px;
+ border-top: 1px solid #eee;
+}
+
+.pc-iml__profile-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.pc-iml__profile-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 10px 12px;
border-radius: 8px;
background: #fafafa;
+ flex-wrap: wrap;
+}
+
+.pc-iml__profile-meta {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ min-width: 0;
+}
+
+.pc-iml__profile-id {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
+ color: #191919;
+ word-break: break-all;
+}
+
+.pc-iml__profile-time,
+.pc-iml__profile-source {
+ font-size: 12px;
+ color: #7a7a7a;
+}
+
+.pc-iml__profile-actions {
+ display: flex;
+ gap: 8px;
+ flex-shrink: 0;
+}
+
+.pc-iml__preview {
+ margin-top: 12px;
+ padding: 12px;
+ border-radius: 8px;
+ background: #fafafa;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.pc-iml__preview-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
}
-.pc-iml__distill-label {
+.pc-iml__preview-section {
+ margin: 4px 0 0;
+ font-size: 13px;
font-weight: 600;
+}
+
+.pc-iml__preview-body {
+ margin: 0;
+ max-height: 240px;
+ overflow: auto;
+ padding: 8px;
+ border-radius: 6px;
+ background: #fff;
+ border: 1px solid #eee;
+ font-size: 12px;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.pc-iml__icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border: none;
+ border-radius: 6px;
+ background: transparent;
+ cursor: pointer;
+ color: #7a7a7a;
+}
+
+.pc-iml__icon-btn:hover {
+ background: #eee;
color: #191919;
}
-.pc-iml__distill-value {
+.pc-iml__empty {
+ margin: 0;
+ font-size: 13px;
color: #7a7a7a;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.tsx
index 1ae7be99ee..64af20f2b9 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/ImLearningPanel.tsx
@@ -1,18 +1,16 @@
/**
* PersonalContextImLearningPanel — 「IM 学习」子页(数字分身学习配置面)。
*
- * 三区块(对齐迁移方案 §4.5):
+ * 区块:
* 1. 状态卡:host_active/running/enabled 徽标 + 总闸联动提示 + fetch 指标 +
- * backfill 每目标三态(pending/truncated/complete)+ index 推进 + last_error +
- * 「立即学习一轮」。运行中 5s 轮询,未运行降频 30s(方案 D8)。
- * 2. 学习范围:渠道下拉 → im.hosting.discover 会话选择器(已在白名单的打
- * 「学习中」标记,前端按三元组 diff)+ 批量粘贴 external_id +
- * 时间范围 preset(近 30/90/180/365 天/不限 ↔ since_ms,非 preset 回显「自定义」)。
- * 3. 周期设置:fetch_interval_seconds / fetch_top_n;distill 只读降级展示(装配缺失)。
+ * backfill 每目标三态 + index 推进 + last_error +「立即学习一轮」。
+ * 2. 学习范围:会话白名单 + 时间范围 preset。
+ * 3. 周期设置:仅 fetch_interval_seconds / fetch_top_n(IM 学习)。
+ * 4. 画像蒸馏(同级卡):档位+秒数 / 立即蒸馏 / 画像版本;走 distill.* / profiles.*。
*
- * 交互:本地草稿 + imLearningConfig 语义签名脏检查(title 不参与)→
- * 「保存学习配置」走 runtime.patch_config {im_learning} 整节提交;
- * 移除会话仅停止新增采集,已学语料保留(文案如实传达)。
+ * 交互:本地草稿 + imLearningConfig 语义签名脏检查 →「保存学习配置」走
+ * runtime.patch_config {im_learning};蒸馏独立 dirty(只比 interval)→
+ * distill.patch_config {enabled:true, interval_seconds}(不传 message_threshold)。
*/
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -21,6 +19,7 @@ import { Loader2, PlayCircle, Plus, X } from 'lucide-react';
import { Switch } from '../Switch';
import { usePersonalContextStore } from '../../stores';
import {
+ type DistillConfig,
type ImLearningBackfill,
type ImLearningBackfillRow,
type ImLearningChannelId,
@@ -28,11 +27,19 @@ import {
type ImLearningDiscoverItem,
type ImLearningTarget,
type ImLearningTargetKind,
+ type ProfileVersionDetail,
IM_LEARNING_CHANNELS,
pcApi,
webErrorCode,
} from '../../services/personalContextApi';
import { PersonalContextImAssociateDialog } from './ImAssociateDialog';
+import {
+ DEFAULT_DISTILL_CONFIG,
+ DISTILL_INTERVAL_PRESETS,
+ isDistillDirty,
+ matchDistillIntervalPreset,
+ validateDistillDraft,
+} from './distillConfig';
import {
SINCE_PRESET_DAYS,
type SincePresetDays,
@@ -103,9 +110,17 @@ export function PersonalContextImLearningPanel({
const {
config,
imLearningStatus,
+ distillConfig,
+ distillStatus,
+ profileVersions,
pendingWrites,
loadImLearningStatus,
saveImLearning,
+ loadDistillConfig,
+ loadDistillStatus,
+ saveDistillConfig,
+ loadProfiles,
+ activateProfile,
setInfoTab,
} = usePersonalContextStore();
@@ -121,7 +136,24 @@ export function PersonalContextImLearningPanel({
setDraft(savedIm);
}, [savedSignature, savedIm]);
+ const [distillDraft, setDistillDraft] = useState<DistillConfig>(
+ distillConfig ?? DEFAULT_DISTILL_CONFIG,
+ );
+ const distillSavedSignature = useMemo(
+ () => JSON.stringify(distillConfig),
+ [distillConfig],
+ );
+ const distillSyncedRef = useRef(distillSavedSignature);
+ useEffect(() => {
+ if (distillSyncedRef.current === distillSavedSignature) return;
+ distillSyncedRef.current = distillSavedSignature;
+ setDistillDraft(distillConfig);
+ }, [distillSavedSignature, distillConfig]);
+
const [notice, setNotice] = useState<PanelNotice | null>(null);
+ const [preview, setPreview] = useState<ProfileVersionDetail | null>(null);
+ const [previewLoading, setPreviewLoading] = useState(false);
+ const [distillRunning, setDistillRunning] = useState(false);
// 会话发现(im.hosting.discover,与托管 UI 数据同源)
const [discoverChannel, setDiscoverChannel] = useState<ImLearningChannelId>('feishu');
@@ -138,15 +170,44 @@ export function PersonalContextImLearningPanel({
const [associateChannel, setAssociateChannel] = useState<ImLearningChannelId | null>(null);
const running = imLearningStatus?.running ?? false;
+ // lease 非空 = 正在蒸馏(手动或自动);distillRunning 仅覆盖 run_now 请求往返。
+ const distillLeaseHeld = !!distillStatus?.lease;
+ const distillBusy = distillRunning || distillLeaseHeld;
- // 阶段状态轮询:运行中 5s,未运行降频 30s。
+ // 阶段状态轮询:运行中 5s,未运行降频 30s;并行刷 distill status。
useEffect(() => {
if (!isConnected || !isActive) return;
- const load = () => void loadImLearningStatus().catch(() => {});
+ const load = () => {
+ void loadImLearningStatus().catch(() => {});
+ void loadDistillStatus().catch(() => {});
+ };
+ void loadDistillConfig().catch(() => {});
+ void loadProfiles().catch(() => {});
load();
- const interval = window.setInterval(load, running ? POLL_ACTIVE_MS : POLL_IDLE_MS);
+ const interval = window.setInterval(
+ load,
+ running || distillBusy ? POLL_ACTIVE_MS : POLL_IDLE_MS,
+ );
return () => window.clearInterval(interval);
- }, [isConnected, isActive, running, loadImLearningStatus]);
+ }, [
+ isConnected,
+ isActive,
+ running,
+ distillBusy,
+ loadImLearningStatus,
+ loadDistillStatus,
+ loadDistillConfig,
+ loadProfiles,
+ ]);
+
+ // 蒸馏 lease 由持有 → 释放:刷新画像版本列表(新版本 / 失败原因均经 status 可见)。
+ const prevLeaseHeldRef = useRef(distillLeaseHeld);
+ useEffect(() => {
+ if (prevLeaseHeldRef.current && !distillLeaseHeld) {
+ void loadProfiles().catch(() => {});
+ }
+ prevLeaseHeldRef.current = distillLeaseHeld;
+ }, [distillLeaseHeld, loadProfiles]);
// 成功提示 5s 自动消失
useEffect(() => {
@@ -163,6 +224,13 @@ export function PersonalContextImLearningPanel({
const dirty = isImLearningDirty(savedIm, draft);
const validationError = validateImLearningDraft(draft);
const saving = !!pendingWrites.im_learning;
+ const distillDirty = isDistillDirty(
+ distillConfig ?? DEFAULT_DISTILL_CONFIG,
+ distillDraft,
+ );
+ const distillValidationError = validateDistillDraft(distillDraft);
+ const distillSaving = !!pendingWrites.distill;
+ const profileActivating = !!pendingWrites.profile_activate;
const sincePreset = sinceMsToPreset(draft.since_ms);
const handleSave = () => {
@@ -196,6 +264,68 @@ export function PersonalContextImLearningPanel({
);
};
+ const handleSaveDistill = () => {
+ setNotice(null);
+ const errorKey = validateDistillDraft(distillDraft);
+ if (errorKey) {
+ setNotice({
+ kind: 'error',
+ message: t(`personalContext.imLearning.distillErrors.${errorKey}`),
+ });
+ return;
+ }
+ void saveDistillConfig({
+ enabled: true,
+ interval_seconds: distillDraft.interval_seconds,
+ })
+ .then(() => setNotice({ kind: 'success', key: 'personalContext.imLearning.distillSaved' }))
+ .catch((e: unknown) =>
+ setNotice({ kind: 'error', message: e instanceof Error ? e.message : String(e) }),
+ );
+ };
+
+ const handleDistillRunNow = () => {
+ setNotice(null);
+ setDistillRunning(true);
+ void pcApi
+ .runDistillNow()
+ .then(async () => {
+ setNotice({
+ kind: 'success',
+ key: 'personalContext.imLearning.distillRunSubmitted',
+ });
+ await loadDistillStatus().catch(() => {});
+ })
+ .catch((e: unknown) =>
+ setNotice({ kind: 'error', message: e instanceof Error ? e.message : String(e) }),
+ )
+ .finally(() => setDistillRunning(false));
+ };
+
+ const handleActivateProfile = (jobId: string) => {
+ setNotice(null);
+ if (!window.confirm(t('personalContext.imLearning.profilesActivateConfirm'))) return;
+ void activateProfile(jobId)
+ .then(() =>
+ setNotice({ kind: 'success', key: 'personalContext.imLearning.profilesActivated' }),
+ )
+ .catch((e: unknown) =>
+ setNotice({ kind: 'error', message: e instanceof Error ? e.message : String(e) }),
+ );
+ };
+
+ const handlePreviewProfile = (jobId: string) => {
+ setNotice(null);
+ setPreviewLoading(true);
+ void pcApi
+ .getProfileVersion(jobId)
+ .then((detail) => setPreview(detail))
+ .catch((e: unknown) =>
+ setNotice({ kind: 'error', message: e instanceof Error ? e.message : String(e) }),
+ )
+ .finally(() => setPreviewLoading(false));
+ };
+
const handleDiscover = () => {
setNotice(null);
setDiscoverLoading(true);
@@ -675,7 +805,7 @@ export function PersonalContextImLearningPanel({
</div>
</section>
- {/* ── 区块 3:周期设置 ── */}
+ {/* ── 区块 3:周期设置(仅 IM 学习) ── */}
<section className="pc-iml__card">
<div className="pc-iml__card-head">
<h4 className="pc-iml__card-title">{t('personalContext.imLearning.cycleTitle')}</h4>
@@ -722,11 +852,207 @@ export function PersonalContextImLearningPanel({
<p className="pc-iml__hint">{t('personalContext.imLearning.topNHint')}</p>
</div>
</div>
- <div className="pc-iml__distill">
- <span className="pc-iml__distill-label">{t('personalContext.imLearning.distillLabel')}</span>
- <span className="pc-iml__distill-value">
- {t('personalContext.imLearning.distillDisabled')}
+ </section>
+
+ {/* ── 区块 4:画像蒸馏(与周期设置同级) ── */}
+ <section className="pc-iml__card">
+ <div className="pc-iml__card-head">
+ <h4 className="pc-iml__card-title">
+ {t('personalContext.imLearning.distillTitle')}
+ </h4>
+ <div className="pc-iml__distill-badges">
+ <span
+ className={`pc-iml__badge${distillStatus?.wired ? ' is-ok' : ' is-bad'}`}
+ >
+ {distillStatus?.wired
+ ? t('personalContext.imLearning.distillWired')
+ : t('personalContext.imLearning.distillNotWired')}
+ </span>
+ <span
+ className={`pc-iml__badge${distillStatus?.scheduler_active ? ' is-ok' : ''}`}
+ >
+ {distillStatus?.scheduler_active
+ ? t('personalContext.imLearning.distillSchedulerOn')
+ : t('personalContext.imLearning.distillSchedulerOff')}
+ </span>
+ </div>
+ </div>
+ {distillStatus && !distillStatus.enabled && (
+ <p className="pc-iml__gate">{t('personalContext.imLearning.distillSaveToEnableHint')}</p>
+ )}
+ {distillStatus?.enabled && !config.collection_enabled && (
+ <p className="pc-iml__gate">{t('personalContext.imLearning.distillGateHint')}</p>
+ )}
+ {!distillStatus?.wired && (
+ <p className="pc-iml__gate">{t('personalContext.imLearning.distillNotWiredHint')}</p>
+ )}
+ <div className="pc-iml__field">
+ <span className="pc-iml__label">{t('personalContext.imLearning.distillInterval')}</span>
+ <div className="pc-iml__distill-presets" role="group">
+ {DISTILL_INTERVAL_PRESETS.map((preset) => {
+ const active =
+ matchDistillIntervalPreset(distillDraft.interval_seconds) === preset.id;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ className={`pc-iml__since-btn${active ? ' is-active' : ''}`}
+ onClick={() =>
+ setDistillDraft((prev) => ({
+ ...prev,
+ interval_seconds: preset.seconds,
+ }))
+ }
+ disabled={distillSaving}
+ >
+ {t(`personalContext.imLearning.distillPreset.${preset.id}`)}
+ </button>
+ );
+ })}
+ </div>
+ <input
+ id="pc-iml-distill-interval"
+ className="pc-iml__input"
+ type="number"
+ min={60}
+ step={60}
+ value={distillDraft.interval_seconds}
+ onChange={(e) =>
+ setDistillDraft((prev) => ({
+ ...prev,
+ interval_seconds: Number(e.target.value),
+ }))
+ }
+ disabled={distillSaving}
+ />
+ <p className="pc-iml__hint">{t('personalContext.imLearning.distillIntervalHint')}</p>
+ </div>
+ {distillStatus?.last_error && (
+ <p className="pc-iml__last-error">
+ {t('personalContext.imLearning.distillLastError')}: {distillStatus.last_error}
+ </p>
+ )}
+ <div className="pc-iml__distill-actions">
+ <button
+ type="button"
+ className="pc-iml__btn"
+ onClick={handleDistillRunNow}
+ disabled={
+ !isConnected ||
+ distillBusy ||
+ distillSaving ||
+ !distillStatus?.wired
+ }
+ >
+ {distillBusy ? (
+ <>
+ <Loader2 className="spin" size={14} />
+ {t('personalContext.imLearning.distillRunning')}
+ </>
+ ) : (
+ <>
+ <PlayCircle size={14} />
+ {t('personalContext.imLearning.distillRunNow')}
+ </>
+ )}
+ </button>
+ <button
+ type="button"
+ className="pc-iml__save"
+ onClick={handleSaveDistill}
+ disabled={
+ !isConnected ||
+ !distillDirty ||
+ distillSaving ||
+ !!distillValidationError
+ }
+ >
+ {distillSaving
+ ? t('personalContext.imLearning.distillSaving')
+ : t('personalContext.imLearning.distillSave')}
+ </button>
+ </div>
+ {distillValidationError && (
+ <span className="pc-iml__save-error">
+ {t(`personalContext.imLearning.distillErrors.${distillValidationError}`)}
</span>
+ )}
+ {!distillValidationError && distillDirty && (
+ <span className="pc-iml__save-hint">
+ {t('personalContext.imLearning.distillDirtyHint')}
+ </span>
+ )}
+
+ <div className="pc-iml__profiles-block">
+ <h5 className="pc-iml__distill-title">
+ {t('personalContext.imLearning.profilesTitle')}
+ </h5>
+ {profileVersions.length === 0 ? (
+ <p className="pc-iml__empty">{t('personalContext.imLearning.profilesEmpty')}</p>
+ ) : (
+ <ul className="pc-iml__profile-list">
+ {profileVersions.map((item) => (
+ <li key={item.job_id} className="pc-iml__profile-row">
+ <div className="pc-iml__profile-meta">
+ <span className="pc-iml__profile-id">{item.job_id}</span>
+ {item.is_current && (
+ <span className="pc-iml__badge is-ok">
+ {t('personalContext.imLearning.profilesCurrent')}
+ </span>
+ )}
+ <span className="pc-iml__profile-time">
+ {formatMs(item.published_at_ms) || '—'}
+ </span>
+ <span className="pc-iml__profile-source">{item.source}</span>
+ </div>
+ <div className="pc-iml__profile-actions">
+ <button
+ type="button"
+ className="pc-iml__btn"
+ onClick={() => handlePreviewProfile(item.job_id)}
+ disabled={previewLoading || !isConnected}
+ >
+ {t('personalContext.imLearning.profilesPreview')}
+ </button>
+ <button
+ type="button"
+ className="pc-iml__btn"
+ onClick={() => handleActivateProfile(item.job_id)}
+ disabled={item.is_current || profileActivating || !isConnected}
+ >
+ {t('personalContext.imLearning.profilesActivate')}
+ </button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ {preview && (
+ <div className="pc-iml__preview">
+ <div className="pc-iml__preview-head">
+ <strong>
+ {t('personalContext.imLearning.profilesPreview')} · {preview.job_id}
+ </strong>
+ <button
+ type="button"
+ className="pc-iml__icon-btn"
+ onClick={() => setPreview(null)}
+ aria-label={t('personalContext.imLearning.profilesPreviewClose')}
+ >
+ <X size={14} />
+ </button>
+ </div>
+ {preview.truncated && (
+ <p className="pc-iml__hint">
+ {t('personalContext.imLearning.profilesPreviewTruncated')}
+ </p>
+ )}
+ <h5 className="pc-iml__preview-section">Persona</h5>
+ <pre className="pc-iml__preview-body">{preview.persona_md}</pre>
+ <h5 className="pc-iml__preview-section">Work</h5>
+ <pre className="pc-iml__preview-body">{preview.work_md}</pre>
+ </div>
+ )}
</div>
</section>
diff --git a/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/distillConfig.ts b/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/distillConfig.ts
new file mode 100644
index 0000000000..85030d03da
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/PersonalContext/distillConfig.ts
@@ -0,0 +1,60 @@
+/**
+ * Distill 配置纯函数:语义签名脏检查与可写字段校验(WEB-03 改版)。
+ * 脏检查只比较 interval_seconds;保存时由 UI 固定写 enabled:true。
+ * message_threshold 不在 UI 编辑(agent-core 默认语义)。
+ */
+
+import type { DistillConfig } from '../../services/personalContextApi';
+
+/** 与后端 DistillScheduleSettings.interval_seconds 常见上界对齐(365 天)。 */
+export const DISTILL_INTERVAL_MAX_SECONDS = 31_536_000;
+export const DISTILL_INTERVAL_MIN_SECONDS = 60;
+
+/** 快捷档位:只填充秒数,不另发枚举字段。 */
+export const DISTILL_INTERVAL_PRESETS = [
+ { id: '1h', seconds: 3_600 },
+ { id: '6h', seconds: 21_600 },
+ { id: '1day', seconds: 86_400 },
+ { id: '3day', seconds: 259_200 },
+ { id: '7day', seconds: 604_800 },
+] as const;
+
+export type DistillIntervalPresetId = (typeof DISTILL_INTERVAL_PRESETS)[number]['id'];
+
+export const DEFAULT_DISTILL_CONFIG: DistillConfig = {
+ enabled: false,
+ interval_seconds: 86400,
+ message_threshold: 50,
+ max_messages: 800,
+ learning_since_ms: null,
+};
+
+export function matchDistillIntervalPreset(
+ seconds: number,
+): DistillIntervalPresetId | null {
+ const found = DISTILL_INTERVAL_PRESETS.find((p) => p.seconds === Number(seconds));
+ return found ? found.id : null;
+}
+
+export function distillSignature(config: DistillConfig): string {
+ return JSON.stringify([Number(config.interval_seconds)]);
+}
+
+export function isDistillDirty(saved: DistillConfig, draft: DistillConfig): boolean {
+ // 服务端 enabled=false 时也视为需保存(保存会写 enabled:true)。
+ return distillSignature(saved) !== distillSignature(draft) || !saved.enabled;
+}
+
+export type DistillValidationError = 'intervalRange';
+
+export function validateDistillDraft(draft: DistillConfig): DistillValidationError | null {
+ const interval = Number(draft.interval_seconds);
+ if (
+ !Number.isFinite(interval) ||
+ interval < DISTILL_INTERVAL_MIN_SECONDS ||
+ interval > DISTILL_INTERVAL_MAX_SECONDS
+ ) {
+ return 'intervalRange';
+ }
+ return null;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 7dba81065b..ae574e334c 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -3287,7 +3287,43 @@
"topNLabel": "Max messages per conversation per cycle",
"topNHint": "Integer 1-200, default 50.",
"distillLabel": "Profile distillation",
- "distillDisabled": "Disabled (coming in a later release)",
+ "distillTitle": "Profile Distillation",
+ "distillInterval": "Distill interval (seconds)",
+ "distillIntervalHint": "Presets only fill the seconds field; the saved value is always interval_seconds. Default 86400 (1 day).",
+ "distillPreset": {
+ "1h": "1h",
+ "6h": "6h",
+ "1day": "1 day",
+ "3day": "3 days",
+ "7day": "7 days"
+ },
+ "distillWired": "Wired",
+ "distillNotWired": "Not wired",
+ "distillNotWiredHint": "Host distill ports are not injected. A normal deployment should be wired; check service logs if this persists.",
+ "distillSchedulerOn": "Scheduler active",
+ "distillSchedulerOff": "Scheduler idle",
+ "distillSaveToEnableHint": "Distillation is off. Save the distill interval to enable the scheduler and Distill now.",
+ "distillGateHint": "Distillation is enabled, but the Personal Context collection master switch is off, so the scheduler will not run.",
+ "distillRunNow": "Distill now",
+ "distillRunning": "Distilling…",
+ "distillRunSubmitted": "A distill job was triggered",
+ "distillSave": "Save distill config",
+ "distillSaving": "Saving…",
+ "distillSaved": "Distill config saved",
+ "distillDirtyHint": "Unsaved distill changes",
+ "distillLastError": "Last error",
+ "distillErrors": {
+ "intervalRange": "Distill interval must be between 60 and 31536000 seconds"
+ },
+ "profilesTitle": "Profile Versions",
+ "profilesEmpty": "No profile versions yet. Complete a distill run to see them here.",
+ "profilesCurrent": "Current",
+ "profilesActivate": "Set as current",
+ "profilesActivateConfirm": "Switch this version to the current profile?",
+ "profilesActivated": "Current profile updated",
+ "profilesPreview": "Preview",
+ "profilesPreviewClose": "Close preview",
+ "profilesPreviewTruncated": "Content truncated for display",
"save": "Save Learning Config",
"saving": "Saving…",
"saved": "Saved and the learning scheduler was rebuilt (brief gap; checkpoints resume without loss)",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 295265fb38..1239b00fd5 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -3276,7 +3276,43 @@
"topNLabel": "单会话单轮抓取上限(条)",
"topNHint": "1~200 的整数,默认 50。",
"distillLabel": "画像蒸馏",
- "distillDisabled": "未启用(待后续版本)",
+ "distillTitle": "画像蒸馏",
+ "distillInterval": "蒸馏周期(秒)",
+ "distillIntervalHint": "档位仅快捷填充秒数;保存以秒数为准。默认 86400 秒(1 天)。",
+ "distillPreset": {
+ "1h": "1 小时",
+ "6h": "6 小时",
+ "1day": "1 天",
+ "3day": "3 天",
+ "7day": "7 天"
+ },
+ "distillWired": "已接线",
+ "distillNotWired": "未接线",
+ "distillNotWiredHint": "Host 蒸馏端口未注入;正常部署应已接线,若仍显示请检查服务日志。",
+ "distillSchedulerOn": "调度中",
+ "distillSchedulerOff": "调度未运行",
+ "distillSaveToEnableHint": "当前蒸馏未启用,请保存蒸馏周期以启用调度与立即蒸馏。",
+ "distillGateHint": "蒸馏已启用,但个人上下文采集总开关未开启,调度不会运行。",
+ "distillRunNow": "立即蒸馏",
+ "distillRunning": "蒸馏中…",
+ "distillRunSubmitted": "已触发一次画像蒸馏",
+ "distillSave": "保存蒸馏配置",
+ "distillSaving": "保存中…",
+ "distillSaved": "蒸馏配置已保存",
+ "distillDirtyHint": "蒸馏配置有未保存的修改",
+ "distillLastError": "最近错误",
+ "distillErrors": {
+ "intervalRange": "蒸馏周期须在 60~31536000 秒之间"
+ },
+ "profilesTitle": "画像版本",
+ "profilesEmpty": "尚无画像版本;完成一轮蒸馏后将出现在此。",
+ "profilesCurrent": "现行",
+ "profilesActivate": "切换为现行",
+ "profilesActivateConfirm": "确认将该版本切换为现行画像?",
+ "profilesActivated": "已切换为现行画像",
+ "profilesPreview": "预览",
+ "profilesPreviewClose": "关闭预览",
+ "profilesPreviewTruncated": "内容过长,已截断展示",
"save": "保存学习配置",
"saving": "保存中…",
"saved": "已保存并重建学习调度(秒级空窗,断点续传不丢失)",
diff --git a/jiuwenswarm/channels/web/frontend/src/services/personalContextApi.ts b/jiuwenswarm/channels/web/frontend/src/services/personalContextApi.ts
index 1146d8dbe2..c4e2e017ab 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/personalContextApi.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/personalContextApi.ts
@@ -221,6 +221,60 @@ export type ImLearningStatus = {
last_error?: string | null;
};
+// ── 画像蒸馏 / 画像版本(WEB-03;专用 distill.* / profiles.*,不进 runtime.patch)──
+export type DistillConfig = {
+ enabled: boolean;
+ interval_seconds: number;
+ message_threshold: number;
+ max_messages?: number;
+ learning_since_ms?: number | null;
+ lease_seconds?: number;
+ poll_seconds?: number;
+};
+
+export type DistillStatus = {
+ wired: boolean;
+ enabled: boolean;
+ scheduler_active: boolean;
+ collection_enabled: boolean;
+ last_attempt_at_ms: number;
+ cursor_ms: number;
+ last_success_job_id: string | null;
+ lease: Record<string, unknown> | null;
+ last_job: Record<string, unknown> | null;
+ last_error: string | null;
+};
+
+export type ProfileVersionItem = {
+ job_id: string;
+ is_current: boolean;
+ published_at_ms: number;
+ source: string;
+ meta_summary?: {
+ message_count?: number | null;
+ analyzer?: string | null;
+ };
+};
+
+export type ProfileVersionDetail = {
+ job_id: string;
+ persona_md: string;
+ work_md: string;
+ meta: Record<string, unknown>;
+ truncated: boolean;
+};
+
+export type ProfileCurrentPayload = {
+ current: {
+ job_id: string;
+ persona_md?: string;
+ work_md?: string;
+ meta?: Record<string, unknown>;
+ source?: string;
+ published_at_ms?: number;
+ } | null;
+};
+
/** im.hosting.login.* 关联会话快照(两阶段:app_setup → user_auth)。 */
export type ImLoginPhase = 'idle' | 'app_setup' | 'user_auth' | 'logged_in' | 'failed';
@@ -586,6 +640,41 @@ export const pcApi = {
{ timeoutMs: FETCH_OP_TIMEOUT_MS },
),
+ /** 蒸馏配置(专用 API;不走 runtime.patch_config)。 */
+ getDistillConfig: () =>
+ webRequest<DistillConfig>('personal_context.distill.get_config', {}),
+
+ patchDistillConfig: (patch: Partial<Pick<DistillConfig, 'enabled' | 'interval_seconds' | 'message_threshold'>>) =>
+ webRequest<DistillConfig>('personal_context.distill.patch_config', { patch }),
+
+ getDistillStatus: () =>
+ webRequest<DistillStatus>(
+ 'personal_context.distill.get_status',
+ {},
+ { timeoutMs: FETCH_RUN_STATUS_TIMEOUT_MS },
+ ),
+
+ /** 后台启动一次手动蒸馏并立即返回;进度与结果经 getDistillStatus 轮询(lease / last_error)。 */
+ runDistillNow: () =>
+ webRequest<{ accepted: boolean }>('personal_context.distill.run_now', {}),
+
+ listProfiles: () =>
+ webRequest<{ versions: ProfileVersionItem[] }>('personal_context.profiles.list', {}),
+
+ getCurrentProfile: () =>
+ webRequest<ProfileCurrentPayload>('personal_context.profiles.get_current', {}),
+
+ getProfileVersion: (job_id: string) =>
+ webRequest<ProfileVersionDetail>('personal_context.profiles.get_version', {
+ job_id,
+ }),
+
+ activateProfile: (job_id: string) =>
+ webRequest<{ current: Record<string, unknown>; versions: ProfileVersionItem[] }>(
+ 'personal_context.profiles.activate',
+ { job_id },
+ ),
+
/**
* 从最近会话中发现可学习目标(复用 im.hosting.discover,与托管 UI 数据同源)。
* 后端可能触发 CLI 探活,对齐托管面板用 60s 超时。
diff --git a/jiuwenswarm/channels/web/frontend/src/stores/personalContextStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/personalContextStore.ts
index 4f52bc7676..76b156b0cb 100644
--- a/jiuwenswarm/channels/web/frontend/src/stores/personalContextStore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/stores/personalContextStore.ts
@@ -9,6 +9,8 @@ import { create } from 'zustand';
import {
type AuthorizationResult,
type ContextGraph,
+ type DistillConfig,
+ type DistillStatus,
type FetchServiceConfig,
type FetchServicePatch,
type FetchProvider,
@@ -16,11 +18,21 @@ import {
type ImLearningStatus,
type PersonalContextConfig,
type PersonalContextStatus,
+ type ProfileVersionItem,
pcApi,
} from '../services/personalContextApi';
export type InfoTab = 'graph' | 'services' | 'settings' | 'imLearning';
+/** Distill 未拉取到配置前的默认投影(对齐 Core DistillScheduleSettings)。 */
+const DEFAULT_DISTILL_CONFIG: DistillConfig = {
+ enabled: false,
+ interval_seconds: 86400,
+ message_threshold: 50,
+ max_messages: 800,
+ learning_since_ms: null,
+};
+
/** IM 学习未配置时的默认形态(与后端 _unconfigured_projection 的 im_learning 节对齐)。 */
const UNCONFIGURED_IM_LEARNING: ImLearningConfig = {
enabled: false,
@@ -49,6 +61,9 @@ interface PersonalContextState {
graph: ContextGraph | null;
authByProvider: Record<string, AuthorizationResult>;
imLearningStatus: ImLearningStatus | null;
+ distillConfig: DistillConfig;
+ distillStatus: DistillStatus | null;
+ profileVersions: ProfileVersionItem[];
// UI
infoTab: InfoTab;
@@ -79,6 +94,14 @@ interface PersonalContextState {
/** 保存学习配置:patch_config {im_learning} 整节提交 + 乐观更新 + 失败回滚。 */
saveImLearning: (imLearning: ImLearningConfig) => Promise<void>;
+ loadDistillConfig: () => Promise<void>;
+ loadDistillStatus: () => Promise<void>;
+ saveDistillConfig: (
+ patch: Partial<Pick<DistillConfig, 'enabled' | 'interval_seconds' | 'message_threshold'>>,
+ ) => Promise<void>;
+ loadProfiles: () => Promise<void>;
+ activateProfile: (jobId: string) => Promise<void>;
+
createService: (service: FetchServiceConfig) => Promise<void>;
/** 保存(编辑)已有采集任务:只更新参数,名称/来源不可改。 */
updateService: (serviceId: string, patch: FetchServicePatch) => Promise<void>;
@@ -104,6 +127,9 @@ export const usePersonalContextStore = create<PersonalContextState>((set, get) =
graph: null,
authByProvider: {},
imLearningStatus: null,
+ distillConfig: DEFAULT_DISTILL_CONFIG,
+ distillStatus: null,
+ profileVersions: [],
infoTab: 'graph',
loadingConfig: false,
@@ -256,6 +282,48 @@ export const usePersonalContextStore = create<PersonalContextState>((set, get) =
}
},
+ loadDistillConfig: async () => {
+ const distillConfig = await pcApi.getDistillConfig();
+ set({ distillConfig });
+ },
+
+ loadDistillStatus: async () => {
+ const distillStatus = await pcApi.getDistillStatus();
+ set({ distillStatus });
+ },
+
+ saveDistillConfig: async (patch) => {
+ set({ pendingWrites: { ...get().pendingWrites, distill: true } });
+ const prev = get().distillConfig;
+ set({ distillConfig: { ...prev, ...patch } });
+ try {
+ const next = await pcApi.patchDistillConfig(patch);
+ set({ distillConfig: next });
+ await get().loadDistillStatus().catch(() => {});
+ } catch (e) {
+ set({ distillConfig: prev });
+ throw e;
+ } finally {
+ set({ pendingWrites: { ...get().pendingWrites, distill: false } });
+ }
+ },
+
+ loadProfiles: async () => {
+ const { versions } = await pcApi.listProfiles();
+ set({ profileVersions: versions });
+ },
+
+ activateProfile: async (jobId) => {
+ set({ pendingWrites: { ...get().pendingWrites, profile_activate: true } });
+ try {
+ const result = await pcApi.activateProfile(jobId);
+ set({ profileVersions: result.versions });
+ await get().loadDistillStatus().catch(() => {});
+ } finally {
+ set({ pendingWrites: { ...get().pendingWrites, profile_activate: false } });
+ }
+ },
+
createService: async (service) => {
set({ pendingWrites: { ...get().pendingWrites, create_service: true } });
try {
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 4eb9705798..32f398e4ed 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -210,6 +210,14 @@ class ReqMethod(Enum):
"personal_context.im_learning.get_status"
)
PERSONAL_CONTEXT_IM_LEARNING_RUN_NOW = "personal_context.im_learning.run_now"
+ PERSONAL_CONTEXT_DISTILL_GET_CONFIG = "personal_context.distill.get_config"
+ PERSONAL_CONTEXT_DISTILL_PATCH_CONFIG = "personal_context.distill.patch_config"
+ PERSONAL_CONTEXT_DISTILL_GET_STATUS = "personal_context.distill.get_status"
+ PERSONAL_CONTEXT_DISTILL_RUN_NOW = "personal_context.distill.run_now"
+ PERSONAL_CONTEXT_PROFILES_LIST = "personal_context.profiles.list"
+ PERSONAL_CONTEXT_PROFILES_GET_CURRENT = "personal_context.profiles.get_current"
+ PERSONAL_CONTEXT_PROFILES_GET_VERSION = "personal_context.profiles.get_version"
+ PERSONAL_CONTEXT_PROFILES_ACTIVATE = "personal_context.profiles.activate"
# Plugin management (reuses skills marketplace infrastructure)
PLUGINS_LIST = "plugins.list"
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 2ec14ffd23..8936e44dbd 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -729,6 +729,14 @@ _FORWARD_REQ_METHODS = frozenset({
"personal_context.context.get_source",
"personal_context.im_learning.get_status",
"personal_context.im_learning.run_now",
+ "personal_context.distill.get_config",
+ "personal_context.distill.patch_config",
+ "personal_context.distill.get_status",
+ "personal_context.distill.run_now",
+ "personal_context.profiles.list",
+ "personal_context.profiles.get_current",
+ "personal_context.profiles.get_version",
+ "personal_context.profiles.activate",
"plugins.list",
"plugins.install",
"plugins.uninstall",
@@ -887,6 +895,14 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"personal_context.context.get_source",
"personal_context.im_learning.get_status",
"personal_context.im_learning.run_now",
+ "personal_context.distill.get_config",
+ "personal_context.distill.patch_config",
+ "personal_context.distill.get_status",
+ "personal_context.distill.run_now",
+ "personal_context.profiles.list",
+ "personal_context.profiles.get_current",
+ "personal_context.profiles.get_version",
+ "personal_context.profiles.activate",
"plugins.list",
"plugins.install",
"plugins.uninstall",
diff --git a/jiuwenswarm/server/personal_context/distill_ports.py b/jiuwenswarm/server/personal_context/distill_ports.py
new file mode 100644
index 0000000000..82cea35d9a
--- /dev/null
+++ b/jiuwenswarm/server/personal_context/distill_ports.py
@@ -0,0 +1,65 @@
+"""Host-owned distill port wiring for PersonalContext Core.
+
+Builds the corpus and runner that ``PersonalContextHostAPI`` injects via
+``set_distill_corpus`` / ``set_distill_runner``. Does not own the distill
+scheduler loop; Core starts that from ``activate_runtime``.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+
+from openjiuwen.harness.personal_context.distill import (
+ CorpusPort,
+ DistillRunResult,
+ LlmPort,
+ SqliteImCorpus,
+ run_distill_job,
+)
+
+
+def build_distill_corpus(home: str | Path) -> SqliteImCorpus:
+ """Return a SQLite IM corpus bound to one PersonalContext home."""
+
+ return SqliteImCorpus(str(home))
+
+
+def build_distill_runner(
+ *,
+ home: str | Path,
+ corpus: CorpusPort,
+ resolve_llm: Callable[[], LlmPort],
+) -> Callable[..., object]:
+ """Return a DistillRunnerPort-compatible callable over ``run_distill_job``.
+
+ ``resolve_llm`` is invoked on each run so the Host can bind the current
+ model selection; it must raise when no usable model is available.
+ """
+
+ home_str = str(home)
+
+ async def _run(
+ home: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None = None,
+ max_messages: int = 800,
+ force_full_window: bool = False,
+ ) -> DistillRunResult:
+ del home # Protocol passes home; binding uses construction-time home_str.
+ llm = resolve_llm()
+ return await run_distill_job(
+ home_str,
+ window_end_ms=window_end_ms,
+ learning_since_ms=learning_since_ms,
+ max_messages=max_messages,
+ corpus=corpus,
+ llm=llm,
+ force_full_window=force_full_window,
+ )
+
+ return _run
+
+
+__all__ = ["build_distill_corpus", "build_distill_runner"]
diff --git a/jiuwenswarm/server/personal_context/host_api.py b/jiuwenswarm/server/personal_context/host_api.py
index f4ff8401e6..39d2d145cb 100644
--- a/jiuwenswarm/server/personal_context/host_api.py
+++ b/jiuwenswarm/server/personal_context/host_api.py
@@ -10,21 +10,46 @@ from __future__ import annotations
import asyncio
import contextlib
from copy import deepcopy
+import json
import os
from pathlib import Path
import stat
import tempfile
+import time
from collections.abc import Awaitable, Callable
from typing import NoReturn, cast
import httpx
import yaml
+from openjiuwen.core.foundation.llm import Model, ModelClientConfig, ModelRequestConfig
from openjiuwen.harness.personal_context import PersonalContext
+from openjiuwen.harness.personal_context.distill import (
+ DistillRunResult,
+ OpenJiuwenLlm,
+ complete_distill_lease,
+ get_last_attempt_at_ms,
+ try_claim_distill_lease,
+)
+from openjiuwen.harness.personal_context.distill.store import (
+ get_cursor_ms,
+ get_distill_lease,
+ get_job,
+)
from jiuwenswarm.common.config import get_config, get_default_models
from jiuwenswarm.server.im.im_connector.learning_source import as_im_learning_source
from jiuwenswarm.server.im.im_hosting.connectors import LazySharedRegistryView
+from jiuwenswarm.server.personal_context.distill_ports import (
+ build_distill_corpus,
+ build_distill_runner,
+)
+from jiuwenswarm.server.personal_context.profiles_ops import (
+ activate_profile,
+ get_current_profile,
+ get_profile_version,
+ list_profile_versions,
+)
_CONFIG_FILENAME = "personal_context.yaml"
@@ -209,6 +234,31 @@ def _im_learning_defaults() -> dict[str, object]:
return default_factory().model_dump(mode="json", by_alias=True)
+def _distill_defaults() -> dict[str, object]:
+ """Distill 配置默认形态(跟随 Core DistillScheduleSettings)。"""
+
+ default_factory = PersonalContext.Config.model_fields["distill"].default_factory
+ if default_factory is None:
+ raise RuntimeError("PersonalContext distill defaults are invalid")
+ return default_factory().model_dump(mode="json", by_alias=True)
+
+
+_DISTILL_PATCH_KEYS = frozenset(
+ {"enabled", "interval_seconds", "message_threshold"}
+)
+
+
+def _read_distill_cursor_payload(home: Path) -> dict[str, object]:
+ path = home / "im" / "distill" / "cursor.json"
+ if not path.is_file():
+ return {}
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, TypeError, ValueError):
+ return {}
+ return raw if isinstance(raw, dict) else {}
+
+
def _unconfigured_projection() -> dict[str, object]:
max_pages, max_subdirectories = _directory_capacity_defaults()
strategy_profile, model_index, model_id = _default_strategy_and_model()
@@ -676,6 +726,293 @@ class PersonalContextHostAPI:
self._stored_config: dict[str, object] | None = None
self._operation_lock = asyncio.Lock()
self._fetch_run_stop_lock = asyncio.Lock()
+ self._distill_last_error: str | None = None
+ self._distill_manual_task: asyncio.Task[None] | None = None
+ self._ensure_distill_ports()
+
+ def _resolve_distill_llm(self) -> OpenJiuwenLlm:
+ """Build an OpenJiuwenLlm from the Host's current model_index selection."""
+
+ stored = self._stored_config
+ if stored is None:
+ _raise_host_error("distill model unavailable: PersonalContext is not configured")
+ model_index = stored.get("model_index")
+ if model_index is None:
+ _raise_host_error("distill model unavailable: no model selected")
+ client, request = _resolve_model_reference(model_index)
+ model = Model(
+ model_client_config=ModelClientConfig.model_validate(client),
+ model_config=ModelRequestConfig.model_validate(request),
+ )
+ return OpenJiuwenLlm(model, max_tokens=16384)
+
+ def _ensure_distill_ports(self) -> None:
+ """Inject SqliteImCorpus and DistillRunnerPort while Core is stopped."""
+
+ corpus = build_distill_corpus(self._home)
+ runner = build_distill_runner(
+ home=self._home,
+ corpus=corpus,
+ resolve_llm=self._resolve_distill_llm,
+ )
+ self._personal_context.set_distill_corpus(corpus)
+ self._personal_context.set_distill_runner(runner)
+
+ def distill_ports_wired(self) -> bool:
+ """Return whether corpus and runner are injected (process-local probe)."""
+
+ core = self._personal_context
+ return (
+ getattr(core, "_distill_corpus", None) is not None
+ and getattr(core, "_distill_runner", None) is not None
+ )
+
+ async def run_distill_now(self) -> dict[str, object]:
+ """Start one manual distill job in the background and return at once.
+
+ The job holds the Core Distill lease so the scheduler tick skips with
+ ``lease_held`` while it runs, and a second manual request is rejected
+ with ``distill_busy``. Progress and outcome surface via
+ ``get_distill_status`` (``lease`` / ``last_success_job_id`` /
+ ``last_error``); the Host lock is never held across the LLM calls.
+ """
+
+ async with self._operation_lock:
+ core = self._personal_context
+ runner = getattr(core, "_distill_runner", None)
+ if getattr(core, "_distill_corpus", None) is None or runner is None:
+ self._distill_last_error = "distill_not_wired"
+ _raise_host_error(
+ "distill_not_wired",
+ status_name="CONTEXT_PROACTIVE_STATE_INVALID",
+ )
+ config = self._config
+ if config is None or not config.distill.enabled:
+ self._distill_last_error = "distill_disabled"
+ _raise_host_error(
+ "distill_disabled",
+ status_name="CONTEXT_PROACTIVE_STATE_INVALID",
+ )
+ # Fail fast when model cannot be resolved (same path as runner).
+ self._resolve_distill_llm()
+ task = self._distill_manual_task
+ if task is not None and not task.done():
+ _raise_host_error(
+ "distill_busy",
+ status_name="CONTEXT_PROACTIVE_STATE_INVALID",
+ )
+ settings = config.distill
+ now_ms = int(time.time() * 1000)
+ token = try_claim_distill_lease(
+ str(self._home),
+ now_ms=now_ms,
+ lease_ms=int(settings.lease_seconds * 1000),
+ )
+ if token is None:
+ _raise_host_error(
+ "distill_busy",
+ status_name="CONTEXT_PROACTIVE_STATE_INVALID",
+ )
+ try:
+ self._distill_manual_task = asyncio.create_task(
+ self._run_manual_distill(
+ runner,
+ token,
+ window_end_ms=now_ms,
+ learning_since_ms=settings.learning_since_ms,
+ max_messages=settings.max_messages,
+ ),
+ name="personal-context-distill-manual",
+ )
+ except BaseException:
+ complete_distill_lease(str(self._home), token)
+ raise
+ return {"accepted": True}
+
+ async def _run_manual_distill(
+ self,
+ runner: Callable[..., Awaitable[DistillRunResult]],
+ lease_token: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None,
+ max_messages: int,
+ ) -> None:
+ """Background body of ``run_distill_now``; releases the lease on any exit."""
+
+ home = str(self._home)
+ try:
+ result = await runner(
+ home,
+ window_end_ms=window_end_ms,
+ learning_since_ms=learning_since_ms,
+ max_messages=max_messages,
+ )
+ except asyncio.CancelledError:
+ self._distill_last_error = "distill_cancelled"
+ raise
+ except Exception as exc:
+ self._distill_last_error = str(exc) or type(exc).__name__
+ else:
+ if result.status == "failed":
+ self._distill_last_error = result.error or "distill_failed"
+ else:
+ self._distill_last_error = None
+ finally:
+ complete_distill_lease(home, lease_token)
+
+ async def _cancel_manual_distill(self) -> None:
+ """Cancel and await the in-flight manual distill job, if any."""
+
+ task = self._distill_manual_task
+ self._distill_manual_task = None
+ if task is None or task.done():
+ return
+ task.cancel()
+ try:
+ # Lease release inside the task is best-effort; only propagate our
+ # own cancellation, never the task's.
+ with contextlib.suppress(Exception):
+ await task
+ except asyncio.CancelledError:
+ current = asyncio.current_task()
+ if current is not None and current.cancelling():
+ raise
+
+ async def get_distill_config(self) -> dict[str, object]:
+ """Return the distill schedule settings projection."""
+
+ async with self._operation_lock:
+ if self._stored_config is None:
+ return _distill_defaults()
+ distill = self._stored_config.get("distill")
+ if isinstance(distill, dict):
+ return deepcopy(distill)
+ return _distill_defaults()
+
+ async def patch_distill_config(
+ self,
+ patch: dict[str, object],
+ ) -> dict[str, object]:
+ """Patch distill settings via dedicated API (D7 keeps runtime.patch free of distill)."""
+
+ if not isinstance(patch, dict):
+ _raise_host_error("patch must be an object")
+ unknown = set(patch) - _DISTILL_PATCH_KEYS
+ if unknown:
+ _raise_host_error("distill patch contains unsupported fields")
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error("PersonalContext is not configured")
+ stored = deepcopy(self._stored_config)
+ current = stored.get("distill")
+ if not isinstance(current, dict):
+ current = _distill_defaults()
+ else:
+ current = deepcopy(current)
+ current.update(deepcopy(patch))
+ stored["distill"] = current
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ )
+ distill = stored.get("distill")
+ return deepcopy(distill) if isinstance(distill, dict) else _distill_defaults()
+
+ async def get_distill_status(self) -> dict[str, object]:
+ """Return honest distill wiring / schedule status for UI polling."""
+
+ async with self._operation_lock:
+ wired = self.distill_ports_wired()
+ if self._stored_config is None or self._config is None:
+ return {
+ "wired": wired,
+ "enabled": False,
+ "scheduler_active": False,
+ "collection_enabled": False,
+ "last_attempt_at_ms": 0,
+ "cursor_ms": 0,
+ "last_success_job_id": None,
+ "lease": None,
+ "last_job": None,
+ "last_error": self._distill_last_error,
+ }
+ enabled = bool(self._config.distill.enabled)
+ collection_enabled = bool(self._config.collection_enabled)
+ home_str = str(self._home)
+ task = getattr(self._personal_context, "_distill_task", None)
+ if task is not None:
+ scheduler_active = not task.done()
+ else:
+ scheduler_active = wired and enabled and collection_enabled
+ cursor_payload = _read_distill_cursor_payload(self._home)
+ last_success_job_id = cursor_payload.get("last_success_job_id")
+ last_job = None
+ if isinstance(last_success_job_id, str) and last_success_job_id.strip():
+ last_job = get_job(home_str, last_success_job_id.strip())
+ return {
+ "wired": wired,
+ "enabled": enabled,
+ "scheduler_active": bool(scheduler_active),
+ "collection_enabled": collection_enabled,
+ "last_attempt_at_ms": get_last_attempt_at_ms(home_str),
+ "cursor_ms": get_cursor_ms(home_str),
+ "last_success_job_id": last_success_job_id,
+ "lease": get_distill_lease(home_str),
+ "last_job": last_job,
+ "last_error": self._distill_last_error,
+ }
+
+ async def list_profiles(self) -> dict[str, object]:
+ """List distilled profile versions (Host disk scan)."""
+
+ async with self._operation_lock:
+ return {"versions": list_profile_versions(str(self._home))}
+
+ async def get_current_profile_payload(self) -> dict[str, object]:
+ """Return the active profile or an explicit empty payload."""
+
+ async with self._operation_lock:
+ current = get_current_profile(str(self._home))
+ return {"current": current}
+
+ async def get_profile_version_payload(
+ self,
+ job_id: str,
+ ) -> dict[str, object]:
+ """Return one profile version for UI preview."""
+
+ async with self._operation_lock:
+ try:
+ return get_profile_version(str(self._home), job_id)
+ except ValueError as exc:
+ _raise_host_error(str(exc))
+ except FileNotFoundError as exc:
+ _raise_host_error(
+ str(exc),
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ )
+
+ async def activate_profile_version_payload(
+ self,
+ job_id: str,
+ ) -> dict[str, object]:
+ """Switch current.json to the given version (manual_switch)."""
+
+ async with self._operation_lock:
+ try:
+ pointer = activate_profile(str(self._home), job_id)
+ except ValueError as exc:
+ _raise_host_error(str(exc))
+ except Exception as exc:
+ _raise_host_error(
+ f"activate profile failed: {exc}",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ cause=exc,
+ )
+ return {"current": pointer, "versions": list_profile_versions(str(self._home))}
def _refresh_embedding_configuration(self) -> None:
model_name, base_url, api_key = _global_embedding_values()
@@ -736,6 +1073,9 @@ class PersonalContextHostAPI:
self._stored_config = deepcopy(stored)
return
+ # The runtime restarts below; a manual distill job holding the old
+ # runner must not keep publishing after the configuration changes.
+ await self._cancel_manual_distill()
temporary: Path | None = _stage_yaml(self._config_path, payload)
disabling = (
previous is not None
@@ -763,10 +1103,14 @@ class PersonalContextHostAPI:
phase = "set"
rollback_runtime = True
+ self._ensure_distill_ports()
await self._personal_context.set_configuration(candidate)
if candidate.collection_enabled:
phase = "activate"
+ # Distill runner resolves model_index from Host stored config.
+ self._config = candidate
+ self._stored_config = deepcopy(stored)
self._refresh_embedding_configuration()
await self._personal_context.activate_runtime()
@@ -1617,6 +1961,7 @@ class PersonalContextHostAPI:
return
stored, config = _prepare_stored_config(raw)
try:
+ self._ensure_distill_ports()
await self._personal_context.set_configuration(config)
except BaseException as exc:
if isinstance(exc, asyncio.CancelledError):
@@ -1662,6 +2007,7 @@ class PersonalContextHostAPI:
status_name="CONTEXT_PROACTIVE_RUNTIME_TIMEOUT",
)
async with self._operation_lock:
+ await self._cancel_manual_distill()
try:
await self._personal_context.deactivate_runtime(
timeout_seconds=timeout_seconds
@@ -1681,17 +2027,22 @@ class PersonalContextHostAPI:
) -> None:
"""Restore after a failed candidate configuration operation."""
+ # Candidate may already sit in Host memory before activate (distill LLM
+ # resolution). Restore memory first so a later stop failure cannot leave
+ # the Host half-configured while Core is still active.
+ self._config = previous
+ self._stored_config = (
+ deepcopy(previous_stored) if previous_stored is not None else None
+ )
await self._personal_context.deactivate_runtime(
timeout_seconds=_STOP_TIMEOUT_SECONDS
)
if previous is None:
self._personal_context = _new_personal_context(self._home)
- self._config = None
- self._stored_config = None
+ self._ensure_distill_ports()
return
+ self._ensure_distill_ports()
await self._personal_context.set_configuration(previous)
if was_active and previous.collection_enabled:
self._refresh_embedding_configuration()
await self._personal_context.activate_runtime()
- self._config = previous
- self._stored_config = deepcopy(previous_stored)
diff --git a/jiuwenswarm/server/personal_context/profiles_ops.py b/jiuwenswarm/server/personal_context/profiles_ops.py
new file mode 100644
index 0000000000..8e33315472
--- /dev/null
+++ b/jiuwenswarm/server/personal_context/profiles_ops.py
@@ -0,0 +1,196 @@
+"""Host-owned profile version disk helpers (WEB-03).
+
+Scans ``im/profiles/versions`` and reads version files. Activate/resolve
+delegate to Core ``activate_profile_version`` / ``resolve_current_profile``.
+No classes — closed-class inventory allows only ``PersonalContextHostAPI``.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from openjiuwen.harness.personal_context.distill import (
+ activate_profile_version,
+ resolve_current_profile,
+)
+from openjiuwen.harness.personal_context.distill.profile import (
+ META_FILENAME,
+ PERSONA_FILENAME,
+ WORK_FILENAME,
+ current_json_path,
+ load_text,
+ profiles_root,
+)
+
+# Align preview truncation with Core profile clip limits.
+_PREVIEW_CLIP_CHARS = 12000
+
+
+def _clip(text: str, limit: int = _PREVIEW_CLIP_CHARS) -> tuple[str, bool]:
+ value = text or ""
+ if len(value) <= limit:
+ return value, False
+ return value[:limit], True
+
+
+def _safe_job_id(job_id: str) -> str:
+ """Reject empty / multi-segment / traversal job_id before any disk join.
+
+ ``version_dir(home, job_id)`` is a plain Path join; values like ``../x``
+ escape ``im/profiles/versions``. Host RPC must only accept a single
+ directory name under that root.
+ """
+
+ cleaned = (job_id or "").strip()
+ if not cleaned:
+ raise ValueError("job_id must be a non-empty string")
+ if cleaned in {".", ".."}:
+ raise ValueError("job_id is invalid")
+ if "/" in cleaned or "\\" in cleaned or "\x00" in cleaned:
+ raise ValueError("job_id must be a single path segment")
+ candidate = Path(cleaned)
+ if candidate.is_absolute() or candidate.anchor:
+ raise ValueError("job_id must be a single path segment")
+ if candidate.name != cleaned:
+ # Catches oddities like trailing separators on some platforms.
+ raise ValueError("job_id must be a single path segment")
+ return cleaned
+
+
+def _resolved_version_dir(home: str, job_id: str) -> Path:
+ """Return the version directory only when it stays under ``versions/``."""
+
+ cleaned = _safe_job_id(job_id)
+ versions_root = (profiles_root(home) / "versions").resolve()
+ root = (versions_root / cleaned).resolve()
+ try:
+ root.relative_to(versions_root)
+ except ValueError as exc:
+ raise ValueError("job_id escapes versions directory") from exc
+ if root.parent != versions_root:
+ raise ValueError("job_id escapes versions directory")
+ return root
+
+
+def _version_files_complete(root: Path) -> bool:
+ return (
+ (root / PERSONA_FILENAME).is_file()
+ and (root / WORK_FILENAME).is_file()
+ and (root / META_FILENAME).is_file()
+ )
+
+
+def _read_json(path: Path) -> dict[str, Any] | None:
+ if not path.is_file():
+ return None
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, TypeError, ValueError):
+ return None
+ return raw if isinstance(raw, dict) else None
+
+
+def _read_current_pointer(home: str) -> dict[str, Any] | None:
+ return _read_json(current_json_path(home))
+
+
+def list_profile_versions(home: str) -> list[dict[str, Any]]:
+ """Scan ``versions/*`` directories; mark current via ``current.json``."""
+
+ pointer = _read_current_pointer(home)
+ current_job = str((pointer or {}).get("job_id") or "").strip()
+ versions_root = profiles_root(home) / "versions"
+ items: list[dict[str, Any]] = []
+ if not versions_root.is_dir():
+ return items
+ for child in versions_root.iterdir():
+ if not child.is_dir():
+ continue
+ job_id = child.name.strip()
+ try:
+ job_id = _safe_job_id(job_id)
+ except ValueError:
+ continue
+ if not _version_files_complete(child):
+ continue
+ meta = _read_json(child / META_FILENAME) or {}
+ published_at_ms = meta.get("published_at_ms")
+ if published_at_ms is None and pointer and job_id == current_job:
+ published_at_ms = pointer.get("published_at_ms")
+ if published_at_ms is None:
+ try:
+ published_at_ms = int(child.stat().st_mtime * 1000)
+ except OSError:
+ published_at_ms = 0
+ source = meta.get("source")
+ if source is None and pointer and job_id == current_job:
+ source = pointer.get("source")
+ meta_summary = {
+ "message_count": meta.get("message_count"),
+ "analyzer": meta.get("analyzer"),
+ }
+ items.append(
+ {
+ "job_id": job_id,
+ "is_current": job_id == current_job,
+ "published_at_ms": int(published_at_ms or 0),
+ "source": source or "distill",
+ "meta_summary": meta_summary,
+ }
+ )
+ items.sort(
+ key=lambda item: (
+ 0 if item.get("is_current") else 1,
+ -int(item.get("published_at_ms") or 0),
+ )
+ )
+ return items
+
+
+def get_current_profile(home: str) -> dict[str, Any] | None:
+ """Delegate to Core resolve; empty when missing or incomplete."""
+
+ return resolve_current_profile(home)
+
+
+def get_profile_version(
+ home: str,
+ job_id: str,
+ *,
+ clip_chars: int = _PREVIEW_CLIP_CHARS,
+) -> dict[str, Any]:
+ """Load one version's persona/work/meta; clip long markdown."""
+
+ cleaned = _safe_job_id(job_id)
+ root = _resolved_version_dir(home, cleaned)
+ if not _version_files_complete(root):
+ raise FileNotFoundError(f"profile version not found or incomplete: {cleaned}")
+ meta = _read_json(root / META_FILENAME) or {}
+ persona_md, persona_truncated = _clip(load_text(root / PERSONA_FILENAME), clip_chars)
+ work_md, work_truncated = _clip(load_text(root / WORK_FILENAME), clip_chars)
+ return {
+ "job_id": cleaned,
+ "persona_md": persona_md,
+ "work_md": work_md,
+ "meta": meta,
+ "truncated": persona_truncated or work_truncated,
+ }
+
+
+def activate_profile(home: str, job_id: str) -> dict[str, Any]:
+ """Atomically switch ``current.json`` via Core (source=manual_switch)."""
+
+ cleaned = _safe_job_id(job_id)
+ # Validate containment before Core join; Core still receives only the safe id.
+ _resolved_version_dir(home, cleaned)
+ return activate_profile_version(home, cleaned, source="manual_switch")
+
+
+__all__ = [
+ "activate_profile",
+ "get_current_profile",
+ "get_profile_version",
+ "list_profile_versions",
+]
diff --git a/jiuwenswarm/server/personal_context/ws_handler.py b/jiuwenswarm/server/personal_context/ws_handler.py
index 39f63687b8..91c8f088a3 100644
--- a/jiuwenswarm/server/personal_context/ws_handler.py
+++ b/jiuwenswarm/server/personal_context/ws_handler.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import asyncio
import logging
from collections.abc import Awaitable, Callable
+from dataclasses import asdict, is_dataclass
from typing import TYPE_CHECKING, Any, cast
from openjiuwen.core.common.exception.errors import BaseError
@@ -58,6 +59,14 @@ PERSONAL_CONTEXT_REQUEST_METHODS = frozenset(
ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_SOURCE,
ReqMethod.PERSONAL_CONTEXT_IM_LEARNING_GET_STATUS,
ReqMethod.PERSONAL_CONTEXT_IM_LEARNING_RUN_NOW,
+ ReqMethod.PERSONAL_CONTEXT_DISTILL_GET_CONFIG,
+ ReqMethod.PERSONAL_CONTEXT_DISTILL_PATCH_CONFIG,
+ ReqMethod.PERSONAL_CONTEXT_DISTILL_GET_STATUS,
+ ReqMethod.PERSONAL_CONTEXT_DISTILL_RUN_NOW,
+ ReqMethod.PERSONAL_CONTEXT_PROFILES_LIST,
+ ReqMethod.PERSONAL_CONTEXT_PROFILES_GET_CURRENT,
+ ReqMethod.PERSONAL_CONTEXT_PROFILES_GET_VERSION,
+ ReqMethod.PERSONAL_CONTEXT_PROFILES_ACTIVATE,
}
)
@@ -67,6 +76,10 @@ def _payload(value: object) -> dict[str, object]:
return {"ok": True}
if isinstance(value, dict):
return value
+ if is_dataclass(value) and not isinstance(value, type):
+ dumped = asdict(value)
+ if isinstance(dumped, dict):
+ return dumped
if hasattr(value, "model_dump"):
dumped = value.model_dump(mode="json")
if isinstance(dumped, dict):
@@ -313,6 +326,25 @@ async def _execute(
return _payload(await host.get_im_learning_status())
if method == ReqMethod.PERSONAL_CONTEXT_IM_LEARNING_RUN_NOW:
return {"triggered": await host.run_im_learning_now()}
+ if method == ReqMethod.PERSONAL_CONTEXT_DISTILL_GET_CONFIG:
+ return await host.get_distill_config()
+ if method == ReqMethod.PERSONAL_CONTEXT_DISTILL_PATCH_CONFIG:
+ patch = params.get("patch")
+ if not isinstance(patch, dict):
+ raise ValueError("patch must be an object")
+ return await host.patch_distill_config(cast(dict[str, object], patch))
+ if method == ReqMethod.PERSONAL_CONTEXT_DISTILL_GET_STATUS:
+ return await host.get_distill_status()
+ if method == ReqMethod.PERSONAL_CONTEXT_DISTILL_RUN_NOW:
+ return _payload(await host.run_distill_now())
+ if method == ReqMethod.PERSONAL_CONTEXT_PROFILES_LIST:
+ return await host.list_profiles()
+ if method == ReqMethod.PERSONAL_CONTEXT_PROFILES_GET_CURRENT:
+ return await host.get_current_profile_payload()
+ if method == ReqMethod.PERSONAL_CONTEXT_PROFILES_GET_VERSION:
+ return await host.get_profile_version_payload(_text(params, "job_id"))
+ if method == ReqMethod.PERSONAL_CONTEXT_PROFILES_ACTIVATE:
+ return await host.activate_profile_version_payload(_text(params, "job_id"))
raise ValueError("unknown PersonalContext method")
diff --git a/tests/unit_tests/personal_context/test_distill_api.py b/tests/unit_tests/personal_context/test_distill_api.py
new file mode 100644
index 0000000000..3cfd89286c
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_distill_api.py
@@ -0,0 +1,258 @@
+"""WEB-03 distill control-plane API (dedicated distill.* ; D7 kept on runtime.patch)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from openjiuwen.harness.personal_context import PersonalContext
+from openjiuwen.harness.personal_context.distill import DistillRunResult
+
+from jiuwenswarm.server.personal_context import host_api as host_module
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+
+def _pin_models(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ host_module,
+ "get_default_models",
+ lambda: [
+ {
+ "model_client_config": {
+ "client_provider": "OpenAI",
+ "api_key": "test-key",
+ "api_base": "https://example.invalid/v1",
+ "model_name": "test-model",
+ },
+ "model_config_obj": {"temperature": 0.2},
+ }
+ ],
+ )
+ monkeypatch.setattr(
+ host_module, "_global_embedding_values", lambda: (None, None, None)
+ )
+
+
+class _FakeSnapshot:
+ state = "STOPPED"
+
+
+class FakeDistillCore:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, object]] = []
+ self.configured: object | None = None
+ self.active = False
+ self.snapshot_state = "STOPPED"
+ self._distill_corpus: object | None = "corpus"
+ self._distill_runner: object | None = None
+ self._distill_task = None
+
+ def set_distill_corpus(self, corpus: object | None) -> None:
+ self._distill_corpus = corpus
+
+ def set_distill_runner(self, runner: object | None) -> None:
+ self._distill_runner = runner
+
+ def _set_embedding_configuration(self, **_kwargs: object) -> None:
+ self.calls.append(("_set_embedding_configuration", None))
+
+ async def snapshot(self) -> object:
+ snap = _FakeSnapshot()
+ snap.state = self.snapshot_state
+ return snap
+
+ async def set_configuration(self, config: object) -> None:
+ self.configured = config
+ self.calls.append(("set_configuration", None))
+
+ async def activate_runtime(self) -> None:
+ self.active = True
+ self.calls.append(("activate_runtime", None))
+
+ async def deactivate_runtime(self, *, timeout_seconds: float = 30.0) -> None:
+ self.active = False
+ self.calls.append(("deactivate_runtime", timeout_seconds))
+
+
+def distill_host(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> tuple[PersonalContextHostAPI, FakeDistillCore]:
+ _pin_models(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "personal_context")
+ fake = FakeDistillCore()
+
+ async def mock_runner(
+ home: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None = None,
+ max_messages: int = 800,
+ force_full_window: bool = False,
+ ) -> DistillRunResult:
+ del home, learning_since_ms, max_messages, force_full_window
+ return DistillRunResult(
+ job_id="job-rpc",
+ status="success",
+ window_start_ms=0,
+ window_end_ms=window_end_ms,
+ message_count=3,
+ sampled=False,
+ )
+
+ fake._distill_runner = mock_runner
+ monkeypatch.setattr(host, "_personal_context", fake)
+ return host, fake
+
+
+async def test_d7_runtime_patch_still_rejects_distill(
+ distill_host: tuple[PersonalContextHostAPI, FakeDistillCore],
+) -> None:
+ host, _fake = distill_host
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ }
+ )
+ with pytest.raises(PersonalContext.Error, match="unsupported fields"):
+ await host.patch_runtime_config({"distill": {"enabled": True}})
+
+
+async def test_patch_distill_config_writes_and_returns(
+ distill_host: tuple[PersonalContextHostAPI, FakeDistillCore],
+) -> None:
+ host, fake = distill_host
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": False, "interval_seconds": 86400},
+ }
+ )
+ result = await host.patch_distill_config(
+ {"enabled": True, "interval_seconds": 3600, "message_threshold": 10}
+ )
+ assert result["enabled"] is True
+ assert result["interval_seconds"] == 3600
+ assert result["message_threshold"] == 10
+ assert ("set_configuration", None) in fake.calls
+ cfg = await host.get_distill_config()
+ assert cfg["enabled"] is True
+ assert cfg["interval_seconds"] == 3600
+
+
+async def test_patch_distill_rejects_unknown_keys(
+ distill_host: tuple[PersonalContextHostAPI, FakeDistillCore],
+) -> None:
+ host, _fake = distill_host
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ }
+ )
+ with pytest.raises(PersonalContext.Error, match="unsupported fields"):
+ await host.patch_distill_config({"max_messages": 100})
+
+
+async def test_get_distill_status_reports_wired(
+ distill_host: tuple[PersonalContextHostAPI, FakeDistillCore],
+) -> None:
+ host, _fake = distill_host
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": True},
+ }
+ )
+ status = await host.get_distill_status()
+ assert status["wired"] is True
+ assert status["enabled"] is True
+ assert status["collection_enabled"] is False
+ assert "last_error" in status
+
+
+async def test_run_distill_now_rpc_success(
+ distill_host: tuple[PersonalContextHostAPI, FakeDistillCore],
+) -> None:
+ host, fake = distill_host
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": True},
+ }
+ )
+
+ async def mock_runner(
+ home: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None = None,
+ max_messages: int = 800,
+ force_full_window: bool = False,
+ ) -> DistillRunResult:
+ del home, learning_since_ms, max_messages, force_full_window
+ return DistillRunResult(
+ job_id="job-rpc",
+ status="success",
+ window_start_ms=0,
+ window_end_ms=window_end_ms,
+ message_count=3,
+ sampled=False,
+ )
+
+ # configure 会经 _ensure_distill_ports 重写 runner;测试再钉回 mock。
+ fake.set_distill_corpus("corpus")
+ fake.set_distill_runner(mock_runner)
+ result = await host.run_distill_now()
+ assert result == {"accepted": True}
+ task = host._distill_manual_task # pylint: disable=protected-access
+ assert task is not None
+ await task
+ status = await host.get_distill_status()
+ assert status["last_error"] is None
+ assert status["lease"] is None
+
+
+async def test_run_distill_now_fails_when_disabled(
+ distill_host: tuple[PersonalContextHostAPI, FakeDistillCore],
+) -> None:
+ host, _fake = distill_host
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": False},
+ }
+ )
+ with pytest.raises(PersonalContext.Error, match="distill_disabled"):
+ await host.run_distill_now()
+ status = await host.get_distill_status()
+ assert status["last_error"] == "distill_disabled"
diff --git a/tests/unit_tests/personal_context/test_distill_injection.py b/tests/unit_tests/personal_context/test_distill_injection.py
new file mode 100644
index 0000000000..a550f60d47
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_distill_injection.py
@@ -0,0 +1,104 @@
+"""Host distill port injection (HOST_DISTILL_INJECTION scope A: T1 / T2)."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from openjiuwen.harness.personal_context.distill import SqliteImCorpus
+
+import jiuwenswarm.server.personal_context.host_api as host_module
+from jiuwenswarm.server.personal_context.distill_ports import (
+ build_distill_corpus,
+)
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+
+def _pin_models(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(host_module, "get_default_models", list)
+ monkeypatch.setattr(
+ host_module, "_global_embedding_values", lambda: (None, None, None)
+ )
+
+
+def test_build_distill_corpus_returns_sqlite_im_corpus(tmp_path) -> None:
+ corpus = build_distill_corpus(tmp_path)
+ assert isinstance(corpus, SqliteImCorpus)
+
+
+def test_host_injects_distill_ports_on_construction(tmp_path) -> None:
+ """T1: Host construction injects corpus and runner while Core is stopped."""
+
+ host = PersonalContextHostAPI(home=tmp_path)
+ assert host.distill_ports_wired() is True
+ core = host._personal_context # pylint: disable=protected-access
+ assert isinstance(core._distill_corpus, SqliteImCorpus) # pylint: disable=protected-access
+ assert core._distill_runner is not None # pylint: disable=protected-access
+
+
+async def test_host_keeps_distill_ports_after_configure(tmp_path, monkeypatch) -> None:
+ """T1: configure / apply path still leaves ports wired."""
+
+ _pin_models(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "fetch_services": [],
+ "distill": {"enabled": False},
+ }
+ )
+ assert host.distill_ports_wired() is True
+ finally:
+ await host.stop()
+
+
+async def test_distill_scheduler_skips_when_disabled(tmp_path, monkeypatch) -> None:
+ """T2: distill.enabled=false → scheduler must not call the runner."""
+
+ _pin_models(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ calls: list[object] = []
+
+ async def mock_runner(
+ home: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None = None,
+ max_messages: int = 800,
+ force_full_window: bool = False,
+ ):
+ del home, window_end_ms, learning_since_ms, max_messages, force_full_window
+ calls.append("ran")
+ raise AssertionError("runner must not be called when distill is disabled")
+
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": True,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "fetch_services": [],
+ "distill": {
+ "enabled": False,
+ "interval_seconds": 1,
+ "message_threshold": 1,
+ "poll_seconds": 0.05,
+ },
+ }
+ )
+ core = host._personal_context # pylint: disable=protected-access
+ await core.deactivate_runtime(timeout_seconds=5.0)
+ core.set_distill_runner(mock_runner)
+ await core.activate_runtime()
+ await asyncio.sleep(0.2)
+ assert calls == []
+ finally:
+ await host.stop()
diff --git a/tests/unit_tests/personal_context/test_distill_run_now.py b/tests/unit_tests/personal_context/test_distill_run_now.py
new file mode 100644
index 0000000000..6b36b9709b
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_distill_run_now.py
@@ -0,0 +1,588 @@
+"""Host process-local distill run_now (HOST_DISTILL_INJECTION scope A: T3 / T4 / T5)."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+
+import pytest
+from openjiuwen.harness.personal_context import PersonalContext
+from openjiuwen.harness.personal_context.distill import (
+ DistillRunResult,
+ FixtureCorpus,
+ default_fixture_messages,
+ try_claim_distill_lease,
+)
+from openjiuwen.harness.personal_context.distill.store import get_distill_lease
+
+import jiuwenswarm.server.personal_context.host_api as host_module
+from jiuwenswarm.server.personal_context.distill_ports import build_distill_runner
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+_DISTILL_ENABLED_CONFIG = {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": True},
+}
+
+
+async def _wait_manual_distill(host: PersonalContextHostAPI) -> None:
+ task = host._distill_manual_task # pylint: disable=protected-access
+ assert task is not None
+ await task
+
+
+def _pin_empty_models(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(host_module, "get_default_models", list)
+ monkeypatch.setattr(
+ host_module, "_global_embedding_values", lambda: (None, None, None)
+ )
+
+
+def _pin_one_model(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ host_module,
+ "get_default_models",
+ lambda: [
+ {
+ "model_client_config": {
+ "client_provider": "OpenAI",
+ "api_key": "test-key",
+ "api_base": "https://example.invalid/v1",
+ "model_name": "test-model",
+ },
+ "model_config_obj": {"temperature": 0.2},
+ }
+ ],
+ )
+ monkeypatch.setattr(
+ host_module, "_global_embedding_values", lambda: (None, None, None)
+ )
+
+
+class _FakeLlm:
+ """Deterministic LlmPort stand-in for disk-product distill tests."""
+
+ async def complete(self, *, system: str, user: str) -> str:
+ del user
+ if "Persona 分析 Prompt" in system:
+ return '口头禅:["先看现有实现"]\n'
+ if "Persona 生成模板" in system:
+ return "# 本人 — Persona\n\n## Layer 2:表达风格\n- 先看现有实现\n"
+ if "Work Skill 分析 Prompt" in system:
+ return "负责领域:前端\n"
+ if "Work Skill 生成模板" in system:
+ return "# 本人 — Work Skill\n\n## 职责范围\n- 前端相关改动\n"
+ return "fallback\n"
+
+
+async def test_run_distill_now_invokes_injected_runner(tmp_path, monkeypatch) -> None:
+ """T3: enabled=true → process-local run_distill_now calls the injected runner."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ calls: list[dict[str, object]] = []
+
+ async def mock_runner(
+ home: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None = None,
+ max_messages: int = 800,
+ force_full_window: bool = False,
+ ) -> DistillRunResult:
+ calls.append(
+ {
+ "home": home,
+ "window_end_ms": window_end_ms,
+ "learning_since_ms": learning_since_ms,
+ "max_messages": max_messages,
+ "force_full_window": force_full_window,
+ }
+ )
+ return DistillRunResult(
+ job_id="job-mock",
+ status="success",
+ window_start_ms=0,
+ window_end_ms=window_end_ms,
+ message_count=0,
+ sampled=False,
+ )
+
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": True, "message_threshold": 1},
+ }
+ )
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(mock_runner)
+ accepted = await host.run_distill_now()
+ assert accepted == {"accepted": True}
+ await _wait_manual_distill(host)
+ assert len(calls) == 1
+ assert calls[0]["home"] == str(host._home) # pylint: disable=protected-access
+ assert get_distill_lease(str(host._home)) is None # pylint: disable=protected-access
+ status = await host.get_distill_status()
+ assert status["last_error"] is None
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_writes_profile_version(tmp_path, monkeypatch) -> None:
+ """T4: fixture corpus + fake LLM → versions/ + current.json on disk."""
+
+ _pin_one_model(monkeypatch)
+ home = tmp_path / "pc"
+ host = PersonalContextHostAPI(home=home)
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": True, "max_messages": 800},
+ }
+ )
+ corpus = FixtureCorpus(default_fixture_messages())
+ runner = build_distill_runner(
+ home=home,
+ corpus=corpus,
+ resolve_llm=lambda: _FakeLlm(),
+ )
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_corpus(corpus)
+ core.set_distill_runner(runner)
+
+ assert await host.run_distill_now() == {"accepted": True}
+ await _wait_manual_distill(host)
+
+ current = json.loads((home / "im" / "profiles" / "current.json").read_text(
+ encoding="utf-8"
+ ))
+ job_id = current["job_id"]
+ version_dir = home / "im" / "profiles" / "versions" / job_id
+ assert (version_dir / "persona.md").is_file()
+ assert (version_dir / "work.md").is_file()
+ assert (version_dir / "meta.json").is_file()
+
+ status = await host.get_distill_status()
+ assert status["last_error"] is None
+ assert status["last_success_job_id"] == job_id
+ assert status["lease"] is None
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_rejects_when_disabled(tmp_path, monkeypatch) -> None:
+ """T5: enabled=false → explicit failure, no success payload."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": False},
+ }
+ )
+ with pytest.raises(PersonalContext.Error, match="distill_disabled"):
+ await host.run_distill_now()
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_rejects_when_no_model(tmp_path, monkeypatch) -> None:
+ """T5: no model_index → explicit model-unavailable failure."""
+
+ _pin_empty_models(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "fetch_services": [],
+ "distill": {"enabled": True},
+ }
+ )
+ with pytest.raises(PersonalContext.Error, match="distill model unavailable"):
+ await host.run_distill_now()
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_rejects_when_not_wired(tmp_path, monkeypatch) -> None:
+ """T5: cleared ports → distill_not_wired."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ await host.start()
+ try:
+ await host.configure(
+ {
+ "collection_enabled": False,
+ "agent_use_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": 0,
+ "fetch_services": [],
+ "distill": {"enabled": True},
+ }
+ )
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_corpus(None)
+ core.set_distill_runner(None)
+ with pytest.raises(PersonalContext.Error, match="distill_not_wired"):
+ await host.run_distill_now()
+ finally:
+ await host.stop()
+
+
+def _blocking_runner(started: asyncio.Event, release: asyncio.Event):
+ async def runner(
+ home: str,
+ *,
+ window_end_ms: int,
+ learning_since_ms: int | None = None,
+ max_messages: int = 800,
+ force_full_window: bool = False,
+ ) -> DistillRunResult:
+ del home, learning_since_ms, max_messages, force_full_window
+ started.set()
+ await release.wait()
+ return DistillRunResult(
+ job_id="job-blocking",
+ status="success",
+ window_start_ms=0,
+ window_end_ms=window_end_ms,
+ message_count=1,
+ sampled=False,
+ )
+
+ return runner
+
+
+async def test_run_distill_now_does_not_block_host_and_holds_lease(
+ tmp_path, monkeypatch
+) -> None:
+ """G1/G2: RPC returns while runner is in flight; lease held until it ends."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ started = asyncio.Event()
+ release = asyncio.Event()
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(_blocking_runner(started, release))
+
+ assert await host.run_distill_now() == {"accepted": True}
+ await asyncio.wait_for(started.wait(), timeout=1.0)
+
+ # Host control plane stays responsive while the job runs.
+ status = await asyncio.wait_for(host.get_distill_status(), timeout=1.0)
+ assert status["lease"] is not None
+
+ release.set()
+ await _wait_manual_distill(host)
+ assert get_distill_lease(str(host._home)) is None # pylint: disable=protected-access
+ finally:
+ release.set()
+ await host.stop()
+
+
+async def test_run_distill_now_rejects_when_lease_held(tmp_path, monkeypatch) -> None:
+ """G3: scheduler (or another manual run) holds the lease → distill_busy."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ calls: list[int] = []
+
+ async def mock_runner(home: str, **kwargs: object) -> DistillRunResult:
+ del home, kwargs
+ calls.append(1)
+ return DistillRunResult(
+ job_id="never",
+ status="success",
+ window_start_ms=0,
+ window_end_ms=0,
+ message_count=0,
+ sampled=False,
+ )
+
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(mock_runner)
+ home = str(host._home) # pylint: disable=protected-access
+ token = try_claim_distill_lease(
+ home, now_ms=int(time.time() * 1000), lease_ms=3_600_000
+ )
+ assert token is not None
+
+ with pytest.raises(PersonalContext.Error, match="distill_busy"):
+ await host.run_distill_now()
+ assert calls == []
+ assert host._distill_manual_task is None # pylint: disable=protected-access
+ # Rejection is not a run error.
+ status = await host.get_distill_status()
+ assert status["last_error"] is None
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_releases_lease_when_create_task_fails(
+ tmp_path, monkeypatch
+) -> None:
+ """§2.1: create_task failure after claim must return the lease."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+
+ async def unused_runner(home: str, **kwargs: object) -> DistillRunResult:
+ del home, kwargs
+ raise AssertionError("runner must not start")
+
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(unused_runner)
+ original_create_task = host_module.asyncio.create_task
+
+ def _fail_create_task(coro, *args, **kwargs):
+ del args, kwargs
+ coro.close()
+ raise RuntimeError("no loop")
+
+ monkeypatch.setattr(host_module.asyncio, "create_task", _fail_create_task)
+ try:
+ with pytest.raises(RuntimeError, match="no loop"):
+ await host.run_distill_now()
+ finally:
+ monkeypatch.setattr(host_module.asyncio, "create_task", original_create_task)
+ assert host._distill_manual_task is None # pylint: disable=protected-access
+ assert get_distill_lease(str(host._home)) is None # pylint: disable=protected-access
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_rejects_duplicate_manual_run(
+ tmp_path, monkeypatch
+) -> None:
+ """G3: second manual request while the first is still running → distill_busy."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ started = asyncio.Event()
+ release = asyncio.Event()
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(_blocking_runner(started, release))
+
+ assert await host.run_distill_now() == {"accepted": True}
+ await asyncio.wait_for(started.wait(), timeout=1.0)
+ with pytest.raises(PersonalContext.Error, match="distill_busy"):
+ await host.run_distill_now()
+ release.set()
+ await _wait_manual_distill(host)
+ finally:
+ release.set()
+ await host.stop()
+
+
+async def test_run_distill_now_records_failed_result(tmp_path, monkeypatch) -> None:
+ """G5: runner returns status=failed → last_error carries result.error."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+
+ async def failing_runner(home: str, **kwargs: object) -> DistillRunResult:
+ del home
+ return DistillRunResult(
+ job_id="job-failed",
+ status="failed",
+ window_start_ms=0,
+ window_end_ms=int(kwargs["window_end_ms"]),
+ message_count=0,
+ sampled=False,
+ error="llm returned empty content",
+ )
+
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(failing_runner)
+ assert await host.run_distill_now() == {"accepted": True}
+ await _wait_manual_distill(host)
+ status = await host.get_distill_status()
+ assert status["last_error"] == "llm returned empty content"
+ assert status["lease"] is None
+ finally:
+ await host.stop()
+
+
+async def test_run_distill_now_records_runner_exception(tmp_path, monkeypatch) -> None:
+ """G5: runner raises → last_error carries the message; lease released."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+
+ async def raising_runner(home: str, **kwargs: object) -> DistillRunResult:
+ del home, kwargs
+ raise RuntimeError("boom")
+
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(raising_runner)
+ assert await host.run_distill_now() == {"accepted": True}
+ await _wait_manual_distill(host)
+ status = await host.get_distill_status()
+ assert status["last_error"] == "boom"
+ assert status["lease"] is None
+ finally:
+ await host.stop()
+
+
+async def test_stop_cancels_manual_distill_and_releases_lease(
+ tmp_path, monkeypatch
+) -> None:
+ """G6: host.stop() cancels the in-flight manual job; lease is released."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ started = asyncio.Event()
+ release = asyncio.Event()
+ await host.start()
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(_blocking_runner(started, release))
+
+ assert await host.run_distill_now() == {"accepted": True}
+ await asyncio.wait_for(started.wait(), timeout=1.0)
+ task = host._distill_manual_task # pylint: disable=protected-access
+ assert task is not None
+
+ await host.stop()
+
+ assert task.cancelled()
+ assert host._distill_manual_task is None # pylint: disable=protected-access
+ assert get_distill_lease(str(host._home)) is None # pylint: disable=protected-access
+ status = await host.get_distill_status()
+ assert status["last_error"] == "distill_cancelled"
+
+
+async def test_patch_distill_config_cancels_manual_distill(
+ tmp_path, monkeypatch
+) -> None:
+ """G6: a configuration change that restarts the runtime cancels the manual job."""
+
+ _pin_one_model(monkeypatch)
+ host = PersonalContextHostAPI(home=tmp_path / "pc")
+ started = asyncio.Event()
+ release = asyncio.Event()
+ await host.start()
+ try:
+ await host.configure(dict(_DISTILL_ENABLED_CONFIG))
+ core = host._personal_context # pylint: disable=protected-access
+ core.set_distill_runner(_blocking_runner(started, release))
+
+ assert await host.run_distill_now() == {"accepted": True}
+ await asyncio.wait_for(started.wait(), timeout=1.0)
+ task = host._distill_manual_task # pylint: disable=protected-access
+ assert task is not None
+
+ await host.patch_distill_config({"interval_seconds": 3600})
+
+ assert task.cancelled()
+ assert get_distill_lease(str(host._home)) is None # pylint: disable=protected-access
+ finally:
+ release.set()
+ await host.stop()
+
+
+async def test_build_distill_runner_delegates_to_run_distill_job(
+ tmp_path, monkeypatch
+) -> None:
+ """Factory runner forwards DistillRunnerPort kwargs into run_distill_job."""
+
+ seen: dict[str, object] = {}
+
+ async def fake_job(home, **kwargs):
+ seen["home"] = home
+ seen.update(kwargs)
+ return DistillRunResult(
+ job_id="x",
+ status="success",
+ window_start_ms=0,
+ window_end_ms=kwargs["window_end_ms"],
+ message_count=0,
+ sampled=False,
+ )
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.personal_context.distill_ports.run_distill_job",
+ fake_job,
+ )
+ corpus = FixtureCorpus(default_fixture_messages())
+ runner = build_distill_runner(
+ home=tmp_path,
+ corpus=corpus,
+ resolve_llm=lambda: _FakeLlm(),
+ )
+ result = await runner(
+ str(tmp_path),
+ window_end_ms=99,
+ learning_since_ms=1,
+ max_messages=10,
+ force_full_window=True,
+ )
+ assert result.job_id == "x"
+ assert seen["home"] == str(tmp_path)
+ assert seen["window_end_ms"] == 99
+ assert seen["learning_since_ms"] == 1
+ assert seen["max_messages"] == 10
+ assert seen["force_full_window"] is True
+ assert seen["corpus"] is corpus
+ assert "llm" in seen
diff --git a/tests/unit_tests/personal_context/test_host_api.py b/tests/unit_tests/personal_context/test_host_api.py
index c09a3e69d4..101b56b023 100644
--- a/tests/unit_tests/personal_context/test_host_api.py
+++ b/tests/unit_tests/personal_context/test_host_api.py
@@ -209,6 +209,14 @@ class FakeCore:
self.authorization_status_error: BaseException | None = None
self.authorization_status_started: asyncio.Event | None = None
self.authorization_status_release: asyncio.Event | None = None
+ self._distill_corpus: object | None = None
+ self._distill_runner: object | None = None
+
+ def set_distill_corpus(self, corpus: object | None) -> None:
+ self._distill_corpus = corpus
+
+ def set_distill_runner(self, runner: object | None) -> None:
+ self._distill_runner = runner
def _set_embedding_configuration(
self,
diff --git a/tests/unit_tests/personal_context/test_im_learning_api.py b/tests/unit_tests/personal_context/test_im_learning_api.py
index ecfaace444..930fb062ab 100644
--- a/tests/unit_tests/personal_context/test_im_learning_api.py
+++ b/tests/unit_tests/personal_context/test_im_learning_api.py
@@ -43,6 +43,14 @@ class FakeImLearningCore:
"targets": 2,
}
self.im_learning_trigger_result = True
+ self._distill_corpus: object | None = None
+ self._distill_runner: object | None = None
+
+ def set_distill_corpus(self, corpus: object | None) -> None:
+ self._distill_corpus = corpus
+
+ def set_distill_runner(self, runner: object | None) -> None:
+ self._distill_runner = runner
def _set_embedding_configuration(
self,
diff --git a/tests/unit_tests/personal_context/test_profiles_api.py b/tests/unit_tests/personal_context/test_profiles_api.py
new file mode 100644
index 0000000000..08dd5d2d75
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_profiles_api.py
@@ -0,0 +1,184 @@
+"""WEB-03 profiles list / preview / activate (Host disk scan + Core activate)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from openjiuwen.harness.personal_context import PersonalContext
+
+from jiuwenswarm.server.personal_context import host_api as host_module
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+from jiuwenswarm.server.personal_context.profiles_ops import (
+ activate_profile,
+ get_profile_version,
+ list_profile_versions,
+)
+
+
+def _pin_models(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(host_module, "get_default_models", list)
+ monkeypatch.setattr(
+ host_module, "_global_embedding_values", lambda: (None, None, None)
+ )
+
+
+def _write_version(home: Path, job_id: str, *, published_at_ms: int = 1000) -> None:
+ root = home / "im" / "profiles" / "versions" / job_id
+ root.mkdir(parents=True, exist_ok=True)
+ (root / "persona.md").write_text(f"# persona {job_id}\n", encoding="utf-8")
+ (root / "work.md").write_text(f"# work {job_id}\n", encoding="utf-8")
+ (root / "meta.json").write_text(
+ json.dumps(
+ {
+ "published_at_ms": published_at_ms,
+ "source": "distill",
+ "message_count": 5,
+ "analyzer": "LlmAnalyzer",
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def _write_current(home: Path, job_id: str, *, published_at_ms: int = 1000) -> None:
+ path = home / "im" / "profiles" / "current.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps(
+ {
+ "job_id": job_id,
+ "source": "distill",
+ "published_at_ms": published_at_ms,
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def profile_host(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> PersonalContextHostAPI:
+ _pin_models(monkeypatch)
+ return PersonalContextHostAPI(home=tmp_path / "personal_context")
+
+
+def test_list_profile_versions_marks_current(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ _write_version(home, "job-a", published_at_ms=100)
+ _write_version(home, "job-b", published_at_ms=200)
+ _write_current(home, "job-a", published_at_ms=100)
+ items = list_profile_versions(str(home))
+ assert [item["job_id"] for item in items] == ["job-a", "job-b"]
+ assert items[0]["is_current"] is True
+ assert items[1]["is_current"] is False
+
+
+async def test_host_list_get_activate(profile_host: PersonalContextHostAPI) -> None:
+ home = profile_host._home # pylint: disable=protected-access
+ _write_version(home, "job-old", published_at_ms=100)
+ _write_version(home, "job-new", published_at_ms=200)
+ _write_current(home, "job-old", published_at_ms=100)
+
+ listed = await profile_host.list_profiles()
+ assert len(listed["versions"]) == 2
+
+ current = await profile_host.get_current_profile_payload()
+ assert current["current"] is not None
+ assert current["current"]["job_id"] == "job-old"
+
+ preview = await profile_host.get_profile_version_payload("job-new")
+ assert "persona job-new" in preview["persona_md"]
+ assert preview["truncated"] is False
+
+ activated = await profile_host.activate_profile_version_payload("job-new")
+ assert activated["current"]["job_id"] == "job-new"
+ assert activated["current"]["source"] == "manual_switch"
+ assert any(
+ item["job_id"] == "job-new" and item["is_current"]
+ for item in activated["versions"]
+ )
+
+ current_after = await profile_host.get_current_profile_payload()
+ assert current_after["current"]["job_id"] == "job-new"
+
+
+async def test_activate_missing_version_fails(
+ profile_host: PersonalContextHostAPI,
+) -> None:
+ with pytest.raises(PersonalContext.Error):
+ await profile_host.activate_profile_version_payload("missing-job")
+
+
+ "job_id",
+ [
+ "../x",
+ "..\\x",
+ "a/b",
+ "a\\b",
+ "..",
+ ".",
+ "",
+ " ",
+ "job/../other",
+ ],
+)
+def test_unsafe_job_id_rejected_by_ops(tmp_path: Path, job_id: str) -> None:
+ home = tmp_path / "home"
+ _write_version(home, "legit-job", published_at_ms=1)
+ # Plant a decoy outside versions that traversal would otherwise reach.
+ decoy = home / "im" / "profiles" / "x"
+ decoy.mkdir(parents=True, exist_ok=True)
+ (decoy / "persona.md").write_text("# decoy\n", encoding="utf-8")
+ (decoy / "work.md").write_text("# decoy\n", encoding="utf-8")
+ (decoy / "meta.json").write_text("{}", encoding="utf-8")
+
+ with pytest.raises(ValueError):
+ get_profile_version(str(home), job_id)
+ with pytest.raises(ValueError):
+ activate_profile(str(home), job_id)
+
+
+ "job_id",
+ ["../x", "..\\x", "a/b", "..", "job/../other"],
+)
+async def test_host_rejects_path_traversal_job_id(
+ profile_host: PersonalContextHostAPI,
+ job_id: str,
+) -> None:
+ home = profile_host._home # pylint: disable=protected-access
+ _write_version(home, "legit-job", published_at_ms=1)
+ decoy = home / "im" / "profiles" / "x"
+ decoy.mkdir(parents=True, exist_ok=True)
+ (decoy / "persona.md").write_text("# decoy\n", encoding="utf-8")
+ (decoy / "work.md").write_text("# decoy\n", encoding="utf-8")
+ (decoy / "meta.json").write_text("{}", encoding="utf-8")
+
+ with pytest.raises(PersonalContext.Error):
+ await profile_host.get_profile_version_payload(job_id)
+ with pytest.raises(PersonalContext.Error):
+ await profile_host.activate_profile_version_payload(job_id)
+
+ # Pointer must remain untouched when activate is rejected.
+ assert not (home / "im" / "profiles" / "current.json").exists()
+
+
+def test_list_skips_unsafe_directory_names(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ _write_version(home, "legit-job", published_at_ms=1)
+ # Create a nested illegal layout under versions (should be ignored).
+ nested = home / "im" / "profiles" / "versions" / "nested" / "child"
+ nested.mkdir(parents=True, exist_ok=True)
+ (nested / "persona.md").write_text("# nested\n", encoding="utf-8")
+ (nested / "work.md").write_text("# nested\n", encoding="utf-8")
+ (nested / "meta.json").write_text("{}", encoding="utf-8")
+
+ items = list_profile_versions(str(home))
+ assert [item["job_id"] for item in items] == ["legit-job"]