@miphamai/cli 0.85.47 → 0.85.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/skills/standard/safe-coding.SKILL.md +10 -1
- package/src/core/crsi-modify.ts +4 -0
- package/src/core/crsi-producer.ts +85 -7
- package/src/core/crsi-sandbox.ts +30 -1
- package/src/core/engine.ts +44 -11
- package/src/core/hooks-executor.ts +25 -2
- package/src/core/improvement-track.ts +349 -0
- package/src/core/instructions.ts +12 -3
- package/src/core/task-performance.ts +70 -3
- package/src/i18n-core/locales/en-US.json +3 -0
- package/src/i18n-core/locales/zh-CN.json +3 -0
- package/src/plugin/plugin-manager.ts +12 -3
- package/src/providers/anthropic.ts +5 -0
- package/src/providers/fetch-utils.ts +16 -1
- package/src/providers/openai-compat.ts +4 -0
- package/src/shared/package-info.ts +2 -2
- package/src/skills/bundled-skills.ts +1 -1
- package/src/skills/sanitizer.ts +16 -2
- package/src/ui/chat.tsx +9 -1
- package/src/ui/commands.ts +77 -2
- package/src/ui/input.tsx +23 -3
- package/src/ui/picker.tsx +15 -3
|
@@ -20,7 +20,7 @@ export const BUNDLED_SKILLS: ReadonlyArray<BundledSkill> = [
|
|
|
20
20
|
{ type: 'standard', raw: "---\nname: memory\ndescription: Read and write persistent memory files for context retention across sessions — one fact per file with frontmatter\nversion: 2.0.0\n---\n\n# Memory Skill\n\nManage persistent memory stored as markdown files with YAML frontmatter.\n\n## File Format\n\nEach memory is one `.md` file under the `memory/` directory:\n\n```markdown\n---\nname: <kebab-case-slug>\ndescription: <one-line summary>\nmetadata:\n type: user | feedback | project | reference\n---\n\n<the fact body>\n\n**Why:** <rationale>\n**How to apply:** <practical guidance>\n```\n\n## File Path Conventions\n\n- Directory: `~/.mipham/memory/` (user-level) or `./.mipham/memory/` (project-level)\n- Filename: `<name-slug>.md` (lowercase, hyphens)\n- Index: `MEMORY.md` — one line per memory file, maintained automatically\n\n## Operations\n\n### List Memories\n\nScan `MEMORY.md` index for available memories. The index has one line per memory:\n\n```markdown\n- [Title](file.md) — brief hook\n```\n\n### Read Memory\n\nRead the full markdown file including frontmatter. Parse YAML frontmatter for metadata.\n\n### Write Memory\n\n1. Check for existing file with same `name:` slug — update if found\n2. Create new file if no match\n3. Add/update entry in `MEMORY.md` index\n4. Never write what the repo already records (code structure, git history, CLAUDE.md)\n\n### Delete Memory\n\nRemove the file and its index entry. Use when a memory is incorrect or superseded.\n\n## Best Practices\n\n- **One fact per file** — atomic, focused, easy to find\n- **Descriptive slugs** — `npm-publish-workflow` not `memory-1`\n- **Link related memories** — use `[[slug-name]]` wikilinks in body\n- **Check before writing** — search existing memories to avoid duplicates\n- **Types matter**: `user` (who), `feedback` (corrections), `project` (goals), `reference` (external)\n\n## Example\n\n```markdown\n---\nname: api-rate-limit\ndescription: OpenAI API has 500 RPM limit on our tier\nmetadata:\n type: reference\n---\n\nThe OpenAI API key for production has a hard 500 requests/minute limit.\nExceeding it returns HTTP 429 with a Retry-After header.\n\n**Why:** We hit this in production during peak usage\n**How to apply:** Use exponential backoff; batch requests where possible\n```\n" },
|
|
21
21
|
{ type: 'standard', raw: "---\nname: mipham-code-setup\ndescription: Install, configure, diagnose, and troubleshoot Mipham Code — the multi-model open-core intelligent coding terminal. Covers setup wizard, API keys, providers, models, skills, permissions, workspace trust, shell/IDE integration, and first-run onboarding.\nversion: 2.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Skill\n---\n\n# Mipham Code Setup — Executable Setup Workflow\n\n**Type**: Rigid — follow the decision tree exactly. Don't skip diagnostic phases.\n\n**Purpose**: Guide users from zero to fully configured Mipham Code. This skill is BOTH:\n\n1. A self-contained diagnostic + configuration workflow the AI can execute\n2. A reference for `/setup` command behavior and slash commands\n\n**Triggers**: \"setup mipham\", \"configure mipham\", \"install mipham code\", \"mipham not working\", \"mipham setup\", \"first time using mipham\", \"help me set up\", \"getting started\", `/setup`\n\n---\n\n## Phase 0: Environment Detection (ALWAYS RUN FIRST)\n\nBefore doing anything, run these diagnostic checks. Report results in a status table.\n\n### 0.1 — Detect Installation\n\n```bash\nwhich mipham 2>/dev/null\nmipham --version 2>/dev/null\nbun --version 2>/dev/null\nnode --version 2>/dev/null\n```\n\n### 0.2 — Detect Configuration\n\n```bash\nls -la .mipham/config.yml 2>/dev/null\nls -la ~/.mipham/config.yml 2>/dev/null\nls -la MIPHAM.md 2>/dev/null\nls -la CLAUDE.md 2>/dev/null\n```\n\n### 0.3 — Detect API Keys\n\n```bash\nenv | grep -E 'ANTHROPIC_API_KEY|OPENAI_API_KEY|DEEPSEEK_API_KEY|QWEN_API_KEY|DOUBAO_API_KEY|HUNYUAN_API_KEY|GEMINI_API_KEY' | cut -d= -f1\n```\n\n### 0.4 — Detect Skills & Permissions\n\n```bash\nls .mipham/skills/ 2>/dev/null\ncat .mipham/config.yml 2>/dev/null | grep -E 'permission|trust' || echo \"no config\"\n```\n\n### 0.5 — Detect Workspace Trust\n\n```bash\ncat ~/.mipham/trusted-workspaces.json 2>/dev/null || echo \"no trust store\"\n```\n\n### Status Report Format\n\nAfter detection, present results as:\n\n```\n── Mipham Code Status ──\n\nInstallation: [✅/⬜] mipham CLI [✅/⬜] Bun [✅/⬜] Node.js\nProject: [✅/⬜] .mipham/ [✅/⬜] config.yml [✅/⬜] MIPHAM.md\nUser Config: [✅/⬜] ~/.mipham/config.yml\nAPI Keys: [N] set (list names or \"none\")\nSkills: [N] installed\nPermissions: [mode] (default/acceptEdits/plan/auto/bypassPermissions)\nTrust: [✅/⬜] workspace trusted\n```\n\nThen proceed to ONLY the phases where something is missing. Don't re-run already-configured steps unless asked.\n\n---\n\n## Phase 1: Installation\n\n**Trigger**: `mipham --version` fails.\n\n### Option A: Quick Install (recommended)\n\n```bash\ncurl -fsSL https://mipham.ai/install.sh | bash\n```\n\nThen restart the shell or run:\n\n```bash\nexport PATH=\"$HOME/.mipham/bin:$PATH\"\n```\n\n### Option B: npm Global Install\n\n```bash\nnpm install -g @miphamai/cli\nmipham\n```\n\n### Option C: From Source (developers)\n\n```bash\ngit clone https://github.com/One-Mipham/mipham-code\ncd mipham-code/apps/cli\nbun install && bun run bin/mipham\n```\n\n### ✅ Verification\n\n```bash\nmipham --version # Should print version ≥ 0.24.0\nmipham --help # Should print usage\n```\n\n---\n\n## Phase 2: Project Initialization\n\n**Trigger**: Missing `.mipham/` directory or `MIPHAM.md`.\n\n### 2.1 — Create .mipham/ directory\n\n```bash\nmkdir -p .mipham\n```\n\n### 2.2 — Create .mipham/config.yml\n\nWrite a minimal config. Ask the user which provider they want to use first, or pick a sensible default:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\npermission: default\n```\n\n**Providers available** (alphabetical):\n\n| Provider | Type | Example Models |\n| --------- | ------------- | -------------------------------------- |\n| anthropic | Native SDK | Claude Haiku 4.5, Sonnet 4.6, Opus 4.8 |\n| deepseek | OpenAI Compat | V4 Flash, V4 Pro |\n| doubao | OpenAI Compat | Seed 1.6, Seed 2.0 |\n| gemini | OpenAI Compat | 3.0 Flash, 3.0 Pro, 2.5 Pro |\n| hunyuan | OpenAI Compat | Lite, TurboS, 2.0, T1 |\n| openai | OpenAI Compat | GPT-5.4 Mini, GPT-5.4, GPT-5.5, Codex |\n| qwen | OpenAI Compat | Qwen Plus, Qwen Max |\n\n### 2.3 — Create MIPHAM.md (optional but recommended)\n\nCreate `MIPHAM.md` in project root to define AI personality:\n\n```markdown\n# MIPHAM.md\n\n## Project Context\n\n- **Project**: [name]\n- **Language**: [zh-CN / en]\n- **Stack**: [TypeScript / Python / etc.]\n\n## Preferences\n\n- Code style: [e.g., functional, OOP]\n- Comment language: [e.g., English]\n- Test framework: [e.g., Vitest]\n```\n\n### ✅ Verification\n\n```bash\nls -la .mipham/config.yml MIPHAM.md\n```\n\n---\n\n## Phase 3: API Key Configuration\n\n**Trigger**: Missing API keys in environment.\n\n### 3.1 — Identify Required Providers\n\nAsk the user which providers they plan to use. For each, set the env var.\n\n### 3.2 — Set API Keys\n\n**Recommended: Environment variables** (not in config files — avoids accidental commits):\n\n```bash\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\nexport OPENAI_API_KEY=\"sk-...\"\nexport DEEPSEEK_API_KEY=\"sk-...\"\nexport QWEN_API_KEY=\"sk-...\"\nexport DOUBAO_API_KEY=\"...\"\nexport HUNYUAN_API_KEY=\"...\"\nexport GEMINI_API_KEY=\"...\"\n```\n\nAdd these to `~/.zshrc` or `~/.bashrc` for persistence:\n\n```bash\necho 'export ANTHROPIC_API_KEY=\"sk-ant-...\"' >> ~/.zshrc\nsource ~/.zshrc\n```\n\n**Alternative**: Store in `~/.mipham/config.yml`:\n\n```yaml\nproviders:\n - id: anthropic\n apiKey: $ANTHROPIC_API_KEY\n - id: openai\n apiKey: $OPENAI_API_KEY\n```\n\n### 3.3 — Verify Keys\n\n```bash\nenv | grep API_KEY\n```\n\n### ❗Security Rules\n\n- NEVER hardcode API keys in project config files (`.mipham/config.yml` in project root should use `$ENV_VAR` references, not raw keys)\n- NEVER commit API keys to git\n- Add to `.gitignore`: `.mipham/config.yml` (if it contains keys), `.env`, `*.pem`\n\n---\n\n## Phase 4: Provider & Model Configuration\n\n**Trigger**: Need to set default or enable/disable providers.\n\n### 4.1 — Set Default Provider & Model\n\nIn `.mipham/config.yml`:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\n```\n\nOr use slash commands:\n\n```\n/model # Interactive model picker (Ctrl+P)\n/switch # Switch provider\n/providers # List all configured providers\n```\n\n### 4.2 — Enable/Disable Providers\n\n```yaml\nproviders:\n - id: anthropic\n status: active\n - id: openai\n status: active\n - id: deepseek\n status: disabled\n```\n\n### ✅ Verification\n\n```\n/model # Should show available models\n/providers # Should list active providers\n```\n\n---\n\n## Phase 5: Skills Installation\n\n**Trigger**: No or few skills installed.\n\n### 5.1 — Built-in Skills\n\nMipham Code ships with 28 built-in skills loaded automatically:\n\n- **Standard (22)**: code-review, codebase-design, compassionate-communication, debug-loop, doc-generator, domain-modeling, github-ops, grill-with-docs, implement, memory, mipham-code-setup, research, safe-coding, security-review, self-review, superpower, tdd, to-spec, triage, trim-process-prose, web-access, web-search\n- **Mipham (6)**: doc-sync, om-artifact, om-model-optimize, om-security, save-to-wiki, self-audit\n\n### 5.2 — Community Skills\n\nInstall from the community registry:\n\n```\n/setup 4 # Guided skill browser\n```\n\nOr directly:\n\n```bash\n# Skills are loaded from:\n# - apps/cli/skills/standard/ (built-in standard)\n# - apps/cli/skills/mipham/ (built-in mipham)\n# - ~/.mipham/skills/ (user-installed)\n# - .mipham/skills/ (project-local)\n```\n\n### 5.3 — Install Specific Skills\n\n```\n/skills install <name> # Install from registry\n/skills list # List available\n/skills search <query> # Search registry\n```\n\n### ✅ Verification\n\n```\n/skills list # Should show installed skills with counts\n```\n\n---\n\n## Phase 6: Permissions Configuration\n\n**Trigger**: Permission mode not configured or wrong for use case.\n\n### 6.1 — Permission Modes\n\n| Mode | Behavior | Use Case |\n| ------------------- | -------------------------------------- | ----------------------------------------- |\n| `default` | Ask-first tools are refused (see note) | Normal development (recommended) |\n| `acceptEdits` | Auto-allow edits, ask for other tools | Active coding sessions |\n| `plan` | Plan-only, no tool execution | Design & architecture work |\n| `auto` | A classifier rules on every call | Long unattended runs you still want gated |\n| `bypassPermissions` | Skip all checks | ⚠️ Only for fully trusted codebases |\n\n**Note on `default`**: Mipham Code has no interactive approval prompt, so \"ask\"\nmeans the call is **refused** with a message naming the mode — it is not queued\nfor your answer. That makes `default` the strictest _usable_ mode for Bash and\nfile writes; `auto` is the mode that lets gated calls proceed without a human,\nby having a classifier rule on each one.\n\n**What `auto` actually gates.** Reads (Read/Grep/Glob) are never sent to the\nclassifier — gating them would make `auto` the only mode in the ladder that cannot\nopen a file without a round-trip to another model. Everything else that the static\nchain would refuse goes to the classifier, which can only **lift** a refusal: a\ndeny rule or an `ask` rule is never overridden. If the classifier cannot be reached\nor answers unusably, the call is refused (fail-closed) with a message saying the\nrefusal is _not_ a policy decision and can be retried.\n\n### 6.2 — Configure\n\nPress **Shift+Tab** to change the mode live; it cycles\n`default → acceptEdits → plan → auto` and lasts for the session only.\n`bypassPermissions` is a legal mode but is deliberately **not** on the wheel —\nit is reached by naming it in config, where the user has said what they mean.\n\nTo persist a mode, name it in `~/.mipham/config.yml`:\n\n```yaml\npermission: default\n```\n\nOr in `~/.mipham/settings.json` as `permissions.defaultMode` (the key Claude Code\nusers already have). Any mode name from the table above is accepted in either,\nincluding `bypassPermissions`.\n\nA **project-level** `.mipham/config.yml` cannot set a mode — that file arrives with\nthe code, so whoever wrote the repository would be choosing the approval gate. A\nmode found there is ignored and reported; the fix is to move the line to the user\nlevel, or to pass `--permission <mode>` for one invocation.\n\nOr via slash command:\n\n```\n/permissions # View current settings\n/setup 5 # Permission setup wizard\n```\n\n### 6.3 — CI/CD Safety\n\nFor CI/CD environments, use the `default` mode (the daemon default): headless\nsessions never prompt, so `ask`-level tools (Bash/Write/Edit) are blocked rather\nthan auto-approved.\n\n### ✅ Verification\n\n```\n/permissions # Should show current mode\n```\n\n---\n\n## Phase 7: Workspace Trust\n\n**Trigger**: Untrusted workspace (prompted on startup in v0.24.3+).\n\n### 7.1 — Understanding Workspace Trust\n\nWorkspace trust is a security mechanism that prevents AI from operating in untrusted directories. Trust is **hierarchical**: trusting `/Users/me/Projects` implicitly trusts all subdirectories.\n\n### 7.2 — Trust a Workspace\n\n**Interactive**: Accept the trust prompt when launching Mipham Code in a new directory.\n\n**Manual**:\n\n```\n/trust # Show trust status\n/trust add <dir> # Trust a directory\n/trust remove <dir> # Revoke trust\n```\n\n### 7.3 — Trust Store\n\n```\n~/.mipham/trusted-workspaces.json\n```\n\n### 7.4 — Auto-Trust for Worktrees\n\nWhen using git worktrees, Mipham Code automatically trusts worktree directories if the parent workspace is already trusted (via `EnterWorktree`).\n\n### ✅ Verification\n\n```\n/trust # Should show \"✅ Yes\" for current directory\n```\n\n---\n\n## Phase 8: Shell & IDE Integration\n\n**Trigger**: Want terminal integration, aliases, or IDE plugins.\n\n### 8.1 — Shell Alias\n\nAdd to `~/.zshrc` or `~/.bashrc`:\n\n```bash\nalias mipham='cd ~/your-project && bun run ~/path/to/mipham-code/apps/cli/bin/mipham.ts'\n# Or if installed globally:\nalias mipham='mipham'\n```\n\n### 8.2 — VS Code Integration\n\nRun `/ide` to auto-generate `.vscode/` config files:\n\n- `settings.json` — terminal profile \"mipham\" using Bun\n- `keybindings.json` — Cmd+Esc to focus terminal, Cmd+Shift+M for new terminal\n- `extensions.json` — recommends `miphamai.mipham-code` extension\n\nTo use after generation:\n\n1. Restart VS Code (or Cmd+Shift+P → Reload Window)\n2. Open terminal: Ctrl+` or Cmd+Esc\n3. Select \"mipham\" profile from terminal dropdown\n\nInstall the VS Code extension:\n\n```bash\ncode --install-extension miphamai.mipham-code\n```\n\n### 8.3 — JetBrains Integration\n\nSettings → Tools → Terminal → Shell path → `bun run mipham`\n\n### 8.4 — Terminal Setup\n\n```\n/terminal-setup # Shell & terminal config wizard\n/setup 6 # Shell integration (part of full wizard)\n```\n\n### ✅ Verification\n\n```bash\nwhich mipham # Should resolve\n# In VS Code: Ctrl+` → select \"mipham\" profile\n```\n\n---\n\n## Phase 9: Full Verification\n\nRun after all configuration phases complete.\n\n### 9.1 — System Diagnostics\n\n```\n/doctor # System diagnostics check\n```\n\n### 9.2 — End-to-End Test\n\nStart a conversation and verify:\n\n1. Model responds (not stuck on \"connecting...\")\n2. File tools work: \"read CLAUDE.md\"\n3. Bash works: \"list files in current directory\"\n4. Skills load: `/skills list`\n\n### 9.3 — Common Issues & Fixes\n\n| Symptom | Diagnosis | Fix |\n| ------------------------- | -------------------------------------- | ------------------------------------------------ |\n| \"Provider not registered\" | Missing or invalid API key | `env \\| grep API_KEY`; check key format |\n| \"Model not found\" | Model ID mismatch or disabled provider | `/models` to list available; `/switch` to change |\n| Slow responses | Large model, network, or context full | Switch to Flash model; `/compact` |\n| Context full | Too many messages in history | `/compact` to compress; `/clear` to reset |\n| Permission denied | Tool blocked by permission mode | `/permissions` to check; adjust mode |\n| \"Workspace not trusted\" | New directory, not yet trusted | Accept startup prompt or run `/trust` |\n| MCP tools not available | Server not connected | `/mcp connect <name>` or check config |\n| Update not applying | Cached binary | `mipham update --force` then restart |\n| Config changes ignored | YAML syntax error | Validate with `mipham --check-config` |\n\n### 9.4 — Get Help\n\n```\n/help # Full command reference\n/setup # Re-run setup wizard\n/doctor # Run diagnostics\n```\n\nChat-based help: \"help me configure X\" or \"why isn't Y working?\"\n\n---\n\n## Quick Reference: Essential Slash Commands\n\n| Category | Command | Purpose |\n| ------------- | ----------------- | ------------------------------------------------------ |\n| **Setup** | `/setup` | Full 6-step setup wizard |\n| | `/setup 1` | Initialize project (.mipham/ + MIPHAM.md + config.yml) |\n| | `/setup 2` | Configure providers & API keys |\n| | `/setup 3` | Choose default model |\n| | `/setup 4` | Browse & install skills |\n| | `/setup 5` | Configure permissions |\n| | `/setup 6` | Shell & IDE integration |\n| **Diagnosis** | `/doctor` | System diagnostics |\n| | `/trust` | Workspace trust status |\n| | `/permissions` | Tool permission settings |\n| **Model** | `/model` | Interactive model picker (Ctrl+P) |\n| | `/switch` | Switch provider |\n| | `/models` | List available models |\n| **Session** | `/clear` | Reset conversation |\n| | `/compact` | Compress context |\n| | `/rename` | Rename session |\n| **Workflow** | `/plan` | Enter plan mode |\n| | `/review` | Code review |\n| | `/todos` | Task list |\n| **IDE** | `/ide` | Generate VS Code integration files |\n| | `/terminal-setup` | Shell & terminal config |\n| **Skills** | `/skills list` | List installed skills |\n| | `/skills search` | Search skill registry |\n| | `/skills install` | Install a skill |\n\n---\n\n## Post-Setup: What to Do Next\n\nAfter configuration is verified:\n\n1. **Initialize your project**: \"help me understand this codebase\"\n2. **Set up CLAUDE.md**: `/init` to generate project documentation for the AI\n3. **Install relevant skills**: `/setup 4` or `/skills search`\n4. **Configure MCP servers**: `/mcp connect` for external tool integration\n5. **Start coding**: Just start a conversation — the AI will use tools and skills automatically\n" },
|
|
22
22
|
{ type: 'standard', raw: "---\nname: research\ndescription: Deep research against primary sources, executed as a background agent. Collects findings into a single cited Markdown file. Use for investigation that requires reading official docs, source code, specs, or first-party APIs — not secondary summaries.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - WebSearch\n - WebFetch\n - Agent\n - Bash\n - Write\n - Read\n---\n\n# Research — Background Deep Research\n\n融合 Mipham web-search v3.0(查询构建+验证)+ Matt Pocock research(后台代理+一手来源+Markdown 报告)。\n\n## When to Use\n\n- \"Research X for me\"\n- \"Find out everything about Y from primary sources\"\n- \"Investigate Z and write up findings\"\n- Any question where googling + reading multiple sources is the right answer\n\n## When NOT to Use\n\n- Quick fact lookup → use `/web-search` directly\n- Question answerable from code already in context\n- Pure logic/algorithmic question\n\n---\n\n## Phase 0: Route\n\n```\nResearch task is...\n├── Quick (1-2 sources, immediate answer)?\n│ └── → Use web-search skill directly (Phase 0-4)\n│\n├── Deep (multiple sources, needs synthesis)?\n│ └── → THIS SKILL — background agent\n│\n└── Login-walled / SPA-only sources?\n └── → web-access skill (ComputerUse browser)\n```\n\n---\n\n## Phase 1: Spin Up Background Agent\n\nLaunch a **background agent** to do the heavy reading, so you keep working while it researches.\n\nThe agent's instructions:\n\n```\nYou are a research agent. Your task:\n\n1. Investigate the question against PRIMARY SOURCES ONLY:\n - Official documentation (docs.*.com, *.org)\n - Source code repositories (GitHub, GitLab)\n - Technical specifications (RFCs, standards)\n - First-party API references\n - NOT: blog posts, Medium articles, forum threads, secondary summaries\n\n2. For every claim, follow it back to the source that owns it.\n If a secondary source makes a claim, find the primary source and cite that.\n\n3. Before external search, scan the local repo and sibling project directories\n for prior work. Open and read the relevant files — a glob hit is not a read.\n Record what you found; if there is none, say \"none\" explicitly.\n\n4. A number, \"unconditional\", \"record\", or \"first\" is a claim about a theorem\n under its stated assumptions, not about the numeral. Open the source's theorem\n statement (not the abstract), copy the assumption it depends on, and pair the\n value with that assumption wherever you write it. If the same value has several\n provenances, say which one you mean.\n\n5. Use WebSearch to find sources.\n Use WebFetch to deep-read promising pages.\n Cross-reference critical claims across 2+ independent primary sources.\n\n6. Write findings to a SINGLE Markdown file.\n - Cite every claim with its primary source URL\n - Distinguish between facts (needs citation) and reasoning (your own)\n - Flag outdated content (\"article from 2024, may be stale\")\n - Note if a source is official docs vs community\n\n7. Save the file where the repo already keeps such notes.\n Match existing conventions. If none exist, put it in docs/research/.\n```\n\n---\n\n## Phase 2: Report Format\n\nThe agent writes findings in this structure:\n\n```markdown\n# [Research Topic]\n\n**Date**: YYYY-MM-DD\n**Sources**: N primary, M cross-references\n\n## Key Findings\n\n- [Finding 1] — [Source](URL)\n- [Finding 2] — [Source](URL)\n\n## Detailed Analysis\n\n### [Subtopic A]\n\n[Claim and citation]\n\n### [Subtopic B]\n\n[Claim and citation]\n\n## Source Evaluation\n\n| Source | Type | Authority | Notes |\n| ----------- | ------------- | --------- | --------------------- |\n| [Name](URL) | Official docs | High | Current as of YYYY-MM |\n| [Name](URL) | Source code | High | Tag vX.Y.Z |\n\n## Open Questions\n\n- [Question 1]\n- [Question 2]\n\nSources:\n\n- [Title](URL) — brief note\n```\n\n---\n\n## Phase 3: Review\n\nWhen the background agent completes:\n\n1. Read the output file\n2. Spot-check: did it follow the chain back to primary sources?\n3. Flag any claims that need further verification\n4. Surface uncertainties to the user\n\n---\n\n## Research Quality Checklist\n\n- [ ] Every factual claim has a primary source citation\n- [ ] At least one critical claim is cross-referenced (2+ sources)\n- [ ] Source type is clearly identified (official docs / source code / spec / community)\n- [ ] Outdated content is flagged with publication year\n- [ ] Reasoning vs facts are clearly distinguished\n- [ ] File saved in repo-appropriate location\n" },
|
|
23
|
-
{ type: 'standard', raw: "---\nname: safe-coding\ndescription: Safe coding rules for code generation — validate external/user input before use and throw RangeError on invalid input\nversion: 1.
|
|
23
|
+
{ type: 'standard', raw: "---\nname: safe-coding\ndescription: Safe coding rules for code generation — validate external/user input before use and throw RangeError on invalid input\nversion: 1.1.0\n---\n\n# Safe Coding\n\n处理外部/用户输入前必须校验:`null`、`undefined`、空字符串、格式非法时,抛出 `RangeError`,消息为 `'invalid input'`。\n\n## 校验规则\n\n1. **严格整串匹配**:用锚定正则(`/^...$/`)校验字符串格式;不要依赖 `Number()` / `parseInt()` / `parseFloat()` 的宽松解析 —— 它们会接受 `'1e3'`、`'4.2abc'` 这类部分匹配。\n2. **先 trim 再校验**:允许首尾空白时,先 `String(input).trim()`;trim 后为空一律视为非法。\n3. **端值检查**:数值结果必须过 `Number.isFinite()`;`NaN`、`±Infinity` 不是合法结果。\n4. **边界参数**:区间类函数(如 `clamp`)在 `min > max` 时必须抛 `RangeError`,不得静默交换。\n5. **按签名返回**:签名声明 `| null` 的函数用 `null` 表示非法输入;声明抛 `RangeError` 的用异常 —— 两者不混用。\n6. **导出形状**:导出名与签名必须与题目要求逐字一致(`export function name(...)`)。\n" },
|
|
24
24
|
{ type: 'standard', raw: "---\nname: security-review\ndescription: Security audit skill — vulnerability scanning, OWASP Top 10, secrets detection, supply chain analysis, and compliance checking\nversion: 1.0.0\n---\n\n# Security Review\n\nComprehensive security audit for codebases. Covers vulnerability detection, compliance, and hardening recommendations.\n\n## Audit Checklist\n\n### 1. Secrets & Credentials\n\n- [ ] No hardcoded API keys, tokens, or passwords in source files\n- [ ] `.env` and `*.pem` files in `.gitignore`\n- [ ] API keys use environment variables or secret managers\n- [ ] No credentials in git history (check `git log -p`)\n- [ ] CI/CD secrets stored securely (not in workflow files)\n\n### 2. OWASP Top 10\n\n- [ ] **Injection**: SQL, NoSQL, OS command, LDAP injection points\n- [ ] **Broken Authentication**: Weak password policies, missing MFA\n- [ ] **Sensitive Data Exposure**: Unencrypted PII, missing TLS\n- [ ] **XXE**: XML external entity processing\n- [ ] **Broken Access Control**: Missing authorization checks\n- [ ] **Security Misconfiguration**: Default credentials, verbose errors\n- [ ] **XSS**: Reflected, stored, DOM-based cross-site scripting\n- [ ] **Insecure Deserialization**: Untrusted data deserialization\n- [ ] **Using Vulnerable Components**: Outdated dependencies with CVEs\n- [ ] **Insufficient Logging**: Missing audit trails for auth events\n\n### 3. Supply Chain\n\n- [ ] All dependencies have known licenses (no copyleft/GPL)\n- [ ] No dependencies with critical CVEs\n- [ ] Lock files committed (pnpm-lock.yaml, package-lock.json)\n- [ ] Dependency update policy in place\n- [ ] SBOM (Software Bill of Materials) available\n\n### 4. Network & API Security\n\n- [ ] TLS 1.3 enforced for all external communications\n- [ ] API endpoints have rate limiting\n- [ ] CORS configured with explicit origins (not `*`)\n- [ ] SSRF protections in place (URL validation, IP filtering)\n- [ ] WebSocket connections use WSS\n- [ ] GraphQL endpoints have query depth limits\n\n### 5. File System & Path Security\n\n- [ ] Path traversal protections (no `../../../etc/passwd`)\n- [ ] File upload validation (type, size, content inspection)\n- [ ] Symlink attacks prevented\n- [ ] Sensitive directories blocked (`/etc`, `/proc`, `/sys`)\n- [ ] Temporary files cleaned up after use\n\n### 6. Code-Level Security\n\n- [ ] No `eval()` or `Function()` with user input\n- [ ] No `child_process.exec()` with unsanitized input\n- [ ] Regex patterns safe from ReDoS\n- [ ] Prototype pollution prevented\n- [ ] No `dangerouslySetInnerHTML` without sanitization (React)\n- [ ] SQL queries use parameterized statements\n\n### 7. Authentication & Sessions\n\n- [ ] Passwords hashed with bcrypt/argon2 (not MD5/SHA1)\n- [ ] Session tokens use `httpOnly`, `secure`, `SameSite=Strict`\n- [ ] JWT tokens have reasonable expiration\n- [ ] Account lockout after failed attempts\n- [ ] Password reset tokens expire and are single-use\n\n### 8. Data Protection\n\n- [ ] PII data encrypted at rest (AES-256-GCM)\n- [ ] Data encrypted in transit (TLS 1.3)\n- [ ] Logs do not contain sensitive data\n- [ ] Database backups encrypted\n- [ ] Data retention policies defined\n\n### 9. Infrastructure\n\n- [ ] Infrastructure as Code (Terraform/Pulumi) used\n- [ ] Cloud resources not publicly exposed unless intended\n- [ ] Security groups / firewalls restrict inbound traffic\n- [ ] Container images scanned for vulnerabilities\n- [ ] Kubernetes pods run as non-root\n\n### 10. Logging & Monitoring\n\n- [ ] Authentication events logged\n- [ ] Failed access attempts logged and alerted\n- [ ] Structured logging format (JSON)\n- [ ] No PII in log messages\n- [ ] Alert thresholds configured for critical events\n\n## Report Format\n\n```\nSecurity Review Report\n======================\nDate: YYYY-MM-DD\nSeverity: Critical | High | Medium | Low\n\nFinding #N: [Title]\nSeverity: Critical/High/Medium/Low\nLocation: file:line\nDescription: [What was found]\nRisk: [What could happen]\nFix: [How to resolve]\n```\n\n## Compliance Standards\n\n- OWASP ASVS Level 2\n- PCI DSS (if handling payment data)\n- GDPR (if handling EU personal data)\n- SOC 2 Type II\n- ISO 27001\n" },
|
|
25
25
|
{ type: 'standard', raw: "---\nname: self-review\ndescription: Self-review of staged or recently changed code — reuse, simplification, efficiency, and architectural alignment\nversion: 2.0.0\n---\n\n# Self Review\n\nReview your own code changes before committing or merging. Focus on quality improvements, not bug hunting.\n\n## When to Run\n\n- Before committing changes\n- After completing a feature or fix\n- Before requesting a peer review\n- As the final step before merging\n\n## Review Passes\n\n### Pass 1: Reuse\n\n- Is there existing code that does the same thing?\n- Are there utility functions or shared libraries you missed?\n- Could this be solved with a standard library method?\n- Are you reimplementing something the framework provides?\n\n### Pass 2: Simplification\n\n- Can a complex function be split into smaller, named functions?\n- Are there unnecessary abstractions (interfaces with one impl, unused generics)?\n- Can nested conditionals be flattened with early returns?\n- Is there dead code, unused imports, or commented-out blocks?\n\n### Pass 3: Efficiency\n\n- Are you looping over data multiple times when once would suffice?\n- Are large objects being copied unnecessarily?\n- Could a synchronous operation be made async/non-blocking?\n- Are regex patterns compiled once or on every call?\n\n### Pass 4: Altitude (Architectural Alignment)\n\n- Does this code belong where it is?\n- Is it in the right layer (UI / business logic / data access)?\n- Does it follow existing patterns in the codebase?\n- Would a new developer understand where to find this?\n\n## Output\n\nAfter each pass, either:\n\n- Apply the improvement directly (for clear wins)\n- Note the observation with a recommendation (for trade-off decisions)\n\n## Anti-Patterns\n\n- ❌ Rewriting working code for style preference\n- ❌ Adding abstractions \"just in case\"\n- ❌ Changing code outside the scope of your changes\n- ❌ \"This could be a microservice\" — no it couldn't\n" },
|
|
26
26
|
{ type: 'standard', raw: "---\nname: superpower\ndescription: Skill discovery and invocation system — find and use skills before any response or action\nversion: 2.1.0\n---\n\n<SUBAGENT-STOP>\nIf you were dispatched as a subagent to execute a specific task, ignore this skill.\n</SUBAGENT-STOP>\n\n# Superpowers — Using Skills\n\n## The Rule\n\n**Invoke relevant or requested skills BEFORE any response or action.** Even a 1% chance a skill might apply means you should invoke it to check.\n\nThen announce \"Using [skill] to [purpose]\" and follow the skill exactly. If it has a checklist, create a todo per item.\n\n## How to Access Skills\n\nUse the `Skill` tool to invoke skills by name. When you invoke a skill, its content is loaded — follow it directly.\n\n## Skill Discovery\n\n### Check Available Skills\n\nSkills are listed in `<system-reminder>` messages. Scan this list when receiving a task.\n\n### Matching Algorithm\n\n1. Parse the user's request for intent keywords\n2. Scan skill names and descriptions for matches\n3. If ANY skill matches at ≥1% probability → invoke it\n4. Multiple matches → invoke all that may apply\n5. Invoked skill doesn't fit → that's fine, don't use it\n\n### Priority Order\n\n1. **Process skills first** — to-spec, debug-loop, tdd. These determine HOW to approach\n2. **Implementation skills second** — implement, codebase-design. These guide execution\n\n## Red Flags\n\nThese thoughts mean STOP — you're rationalizing:\n\n| Thought | Reality |\n| ----------------------------------- | ------------------------------------------------------ |\n| \"This is just a simple question\" | Questions are tasks. Check skills. |\n| \"I need more context first\" | Skill check comes BEFORE clarifying questions. |\n| \"Let me explore the codebase first\" | Skills tell you HOW to explore. Check first. |\n| \"I can check git/files quickly\" | Files lack conversation context. Check for skills. |\n| \"Let me gather information first\" | Skills tell you HOW to gather information. |\n| \"This doesn't need a formal skill\" | If a skill exists, use it. |\n| \"I remember this skill\" | Skills evolve. Read current version. |\n| \"This doesn't count as a task\" | Action = task. Check for skills. |\n| \"The skill is overkill\" | Simple things become complex. Use it. |\n| \"I'll just do this one thing first\" | Check BEFORE doing anything. |\n| \"This feels productive\" | Undisciplined action wastes time. Skills prevent this. |\n| \"I know what that means\" | Knowing the concept ≠ using the skill. Invoke it. |\n\n## Skill Types\n\n- **Rigid** (tdd, debug-loop): Follow exactly. Don't adapt away discipline.\n- **Flexible** (patterns): Adapt principles to context.\n\nThe skill itself tells you which type it is.\n\n## User Instructions\n\nUser instructions (CLAUDE.md, AGENTS.md, MIPHAM.md, direct requests) take precedence over skills, which in turn override default behavior.\n\nInstructions say WHAT, not HOW. \"Add X\" or \"Fix Y\" doesn't mean skip workflows. Only skip a skill workflow when the user has explicitly told you to.\n" },
|
package/src/skills/sanitizer.ts
CHANGED
|
@@ -29,12 +29,19 @@ export interface ShadowCheck {
|
|
|
29
29
|
shadowed: boolean
|
|
30
30
|
/** Name of the conflicting command/tool */
|
|
31
31
|
conflictsWith: string
|
|
32
|
-
/** Type of conflict: 'command' | 'mcp-tool' */
|
|
33
|
-
conflictType: 'command' | 'mcp-tool'
|
|
32
|
+
/** Type of conflict: 'command' | 'mcp-tool' | 'reserved-name' */
|
|
33
|
+
conflictType: 'command' | 'mcp-tool' | 'reserved-name'
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
// ── Constants ──
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Tool names the CLI gives a native capability. A skill with one of these names
|
|
40
|
+
* is not shadowing a slash command or an MCP tool, so it used to pass every
|
|
41
|
+
* check — and the model then had two different things called `computer-use`.
|
|
42
|
+
*/
|
|
43
|
+
const RESERVED_SKILL_NAMES = new Set(['computer-use'])
|
|
44
|
+
|
|
38
45
|
/** Known local command names that skills should not shadow */
|
|
39
46
|
const BUILTIN_COMMANDS = new Set([
|
|
40
47
|
'/help',
|
|
@@ -193,6 +200,13 @@ export function checkSkillShadow(
|
|
|
193
200
|
return { shadowed: true, conflictsWith: skillName, conflictType: 'command' }
|
|
194
201
|
}
|
|
195
202
|
|
|
203
|
+
// Names the CLI itself gives a native capability. These are tools, not slash
|
|
204
|
+
// commands, so the command check above does not see them — a same-named skill
|
|
205
|
+
// loaded silently and left the model with two different `computer-use`s.
|
|
206
|
+
if (RESERVED_SKILL_NAMES.has(skillName)) {
|
|
207
|
+
return { shadowed: true, conflictsWith: skillName, conflictType: 'reserved-name' }
|
|
208
|
+
}
|
|
209
|
+
|
|
196
210
|
// Check description for embedded command names
|
|
197
211
|
for (const cmd of BUILTIN_COMMANDS) {
|
|
198
212
|
const cmdPattern = cmd.replace(/\//g, '')
|
package/src/ui/chat.tsx
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
stripControlCharsForDisplay,
|
|
10
10
|
} from '../shared/sanitize'
|
|
11
11
|
import { homedir } from 'node:os'
|
|
12
|
+
import { isCompactionSummary } from '../core/session-log'
|
|
12
13
|
import type { UpdateStatus } from '../shared/update'
|
|
13
14
|
|
|
14
15
|
interface ChatPanelProps {
|
|
@@ -164,7 +165,14 @@ const MessageRow = React.memo(
|
|
|
164
165
|
</Box>
|
|
165
166
|
) : (
|
|
166
167
|
<>
|
|
167
|
-
{msg
|
|
168
|
+
{isCompactionSummary(msg) ? (
|
|
169
|
+
// The summary is stored as a user message (that is the role the
|
|
170
|
+
// model reads it in), but showing it under the user label made a
|
|
171
|
+
// resumed session claim the user had typed the whole thing.
|
|
172
|
+
<Text bold color="yellow">
|
|
173
|
+
⚑ {t('ui.compaction.role_label')}:
|
|
174
|
+
</Text>
|
|
175
|
+
) : msg.role === 'user' ? (
|
|
168
176
|
<Text bold color="green">
|
|
169
177
|
▸ {displayCwd()}:
|
|
170
178
|
</Text>
|
package/src/ui/commands.ts
CHANGED
|
@@ -69,6 +69,7 @@ import {
|
|
|
69
69
|
measureSkillDeltaRepeated,
|
|
70
70
|
stripCodeFences,
|
|
71
71
|
loadPerformanceTasks,
|
|
72
|
+
resolveSkillName,
|
|
72
73
|
} from '../core/task-performance'
|
|
73
74
|
import { measureCapture, measureSealed } from '../core/capture-measure'
|
|
74
75
|
import { randomUUID } from 'node:crypto'
|
|
@@ -79,6 +80,10 @@ import {
|
|
|
79
80
|
formatRsiTaxLine,
|
|
80
81
|
normalizeProblemKey,
|
|
81
82
|
groupImprovementsByProblem,
|
|
83
|
+
fixedSummary,
|
|
84
|
+
renderSimBlock,
|
|
85
|
+
renderProblemHistory,
|
|
86
|
+
SIM_MAX_ATTEMPTS,
|
|
82
87
|
measurementTaxSummary,
|
|
83
88
|
appendImprovement,
|
|
84
89
|
readImprovements,
|
|
@@ -1117,6 +1122,23 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
|
|
|
1117
1122
|
if (groups.length > 10) lines.push(`… 另有 ${groups.length - 10} 组未列出`)
|
|
1118
1123
|
}
|
|
1119
1124
|
|
|
1125
|
+
// ── 逐题修复(区间支持度):三个桶分开报,缺席与「零修复」不同形 ──
|
|
1126
|
+
const fx = fixedSummary(records)
|
|
1127
|
+
lines.push('')
|
|
1128
|
+
lines.push('### 逐题修复(区间支持度)')
|
|
1129
|
+
if (fx.recordsWithFixed === 0) {
|
|
1130
|
+
lines.push(`暂无逐题修复读数(${fx.noFixed} 条记录都没有逐题计数 —— 缺席不是「零修复」)。`)
|
|
1131
|
+
} else {
|
|
1132
|
+
lines.push(
|
|
1133
|
+
`修好 ${fx.fixed} 题次 · 其中区间分离 ${fx.separated} 题次(两臂 Wilson 95% 区间不相交才算)`,
|
|
1134
|
+
)
|
|
1135
|
+
lines.push(
|
|
1136
|
+
`区间可判: ${fx.recordsWithInterval}/${fx.recordsWithFixed} 条有逐题计数` +
|
|
1137
|
+
(fx.noInterval > 0 ? `(${fx.noInterval} 条只有修复集)` : ''),
|
|
1138
|
+
)
|
|
1139
|
+
if (fx.noFixed > 0) lines.push(`另有 ${fx.noFixed} 条旧记录没有逐题计数(缺席 ≠ 零修复)`)
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1120
1142
|
// ── RSI Tax:验证成本(只记录、只展示,不进任何判定) ──
|
|
1121
1143
|
const tax = measurementTaxSummary(records)
|
|
1122
1144
|
lines.push('')
|
|
@@ -1163,6 +1185,22 @@ function renderGateNote(result: { rewardNote?: string; regretNote?: string }): s
|
|
|
1163
1185
|
return lines.length > 0 ? lines.join('\n') + '\n' : ''
|
|
1164
1186
|
}
|
|
1165
1187
|
|
|
1188
|
+
/**
|
|
1189
|
+
* P3 出处:实测用的**真实模型 id**(不是档位标签 —— 档位在部分配置里映射到同一模型)。
|
|
1190
|
+
*
|
|
1191
|
+
* 判据是「量的是不是注册表本身」:只有那时模型才已知。挂载的自定义 `ctx.llm`
|
|
1192
|
+
* 不暴露模型 ⇒ 返回 undefined,台账记成**缺席**。不许拿注册表当前模型冒充 ——
|
|
1193
|
+
* 记错比不记更坏,读侧会把「别的模型上的证据」当成同设置证据。
|
|
1194
|
+
*
|
|
1195
|
+
* 只记录、不进任何判定(与 RSI Tax / 耗时维同一条纪律)。
|
|
1196
|
+
*/
|
|
1197
|
+
function measurementModel(ctx: Parameters<CommandHandler>[0]): string | undefined {
|
|
1198
|
+
if (ctx.engine.getLlm()) return undefined
|
|
1199
|
+
// 单测里注册表可能是桩 ⇒ 按能力探测,不按类型假设。
|
|
1200
|
+
const registry = ctx.engine.getRegistry() as { getActiveModel?: () => string } | undefined
|
|
1201
|
+
return typeof registry?.getActiveModel === 'function' ? registry.getActiveModel() : undefined
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1166
1204
|
/**
|
|
1167
1205
|
* 单提案与整合提案共用的「过闸后测量」段。
|
|
1168
1206
|
*
|
|
@@ -1194,6 +1232,7 @@ async function measureModification(
|
|
|
1194
1232
|
// 同一句话被反复修时,它们才聚得起来。
|
|
1195
1233
|
problemKey: normalizeProblemKey(params.description),
|
|
1196
1234
|
rationale: params.description,
|
|
1235
|
+
model: measurementModel(ctx),
|
|
1197
1236
|
})
|
|
1198
1237
|
setPendingVerdict(report.verdict)
|
|
1199
1238
|
appendImprovement({ ...report, id: randomUUID(), timestamp: new Date().toISOString() })
|
|
@@ -1356,6 +1395,18 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
|
|
|
1356
1395
|
// 文件不存在 → 宽松模式(originalContent 为空)
|
|
1357
1396
|
}
|
|
1358
1397
|
|
|
1398
|
+
// SIM 选择者侧:这个问题上此前试过什么、结果如何。必须在测量**之前**算 ——
|
|
1399
|
+
// 测量会把本次尝试追进台账,之后再算就把「刚做的这一次」当成了历史(自我包含)。
|
|
1400
|
+
// 纯算术,无 LLM 参与;无匹配记录时为空串 ⇒ 回执逐字不变。
|
|
1401
|
+
// 规则 8:这里两个轴都已知(skill 由 filePath 解出、model 由注册表给出),
|
|
1402
|
+
// 所以同设置的证据会被排在前面,被降权的那些自报「异设置」原因。
|
|
1403
|
+
const simNote = renderProblemHistory(
|
|
1404
|
+
readImprovements(),
|
|
1405
|
+
normalizeProblemKey(description),
|
|
1406
|
+
SIM_MAX_ATTEMPTS,
|
|
1407
|
+
{ skill: resolveSkillName(filePath, newContent), model: measurementModel(ctx) },
|
|
1408
|
+
)
|
|
1409
|
+
|
|
1359
1410
|
const result = await runCrsiModification({
|
|
1360
1411
|
description,
|
|
1361
1412
|
filePath,
|
|
@@ -1369,7 +1420,7 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
|
|
|
1369
1420
|
}
|
|
1370
1421
|
}
|
|
1371
1422
|
|
|
1372
|
-
// 测量在 runCrsiModification 成功后进行(避免 failed proposal 白跑
|
|
1423
|
+
// 测量在 runCrsiModification 成功后进行(避免 failed proposal 白跑 10 次 LLM 调用(k=5 × 前/后两臂))。
|
|
1373
1424
|
const improvementLine = await measureModification(ctx, {
|
|
1374
1425
|
description,
|
|
1375
1426
|
filePath,
|
|
@@ -1380,6 +1431,7 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
|
|
|
1380
1431
|
return {
|
|
1381
1432
|
content:
|
|
1382
1433
|
`✅ 测试通过。审阅下方 diff:\n` +
|
|
1434
|
+
(simNote ? `${simNote}\n` : '') +
|
|
1383
1435
|
renderGateNote(result) +
|
|
1384
1436
|
`\n${result.diff}\n` +
|
|
1385
1437
|
improvementLine +
|
|
@@ -1439,6 +1491,26 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
|
|
|
1439
1491
|
// 常驻教训块**内联**(不带指针):生成算子是无工具的 `llm.chat` 单条消息 ——
|
|
1440
1492
|
// 在此之前它拿到零条教训,而它写出的散文随后就是主代理要遵守的规则。
|
|
1441
1493
|
loadAlwaysOnLessonsBlock(join(root, LESSONS_FILE)),
|
|
1494
|
+
// SIM 读侧:把台账里的实测结果与预测命中一并交给生成算子。此前它只拿到教训散文
|
|
1495
|
+
// (= 只有根因的弱条件)。空台账渲染成空串 ⇒ 提示词逐字不变。
|
|
1496
|
+
// 规则 8:块**延迟到选完目标之后**才渲染 —— 那时才拿得到目标 skill,两个轴
|
|
1497
|
+
// (skill + model)都齐;提前渲染就只能比模型一个轴。
|
|
1498
|
+
(filePath, originalContent) => {
|
|
1499
|
+
const skill = resolveSkillName(filePath, originalContent)
|
|
1500
|
+
return {
|
|
1501
|
+
simBlock: renderSimBlock(readImprovements(), undefined, {
|
|
1502
|
+
model: measurementModel(ctx),
|
|
1503
|
+
skill,
|
|
1504
|
+
}),
|
|
1505
|
+
// P4:该 skill 绑定的可测任务 —— 提议者只能从这些 id 里预测会被修好的题。
|
|
1506
|
+
// 非 skill 文件 / 未绑定任务 ⇒ 空数组(不是「没预测」,是「无从预测」)。
|
|
1507
|
+
taskIds: skill
|
|
1508
|
+
? loadPerformanceTasks()
|
|
1509
|
+
.filter((t) => t.skill === skill)
|
|
1510
|
+
.map((t) => t.id)
|
|
1511
|
+
: [],
|
|
1512
|
+
}
|
|
1513
|
+
},
|
|
1442
1514
|
)
|
|
1443
1515
|
if (!proposal) {
|
|
1444
1516
|
return { content: '散文提议生成失败(LLM 未返回有效结果)。' }
|
|
@@ -1467,7 +1539,7 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
|
|
|
1467
1539
|
|
|
1468
1540
|
// ε 预登记落地:prose 路径此前**不测量**(measureSkillDeltaRepeated 全仓库只有手工路径一个
|
|
1469
1541
|
// 调用点)⇒ ε 曾在 A 流程登记、判定侧在 B 流程,两端永不相遇。这里补上测量。
|
|
1470
|
-
// 成本:每次提案多
|
|
1542
|
+
// 成本:每次提案多 10 次 LLM 调用(k=5 × 前/后两臂,同手工路径 :867 的注释)。
|
|
1471
1543
|
let predictionLine = ''
|
|
1472
1544
|
try {
|
|
1473
1545
|
const sample = await measureSkillDeltaRepeated(llm, {
|
|
@@ -1485,6 +1557,9 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
|
|
|
1485
1557
|
// 反复出现时才能看出这个环到底在修同一件事还是到处救火。
|
|
1486
1558
|
problemKey: normalizeProblemKey(`${signal.category}: ${signal.title}`),
|
|
1487
1559
|
rationale: proposal.description,
|
|
1560
|
+
model: measurementModel(ctx),
|
|
1561
|
+
// P4:缺席(没预测)与空数组(预测「一题都不修好」)是两种读数,原样传。
|
|
1562
|
+
expectedFixes: proposal.expectedFixes,
|
|
1488
1563
|
},
|
|
1489
1564
|
)
|
|
1490
1565
|
setPendingVerdict(report.verdict)
|
package/src/ui/input.tsx
CHANGED
|
@@ -530,7 +530,16 @@ export function InputBar({
|
|
|
530
530
|
}
|
|
531
531
|
// Idle → clear the draft (the intuitive "cancel"), keeping it recoverable:
|
|
532
532
|
// Up from the now-empty input restores it (see the arrow-key branch).
|
|
533
|
-
|
|
533
|
+
// While browsing history, the text on screen is a recalled entry, not the
|
|
534
|
+
// user's draft — save the *draft* slot instead, or Escape overwrites the
|
|
535
|
+
// only copy of what they were typing with an old prompt.
|
|
536
|
+
if (historyIndexRef.current === -1) {
|
|
537
|
+
if (valueRef.current) clearedDraftRef.current = valueRef.current
|
|
538
|
+
} else if (savedDraftRef.current) {
|
|
539
|
+
clearedDraftRef.current = savedDraftRef.current
|
|
540
|
+
}
|
|
541
|
+
historyIndexRef.current = -1
|
|
542
|
+
savedDraftRef.current = ''
|
|
534
543
|
setValue('')
|
|
535
544
|
valueRef.current = ''
|
|
536
545
|
clearSuggestion()
|
|
@@ -605,6 +614,16 @@ export function InputBar({
|
|
|
605
614
|
return
|
|
606
615
|
}
|
|
607
616
|
|
|
617
|
+
// Editing a recalled entry ends browsing but must not destroy the text
|
|
618
|
+
// that was there before the recall. Down brings that draft back instead of
|
|
619
|
+
// being a no-op (the entry used to blank `savedDraft` on the first edit).
|
|
620
|
+
if (key.downArrow && historyIndexRef.current === -1 && savedDraftRef.current) {
|
|
621
|
+
const restored = savedDraftRef.current
|
|
622
|
+
savedDraftRef.current = ''
|
|
623
|
+
setValue(restored)
|
|
624
|
+
return
|
|
625
|
+
}
|
|
626
|
+
|
|
608
627
|
const result = navigateHistory(
|
|
609
628
|
{
|
|
610
629
|
history,
|
|
@@ -698,10 +717,11 @@ export function InputBar({
|
|
|
698
717
|
<MiphamTextInput
|
|
699
718
|
value={value}
|
|
700
719
|
onChange={(val) => {
|
|
701
|
-
// Reset history browsing when user starts typing
|
|
720
|
+
// Reset history browsing when user starts typing. `savedDraft` is
|
|
721
|
+
// deliberately kept: it is the only copy of what they were writing
|
|
722
|
+
// before the recall, and Down restores it (see the arrow branch).
|
|
702
723
|
if (historyIndexRef.current !== -1) {
|
|
703
724
|
historyIndexRef.current = -1
|
|
704
|
-
savedDraftRef.current = ''
|
|
705
725
|
}
|
|
706
726
|
// ── Ghost-text 自动补全:每次输入清 suggestion + 重排防抖 ──
|
|
707
727
|
setSuggestion(null)
|
package/src/ui/picker.tsx
CHANGED
|
@@ -45,7 +45,14 @@ export function ModelPicker({
|
|
|
45
45
|
const idx = providers.findIndex((p) => p.id === currentProvider)
|
|
46
46
|
return idx >= 0 ? idx : 0
|
|
47
47
|
})
|
|
48
|
-
|
|
48
|
+
// Seed the model cursor on the model the session is actually using, so Tab
|
|
49
|
+
// into the model panel lands on it (it used to start at row 0).
|
|
50
|
+
const modelIdx = useKeyState(() => {
|
|
51
|
+
const provider = providers.find((p) => p.id === currentProvider)
|
|
52
|
+
const models = provider ? activeModels(provider) : []
|
|
53
|
+
const idx = models.findIndex((m) => m.id === currentModel)
|
|
54
|
+
return idx >= 0 ? idx : 0
|
|
55
|
+
})
|
|
49
56
|
|
|
50
57
|
const selectedProvider = providers[providerIdx.value]
|
|
51
58
|
const models = selectedProvider ? activeModels(selectedProvider) : []
|
|
@@ -54,10 +61,15 @@ export function ModelPicker({
|
|
|
54
61
|
const goToProvider = useCallback(
|
|
55
62
|
(idx: number) => {
|
|
56
63
|
providerIdx.set(wrap(idx, providers.length))
|
|
57
|
-
|
|
64
|
+
// Land on the session's current model when this is its provider; any
|
|
65
|
+
// other provider stays at row 0.
|
|
66
|
+
const provider = providers[wrap(idx, providers.length)]
|
|
67
|
+
const models = provider ? activeModels(provider) : []
|
|
68
|
+
const current = models.findIndex((m) => m.id === currentModel)
|
|
69
|
+
modelIdx.set(current >= 0 ? current : 0)
|
|
58
70
|
activePanel.set('model') // auto-switch to model panel
|
|
59
71
|
},
|
|
60
|
-
[providers
|
|
72
|
+
[providers, providerIdx, modelIdx, currentModel],
|
|
61
73
|
)
|
|
62
74
|
|
|
63
75
|
/** 相对移动 —— 按 `read()` 叠加,同一拍里的两次 ↓ 就是两步。 */
|