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
+41
View File
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+1
View File
@@ -0,0 +1 @@
legacy-peer-deps=true
+5
View File
@@ -0,0 +1,5 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+36
View File
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+100
View File
@@ -0,0 +1,100 @@
'use client';
import { useEffect, useRef } from 'react';
import Link from 'next/link';
import SiteNav from '../components/SiteNav';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
export default function ApiDocsPage() {
const containerRef = useRef<HTMLDivElement>(null);
const initialized = useRef(false);
useEffect(() => {
if (initialized.current || !containerRef.current) return;
initialized.current = true;
// Dynamically load Swagger UI from CDN
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://unpkg.com/swagger-ui-dist@5/swagger-ui.css';
document.head.appendChild(link);
const script = document.createElement('script');
script.src = 'https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js';
script.onload = () => {
const SwaggerUIBundle = (window as unknown as { SwaggerUIBundle: (opts: unknown) => void }).SwaggerUIBundle;
if (!SwaggerUIBundle || !containerRef.current) return;
SwaggerUIBundle({
url: `${API_BASE}/openapi.json`,
dom_id: '#swagger-ui',
presets: [(window as unknown as { SwaggerUIBundle: { presets: { apis: unknown } } }).SwaggerUIBundle.presets.apis],
layout: 'BaseLayout',
defaultModelsExpandDepth: -1,
docExpansion: 'list',
filter: true,
tryItOutEnabled: true,
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
requestInterceptor: (request: { headers: Record<string, string> }) => {
// Inject API key from localStorage if present
const key = localStorage.getItem('arcrun_api_key');
if (key) request.headers['X-Arcrun-API-Key'] = key;
return request;
},
});
};
document.head.appendChild(script);
return () => {
// cleanup not strictly needed for page navigation
};
}, []);
return (
<div className="min-h-screen bg-[#0a0a0a] text-[#ededed]">
<SiteNav currentPath="/api-docs" />
{/* Header */}
<div className="max-w-5xl mx-auto px-6 py-8">
<h1 className="text-2xl font-bold text-white mb-2">API Reference</h1>
<p className="text-[#555] text-sm mb-2">
arcrun APIPython / JS lib HTTP request
</p>
<p className="text-[#444] text-xs mb-6">
Endpoint: <span className="font-mono text-[#666]">{API_BASE}</span>
</p>
{/* API Key hint */}
<div className="bg-[#111] border border-[#222] rounded-lg p-4 mb-8 text-sm">
<p className="text-[#666] mb-2">
API API Key
</p>
<ApiKeyInput />
</div>
{/* Swagger UI */}
<div className="bg-white rounded-xl overflow-hidden" ref={containerRef}>
<div id="swagger-ui" className="min-h-96"></div>
</div>
</div>
</div>
);
}
function ApiKeyInput() {
return (
<div className="flex gap-2">
<input
type="text"
placeholder="ak_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
className="flex-1 bg-[#0a0a0a] border border-[#2a2a2a] rounded px-3 py-1.5 text-xs font-mono text-[#cdd6f4] focus:outline-none focus:border-indigo-700"
onChange={(e) => {
if (e.target.value.startsWith('ak_')) {
localStorage.setItem('arcrun_api_key', e.target.value);
}
}}
/>
<span className="text-[#444] text-xs self-center"> requests</span>
</div>
);
}
+90
View File
@@ -0,0 +1,90 @@
'use client';
// 九宮格 App Launcher(受 Google Apps menu 啟發)
// 規範:matrix/identity/.agents/specs/identity/design.md §2.5
// 非白名單 user 看到 mira 等受限 app 顯示為灰色 + tooltip「即將開放」
import { useEffect, useRef, useState } from 'react';
import { MATRIX_APPS, isAppAccessible, type AppEntry } from './apps';
export default function AppLauncher({ userEmail }: { userEmail: string | null }) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onClickOutside = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', onClickOutside);
return () => document.removeEventListener('mousedown', onClickOutside);
}, [open]);
return (
<div className="relative" ref={ref}>
<button
type="button"
onClick={() => setOpen(o => !o)}
aria-label="切換應用"
className="flex items-center justify-center w-9 h-9 rounded-md text-[#888] hover:text-white hover:bg-[#1a1a1a] transition-colors"
>
{/* 九宮格 icon */}
<svg width="18" height="18" viewBox="0 0 18 18" fill="currentColor">
<circle cx="3" cy="3" r="1.5" /><circle cx="9" cy="3" r="1.5" /><circle cx="15" cy="3" r="1.5" />
<circle cx="3" cy="9" r="1.5" /><circle cx="9" cy="9" r="1.5" /><circle cx="15" cy="9" r="1.5" />
<circle cx="3" cy="15" r="1.5" /><circle cx="9" cy="15" r="1.5" /><circle cx="15" cy="15" r="1.5" />
</svg>
</button>
{open && (
<div
className="absolute right-0 mt-2 w-72 bg-[#0f0f0f] border border-[#222] rounded-lg shadow-xl p-2 z-50"
role="menu"
>
<div className="grid grid-cols-3 gap-1">
{MATRIX_APPS.map(app => (
<AppTile key={app.id} app={app} userEmail={userEmail} onClose={() => setOpen(false)} />
))}
</div>
</div>
)}
</div>
);
}
function AppTile({
app,
userEmail,
onClose,
}: {
app: AppEntry;
userEmail: string | null;
onClose: () => void;
}) {
const accessible = isAppAccessible(app, userEmail);
const tooltip = !accessible ? (app.locked_tooltip ?? '即將開放') : (app.description ?? '');
if (!accessible) {
return (
<div
title={tooltip}
className="flex flex-col items-center justify-center gap-1 p-3 rounded-md cursor-not-allowed opacity-40"
>
<span className="text-2xl grayscale">{app.icon ?? '📦'}</span>
<span className="text-xs text-[#666] text-center">{app.name}</span>
</div>
);
}
return (
<a
href={app.url}
onClick={onClose}
title={tooltip}
className="flex flex-col items-center justify-center gap-1 p-3 rounded-md hover:bg-[#1a1a1a] transition-colors text-[#ccc] hover:text-white"
>
<span className="text-2xl">{app.icon ?? '📦'}</span>
<span className="text-xs text-center">{app.name}</span>
</a>
);
}
+82
View File
@@ -0,0 +1,82 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import AppLauncher from './AppLauncher';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
type NavUser = {
display_name: string;
email: string;
avatar_url?: string;
};
export default function SiteNav({ currentPath }: { currentPath?: string }) {
const [user, setUser] = useState<NavUser | null | undefined>(undefined);
useEffect(() => {
fetch(`${API_BASE}/me`, { credentials: 'include' })
.then(r => r.ok ? r.json() as Promise<NavUser> : null)
.then(u => setUser(u))
.catch(() => setUser(null));
}, []);
const logout = async () => {
await fetch(`${API_BASE}/auth/logout`, { method: 'POST', credentials: 'include' });
window.location.href = '/';
};
const linkCls = (path: string) =>
`transition-colors text-sm ${currentPath === path ? 'text-white' : 'text-[#666] hover:text-white'}`;
return (
<nav className="flex items-center justify-between px-6 py-4 border-b border-[#1a1a1a]">
<Link href="/" className="text-white font-bold text-lg tracking-tight hover:opacity-80 transition-opacity">
arcrun
</Link>
<div className="flex items-center gap-4 text-sm">
<Link href="/integrations" className={linkCls('/integrations')}>Integrations</Link>
<Link href="/api-docs" className={linkCls('/api-docs')}>API</Link>
<a
href="https://github.com/richblack/arcrun"
target="_blank"
rel="noopener noreferrer"
className="text-[#666] hover:text-white transition-colors"
>
GitHub
</a>
{user === undefined ? (
// Loading — placeholder to prevent layout shift
<div className="w-20 h-7" />
) : user ? (
<>
<AppLauncher userEmail={user.email} />
<Link href="/dashboard" className="flex items-center gap-2 hover:opacity-80 transition-opacity">
{user.avatar_url && (
// eslint-disable-next-line @next/next/no-img-element
<img src={user.avatar_url} alt="" width={26} height={26} className="rounded-full" />
)}
<span className="text-[#aaa]">{user.display_name}</span>
</Link>
<button
onClick={logout}
className="text-[#555] hover:text-[#888] transition-colors cursor-pointer"
>
</button>
</>
) : (
<Link
href="/login"
className="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-1.5 rounded-md font-medium transition-colors"
>
Get API Key
</Link>
)}
</div>
</nav>
);
}
+54
View File
@@ -0,0 +1,54 @@
// Matrix App Launcher 九宮格清單
// 來源:matrix/identity/.agents/specs/identity/apps.jsonv0 過渡複製,未來 v1 抽進 @matrix/identity-ui
// 規範:matrix/identity/.agents/specs/identity/design.md §2.5
export type AppEntry = {
id: string;
name: string;
url: string;
icon?: string;
description?: string;
access?: 'public' | 'allowlist';
allowlist_emails?: string[];
locked_tooltip?: string;
};
export const MATRIX_APPS: AppEntry[] = [
{
id: 'arcrun',
name: 'Arcrun',
url: 'https://arcrun.dev',
icon: '🔄',
description: '工作流引擎與零件平台',
},
{
id: 'dashboard',
name: 'Dashboard',
url: 'https://arcrun.dev/dashboard',
icon: '🔑',
description: 'API Key 管理',
},
{
id: 'integrations',
name: 'Integrations',
url: 'https://arcrun.dev/integrations',
icon: '🧩',
description: '服務目錄',
},
{
id: 'mira',
name: 'Mira',
url: 'https://arcrun.dev/mira',
icon: '🌊',
description: '個人化 KM 河道',
access: 'allowlist',
allowlist_emails: ['leo21c@gmail.com'],
locked_tooltip: '即將開放',
},
];
export function isAppAccessible(app: AppEntry, userEmail: string | null): boolean {
if (app.access !== 'allowlist') return true;
if (!userEmail) return false;
return (app.allowlist_emails ?? []).includes(userEmail);
}
+215
View File
@@ -0,0 +1,215 @@
'use client';
import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import SiteNav from '../components/SiteNav';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
type User = {
email: string;
display_name: string;
avatar_url?: string;
api_key: string;
provider: string;
created_at: string;
};
export default function DashboardPage() {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [copied, setCopied] = useState(false);
const [rotating, setRotating] = useState(false);
const [revoking, setRevoking] = useState(false);
const [error, setError] = useState('');
const [showKey, setShowKey] = useState(false);
const fetchUser = useCallback(async () => {
try {
const res = await fetch(`${API_BASE}/me`, { credentials: 'include' });
if (res.status === 401) {
window.location.href = '/login?redirect=/dashboard';
return;
}
if (!res.ok) throw new Error('Failed to fetch user');
const data = await res.json() as User;
setUser(data);
} catch {
setError('無法載入用戶資訊,請重新整理。');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchUser();
}, [fetchUser]);
const copyKey = async () => {
if (!user) return;
await navigator.clipboard.writeText(user.api_key);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const rotateKey = async () => {
if (!confirm('確定要 Rotate API Key 嗎?舊 Key 的 workflow credentials 不會自動遷移。')) return;
setRotating(true);
setError('');
try {
const res = await fetch(`${API_BASE}/me/api-key/rotate`, {
method: 'PUT',
credentials: 'include',
});
if (!res.ok) throw new Error('rotate failed');
const data = await res.json() as { api_key: string; message: string };
setUser(prev => prev ? { ...prev, api_key: data.api_key } : null);
setShowKey(true);
} catch {
setError('Rotate 失敗,請稍後重試。');
} finally {
setRotating(false);
}
};
const revokeKey = async () => {
if (!confirm('確定要 Revoke API Key 嗎?所有使用此 Key 的服務將立即失效。')) return;
setRevoking(true);
setError('');
try {
const res = await fetch(`${API_BASE}/me/api-key`, {
method: 'DELETE',
credentials: 'include',
});
if (!res.ok) throw new Error('revoke failed');
window.location.href = '/login?revoked=1';
} catch {
setError('Revoke 失敗,請稍後重試。');
} finally {
setRevoking(false);
}
};
if (loading) {
return (
<div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center">
<div className="text-[#444] text-sm animate-pulse">...</div>
</div>
);
}
if (!user) {
return (
<div className="min-h-screen bg-[#0a0a0a] flex flex-col items-center justify-center gap-4">
<p className="text-[#666]">{error || '請先登入。'}</p>
<Link href="/login" className="text-indigo-400 hover:text-indigo-300 text-sm"></Link>
</div>
);
}
const maskedKey = showKey ? user.api_key : user.api_key.slice(0, 8) + '••••••••••••••••••••••••';
return (
<div className="min-h-screen bg-[#0a0a0a] text-[#ededed]">
<SiteNav currentPath="/dashboard" />
<main className="max-w-2xl mx-auto px-6 py-12">
<h1 className="text-2xl font-bold text-white mb-1">{user.display_name}</h1>
<p className="text-[#555] text-sm mb-10">
{user.provider} · {new Date(user.created_at).toLocaleDateString('zh-TW')}
</p>
{error && (
<div className="bg-red-950/50 border border-red-900/50 text-red-400 text-sm px-4 py-3 rounded-lg mb-6">
{error}
</div>
)}
{/* API Key Card */}
<div className="bg-[#111] border border-[#222] rounded-2xl p-6 mb-6">
<h2 className="text-white font-semibold mb-4"> API Key</h2>
<div className="flex items-center gap-2 mb-4">
<div className="flex-1 bg-[#0a0a0a] border border-[#2a2a2a] rounded-lg px-4 py-3 font-mono text-sm text-[#cdd6f4] overflow-hidden text-ellipsis whitespace-nowrap">
{maskedKey}
</div>
<button
onClick={() => setShowKey(v => !v)}
className="px-3 py-3 text-[#555] hover:text-[#aaa] text-xs border border-[#2a2a2a] rounded-lg transition-colors cursor-pointer whitespace-nowrap"
title={showKey ? '隱藏' : '顯示'}
>
{showKey ? '隱藏' : '顯示'}
</button>
<button
onClick={copyKey}
className="px-4 py-3 bg-[#1e1e2e] hover:bg-[#2a2a3e] text-indigo-400 text-xs border border-indigo-900/30 rounded-lg transition-colors cursor-pointer whitespace-nowrap"
>
{copied ? '已複製!' : '複製'}
</button>
</div>
<div className="bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg p-4 mb-6 text-xs font-mono text-[#666] space-y-1">
<div className="text-[#444] mb-2"># 使</div>
<div>Authorization: Bearer {user.api_key.slice(0, 8)}...</div>
<div># </div>
<div>X-Arcrun-API-Key: {user.api_key.slice(0, 8)}...</div>
</div>
<div className="flex gap-3 flex-wrap">
<button
onClick={rotateKey}
disabled={rotating}
className="flex-1 border border-[#333] hover:border-[#555] text-[#aaa] hover:text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
{rotating ? 'Rotating...' : 'Rotate Key'}
</button>
<button
onClick={revokeKey}
disabled={revoking}
className="flex-1 border border-red-900/50 hover:border-red-700/50 text-red-500 hover:text-red-400 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
{revoking ? 'Revoking...' : 'Revoke Key'}
</button>
</div>
</div>
{/* Quick Start */}
<div className="bg-[#111] border border-[#222] rounded-2xl p-6">
<h2 className="text-white font-semibold mb-4"></h2>
<div className="space-y-3 text-sm">
<div className="flex items-start gap-3">
<span className="text-indigo-500 font-mono mt-0.5">1.</span>
<div>
<div className="text-[#aaa]"> CLI</div>
<pre className="bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg px-3 py-2 mt-1 text-xs text-[#cdd6f4] font-mono">npm install -g arcrun</pre>
</div>
</div>
<div className="flex items-start gap-3">
<span className="text-indigo-500 font-mono mt-0.5">2.</span>
<div>
<div className="text-[#aaa]"> API Key </div>
<pre className="bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg px-3 py-2 mt-1 text-xs text-[#cdd6f4] font-mono">acr init</pre>
</div>
</div>
<div className="flex items-start gap-3">
<span className="text-indigo-500 font-mono mt-0.5">3.</span>
<div>
<div className="text-[#aaa]"></div>
<pre className="bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg px-3 py-2 mt-1 text-xs text-[#cdd6f4] font-mono">acr auth-recipe scaffold notion</pre>
</div>
</div>
</div>
</div>
<div className="flex gap-4 mt-6 text-sm">
<Link href="/integrations" className="text-indigo-400 hover:text-indigo-300 transition-colors">
20
</Link>
<Link href="/api-docs" className="text-indigo-400 hover:text-indigo-300 transition-colors">
API
</Link>
</div>
</main>
</div>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+22
View File
@@ -0,0 +1,22 @@
@import "tailwindcss";
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
}
body {
background: var(--background);
color: var(--foreground);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
pre, code {
font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
}
+164
View File
@@ -0,0 +1,164 @@
export const runtime = 'edge';
import Link from 'next/link';
import SiteNav from '../components/SiteNav';
type Recipe = {
id: string;
name: string;
primitive: 'static_key' | 'service_account';
category: string;
secrets: string[];
badge?: 'official';
};
const RECIPES: Recipe[] = [
// AI / LLM
{ id: 'openai', name: 'OpenAI', primitive: 'static_key', category: 'AI', secrets: ['OPENAI_API_KEY'], badge: 'official' },
{ id: 'anthropic', name: 'Anthropic', primitive: 'static_key', category: 'AI', secrets: ['ANTHROPIC_API_KEY'], badge: 'official' },
// Productivity
{ id: 'notion', name: 'Notion', primitive: 'static_key', category: 'Productivity', secrets: ['NOTION_TOKEN'], badge: 'official' },
{ id: 'airtable', name: 'Airtable', primitive: 'static_key', category: 'Productivity', secrets: ['AIRTABLE_TOKEN'], badge: 'official' },
{ id: 'typeform', name: 'Typeform', primitive: 'static_key', category: 'Productivity', secrets: ['TYPEFORM_TOKEN'], badge: 'official' },
{ id: 'jira', name: 'Jira', primitive: 'static_key', category: 'Productivity', secrets: ['JIRA_DOMAIN', 'JIRA_EMAIL', 'JIRA_API_TOKEN'], badge: 'official' },
// Communication
{ id: 'slack', name: 'Slack', primitive: 'static_key', category: 'Communication', secrets: ['SLACK_TOKEN'], badge: 'official' },
{ id: 'discord', name: 'Discord', primitive: 'static_key', category: 'Communication', secrets: ['DISCORD_BOT_TOKEN'], badge: 'official' },
{ id: 'twilio', name: 'Twilio', primitive: 'static_key', category: 'Communication', secrets: ['TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN'], badge: 'official' },
{ id: 'sendgrid', name: 'SendGrid', primitive: 'static_key', category: 'Communication', secrets: ['SENDGRID_API_KEY'], badge: 'official' },
{ id: 'resend', name: 'Resend', primitive: 'static_key', category: 'Communication', secrets: ['RESEND_API_KEY'], badge: 'official' },
// Dev / Code
{ id: 'github', name: 'GitHub', primitive: 'static_key', category: 'Dev', secrets: ['GITHUB_TOKEN'], badge: 'official' },
{ id: 'linear', name: 'Linear', primitive: 'static_key', category: 'Dev', secrets: ['LINEAR_API_KEY'], badge: 'official' },
{ id: 'supabase', name: 'Supabase', primitive: 'static_key', category: 'Dev', secrets: ['SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY'], badge: 'official' },
// Commerce
{ id: 'stripe', name: 'Stripe', primitive: 'static_key', category: 'Commerce', secrets: ['STRIPE_SECRET_KEY'], badge: 'official' },
{ id: 'shopify', name: 'Shopify', primitive: 'static_key', category: 'Commerce', secrets: ['SHOPIFY_STORE_DOMAIN', 'SHOPIFY_ACCESS_TOKEN'], badge: 'official' },
{ id: 'hubspot', name: 'HubSpot', primitive: 'static_key', category: 'Commerce', secrets: ['HUBSPOT_ACCESS_TOKEN'], badge: 'official' },
// Google Service Account
{ id: 'google_drive_sa', name: 'Google Drive', primitive: 'service_account', category: 'Google', secrets: ['GOOGLE_SERVICE_ACCOUNT_JSON'], badge: 'official' },
{ id: 'google_gmail_sa', name: 'Gmail', primitive: 'service_account', category: 'Google', secrets: ['GOOGLE_SERVICE_ACCOUNT_JSON'], badge: 'official' },
{ id: 'google_sheets_sa', name: 'Google Sheets', primitive: 'service_account', category: 'Google', secrets: ['GOOGLE_SERVICE_ACCOUNT_JSON'], badge: 'official' },
];
const CATEGORIES = ['All', 'AI', 'Productivity', 'Communication', 'Dev', 'Commerce', 'Google'];
export default function IntegrationsPage({
searchParams,
}: {
searchParams: Promise<{ cat?: string }>;
}) {
return <IntegrationsContent searchParamsPromise={searchParams} />;
}
async function IntegrationsContent({
searchParamsPromise,
}: {
searchParamsPromise: Promise<{ cat?: string }>;
}) {
const params = await searchParamsPromise;
const cat = params.cat ?? 'All';
const filtered = cat === 'All' ? RECIPES : RECIPES.filter(r => r.category === cat);
const staticCount = RECIPES.filter(r => r.primitive === 'static_key').length;
const saCount = RECIPES.filter(r => r.primitive === 'service_account').length;
return (
<div className="min-h-screen bg-[#0a0a0a] text-[#ededed]">
<SiteNav currentPath="/integrations" />
<div className="max-w-5xl mx-auto px-6 py-12">
{/* Header */}
<h1 className="text-3xl font-bold text-white mb-2">
{RECIPES.length}
</h1>
<p className="text-[#555] mb-2">
arcrun recipe
</p>
<div className="flex gap-4 text-sm text-[#444] mb-8">
<span>{staticCount} API Key </span>
<span>·</span>
<span>{saCount} Service Account </span>
</div>
{/* Category filter */}
<div className="flex gap-2 flex-wrap mb-8">
{CATEGORIES.map(c => (
<Link
key={c}
href={c === 'All' ? '/integrations' : `/integrations?cat=${c}`}
className={`px-3 py-1.5 rounded-full text-sm transition-colors ${
cat === c
? 'bg-indigo-600 text-white'
: 'bg-[#111] border border-[#222] text-[#666] hover:text-white hover:border-[#444]'
}`}
>
{c}
</Link>
))}
</div>
{/* Recipe grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-12">
{filtered.map(recipe => (
<RecipeCard key={recipe.id} recipe={recipe} />
))}
</div>
{/* Contribute CTA */}
<div className="bg-[#111] border border-[#222] rounded-2xl p-8 text-center">
<h2 className="text-white font-semibold text-xl mb-2"></h2>
<p className="text-[#555] text-sm mb-4 max-w-lg mx-auto">
API Key YAML
API AI PR
</p>
<div className="flex gap-3 justify-center flex-wrap">
<a href="https://github.com/richblack/arcrun" target="_blank" rel="noopener noreferrer"
className="bg-indigo-600 hover:bg-indigo-500 text-white px-5 py-2.5 rounded-lg text-sm font-medium transition-colors">
</a>
<a href="https://github.com/richblack/arcrun/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer"
className="border border-[#333] hover:border-[#555] text-[#aaa] hover:text-white px-5 py-2.5 rounded-lg text-sm font-medium transition-colors">
Recipe
</a>
</div>
</div>
</div>
</div>
);
}
function RecipeCard({ recipe }: { recipe: Recipe }) {
const primitiveLabel = recipe.primitive === 'static_key' ? 'API Key' : 'Service Account';
const primitiveColor = recipe.primitive === 'static_key' ? 'text-blue-400' : 'text-orange-400';
return (
<div className="bg-[#111] border border-[#1e1e1e] hover:border-[#333] rounded-xl p-5 transition-colors">
<div className="flex items-start justify-between mb-3">
<div>
<h3 className="text-white font-medium">{recipe.name}</h3>
<span className={`text-xs font-mono mt-0.5 ${primitiveColor}`}>{primitiveLabel}</span>
</div>
{recipe.badge === 'official' && (
<span className="text-xs bg-indigo-950/50 text-indigo-400 border border-indigo-900/30 px-2 py-0.5 rounded-full">
</span>
)}
</div>
<div className="text-xs text-[#444] space-y-1">
{recipe.secrets.map(s => (
<div key={s} className="font-mono flex items-center gap-1">
<span className="text-[#333]"></span> {s}
</div>
))}
</div>
<div className="mt-4 text-xs">
<code className="text-[#555] bg-[#0a0a0a] px-2 py-1 rounded font-mono">
acr auth-recipe scaffold {recipe.id}
</code>
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "arcrun — Stop fighting OAuth",
description: "One API key. Every service. Works anywhere. arcrun handles Google, Notion, GitHub, Slack authentication so your code doesn't have to.",
openGraph: {
title: "arcrun — Stop fighting OAuth",
description: "One API key. Every service. Works anywhere.",
url: "https://arcrun.dev",
siteName: "arcrun",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className="h-full">
<body className="min-h-full flex flex-col bg-[#0a0a0a] text-[#ededed]">
{children}
</body>
</html>
);
}
+102
View File
@@ -0,0 +1,102 @@
export const runtime = 'edge';
import Link from 'next/link';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
export default function LoginPage({
searchParams,
}: {
searchParams: Promise<{ error?: string; redirect?: string }>;
}) {
return (
<LoginContent searchParamsPromise={searchParams} />
);
}
async function LoginContent({
searchParamsPromise,
}: {
searchParamsPromise: Promise<{ error?: string; redirect?: string }>;
}) {
const params = await searchParamsPromise;
const error = params.error;
const redirect = params.redirect ?? '/dashboard';
const googleUrl = `${API_BASE}/auth/google/start?redirect=${encodeURIComponent(redirect)}`;
const githubUrl = `${API_BASE}/auth/github/start?redirect=${encodeURIComponent(redirect)}`;
const errorMessages: Record<string, string> = {
cancelled: '登入已取消。',
invalid_state: '安全性驗證失敗,請重試。',
server_error: '伺服器錯誤,請稍後重試。',
github_email_required: 'GitHub 帳號需要設定公開 Email 才能登入。',
};
return (
<div className="min-h-screen bg-[#0a0a0a] flex flex-col items-center justify-center px-6">
{/* Logo */}
<div className="mb-8 text-center">
<Link href="/" className="text-white font-bold text-2xl tracking-tight hover:opacity-80 transition-opacity">
arcrun
</Link>
</div>
{/* Card */}
<div className="w-full max-w-sm bg-[#111] border border-[#222] rounded-2xl p-8">
<h1 className="text-xl font-semibold text-white mb-2 text-center"></h1>
<p className="text-[#555] text-sm text-center mb-8"> API Key使</p>
{error && (
<div className="bg-red-950/50 border border-red-900/50 text-red-400 text-sm px-4 py-3 rounded-lg mb-6">
{errorMessages[error] ?? '登入時發生錯誤,請重試。'}
</div>
)}
<div className="flex flex-col gap-3">
{/* Google */}
<a href={googleUrl}
className="flex items-center justify-center gap-3 bg-white hover:bg-gray-100 text-gray-900 px-4 py-3 rounded-lg font-medium text-sm transition-colors">
<GoogleIcon />
Continue with Google
</a>
{/* GitHub */}
<a href={githubUrl}
className="flex items-center justify-center gap-3 bg-[#24292e] hover:bg-[#2f363d] text-white border border-[#444] px-4 py-3 rounded-lg font-medium text-sm transition-colors">
<GitHubIcon />
Continue with GitHub
</a>
</div>
<p className="text-[#444] text-xs text-center mt-6 leading-relaxed">
</p>
</div>
<Link href="/" className="mt-6 text-[#444] hover:text-[#888] text-sm transition-colors">
</Link>
</div>
);
}
function GoogleIcon() {
return (
<svg width="18" height="18" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
</svg>
);
}
function GitHubIcon() {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"/>
</svg>
);
}
+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 ?? '';
}
+199
View File
@@ -0,0 +1,199 @@
'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import SiteNav from './components/SiteNav';
const API_BASE = process.env.NEXT_PUBLIC_API_BASE ?? 'https://cypher.arcrun.dev';
const CODE_DEMOS = {
python: `pip install arcrun
from arcrun import Arcrun
client = Arcrun() # reads ARCRUN_API_KEY from env
# One-time setup: upload credential
client.auth.setup("notion", token="secret_xxx")
# Every time after: just bind and use
notion = client.auth.bind("notion")
pages = notion.get("/pages").json()
# Works with any of 20+ services
drive = client.auth.bind("google_drive_sa")
files = drive.get("/files").json()`,
javascript: `npm install arcrun
import { Arcrun } from 'arcrun'
const client = new Arcrun() // reads ARCRUN_API_KEY from env
// One-time setup: upload credential
await client.auth.setup('notion', { token: 'secret_xxx' })
// Every time after: just bind and use
const notion = await client.auth.bind('notion')
const pages = await (await notion.get('/pages')).json()
// Run a deployed workflow
const result = await client.workflows.run('my-flow', {
email: 'user@example.com'
})`,
http: `# Works with any HTTP tool — curl, n8n, Make, Postman
POST ${API_BASE}/webhooks/named/my-workflow/trigger
X-Arcrun-API-Key: YOUR_API_KEY
Content-Type: application/json
{
"email": "user@example.com"
}
# n8n: HTTP Request 西`,
};
export default function HomePage() {
const [activeTab, setActiveTab] = useState<'python' | 'javascript' | 'http'>('python');
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() => {
fetch(`${API_BASE}/me`, { credentials: 'include' })
.then(r => { if (r.ok) setIsLoggedIn(true); })
.catch(() => {});
}, []);
return (
<div className="flex flex-col min-h-screen bg-[#0a0a0a] text-[#ededed]">
<SiteNav currentPath="/" />
{/* Hero */}
<section className="flex flex-col items-center text-center px-6 pt-24 pb-16">
<div className="inline-flex items-center gap-2 bg-[#1a1a2e] text-indigo-400 text-xs px-3 py-1 rounded-full mb-6 border border-indigo-900/50">
<span className="w-1.5 h-1.5 bg-indigo-400 rounded-full animate-pulse inline-block"></span>
Open Source · Free API Key · No Credit Card
</div>
<h1 className="text-5xl md:text-6xl font-bold text-white mb-4 leading-tight max-w-3xl">
Stop fighting OAuth.
</h1>
<p className="text-xl md:text-2xl text-[#888] mb-3 max-w-2xl">
One API key. Every service. Works anywhere.
</p>
<p className="text-[#555] max-w-xl mb-10">
arcrun handles Google, Notion, GitHub, Slack authentication
so your Python / JS code doesn&apos;t have to.
</p>
<div className="flex gap-3 flex-wrap justify-center">
<Link href={isLoggedIn ? '/dashboard' : '/login'}
className="bg-indigo-600 hover:bg-indigo-500 text-white px-6 py-3 rounded-lg font-medium transition-colors">
{isLoggedIn ? 'Go to Dashboard' : 'Get API Key — Free'}
</Link>
<a href="https://github.com/richblack/arcrun" target="_blank" rel="noopener noreferrer"
className="border border-[#333] hover:border-[#555] text-[#aaa] hover:text-white px-6 py-3 rounded-lg font-medium transition-colors">
View on GitHub
</a>
</div>
</section>
{/* Before / After */}
<section className="max-w-4xl mx-auto px-6 pb-16 w-full">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-center">
<div className="bg-[#111] border border-[#222] rounded-xl p-6">
<div className="text-[#555] text-xs mb-3 font-mono uppercase tracking-wider">Before</div>
<div className="text-red-400 text-sm font-mono space-y-1 opacity-70">
<div>40 OAuth </div>
<div>GCP Console </div>
<div>debug </div>
<div>Service Account JSON</div>
<div>token </div>
</div>
</div>
<div className="flex items-center justify-center text-[#333] text-4xl font-thin select-none"></div>
<div className="bg-[#111] border border-indigo-900/50 rounded-xl p-6">
<div className="text-indigo-400 text-xs mb-3 font-mono uppercase tracking-wider">After</div>
<pre className="text-green-400 text-sm font-mono leading-relaxed">
{`from arcrun import auth
drive = auth.bind(
"google_drive"
)
# done.`}
</pre>
</div>
</div>
</section>
{/* Code Demo */}
<section className="max-w-3xl mx-auto px-6 pb-20 w-full">
<div className="bg-[#111] border border-[#222] rounded-xl overflow-hidden">
<div className="flex border-b border-[#1e1e1e]">
{(['python', 'javascript', 'http'] as const).map(tab => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`px-5 py-3 text-sm font-medium transition-colors cursor-pointer ${
activeTab === tab
? 'text-white border-b-2 border-indigo-500 bg-[#0d0d1a]'
: 'text-[#555] hover:text-[#aaa]'
}`}
>
{tab === 'python' ? 'Python' : tab === 'javascript' ? 'JavaScript' : 'HTTP / n8n'}
</button>
))}
</div>
<div className="p-6 overflow-x-auto">
<pre className="text-sm text-[#cdd6f4] leading-relaxed">
<code>{CODE_DEMOS[activeTab]}</code>
</pre>
</div>
</div>
{activeTab === 'http' && (
<p className="text-[#444] text-sm mt-3 text-center">
n8n HTTP Request 西
</p>
)}
</section>
{/* Features */}
<section className="max-w-4xl mx-auto px-6 pb-20 w-full">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{[
{ title: '20+ 服務開箱即用', desc: 'Google、Notion、GitHub、Slack、OpenAI、Stripe... 全部一個 bind() 搞定。', icon: '🔌' },
{ title: 'AI-first 設計', desc: 'Token 消耗極小,YAML workflow 幾十個 token,讓 AI 直接讀寫執行。', icon: '🤖' },
{ title: '完全開源', desc: 'MIT 授權。Self-host 在你自己的 Cloudflare,或使用我們的 hosted 服務。', icon: '🔓' },
].map(f => (
<div key={f.title} className="bg-[#111] border border-[#1e1e1e] rounded-xl p-6">
<div className="text-2xl mb-3">{f.icon}</div>
<h3 className="text-white font-semibold mb-2">{f.title}</h3>
<p className="text-[#555] text-sm leading-relaxed">{f.desc}</p>
</div>
))}
</div>
</section>
{/* CTA */}
<section className="border-t border-[#1a1a1a] py-16 text-center px-6">
<h2 className="text-3xl font-bold text-white mb-3"></h2>
<p className="text-[#555] mb-8"> API Key</p>
<Link href={isLoggedIn ? '/dashboard' : '/login'}
className="bg-indigo-600 hover:bg-indigo-500 text-white px-8 py-3 rounded-lg font-medium transition-colors">
{isLoggedIn ? 'Go to Dashboard' : '免費取得 API Key'}
</Link>
</section>
{/* Footer */}
<footer className="border-t border-[#1a1a1a] py-8 px-6 text-center text-[#333] text-sm mt-auto">
<div className="flex items-center justify-center gap-6">
<Link href="/integrations" className="hover:text-[#777] transition-colors">Integrations</Link>
<Link href="/api-docs" className="hover:text-[#777] transition-colors">API Docs</Link>
<a href="https://github.com/richblack/arcrun" target="_blank" rel="noopener noreferrer"
className="hover:text-[#777] transition-colors">GitHub</a>
</div>
<p className="mt-4">arcrun MIT License</p>
</footer>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Protect /dashboard and /mira (login required; mira 額外白名單檢查在 layout)
if (pathname.startsWith('/dashboard') || pathname.startsWith('/mira')) {
const session = request.cookies.get('arcrun_session');
if (!session?.value) {
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('redirect', pathname);
return NextResponse.redirect(loginUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard', '/dashboard/:path*', '/mira', '/mira/:path*'],
};
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// Cloudflare Pages edge runtime compatibility
};
export default nextConfig;
+4965
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "landing",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"build:pages": "npx @cloudflare/next-on-pages",
"start": "next start",
"deploy": "npm run build:pages && wrangler pages deploy"
},
"dependencies": {
"@cloudflare/next-on-pages": "^1.13.16",
"next": "^15.5.15",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"wrangler": "^4.83.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"tailwindcss": "^4",
"typescript": "^5"
}
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+1
View File
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

+42
View File
@@ -0,0 +1,42 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": [
"node_modules"
]
}
+7
View File
@@ -0,0 +1,7 @@
name = "arcrun-landing"
compatibility_date = "2025-02-19"
compatibility_flags = ["nodejs_compat"]
pages_build_output_dir = ".vercel/output/static"
[vars]
NEXT_PUBLIC_API_BASE = "https://cypher.arcrun.dev"