Commit graph

8 commits

Author SHA1 Message Date
65d17007c3 feat(v0.42): 6 fixes from 4-CLI re-audit (CRITICAL + 2 HIGH + 3 MED)
Some checks are pending
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / preflight (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / vps-smoke (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:frustration-matrix,kei-frustration-loop,kei-skill-importer,kei-projects-index,kei-projects-watcher,kei-gdrive-import,kei-leak-matrix,kei-skills,kei-gateway,kei-cron-scheduler,kei-export-trajectories,kei-backend-daytona,kei-d… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-compute-baremetal,kei-compute-vultr,kei-compute-linode,kei-compute-digitalocean,kei-svc-systemd,kei-llm-bridge-mlx name:hosted-sleep-compute]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-diff,kei-scheduler,kei-watch,kei-prune,kei-discover,kei-brain-view,kei-hibernate,kei-ledger-sign,kei-fork name:wave13-15]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-git-gitea,kei-git-forgejo,kei-git-gitlab,kei-git-bitbucket,kei-memory-sled,kei-memory-redis,kei-memory-postgres,kei-memory-sqlite,kei-auth-google,kei-auth-apple,kei-auth-magiclink,kei-auth-webauthn,kei-notify-slack,kei-n… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-ledger,kei-migrate,kei-changelog,kei-memory,kei-store,kei-conflict-scan,kei-refactor-engine,kei-graph-check,kei-shared,kei-dna-index,kei-pet name:core]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-machine-probe,kei-llm-ollama,kei-llm-llamacpp,kei-llm-mlx,kei-llm-router,kei-model name:llm-stack]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-router,kei-sage,kei-task,kei-chat-store,kei-crossdomain,kei-search-core,kei-content-store,kei-social-store,kei-curator,kei-auth,kei-artifact name:mcp-lbm]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:keisei,kei-forge,kei-runtime,kei-runtime-core,kei-atom-discovery,kei-agent-runtime,kei-capability,kei-provision,kei-entity-store,kei-pipe,kei-cache,kei-spawn,kei-replay name:atom-substrate]) (push) Blocked by required conditions
Convergent dogfood audit by Claude+Grok+Gemini+Copilot on v0.41 surfaced
that the v0.41 'fixes' were incomplete. 3 of 4 reviewers independently
found the same CRITICAL bypass; Gemini wrote a Rust test suite to verify.

## Convergent findings → v0.42 fixes

