No description
Find a file
Parfii-bot 0cf823413e feat(sleep): cloud-agent reasoning + Telegram delivery to whitelist
User pushback: "Агент должен делать осмысленные выводы! С утра должен
быть отчет и пусть он приходит куда-то! На телеграмм, например, лучше
сразу после фазы сна, бот есть"

Wires the @KeiSeiBot Telegram bot as the delivery channel for nightly
Phase B reports, with a Claude Sonnet 4.6 reasoning step in front to
distil the multi-section markdown into a single actionable brief.

NEW — `hooks/sleep-report-tg.sh` (130 LOC POSIX bash)

Pipeline:
  1. Source ~/.claude/secrets/.env  (umbrella SSoT — RULE 0.8)
  2. POST report markdown to Claude API messages endpoint with a
     system prompt mandating: TL;DR + numbers + 3-5 actionable
     findings + rule-candidates if any cross-session pattern ≥3×.
     Sonnet 4.6, max_tokens=1500, 120s timeout.
  3. Send distilled summary via Telegram sendMessage to whitelisted
     chat_id (defaults to TELEGRAM_ALLOWED_CHAT_ID env, falls back
     to 86059912).
  4. Cap message at 3900 chars (TG limit 4096).
  5. Fallback if Markdown parse_mode fails (orphan * / [ in body) →
     retry without parse_mode so the user still sees the report.
  6. Defensive on every step: missing API key → send raw excerpt;
     missing curl/jq → log + exit 0; HTTP failure → log + exit 0.
  7. Bypass: SLEEP_REPORT_TG_BYPASS=1.

WIRE — `hooks/phase-b-rem.sh`
  Step 7 (new) calls sleep-report-tg.sh after the existing commit/push
  step. Failure of TG delivery never affects Phase B's exit code —
  the local report + memory-repo push remain the source-of-truth;
  TG is convenience.

CONFIG (already done outside this commit, documented for completeness)
  - ~/.claude/secrets/.env now has TELEGRAM_BOT_TOKEN +
    TELEGRAM_ALLOWED_CHAT_ID (single-user whitelist 86059912).
  - ~/.claude/tg-webhook.py whitelist locked to {86059912}; group
    chat (-1003758632751) and partner (10954083) removed per
    user request "сделай боту только один вайт адрес". Blocked
    senders land in /var/log/tg-webhook/blocked.jsonl, no auto-reply.
  - ~/.claude/tg-contacts.json shrunk from 3 contacts to 1.

Smoke verified: today's sleep-2026-05-02.md → cloud agent emitted
TL;DR ("Opus burned $1239 across 117 runs with 100% unknown outcomes")
+ 5 findings + 3 rule-candidates → delivered to chat_id 86059912 as
msg_id 1129 (HTTP 200). Cost: 3955 in + 897 out tokens on Sonnet
≈ $0.025/run. At 1 run/night that is ~$0.75/month for full reasoning
on every nightly report.

What this does NOT yet do:
  - No retry on Telegram rate-limit (429). Single nightly call
    is well below the 30/sec limit, but if the system ever bursts
    multiple reports it would lose them.
  - No multi-day digest mode (each run is independent; future:
    weekly Sunday recap aggregating 7 reports).
  - Cloud agent prompt is hard-coded inline; future: extract to
    a path-atom-style block (post-2026-05-02 substrate work).

=== STATUS-TRUTH MARKER ===
shipped: functional
stubs: 0
cargo-check: NOT-RUN  (pure shell)
behaviour-verified: yes
follow-up-required:
  - Phase B prompt template extracted to atom (low priority)
  - Weekly recap mode (Sunday)
  - 429 rate-limit retry (defensive)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 04:38:52 +08:00
.claude/agents/_merge/kei-memory-2026-05-01 feat(kei-memory): functional schema fix + 4-wave architecture refactor 2026-05-01 14:10:06 +08:00
.claude-plugin KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
.forgejo KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
.github fix(ci): leak-check uses awk instead of sed (shellcheck SC2001) 2026-05-01 21:15:09 +08:00
_assembler feat(path-atoms): atomize ~/.claude memory + rules path references 2026-05-01 22:29:50 +08:00
_blocks feat(outcome-hook): PostToolUse:Agent backfills outcome + stubs in ledger 2026-05-01 23:24:02 +08:00
_bridges KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
_capabilities KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
_generated feat(model-tier+branch-dna): activate cost router + give branches DNA 2026-05-01 23:05:07 +08:00
_manifests feat(model-tier+branch-dna): activate cost router + give branches DNA 2026-05-01 23:05:07 +08:00
_primitives feat(sleep-sync): mirror time-metrics + ledger snapshots, surface in Phase B report 2026-05-02 04:02:28 +08:00
_roles KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
_schemas/fragments KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
_templates KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
_ts_packages KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
bin KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
docs feat(tracking): close 3 last observability gaps — toolStats + skill-record + numeric-claims journal 2026-05-02 03:42:09 +08:00
hooks feat(sleep): cloud-agent reasoning + Telegram delivery to whitelist 2026-05-02 04:38:52 +08:00
install feat(install): Rust binary acquisition for fresh-clone installs (Path A + Path B) 2026-05-01 19:07:55 +08:00
scripts KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
skills chore(security): scrub username paths from public artefacts + leak-check CI 2026-05-01 19:59:29 +08:00
tasks KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
tests feat(outcome-hook): PostToolUse:Agent backfills outcome + stubs in ledger 2026-05-01 23:24:02 +08:00
tools KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
.dockerignore KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
.gitignore KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
BACKUP-INDEX.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
bootstrap.sh KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
DECISIONS.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
HERMES-MIGRATION-PLAN.md chore(security): scrub residual leaks — NOTICE email + HERMES patent section 2026-05-01 18:19:14 +08:00
install.sh feat(install): Rust binary acquisition for fresh-clone installs (Path A + Path B) 2026-05-01 19:07:55 +08:00
kei-architect.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-code-implementer.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-cost-guardian.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-critic.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-fal-ai-runner.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-infra-implementer.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-ml-implementer.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-ml-researcher.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-modal-runner.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-researcher.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-security-auditor.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
kei-validator.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
LICENSE KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
NOTICE chore(security): scrub residual leaks — NOTICE email + HERMES patent section 2026-05-01 18:19:14 +08:00
PLUGIN.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
README.md KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00
settings-snippet.json KeiSeiKit-public — clean state 2026-05-01 12:09:03 +08:00

KeiSeiKit

A multi-LLM substrate that gives any agentic coding tool persistent memory, deterministic agent identity, and self-maintaining orchestration. Works first-class with Claude Code; MCP-compatible bridges generate context for Cursor / Continue / Zed / Aider / Windsurf / Cline / OpenClaw / Kimi from the same source-of-truth.

Apache 2.0 — explicit patent grant + retaliation clause. 102 Rust crates (~132K LOC), 67 skills, 35 hooks, 37 agent manifests, 82 substrate blocks, 18 capability bundles, 7 substrate roles. Self- indexing via kei-registry SQLite (currently 495 active DNAs across the public substrate). Three-phase nightly consolidation. Foreign-project ingestion runtime (kei-import <repo-url>).

What it does

Persistent memory SQLite ledger + content-addressable memory store, session-spanning context, cross-machine sync via memory-repo
Agent DNA Deterministic 80-char identity per invocation: <role>::<caps>::<scope-sha8>::<body-sha8>-<nonce>. Same task → same prefix → "did this run before?" via SQL, no embeddings
Constructor Pattern for prompts Agent .md files composed from manifests + blocks + capability bundles + rule fragments. Edit a block → all agents using it recompose. Single source of truth
kei-fork Atomic git triplet (branch + worktree + ledger row) for parallel agent runs. Atomic rollback. No main-branch collisions across 4-8 simultaneous Claude sessions
Three-phase sleep Phase A incubation (queued tasks) → Phase B REM consolidation (analyzes last 30 sessions, writes morning markdown report) → Phase C NREM deep-sleep (every 7 days, conflict scan + refactor proposals). No feedback loop — outputs are markdown, you decide what to keep
Auto self-indexing Every substrate file edit triggers registry update + agent regeneration + DNA-INDEX.md refresh + keimd graph reindex
Foreign-project ingestion kei-import <repo> walks → matches against 12 runtime traits → extracts skills from README/docs → generates migration plan → produces per-phase agent prompts
Cross-tool bridges One rule-set, 11 target formats (.cursorrules, .windsurf/rules/main.md, .github/copilot-instructions.md, AGENTS.md, GEMINI.md, etc)
Community npm registry Publish your agents / skills / hooks as scoped packages on keigit.com (public Forgejo + npm registry, OAuth login, per-user PAT). npm publish to your own scope, npm install from anyone else's. See docs/PUBLISHING.md

Why it exists

The author runs 4-8 parallel Claude Code terminals daily. Without substrate, every session loses context, every parallel agent collides on main, every "did we already solve this?" requires manual grep. With substrate, identity carries — agents know what ran before, results converge through the ledger, fork-as-triplet prevents collisions, three-phase sleep produces overnight consolidation.

This is a tool first, not a product. If it solves your problem, fork it.

Quick start

# Claude Code (primary target — full hook + agent integration)
/plugin marketplace add KeiSei84/KeiSeiKit
/plugin install keisei@keisei-marketplace

# Any MCP-compatible client (Cursor / Continue / Zed / Aider / etc)
git clone https://github.com/KeiSei84/KeiSeiKit-1.0
cd KeiSeiKit-1.0
./install.sh --profile=minimal

37 agents + 67 skills + 35 hooks + nightly consolidation wired in 60 seconds. Eleven install profiles (minimalcorefull + MCP-only / Cortex / Cursor / Continue / Zed / Aider / Docker / Nix) documented in docs/INSTALL.md.

Self-maintaining

After install, the substrate maintains itself. Every edit cascades:

edit any rule .md       → kei-decompose registers fragments
edit any manifest .toml → assembler regenerates one agent .md
edit any block .md      → assembler regenerates ALL agents
edit any skill SKILL.md → kei-registry updates
edit any hook .sh       → kei-registry updates
edit any primitive src/ → kei-import-project register updates
ANY substrate edit      → DNA-INDEX.md auto-refreshes
ANY substrate edit      → keimd graph auto-reindexes

nightly:
  Phase A (incubation)         → process queued tasks
  Phase B (REM consolidation)  → analyze last 30 sessions → morning report
  Phase C (NREM, every 7d)     → conflict scan + refactor proposals

No automatic feedback loop into agent state. All consolidation outputs are human-readable markdown. You read, you decide what merges.

Honest limits

  • Phase 5 executor (kei-import-project) generates per-phase agent prompts as JSON; the actual Agent({...}) spawn happens orchestrator-side (Claude Code Agent tool, MCP wrapper, or a thin shell loop). A first-class JS/TS wrapper that auto-spawns + tracks is future work.
  • Phase 9 Path A (model-router assembler-time rebake) — 37 agent manifests currently declare model: opus in frontmatter. Bayesian posterior router activates per-task-class when ≥100 outcome rows accumulate (currently 3). Until then, routing happens via orchestrator discipline plus advisor-hook stderr nudges.
  • Cortex stack (kei-cortex / kei-tty / kei-mcp) ships as beta. Local HTTP daemon + ratatui TUI + MCP stdio JSON-RPC build clean. Browser app and VSCode-extension frontends are concept.
  • @keisei/mcp-server npm package — local dist/ builds work; not yet published to npm registry.
  • Non-Claude clients integrate via MCP + bridges, not native hooks. PreToolUse / PostToolUse / UserPromptSubmit / Stop semantics are Claude Code primitives. Other clients get capability exposure but not the hook wire-up.

What it's NOT

  • Not a Claude Code replacement — runs alongside, not instead-of
  • Not a SaaS — local-first by default; hosted offering under consideration if community demand emerges (see Roadmap)
  • Not enterprise — solo-maintained, no SLA, no dedicated support
  • Not a framework — substrate. You compose; it doesn't dictate workflow

Roadmap

The substrate is functionally complete for solo-developer use. What might be valuable as a hosted service if there's demand:

  • Cross-machine memory sync — DNA-indexed memory available across laptop + desktop + cloud Claude session
  • Hosted Phase B/C nightly — traces consolidated by a remote agent, morning report delivered to inbox
  • Encyclopedia search-as-API — query team substrate by DNA / role / capability across multiple agents

These are considered, not committed. Open an issue with your use-case if any of these would solve real pain. Until then: fork, run locally, file PRs.

Hermes — proof of foreign-architecture ingest

Ten phases of Nous Research's Hermes (MIT, Python agent framework) ingested into KeiSeiKit substrate through April 2026. Each Hermes concept lives as a KeiSeiKit primitive:

Hermes phase KeiSeiKit landing
ShareGPT trajectory export kei-export-trajectories crate
OpenAI-compat HTTP server kei-llm-router providers + chat handler
Daytona sandbox backend kei-backend-daytona (with toolbox proxy URL split)
Injection-guard on memory writes wired through kei-memory::ingest + kei-pet::memory
Memory-nudge invoker Invoker trait + MemoryStore Arc plumbed
SKILL.md skill format kei-skills::SkillRegistry, consumed by kei-mcp
Skill-invocation aggregation kei-ledger schema v8 + aggregate-skills CLI
Multi-platform gateway kei-gateway (Telegram / Discord / Slack / CLI)
Cron / scheduler kei-cron-scheduler parser+job+runner

The kei-import umbrella runs the same pipeline (decompose → match → extract-skills → plan → execute) on any Rust / TS / Python / Go repo. Hermes was the validation case; the runtime works on others.

Frontend design — anti-AI-slop philosophy

The frontend-design skill is a deliberate counter-position to the same-shape output of v0 / Lovable / Bolt:

  • 10 archetypes — Editorial / Swiss / Brutalist / Minimal / Maximalist / Retro-Futuristic / Organic / Industrial / Art Deco / Lo-Fi. Each declares typography pairing + color palette + layout language + motion style.
  • OKLCH color system — one --brand-hue controls the full palette, perceptually uniform.
  • Phase Gate (mandatory before any code): purpose, archetype, the one differentiator, three anti-references, design tokens. Skip the gate = skip the skill.
  • Hard bans: Inter / Roboto / Space Grotesk, purple gradients on white, centered card grids as default, hero → cards → testimonials template, linear easing on UI transitions.
  • Diverge-Kill-Mutate loop when output feels generic.
  • The Blur Test: at 20% visibility, layout silhouette must be distinguishable from anti-references.

Orchestrator skill landing-page composes 11 skills across 6 recipes (apple-product / saas / portfolio / ecommerce / agency / startup).

Architecture

Stack: Rust core (102 crates, ≤2 MB each, 12-trait runtime + plugin registry) + TypeScript glue (6 adapters: gmail / grok / recall / telegram / youtube / mcp-server). Backend impls cover:

Trait Impls
ComputeProvider bare-metal SSH, DigitalOcean, Linode, Vultr
GitProvider Forgejo, Gitea, GitLab, Bitbucket
MemoryBackend SQLite, Sled, Postgres, Redis
AuthProvider Google OIDC, Apple Sign-In, WebAuthn passkeys, magic-link
NotifyChannel Telegram, Discord, Slack, SMS (Twilio)
NetworkMode WireGuard, OpenVPN, IPsec
LlmBackend Anthropic, OpenAI, Kimi (Moonshot), MLX, llama.cpp, Ollama
ServiceManager systemd

Declare which impl to use in ~/.keisei/config.toml; runtime resolves at startup. See docs/ARCHITECTURE.md, docs/PHILOSOPHY.md, docs/SUBSTRATE-SCHEMA.md, docs/IMPORT-RUNTIME.md, docs/PUBLISHING.md, docs/RULES-AS-BLOCKS.md, docs/DNA-INDEX.md.

License

Apache 2.0. Use, fork, ship, modify. Explicit patent grant + retaliation clause: contributors who sue any user over patents covered by their contributions lose their license to the work. Pre-2026-04-30 versions remain available under their original MIT terms (irrevocable). See LICENSE and NOTICE.

Author & collaboration

Built by Denis Parfionovich (info@greendragon.info) running 48 parallel Claude Code terminals per day. Solo-maintained. Apache 2.0 makes the bus factor manageable: any AI-assisted developer (you, your Claude, your Cursor, your Aider) can read this codebase and continue it.

Forks welcome. PRs welcome. Issues welcome.

Open to collaboration. If you have:

  • a use-case this substrate would solve and you can't see how — open a discussion
  • ideas for the SaaS roadmap (cross-machine memory sync, hosted nightly consolidation, encyclopedia-as-API) — email or open an issue
  • a related project you're building (agent infra, MCP servers, cross-tool bridges, prompt-engineering substrates) and want to cross-pollinate — reach out
  • want to integrate KeiSeiKit primitives into your product or research — Apache 2.0 already permits it; happy to help you wire it

Email reaches the author directly. No marketing list, no funnel.