') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat: add serial crash-safe mutation recovery by gwokhou · Pull Request #142 · VectifyAI/OpenKB · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions openkb/agent/compiler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
resolve_entity_types,
)
from openkb.lint import list_existing_wiki_targets, strip_ghost_wikilinks
from openkb.locks import atomic_write_text
from openkb.schema import INDEX_SEED, get_agents_md

logger = logging.getLogger(__name__)
Expand DownExpand Up@@ -779,7 +780,7 @@ def _write_summary(wiki_dir: Path, doc_name: str, summary: str,
fm_lines.append(f"doc_type: {doc_type}")
fm_lines.append(_yaml_kv_line("full_text", f"sources/{doc_name}.{ext}"))
fm_block = "---\n" + "\n".join(fm_lines) + "\n---\n\n"
(summaries_dir / f"{doc_name}.md").write_text(fm_block + summary, encoding="utf-8")
atomic_write_text(summaries_dir / f"{doc_name}.md", fm_block + summary)


_SAFE_NAME_RE = re.compile(r'[^\w\-]')
Expand DownExpand Up@@ -839,7 +840,7 @@ def _write_concept(wiki_dir: Path, name: str, content: str, source_file: str, is
if brief:
fm_lines.append(_yaml_kv_line("description", brief))
existing = frontmatter.block(fm_lines) + clean
path.write_text(existing, encoding="utf-8")
atomic_write_text(path, existing)
return
# Guarantee type + refresh description on update; remove legacy brief:.
ex_parts2 = frontmatter.split(existing)
Expand All@@ -851,7 +852,7 @@ def _write_concept(wiki_dir: Path, name: str, content: str, source_file: str, is
# Drop legacy brief: lines (migrated to description:).
fm_block = frontmatter.drop_line(fm_block, "brief")
existing = fm_block + body
path.write_text(existing, encoding="utf-8")
atomic_write_text(path, existing)
else:
clean_parts = frontmatter.split(content)
if clean_parts is not None:
Expand All@@ -863,7 +864,7 @@ def _write_concept(wiki_dir: Path, name: str, content: str, source_file: str, is
if brief:
fm_lines.append(_yaml_kv_line("description", brief))
fm_block = "---\n" + "\n".join(fm_lines) + "\n---\n\n"
path.write_text(fm_block + content, encoding="utf-8")
atomic_write_text(path, fm_block + content)


def _write_entity(
Expand DownExpand Up@@ -927,10 +928,10 @@ def _build_entity_frontmatter(sources: list[str]) -> str:
break
merged = [source_file] + [s for s in recovered if s != source_file]
existing = _build_entity_frontmatter(merged) + clean
path.write_text(existing, encoding="utf-8")
atomic_write_text(path, existing)
return

path.write_text(_build_entity_frontmatter([source_file]) + clean, encoding="utf-8")
atomic_write_text(path, _build_entity_frontmatter([source_file]) + clean)


_set_fm_line = frontmatter.set_line
Expand DownExpand Up@@ -1041,7 +1042,7 @@ def _add_related_link(
text = _prepend_source_to_frontmatter(text, source_file)

text += f"\n\nSee also: {link}"
path.write_text(text, encoding="utf-8")
atomic_write_text(path, text)
return True


Expand All@@ -1068,7 +1069,7 @@ def _backlink_summary_pages(
_ensure_h2_section(lines, section, quiet=True)
for slug in reversed(missing):
_insert_section_entry(lines, section, f"- [[{page_dir}/{slug}]]")
summary_path.write_text("\n".join(lines), encoding="utf-8")
atomic_write_text(summary_path, "\n".join(lines))


def _backlink_pages(
Expand All@@ -1089,7 +1090,7 @@ def _backlink_pages(
lines = text.split("\n")
_ensure_h2_section(lines, "## Related Documents", quiet=True)
_insert_section_entry(lines, "## Related Documents", f"- {link}")
path.write_text("\n".join(lines), encoding="utf-8")
atomic_write_text(path, "\n".join(lines))


def _backlink_summary(wiki_dir: Path, doc_name: str, concept_slugs: list[str]) -> None:
Expand DownExpand Up@@ -1195,7 +1196,7 @@ def _remove_doc_from_pages(
path.unlink()
deleted.append(path.stem)
elif new_text != text:
path.write_text(new_text, encoding="utf-8")
atomic_write_text(path, new_text)
modified.append(path.stem)

return {"modified": modified, "deleted": deleted}
Expand DownExpand Up@@ -1291,7 +1292,7 @@ def remove_doc_from_index(wiki_dir: Path, doc_name: str, concept_slugs_deleted:
while _remove_section_entry(lines, "## Entities", entity_link):
pass

index_path.write_text("\n".join(lines), encoding="utf-8")
atomic_write_text(index_path, "\n".join(lines))


def _update_index(
Expand All@@ -1315,7 +1316,7 @@ def _update_index(

index_path = wiki_dir / "index.md"
if not index_path.exists():
index_path.write_text(INDEX_SEED, encoding="utf-8")
atomic_write_text(index_path, INDEX_SEED)

lines = index_path.read_text(encoding="utf-8").split("\n")

Expand DownExpand Up@@ -1361,7 +1362,7 @@ def _update_index(
else:
_insert_section_entry(lines, "## Entities", entry)

index_path.write_text("\n".join(lines), encoding="utf-8")
atomic_write_text(index_path, "\n".join(lines))


# ---------------------------------------------------------------------------
Expand DownExpand Up@@ -2035,7 +2036,7 @@ async def compile_long_doc(
updated = fm_block + body
if updated != summary_content:
summary_content = updated
summary_path.write_text(summary_content, encoding="utf-8")
atomic_write_text(summary_path, summary_content)

# Base context A. cache_control marker on the doc message creates a
# cache breakpoint covering (system + doc) for every concept call.
Expand Down
Loading