Dianel555/DSkills / skills/agent-wiki
agent-wiki
UnverifiedIncremental LLM-friendly wiki generator for Obsidian note vaults. Use when: (1) Building wiki from notes, (2) Ingesting notes to wiki, (3) Obsidian LLM wiki, (4) Incremental knowledge base management. Triggers: 'build wiki from notes', 'ingest notes to wiki', 'Obsidian LLM wiki', 'incremental knowledge base'.
scripts/agent_wiki/home.py
View on GitHub"""Deterministic Obsidian homepage (``wiki/index.md``) skeleton + managed cards.
gen-home builds a *skeleton*: an Obsidian-native page frame (overview line, the
Bases embed ``![[index.base#主题总览]]``, a topic-navigation table scaffold and a
relationship-graph placeholder) plus one managed, regenerable region — the
"工作区" — delimited by HTML markers. The agent fills the semantic prose (topic
grouping, 范围 cells, relationship narrative); only the managed region is
script-owned and refreshed on every run, so re-running never clobbers agent
edits outside the markers.
The managed region renders captured reports / graphs as a responsive,
centered card grid via a Dataview ``dataviewjs`` query when Dataview + its JS
queries are available, else as a static NFC-sorted Markdown list. No wall-clock
timestamps, so output is byte-identical for a fixed vault. This module never
touches ``index.base`` or any ``.base`` file.
"""
from __future__ import annotations
from pathlib import Path
from . import boundary, config, frontmatter
from .config import nfc as _nfc
EMBED ="![[index.base#主题总览]]"
AUTO_START = "<!-- agent-wiki:auto start — generated by gen-home; do not edit inside -->"
AUTO_END = "<!-- agent-wiki:auto end -->"
PLACEHOLDER = "_待补充_"
# dataviewjs card block: scans wiki/queries|graphs relative to this note
# and renders clickable, theme-aware cards in a centered flex grid. Centering
# makes the trailing (short) row balanced instead of left-aligned with a gap;
# cards grow within [168px, 232px] so any item count fills rows evenly.
_CARDS_JS = """```dataviewjs
const root = dv.current().file.folder;
const groups = [
{ title: "🔎 检索报告", dir: root + "/queries", ext: "md" },
{ title: "🕸 图谱", dir: root + "/graphs", ext: "canvas" },
];
const style = dv.container.createEl("style");
style.textContent = `
.aw-grid{display:flex;flex-wrap:wrap;justify-content:center;gap:.75rem;margin:.5rem 0 1.25rem}
.aw-card{flex:1 1 168px;max-width:232px;min-height:44px;display:flex;align-items:center;justify-content:center;text-align:center;padding:.7rem .9rem;border:1px solid var(--background-modifier-border);border-radius:12px;background:var(--background-secondary);color:var(--text-normal);text-decoration:none;font-weight:500;box-shadow:0 1px 2px rgba(0,0,0,.06);transition:transform .18s ease,box-shadow .18s ease,border-color .18s ease}
.aw-card:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.12);border-color:var(--interactive-accent)}
.aw-card:focus-visible{outline:2px solid var(--interactive-accent);outline-offset:2px}
.aw-card:active{transform:translateY(0)}
@media (prefers-reduced-motion:reduce){.aw-card{transition:none}}
`;
for (const g of groups) {
dv.header(3, g.title);
const files = app.vault.getFiles()
.filter(f => f.extension === g.ext && f.path.startsWith(g.dir + "/"))
.sort((a, b) => a.basename.localeCompare(b.basename));
if (!files.length) { dv.paragraph("_(空)_"); continue; }
const grid = dv.container.createEl("div", { cls: "aw-grid" });
for (const f of files) {
const card = grid.createEl("a", { cls: "internal-link aw-card", href: f.path });
card.dataset.href = f.path;
card.setText(f.basename);
}
}
```"""
def _tiles(directory: Path, ext: str) -> list[tuple[str, str]]:
"""``(label, wiki-relative POSIX path)`` per ``*{ext}`` file, NFC-sorted;
empty when the directory is missing."""
entries = boundary.entries(directory, suffix=ext)
entries = sorted(entries, key=lambda e: _nfc(e.name))
return [(_nfc(e.stem), f"{directory.name}/{_nfc(e.name)}") for e in entries]
def _callout(kind: str, title: str, tiles: list[tuple[str, str]]) -> str:
lines = [f"> [!{kind}] {title}"]
if tiles:
lines += [f"> - [{label}]({path})" for label, path in tiles]
else:
lines.append("> _(空)_")
return "\n".join(lines)
def _topic_rows(vault: str | Path) -> list[tuple[str, int]]:
"""``(topic-name, source-count)`` per ``wiki/topics/*.md``, NFC-sorted. Count
is the frontmatter ``sources`` length (0 when absent/unparsable)."""
topics_dir = config.topics_dir(vault)
rows: list[tuple[str, int]] = []
entries = sorted(boundary.entries(topics_dir, suffix=".md"), key=lambda e: _nfc(e.name))
for entry in entries:
count = 0
try:
meta, _ = frontmatter.parse(entry.read_text())
sources = meta.get("sources")
count = len(sources) if isinstance(sources, list) else 0
except (OSError, UnicodeDecodeError, frontmatter.FrontmatterError):
count = 0
rows.append((_nfc(entry.stem), count))
return rows
def _nav_table(rows: list[tuple[str, int]]) -> str:
if not rows:
return f"{PLACEHOLDER}(暂无主题页;运行 index 后由 agent 分组并补全范围)"
lines = ["| 主题 | 篇数 | 范围 |", "|---|---|---|"]
lines += [f"| [[{name}]] | {count} | {PLACEHOLDER} |" for name, count in rows]
return "\n".join(lines)
def _workspace_body(vault: str | Path, cards: bool) -> str:
"""The 工作区 section body (heading + content); cards or static fallback."""
if cards:
callout = (
"> [!abstract] 由 agent-wiki 自动维护(Dataview 动态卡片)\n"
"> 检索报告 / 图谱 由 Dataview 实时扫描 `queries`、`graphs` 文件夹,"
"新增文件自动出现,无需手改。"
)
return f"## 🗂 工作区\n\n{callout}\n\n{_CARDS_JS}"
note = (
"> [!tip] 工作区(静态列表)\n"
"> 未检测到 Dataview 插件或其 JavaScript 查询未开启,已改用静态链接。"
"安装 Dataview 并在其设置中开启「Enable JavaScript Queries」后重跑 `gen-home` 即可获得动态卡片。"
)
queries = _callout("info", "🔎 检索报告", _tiles(config.queries_dir(vault), ".md"))
graphs = _callout("note", "🕸 图谱", _tiles(config.graphs_dir(vault), ".canvas"))
return f"## 🗂 工作区\n\n{note}\n\n{queries}\n\n{graphs}"
def managed_block(vault: str | Path, cards: bool) -> str:
"""The marker-delimited, script-owned 工作区 region (idempotent)."""
boundary.bind(vault)
return f"{AUTO_START}\n\n{_workspace_body(vault, cards)}\n\n{AUTO_END}"
def render_skeleton(vault: str | Path, cards: bool) -> str:
"""The full first-run page: frame + Bases embed + nav-table scaffold +
relationship placeholder + managed workspace region."""
boundary.bind(vault)
rows = _topic_rows(vault)
total = sum(count for _, count in rows)
blocks = [
"---\ncssclasses:\n - agent-wiki-home\n---",
"# Wiki Index",
f"> 文献阅读记录知识库 · {len(rows)} 个主题 · 来源合计 {total}(含跨主题重复)。{PLACEHOLDER}:概述可由 agent 补充。",
"## 🧭 动态视图(Bases)",
"> 可排序 / 可筛选的实时主题表(依赖 Bases 核心插件)。",
EMBED,
"## 📚 主题导航",
_nav_table(rows),
"## 🔗 主题关系图谱",
f"{PLACEHOLDER}:由 agent 依据主题间的机理 / 材料 / 应用关系生成叙述。",
managed_block(vault, cards),
]
return "\n\n".join(blocks) + "\n"
def _is_placeholder(text: str) -> bool:
return text.strip() in ("", "# Wiki Index")
def merge(existing: str | None, vault: str | Path, cards: bool) -> str:
"""Produce index.md content. Empty/placeholder -> full skeleton. Existing
managed markers -> refresh only that region (preserve agent prose). Existing
content without markers -> append the managed region (never clobber)."""
boundary.bind(vault)
block = managed_block(vault, cards)
if existing is None or _is_placeholder(existing):
return render_skeleton(vault, cards)
start = existing.find(AUTO_START)
if start != -1:
end = existing.find(AUTO_END, start + len(AUTO_START))
if end != -1:
return existing[:start] + block + existing[end + len(AUTO_END):]
return existing.rstrip("\n") + "\n\n" + block + "\n"
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |