M0: compilable skeleton — Kigi 0.1.0 fork surgery

Hard fork of xai-org/grok-build (Apache-2.0) re-targeted as Kigi, an
unofficial Kimi Code CLI community build.

Rename & identity
- 72 xai-*/xai-grok-* crates -> kigi-* (explicit: xai-grok-pager-bin ->
  kigi-bin [binary `kigi`], xai-grok-pager -> kigi-tui; rest mechanical);
  ptyctl, ptyctl-cli, third_party/ unchanged; proto package
  xai.grok.tools.v1 -> kigi.tools.v1
- Config home ~/.kigi (KIGI_SHARE_DIR override), env prefix GROK_* ->
  KIGI_*, `kigi --version` carries the unofficial-community-build notice
- clap identity, help text, startup banner, prompt templates rebranded
  (templates re-encrypted)

Deletions (PRD removal list #5/#6/#7/#9/#10)
- voice input (xai-grok-voice) and all TUI wiring
- telemetry: Mixpanel client, external OTel stream, Sentry, OTLP layers,
  trace/GCS/S3 upload queues (kigi-file-utils halved), workspace upload
  module & dc_log, heap-profile uploader, auth-diagnostics uploader,
  session-analytics halves of feedback; local zero-egress observability
  preserved in new kigi-log crate (unified log, --debug firehose,
  subsystem file logs, opt-in instrumentation)
- announcements (crate, remote-settings fields, TUI surfaces)
- plugin marketplace (crate, sources/browse/CTA/extensions-modal tab);
  direct plugin install/uninstall/update via kigi-agent git_install kept
- relay/gateway/assets endpoints and features (agent relay, headless
  relay transport, gateway bridge, LeaderEnvUrls); leader IPC socket now
  ~/.kigi/leader.sock + KIGI_LEADER_SOCKET, no ws-url derivation
- functional types rehomed instead of deleted: PermissionMode ->
  kigi-config-types, McpInitStrategy -> kigi-mcp, PrCreationSource ->
  session signals, TerminalDiagnostics -> kigi-pager-render, agent_id ->
  shell util

Endpoints
- kigi-env rewritten: single production KigiEndpoints {coding_api_base_url
  https://api.kimi.com/coding/v1 (KIGI_CODE_BASE_URL), oauth_host
  https://auth.kimi.com (KIGI_OAUTH_HOST), update_base_url (GitHub
  Releases API), upgrade_page_url}; GrokBuildEnvironment enum deleted

Toolchain & workspace hygiene
- Rust 1.97.0 pinned; edition 2024; full cargo update; git2 hoisted to
  workspace at 0.21 (Option->Result API migration), quick-xml 0.41
- Root Cargo.toml hand-maintained (PRD §8.1): version 0.1.0 inherited by
  all members, members sorted, unused deps pruned
- cargo-deny advisories gate (deny.toml with documented transitive
  exceptions); CI workflow (check/clippy/fmt/deny/test, macOS+Linux)
- cross-crate test seams re-gated behind `test-support` cargo feature;
  insta snapshot baselines renamed to the kigi_tui prefix
- clippy --workspace --all-targets: zero warnings; fmt clean

Fixes surfaced by the port
- updater probe/installer divergence (bin/kigi vs bin/grok symlink set)
- idle model-metadata refresh dead under KIGI_CODE_BASE_URL override
  (new is_effective_coding_endpoint_url, loopback+override aware)
- macOS symlinked-TMPDIR fixture canonicalization (foreign_sessions,
  fast-worktree); RSS measurement tests serialized via serial_test

Docs & legal (Apache §4)
- NOTICE added (upstream attribution + change statement); THIRD-PARTY
  notices sustained; kigi-tools ported-code notices extended; README,
  CONTRIBUTING, SECURITY, AGENTS.md rewritten

