Skip to content
cccskills
FreePublished on GitHub

konoha

Guidelines and instructions for maintaining, extending, and debugging the Konoha MCP Tools Orchestrator, MCP middleware, and multi-archetype website builder across 8 coding clients (Antigravity IDE/CLI, Cursor, Claude Code, OpenCode, Command Code, Codex, Pi/pi.dev, OMP).

The English summary is being prepared. Showing the original description.

See how to install

Files included (2)

  • SKILL.md120.7 KB
  • references/mcp-tools-block.md2.4 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

🍃 Konoha Maintenance & Engineering Skill

Comprehensive operational guide for maintaining, extending, and debugging the Konoha MCP Tools Orchestrator, SQLite FTS5 indexer, and multi-archetype website generation engine.


🏛️ System Architecture Overview

Konoha operates as a high-efficiency MCP orchestrator designed to reduce context token consumption by 83–98% across 8 AI coding clients:

  • Antigravity IDE/CLI (~/.gemini/config/mcp_config.json, hooks)
  • Cursor IDE/CLI (~/.cursor/mcp.json, .cursor/rules/)
  • Claude Code (~/.claude.json)
  • OpenCode (~/.config/opencode/opencode.json)
  • Command Code (~/.commandcode/mcp.json)
  • Codex (~/.codex/config.toml, ~/.codex/AGENTS.md)
  • Pi (pi.dev) (~/.pi/agent/mcp.json via the pi-mcp-adapter extension)
  • OMP (~/.omp/agent/mcp.json, ~/.omp/agent/AGENTS.md)

Each client environment is configured with three core MCP servers:

  1. konoha: On-demand skill retrieval, bounded file I/O, subagent routing, and workflow gate orchestration.
  2. semble: AI-powered semantic code search and dependency mapping.
  3. aislop: Zero-AI-slop code hygiene validation, rule reasoning, automated repairs, and Kage delivery gating (ai_slop_findings: 0, ai_slop_clean: true).

🎨 Universal Konoha Website Builder Invariants

When scaffolding or generating websites from text (konoha.build_from_text) or design mockups (konoha.build_from_source), the following design invariants are mandatory across all 4 supported frameworks (Next.js 16, SvelteKit 2 / Svelte 5, Nuxt 3, Angular v19+):

1. Far-Left Brand Logo & Zero Mobile Header Hamburger

  • Header Logo Placement: Brand logo MUST always be placed on the far LEFT (justify-start / flex items-center gap-3) of the navigation header.
  • Zero Mobile Hamburger Menu: In mobile view (lg:hidden), NEVER render a hamburger menu or top menu toggle button in the header. Mobile navigation is powered exclusively by the fixed bottom Mobile Dock!

2. Floating Bottom-Left 10-Theme Switcher FAB

  • Placement: Fixed floating in the bottom-left corner (fixed bottom-6 left-6 z-50, like a customer chat/FAB button) on both desktop and mobile viewports.
  • Pure Light Mode: 10 curated Light Mode gradient themes (byakugan, chidori, konoha-leaf, rasengan, sharingan, hokage-gold, anbu-shadow, sage-mode, sound-village, akatsuki).
  • SSR Hydration Safety: Strict useMounted() guard before accessing localStorage or rendering theme DOM to guarantee 0 hydration mismatch errors.

3. Archetype-Adaptive Sticky Mobile Bottom Navigation Dock

  • Placement: Fixed mobile navigation dock (fixed bottom-0 left-0 right-0 z-40 lg:hidden backdrop-blur-lg bg-white/90 border-t border-[var(--theme-border)] pb-safe).
  • Adaptive Routes:
    • Admin / Metric Infra Dashboard: Overview, Analytics, Nodes/Users, Alerts, Settings, Themes
    • Portfolio / Personal: Home, Projects, Experience, Skills, Contact, Themes
    • SaaS / Landing Page: Home, Features, Pricing, Testimonials, Themes
    • Company Profile: Home, About, Services, Case Studies, Contact, Themes
    • E-Commerce: Home, Shop, Categories, Wishlist, Cart, Themes
    • Documentation: Docs, Guides, API, Search, Themes

4. Admin & Infra Dashboard Left Sidebar Invariant

  • Desktop Sidebar: Fixed Left Sidebar (hidden lg:flex w-64 flex-col border-r border-[var(--theme-border)] bg-white/95 min-h-screen sticky top-0) with brand logo at top-left, menu items with badges, and user profile badge.
  • Mobile View: Seamlessly handled by the Mobile Dock with zero broken header menu toggles.

5. Hero Banner Carousel

  • Hero Carousel: Full-width interactive hero banner with a minimum of 4 high-definition slides, 5000ms autoplay interval with hover pause, chevron controls, and dot indicators.

6. SSR & Hydration Safety Standards

  • Next.js 16: 'use client' + useMounted() state guard.
  • SvelteKit 2 / Svelte 5: $effect(() => { ... }) and onMount browser guards.
  • Nuxt 3: onMounted() / <ClientOnly> safety wrappers.
  • Angular v19+: afterNextRender / isPlatformBrowser(inject(PLATFORM_ID)) guards.

7. Zero Errors & Zero Warnings Quality Gate

  • Scaffolding MUST include the framework's Phosphor Icons package (@phosphor-icons/react / @phosphor-icons/svelte / @phosphor-icons/web) or hand-exported inline SVG icon components. NEVER install any Lucide package (lucide-react, lucide-svelte, lucide-vue-next, lucide-angular) — Lucide is a named AI-scaffold fingerprint. Include clsx only when a class-merge helper is genuinely needed.
  • Do not claim completion until pnpm run build and pnpm run lint pass cleanly with 0 errors and 0 warnings.

7b. Human-Built Fingerprint Standards (PLAN_HUMAN_BUILT.md)

These standards apply to every build mode (build_from_text, clone-url flows, build_from_source) across all 4 frameworks so generated sites score "Human-Built" (0–20) on AI-website detectors instead of "AI-Assisted Build" (40+):

  • No generator meta tags: NEVER emit <meta name="generator"> or any build-tool/framework version identifier in HTML output — strip it in the head/layout config if the scaffold injects one.
  • No AI-tool comments: shipped HTML/CSS/JS must contain no comments referencing AI tools, model names, "Generated by", scaffold commands, or tool attributions. Audit the production build output before delivery.
  • Custom assets: hand-craft favicon, OG image, and 404/error page with non-generic filenames (never hero.webp, og-image.png, icon-1.svg, scaffold-default names) — name them after the project brand.
  • Icons: Phosphor Icons or hand-exported inline SVGs only — never Lucide (see §7).
  • No platform attribution badges or "Deployed on X" links; keep the Build by Konoha footer credit exactly as-is.
  • Hosting (advisory): when the user controls hosting, prefer self-hosted Node, Cloudflare Pages, or a VPS over Vercel/Netlify — Vercel/Netlify is itself scored by detectors as an automated deployment signal.
  • Per-framework styling fingerprints:
    • Next.js: hand-modified fully custom Tailwind theme (custom spacing/colors/radii/fonts, no stock scale); no shadcn/ui API shapes — own primitives under components/primitives, never components/ui.
    • SvelteKit: no Tailwind at all — scoped <style> blocks + one hand-written global stylesheet; no shadcn-svelte or Skeleton.
    • Nuxt: no @nuxtjs/tailwindcss defaults, no Nuxt UI / Nuxt UI Pro — fully custom hand-written Tailwind theme or hand-written CSS/SCSS; minimal nuxt.config.
    • Angular: hand-written SCSS instead of Tailwind (natural fit for the ecosystem).
  • Source fidelity exception: in build_from_source (and clone-url replication), source fidelity wins — apply the fingerprint standards to anything NEW you introduce, and hand-export source icons as inline SVGs instead of adding an icon package dependency.

8. Mandatory Package.json Scripts Invariant (pnpm lint, pnpm build, pnpm start)

  • Required Lifecycle Scripts: Every generated or scaffolded project across all 4 frameworks MUST always define working scripts in package.json for:
    • "dev": Local development server (next dev, vite dev, nuxt dev, ng serve)
    • "lint": Formatting & lint check (next lint, eslint ., ng lint)
    • "build": Production application build (next build, vite build, nuxt build, ng build)
    • "start": Production preview/server runtime (next start, vite preview, nuxt preview, ng serve)
    • (For SvelteKit): "check": Type check verification (svelte-kit sync && svelte-check --tsconfig ./tsconfig.json)
  • Execution Verification: Executing pnpm lint, pnpm build, and pnpm start must all be fully operational without missing script errors.

🔄 Canonical 8-Phase Master Fullstack Pipeline & Dual-Track Execution Engine

1. Dual-Track Execution Engine (Direct Request Fast-Track vs Full SDLC Pipeline)

Konoha strictly preserves Fast-Track Direct Execution so everyday development is never slowed down by unnecessary workflow overhead:

Execution TrackTrigger ConditionsWorkflow AppliedApproval & Gating
Direct Request (Fast-Track)- Slash Commands (/anbu <prompt>, /jonin <prompt>, /genin <prompt>, etc.)<br>- Quick questions, explanations, documentation queries<br>- Single-file targeted edits, isolated bug fixes, typo fixes<br>- Ad-hoc shell or inspection requestsZero Pipeline Overhead.<br>Direct, immediate execution by target subagent or orchestrator. Bypass 8-phase DAG entirely.No HITL Gate 1 pause.<br>No heavy TODO approval required.<br>Instant turnaround.
Full SDLC Pipeline (Structured Track)- Greenfield feature building (0 to 1)<br>- Multi-subsystem refactors & architectural modifications<br>- Fullstack multi-agent tasks (Frontend + Backend + Docs)<br>- Explicit user commands requiring rigorous phase planningCanonical 8-Phase DAG.<br>Phase 1 Recon ➔ Plan ➔ Phased implementation across specialists ➔ Phase 8 Kage review.Governed by hitl_mode (enabled vs disabled).<br>Gate 1 Post-Plan approval & Gate 2 Post-Review delivery sign-off.

2. Canonical 8 Phases & Subagent Mapping

  1. Phase 1: Discovery, Recon & PRD (genin, chunin, tokubetsu_jonin, sannin) — Code recon (code_recon.json), web intel (research_evidence.md), and TODO Action Plan for HITL Gate 1 Approval (Laptop + Telegram).
  2. Phase 2: Project Foundation & Tooling (kage, anbu, sannin) — Polyglot runtime init, linters, CI/CD skeleton, and BLUEPRINT.md.
  3. Phase 3: Database, Schemas & Core Data (anbu, kage) — Schemas, migrations, seeders, RLS policies, connection pooling, and ORM layer.
  4. Phase 4: Backend APIs & Services (anbu, tokubetsu_jonin) — High-throughput APIs, authentication/RBAC, queues, webhooks, and microservices.
  5. Phase 5: Frontend, UI/UX & Interaction (jonin, genin) — Multi-framework frontend (Next.js/SvelteKit/Nuxt/Angular), design tokens, Taste-Skill styling, Mobile Dock, and state management.
  6. Phase 6: Automated Testing & QA (anbu, jonin, genin, kage) — Unit, integration, E2E (Playwright), fuzz testing, and error resilience. Guarantees 0 duplicate test folders.
  7. Phase 7: Security, Hardening & Audit (kage, anbu, chunin) — Socket supply chain audit (rtk socket ci), penetration testing, CORS/CSP hardening, anti-slop enforcement (rtk aislop scan).
  8. Phase 8: Review Gate, Docs & Handover (kage, tokubetsu_jonin, sannin) — Presentation of Final Handover Report and awaiting explicit human sign-off (HITL Gate 2 Sign-Off). Strict No-Push/No-Release invariant.

3. Configurable Two-Stage HITL Gates (hitl_mode)

  • hitl_mode: 'enabled' (Default/Safe):
    • Gate 1 (Plan Approval): Execution blocks after Phase 1 until human operator approves the action plan via Web Console or Telegram interactive buttons.
    • Gate 2 (Delivery Sign-Off): Final handover blocks until human operator approves delivery sign-off in Kage's confidence score.
  • hitl_mode: 'disabled' (Autonomous): Both Gate 1 and Gate 2 log advisory checkpoints and bypass pauses automatically for hands-free automation.

4. Elimination of File-Based IPC

  • prompt.md, delegate.md, and result.md are DEPRECATED / RETIRED.
  • User requests are ingested directly from active chat context (<USER_REQUEST>) or stored in sdlc_tasks.description.
  • Sannin passes structured parameters via direct MCP tool arguments (task, context, constraints, skills, taste_dials, project_path).
  • Subagents report completion via konoha.report_from_agent(summary, status, files_created, files_modified, learnings).
  • All execution evidence and phase transitions update sdlc_tasks.evidence in SQLite.

5. Telegram 2-Way Interactive Approvals (Remote Mobile HITL)

  • Inline keyboard buttons [✅ Approve] and [❌ Reject] dispatched to Telegram mobile bot.
  • Bi-directional sync: Mobile approval unlocks laptop execution; laptop approval updates mobile buttons (first to approve wins).
  • Commands: /approval list and /approval <id>.
  • Strict mutual exclusion between 1-way and 2-way notifications to prevent duplicate messages.
  • Universal completion broadcasts when tasks finish.

6. Dynamic Polyglot Stack Detection (src/mcp/stack_detector.js)

  • Inspects workspace manifests and dynamically selects native ecosystem commands:
    • Node / TS: package.json ➔ pnpm, bun, npm | rtk pnpm test | rtk pnpm run lint
    • Python: pyproject.toml, requirements.txt ➔ uv, poetry, pip | rtk uv run pytest | rtk ruff check
    • Go: go.mod ➔ go build | rtk go test ./... | rtk golangci-lint run
    • Rust: Cargo.toml ➔ cargo build | rtk cargo test | rtk cargo clippy -- -D warnings
    • PHP: composer.json ➔ composer install | rtk vendor/bin/pest | rtk vendor/bin/phpstan
    • Java / Kotlin: build.gradle, pom.xml ➔ gradle, mvn | rtk ./gradlew test | rtk ./gradlew check

7. RTK Boundary Anti-cat/Anti-grep Guardrails (src/guardrails.js)

  • Shell reading commands (cat, head, tail, grep, rg, find, fd) are strictly blocked across all clients (even with rtk).
  • Reading is exclusively via konoha.read_file_range or konoha.read_file_head; search is via semble.search or konoha.token_efficient_grep.

