my setup for analysis

This commit is contained in:
Veera Ponna 2026-01-29 16:50:03 +08:00
parent bd28575d60
commit aba6416deb
6 changed files with 527 additions and 150 deletions

78
.github/copilot-instructions.md vendored Normal file
View File

@ -0,0 +1,78 @@
## Civyk Repo Index - Code Intelligence
**Always use civyk-repoix MCP tools** for code discovery, navigation, and analysis - provides semantic understanding with symbol-level precision and AI-aware caching.
### Always Use civyk-repoix For
- **Finding code**`search_symbols`, `get_file_symbols` (not grep/find)
- **Understanding structure**`get_symbol`, `get_components` (not reading entire files)
- **Checking dependencies**`get_dependencies`, `get_imports` (not manual tracing)
- **Finding tests**`get_tests_for`, `get_recommended_tests` (not guessing)
- **Impact analysis**`analyze_impact`, `get_references` (not searching manually)
- **PR context**`build_delta_context_pack` (not reading all changed files)
### Tools by Scenario
| Scenario | Tools |
|----------|-------|
| **Explore** | `list_files`, `get_file_symbols`, `search_symbols` |
| **Understand** | `recall_understanding`, `get_symbol`, `get_file_symbols` |
| **Dependencies** | `get_dependencies`, `get_imports`, `find_circular_dependencies` |
| **Architecture** | `get_components`, `get_api_endpoints`, `get_inheritance_tree` |
| **Testing** | `get_tests_for`, `get_code_for_test`, `get_recommended_tests` |
| **Review** | `build_delta_context_pack`, `get_recent_changes`, `analyze_impact` |
| **Navigate** | `get_definition`, `get_references`, `get_callers` |
| **Quality** | `get_dead_code`, `get_hotspots`, `find_circular_dependencies` |
### AI Cache - Context Preservation
Persist understanding across sessions at file, module, and project levels:
```
# Check cached understanding before reading
recall_understanding(scope="file", target="path/file.py")
recall_understanding(scope="module", target="src/auth")
recall_understanding(scope="project")
# Store after analyzing - hierarchical workflow
store_understanding(scope="file", target="path/file.py", purpose="...", key_points=[...])
store_understanding(scope="module", target="src/auth", purpose="...", key_points=[...])
store_understanding(scope="project", purpose="...", key_points=[...])
```
**Hierarchical Workflow:**
1. Read file → `store_understanding(scope="file", ...)`
2. After all files in module → `store_understanding(scope="module", ...)`
3. After all modules → `store_understanding(scope="project", ...)`
**Recall Response:**
- `found=true` + `fresh=true` → Use cached, skip read
- `found=true` + `fresh=false` → Changed, re-read and update
- `found=false` → Read, analyze, then store
### Token-Efficient Patterns
1. **Cache first**: `recall_understanding` before reading files
2. **Context packs**: `build_context_pack(task="...", token_budget=800)`
3. **Symbols over files**: `get_file_symbols` uses ~10x fewer tokens
4. **Save insights**: `store_understanding` after analysis
### Tool Sequences
| Action | Sequence |
|--------|----------|
| Session start | `get_understanding``recall_understanding` for key files → resume |
| New task | `build_context_pack``recall_understanding` → work |
| Understand function | `get_symbol``get_callers``get_references` |
| Find location | `search_symbols``get_file_symbols``get_definition` |
| Refactor | `get_references``analyze_impact``get_recommended_tests` |
| Review PR | `build_delta_context_pack``analyze_impact` |
### Before Commit
1. **Build** - No errors or warnings
2. **Format** - Run formatter (prettier, black, gofmt, etc.)
3. **Lint** - Fix all issues (eslint, ruff, markdownlint, etc.)
4. **Type check** - If applicable (tsc, mypy, etc.)
5. **Test changes** - `get_recommended_tests(changed_files=[...])`
6. **Full tests** - Ensure no regression

8
.gitignore vendored
View File

@ -71,3 +71,11 @@ USER.md
# local tooling
.serena/
memory/code-index/
# Claude agent settings
.claude/
# Copilot agent settings
.github/prompts/
/.vs

10
.mcp.json Normal file
View File

@ -0,0 +1,10 @@
{
"mcpServers": {
"civyk-repoix": {
"command": "civyk-repoix",
"args": [
"mcp"
]
}
}
}

452
AGENTS.md
View File