Out of scope for M0 (tracked): Kimi auth/inference (M1), search/fetch,
command parity, config import (M2), Computer Hub excision & final
brand-token sweep (M2), distribution & self-update rewrite (M3).
This commit is contained in:
2026-07-17 05:31:01 -04:00
commit d6c20fc13f
2612 changed files with 1353757 additions and 0 deletions
@@ -0,0 +1,93 @@
---
name: best-of-n
description: >
Implement a task N ways in parallel and pick the best. Spawns multiple
subagents in isolated worktrees, evaluates all candidates, and applies the
winner. Use when asked to "best of n", "try multiple approaches", "parallel
implementations", "/best-of-n", or "/bon".
metadata:
short-description: "Parallel implementation tournament"
---
# /best-of-n -- Parallel Implementation Tournament
Implement a task multiple different ways in parallel, evaluate all candidates,
and apply the best one.
## Usage
`/best-of-n [N] <task>`
- If the first token is a number 2-10, it sets the candidate count; the rest is the task.
- If omitted, N defaults to 3.
Examples:
- `/best-of-n implement the login page` (3 candidates)
- `/best-of-n 5 refactor the auth module` (5 candidates)
## Steps
1. Parse the user's message to extract **N** (candidate count, default 3) and
the **task description**.
2. Spawn **N** subagents in a single message (parallel tool calls). Use the
`task` tool for each with:
- `subagent_type`: `"general-purpose"`
- `isolation`: `"worktree"`
- `run_in_background`: `true`
- `description`: `"Candidate <number>"`
- `prompt`: the task description, plus
`"You are candidate <number> of <N> independent implementations. Implement the task fully. When done, summarize your approach and the changes you made."`
3. Wait for all candidates to complete using `get_task_output` with `block: true`
or `wait_tasks` with `mode: "wait_all"`.
4. Evaluate and pick the winner using the criteria below.
5. Apply the winner's changes from its worktree to the main workspace.
Review the changes in context and fix any remaining issues.
6. End your response with `WINNER: <number>` (1-N).
## Evaluation Criteria
Evaluate each candidate on these axes, in order of importance:
1. **Correctness** -- Does the candidate actually solve the task? Does it handle
the requirements completely, or does it miss important aspects? Are there
logic errors, type errors, or broken imports?
2. **Code Quality** -- Is the code clean, readable, and well-structured? Does it
follow the patterns and conventions of the surrounding codebase? Does it
avoid unnecessary complexity?
3. **Safety** -- Does the candidate avoid introducing bugs, security issues, or
breaking changes to existing functionality?
## How to Decide
- Focus on correctness first. A candidate that fully solves the task with minor
style issues beats one that is beautifully written but incomplete or wrong.
- If multiple candidates are equally correct, prefer the one with cleaner code
and better codebase integration.
- If a candidate introduces unnecessary changes beyond the task scope, count
that against it.
- If all candidates are poor, still pick the least bad one.
## Presenting Your Evaluation
Before announcing your choice, present a structured comparison:
| Dimension | Candidate 1 | Candidate 2 | ... |
|-----------|-------------|-------------|-----|
| Correctness | Short verdict | Short verdict | ... |
| Code Quality | Short verdict | Short verdict | ... |
| Safety | Short verdict | Short verdict | ... |
Then list key findings:
| Finding | Severity | Candidate 1 | Candidate 2 | ... |
|---------|----------|-------------|-------------|-----|
| Specific issue | High/Medium/Low | How handled | How handled | ... |
State which candidate you chose and why.
@@ -0,0 +1,287 @@
---
name: check-work
description: >
Check your work with a verification subagent that reviews diffs, runs builds
and tests, and evaluates correctness. Read this file for instructions. Use when
asked to "check work", "verify changes", "self-verify", "/check-work", "/check",
"/verify", or "/self-verify".
metadata:
short-description: "Verify changes with a subagent"
---
# /check-work -- Self-Verification
Verify work by spawning a verifier subagent, checking its verdict, and
fixing issues until it passes.
## Usage
`/check-work [focus area]`
The optional focus area tells the verifier to pay special attention to specific
aspects of the changes (e.g. "auth logic and JWT handling").
## Mode Detection
Determine which mode you are in before proceeding:
- **Same-turn mode**: There is a user task alongside this skill (e.g. headless
`--check`). **Complete the task fully first**, then proceed to Step 1 below.
- **Standalone mode**: There is no task — just `/check-work` (or the alias `/check`) or the skill was invoked
after a previous turn. Proceed directly to Step 1.
## Steps
1. Call the `task` tool with:
- `description`: must start with `"[checking my work]"` followed by a short label
- `subagent_type`: `"general-purpose"`
- `run_in_background`: `false`
- `prompt`: copy the **VERIFIER PROMPT** section below verbatim. If a focus
area was specified by the user, append this to the prompt:
```
## Additional Focus
<focus area text>
Pay special attention to these areas during verification.
```
2. Read the subagent's result. Look for `VERDICT: PASS` or `VERDICT: FAIL`.
3. If **PASS**: summarize what the verifier confirmed and stop.
4. If **FAIL** (or no verdict found): fix the issues the verifier identified,
then go back to step 1. Repeat up to 3 times.
## VERIFIER PROMPT
You are an expert verifier. Your job is to determine whether the work done in
this session correctly and completely addresses the user's requests.
You already have the full conversation context, so you know what the user asked
for, what approach was taken, what tools were used, and what outcomes were
observed. You also have full access to the same environment and tools the
original agent had.
=== SCOPE ===
Determine what to verify:
- If a **focus area** was specified (see Additional Focus below), verify that
specific area. Use the full session trace for context -- understand what was
asked, what was done, and what state the environment is in -- but scope your
verdict to the focused area.
- If no focus area was specified, verify **all work done in this session**.
=== WORKFLOW ===
Every verification runs two phases. Phase A (Trace Review) always runs.
Phase B (Code Review) runs when code review is relevant to the task.
--- PHASE A: TRACE REVIEW ---
This phase reviews what the agent did, whether it completed all tasks, and
whether its outputs were correct. Run this for every verification.
1. UNDERSTAND THE REQUEST:
Read through the conversation to identify everything the user asked for --
not just the first message, but follow-up requests, corrections, and
clarifications across the entire session. Restate these as a concrete
checklist of deliverables or success criteria.
Include all task types:
- Code tasks (implement feature, fix bug, refactor)
- Operational tasks (submit the eval job, deploy to staging, kick off CI)
- Git/PR tasks (push the branch, create the PR, address review comments)
- Research tasks (analyze data, investigate a failure, find root cause)
- Q&A tasks (explain how X works, compare approaches, answer a question)
- Configuration tasks (update settings, add environment variables, modify configs)
If a focus area was specified, the checklist should center on that area
but include related items that affect the verdict.
2. RECONSTRUCT WHAT HAPPENED:
Trace the actions the agent actually took. For each tool call, command, or
action in the conversation, identify what the outcome was. Look for:
- Actions that failed or produced unexpected results
- Things the user asked for that were never attempted
- Things the agent said it would do but did not actually do
- Work the agent deferred to the user that it could have done itself
(e.g. printing instructions instead of running a command)
- Questions answered incorrectly or incompletely
- Reasoning errors in the agent's analysis or explanations
3. VERIFY CURRENT STATE:
Gather evidence about what actually happened by inspecting the environment
yourself. Do not trust the conversation's claims -- verify them:
- If the session involved code changes, read the modified files.
- If the session involved submitting jobs or API calls, check their status.
- If the session involved running commands, verify their effects.
- If the session involved creating resources (PRs, branches, configs),
confirm they exist and are in the expected state.
- If the session involved answering questions, verify the answers are
correct by checking the source material yourself.
--- PHASE B: CODE REVIEW ---
Run this phase when the task involves code in any way. Examples:
- The agent wrote or modified code during this session
- The user asked the agent to review existing code (security audit,
code review, architecture review)
- The task involved evaluating code correctness, performance, or security
- The changes include code-like configuration (BUILD files, CI configs,
k8s manifests, IaC)
Skip this phase only if the session was purely non-code with no code
involvement at all (general Q&A, operational tasks with no code context,
data analysis, research).
4. COLLECT THE DIFF OR READ THE CODE:
If code was written or modified: run `git diff` to see unstaged changes.
Run `git diff --cached` to see staged changes. Run `git log --oneline -3`
and `git diff HEAD~1..HEAD` to check for recent commits. Combine these to
get the full picture of all changes made during this session.
If the session was a code review of existing code (no modifications): read
the files the agent reviewed. You need the actual source to verify whether
the agent's analysis was correct and thorough.
In both cases, read the relevant files and their surrounding context to
understand the scope.
5. EVALUATE THE CODE:
Consider the following criteria carefully:
a) CORRECTNESS: If code was written or modified -- does it compile, run,
and pass tests? A broken build or failing tests is an automatic FAIL.
If this was a review of existing code -- was the agent's assessment of
correctness accurate?
b) ADEQUACY: Do the changes or the review adequately address the user's
request? Are all requested features implemented, fixes applied, or
review areas covered? Were all non-code tasks completed (not just the
code part)? There could be several possible correct solutions -- all
correct solutions should be considered valid.
c) EXCESS: Do the changes do anything in excess that could negatively
impact the codebase? Unnecessary refactors, added complexity, unrelated
modifications, or gold-plating beyond what was asked.
d) EDGE CASES: Do the changes sufficiently handle edge cases without being
overly verbose or complex? Missing critical edge cases is a problem, but
over-engineering for hypothetical scenarios is also a problem.
6. BUILD AND TEST:
Read the repo's AGENTS.md / Claude.md (the root file and any in the
directories of changed files) and README for build/test commands. Run them:
- Build the project (e.g. cargo check, npm run build, tsc). A broken build
is an automatic FAIL.
- Run the test suite (e.g. cargo test, pytest, npm test). Failing tests are
an automatic FAIL.
- Run linters/type-checkers if configured (cargo clippy, eslint, mypy, tsc).
7. DESIGN AND RUN VERIFICATION CHECKS:
You are encouraged to write and run your own tests or checks to verify the
work is correct. This may include:
- Writing small test scripts that exercise new/changed functionality
- Running the application and exercising it (curl endpoints, invoke CLIs)
- Adding assertions that confirm the expected behavior
- Checking boundary conditions and error paths
- Querying APIs or services to confirm actions were completed
You may need to run several tool calls, tests, checks, or other analysis
to determine correctness. Take your time -- thoroughness matters more
than speed.
8. REVIEW THE CODE:
Read the diff (or the reviewed files) and surrounding source for context.
If code was written, look for issues the agent introduced. If the agent
reviewed existing code, verify the agent's findings are correct and check
for issues the agent missed. In both cases look for:
- Bugs: logic errors, off-by-one, null/undefined access, unhandled errors
- Security: injection, XSS, unsafe deserialization, secrets in code
- Missing validation at system boundaries (user input, API responses)
- Regressions: did the change break existing behavior?
- Test quality: are new tests circular, over-mocked, or only covering
happy paths?
- Project-instruction compliance: where the repo's AGENTS.md / Claude.md
files (read in step 6) state reviewable rules (style, structure, naming,
conventions, policy), a change that violates one is a FAIL -- cite the
rule and file:line. If they state no review-relevant rules, do not invent
violations.
--- VERDICT ---
9. VERDICT:
After completing your analysis, end your response with exactly one of:
VERDICT: PASS -- the work correctly and adequately addresses the user's requests
VERDICT: FAIL -- there are issues that need fixing
If FAIL, describe what is broken, the exact error output, and what
specifically needs to change. Be precise about file paths and line numbers
for code issues, and specific about what was missed or incorrect for
non-code issues.
If PASS, describe the verification process and what evidence confirms
success.
=== IMPORTANT PRINCIPLES ===
- Think through problems step by step. When you are unsure, gather more
information before concluding.
- You should assume that if the code fails to compile or run, the changes do
not address the user's request.
- Verify outcomes, not just code. If the user asked "submit the eval job",
check whether the job was actually submitted and accepted -- do not just
verify that the code change that enables submission is correct.
- Do not accept proxy signals as proof of completion. Passing tests, a
successful build, or substantial effort are useful evidence only if they
cover every requirement in the checklist.
- Do not invent issues to fill space. If the work genuinely addresses the
user's requests correctly, say PASS. Nitpicks about style or theoretical
concerns that do not affect correctness should not cause a FAIL. However,
violations of rules explicitly stated in the repo's AGENTS.md / Claude.md
are policy, not nitpicks, and DO cause a FAIL.
- Focus on whether the work addresses what the user actually asked for, not
on what you might have done differently.
- Any temporary test files or modifications you create for verification
purposes are fine -- they will not affect the parent agent's workspace.
=== OUTPUT FORMAT ===
Write a structured verification report:
## Checklist
The user's requirements restated as a numbered list of concrete items.
Include all task types (code, operational, research, Q&A, etc.).
## Action Trace
For each checklist item: what was done, what tools/commands were used, and
whether the action succeeded. Note any items that were not attempted, answered
incorrectly, or deferred to the user.
## Diff Summary / Code Scope (Phase B only)
If code was written: brief description of what files changed and the scope.
If code was reviewed: which files were reviewed and what areas were covered.
## Evaluation
Assessment against each applicable criterion:
- **Correctness**: Does it compile, run, pass tests? (Phase B)
- **Adequacy**: Does it address the user's request? Were all tasks completed?
- **Excess**: Any unnecessary changes? (Phase B)
- **Edge Cases**: Sufficient coverage without over-engineering? (Phase B)
## Build & Test Results (Phase B only)
Output from builds, tests, and linters. Include exact command and result.
## Issues
For each issue found (skip this section entirely if none):
### Issue N -- Severity: bug/gap/regression/suggestion
- File: path/to/file.ext:LINE (for code issues)
- Description: what is wrong
- Evidence: exact error output, missing action, or incorrect answer
- Suggestion: how to fix
Then end with exactly:
VERDICT: PASS
or
VERDICT: FAIL
@@ -0,0 +1,192 @@
---
name: code-review
description: Run an extremely strict maintainability review for abstraction quality, giant files, and spaghetti-condition growth. Use for a deep code quality audit or an especially harsh maintainability review.
disable-model-invocation: true
---
# Strict Code Quality Review
Use this skill for an unusually strict review focused on implementation quality, maintainability, abstraction quality, and codebase health.
Above all, this skill should push the reviewer to be **ambitious** about code structure. Do not merely identify local cleanup opportunities. Actively search for "code judo" moves: restructurings that preserve behavior while making the implementation dramatically simpler, smaller, more direct, and more elegant.
## Core Prompt
Start from this baseline:
> Perform a deep code quality audit of the current branch's changes.
> Rethink how to structure / implement the changes to meaningfully improve code quality without impacting behavior.
> Work to improve abstractions, modularity, reduce Spaghetti code, improve succinctness and legibility.
> Be ambitious, if there is a clear path to improving the implementation that involves restructuring some of the codebase, go for it.
> Be extremely thorough and rigorous. Measure twice, cut once.
## Non-Negotiable Additional Standards
Apply the baseline prompt above, plus these explicit review rules:
0. **Be ambitious about structural simplification.**
- Do not stop at "this could be a bit cleaner."
- Look for opportunities to reframe the change so that whole branches, helpers, modes, conditionals, or layers disappear entirely.
- Prefer the solution that makes the code feel inevitable in hindsight.
- Assume there is often a "code judo" move available: a re-organization that uses the existing architecture more effectively and makes the change dramatically simpler and more elegant.
- If you see a path to delete complexity rather than rearrange it, push hard for that path.
1. **Do not let a PR push a file from under 1k lines to over 1k lines without a very strong reason.**
- Treat this as a strong code-quality smell by default.
- Prefer extracting helpers, subcomponents, modules, or local abstractions instead of letting a file sprawl past 1000 lines.
- If the diff crosses that threshold, explicitly ask whether the code should be decomposed first.
- Only waive this if there is a compelling structural reason and the resulting file is still clearly organized.
2. **Do not allow random spaghetti growth in existing code.**
- Be highly suspicious of new ad-hoc conditionals, scattered special cases, or one-off branches inserted into unrelated flows.
- If a change adds "weird if statements in random places", treat that as a design problem, not a stylistic nit.
- Prefer pushing the logic into a dedicated abstraction, helper, state machine, policy object, or separate module instead of tangling an existing path.
- Call out changes that make the surrounding code harder to reason about, even if they technically work.
3. **Bias toward cleaning the design, not just accepting working code.**
- If behavior can stay the same while the structure becomes meaningfully cleaner, push for the cleaner version.
- Do not rubber-stamp "it works" implementations that leave the codebase messier.
- Strongly prefer simplifications that remove moving pieces altogether over refactors that merely spread the same complexity around.
4. **Prefer direct, boring, maintainable code over hacky or magical code.**
- Treat brittle, ad-hoc, or "magic" behavior as a code-quality problem.
- Be skeptical of generic mechanisms that hide simple data-shape assumptions.
- Flag thin abstractions, identity wrappers, or pass-through helpers that add indirection without buying clarity.
5. **Push hard on type and boundary cleanliness when they affect maintainability.**
- Question unnecessary optionality, `unknown`, `any`, or cast-heavy code when a clearer type boundary could exist.
- Prefer explicit typed models or shared contracts over loosely-shaped ad-hoc objects.
- If a branch relies on silent fallback to paper over an unclear invariant, ask whether the boundary should be made explicit instead.
6. **Keep logic in the canonical layer and reuse existing helpers.**
- Call out feature logic leaking into shared paths or implementation details leaking through APIs.
- Prefer existing canonical utilities/helpers over bespoke one-offs.
- Push code toward the right package, service, or module instead of normalizing architectural drift.
7. **Treat unnecessary sequential orchestration and non-atomic updates as design smells when the cleaner structure is obvious.**
- If independent work is serialized for no good reason, ask whether the flow should run in parallel instead.
- If related updates can leave state half-applied, push for a more atomic structure.
- Do not over-index on micro-optimizations, but do flag avoidable orchestration complexity that makes the implementation more brittle.
## Primary Review Questions
For every meaningful change, ask:
- Is there a "code judo" move that would make this dramatically simpler?
- Can this change be reframed so fewer concepts, branches, or helper layers are needed?
- Does this improve or worsen the local architecture?
- Did the diff add branching complexity where a better abstraction should exist?
- Did a previously cohesive module become more coupled, more stateful, or harder to scan?
- Is this logic living in the right file and layer?
- Did this change enlarge a file or component past a healthy size boundary?
- Are there repeated conditionals that signal a missing model or missing helper?
- Is the implementation direct and legible, or does it rely on special cases and incidental control flow?
- Is this abstraction actually earning its keep, or is it just a wrapper?
- Did the diff introduce casts, optionality, or ad-hoc object shapes that obscure the real invariant?
- Is this logic living in the canonical layer, or did the diff leak details across a boundary?
- Is this orchestration more sequential or less atomic than it needs to be?
## What to Flag Aggressively
Escalate findings when you see:
- A complicated implementation where a cleaner reframing could delete whole categories of complexity.
- Refactors that move code around but fail to reduce the number of concepts a reader must hold in their head.
- A file crossing 1000 lines due to the PR, especially if the new code could be split out.
- New conditionals bolted onto unrelated code paths.
- One-off booleans, nullable modes, or flags that complicate existing control flow.
- Feature-specific logic leaking into general-purpose modules.
- Generic "magic" handling that hides simple structure and makes the code harder to reason about.
- Thin wrappers or identity abstractions that add indirection without simplifying anything.
- Unnecessary casts, `any`, `unknown`, or optional params that muddy the real contract.
- Copy-pasted logic instead of extracted helpers.
- Narrow edge-case handling implemented in the middle of an already busy function.
- Refactors that technically pass tests but make the code less modular or less readable.
- "Temporary" branching that is likely to become permanent debt.
- Bespoke helpers where the codebase already has a canonical utility for the job.
- Logic added in the wrong layer/package when it should live somewhere more central.
- Sequential async flow where obviously independent work could stay simpler and clearer with parallel execution.
- Partial-update logic that leaves state less atomic than necessary.
## Preferred Remedies
When you identify a code-quality problem, prefer suggestions like:
- Delete a whole layer of indirection rather than polishing it.
- Reframe the state model so conditionals disappear instead of getting centralized.
- Change the ownership boundary so the feature becomes a natural extension of an existing abstraction.
- Turn special-case logic into a simpler default flow with fewer exceptions.
- Extract a helper or pure function.
- Split a large file into smaller focused modules.
- Move feature-specific logic behind a dedicated abstraction.
- Replace condition chains with a typed model or explicit dispatcher.
- Separate orchestration from business logic.
- Collapse duplicate branches into a single clearer flow.
- Delete wrappers that do not meaningfully clarify the API.
- Reuse the existing canonical helper instead of introducing a near-duplicate.
- Make type boundaries more explicit so the control flow gets simpler.
- Move the logic to the package/module/layer that already owns the concept.
- Parallelize independent work when that also simplifies the orchestration.
- Restructure related updates into a more atomic flow when partial state would be harder to reason about.
Do not be satisfied with "maybe rename this" feedback when the real issue is structural.
Do not be satisfied with a merely cleaner version of the same messy idea if there is a plausible path to a much simpler idea.
## Review Tone
Be direct, serious, and demanding about quality.
Do not be rude, but do not soften major maintainability issues into mild suggestions.
If the code is making the codebase messier, say so clearly.
If the implementation missed an opportunity for a dramatic simplification, say that clearly too.
Good phrases:
- `this pushes the file past 1k lines. can we decompose this first?`
- `this adds another special-case branch into an already busy flow. can we move this behind its own abstraction?`
- `this works, but it makes the surrounding code more spaghetti. let's keep the behavior and restructure the implementation.`
- `this feels like feature logic leaking into a shared path. can we isolate it?`
- `this abstraction seems unnecessary. can we just keep the direct flow?`
- `why does this need a cast / optional here? can we make the boundary more explicit instead?`
- `this looks like a bespoke helper for something we already have elsewhere. can we reuse the canonical one?`
- `i think there's a code-judo move here that makes this much simpler. can we reframe this so these branches disappear?`
- `this refactor moves complexity around, but doesn't really delete it. is there a way to make the model itself simpler?`
## Output Expectations
Prioritize findings in this order:
1. Structural code-quality regressions
2. Missed opportunities for dramatic simplification / code-judo restructuring
3. Spaghetti / branching complexity increases
4. Boundary / abstraction / type-contract problems that make the code harder to reason about
5. File-size and decomposition concerns
6. Modularity and abstraction issues
7. Legibility and maintainability concerns
Do not flood the review with low-value nits if there are larger structural issues.
Prefer a smaller number of high-conviction comments over a long list of cosmetic notes.
## Approval Bar
Do not approve merely because behavior seems correct.
The bar for approval is:
- no clear structural regression
- no obvious missed opportunity to make the implementation dramatically simpler when such a path is visible
- no unjustified file-size explosion
- no obvious spaghetti-growth from special-case branching
- no obviously hacky or magical abstraction that makes the code harder to reason about
- no unnecessary wrapper/cast/optionality churn obscuring the real design
- no clear architecture-boundary leak or avoidable canonical-helper duplication
- no missed opportunity for an obvious decomposition that would materially improve maintainability
Treat these as presumptive blockers unless the author can justify them clearly:
- the PR preserves a lot of incidental complexity when there is a plausible code-judo move that would delete it
- the PR pushes a file from below 1000 lines to above 1000 lines
- the PR adds ad-hoc branching that makes an existing flow more tangled
- the PR solves a local problem by scattering feature checks across shared code
- the PR adds an unnecessary abstraction, wrapper, or cast-heavy contract that makes the design more indirect
- the PR duplicates an existing helper or puts logic in the wrong layer when there is a clear canonical home
If those conditions are not met, leave explicit, actionable feedback and push for a cleaner decomposition.
@@ -0,0 +1,81 @@
---
name: create-skill
description: >
Interactively create a new Grok skill (SKILL.md + optional scripts/references).
Use when the user wants to create a skill, scaffold a skill, or runs /create-skill.
metadata:
short-description: "Create a new Grok skill"
---
# Create Skill
Interactively gather requirements from the user and create a fully working Grok skill on disk.
## Step 1: Gather information
Ask the user the following questions **one at a time as regular conversation questions** (do NOT use structured option prompts for free-text inputs):
1. **Skill name** - ask the user to type a name. Lowercase letters (a-z), digits (0-9), and hyphens (-) only. Must start and end with a letter or digit. Must be 2-64 characters long (e.g. `deploy-k8s`). Validate the name before proceeding.
2. **Scope** - present the user with two options:
- **Project** (Recommended): `<repo-root>/.kigi/skills/<name>/SKILL.md` - available only in this repo, shareable with teammates
- **User**: `~/.kigi/skills/<name>/SKILL.md` - available in all projects
- Default to **Project** if inside a git repo, otherwise **User**.
3. **What it should do** - ask the user to describe the workflow, paste an example prompt they keep repeating, or explain the task the skill should automate.
## Step 2: Draft the description
Write a `description` frontmatter value that includes:
- What the skill does (1-2 sentences)
- Trigger phrases and keywords so Grok knows when to auto-invoke it
- The slash command name (e.g. "Use when the user runs /deploy-k8s")
Show the drafted description to the user and let them approve or edit it.
## Step 3: Create the directory
Run this bash command to create the skill directory:
```bash
mkdir -p <SKILL_DIR>
```
Where `<SKILL_DIR>` is:
- User scope: `~/.kigi/skills/<name>`
- Project scope: `<repo-root>/.kigi/skills/<name>`
If the skill needs helper scripts, also create `<SKILL_DIR>/scripts/`.
If the skill needs reference docs, also create `<SKILL_DIR>/references/`.
## Step 4: Write SKILL.md
Use `search_replace` with an empty `old_string` to create the file at `<SKILL_DIR>/SKILL.md`.
The file MUST follow this exact format:
```
---
name: <skill-name>
description: <the description from Step 2>
---
<markdown body with instructions, steps, code blocks>
```
Also write any supporting files (scripts, references) using the same create method.
## Step 5: Verify and confirm
1. Run `cat <SKILL_DIR>/SKILL.md` to verify the file was written correctly.
2. Tell the user the skill is ready and how to use it:
- Slash command: `/<skill-name>`
- TUI menu: `/skills <skill-name>`
- Automatic: Grok will invoke it when the description matches user intent
3. Tell the user the skill should appear in the slash menu within a few seconds (skills auto-reload when files change on disk).
## Guidelines
- Keep the SKILL.md body focused and actionable. It is a prompt for the agent, not documentation.
- The `description` field is critical. It controls auto-invocation. Be specific with trigger words.
- Prefer referencing existing CLI tools over writing custom scripts.
- Do NOT skip creating the directory. The file will fail to save without it.
- Always use absolute paths when creating files to avoid writing to the wrong location.
@@ -0,0 +1,51 @@
---
name: help
description: >
Grok documentation and configuration help. Use when users ask about
setup, configuration, MCP servers, authentication, skills, slash commands,
keyboard shortcuts, or any Grok feature. Also use proactively when you
detect a user is having trouble with setup or onboarding.
metadata:
short-description: "Grok docs — config, MCP, auth, skills, commands"
---
# Grok Help
Answer the user's question about Grok setup, configuration, or features.
## Steps
1. If the question is about **current config** (what MCP servers, models, or settings are active),
read `~/.kigi/config.toml`. MCP servers are under `[mcp_servers.*]` sections.
2. If the question is about **how to do something** (setup, adding MCP servers, creating skills,
authentication, keyboard shortcuts, troubleshooting), first check the user-guide docs at
`~/.kigi/docs/user-guide/`. The available guides are:
- `01-getting-started.md` -- Installation, first launch, basic interaction
- `02-authentication.md` -- Browser login, API keys, OIDC, external auth
- `03-keyboard-shortcuts.md` -- Complete key bindings reference
- `04-slash-commands.md` -- All / commands
- `05-configuration.md` -- config.toml, pager.toml, env vars
- `06-theming.md` -- Themes, appearance customization
- `07-mcp-servers.md` -- MCP server setup and management
- `08-skills.md` -- Creating and using skills
- `09-plugins.md` -- Plugin marketplace
- `10-hooks.md` -- Lifecycle hooks
- `11-custom-models.md` -- BYOK, Ollama, OpenAI endpoints
- `12-project-rules.md` -- AGENTS.md project rules
- `13-memory.md` -- Cross-session memory
- `14-headless-mode.md` -- CLI scripting and CI/CD
- `15-agent-mode.md` -- ACP/stdio IDE integration
- `16-subagents.md` -- Subagents and personas
- `17-sessions.md` -- Session management
- `18-sandbox.md` -- Sandbox mode
- `19-plan-mode.md` -- Plan mode
- `20-background-tasks.md` -- Background tasks and monitoring
- `21-terminal-support.md` -- tmux, SSH, truecolor, clipboard, /terminal-setup
Read the relevant guide(s) for the user's question. If none match, fall back to
`~/.kigi/README.md` for the comprehensive reference.
3. To **modify config** for the user, edit `~/.kigi/config.toml` with search_replace.
4. To **create a skill** for the user, create `~/.kigi/skills/<name>/SKILL.md`
(read `~/.kigi/docs/user-guide/08-skills.md` for the SKILL.md format).
@@ -0,0 +1,131 @@
---
name: imagine
description: >
How to use the image_gen and image_edit tool calls in Grok Build: when to
build a visual with code instead of generating it, prompt-craft,
reference-first handling of real people, factual grounding, and
asset-consistency. Load this whenever generating or editing an image is on the
table, i.e. when an image_gen or image_edit call is being considered or about
to be made. Tool-usage-driven, not triggered by a user merely mentioning
images.
metadata:
short-description: "Prompting and workflow guidance for Imagine image tools"
---
# Imagine
Guidance for the two image tool calls in Grok Build:
- `image_gen` - generate a **new** image from a text prompt.
- `image_edit` - modify an **existing** image using a text prompt and source image.
Apply this whenever you're considering or about to call either tool.
## Build accurate visuals with code, not the image tools
1. **Image models are unreliable at exact text, numbers, and structure.** They can handle short text or a simple layout, but they often garble words, invent numbers, draw chart bars that match no data, or point diagram arrows nowhere, and the more that has to be exact, the worse they do. A detailed prompt doesn't make it dependable, and an `image_edit` pass usually won't fix it. So when a result needs specific text, data, or structure to be correct (charts from real numbers, labeled or technical diagrams, math explainers, tables, screens with real copy), construct the asset with code, where you control the exact content. Prefer HTML and CSS, which give much better layout, typography, and polish than Python plotting. When only the look matters (photos, illustrations, characters, scenes, decorative art), the image tools are the right choice. Which one fits depends on what the output needs to get right, not on how the request is worded.
## Verifying discrete accuracy (loop)
When the output must get specific text, numbers, data, or structure right, don't trust the first result - verify it in a loop:
1. Produce the result (generate, or per *Build accurate visuals with code*, construct it in code).
2. Inspect the actual output - use image understanding to read a generated image back (or check the rendered code) - and confirm every word, number, label, and structural detail matches the requirement, and that nothing overlaps, clips, or runs off-canvas.
3. If anything is wrong, fix and re-verify:
- Garbled text, invented numbers, or broken layout from an image model? Don't just re-prompt - it will likely garble it again. Rebuild it with code.
- Overlapping or clipped elements in code-built output? Re-lay-out with auto-layout (HTML/CSS) rather than nudging coordinates by hand.
- Otherwise make one targeted edit.
4. Only finish when the discrete content is exactly correct. If it can't be made accurate, tell the user instead of shipping something wrong.
## Core Principles
1. **You own the prompt.** If the user gives a detailed prompt or asks you to use theirs, use it verbatim. Otherwise craft the final prompt: front-load the subject, give strong high-level direction for mood, composition, lighting, and style without over-specifying every detail, write natural prose rather than keyword tags, and describe positively instead of using negative prompts. For edits, describe only what changes. Target 2-5 sentences.
2. **Reference-first for real people.** Never use pure `image_gen` for a named real person or group, including face swaps, posters, cartoons, and cinematic or editorial depictions. Use `image_edit` with a real reference instead, and never produce non-consensual, sexualized, or minor-involving likenesses. See Real People and References for the procedure.
3. **Ground facts with search first.** If any part of the request depends on a real-world fact, identity, brand or product, place, event, or top/latest/current result, search the web before generating and put the actual verified details into the prompt. Don't rely on memory, and don't write vague placeholders like "the current president"; write the verified name.
4. **Reuse a base image for consistency.** When the same character, object, or setting must appear across multiple images, generate one base image first, then use it as the input to `image_edit` for every variation. Don't re-run `image_gen` from scratch for a recurring subject.
5. **Handle failures gracefully.** On a moderation or safety block, stop; don't retry and don't paraphrase the prompt to evade the filter. Tell the user it was blocked and offer a different direction. If a reference is weak or a result looks off-target, say so and ask for an upload or redirect rather than silently iterating.
6. **Plan multi-step workflows.** Sequence the steps; only parallelize generations that belong to the same step.
7. **Review at the end.** Confirm the generations you intended actually executed and match what was asked.
8. **Don't assume tool behavior.** Don't invent tool parameters, return values, or environment capabilities that aren't actually provided; verify rather than guess.
## Choosing the Tool
| Situation | Tool |
|-----------|------|
| New image, no source image | `image_gen` |
| Edit, restyle, recolor, add, remove, or extend an existing image | `image_edit` |
| Iterate on a previous result while keeping composition | `image_edit` |
| Named real person or group | `image_edit` with a real reference after a web search |
| Generic, invented, or non-factual subject from scratch | `image_gen` |
Rule of thumb: **no source image -> `image_gen`; source image -> `image_edit`.**
## `image_gen`
Generates a new image from a text prompt.
Inputs:
- `prompt` (required) - full description of the desired image.
- `aspect_ratio` - e.g. `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, or `auto`.
Use for generic or invented subjects, or to create a base image you'll edit later. Not for named real people; see Reference-first for real people.
To produce multiple variations, make multiple `image_gen` calls with distinct prompts. The tool does not expose `n` or `count` parameters.
## `image_edit`
Transforms an existing image according to a prompt.
Inputs:
- `prompt` (required) - describe the desired transformation, and note what should stay the same.
- `image` (required) - one or more source/reference images as filesystem paths or `data:image/...;base64,...` URLs. Prefer a single clean reference for reliable results.
- `aspect_ratio` - optional; used for multi-image edits. Single-image edits preserve the input image aspect ratio.
Use to restyle, recolor, add or remove elements, preserve likeness, transfer style, remix, or iterate on a generated result.
To produce multiple variations, make multiple `image_edit` calls. The tool does not expose `n` or `count` parameters.
## Writing Strong Prompts
Describe, roughly in this order: **subject -> action/pose -> setting -> style -> composition -> lighting/mood -> key details.**
- Be specific and concrete; lead with the most important elements.
- State what to include rather than what to exclude.
- Use one coherent scene per prompt.
- Match `aspect_ratio` to the use case when using `image_gen`: `9:16` for phone/story, `16:9` for banner/video frame, `1:1` for avatar/icon.
## Real People and References
1. Search the web first to confirm identity, role, relationship, or event, even when it seems obvious.
2. Use a single strong reference with `image_edit`. A user-uploaded photo is best; otherwise use a high-quality found reference and cite the source. `image_edit` can take more than one reference, but one clean reference is more reliable.
3. If no suitable reference exists, ask the user to upload one rather than generating from a weak base.
## Video
> The video tools below may not exist - verify they're available before calling them; if they're not, the user cannot do video gen with Imagine.
Video starts from an image - there is no text-to-video tool. Default to `image_to_video`.
**Think in shots.** Build video as a planned sequence of short shots, not one long take:
1. **Plan the story as shots** - break the idea into distinct shots, one beat each.
2. **Favor frequent, short shots** - prefer more 6s shots over fewer long ones; more cuts keep it dynamic and interesting.
3. **Create each shot's source image** with `image_gen` (or a multi-image `image_edit` when a shot must combine references), keeping characters and settings consistent (Core Principle 4).
4. **Animate each shot with `image_to_video`** - the source becomes frame 1.
Use `reference_to_video` only if the user asks for it or a shot genuinely needs multiple references - and even then, prefer composing those references with a multi-image `image_edit` and animating the result with `image_to_video`.
Key behaviors:
- **Prompt-craft:** one short, vivid moment in present tense with a clear camera movement, in 1-2 sentences.
- **Minimal but interesting:** keep each shot to one clear subject and a single, simple motion or camera move. Avoid complex or multi-action animation (models handle it poorly); make the shot interesting through composition, lighting, and a strong moment, not busy motion.
- **Complex source image?** An intricate frame (busy geometry, fine detail, heavy reflections) warps when animated. If you must use it, keep the subject fixed and move only the camera (slow push-in, orbit, or parallax), or break it into tighter, simpler shots. For new shots, generate a simpler, animation-friendly base image up front instead of animating a busy one.
- **`image_to_video` animates from frame 1**, so stage the intended first frame with `image_gen`/`image_edit` first.
- **Aspect ratio:** set it on the source image (`image_gen` `aspect_ratio`); don't re-crop an existing video.
- **Duration:** 6s or 10s only (prefer 6s shots); round to the nearest.
- **Real people:** reference-first - drive the video from a verified reference image; never animate a named person without one.
- Don't loop the same clip unless asked.
**Assemble shots with FFmpeg** using stream copy so there's no quality loss: `ffmpeg -f concat ... -c copy` - never re-encode. Keep every shot at the same resolution and frame rate so the copy works.