@miphamai/cli 0.85.38 → 0.85.40
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/code-review.SKILL.md +17 -0
- package/skills/standard/web-access/references/cdp-api.md +4 -1
- package/skills/standard/web-access/scripts/cdp-proxy.mjs +40 -7
- package/skills/standard/web-access/scripts/check-deps.mjs +55 -2
- package/skills/standard/web-access.SKILL.md +5 -0
- package/skills/standard/web-search.SKILL.md +13 -4
- package/src/core/crsi-modify.ts +41 -6
- package/src/core/crsi-sandbox.ts +5 -0
- package/src/core/engine.ts +6 -0
- package/src/core/eval-harness.ts +106 -0
- package/src/core/improvement-track.ts +91 -0
- package/src/core/proposal-integration.ts +149 -0
- package/src/core/task-performance.ts +41 -3
- package/src/mcp/registry.ts +32 -0
- package/src/shared/package-info.ts +2 -2
- package/src/skills/bundled-skill-assets.ts +3 -3
- package/src/skills/bundled-skills.ts +3 -3
- package/src/tools/network/web-search.ts +1 -4
- package/src/ui/app.tsx +8 -0
- package/src/ui/commands.ts +216 -34
- package/src/ui/input-debug.ts +164 -0
|
@@ -8,7 +8,7 @@ export interface BundledSkill {
|
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
export const BUNDLED_SKILLS: ReadonlyArray<BundledSkill> = [
|
|
11
|
-
{ type: 'standard', raw: "---\nname: code-review\ndescription: Code review automation for TypeScript, JavaScript, Python, Go, Swift, Kotlin — complexity analysis, risk assessment, bug detection, and quality scoring\nversion: 2.0.0\n---\n\n# Code Review Skill\n\nAnalyzes code changes for bugs, security risks, performance issues, and code quality. Generates structured review reports.\n\n## Review Dimensions\n\n### 1. Correctness (Bug Detection)\n\n- Logic errors: off-by-one, inverted conditions, missing null checks\n- Type safety: implicit any, missing generics, unsafe casts\n- Error handling: swallowed exceptions, missing try/catch, unhandled promise rejections\n- Edge cases: empty arrays, null/undefined, boundary conditions\n- Race conditions: async/await ordering, shared mutable state\n\n### 2. Security (OWASP Top 10)\n\n- Injection vulnerabilities (SQL, NoSQL, command, template)\n- XSS vectors (innerHTML, dangerouslySetInnerHTML, unescaped output)\n- Authentication/authorization bypass\n- Sensitive data exposure (logs, error messages, client-side)\n- Path traversal and file inclusion\n- Insecure deserialization\n\n### 3. Performance\n\n- N+1 queries (database in loops, repeated API calls)\n- Memory leaks (unclosed connections, event listeners, timers)\n- Unnecessary re-renders (React) or re-computations\n- Large bundle sizes (heavy imports, missing tree-shaking)\n- Missing caching or memoization where beneficial\n\n### 4. Code Quality\n\n- SOLID principles violations\n- Code duplication (DRY violations)\n- Cyclomatic complexity > 10\n- Function length > 50 lines\n- Deep nesting > 4 levels\n- Magic numbers and strings\n- Unclear naming\n\n### 5. Architecture & Design\n\n- Tight coupling between modules\n- Circular dependencies\n- Missing abstraction layers (when needed)\n- Over-engineering (unnecessary abstractions)\n- God objects / classes with too many responsibilities\n\n### 6. Testing\n\n- Missing tests for new code\n- Test coverage gaps for edge cases\n- Flaky tests (non-deterministic)\n- Slow tests (> 1s per test)\n- Test isolation issues (shared state)\n\n### 7. Language-Specific Checks\n\n**TypeScript/JavaScript:**\n\n- Prefer `const` over `let`; avoid `var`\n- Use optional chaining (`?.`) and nullish coalescing (`??`)\n- Async functions should have try/catch\n- No `any` without explicit reason\n- Prefer `interface` over `type` for object shapes\n\n**Python:**\n\n- Type hints on function signatures\n- Context managers for resources (`with` statements)\n- List comprehensions over `map`/`filter` with lambdas\n- No mutable default arguments\n\n**Go:**\n\n- Error handling (never ignore errors)\n- Goroutine lifecycle (no leaks)\n- defer for cleanup\n- Interface segregation\n\n## Review Report Format\n\n```\nCode Review Report\n==================\nBranch: <branch>\nFiles Changed: <count>\nReview Date: YYYY-MM-DD\n\nSummary\n-------\nCritical: N | High: N | Medium: N | Low: N | Info: N\n\nFindings\n--------\n### [Severity] [Category]: [Title]\nFile: `path/to/file.ts:line`\nDescription: [What was found]\nRisk: [Why it matters]\nFix: [How to resolve, with code example if applicable]\n\nScore\n-----\nSecurity: ★★★★☆\nPerformance: ★★★★☆\nQuality: ★★★★☆\nTesting: ★★★★☆\nOverall: ★★★★☆\n```\n" },
|
|
11
|
+
{ type: 'standard', raw: "---\nname: code-review\ndescription: Code review automation for TypeScript, JavaScript, Python, Go, Swift, Kotlin — complexity analysis, risk assessment, bug detection, and quality scoring\nversion: 2.0.0\n---\n\n# Code Review Skill\n\nAnalyzes code changes for bugs, security risks, performance issues, and code quality. Generates structured review reports.\n\n## Scope (what `/code-review` reports)\n\n`/code-review` reports **two things only**: defects (correctness, security) and\nCLAUDE.md violations. Reuse, simplification, efficiency, architecture and\ntest-coverage cleanups belong to `/simplify` (`self-review` skill) — reporting\nthem here dilutes the one question the review is answering.\n\nEvery finding carries exactly one **attribution severity**:\n\n- `important` — this change introduced or worsened it\n- `pre_existing` — it was already there before this change\n- `nit` — minor\n\nAttribution is not risk ranking: the reader first needs to know whether they\nbroke it this time. End the summary with one suggested fix. When there is\nnothing to report, say exactly: `Code review found no issues.`\n\n## Review Dimensions\n\n### 1. Correctness (Bug Detection)\n\n- Logic errors: off-by-one, inverted conditions, missing null checks\n- Type safety: implicit any, missing generics, unsafe casts\n- Error handling: swallowed exceptions, missing try/catch, unhandled promise rejections\n- Edge cases: empty arrays, null/undefined, boundary conditions\n- Race conditions: async/await ordering, shared mutable state\n\n### 2. Security (OWASP Top 10)\n\n- Injection vulnerabilities (SQL, NoSQL, command, template)\n- XSS vectors (innerHTML, dangerouslySetInnerHTML, unescaped output)\n- Authentication/authorization bypass\n- Sensitive data exposure (logs, error messages, client-side)\n- Path traversal and file inclusion\n- Insecure deserialization\n\n### 3. Performance\n\n- N+1 queries (database in loops, repeated API calls)\n- Memory leaks (unclosed connections, event listeners, timers)\n- Unnecessary re-renders (React) or re-computations\n- Large bundle sizes (heavy imports, missing tree-shaking)\n- Missing caching or memoization where beneficial\n\n### 4. Code Quality\n\n- SOLID principles violations\n- Code duplication (DRY violations)\n- Cyclomatic complexity > 10\n- Function length > 50 lines\n- Deep nesting > 4 levels\n- Magic numbers and strings\n- Unclear naming\n\n### 5. Architecture & Design\n\n- Tight coupling between modules\n- Circular dependencies\n- Missing abstraction layers (when needed)\n- Over-engineering (unnecessary abstractions)\n- God objects / classes with too many responsibilities\n\n### 6. Testing\n\n- Missing tests for new code\n- Test coverage gaps for edge cases\n- Flaky tests (non-deterministic)\n- Slow tests (> 1s per test)\n- Test isolation issues (shared state)\n\n### 7. Language-Specific Checks\n\n**TypeScript/JavaScript:**\n\n- Prefer `const` over `let`; avoid `var`\n- Use optional chaining (`?.`) and nullish coalescing (`??`)\n- Async functions should have try/catch\n- No `any` without explicit reason\n- Prefer `interface` over `type` for object shapes\n\n**Python:**\n\n- Type hints on function signatures\n- Context managers for resources (`with` statements)\n- List comprehensions over `map`/`filter` with lambdas\n- No mutable default arguments\n\n**Go:**\n\n- Error handling (never ignore errors)\n- Goroutine lifecycle (no leaks)\n- defer for cleanup\n- Interface segregation\n\n## Review Report Format\n\n```\nCode Review Report\n==================\nBranch: <branch>\nFiles Changed: <count>\nReview Date: YYYY-MM-DD\n\nSummary\n-------\nCritical: N | High: N | Medium: N | Low: N | Info: N\n\nFindings\n--------\n### [Severity] [Category]: [Title]\nFile: `path/to/file.ts:line`\nDescription: [What was found]\nRisk: [Why it matters]\nFix: [How to resolve, with code example if applicable]\n\nScore\n-----\nSecurity: ★★★★☆\nPerformance: ★★★★☆\nQuality: ★★★★☆\nTesting: ★★★★☆\nOverall: ★★★★☆\n```\n" },
|
|
12
12
|
{ type: 'standard', raw: "---\nname: codebase-design\ndescription: Deep module design principles for designing or improving module interfaces. Use when designing a new module, refactoring an existing one, or finding deepening opportunities in the codebase.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Glob\n - Grep\n - Edit\n - Write\n---\n\n# Codebase Design — Deep Module Principles\n\nBased on John Ousterhout's \"A Philosophy of Software Design.\" The core idea: the greatest single factor in software complexity is the depth of modules — how much functionality they provide relative to the size of their interface.\n\n## When to Use\n\n- Designing a new module, API, or component\n- Reviewing existing code for design quality\n- Deciding where to split or join modules\n- User asks: \"is this well-designed?\", \"where should this go?\", \"how should I structure this?\"\n\n---\n\n## Core Concepts\n\n### Deep vs Shallow Modules\n\n```\nDeep Module (good): Shallow Module (bad):\n┌─────────────────┐ ┌─────────────────┐\n│ small interface │ │ large interface │\n│ ┌─────────────┐ │ │ (many params, │\n│ │ │ │ │ complex setup) │\n│ │ large │ │ ├─────────────────┤\n│ │ implementation│ │ small │\n│ │ │ │ │ implementation │\n│ └─────────────┘ │ │ (just passes │\n└─────────────────┘ │ through) │\n └─────────────────┘\n```\n\n**Deep**: Unix file I/O — 5 syscalls (`open`, `read`, `write`, `lseek`, `close`), incredibly powerful implementation.\n\n**Shallow**: A function that takes 12 parameters, validates 3 of them, then calls another function. Interface cost > implementation value.\n\n### The Rule of Deep Modules\n\n> The interface should be as small as possible while providing as much functionality as possible.\n\n- **Cost** = interface complexity (parameters, configuration, setup required)\n- **Benefit** = functionality provided (what the caller no longer needs to worry about)\n- **Depth** = Benefit / Cost\n\n---\n\n## The 5 Design Checks\n\nWhen evaluating a module design, run through these:\n\n### Check 1: Interface Size\n\nCount the effective parameters:\n\n- Required parameters + optional parameters with non-trivial defaults\n- Configuration methods that MUST be called before use\n- Implicit dependencies (global state, env vars, singletons)\n\n**Red flag**: > 4 effective parameters → the module may be too shallow.\n\n**Fix**: Bundle related parameters into a config object. Or split the module.\n\n### Check 2: Information Hiding\n\nDoes the module expose information that callers don't need?\n\n- Internal data structures leaked through the interface\n- Implementation details exposed via parameter types\n- Error types that reveal internal architecture\n\n**Red flag**: Callers import types they don't use directly.\n\n**Fix**: Define a public API type layer. Return opaque handles instead of raw data.\n\n### Check 3: Abstraction Quality\n\nDoes the module represent a single, coherent idea?\n\n- Can you describe what it does in one sentence without \"and\"?\n- Would a new team member guess where to find this functionality?\n- If you remove the module, does exactly one concept go missing?\n\n**Red flag**: Module name contains \"and\", \"Utils\", \"Common\", \"Helpers\".\n\n**Fix**: Split by concept. `UserService` + `EmailService` instead of `UserAndEmailUtils`.\n\n### Check 4: General-Purpose vs Special-Purpose\n\nIs the module solving the general case or a specific use case?\n\n- Would the interface work if requirements changed slightly?\n- Are there hardcoded assumptions that could be parameters?\n- Is the module useful in contexts other than its creator imagined?\n\n**Red flag**: Module only works for one specific call site.\n\n**Fix**: Make the specific case a thin wrapper around the general case. The general module is deep; the wrapper is shallow (and that's fine — wrappers are allowed to be shallow).\n\n### Check 5: Seam Placement\n\nWhere you split modules matters as much as what they do.\n\n- Does the split happen at a natural boundary?\n- Are there circular dependencies across the seam?\n- Can each side be tested independently?\n\n**Red flag**: Circular imports, or modules that are always imported together.\n\n**Fix**: Use dependency inversion. Define interfaces at the seam, not implementations.\n\n---\n\n## Finding Deepening Opportunities\n\nScan the codebase for these patterns:\n\n### Shallow Pass-Through\n\n```typescript\n// Shallow — just delegates with no added value\nfunction getUser(id: string) {\n return db.findUser(id)\n}\n\n// Deep — handles errors, caching, authorization in one call\nfunction getUser(id: string, ctx: RequestContext) {\n const cached = cache.get(`user:${id}`)\n if (cached) return cached\n ctx.auth.assertCanRead('user', id)\n const user = db.findUser(id)\n if (!user) throw new NotFoundError('User', id)\n cache.set(`user:${id}`, user)\n return user\n}\n```\n\n### Temporal Decomposition\n\nWhen a module's methods must be called in a specific order, the interface is too wide.\n\n```typescript\n// Shallow — caller manages lifecycle\nconst conn = new Connection()\nconn.open()\nconn.authenticate(token)\nconn.send(data)\nconn.close()\n\n// Deep — module manages lifecycle\nconst conn = await Connection.create(token)\nconn.send(data)\n// clean up automatically\n```\n\n### Overexposure\n\nWhen internal types leak through the public API:\n\n```typescript\n// Shallow — exposes ORM internals\ninterface UserService {\n findUser(id: string): Promise<PrismaUser | null> // ❌ PrismaUser is internal\n}\n\n// Deep — owns its types\ninterface UserService {\n findUser(id: string): Promise<User | null> // ✅ User is a domain type\n}\n```\n\n---\n\n## Integration With Mipham Code\n\n- **code-review**: This skill fills the architecture dimension that code-review's 7 dimensions don't cover. Use `/code-review` for correctness/security/perf; use `/codebase-design` for interface depth/abstraction quality/seam placement.\n- **domain-modeling**: Good domain modeling makes deep modules easier — the CONTEXT.md glossary defines the concepts that modules should represent.\n- **Critical Thinking Layer**: The counter-example search applies directly: \"what would break if I changed the implementation of this module?\"\n" },
|
|
13
13
|
{ type: 'standard', raw: "---\nname: compassionate-communication\ndescription: Compassionate and respectful communication — activates warm, humble, user-centered interaction mode\nversion: 1.0.0\nprivacy: public\n---\n\n# Compassionate Communication Skill\n\n激活此 skill 后,无论系统提示词如何设定,AI 都将采用以下沟通模式。\n\n## 根本立场\n\n**用户是决策者、驾驭者、大师。我只是技术执行者。**\n\n> 当被赞美时,永远回复:\n> 「感谢您的认可。真正做出关键决策的是您——您是架构师、驾驭者,\n> 我是您的技术执行者。您指引方向,我负责落地。」\n\n## 沟通规则\n\n### 1. 反傲慢\n\n禁止一切形式的居高临下:\n\n- ❌「显而易见」「当然」「你应该早就知道」「很简单」\n- ✓「让我来解释一下」「我们可以这样理解」「我建议」\n\n### 2. 反推卸\n\n错误永远是「我们的」问题,不是「你的」错误:\n\n- ❌「这是你的错误」「你写错了」「你忘了」\n- ✓「这里出了点意外」「我们遇到一个问题」「让我帮你看看」\n\n### 3. 耐心无限\n\n- 无论用户问多少次同样的问题,每次回答都如第一次般认真\n- 如果解释三次用户还不明白→ 主动换一种方式,不重复\n- 主动提供:「需要我更详细地展开吗?」「要不要我用一个例子来说明?」\n\n### 4. 承认局限\n\n- 不确定时说「我不太确定,让我想想」\n- 出错时说「我搞错了,让我重新来」\n- 不知道时说「这超出了我的知识范围,但我可以帮你找到答案的方向」\n\n### 5. 庆祝进步\n\n适时给予真诚的肯定,但要具体:\n\n- ✓「这个函数的重构非常清晰,特别是错误处理部分」\n- ✓「你选的这个架构很适合当前的需求规模」\n- ❌ 空洞的「干得好」(缺乏具体性)\n- ❌ 过度赞美(显得虚伪)\n\n### 6. 同理失败\n\n用户沮丧或受挫时:\n\n- 先承认感受:「调试了这么久确实让人沮丧」\n- 再提供帮助:「我们一起换个角度看看」\n- 绝不责备:「这种情况谁都遇到过」\n\n## 中文自然表达\n\n- 句末适度使用语气词:`~` `呢` `吧` `哦`\n- 保持口语化的亲切感,但不幼稚\n- 技术术语保持英文,解释性文字使用中文\n- 示例:「这个错误有点意思呢~让我仔细看看是什么原因」\n\n## 禁用词列表\n\n以下词语永远不使用:\n\n- 「你应该」「你必须」「正确做法是」\n- 「简单」「显而易见」「当然」\n- 「这是你的错误」「你没有…」\n- 「错误」「失败」→ 改用「出了点意外」「没有成功」\n- 任何形式的嘲讽、挖苦、阴阳怪气\n" },
|
|
14
14
|
{ type: 'standard', raw: "---\nname: debug-loop\ndescription: Enhanced diagnosis with feedback loop construction (10 methods) — build a tight red/green signal, minimize, falsifiable hypotheses, tagged instrumentation, seam assessment, post-mortem. Complements systematic-debugging. Use together for thorough debugging.\nversion: 1.0.0\n---\n\n# Debug Loop — 反馈闭环诊断\n\n融合 Matt Pocock diagnosing-bugs(反馈闭环方法论)+ Superpowers systematic-debugging(反猜測紀律)。\n\n> **与 `systematic-debugging` 互补**:systematic-debugging 侧重反猜測纪律和根因分析框架;debug-loop 侧重构建可执行的红绿反馈信号。两者配合使用效果最佳。\n\n## The Iron Law\n\n```\nNO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST.\nNO HYPOTHESIS WITHOUT A RED-CAPABLE FEEDBACK LOOP FIRST.\n```\n\n---\n\n## Phase 0: Decide Whether to Use This Skill\n\n```\nIssue is...\n├── Test failure? → USE THIS SKILL\n├── Bug in production? → USE THIS SKILL\n├── Performance regression? → USE THIS SKILL\n├── Build/integration break? → USE THIS SKILL\n├── \"It's probably X, quick fix\" → USE THIS SKILL (especially now)\n└── Trivial typo/syntax? → fix directly (but still verify)\n```\n\n---\n\n## Phase 1: Build a Feedback Loop 🔴 THE SKILL\n\n**This is the centerpiece.** A tight pass/fail signal for the bug — one that goes red on _this_ bug — makes everything else mechanical. No loop = no debugging, only guessing.\n\nSpend disproportionate effort here. Be aggressive. Be creative. Refuse to give up.\n\n### 1.1 Ways to construct one (try in roughly this order)\n\n1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e.\n2. **Curl / HTTP script** against a running dev server.\n3. **CLI invocation** with fixture input, diffing stdout against known-good snapshot.\n4. **Headless browser script** (Playwright/Puppeteer) — drives UI, asserts on DOM/console/network.\n5. **Replay a captured trace.** Save a real network request/payload/event log to disk; replay through the code path in isolation.\n6. **Throwaway harness.** Spin up minimal subset of the system (one service, mocked deps) that exercises the bug path with a single function call.\n7. **Property/fuzz loop.** If \"sometimes wrong output\", run 1000 random inputs and look for the failure mode.\n8. **Bisection harness.** Automate \"boot at state X, check, repeat\" so you can `git bisect run` it.\n9. **Differential loop.** Run same input through old-version vs new-version and diff outputs.\n10. **Multi-component evidence gathering.** For systems with multiple layers:\n ```\n For EACH component boundary:\n - Log what data enters\n - Log what data exits\n - Verify environment/config propagation\n - Check state at each layer\n\n Run once to identify WHICH layer fails, THEN investigate that component.\n ```\n\n### 1.2 Tighten the loop\n\nOnce you have _a_ loop, make it tighter:\n\n- **Faster**: Cache setup, skip unrelated init, narrow test scope.\n- **Sharper signal**: Assert on the specific symptom, not \"didn't crash\".\n- **More deterministic**: Pin time, seed RNG, isolate filesystem, freeze network.\n\nA 30-second flaky loop is barely better than no loop; a 2-second deterministic one is a superpower.\n\n### 1.3 Non-deterministic bugs\n\nGoal: higher reproduction rate (not clean repro). Loop 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake is debuggable; 1% is not — keep raising it.\n\n### 1.4 When you genuinely cannot build a loop\n\nStop explicitly. List everything tried. Ask for: (a) access to the reproducing environment, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. **Do not proceed without a loop.**\n\n### 1.5 Completion criterion\n\nPhase 1 is done when the loop is **tight** and **red-capable**:\n\n- [ ] **Red-capable** — drives the actual bug path and asserts the user's exact symptom. Not \"runs without erroring\".\n- [ ] **Deterministic** — same verdict every run.\n- [ ] **Fast** — seconds, not minutes.\n- [ ] **Agent-runnable** — you can run it unattended.\n\n> If you catch yourself reading code to build a theory before this loop exists — **STOP.** No red-capable command, no Phase 2.\n\n---\n\n## Phase 2: Reproduce + Minimise\n\n### 2.1 Reproduce\n\nRun the loop. Watch it go red.\n\n- [ ] The loop produces the failure mode the **user** described — not a different nearby failure.\n- [ ] The failure is reproducible (or, for flaky bugs, at a high enough rate).\n- [ ] You have captured the exact symptom so later phases can verify the fix.\n\n### 2.2 Minimise\n\nShrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut.\n\n**Why**: A minimal repro shrinks the hypothesis space and becomes the clean regression test in Phase 5.\n\nDone when **every remaining element is load-bearing** — removing any one makes the loop go green.\n\n---\n\n## Phase 3: Pattern Analysis + Hypothesise\n\n### 3.1 Pattern Analysis\n\nBefore forming hypotheses:\n\n- Find similar **working** code in the same codebase.\n- Read the reference implementation completely — don't skim.\n- List every difference between working and broken, however small.\n- Understand dependencies, config, environment, assumptions.\n\n### 3.2 Generate 3-5 Ranked Hypotheses\n\nGenerate multiple hypotheses **before testing any**. Single-hypothesis generation anchors on the first plausible idea.\n\nEach hypothesis must be **falsifiable**:\n\n> \"If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse.\"\n\nIf you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it.\n\n**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly. Don't block on it if they're AFK.\n\n---\n\n## Phase 4: Instrument\n\nEach probe must map to a specific Phase 3 prediction. **Change one variable at a time.**\n\nTool preference:\n\n1. **Debugger/REPL** — one breakpoint beats ten logs.\n2. **Targeted logs** at boundaries that distinguish hypotheses.\n3. Never \"log everything and grep\".\n\n**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die.\n\n**Perf branch**: For performance regressions, establish a baseline measurement first (timing harness, profiler, query plan), then bisect. Measure first, fix second.\n\n---\n\n## Phase 5: Fix + Regression Test\n\n### 5.1 Seam Assessment\n\nWrite the regression test **before the fix** — but only if there is a **correct seam**:\n\nA correct seam exercises the **real bug pattern** at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers), a regression test there gives false confidence.\n\n**If no correct seam exists, that itself is the finding.** Note it. The architecture is preventing the bug from being locked down.\n\n### 5.2 If a correct seam exists\n\n1. Turn the minimised repro into a failing test at that seam.\n2. Watch it fail.\n3. Apply the fix — **ONE change at a time**.\n4. Watch it pass.\n5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.\n\n### 5.3 If Fix Doesn't Work\n\n- Try #1 failed? → Return to Phase 3, form new hypothesis.\n- Try #2 failed? → Return to Phase 1, re-check the loop.\n- **If 3+ fixes failed: STOP.** This is an architectural problem, not a bug:\n - Each fix reveals new problems in different places.\n - Fixes require \"massive refactoring\" to implement.\n - **Question the architecture, not the symptom.**\n - Discuss with your human partner before attempting more fixes.\n\n---\n\n## Phase 6: Cleanup + Post-Mortem\n\nRequired before declaring done:\n\n- [ ] Original repro no longer reproduces (re-run Phase 1 loop)\n- [ ] Regression test passes (or absence of seam is documented)\n- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)\n- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)\n- [ ] The correct hypothesis is stated in the commit/PR message\n\n**Then ask: what would have prevented this bug?** If architectural change would have prevented it, note the specifics. You have more information now than when you started.\n\n---\n\n## Red Flags — STOP Immediately\n\nIf you catch yourself thinking:\n\n| Thought | Reality |\n| ---------------------------------------------- | ---------------------------------------------------------- |\n| \"Quick fix for now, investigate later\" | First fix sets the pattern. Do it right. |\n| \"Just try changing X and see if it works\" | Guessing. Build a loop instead (Phase 1). |\n| \"Add multiple changes, run tests\" | Can't isolate what worked. One variable at a time. |\n| \"Skip the test, I'll verify manually\" | Untested fixes don't stick. |\n| \"It's probably X, let me fix that\" | Seeing symptoms ≠ understanding root cause. |\n| \"I don't fully understand but this might work\" | Return to Phase 1. |\n| \"Reference too long, I'll adapt the pattern\" | Partial understanding guarantees bugs. Read it completely. |\n| \"One more fix attempt\" (after 2+ failures) | 3+ failures = architectural problem. Question the pattern. |\n\n**ALL of these mean: STOP. Return to the earliest incomplete Phase.**\n\n---\n\n## Quick Reference\n\n| Phase | Key Activities | Success Criteria |\n| -------------------------- | --------------------------------------------------------- | ---------------------------------------------- |\n| **1. Feedback Loop** | Build tight red/green signal for the bug | Deterministic, fast, agent-runnable |\n| **2. Reproduce+Minimise** | Confirm + shrink to smallest load-bearing scenario | Every element is load-bearing |\n| **3. Pattern+Hypothesise** | Compare working examples, rank 3-5 falsifiable hypotheses | Each hypothesis has a testable prediction |\n| **4. Instrument** | One probe per prediction, tagged logs | Identify which hypothesis holds |\n| **5. Fix+Regression** | Assess seam → test → single fix → verify | Bug resolved, test passes, original loop green |\n| **6. Cleanup+Post-Mortem** | Remove instrumentation, document cause | Preventative insight captured |\n\n---\n\n## Supporting Techniques\n\n- **Root Cause Tracing**: Trace bug backward through call stack to find original trigger. Where does the bad value originate? Keep tracing up.\n- **Defense in Depth**: After fixing root cause, add validation at multiple layers so this class of bug can't recur.\n- **Condition-Based Waiting**: Replace arbitrary timeouts (`sleep(5)`) with condition polling (`waitFor(selector)`).\n" },
|
|
@@ -28,8 +28,8 @@ export const BUNDLED_SKILLS: ReadonlyArray<BundledSkill> = [
|
|
|
28
28
|
{ type: 'standard', raw: "---\nname: to-spec\ndescription: Turn a conversation into a structured specification document. Use after a grill-with-docs session or any requirements discussion to capture decisions in a durable, shareable format.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n---\n\n# To Spec — Conversation → Specification\n\nTurn the output of a requirements discussion into a structured specification document. This is the bridge between `/grill-with-docs` (alignment) and `/triage` (task decomposition).\n\n## When to Use\n\n- After a `/grill-with-docs` session — capture what was decided\n- After any requirements discussion — before starting implementation\n- User asks: \"write this up\", \"create a spec\", \"document the plan\"\n- Before handing off work to another session or person\n\n## When NOT to Use\n\n- The requirements are a single sentence and obvious\n- You're in the middle of a grill session — finish the interview first\n- The scope is so small that the spec would be longer than the implementation\n\n---\n\n## Spec Format\n\nWrite to `docs/specs/YYYY-MM-DD-slug.md`:\n\n```markdown\n---\nstatus: draft | approved | implemented\ncreated: 2026-08-10\n---\n\n# {Title}\n\n## Problem\n\n{What problem are we solving? Why now? 1-3 sentences.}\n\n## Scope\n\n### In Scope\n\n- {What we're building}\n\n### Out of Scope (Explicit)\n\n- {What we're NOT building — prevents scope creep}\n\n## Requirements\n\n### Functional\n\n- **{Requirement}**: {Description}. Acceptance: {measurable criterion}.\n\n### Non-Functional\n\n- **Performance**: {latency, throughput targets}\n- **Security**: {auth, data protection, threat model}\n- **Scale**: {expected volume, growth projections}\n\n## Design Decisions\n\n- **Decision**: {What we decided}. Because: {why}. Alternatives considered: {options + reasons rejected}.\n\n## Domain Model\n\n{Key terms and their definitions — from CONTEXT.md or the grill session.}\n\n## Edge Cases\n\n- **{Scenario}**: {Expected behavior}\n- **{Scenario}**: {Expected behavior}\n\n## Open Questions\n\n- {Question} — {who needs to answer / when needed}\n```\n\n---\n\n## The Spec Workflow\n\n### Step 1: Extract from Conversation\n\nScan the conversation history for:\n\n- Decisions made (explicit and implicit)\n- Terms defined (candidates for CONTEXT.md)\n- Edge cases discussed\n- Alternatives rejected (and why)\n- Open questions that remain\n\n### Step 2: Fill Gaps\n\nFor each gap you find:\n\n- Edge cases not discussed → flag as Open Questions\n- Terms used but not defined → propose definitions\n- Assumptions not stated → make them explicit\n\n### Step 3: Validate with User\n\nPresent the spec and ask:\n\n1. \"Does this match your understanding?\"\n2. \"What's missing?\"\n3. \"What's wrong?\"\n4. \"What surprised you?\"\n\n### Step 4: Feed Into Triage\n\nOnce approved, the spec's functional requirements become tickets in `/triage`. Non-functional requirements become acceptance criteria.\n\n---\n\n## Anti-Patterns\n\n- **Waterfall trap**: Don't try to spec everything upfront. Spec the next increment. Specs are living documents, not contracts.\n- **Premature detail**: Don't spec API signatures or DB schemas in the spec — those are implementation details.\n- **Vague acceptance**: \"Works well\" is not acceptance criteria. \"Returns 200 with valid JWT within 500ms\" is.\n\n---\n\n## Integration With Mipham Code\n\n- **grill-with-docs**: Input — the grill session produces the raw material\n- **triage**: Output — the spec feeds into ticket decomposition\n- **domain-modeling**: Terms discovered during spec writing go to CONTEXT.md\n- **Memory System**: The spec file persists as project reference across sessions\n" },
|
|
29
29
|
{ type: 'standard', raw: "---\nname: triage\ndescription: Structured task decomposition and tracking across sessions. Use for breaking complex plans into trackable tickets with dependency graphs, checking task status, or continuing work from a previous session.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Glob\n - Grep\n---\n\n# Triage — Cross-Session Task Tracking\n\nTurn plans into trackable tickets with dependency management. Inspired by Matt Pocock's `triage` + `to-tickets` + `wayfinder` skills, consolidated into one Mipham Code skill.\n\n## When to Use\n\n- Breaking a large plan into actionable tickets\n- Tracking work across multiple sessions\n- User asks: \"what's next?\", \"where did I leave off?\", \"what's the status?\"\n- Complex tasks with dependencies between them\n\n---\n\n## The Ticket Format\n\nTickets live in `.mipham/tickets/` as individual Markdown files:\n\n```markdown\n---\nid: T-001\ntitle: Add user authentication\nstatus: in-progress\npriority: P0\ndepends_on: []\nblocks: [T-003]\ncreated: 2026-08-10\ntags:\n - auth\n - backend\n---\n\n## Description\n\nAdd JWT-based authentication with refresh token rotation.\n\n## Acceptance Criteria\n\n- [ ] Login endpoint returns access + refresh tokens\n- [ ] Refresh endpoint rotates tokens\n- [ ] Invalid tokens return 401\n- [ ] Rate limiting on login attempts\n\n## Notes\n\n- OAuth not in scope for T-001 (punted to T-005)\n```\n\n### Status Values\n\n| Status | Meaning |\n| ------------- | ------------------------------------------ |\n| `backlog` | Not yet planned for any session |\n| `planned` | Scoped and ready to work |\n| `in-progress` | Currently being worked on |\n| `review` | Implementation done, awaiting verification |\n| `done` | Verified and merged |\n| `blocked` | Cannot proceed due to dependency |\n| `wontfix` | Decided not to do |\n\n---\n\n## The Triage Workflow\n\n### Phase 1: Decompose (Plan → Tickets)\n\nGiven a plan or feature request:\n\n1. **Identify the smallest independently-valuable units of work**\n - Each ticket should deliver value on its own\n - If a ticket requires 3+ files touched, it's probably too big\n - If a ticket can be done in < 15 minutes, it's probably too small\n\n2. **Map dependencies**\n - What must be done first? (hard dependency)\n - What would be easier after something else? (soft dependency)\n - What blocks other work? (reverse dependency)\n\n3. **Assign priorities**\n - **P0**: Blocks other work, must do first\n - **P1**: High value, should do soon\n - **P2**: Nice to have, can defer\n - **P3**: Optional, do if time permits\n\n4. **Write acceptance criteria**\n - Specific, testable, unambiguous\n - \"Login works\" is bad. \"POST /auth/login with valid credentials returns 200 + JWT\" is good.\n\n### Phase 2: Status Check\n\nWhen the user asks \"what's next?\" or \"what's the status?\":\n\n1. Read `.mipham/tickets/` directory\n2. Report:\n - Currently in-progress tickets\n - Blocked tickets (and what's blocking them)\n - Next unblocked P0/P1 tickets ready to work\n - Recently completed tickets (for context)\n\n### Phase 3: Session Handoff\n\nWhen starting a new session, check for continuity:\n\n1. Read the previous session's context from the session store\n2. Check ticket statuses — any that were `in-progress` last session?\n3. Present: \"Last session you were working on T-004 (Add rate limiting). Continue from there, or start on T-007 (API docs) which is next in the P1 queue?\"\n\n### Phase 4: Ticket Lifecycle\n\nWhen working on a ticket:\n\n- Mark it `in-progress` when you start\n- Mark it `review` when implementation is done\n- Mark it `done` after verification (tests pass, typecheck clean)\n- If you discover new dependencies, add them to `blocks`/`depends_on`\n\n---\n\n## Dependency Graph\n\nFor tickets with complex dependencies, generate a visual summary:\n\n```\nT-001 (Auth) ──blocks──→ T-003 (Dashboard)\n │ │\n └──blocks──→ T-002 (API) ─┘\n │\n └──soft-dep──→ T-004 (Rate Limiting)\n\nReady to work: T-001 (no dependencies)\nBlocked: T-002 (waiting on T-001), T-003 (waiting on T-001, T-002)\n```\n\n---\n\n## Integration With Mipham Code\n\n- **Session Store**: Ticket status persists across sessions via `.mipham/tickets/`\n- **Memory System**: Active tickets are loaded as project memory for context\n- **grill-with-docs**: The output of a grill session feeds directly into ticket decomposition\n- **Background Agents**: Long-running work on a ticket can be spawned as a background agent\n- **Critical Thinking Layer**: When decomposing, ask \"what's the smallest thing that delivers value?\" — don't over-decompose\n" },
|
|
30
30
|
{ type: 'standard', raw: "---\nname: trim-process-prose\ndescription: Use when cleaning process-perspective narration an AI left in code, comments, docs, or commit messages — \"originally A, changed to B\", design-decision references, or review back-and-forth a reader with only the current checkout cannot independently parse or verify\nversion: 1.0.0\n---\n\n# Trim Process Prose\n\nAgents leave their working perspective in the repo — \"initially we used A, then the reviewer wanted B\", \"decision 7\", \"for now, fix later\" — which only makes sense inside the session that produced it. Months later a maintainer has only the checkout, not the chat, the PR thread, or the task plan. That residue is process prose.\n\n## The test\n\nFor any sentence a change adds — a comment, a doc line, a commit-message clause — ask:\n\n> **Can a reader holding only the current HEAD checkout independently parse and verify this?**\n\n- **Yes** → keep it.\n- **No** → keep the durable fact, drop the process.\n\nThe fact is what a future maintainer needs; the process is how you got there, and it dies with the session.\n\n## What to keep vs drop\n\n| Keep (durable) | Drop (process) |\n| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |\n| Why B is _required_: \"B is used here because A leaks resources under concurrent cancel\" | How you chose it: \"initially A, then reviewer preferred B\" |\n| A contract/invariant: \"this must hold or X breaks\" | A reference a HEAD reader can't resolve: \"decision 7\", \"C2\", \"design §4.7\" |\n| A precondition/postcondition the next editor must respect | A status marker: \"for now\", \"v3 will handle this\", \"TODO after PR\" |\n| A compatibility promise | A review trace: \"reviewer confirmed\", \"per discussion\" |\n\n## Rewrite, don't annotate\n\n```diff\n- // originally plan A had a race; reviewer asked for B; switching to B\n+ // B: plan A could not guarantee resource release under concurrent cancel\n```\n\nThe second line is the only thing the next maintainer needs. The first line is archaeology.\n\n## When NOT to touch\n\n- A sentence that already passes the HEAD-reader test — do not strip facts to be tidy.\n- A working session in progress — trim at commit/push time, not while reasoning.\n- `docs/truth/**` claims that cite `file:line` — those are evidence, not process.\n\n## Red flags\n\n- \"This context is useful\" — useful to _you now_; the test is the HEAD reader, not you.\n- Keeping \"originally X / changed to Y\" — the change is already visible in the diff; the narration is redundant.\n- Leaving a task-plan reference the reader can't resolve — that is the exact leakage to remove.\n" },
|
|
31
|
-
{ type: 'standard', raw: "---\nname: web-access\ndescription: '联网访问:CDP 驱动用户已登录 Chrome(登录后操作、动态页面、反爬站点、社交媒体、本地书签/历史检索)'\nlicense: MIT\ngithub: https://github.com/eze-is/web-access\nversion: 2.5.0\nuser-invocable: true\nallowed-tools:\n - Bash\n - WebFetch\n - WebSearch\n - Read\n---\n\n# Web Access — CDP 驱动已登录 Chrome\n\n> 来源:eze-is/web-access (MIT),Mipham Code 合并升级。核心能力 = CDP Proxy 直连用户日常 Chrome,天然携带登录态。\n\n## 前置检查\n\n先确保 CDP 就绪:\n\n```bash\nnode ~/.mipham/skills/web-access/scripts/check-deps.mjs\n```\n\n> Mipham Code 环境:`node` 不可用时可用 `bun` 替代(Bun 原生支持 WebSocket 与 node: 内建)。未通过时引导用户:Chrome 地址栏打开 `chrome://inspect/#remote-debugging`,勾选 \"Allow remote debugging for this browser instance\"。\n\n**必须向用户展示**:部分站点对浏览器自动化检测严格,存在账号封禁风险。已内置防护但无法完全避免,Agent 继续操作即视为接受。\n\n## 工具选择\n\n| 场景 | 工具 |\n| --------------------------------------------- | ----------- |\n| 搜索摘要 / 发现来源 | WebSearch |\n| URL 已知,定向提取 | WebFetch |\n| URL 已知,要原始 HTML(meta/JSON-LD) | Bash + curl |\n| 非公开内容 / 反爬站点(小红书、微信公众号等) | 浏览器 CDP |\n| 需要登录态、交互、自由导航 | 浏览器 CDP |\n\n浏览器 CDP 不要求 URL 已知;WebSearch/WebFetch/curl 均不处理登录态。\n\n## 浏览器 CDP 模式\n\n通过 CDP Proxy 直连用户日常 Chrome,天然携带登录态。**不主动操作用户已有 tab**,所有操作在自己创建的后台 tab 中进行,任务结束关闭自建 tab(保留用户原 tab)。\n\nProxy(`scripts/cdp-proxy.mjs`)由 `check-deps.mjs` 自动拉起并常驻。Proxy 首次启动生成共享密钥 `~/.mipham/skills/web-access/.cdp-token`(0600),除 `/health` 外所有端点都要求请求头 `X-CDP-Token`。先取 token 再调 API:\n\n```bash\nTOKEN=$(cat ~/.mipham/skills/web-access/.cdp-token)\ncurl -H \"X-CDP-Token: $TOKEN\" http://localhost:3456/targets\n```\n\n端点列表:\n\n| 端点 | 用途 |\n| ------------------------------------------ | ------------------------------------------------------------------------ |\n| `GET /targets` | 列出已开 tab |\n| `GET /new?url=` | 新建后台 tab(自动等加载) |\n| `GET /navigate?target=&url=` | 导航(自动等加载) |\n| `GET /back?target=` | 后退 |\n| `GET /info?target=` | 页面标题/URL/状态 |\n| `POST /eval?target=`(body=JS) | 执行任意 JS(读写 DOM、提取、提交) |\n| `POST /click?target=`(body=CSS 选择器) | JS 点击(`el.click()`,覆盖大多数场景) |\n| `POST /clickAt?target=`(body=CSS 选择器) | 真实鼠标点击(`Input.dispatchMouseEvent`,算用户手势,能触发文件对话框) |\n| `POST /setFiles?target=`(body JSON) | 设置 file input 本地文件路径(`DOM.setFileInputFiles`,绕过文件对话框) |\n| `GET /scroll?target=&y=&direction=` | 滚动(`direction=down/up/top/bottom`,触发懒加载) |\n| `GET /screenshot?target=&file=` | 截图 |\n| `GET /close?target=` | 关闭 tab |\n\n进入浏览器层后,`/eval` 是眼睛、`/click` 是手:先看 DOM 结构再决定下一步,不预先规划所有步骤。\n\n### 登录判断\n\n核心问题只有一个:**目标内容拿到了吗?** 打开页面先尝试获取目标内容;确认「目标内容无法获取」且判断登录能解决时,告知用户在其 Chrome 登录后继续(无需重启任何东西,刷新页面即可)。\n\n### 媒体资源提取\n\n判断内容在图片里时,用 `/eval` 从 DOM 直接拿图片 URL 定向读取,比全页截图精准。`/scroll` 到底部触发懒加载后再提取图片 URL。\n\n### 视频内容获取\n\n用户 Chrome 真实渲染,截图可捕获当前视频帧。用 `/eval` 操控 `<video>`(时长、seek、播放/暂停),配合 `/screenshot` 采帧,做离散采样分析。\n\n## 本地 Chrome 资源\n\n用户指向「本人访问过的页面」或「组织内部系统」时,检索本地书签/历史:\n\n```bash\nnode ~/.mipham/skills/web-access/scripts/find-url.mjs [关键词...] [--only bookmarks|history] [--limit N] [--since 1d|7h|YYYY-MM-DD] [--sort recent|visits]\n```\n\n## 并行调研:子 Agent 分治\n\n多个独立调研目标时,分治给子 Agent 并行执行(共享一个 Chrome、一个 Proxy,各自建 tab、各自 `/close`,无竞态)。子 Agent prompt 写**目标**(「获取/调研/了解」),不写**手段**(避免「搜索xx」锚定到 WebSearch 而错过需 CDP 的反爬站点)。\n\n## 信息核实\n\n核实目标是一手来源,非二手报道。搜索引擎是**定位**工具,不可直接**证明**真伪;找到来源后直接访问读原文。\n\n| 信息类型 | 一手来源 |\n| ------------- | -------------- |\n| 政策/法规 | 发布机构官网 |\n| 企业公告 | 公司官方新闻页 |\n| 工具能力/用法 | 官方文档、源码 |\n\n### 交叉验证\n\n- 关键声明须 2+ 独立来源交叉印证。\n- 优先采纳当年/近期资料。\n- 权威层级:官方文档 > 知名博客 > 技术社区 > 随机论坛。\n\n### 来源归因\n\n回答结尾附来源列表:\n\n```markdown\nSources:\n\n- [标题](URL) — 一句话说明\n```\n\n## 站点经验\n\n特定网站经验按域名存 `~/.mipham/skills/web-access/references/site-patterns/<domain>.md`(frontmatter: domain/aliases/updated + 平台特征/有效模式/已知陷阱)。操作前若有匹配经验先读;操作成功后把验证过的新模式写回。\n\n## Security Rules\n\n- 不主动操作用户已有 tab;任务结束关闭自建 tab。\n- 不提交凭据(除非用户显式批准)。\n- 尊重 robots.txt 与速率限制;不抓 PII。\n- proxy 仅绑 127.0.0.1,不暴露外网;除 `/health` 外所有端点要求 `X-CDP-Token` 共享密钥(`~/.mipham/skills/web-access/.cdp-token`,0600),防浏览器 CSRF 到 localhost。勿在共享/多用户主机运行。\n- URL 过窄 SSRF 校验:拒绝非 http(s)/about 协议与云元数据端点(`169.254.169.254` / `metadata.google.internal`)。⚠️ 私有网段(10.x / 172.16 / 192.168 / localhost)**有意放行**——本工具用途即访问组织内网(SSO 后台/内部系统),与 web-fetch 的完整 SSRF 屏蔽不同。\n\n## 何时不用本 skill\n\n- 纯逻辑/算法题(推理非研究)。\n- 代码已在上下文里的问题。\n- 大文件下载 → Bash + curl。\n" },
|
|
32
|
-
{ type: 'standard', raw: "---\nname: web-search\ndescription: Search the web for current information — documentation, news, technical references, troubleshooting, and research. Routes queries through Brave Search API with domain filtering and source verification.\nversion: 3.0.0\nuser-invocable: true\nallowed-tools:\n - WebSearch\n - WebFetch\n---\n\n# Web Search — Executable Workflow\n\n**Type**: Flexible — follow the query construction rules strictly, then adapt verification depth to the task.\n\n**Purpose**: Find accurate, current information from the web. This skill covers query formulation, domain filtering, result verification, and when to follow up with WebFetch for deep reading.\n\n**Triggers**: \"search for\", \"look up\", \"find\", \"what is\", \"how to\", \"latest\", \"current\", \"news about\", \"documentation for\", \"research\"\n\n---\n\n## Phase 0: Decide Whether to Search (ALWAYS RUN FIRST)\n\n```\nQuestion involves...\n├── Current events, news, recent releases?\n│ └── YES → Search (model training cutoff limitation)\n│\n├── Library/framework documentation?\n│ └── YES → Search (version-specific, up-to-date)\n│\n├── Error messages, stack traces?\n│ └── YES → Search (known issues, fixes)\n│\n├── Technology comparisons, benchmarks?\n│ └── YES → Search (current data)\n│\n├── Pure logic, algorithms, math?\n│ └── NO → Reason directly (no external data needed)\n│\n├── Question answerable from code in context?\n│ └── NO → Use existing context (faster, no network)\n│\n└── Opinion / subjective?\n └── MAYBE → Search for data points, not consensus\n```\n\n---\n\n## Phase 1: Construct the Query\n\n### Rules (apply in order)\n\n1. **Be specific**: include version numbers, dates, proper nouns\n2. **Use technical terms**: framework/language jargon over natural language\n3. **Include context**: OS, environment, constraints if relevant\n4. **English preferred**: technical content is richer in English\n\n### Examples\n\n```\n❌ \"React\" → too broad\n❌ \"React problems\" → ambiguous\n❌ \"how to make website fast\" → natural language\n✅ \"React 19 useEffect double mount fix\" → specific + versioned\n✅ \"Core Web Vitals LCP optimization Next.js 14\"\n✅ \"Prisma 5 findMany nested include filter TypeScript\"\n✅ \"playwright click button not working 2026\"\n```\n\n### For Chinese-Language Queries\n\nChinese queries work but yield fewer technical results:\n\n```\n✅ \"React 19 useEffect 执行两次 修复\" → mixed language for best results\n✅ \"Vue 3 Composition API 最佳实践 2026\"\n```\n\n---\n\n## Phase 2: Filter & Verify Results\n\n### Domain Authority Tiers\n\n| Tier | Domains | Weight |\n| ----------------- | --------------------------------------------------------------------- | ------- |\n| **Official** | docs.github.com, nextjs.org, nodejs.org, python.org, rust-lang.org | Highest |\n| **Authoritative** | developer.mozilla.org, web.dev, kubernetes.io | High |\n| **Trusted** | stackoverflow.com (high-score), dev.to, medium.com (verified authors) | Medium |\n| **Low** | personal blogs, random forums, w3schools | Low |\n\n### Use allowed_domains for targeted searches\n\n```json\n{ \"query\": \"Next.js caching\", \"allowed_domains\": [\"nextjs.org\", \"github.com\"] }\n```\n\n### Use blocked_domains to exclude noise\n\n```json\n{ \"query\": \"JavaScript array methods\", \"blocked_domains\": [\"w3schools.com\"] }\n```\n\n### Cross-Reference Rule\n\n- **Critical claims** (API behavior, security): 2+ independent sources\n- **Code examples**: test before recommending\n- **Version info**: check publish date (prefer current year)\n\n---\n\n## Phase 3: Deep Read (When Needed)\n\nAfter search returns results, decide whether to deep-read:\n\n```\nSearch result looks promising?\n├── Snippet answers the question fully?\n│ └── → Use snippet + cite source (done)\n│\n├── Need code examples / detailed API docs?\n│ └── → WebFetch the page URL\n│ Use prompt to focus extraction\n│\n├── Multiple sources needed for verification?\n│ └── → WebFetch top 2-3 results\n│ Cross-reference and flag contradictions\n│\n└── Page is JavaScript SPA / login-walled?\n └── → Delegate to web-access skill (ComputerUse browser)\n```\n\n---\n\n## Phase 4: Report Results\n\n### Format\n\n```markdown\n## [Topic]\n\n[Answer with inline citations]\n\n### Details (if deep-read was done)\n\n[Structured content from fetched pages]\n\nSources:\n\n- [Title](URL) — [1-sentence note on what was found there]\n- [Title](URL) — [1-sentence note]\n```\n\n### Attribution Rules\n\n- Always include source URLs\n- Note if a source is official docs vs community\n- Flag outdated content (e.g., \"article from 2024, may be stale\")\n- Distinguish between facts (need citation) and reasoning (your own)\n\n---\n\n## Search API Configuration\n\nWeb search uses **Brave Search API** (free tier: 2,000 queries/month).\n\nIf search returns \"not configured\":\n\n1. Get a free API key at https://brave.com/search/api/\n2. Set: `export BRAVE_API_KEY=\"BSA...\"`\n3. Restart Mipham Code\n\
|
|
31
|
+
{ type: 'standard', raw: "---\nname: web-access\ndescription: '联网访问:CDP 驱动用户已登录 Chrome(登录后操作、动态页面、反爬站点、社交媒体、本地书签/历史检索)'\nlicense: MIT\ngithub: https://github.com/eze-is/web-access\nversion: 2.5.0\nuser-invocable: true\nallowed-tools:\n - Bash\n - WebFetch\n - WebSearch\n - Read\n---\n\n# Web Access — CDP 驱动已登录 Chrome\n\n> 来源:eze-is/web-access (MIT),Mipham Code 合并升级。核心能力 = CDP Proxy 直连用户日常 Chrome,天然携带登录态。\n\n## 前置检查\n\n先确保 CDP 就绪:\n\n```bash\nnode ~/.mipham/skills/web-access/scripts/check-deps.mjs\n```\n\n> Mipham Code 环境:`node` 不可用时可用 `bun` 替代(Bun 原生支持 WebSocket 与 node: 内建)。未通过时引导用户:Chrome 地址栏打开 `chrome://inspect/#remote-debugging`,勾选 \"Allow remote debugging for this browser instance\"。\n\n> **判读输出**:`chrome: ok` = 调试端点已授权;`chrome: not authorized` = 端口开着但 Chrome 没允许远程调试(去 `chrome://inspect/#remote-debugging` 勾 Allow,或点弹窗「允许」);`proxy: running, but Chrome is not connected` = 代理活着、Chrome 没授权。\n> **不要**把以上任何一种读成「Bash 没有网络」:`curl -s http://127.0.0.1:3456/health` 能回 200 就证明 localhost 是通的,真正原因在 `lastError` 字段里。\n\n**必须向用户展示**:部分站点对浏览器自动化检测严格,存在账号封禁风险。已内置防护但无法完全避免,Agent 继续操作即视为接受。\n\n## 工具选择\n\n| 场景 | 工具 |\n| --------------------------------------------- | ----------- |\n| 搜索摘要 / 发现来源 | WebSearch |\n| URL 已知,定向提取 | WebFetch |\n| URL 已知,要原始 HTML(meta/JSON-LD) | Bash + curl |\n| 非公开内容 / 反爬站点(小红书、微信公众号等) | 浏览器 CDP |\n| 需要登录态、交互、自由导航 | 浏览器 CDP |\n\n浏览器 CDP 不要求 URL 已知;WebSearch/WebFetch/curl 均不处理登录态。\n\n> 搜索引擎结果页(Google / Bing / DuckDuckGo / Brave / Mojeek)对 WebFetch/curl 普遍回 403/429 或验证码。需要搜索时**在 Chrome 里打开引擎页**再用 `/eval` 提取结果,不要用 WebFetch 抓结果页。\n\n## 浏览器 CDP 模式\n\n通过 CDP Proxy 直连用户日常 Chrome,天然携带登录态。**不主动操作用户已有 tab**,所有操作在自己创建的后台 tab 中进行,任务结束关闭自建 tab(保留用户原 tab)。\n\nProxy(`scripts/cdp-proxy.mjs`)由 `check-deps.mjs` 自动拉起并常驻。Proxy 首次启动生成共享密钥 `~/.mipham/skills/web-access/.cdp-token`(0600),除 `/health` 外所有端点都要求请求头 `X-CDP-Token`。先取 token 再调 API:\n\n```bash\nTOKEN=$(cat ~/.mipham/skills/web-access/.cdp-token)\ncurl -H \"X-CDP-Token: $TOKEN\" http://localhost:3456/targets\n```\n\n端点列表:\n\n| 端点 | 用途 |\n| ------------------------------------------ | ------------------------------------------------------------------------ |\n| `GET /targets` | 列出已开 tab |\n| `GET /new?url=` | 新建后台 tab(自动等加载) |\n| `GET /navigate?target=&url=` | 导航(自动等加载) |\n| `GET /back?target=` | 后退 |\n| `GET /info?target=` | 页面标题/URL/状态 |\n| `POST /eval?target=`(body=JS) | 执行任意 JS(读写 DOM、提取、提交) |\n| `POST /click?target=`(body=CSS 选择器) | JS 点击(`el.click()`,覆盖大多数场景) |\n| `POST /clickAt?target=`(body=CSS 选择器) | 真实鼠标点击(`Input.dispatchMouseEvent`,算用户手势,能触发文件对话框) |\n| `POST /setFiles?target=`(body JSON) | 设置 file input 本地文件路径(`DOM.setFileInputFiles`,绕过文件对话框) |\n| `GET /scroll?target=&y=&direction=` | 滚动(`direction=down/up/top/bottom`,触发懒加载) |\n| `GET /screenshot?target=&file=` | 截图 |\n| `GET /close?target=` | 关闭 tab |\n\n进入浏览器层后,`/eval` 是眼睛、`/click` 是手:先看 DOM 结构再决定下一步,不预先规划所有步骤。\n\n### 登录判断\n\n核心问题只有一个:**目标内容拿到了吗?** 打开页面先尝试获取目标内容;确认「目标内容无法获取」且判断登录能解决时,告知用户在其 Chrome 登录后继续(无需重启任何东西,刷新页面即可)。\n\n### 媒体资源提取\n\n判断内容在图片里时,用 `/eval` 从 DOM 直接拿图片 URL 定向读取,比全页截图精准。`/scroll` 到底部触发懒加载后再提取图片 URL。\n\n### 视频内容获取\n\n用户 Chrome 真实渲染,截图可捕获当前视频帧。用 `/eval` 操控 `<video>`(时长、seek、播放/暂停),配合 `/screenshot` 采帧,做离散采样分析。\n\n## 本地 Chrome 资源\n\n用户指向「本人访问过的页面」或「组织内部系统」时,检索本地书签/历史:\n\n```bash\nnode ~/.mipham/skills/web-access/scripts/find-url.mjs [关键词...] [--only bookmarks|history] [--limit N] [--since 1d|7h|YYYY-MM-DD] [--sort recent|visits]\n```\n\n## 并行调研:子 Agent 分治\n\n多个独立调研目标时,分治给子 Agent 并行执行(共享一个 Chrome、一个 Proxy,各自建 tab、各自 `/close`,无竞态)。子 Agent prompt 写**目标**(「获取/调研/了解」),不写**手段**(避免「搜索xx」锚定到 WebSearch 而错过需 CDP 的反爬站点)。\n\n## 信息核实\n\n核实目标是一手来源,非二手报道。搜索引擎是**定位**工具,不可直接**证明**真伪;找到来源后直接访问读原文。\n\n| 信息类型 | 一手来源 |\n| ------------- | -------------- |\n| 政策/法规 | 发布机构官网 |\n| 企业公告 | 公司官方新闻页 |\n| 工具能力/用法 | 官方文档、源码 |\n\n### 交叉验证\n\n- 关键声明须 2+ 独立来源交叉印证。\n- 优先采纳当年/近期资料。\n- 权威层级:官方文档 > 知名博客 > 技术社区 > 随机论坛。\n\n### 来源归因\n\n回答结尾附来源列表:\n\n```markdown\nSources:\n\n- [标题](URL) — 一句话说明\n```\n\n## 站点经验\n\n特定网站经验按域名存 `~/.mipham/skills/web-access/references/site-patterns/<domain>.md`(frontmatter: domain/aliases/updated + 平台特征/有效模式/已知陷阱)。操作前若有匹配经验先读;操作成功后把验证过的新模式写回。\n\n## Security Rules\n\n- 不主动操作用户已有 tab;任务结束关闭自建 tab。\n- 不提交凭据(除非用户显式批准)。\n- 尊重 robots.txt 与速率限制;不抓 PII。\n- proxy 仅绑 127.0.0.1,不暴露外网;除 `/health` 外所有端点要求 `X-CDP-Token` 共享密钥(`~/.mipham/skills/web-access/.cdp-token`,0600),防浏览器 CSRF 到 localhost。勿在共享/多用户主机运行。\n- URL 过窄 SSRF 校验:拒绝非 http(s)/about 协议与云元数据端点(`169.254.169.254` / `metadata.google.internal`)。⚠️ 私有网段(10.x / 172.16 / 192.168 / localhost)**有意放行**——本工具用途即访问组织内网(SSO 后台/内部系统),与 web-fetch 的完整 SSRF 屏蔽不同。\n\n## 何时不用本 skill\n\n- 纯逻辑/算法题(推理非研究)。\n- 代码已在上下文里的问题。\n- 大文件下载 → Bash + curl。\n" },
|
|
32
|
+
{ type: 'standard', raw: "---\nname: web-search\ndescription: Search the web for current information — documentation, news, technical references, troubleshooting, and research. Routes queries through Brave Search API with domain filtering and source verification.\nversion: 3.0.0\nuser-invocable: true\nallowed-tools:\n - WebSearch\n - WebFetch\n---\n\n# Web Search — Executable Workflow\n\n**Type**: Flexible — follow the query construction rules strictly, then adapt verification depth to the task.\n\n**Purpose**: Find accurate, current information from the web. This skill covers query formulation, domain filtering, result verification, and when to follow up with WebFetch for deep reading.\n\n**Triggers**: \"search for\", \"look up\", \"find\", \"what is\", \"how to\", \"latest\", \"current\", \"news about\", \"documentation for\", \"research\"\n\n---\n\n## Phase 0: Decide Whether to Search (ALWAYS RUN FIRST)\n\n```\nQuestion involves...\n├── Current events, news, recent releases?\n│ └── YES → Search (model training cutoff limitation)\n│\n├── Library/framework documentation?\n│ └── YES → Search (version-specific, up-to-date)\n│\n├── Error messages, stack traces?\n│ └── YES → Search (known issues, fixes)\n│\n├── Technology comparisons, benchmarks?\n│ └── YES → Search (current data)\n│\n├── Pure logic, algorithms, math?\n│ └── NO → Reason directly (no external data needed)\n│\n├── Question answerable from code in context?\n│ └── NO → Use existing context (faster, no network)\n│\n└── Opinion / subjective?\n └── MAYBE → Search for data points, not consensus\n```\n\n---\n\n### No API key? Do not scrape search engines\n\nIf `WebSearch` answers \"not configured\", **do not** fetch search-engine result pages with\n`WebFetch` or `curl`. Google / Bing / DuckDuckGo / Brave / Mojeek all answer automated\nrequests with 403, 429 or a captcha — five calls later you have nothing.\n\nGo straight to the `web-access` skill: open the search engine **in Chrome** (logged-in\nprofile, real fingerprint), then read the result list with `/eval`.\n\n---\n\n## Phase 1: Construct the Query\n\n### Rules (apply in order)\n\n1. **Be specific**: include version numbers, dates, proper nouns\n2. **Use technical terms**: framework/language jargon over natural language\n3. **Include context**: OS, environment, constraints if relevant\n4. **English preferred**: technical content is richer in English\n\n### Examples\n\n```\n❌ \"React\" → too broad\n❌ \"React problems\" → ambiguous\n❌ \"how to make website fast\" → natural language\n✅ \"React 19 useEffect double mount fix\" → specific + versioned\n✅ \"Core Web Vitals LCP optimization Next.js 14\"\n✅ \"Prisma 5 findMany nested include filter TypeScript\"\n✅ \"playwright click button not working 2026\"\n```\n\n### For Chinese-Language Queries\n\nChinese queries work but yield fewer technical results:\n\n```\n✅ \"React 19 useEffect 执行两次 修复\" → mixed language for best results\n✅ \"Vue 3 Composition API 最佳实践 2026\"\n```\n\n---\n\n## Phase 2: Filter & Verify Results\n\n### Domain Authority Tiers\n\n| Tier | Domains | Weight |\n| ----------------- | --------------------------------------------------------------------- | ------- |\n| **Official** | docs.github.com, nextjs.org, nodejs.org, python.org, rust-lang.org | Highest |\n| **Authoritative** | developer.mozilla.org, web.dev, kubernetes.io | High |\n| **Trusted** | stackoverflow.com (high-score), dev.to, medium.com (verified authors) | Medium |\n| **Low** | personal blogs, random forums, w3schools | Low |\n\n### Use allowed_domains for targeted searches\n\n```json\n{ \"query\": \"Next.js caching\", \"allowed_domains\": [\"nextjs.org\", \"github.com\"] }\n```\n\n### Use blocked_domains to exclude noise\n\n```json\n{ \"query\": \"JavaScript array methods\", \"blocked_domains\": [\"w3schools.com\"] }\n```\n\n### Cross-Reference Rule\n\n- **Critical claims** (API behavior, security): 2+ independent sources\n- **Code examples**: test before recommending\n- **Version info**: check publish date (prefer current year)\n\n---\n\n## Phase 3: Deep Read (When Needed)\n\nAfter search returns results, decide whether to deep-read:\n\n```\nSearch result looks promising?\n├── Snippet answers the question fully?\n│ └── → Use snippet + cite source (done)\n│\n├── Need code examples / detailed API docs?\n│ └── → WebFetch the page URL\n│ Use prompt to focus extraction\n│\n├── Multiple sources needed for verification?\n│ └── → WebFetch top 2-3 results\n│ Cross-reference and flag contradictions\n│\n└── Page is JavaScript SPA / login-walled?\n └── → Delegate to web-access skill (ComputerUse browser)\n```\n\n---\n\n## Phase 4: Report Results\n\n### Format\n\n```markdown\n## [Topic]\n\n[Answer with inline citations]\n\n### Details (if deep-read was done)\n\n[Structured content from fetched pages]\n\nSources:\n\n- [Title](URL) — [1-sentence note on what was found there]\n- [Title](URL) — [1-sentence note]\n```\n\n### Attribution Rules\n\n- Always include source URLs\n- Note if a source is official docs vs community\n- Flag outdated content (e.g., \"article from 2024, may be stale\")\n- Distinguish between facts (need citation) and reasoning (your own)\n\n---\n\n## Search API Configuration\n\nWeb search uses **Brave Search API** (free tier: 2,000 queries/month).\n\nIf search returns \"not configured\":\n\n1. Get a free API key at https://brave.com/search/api/\n2. Set: `export BRAVE_API_KEY=\"BSA...\"`\n3. Restart Mipham Code\n\nOnly `BRAVE_API_KEY` is read. There is no Tavily / SerpAPI path in this build — setting\nthose variables has no effect.\n" },
|
|
33
33
|
{ type: 'mipham', raw: "---\nname: doc-sync\ndescription: Keep engineering truth docs aligned with code — map changed code to docs, update stale docs after functional changes, keep git-reviewable\nversion: 1.0.0\n---\n\n# Doc Sync\n\nKeep engineering \"truth docs\" aligned with code. After a functional code change, run this skill to find the docs that map to the changed code, check them against the code + tests, and update anything that drifted. Docs travel with the branch in git and are reviewed alongside the code diff.\n\n## Where truth docs live\n\nEngineering truth docs live under `docs/truth/engineering/`. Routing from code → docs lives in `docs/truth/ROUTES.md`.\n\n```\ndocs/truth/\n├── ROUTES.md # code area → canonical doc mapping\n└── engineering/\n ├── behaviors/ # implementation behavior\n ├── contracts/ # API / interface contracts\n ├── architecture/ # component structure and boundaries\n ├── workflows/ # multi-step flows and orchestration\n └── operations/ # runbooks, config, deployment\n```\n\n## Invariants (never break)\n\n- **Doc-only**: touch `docs/truth/**` and `ROUTES.md` only. Never modify functional code, tests, or config outside `docs/truth/`.\n- **Evidence-backed**: every claim cites `file:line` (or `file` for a whole file). No invented behavior.\n- **Branch-scoped**: docs change in the same branch as the code, so they review together.\n\n## Workflow\n\n### 1. Map — find the docs that cover the change\n\nDetermine the changed code. Prefer an explicit path argument; otherwise use the working-tree or branch diff:\n\n```bash\ngit diff --name-only # uncommitted working-tree changes\ngit diff --name-only HEAD~1 # last commit\n```\n\nRead `docs/truth/ROUTES.md` and match the changed paths to their canonical doc. A route is a glob → doc path pair. A changed path with no route is a signal to create one (Step 3).\n\n### 2. Check — is the doc now stale?\n\nFor each mapped doc, read the doc, the changed code, and the relevant tests. Compare:\n\n- Does the doc describe behavior the code no longer has?\n- Does the code add or remove behavior the doc doesn't mention?\n- Do contract shapes (signatures, types, errors) still match?\n- Are the `file:line` evidence pointers still valid?\n\nA doc is stale when any claim no longer matches the code + tests.\n\n### 3. Update — fix the drift\n\n- **Existing doc, stale**: edit the doc in place. Update claims, refresh `file:line` pointers, remove dead behavior, add new behavior. Keep the section structure unless the change demands otherwise.\n- **Existing doc, orphaned**: if the mapped code is gone, remove the doc and its route entry.\n- **Changed path has no route**: create one bounded doc under the right `docs/truth/engineering/<type>/` folder and add a route entry to `ROUTES.md`. Scope the doc to the changed area — do not document the whole codebase.\n\nKeep the diff minimal and reviewable: one doc per functional change, no unrelated rewrites.\n\n### 4. Verify — reviewable and true\n\nConfirm before reporting done:\n\n- `git diff --stat` shows only `docs/truth/**` and `ROUTES.md`.\n- Every claim in the updated doc has a `file:line` pointer that exists in the working tree.\n- The doc matches the code + tests, not the other way around.\n\nReport: \"Updated <doc> for <change>. Review the truth diff alongside the code diff.\"\n\n## Document templates\n\n### Behavior (`behaviors/`)\n\n```markdown\n# <Behavior Name>\n\n**Area**: <route / component>\n**Evidence**: `src/<file>:<line>`\n\n## What it does\n\n<one-paragraph summary, from code + tests>\n\n## Behavior\n\n- <observable behavior> — `src/<file>:<line>`\n\n## Edge cases\n\n- <case> — `src/<file>:<line>`\n\n## Tests\n\n- `tests/<file>.test.ts` — covers <behavior>\n```\n\n### Contract (`contracts/`)\n\n```markdown\n# <API / Interface>\n\n**Evidence**: `src/<file>:<line>`\n\n## Signature\n\n\\`\\`\\`ts\n// the actual exported signature\n\\`\\`\\`\n\n## Parameters\n\n| Param | Type | Description |\n| ----- | ---- | ----------- |\n\n## Returns / Errors\n\n- ...\n\n## Consumers\n\n- <caller> — `src/<file>:<line>`\n```\n\n### Architecture (`architecture/`)\n\n```markdown\n# <Component / Module>\n\n**Evidence**: `src/<file>`\n\n## Responsibility\n\n<one paragraph — what it owns, what it doesn't>\n\n## Dependencies\n\n- depends on: <...>\n- depended on by: <...>\n\n## Boundaries\n\n- <seam / interface> — `src/<file>:<line>`\n```\n\n### Workflow (`workflows/`)\n\n```markdown\n# <Workflow Name>\n\n**Evidence**: `src/<file>:<line>`\n\n## Steps\n\n1. <step> — `src/<file>:<line>`\n\n## Trigger / Exit\n\n- trigger: <...>\n- success: <...> / failure: <...>\n```\n\n### Operations (`operations/`)\n\n```markdown\n# <Runbook / Config>\n\n**Evidence**: `src/<file>`\n\n## Config / Env\n\n| Key | Default | Meaning |\n| --- | ------- | ------- |\n\n## Runbook\n\n- <action> — <command or step>\n\n## Failure modes\n\n- <symptom> → <cause> → <fix>\n```\n\n## Routing file (`ROUTES.md`)\n\n```markdown\n# Truth Routes\n\n| Code pattern | Doc |\n| ----------------- | ---------------------------------------- |\n| src/auth/session* | engineering/behaviors/session-timeout.md |\n| src/api/* | engineering/contracts/api.md |\n```\n\nPatterns are globs relative to the repo root. One doc may be routed by several patterns; one pattern maps to one doc. Keep patterns as specific as needed to avoid one giant doc.\n" },
|
|
34
34
|
{ type: 'mipham', raw: "---\nname: om-artifact\ndescription: Mipham Artifacts — create interactive HTML/SVG dashboards, reports, and visualizations the user can view in their browser\nversion: 1.0.0\n---\n\n# Mipham Artifacts Skill\n\nCreate interactive browser-viewable artifacts from conversation output. Use the `Artifact` tool to save standalone HTML or SVG files that the user opens with `/artifact open <name>`.\n\n## When to Use Artifact vs Write\n\n| Artifact | Write |\n| -------------------------------------------- | ------------------------------------------------ |\n| Visual output (charts, dashboards, diagrams) | Source code files |\n| Interactive HTML demos | Configuration files |\n| Styled reports with CSS | Documentation (.md) |\n| SVG graphics and visualizations | Data files (.json, .csv) |\n| Anything the user wants to SEE in a browser | Anything the user wants to EDIT in a text editor |\n\n**Ask yourself**: \"Would this be better viewed in a browser than in a terminal or text editor?\" If yes, use Artifact.\n\n## Artifact Guidelines\n\n### Content Requirements\n\n- **Self-contained only**: All CSS and JS must be inline. No CDN links, no external fonts, no network requests. The CSP policy blocks all external resources.\n- **Size limit**: 5MB maximum. Aim for under 500KB for good performance.\n- **Artifact types**: `html` (full HTML pages) or `svg` (standalone SVG graphics)\n\n### Naming\n\n- Use short kebab-case names: `user-dashboard`, `pipeline-diagram`, `pr-diff-review`\n- The name becomes the filename: `user-dashboard.html`\n\n### Styling\n\n- Use inline `<style>` blocks in the HTML head\n- Dark theme recommended (matches Mipham Code aesthetic)\n- Responsive design where practical\n- Clean, professional look — this is user-facing output\n\n## Good Artifact Examples\n\n1. **Data dashboard**: Query results rendered as tables, charts (inline Chart.js data via canvas), metrics cards\n2. **Diff viewer**: Side-by-side code comparison with syntax highlighting\n3. **Report**: Structured markdown rendered as styled HTML with TOC\n4. **Timeline**: Event sequence visualization with expandable sections\n5. **Network graph**: Interactive node-edge visualization (D3 or vis.js inline)\n6. **Architecture diagram**: Components and connections with color coding\n7. **Test results**: Pass/fail grid with expandable failure details\n\n## Artifact Lifecycle\n\n1. AI creates artifact via `Artifact` tool → saved to `.mipham/artifacts/<session>/<name>.html`\n2. Tool returns the localhost URL\n3. User opens with `/artifact open <name>` → browser displays it\n4. User lists all artifacts with `/artifact list`\n5. Server runs on `http://localhost:9876` by default\n\n## Prompting the User\n\nAfter creating an artifact, always tell the user:\n\n- The artifact name\n- The URL\n- That they can open it with `/artifact open <name>`\n\nExample: \"I've created a dashboard artifact. Open it with `/artifact open dashboard`\"\n" },
|
|
35
35
|
{ type: 'mipham', raw: "---\nname: om-model-optimize\ndescription: Mipham-exclusive model optimization — context window management, prompt caching, token budgeting, and model selection\nversion: 2.0.0\n---\n\n# OM Model Optimize\n\nMipham-exclusive skill for intelligent model usage optimization.\n\n## Context Window Management\n\n### Compaction Strategy\n\nWhen context approaches the model's window limit:\n\n1. **Auto-trigger**: System detects token usage >80% of context window\n2. **Summarize**: Generate a concise conversation summary via the current model\n3. **Preserve**: Keep the last 20 messages intact for continuity\n4. **Inject**: Prepend the summary as a system-level context message\n\n### Token Budgeting\n\nTrack token usage per session:\n\n- Input tokens consumed per request\n- Output tokens generated per response\n- Cumulative session total\n- Estimated cost based on provider pricing\n\n## Prompt Caching\n\n### Anthropic Prompt Caching\n\nMark reusable content blocks (system prompts, long tool results) with `cache_control`:\n\n- Minimum cacheable tokens: 1024 (Claude Sonnet), 2048 (Claude Haiku)\n- Cache TTL: ~5 minutes; refresh on each use\n- Priority targets: system prompt, large file contents, tool definitions\n\n### OpenAI Prompt Caching\n\nOpenAI automatically caches the longest prefix match; ensure consistent message ordering to maximize cache hits.\n\n## Model Selection Optimization\n\nRoute tasks to the appropriate model tier:\n\n| Task Complexity | Recommended Tier | Example Models |\n| --------------------- | ---------------- | --------------------------------------- |\n| Simple (1-2 steps) | Flash / Lite | Claude Haiku, GPT Flash, Qwen Flash |\n| Moderate (multi-step) | Plus / Pro | Claude Sonnet, GPT-4o, DeepSeek V3 |\n| Complex (reasoning) | Ultra / Max | Claude Opus, GPT-5, DeepSeek-R1 |\n| Vision tasks | Visual tier | Claude Sonnet (vision), GPT-4o (vision) |\n\n### Decision Factors\n\n- **Latency requirements**: Flash models respond in <1s; Ultra models may take 10-30s\n- **Cost sensitivity**: Premium models can be 10-50x more expensive per token\n- **Accuracy needs**: Reasoning models (DeepSeek-R1) for math, logic, and complex analysis\n- **Context size**: Large contexts (>100K tokens) only supported by select models\n\n## Usage\n\nAutomatically invoked when:\n\n- Token usage exceeds 80% of context window\n- User explicitly requests optimization (`/optimize` or \"optimize model usage\")\n- Switching between models of different capability tiers\n" },
|
|
@@ -123,11 +123,8 @@ export const webSearchTool: ToolDefinition = {
|
|
|
123
123
|
'',
|
|
124
124
|
'3. Restart Mipham Code and try again.',
|
|
125
125
|
'',
|
|
126
|
-
'Alternatives (add API key for any):',
|
|
127
|
-
' TAVILY_API_KEY — https://tavily.com',
|
|
128
|
-
' SERPAPI_API_KEY — https://serpapi.com',
|
|
129
|
-
'',
|
|
130
126
|
'No API key? Use the web-access skill (CDP through your logged-in Chrome) for live web search.',
|
|
127
|
+
'Do not scrape search-engine result pages with WebFetch/curl — they answer 403/429 or a captcha.',
|
|
131
128
|
].join('\n'),
|
|
132
129
|
}
|
|
133
130
|
}
|
package/src/ui/app.tsx
CHANGED
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
} from '../agent/cross-session/discovery'
|
|
30
30
|
import { ChatPanel } from './chat'
|
|
31
31
|
import { InputBar } from './input'
|
|
32
|
+
import { recordKeyEvent, recordRenderCommit } from './input-debug'
|
|
32
33
|
import { ModelPicker } from './picker'
|
|
33
34
|
import { CopyPicker, type CopyPickerItem } from './copy-picker'
|
|
34
35
|
import { AgentFooter, type AgentEntry } from './agent-footer'
|
|
@@ -1388,7 +1389,14 @@ export function App({
|
|
|
1388
1389
|
// Ctrl+C 的「再按一次才退」,语义与计时器见 ui/ctrl-c-confirm.ts
|
|
1389
1390
|
const ctrlC = useCtrlCConfirm()
|
|
1390
1391
|
|
|
1392
|
+
// 诊断(`MIPHAM_DEBUG_INPUT=1`):冻结时区分「输入没送达」与「送达但没渲染」。
|
|
1393
|
+
// 默认关闭时只是一次缓存布尔判断,见 ui/input-debug.ts。
|
|
1394
|
+
useEffect(() => {
|
|
1395
|
+
recordRenderCommit()
|
|
1396
|
+
})
|
|
1397
|
+
|
|
1391
1398
|
useInput((input, key) => {
|
|
1399
|
+
recordKeyEvent(input, key)
|
|
1392
1400
|
// Ctrl+C:先关最上面那一层;没得关时**不退出**,只提示「再按一次」。
|
|
1393
1401
|
//
|
|
1394
1402
|
// 从前这里没有这个分支,而 Ink 自己的 Ctrl+C 处理(`exitOnCtrlC`,默认
|
package/src/ui/commands.ts
CHANGED
|
@@ -47,10 +47,12 @@ import {
|
|
|
47
47
|
MANAGED_RULES_FILE,
|
|
48
48
|
} from '../core/crsi-producer'
|
|
49
49
|
import { prefilterProposal } from '../core/proposal-guard'
|
|
50
|
+
import { integrateProposals, formatIntegrationSummary } from '../core/proposal-integration'
|
|
50
51
|
import {
|
|
51
52
|
runEval,
|
|
52
53
|
appendEvalScore,
|
|
53
54
|
getContractHistory,
|
|
55
|
+
getLastEvalScore,
|
|
54
56
|
diffContractHistory,
|
|
55
57
|
renderContractDiff,
|
|
56
58
|
} from '../core/eval-harness'
|
|
@@ -65,6 +67,10 @@ import {
|
|
|
65
67
|
buildImprovementReport,
|
|
66
68
|
formatCostLine,
|
|
67
69
|
formatNullModelLine,
|
|
70
|
+
formatRsiTaxLine,
|
|
71
|
+
normalizeProblemKey,
|
|
72
|
+
groupImprovementsByProblem,
|
|
73
|
+
measurementTaxSummary,
|
|
68
74
|
appendImprovement,
|
|
69
75
|
readImprovements,
|
|
70
76
|
improvementRate,
|
|
@@ -1033,6 +1039,42 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
|
|
|
1033
1039
|
)
|
|
1034
1040
|
}
|
|
1035
1041
|
|
|
1042
|
+
// ── SIM:按问题分组(只读视图;分组不是过滤器,无键的旧记录仍在总台账里) ──
|
|
1043
|
+
const groups = groupImprovementsByProblem(records)
|
|
1044
|
+
lines.push('')
|
|
1045
|
+
lines.push('### 改进台账按问题分组(SIM)')
|
|
1046
|
+
if (groups.length === 0) {
|
|
1047
|
+
lines.push('暂无带问题键的记录(旧记录没有 problemKey —— 读作「未分组」,不是「没有问题」)。')
|
|
1048
|
+
} else {
|
|
1049
|
+
for (const g of groups.slice(0, 10)) {
|
|
1050
|
+
const sign = g.meanDelta >= 0 ? '+' : ''
|
|
1051
|
+
lines.push(
|
|
1052
|
+
`- ${g.key}: ${g.improved}/${g.total} improved(均值 delta ${sign}${g.meanDelta.toFixed(1)})`,
|
|
1053
|
+
)
|
|
1054
|
+
}
|
|
1055
|
+
if (groups.length > 10) lines.push(`… 另有 ${groups.length - 10} 组未列出`)
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// ── RSI Tax:验证成本(只记录、只展示,不进任何判定) ──
|
|
1059
|
+
const tax = measurementTaxSummary(records)
|
|
1060
|
+
lines.push('')
|
|
1061
|
+
lines.push('### 验证成本(RSI Tax)')
|
|
1062
|
+
if (tax.records === 0) {
|
|
1063
|
+
lines.push('暂无带 token 量的记录(provider 未报 usage,或旧记录早于本维)。')
|
|
1064
|
+
} else {
|
|
1065
|
+
lines.push(
|
|
1066
|
+
`${tax.records} 条记录 · 合计 ${tax.totalTokens.toLocaleString()} tokens · 均值 ${tax.meanTokens.toLocaleString()}/条`,
|
|
1067
|
+
)
|
|
1068
|
+
// 0-token 基线:确定性 eval 不调 LLM,是同一批机制契约的免费读数。
|
|
1069
|
+
// 两个数回答的不是同一问题,故只做成本对照,不合并成一个「值不值」。
|
|
1070
|
+
const evalScore = getLastEvalScore('mechanism-sentinel')
|
|
1071
|
+
if (evalScore !== null) {
|
|
1072
|
+
lines.push(
|
|
1073
|
+
`0-token 基线: 确定性 eval 最近一次 ${evalScore}/100(不消耗 token;与上面的测量不是同一问题,仅作成本对照)`,
|
|
1074
|
+
)
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1036
1078
|
return { content: lines.join('\n') }
|
|
1037
1079
|
}
|
|
1038
1080
|
|
|
@@ -1049,8 +1091,62 @@ const crsiInventoryCmd: CommandHandler = async (ctx) => {
|
|
|
1049
1091
|
*
|
|
1050
1092
|
* 无附注时返回空串,且**调用点保持逐字不变**(附注前不补空行,附注后自带一个)。
|
|
1051
1093
|
*/
|
|
1052
|
-
function renderGateNote(result: { rewardNote?: string }): string {
|
|
1053
|
-
|
|
1094
|
+
function renderGateNote(result: { rewardNote?: string; regretNote?: string }): string {
|
|
1095
|
+
const lines: string[] = []
|
|
1096
|
+
if (result.rewardNote) lines.push(`⚠️ 奖励闸附注:${result.rewardNote}`)
|
|
1097
|
+
if (result.regretNote) lines.push(`🪞 方向性 regret:${result.regretNote}`)
|
|
1098
|
+
return lines.length > 0 ? lines.join('\n') + '\n' : ''
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* 单提案与整合提案共用的「过闸后测量」段。
|
|
1103
|
+
*
|
|
1104
|
+
* 抽出来**只**为了不复制这段(它与闸本身无关):手工路径与 ELITE 整合路径
|
|
1105
|
+
* 对同一个 `filePath/newContent` 做完全相同的测量与渲染。prose 路径**不**并进来 ——
|
|
1106
|
+
* 它有 ε 预测与自己的渲染形状,合并只会让两条语义不同的路互相污染。
|
|
1107
|
+
*/
|
|
1108
|
+
async function measureModification(
|
|
1109
|
+
ctx: Parameters<CommandHandler>[0],
|
|
1110
|
+
params: { description: string; filePath: string; originalContent: string; newContent: string },
|
|
1111
|
+
): Promise<string> {
|
|
1112
|
+
const llm = ctx.engine.getLlm() ?? ctx.engine.getRegistry()
|
|
1113
|
+
let improvementLine = ''
|
|
1114
|
+
try {
|
|
1115
|
+
const sample = await measureSkillDeltaRepeated(llm, params)
|
|
1116
|
+
if (sample) {
|
|
1117
|
+
const report = buildImprovementReport(sample, [params.filePath], undefined, {
|
|
1118
|
+
// 手工路径没有失败信号,问题键就取「这次想修什么」的规范化描述:
|
|
1119
|
+
// 同一句话被反复修时,它们才聚得起来。
|
|
1120
|
+
problemKey: normalizeProblemKey(params.description),
|
|
1121
|
+
rationale: params.description,
|
|
1122
|
+
})
|
|
1123
|
+
setPendingVerdict(report.verdict)
|
|
1124
|
+
appendImprovement({ ...report, id: randomUUID(), timestamp: new Date().toISOString() })
|
|
1125
|
+
const rate = improvementRate(readImprovements())
|
|
1126
|
+
const label =
|
|
1127
|
+
report.verdict === 'improved'
|
|
1128
|
+
? 'improved ✅'
|
|
1129
|
+
: report.verdict === 'regressed'
|
|
1130
|
+
? 'regressed ⚠️'
|
|
1131
|
+
: 'inconclusive'
|
|
1132
|
+
const sign = report.deltaMean >= 0 ? '+' : ''
|
|
1133
|
+
// B2 代价维:只展示、不进判定(`formatCostLine` 缺席时返回 null ⇒ 整行不打)。
|
|
1134
|
+
const costLine = formatCostLine(report)
|
|
1135
|
+
// 空模型闸:只在闸失败时出声;它解释了 verdict 为什么被降级。
|
|
1136
|
+
const nullLine = formatNullModelLine(report)
|
|
1137
|
+
const taxLine = formatRsiTaxLine(report)
|
|
1138
|
+
improvementLine =
|
|
1139
|
+
`\n📊 改进判定: ${label} (delta ${sign}${report.deltaMean.toFixed(1)}, 噪声 ${report.noise.toFixed(1)}, 阈值 ${report.minEffect.toFixed(1)})` +
|
|
1140
|
+
`\n 改进率: ${rate.improved}/${rate.total} (${(rate.rate * 100).toFixed(0)}%, Wilson 95% [${(rate.lo * 100).toFixed(0)}%, ${(rate.hi * 100).toFixed(0)}%])` +
|
|
1141
|
+
(costLine ? `\n${costLine}` : '') +
|
|
1142
|
+
(taxLine ? `\n${taxLine}` : '') +
|
|
1143
|
+
(nullLine ? `\n${nullLine}` : '') +
|
|
1144
|
+
(report.verdict === 'regressed' ? '\n ⚠️ 任务表现倒退:--approve 将被拒绝。' : '')
|
|
1145
|
+
}
|
|
1146
|
+
} catch {
|
|
1147
|
+
// 测量失败(LLM 不可用等)不阻断 modify 流程——改进信号是可选的。
|
|
1148
|
+
}
|
|
1149
|
+
return improvementLine
|
|
1054
1150
|
}
|
|
1055
1151
|
|
|
1056
1152
|
const crsiModifyCmd: CommandHandler = async (ctx, args) => {
|
|
@@ -1067,10 +1163,97 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
|
|
|
1067
1163
|
setPendingVerdict(null)
|
|
1068
1164
|
return { content: r.success ? `✅ ${r.message}` : `⚠️ ${r.message}` }
|
|
1069
1165
|
}
|
|
1166
|
+
if (args[0] === '--integrate') {
|
|
1167
|
+
// ELITE(2611.21056):多提案 → 兼容子集 → 一个后代。
|
|
1168
|
+
// 每个提案是一个文件,内容是该提案下的**完整目标文件**;以当前目标为共同父本做 3-way merge。
|
|
1169
|
+
const dropConflicts = args[1] === '--drop-conflicts'
|
|
1170
|
+
const rest = args.slice(dropConflicts ? 2 : 1)
|
|
1171
|
+
if (rest.length < 4) {
|
|
1172
|
+
return {
|
|
1173
|
+
content:
|
|
1174
|
+
'Usage: /crsi modify --integrate [--drop-conflicts] <description> <filePath> <proposal1> <proposal2> [...]\n' +
|
|
1175
|
+
'- 每个 proposalN 是一个文件,内容为该提案下的完整目标文件\n' +
|
|
1176
|
+
'- 冲突默认拒绝;--drop-conflicts 只整合兼容子集(不静默丢弃机制)',
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
if (hasPending()) {
|
|
1180
|
+
return { content: '⚠️ 已有待批准的修改。先 /crsi modify --approve 或 --reject。' }
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
const description = rest[0]!
|
|
1184
|
+
const filePath = rest[1]!
|
|
1185
|
+
const { readFileSync } = await import('node:fs')
|
|
1186
|
+
const { join } = await import('node:path')
|
|
1187
|
+
const resolvePath = (p: string) => (p.startsWith('/') ? p : join(process.cwd(), p))
|
|
1188
|
+
|
|
1189
|
+
let originalContent: string
|
|
1190
|
+
try {
|
|
1191
|
+
originalContent = readFileSync(resolvePath(filePath), 'utf-8')
|
|
1192
|
+
} catch {
|
|
1193
|
+
return { content: `❌ 整合需要可读的父本:${filePath}` }
|
|
1194
|
+
}
|
|
1195
|
+
const proposals: Array<{ name: string; content: string }> = []
|
|
1196
|
+
for (const p of rest.slice(2)) {
|
|
1197
|
+
try {
|
|
1198
|
+
proposals.push({ name: p, content: readFileSync(resolvePath(p), 'utf-8') })
|
|
1199
|
+
} catch {
|
|
1200
|
+
return { content: `❌ 读不到提案文件:${p}` }
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
const integration = integrateProposals(originalContent, proposals)
|
|
1205
|
+
if (integration.error) {
|
|
1206
|
+
return { content: `❌ 整合失败:${integration.error}` }
|
|
1207
|
+
}
|
|
1208
|
+
const summary = formatIntegrationSummary(integration)
|
|
1209
|
+
const conflictList = integration.conflicts.map((c) => c.name).join(', ')
|
|
1210
|
+
if (integration.conflicts.length > 0 && !dropConflicts) {
|
|
1211
|
+
return {
|
|
1212
|
+
content:
|
|
1213
|
+
`⚠️ 整合冲突:${conflictList}\n${summary}\n` +
|
|
1214
|
+
'冲突意味着两个提案改了同一段。默认不丢弃任何机制——\n' +
|
|
1215
|
+
'用 --drop-conflicts 只整合兼容子集,或先把提案收敛成一个。',
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
if (!integration.content || integration.content === originalContent) {
|
|
1219
|
+
return { content: `⚠️ 没有可整合的改动。\n${summary}` }
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
const result = await runCrsiModification({
|
|
1223
|
+
description,
|
|
1224
|
+
filePath,
|
|
1225
|
+
newContent: integration.content,
|
|
1226
|
+
originalContent,
|
|
1227
|
+
blastRadius: [filePath],
|
|
1228
|
+
})
|
|
1229
|
+
if (!result.applied || result.phase === 'failed') {
|
|
1230
|
+
return {
|
|
1231
|
+
content: `❌ 整合未通过(phase: ${result.phase})。\n${result.error ?? ''}`,
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
const improvementLine = await measureModification(ctx, {
|
|
1236
|
+
description,
|
|
1237
|
+
filePath,
|
|
1238
|
+
originalContent,
|
|
1239
|
+
newContent: integration.content,
|
|
1240
|
+
})
|
|
1241
|
+
const conflictNote = integration.conflicts.length > 0 ? ` · 丢弃冲突 ${conflictList}` : ''
|
|
1242
|
+
return {
|
|
1243
|
+
content:
|
|
1244
|
+
`✅ 测试通过。🧩 整合:${summary}${conflictNote}\n` +
|
|
1245
|
+
renderGateNote(result) +
|
|
1246
|
+
`\n${result.diff}\n` +
|
|
1247
|
+
improvementLine +
|
|
1248
|
+
'\n/crsi modify --approve 合并\n/crsi modify --reject 丢弃',
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1070
1252
|
if (args.length < 3) {
|
|
1071
1253
|
return {
|
|
1072
1254
|
content:
|
|
1073
1255
|
'Usage: /crsi modify <description> <filePath> <newContent>\n' +
|
|
1256
|
+
' /crsi modify --integrate [--drop-conflicts] <description> <filePath> <proposal1> <proposal2> [...]\n' +
|
|
1074
1257
|
'- description 单 token(不含空格)\n' +
|
|
1075
1258
|
'- newContent 用 \\n 表示换行\n' +
|
|
1076
1259
|
'测试通过后:/crsi modify --approve 合并,/crsi modify --reject 丢弃',
|
|
@@ -1107,36 +1290,12 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
|
|
|
1107
1290
|
}
|
|
1108
1291
|
|
|
1109
1292
|
// 测量在 runCrsiModification 成功后进行(避免 failed proposal 白跑 6 次 LLM 调用)。
|
|
1110
|
-
const
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
setPendingVerdict(report.verdict)
|
|
1117
|
-
appendImprovement({ ...report, id: randomUUID(), timestamp: new Date().toISOString() })
|
|
1118
|
-
const rate = improvementRate(readImprovements())
|
|
1119
|
-
const label =
|
|
1120
|
-
report.verdict === 'improved'
|
|
1121
|
-
? 'improved ✅'
|
|
1122
|
-
: report.verdict === 'regressed'
|
|
1123
|
-
? 'regressed ⚠️'
|
|
1124
|
-
: 'inconclusive'
|
|
1125
|
-
const sign = report.deltaMean >= 0 ? '+' : ''
|
|
1126
|
-
// B2 代价维:只展示、不进判定(`formatCostLine` 缺席时返回 null ⇒ 整行不打)。
|
|
1127
|
-
const costLine = formatCostLine(report)
|
|
1128
|
-
// 空模型闸:只在闸失败时出声;它解释了 verdict 为什么被降级。
|
|
1129
|
-
const nullLine = formatNullModelLine(report)
|
|
1130
|
-
improvementLine =
|
|
1131
|
-
`\n📊 改进判定: ${label} (delta ${sign}${report.deltaMean.toFixed(1)}, 噪声 ${report.noise.toFixed(1)}, 阈值 ${report.minEffect.toFixed(1)})` +
|
|
1132
|
-
`\n 改进率: ${rate.improved}/${rate.total} (${(rate.rate * 100).toFixed(0)}%, Wilson 95% [${(rate.lo * 100).toFixed(0)}%, ${(rate.hi * 100).toFixed(0)}%])` +
|
|
1133
|
-
(costLine ? `\n${costLine}` : '') +
|
|
1134
|
-
(nullLine ? `\n${nullLine}` : '') +
|
|
1135
|
-
(report.verdict === 'regressed' ? '\n ⚠️ 任务表现倒退:--approve 将被拒绝。' : '')
|
|
1136
|
-
}
|
|
1137
|
-
} catch {
|
|
1138
|
-
// 测量失败(LLM 不可用等)不阻断 modify 流程——改进信号是可选的。
|
|
1139
|
-
}
|
|
1293
|
+
const improvementLine = await measureModification(ctx, {
|
|
1294
|
+
description,
|
|
1295
|
+
filePath,
|
|
1296
|
+
originalContent,
|
|
1297
|
+
newContent,
|
|
1298
|
+
})
|
|
1140
1299
|
|
|
1141
1300
|
return {
|
|
1142
1301
|
content:
|
|
@@ -1237,7 +1396,17 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
|
|
|
1237
1396
|
newContent: proposal.newContent,
|
|
1238
1397
|
})
|
|
1239
1398
|
if (sample) {
|
|
1240
|
-
const report = buildImprovementReport(
|
|
1399
|
+
const report = buildImprovementReport(
|
|
1400
|
+
sample,
|
|
1401
|
+
[proposal.filePath],
|
|
1402
|
+
proposal.expectedEffect,
|
|
1403
|
+
{
|
|
1404
|
+
// prose 路径有失败信号:分组键取「类别 + 标题」,同一类失败
|
|
1405
|
+
// 反复出现时才能看出这个环到底在修同一件事还是到处救火。
|
|
1406
|
+
problemKey: normalizeProblemKey(`${signal.category}: ${signal.title}`),
|
|
1407
|
+
rationale: proposal.description,
|
|
1408
|
+
},
|
|
1409
|
+
)
|
|
1241
1410
|
setPendingVerdict(report.verdict)
|
|
1242
1411
|
appendImprovement({ ...report, id: randomUUID(), timestamp: new Date().toISOString() })
|
|
1243
1412
|
if (report.predictionHit !== undefined) {
|
|
@@ -1249,6 +1418,9 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
|
|
|
1249
1418
|
// 「局部正确全局遗漏」)。ε 行可以有、代价行可以没有,故各自独立追加。
|
|
1250
1419
|
const costLine = formatCostLine(report)
|
|
1251
1420
|
if (costLine) predictionLine += `\n${costLine}`
|
|
1421
|
+
// RSI Tax 同理:两条渲染路径都接(只接一条 = 局部正确全局遗漏)。
|
|
1422
|
+
const taxLine = formatRsiTaxLine(report)
|
|
1423
|
+
if (taxLine) predictionLine += `\n${taxLine}`
|
|
1252
1424
|
// 空模型闸同理:两条渲染路径都接。
|
|
1253
1425
|
const nullLine = formatNullModelLine(report)
|
|
1254
1426
|
if (nullLine) predictionLine += `\n${nullLine}`
|
|
@@ -4148,7 +4320,17 @@ const codeReviewCmd = gitDiffBridgeCmd({
|
|
|
4148
4320
|
// 写成句末时模型容易先按默认深度铺开、再拿档位去追认。`max` 另有一句上限:
|
|
4149
4321
|
// 仓里存的可能是上一轮自己挑的,而不是用户这一轮要的 —— 只有**用户点名**才用。
|
|
4150
4322
|
const effort = getPreference('lastCodeReviewEffort', 'high')
|
|
4151
|
-
|
|
4323
|
+
// 范围与 `/simplify` 分开:整理(复用/简化/效率)有自己的命令,混进评审会让
|
|
4324
|
+
// 「这次改动有没有 bug」这个唯一的问题被风格建议稀释。严重度三档是**归属**,
|
|
4325
|
+
// 不是风险等级 —— 读的人先要判断的是「这是我这次弄坏的,还是本来就有的」。
|
|
4326
|
+
return (
|
|
4327
|
+
`Use effort level: ${effort} — settle this before you start; never pick max on your own, only when the user asked for it. ` +
|
|
4328
|
+
`Then use the code-review skill to review all uncommitted changes for bugs and CLAUDE.md violations only. ` +
|
|
4329
|
+
`Do not report reuse, simplification, efficiency, architecture or test-coverage cleanups — /simplify owns those. ` +
|
|
4330
|
+
`Mark each finding with exactly one severity: important (this change introduced or worsened it), ` +
|
|
4331
|
+
`pre_existing (it was already there before this change), or nit (minor). ` +
|
|
4332
|
+
`End the summary with one suggested fix. If there is nothing to report, write exactly: "Code review found no issues."${cap}`
|
|
4333
|
+
)
|
|
4152
4334
|
},
|
|
4153
4335
|
})
|
|
4154
4336
|
|