konoha-mcp 2.2.23 → 2.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/NOTICE +38 -0
  2. package/README.md +3 -3
  3. package/apps/web/build/adapter-node.js +1 -1
  4. package/apps/web/build/build-meta.json +2 -2
  5. package/apps/web/build/client/_app/immutable/entry/{app.TYH87iYy.js → app.CKJ0NhrX.js} +2 -2
  6. package/apps/web/build/client/_app/immutable/entry/app.CKJ0NhrX.js.br +0 -0
  7. package/apps/web/build/client/_app/immutable/entry/app.CKJ0NhrX.js.gz +0 -0
  8. package/apps/web/build/client/_app/immutable/nodes/{0.D7dPIEWA.js → 0.7A6fQJ6z.js} +1 -1
  9. package/apps/web/build/client/_app/immutable/nodes/0.7A6fQJ6z.js.br +0 -0
  10. package/apps/web/build/client/_app/immutable/nodes/{0.D7dPIEWA.js.gz → 0.7A6fQJ6z.js.gz} +0 -0
  11. package/apps/web/build/client/_app/immutable/nodes/{13.TOXVaTBr.js → 13.CQB_Ed6W.js} +1 -1
  12. package/apps/web/build/client/_app/immutable/nodes/13.CQB_Ed6W.js.br +0 -0
  13. package/apps/web/build/client/_app/immutable/nodes/{13.TOXVaTBr.js.gz → 13.CQB_Ed6W.js.gz} +0 -0
  14. package/apps/web/build/client/_app/version.json +1 -1
  15. package/apps/web/build/client/_app/version.json.br +0 -0
  16. package/apps/web/build/client/_app/version.json.gz +0 -0
  17. package/apps/web/build/server/chunks/instance.js +3 -3
  18. package/apps/web/build/server/chunks/internal.js +1 -1
  19. package/apps/web/build/server/entries/pages/_layout.svelte.js +1 -1
  20. package/apps/web/build/server/entries/pages/_layout.svelte.js.map +1 -1
  21. package/apps/web/build/server/entries/pages/docs/_page.svelte.js +1 -1
  22. package/apps/web/build/server/entries/pages/docs/_page.svelte.js.map +1 -1
  23. package/apps/web/build/server/manifest-full.js +1 -1
  24. package/apps/web/build/server/manifest.js +1 -1
  25. package/apps/web/build/server/nodes/0.js +1 -1
  26. package/apps/web/build/server/nodes/13.js +1 -1
  27. package/apps/web/build/server/server.js +1 -1
  28. package/apps/web/package.json +1 -1
  29. package/bin/commands/bridge.js +62 -4
  30. package/bin/commands/doctor.js +2 -0
  31. package/bin/commands/doctor_services.js +57 -0
  32. package/bin/commands/init.js +16 -5
  33. package/bin/commands/init_clients.js +95 -8
  34. package/bin/lib/config_defaults.js +3 -0
  35. package/bin/lib/runtime_install.js +141 -54
  36. package/package.json +2 -1
  37. package/patches/gpt-tokenizer@4.1.0.patch +15 -0
  38. package/src/agent_contract.js +1 -1
  39. package/src/agent_deployer.js +48 -35
  40. package/src/agent_file_safety.js +57 -0
  41. package/src/bridge/gateway.js +2 -0
  42. package/src/bridge/gateway_adapters.js +155 -29
  43. package/src/bridge/handlers/anthropic.js +95 -26
  44. package/src/bridge/handlers/openai.js +18 -5
  45. package/src/bridge/sidecar/raw.js +10 -2
  46. package/src/bridge/stream_usage.js +66 -0
  47. package/src/client_commands.js +190 -0
  48. package/src/db_bridges.js +53 -7
  49. package/src/db_schema.js +11 -2
  50. package/src/file_tools_mcp.js +17 -9
  51. package/src/global_skill_sync.js +3 -1
  52. package/src/mcp/langgraph/edges/router.js +3 -0
  53. package/src/mcp/langgraph/index.js +22 -3
  54. package/src/mcp/langgraph/nodes/dispatch.js +3 -0
  55. package/src/mcp/langgraph/nodes/execute.js +87 -13
  56. package/src/mcp/langgraph/nodes/review.js +13 -1
  57. package/src/mcp/langgraph/slice_executor_registry.js +22 -0
  58. package/src/mcp/langgraph/state.js +5 -0
  59. package/src/mcp/lazy_subagent.js +11 -1
  60. package/src/mcp/memory_project_context.js +4 -1
  61. package/src/mcp/memory_subagent_runner.js +2 -1
  62. package/src/mcp/skills_common.js +1 -0
  63. package/src/mcp/subagent_spawner.js +7 -0
  64. package/src/mcp/todo_walkthrough_sync.js +7 -0
  65. package/src/mcp/tool_dispatch.js +16 -0
  66. package/src/mcp/workflow_completion_helpers.js +6 -1
  67. package/src/mcp/workflow_gates.js +118 -5
  68. package/src/mcp/workflow_sannin.js +9 -3
  69. package/src/mcp_tool_manifest.json +5 -1
  70. package/src/provider_usage_logger.js +92 -0
  71. package/src/schema_ddl.js +17 -1
  72. package/src/templates/AGENTS.md +1 -1
  73. package/src/templates/GEMINI.md +1 -1
  74. package/src/templates/skills/kage-skill/SKILL.md +1 -1
  75. package/src/templates/skills/konoha/SKILL.md +23 -165
  76. package/src/templates/skills/konoha/references/contract.md +1 -1
  77. package/src/templates/skills/konoha/references/peragent-usage.md +1 -1
  78. package/src/token_usage.js +57 -0
  79. package/src/tools_savings_logger.js +26 -8
  80. package/src/web/controllers/core_controller.js +10 -1
  81. package/src/workflow/jonin-builder/live_browser_monitor.js +23 -7
  82. package/apps/web/build/client/_app/immutable/entry/app.TYH87iYy.js.br +0 -0
  83. package/apps/web/build/client/_app/immutable/entry/app.TYH87iYy.js.gz +0 -0
  84. package/apps/web/build/client/_app/immutable/nodes/0.D7dPIEWA.js.br +0 -0
  85. package/apps/web/build/client/_app/immutable/nodes/13.TOXVaTBr.js.br +0 -0
  86. package/src/templates/skills/konoha/references/architecture.md +0 -99
  87. package/src/templates/skills/konoha/references/benchmark.md +0 -123
  88. package/src/templates/skills/konoha/references/docs.md +0 -46
  89. package/src/templates/skills/konoha/references/test.md +0 -71
  90. package/src/templates/skills/konoha/references/workflow.md +0 -104