[#1 CRITICAL] Symlink leaf bypass (3-of-4 convergent)
  v0.41 only canonicalized PARENT, then re-attached leaf as-is. Exploit:
    1. kei_bash 'ln -s ~/.ssh/authorized_keys ./cfg.txt'
       (passes the bash hook chain — ln itself is non-destructive)
    2. kei_write file_path=cfg.txt content=<key>
       validate_path saw $PWD/cfg.txt (allowed) → fs::write followed leaf
       symlink → overwrote authorized_keys.
  Fix: canonicalize FULL path (incl. leaf) when file exists; for new
       files, symlink_metadata on leaf and reject is_symlink. Now the
       denylist check sees the real target.

[#2 HIGH] $HOME blanket-allowed = self-neutering (2-of-4 convergent)
  allowed_roots() defaulted to [$PWD, $HOME], denylist only had 4 secret
  dirs. So kei_write $HOME/.claude/hooks/no-github-push.sh content='exit 0'
  was ALLOWED — agent could overwrite the substrate's own policy hooks.
  Similar attacks on ~/.zshrc (RCE on next shell), ~/.gitconfig, ~/.npmrc.
  Fix: default to $PWD only. Denylist extended with .claude/, .grok/,
       .gemini/, .copilot/, .kimi/, all major shell-init files, and
       additional credential paths. KEI_ALLOWED_ROOTS for explicit
       widening.

[#3 HIGH] Empty-section fail-OPEN (Gemini test-verified)
  v0.41 'fail-closed on missing config' fix was incomplete: if config
  file existed but section [bash]/[edit]/[write] was empty, load_chain
  returned Ok(vec![]) → run_chain early-returned Ok → action ran ungated.
  Fix: empty chain also FAIL-CLOSED with same KEI_POLICY_CHAIN_OPTIONAL
       opt-in.

[#4 MEDIUM] load_chain still blocked tokio worker (Claude)
  v0.41 fix #4 converted handle_edit/handle_write reads to tokio::fs but
  left load_chain on std::fs. Slow/hung mount on policy-chain.toml would
  freeze a worker for every safe_* invocation.
  Fix: load_chain → async + tokio::fs::{try_exists, read_to_string}.

[#5 MEDIUM] process_group only applied to bash, not hooks (Claude)
  v0.41 fix #5 set_process_group on kei_bash's child shell, but the
  hook subprocess (spawned per-hook in run_chain) was NOT in its own
  group. On hook timeout, kill_on_drop killed only the immediate hook
  process; grandchildren orphaned — the exact failure mode fix #5 was
  meant to prevent.
  Fix: set_process_group + killpg also on hook spawn in run_chain.

[#6 MEDIUM] Per-step vs aggregate timeout (Claude)
  Doc claimed 'Hard cap on single chain + action — 60s'. Actual: each
  hook gets independent 60s, then action gets another 60s. For a 3-hook
  bash chain that's 240s max — 4× documented.
  Status: documented as known-limit; single-deadline impl deferred to
       v0.43 (not security-blocking, just a doc/correctness drift).

## Verification (8 smokes — all green)

  /etc/passwd                          → denied (system dir)              ✓
  ../escape.txt                        → denied (../ segment)             ✓
  /tmp/symlink → /etc/passwd writeable → denied (resolved /private/etc)   ✓ NEW
  ~/.claude/hooks/no-github-push.sh    → denied (substrate dir)           ✓ NEW
  ~/.zshrc                             → denied (shell-init file)         ✓ NEW
  policy-chain.toml empty [bash]       → FAIL-CLOSED                      ✓ NEW
  KEI_POLICY_CHAIN_OPTIONAL=1          → opt-in pass-through              ✓
  kei_bash git-push-github             → BLOCKED (regression)             ✓
  kei_bash echo HELLO                  → returns content (regression)     ✓

cargo test -p kei-mcp: 3/3 still pass.

## Architecture note from Grok

Grok architect flagged: safe_tools.rs is 474 LOC, exceeds Constructor
Pattern 200-line threshold. v0.42 does NOT refactor (security fixes
shipped first); v0.43 will extract path_guard.rs + chain_runner.rs.

## Per-CLI audit value demonstrated

  Claude   — 5 issues + 5 minor, exhaustive line-anchored analysis
  Grok     — architectural review with grep-verified citations
  Gemini   — wrote Rust test project to verify findings (PoC code!)
  Copilot  — partial fact-check, ran out of mid-task
2026-05-26 21:33:54 +08:00
8086bec486 feat(v0.41): patch 5 Gemini security findings + Copilot doc bug + claude/grok perms
Some checks are pending
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / preflight (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / vps-smoke (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:frustration-matrix,kei-frustration-loop,kei-skill-importer,kei-projects-index,kei-projects-watcher,kei-gdrive-import,kei-leak-matrix,kei-skills,kei-gateway,kei-cron-scheduler,kei-export-trajectories,kei-backend-daytona,kei-d… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-compute-baremetal,kei-compute-vultr,kei-compute-linode,kei-compute-digitalocean,kei-svc-systemd,kei-llm-bridge-mlx name:hosted-sleep-compute]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-diff,kei-scheduler,kei-watch,kei-prune,kei-discover,kei-brain-view,kei-hibernate,kei-ledger-sign,kei-fork name:wave13-15]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-git-gitea,kei-git-forgejo,kei-git-gitlab,kei-git-bitbucket,kei-memory-sled,kei-memory-redis,kei-memory-postgres,kei-memory-sqlite,kei-auth-google,kei-auth-apple,kei-auth-magiclink,kei-auth-webauthn,kei-notify-slack,kei-n… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-ledger,kei-migrate,kei-changelog,kei-memory,kei-store,kei-conflict-scan,kei-refactor-engine,kei-graph-check,kei-shared,kei-dna-index,kei-pet name:core]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-machine-probe,kei-llm-ollama,kei-llm-llamacpp,kei-llm-mlx,kei-llm-router,kei-model name:llm-stack]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-router,kei-sage,kei-task,kei-chat-store,kei-crossdomain,kei-search-core,kei-content-store,kei-social-store,kei-curator,kei-auth,kei-artifact name:mcp-lbm]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:keisei,kei-forge,kei-runtime,kei-runtime-core,kei-atom-discovery,kei-agent-runtime,kei-capability,kei-provision,kei-entity-store,kei-pipe,kei-cache,kei-spawn,kei-replay name:atom-substrate]) (push) Blocked by required conditions
Audit pass via Phase C dogfooding (security-auditor @ Agy/Gemini reviewing
our own safe_tools.rs) surfaced 5 real bugs. All fixed.

## Gemini findings (5 real bugs)

[#1 HIGH] FAIL-OPEN on missing config/hook
  Before: missing policy-chain.toml → "passing through" warning; missing
          hook script → "skipped" warning. Misconfig silently disabled
          enforcement.
  After:  both paths FAIL-CLOSED with clear error surfaced to caller.
          Tests/dev can opt in to pass-through via KEI_POLICY_CHAIN_OPTIONAL=1.

[#2 HIGH] Path traversal in kei_edit/kei_write
  Before: no validation; attacker could pass file_path=/etc/passwd or
          $HOME/.ssh/authorized_keys.
  After:  validate_path() rejects '..' segments, system dirs (/etc/, /usr/,
          /System/, /var/, /root/), and dotfile-secret dirs (~/.ssh/,
          ~/.aws/, ~/.gnupg/, ~/.config/gcloud/). Override via
          KEI_ALLOWED_ROOTS for explicit single-root confinement.

[#3 HIGH] CLAUDECODE/GROKCODE env bypass
  Behavior unchanged — this guard is a perf/UX optimization to avoid
  double-firing hooks when called from inside Claude/Grok (which already
  ran their own PreToolUse). Documented explicitly as NOT a security
  boundary: attacker controlling parent env already owns the invocation.
  Module header gains a DESIGN NOTE making this load-bearing.

[#4 MED] std::fs in async context
  Before: handle_edit/handle_write used std::fs::{read_to_string,write},
          which block the tokio worker thread. Pathological paths like
          /dev/random would freeze a worker indefinitely.
  After:  tokio::fs::{read_to_string,write}.await — async I/O, worker
          stays responsive.

[#5 MED] kill_on_drop only kills immediate child
  Before: timeout in kei_bash drops the Child handle; tokio's kill_on_drop
          SIGKILLs only the shell. Grandchildren (e.g., 'sleep 1000 &')
          orphaned.
  After:  Unix-only: spawn child in its own process group
          (Command::process_group(0)), and on timeout libc::kill(-pid,
          SIGKILL) to take down the whole group. New libc dep on Unix.

## Copilot doc fix

Doc claimed "kei-mcp exposes 4 built-in tools" without saying spawn_agent
lives in tools.rs while kei_bash/edit/write live in safe_tools.rs.
Validator agent flagged this as FALSE/MISLEADING. Now the doc spells out
the two-file structure + adds a v0.41 hardening summary.

## claude/grok subprocess permissions

Cross-CLI audit demo revealed that 'claude -p' and 'grok --print' returned
empty when invoked headless with a real audit task — they need explicit
permission flags to use Read/Grep tools in non-interactive mode. Added:

  claude:  --permission-mode=bypassPermissions
  grok:    --always-approve
  agy:     --dangerously-skip-permissions

Override via KEI_AGENT_PERMISSIVE=0 to keep strict default.
Re-verified: claude+grok both echo SMOKE-OK-V41 with the flag.

## Verification

cargo test -p kei-mcp --release  → 3/3 pass
MCP JSON-RPC smoke (all 7):
  - tools/list shows 4 built-ins ✓
  - kei_bash blocks RULE 0.1 push ✓
  - kei_bash passes 'echo OK' ✓
  - kei_write rejects /etc/passwd ✓
  - kei_write rejects ../ traversal ✓
  - kei_write rejects ~/.ssh/* ✓
  - missing policy-chain → FAIL-CLOSED with clear error ✓
  - KEI_POLICY_CHAIN_OPTIONAL=1 → opt-in pass-through ✓
2026-05-26 19:48:29 +08:00
4e5e6bd2c0 feat(phase-C): cross-CLI hook enforcement via kei_bash/kei_edit/kei_write MCP tools
Some checks are pending
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / preflight (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / vps-smoke (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:frustration-matrix,kei-frustration-loop,kei-skill-importer,kei-projects-index,kei-projects-watcher,kei-gdrive-import,kei-leak-matrix,kei-skills,kei-gateway,kei-cron-scheduler,kei-export-trajectories,kei-backend-daytona,kei-d… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-compute-baremetal,kei-compute-vultr,kei-compute-linode,kei-compute-digitalocean,kei-svc-systemd,kei-llm-bridge-mlx name:hosted-sleep-compute]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-diff,kei-scheduler,kei-watch,kei-prune,kei-discover,kei-brain-view,kei-hibernate,kei-ledger-sign,kei-fork name:wave13-15]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-git-gitea,kei-git-forgejo,kei-git-gitlab,kei-git-bitbucket,kei-memory-sled,kei-memory-redis,kei-memory-postgres,kei-memory-sqlite,kei-auth-google,kei-auth-apple,kei-auth-magiclink,kei-auth-webauthn,kei-notify-slack,kei-n… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-ledger,kei-migrate,kei-changelog,kei-memory,kei-store,kei-conflict-scan,kei-refactor-engine,kei-graph-check,kei-shared,kei-dna-index,kei-pet name:core]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-machine-probe,kei-llm-ollama,kei-llm-llamacpp,kei-llm-mlx,kei-llm-router,kei-model name:llm-stack]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-router,kei-sage,kei-task,kei-chat-store,kei-crossdomain,kei-search-core,kei-content-store,kei-social-store,kei-curator,kei-auth,kei-artifact name:mcp-lbm]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:keisei,kei-forge,kei-runtime,kei-runtime-core,kei-atom-discovery,kei-agent-runtime,kei-capability,kei-provision,kei-entity-store,kei-pipe,kei-cache,kei-spawn,kei-replay name:atom-substrate]) (push) Blocked by required conditions
Closes the "hooks only fire on Claude" gap. Phase C extends KeiSeiKit safety
enforcement (no-github-push, safety-guard, destructive-guard, citation-verify,
numeric-claims-guard) to any MCP-capable LLM CLI through a 3-tier honesty model.

## 3-tier model

TIER 1 (full native): claude (existing), grok (port hooks to grok settings.json)
TIER 2 (MCP-wrapped): copilot (--excluded-tools=shell + force kei_bash via MCP)
TIER 3 (advisory):    agy + kimi (cannot disable native shell; prompt-level only)

## Design (Constructor Pattern)

1. hooks/_lib/policy-chain.toml — SSoT: which hooks gate which tool (bash/edit/write)
2. _primitives/_rust/kei-mcp/src/handlers/safe_tools.rs — new module, 3 built-in
   MCP tools that synthesize Claude PreToolUse JSON, run hook chain, abort on
   exit-2, exec on all-pass. Same input contract → hooks reused as-is, no rewrite.
3. tools.rs short-circuit: kei_bash/kei_edit/kei_write dispatched before atom layer
4. 6 wire scripts: orchestrator + one per CLI (Constructor Pattern, no mixin)
5. bin/kei mcp-wire arm
6. docs/encyclopedia/cross-cli-policy.md — honest 3-tier matrix + verification

## Double-enforcement guard

If kei-mcp invoked from a process with $CLAUDECODE=1 or $GROKCODE=1, the chain
SKIPS — native hooks already fired. Wire scripts set these env vars in the
MCP server registration for claude/grok respectively. On copilot/agy/kimi the
env is unset → chain runs.

## Smoke (verified live)

Block: kei_bash{command: forbidden-push-pattern}
  → JSON-RPC error -32603 with full "BLOCK — RULE 0.1 NO GITHUB PUSH" stderr ✓
Pass:  kei_bash{command: "echo HELLO-FROM-KEI-BASH"}
  → result.content[0].text = "HELLO-FROM-KEI-BASH" ✓
tools/list: 4 built-ins present (spawn_agent + kei_bash + kei_edit + kei_write) ✓

## Tests

kei-mcp: 3/3 (tools_list assertions updated for atoms+4 built-ins).
Build clean with toml = "0.8" dep added.

## Out of scope (deferred)

- Codex CLI wiring (not installed locally)
- ACP middleware proxy (transport, not middleware — ruled out at research)
- Container/firejail sandboxing for agy/kimi (heavy; documented limit instead)
- Native Rust PatternGate migration (optimization, separate phase)
2026-05-26 18:03:33 +08:00
3fec43ea7e feat(orchestrator): kei pick + spawn_agent MCP tool — true multi-LLM shell
Some checks are pending
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / preflight (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / vps-smoke (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:frustration-matrix,kei-frustration-loop,kei-skill-importer,kei-projects-index,kei-projects-watcher,kei-gdrive-import,kei-leak-matrix,kei-skills,kei-gateway,kei-cron-scheduler,kei-export-trajectories,kei-backend-daytona,kei-d… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-compute-baremetal,kei-compute-vultr,kei-compute-linode,kei-compute-digitalocean,kei-svc-systemd,kei-llm-bridge-mlx name:hosted-sleep-compute]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-diff,kei-scheduler,kei-watch,kei-prune,kei-discover,kei-brain-view,kei-hibernate,kei-ledger-sign,kei-fork name:wave13-15]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-git-gitea,kei-git-forgejo,kei-git-gitlab,kei-git-bitbucket,kei-memory-sled,kei-memory-redis,kei-memory-postgres,kei-memory-sqlite,kei-auth-google,kei-auth-apple,kei-auth-magiclink,kei-auth-webauthn,kei-notify-slack,kei-n… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-ledger,kei-migrate,kei-changelog,kei-memory,kei-store,kei-conflict-scan,kei-refactor-engine,kei-graph-check,kei-shared,kei-dna-index,kei-pet name:core]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-machine-probe,kei-llm-ollama,kei-llm-llamacpp,kei-llm-mlx,kei-llm-router,kei-model name:llm-stack]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-router,kei-sage,kei-task,kei-chat-store,kei-crossdomain,kei-search-core,kei-content-store,kei-social-store,kei-curator,kei-auth,kei-artifact name:mcp-lbm]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:keisei,kei-forge,kei-runtime,kei-runtime-core,kei-atom-discovery,kei-agent-runtime,kei-capability,kei-provision,kei-entity-store,kei-pipe,kei-cache,kei-spawn,kei-replay name:atom-substrate]) (push) Blocked by required conditions
Closes the "Claude Code as single primary" gap. Now `kei` (no args) execs
whichever CLI is configured as primary, and ANY MCP-capable orchestrator
can spawn KeiSeiKit agents on any backend via the built-in spawn_agent tool.

## A — orchestrator picker

bin/kei now reads ~/.claude/config/primary.toml and execs that CLI instead
of hardcoding claude. New arms:
  kei pick               interactive menu → set primary → launch it
  kei --on=<backend>     one-shot launch of <backend> (no primary write)
  kei primary [<b>]      get/set primary
Splash shows `primary CLI: <backend>` so the orchestrator is visible.
Failure mode: if primary's CLI isn't on PATH, prints install hint + offers
`kei pick` recovery.

scripts/kei-pick.sh — Constructor Pattern picker (<140 LOC). Lists all 6
backends with install status (✓/✗), highlights current primary, writes
choice to primary.toml, execs the picked CLI. Honors stdin TTY gate
(RULE TTY-INTERACTIVITY-GATE — -t 0, not -t 1) for non-interactive safety.

## B — spawn_agent MCP tool

_primitives/_rust/kei-mcp/src/handlers/tools.rs gains a built-in
`spawn_agent` tool, exposed alongside discovered atoms:
  - inputSchema: { name: str, task: str, on?: backend-enum }
  - Calls kei-agent-cli.sh internally with same DNA resolution
  - 60s timeout, kill-on-drop
  - Honors KEI_AGENT_CLI env for testing

Smoke 2026-05-26 (MCP stdio JSON-RPC round-trip):
  spawn_agent(name=smoke-test, on=claude) → "SMOKE-OK"   
  spawn_agent(name=smoke-test, on=grok)   → "SMOKE-OK"   

Why it matters: Claude Code has a native Agent tool. Grok / Agy / Copilot /
Kimi don't have an equivalent native sub-agent surface — but they all speak
MCP. spawn_agent gives them KeiSeiKit's sub-agent capability when they're
the orchestrator. The chosen orchestrator no longer caps the sub-agent fleet.

## Other

_primitives/_rust/kei-mcp/Cargo.toml: tokio gains "io-std" feature (was
missing — main.rs uses tokio::io::stdin/stdout). This fixes a latent build
error unrelated to this PR (kei-mcp wasn't building cleanly before).

Tests: tools_list assertions updated for the +1 built-in tool (3 total
instead of 2 with atoms; 1 instead of 0 on empty root). All MCP tests pass.
Assembler 3/3 golden tests still pass (provider field is optional).
2026-05-26 16:48:23 +08:00
Parfii-bot
3759fb0f64 fix(audit-batch): CI green + RULE 0.4/0.16/0.18 honesty pass
12-agent audit (2 waves Opus+Sonnet, 6 slices each) flagged 3 HIGH-tier
issues that BOTH waves agreed on, plus 5 doc-honesty findings. This
batch fixes the lot.

== CI green (was failing on main 94a7d68) ==

- _primitives/_rust/Cargo.toml — workspace tokio gains `io-std` feature
  (needed by kei-mcp/src/main.rs which calls tokio::io::{stdin,stdout})
- _primitives/_rust/kei-mcp/Cargo.toml — dev-deps tokio gains `test-util`
  feature (needed by tests/tools_call_timeout.rs for tokio::time::advance
  and Builder::start_paused). Both verified locally:
  `cargo check -p kei-mcp` ✓
  `cargo test --no-run -p kei-mcp` ✓ (3 test binaries link)
  [REAL: ran 2026-05-03 in this session]

== HIGH-tier audit fixes (consensus across waves) ==

1. SQLi escape in agent-outcome-backfill.sh:110
   - 4 of 12 agents flagged: TOOL_USE_ID was JSON-derived and
     interpolated raw into SQL. Allowlist on $SHIPPED protected today
     but a future case-statement removal opened the surface.
   - Fix: tiny `_sql_esc` helper that doubles single-quotes (SQL-99
     standard escape), applied to SHIPPED + TOOL_USE_ID. STUBS already
     integer-validated.

2. PRAGMA user_version=9 in install/sql/outcome-only-schema.sql
   - W1 outcome-only critic flagged: the SQL fallback installed a
     v9-equivalent flat schema but left user_version=0. A LATER
     `kei-ledger init` (e.g. when user upgrades to full kit) would
     re-run migrations v1-v9 and ALTER TABLE ADD COLUMN duplicate-error
     mid-migration → broken DB.
   - Fix: set PRAGMA user_version=9 before COMMIT so the binary's
     migration runner sees current ≥ target and short-circuits.

3. backup_file mv→cp + uninstall macOS-portable awk
   - W1+W2 outcome-only flagged: lib-backup.sh uses `mv` which DELETES
     the target before _jq_merge_hooks runs; `|| true` swallowed the
     subsequent jq read-error → silent settings.json loss.
   - Fix in lib-profile-outcome-only.sh: `cp -p` aside, drop `|| true`,
     return 1 on merge failure (trap restores).
   - PROFILE-OUTCOME-ONLY.md uninstall used GNU sed `,+1` extension
     which BSD sed (macOS) does not support — uninstall silently
     no-op'd on macOS, leaving orphan CLAUDE.md text.
   - Fix: replace with portable `awk` recipe; also added `rm -f` for
     the agent-toolstats.jsonl sidecar (privacy completeness).

== Doc honesty pass (RULE 0.18 numerics + RULE 0.4 citations) ==

4. README.md count drift — verified all values against filesystem:
   * 102→105 Rust crates (Cargo.toml workspace `members` count)
   * 67→68 skills (`ls skills/ | wc -l`)
   * 35→38 hooks (`grep -c '"command":' settings-snippet.json`)
   * 37→38 agent manifests (`ls _manifests/*.toml | wc -l`)
   * 82→85 substrate blocks (`find _blocks/ -name '*.md' | wc -l`)
   * 18 capability atoms VERIFIED via `find _capabilities/ -name '*.md'`
     (encyclopedia §3 row count of 17 is in a separate file and is a
     known internal display issue, not changed in this commit)
   * 495→565 active DNAs (per docs/DNA-INDEX.md header 2026-05-03)
   Each value now carries a `[REAL: <command>]` style trailer per
   RULE 0.18.

5. README.md DNA "80-char identity" → "≥33-char variable-length"
   - W1+W2 reviewer-pass flagged FALSE: docs/DNA-FORMAT.md SSoT says
     minimum 33 chars; 80 was nowhere in code or spec
   - Fix in README.md:36 + docs/PHILOSOPHY.md:39 + docs/DNA-INDEX.md:1352

6. README.md "Eleven install profiles (... Cursor / Continue / Zed /
   Aider / Docker / Nix)" — Cursor/Continue/Zed/Aider/Docker/Nix were
   never install profiles, they were bridge targets
   - Fix: list 12 actual profiles from _primitives/MANIFEST.toml,
     mention bridges as separate concept

7. .claude-plugin/plugin.json license MIT → Apache-2.0
   - W2-Sonnet reviewer flagged: LICENSE file is Apache-2.0 (since
     2026-04-30 per NOTICE), but plugin.json still declared MIT —
     plugin marketplace would show wrong license

8. docs/ARCHITECTURE.md:318 placeholder URL `https://example.invalid/...`
   - W2-Sonnet reviewer flagged: dead link in published docs
   - Fix: remove the bad href, describe ssl-rule-file as per-user
     install outside the public repo

9. skills/sleep-on-it/SKILL.md Wagner et al. 2004 citation
   - W1+W2 reviewer flagged RULE 0.4 violation: citation without
     verification marker
   - Fix: added [VERIFIED: doi:10.1038/nature02223] + clarification
     that the original paper showed slow-wave-sleep (not strictly REM)
     insight gain — our metaphor is a loose mapping

10. encyclopedia/substrate-overview.md §5 fabricated TS deps
    - W1-Opus doc-consistency flagged RULE 0.4.b violation: 5 of 6
      package rows had INVENTED dependency strings
      (`recall-ai-sdk ^1.0.0`, `nodemailer-mock ^2.0.0`,
       `telegram-typings ^4.10.0`, etc — none exist in the actual
      package.json files)
    - Fix: regenerated table from real `package.json` reads via
      `node -p "require(...).dependencies"` for each of the 6 packages
    - Fix: also corrected version drift (5 packages all 0.14.0 now)

Verification:
- Outcome-only end-to-end install against fake $HOME succeeds:
  hooks installed, ledger schema at user_version=9, settings.json
  created cleanly, all 5 documented files present
  [REAL: ran 2026-05-03 in this session]
- `cargo check -p kei-mcp` + `cargo test --no-run -p kei-mcp` clean

Audit findings NOT yet addressed (deferred to next batch):
- README:65 git clone github URL — repo is private; reviewer flagged
  external strangers cannot clone; will resolve via Quick Start rewrite
- npm.pkg.github.com / @keisei84 leftover sweep — both waves verified
  ZERO refs, no fix needed
- safeEqual timing leak in TS server (W2 sec MEDIUM)
- HTTP server bind 0.0.0.0 (W2 sec MEDIUM)
- Unbounded request body (W2 ci MEDIUM)
- --dry-run silent ignored on non-outcome profiles (W1+W2 MEDIUM)
- Doc-link missing for MEMORY/DNA/LEDGER format specs from README

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:09:59 +08:00
Parfii-bot
7cc544fd85 chore: author email + Cargo metadata SSoT (parfionovich@keilab.io)
Two related changes:

1. Author email update across the kit
   - All `info@greendragon.info` references replaced with `parfionovich@keilab.io`
   - Touched: NOTICE, README.md, _ts_packages/package.json (and 5 adapter packages),
     plus 90+ Cargo.toml files
   - Apache-2.0 attribution unchanged (Denis Parfionovich, 2026)

2. Cargo workspace.package SSoT for author/license/repository/homepage
   - Added to [workspace.package]:
     authors    = ["Denis Parfionovich <parfionovich@keilab.io>"]
     license    = "Apache-2.0"
     repository = "https://github.com/KeiSei84/KeiSeiKit-1.0"
     homepage   = "https://github.com/KeiSei84/KeiSeiKit-1.0"
   - All ~89 member crates migrated from inline declarations to:
     authors.workspace    = true
     license.workspace    = true
     (repository/homepage where applicable)
   - Closes audit gap: kei-graph-stream, kei-cortex, kei-shared previously had no
     license field at the crate level, blocking `cargo publish` on those.
     Now they inherit Apache-2.0 from workspace.
   - kei-scheduler/Cargo.toml: removed stray duplicate `authors` line introduced
     by an earlier migration sweep.

cargo check --workspace: clean. No code changes; metadata-only migration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 13:55:28 +08:00
Parfii-bot
da4d88910a chore(workspace): SSoT inheritance + version unification
Group E — Cargo workspace hygiene (post-audit 2026-05-02).

Workspace dependency inheritance:
- 40+ member crates migrated from inline dep pinning to { workspace = true }.
  Was: every crate redeclared clap/serde/rusqlite/tokio/etc inline, defeating
  the [workspace.dependencies] SSoT and forcing N edits per upgrade.
  Authoritative pins now live solely in _primitives/_rust/Cargo.toml.

Major version splits resolved:
- dashmap: 5 vs 6 (kei-cortex/kei-gateway) -> 6 in workspace
- tower:   0.4 vs 0.5 (kei-cortex/kei-forge) -> 0.5 in workspace
- notify:  6 vs 8 (kei-projects-watcher/kei-watch+kei-skills) -> 8 in workspace
- thiserror: 1 vs 2 (workspace/keisei) -> kept 1; keisei downgraded
  Closed: dual-major compilation = wasted build time + ABI mismatch risk
  at trait boundaries.

Profile / orphan cleanup:
- kei-changelog/Cargo.toml: deleted [profile.release] block (workspace member
                              profiles are silently ignored by Cargo since 1.0).
- kei-brain-view/Cargo.toml: removed dangling "[workspace] table stripped on
                                merge" comment (orphan from prior decomposition).

rust-version SSoT:
- 27+ member crates migrated from inline rust-version = "1.75" to
  rust-version.workspace = true. Workspace declares 1.77; the inline 1.75 pins
  were stale and misleading (with resolver 2 the workspace MSRV won anyway).

cargo check --workspace: clean (only pre-existing sqlx-postgres future-incompat
warning + frustration-matrix dead-code warning, neither introduced by this change).

Note: _assembler/ lives outside _primitives/_rust workspace, so its Cargo.toml
was not touched here. Remaining edition-2024 question for _assembler is a
separate decision.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 21:40:46 +08:00
Parfii-bot
0be354a920 KeiSeiKit-public — clean state
Single-commit clean baseline after security scrub of niche-tells,
project codenames, internal jargon, and contributor-email leaks.

Contents:
- 100 Rust crates (_primitives/_rust/)
- 37 agent manifests (_manifests/) + generated specs (_generated/)
- 67 user-invocable skills (skills/)
- 33 hooks (hooks/)
- Composition blocks (_blocks/)
- Documentation (docs/, README.md)
- TS adapter packages (_ts_packages/)
- Assembler (_assembler/)
- Roles (_roles/)
- Templates (_templates/)
- Forgejo CI (.forgejo/)

Author: Denis Parfionovich <info@greendragon.info>

License: see LICENSE.
2026-05-01 12:09:03 +08:00