Commit graph

79 commits

Author SHA1 Message Date
Parfii-bot
b82e3b039e feat(agent-substrate/phase-3): kei-agent-runtime + kei-capability binaries
Two new crates implementing the substrate runtime per locked §Runtime
execution contract + §Capability trait contract (Rust) + §Verify
execution worktree→simulated-merge.

kei-agent-runtime — library + CLI binary:
- src/capability.rs — Capability trait (name/check/verify) + GateContext
  + GateDecision + VerifyContext + VerifyResult + RunMode + TaskSpec
- src/registry.rs — &str → &'static dyn Capability dispatch for 14 impls
- src/gates/ — 6 PreToolUse modules (policy::no-git-ops,
  scope::files-{whitelist,denylist}, safety::no-dep-bump,
  tools::read-only, tools::cargo-only-bash)
- src/verifies/ — 8 on-return modules (quality::constructor-pattern,
  quality::cargo-check-green, quality::tests-green, safety::no-dep-bump,
  scope::files-{whitelist,denylist}, output::{report-format,severity-grade})
- src/compose.rs — task.toml + role + capabilities → prompt.md
- src/spawn.rs — ledger fork + prompt write (actual Agent invocation
  remains orchestrator's tool call)
- src/verify.rs — runs all capability verifies per role; collects
  VerifyReport {passed, failed}
- src/simulated_merge.rs — git worktree add test-merge/<id> + apply diff
  + run verify; cleanup on Drop
- src/main.rs — clap CLI: compose | spawn | verify | run

kei-capability — thin CLI adapter crate:
- Depends on kei-agent-runtime path dep
- Subcommand `check <cap-name>` (PreToolUse gate; stdin JSON, exit 0|2)
- Subcommand `verify <cap-name>` (on-return; env-driven, exit 0 or fail)
- Pattern: shell hook = 3-line `exec kei-capability check "$CAP_NAME"`

Workspace Cargo.toml: both crates registered as members (under agent
substrate v1 marker).

cargo check --workspace: PASS
cargo test -p kei-agent-runtime: 37/37 green
  - 6 capability_trait_smoke (registry lookups, unknown name → None)
  - 3 compose_smoke (fixture role + caps → composed prompt)
  - 12 gate_smoke (each gate: happy + deny + bypass)
  - 4 simulated_merge_smoke (git worktree lifecycle)
  - 12 verify_smoke (each verify: pass + fail + edge cases)
cargo test -p kei-capability: 0/0 (CLI binary, tested via lib)

(Agent completion report cut off by rate-limit at 60 tool-uses; code
itself is green — verified by orchestrator post-commit.)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 02:35:53 +08:00
Parfii-bot
07b47dba7e Merge feat/stream-g-sage-rules — atoms+rules unified graph 2026-04-23 01:21:12 +08:00
Parfii-bot
7fb562cfc5 Merge feat/stream-f-forge-pure-rust — eliminate shell-out 2026-04-23 01:21:12 +08:00
Parfii-bot
15bf40196b feat(stream-g): kei-sage rules integration — atoms + rules unified graph
Unify atoms and rules in kei-sage's graph. Previously [[rules/...]]
wikilinks were filtered (explicit Stream C scope-deferral). Now they
resolve to rule-node units with rule_ref edges.

kei-atom-discovery extension (non-breaking):
- WikilinkTarget enum: Atom(String) | Rule(String) | Other(String)
- classify_wikilink(inner: &str) -> WikilinkTarget — exposed via lib.rs
- parse_wikilink unchanged for backwards-compat; new callers use
  classify for richer semantics

kei-sage additions:
- rule_index.rs (129 LOC) — RuleRecord + discover_rules walking flat
  *.md + extract_h1 for display name + index_rules (unit_type="rule",
  vault_path="rule:<slug>") + index_rule_edges (walks atom.related,
  emits rule_ref edges atom → rule node)
- atom_cli.rs: cmd_rules_discover + default_rules_root
- main.rs: AtomsRulesDiscover subcommand with --rules-root flag
- tests/rules_smoke.rs: 5 tests (discovery, heading extraction,
  slug fallback for headingless files, empty-dir, atom→rule edge
  persistence)

Tests: 12/12 kei-atom-discovery (+3 classify_wikilink),
28/28 kei-sage (+5 rules_smoke + unit tests now counted).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 01:21:00 +08:00
Parfii-bot
e84e9fc1fe feat(stream-f): kei-forge pure-Rust templating — eliminate shell-out
Remove std::process::Command invocation of scripts/new-atom.sh from
kei-forge. Templating moves to pure Rust — eliminates the
sed-metacharacter injection class structurally, on top of the
description whitelist that E2 added as defence-in-depth.

src/generate.rs split into 4 Cubes (Constructor Pattern):
- generate/placeholders.rs — 6-token substitution, longer-first ordering
- generate/paths.rs — TargetPaths::resolve + assert_none_exist
- generate/rollback.rs — Drop-based atomic rollback (Rust idiom for
  shell `trap ERR`)
- generate/atom_tests.rs — 5 tempdir integration tests

generate.rs dropped from 295 → 159 LOC as orchestration thin wrapper.

Behavioural parity with scripts/new-atom.sh maintained: same 6 tokens,
same order, refuse-overwrite, atomic rollback, same file-list
ordering. scripts/new-atom.sh untouched on disk (still usable as
standalone CLI).

Cargo.toml: removed mock-generate feature flag (no longer needed —
pure-Rust tests use tempfile::TempDir), added tempfile dev-dep.

Tests: 44/44 (was 29 with mock-generate; +15 new pure-Rust unit tests
across placeholders/paths/rollback/atom_tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 01:21:00 +08:00
Parfii-bot
8626e23c22 feat(stream-e): invoke wire — kei-runtime subprocess → real atoms
Replace NotImplemented stub with real atom execution per schema
§Runtime invocation contract.

Convention: JSON-in/JSON-out over subprocess. Every refactored crate
exposes `<crate> run-atom <verb>` that reads JSON from stdin (or
--input), dispatches to atoms::<verb>::run, emits Output JSON on
stdout, exits per atom-error class.

Runtime side (kei-runtime):
- InvokeError: +AtomFailed{atom,code,stderr} +SubprocessError
  +OutputParse +BinaryNotFound{crate_name}. NotImplemented kept as
  legacy escape for atoms opting out of run-atom protocol.
- Output: now {atom: String, result: Value} — carries atom's actual
  return value.
- invoke_exit_code: AtomFailed passes through child exit (0..=255),
  Subprocess/OutputParse → 1, BinaryNotFound → 127, NotImplemented → 64.
- Binary resolution: KEI_RUNTIME_BIN_DIR env → PATH fallback.

kei-task side:
- New `pub mod run_atom` in lib.rs
- atoms/mod.rs: VERBS const + DispatchError enum wrapping per-atom errors
- src/run_atom.rs: read_input (stdin/@path/literal), dispatch, exit mapping
- main.rs: Cmd::RunAtom{verb, input} subcommand; collapsed three
  classify_*_error helpers into single classify_dispatch. Legacy
  create/search/add-dependency CLIs preserved.

Tests: 5/5 runtime (+1 invoke_real_atom integration), 9/9 kei-task
(+1 atoms::tests::verbs_list_matches_submodules).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 01:21:00 +08:00
Parfii-bot
f7e4725573 fix(substrate): amendment A-1 (input/output required all kinds) + integration test + jsonschema 0.18 relative-$id bug
Three post-E1/E2/E3-merge items:

1. Schema amendment A-1 (architect P0-a, non-breaking clarification):
   input.schema and output.schema are REQUIRED for all atom kinds. The
   shared kei-atom-discovery parses them as Option<PathBuf> only to allow
   tolerant skip-on-missing (stderr warn), not to permit absent schemas.
   Resolves Stream C / Stream D enforcement asymmetry documented in
   critic finding #6.

2. Cross-stream integration test (architect P0-b): tests/substrate_integration.sh
   builds release binaries, scaffolds a test atom corpus, runs
   schema-lint + list-atoms + atoms-discover + invoke; asserts all four
   streams agree on the same atom corpus and exit codes honour the
   locked §Runtime contract. Previously missing — only manual smoke
   checks existed.

3. Fix regression introduced by E1's jsonschema 0.18 upgrade:
   "relative URL without a base" on compile when schema declared a
   relative $id like "kei-task/atoms/schemas/create-input.json".
   validate.rs now synthesises an absolute file:// $id from the
   canonicalised schema path before compile. Internal $refs still
   resolve relative to the schema file; LocalFileResolver still confines
   to the schema's parent dir. Integration test catches this.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:56:27 +08:00
Parfii-bot
ca0635e0fa Merge fix/e3-contract-compliance — exit codes + invoke Err + strict lint
# Conflicts:
#	_primitives/_rust/kei-runtime/src/invoke.rs
2026-04-23 00:52:54 +08:00
Parfii-bot
4e9a7dddfb Merge fix/e2-kei-forge-hardening — DNS/CSRF/injection + headers 2026-04-23 00:49:59 +08:00
Parfii-bot
1bc6fbf4e3 fix(substrate): E3 — CLI contract compliance (exit codes + invoke Err)
Four audit findings on CLI contract violations per locked §Runtime schema:

- crit#7: invoke returned Ok with error payload — now returns
  Err(InvokeError::NotImplemented) → exit 64
- crit#5: typed errors collapsed via anyhow::anyhow!("{e}") in kei-task —
  replaced with CliError { code, msg } + classify_*_error helpers;
  validation errors exit 2, storage errors exit 1 (spec-compliant)
- crit#8: lint.rs wikilink parser accepted [[[foo]] — strict parse_wikilink
  from kei-atom-discovery used; emits finding for malformed entries
- crit#15: draft-07 detection was substring match — is_draft07_uri exact
  match against canonical URIs only

Tests: 4/4 kei-runtime (was 2; +2 invoke exit-code tests) + 8/8 kei-task
(was 7; +1 empty-title exit-2 test) = 12/12 green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:49:49 +08:00
Parfii-bot
f7982f0415 fix(substrate): E2 — kei-forge security hardening (DNS rebind + CSRF + injection)
Three HIGH security findings resolved in _primitives/_rust/kei-forge/:

- F-1: DNS rebinding — require_local_host middleware returns 421 on
  non-localhost Host headers
- F-2: CSRF via urlencoded — require_json_content_type middleware
  returns 415 on non-JSON; form HTML now POSTs JSON via fetch()
- crit#1/SA F-7: description sed injection — whitelist validator rejects
  newline/CR/tab/NUL/backtick/$/length>200, blocks the shell-script attack
  at the Rust layer
- crit#11: missing security headers — CSP, X-Frame-Options DENY,
  X-Content-Type-Options nosniff, Referrer-Policy no-referrer on GET /

Zero new deps (axum 0.7 middleware::from_fn + HeaderMap native).
Constructor Pattern compliant — 6 Cube files, largest 231 LOC including tests.

Tests: 29/29 (was 12/12; +17 new). Includes 4 adversarial integration
tests for each defence layer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:49:49 +08:00
Parfii-bot
990f5e3711 fix(substrate): E1 — kei-atom-discovery shared crate + 4 critical security fixes
Extracts authoritative atom discovery + frontmatter parsing into new crate
_primitives/_rust/kei-atom-discovery/. kei-sage and kei-runtime now both
consume the same implementation, eliminating Frontmatter drift.

Resolved findings:
- F-3/crit#3: path traversal via md_dir.join() — safe_join helper rejects
  absolute paths + .. components + post-canonicalise escapes (4 sites)
- crit#6/architect P0-a: Frontmatter drift — single AtomMeta struct
- SA supply-chain: serde_yaml archived — migrated to serde_yaml_ng 0.10
- crit#2: JSON Schema $ref SSRF — jsonschema 0.17→0.18 with resolve-file
  feature only, custom LocalFileResolver denies non-file:// schemes
- F-4: symlink traversal — walkdir follow_links(false) explicit everywhere
- F-5: YAML billion-laughs — 64 KiB pre-parse cap

Tests: 9/9 new crate + 23/23 sage + 2/2 runtime + 7/7 kei-task = 41/41 green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:49:49 +08:00
Parfii-bot
42fe08232e Merge feat/stream-d-kei-runtime — invoke/list-atoms/schema-lint MVP
# Conflicts:
#	_primitives/_rust/Cargo.lock
#	_primitives/_rust/Cargo.toml
2026-04-23 00:13:16 +08:00
Parfii-bot
2361a21d15 Merge feat/stream-c-kei-sage-substrate — kei-sage walks atoms/*.md 2026-04-23 00:10:44 +08:00
Parfii-bot
ef48c9993b Merge feat/stream-b-atoms-kei-task — 3 pilot atoms per locked schema 2026-04-23 00:10:44 +08:00
Parfii-bot
d68fddb59a feat(stream-d): kei-runtime — discover + validate + lint (invoke stub)
New crate _primitives/_rust/kei-runtime/ implementing §Runtime invocation
contract from locked substrate schema.

CLI (clap-derive):
- list-atoms [--root] [--crate] [--kind]   → walk + print
- invoke <atom-id> --input <json|@file>    → discover + validate input (stub exec)
- schema-lint [--root] [--crate]           → 6-check validator
- pipe <dag.toml>                          → "not yet implemented" stub

Modules (≤ 200 LOC each, largest lint.rs @ 171):
- src/discover.rs — walk_atoms walks <root>/*/atoms/*.md, parses frontmatter
- src/validate.rs — JSONSchema draft-07 via jsonschema 0.17.1
- src/invoke.rs — MVP stub: discover → parse → validate_input → boundary ack
- src/lint.rs — 6 checks: required fields, kind enum, side_effects shape,
  schema path existence + draft-07 declaration, wikilink resolution
- src/main.rs — clap CLI, exit 0|1|2 per §Runtime contract

Intentional stub boundary: invoke returns structured JSON ack (exit 0),
wire-up to concrete atom impls deferred to integration pass (needs
Stream B atoms landed first).

Registered kei-runtime in workspace members.

Tests: 2/2 integration smoke (lint_smoke, discover_smoke) green.

Stream D of substrate v1 parallel build.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:09:58 +08:00
Parfii-bot
57b9475e50 feat(stream-c): kei-sage substrate — walk atoms/*.md + wikilink graph
Extends kei-sage with substrate-atom indexing layer per locked schema
§Graph / discovery contract.

New modules (all ≤ 200 LOC, Constructor Pattern):
- src/atom_parse.rs — frontmatter splitter, wikilink parser, id splitter
- src/atoms.rs — AtomKind + FromStr, AtomRecord, discover_atoms, resolve_wikilinks
- src/atom_index.rs — persists atoms as Units + atom_related edges into existing Store
- src/atom_cli.rs — 4 subcommand handlers

New CLI subcommands (default root ~/.claude/agents/_primitives/_rust):
- atoms-discover — walks atoms/*.md, prints table
- atoms-rank — PageRank over wikilink edges (composes w/ existing vault)
- atoms-related <atom-id> — BFS from atom
- atoms-search <query> — FTS over frontmatter + body

Tolerant scan: invalid frontmatter → stderr warn + continue (never abort).
[[rules/...]] wikilinks filtered at edge resolution per scope (rules
integration deferred to follow-up).

Tests: 9 unit + 6 integration smoke + 8 pre-existing = 23/23 green.
Zero regression. Single new dep: serde_yaml 0.9.

Stream C of substrate v1 parallel build.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:09:57 +08:00
Parfii-bot
ae82bc6242 feat(stream-b): kei-task pilot — 3 atoms (create/search/add-dependency)
Pilot refactor per locked substrate schema. kei-task migrated to atom
layout:

- atoms/<verb>.md — YAML frontmatter + human body for 3 verbs
- atoms/schemas/<verb>-{input,output}.json — JSON Schema draft-07
- src/atoms/<verb>.rs — typed Input/Output/Error + pub fn run()
- src/atoms/mod.rs — module registry
- Cargo.toml [package.metadata.keisei] — crate-level substrate data
- src/main.rs — dispatcher for 3 pilot commands via atoms::

Zero behaviour change: 7/7 integration tests pass before and after
(create_and_get, update_persists, cycle_detected, milestone_linking,
dependency_chain_traversal, task_graph_edges, search_finds_task).

main.rs still has 5 non-migrated subcommands (update, graph,
dependency-chain, milestone, link-milestone) — scope discipline, they
migrate in later passes. main.rs 120 → 132 LOC.

Stream B pilot reference — other crates follow this pattern in v0.24+.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:09:55 +08:00
Parfii-bot
fd25c3af60 feat(stream-a): kei-forge MVP — local web wizard scaffolding atoms
New crate _primitives/_rust/kei-forge/ exposing POST /forge over axum
on 127.0.0.1:8747. Shell-outs to scripts/new-atom.sh for generation.
5-input inline HTML form, no JS required. 9 unit + 3 integration tests
green via `cargo test --features mock-generate`.

Registered kei-forge in workspace members.

Stream A of substrate v1 parallel build — see docs/SUBSTRATE-SCHEMA.md.
Spec pre-locked; schema immutable until 2026-06-03 or revocation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:09:53 +08:00
Parfii-bot
5ec90ca241 fix(tests): repair 2 missing closing braces from v0.22 Track-A↔Track-C merge
Merge of feat/v0.22-keisei-schema-v4 into main (which already had
Track C's fs_type tests) elided '); }' at 2 seams. Tests compiled
once I added them back, but the edit missed the git-add step.

No behaviour change — both tests already passed after the fix;
commit just closes out the working tree.
2026-04-22 21:16:22 +08:00
Parfii-bot
4ccb1548a2 Merge refactor/v0.22-kei-store-async-backend — AsyncBackend trait + shared runtime 2026-04-22 21:06:50 +08:00
Parfii-bot
bc7e099697 refactor(v0.22): kei-store AsyncBackend trait + shared tokio runtime (Track B)
Extracts an AsyncBackend trait in kei-store so future GCS/Azure/Bunny
backends implement 5 async fns, not re-invent the sync-over-tokio
bridge. Closes architect P1 + P2 findings.

NEW src/async_backend.rs (189 LOC):
  - trait AsyncBackend with get/put/list/list_recursive/delete/exists
  - AsyncBackendStore<B: AsyncBackend> — generic MemoryStore impl
    (sync-over-async via shared runtime)
  - shared_runtime() -> &'static Runtime via OnceLock
    (multi-thread, 2 workers, enable_io+enable_time)
  - path helpers (validate_rel, short_hash, is_manifest_key) moved
    here as single source of truth

NEW src/s3_cloud/backend.rs (120 LOC):
  - S3AsyncBackend impl of AsyncBackend — 5 async fns using the
    existing aws-sdk-s3::Client

MODIFIED src/s3_cloud/mod.rs (200 → 43 LOC):
  pub type S3CloudStore = AsyncBackendStore<S3AsyncBackend>;
  Thin re-export + inherent new(cfg) constructor.
  Doc-header documents the extension seam: 'adding GCS = impl 5 async fns'.

MODIFIED src/s3_cloud/keys.rs (66 → 40 LOC): compat shim — re-exports
  validate_rel / short_hash / is_manifest_key from async_backend.
  Old call-sites + 4 unit tests unchanged.

Deps: async-trait = 0.1 added under s3 feature; tokio now has
  rt-multi-thread feature too.

FIXES N=2 Store footgun: prior impl created a current_thread Runtime
  per instance — 2 instances in one process = 2 runtimes, block_on
  panic if caller is on another runtime. Shared multi-thread runtime
  via OnceLock means N instances all share 2 workers.

REAL VERIFICATION (agent-pasted):
  cargo check -p kei-store: clean
  cargo check -p kei-store --features s3: clean
  cargo test -p kei-store --release: 10+9+0 = 19 passed
  cargo test -p kei-store --features s3 --release: 38+9+6 = 53 passed
    (+7 vs baseline 46)

Tests added (7):
  async_backend::tests::shared_runtime_is_singleton
  async_backend::tests::validate_rel_rejects_absolute
  async_backend::tests::validate_rel_rejects_parent
  async_backend::tests::short_hash_deterministic
  async_backend::tests::is_manifest_key_matches_format
  s3_cloud::tests::async_backend_shared_runtime_handles_two_store_instances
  s3_cloud::tests::async_backend_runtime_is_multi_thread

Public API preserved: S3CloudStore::new / .branch / .current_branch /
  .key / .backend_name. Factory + integration tests untouched.

Pre-existing: list_inner 38 LOC (moved verbatim from mod.rs, not
  refactored per Core Rule 3).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 21:06:50 +08:00
Parfii-bot
27c153cefb Merge feat/v0.22-keisei-schema-v4 — schema v4 + Scope::Auto + registry (conflicts resolved)
CHANGELOG: merged Track A (schema v4 + Auto + registry + time.rs split) and Track C (fs_type.rs + battle-matrix + USB guide split) Added entries side-by-side. Kept Track A's Removed block.

integration.rs: 2 conflict blocks merged by concatenation — Track C's
fs_type detection tests (2) and Track A's schema v4 / multi-brain /
Scope::Auto / templated hint / registry tests (16). Total 48 tests pass
(46 Track A + 2 Track C).

Missing closing braces on both merge boundaries repaired
(auto-merge dropped '); }' at 2 seams).
2026-04-22 21:06:23 +08:00
Parfii-bot
4bbc95fd7c feat(v0.22): keisei schema v4 + Scope::Auto + templated hint + registry (Track A)
BREAKING schema bump v3 → v4. Backward-compat via untagged serde
for v1/v2/v3 read-paths — no user-visible regression.

1. Schema v4 — multi-brain marker
   AttachRecord inverted: each Attachment carries its own brain_path
   + brain_name + scope + attached_at. Enables brain-A to Claude-
   Code (user scope) + brain-B to Cursor (project scope) in ONE
   marker. v1/v2/v3 auto-migrate via config_migrate.rs (NEW, 114
   LOC) — silent stderr notice on first v0.22 read.

2. Scope::Auto — default CLI behaviour
   'keisei attach <brain>' no longer defaults User scope blindly.
   New Scope::Auto resolves per-adapter via auto_scope():
     claude-code: CWD/.claude/ present → Project else User
     cursor:      CWD/.cursor/ present → Project else User
     continue:    User (no project concept)
     zed:         User (global settings only)
   'keisei mount' stays host-wide (always User fan-out).

3. Templated post_attach_hint
   fn post_attach_hint(&self, brain: &Brain, scope: Scope) -> String
   Each adapter interpolates brain name + scope. Example for
   claude-code: 'run /help in Claude Code (user scope) — verify
   '<brain-name>' is in mcpServers'.

4. Adapter registry
   adapters/_registry.rs (NEW, 32 LOC) — single canonical list
   of 4 adapters. adapter::all() delegates. 5th adapter = one
   line change, one place.

5. Dead code cleanup
   Error::NotAttached + Error::AdapterFailed removed. Grep-verified
   zero references.

6. config.rs decomposition (200 LOC rule)
   config.rs 224 → 197 LOC.
   time.rs (NEW, 90 LOC) — now_utc_string + format_epoch_utc +
     civil_from_days Howard Hinnant + 5 unit tests
     (epoch-0, leap day 2020-02-29, century-non-leap 2100-03-01,
      arbitrary 2026-04-22, RFC3339 shape).
   config_migrate.rs (NEW, 114 LOC) — WireRecord migration.

REAL VERIFICATION:
  cargo test -p keisei --release: 46 passed 0 failed
    (5 time::tests + 41 integration — 30 existing adjusted to v4 + 11 new)

Tests added:
  marker_v3_migrates_to_v4
  two_brains_can_be_attached_simultaneously
  detach_removes_single_brain_preserves_others
  scope_auto_resolves_to_{project,user}_*
  cursor_auto_scope_respects_cwd_dot_cursor
  post_attach_hint_interpolates_brain_name
  adapter_registry_lists_all_four
  dead_error_variants_removed
  time_now_utc_string_has_rfc3339_shape
  fresh_marker_has_schema_version_4

Agent corrected 3 of the spec's epoch anchor timestamps
(1583020800 → 1582977600 for 2020-02-29T12:00:00Z, 1776870000 →
1776877200 for 2026-04-22T17:00:00Z); century-non-leap anchor
4107542400 → 2100-03-01 was already correct.

Known pre-existing: continue_adapter.rs 206 LOC (was 204; +2 for
signature widening). Out-of-scope for this track.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 21:00:13 +08:00
Parfii-bot
5993f32146 feat(v0.22): FS warn + battle-test matrix + USB docs platform split (Track C)
1. Filesystem type detection (architect P2 finding)
   _primitives/_rust/keisei/src/fs_type.rs (NEW, 103 LOC)
     - statfs(2)-based detection on unix (libc = '0.2' under
       [target.'cfg(unix)'.dependencies])
     - Recognizes exfat / msdos (FAT32) via f_fstypename on macOS,
       via f_type magic numbers on Linux (0x4d44, 0x2011bab0)
     - Windows stub returns Unknown (GetVolumeInformationW TBD)
     - warn_on_unsafe_fs(root) emits stderr warning on ExFat/Fat32
   brain.rs::load calls warn_on_unsafe_fs after canonicalize+symlink
     checks. Warning NOT fatal — user can opt into single-client use.

2. Battle-test matrix (architect P3 finding)
   tests/battle/Dockerfile.install-test-alpine (NEW)
     - alpine:3.19 + apk rust/cargo/pandoc
     - Exposes musl-vs-glibc issues in aws-sdk-s3, rusqlite, git2
   tests/battle/Dockerfile.install-test-debian (NEW)
     - debian:12 + rustup stable + pandoc
     - Default server distro, different apt structure from Ubuntu
   tests/battle/README.md rewritten — 3-distro matrix with run script

3. USB-BRAIN-GUIDE platform split
   docs/USB-BRAIN-GUIDE.md — restructured as TOC + platform-agnostic
     preamble + exFAT warning + cross-platform troubleshooting
   docs/USB-BRAIN-GUIDE-macos.md (NEW, 97 LOC) — Gatekeeper, diskutil,
     /Volumes, xattr -d com.apple.quarantine
   docs/USB-BRAIN-GUIDE-linux.md (NEW, 98 LOC) — /media/$USER,
     umount, ext4 recommended, systemd-udev auto-mount note
   docs/USB-BRAIN-GUIDE-windows.md (NEW, 115 LOC) — PowerShell
     Dismount-Volume, NTFS, FS-advisory Unknown caveat

REAL VERIFICATION (paste from agent):
  cargo check -p keisei: Finished (clean)
  cargo test -p keisei --release: 32 passed 0 failed (30 existing + 2 new)
  docker buildx outline: both new Dockerfiles parse

Constructor Pattern:
  fs_type.rs 103 LOC, brain.rs 198 LOC (at limit 200, held the line)
  All fns <30 LOC. Each USB guide sub-doc 97-115 LOC.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 20:56:42 +08:00
Parfii-bot
f12eb9f83c fix(v0.21.1): wave-audit consolidated — 5 critic HIGH + 2 security HIGH + 3 polish
Closes 10 audit findings from 4-agent wave (critic + security +
architect + validator) on v0.21.0.

CRITIC HIGH (5):
  H1 s3_cloud::commit() was listing with delimiter='/' — nested
     writes silently dropped from manifest hash. Added
     list_recursive() (no delimiter), filter manifest-*.json from
     hash input.
  H2 S3Cfg access_key_env + secret_key_env were advertised in TOML
     but never read. Wired via resolve_explicit_creds() with
     aws-credential-types. Partial-set or empty-resolve → error.
  H3 display::sanitize_display missing in detach.rs + mount.rs
     (regression of v0.19.2 L9 ANSI injection fix). Applied at 8
     print sites. 2 new integration tests.
  H4 adapters/jsonmcp.rs RESTORED (was lost in earlier merge).
     107 LOC shared module: load_json_or_empty / upsert_under_key /
     remove_under_key / persist. claude_code 163→105, cursor 165→106,
     zed 178→114. Unified error handling via ConfigParseError.
  H5 ENV_LOCK shared across kei-store tests. New test_env.rs (24 LOC)
     exposed under cfg(any(test, feature='s3')). github.rs +
     s3_cloud/tests.rs + s3_smoke.rs all use shared mutex. Fixes
     parallel-test race on KEI_STORE_S3_ENDPOINT.

SECURITY HIGH (2):
  SEC-H1 scripts/install-actionlint.sh — added sha256 verify
     (shasum/sha256sum) before extract. ACTIONLINT_SHA256_OVERRIDE
     env var for CI injection. Per-platform constants marked
     [UNVERIFIED: SKIP] pending live checksums.txt fetch (agent had
     no WebFetch this session — user follow-up: paste from
     https://github.com/rhysd/actionlint/releases/download/v1.7.12/checksums.txt).
  SEC-H2 S3 SSRF/IMDS guard. validate_endpoint() rejects:
     loopback (127/8, ::1, localhost), link-local (169.254/16,
     fe80::/10), metadata hostnames (google/azure). Override via
     KEI_STORE_S3_ALLOW_INTERNAL=1. HTTP rejected unless
     KEI_STORE_S3_ALLOW_INSECURE=1. Custom endpoint now REQUIRES
     explicit creds (no IMDS chain leak via third-party endpoint).
     4 reject + 3 accept tests pass.

POLISH (3):
  D1 docs/USB-BRAIN-GUIDE.md — ⚠️ WARNING block under Prerequisites:
     exFAT/FAT32 NOT safe for multi-client attach (SQLite WAL needs
     shared-mem mmap). Use ONE client at a time on those FSes.
     New Troubleshooting entry 'SQLite corruption on mount-attach'.
  D2 '~5 MB release binary growth' now labelled [estimate, E5 —
     not yet measured] in CHANGELOG.md + s3_cloud/mod.rs header.
  D3 scripts/validate-workflow-shas.sh exits 2 (not 0) when
     UNVERIFIED_COUNT > 0 and GITHUB_TOKEN absent. Distinguishes
     'network denied' from 'all good'.

REAL VERIFICATION (pasted by agent):
  cargo check -p keisei -p kei-store: Finished (clean)
  cargo test -p keisei --release: 30 passed 0 failed
  cargo test -p kei-store --release: 10 + 9 passed (default features)
  cargo test -p kei-store --features s3 --release:
    31 + 9 + 6 = 46 passed (with s3)
  bash -n scripts/*.sh: OK
  regen-counts.sh --check: no drift

Constructor Pattern: largest new src 200 LOC (s3_cloud/mod.rs, at
limit). jsonmcp.rs 107 LOC. test_env.rs 24 LOC.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 20:03:17 +08:00
Parfii-bot
969ddf34cd Merge feat/v0.21-kei-store-s3 — real S3 backend (CHANGELOG conflict resolved)
Kept both Added blocks: v0.21 SSoT/Scope (from earlier merge) and
v0.21 kei-store S3. Both are part of the v0.21 ship.
2026-04-22 17:59:56 +08:00
Parfii-bot
e5cd0d6790 feat(v0.21): kei-store real S3 backend behind opt-in 's3' feature flag
Promotes S3 from MVP stub to functional via aws-sdk-s3. Default builds
unchanged (zero new deps). Feature flag ensures users who don't need
S3 don't pay the ~5MB binary / C-toolchain cost.

Cargo.toml: new [features] s3 = [...] gating 4 optional deps:
  aws-sdk-s3 = 1.130.0
  aws-config = 1.8.16 (with behavior-version-latest)
  tokio = 1.52.1 (current-thread runtime, no multi-threaded bloat)
  bytes = 1 (S3 body passthrough)

s3_cloud/ module (4 files, Constructor Pattern):
  mod.rs (190 LOC) — S3CloudStore + MemoryStore trait impl
  client.rs (81 LOC) — aws-config builder, KEI_STORE_S3_ENDPOINT
    override for R2 / Wasabi / MinIO / any S3-compat
  keys.rs (60 LOC) — path-traversal guard + DJB2 hash helper
  tests.rs (63 LOC) — builder + prefix + key-guard unit tests

Factory routing (factory.rs):
  with 's3' feature + bucket URL → S3CloudStore (real network)
  without 's3' feature → S3Store stub (existing MVP, preserved)

Security posture:
  - Branch-prefix isolation rejects  traversal at keys.rs layer
  - aws-config default credential chain (env → ~/.aws → IMDS);
    no bespoke credential handling
  - rustls, not OpenSSL (matches existing crate tree)

Tests: 22 existing + 11 new (4 keys + 3 client + 5 mod + 5 smoke)
  cargo test -p kei-store (default features): 9 passed
  cargo test -p kei-store --features s3: 22 + 9 + 5 = 36 passed
  cargo clippy -p kei-store --features s3: clean

Real stdout verified for all verify criteria. No fabrication.

MANIFEST.toml [primitive.kei-store] deps updated to reflect feature
opt-in model.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:59:11 +08:00
Parfii-bot
81e3b58533 feat(v0.21): keisei SSoT relocation + Scope enum (user/project)
Two architect-audit P1/P2 findings closed.

PART A — SSoT relocation
  Before: ~/.claude/keisei-attached.toml (baked Claude-Code subpath)
  After: ~/.keisei/attached.toml (client-neutral)
  config::migrate_from_legacy() runs inside config::read() — first
  call after v0.21 install reads legacy path, writes new path,
  deletes legacy, emits stderr notice.
  claude_code adapter's .claude/ subpath UNCHANGED — that's Claude
  Code's real config dir, not keisei's marker namespace.

PART B — Scope enum (architect P1)
  ClientAdapter trait gains:
    fn supported_scopes(&self) -> &[Scope] { &[Scope::User] }  // default
    fn config_path(&self, scope: Scope) -> PathBuf
    fn attach(&self, brain: &Brain, scope: Scope) -> Result<()>
    fn detach(&self, brain_name: &str, scope: Scope) -> Result<()>

  Per-adapter scope support:
    claude_code — [User, Project]  (~/.claude vs ./.claude)
    cursor      — [User, Project]  (~/.cursor vs ./.cursor)
    continue    — [User] only (Continue has no project concept)
    zed         — [User] only (Zed uses global settings)

  CLI: keisei attach <brain> --scope={user|project} (default user).
  keisei mount → always Scope::User (host-wide fan-out).
  Marker Attachment gains scope field with #[serde(default)] so
  v0.20 markers read as Scope::User (backward-compat).

  New Error::ScopeUnsupported { client, scope, supported } — blocks
  invalid combos (e.g. zed --scope=project) with clear message.

New module scope.rs (49 LOC) — Scope enum + serde + Display + FromStr.
paths.rs gains keisei_state_dir() returning $HOME/.keisei.

5 new integration tests:
  - legacy_marker_migrates_on_first_read
  - attach_with_project_scope_writes_local_config
  - attach_user_scope_still_default
  - scope_unsupported_by_adapter_errors
  - detach_respects_scope_from_marker

REAL VERIFIED cargo test -p keisei output: 28 passed; 0 failed.
cargo check -p keisei: clean.
grep /Users/denisparfionovich/ in edits: zero hits.

Constructor Pattern: scope.rs 49 LOC, paths.rs 34 LOC, largest fn
migrate_from_legacy() 22 LOC.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:56:10 +08:00
Parfii-bot
909205f63b Merge feat/v0.20-schema-v2-multi-platform — schema v2 multi-platform + post_attach_hint
Conflicts resolved by composition (not picking sides):
  error.rs: keep ManifestTooLarge (v0.19.2) + NoPlatformBinary (v0.20);
    UnsupportedSchema message updated to 'need 1 or 2'.
  brain.rs: merged v0.19.2 invariants block + v0.20 platform-key docs
    into a single Invariants section listing both hardening constraints
    and v2 schema range.
  attach.rs: composed v0.19.2 sanitize_display wrapping with v0.20
    Result<PathBuf> handling — mcp_server_path errors now sanitized too.
  integration.rs: concatenated v0.19.2 (3 tests + helper) + v0.20
    (4 tests + 2 helpers) blocks preserving all 7 new cases.

Tests: 23/23 pass (16 existing + 3 v0.19.2 + 4 v0.20).
cargo check -p keisei: clean.

v1 brains still load, v2 brains dispatch per-platform, adapters have
client-specific post_attach_hint.
2026-04-22 17:23:18 +08:00
Parfii-bot
12e56d6590 feat(v0.20): Brain schema v2 per-platform mcp_server + post_attach_hint() trait
Closes 2 architect audit P3 findings. MVP on the USB-droppable brain
vision — one brain directory now serves every platform.

Schema v2 — per-platform mcp_server dispatch:
  [paths.mcp_server]
  darwin-arm64 = 'bin/kei-mcp-server-darwin-arm64'
  darwin-x64 = 'bin/kei-mcp-server-darwin-x64'
  linux-x64 = 'bin/kei-mcp-server-linux-x64'
  linux-arm64 = 'bin/kei-mcp-server-linux-arm64'
  windows-x64 = 'bin/kei-mcp-server-windows-x64.exe'

Schema v1 (single string) still accepted — v0.19 brains load unchanged.

Implementation:
  brain.rs — new McpServerPath enum (Single / PerPlatform BTreeMap<String, String>)
  with #[serde(untagged)]. Brain::current_platform_key() maps std::env::consts
  (macos→darwin, x86_64→x64, aarch64→arm64) to canonical key format.
  mcp_server_path() now returns Result — looks up current platform,
  returns Error::NoPlatformBinary { os, arch, available } if missing.
  Pre-canonicalized cache field removed so partial v2 brains load for
  status (just fail at actual resolve).
  brain_validate.rs — validate_schema accepts MIN..=MAX range (1 or 2);
  check_all_paths iterates v2 map entries for confinement check.

ClientAdapter::post_attach_hint() — default method + 4 overrides:
  claude_code: 'run /help in Claude Code to verify the MCP server is reachable'
  cursor: 'reload Cursor window (Cmd+Shift+P → Reload Window) to pick up the MCP server'
  continue_adapter: 'reload the Continue extension in VS Code (or restart) to pick up the MCP server'
  zed: 'run Zed :reload command to pick up the MCP server config'
  attach.rs prints adapter.post_attach_hint() instead of the hardcoded
  Claude-Code-specific string. No more client leak in orchestrator.

Error::NoPlatformBinary { os, arch, available } with thiserror Display.

Tests: 16 existing + 4 new = 20/20 pass.
  - schema_v2_current_platform_resolves
  - schema_v2_missing_current_platform_errors (macOS-gated)
  - schema_v1_still_readable_with_v2_code
  - post_attach_hint_is_adapter_specific

Constructor Pattern: all files <200 LOC (continue_adapter.rs 197 LOC
max). All fns <30 LOC (current_platform_key + check_all_paths 19 LOC max).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:19:58 +08:00
Parfii-bot
e43b13335e fix(v0.19.2): polish — marker perms 0600, ANSI sanitize, manifest size bound, dead-code cleanup
Closes remaining MEDIUM/LOW audit findings not in v0.19.0 security wave.

M1 — marker file 0600 perms (unix)
  config.rs::write() applies chmod 0o600 after write, cfg(unix) gated.
  Test marker_file_has_0600_perms_on_unix asserts mode & 0o777 == 0o600.

L9 — ANSI-escape sanitization
  New module display.rs (27 LOC) — sanitize_display(&str) replaces
  ASCII < 0x20 OR == 0x7F with '?', leaves space + unicode alone.
  Applied in status.rs + attach.rs to brain_name / brain_path /
  attached_at / client_type / config_path / mcp_path before print.
  Test status_sanitizes_control_chars_in_brain_name asserts
  sanitize_display('evil\x1b[2Jpayload') → 'evil?[2Jpayload'.

L12 — manifest size bound
  brain_validate.rs const MAX_MANIFEST_BYTES = 64 * 1024; metadata
  check before read_to_string. New Error::ManifestTooLarge { size, max }
  with thiserror Display impl. Test manifest_too_large_rejected
  writes 100 KB manifest, asserts error + marker not written.

Dead-code cleanup:
  - Error::NotAttached: #[allow(dead_code)] + comment (reserved for
    future detach subcommand when no marker exists)
  - config::has_client: #[allow(dead_code)] + comment (reserved for
    future multi-brain support)
  - mount.rs / detach.rs: dropped unused ClientAdapter import

brain.rs module doc-comment expanded — lists all v0.19 invariants:
path confinement, symlink reject, name regex, 64 KiB manifest cap,
schema v1; notes v2 (multi-platform) lands in v0.20.

Tests: 16 existing + 3 new = 19/19 pass.
cargo check -p keisei: zero warnings in keisei crate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:17:14 +08:00
Parfii-bot
3ad64332bc Merge fix/v0.19-audit-hardening — security HIGH + critic HIGH consolidated (conflicts resolved)
4 adapter conflicts resolved by taking fix-wave version — preserves
security hardening (path confinement, name validation + collision
refuse, paths::resolve_home SSoT, fsx::write_atomic_json via
NamedTempFile). jsonmcp.rs from v0.19 refactor commit fa253d0
became dead code post-merge; deleted + unregistered from adapters/mod.rs.

If future iteration wants jsonmcp-style shared merge, it should
layer on top of the security-hardened adapter inline logic, not
replace it.

Tests: 16/16 pass (11 pre-existing + 5 new adversarial).
cargo check -p keisei: clean (4 pre-existing dead-code warnings,
not introduced by this merge).
2026-04-22 16:37:19 +08:00
Parfii-bot
d32ca0bc28 fix(v0.19): audit hardening — 3 security HIGH + 3 critic HIGH + 2 critic MEDIUM
Closes consolidated findings from wave-audit (critic + security + architect):

SECURITY HIGH:
  H1 path escape — Brain::load rejects absolute mcp_server paths +
    any containing '..'; canonicalize + starts_with(root) assertion;
    new Error::PathEscape variant.
  H2 brain name validation + clobber refuse — regex ^[a-z][a-z0-9_-]{0,63}$
    enforced at Brain::load; adapters refuse to overwrite existing
    mcpServers[name] with NameConflict (unless same content).
  H3 symlink reject at canonicalize — std::fs::symlink_metadata()
    called before canonicalize; Error::BrainIsSymlink with resolved
    target path; prevents USB → $HOME pivot.

CRITIC HIGH:
  #1 rusqlite dep deleted (zero uses in src/, pulls C toolchain).
  #3 BrainPaths memory/artifacts/manifests now Option<String>
    (only mcp_server required; schema no longer lies about contract).

CRITIC MEDIUM:
  #1 _primitives/_rust/keisei/src/paths.rs (new, 23 LOC) — SSoT for
    $KEISEI_HOME/$HOME resolver; config.rs and claude_code.rs
    delegate instead of duplicating 7-line block.
  #2 canonicalize error preserves io::Error via new Error::BrainLoad
    { path, source } with #[source] attribute.
  #5 fsx::write_atomic_json rewrite via tempfile::NamedTempFile
    + persist — Windows-safe, cross-fs-fallback handling.

New module split (Constructor Pattern): brain.rs (104 → 122) now a
thin orchestrator over brain_validate.rs (108 LOC) which owns
symlink-reject / canonicalize-root / read-manifest / validate-schema
/ validate-name / check-relative-in-root / canonicalize-in-root.

Deps: regex = { workspace = true }, tempfile = "3" (runtime).
Workspace-level regex = "1.10" added.
MANIFEST.toml [primitive.keisei] deps updated.

Tests: 11 pre-existing + 5 adversarial:
  - manifest_with_absolute_mcp_server_rejected — proves /usr/bin/python3
    CANNOT land in settings.json (PathEscape + marker absent asserts)
  - manifest_with_parent_traversal_rejected — ../../etc/passwd rejected
  - manifest_with_invalid_name_rejected — 'claude-ide!' rejected
  - brain_path_is_symlink_rejected — USB → $HOME pivot blocked
  - attach_refuses_to_clobber_existing_mcp_entry — NameConflict on diff

All 16 pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 16:36:11 +08:00
Parfii-bot
fa253d04cc refactor(v0.19): extract adapters/jsonmcp.rs shared MCP entry merge/remove
v0.19 agent's additional factorization that wasn't captured in the
initial branch commit. Extracts shared merge/remove-named helpers
for claude-code/cursor/zed into adapters/jsonmcp.rs (70 LOC). 3
adapters simplify significantly (-65/-68/-102 LOC each).

Also: #[allow(dead_code)] on Error::AdapterFailed (surfaced by
mount/detach orchestration; reserved for library consumers).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 16:35:02 +08:00
Parfii-bot
e6cab72587 feat(v0.19): multi-client adapters + detach/mount/list-adapters + schema v2
Extends keisei CLI from single-client (v0.18) to multi-client exobrain:
new subcommands detach/mount/list-adapters, 3 new adapters (Cursor,
Continue, Zed), schema v2 for ~/.claude/keisei-attached.toml with
[[attachments]] array (v1 backward-compat via untagged serde).

New subcommands:
  detach — iterate marker attachments, call adapter.detach() on each,
    then delete marker. Real strip of mcpServers entry per adapter.
  mount <brain> — auto-attach to ALL detected clients in one call.
  list-adapters — tabular status (name / detected / config path).

New adapters (each <130 LOC mirrors claude_code.rs pattern):
  adapters/cursor.rs — .cursor/mcp.json project-local, fallback
    ~/.cursor/mcp.json global.
  adapters/continue_adapter.rs — ~/.continue/config.json with
    experimental.modelContextProtocolServers key.
  adapters/zed.rs — ~/.config/zed/settings.json (Linux) or
    ~/Library/Application Support/Zed/settings.json (macOS) with
    context_servers key. Zed schema marked [UNVERIFIED] pending docs.

Schema v2 (~/.claude/keisei-attached.toml):
  [[attachments]]
  client_type = "claude-code"
  config_path = "/Users/.../.claude/settings.json"
  [[attachments]]
  client_type = "cursor"
  config_path = "/Users/.../proj/.cursor/mcp.json"

v1 marker migration: untagged serde accepts legacy client_type=string,
upgrades to single-entry attachments[] on next write.

Tests: 5 (v0.18) + 6 new = 11 integration tests, all pass:
  - attach_then_status_happy_path
  - attach_missing_manifest_errors
  - attach_unsupported_schema_errors
  - status_without_attach_is_clean
  - attach_writes_marker_with_expected_fields
  - mount_with_claude_code_only_detected (new)
  - mount_with_no_client_detected (new)
  - detach_round_trip (new)
  - detach_preserves_other_mcp_servers (new)
  - list_adapters_prints_expected_rows (new)
  - schema_v1_to_v2_migration (new)

Known issues (defer to follow-up commit):
  - CRITIC HIGH#1: rusqlite declared but unused
  - CRITIC HIGH#3: BrainPaths fields required but only mcp_server used
  - SECURITY H1/H2/H3: brain path/name not validated before writing
    into client config — will be addressed before tagging v0.19.0

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 16:04:45 +08:00
Parfii-bot
3bb9ba7911 feat(v0.18): keisei CLI MVP — exobrain attach/status
Phase 3 of exobrain architecture. Ships the entry-point CLI
that mounts a portable brain (memory + artifacts + manifests +
mcp-server) into an AI client via one command.

MVP scope: 2 subcommands (attach, status), 1 adapter (claude-code).
detach + mount + multi-client deferred to v1.0.

New Rust crate _primitives/_rust/keisei/ — 10 src files + 1 tests
(Constructor Pattern: all files <150 LOC, all fns <=23 LOC).
  main.rs (53 LOC) — clap dispatch
  error.rs (36 LOC) — thiserror enum (BrainNotFound,
    UnsupportedSchema, NoClientDetected, Io/Toml/Json #[from])
  brain.rs (103 LOC) — Brain::load() reads brain/manifest.toml
    schema_v1 (name, created, paths.{memory,artifacts,manifests,
    mcp_server})
  adapter.rs (38 LOC) — ClientAdapter trait (detect/attach/
    detach/config_path) + registry
  adapters/claude_code.rs (121 LOC) — writes MCP server entry
    into ~/.claude/settings.json via merge_mcp_entry (23 LOC,
    mirrors jq-merge pattern from install/lib-hooks.sh)
  attach.rs (44 LOC) — load brain, detect client, call adapter,
    write SSoT ~/.claude/keisei-attached.toml
  status.rs (62 LOC) — read SSoT, print brain name/path/client/
    timestamp + health check (mcp_server binary exists?)
  config.rs (97 LOC) — KeiseiAttached TOML struct + KEISEI_HOME
    env hook for test isolation
  tests/integration.rs (142 LOC) — 5 cases via tempfile + Mutex
    env guard: happy-path, missing-manifest, unsupported-schema,
    no-attach-state, marker-field verification

Workspace: keisei added to _primitives/_rust/Cargo.toml members.
MANIFEST.toml: [primitive.keisei] rust kind, kei-ledger-style
deps (rusqlite bundled, stub for future artifact reads), added
to full profile (standalone opt-in via --add=keisei).

README Rust crates table gains 1 row; count marker untouched.
CHANGELOG [Unreleased] bullet added.

Usage:
  keisei attach /path/to/brain    # mounts into current Claude Code
  keisei status                   # shows mounted brain + health

Next (v0.18 follow-ups): detach impl, cursor/continue adapters,
list-adapters subcommand.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 15:52:40 +08:00
Parfii-bot
14ae1af585 Merge feat/v0.16.1-polish — dynamic schema + mode matrix Phase 3.6 2026-04-22 15:13:05 +08:00
Parfii-bot
d95a3ba48c feat(v0.16.1): dynamic schema SSoT + KNOWN_SCHEMAS drift-test + mode-matrix Phase 3.6
Three polish items from post-audit parallel agent.

1. Dynamic schema whitelist (drops hardcoded const drift)
   _assembler/src/schemas_export.rs (NEW, 136 LOC) — loader cube,
     priority path $AGENT_ROOT/artifacts/schemas.json →
     ~/.claude/agents/artifacts/schemas.json → BUILTIN fallback.
     Hand-rolled JSON parser (no serde_json dep).
   _assembler/src/validator.rs delegates to schemas_export::load,
     keeps KNOWN_ARTIFACT_SCHEMAS alias for back-compat.
   _primitives/_rust/kei-artifact/src/export.rs (NEW, 82 LOC) —
     write() + render() + default_path().
   _primitives/_rust/kei-artifact/src/cli_cmds.rs (NEW, 126 LOC) —
     extracted cmd_emit/get/list/chain so main stays <200 LOC.
   ExportSchemas + ListSchemas subcommands; cmd_register
     auto-refreshes export file (best-effort).

2. KNOWN_SCHEMAS SSoT — documented-dual-const + drift-test
   (Option "simpler than new crate"). SSoT in kei-artifact's
   BUILTIN; schemas_export::BUILTIN is a documented mirror;
   builtin_schemas_do_not_drift_from_kei_artifact test in
   validator.rs parses the primitive's source at test time and
   diffs. <30 LOC change. No workspace structural change —
   assembler stays decoupled from runtime primitive.

3. Agent-to-mode matrix + wizard Phase 3.6
   _blocks/mode-matrix.md (NEW, 24 LOC) — 11-row table mapping
     agent role × recommended mode blocks.
   skills/new-agent/SKILL.md — new Phase 3.6 (between name-confirm
     3.5 and manifest-write 4). AskUserQuestion with 5
     cognitive-mode options (skeptic/devils-advocate/minimalist/
     maximalist/first-principles, multiSelect). Appends picked
     labels to manifest's blocks array. Defaults to NONE.
   _blocks/README.md adds one-line reference to the matrix.
   _assembler/tests/mode_blocks.rs (NEW, 78 LOC) — 3 integration
     tests lock the wiring.

README.md — all accumulated count + pre-built-binaries + plugin
section edits from the v0.16 cycle consolidated here (will be
replaced by markers in v0.17 counts-autogen refactor).

Tests: assembler 24 → 33 (+9), kei-artifact 24 → 31 (+7), total
48 → 64. cargo check --workspace clean.

Constructor Pattern: largest new file validator.rs 180 LOC.

Pre-existing flagged for separate refactor: kei-artifact
validate.rs 268 LOC (not touched by this polish).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 15:10:46 +08:00
Parfii-bot
f77c1b7fdc fix(v0.15.1): RED-1 CVE + typed-handoff + schema minItems
Security hotfix — v0.15.1 Wave 1 fixes from 4-parallel audit.

RED-1 (CVE): KEI_DISABLED_HOOKS tokenized match — was `*all*`
substring-glob (trivially bypassable via "install", "wall-clock", etc.),
now exact-token split on comma/space. Patched in all 9 hooks:
no-hand-edit-agents, assemble-agents, assemble-validate, tomd-preread,
agent-fork-logger, site-wysiwyd-check, error-spike-detector,
milestone-commit-hook, session-end-dump.

RED-2 (observability): minimal profile whitelist now includes
agent-fork-logger and session-end-dump (ledger + trace paths) so
observability is not silently lost on minimal installs.

HIGH: review.json schema minItems:1 on findings — rejects empty
reviews; new Rust test review_schema_rejects_empty_findings.

HIGH: typed-handoff wire-up — produces_artifact declared at top
level on 5 manifests (kei-security-auditor, kei-validator,
kei-architect, kei-code-implementer, kei-critic); duplicate
per-handoff declarations removed.

MED: kei-artifact validate.rs gains warn_unsupported_keywords —
non-fatal stderr warning when schema uses keywords outside the
hand-rolled 2020-12 subset.

LOW: CI Node matrix dropped 18, now ['20','22'].

Doc drift: skills/hooks-control/SKILL.md reflects tokenized-match
semantics and updated minimal-profile hook list.

Tests: 191 Rust workspace + 30 assembler (both pass). RED-1
reproducer 10/10 (4 former-CVE vectors blocked, 5 legit vectors
accepted, empty passes).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 15:08:51 +08:00
Parfii-bot
59725ae021 Merge branch 'feat/v0.15-artifact-handoff' — kei-artifact typed handoff pipeline
# Conflicts:
#	_primitives/MANIFEST.toml
2026-04-22 14:15:17 +08:00
Parfii-bot
24c584ee50 fix: remove genesis-scan from public kit (internal tool, Bundle-only)
Per user decision: publishing the sensitive IP pattern blocklist via public
scanner is leak of the blocklist itself (attack surface). genesis-scan
remains in PROJECT-E (private); user-global
~/.claude/hooks/genesis-leak-guard.sh (runtime hook) separate.

Deleted:
- _primitives/_rust/genesis-scan/ (whole crate, 5 files)
- hooks/git-pre-commit-genesis.sh (scanner companion)

Modified:
- workspace Cargo.toml -1 member (24→23)
- MANIFEST.toml — removed [primitive.genesis-scan] + core/full profile refs
- .github/workflows/ci.yml — removed genesis-scan job
- README.md — 7 count/description edits (24→23 rust, 10→9 hooks, 37→36 full)
- install.sh — 5 edits (--help + menus)
- mcp-server tool-registry.ts + test — scanner removed from MCP surface
- kei-sleep-queue.sh — removed scan_prompt() pre-submit hook
- 2 sleep-on-it skill phases — removed genesis-scan references

Tests: 160 Rust (was 167, -7 genesis-scan tests as expected), 24 assembler unchanged.
2026-04-22 14:11:22 +08:00
Parfii-bot
537589e6a7 feat(primitives): kei-artifact typed handoff pipeline (BMAD-style doc passthrough)
- kei-artifact Rust crate (25th): schema registry + artifact store + SHA-256 id + chain walker
- 5 schemas (JSON Schema 2020-12 strict): spec / plan / patch / review / research
- Manifest extension: optional produces_artifact + expects_artifact per handoff (non-breaking)
- Validator extension: KNOWN_ARTIFACT_SCHEMAS whitelist check + 4 new tests
- 3 kei-* manifests updated with typed handoff (architect→code-implementer→critic chain)
- compose-solution phase-5 cross-ref to kei-artifact

Tests: 189 Rust workspace (was 167, +22 artifact tests) + 24 assembler (was 20, +4 validator tests)
2026-04-22 14:10:08 +08:00
Parfii-bot
81462a03ef chore(rust): misc schema/main refactor in 8 crates (assorted CP splits)
kei-chat-store, kei-content-store, kei-crossdomain, kei-curator, kei-router, kei-sage, kei-search-core, kei-social-store, kei-task — small schema + main refactors for test pass parity (167 Rust tests, 20 assembler).
2026-04-22 13:36:17 +08:00
Parfii-bot
37c8e857d7 refactor(mock-render): split main.rs 227 LOC into 4 cubes (F5a Constructor Pattern)
main.rs 227→55 + cli_args.rs + cmd_screenshot.rs + cmd_lock.rs + cmd_verify.rs (each <100 LOC).
2026-04-22 13:36:17 +08:00
Parfii-bot
ff10f76469 fix(kei-auth): remove --key CLI flag (F12 HIGH — /proc/cmdline leak)
KEI_AUTH_KEY env only. On missing env, explicit error with openssl rand suggestion + RULE 0.8 SSoT pointer.
2026-04-22 13:36:17 +08:00
Parfii-bot
363352e7bf fix(kei-refactor-engine): retract 'git apply-ready' claim (F1 RELEASE BLOCKER)
Output renamed plan-autoresolve.md; header changed to '# AUTO-RESOLVABLE items' (no fake --- a/ /+++ b/ wrapper).
Added test autoresolve_output_is_not_claimed_as_diff.
Template updated: user manually applies, not via git apply.
2026-04-22 13:36:17 +08:00
Parfii-bot
ef95bf2a7c fix(kei-store): path-traversal guard (F2 RELEASE BLOCKER) + S3 stub gate (F7) + GitHub RULE 0.1 guard (F8)
F2: filesystem.rs + s3.rs 'fn full' now Result<PathBuf>, rejects absolute + ParentDir components. 7 new unit tests.
F7: factory.rs rejects 'backend=s3' without KEI_STORE_ALLOW_S3_STUB=1; backend_name() = 's3-local-stub'.
F8: github.rs push() blocks github.com unless KEI_STORE_ALLOW_GITHUB_PUSH=1 (RULE 0.1).
2026-04-22 13:36:17 +08:00
Parfii-bot
a3769ebbb6 refactor(rust-core): Constructor-Pattern splits in kei-router + kei-auth
- kei-router: extract kw_tables.rs from keywords.rs (keep <200 LOC)
- kei-auth: extract new_payload + encode_token helpers
2026-04-22 12:57:12 +08:00
Parfii-bot
adc007b7b0 feat(primitives): 10 Rust crates extracted from LBM (Genesis-scrubbed)
- kei-router — keyword-dispatch meta-tool (CfC ML fallback removed)
- kei-sage — Obsidian-style knowledge graph, FTS5 + BFS + PageRank
- kei-task — task DAG with deps, milestones, dependency-chain queries
- kei-chat-store — Claude conversation session persistence + FTS search
- kei-crossdomain — typed-edge store + BFS cross-domain glue
- kei-search-core — 3-wave deep research with microcent budget cap
- kei-content-store — asset + prompt + campaign registry
- kei-social-store — people + interactions CRM (lite)
- kei-curator — edge-decay graph hygiene utility
- kei-auth — multi-tenant session tokens (replaces single-bearer)

Genesis-scan pre-import pass: skipped pkg/mxl1/*, pkg/inference/*, pkg/trainer/*,
pkg/nc01/*, internal/ml/* (all Genesis/CfC adjacent, sensitive IP).
Security: skipped tools_threat/radio/protocol/med/mlreg (offensive/banned).
Domain verticals skipped: hr/legal/infra/ops/api/osint/edu/geo/hw/finance.

New 'mcp' profile in MANIFEST.toml bundles all 10 for MCP server deployment.

Workspace now 24 crates, cargo check --workspace clean, 94 workspace tests pass.
2026-04-22 12:48:56 +08:00