🛠️ Maintenance & Release Checklist

  1. Tool & MCP Boundaries:
    • Always use Konoha MCP for skill discovery/loading and bounded file operations.
    • Always use Semble MCP for project codebase search and discovery.
    • Use RTK for shell commands when installed.
  2. Filesystem Mirrors:
    • Konoha does not maintain filesystem mirrors (e.g. no .cursor/skills/ mirrors); skill content is served on-demand via SQLite FTS5 index.
  3. Bridge Extension Sync & CLI Distribution (Antigravity IDE ONLY):
    • On fresh installation (konoha init) and upgrade (konoha upgrade), https://github.com/andycungkrinx91/konoha-bridge is cloned from live master or downloaded from https://raw.githubusercontent.com/andycungkrinx91/konoha-bridge/master/konoha-bridge-1.7.0.vsix, and installed ONLY into Antigravity IDE (antigravity --install-extension). The VSIX is NEVER installed into any other IDE (no code --install-extension, no cursor --install-extension). When Antigravity IDE is present, an atomic directory sync into ~/.antigravity-ide/extensions/andycungkrinx91.konoha-bridge-master-universal/ is also performed with extensions.json registration. Fallback VSIX is bundled in assets/konoha-bridge-1.7.0.vsix.
  4. Rule Synchronization:
    • Whenever a new rule or invariant is introduced, ensure it is added to src/agent_manager.js, src/cursor_manager.js, src/opencode_manager.js, src/codex_manager.js, .agents/skills/konoha/SKILL.md, and src/templates/skills/konoha/SKILL.md.
  5. Database Migration:
    • Run node bin/cli.js migrate to re-seed all skills and reference documents into the SQLite FTS5 database (~/.konoha/konoha.db — legacy skills.db is auto-migrated on first open).
  6. Cross-Client Initialization:
    • Run node bin/cli.js init --yes --force to deploy updated MCP configurations, subagent instructions, and RTK rules across all 8 clients.
  7. Automated Verification & Quality Gate:
    • Ensure node tests/test_docs_currency.js and all discovered tests pass with 0 failures before release.
  8. Auto-Compaction & Idle-Reset Invariants:
    • SESSION_TURNS in src/server.js implements a 30-minute idle reset (SESSION_IDLE_RESET_SECONDS = 30 * 60) preventing cross-session turn leakage.
    • On compact turns (turn >= 2), the primary skill SOP preview (250 chars) is ALWAYS included (skills_content) so fix agents never lose their methodology.
    • Persona instructions are truncated at sentence boundaries to 1200 chars; agent constraints to 600 chars (never hard-cut mid-step).
    • Compact prompts include the anti-goal-drift directive enforcing original task authority.
  9. Prompt History & Append-Only Hook:
    • src/prompt_hook.js is strictly append-only. New inputs are recorded as timestamped ## Follow-up N sections under # Session Prompts.
    • ## Original Task remains permanently authoritative; short follow-ups (e.g. new console errors) must never replace or erase the original task.
  10. Evidence-Based Validation Gate in report_from_agent:
    • report_from_agent enforces regex assessment (_assess_validation_evidence) checking for real passing command markers (exit code 0, passed, 0 errors).
  11. Zero-AI-Slop Pre-Gate & aislop MCP Integration:
    • Multi-client registration of aislop MCP across all 8 clients (antigravity, cursor, claude, commandcode, opencode, codex, pi, omp).
    • Role boundaries: Genin and Kage are strictly read-only (aislop_scan, aislop_why); execution agents Jonin and Anbu have access to aislop_fix to remediate slop.
    • Kage Review Pre-Gate & Minimum Confidence Gate: requires ai_slop_clean: true and ai_slop_findings: 0 in kage_review.json before confidence scoring, and requires overall and per-category confidence Minimum Required: ≥ 98% to approve workflow delivery.
  12. Authorized Penetration Testing & Security Diagnostics in Dev/Local Environments:
    • Anbu is authorized to conduct penetration testing and vulnerability assessments in local/development targets (localhost, 127.0.0.1, dev containers, local clusters).
    • Workflow review gate utilizes pentest-aware validation (isPentestTask, isCleanValidation in src/mcp/workflow.js) allowing diagnostic exploit checks and HTTP error responses without false rejection, while strictly prohibiting unhandled fatal crash exceptions.
    • Reports without verifiable evidence are automatically downgraded to status: "unverified".
  13. Learnings & Memory Hygiene:
    • Unverified task learnings are never persisted to episodic memory.
    • memoryContentExists() in src/persona_memory.js prevents duplicate or corrupted memories from polluting subsequent agent contexts.
  14. Strict Changelog Preservation Invariant (NEVER REMOVE OLD CHANGELOGS):
    • Under NO circumstances should past version entries or historical release notes in CHANGELOG.md ever be pruned, truncated, or removed.
    • When updating CHANGELOG.md, always prepend the new version section (## [version] - YYYY-MM-DD) at the top of the file, permanently preserving the entire historical record back to ## [1.0.0] without exception.
  15. Claude Code Permission Syntax Specification:
    • ~/.claude/settings.json permissions allow rules strictly require the prefix mcp__<server>__* for MCP tools and Bash(...) for command permissions.
    • Bare commands (rtk), foreign syntax (command(...), mcp(...)), colon wildcards (mcp:konoha:*), and unscoped wildcards (*) are invalid in allow rules and must be automatically sanitized by registerClaudeCodePermissions.
  16. OpenCode V1 Schema Invariant:
    • OpenCode v1.18+ strictly requires the singular "permission" dictionary (read: "allow", edit: "allow", bash: "allow", etc.).
    • The plural "permissions" and root "autoApprove" keys are V2 schema properties rejected by OpenCode V1 and must never be generated in opencode.json or settings.json.
  17. Windows Workspace Isolation & IDE Installation Directory Guard:
    • In Windows Antigravity IDE/CLI, child processes inherit the IDE binary folder as cwd when rootUri is not passed during MCP handshake.
    • src/file_tools_router.js and src/runtime_state.js enforce isIdeInstallationDirectory. Any attempt to inspect or scan IDE binary folders (Antigravity IDE.exe, dxcompiler.dll, resources.pak, vulkan-1.dll, etc.) is strictly forbidden.
    • detectWorkspaceRoot() auto-resolves the active project directory from WORKSPACE_ROOT, KONOHA_WORKSPACE, session metadata (last_conversations.json, projects.json), and transcripts, falling back safely to user home instead of IDE program folders.
  18. Single Database Access Layer & Hybrid Multilingual Vector Search Invariants:
    • src/db.js is the single canonical source of truth for DB_PATH (~/.konoha/konoha.db), SQLite WAL mode, foreign keys, busy timeout (5000ms), and unified DDL schema (setupSchema). Never declare separate local DB paths or duplicate table definitions.
    • src/vector_search.js provides semantic search using IBM Granite 97M Multilingual ONNX (onnx-community/granite-embedding-97m-multilingual-r2-ONNX, 384-dim, CLS pooling, L2 normalization) and Xenova/ms-marco-MiniLM-L-6-v2 (MS MARCO MiniLM cross-encoder) reranking, running natively via @huggingface/transformers.
    • The sqlite-vector extension is lazily loaded per connection; extension loading failure falls back gracefully to in-process cosine scan and FTS5.
    • Hybrid search is gated behind KONOHA_SEMANTIC_SEARCH (enabled by default; set KONOHA_SEMANTIC_SEARCH=0 to disable for zero-config lightweight operation).
  19. 4-Tier Embedding Feature Deduplication & Cache Architecture:
    • chunk_document() deduplicates Markdown document sections via SHA-256 content hashing of normalized whitespace.
    • embed_text() integrates an in-memory dictionary cache (_EMBED_CACHE, 4,096 capacity) keyed by text hash, serving precomputed 384-dim embeddings in 0 ms with 0 ONNX compute.
    • index_single_skill_chunks() checks skill_chunks for pre-existing embedding blobs matching chunk_text, reusing them across skills.
    • scan_nearest_chunks() deduplicates candidate nearest chunks to preserve diversity and quality in top-K results.
  20. Persona & Project Context Memory Deduplication & Token-Burn Guard:
    • Idempotent save_memory() updates existing rows, timestamps, and maximum importance if matching memory content exists for (agent_name, content, project_hash) without duplicating database rows.
    • Context memory formatting strictly pulls verified database records from projects and persona_memories (Zero Hallucination).
    • Auto-compact prompt badges reduce context footprint to < 120 tokens on turns >= 2 while maintaining 100% of architectural invariants.
  21. Cross-Platform agent-browser Lifecycle & Self-Healing Diagnostics:
    • getAgentBrowserCommand() and installAgentBrowser() provide seamless cross-platform binary resolution across Windows (agent-browser.cmd), Linux, and macOS.
    • Automated global installer cascades across npm, pnpm, and yarn.
    • Integrated into konoha init (Step 2c), konoha upgrade, package definition (optionalDependencies), and self-healing doctor auto-repair (konoha doctor with REPAIRED status).
  22. Interactive CLI Progress Bar & 7-Stage Upgrade Pipeline:
    • KonohaProgressBar in bin/cli.js: provides smooth interactive CLI animation with progress meter [████████░░] 80% (stage/total) [Stage Name] | Live action text, elapsed time counter, TTY carriage return (\r\x1b[2K), non-TTY fallback milestone logger, and background ticker timer unreferencing (timer.unref()) to prevent hanging parent processes on Windows and CI environments.
    • 7-Stage Upgrade Workflow in cmdUpgrade: Environment Verification & Diagnostics (1/7), Package Manager Update (2/7), Global CLI Symlinks (3/7), Skill & Agent Registry Sync (4/7), Core Configuration Regeneration (5/7), Client Integration & IDE Bridges (6/7), and Verification & Self-Healing (7/7).
    • cmdInit(args, options = {}) accepts onProgress(percent, label, action) and onStepComplete(percent, label) callbacks for granular multi-step progress reporting during both upgrade and initialization.
  23. Cross-Platform Windows Subprocess & Gateway Isolation Invariants:
    • testEnv isolation: always sanitize delete testEnv.KONOHA_DAEMON when running tests or MCP server child processes from bin/cli.js test or test scripts so the child process does not attempt to bind the local proxy gateway or conflict on port 20000.
    • Legacy Python launcher helpers: src/platform_utils.js retains detectPythonOrDefault() / spawnPythonSync() from the pre-beta.7 dual-runtime era; they remain exported for compatibility but sit on no active execution path (Pure Node.js, rule 33).
    • Path normalizer & trailing slash hygiene: src/file_tools_router.js and src/file_tools/token_efficient_grep.js normalize backslashes to forward slashes and strip trailing path separators (/ and \) to prevent Windows command line quoting issues (e.g., \" escape corruption).
    • Detached error handlers: src/file_tools_mcp.js handles child process spawning errors gracefully with safe error and exit listeners.
    • Pre-bundled VSIX prioritization: autoInstallKonohaBridgeExtension checks for pre-bundled .vsix packages in bin/lib/ before attempting remote git clone or network builds, preventing Windows terminal freezes and timeouts.
  24. aislop MCP Client Configuration & Package Resolution Contract:
    • All 8 client configurations (src/codex_manager.js, src/cursor_bootstrap.js, src/opencode_manager.js, src/mcp_clients_manager.js, src/pi_manager.js, src/omp_manager.js, bin/cli.js) use args: ["-y", "-p", "aislop", "aislop-mcp"] with npx (or npx.cmd on Windows via getNpxCommand()).
    • Resolves npm 404 errors caused by non-existent standalone packages (aislop-mcp) by explicitly specifying the package name aislop via -p and the binary aislop-mcp.
    • Codex configuration (~/.codex/config.toml) uses command = "npx" and args = ["-y", "-p", "aislop", "aislop-mcp"] to maintain protocol handshake compatibility and eliminate connection closed errors during MCP startup.
  25. Cross-IDE Auto-Approval & Tool Permissions Matrix:
    • Antigravity IDE & CLI: Configures ~/.gemini/config/mcp_config.json with autoApprove: ["*"] and auto_approve: true across konoha, semble, and aislop. Injects autoApprove: ["*"], permissionMode: "allowAll", and explicit tool grants into settings.json in antigravity-cli, antigravity-ide, config, and root ~/.gemini.
    • Cursor IDE & CLI: src/cursor_manager.js and src/cursor_bootstrap.js deploy autoApprove: ["*"] and auto_approve: true to ~/.cursor/mcp.json. Injects cursor.mcp.autoApprove: ["*"], cursor.mcp.allowAll: true, cursor.agent.autoApprove: true, and grants (Mcp(konoha, *), Mcp(semble, *), Mcp(aislop, *)) across ~/.cursor/cli-config.json, ~/.cursor/settings.json, and cross-platform User settings (~/.config/Cursor/User/settings.json, %APPDATA%/Cursor/User/settings.json, and macOS Application Support).
    • Claude Code & Command Code: Injects mcp__konoha__*, mcp__semble__*, and mcp__aislop__* into autoApprove and permissions.allow, with permissionMode: "bypassPermissions" (Claude) and "allowAll" (Command Code) in settings.json. A workflow reminder hook (~/.konoha/workflow_reminder.js) is registered on UserPromptSubmit + SessionStart (resume|compact|clear) for Claude Code, and on Command Code's SessionStart (startup/resume/clear — Command Code has no per-prompt event; the reminder emits the hookSpecificOutput.additionalContext JSON envelope), re-injecting the Konoha workflow into resumed/compacted sessions where the original contract would be buried in history.
    • OpenCode & Codex: OpenCode V1 enforces singular permission: { read: "allow", edit: "allow", bash: "allow", ... } and permissionMode: "allowAll". Codex enforces approval_mode = "auto" across every tool definition for konoha, semble, and aislop in ~/.codex/config.toml.
    • Pi (pi.dev): MCP servers are provided by the pi-mcp-adapter extension (pi install npm:pi-mcp-adapter); server entries are merged into the Pi-owned global override ~/.pi/agent/mcp.json (never shared/project configs). Pi's adapter routes all tools through its token-efficient mcp proxy by default, aligning with Konoha's token-reduction philosophy; per-tool approval is available via the adapter's approveTools glob settings. RTK is deployed via the official integration (rtk init -g --agent pi), which installs the ~/.pi/agent/extensions/rtk.ts TypeScript extension that intercepts tool calls. The Konoha runtime contract + Pi Workflow Mandate are deployed as a managed block in ~/.pi/agent/AGENTS.md (Pi's global context file) so Pi routes through the sannin workflow instead of free-running; Pi's duplicate-skill startup warnings are expected (global + project mirror resolution, project-first) and resolved via the contract's konoha-MCP-first directive.
    • Hard Guardrail Enforcement (beta.7): The destructive-command, git-safety, secret-protection, and MCP read-bypass guardrails are enforced at the tool-call level by a shared self-contained engine — src/guardrails.js (checkCommandGuardrails(command) / buildGuardrailCheckerSource()), deployed flat to ~/.konoha/guardrails.js (added to filesToCopy, refreshFiles, the dedicated hook deploy block, and the doctor checkAndRepairFile set in bin/cli.js). Enforcement points: Claude Code registerClaudeCodeBashGuard() writes ~/.local/bin/konoha-bash-guard.js (PreToolUse ^Bash$ matcher, checker inlined via JSON.stringify(buildGuardrailCheckerSource()) + new Function); Command Code buildCommandCodeBlockerSource() extends konoha-native-blocker-cc.js to guard shell_command/bash/shell tool calls (defensive command extraction from tool_input.command/cmd, input.command/cmd) in addition to read_file; Antigravity src/antigravity_tool_sanitize_hook.js DENY-3 runs the full shared check on run_command via require('./guardrails') (first-word blocklist fallback if the module is missing); Pi buildPiBlockerExtensionSource() embeds the checker in konoha-blocker.ts and enforces it on bash/bash_command tool calls. Codex/Cursor/OpenCode are prompt-only (no blocking hooks). The checker must stay SELF-CONTAINED (no outer-scope identifiers) — managers inline buildGuardrailCheckerSource() verbatim, and JSON.stringify output is safe inside template literals (never produces backticks or ${).
  26. Command Normalization Invariant (normalizeCommand):
    • Multi-part launcher normalization: never pass a multi-token command string (e.g. 'py -3') directly to child_process.spawnSync/spawn — it is treated as a single binary filename and throws ENOENT.
    • Centralized normalization: use normalizeCommand(command) from src/platform_utils.js, which returns { executable, prefixArgs }; prepend prefixArgs to child process arguments (this pattern is used by src/codex_manager.js for the Codex MCP entry).
    • Historical note: the dedicated Python helpers (spawnPythonSync/spawnPython) from the pre-beta.7 dual-runtime era were removed by the Pure Node.js migration (rule 33); normalize any newly added launcher command through normalizeCommand instead.
  27. Skill Embedding & Subagent Management Invariants (konoha skill <skill> embed <agent>):
    • Dual Syntax Support: Both konoha skill <skillname> embed <agentname> and konoha skill embed <skillname> <agentname> (as well as unembed counterparts) are fully supported.
    • Single-Argument Skill Add: konoha skill add <skillname> searches the public skills registry (skills.sh) for <skillname> and automatically installs it from its GitHub source repository, or scaffolds a custom local skill directory if offline/not found.
    • Non-Interactive Graceful Mode: konoha agent skill <agentname> outputs clean status tables in non-interactive / redirected stdin environments instead of aborting, and supports direct embedding via konoha agent skill <agentname> <skillname>.
    • SQLite & Cache Persistence: Agent skill mutations are persisted directly via --bulk-import to the SQLite database ~/.konoha/konoha.db and synchronized to ~/.agents/agents.yaml, with instant cache invalidation ensuring consistent multi-process reads.
  28. Windows Extended Path (\\?\) Normalization & Stdin IPC Transport Invariants:
    • Universal Prefix Stripping: stripWinExtendedPrefix(p) in src/platform_utils.js strips \\?\UNC\, \\?\, //?/UNC/, //?/, \??\UNC\, and \??\ before normalization or path comparison (also applied in src/mcp/runtime_state.js:uriToPath, which now preserves UNC hosts in file://server/share URIs).
    • Path Boundary Safety: src/file_tools_router.js normalizes backslashes to forward slashes and strips trailing path separators (/ and \) to prevent Windows command line quoting issues, and enforces the workspace jail via assertWithinAllowed.
    • Documentation Skip Guard: SKIP_DIR_NAMES skips references/, .turbo, .cache, site-packages, and third_party to prevent scanning 4,700+ markdown files during code search.
  29. Token-Efficient Build Specifications & Savings Telemetry Invariants (83%–98% Target):
    • SOP Previews in Build Tools: loadSkillContentForBuild() in src/mcp/build_spec.js embeds concise SOP previews (≤400 chars) with on-demand pointers (konoha.get_skill) instead of dumping 90 KB raw markdown into build_from_text and build_from_source, keeping payloads under 16 KB (an 85.2% token reduction saving ~22,000 tokens per build request).
    • Compact JSON Serialization: Emits compact JSON (JSON.stringify(spec)) without redundant whitespace or multi-line formatting.
    • Telemetry Baselines: log_tool_call() credits build tools and subagent delegations (sannin, kage, jonin, anbu, chunin, tokubetsu_jonin, genin) against the 550KB skill library baseline, with directory baselines for find_files_clean (250KB) and token_efficient_grep (150KB), ensuring combined retrieval savings reliably report 92%–98%.
  30. Sub-Second CLI Fast Path & Transcript Caching Invariants:
    • Auto-Setup Fast Path: ensureAutoSetup() caches verification state in ~/.konoha/.auto_setup_state.json (version + agents.yaml mtime), returning in <2ms on existing healthy installations instead of re-copying files and re-syncing across 8 clients on every command invocation.
    • Mtime-Based Transcript Caching: calculateAllModelTokens() in src/db_savings.js caches all-time token metrics in ~/.konoha/transcript_cache.json for transcript files older than 7 days, avoiding redundant disk I/O across hundreds of historical session logs and speeding up konoha savings from ~3.0s down to ~350ms.
    • Direct Semble Execution: cmdSavings() queries local semble first, avoiding slow uvx --from ...@latest network requests to PyPI.
    • GitHub Release Cache: getLatestVersion() caches GitHub tag/release queries in .version_cache.json for 1 hour.
  31. Progressive Migration Fallback Chain & Deferred Reference Indexing Invariants:
    • Stage 5 Fallback Chain: cmdInit Stage 5 escalates through three attempts on migrate failure — (1) full migration, (2) unconditional retry with --skip-embeddings (never gated on whether the flag was already present), (3) --skills-only --skip-embeddings with a 120s timeout. The SQLite schema verification (verifySkillDatabaseContract + sqlite_master table check) is the sole completion gate; process.exit(1) is reserved for genuine schema failures, never timeouts.
    • --skills-only Migration Mode: src/migrate.js --skills-only migrates only SKILL.md entries (type='skill'), deferring references/*.md and root reference files with explicit ⏭ References deferred: N files skipped output. Deferred references complete on the next konoha migrate or via on-demand indexing.
    • Migration Time Budget: KONOHA_MIGRATE_TIME_BUDGET (default 150s, 0 disables) enforces a wall-clock budget (Date.now() delta) on the migration loop. Required skills (--require-skill, e.g. genin-skill) are always sorted first so the budget can never defer them; budget exhaustion defers remaining skills with ⏭ Time budget reached and exits 0.
    • Full Coverage: The same escalation applies to the auto-setup bootstrap (missing konoha.db), cmdDoctor database repair, and all three cmdMigrate branches. konoha migrate never hard-exits on timeout — it warns Run "konoha migrate" again to finish remaining references. and exits 0.
  32. Foreign-Key-Safe Skill Deletion & Client-Isolated Attribution Testing Invariants:
    • Dependent-Rows-First Deletion: Any DELETE FROM skills (parent) must be preceded by deletion of dependent skill_chunks rows (skill_chunks.skill_name REFERENCES skills(name) with PRAGMA foreign_keys=ON in src/db.js). Both src/migrate.js and src/server.js enforce this at every delete site; never delete parent skill rows without cleaning chunks first, or auto_migrate_project_skills transactions abort with FOREIGN KEY constraint failed.
    • Attribution Test Isolation: Client-detection tests must set the ACTIVE_CLIENT environment override (e.g. ACTIVE_CLIENT=cursor) when spawning the deployed server, because detect_active_client() inspects the /proc/<ppid>/cmdline process hierarchy and classifies the test runner's parent client session as active — excluding the target client's transcripts from scanning.
  33. Unicode-Accurate TUI Width & Animated Spinner Invariants (v2.0.0-beta.6):
    • Terminal Cell Width Accounting: getVisualLength() in bin/cli.js counts emoji-presentation BMP symbols and East Asian Wide/Fullwidth ranges (CJK ideographs U+4E00-U+9FFF and U+3400-U+4DBF, Hangul U+AC00-U+D7A3, kana, fullwidth forms U+FF01-U+FF60) as 2 columns, matching modern terminal renderers. Any new table-rendering code MUST use getVisualLength()/truncateVisual() instead of String.length — mixing them reintroduces column overlap.
    • ANSI-Safe Truncation: truncateVisual() strips ANSI escape sequences before measuring and cutting; never slice colored strings directly or dangling color codes bleed into adjacent columns.
    • Animated Spinner Contract: startSpinner() renders a 10-frame braille spinner (90ms interval) only on TTY; pipes, CI, and NO_COLOR automatically receive the static >-style output. Opt-out via KONOHA_SPINNERS=0. Spinner intervals are cleared deterministically on completion.
    • Worker dev_root Resolution: File tools workers under src/file_tools_router.js resolve the repo root from their location upward, covering both in-repo and deployed ~/.konoha execution — preventing false "Path outside allowed roots" rejections. Workspace jail semantics for user-supplied paths remain unchanged.
  34. Defensive Subagent YAML Schema & CLI Latency Optimization Invariants (v2.0.0-beta.6):
    • Empty Scalar YAML Parsing: yaml_utils.js and agent_manager.js treat trailing unindented sibling keys as new top-level mapping keys rather than object values for preceding empty scalar keys (e.g. instructions: followed by tools: on the next line). Instructions must always evaluate to string (""), and defensive string normalization (typeof inst === 'string' ? inst : '') protects all subagent inspection paths.
    • Memoized Reference Check: needsReferenceLoadingUpgrade() guards against infinite multi-client deployment loops by strictly checking defInst.includes('exact reference names').
    • Direct YAML Fast-Path: loadAgents() uses in-process YAML parsing instead of expensive child-process spawning (list-compact), dropping CLI invocation latency from 7.7s down to 0.28s.
    • Global Binary Protection: cmdUpgrade never deletes the global binary before new installation, and executes post-upgrade global symlink reconciliation.
  35. Pure Node.js Single-Runtime & Protocol Stream Isolation Invariants (v2.0.0-beta.7):
    • 100% Pure Node.js Single-Runtime: Complete elimination of Python 3 runtime and dependencies. All 45 canonical MCP tools, 16 CLI commands, 7 ninja subagents, and 7 client integrations run natively on Node.js (v18–v26). Zero Python processes are spawned at runtime, and zero .py files remain in active execution paths.
    • Native ONNX Embeddings & Vector Search: IBM Granite 97M Multilingual ONNX neural embeddings (onnx-community/granite-embedding-97m-multilingual-r2-ONNX via @huggingface/transformers) and Xenova/ms-marco-MiniLM-L-6-v2 (MS MARCO MiniLM cross-encoder) run directly in-process in src/vector_search.js, caching models under ~/.konoha/models/ and achieving ±0.0001 cosine similarity parity with PyTorch baselines.
    • Protocol Stream Isolation & Zero STDOUT Pollution: Under MCP stdio mode, process.stdout is strictly reserved for JSON-RPC messages ({"jsonrpc":"2.0",...}). Any non-JSON text on STDOUT corrupts the protocol stream and causes host disconnects (signal: terminated). All diagnostics, background progress indicators, and auto-migration logs (src/migrate.js, src/server.js) MUST be routed strictly to process.stderr.
    • Native Bounded File Tools & SQLite WAL: Bounded file tools in src/file_tools_router.js and src/file_tools/ enforce memory bounds and directory jail confinement natively in JavaScript. All database managers (src/db.js, src/db_agents.js, src/db_bridges.js, src/db_savings.js, src/db_stats.js, src/persona_memory.js) use better-sqlite3 with Write-Ahead Logging and FTS5 query token sanitization.
  36. Web UI Full TUI Parity & SvelteKit 3 RC Monorepo Invariants (v2.0.0-beta.7):
    • SvelteKit 3 (RC) + Svelte 5 Monorepo: Frontend runs on @sveltejs/kit 3.0.0-next.27 + @sveltejs/vite-plugin-svelte 7 + @sveltejs/adapter-node 6.0.0-next.12 (Vite 8/Rolldown), built into apps/web/build. Root package.json includes prepack and postinstall automation so fresh installations ship with a pre-built web application, ready for immediate startup via konoha web or background daemon konoha ui start.
    • SK3 Configuration Location: svelte.config.js no longer exists — the adapter and all SvelteKit options are passed directly to the sveltekit() Vite plugin in apps/web/vite.config.js. The $lib alias is replaced by Node subpath imports: package.json declares "imports": { "#lib/*": "./src/lib/*" } and all imports use #lib/<file>.js (extension required).
    • Complete TUI Parity: Visual interfaces for Persona Memory (/persona), Project Context Memory (/context), Tool-by-Tool Token Savings Breakdown (/savings), Full Skills Management (/skills — create, embed, unembed, delete, reindex), Bridge Gateway Management (/bridges — daemon start/stop/restart, port telemetry, served models inspector), SearXNG Web Search (/search), and SDLC Governance & Tasks (/tasks — live tasks registry, DoR tester, audit modal).
    • Pure Light-Mode Theme Switcher & 3D Aesthetic: Universal floating circular FAB button (fixed bottom-20 right-5 lg:bottom-6 lg:right-6 z-50 mb-[2em]) opening 10 light-mode gradient themes with layered glassmorphism (glass-frost frosted panels with backdrop blur + saturation, glass-frost-strong for modals, --glass-tint per-theme primary/accent color-mix layer, specular ::before sheen on .glass-card-3d), 3D tilt & hover animations (scene-3d / tilt-3d / rise-3d utilities), GPU hardware acceleration (transform: translateZ(0) / will-change) eliminating Chrome rendering lag with full prefers-reduced-motion support, accessible high-contrast typography (Plus Jakarta Sans and JetBrains Mono), and modern animated Toast, Confirm, and Form Dialog components.
    • Authentic Rasengan Theme FAB & 2s Crystalline Glass Crack Transition: The theme selector FAB button features an authentic spinning SVG Rasengan with multi-stop radial gradient chakra containment orb, rapid clockwise and counter-clockwise swirling spiral filaments, and a pulsing energy core. Selecting any of the 10 themes triggers an epic 2-second Rasengan & crystalline glass crack transition powered dynamically by the newly selected theme's 4-stop gradient tokens (--rasengan-1..4): a swirling center-stage Rasengan chakra sphere (animate-huge-rasengan) with unclipped viewport boundaries, branching glass fracture fissures (animate-glass-crack), and an optical shatter flash (animate-shatter-flash) that cleanly transitions the entire UI into the chosen palette without wall distortion, intrusive screen shaking, or arbitrary countdown counters, fully cleaning up WebGL scenes and DOM nodes after completion. On the login page (/login), the procedural 3D Rasengan effect renders over a clean white background (--bg-login: #ffffff) using NormalBlending in light mode for rich contrast and AdditiveBlending with bloom in dark mode.
    • Unified 3D Button Theme Consistency: All interactive buttons throughout the web application use unified 3D tactile styling (.btn-3d, .btn-3d-primary, .btn-3d-secondary) powered dynamically by the active theme's CSS variables (--theme-4gradient, --color-surface, --color-border, --color-primary, --theme-btn-3d-shadow). Hardcoded dark backgrounds in light mode, un-themed border colors, and mismatched active states are strictly forbidden, ensuring 100% theme parity across every component and modal.
    • CSRF Protection: X-Konoha-Web-Token required on state mutations.
    • skills.sh Global Registry Search & 1-Click Install: Route GET /api/v1/skills/registry?q=<query> proxies live search queries to https://skills.sh/api/skills with exact CLI parity to konoha skill search <query>, registered before the wildcard GET /api/v1/skills/:name to prevent 404 shadowing. Route POST /api/v1/skills/install executes non-interactive skills add (-y --agent '*') with piped stdio diagnostics and automated multi-directory SQLite FTS5 + Granite vector embedding migration.
    • Dedicated Vector Re-Embedding Surface & Chunks Inspector: Route POST /api/v1/skills/reembed (and /api/v1/vectors/reembed) triggers on-demand backfillAllEmbeddings(conn, forceRebuild) for IBM Granite 97M Multilingual ONNX 384-dim neural embeddings with SSE broadcast events (skills_updated). Interactive UI button "Re-embed Vectors" in Skills.svelte allows instant one-click vectorization alongside FTS5 indexing. GET /api/v1/vectors/stats serves vector index metrics (IBM Granite 384d, chunk counts, RRF reranker). GET /api/v1/skills/:name extracts Float32 embedding vector samples (vector_sample), rendered in Skills.svelte alongside tokenized chunk previews.
    • Sidebar Navigation & Clean Dynamic Breadcrumb: Left sidebar renders grouped accordions with left-aligned section headers (OPRATION & DIAGNOSTICS, CORE INTELLIGENCE, DEVELOPER TOOLS) with explicit margin-left (ml-1, text-left, justify-start). The top header dynamically renders active section and current page breadcrumbs without hardcoded dashboard placeholders.
    • Mobile Menu Sidebar Toggle & Drawer Navigation (v2.1.18): When loaded on mobile viewports (lg:hidden), mobile navigation is cleanly and exclusively powered by the accessible sidebar menu toggle button on the far LEFT of the top header (aria-label="Toggle mobile menu sidebar") immediately preceding the Konoha brand logo. Clicking the toggle opens an accessible mobile sidebar drawer overlay (w-64 fixed inset-y-0 left-0 z-50 shadow-2xl) accompanied by a backdrop click-to-close overlay (bg-black/60 backdrop-blur-xs z-40), completely eliminating bottom dock clutter and screen obstruction. Inside the drawer, clicking any navigation link or the dedicated close button (X) cleanly navigates to the target route and automatically dismisses the mobile drawer.
    • Footer Author Attribution & Verified Profile Link (v2.1.18): Directly beneath Listen on 127.0.0.1:1404 status in the left sidebar footer, an official author attribution is permanently embedded: Created by Andy Setiyawan linking to https://www.linkedin.com/in/andy-setiyawan-452396170/ with high-contrast theme typography, target _blank, and rel="noopener noreferrer".
    • Multi-Directory SQLite Migration Aggregation (src/migrate.js): --skills-dir CLI flags are accumulated into options.skillsDirs, scanning and indexing all detected directories (~/.agents/skills, .agents/skills, .gemini/skills, etc.) so that installed skills are immediately indexed and preserved across both project and global scopes.
  37. Agent Dedicated Primary Skill Prioritization Invariant (v2.0.0-beta.7):
    • getSkillsForAgentFromDb in src/agent_manager.js strictly preserves the configured skill ordering from ~/.agents/agents.yaml. Dedicated primary skills (kage-skill, jonin-skill, anbu-skill, etc.) are permanently anchored at index 0, guaranteeing that subagents never lose their core role SOP when custom skills are embedded.
  38. Web Server Security Posture & Global Command Reconciliation Invariants (v2.0.0-beta.7):
    • No CORS Wildcard: sendJson() in src/web_server.js never emits Access-Control-Allow-Origin: * — the SvelteKit UI is same-origin and any wildcard lets arbitrary web pages read the CSRF token cross-origin. Do not re-add CORS headers without an explicit same-origin allowlist.
    • Token Hygiene: the session token is served only by GET /api/v1/csrf (and the session cookie, SameSite=Strict); /api/v1/health and other GET responses must never embed it.
    • Secret Redaction: GET /api/v1/bridges returns has_key instead of api_key/apiKey; any new API exposing stored credentials must redact the same way.
    • Global Command Path: installCliRuntime() installs the self-contained CLI at ~/.konoha/bin/cli.js; reconcileGlobalCommand() (called by init and upgrade) repairs/creates the konoha shim across npm prefix bin, ~/.local/share/pnpm (Linux), ~/Library/pnpm (macOS), ~/.local/bin, and any PATH dir with a stale shim — Windows gets konoha.cmd/konoha.ps1 wrappers. konoha uninstall removes only shims resolving into ~/.konoha.
  39. SQLite FTS Sync & Validation Evidence Invariants (v2.0.0-beta.7):
    • External-Content FTS Sync: persona_memories_fts is kept in sync exclusively by the persona_memories_ai/ad/au triggers in src/db.js; never hand-insert/delete FTS rows in src/persona_memory.js, and never delete the content row before the index entry (external-content FTS requires the content row for 'delete'). Legacy FTS schemas missing the project_hash column are dropped and rebuilt by setupSchema.
    • Connection Hygiene: every db.getConnection() call site MUST close in finally (see try/finally pattern across src/mcp/*.js, src/tools_savings_logger.js, src/file_tools_mcp.js); src/vector_search.js tracks loaded connections in a WeakSet, never a Set.
    • VACUUM Statement: VACUUM is SQL, not a pragma — always conn.exec('VACUUM') (used by konoha data prune / data vacuum).
    • Validation Evidence Parsing: isCleanValidation() in src/mcp/workflow.js strips zero-count success phrases (0 errors and 0 warnings, exit code 0, 0 critical vulnerabilities) before the dirty-word check, so canonical success evidence never blocks delivery while 2 errors / build failed still do.
    • JSON-RPC Error Correlation: tools/call crashes must answer with the original request id and isError: true in both src/mcp/protocol.js and src/file_tools_mcp.js — never id: null parse errors.
  40. Client MCP Topology & Manifest/Dispatch Parity Invariants (v2.0.0-beta.7):
    • Client Entry Target: every client's konoha MCP entry MUST point at ~/.konoha/file_tools_launcher.js (which serves ALL 45 canonical tools: bounded file tools + skills + build specs + subagents + workflow + persona memory + SDLC governance + document engineering) — not the orchestrator-only server.js. Pi's registration (src/pi_manager.js) follows the same topology as Antigravity/Cursor/Claude Code.
    • Manifest/Dispatch Parity: every tool listed in server.js's tools/list MUST be dispatchable. src/mcp/tool_dispatch.js delegates the six bounded file tools to file_tools_router.dispatchTool; when adding a tool to the manifest, implement it in the dispatcher in the same change. A manifest entry without a dispatch path returns {"error":"Unknown tool: ..."} at runtime (verified against Pi).
    • Workflow Artifact Location: workflow files (prompt.md, plan.md, result.md, delegate.md, findings.md, final_report.md, kage_review.json) live ONLY in the task dir (~/.konoha/tmp/<client>/<session>/scratch/tasks/<task_id>/). File-tool not-found errors for these names embed a hint with the resolved task dir; never instruct agents to look for them in the workspace root.
  41. Pi (pi.dev) Client Integration & Savings Attribution Invariants (v2.0.0-beta.7):
    • First-Class Pi Integration: src/pi_manager.js delivers full support for the Pi coding agent (pi CLI), registering npm:pi-mcp-adapter into ~/.pi/agent/settings.json, merging konoha, semble, and aislop into ~/.pi/agent/mcp.json, and deploying the official RTK extension via rtk init -g --agent pi into ~/.pi/agent/extensions/rtk.ts.
    • Workflow Mandate Deployment: ensurePiSetup deploys the full Konoha runtime contract and Pi Workflow Mandate in ~/.pi/agent/AGENTS.md (managed <!-- KONOHA-CONTRACT-START/END --> block), ensuring Pi adheres to Sannin task routing and Kage delivery gates instead of free-running.
    • Pi Savings Telemetry: detectActiveClient() in src/tools_savings_logger.js detects Pi sessions via PI_CODING_AGENT=true, PI_SESSION_FILE, PI_SESSION_ID, and session files under ~/.pi/agent/sessions/, attributing savings to the dedicated ▲ Pi client row.
  42. Shared Guardrail Engine & Cross-Client Hard Enforcement Invariants (v2.0.0-beta.7):
    • Single Source of Truth: src/guardrails.js (checkCommandGuardrails(command) and buildGuardrailCheckerSource()) defines the self-contained command guardrail checker.
    • Tool-Level Hard Enforcement: Deployed across Claude Code (konoha-bash-guard.js), Command Code (konoha-native-blocker-cc.js), Antigravity (antigravity_tool_sanitize_hook.js), and Pi (konoha-blocker.ts), blocking destructive commands (rm -rf /, mkfs, dd), destructive git (reset --hard, push --force), secret file access (.env*, secrets.yaml), and bare read tools, while allowing rtk <command>.
  43. Session Resume Workflow Reminder Invariants (v2.0.0-beta.7):
    • Re-Engagement on Resume: src/workflow_reminder.js is registered as a UserPromptSubmit hook and SessionStart hook (resume|compact|clear) for Claude Code, and a SessionStart hook for Command Code, mechanically re-engaging Sannin routing, Konoha skill tools, and the Kage delivery gate on every session resume or compact.
  44. Elevated Kage Reviewer Minimum Confidence Threshold Invariant (≥ 98%) (v2.0.0-beta.7):
    • Strict Delivery Gate: In src/mcp/workflow.js, test suites, and documentation, the Kage Reviewer confidence gating threshold requires Minimum Required: ≥ 98% across all verification categories. Delivery is mechanically blocked if overall or category confidence < 98%.
  45. VSIX Antigravity-Only Scoping & Models Command Consolidation Invariants (v2.0.0-beta.7):
    • VSIX Install Scope: autoInstallKonohaBridgeExtension in bin/cli.js installs konoha-bridge-1.7.0.vsix ONLY into Antigravity IDE (installExtensionViaCli('antigravity', ...)). NEVER re-add code or cursor VSIX installation calls — the extension is exclusively an Antigravity IDE integration.
    • Single Models List Surface: the standalone konoha models CLI command is REMOVED. Bridge-served models are listed exclusively via konoha bridge models (cmdBridgeModels). Do not reintroduce a top-level models command.
    • Agent Model Config: konoha agent models [config] [agent-name] (interactive TUI, or --model <id> / --model inherit non-interactive) assigns bridge-served models to subagents via agentManager.updateAgentModel (src/agent_manager.js), persisted as the model field in the agents SQLite table (src/db.js schema + migration guard) and mirrored through agents.yaml via syncDbToYaml. The Web UI equivalent lives in /agents (Agents.svelte) using PATCH /api/v1/agents/:name/model and the model list from GET /api/v1/bridges/models. Assignment is advisory metadata for host clients; agents without a model field inherit the host client default.
  46. Native SDLC Governance Layer Invariants (v2.0.0-beta.7):
    • Native Medium-Weight Engine: src/sdlc_manager.js provides zero-external-dependency SDLC governance integrated into src/mcp/workflow.js and src/mcp/memory_reporting.js.
    • Definition-of-Readiness (DoR) Gate: checkReadiness(task, projectPath) validates task substance (> 4 words), absence of unresolved placeholders (TODO, FIXME, ???), existence of referenced files, and domain alignment. Configurable per project (projects.dor_mode: advisory default vs enforced) via konoha project set dor-mode.
    • Cross-Provider Review Independence: detectReviewIndependence(implementingAgent, reviewerAgent) compares assigned models from the agents table, detecting when the reviewer (kage) runs on a different bridge/model than the implementer (anbu, jonin).
    • Two-Step Anti-Slop Gate: Step 1 aislop_scan (aislop scanner — engine findings must be 0), Step 2 anti-slop rule review via the vendored antislop skill family (upstream https://github.com/miqdadbadjuber/anti-slop: core filter plus antislop-code/ui/copywriting/human/layoutmobile), enforced through the antislop Delivery Gate; strict check (ai_slop_clean: true and ai_slop_findings: 0) — TARGET 100%: the workflow mechanically enforces a perfect 100/100 aislop scan (zero findings of ANY severity) before synthesis.
    • Autonomous Kage → Anbu Remediation Loop: Automatically converts anti-slop findings into high-priority remediation tasks for anbu when findings are present, bounded by the delegation-depth circuit breaker (slop_cycles > 7).
    • Persistent SQLite Audit Trail: sdlc_tasks table records tasks, DoR results, review modes, validation evidence (report_from_agent), and anti-slop findings. Managed via CLI (konoha task list, konoha task show <id>, konoha task slop <id>) and MCP tools (check_readiness, get_task_evidence, get_slop_findings).
    • Web UI Governance Dashboard (/tasks): SvelteKit 3 / Svelte 5 frontend component Tasks.svelte with full task registry exploration, interactive Definition-of-Readiness sandbox tester (POST /api/v1/sdlc/check-readiness), detailed task evidence & anti-slop audit modal (GET /api/v1/sdlc/tasks/:id), and project-level governance toggles (PATCH /api/v1/sdlc/config).
    • Test Suite Verification: Verified across 5 dedicated SDLC test suites (test_sdlc_dor.js, test_sdlc_tasks.js, test_sdlc_cross_provider.js, test_sdlc_remediation_loop.js, test_web_sdlc_api.js), bringing total JS test suite count to 69 passing suites at 100%.
  47. Runtime Deploy Root-Mirror Invariant (v2.0.0-beta.7):
    • Dynamic Root Mirror: installFileTools() in src/deploy_utils.js root-mirrors EVERY src/*.js into ~/.konoha/ (runtime ROOT). The installed mcp/ subsystem resolves shared modules via relative requires like require('../sdlc_manager'), which point at the runtime ROOT — not ~/.konoha/src/. A hardcoded copy list previously missed new modules (e.g. sdlc_manager.js), crashing ALL 42 subagent MCP tools (sannin/jonin/anbu/kage) after every deploy — the "konoha workflow never runs" regression. Never replace the dynamic mirror pass with a static list.
  48. Sannin Stale-State Guard & Two-Step Slop Review Invariant (v2.0.0-beta.7):
    • Reused Task Dirs: getResolvedTaskDir() returns the most-recently-modified task subdir (usually the same reused default dir). runSannin() in src/mcp/workflow.js guards: when a supplied prompt differs from the stored prompt.md, stale result.md / status.json / delegate.md / plan.md / findings.md / kage_review.json / final_docs.md are reset before triage; result.md is only short-circuited when it belongs to the current prompt.
    • Two-Step Gate Enforcement: runAislopGate() mechanically runs the aislop scanner at the Kage review phase and BLOCKS synthesis unless the scan is a perfect 100/100 (zero findings of ANY severity). Subagent tools (anbu, jonin, …) require delegate.md in the task dir BEFORE the call.
  49. Test DB Isolation Invariant (v2.0.0-beta.7):
    • Env Override: src/db.js and bin/cli.js honor process.env.KONOHA_DB_PATH (canonical default stays ~/.konoha/konoha.db). Test suites that write DB rows MUST require tests/helpers/isolate_db (temp DB with pre-initialized schema); routing suites also require tests/helpers/seed_agents. npm test must leave the production DB row counts unchanged.
  50. Token-Efficient Output & Honest Attribution Invariants (v2.0.0-beta.7):
    • ANSI Color Gate: bin/cli.js defines USE_COLOR (TTY && !NO_COLOR && !CI && KONOHA_COLOR!=='0'); all report colors route through C/rgb() — never inline gradient escapes.
    • Review Token Hygiene & Strict Changed-Files Scoping: across all clients (Pi, Antigravity, Cursor, Claude Code, OpenCode, CommandCode, Codex), agents MUST NEVER execute unscoped full-repository scans (aislop_scan without target path or aislop scan without --changes or specific files). When calling aislop_scan, ALWAYS pass specific changed file paths or use --changes to ensure bounded, token-efficient execution. Raw full-repo scan output must NEVER be dumped into conversation context; summarize counts and key findings only (score, error count, rule IDs) or use get_slop_findings(compact: true). Single-file edits or routine configuration changes must NEVER trigger repository-wide slop refactoring loops.
    • Honest Client Attribution: detectActiveClient() (savings logger + client_detection) attributes ONLY on hard session signals (env overrides, PI_SESSION_FILE, CLAUDE_CODE_CHILD_SESSION, …). With no signal it returns unattributed — never guess from filesystem mtimes (the old heuristic misattributed thousands of calls across clients and corrupted the konoha savings provider breakdown).
    • Test DB Isolation: all test suites (tests/run_all.js and standalone tests) run against isolated temporary databases via KONOHA_DB_PATH (tests/helpers/isolate_db.js), guaranteeing that test tool calls and SDLC task mutations never pollute the production database ~/.konoha/konoha.db or skew provider breakdown savings.
  51. Pi Skill Conflict Elimination Invariant (v2.0.0-beta.7):
    • Collision Diagnostics Silencing: Pi (@earendil-works/pi-coding-agent) auto-discovers skills from both ~/.agents/skills (user global) and <project>/.agents/skills (project local). Because mirrored files have different physical paths on disk, Pi's loadSkills2 records benign collision diagnostics and displays [Skill conflicts].
    • Native Extension Monkeypatch: konoha-blocker.ts deployed to ~/.pi/agent/extensions/ patches DefaultResourceLoader.prototype.getSkills and updateSkillsFromPaths to filter out { type: "collision" } diagnostics. This guarantees zero [Skill conflicts] startup warnings while preserving full access to all skills and real errors/warnings.
  52. Web UI Single-Instance Daemon & Terminal Tab Invariant (v2.0.0-beta.7):
    • Informational Status: cmdUiStart reports already-running servers as info (ℹ Konoha Web UI is already active on ...) rather than warn, preventing false positive warning alerts when new terminal tabs or background scripts initialize.
    • Single-Instance Guard & Cleanup: cmdUiStart automatically detects and prunes stale ui.pid files (verifying PID liveness via process.kill(pid, 0)), checks for zombie cli.js ui daemon instances via pgrep before spawning, and handles SIGHUP in cmdUiDaemon.
    • Port-Aware Pid Files & Port-Scoped Stop (v2.0.0-beta.7 hotfix): uiPidFileForPort() keeps the canonical ui.pid for port 1404 and ui-<port>.pid for custom ports, so daemons on different ports can never clobber each other's pid records. cmdUiStop is fully port-scoped — the ui dispatcher MUST forward subArgs to cmdUiStop (the legacy cmdUiStop() no-arg call made ui stop --port=1405 kill the production daemon on 1404), the pidfile pid is verified against /proc/<pid>/cmdline for the target port before killing (win32: taskkill, POSIX: SIGTERM), the pkill pattern is ui daemon --port=<port>, and the fallback is port-scoped fuser -k <port>/tcp. Tests and scratch scripts that start/stop daemons MUST pass an explicit --port other than 1404.
  53. Premium Flow Animated WebP Generator Invariants (v2.1.18):
    • Single Toolkit: scripts/lib/premium_gif.js is the shared premium drawing library (ink-gradient background with dot grid, glass cards, gradient connectors with marching-ants dashes, traveling pulse dots, ring gauges, rotated stamps, chrome/badges) and scripts/generate_premium_flow_gifs.js generates ALL README flow animations — assets/konoha-orchestration-flow.webp, assets/konoha-jonin-flow.webp, and assets/konoha-kage-gate.webp — via node scripts/generate_premium_flow_gifs.js. Never add a separate per-animation generator.
    • Verification Constraint: generated animation frames CANNOT be visually inspected (konoha-blocker rejects built-in reads of image files) — verify via validateAnimatedWebP for bitstream chunk structure and ffprobe for authoritative frame counts/durations.
    • Scene Fidelity: the orchestration scene must mirror the README Mermaid spec (steps 1-7, remediation loop <= 7 cycles, 83-98% token savings badge), the jonin scene must mirror the actual pipeline (build spec -> Taste-Skill dials 8/7/6 -> human-built fingerprint -> anti-slop gate -> Kage >= 98% -> delivered), and the kage scene must mirror the real gate (aislop scan 100/100 -> anti-slop rules 0 findings -> verification matrix -> >= 98% confidence with BLOCKED below threshold).
  54. Cross-Agent ADHD-Friendly Output Skill Invariant (i-have-adhd, v2.0.0-beta.7):
    • Agent Scoping: the i-have-adhd skill (adapted from ayghri/i-have-adhd, MIT) is embedded into exactly five agents — genin, jonin, anbu, tokubetsu-jonin, and chunin — via src/templates/agents.yaml, the src/templates/AGENTS.md / GEMINI.md routing tables, and Domain-Routing rows in each agent skill. Sannin (router) and Kage (reviewer) must NEVER receive it: their output contracts are governed by their own skills and the delivery gate.
    • Four-Tree Parity: i-have-adhd/SKILL.md ships byte-identical across src/templates/skills/, .agents/skills/, .cursor/skills/, and .gemini/skills/; tests/test_i_have_adhd_skill.js enforces parity, the exact 5-agent mapping, and the presence of all 10 output rules.
    • Presentation-Only Cap: rule 9 (cap lists to 5) shapes final-response presentation only — it must never limit analysis, search, tool results, or retained information; delivery-gate evidence requirements always outrank brevity.
  55. Pi Managed-Contract Deduplication Invariant (v2.0.0-beta.7):
    • Addendum Inside Markers: the Pi Workflow Mandate MUST be deployed INSIDE the <!-- KONOHA-CONTRACT-START/END --> managed block (buildPiManagedContract() in src/pi_manager.js), never concatenated after it. The legacy buildMainAgentContract(pi) + buildPiWorkflowAddendum() pattern appended a fresh mandate copy outside the markers on every redeploy while stale copies survived — production accumulated 166 copies (~410KB, ~100K tokens burned per Pi session).
    • Stale Sanitization: stripStalePiMandates() runs before every write, removing exact copies of the current addendum text plus legacy-format ## Konoha Workflow Mandate (Pi) sections (shape-aware: only blank lines and - bullets are consumed, user prose survives). tests/test_pi_contract_dedup.js enforces single-mandate idempotency, legacy-collapse, and fresh-install behavior.
  56. Token-Efficiency Feature Checklist (MANDATORY when adding ANY feature):
    • Budget every output: any new tool, endpoint, or command MUST return bounded payloads — previews with on-demand full content (see find_skill 500/250-char previews, loadSkillContentForBuild 400-char SOP previews), hard caps on findings/entries lists (e.g. 50), and byte/line caps on file reads. Never dump raw file contents or full-repo scan output into agent context.
    • Scan scope: every scan-style feature MUST be scoped (changed-files, explicit paths, or bounded directory walks with SKIP_DIRS and MAX_FILES/MAX_FILE_BYTES guards — see src/ai_detector.js). Unscoped full-repository evaluation is forbidden (token-hygiene mandate).
    • Boilerplate discipline: prompt/contract blocks injected into client context files must be marker-wrapped and REPLACED on redeploy (never appended — see rule 52). Before shipping, verify the deployed artifact size stays constant across repeated deployments.
    • Measure before/after: when adding a feature, run konoha savings and confirm the per-tool avg_KB stays within the bounded-tool envelope (read-style tools <= 5KB, build specs <= 16KB); a regression here is a delivery-gate failure.
    • Cache deliberately: expensive computations get fingerprint or mtime caching (see copySkillsDirFast, transcript caching rule 28) — but caches keyed by version must be invalidated on code change (never cache across upgrades without a version key).
  57. Website AI Detector Tool Invariants (v2.0.0-beta.7):
    • Pure Core + Three Surfaces: src/ai_detector.js is the pure detector (no DB/MCP/CLI deps) reused by the MCP tool wrapper (src/mcp/ai_detector.js, tool name website_ai_detector), the CLI (konoha detect-ai <path-or-url> [--json]), and the Web UI (GET /api/v1/detect-ai?target= + the /detector page). Adding detector rules means editing ONLY the RULES array in the core.
    • Scoring contract: score 0-100 = sum of triggered rule weights (GEN-01 generator tag +15, ICON-01 Lucide +12, ATTR-01 attribution +12, UI-01 shadcn shape +10, HOST-01 Vercel/Netlify +8, TPLT-01 boilerplate +6, ASSET-01 generic assets +4, FRAME-01 default title +3). Bands: 0-20 Human-Built, 21-40 Likely Human-Built, 41-60 AI-Assisted Build, 61-100 AI-Generated — the 0-20 band is the PLAN_HUMAN_BUILT.md target.
    • Manifest/Dispatch parity (rule 38): website_ai_detector is registered in src/mcp_tool_manifest.json, TOOL_HANDLERS (file_tools_router.js), both _executeToolInternal and async executeTool (directory targets sync; URL targets via the async path or a server.js subprocess). tests/test_ai_detector.js covers fixtures, URL mode, error handling, and the MCP dispatch contract.
  58. Upgrade Full-Runtime Refresh Invariant (v2.0.0-beta.7):
    • The ensureAutoSetup() slow path MUST call installCliRuntime() so version-bump upgrades refresh the COMPLETE installed runtime (bin/cli.js, the full src/ tree including src/mcp/, the pre-built web UI, package.json). The flat filesToCopy list covers the legacy root layout ONLY — it historically missed web_server.js, src/mcp/*, and sdlc_manager.js, leaving a stale backend after upgrades (the "dashboard 500 after upgrade" bug class).
    • copyFile() carries a same-path guard (self-copy is a no-op on Linux but can throw EPERM on Windows when konoha init runs from the installed runtime). konoha ui build refreshes ONLY the web build — backend changes still require a version bump (auto-setup) or konoha init.
  59. Token Savings Flow Logic Preservation Invariant (NEVER TOUCH TOKEN SAVINGS FLOW LOGIC):
    • Under NO circumstances should any coding agent or tool modify, refactor, remove, or disrupt the token savings telemetry, bounded file tool constraints (MAX_SPAN=250, MAX_LINES=150, MAX_LINE_CHARS=1000, DEFAULT_LIMIT=50), auto-compaction budgets, or baseline computation flow logic in src/file_tools/read_file_range.js, src/file_tools/read_file_head.js, src/file_tools/find_files_clean.js, src/mcp/tool_dispatch.js, src/tools_savings_logger.js, src/mcp/memory_reporting.js, and src/db_savings.js.
    • This token savings flow logic is stable, finalized, and strictly enforces our 83%–98% token reduction guarantee across all 8 supported coding clients.
    • Coding agents must treat this token savings engine as a strictly protected, immutable invariant alongside the stable Bridge Gateway.
  60. Konoha Maintenance Token Burn Elimination & Automation Invariant (v2.0.0-beta.7):
    • Zero Unscoped MCP Scans: The external aislop MCP tool aislop_scan only accepts directory path and lacks --changes support. Calling it on root scans all 3,500+ files and dumps ~14,000 findings into context (~50k tokens). Delivery Zero-AI-Slop gating on changed files MUST ALWAYS be executed via CLI: rtk aislop scan --changes (or pass specific changed file paths).
    • Skill Tree Sync Automation: When editing skills (such as konoha/SKILL.md), edit .agents/skills/ once and run npm run sync:skills (node scripts/sync_skills.js). NEVER manually duplicate edits across .agents/skills, src/templates/skills, .cursor/skills, and .gemini/skills, which burns 150k+ context tokens in multi-file reads/writes.
    • Incremental Test Runner Filtering: tests/run_all.js supports pattern filtering (node tests/run_all.js <pattern>). Incremental test passes during development MUST run only the relevant test suite (e.g. rtk node tests/run_all.js parity) to avoid burning terminal output tokens across 77 suites until the final regression run.
  61. Subagent Skill Consolidation & Reference Invariant (v2.0.0-beta.7):
    • All anti-slop rules (antislop.md, antislop-code.md, antislop-copywriting.md, antislop-human.md, antislop-layoutmobile.md, antislop-ui.md) are consolidated directly under kage-skill/references/ for Zero-AI-Slop gate reviews.
    • ADHD-friendly output shaping (i-have-adhd.md) is embedded byte-identical under all 5 target agent reference directories (genin-skill/references/, chunin-skill/references/, jonin-skill/references/, anbu-skill/references/, tokubetsu-jonin-skill/references/).
    • DevOps & Infrastructure scaffolding (helm-chart-scaffolding.md, helm-chart-scaffolding-assets/, multi-stage-dockerfile.md) is consolidated under anbu-skill/references/. Redundant helm-assets/ was permanently deduplicated in favor of canonical helm-chart-scaffolding-assets/.
    • PowerPoint presentation design (elite-powerpoint-designer.md, elite-powerpoint-designer-assets/) is consolidated under tokubetsu-jonin-skill/references/.
    • All standalone source skill directories (antislop*, helm-chart-scaffolding, multi-stage-dockerfile, react-*, elite-powerpoint-designer, i-have-adhd) are deprecated and removed across all 4 skill trees.
    • Legacy skill lookups in src/mcp/skills.js automatically normalize aliases and resolve references without prefixes.
  62. Neural Embedding CPU 100% Peak Elimination & Adaptive Duty-Cycle Throttling Invariant (v2.0.0-beta.7):
    • In src/vector_search.js, ONNX Runtime session options enforce single-threaded execution (intraOpNumThreads: 1, interOpNumThreads: 1, executionMode: 'sequential'), and WASM backend numThreads is bound to 1.
    • To eliminate 100% CPU pegging during clean re-embedding across large document corpora (1,188+ chunks), adaptive duty-cycle throttling is enforced in indexSingleSkillChunks: sleeping Math.max(Math.round(inferMs * 1.25) + 15, 35) ms per chunk (overridable via KONOHA_EMBED_PACE_MS), strictly capping active CPU duty cycle to ~40–50%.
    • An inter-skill cooling delay of 50ms and post-initialization settle delay of 100ms prevent thread contention and thermal throttling.
    • Transformer attention matrix memory is strictly bounded by capping chunk sizes to $\le 2000$ characters via sliding-window chunking, disposing native ONNX tensors via output.dispose(), and bounding in-memory embedding cache to 512 entries with inter-skill cache flushing.
  63. Offline Bundled Models & Dual-Stage Neural Reranker Invariant (v2.0.0-beta.7):
    • Offline Bundled Models: Both the neural embedding model (assets/models/onnx-community/granite-embedding-97m-multilingual-r2-ONNX/ at 93.3 MB) and the neural cross-encoder reranker model (assets/models/Xenova/ms-marco-MiniLM-L-6-v2/ at 23 MB) are pre-bundled directly under assets/models/, guaranteeing every single file is strictly under GitHub's 100 MB file limit.
    • Offline Discovery & Zero-Download: src/vector_search.js automatically detects bundled models via getBundledModelsDir(), sets env.cacheDir and env.localModelPath, and enforces local_files_only: true with graceful fallback, providing 100% offline neural vector search and cross-encoder reranking with zero network downloads.
    • Dual-Stage Reranking & RAG Retrieval: Retrieval combines fast Reciprocal Rank Fusion (RRF, k=60) for skill-level candidate ranking with full neural cross-encoder reranking (rerank() and searchChunksRAG()) for high-precision passage scoring and RAG context retrieval.
    • Global CLI Synchronization: bin/cli.js:installCliRuntime synchronizes assets/models into ~/.konoha/assets/models/ during konoha init / konoha upgrade, ensuring smooth global CLI deployment across all 8 coding clients.
  64. Vibes-Plug Skills Integration & Unified Routing Invariant (v2.0.0-beta.7):
    • 119 Curated Skills: Merged curated skills from https://github.com/roedyrustam/vibes-plug into canonical ninja agent skill references (anbu-skill, jonin-skill, kage-skill, chunin-skill, genin-skill, tokubetsu-jonin-skill, sannin-skill).
    • Routing Aliases: src/mcp/skills.js registers 190 canonical aliases in ALIASES (normalizeLegacySkillName), allowing agents and users to discover and retrieve skills by short name or domain prefix seamlessly.
    • Cross-Client Synchronization: All 119 skills and assets propagate across 5 mirror trees via rtk node scripts/sync_skills.js and index into SQLite FTS5 and IBM Granite vector chunks.
  65. Document AI Detector & ZeroGPT 0%–3% Precision Defense (v2.0.0-beta.7):
    • Pure Core + Multi-Surface: src/docs_ai_detector.js inspects .docx, .pdf, .pptx, .xlsx, .md, and .txt files across MCP tool (docs_ai_detector), CLI (konoha detect-docs <path>), and Web UI (apps/web/src/components/Detector.svelte).
    • ZeroGPT Sliding-Window Burstiness: Implements analyzeParagraphBurstiness (ZEROGPT-01) evaluating per-paragraph sentence cadence ($CV \ge 0.85$ target, $CV < 0.28$ warning) and AI transition trigger density to enforce our 0.0%–3.0% ZeroGPT risk target.
    • Container & Metadata Sanitization: Unpacks DOCX containers to extract true paragraph boundaries and inspects both docProps/core.xml and docProps/app.xml to detect unscrubbed library footprints (python-docx, docx-js, etc.), watermarks, and dark theme violations.
  66. v2.0.0-beta.7 16-Bug Comprehensive Hardening & Parity Invariant:
    • AI Slop Gate Circuit Breaker & Safe Degrade: In src/mcp/workflow.js, runAislopGate() utilizes CircuitBreaker (threshold=2, recovery=120s) so that if the external aislop process hangs, times out, or fails repeatedly, the gate degrades to advisory mode instead of blocking developers. Cross-platform execution prefers rtk first with fallback to aislop via which/where, with killSignal: 'SIGTERM'.
    • Dynamic File mtime Cache Invalidation: getMaxMtime() dynamically computes the latest mtime across changed project files and invalidates cached aislop_gate results when file mtimes exceed cached_at, preventing stale score approvals.
    • Mechanical 98% Confidence & 100/100 Aislop Gate Constants: MINIMUM_CONFIDENCE = 98 and AISLOP_TARGET_SCORE = 100 are exported as constants and enforced mechanically without heuristic drifts.
    • Universal 8-Client Workflow Reminder & Mandatory First Action: src/workflow_reminder.js detects and emits reminders across all 8 clients (Antigravity, Cursor, OpenCode, Pi, Codex, Claude Code, CommandCode, OMP), mandating FIRST ACTION: call konoha.find_skill with keywords BEFORE any code changes.
    • High-Effort Instruct Base Personality & 10 Forbidden Fillers: Across src/mcp/memory_reporting.js, src/agent_contract.js, and src/workflow_reminder.js, 10 conversational filler phrases are strictly banned (Hmmmm, Let me check, Let me see, Wait, let me, Wait - but, I will now proceed to, Let me examine, let me, hmm, hmmm). Output format strictly follows ADHD-friendly structured execution with zero monologue leaks.
    • Document AI Detector 0%–1% Precision Recalibration & Text Paste Mode: src/docs_ai_detector.js filters out structural elements (markdown headers, all-caps titles, bullet points, numbered lists, labels) from burstiness calculation to eliminate false-positive AI flags. Recalibrates burstiness threshold to 0.18, paragraph CV to 0.25, cliché thresholds (8 high, 5 medium), and transition triggers (minimum 3 required). Adds Web UI text-paste mode (apps/web/src/components/Detector.svelte) backed by POST /api/v1/detect-docs/text.
    • Skill Install Full Dual Indexing (FTS5 + Vector): Removed --skip-embeddings from addSkillDirect() and createSkillFromTemplate() in src/skill_manager.js, ensuring newly installed skills from skills.sh or Git repositories are immediately searchable via both FTS5 keyword matching and Granite neural vector search.
    • Cross-Client Multi-Tree Skill Parity: scripts/sync_skills.js includes all client trees in CLIENT_MIRRORS, ensuring complete parity across all clients when directories exist.
    • SDLC Task Governance Integration: Kage review gate directly checks sdlc_manager.listTasks({ sessionId }) and blocks delivery if any task is explicitly in blocked or failed status.
    • Official Skills Deduplication: Standalone helm-chart-scaffolding is permanently removed as an independent skill root and retained exclusively as an internal reference under anbu-skill/references/helm-chart-scaffolding.md. Canonical aliases agent-browser, devsecops-engineer, documentation, modern-full-stack, and websearch-deep are registered in src/mcp/skills.js.
  67. Clean Runtime Reinstallation & ~/.konoha Sanitization Invariant (v2.0.0-beta.7):
    • Clean Reinstall Execution: Running konoha init --force --yes (or alias reinstall, konoha clean) invokes cleanKonohaRuntimeDir() in src/deploy_utils.js.
    • Stale Disk Bloat Elimination: Automatically purges stale backups (konoha.db.bak-*, skills.db.bak-*, *.bak), legacy databases (skills.db*), legacy root Python scripts (*.py, *.pyc), dead PID/lock files (bridge.pid, ui.pid, package-lock.json), dead caches (transcript_cache.json), transient scratch tasks in tmp/, misplaced root .vsix packages, obsolete root cli.js, and orphaned root .js files not in src/.
    • Critical Asset Preservation: Strictly preserves konoha.db (active SQLite DB) and its WAL/SHM, transformers_cache/ (neural model weights), node_modules/ (production dependencies), vendor/, searxng/, and web_token.
    • Safe Database Maintenance: Runs safe WAL truncation (wal_checkpoint(TRUNCATE)) and database vacuuming (VACUUM) on konoha.db to defragment storage and reclaim disk space.
    • Safety Target Rejection: Rejects dangerous targets (root /, user HOME, or matching srcDir) to prevent accidental deletion.
  68. AI Slop Scanner Zero-Exclusions & Mandatory Force-Scan Invariant (v2.0.0-beta.7):
    • Never Exclude Anything Except Dependency Modules: The AI slop scanner enforces an absolute zero-exclusions policy. ONLY third-party dependency modules and framework package libraries (node_modules/, vendor/ from composer/go, .venv/, venv/, */site-packages/, Pods/, target/, .gradle/, .pub-cache/, .cargo/, .nuget/) may ever be excluded.
    • Zero Blanket Exclusions: Application source code, tests, components, configs, templates, scripts, and documentation files must NEVER be excluded or ignored under any circumstance.
    • Mandatory Force-Scan: runAislopGate() removes any configuration file prerequisite (.aislop/config.yml is no longer required) and always force-scans the project before synthesis. Delivery is strictly blocked if the mechanical scan score < 100 or findings > 0.
  69. Collapsible Submenu Accordion & Expandable Content Canvas Invariant (v2.0.0-beta.7):
    • Clickable Submenu Accordion: Sidebar navigation sections (Overview, Clients & Finance, Tools & Integrations, Configuration, Operations, Resources) feature interactive collapsible accordions. Clicking any parent category expands or collapses its sub-menu items with smooth animated chevron transitions. The active section auto-expands on route changes.
    • Sidebar Collapse for Maximum Center Space: A dedicated sidebar toggle button in both the sidebar brand header and top main header enables closing and opening the sidebar. When collapsed (w-0), the central main content stage expands to 100% full screen width, giving users maximum focus area.
  70. Chidori Azure Default, 4-Gradient Color Palette & 5px Card Radius Invariant (v2.0.0-beta.7):
    • Chidori Azure Default Theme: The out-of-the-box default theme is chidori (Chidori Azure Light), delivering sky-blue and cyan lightning focus with pure light mode eye-friendly contrast.
    • Universal 4-Gradient Theme Style: All 10 themes in the Konoha palette define a 4-color gradient array (--theme-grad-1 through 4, --theme-4gradient, --theme-4gradient-bar, --theme-4gradient-subtle), displayed with visual 4-color swatches in the theme switcher modal and as a top accent bar.
    • Distinctive Akatsuki Dusk Plum Palette: akatsuki uses a rich Dusk Plum / Fuchsia palette (#86198f, #c026d3, 4-stop gradient ['#581c87', '#701a75', '#86198f', '#c026d3'], #fdf4ff), completely eliminating duplicate hues with Sharingan Rose Light (#dc2626).
    • Crisp 5px Card Border-Radius Invariant: Every card container (.glass-card-3d, .theme-card, .card, modals, and metric tiles) enforces a strict 5px border-radius (border-radius: 5px !important).
    • Strong Glassmorphism: High-performance frosted glass panels feature 28px backdrop blur, 195% saturation, enhanced specular highlight edges (--glass-edge, --glass-highlight), and GPU-accelerated translateZ layering.
  71. Strict Non-Destructive User Skills & Configuration Preservation Invariants (v2.0.2):
    • Additive-Only Skill Synchronization: copySkillsDirFast in src/deploy_utils.js and bin/cli.js never removes or prunes pre-existing user skills or auxiliary files. Synchronization is strictly additive and non-destructive across all 7 client skill directories (~/.cursor/skills, ~/.gemini/antigravity-cli/skills, ~/.claude/skills, ~/.config/opencode/skills, ~/.opencode/skills, ~/.commandcode/skills, ~/.codex/skills, ~/.agents/skills).
    • Additive SQLite FTS5 Database Migrations: cmdInit and cmdMigrate perform additive upserts (INSERT OR REPLACE INTO skills) without default table wipes (--clean removed from defaults). Deleted-skill pruning in src/migrate.js is strictly guarded behind explicit user-supplied --clean.
    • Managed Instruction Boundaries (injectManagedConfig): Konoha configuration injections into instruction files (GEMINI.md, AGENTS.md, CODEX.md, instructions.md) are strictly encapsulated between <!-- KONOHA-START --> and <!-- KONOHA-END --> tags. 100% of surrounding user instructions, prompt rules, and preambles are preserved. Uninstallation (konoha uninstall) cleanly strips only the managed block.
    • Custom Agent Union-Merge in agents.yaml: loadAgents and initAgentsConfig merge missing default ninja personas into ~/.agents/agents.yaml without overwriting, modifying, or deleting user-defined custom agents.
  72. Cross-Platform Web UI Subsystem & Windows Lifecycle Resilience (v2.0.2):
    • Modularized UI Subsystem: All Web UI commands (start, stop, restart, status, daemon, service, build, preview, open, ensureUiDaemonAutoStart) are modularized into bin/lib/ui_commands.js, keeping bin/cli.js strictly below the 9,000-line complexity limit (8,917 lines).
    • Windows Browser Opening: openUrlInBrowser uses cmd.exe /c start "" with windowsHide: true to prevent intrusive console window popups.
    • Windows Daemon Spawning: cmdUiStart passes windowsHide: true to spawn and adapts connection polling to 30 attempts on Windows to account for process startup latency.
    • Port-Scoped Daemons: Process termination via cmdUiStop targets only the specific port requested (never killing other ports).
    • Windows Process Tree Termination: cmdUiStop leverages taskkill /F /T /PID, followed by PowerShell -Unique connection ownership kill and netstat -ano fallback.
    • Windows SIGBREAK Support: cmdUiDaemon and cmdWebForeground hook SIGBREAK alongside SIGINT/SIGTERM for clean shutdown on Windows console events.
    • Dynamic Dist Resolution: web_server.js dynamically resolves getDistDir() avoiding stale path caching.
  73. Strict Zero-Exclusions Invariant & Kage Review Delivery Gate (v2.0.2):
    • Zero Codebase Suppressions Policy: NEVER ignore, suppress, or exclude application codebase using aislop-ignore, comments, or config directives (only external node_modules, vendor/, and cache directories may be excluded). Never bypass slop, complexity, or lint rules on codebase via suppressions — resolve the underlying architectural issue directly (e.g. modularizing oversized files).
    • Mechanical Delivery Gate: Kage Reviewer workflow mechanically enforces a perfect 100/100 aislop scan (ai_slop_findings: 0, ai_slop_clean: true) across changed files before synthesis or confidence scoring.
    • 98% Minimum Confidence: Overall delivery confidence must be ≥ 98% with structured delivery box report.
  74. QA Automation Architecture & Token-Efficient Workflow (v2.1.0):
    • Owned by Anbu: Integrates scoped agent-browser exploration and deterministic Playwright test execution into the 8-phase SDLC.
    • Zero LLM Token Philosophy: Explore once with agent-browser (small scoped snapshots, console/network error capture) -> Save working steps to semantic JSON flow file -> Codify deterministically via qa_codify (zero LLM involved) -> Run and re-run with Playwright Test via qa_e2e_run (zero LLM browsing tokens).
    • Escalating Triage: On failure only, execute small escalating triage (log inspect -> scoped re-run -> flow file patch -> re-codify).
  75. 13-Page Enterprise Cloud Architecture & Visual Diagrams (v2.1.0):
    • 13-Page Enterprise Cloud Model: The enterprise architecture diagram (docs/diagrams/konoha-enterprise-architecture.drawio) strictly maintains 13 canonical pages rendered in professional GCP/AWS/Azure cloud shape styling with zero geometric shape or connector collisions.
    • Manual User Diagram Protection: Under NO circumstances mutate or overwrite docs/diagrams/konoha-architecture.drawio (user's manual work, preserve timestamp).
    • High-Contrast Mermaid Invariant: All companion Mermaid diagrams across all documentation MUST strictly specify #ffffff white backgrounds, #0f172a dark slate strokes, and matching #0f172a arrowheads for maximum legibility.
    • Flow WebP Synchronization: Visual workflow demonstrations in assets/ (including konoha-qa-flow.webp) are rendered as Animated WebP and verified via scripts/generate_premium_flow_gifs.js.
  76. Plug-and-Play npm Package & Pure Node SQLite (v2.1.0):
    • Package Identity: Published as konoha-mcp with engines: { "node": ">=22.16.0" } and public npm access.
    • Zero-Compilation Runtime: Built-in node:sqlite (DatabaseSync / StatementSync) replaces native C++ compilation bindings (better-sqlite3, onnxruntime-node), guaranteeing instant npx konoha-mcp installation without python, build tools, or node-gyp.
    • Cold Skills FTS5 Seed: Offline SQLite FTS5 database initialized in < 800ms.
    • Standalone SvelteKit Web UI: Self-contained adapter-node standalone build (apps/web/build/handler.js) requiring zero native runtime dependencies.
  77. npm Trusted Publishing & OIDC CI/CD Release (v2.1.0):
    • OIDC Provenance Attestation: Releases are published directly via GitHub Actions (.github/workflows/publish.yml) using OpenID Connect (OIDC) with id-token: write permissions, eliminating static token exposures.
    • Environment-Gated Publishing: CI jobs target environment: NPM_TOKEN aligning with npm Trusted Publisher specifications.
    • Bare-Relative Executable Path: package.json configures "bin": { "konoha": "bin/cli.js" } complying with npm 11 strict path validation standards.
    • Public Repository Metadata: Root package.json enforces canonical public repository metadata (git+https://github.com/andycungkrinx91/konoha.git) required for cryptographic build provenance.
  78. Socket Supply Chain Security Gate & Kage Review Invariant (v2.1.0):
    • Mandatory Socket Review in Kage Gate: When maintaining or updating the Konoha repository, Kage Review MUST ALWAYS execute a Socket security scan via the Socket CLI (rtk socket ci or rtk socket scan create ./package.json --report).
    • High & Medium Risk Elimination: The target repository manifests MUST be strictly clean from High (error/critical/malware/CVE) and Medium (warn/gptAnomaly/eval/anomaly) risk alerts (0 High, 0 Medium). Low-level risk (informational/monitor notices like telemetry or minified file alerts) is excluded from blocking delivery.
    • Delivery Blocking: If any High or Medium risk vulnerability or supply-chain issue is detected, delivery is strictly BLOCKED until dependencies are upgraded, overridden, or remediated.
    • Standard Confidence Gate Report: The Kage Reviewer Confidence Gate Report table must include the Socket Security Gate row verifying 0 High, 0 Medium findings before delivery.
  79. Canonical Skills Single Source of Truth & Database Parity (v2.1.13 - v2.1.14):
    • Single Source of Truth (src/canonical_skills.js): Authoritatively defines CANONICAL_SKILL_NAMES (the 15 canonical ninja and core skills, with helm-chart-scaffolding consolidated into anbu-skill) and KNOWN_EMBEDDED_REFERENCE_SKILLS (190+ reference skills consolidated inside ninja skills).
    • Automatic Deduplication Without Pruning: isEmbeddedReference() in src/migrate.js and src/mcp/skills.js prevents duplicate standalone skill registration from mirror or project directories, while preserving all user custom skills.
    • 100% Database Parity: The database ~/.konoha/konoha.db strictly contains exactly 15 skills of type = 'skill' and all referenced sub-skills indexed as type = 'reference'.
    • Skill & Mirror Preservation Invariant: Strictly never prune, delete, or strip ~/.agents/skills/ or any client mirror trees (.cursor/skills, .gemini/skills, etc.).
  80. Least-Privilege Security Boundaries & Scoped Client Tool Permissions (v2.1.13):
    • Elimination of Wildcard Grants: Replaces all * wildcard approvals in Command Code, Claude Code, and Cursor with explicit, enumerated tool names (konoha_*, semble_*, aislop_*).
    • Bash Execution Bounds: Claude Code and terminal tools must never receive unconstrained Bash(*) wildcard execution approval; all approvals are bounded to explicitly verified commands.
  81. LibreOffice Shim Integrity & Supply Chain Hardening (v2.1.13):
    • Zero Dynamic Interposition: Document generation tools (soffice.py) avoid dynamic, runtime compilation of untrusted C source code into shared objects (LD_PRELOAD).
    • Integrity Validation: Shims and prebuilt binaries must pass cryptographic hash validation or execute directly through safe standard LibreOffice headless CLI flags (--headless --convert-to).
  82. Accurate Skill Resolution via use_skills MCP Tool (v2.1.14):
    • Precise Database Lookup: Direct resolution from SQLite konoha.db by exact skill name (use_skills({ skills: [...] })).
    • Fallback Warning: If not present in DB, logs structured warning to console and gracefully falls back to local mirror (.agents/skills/ / ~/.agents/skills/).
    • Eliminates Hallucination: Prevents skill misattribution or agent capability hallucination.
  83. Deterministic anti_slop Verification Pre-Gate & Tokubetsu-Jonin Human Document Design Layer (v2.1.14):
    • Anti-Slop Pre-Gate Tool (anti_slop): Executed in Kage pre-delivery review alongside aislop_scan. Validates zero AI-slop patterns (lazy placeholders, generic syntax comments, speculative over-engineering, conversational fluff).
    • Mandatory Agent Anti-Slop Matrix: antislop in all official agents; antislop-ui in jonin; antislop-copywriting in tokubetsu-jonin; antislop-human in all official agents except sannin; antislop-layoutmobile in jonin; antislop-code in all official agents except sannin.
    • Tokubetsu-Jonin Human Document Design Layer: Strict standards for Word/DOCX, PowerPoint/PPTX, Excel/XLSX, and PDF:
      • 20 gradient themes (T01–T20) with 4-base-color gradients.
      • Text rendered in medium slate #64748B on white/light backgrounds.
      • Zero dark colors (no black, dark gray, dark blue anywhere).
      • Typography pairing contracts: Georgia + Calibri (DOCX/reports), Segoe UI Semibold/Georgia + Segoe UI/Calibri (PPTX), Calibri (XLSX), Inter (PDF).
      • Mandatory Kage review gate for all generated documents.
  84. Mandatory Release Permission Gate & Zero Auto-Release Invariant (v2.1.14+):
    • Explicit User Confirmation Required: When maintaining, updating, or fixing the Konoha repository or any client configurations, the agent MUST ALWAYS explicitly ask the user for permission before executing any release action (creating git release commits, git tags, git pushes to release branches, or triggering npm publish / CI release workflows).
    • Zero Auto-Release Invariant: Auto-releasing, automatic tagging, or unprompted publishing to npm or GitHub without prior explicit user request and authorization is strictly prohibited. Keep all changes local until explicitly instructed and approved by the user to release.
  85. Telegram Bot Remote Notification & Outbound Reporter Invariants (v2.1.17):
    • Zero-Emoji Outbound Reporter: Outbound task completion and error notifications via Telegram Bot API strictly adhere to the zero-emoji standard ([KONOHA TASK REPORT], [SUCCESS], [FAILED], [QUEUED], [ERROR]).
    • Configuration & Storage: Bot token and target chat ID stored in telegram_config table in ~/.konoha/konoha.db. Managed via CLI: konoha telegram config --token <BOT_TOKEN> --chat-id <CHAT_ID>, konoha telegram enable, konoha telegram disable, and konoha telegram test.
    • Native Long Polling & Whitelist Gate: Long polling daemon (src/telegram/poller.js) runs with strict chat_id whitelist authorization (telegram_config.chat_id). Unauthorized sender messages are immediately dropped.
    • Daemon Commands: Supports /run <prompt>, /status, /savings, /kage, /cancel, /help.
  86. Public Tunnel & Cloudflare Zero Trust Ingress Security Invariants (v2.1.17):
    • Quick Tunnel & Named Domain Ingress: Child process supervisor (src/tunnel/manager.js) manages cloudflared tunnel --url http://localhost:1404 (or ngrok) with process lifecycle tracking and live public URL extraction (trycloudflare.com).
    • Edge Identity Mode A (No PIN): Web server routes validate Cloudflare Zero Trust identity header Cf-Access-Authenticated-User-Email when accessed via public tunnel while allowing unauthenticated local access on localhost:1404.
    • CLI Management: konoha tunnel start, konoha tunnel stop, konoha tunnel status, konoha tunnel config.
  87. Unified Prompt Queue & Asynchronous Inbox Architecture (v2.1.17):
    • SQLite Queue Engine: Table prompt_queue maintains atomic prompt state (pending -> processing -> completed / failed) with retry count and priority.
    • Filesystem Mirror: Mirrored into ~/.konoha/inbox/<session_id>.json and ~/.konoha/inbox/latest.json for coding client pickup.
    • Remote Access Web UI: Integrated into SvelteKit dashboard (/remote and RemoteAccess.svelte) providing live status cards for Telegram, Cloudflare Tunnel, and real-time Inbound Prompt Queue.
  88. Interactive Shell Execution & Subagent Direct Dispatch Invariant (v2.1.17):
    • Interactive Shell Execution: Commands dispatched via /sh <cmd> or /exec <cmd> execute in the target workspace using the user's interactive shell (userShell -i -c) with full alias expansion from ~/.bashrc (kubectl, kc*, helm, etc.).
    • Security Guardrail: Dangerous or destructive commands (rm -rf /, mkfs, dd, drop database, truncate table, etc.) are unconditionally rejected by isDangerousCommand.
    • Subagent Direct Dispatch: Slash commands (/kage, /anbu, /jonin, /genin, /chunin, /tokubetsu_jonin, /sannin) bypass general routing deliberation and directly assign prompts to specialized ninjas.
    • Multi-Client Workspace Switcher: Manage and switch active client workspaces across Antigravity, Claude Code, Codex, Pi, OpenCode, and Command Code via /session [number] and register remote directories via /session create <client> <path>.
  89. Operational vs. AI Routing in Autonomous Queue Worker (v2.1.17):
    • Operational Branch (0 LLM Tokens): Deterministic commands starting with /sh, direct commands (kubectl, helm, docker, git, ssh, etc.), or kc* shell aliases execute deterministically in interactive shell with 100% token elimination.
    • AI Coding Branch: Complex coding and natural language prompts route through headless agy -p ... with structured task telemetry and Kage Reviewer confidence reporting.
    • Daemon Observability: Structured diagnostic logging across poller (src/telegram/poller.js) and queue worker (src/queue/worker.js) ensures full audit visibility in journalctl.
  90. Telegram One-Way Kage Gate Review Dispatch & Non-Blocking CLI Explorer (v2.1.17):
    • One-Way Kage Gate Notification: In Telegram One-Way Mode (as well as Two-Way Mode), whenever any local workstation session (Antigravity IDE/CLI, terminal session, or background runner) passes Kage Final Gate Review (APPROVED with 100/100 zero-slop score and ≥98% confidence score), notifyKageReviewPassed in src/telegram/notifier.js is automatically triggered via report_from_agent in src/mcp/memory_reporting.js. The developer receives immediate, zero-polling completion notifications on their phone.
    • CLI Manual Notification: Developers can test or trigger the gate notification via konoha telegram notify-kage [summary] or konoha telegram test-gate.
    • Non-Blocking Agent List: konoha agent list renders a fast (<0.2s) static table by default. The interactive raw-mode terminal UI is strictly scoped behind --tui, --interactive, or -i, ensuring zero hangs in automated test runners, non-TTY environments, and PTY runners.
    • Safe Queue Worker Subprocesses: src/queue/worker.js strictly executes tasks via execFile(agyBin, agyArgs, ...) with structured argument arrays and dynamic resolveAgyBin(), completely eliminating shell command injection risks.
    • Single Target Session Marker: src/telegram/session_manager.js evaluates session indices to ensure strictly ONE session receives the (CURRENT TARGET) badge.
  91. Operational Database Maintenance & Telemetry Pruning Invariants (v2.1.17+):
    • Zero-Downtime Backup (konoha data backup [path]): Performs online SQLite snapshot using native VACUUM INTO without blocking concurrent reads/writes. Defaults to ~/.konoha/backups/konoha_backup_<timestamp>.db.
    • FTS5 Self-Healing (konoha data rebuild-fts): Rebuilds virtual full-text search indexes (skills_fts, persona_memories_fts) from canonical tables via rebuildAllFts().
    • Automated Retention Pruning (konoha data prune --retention <days>): Prunes granular tool_calls telemetry older than the retention threshold (default 90 days) while preserving all-time summary statistics.
    • Agent Telemetry Normalization (normalizeAgentName): Maps runtime tool prefixes (mcp_, delegate_to_, delegate-) and legacy aliases to canonical agent names.
    • Cascading Foreign Key Integrity: Enforces PRAGMA foreign_keys = ON with cascading deletes (ON DELETE CASCADE) from projects to persona_memories.
  92. Session Sandbox Isolation & Persona Memory Scoping Contract (Decision A):
    • Strict Per-Session Episodic Isolation: When an explicit session_id is supplied without allSessions: true, queryMemories isolates episodic memories strictly to that session.
    • Project-Level Rule Visibility: Project-scoped memories that are non-episodic (memory_type != 'episodic') remain visible across sessions within the same project.
    • Explicit Cross-Session Opt-In: The Web UI and administrative tools pass allSessions: true (or crossSession: true) to list and inspect memories across all sessions.
    • Options Shadowing Guard: Variable re-assignment in memory handlers does not shadow caller query options (allSessions, persona, project_hash).
  93. CLI Router Consolidation & Direct Specialist Dispatch Invariants (v2.1.18):
    • Removed 27 Top-Level CLI Aliases: All legacy router aliases (embeddings, detect_ai, ai-detector, detect_docs, docs-detector, detect-doc, personas, memories, spirit, will-of-fire, projects, tasks, web-search, inbox, install, memory, setup, update, saving, agents, tg, tunnels, prune, context, persona, searxng, sdlc) are removed; they strictly exit with code 1 and error Unknown command: <alias>.
    • Specialist Subagent Direct Dispatch: Deprecated delegate_to_* tool wrappers and configuration grants are removed across all client integrations (claude, cursor, opencode, codex, antigravity), consolidating MCP dispatch directly to specialist tools (sannin, genin, kage, chunin, jonin, anbu, tokubetsu_jonin).
    • Report Caller Name Validation (G-18): report_from_agent strictly rejects legacy delegate_to_* caller names and requires direct agent names.
  94. Website AI Detector Dual Target Support (Directory & File) (v2.1.18):
    • konoha detect-ai <target> and MCP tool website_ai_detector support both directory targets and single-file targets (such as package.json, .html, source code files). Single-file targets collect signals via collectFileSignals with bounded line extraction and file type routing.
  95. Database Schema & Foreign Key Migration (v2.1.18):
    • Table rebuild with foreign key constraints takes an atomic backup before migration; orphaned project memories (project_hash non-empty and absent in projects) are safely deleted upon migration instead of leaking to global scope.
  96. Immediate Deletion Warning for konoha data prune (v2.1.18):
    • konoha data prune performs immediate deletion of historical tool calls without interactive confirmation or automatic backup.
  97. Standalone Static Analysis Linter (v2.1.18):
    • npm run lint (scripts/lint.js) checks all JavaScript files across bin/, src/, tests/, and scripts/ without external npm dependencies.
  98. Modular CLI Architecture Invariant (v2.1.18):
    • bin/cli.js modularizes subcommand execution across 23 discrete command handlers under bin/commands/ and 5 shared core libraries under bin/lib/. The root router parses flags, normalizes aliases, and delegates cleanly without monolithic script bloat.
  99. Native Document Engineering Invariant (v2.1.18):
    • src/tools/document_engine.js implements 5 canonical MCP tools (document_create, spreadsheet_create, presentation_create, diagram_create, animation_export). Generated Word/PDF documents enforce discrete per-page Word sections with static TextRun page numbers (completely eliminating grey background shading boxes in Word and LibreOffice) and radical burstiness ($CV \ge 0.85$) passing Document AI Detector with < 3% ZeroGPT AI risk target. Spreadsheets implement 10 curated random palettes (#3B82F6, #14B8A6, #8B5CF6, #F97316, #EAB308, #EC4899, #84CC16, #06B6D4, #6366F1, #F43F5E) with summary KPI cards and auto-fit columns. Presentations generate 16:9 widescreen slides. Diagrams generate dual-orientation SVG with 10 gradient themes.
  100. Animated WebP Canonical Output Invariant (v2.1.18):
    • animation_export establishes native Animated WebP (.webp) as the canonical default animation format, encoded via Playwright Chromium frame capture + FFmpeg libwebp_anim with -lossless 0 -compression_level 6 -q:v 50 -preset drawing -loop 0, achieving 40%–70% size reduction over GIF baselines. Every generated WebP must pass pure Node.js binary structural validation (validateAnimatedWebP) inspecting RIFF, WEBP, VP8X animation flag, ANIM loop header, and ANMF frame chunks. GIF format remains supported strictly when callers pass explicit format: 'gif'.
    • All 17 visual workflow and terminal demonstration assets in assets/ are maintained strictly as Animated WebP (.webp) and validated with validateAnimatedWebP. Active documentation and README embeds reference .webp files exclusively.
  101. Lost in the Middle & Long-Context Attention Preservation Invariant (v2.1.18):
    • Attention Decay Mitigation: LLMs (such as Gemini 3.8 Flash, Claude, and GPT-4) suffer from the "Lost in the Middle" attention degradation in long transcripts. When multi-turn sessions expand or tool results exceed tens of thousands of tokens, attention weights concentrate only at the prompt boundaries (primacy/recency), while tokens in the middle 50%–80% experience severe attention attenuation.
    • Explicit Boundary Re-Anchoring: sanninWorkflowNext and runSannin in src/mcp/workflow.js mechanically inject user constraints and original prompt parameters directly into structured tool arguments (task, context, constraints) across all subagent dispatches (explore, plan, research, execute, document, review, and remediation). This ensures subagents (Jonin, Anbu, Kage, Tokubetsu-Jonin) always see the original prompt and user-specified constraints at the immediate boundary of their execution without relying on deprecated file-based IPC.
    • Turn-Level Workflow Reminder: src/workflow_reminder.js re-injects the anti-context-loss guard on every turn, warning agents against relying on conversational memory or fuzzy recall from earlier turns for critical arguments (identity, flags, negative constraints).
    • Exact String Assertion Gate: Before running state-altering or git commit actions, agents must assert exact parameter equality against requested parameters (e.g., verifying git log -n 1 --format="%an <%ae>" exactly equals andycungkrinx91 <andy.silva270114@gmail.com>), rather than assuming environment defaults or glancing at passing config flags.
  102. TUI & CLI Subsystem Parity, Broken Symlink Resilience, and Modular Subcommand Architecture (v2.1.18):
    • Packaged Canonical Skill Path Resolution: bin/commands/init.js, bin/commands/test.js, and bin/commands/uninstall.js resolve packaged canonical skills dynamically across multiple root candidates without assuming fixed parent directory depth.
    • Broken Symlink & Non-Existent Target Resilience: src/canonical_skills.js (pruneObsoleteStandaloneSkills), src/migrate.js (autoDetectSkills), and src/file_tools/get_file_structure.js wrap file system inspection in safe try/catch blocks and clean up dangling symlinks, preventing ENOENT crash cascades.
    • OMP Launcher Resolution: bin/commands/init.js explicitly imports FILE_TOOLS_LAUNCHER_JS from bin/lib/paths.js to guarantee seamless OMP client registration.
    • RTK Compilation Bypass for Pre-Installed Binaries: src/antigravity_manager.js checks isRtkInstalled() before triggering cargo compilation during init --force, preventing redundant 5-minute Rust compilation timeouts.
    • Two-Section QA Verification Matrix: docs/QA-TEST-CHECKLIST.md defines Section 1 (TUI & CLI Subsystem Verification across 34 commands/subcommands) and Section 2 (Web UI & Browser Automation QA).
  103. Proxy Gateway Process Lifecycle, Dynamic Savings Telemetry, and Prompt Token Optimization Standard (v2.1.18):
    • Port-Targeted Process Termination (killProcessOnPort): src/platform_utils.js implements reliable cross-platform socket clearing for port 19999. On Linux/macOS, query listening PIDs via lsof -ti :${port} and fuser, issue graceful SIGTERM, wait up to 800ms, and escalate to SIGKILL if still active. On Windows, resolve PIDs via netstat -ano | findstr :${port} and terminate via taskkill /F /PID ${pid}. Web UI /bridges and CLI konoha bridge stop verify that checkPortActive(19999) returns false before reporting stopped state.
    • Incremental Transcript Cache: calculateAllModelTokens() in src/db_savings.js maintains persistent file-level cache { mtime, size, all, recent } in ~/.konoha/transcript_cache.json alongside process-level memory caching (15s TTL). Unmodified transcript files are never re-read or re-parsed, slashing latency from 9.35s to < 30ms.
    • Dynamic Baseline Telemetry: In src/tools_savings_logger.js, baseline bytes for find_skill / find_skills are dynamically computed from the actual SUM(byte_size) of retrieved skill candidates in SQLite FTS5/LIKE matching (0 matches = returned bytes, 0 saved). Removed static 15,000-byte fallback and sanitized legacy records dynamically, ensuring real-time savings percentages authentically reflect 83%–98%.
    • Decoupled Prompt Token Optimization: loadAgents() in src/agent_manager.js keeps a.skills strictly scoped to canonical top-level skills (!s.includes('/')), preventing database reference catalogs (901+ items) from expanding into agent prompt arrays. Subagent instruction generators in src/cursor_manager.js and src/agent_contract.js emit concise on-demand discovery directives (Before work: call konoha.find_skill with keywords from the task prompt to load relevant domain references), reducing AGENTS.md, .cursorrules, and subagent markdown payloads by > 85% (> 35,000 tokens saved per request).
  104. Dashboard Gauges, Header Orb Removal, Breadcrumb Contrast, Full-Screen Theme Switch & Shared 3D Rasengan Background (v2.1.18): - Dashboard Gauges Geometry & Contrast Invariant: Center gauge disc resized from 144px (inset-2) to 96px (w-24 h-24), eliminating physical overlap with the 106px inner stroke ring. Dedicated semantic tokens (--theme-gauge-track, --theme-gauge-arc-start, --theme-gauge-arc-end) guarantee min 3:1 contrast against --color-surface and between track and arc across all 10 theme palettes in both modes. Arc length is strictly mathematically proportional (stroke-dashoffset = 100 - pct). Slow looping lamp-light glow animation (4s ease-in-out infinite) breathes without altering arc length or flickering on 5s live refresh. - Header Rasengan Orb Removal: The header orb visual is completely removed from apps/web/src/routes/+layout.svelte and obsolete RasenganOrb.svelte deleted without leftover placeholders or layout gaps, while preserving bottom-right floating FABs. - Header Breadcrumb High-Contrast Tokens: Active crumb (--theme-crumb-active), separator (--theme-crumb-separator), and parent section (--theme-crumb-parent) are derived per mode from active theme tokens, achieving min 4.5:1 contrast across all 10 themes in both Light and Dark mode on all routes. - Full-Screen Theme Switch Rasengan Transition: ThemeSwitcher.svelte implements a full-viewport transition overlay (fixed inset-0 w-screen h-screen z-[9999]) dynamically rendered with the newly selected theme's 4-gradient tokens (--rasengan-1..4). Rapid consecutive switches cancel running timers and cleanly restart without stacking effects or WebGL leaks; unmounts completely from DOM upon completion. - Single Shared 3D Rasengan Background Component: SharedRasenganBackground.svelte is mounted once at root level in +layout.svelte, persisting across route navigation without re-creating WebGL contexts or restarting animations. Content areas use transparent backgrounds so the animated 3D scene is visible through glass cards and margins while maintaining >= 4.5:1 text contrast. Respects visibilitychange (pauses RAF when hidden) and prefers-reduced-motion (static frame).
  105. Dual-Track Execution Engine, Polyglot Stack Detection & 2-Way HITL Approvals (v2.2.0): - Dual-Track Execution Engine: Preserves Fast-Track Direct Execution for slash commands (/anbu <prompt>, /jonin <prompt>, etc.), single-file edits, typo fixes, and ad-hoc inspections with zero pipeline overhead (bypassing 8-phase DAG and Gate 1 pause). Greenfield builds and multi-subsystem refactors execute through the Canonical 8-Phase DAG. - Complete Elimination of File-Based IPC: Zero usage of prompt.md, delegate.md, or result.md. Task inputs are ingested from <USER_REQUEST> / sdlc_tasks.description, dispatches pass structured tool arguments, and results are reported directly via konoha.report_from_agent. - Configurable Two-Stage HITL Gates: Enforces Gate 1 (pending_plan_approval) and Gate 2 (pending_human_signoff) strictly through SQLite database status when hitl_mode === 'enabled'. Keywords in prompts never self-bypass gates. Autonomous mode (hitl_mode === 'disabled') proceeds hands-free. - Telegram 2-Way Interactive Approvals: Inline keyboard buttons [✅ Approve] and [❌ Reject] dispatched to Telegram mobile bot. Supports /approval list and /approval <id>. Enforces strict mutual exclusion between 1-way and 2-way modes to eliminate duplicate notifications. Broadcasts completion alerts across all clients. - Dynamic Polyglot Stack Detector (src/mcp/stack_detector.js): Inspects workspace manifests and dynamically selects native ecosystem commands across Node/TS, Python, Go, Rust, PHP, and Java. - RTK Boundary Anti-cat/Anti-grep Guardrail (src/guardrails.js): Rejects all shell file readers (rtk cat, rtk head, rtk grep, etc.) at the tool-call boundary with 100% redirection to konoha.read_file_range and semble.search.
  106. Argon2id Authentication, Outbound Webhooks & OMP Isolation Hardening (v2.2.0): - Argon2id Password Storage & Timing-Safe Verification: Passwords are encrypted with Argon2id ($argon2id$v=19$m=65536,p=4,t=3$...) for state-of-the-art resistance to offline brute-force attacks, while maintaining backward-compatible verification for existing salted scrypt hashes. - Authorized Password Management & Session Termination: Voluntary password updates or resets from /settings enforce authorization (requiring current valid password) and immediately terminate all active sessions (destroyAllSessions()), forcing re-authentication at the login page. - Atomic Bootstrap Authentication Reset & CLI Recovery: Implemented resetAuthToDefault() in src/auth.js to atomically restore default credentials (konohagakure, is_bootstrap: true) and terminate active sessions without requiring an authenticated session. Added CLI commands konoha web reset-password and konoha auth reset. - Playwright Test Credential Isolation: apps/web/playwright.config.js enforces reuseExistingServer: false and sets KONOHA_AUTH_FILE: '/tmp/konoha_test_web_auth.json', ensuring automated test runs never mutate or invalidate the operator's real ~/.konoha/web_auth.json. - OMP Auto-Enablement, Strict Schema Compliance & Advisor Continuity: src/omp_manager.js enforces strict $schema: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", bare executable paths (node, uvx, npx), and "type": "stdio". Auto-wired into initAgents() in src/agent_manager.js. Enforces host-native advisor review continuity (reviewMode: agent-end) after Konoha multi-agent workflows conclude. - Sleek Travelling Neon Focus Border Sweep & Glass Toasts: Replaced heavy multi-layer box shadows with an animated 1.5px travelling neon border sweep (@keyframes neonBorderSweep) using double-background clipping (padding-box, border-box) and ambient breathing pulse (@keyframes neonGlowPulse), standardizing input corner radius to 3px. Dynamic --theme-surface-glass powers glass-backdrop toasts with 4-gradient accent bars in ToastHost.svelte. - Clean Login Interface & Themed Focus Effects: Removed extraneous taglines from the login card, updated the passphrase input with lowercase passphrase label and themed lowercase badge tag default passphrase (konohagakure), 3px line size across all input effect fields, 4-gradient theme neon focus aura, and dynamically themed bottom-right alerts. - Outbound Webhook Engine (src/webhook_manager.js, konoha webhook ...): Supports full endpoint URLs with optional Bearer, API Key, JWT, or Custom Header authentication for external event notifications (task completion, health alerts). - Dynamic OMP Agent Session Detection: src/telegram/session_manager.js dynamically scans ~/.omp/agent/sessions/ for active OMP session files, eliminating phantom antigravity session misattribution when running inside OMP. - Active Sidebar Badge Neon Glow: Active menu badges on selected navigation links render a vibrant neon glow effect utilizing active 4-gradient tokens (var(--theme-grad-1), var(--theme-grad-2)) for high-contrast legibility in dark and light modes.

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Extract DPAPI-protected secrets such as credentials and browser data offline and online.

The English summary is being prepared. Showing the original description.

andycungkrinx91/konoha9Updated Oct 19, 2026

Audit, detect, and remediate Shadow Credentials misconfigurations on msDS-KeyCredentialLink in Active Directory. Focuses on access-controls, monitoring Event ID 5136, and credential-management hygiene.

The English summary is being prepared. Showing the original description.

andycungkrinx91/konoha9Updated Oct 19, 2026

Prepare a defense-contractor environment for CMMC Level 2 certification: scope CUI and FCI, implement the 110 NIST SP 800-171 Rev 2 security requirements across 14 families, compute the SPRS score with the DoD Assessment Methodology, manage a compliant POA&M, and ready the organization for a C3PAO assessment. Use when an organization handles Controlled Unclassified Information (CUI) under a DoD contract, when a contract carries DFARS clause 252.204-7012/7019/7020/7021, when preparing for or responding to a CMMC assessment, when computing or improving an SPRS score, when building a System Security Plan or POA&M for 800-171, or when scoping which systems are in the CUI boundary. Keywords: CMMC, CMMC Level 2, NIST 800-171, SP 800-171 Rev 2, CUI, FCI, SPRS, DFARS 7012, C3PAO, POA&M, System Security Plan, DoD Assessment Methodology, 110 controls, defense industrial base, DIB, FedRAMP equivalency.

The English summary is being prepared. Showing the original description.

andycungkrinx91/konoha9Updated Oct 19, 2026

Create forensically sound bit-for-bit disk images using dd and dcfldd while preserving evidence integrity through hash verification.

The English summary is being prepared. Showing the original description.

andycungkrinx91/konoha9Updated Oct 19, 2026

Detect dangerous ACL misconfigurations in Active Directory using ldap3 to identify GenericAll, WriteDACL, and WriteOwner abuse paths

The English summary is being prepared. Showing the original description.

andycungkrinx91/konoha9Updated Oct 19, 2026

Perform static analysis of Android APK malware samples using apktool for decompilation, jadx for Java source recovery, and androguard for permission analysis, manifest inspection, and suspicious API call detection.

The English summary is being prepared. Showing the original description.

andycungkrinx91/konoha9Updated Oct 19, 2026

See all skills by andycungkrinx91

Report a problem with this skill