@@ -1,99 +0,0 @@
1
- # 🍃 Konoha System Architecture & MCP Server Specifications (v2.2.23)
2
-
3
- Technical specification of the Konoha MCP Server architecture, 56 canonical tools, transport mechanisms, runtime state, parallel worktree isolation, Real-Time Idle `@advisor`, and dynamic website builder invariants.
4
-
5
- ---
6
-
7
- ## 🏛️ System Architecture Overview
8
-
9
- Konoha is a production-grade Model Context Protocol (MCP) orchestrator and multi-agent coordination server. It serves ALL 56 canonical tools through standard MCP protocols, reducing token consumption by 83%–98% across 8 AI coding clients:
10
- - **Antigravity IDE/CLI** (`~/.gemini/config/mcp_config.json`, hooks)
11
- - **Cursor IDE/CLI** (`~/.cursor/mcp.json`, `~/.cursor/rules/`)
12
- - **Claude Code** (`~/.claude.json`, `~/.claude/settings.json`)
13
- - **OpenCode** (`~/.config/opencode/opencode.json`)
14
- - **Command Code** (`~/.commandcode/mcp.json`)
15
- - **Codex** (`~/.codex/config.toml`, `~/.codex/AGENTS.md`)
16
- - **Pi (pi.dev)** (`~/.pi/agent/mcp.json` via the `pi-mcp-adapter` extension)
17
- - **OMP** (`~/.omp/agent/mcp.json`, `~/.omp/agent/AGENTS.md`)
18
-
19
- ---
20
-
21
- ## 🛠️ Canonical MCP Tools & Server Boundaries
22
-
23
- All 56 canonical MCP tools (plus 2 hidden deprecated compatibility aliases, 58 total in manifest) are formally declared in `src/mcp_tool_manifest.json` and dispatched via `src/mcp/tool_dispatch.js`:
24
-
25
- | Category | Tools | Primary Purpose |
26
- |---|---|---|
27
- | **Orchestration & Workflow** | `sannin`, `check_readiness`, `get_resolved_task_dir`, `report_from_agent`, `get_task_evidence`, `get_slop_findings`, `qa_codify`, `qa_e2e_run` | Request triage, LangGraph StateGraph execution, Real-Time Idle `@advisor` inspection, test codification, E2E runner. |
28
- | **Skill & Knowledge RAG** | `find_skill`, `get_skill`, `list_skills`, `use_skills`, `migrate_skills`, `optimize_report` | SQLite FTS5 RAG search merged with the project's own skill tree (`.agents/skills` + 16 siblings via `getSkillReadRoots`), compact multi-skill digest (`<= 6,400 bytes`), on-demand skill retrieval, token footprint analysis. `migrate_skills` adds ranking, not access. |
29
- | **Bounded File Operations** | `read_file_head`, `read_file_range`, `token_efficient_grep`, `file_info`, `get_file_structure`, `find_files_clean` | Bounded file I/O, token-capped grepping, symbol outline preview. |
30
- | **Native Code Intelligence** | `code_index`, `code_search`, `code_symbol`, `code_context`, `code_impact`, `code_related`, `code_status`, `code_remove` | In-process SQLite FTS5 code indexing, definition-first search, and symbol/impact graph. |
31
- | **Specialist Subagents** | `kage`, `jonin`, `anbu`, `chunin`, `tokubetsu_jonin`, `genin`, `akatsuki`, `yamanaka` | Direct invocation of the 8 specialist personas (`@sannin` is router-only). |
32
- | **Security & Auditing** | `akatsuki_init`, `anti_slop`, `docs_ai_detector`, `website_ai_detector` | Dual-mode red/blue security, Zero-AI-Slop audit, AI detection. |
33
- | **Document Engineering** | `document_create`, `spreadsheet_create`, `presentation_create`, `diagram_create`, `animation_export` | Native DOCX/PDF, XLSX, PPTX, SVG diagrams, and animated WebP exports. |
34
- | **Web & Research** | `web_search`, `build_from_text`, `build_from_source` | Live web research and dynamic website scaffolding specification generators. |
35
- | **Memory & Context** | `get_project_context`, `save_project_context`, `query_project_memory`, `save_persona_memory`, `query_persona_memory`, `list_persona_memories`, `delete_persona_memory`, `get_soul` | Project invariants, flow-bounded persona memories, and soul archetypes. |
36
-
37
- The `aislop_scan`, `aislop_why`, `aislop_fix`, and `aislop_baseline` tools are **not** Konoha tools. They are served by the separate Aislop MCP server, so they appear in no manifest row above and are absent from `src/mcp/tool_dispatch.js`; the 56-tool count is Konoha's own surface.
38
-
39
- ### Strict Tool Boundaries
40
- 1. **Repository Code Search**: ALWAYS use the native code intelligence tools (`code_search`, `code_symbol`, `code_impact`) with the absolute repository root. NEVER use native grep/find/cat or Konoha skill tools for code exploration.
41
- 2. **Skill Discovery**: ALWAYS use Konoha MCP (`konoha.find_skill`, `konoha.get_skill`, `konoha.use_skills`). NEVER search for skills with `code_search`.
42
- 3. **File Inspection**: ALWAYS use Konoha bounded tools (`read_file_range`, `read_file_head`, `token_efficient_grep`). Never execute raw shell `cat` or `grep`.
43
- 4. **Shell Execution**: ALWAYS prefix shell commands with `rtk <command>`.
44
-
45
- ### The Project Guardrail Is an Architecture Boundary, Not a Lint Rule
46
-
47
- `src/project_konoha_mcp_guardrail.js` evaluates every tool call and every shell command before it runs, and it can refuse. A refusal is a **branchable decision**, not a dead end:
48
-
49
- - **`GUARDRAIL_REMEDIATION`** maps each denial code to what the operator should do instead, so a denial never arrives as a bare "denied".
50
- - **`--hitl`** opens a menu on the *controlling terminal* (`/dev/tty`; `CONIN$`/`CONOUT$` on Windows) when stdin is a pipe, and records a code+tool-scoped risk acceptance with a TTL capped at one hour. Hooks never prompt — they stay fail-closed, and `KONOHA_GUARD_NO_TTY=1` can only force a block, never grant one.
51
- - **The exception store is an attack surface.** `.konoha/guardrail-exceptions.json` and `.konoha/guardrail-audit.jsonl` are writable only through `src/guardrail_exceptions.js`; any tool path that could write them is itself denied with a `NON_ACCEPTABLE_CODES` entry, which the menu refuses to accept. Some denials — secret write, destructive shell, retired IPC/MCP, store write — have no acceptable form at all.
52
- - **Every client binds through one spelling.** `src/mcp/hitl_picker.js` keys `claudecode` and `antigravity`, serves the web picker from the MCP process itself (port `ui_port + 1`), and never preselects an option.
53
-
54
- Guards: `tests/test_project_konoha_mcp_guardrail.js` tests 9-15, including a pty leg driven by `tests/helpers/pty_driver.py` that proves the CLI exits on its own.
55
-
56
-
57
- ### A Query Indexes What It Names, and Only on the Path That Can Afford It
58
-
59
- `code_search` used to answer `root not indexed: <path>` for any directory named for the first time, which is the normal state of a sibling project. `src/code_intel/auto_index.js` stats the directory and runs a lexical-only pass (`embed: false`, `maxFiles: 5000`, `timeoutMs: 15000`); `code_index` adds vectors later.
60
-
61
- - **Sync handlers index inline.** `resolveRoot` is one choke point, so `code_search`, `code_symbol`, `code_context`, `code_impact`, and `code_related` all inherit the behaviour.
62
- - **Async handlers never take the blocking pass.** `prepareSearchSetupAsync` and `_resolveAnchorAsync` await `indexRepositoryAsync` (yields every four files) before the sync base runs, which is what keeps `tools/list` answerable during a first-use index.
63
- - **`code_status` stays read-only.** It calls `store.getRoot`; indexing there would resurrect a root `code_remove` just cleared.
64
-
65
- A row is not proof of an index. `ensureRoot` inserts `stale` with `indexed_at NULL` *before* the walk, so a pass that timed out or threw leaves behind exactly the row every later query would trust — turning the old loud error into an empty result set. `isUsableRoot` therefore requires `fresh`, or `stale` with a completion time, and retries anything else; a `stale` row that a completed walk left partial is surfaced as `index_incomplete: true` rather than passing for a small repo. Only a writer may create a row: `@genin` and `@advisor` are read-only by role, `checkGeninToolAccess` guards `code_index` but not `code_search`, so the first-use pass is skipped for them (`KONOHA_READONLY=1` or the detected agent) and the caller gets the actionable error. Concurrent first-use queries on one root share a single pass through a module-level in-flight map, because the indexer holds no lock of its own.
66
-
67
- Guards: `tests/test_code_intel_tools.js` — the auto-index leg, an async leg that replaces `indexRepository` with a throwing stub, a never-finished-row leg, an `index_incomplete` leg, two read-only legs (`KONOHA_READONLY` and a detected `@genin`), and a dedupe leg that asserts three concurrent `code_search_async` calls reach the indexer once.
68
- ---
69
-
70
- ## 📡 Transports & Communications
71
-
72
- - **stdio**: Primary low-latency JSON-RPC transport for local IDE/CLI clients (Cursor, Claude Code, Antigravity, OpenCode, Command Code, Codex, Pi, OMP).
73
- - **SSE (Server-Sent Events)**: Web UI streaming events and real-time log dispatching.
74
- - **WebSocket (`port 1404`)**: Real-time bidirectional telemetry, status streaming, and remote client coordination. Note: the Yamanaka 3D Studio menu in the Web UI is hidden (`SHOW_3D_STUDIO_MENU = false`) and 3D controllers are lazy-loaded on demand with zero idle memory overhead.
75
-
76
- ---
77
-
78
- ## 🎨 Dynamic Konoha Website Builder Architecture (`v2.2.23`)
79
-
80
- When scaffolding or generating websites from text (`konoha.build_from_text`) or design mockups (`konoha.build_from_source`), `@jonin` executes a dynamic, context-driven design architecture across all supported frameworks (**Next.js, SvelteKit, Nuxt, Angular**):
81
-
82
- ### 1. Dynamic Astra/Fable-Inspired Composition (No Rigid Template)
83
- - **Context-Driven Layouts**: Every generated interface derives hero composition, typography scale, section rhythm, and interactive surfaces from the design brief. There is no fixed hero, carousel, or floating theme-widget preset.
84
- - **Brief-Derived Design**: `build_from_text`/`build_from_source` return a 9-field `design_brief` (product, industry, audience, primary_objective, user_outcome, information_architecture, interactions, visual_identity, technical_constraints) plus `inferred_domain_hints` across 16 domains. Art direction, IA, navigation pattern, theme count, and motion are derived from that brief — never from a fixed archetype map.
85
- - **Theme Strategy**: Semantic CSS custom properties (`--bg-canvas`, `--bg-surface`, `--text-primary`, `--text-muted`, `--border-subtle`, `--accent-primary`) defined per project with WCAG AA contrast; single or dual theme as the brief decides.
86
- - **Branding Scope**: Myōboku/Konoha branding applies only to the Konoha Web UI itself, never to generated client projects (which carry only the `Build by konoha` generator meta and footer signature).
87
-
88
- ### 2. Optional Figma & OpenDesign Dual-Mode Integration
89
- - **Mode A (Exported Design Files)**: `build_from_source` ingests mockup images (`.png`, `.jpg`, `.webp`, `.svg`) and design documents (`.fig`, `.pen`, `.json` token exports) with 100% layout fidelity.
90
- - **Mode B (Live MCP Sync)**: When `figma` or `opendesign` MCP servers are active, `@jonin` queries live frames and design tokens directly.
91
-
92
- ### 3. Real-Time Auto-Open Browser Monitor & Project Maintenance Skill
93
- - **Live Browser Monitor (`src/workflow/jonin-builder/live_browser_monitor.js`)**: Automatically opens the user's system browser (`xdg-open`, `open`, `start`) during dev server verification and audits responsive viewports (`375x812`, `768x1024`, `1440x900`), zero console errors, and zero emojis.
94
- - **Automatic Project Skill Generator (`src/workflow/jonin-builder/project_skill_generator.js`)**: Generates `<project_path>/.agents/skills/<project-slug>-frontend-maintenance/SKILL.md` after frontend generation and indexes it into `konoha.db` (`skills`, `skills_fts`, `skill_chunks`) isolated by `project_hash`.
95
-
96
- ### 4. Mandatory Konoha Brand Signature & Quality Gates
97
- - **Generator Signature**: Every generated website MUST include `<meta name="generator" content="Build by konoha">` in `<head>` and render the exact visible text `Build by konoha` in `<footer>` (exempted from AI-fingerprint penalties in `src/workflow/jonin-builder/ai_detector.js`).
98
- - **Zero-Emoji Policy**: Strictly zero emojis or emoticons in UI controls, headings, or body copy. Use crisp SVG vector icons (`@phosphor-icons/*` or `@radix-ui/react-icons`).
99
- - **Mandatory Package Scripts**: Every generated project's `package.json` must define `"dev"`, `"lint"`, `"build"`, `"start"`, and `"test"` (plus `"check"` for SvelteKit), passing cleanly with 0 errors and 0 warnings.
@@ -1,123 +0,0 @@
1
- # 🍃 Konoha Token Economy & Benchmark Standards (v2.2.23)
2
-
3
- Technical reference on Konoha's token economy, compact multi-skill digests (`use_skills`), Real-Time Idle `@advisor` budget (`<= 8,192 tokens/turn`), dynamic baseline savings calculations, SQLite FTS5 benchmark metrics, and KV-cache prefix optimization.
4
-
5
- ---
6
-
7
- ## 📉 Context Token Economy & Savings Architecture (`v2.2.23`)
8
-
9
- Konoha delivers an authentic **83%–98% token reduction** across all 8 supported AI coding clients:
10
- 1. **Compact Multi-Skill Digest (`use_skills` <= 6,400 Bytes / <= 1,600 Tokens)**:
11
- - Direct subagent invocations (e.g. `@genin` or `@anbu` loading 5 skills including `i-have-adhd` and `antislop*`) compile a structured, budget-governed digest (`~5,093 bytes` / `1,274 tokens` on Turn 1, and `~2,818 bytes` / `705 tokens` on repeat turns via session deduplication), down from `48,604 bytes` (`~12.1k tokens`) — an **89.5%–94.2% reduction** while keeping every discipline skill active.
12
- 2. **Real-Time Idle `@advisor` Budget (`<= 8,192 Tokens` / Turn)**:
13
- - Consumes **`0` tokens** when workers are idle or compliant (`status: 'IDLE_OK'`), and enforces a **`<= 8,192 tokens` (`32,768 bytes`)** ceiling when emitting an `INTERRUPT_CORRECTION` directive, with Head+Middle+Tail context preservation (`src/context_budget.js`) so intermediate plan rules, TODOs, and goals are never dropped, plus immediate stale telemetry eviction (`evict_stale_results: true`).
14
- 3. **Post-Approval Context Compaction**:
15
- - Approving Gate 1 (`1. Compact and approve`) automatically prunes pre-approval exploratory dumps and compacts `plan.md` before Phase 2 execution begins.
16
-
17
- ---
18
-
19
- ## 🧱 Fixed-Prefix Budget: What Konoha Injects on Every Turn
20
-
21
- Every supported harness prepends a fixed block before the first user token. Konoha controls three of its terms — the managed contract block, the OMP workflow addendum, and the MCP tool schemas — and a cache hit only survives while those bytes stay identical between turns.
22
-
23
- | Term | Deployed size | Rule |
24
- |---|---|---|
25
- | `~/.omp/agent/AGENTS.md` (OMP user context) | ~5.5 KB | exactly one managed block, exactly one contract version |
26
- | OMP workflow addendum (`buildOmpWorkflowAddendum`) | ~4.1 KB | rules only; command dumps and procedure belong to the skill that owns them |
27
- | Lightweight contract (`buildLightweightContract`) | ~1.0 KB per foreign client file | version bump only; the body does not vary by client |
28
- | Tool schemas (`src/mcp_tool_manifest.json`) | 28,986 B / 6,598 tok | an API contract — prose trimming moves ~1.6k of 6.6k tokens, and the remaining ~5.0k is JSON structure; only tool-count reduction moves it materially |
29
-
30
- 1. **One managed block, one version.** `buildManagedContract` (`src/agent_contract.js`) removes *every* `KONOHA-CONTRACT-START`…`KONOHA-CONTRACT-END` span before writing the fresh block. Splicing only the first pair left any second block in place forever and made redeploy a permanent no-op; a deployed file once carried 2.2.23 and 2.2.12 side by side, so the agent read two versions of the same rules on every turn.
31
- 2. **Only one user-level context file is injected.** OMP keeps one user context file and `native` (`~/.omp/agent/AGENTS.md`) wins it, so `~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md`, `~/.config/opencode/AGENTS.md`, and `~/.agents/AGENTS.md` are not part of an OMP prompt. Each serves its own harness; never assume the contract is read twice.
32
- 3. **`~/.omp/AGENTS.md` is not a context file.** The native user location is `~/.omp/agent/AGENTS.md`. `~/.omp/AGENTS.md` sits in a dot-directory with no provider mapping, so it is never injected — keeping a copy there is a trap for a future release, not a saving.
33
- 4. **Duplicated procedure costs twice.** Framework scaffolding commands and scan-scoping procedure were once in both the addendum and `jonin-skill` / `konoha` references. The skill loads on demand; the addendum is paid every turn. Procedure belongs in the skill.
34
- 5. **Byte-stability beats brevity.** A block that changes size or order between turns loses the cache for everything after it. Deploying the same contract twice must be byte-identical — `tests/test_lightweight_contracts.js` asserts the second deploy reports `changed: false`.
35
-
36
- ### Honest Limit: Konoha Cannot Report Its Own Cache Hit Rate
37
-
38
- `tool_calls` carries `input_tokens`, `output_tokens`, and `cached_tokens` (`src/db_schema.js`), but nothing on the MCP path writes them: the only usage objects built live in `src/bridge/gateway_adapters.js` and `src/bridge/handlers/anthropic.js`, and they return those counts to the caller instead of persisting them. Every row's token columns are NULL, so any cache-hit figure attributed to Konoha is inference from payload sizes, never measurement. Fix the writer before quoting a number.
39
-
40
- ---
41
-
42
- ## 🧮 Dynamic Token Savings Telemetry (`src/tools_savings_logger.js` & `src/mcp/skills_common.js`)
43
-
44
- Konoha computes authentic token savings on every MCP tool call, persisting records into `tool_calls` inside `~/.konoha/konoha.db`:
45
-
46
- ### 1. Skill Discovery & Multi-Skill Retrieval (`find_skill`, `use_skills`, `get_skill`)
47
- - **`use_skills` Baseline Bytes**: Dynamically queries the exact `SUM(byte_size)` of all requested skills from the `skills` table in `konoha.db` (`_getUseSkillsBaselineBytes` in `src/mcp/skills_common.js`).
48
- - **`find_skill` Baseline Bytes**: Dynamically computed from the actual `SUM(byte_size)` of matching skill candidates in SQLite FTS5.
49
- - **Formula**:
50
- $$\text{Bytes Saved} = \max(0, \text{Baseline Bytes} - \text{Returned Bytes})$$
51
- $$\text{Tokens Saved} = \left\lfloor \frac{\text{Bytes Saved}}{4} \right\rfloor$$
52
- - **Invariant**: Baseline calculation logic in `src/tools_savings_logger.js` and `src/db_savings.js` must never be fabricated or hardcoded; `konoha savings` always reports real, verifiable telemetry.
53
-
54
- ### 2. Bounded File Inspection Tools (`read_file_head`, `read_file_range`, `token_efficient_grep`)
55
- - **Baseline Bytes**: Total byte size of the target file on disk (`fs.statSync(file).size`).
56
- - **Returned Bytes**: The bounded line window or matching snippet returned.
57
- - **Savings Ratio**: Consistently > 98% savings on large codebases.
58
-
59
- ---
60
-
61
- ## 🔍 Chunk Store vs Append-Only Log: Why Retrieval Beats Injection
62
-
63
- The question is not "FTS5 or JSONL" but *inject everything* vs *retrieve chunks on demand*.
64
- Konoha has exactly one retrieval store (`skill_chunks`: FTS5 + embeddings) and JSONL
65
- appears only as an audit trail (`.konoha/guardrail-audit.jsonl`, client `transcript.jsonl`),
66
- with no relevance signal and no bounded read. Chunked retrieval wins on both axes:
67
-
68
- | Property | FTS5 chunk store | JSONL append log |
69
- |---|---|---|
70
- | Cost of one answer | `O(top-k)` — ranked, bounded | `O(file)` — every line read and injected |
71
- | Relevance signal | BM25 + cross-encoder + vector | none (append order only) |
72
- | Failure mode | stale row → reindex | unbounded context growth |
73
- | Measured here | 6,382 rows, avg 556 B, all embedded | no retrieval path exists |
74
-
75
- **Measured chunk economics** (`src/code_intel/config.js`): `CHUNK_MAX_LINES=40`,
76
- `CHUNK_MAX_CHARS=1800`, `CHUNK_OVERLAP_LINES=8`, `CHUNK_TOKEN_TARGET=420` — 6,382 rows
77
- across 285 skills, avg 556 B, all embedded. `skill_top_k: 5`, `skill_candidate_k: 25`
78
- (`bin/lib/config_defaults.js:61-62`). A `find_skill` answer measures **301–439 tok**
79
- across five probe queries because it returns ranked metadata rows, not chunk text; the
80
- chunk budget is what `use_skills`/`get_skill` spend. One full skill digest is **1,956 tok**,
81
- so retrieval already wins the moment the task needs to consult more than one skill.
82
-
83
- **External evidence** (the accuracy half of the question, not just cost):
84
- - *Context Length Alone Hurts LLM Performance Despite Perfect Retrieval* (EMNLP 2025 Findings 1264): accuracy drops **13.9%–85%** as input length grows even with the gold passage present. Long context is a quality hazard, not only a bill.
85
- - *SELF-ROUTE* (EMNLP 2024 Industry 66, Google DeepMind): long context wins on average quality when resourced, but RAG's cost advantage is decisive; the hybrid route matches long-context quality at far lower cost.
86
- - arXiv 2505.21700: **64–128 tok** chunks are optimal for fact-based QA, **512–1024 tok** for broad contextual understanding — Konoha's 420-token target sits between the two regimes, correct for procedure-heavy skills.
87
- - NVIDIA chunking study: page-level chunks give the best mean end-to-end accuracy (**0.648**) and the lowest variance (**0.107**); both extremes (128, 2048 tok) underperform; **15% overlap** is the sweet spot (Konoha: 8/40 lines = 20%).
88
-
89
- **Boundary that used to defeat this**: `get_skill(name, {tokenBudget})` with no `section`
90
- sliced to `rawSections[0]` — the frontmatter plus preamble — and returned ~250 tok for a
91
- 1,500-token request. A budget now produces a whole-document digest with head/middle/tail
92
- anchors and lists the top-level sections still available. Covered by
93
- `tests/test_skill_budget_digest.js`.
94
-
95
- **Known ceiling**: the cap decides the cost, not the request. `get_skill({section: 'Cardinal
96
- Maintenance Invariants'})` returns **7,854 B / 1,932 tok** and the full digest returns
97
- **7,927 B / 1,956 tok** — 1.2% apart, because `MAX_CONTENT_SIZE` (8,000 B) is smaller than the
98
- section. That section is **19,410 B / 4,985 tok**, 48.5% of the 40,039 B document, so the
99
- section request silently drops 60% of the one section a maintainer most needs, and the
100
- remaining-sections hint cannot help because there is only one section in play. A caller
101
- asking for three invariants pays for eight thousand bytes. The upgrade path is invariant-level
102
- chunking — one numbered item per chunk, 400–600 tok — so a caller can buy the three rules it
103
- needs; the `konoha` skill already has `skill_chunks` rows in the index (avg ~820 B) that a section
104
- request never consults — `src/mcp/skills_retrieval.js` reads the file, not the table.
105
-
106
- ---
107
-
108
- ## ⚡ SQLite FTS5 Benchmark & Query Performance
109
-
110
- | Operation | Workload / Ops | Throughput | Latency (p95) | Mechanism |
111
- |---|---|---|---|---|
112
- | **FTS5 Skill Search (`skills`)** | 500 ops | **> 25,000 queries/sec** | **< 0.04 ms** | In-process relational + BM25 ranking |
113
- | **Persona Memory Recall** | 500 ops | **> 28,000 queries/sec** | **< 0.03 ms** | Indexed flow-bounded key-value recall |
114
- | **Tool Call Logging** | 1,000 ops | **> 32,000 writes/sec** | **< 0.03 ms** | SQLite WAL mode (`PRAGMA synchronous = NORMAL`) |
115
- | **Neural Hybrid RAG** | 100 ops | **> 1,200 queries/sec** | **< 0.82 ms** | FTS5 BM25 + Granite ONNX embeddings |
116
-
117
- ---
118
-
119
- ## 📊 Verification & Telemetry Commands
120
-
121
- - View live session savings: `rtk node bin/cli.js savings`
122
- - Verify compact `use_skills`: `rtk node tests/test_use_skills_compact.js`
123
- - Verify database performance: `rtk node tests/test_db_consolidation.js`
@@ -1,46 +0,0 @@
1
- # 🍃 Konoha Documentation Maintenance Standard (v2.2.23)
2
-
3
- Guidelines and requirements for authoring, updating, and synchronizing Konoha `v2.2.23` documentation, compliance records, Draw.io diagrams, and visual assets.
4
-
5
- ---
6
-
7
- ## 📁 Documentation Architecture & Directory Structure
8
-
9
- Every topic has exactly one live document. `docs/README.md` is the live index: open it first and follow the row for the topic you need instead of guessing a filename.
10
- - `README.md`: Executive entry point, quick start (`konoha init --client=<name>`), 9-agent roster (`@sannin` router + 8 specialists), 56 canonical MCP tools, LangGraph + Real-Time Idle `@advisor` + Git Worktree architecture, and security badges.
11
- - `CHANGELOG.md`: Authoritative chronological release notes following Keep a Changelog format.
12
- - `docs/README.md`: Live index of every current document, grouped by topic keys (architecture, security, setup, data, assets, conventions). It is the only place the document set is enumerated — never restate the count elsewhere, it drifts.
13
- - `docs/ARCHITECTURE.md`: Technical architecture specification, LangGraph StateGraph engine, Real-Time Idle `@advisor` (`<= 8,192 tokens/turn`), Per-Agent Git Worktree isolation, MCP transports, and dynamic website builder specs.
14
- - `docs/SECURITY.md`: Current security architecture, ingress controls, and auth model for `v2.2.23`.
15
- - `docs/ALL-WORKFLOW-DIAGRAMS.md`: Comprehensive Mermaid diagram catalog of all system workflows.
16
- - `docs/QA-TEST-CHECKLIST.md`: Full QA testing matrices, manual verification procedures, and release verification checklists.
17
- - `docs/MANUAL.md` + `docs/MANUAL.pdf`: The operator's manual. The PDF is generated (`node scripts/build_manual_pdf.js`), never hand-edited, and must be newer than the Markdown it was built from (`tests/test_manual_book.js`).
18
- - `docs/CI.md`: Cross-platform workflow, `act` and Windows-VM local mirrors, browser provisioning, and the engine capability split. Platform-specific defects belong here as reproduction steps, not as prose in the changelog.
19
- - `docs/TROUBLESHOOTING.md`: Symptom → cause → fix, with platform-specific sections. New failure modes observed in QA go here, not into `CHANGELOG.md`.
20
- - `docs/SecurityCompliance/`: Holds a single file, the newest dated external audit (`security_compliance_report_2.2.23_2026-11-17.md`). It is a dated record, not the security reference; current controls live in `docs/SECURITY.md`. Earlier reports are archived under `docs/archive/security-compliance/`.
21
- - `docs/archive/`: Frozen dated reports and finished reviews, one directory per topic. `docs/archive/README.md` indexes them and states the keep-or-archive rule. A live document never links into `docs/archive/`.
22
- - `docs/architecture/`: Canonical specifications (`CANONICAL-API.md`, `CANONICAL-CLI.md`, `CANONICAL-NAMING.md`, `CAPABILITY-MAP.md`, `ARCHITECTURAL-GAPS.md`, `TOKEN-BASELINE.md`).
23
- - `docs/security/`: Database isolation, schema, red-skill, and skill-authz inventories.
24
- - `docs/diagrams/`: Draw.io XML source files (`konoha-architecture.drawio` — 19 pages, `konoha-infrastructure-architecture.drawio` — 18 pages, 0 geometric collisions).
25
- - `docs/templates/`: Client configuration templates (`claude-code.mcp.yaml`).
26
- - `assets/`: Production animated WebP diagrams and demo walkthroughs (zero legacy `.gif` files). `tests/test_all_assets_webp.js` owns the canonical 34-asset list — read the count from it, never from prose.
27
-
28
- ---
29
-
30
- ## 📝 Tone, Anti-Slop & Zero-AI Fingerprint Standard
31
-
32
- All documentation authored or updated by Konoha subagents (especially `@tokubetsu-jonin`) must strictly adhere to Reader-First Craftsmanship standards:
33
- 1. **Zero Conversational Filler**: Never use conversational padding, artificial hesitation, or pleasantries (`"hmmmm"`, `"let me"`, `"wait - but"`).
34
- 2. **High Perplexity & Natural Burstiness**: Vary sentence length dynamically. Use active verbs, direct declarative statements, and concrete numbers over vague generalities.
35
- 3. **No Legacy IPC References**: Active documentation must never instruct agents to use retired file-based IPC (`prompt.md`, `report.md`, `delegate.md`, `result.md`). All delegation uses structured MCP arguments and isolated `task_dir` state (`status.json`, `plan.md`, `walkthrough_todos.json`, `final_report.md`).
36
- 4. **Strict < 3.0% AI Detection Threshold**: Shipped engineering whitepapers, compliance audits, and architectural reports must score below 3.0% on `docs_ai_detector`.
37
-
38
- ---
39
-
40
- ## 🔄 Verification Commands
41
-
42
- - Verify version synchronization across all 18 targets: `rtk node tests/test_version_consistency.js`
43
- - Verify documentation symbol currency: `rtk node tests/test_docs_currency.js`
44
- - Verify the live index covers every live document and no archived one: `rtk node tests/test_docs_index.js`
45
- - Verify Draw.io zero collisions across all 19 architecture pages: `rtk node tests/test_diagram_sync.js`
46
- - Verify all 34 animated WebP assets and 109 active markdown embeds: `rtk node tests/test_all_assets_webp.js`
@@ -1,71 +0,0 @@
1
- # 🍃 Konoha QA Testing & Verification SOPs (v2.2.23)
2
-
3
- Operational runbook and testing matrix for verifying Konoha `v2.2.23` core engines, compact `use_skills`, parallel subagent spawning, Real-Time Idle `@advisor`, HITL post-approval compaction, Jonin dynamic frontend builder, Draw.io diagrams, and animated WebP assets.
4
-
5
- ---
6
-
7
- ## ▶️ How to Run
8
-
9
- | Gate | Command | Scope |
10
- |---|---|---|
11
- | **1. Linux — Debian container sandbox (mandatory)** | `pnpm test:sandbox` (or `pnpm test:sandbox -- --shard=I/8`) | Builds `konoha-sandbox:local` (Debian Bookworm) and runs install, lint, the full suite (or shard `I/8`), and the fresh-install smoke inside it. Host `HOME`, `/tmp`, `node_modules`, and working tree stay untouched. `--lint` is the fast path, `--no-build` reuses the last image. |
12
- | **1b. Linux — Ubuntu `act` CI workflow** | `pnpm ci:act` / `pnpm ci:act:shard` | `act` against `.github/workflows/cross-platform.yml` (`ubuntu-latest` → `catthehacker/ubuntu:act-latest` in `.actrc`). `ci:act` runs `checks` (lint + smoke); `ci:act:shard` runs suite shard 1 (pass `--matrix shard:<N>` for others). |
13
- | **2. Windows — Local `dockur/windows` QEMU VM** | `docker/windows-vm/oem/run-ci.cmd [-Shard I/N]` / `retest.cmd` | Drives `scripts/windows-ci.ps1` inside the Windows 11 guest (`docker/windows-vm/compose.yml`), mirroring `windows-latest` step-for-step over local NTFS `C:\konoha` (install, Playwright, web build, `libwebp_anim`, lint, suite/shard, smoke). The guest runs the **full suite in one pass by default** — the CI matrix's 16 Windows shards exist to spread work across 16 separate runners, and splitting one 4 GB guest only repeats install and seed per shard. Pass `-Shard I/N` to narrow a single failure, not to reproduce the matrix. |
14
- | **3. macOS — Apple `container` sandbox + native CI** | `KONOHA_SANDBOX_RUNTIME=container pnpm test:sandbox [-- --shard=I/8]` | Same image and mounts through [apple/container](https://github.com/apple/container) on Apple silicon (macOS 26, `container system start`), no Docker Desktop needed (`--memory 4g`, `KONOHA_SANDBOX_MEMORY` overrides). Boots a Linux guest, so macOS-native `/var` → `/private/var`, APFS, and `.dmg` behaviour is covered by `macos-latest` CI (`docs/CI.md`). |
15
- | **Full suite directly on host** | refused | `tests/run_all.js` exits 1 before discovery unless `KONOHA_SANDBOX_CONTAINER=1` or `CI=true` is set. `rtk node tests/run_all.js` refuses identically — the guard reads the process environment, and RTK only rewrites argv. A single file by path still runs and is still not evidence. |
16
-
17
- `tests/run_all.js` auto-discovers every `tests/test_*.js`, builds one golden seed, and copies it per suite with `HOME`, `USERPROFILE`, and `KONOHA_DB_PATH` redirected at that copy, so a suite never reads the developer's real config. A suite that needs the developer's environment is a defect in the suite, not a reason to relax it.
18
-
19
- ### The guard is enforced in-process, not by convention
20
-
21
- `tests/run_all.js` calls `assertMaintenanceSandbox()` before it discovers a single suite. It refuses
22
- unless the process carries `KONOHA_SANDBOX_CONTAINER=1` (set by `scripts/sandbox.js` on the container
23
- argv) or runs on an ephemeral CI runner (`CI=true`). A host invocation exits 1 with the accepted
24
- command named, so a maintenance run cannot half-execute against the developer's `~/.konoha`.
25
-
26
- `rtk` does not lift the guard: it rewrites argv, and the check reads this process's environment. `rtk
27
- node tests/run_all.js` refuses exactly like `node tests/run_all.js`. Pointing `HOME` at a temp directory
28
- does not lift it either — an isolated `HOME` is what the runner already gives each suite, not evidence
29
- that the run is sandboxed. `tests/test_sandbox_guard.js` and `tests/test_runner_isolation.js` pin all
30
- three properties.
31
-
32
- Linux, macOS, and Windows all go through the container. A host has a real `konoha` installed globally, a populated `~/.konoha`, and a client config; the sandbox mount is read-only, `HOME` is container-local, and `KONOHA_TEST_SANDBOX=1` stops `reconcileGlobalCommand()` from writing a shim, so a maintenance run cannot modify the install a developer actually uses. macOS keeps a second native pass because the container is a Linux guest and cannot reproduce APFS or `/var` canonicalization.
33
-
34
- ---
35
-
36
- ## 🧪 Comprehensive QA Verification Matrix (`v2.2.23`)
37
-
38
- | Verification Target | Command | Expected Pass Criteria |
39
- |---|---|---|
40
- | **Version Consistency** | `rtk node tests/test_version_consistency.js` | 18/18 managed repository targets strictly verified at `v2.2.23`. |
41
- | **Compact `use_skills` & Discipline Skills** | `rtk node tests/test_use_skills_compact.js` | 5-skill bundle `<= 6,400 bytes` (`genin=5093B`, `dedup=2818B`, `anbu=5239B`), all 8 specialists retain `i-have-adhd` & `antislop`. |
42
- | **8 Subagents Spawn, Parallel & `/konoha`** | `rtk node tests/test_langgraph_parallel_and_konoha.js` | All 8 specialists spawn across all 8 clients, `@sannin` router-only, parallel workstreams & `/konoha` LangGraph routing verified. |
43
- | **Spawn Harness Contracts** | `rtk node tests/test_spawn_harness_contracts.js` | 16/16: OMP/Pi identity from the state directory, `omp` argv and `task` schema (no repeated `context`, no `cwd`), harness-binary probing with the execute-bit/`PATHEXT` filter, CLI and parallel fallbacks, Windows `.cmd` route and `taskkill /T` tree kill. |
44
- | **Agent Deploy Safety** | `rtk node tests/test_deploy_safety.js` | A legacy contract-managed agent upgrades in place instead of parking as `.konoha-proposed`; user-authored files still get `.konoha-backup` + a candidate; a superseded candidate is removed. |
45
- | **OMP Config Isolation** | `rtk node tests/test_omp_manager.js` | A temporary-home run leaves the project `.omp/mcp.json` byte-identical; agents deploy with `generated_by: konoha` and the current contract version. |
46
- | **Real-Time Idle `@advisor` (`<= 8k` tok)** | `rtk node tests/test_advisor_realtime_monitor.js` | `0 tokens` when idle (`IDLE_OK`), `<= 8,192 tokens` (`32,768 bytes`) cap, `evict_stale_results: true`, `INTERRUPT_CORRECTION` on drift/breach. |
47
- | **HITL Compaction & Native TODOs** | `rtk node tests/test_hitl_compaction_and_todos.js` | Native TODO tools across all 8 clients, `walkthrough_todos.json` written, Gate 1 Option 1 compacts context. |
48
- | **Jonin Dynamic Design & Watermark** | `rtk node tests/test_jonin_dynamic_design_and_watermark.js` | 3D Studio menu hidden (`SHOW_3D_STUDIO_MENU = false`), `Build by konoha` meta/footer verified with 0 AI-detector penalty, live browser monitor & project skill generator verified. |
49
- | **Worktree Isolation & Merge Barrier** | `rtk node tests/test_worktree_isolation.js` | 16/16 worktree isolation, syntax gate, and parallel barrier tests pass. |
50
- | **E2E Install, Upgrade & Token Bounds** | `rtk node tests/test_e2e_install_upgrade_reinstall.js` | Fresh install, upgrade, reinstall, and bounded payloads (`runSannin < 3.4KB on the worst of 10 clients`, `build_from_text < 25KB`) pass with 100% parity. |
51
- | **Documentation Currency** | `rtk node tests/test_docs_currency.js` | Zero drift between exported code symbols and markdown documents. |
52
- | **Draw.io Diagram Collisions** | `rtk node tests/test_diagram_sync.js` | All 19 drawio pages verified with strictly **0 geometric collisions** (0 penetrations, 0 crossings, 0 overlaps), plus 18 infrastructure pages, 9-agent roster parity on both routing pages, and version labels matching `package.json`. |
53
- | **Animated WebP Assets** | `rtk node tests/test_all_assets_webp.js` | All 34 WebPs valid, 0 legacy `.gif` files, 109 active markdown files with 0 broken embeds. |
54
- | **Backend Static Linter** | `rtk node scripts/lint.js` | All JavaScript/Svelte files verified under 700 lines with **0 errors and 0 warnings**. |
55
- | **Zero-AI-Slop Code Hygiene** | `rtk npx aislop scan --changes` | Score **100 / 100 Healthy**, 0 errors, 0 warnings, 0 fixable. |
56
- | **MCP Orphan Guard** | `rtk node tests/test_mcp_orphan_guard.js` | 5/5 on POSIX: a reparented stdio server exits on the `ppid === 1` poll (T2), a superseded daemon exits on `bridge.pid` takeover (T3), a daemon starting behind a live owner exits (T4), and the idle budget exits a silent server (T1, T5). Windows never reparents, so T2 prints a skip there and the idle budget is the Windows exit (T1/T5 still run). |
57
- | **Web UI Manual-Only + Single Instance** | `rtk node tests/test_ui_manual_only.js` | 29/29: the dispatcher exposes only `start`/`build`, no module in the init/upgrade/bootstrap path references autostart, and a second `start` on a live port exits non-zero with `already running`. Needs no seeded `HOME`. |
58
- | **Project Guardrail: Denial Is Branchable** | `rtk node tests/test_project_konoha_mcp_guardrail.js` | 15/15: every denial code carries remediation, an accepted risk is code+tool scoped with a capped TTL, an expired entry is pruned, a tool call cannot write the exception store, and a **real pty leg** (`tests/helpers/pty_driver.py`) proves the CLI prompts on the controlling terminal and then exits on its own — 1.6 s, no driver kill. |
59
- | **Database Salvage Names Its Reason** | `rtk node tests/test_db_recovery.js` | A `sqlite_master` row no build can parse is neutralised (probe differs in exactly two bytes, `;` → `--`) instead of sinking the salvage; a rejected table does not sink its siblings; a failed salvage returns `{ ok: false, reason }` rather than `undefined`. |
60
- | **Per-Turn Prefix Budget** | `rtk node tests/test_lightweight_contracts.js` | Every tracked contract file `< 1800 B`; OMP addendum `<= 4200 B` and managed contract `<= 5200 B`; the five load-bearing rules survive; no framework-scaffolding command in the addendum; a second deploy reports `changed: false`. |
61
- | **Skill Tree Parity** | `rtk node tests/test_skill_tree_parity.js` | The tracked `.agents/skills` mirror matches `src/templates/skills` byte-for-byte and the cursor runtime mirror resolves. The deployed `~/.agents/skills` comparison is **opt-in** (`KONOHA_TEST_SKILL_PARITY_HOME=1`, set by `tests/run_all.js`) so a release gate never reads ambient machine state. |
62
-
63
- ---
64
-
65
- ## 📐 Draw.io Zero-Collision Rule & Sync SOP
66
-
67
- When editing `docs/diagrams/konoha-architecture.drawio` or `docs/diagrams/konoha-infrastructure-architecture.drawio`:
68
- 1. **Never alter existing `mxGeometry` coordinates** unless doing a dedicated layout refactor.
69
- 2. Edit the `value="..."` attribute of existing cells in-place to keep 0 geometric collisions.
70
- 3. Every cell MUST have a globally unique `id="..."`.
71
- 4. Validate immediately with `rtk node tests/test_diagram_sync.js`.
@@ -1,104 +0,0 @@
1
- # 🍃 Konoha LangGraph.js Production StateGraph Workflow (v2.2.23)
2
-
3
- Technical specification and operational guide for the LangGraph.js cyclic StateGraph orchestration engine, parallel git worktree execution, Real-Time Idle `@advisor` worker guard, native walkthrough/TODO synchronization, per-turn token budget governor, and HITL gates.
4
-
5
- ---
6
-
7
- ## 🏗️ StateGraph Architecture Overview
8
-
9
- In Konoha `v2.2.23`, all multi-step engineering tasks and `/konoha <prompt>` invocations run on a compiled, cyclic LangGraph.js StateGraph (`src/mcp/langgraph/index.js`) with persistent SQLite checkpoints via `KonohaCheckpointSaver`.
10
-
11
- ### Dual-Track Execution Model
12
- 1. **Branch B (Fast-Track / Single-Slice Tasks)**: Direct single-domain requests or slash shortcuts (`/jonin`, `/anbu`, `/genin`, etc.) dispatch with a compact delegation envelope (`< 3.4KB` router payload on the worst of 10 clients) and client-native `spawn_directive`.
13
- 2. **Branch A (Full SDLC & Parallel Multi-Agent Pipeline)**: Multi-step engineering and `/konoha` workflows traverse the cyclic StateGraph with parallel git worktree isolation, Real-Time Idle `@advisor` monitoring, native TODO/walkthrough synchronization, and Kage 98% governance.
14
-
15
- ---
16
-
17
- ## 🔄 Graph Topology & Node Lifecycles
18
-
19
- ```
20
- ┌──────────────┐
21
- │ classifyNode │
22
- └──────┬───────┘
23
- │
24
- ┌──────▼───────┐
25
- │ planNode │
26
- └──────┬───────┘
27
- │
28
- [Gate 1: pending_plan_approval] ◄─── HITL Gate 1 + Post-Approval Compaction
29
- │
30
- ┌──────▼───────┐
31
- │ briefNode │
32
- └──────┬───────┘
33
- │
34
- ┌──────▼───────┐
35
- │ todoNode │ ───► Syncs Native Walkthrough & Client TODOs
36
- └──────┬───────┘
37
- │
38
- ┌─────────────┴─────────────┐
39
- │ │
40
- ┌──────▼───────┐ ┌──────▼───────┐
41
- │ dispatchNode │ ◄───────── │ remediateNode│ (slop_cycles <= 7)
42
- └──────┬───────┘ └──────▲───────┘
43
- │ (Parallel Worktrees + │
44
- │ Real-Time Idle @advisor) │
45
- ┌──────▼───────┐ │ (remediate)
46
- │ executeNode │ │
47
- └──────┬───────┘ │
48
- │ (3-Way Worktree Merge) │
49
- ▼ │
50
- [status.phase = 'document', assigned = 'tokubetsu-jonin']
51
- │ │
52
- ┌──────▼───────┐ │
53
- │ reviewNode │ ──────────────────┘
54
- └──────┬───────┘ (100/100 aislop & >= 98% confidence)
55
- │
56
- [Gate 2: pending_human_signoff] (or auto_signoff: true)
57
- │
58
- ┌──────▼───────┐
59
- │ completeNode │ ──► __end__
60
- └──────────────┘
61
- ```
62
-
63
- ### Node Responsibilities
64
- - **`classifyNode`** (`src/mcp/langgraph/nodes/classify.js`): Strips `/konoha` and `@sannin` prefixes, evaluates prompt intent (`'fast_track'`, `'pentest'`, `'full_sdlc'`), detects parallel workstreams across all 8 specialist domains, and derives deterministic 12-char `flowHash`.
65
- - **`planNode`** (`src/mcp/langgraph/nodes/plan.js`): Generates implementation blueprint (`plan.md`) via Kage and synchronizes `walkthrough_steps` and `todos`. Blocks execution for **HITL Gate 1** (`pending_plan_approval`).
66
- - **`briefNode`** (`src/mcp/langgraph/nodes/brief.js`): Synthesizes task objectives and architectural constraints after post-approval context compaction.
67
- - **`todoNode`** (`src/mcp/langgraph/nodes/todo.js`): Decomposes work into structured task slices with assigned specialist roles, disjoint `owned_files`, and native client TODO directives (`src/mcp/todo_walkthrough_sync.js`).
68
- - **`dispatchNode`** (`src/mcp/langgraph/nodes/dispatch.js`): Assembles single or concurrent (`parallel_dispatches`) payloads with isolated git worktrees (`prepareParallelWorktrees` / `prepareTaskWorktree`), `spawn_directive`, and `parallel_spawn_directive`.
69
- - **`executeNode`** (`src/mcp/langgraph/nodes/execute.js`): Tracks worker completion, runs `mergeBackParallelGroup` across parallel worktree branches (enforcing `syntaxGateForFiles`), and transitions to `document` (`@tokubetsu-jonin`) or `review` (`@kage`).
70
- - **`reviewNode`** (`src/mcp/langgraph/nodes/review.js`): Executes the Kage Review Gate via `runAislopGate`. Verifies `ai_slop_clean: true`, `ai_slop_findings: 0` (100/100 score), and `confidence >= 98%`.
71
- - **`remediateNode`** (`src/mcp/langgraph/nodes/remediate.js`): Autonomous repair loop (`slop_cycles <= 7`), re-delegating failing slices to the responsible worker subagent.
72
-
73
- ---
74
-
75
- ## 🛡️ Real-Time Idle `@advisor` Worker Manager (`<= 8,192 Tokens` / Turn)
76
-
77
- Implemented in `src/workflow/kage-reviewer/advisor_monitor.js` and integrated into `konoha.report_from_agent`, `runMcpAgent`, `sannin`, and SDLC settings:
78
- - **Zero-Token Idle State**: When workers are idle or compliant, `@advisor` sits idle from turn 0 and returns `status: 'IDLE_OK'` with **`0` output tokens**.
79
- - **8,192-Token Per-Turn Cap**: Input digests and interrupt directives are clamped via `clampAdvisorBytes` to **`<= 32,768 bytes` (`<= 8,192 tokens`)** with Head+Middle+Tail preservation (`advisor_max_tokens = 8192`).
80
- - **Dynamic 100k Per-Agent Input Token Quota (`agent_input_token_quota` / `KONOHA_AGENT_INPUT_TOKEN_QUOTA`)**: Compaction activates dynamically when an agent reaches its input token quota (default `100,000`), saves a per-agent snapshot in LangGraph SQLite checkpoint state (`lg_checkpoints` namespace `agent:<name>` and `KonohaWorkflowState.agentSnapshots`), resets the baseline, and auto-continues from `## LATEST CONDITION CHECKPOINT (Auto-Continue)`.
81
- - **Realtime Client TODO Sync**: `syncTodoAndWalkthrough` emits full `client_todo_directive` (`native_payload` + `markdown_checklist` + `walkthrough_steps`) and updates `TODO.md` + `sdlc_tasks` across all 8 harnesses on every transition.
82
- - **5-Point Real-Time Guard**:
83
- 1. `todo_drift`: Worker output deviates from the delegated task slice.
84
- 2. `owned_files_breach` / `worktree_escape`: Worker modifies files outside `owned_files` or outside `worktree_path`.
85
- 3. `fabricated_file` / `conflict_marker`: Claimed file does not exist on disk or contains unresolved git conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`).
86
- 4. `unverified_claim`: Worker claims completion without command/exit-code validation evidence.
87
- 5. `placeholder_slop`: Summary contains placeholder or incomplete stub markers.
88
- - **On-the-Fly Interruption**: When any violation occurs, `report_from_agent` returns `status: 'interrupted_by_advisor'` with a compact `INTERRUPT_CORRECTION` directive so the worker self-corrects immediately.
89
-
90
- ---
91
-
92
- ## 🤝 Authoritative Two-Stage HITL Gates & Post-Approval Compaction
93
-
94
- 1. **Gate 1 (`pending_plan_approval`)**:
95
- - Prompt choices:
96
- - `1. Compact and approve`
97
- - `2. Reject and Regenerate PLAN`
98
- - `3. Input your own choice`
99
- - **Automatic Post-Approval Compaction**: Selecting Option 1 automatically invokes `compactPostApprovalContext(taskDir, status)` (`src/mcp/workflow_gates.js`), pruning verbose pre-approval discovery dumps and compacting `plan.md` to actionable steps before Phase 2 starts.
100
- 2. **Gate 2 (`pending_human_signoff`)**:
101
- - Prompt choices:
102
- - `1. Compact and approve`
103
- - `2. Remediation`
104
- - `3. Input your own choice`