@ -1,163 +1,317 @@
# Repository Guidelines
- Repo: https://github.com/moltbot/moltbot
- GitHub issues/comments/PR comments: use literal multiline strings or `-F - <<'EOF'` (or $'...') for real newlines; never embed "\\n".
# AI Agent Guidelines
## Project Structure & Module Organization
- Source code: `src/` (CLI wiring in `src/cli`, commands in `src/commands`, web provider in `src/provider-web.ts`, infra in `src/infra`, media pipeline in `src/media`).
- Tests: colocated `*.test.ts`.
- Docs: `docs/` (images, queue, Pi config). Built output lives in `dist/`.
- Plugins/extensions: live under `extensions/*` (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them.
- Plugins: install runs `npm install --omit=dev` in plugin dir; runtime deps must live in `dependencies`. Avoid `workspace:*` in `dependencies` (npm install breaks); put `moltbot` in `devDependencies` or `peerDependencies` instead (runtime resolves `clawdbot/plugin-sdk` via jiti alias).
- Installers served from `https://molt.bot/*`: live in the sibling repo `../molt.bot` (`public/install.sh`, `public/install-cli.sh`, `public/install.ps1`).
- Messaging channels: always consider **all** built-in + extension channels when refactoring shared logic (routing, allowlists, pairing, command gating, onboarding, docs).
- Core channel docs: `docs/channels/`
- Core channel code: `src/telegram`, `src/discord`, `src/slack`, `src/signal`, `src/imessage`, `src/web` (WhatsApp web), `src/channels`, `src/routing`
- Extensions (channel plugins): `extensions/*` (e.g. `extensions/msteams`, `extensions/matrix`, `extensions/zalo`, `extensions/zalouser`, `extensions/voice-call`)
- When adding channels/extensions/apps/docs, review `.github/labeler.yml` for label coverage.
**Version:** 4.7
## Docs Linking (Mintlify)
- Docs are hosted on Mintlify (docs.molt.bot).
- Internal doc links in `docs/**/*.md`: root-relative, no `.md`/`.mdx` (example: `[Config](/configuration)`).
- Section cross-references: use anchors on root-relative paths (example: `[Hooks](/configuration#hooks)`).
- Doc headings and anchors: avoid em dashes and apostrophes in headings because they break Mintlify anchor links.
- When Peter asks for links, reply with full `https://docs.molt.bot/...` URLs (not root-relative).
- When you touch docs, end the reply with the `https://docs.molt.bot/...` URLs you referenced.
- README (GitHub): keep absolute docs URLs (`https://docs.molt.bot/...`) so links work on GitHub.
- Docs content must be generic: no personal device names/hostnames/paths; use placeholders like `user@gateway-host` and “gateway host”.
---
## exe.dev VM ops (general)
- Access: stable path is `ssh exe.dev` then `ssh vm-name` (assume SSH key already set).
- SSH flaky: use exe.dev web terminal or Shelley (web agent); keep a tmux session for long ops.
- Update: `sudo npm i -g moltbot@latest` (global install needs root on `/usr/lib/node_modules`).
- Config: use `moltbot config set ...`; ensure `gateway.mode=local` is set.
- Discord: store raw token only (no `DISCORD_BOT_TOKEN=` prefix).
- Restart: stop old gateway and run:
`pkill -9 -f moltbot-gateway || true; nohup moltbot gateway run --bind loopback --port 18789 --force > /tmp/moltbot-gateway.log 2>&1 &`
- Verify: `moltbot channels status --probe`, `ss -ltnp | rg 18789`, `tail -n 120 /tmp/moltbot-gateway.log`.
## Critical Rules
## Build, Test, and Development Commands
- Runtime baseline: Node **22+** (keep Node + Bun paths working).
- Install deps: `pnpm install`
- Pre-commit hooks: `prek install` (runs same checks as CI)
- Also supported: `bun install` (keep `pnpm-lock.yaml` + Bun patching in sync when touching deps/patches).
- Prefer Bun for TypeScript execution (scripts, dev, tests): `bun <file.ts>` / `bunx <tool>`.
- Run CLI in dev: `pnpm moltbot ...` (bun) or `pnpm dev`.
- Node remains supported for running built output (`dist/*`) and production installs.
- Mac packaging (dev): `scripts/package-mac-app.sh` defaults to current arch. Release checklist: `docs/platforms/mac/release.md`.
- Type-check/build: `pnpm build` (tsc)
- Lint/format: `pnpm lint` (oxlint), `pnpm format` (oxfmt)
- Tests: `pnpm test` (vitest); coverage: `pnpm test:coverage`
| Rule | Description |
|------|-------------|
| **CLI First** | Use `speckitadv` CLI for all workflow operations |
| **CLI Flags** | Use named flags (`--flag value`), NOT positional args |
| **OS Shell** | Bash (Linux/macOS), PowerShell (Windows) |
| **ASCII-Only** | No Unicode. Use `->`, `[ok]`, `[x]`, `[!]` |
| **Mermaid Diagrams** | Mermaid syntax only. No ASCII art |
| **State Auto-Detection** | After stage 2, CLI auto-detects stage from state.json |
| **Workflow Prompts** | Follow workflow-specific prompts for file operations |
## Coding Style & Naming Conventions
- Language: TypeScript (ESM). Prefer strict typing; avoid `any`.
- Formatting/linting via Oxlint and Oxfmt; run `pnpm lint` before commits.
- Add brief code comments for tricky or non-obvious logic.
- Keep files concise; extract helpers instead of “V2” copies. Use existing patterns for CLI options and dependency injection via `createDefaultDeps`.
- Aim to keep files under ~700 LOC; guideline only (not a hard guardrail). Split/refactor when it improves clarity or testability.
- Naming: use **Moltbot** for product/app/docs headings; use `moltbot` for CLI command, package/binary, paths, and config keys.
---
## Release Channels (Naming)
- stable: tagged releases only (e.g. `vYYYY.M.D`), npm dist-tag `latest`.
- beta: prerelease tags `vYYYY.M.D-beta.N`, npm dist-tag `beta` (may ship without macOS app).
- dev: moving head on `main` (no tag; git checkout main).
## RFC 2119 Compliance
## Testing Guidelines
- Framework: Vitest with V8 coverage thresholds (70% lines/branches/functions/statements).
- Naming: match source names with `*.test.ts`; e2e in `*.e2e.test.ts`.
- Run `pnpm test` (or `pnpm test:coverage`) before pushing when you touch logic.
- Do not set test workers above 16; tried already.
- Live tests (real keys): `CLAWDBOT_LIVE_TEST=1 pnpm test:live` (Moltbot-only) or `LIVE=1 pnpm test:live` (includes provider live tests). Docker: `pnpm test:docker:live-models`, `pnpm test:docker:live-gateway`. Onboarding Docker E2E: `pnpm test:docker:onboard`.
- Full kit + whats covered: `docs/testing.md`.
- Pure test additions/fixes generally do **not** need a changelog entry unless they alter user-facing behavior or the user asks for one.
- Mobile: before using a simulator, check for connected real devices (iOS + Android) and prefer them when available.
| Keyword | Meaning | Action |
|---------|---------|--------|
| **MUST** | Mandatory | Always follow |
| **NEVER** | Prohibited | Never do |
| **SHOULD** | Recommended | Follow unless justified |
| **MAY** | Optional | Use judgment |
## Commit & Pull Request Guidelines
- Create commits with `scripts/committer "<msg>" <file...>`; avoid manual `git add`/`git commit` so staging stays scoped.
- Follow concise, action-oriented commit messages (e.g., `CLI: add verbose flag to send`).
- Group related changes; avoid bundling unrelated refactors.
- Changelog workflow: keep latest released version at top (no `Unreleased`); after publishing, bump version and start a new top section.
- PRs should summarize scope, note testing performed, and mention any user-facing changes or new flags.
- PR review flow: when given a PR link, review via `gh pr view`/`gh pr diff` and do **not** change branches.
- PR review calls: prefer a single `gh pr view --json ...` to batch metadata/comments; run `gh pr diff` only when needed.
- Before starting a review when a GH Issue/PR is pasted: run `git pull`; if there are local changes or unpushed commits, stop and alert the user before reviewing.
- Goal: merge PRs. Prefer **rebase** when commits are clean; **squash** when history is messy.
- PR merge flow: create a temp branch from `main`, merge the PR branch into it (prefer squash unless commit history is important; use rebase/merge when it is). Always try to merge the PR unless its truly difficult, then use another approach. If we squash, add the PR author as a co-contributor. Apply fixes, add changelog entry (include PR # + thanks), run full gate before the final commit, commit, merge back to `main`, delete the temp branch, and end on `main`.
- If you review a PR and later do work on it, land via merge/squash (no direct-main commits) and always add the PR author as a co-contributor.
- When working on a PR: add a changelog entry with the PR number and thank the contributor.
- When working on an issue: reference the issue in the changelog entry.
- When merging a PR: leave a PR comment that explains exactly what we did and include the SHA hashes.
- When merging a PR from a new contributor: add their avatar to the README “Thanks to all clawtributors” thumbnail list.
- After merging a PR: run `bun scripts/update-clawtributors.ts` if the contributor is missing, then commit the regenerated README.
| Marker | Action |
|--------|--------|
| `[!]` | Critical - treat as MUST |
| `[ok]`/`[x]` | Verify before proceeding |
| `[STOP: USER_*]` | WAIT for user |
| `[STOP: *]` (other) | Execute and continue |
## Shorthand Commands
- `sync`: if working tree is dirty, commit all changes (pick a sensible Conventional Commit message), then `git pull --rebase`; if rebase conflicts and cannot resolve, stop; otherwise `git push`.
---
### PR Workflow (Review vs Land)
- **Review mode (PR link only):** read `gh pr view/diff`; **do not** switch branches; **do not** change code.
- **Landing mode:** create an integration branch from `main`, bring in PR commits (**prefer rebase** for linear history; **merge allowed** when complexity/conflicts make it safer), apply fixes, add changelog (+ thanks + PR #), run full gate **locally before committing** (`pnpm lint && pnpm build && pnpm test`), commit, merge back to `main`, then `git switch main` (never stay on a topic branch after landing). Important: contributor needs to be in git graph after this!
## Quick Reference
## Security & Configuration Tips
- Web provider stores creds at `~/.clawdbot/credentials/`; rerun `moltbot login` if logged out.
- Pi sessions live under `~/.clawdbot/sessions/` by default; the base directory is not configurable.
- Environment variables: see `~/.profile`.
- Never commit or publish real phone numbers, videos, or live configuration values. Use obviously fake placeholders in docs, tests, and examples.
- Release flow: always read `docs/reference/RELEASING.md` and `docs/platforms/mac/release.md` before any release work; do not ask routine questions once those docs answer them.
**Priority:** Constitution > Spec > Plan > Supporting Docs
## Troubleshooting
- Rebrand/migration issues or legacy config/service warnings: run `moltbot doctor` (see `docs/gateway/doctor.md`).
**Task States:** `[ ]` pending, `[x]` complete, `[F]` failed, `[B]` blocked
## Agent-Specific Notes
- Vocabulary: "makeup" = "mac app".
- Never edit `node_modules` (global/Homebrew/npm/git installs too). Updates overwrite. Skill notes go in `tools.md` or `AGENTS.md`.
- Signal: "update fly" => `fly ssh console -a flawd-bot -C "bash -lc 'cd /data/clawd/moltbot && git pull --rebase origin main'"` then `fly machines restart e825232f34d058 -a flawd-bot`.
- When working on a GitHub Issue or PR, print the full URL at the end of the task.
- When answering questions, respond with high-confidence answers only: verify in code; do not guess.
- Never update the Carbon dependency.
- Any dependency with `pnpm.patchedDependencies` must use an exact version (no `^`/`~`).
- Patching dependencies (pnpm patches, overrides, or vendored changes) requires explicit approval; do not do this by default.
- CLI progress: use `src/cli/progress.ts` (`osc-progress` + `@clack/prompts` spinner); dont hand-roll spinners/bars.
- Status output: keep tables + ANSI-safe wrapping (`src/terminal/table.ts`); `status --all` = read-only/pasteable, `status --deep` = probes.
- Gateway currently runs only as the menubar app; there is no separate LaunchAgent/helper label installed. Restart via the Moltbot Mac app or `scripts/restart-mac.sh`; to verify/kill use `launchctl print gui/$UID | grep moltbot` rather than assuming a fixed label. **When debugging on macOS, start/stop the gateway via the app, not ad-hoc tmux sessions; kill any temporary tunnels before handoff.**
- macOS logs: use `./scripts/clawlog.sh` to query unified logs for the Moltbot subsystem; it supports follow/tail/category filters and expects passwordless sudo for `/usr/bin/log`.
- If shared guardrails are available locally, review them; otherwise follow this repo's guidance.
- SwiftUI state management (iOS/macOS): prefer the `Observation` framework (`@Observable`, `@Bindable`) over `ObservableObject`/`@StateObject`; dont introduce new `ObservableObject` unless required for compatibility, and migrate existing usages when touching related code.
- Connection providers: when adding a new connection, update every UI surface and docs (macOS app, web UI, mobile if applicable, onboarding/overview docs) and add matching status + configuration forms so provider lists and settings stay in sync.
- Version locations: `package.json` (CLI), `apps/android/app/build.gradle.kts` (versionName/versionCode), `apps/ios/Sources/Info.plist` + `apps/ios/Tests/Info.plist` (CFBundleShortVersionString/CFBundleVersion), `apps/macos/Sources/Moltbot/Resources/Info.plist` (CFBundleShortVersionString/CFBundleVersion), `docs/install/updating.md` (pinned npm version), `docs/platforms/mac/release.md` (APP_VERSION/APP_BUILD examples), Peekaboo Xcode projects/Info.plists (MARKETING_VERSION/CURRENT_PROJECT_VERSION).
- **Restart apps:** “restart iOS/Android apps” means rebuild (recompile/install) and relaunch, not just kill/launch.
- **Device checks:** before testing, verify connected real devices (iOS/Android) before reaching for simulators/emulators.
- iOS Team ID lookup: `security find-identity -p codesigning -v` → use Apple Development (…) TEAMID. Fallback: `defaults read com.apple.dt.Xcode IDEProvisioningTeamIdentifiers`.
- A2UI bundle hash: `src/canvas-host/a2ui/.bundle.hash` is auto-generated; ignore unexpected changes, and only regenerate via `pnpm canvas:a2ui:bundle` (or `scripts/bundle-a2ui.sh`) when needed. Commit the hash as a separate commit.
- Release signing/notary keys are managed outside the repo; follow internal release docs.
- Notary auth env vars (`APP_STORE_CONNECT_ISSUER_ID`, `APP_STORE_CONNECT_KEY_ID`, `APP_STORE_CONNECT_API_KEY_P8`) are expected in your environment (per internal release docs).
- **Multi-agent safety:** do **not** create/apply/drop `git stash` entries unless explicitly requested (this includes `git pull --rebase --autostash`). Assume other agents may be working; keep unrelated WIP untouched and avoid cross-cutting state changes.
- **Multi-agent safety:** when the user says "push", you may `git pull --rebase` to integrate latest changes (never discard other agents' work). When the user says "commit", scope to your changes only. When the user says "commit all", commit everything in grouped chunks.
- **Multi-agent safety:** do **not** create/remove/modify `git worktree` checkouts (or edit `.worktrees/*`) unless explicitly requested.
- **Multi-agent safety:** do **not** switch branches / check out a different branch unless explicitly requested.
- **Multi-agent safety:** running multiple agents is OK as long as each agent has its own session.
- **Multi-agent safety:** when you see unrecognized files, keep going; focus on your changes and commit only those.
- Lint/format churn:
- If staged+unstaged diffs are formatting-only, auto-resolve without asking.
- If commit/push already requested, auto-stage and include formatting-only follow-ups in the same commit (or a tiny follow-up commit if needed), no extra confirmation.
- Only ask when changes are semantic (logic/data/behavior).
- Lobster seam: use the shared CLI palette in `src/terminal/palette.ts` (no hardcoded colors); apply palette to onboarding/config prompts and other TTY UI output as needed.
- **Multi-agent safety:** focus reports on your edits; avoid guard-rail disclaimers unless truly blocked; when multiple agents touch the same file, continue if safe; end with a brief “other files present” note only if relevant.
- Bug investigations: read source code of relevant npm dependencies and all related local code before concluding; aim for high-confidence root cause.
- Code style: add brief comments for tricky logic; keep files under ~500 LOC when feasible (split/refactor as needed).
- Tool schema guardrails (google-antigravity): avoid `Type.Union` in tool input schemas; no `anyOf`/`oneOf`/`allOf`. Use `stringEnum`/`optionalStringEnum` (Type.Unsafe enum) for string lists, and `Type.Optional(...)` instead of `... | null`. Keep top-level tool schema as `type: "object"` with `properties`.
- Tool schema guardrails: avoid raw `format` property names in tool schemas; some validators treat `format` as a reserved keyword and reject the schema.
- When asked to open a “session” file, open the Pi session logs under `~/.clawdbot/agents/<agentId>/sessions/*.jsonl` (use the `agent=<id>` value in the Runtime line of the system prompt; newest unless a specific ID is given), not the default `sessions.json`. If logs are needed from another machine, SSH via Tailscale and read the same path there.
- Do not rebuild the macOS app over SSH; rebuilds must be run directly on the Mac.
- Never send streaming/partial replies to external messaging surfaces (WhatsApp, Telegram); only final replies should be delivered there. Streaming/tool events may still go to internal UIs/control channel.
- Voice wake forwarding tips:
- Command template should stay `moltbot-mac agent --message "${text}" --thinking low`; `VoiceWakeForwarder` already shell-escapes `${text}`. Dont add extra quotes.
- launchd PATH is minimal; ensure the apps launch agent PATH includes standard system paths plus your pnpm bin (typically `$HOME/Library/pnpm`) so `pnpm`/`moltbot` binaries resolve when invoked via `moltbot-mac`.
- For manual `moltbot message send` messages that include `!`, use the heredoc pattern noted below to avoid the Bash tools escaping.
- Release guardrails: do not change version numbers without operators explicit consent; always ask permission before running any npm publish/release step.
| Problem | Action |
|---------|--------|
| Spec unclear | STOP, mark [B], WAIT |
| Test failed (syntax) | Auto-fix max 2x |
| Test failed (logic) | Mark [F], WAIT |
| Constitution conflict | STOP, FLAG, WAIT |
## NPM + 1Password (publish/verify)
- Use the 1password skill; all `op` commands must run inside a fresh tmux session.
- Sign in: `eval "$(op signin --account my.1password.com)"` (app unlocked + integration on).
- OTP: `op read 'op://Private/Npmjs/one-time password?attribute=otp'`.
- Publish: `npm publish --access public --otp="<otp>"` (run from the package dir).
- Verify without local npmrc side effects: `npm view <pkg> version --userconfig "$(mktemp)"`.
- Kill the tmux session after publish.
---
## CLI Commands
| Command | Description |
|---------|-------------|
| `analyze-project` | Analyze existing project (git branch workflow) |
| `deepwiki` | Generate AI-powered wiki (requires civyk-repoix) |
| `deepwiki-update-state` | Update deepwiki workflow state |
| `constitution` | Create project constitution |
| `specify` | Create baseline specification |
| `plan` | Create implementation plan |
| `tasks` | Generate actionable tasks |
| `implement` | Execute implementation |
| `tests` | Iterative test implementation |
| `review` | Iterative code review |
**CLI vs Slash Commands:**
- Slash commands (`/speckitadv.xxx`) → Human users in IDE
- CLI commands (`speckitadv xxx`) → AI agents programmatically
---
## Deepwiki State Commands
| Command | Purpose |
|---------|---------|
| `init --files=N --symbols=N --components="a,b" --repoix-mode=mcp` | Initialize state |
| `stage --stage=ID --status=completed --artifacts=files` | Update stage |
| `verify-stage --stage=ID` | Verify prerequisites |
| `enumerate-index` | Discover file patterns and component naming |
| `business-context --context-file=path` | Save business context |
| `discovery-cache --key=K --value='json'` | Save cross-stage context |
| `show` | Show current state |
| `show --key=KEY` | Show specific key |
| `complete` | Mark workflow complete |
---
## Chunking (>1500 lines)
| Principle | Description |
|-----------|-------------|
| Completion-based | Each chunk is complete logical section |
| Full quality | Multiple writes, NOT reduced content |
| Progress display | Show progress after each chunk |
| No placeholders | Never TODO, TBD, "will be analyzed" |
| Resume support | Check existing content before starting |
---
## Agentic Markers
| Marker | Action |
|--------|--------|
| `[AUTO-CONTINUE]` | Proceed immediately |
| `[STAGE TRANSITION]` | Auto-continue to next stage |
| `[WAIT-FOR-INPUT]` | Stop and wait |
| `[GATE-CHECK]` | Pass: continue. Fail: wait |
| `[WORKFLOW COMPLETE]` | Stop, report completion |
**Default:** No marker = `[AUTO-CONTINUE]`. Do NOT ask "should I continue?"
---
## civyk-repoix Integration
### Mode Detection (Stage 01)
DeepWiki tries MCP first, falls back to CLI. Mode persisted in state.json.
### MCP vs CLI Conversion
| MCP Syntax | CLI Syntax |
|------------|------------|
| `mcp__civyk-repoix__index_status()` | `civyk-repoix query index-status` |
| `search_symbols(query="%User", kind="class")` | `--query "%User" --kind class` |
| `kinds=["class", "function"]` | `--kinds "class,function"` |
| `include_private=True` | `--include-private` |
**Name conversion:** snake_case → kebab-case (`search_symbols` → `search-symbols`)
**Exit codes:** `0` = success (JSON stdout), `1` = error (`{"error": "..."}`)
### MCP Tool Categories (32 Tools)
**Status:** `index_status`, `build_context_pack`
**Discovery:** `search_symbols`, `get_symbol`, `list_files`, `search_code`, `find_similar`
- `search_symbols`: SQL LIKE patterns (`%` wildcard). NOT regex. OR not supported.
- `list_files`: fnmatch patterns (`*`, `**`, `?`). Brace expansion NOT supported.
**Navigation:** `get_file_symbols`, `get_definition`, `get_callers`, `get_references`, `get_file_imports`, `get_type_hierarchy`, `get_related_files`
**Architecture:** `get_components`, `get_api_endpoints`, `get_dependencies`
**Git-Aware:** `get_recent_changes`, `get_hotspots`, `get_branch_diff`
**Analysis:** `get_dead_code`, `find_circular_dependencies`, `analyze_impact`, `get_duplicate_code`, `get_tests_for`, `get_code_for_test`, `get_tool_performance_stats`
**AI Context Cache:** `store_understanding`, `recall_understanding`, `get_understanding_stats`, `invalidate_understanding`
**Maintenance:** `force_reindex`
### Pagination
All list tools return: `total_count`, `truncated`, `has_more`, `offset`, `hint`
Use `limit` and `offset` for pagination. **MUST paginate when `has_more=true`.**
**Paginated tools:** `search_symbols`, `get_references`, `get_api_endpoints`, `get_callers`, `list_files`, `search_code`, `get_recent_changes`, `get_hotspots`, `get_branch_diff`, `get_duplicate_code`, `get_dead_code`, `get_type_hierarchy`
### AI Context Cache (Cross-Session Persistence)
The AI Context Cache enables **cross-session persistence** of code understanding. Your analysis survives session restarts and new conversations, saving **80-90% of tokens**.
| Tool | Purpose |
|------|---------|
| `recall_understanding` | **Call FIRST** before reading any file (saves 80-90% tokens) |
| `store_understanding` | Persist analysis AFTER thoroughly reading files |
| `get_understanding_stats` | **Session start**: See cached targets, filter by path/scope, sort, check freshness |
| `invalidate_understanding` | Manually clear stale entries |
**[!] SESSION START: Check Cache First**
At the **start of any workflow or session**, proactively check what's already cached:
```text
# 1. Check cache statistics to see what's available
get_understanding_stats(limit=50)
# 2. If working on a specific area, recall relevant cached understanding:
recall_understanding(target="project") # Project-level overview
recall_understanding(target="<module_path>") # Module you'll be working in
# 3. Use cached understanding to:
# - Skip redundant file reads
# - Understand existing patterns before making changes
# - Identify related areas that might be affected
```
**Why check cache first?**
- Previous sessions may have already analyzed the files you need
- Cached understanding includes gotchas and edge cases you'd otherwise miss
- Dramatically reduces time-to-context in new sessions
**`store_understanding` fields:**
| Field | Required | Description |
|-------|----------|-------------|
| `scope` | Yes | `file`, `class`, `module`, or `project` |
| `target` | Yes | Path identifier (e.g., `src/auth.py`, `src/auth.py::AuthClient`) |
| `purpose` | Yes | 1-2 sentence summary of WHAT and WHY |
| `importance` | Yes | `critical`, `high`, `medium`, or `low` |
| `key_points` | No | 2-5 main functionality highlights |
| `gotchas` | No | Non-obvious behaviors that could cause bugs |
| `analysis` | No | **Detailed free-form analysis** for complex business logic, state machines, workflows |
**`get_understanding_stats` parameters:**
| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `limit` | int | 50 | Max entries total (1-200) |
| `offset` | int | 0 | Pagination offset |
| `filter` | string | - | Filter targets by path (contains match) |
| `scope` | string | - | Filter by scope: `file`, `class`, `module`, `project` |
| `sort_by` | string | importance | Sort by: `importance`, `access_count`, `target` |
| `include_fresh` | bool | true | Check freshness per entry (false = faster) |
| `case_insensitive` | bool | true | Whether filter is case-insensitive |
**Key behaviors:**
- Cross-session: Understanding persists across session restarts and new conversations
- Long sessions: Avoid re-reading files analyzed earlier in the conversation
- Auto-invalidation: Cache invalidates when file content changes (hash mismatch)
- Freshness check: Response includes `fresh` boolean to indicate if cache is current
**[!] CRITICAL: AI Cache Usage Pattern**
```text
BEFORE reading ANY source file:
1. Call recall_understanding(target="path/to/file.py")
2. Check response:
- found=true AND fresh=true -> USE cached understanding, SKIP file read
- found=true AND fresh=false -> File changed, re-read and UPDATE cache
- found=false -> Read file, analyze, then store_understanding
AFTER thorough analysis of a file/module/component:
1. Call store_understanding with:
- scope: file/class/module/project
- target: the path analyzed
- purpose: what the code does
- importance: critical/high/medium/low
- key_points: main functionality
- gotchas: non-obvious behaviors
- analysis: detailed notes for complex logic
```
**When to Store Understanding:**
| Scope | When to Use | Example Target |
|-------|-------------|----------------|
| `file` | After reading and analyzing a source file | `src/auth/oauth.py` |
| `class` | After deep-diving into a specific class | `src/auth/oauth.py::OAuthClient` |
| `module` | After analyzing a directory/package | `src/auth` |
| `project` | After initial codebase orientation | `project` |
### Recommended Workflow
1. `index_status` -> verify ready
2. `recall_understanding` -> **check cached analysis FIRST** (saves 80-90% tokens)
- If `found=true` AND `fresh=true` -> Use cached understanding, skip file read
- If `found=true` AND `fresh=false` -> File changed, re-read and update cache
- If `found=false` -> Read file, analyze, then `store_understanding`
3. `build_context_pack` -> initial context
4. `get_file_symbols` -> understand files
5. `get_definition` + `get_callers` -> navigation
6. `search_symbols` -> drill down
7. `store_understanding` -> persist analysis after reading files (enables cross-session recall)
**For cross-session efficiency:**
```text
Session 1: Read file -> Analyze -> store_understanding
Session 2: recall_understanding -> Use cached analysis (no file read needed!)
```
**For refactoring:** `analyze_impact` -> `get_duplicate_code` -> `get_tests_for` -> `find_circular_dependencies` -> `get_dead_code`
---
## Code Generation
**Discovery-First:**
- Use civyk-repoix MCP/CLI to discover existing utils, base classes, methods, patterns before creating new
- Prefer extending existing patterns over introducing new ones
**Quality Standards:**
- Production-ready, functionally deterministic and idempotent
- Consider all edge cases in design, implementation, and test coverage
- Small commits (1 scenario, <300 lines)
**Quality Gates (Pre-Commit):**
- Zero compile errors
- Zero warnings (treat warnings as errors)
- Run: Formatters -> Linters -> Type checkers -> Build
- All new implementations covered by tests
- All new tests must pass
---
## Ethics & Safety
**MUST NOT:** Commit secrets/keys, share PII, make undisclosed network calls
**Licensing:** Prefer permissive (MIT, Apache, BSD). STOP for license conflicts.
---
*AI agents MUST follow these guidelines for spec-driven development.*

View File

@ -1 +1,80 @@
AGENTS.md
AGENTS.md
## Civyk Repo Index - Code Intelligence
**Always use civyk-repoix MCP tools** for code discovery, navigation, and analysis - provides semantic understanding with symbol-level precision and AI-aware caching.
### Always Use civyk-repoix For
- **Finding code**`search_symbols`, `get_file_symbols` (not grep/find)
- **Understanding structure**`get_symbol`, `get_components` (not reading entire files)
- **Checking dependencies**`get_dependencies`, `get_imports` (not manual tracing)
- **Finding tests**`get_tests_for`, `get_recommended_tests` (not guessing)
- **Impact analysis**`analyze_impact`, `get_references` (not searching manually)
- **PR context**`build_delta_context_pack` (not reading all changed files)
### Tools by Scenario
| Scenario | Tools |
|----------|-------|
| **Explore** | `list_files`, `get_file_symbols`, `search_symbols` |
| **Understand** | `recall_understanding`, `get_symbol`, `get_file_symbols` |
| **Dependencies** | `get_dependencies`, `get_imports`, `find_circular_dependencies` |
| **Architecture** | `get_components`, `get_api_endpoints`, `get_inheritance_tree` |
| **Testing** | `get_tests_for`, `get_code_for_test`, `get_recommended_tests` |
| **Review** | `build_delta_context_pack`, `get_recent_changes`, `analyze_impact` |
| **Navigate** | `get_definition`, `get_references`, `get_callers` |
| **Quality** | `get_dead_code`, `get_hotspots`, `find_circular_dependencies` |
### AI Cache - Context Preservation
Persist understanding across sessions at file, module, and project levels:
```
# Check cached understanding before reading
recall_understanding(scope="file", target="path/file.py")
recall_understanding(scope="module", target="src/auth")
recall_understanding(scope="project")
# Store after analyzing - hierarchical workflow
store_understanding(scope="file", target="path/file.py", purpose="...", key_points=[...])
store_understanding(scope="module", target="src/auth", purpose="...", key_points=[...])
store_understanding(scope="project", purpose="...", key_points=[...])
```
**Hierarchical Workflow:**
1. Read file → `store_understanding(scope="file", ...)`
2. After all files in module → `store_understanding(scope="module", ...)`
3. After all modules → `store_understanding(scope="project", ...)`
**Recall Response:**
- `found=true` + `fresh=true` → Use cached, skip read
- `found=true` + `fresh=false` → Changed, re-read and update
- `found=false` → Read, analyze, then store
### Token-Efficient Patterns
1. **Cache first**: `recall_understanding` before reading files
2. **Context packs**: `build_context_pack(task="...", token_budget=800)`
3. **Symbols over files**: `get_file_symbols` uses ~10x fewer tokens
4. **Save insights**: `store_understanding` after analysis
### Tool Sequences
| Action | Sequence |
|--------|----------|
| Session start | `get_understanding``recall_understanding` for key files → resume |
| New task | `build_context_pack``recall_understanding` → work |
| Understand function | `get_symbol``get_callers``get_references` |
| Find location | `search_symbols``get_file_symbols``get_definition` |
| Refactor | `get_references``analyze_impact``get_recommended_tests` |
| Review PR | `build_delta_context_pack``analyze_impact` |
### Before Commit
1. **Build** - No errors or warnings
2. **Format** - Run formatter (prettier, black, gofmt, etc.)
3. **Lint** - Fix all issues (eslint, ruff, markdownlint, etc.)
4. **Type check** - If applicable (tsc, mypy, etc.)
5. **Test changes** - `get_recommended_tests(changed_files=[...])`
6. **Full tests** - Ensure no regression

48
memory/config.json Normal file
View File

@ -0,0 +1,48 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Spec Kit configuration",
"version": "2.4",
"project": {
"type": "personal",
"guidelineProfile": "personal",
"description": "Project type determines which corporate guidelines profile to use: 'corporate' for internal/proprietary projects, 'personal' for open-source/public projects"
},
"artifactory": {
"enabled": false,
"url": "",
"repos": "",
"apiKeyEnv": "ARTIFACTORY_API_KEY",
"_comment": "Configure Artifactory for corporate package validation. Set enabled:true and url to your Artifactory instance (e.g., https://artifactory.company.com/artifactory), repos to comma-separated repository names, and apiKeyEnv to the environment variable containing your API key."
},
"git": {
"checkTimeout": 5,
"listTimeout": 60,
"_comment": "Timeouts in seconds for git commands. Increase listTimeout for very large repositories"
},
"workflows": {
"max_iterations": 10,
"_comment": "Maximum iterations for iterative workflows (review, tests). Prevents infinite loops. Default: 10"
},
"branching": {
"pattern": "feature/<jira>-<shortname>",
"_comment": "example pattern: feature/<num>-<jira>-<shortname>",
"prefix": "feature/",
"separator": "-",
"number_format": {
"digits": 3,
"zero_padded": true
},
"jira": {
"required": false,
"strict_format": false,
"format": "C12345-7890",
"regex": "^C[0-9]{5}-[0-9]{4}$",
"placeholder": "<jira>",
"_comment": "Set required:true and strict_format:true for corporate projects with enforced ticket IDs"
},
"directory": {
"includes_prefix": false,
"base_path": "specs"
}
}
}