chore: D22 落地——docs/SDD/wiki/CLAUDE.md 進 repo(Gitea private 預設全 push)

頂層 D22 決策(leo 2026-07-03 拍板):推什麼由開發環境歸屬決定,
Gitea private=除機敏值/build 產物/.github 外全 push。
解 T1.5 卡點:雲端工人 clone 拿得到 credential-store-migration.md,可就地改寫 SDD。
機敏掃描兩輪通過(新增 189 檔約 2.1MB,node_modules/dist/wasm 照舊排除)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
uncle6me-web
2026-07-03 07:13:15 +08:00
parent c830150da1
commit 5d00e71275
190 changed files with 39486 additions and 14 deletions
+199
View File
@@ -0,0 +1,199 @@
'use client';
// Mira 對話核心元件(河道右側 dock 與 /mira/chat 單頁共用)
// SDD: polaris/mira/.agents/specs/mira-app/design.md §3.6.5
// RAG:提問先語義搜尋 KBDBwiki + 河道)取 context → claude-api daemon。
// 重要:context 空時 prompt 明確要求「只說沒有相關筆記」,避免 daemon 自由發揮(曾幻想 OpenWebUI
import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { MarkdownView } from './markdown';
const KBDB_BASE = 'https://kbdb.finally.click';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
const CLAUDE_API = 'https://claude-api.arcrun.dev';
type Source = { label: string; href: string };
type Msg = { role: 'user' | 'mira'; text: string; sources?: Source[]; pending?: boolean };
type SearchMatch = {
score: number;
type: 'block' | 'triplet';
block: { id: string; page_name: string | null; content: string | null; type: string } | null;
triplet: { subject?: string; predicate?: string; object?: string } | null;
};
// 繁體異體字正規化(臺→台 等),讓 query 跟 KB 內容(多用「台」)對得上
function normalizeQuery(q: string): string {
return q.replace(/臺/g, '台');
}
async function fetchContext(apiKey: string, query: string): Promise<{ context: string; sources: Source[] }> {
try {
const res = await fetch(`${KBDB_BASE}/search`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
body: JSON.stringify({ query: normalizeQuery(query), type: 'semantic', topK: 8 }),
});
if (!res.ok) return { context: '', sources: [] };
const data = (await res.json()) as { matches?: SearchMatch[] };
const parts: string[] = [];
const sources: Source[] = [];
for (const m of data.matches ?? []) {
if (m.block?.content) {
const b = m.block;
parts.push(`### ${b.type}${b.page_name ?? b.id}\n${b.content}`);
if (b.type === 'wiki-page' && b.page_name) {
sources.push({ label: `📚 ${(b.content || b.page_name).slice(0, 20)}`, href: `/mira/wiki/${encodeURIComponent(b.page_name)}` });
} else if (b.page_name) {
sources.push({ label: `🌊 ${(b.content || '').slice(0, 20) || b.page_name}`, href: `/mira/feed#page=${encodeURIComponent(b.page_name)}` });
}
} else if (m.triplet) {
const t = m.triplet;
parts.push(`關係:${t.subject} >> ${t.predicate} >> ${t.object}`);
}
}
const seen = new Set<string>();
const uniq = sources.filter(s => (seen.has(s.href) ? false : (seen.add(s.href), true)));
return { context: parts.join('\n\n'), sources: uniq.slice(0, 5) };
} catch {
return { context: '', sources: [] };
}
}
function buildPrompt(history: Msg[], context: string, question: string): string {
const convo = history
.filter(m => !m.pending)
.map(m => `${m.role === 'user' ? 'leo' : 'Mira'}${m.text}`)
.join('\n');
const persona =
`你是 Mira,leo 的個人知識庫副駕 AI。你只能根據下方「知識庫」與「對話脈絡」回答,` +
`沒有任何外部系統存取權(沒有 OpenWebUI、沒有檔案系統、沒有別的工具)。\n\n`;
const kb = context
? `## 知識庫(跟本次提問相關的 wiki / 河道內容)\n\n${context}\n\n`
: `## 知識庫\n(這次在 leo 的筆記裡找不到相關內容。)\n\n`;
const rules = context
? `規則:繁體中文(台灣用語)、務實不客套、優先引用上方知識庫並說「你之前寫過⋯」、簡短切題。`
: `規則:繁體中文。**明確告訴 leo「你的筆記裡目前沒有關於這個的內容」**,` +
`可以再用常識補一兩句(要標明那不是來自他的筆記),不要假裝有資料、不要編造系統或工具。`;
return (
persona +
kb +
(convo ? `## 對話脈絡\n${convo}\n\n` : '') +
`---\n\nleo 現在問:「${question}\n\n${rules}`
);
}
export default function MiraChat({ compact = false }: { compact?: boolean }) {
const [apiKey, setApiKey] = useState<string | null>(null);
const [msgs, setMsgs] = useState<Msg[]>([]);
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
useEffect(() => {
fetch(`${API_BASE}/me`, { credentials: 'include' })
.then(r => (r.ok ? r.json() : null))
.then((me: { api_key: string } | null) => { if (me?.api_key) setApiKey(me.api_key); })
.catch(() => {});
}, []);
useEffect(() => {
logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: 'smooth' });
}, [msgs]);
const send = async () => {
const question = input.trim();
if (!question || sending || !apiKey) return;
setInput('');
setSending(true);
const history = msgs;
setMsgs(m => [...m, { role: 'user', text: question }, { role: 'mira', text: '', pending: true }]);
try {
const { context, sources } = await fetchContext(apiKey, question);
const prompt = buildPrompt(history, context, question);
const res = await fetch(CLAUDE_API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, timeout_ms: 60000 }),
});
const data = (await res.json()) as { success?: boolean; pending?: boolean; data?: { text?: string }; error?: string };
let text: string;
if (!res.ok || !data.success) text = `(回答失敗:${data.error ?? res.status}`;
else if (data.pending) text = 'Mira 還在想,daemon 切到背景模式,請稍後再問一次)';
else text = data.data?.text ?? '(沒有內容)';
setMsgs(m => {
const next = [...m];
next[next.length - 1] = { role: 'mira', text, sources: sources.length ? sources : undefined };
return next;
});
} catch (e) {
setMsgs(m => {
const next = [...m];
next[next.length - 1] = { role: 'mira', text: `(錯誤:${e instanceof Error ? e.message : String(e)}` };
return next;
});
} finally {
setSending(false);
}
};
return (
<div className={`mira-chat${compact ? ' is-compact' : ''}`}>
<div className="mira-chat-log" ref={logRef}>
{msgs.length === 0 && (
<div className="empty-state" style={{ marginTop: 28 }}>
<div style={{ fontSize: 40, marginBottom: 8 }}>💬</div>
<p style={{ color: 'var(--mira-text-2)', fontSize: 13 }}> Mira </p>
</div>
)}
{msgs.map((m, i) => (
<div key={i} className={`mira-chat-msg ${m.role === 'user' ? 'is-user' : 'is-mira'}`}>
<div className="mira-chat-bubble">
{m.pending ? (
<span className="mira-thinking-dots">Mira </span>
) : m.role === 'mira' ? (
<MarkdownView text={m.text} />
) : (
m.text
)}
{m.sources && m.sources.length > 0 && (
<div className="mira-chat-sources">
{m.sources.map((s, j) => (
<span key={j}>
{j > 0 && ' · '}
<Link href={s.href}>{s.label}</Link>
</span>
))}
</div>
)}
</div>
</div>
))}
</div>
<div className="mira-chat-input-row">
<textarea
className="mira-chat-input"
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); void send(); }
}}
placeholder="問 Mira…(⌘+Enter 送出)"
rows={2}
disabled={sending || !apiKey}
/>
<button
type="button"
className="mira-btn-primary"
onClick={() => void send()}
disabled={sending || !apiKey || !input.trim()}
>
{sending ? '⋯' : '送出'}
</button>
</div>
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
'use client';
// Mira 右側常駐對話 dock(桌機,所有頁簽都在;手機隱藏改走 /mira/chat 單頁)
// 可收合,狀態存 localStorage。SDD: design.md §3.6.5 對話內建化
import { useEffect, useState } from 'react';
import MiraChat from './MiraChat';
const LS_KEY = 'mira-chat-dock-open';
export default function MiraChatDock() {
const [open, setOpen] = useState(false);
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
setOpen(localStorage.getItem(LS_KEY) === '1');
}, []);
const toggle = () => {
setOpen(o => {
const next = !o;
localStorage.setItem(LS_KEY, next ? '1' : '0');
return next;
});
};
// SSR/首渲不輸出,避免 hydration 閃爍
if (!mounted) return null;
return (
<div className={`mira-chat-dock${open ? ' is-open' : ''}`}>
{open ? (
<>
<header className="mira-chat-dock-head">
<span>💬 Mira </span>
<button type="button" className="mira-chat-dock-close" onClick={toggle} aria-label="收合對話"></button>
</header>
<MiraChat compact />
</>
) : (
<button type="button" className="mira-chat-dock-fab" onClick={toggle} title="開啟 Mira 對話">
💬
</button>
)}
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
'use client';
// Mira 側邊欄(桌機左固定欄 / 手機底部 tab bar)
// SDD: polaris/mira/.agents/specs/mira-app/design.md §5.2 v2.1 + §3.7.4
// 對應 task: 10B0.1 / 10B0.2 / 10B0.4
// 現階段入口手寫;detector framework#8)上線後改讀 detector view 規格動態生成
import { useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
type NavItem = {
href: string;
icon: string;
label: string;
status: 'live' | 'planned';
};
// 側邊欄入口 = 各 detector 的 view(§3.7.4)。河道是固定輸入入口,其餘是 detector 產物頁。
const NAV_ITEMS: NavItem[] = [
{ href: '/mira/feed', icon: '🌊', label: '河道', status: 'live' },
{ href: '/mira/chat', icon: '💬', label: '對話', status: 'live' },
{ href: '/mira/wiki', icon: '📚', label: 'Wiki', status: 'live' },
{ href: '/mira/projects', icon: '📋', label: '專案', status: 'live' },
{ href: '/mira/dissent', icon: '⚔️', label: '異見牆', status: 'planned' },
];
function isActive(pathname: string | null, href: string): boolean {
if (!pathname) return false;
if (href === '/mira/feed') return pathname === '/mira/feed' || pathname === '/mira';
return pathname === href || pathname.startsWith(href + '/');
}
export default function MiraSidebar() {
const pathname = usePathname();
const router = useRouter();
const [q, setQ] = useState('');
const submitSearch = (e: React.FormEvent) => {
e.preventDefault();
const query = q.trim();
if (!query) return;
router.push(`/mira/search?q=${encodeURIComponent(query)}`);
};
return (
<nav className="mira-sidebar" aria-label="Mira 導覽">
<Link href="/mira/feed" className="mira-sidebar-logo">
<span className="mira-sidebar-logo-icon">🦔</span>
<span className="mira-sidebar-logo-text">Mira</span>
</Link>
{/* 桌機:側欄輸入框 */}
<form className="mira-sidebar-search" onSubmit={submitSearch}>
<input
value={q}
onChange={e => setQ(e.target.value)}
placeholder="🔍 搜尋 wiki…"
aria-label="搜尋"
/>
</form>
{/* 手機:底部 bar 已滿,搜尋收成一個放大鏡 icon → 去搜尋頁輸入 */}
<Link
href="/mira/search"
className={`mira-sidebar-search-icon${isActive(pathname, '/mira/search') ? ' is-active' : ''}`}
aria-label="搜尋"
title="搜尋"
>
🔍
</Link>
<ul className="mira-sidebar-list">
{NAV_ITEMS.map(item => {
const active = isActive(pathname, item.href);
const planned = item.status === 'planned';
const className = `mira-sidebar-item${active ? ' is-active' : ''}${planned ? ' is-planned' : ''}`;
const inner = (
<>
<span className="mira-sidebar-icon">{item.icon}</span>
<span className="mira-sidebar-label">{item.label}</span>
{planned && <span className="mira-sidebar-badge"></span>}
</>
);
return (
<li key={item.href}>
{planned ? (
<span className={className} aria-disabled="true" title="即將開放">
{inner}
</span>
) : (
<Link href={item.href} className={className} aria-current={active ? 'page' : undefined}>
{inner}
</Link>
)}
</li>
);
})}
</ul>
</nav>
);
}
+93
View File
@@ -0,0 +1,93 @@
'use client';
// Mira 共用 Markdown 渲染器(河道 + Wiki 共用)
// SDD: polaris/mira/.agents/specs/mira-app/design.md §3.5.7
import { useMemo } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
export function MarkdownView({ text }: { text: string }) {
// 三階段預處理:1. strip Logseq metadata2. [[entity]] 轉 link3. raw:<uuid> 轉河道 deep-link
const cleaned = useMemo(
() => expandRawRefs(expandWikilinks(stripLogseqMeta(text))),
[text],
);
return (
<div className="mira-md">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
a: ({ href, children, ...rest }) => {
const isInternal =
typeof href === 'string' &&
(href.startsWith('/mira/wiki/') || href.startsWith('/mira/feed'));
return (
<a
href={href}
{...(isInternal ? {} : { target: '_blank', rel: 'noopener noreferrer' })}
className="wiki-link"
{...rest}
>
{children}
</a>
);
},
// 圖片不直接 inline 顯示(避免大圖打亂 feed),改成連結
img: ({ src, alt }) => {
const href = typeof src === 'string' ? src : '';
return href ? (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="wiki-link"
style={{ fontStyle: 'italic' }}
>
🖼 {alt || 'image'}
</a>
) : null;
},
}}
>
{cleaned}
</ReactMarkdown>
</div>
);
}
// Strip Logseq 專屬語法
// - 屬性行:`xxx:: yyy`、`collapsed:: true`、`id:: ...`、`logseq.order-list-type:: ...`
// - block ref`((uuid))` 暫時保留為純文字
export function stripLogseqMeta(text: string): string {
return text
.split('\n')
.filter((line) => {
const trimmed = line.trimStart();
if (/^[a-zA-Z][a-zA-Z0-9_.-]*::\s/.test(trimmed)) return false;
return true;
})
.join('\n');
}
// 把 [[entity]] 轉成 markdown link 指向 /mira/wiki/wiki-{entity}
// 對應 mira-app design.md §3.6.2 + tasks.md backlog #12
export function expandWikilinks(text: string): string {
return text.replace(/\[\[([^\[\]\n]+?)\]\]/g, (_, entity: string) => {
const e = entity.trim();
if (!e) return '[[]]';
const url = `/mira/wiki/${encodeURIComponent('wiki-' + e)}`;
return `[${e}](${url})`;
});
}
// index-entry / wiki backlink 區塊內的 `raw:<uuid>` bare 文字轉成可點河道 deep-link。
// 對應 leo 反饋 #3index 顯示 uuid 無法點擊。河道 hash handler 認得 #raw=<id> 並解析回 page_name。
// 已在 markdown link 內([..](..))的不重複處理;只抓裸 raw:uuid。
const UUID_RE = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
export function expandRawRefs(text: string): string {
return text.replace(
new RegExp(`(?<![\\(\\[\\w])raw:(${UUID_RE})`, 'g'),
(_m, id: string) => `[raw:${id.slice(0, 8)}…](/mira/feed#raw=${id})`,
);
}
+23
View File
@@ -0,0 +1,23 @@
'use client';
export const runtime = 'edge';
// Mira 對話單頁(手機用;桌機改用 layout.tsx 的右側 dock
// SDD: polaris/mira/.agents/specs/mira-app/design.md §3.6.5
import Link from 'next/link';
import MiraChat from '../_shared/MiraChat';
import '../mira.css';
export default function MiraChatPage() {
return (
<main className="mira-page mira-chat-page">
<header style={{ padding: '16px 0 4px' }}>
<Link href="/mira/feed" style={{ color: '#888', fontSize: 14, textDecoration: 'none' }}> </Link>
<h1 style={{ fontSize: 20, fontWeight: 700, color: '#fff', margin: '6px 0 0' }}>💬 Mira </h1>
<p style={{ color: '#888', fontSize: 12, marginTop: 2 }}> wiki / </p>
</header>
<MiraChat />
</main>
);
}
File diff suppressed because it is too large Load Diff
+96
View File
@@ -0,0 +1,96 @@
'use client';
// Mira 子應用 layout
// SDD: polaris/mira/.agents/specs/mira-app/design.md §5.5
// 規範:白名單 user 進得去;非白名單 user 看到「即將開放」頁
// middleware 已做未登入跳 /loginredirect=/mira 檢查(不在這裡重做)
import { useEffect, useState } from 'react';
import SiteNav from '../components/SiteNav';
import { MATRIX_APPS } from '../components/apps';
import MiraSidebar from './_shared/MiraSidebar';
import MiraChatDock from './_shared/MiraChatDock';
import './mira.css';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
type Me = { email: string; display_name: string; api_key: string };
const MIRA = MATRIX_APPS.find(a => a.id === 'mira');
const ALLOWED = new Set(MIRA?.allowlist_emails ?? []);
export default function MiraLayout({ children }: { children: React.ReactNode }) {
const [me, setMe] = useState<Me | null | undefined>(undefined);
useEffect(() => {
fetch(`${API_BASE}/me`, { credentials: 'include' })
.then(r => r.ok ? r.json() as Promise<Me> : null)
.then(u => setMe(u))
.catch(() => setMe(null));
}, []);
if (me === undefined) {
return (
<>
<SiteNav currentPath="/mira" />
<div className="flex-1 flex items-center justify-center text-[#666]"></div>
</>
);
}
if (me === null) {
// 理論上 middleware 已擋住,但保險
if (typeof window !== 'undefined') {
window.location.href = '/login?redirect=/mira';
}
return null;
}
if (!ALLOWED.has(me.email)) {
return (
<>
<SiteNav currentPath="/mira" />
<BetaBlocked email={me.email} />
</>
);
}
return (
<>
<div className="mira-topnav-sticky">
<SiteNav currentPath="/mira" />
</div>
<div className="mira-app mira-shell">
<MiraSidebar />
<div className="mira-shell-content">{children}</div>
<MiraChatDock />
</div>
</>
);
}
function BetaBlocked({ email }: { email: string }) {
return (
<main className="flex-1 flex items-center justify-center px-6">
<div className="max-w-md text-center space-y-4">
<div className="text-6xl mb-2">🌊</div>
<h1 className="text-3xl font-bold text-white">Mira </h1>
<p className="text-[#888] leading-relaxed">
Mira arcrun KM
</p>
<p className="text-sm text-[#555]">
<span className="font-mono text-[#888]">{email}</span>
</p>
<div className="pt-4">
<a
href="/dashboard"
className="inline-block bg-indigo-600 hover:bg-indigo-500 text-white px-5 py-2 rounded-md text-sm font-medium transition-colors"
>
Dashboard
</a>
</div>
</div>
</main>
);
}
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
import { redirect } from 'next/navigation';
// Mira 首頁 → redirect 到河道
// SDD: polaris/mira/.agents/specs/mira-app/design.md §5.2 v2.1
// v2.1 改側邊欄式版面後,原本的卡片入口導覽移到側邊欄(MiraSidebar),
// 首頁不再需要列入口,直接進河道(feed = 主要輸入/瀏覽頁)
export default function MiraHubPage() {
redirect('/mira/feed');
}
+300
View File
@@ -0,0 +1,300 @@
'use client';
// Mira repo 總管 + 工作台
// SDD: polaris/mira/.agents/specs/mira-app/design.md §3.9.1.2 + §5.2 v2.1
// 對應 task: 階段 10-B
// GitHub = repo 全清單 SSOTclone 到 Hetzner = 激活進工作態
// 資料源:mira daemon GET /projects(轉發 AI-Meka GitHub 掃描器)
import { useEffect, useMemo, useState } from 'react';
import '../mira.css';
// mira daemonnginx mira.uncle6.me/mira/ → 容器)
const DAEMON = process.env.NEXT_PUBLIC_MIRA_DAEMON ?? 'https://mira.uncle6.me/mira';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
const KBDB_BASE = 'https://kbdb.finally.click'; // 既有技術債(同 feed/wiki),KI-3 未解前沿用
export type RepoSummary = {
name: string;
full_name: string;
cloned: boolean;
has_sdd: boolean;
archived: boolean;
fork: boolean;
total: number;
done: number;
in_progress: number;
ai_count: number;
leo_count: number;
blocked_count: number;
last_activity: string | null;
};
// project_detector 拆出的 todo blocktype=note, source=ai-project-detector
// G1:一篇河道筆記可拆多條 todo,各自掛 suggested-repodesign.md §3.7.5.7
type Todo = {
id: string;
content: string;
suggested_repo: string; // repo name 或 "new"
raw_id: string; // 溯源回河道原 raw(raw: tag),給「來自河道」連結
};
type Filter = 'sdd' | 'all';
// 從 tags_json 解析 detector 打的 tag
function parseTodoTags(tagsJson: string | null): { isTodo: boolean; repo: string; rawId: string } {
let tags: string[] = [];
try { tags = JSON.parse(tagsJson || '[]'); } catch { /* */ }
const isTodo = tags.includes('is_todo:true');
const repoTag = tags.find(t => t.startsWith('suggested-repo:'));
const repo = repoTag ? repoTag.slice('suggested-repo:'.length) : '';
const rawTag = tags.find(t => t.startsWith('raw:'));
const rawId = rawTag ? rawTag.slice('raw:'.length) : '';
return { isTodo, repo, rawId };
}
export default function ProjectsPage() {
const [repos, setRepos] = useState<RepoSummary[] | null>(null);
const [todos, setTodos] = useState<Todo[]>([]);
const [error, setError] = useState<string | null>(null);
const [filter, setFilter] = useState<Filter>('sdd');
const [cloning, setCloning] = useState<string | null>(null);
const [newRepo, setNewRepo] = useState('');
const load = () => {
setError(null);
fetch(`${DAEMON}/projects`)
.then(async r => {
if (!r.ok) throw new Error(`daemon 回 ${r.status}`);
return r.json() as Promise<{ repos: RepoSummary[] }>;
})
.then(d => setRepos(d.repos ?? []))
.catch(e => setError(e instanceof Error ? e.message : String(e)));
void loadTodos();
};
// 撈 project_detector 拆出的 todo blocksource=ai-project-detectorG1 一篇拆多條)
// client 過濾 is_todo:trueKI-3 tag query bug 故用 source filter 而非 tag query
const loadTodos = async () => {
try {
const me = await fetch(`${API_BASE}/me`, { credentials: 'include' }).then(r => r.ok ? r.json() : null);
if (!me?.api_key) return;
const res = await fetch(`${KBDB_BASE}/blocks?type=note&source=ai-project-detector&limit=300`, {
headers: { Authorization: `Bearer ${me.api_key}` },
});
if (!res.ok) return;
const data = await res.json() as { blocks?: Array<{ id: string; content: string; tags_json: string | null }> };
const list: Todo[] = [];
for (const b of data.blocks ?? []) {
const { isTodo, repo, rawId } = parseTodoTags(b.tags_json);
if (isTodo) list.push({ id: b.id, content: b.content, suggested_repo: repo || 'new', raw_id: rawId });
}
setTodos(list);
} catch { /* todos best-effort */ }
};
useEffect(load, []);
const clone = async (fullName: string) => {
setCloning(fullName);
setError(null);
try {
const r = await fetch(`${DAEMON}/projects/clone`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repo: fullName }),
});
if (!r.ok) throw new Error(`clone 失敗 ${r.status}`);
setNewRepo('');
load();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setCloning(null);
}
};
const addRepo = () => {
const v = newRepo.trim();
if (!v) return;
// 允許輸入 "name" 或 "owner/name"
const full = v.includes('/') ? v : `richblack/${v}`;
clone(full);
};
const shown = useMemo(() => {
if (!repos) return [];
const arr = repos.filter(r => {
if (filter === 'sdd') return r.has_sdd;
return true;
});
// 有進度等你處理的優先,其次已 clone,其次最近活動
arr.sort((a, b) =>
b.leo_count - a.leo_count ||
Number(b.cloned) - Number(a.cloned) ||
(b.last_activity ?? '').localeCompare(a.last_activity ?? ''),
);
return arr;
}, [repos, filter]);
// 待辦按 suggested_repo 分組(outlinerRepo 父 → todo 子)
const todosByRepo = useMemo(() => {
const m = new Map<string, Todo[]>();
for (const t of todos) {
const key = t.suggested_repo || 'new';
if (!m.has(key)) m.set(key, []);
m.get(key)!.push(t);
}
return m;
}, [todos]);
const newTodos = todosByRepo.get('new') ?? [];
return (
<main className="mira-page">
<div className="mira-content">
<header className="mira-proj-header">
<h1 className="mira-proj-title">📋 </h1>
<p className="mira-proj-sub"> clone repo · 🤖 Mira / 👤 </p>
<div className="mira-proj-controls">
<div className="mira-proj-sort">
{([['sdd', '有進度'], ['all', '全部']] as [Filter, string][]).map(([k, label]) => (
<button
key={k}
className={`mira-proj-sort-btn${filter === k ? ' is-active' : ''}`}
onClick={() => setFilter(k)}
>
{label}
</button>
))}
</div>
<div className="mira-proj-add">
<input
className="mira-proj-add-input"
placeholder="加 reponame 或 owner/name"
value={newRepo}
onChange={e => setNewRepo(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') addRepo(); }}
/>
<button className="mira-proj-add-btn" onClick={addRepo} disabled={!!cloning || !newRepo.trim()}>
{cloning ? 'clone 中…' : '↓ clone'}
</button>
</div>
</div>
</header>
{error && (
<div className="mira-card mira-proj-error">
<strong> repo </strong>{error}
<div className="mira-proj-error-hint">
mira daemon{DAEMON}/projects daemon endpoint 10-A
</div>
</div>
)}
{!error && repos === null && <div className="mira-proj-loading"></div>}
{!error && repos?.length === 0 && (
<div className="mira-card mira-proj-empty">GitHub repo</div>
)}
<div className="mira-proj-grid">
{shown.map(r => (
<RepoCard
key={r.full_name}
r={r}
cloning={cloning === r.full_name}
onClone={() => clone(r.full_name)}
todos={todosByRepo.get(r.name) ?? []}
/>
))}
</div>
{newTodos.length > 0 && (
<div className="mira-card mira-proj-new-group">
<div className="mira-proj-new-title">💡 {newTodos.length}</div>
<ul className="mira-proj-todo-list">
{newTodos.map(t => (
<li key={t.id} className="mira-proj-todo-item">
<span className="mira-proj-todo-dot">·</span> {t.content}
{t.raw_id && (
<a className="mira-proj-todo-src" href={`/mira/feed#raw=${t.raw_id}`}> </a>
)}
</li>
))}
</ul>
</div>
)}
</div>
</main>
);
}
function pct(r: RepoSummary): number {
return r.total === 0 ? 0 : Math.round((r.done / r.total) * 100);
}
function relTime(iso: string | null): string {
if (!iso) return '—';
const t = new Date(iso).getTime();
if (Number.isNaN(t)) return '—';
const days = Math.floor((Date.now() - t) / 86400000);
if (days <= 0) return '今天';
if (days === 1) return '昨天';
if (days < 30) return `${days} 天前`;
return `${Math.floor(days / 30)} 個月前`;
}
function RepoCard({ r, cloning, onClone, todos }: { r: RepoSummary; cloning: boolean; onClone: () => void; todos: Todo[] }) {
const percent = pct(r);
return (
<div className="mira-card mira-proj-card">
<div className="mira-proj-card-top">
<span className="mira-proj-name">
{r.name}
{r.fork && <span className="mira-proj-tag">fork</span>}
{r.archived && <span className="mira-proj-tag">archived</span>}
</span>
<span className="mira-proj-time mira-en">{relTime(r.last_activity)}</span>
</div>
<div className="mira-proj-path mira-en">{r.full_name}</div>
{/* 河道偵測到、建議整進此專案的待辦(outliner 子項)*/}
{todos.length > 0 && (
<ul className="mira-proj-todo-list">
{todos.map(t => (
<li key={t.id} className="mira-proj-todo-item">
<span className="mira-proj-todo-dot">·</span> {t.content}
{t.raw_id && (
<a className="mira-proj-todo-src" href={`/mira/feed#raw=${t.raw_id}`}> </a>
)}
</li>
))}
</ul>
)}
{!r.cloned ? (
<div className="mira-proj-uncloned">
<span className="mira-proj-uncloned-hint"> clone Hetzner</span>
<button className="mira-proj-clone-btn" onClick={onClone} disabled={cloning}>
{cloning ? 'clone 中…' : '↓ clone 進工作態'}
</button>
</div>
) : !r.has_sdd ? (
<div className="mira-proj-nosdd"> clone · SDD .agents/specs</div>
) : (
<>
<div className="mira-proj-bar">
<div className="mira-proj-bar-fill" style={{ width: `${percent}%` }} />
</div>
<div className="mira-proj-stats">
<span className="mira-proj-pct mira-en">{percent}%</span>
<span className="mira-en">{r.done}/{r.total}</span>
{r.leo_count > 0 && <span className="mira-proj-chip mira-chip-leo">👤 {r.leo_count} </span>}
{r.ai_count > 0 && <span className="mira-proj-chip mira-chip-ai">🤖 {r.ai_count} Mira</span>}
{r.blocked_count > 0 && <span className="mira-proj-chip mira-chip-blocked"> {r.blocked_count}</span>}
</div>
</>
)}
</div>
);
}
+307
View File
@@ -0,0 +1,307 @@
'use client';
export const runtime = 'edge';
// Mira 搜尋頁 — Karpathy index pattern 為 primaryleo 2026-05-23
// SDD: polaris/mira/.agents/specs/mira-app/design.md §3.5.12.4「Karpathy index pattern(不用 vector embedding)」
// 三層(C 混合):
// 1. Index 即時文字比對:掃 index-entry(entity 名 + 摘要)子字串命中 → 列 entity(零 token
// 2. LLM 路由(選用):整個 index 餵 Claude,問「leo 想找哪些 entity」→ 最貼 Karpathy 本意
// 3. 向量兜底(折疊):KBDB /search semanticSDD 明文「不是 primary,當保險」
import { Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { MarkdownView } from '../_shared/markdown';
import '../mira.css';
const KBDB_BASE = 'https://kbdb.finally.click';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
const CLAUDE_API = 'https://claude-api.arcrun.dev';
// 繁體異體字正規化(臺→台),讓 query 對得上多用「台」的 KB 內容
function normalizeQuery(q: string): string {
return q.replace(/臺/g, '台');
}
type IndexEntry = {
entity: string; // H1 / page_name 去 index- 前綴
pageName: string; // index-entry 自己的 page_nameindex-{entity}
oneLiner: string; // 「一句話定義」
outline: string; // facet outline 全文(拿來比對 + 餵 LLM)
raw: string; // 完整 content(餵 LLM 用,截斷)
};
// 解析 index-entry markdown → 結構
function parseIndexEntry(content: string, pageName: string): IndexEntry {
const entity = (content.match(/^#\s+(.+)$/m)?.[1] ?? pageName.replace(/^index-/, '')).trim();
const oneLiner = (content.match(/##\s*一句話定義\s*\n+([^\n#]+)/)?.[1] ?? '').trim();
const outlineMatch = content.match(/##\s*段落 outline[^\n]*\n([\s\S]*?)(?=\n##|$)/);
const outline = (outlineMatch?.[1] ?? '').trim();
return { entity, pageName, oneLiner, outline, raw: content.slice(0, 700) };
}
// entity 名 → wiki page 路由(wiki-{entity}
function wikiHref(entity: string): string {
return `/mira/wiki/${encodeURIComponent('wiki-' + entity)}`;
}
// ── 向量兜底型別 ──
type SearchMatch = {
score: number;
type: 'block' | 'triplet';
metadata?: { entity?: string;[k: string]: unknown };
block: { id: string; page_name: string | null; content: string | null; type: string; source: string | null } | null;
triplet: { id: string; subject?: string; predicate?: string; object?: string } | null;
};
function SearchInner() {
const router = useRouter();
const params = useSearchParams();
const initialQ = params.get('q') ?? '';
const [apiKey, setApiKey] = useState<string | null>(null);
const [input, setInput] = useState(initialQ);
const [query, setQuery] = useState(initialQ.trim());
const [index, setIndex] = useState<IndexEntry[] | null>(null);
const [error, setError] = useState<string | null>(null);
// LLM 路由結果
const [llmEntities, setLlmEntities] = useState<{ entity: string; reason: string }[] | null>(null);
const [llmLoading, setLlmLoading] = useState(false);
// 向量兜底
const [vecMatches, setVecMatches] = useState<SearchMatch[] | null>(null);
const [vecLoading, setVecLoading] = useState(false);
const [vecOpen, setVecOpen] = useState(false);
// 載入:me + 全部 index-entry
useEffect(() => {
(async () => {
try {
const meRes = await fetch(`${API_BASE}/me`, { credentials: 'include' });
if (!meRes.ok) { window.location.href = '/login?redirect=/mira/search'; return; }
const me = (await meRes.json()) as { api_key: string };
setApiKey(me.api_key);
const r = await fetch(`${KBDB_BASE}/blocks?type=index-entry&limit=300`, {
headers: { Authorization: `Bearer ${me.api_key}` },
});
if (!r.ok) { setError(`index 讀取失敗:${r.status}`); return; }
const data = (await r.json()) as { blocks?: { content: string; page_name: string }[] };
setIndex((data.blocks ?? []).map(b => parseIndexEntry(b.content || '', b.page_name || '')));
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
})();
}, []);
// 即時 index 文字比對(純 client,零 token
const indexHits = useMemo(() => {
if (!index || !query) return [];
const q = normalizeQuery(query).toLowerCase();
const terms = q.split(/\s+/).filter(Boolean);
const scored = index
.map(e => {
const hay = normalizeQuery(`${e.entity}\n${e.oneLiner}\n${e.outline}`).toLowerCase();
let score = 0;
for (const t of terms) {
if (e.entity.toLowerCase().includes(t)) score += 10; // entity 名命中權重高
else if (hay.includes(t)) score += 3;
}
return { e, score };
})
.filter(x => x.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, 12);
return scored.map(x => x.e);
}, [index, query]);
const submit = (e: React.FormEvent) => {
e.preventDefault();
const q = input.trim();
setQuery(q);
setLlmEntities(null);
setVecMatches(null);
setVecOpen(false);
router.replace(`/mira/search?q=${encodeURIComponent(q)}`);
};
// LLM 路由:整個 index 餵 Claude
const runLlmRoute = useCallback(async () => {
if (!index || !query || llmLoading) return;
setLlmLoading(true);
setLlmEntities(null);
try {
const indexDigest = index
.map(e => `- ${e.entity}${e.oneLiner || '(無摘要)'}`)
.join('\n');
const prompt =
`你是 leo 知識庫的索引導航員。以下是所有 wiki entity 的索引(entity:一句話定義):\n\n` +
`${indexDigest}\n\n---\n\n` +
`leo 想找:「${query}\n\n` +
`請從上面索引挑出最相關的 entity(最多 6 個,可能 0 個)。` +
`只輸出 JSON 陣列,格式 [{"entity":"<完全照抄索引裡的名稱>","reason":"<為何相關,20字內>"}],不要其他文字。`;
const res = await fetch(CLAUDE_API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, timeout_ms: 45000 }),
});
const data = (await res.json()) as { success?: boolean; data?: { text?: string } };
const text = data.data?.text ?? '';
const jsonMatch = text.match(/\[[\s\S]*\]/);
const parsed = jsonMatch ? JSON.parse(jsonMatch[0]) as { entity: string; reason: string }[] : [];
// 只留實際存在於 index 的 entity
const known = new Set(index.map(e => e.entity));
setLlmEntities(parsed.filter(p => known.has(p.entity)));
} catch {
setLlmEntities([]);
} finally {
setLlmLoading(false);
}
}, [index, query, llmLoading]);
// 向量兜底
const runVecSearch = useCallback(async () => {
if (!apiKey || !query || vecLoading) return;
setVecOpen(true);
setVecLoading(true);
try {
const res = await fetch(`${KBDB_BASE}/search`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
body: JSON.stringify({ query: normalizeQuery(query), type: 'semantic', topK: 12 }),
});
const data = (await res.json()) as { matches?: SearchMatch[] };
setVecMatches(data.matches ?? []);
} catch {
setVecMatches([]);
} finally {
setVecLoading(false);
}
}, [apiKey, query, vecLoading]);
return (
<main className="mira-page">
<div className="mira-content">
<header style={{ padding: '24px 0 8px' }}>
<Link href="/mira/feed" style={{ color: '#888', fontSize: 14, textDecoration: 'none' }}> </Link>
<h1 style={{ fontSize: 26, fontWeight: 700, color: '#fff', margin: '8px 0 0' }}>🔍 Wiki </h1>
<p style={{ color: '#888', fontSize: 12, marginTop: 4 }}>
{index?.length ?? '…'} wiki Karpathy index
</p>
</header>
<form className="mira-search-form" onSubmit={submit}>
<input
className="mira-search-input"
value={input}
onChange={e => setInput(e.target.value)}
placeholder="找主題(例:特化、台北大學、本地模型)"
autoFocus
/>
<button type="submit" className="mira-btn-primary" disabled={!index}></button>
</form>
{error && <div className="mira-error" style={{ marginBottom: 10 }}>{error}</div>}
{!index && !error && <div className="empty-state"></div>}
{index && query && (
<>
{/* 第 1 層:index 即時命中 */}
<section style={{ marginTop: 8 }}>
<div className="mira-search-section-head">📇 {indexHits.length}</div>
{indexHits.length === 0 ? (
<div className="empty-state" style={{ padding: '16px 0' }}></div>
) : (
indexHits.map(e => (
<Link key={e.pageName} href={wikiHref(e.entity)} className="mira-search-result">
<div className="mira-search-result-meta"><span>📚 {e.entity}</span></div>
{e.oneLiner && <div className="mira-search-snippet">{e.oneLiner}</div>}
</Link>
))
)}
</section>
{/* 第 2 層:LLM 路由(選用) */}
<section style={{ marginTop: 18 }}>
{!llmEntities && (
<button type="button" className="mira-search-llm-btn" onClick={runLlmRoute} disabled={llmLoading}>
{llmLoading ? '🧠 Mira 翻索引中…' : '🧠 找不到?讓 Mira 讀整個索引幫你找'}
</button>
)}
{llmEntities && (
<>
<div className="mira-search-section-head">🧠 Mira {llmEntities.length}</div>
{llmEntities.length === 0 ? (
<div className="empty-state" style={{ padding: '12px 0' }}>Mira </div>
) : (
llmEntities.map(p => (
<Link key={p.entity} href={wikiHref(p.entity)} className="mira-search-result">
<div className="mira-search-result-meta"><span>📚 {p.entity}</span></div>
<div className="mira-search-snippet" style={{ color: 'var(--mira-text-3)' }}>{p.reason}</div>
</Link>
))
)}
</>
)}
</section>
{/* 第 3 層:向量兜底(折疊) */}
<section style={{ marginTop: 18 }}>
{!vecOpen ? (
<button type="button" className="mira-search-vec-toggle" onClick={runVecSearch}>
/
</button>
) : (
<>
<div className="mira-search-section-head">🧬 </div>
{vecLoading && <div className="empty-state" style={{ padding: '12px 0' }}></div>}
{vecMatches && vecMatches.length === 0 && !vecLoading && (
<div className="empty-state" style={{ padding: '12px 0' }}></div>
)}
{vecMatches && vecMatches.map((m, i) => <VecResult key={i} match={m} />)}
</>
)}
</section>
</>
)}
</div>
</main>
);
}
function VecResult({ match }: { match: SearchMatch }) {
const pct = Math.round((match.score ?? 0) * 100);
if (match.triplet) {
const { subject, predicate, object } = match.triplet;
return (
<div className="mira-search-result">
<div className="mira-search-result-meta"><span></span>{pct > 0 && <span className="mira-search-score">{pct}%</span>}</div>
<div className="mira-search-snippet" style={{ fontFamily: 'monospace' }}>{subject} {predicate} {object}</div>
</div>
);
}
const b = match.block;
if (!b) return null;
const snippet = (b.content ?? '').replace(/\n+/g, ' ').slice(0, 200);
const href = b.type === 'wiki-page' && b.page_name
? `/mira/wiki/${encodeURIComponent(b.page_name)}`
: b.page_name ? `/mira/feed#page=${encodeURIComponent(b.page_name)}` : `/mira/feed#raw=${encodeURIComponent(b.id)}`;
return (
<Link href={href} className="mira-search-result">
<div className="mira-search-result-meta">
<span>{b.type === 'wiki-page' ? '📚 Wiki' : '🌊 河道'}</span>
{pct > 0 && <span className="mira-search-score">{pct}%</span>}
</div>
<div className="mira-search-snippet"><MarkdownView text={snippet + ((b.content ?? '').length > 200 ? '…' : '')} /></div>
</Link>
);
}
export default function MiraSearchPage() {
return (
<Suspense fallback={<div className="empty-state"></div>}>
<SearchInner />
</Suspense>
);
}
+467
View File
@@ -0,0 +1,467 @@
'use client';
export const runtime = 'edge';
// Mira Wiki 單篇頁
// SDD: polaris/mira/.agents/specs/mira-app/design.md §5.2 + §3.5.12
// 對應 task: 7C.2 + 7B.3g
// 路由:/mira/wiki/[pageName]
// 顯示:wiki-page parent → wiki-paragraph children (按 facet 分區) → triplet grandchildren
// 7B.3g 升級:樹狀渲染 + 折疊 + triplet 跨 wiki 連結化
import { useEffect, useMemo, useState, use } from 'react';
import Link from 'next/link';
import { MarkdownView } from '../../_shared/markdown';
import '../../mira.css';
const KBDB_BASE = 'https://kbdb.finally.click';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
type Block = {
id: string;
page_name: string | null;
content: string;
type: string;
parent_id: string | null;
tags_json: string | null;
source: string | null;
created_at: number;
updated_at: number;
};
type FacetGroup = {
facet: string;
paragraphs: Array<{
block: Block;
triplets: Block[];
}>;
};
export default function WikiPagePage({
params,
}: {
params: Promise<{ pageName: string }>;
}) {
const { pageName } = use(params);
const decodedName = decodeURIComponent(pageName);
const [block, setBlock] = useState<Block | null>(null);
const [paragraphs, setParagraphs] = useState<Block[]>([]);
const [triplets, setTriplets] = useState<Block[]>([]);
const [entitySet, setEntitySet] = useState<Set<string>>(new Set());
// Backlinks:所有提到此 entity 的 raw noteV3 wiki_synthesis 在 wiki-page tags 寫 raw:XXX
// 對應 leo 2026-05-17 #2 反饋:「從這本書的條目應該反向連到那篇筆記去」
const [backlinkRaws, setBacklinkRaws] = useState<Block[]>([]);
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
async function load() {
try {
const meRes = await fetch(`${API_BASE}/me`, { credentials: 'include' });
if (!meRes.ok) throw new Error('未登入');
const me = (await meRes.json()) as { api_key: string };
const headers = { Authorization: `Bearer ${me.api_key}` };
// 1. 抓 wiki-page parent block by page_name
const pageRes = await fetch(
`${KBDB_BASE}/blocks?page_name=${encodeURIComponent(decodedName)}&limit=1`,
{ headers },
);
if (!pageRes.ok) throw new Error(`KBDB ${pageRes.status}`);
const pageData = await pageRes.json();
const wikiPage: Block | undefined = pageData.blocks?.[0];
if (cancelled) return;
if (!wikiPage) {
setError(`找不到 wiki page${decodedName}`);
return;
}
setBlock(wikiPage);
// 2. 平行撈所有 wiki-paragraph + triplet + wiki-page(跨 wiki 連結用),客戶端 filter by parent_id
// KBDB 沒 parent_id server filter(兼 tag filter 還有 KI-3 bug),用 source+type 取再 client-side filter
const [paraRes, tripRes, pageListRes] = await Promise.all([
fetch(`${KBDB_BASE}/blocks?source=ai-canon-wiki&type=wiki-paragraph&limit=500`, { headers }),
fetch(`${KBDB_BASE}/blocks?source=ai-canon-wiki&type=triplet&limit=1000`, { headers }),
fetch(`${KBDB_BASE}/blocks?source=ai-canon-wiki&type=wiki-page&limit=500`, { headers }),
]);
if (!paraRes.ok || !tripRes.ok || !pageListRes.ok) {
throw new Error('KBDB tree fetch failed');
}
const paraData = await paraRes.json();
const tripData = await tripRes.json();
const pageListData = await pageListRes.json();
if (cancelled) return;
const allParas: Block[] = paraData.blocks ?? [];
const allTrips: Block[] = tripData.blocks ?? [];
const allPages: Block[] = pageListData.blocks ?? [];
// 該 wiki-page 的 paragraphs
const myParas = allParas
.filter((p) => p.parent_id === wikiPage.id)
.sort((a, b) => a.created_at - b.created_at);
setParagraphs(myParas);
// 該 wiki-page 範圍內所有 paragraph 的 triplets
const paraIdSet = new Set(myParas.map((p) => p.id));
const myTrips = allTrips.filter((t) => t.parent_id && paraIdSet.has(t.parent_id));
setTriplets(myTrips);
// 跨 wiki 連結用:所有 wiki-page 的 entity 名稱(content 就是 entity
// 額外把 page_name 也加入(page_name=wiki-{entity}
const eset = new Set<string>();
for (const p of allPages) {
if (p.content) eset.add(p.content.trim());
if (p.page_name?.startsWith('wiki-')) {
eset.add(p.page_name.slice(5).trim());
}
}
setEntitySet(eset);
// Backlinks:找此 entity 的所有 wiki-page (可能多次寫入),提取 raw:XXX tag → fetch raw blocks
if (wikiPage.type === 'wiki-page' && wikiPage.content) {
const sameEntity = allPages.filter((p) => p.content?.trim() === wikiPage.content?.trim());
const rawIds = new Set<string>();
for (const wp of sameEntity) {
try {
const tags = JSON.parse(wp.tags_json || '[]') as string[];
for (const t of tags) {
if (typeof t === 'string' && t.startsWith('raw:')) {
rawIds.add(t.slice(4));
}
}
} catch { /* skip */ }
}
if (rawIds.size > 0) {
// 一次撈 raw blockspage_name 是 unique 一次 query 一個
const rawBlocks: Block[] = [];
await Promise.all(
Array.from(rawIds).map(async (rawId) => {
try {
// KBDB GET /blocks/:id 直接 by id (走 list with block_id filter)
const r = await fetch(`${KBDB_BASE}/blocks/${rawId}`, { headers });
if (r.ok) {
const data = await r.json();
const b = data.blocks?.[0] ?? data;
if (b?.id) rawBlocks.push(b as Block);
}
} catch { /* skip */ }
}),
);
if (!cancelled) {
setBacklinkRaws(rawBlocks.sort((a, b) => b.updated_at - a.updated_at));
}
}
}
} catch (e: any) {
if (!cancelled) setError(e?.message ?? 'load failed');
} finally {
if (!cancelled) setLoading(false);
}
}
load();
return () => {
cancelled = true;
};
}, [decodedName]);
// 按 facet 分區
const facetGroups = useMemo<FacetGroup[]>(() => {
const groups: Map<string, Array<{ block: Block; triplets: Block[] }>> = new Map();
for (const p of paragraphs) {
const facet = extractFacet(p.tags_json) ?? '未分類';
const myTrips = triplets.filter((t) => t.parent_id === p.id);
if (!groups.has(facet)) groups.set(facet, []);
groups.get(facet)!.push({ block: p, triplets: myTrips });
}
return Array.from(groups.entries()).map(([facet, paragraphs]) => ({ facet, paragraphs }));
}, [paragraphs, triplets]);
const isWikiPage = block?.type === 'wiki-page';
// 標題:wiki-page 用 contententity 名稱),其他(index-entry/schema/log/...)用 page_name 剝 prefix
// 修 bug:原本一律用 block.content,但 index-entry 的 content 是整篇 markdown,會把整個 content render 成 h1
const entity = isWikiPage
? (block?.content?.trim() || decodedName.replace(/^wiki-/, ''))
: decodedName.replace(/^(wiki|index)-/, '');
function toggleCollapse(key: string) {
setCollapsed((c) => ({ ...c, [key]: !c[key] }));
}
return (
<main className="mira-page">
<div className="mira-content mira-wiki-detail">
<header style={{ padding: '24px 0 16px', borderBottom: '1px solid #2a2a2a' }}>
<Link
href="/mira/wiki"
style={{ color: '#888', fontSize: 14, textDecoration: 'none' }}
>
Wiki
</Link>
<h1 style={{ fontSize: 28, fontWeight: 700, color: '#fff', margin: '8px 0 4px' }}>
{entity}
</h1>
{block && (
<div style={{ color: '#666', fontSize: 12 }}>
{block.type} updated {new Date(block.updated_at * 1000).toLocaleString('zh-TW')}
</div>
)}
</header>
{loading && <div style={{ padding: 24, color: '#666' }}></div>}
{error && <div style={{ padding: 24, color: '#e66' }}>{error}</div>}
{block && !loading && !error && (
<>
{/* wiki-page tree view */}
{isWikiPage && facetGroups.length > 0 && (
<article style={{ padding: '8px 0 24px' }}>
{facetGroups.map((group) => (
<FacetSection
key={group.facet}
group={group}
entitySet={entitySet}
collapsed={collapsed}
toggleCollapse={toggleCollapse}
/>
))}
</article>
)}
{/* wiki-page 但沒 childrenfallback render content */}
{isWikiPage && facetGroups.length === 0 && (
<article style={{ padding: '8px 0 24px', color: '#888' }}>
<em>wiki_synthesis children</em>
<MarkdownView text={block.content} />
</article>
)}
{/* 非 wiki-pageschema / index / log / index-entry 等):直接 render content */}
{!isWikiPage && (
<article style={{ padding: '20px 0' }}>
<MarkdownView text={block.content} />
</article>
)}
{/* Backlinks:提到此 entity 的 raw notes */}
{isWikiPage && backlinkRaws.length > 0 && (
<section
style={{
margin: '24px 0 16px',
padding: '12px 14px',
borderLeft: '3px solid #4a3a2a',
background: 'rgba(80, 60, 40, 0.08)',
}}
>
<h3 style={{ margin: '0 0 8px', fontSize: 14, color: '#aab', fontWeight: 600 }}>
📎 entity ({backlinkRaws.length})
</h3>
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.6 }}>
{backlinkRaws.map((raw) => {
const preview = (raw.content || '').replace(/\n/g, ' ').slice(0, 100);
const href = `/mira/feed#page=${encodeURIComponent(raw.page_name || raw.id)}`;
return (
<li key={raw.id} style={{ marginBottom: 4 }}>
<a
href={href}
style={{ color: '#9ab', textDecoration: 'none' }}
title={raw.content || ''}
>
{preview}
{(raw.content || '').length > 100 && '…'}
</a>
</li>
);
})}
</ul>
</section>
)}
<footer
style={{
padding: '20px 0',
borderTop: '1px solid #1f1f1f',
color: '#555',
fontSize: 12,
}}
>
<div>id: <span style={{ fontFamily: 'monospace' }}>{block.id}</span></div>
<div>type: {block.type}</div>
{block.source && <div>source: {block.source}</div>}
{block.parent_id && (
<div>
parent: <span style={{ fontFamily: 'monospace' }}>{block.parent_id}</span>
</div>
)}
{paragraphs.length > 0 && (
<div>
{paragraphs.length} paragraph(s) {triplets.length} triplet(s)
</div>
)}
</footer>
</>
)}
</div>
</main>
);
}
function FacetSection({
group,
entitySet,
collapsed,
toggleCollapse,
}: {
group: FacetGroup;
entitySet: Set<string>;
collapsed: Record<string, boolean>;
toggleCollapse: (key: string) => void;
}) {
const key = `facet:${group.facet}`;
const isCollapsed = collapsed[key] ?? false; // 預設展開(leo 看一篇 wiki 時要看內容)
return (
<section style={{ margin: '16px 0', borderLeft: '3px solid #2a3a4a', paddingLeft: 14 }}>
<button
onClick={() => toggleCollapse(key)}
style={{
background: 'transparent',
border: 'none',
color: '#aab',
fontSize: 16,
fontWeight: 600,
padding: '4px 0',
cursor: 'pointer',
textAlign: 'left',
width: '100%',
}}
>
{isCollapsed ? '▸' : '▾'} {group.facet}
<span style={{ color: '#555', fontWeight: 400, fontSize: 13, marginLeft: 8 }}>
({group.paragraphs.length})
</span>
</button>
{!isCollapsed &&
group.paragraphs.map((p) => (
<ParagraphBlock
key={p.block.id}
block={p.block}
triplets={p.triplets}
entitySet={entitySet}
collapsed={collapsed}
toggleCollapse={toggleCollapse}
/>
))}
</section>
);
}
function ParagraphBlock({
block,
triplets,
entitySet,
collapsed,
toggleCollapse,
}: {
block: Block;
triplets: Block[];
entitySet: Set<string>;
collapsed: Record<string, boolean>;
toggleCollapse: (key: string) => void;
}) {
const tripKey = `trip:${block.id}`;
const tripsCollapsed = collapsed[tripKey] ?? true; // triplets 預設折疊
return (
<div style={{ margin: '12px 0 16px', paddingLeft: 4 }}>
<div style={{ color: '#ddd', lineHeight: 1.7 }}>
<MarkdownView text={block.content} />
</div>
{triplets.length > 0 && (
<div style={{ marginTop: 8 }}>
<button
onClick={() => toggleCollapse(tripKey)}
style={{
background: 'transparent',
border: 'none',
color: '#666',
fontSize: 12,
padding: '2px 0',
cursor: 'pointer',
}}
>
{tripsCollapsed ? '▸' : '▾'} ({triplets.length})
</button>
{!tripsCollapsed && (
<ul style={{ listStyle: 'none', padding: '4px 0 0 12px', margin: 0 }}>
{triplets.map((t) => (
<li
key={t.id}
style={{
color: '#888',
fontSize: 13,
padding: '2px 0',
fontFamily: 'monospace',
}}
>
<TripletRender content={t.content} entitySet={entitySet} />
</li>
))}
</ul>
)}
</div>
)}
</div>
);
}
/** Render triplet "A >> 關係 >> B" with A/B linkified if they match an existing wiki entity */
function TripletRender({
content,
entitySet,
}: {
content: string;
entitySet: Set<string>;
}) {
// 切「>>」分 A / 關係 / B
const parts = content.split('>>').map((s) => s.trim());
if (parts.length !== 3) {
return <>{content}</>;
}
const [a, rel, b] = parts;
return (
<>
<EntityLink name={a} entitySet={entitySet} />{' '}
<span style={{ color: '#666' }}>&gt;&gt; {rel} &gt;&gt;</span>{' '}
<EntityLink name={b} entitySet={entitySet} />
</>
);
}
function EntityLink({ name, entitySet }: { name: string; entitySet: Set<string> }) {
if (entitySet.has(name)) {
return (
<Link
href={`/mira/wiki/${encodeURIComponent(`wiki-${name}`)}`}
style={{ color: '#88c0ff', textDecoration: 'none' }}
>
{name}
</Link>
);
}
return <span style={{ color: '#ccc' }}>{name}</span>;
}
function extractFacet(tags_json: string | null | undefined): string | null {
if (!tags_json) return null;
try {
const tags = JSON.parse(tags_json) as string[];
const facetTag = tags.find((t) => t.startsWith('facet:'));
return facetTag ? facetTag.slice(6) : null;
} catch {
return null;
}
}
+346
View File
@@ -0,0 +1,346 @@
'use client';
// Mira Wiki 索引頁
// SDD: polaris/mira/.agents/specs/mira-app/design.md §5.2 + §3.5.10
// 對應 task: 7C.1
// 階段 7-A 已建:mira-wiki-schema、mira-wiki-index(+4 children)、mira-wiki-log(+1 child)
// 此頁列出這些 infra block 與既有 wiki-page,方便 leo 在瀏覽器確認 schema 寫得對不對
import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import '../mira.css';
const KBDB_BASE = 'https://kbdb.finally.click';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
type Block = {
id: string;
page_name: string;
content: string;
type: string;
parent_id: string | null;
tags_json: string | null;
created_at: number;
};
export default function WikiIndexPage() {
const [schema, setSchema] = useState<Block | null>(null);
const [indexChildren, setIndexChildren] = useState<Block[]>([]);
const [logEntries, setLogEntries] = useState<Block[]>([]);
const [otherWikiPages, setOtherWikiPages] = useState<Block[]>([]);
const [indexEntries, setIndexEntries] = useState<Block[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
async function load() {
try {
// 先拿 ak_ partner key(同 page.tsx pattern
const meRes = await fetch(`${API_BASE}/me`, { credentials: 'include' });
if (!meRes.ok) throw new Error('未登入');
const me = (await meRes.json()) as { api_key: string };
const headers = { Authorization: `Bearer ${me.api_key}` };
// 撈所有 type=wiki-page,再 client 端過濾 tags 含 'mira-wiki'
// 原本 ?tag=mira-wiki 撞 KBDB worker D1 bugmalformed JSON),改 type filter
// 待 KBDB 修 tag filter 後可改回(SDD 待開 kbdb-tag-filter-fix
const res = await fetch(
`${KBDB_BASE}/blocks?type=wiki-page&limit=200`,
{ headers },
);
if (!res.ok) throw new Error(`KBDB ${res.status}`);
const data = await res.json();
if (cancelled) return;
const allWikiBlocks: Block[] = data.blocks ?? [];
// Client 端過濾:只留 tags 含 'mira-wiki'
const blocks: Block[] = allWikiBlocks.filter((b) => {
if (!b.tags_json) return false;
try {
const tags = JSON.parse(b.tags_json) as string[];
return tags.includes('mira-wiki');
} catch {
return false;
}
});
const tagsOf = (b: Block): string[] => {
if (!b.tags_json) return [];
try {
return JSON.parse(b.tags_json) as string[];
} catch {
return [];
}
};
const hasSubtype = (b: Block, st: string) =>
tagsOf(b).includes(`subtype:${st}`);
const hasAnyInfraSubtype = (b: Block) =>
['schema', 'index', 'index-child', 'log', 'log-child'].some((st) => hasSubtype(b, st));
const hasMetaTag = (b: Block) =>
tagsOf(b).some((t) => t === 'data-source-config' || t === 'source-skill');
setSchema(blocks.find((b) => hasSubtype(b, 'schema')) ?? null);
setIndexChildren(
blocks
.filter((b) => hasSubtype(b, 'index-child'))
.sort((a, b) => a.page_name.localeCompare(b.page_name)),
);
setLogEntries(
blocks
.filter((b) => hasSubtype(b, 'log-child'))
.sort((a, b) => b.page_name.localeCompare(a.page_name)),
);
// 真正的 wiki-page paragraphs(排除 infra 跟 meta 配置)
setOtherWikiPages(
blocks
.filter((b) => !hasAnyInfraSubtype(b) && !hasMetaTag(b))
.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0)),
);
// 平行撈 index-entry blocksper-entity 摘要,CC navigation entry point
// 對應 design.md §3.5.12.4.1 / 7B.3f
const idxRes = await fetch(
`${KBDB_BASE}/blocks?type=index-entry&limit=200`,
{ headers },
);
if (idxRes.ok) {
const idxData = await idxRes.json();
if (!cancelled) {
const idxBlocks: Block[] = idxData.blocks ?? [];
setIndexEntries(
idxBlocks.sort((a, b) => (a.page_name ?? '').localeCompare(b.page_name ?? '')),
);
}
}
} catch (e: any) {
if (!cancelled) setError(e?.message ?? 'load failed');
} finally {
if (!cancelled) setLoading(false);
}
}
load();
return () => {
cancelled = true;
};
}, []);
// Dedupe wiki-pages by entitycontent)— 累積式設計每個 raw 各建一個 wiki-page
// 同 entity 多版只在 listing 顯示最新一張卡 + 版本數提示
const dedupedWikiPages = useMemo(() => {
const groups = new Map<string, { entity: string; latest: Block; versionCount: number }>();
for (const p of otherWikiPages) {
const entity = (p.content || '').trim() || p.page_name || '?';
const existing = groups.get(entity);
if (!existing) {
groups.set(entity, { entity, latest: p, versionCount: 1 });
} else {
existing.versionCount++;
if ((p.created_at ?? 0) > (existing.latest.created_at ?? 0)) {
existing.latest = p;
}
}
}
return Array.from(groups.values()).sort(
(a, b) => (b.latest.created_at ?? 0) - (a.latest.created_at ?? 0),
);
}, [otherWikiPages]);
return (
<main className="mira-page">
<div className="mira-content">
<header style={{ padding: '24px 0 16px', borderBottom: '1px solid #2a2a2a' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 4 }}>
<Link
href="/mira"
style={{ color: '#888', fontSize: 14, textDecoration: 'none' }}
>
Mira
</Link>
</div>
<h1 style={{ fontSize: 28, fontWeight: 700, color: '#fff', margin: 0 }}>
📚 Mira Wiki
</h1>
<p style={{ color: '#888', fontSize: 14, marginTop: 4 }}>
leo Karpathy LLM Wiki
</p>
</header>
{loading && <div style={{ padding: 24, color: '#666' }}></div>}
{error && (
<div style={{ padding: 24, color: '#e66' }}>{error}</div>
)}
{!loading && !error && (
<>
<Section title="📋 Schema(合成規則)">
{schema ? (
<WikiCardLink page_name={schema.page_name} title="mira-wiki-schema" excerpt="ingest 規則手冊:cypher binding、17 predicates、entity normalize⋯" />
) : (
<Empty> schema</Empty>
)}
</Section>
<Section title="🗂 Index4 個分類)">
{indexChildren.length > 0 ? (
<div style={{ display: 'grid', gap: 8 }}>
{indexChildren.map((b) => {
const tags = b.tags_json ? (JSON.parse(b.tags_json) as string[]) : [];
const key = tags.find((t) => t.startsWith('index-key:'))?.replace('index-key:', '') ?? '?';
return (
<WikiCardLink
key={b.id}
page_name={b.page_name}
title={`${iconForKey(key)} ${key}`}
excerpt={firstLineOf(b.content)}
/>
);
})}
</div>
) : (
<Empty>index children </Empty>
)}
</Section>
<Section title={`🧭 Index Entries${indexEntries.length})— CC 看的 entity 摘要`}>
{indexEntries.length > 0 ? (
<div style={{ display: 'grid', gap: 8 }}>
{indexEntries.map((b) => {
const entity = (b.page_name ?? '').replace(/^index-/, '');
const firstLine = firstLineOf(b.content)
.replace(/^#+\s*/, '')
.slice(0, 80);
return (
<WikiCardLink
key={b.id}
page_name={b.page_name ?? ''}
title={entity}
excerpt={firstLine || `index for ${entity}`}
/>
);
})}
</div>
) : (
<Empty> index-entrywiki_synthesis </Empty>
)}
</Section>
<Section title="📜 Log(每月一筆)">
{logEntries.length > 0 ? (
<div style={{ display: 'grid', gap: 8 }}>
{logEntries.map((b) => (
<WikiCardLink
key={b.id}
page_name={b.page_name}
title={b.page_name}
excerpt={firstLineOf(b.content)}
/>
))}
</div>
) : (
<Empty> log</Empty>
)}
</Section>
<Section title={`📖 Wiki Pages${dedupedWikiPages.length},原 ${otherWikiPages.length} 筆累積版本)`}>
{dedupedWikiPages.length > 0 ? (
<div style={{ display: 'grid', gap: 8 }}>
{dedupedWikiPages.map((g) => (
<WikiCardLink
key={g.latest.id}
page_name={g.latest.page_name}
title={g.entity}
excerpt={
g.versionCount > 1
? `${g.versionCount} 版累積 ・ 最新 ${new Date((g.latest.created_at ?? 0) * 1000).toLocaleString('zh-TW')}`
: `建立 ${new Date((g.latest.created_at ?? 0) * 1000).toLocaleString('zh-TW')}`
}
/>
))}
</div>
) : (
<Empty> wiki page 7-B ai-canon-wiki workflow </Empty>
)}
</Section>
</>
)}
</div>
</main>
);
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section style={{ padding: '20px 0', borderBottom: '1px solid #1f1f1f' }}>
<h2 style={{ fontSize: 16, fontWeight: 600, color: '#ddd', marginBottom: 12 }}>
{title}
</h2>
{children}
</section>
);
}
function Empty({ children }: { children: React.ReactNode }) {
return (
<div style={{ color: '#555', fontStyle: 'italic', fontSize: 13 }}>{children}</div>
);
}
function WikiCardLink({
page_name,
title,
excerpt,
}: {
page_name: string;
title: string;
excerpt: string;
}) {
return (
<Link
href={`/mira/wiki/${encodeURIComponent(page_name)}`}
style={{
display: 'block',
padding: '12px 14px',
background: '#1a1a1a',
border: '1px solid #2a2a2a',
borderRadius: 6,
textDecoration: 'none',
color: 'inherit',
}}
>
<div style={{ color: '#ddd', fontWeight: 500, marginBottom: 4 }}>{title}</div>
{excerpt && (
<div
style={{
color: '#888',
fontSize: 13,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{excerpt}
</div>
)}
</Link>
);
}
function iconForKey(key: string): string {
return (
{
entities: '🧩',
topics: '📂',
sources: '🔗',
stale: '⚠️',
}[key] ?? '•'
);
}
function firstLineOf(content: string): string {
if (!content) return '';
const firstNonHeader = content
.split('\n')
.map((l) => l.trim())
.find((l) => l && !l.startsWith('#') && !l.startsWith('>'));
return firstNonHeader ?? '';
}