```
## 学习资源
* [MDN Web Docs](https://developer.mozilla.org/zh-CN/) - 最权威的 Web 技术文档
* [W3Schools](https://www.w3schools.com/) - 在线教程和实例
* [FreeCodeCamp](https://www.freecodecamp.org/) - 免费编程课程
* [CSS-Tricks](https://css-tricks.com/) - CSS 技巧和教程
* [JavaScript.info](https://javascript.info/) - 现代 JavaScript 教程
## 开发工具
* **浏览器**:Chrome DevTools, Firefox DevTools
* **编辑器**:VS Code, Sublime Text
* **在线工具**:CodePen, JSFiddle, CodeSandbox
## 最佳实践
1. **语义化 HTML**:使用合适的标签
2. **响应式设计**:适配不同设备
3. **性能优化**:压缩资源,懒加载
4. **可访问性**:支持屏幕阅读器
5. **代码规范**:保持一致的编码风格
6. **版本控制**:使用 Git 管理代码
# About
Source: https://base.bangwu.me/about/index
About bangwu (markbang) — ECNUer and full-stack developer, with blog and knowledge base links, personal interests, and content platforms.
## bangwu / markbang
* Deep thinker on *Under One Person*
* ECNUer
* Full-stack developer who believes "everything exists for a reason"
* Gaming addict, badminton beginner, tinkerer champion, music listener
* INFP-A
## Content output
| Platform | Description | Link |
| - | - | - |
| Blog | Daily thoughts and life sharing | [blog.bangwu.top](https://blog.bangwu.top) |
| Knowledge Base | CS knowledge collection | [base.bangwu.me](https://base.bangwu.me) |
| Micro-blog | RSS feed | [now.bangwu.top](https://now.bangwu.top/rss.xml) |
## Contact
* **Email**: [i@bangwu.top](mailto:i@bangwu.top)
* **GitHub**: [markbang](https://github.com/markbang)
> [!NOTE]
>
> I usually reply to email slowly, so thanks for your patience.
## Declaration
In the vast ocean of the internet, meeting each other is a kind of fate—so please be kind in your words. A URL is my first promise to the internet, and I plan to keep this domain for a long time. — September 27, 2024
# Site Info
Source: https://base.bangwu.me/about/site
Knowledge base site guide covering four content sections, page conventions, recommended reading workflow, and current maintenance principles.
# Site Introduction
I started building this site because tutorial quality online is inconsistent — especially on domestic forums like CSDN, Juejin, and Jianshu. So I decided to create my own — detailed, beginner-friendly tutorials that not only push me to learn, but also share better resources to save everyone's time.
One person can't cover everything, so contributions are welcome to build a high-quality knowledge base together.
## Logo Origin
The site logo comes from a Google emoji combiner I found on a post — Clown + Angry.
## Metadata & Conventions
| Element | Description |
| - | - |
| Sidebar | Links to topics within the current section, or tutorial sequence |
| Section landing page | Introduction to the section's scope and purpose |
| Search | Top-left search bar, or `Ctrl+K` to open quickly |
| Comments | Available at the bottom of each page |
# Bit manipulation
Source: https://base.bangwu.me/algo/bit
Bitwise operations guide covering AND/OR/XOR, common tricks like checking powers of two, and LeetCode examples using low-level binary manipulation.
# Bit manipulation
Bitwise operations work directly on binary bits. They are efficient and commonly used for algorithm optimization.
## Basic bit operators
| Operators | Name | Description | Example | | | |
| - | - | - | - | - | - | - |
| `&` | Bitwise AND | The result is `1` only when both bits are `1` | `5 & 3 = 1` (101 & 011 = 001) | | | |
| \` | \` | Bitwise OR | The result is `1` when either bit is `1` | \`5 | 3 = 7\` (101 | 011 = 111) |
| `^` | Bitwise XOR | The result is `1` when the bits are different | `5 ^ 3 = 6` (101 ^ 011 = 110) | | | |
| `~` | Bitwise NOT | Flip `0` to `1` and `1` to `0` | `~5 = -6` | | | |
| `<<` | Left shift | Shift left by `n` bits, equivalent to multiplying by `2^n` | `5 << 1 = 10` | | | |
| `>>` | Right shift | Shift right by `n` bits, roughly equivalent to dividing by `2^n` | `5 >> 1 = 2` | | | |
## Common tricks
### 1. Check odd or even
### 2. Swap two numbers without a temporary variable
### 3. Check whether the k-th bit is `1`
### 4. Set the k-th bit to `1`
### 5. Set the k-th bit to `0`
### 6. Flip the k-th bit
### 7. Extract the lowest `1` bit
### 8. Remove the lowest `1` bit
### 9. Check whether a number is a power of two
### 10. Count the number of `1` bits in binary
## Classic problems
### [LeetCode 136. Single Number](https://leetcode.cn/problems/single-number/)
**Problem:** every number in the array appears twice except one. Find the one that appears only once.
**Idea:** use the XOR properties `a ^ a = 0` and `a ^ 0 = a`.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for num in nums:
ans ^= num
return ans
```
### [LeetCode 191. Number of 1 Bits](https://leetcode.cn/problems/number-of-1-bits/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return count
```
### [LeetCode 231. Power of Two](https://leetcode.cn/problems/power-of-two/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
```
### [LeetCode 338. Counting Bits](https://leetcode.cn/problems/counting-bits/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i >> 1] + (i & 1)
return dp
```
## Typical use cases
* **State compression**: represent multiple boolean states with one integer
* **Set operations**: implement intersection, union, and complement through bit masks
* **Permission systems**: store different permissions as bits
* **Performance optimization**: use fast bitwise operations to replace some multiply/divide cases
# Algorithm Learning
Source: https://base.bangwu.me/algo/index
Algorithm learning roadmap with open-source resources like Hello Algo, Code Carried Away, and labuladong's notes, plus LeetCode tracking.
Algorithm study here mainly follows open-source books on GitHub together with LeetCode practice.

## Recommended resources
> [accordion] Hello Algo
>
> [Hello Algo](https://github.com/krahets/hello-algo): An animated, beginner-friendly data structures and algorithms tutorial with one-click runnable examples. It supports Java, C++, Python, Go, JS, TS, C#, Swift, Rust, Dart, and Zig.
> [accordion] Code Thinking Record
>
> [Code Thinking Record](https://github.com/youngyangyang04/leetcode-master): A classic structured problem set with detailed explanations, videos, mind maps, and multi-language support.
> [accordion] labuladong's Algorithm Notes
>
> [labuladong](https://github.com/labuladong/fucking-algorithm): Original articles built around LeetCode problems, focused on patterns, intuition, and transferable problem-solving techniques.
> [accordion] AI Engineering from Scratch
>
> [AI Engineering from Scratch](https://github.com/rohitg00/ai-engineering-from-scratch): 20 stages, 523 lessons, \~342 hours — from linear algebra to autonomous agents. Every lesson ships a reusable artifact (SKILL.md, prompt, MCP server); install with `npx skills add rohitg00/ai-engineering-from-scratch`.
> [accordion] Stanford CS 329Z
>
> [CS 329Z: Engineering AI Agents](https://cs329z.stanford.edu) (Fall 2026, Diyi Yang et al.): the engineering path from LLM pipelines to compound systems to autonomous agents. Lecture slides are public — the tool-use and frameworks/orchestration decks pair well with the harness notes on this site.
> [card] [Sliding Window](/algo/sliding_window)
>
> Two-pointer and sliding window patterns.
> [card] [Bit Manipulation](/algo/bit)
>
> Common bit tricks and problem types.
# Sliding window
Source: https://base.bangwu.me/algo/sliding_window
Sliding window algorithm using two pointers for subarray and substring problems, with a Python template, LeetCode examples, and O(n) analysis.
[leetcode.3](https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/)
The sliding window technique is a common two-pointer pattern for array and string problems. By maintaining a window that moves across the sequence, many problems can be solved in `O(n)` time.
### Core idea
1. Use two pointers, `left` and `right`, to represent the window boundaries.
2. Move `right` to expand the window.
3. When the window satisfies a shrink condition, move `left` to contract it.
4. Update the answer while the window changes.
### Template code
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def sliding_window(s: str):
left = 0
window = {} # 窗口内's 数据
result = 0
for right in range(len(s)):
# 1. 将right位置's 元素加入窗口
c = s[right]
window[c] = window.get(c, 0) + 1
# 2. 判断窗口是否需要收缩
while 窗口需要收缩's 条件:
# 3. 移出left位置's 元素
d = s[left]
left += 1
window[d] -= 1
# 4. 更新结果
result = max(result, right - left + 1)
return result
```
## Classic problems
### 1. [LeetCode 3. Longest substring without repeating characters](https://leetcode.cn/problems/longest-substring-without-repeating-characters/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# leetcode.3 滑动窗口+哈希表
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic, res, i = {}, 0, -1
for j in range(len(s)):
if s[j] in dic:
i = max(i, dic[s[j]])
dic[s[j]] = j
res = max(res, j-i)
return res
```
### 2. [LeetCode 76. Minimum window substring](https://leetcode.cn/problems/minimum-window-substring/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def minWindow(self, s: str, t: str) -> str:
from collections import Counter
need = Counter(t)
window = {}
left = 0
valid = 0
start, length = 0, float('inf')
for right in range(len(s)):
c = s[right]
if c in need:
window[c] = window.get(c, 0) + 1
if window[c] == need[c]:
valid += 1
while valid == len(need):
if right - left + 1 < length:
start = left
length = right - left + 1
d = s[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return "" if length == float('inf') else s[start:start+length]
```
### 3. [LeetCode 438. Find all anagrams in a string](https://leetcode.cn/problems/find-all-anagrams-in-a-string/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
from collections import Counter
need = Counter(p)
window = {}
left = 0
valid = 0
result = []
for right in range(len(s)):
c = s[right]
if c in need:
window[c] = window.get(c, 0) + 1
if window[c] == need[c]:
valid += 1
while right - left + 1 >= len(p):
if valid == len(need):
result.append(left)
d = s[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return result
```
### 4. [LeetCode 209. Minimum size subarray sum](https://leetcode.cn/problems/minimum-size-subarray-sum/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = 0
total = 0
result = float('inf')
for right in range(len(nums)):
total += nums[right]
while total >= target:
result = min(result, right - left + 1)
total -= nums[left]
left += 1
return 0 if result == float('inf') else result
```
### 5. [LeetCode 567. Permutation in string](https://leetcode.cn/problems/permutation-in-string/)
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
from collections import Counter
need = Counter(s1)
window = {}
left = 0
valid = 0
for right in range(len(s2)):
c = s2[right]
if c in need:
window[c] = window.get(c, 0) + 1
if window[c] == need[c]:
valid += 1
while right - left + 1 >= len(s1):
if valid == len(need):
return True
d = s2[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return False
```
## Typical use cases
* Finding the best value over a continuous subarray or substring
* String matching problems
* Fixed-length window problems
* Longest or shortest subarray satisfying a condition
## Time complexity
Although there are two loops, each element is visited at most twice—once by `right` and once by `left`—so the overall time complexity is `O(n)`.
# Apifox
Source: https://base.bangwu.me/apps/Apifox
Apifox is an all-in-one API platform combining Postman, Swagger, Mock, and JMeter for REST API design, debugging, testing, and documentation.
[Apifox](https://apifox.com/) is an all-in-one API design, development, and testing platform — a domestic Chinese app. Apifox = Postman + Swagger + Mock + JMeter.
If you've worked with backend API debugging, you know that a good API testing tool speeds up development. Apifox is exactly that kind of platform.

# Barrier
Source: https://base.bangwu.me/apps/Barrier
Barrier is an open-source Synergy alternative for sharing one keyboard and mouse across multiple computers on Windows, macOS, or Linux.
# Device Sharing
Barrier lets you use one keyboard and mouse across multiple devices — an open-source alternative to Synergy.
## Installation
> [tab] Scoop
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> scoop install barrier
> ```
>
> > [!WARNING]
> >
> > Barrier installed via Scoop may fail to connect to the LAN, possibly due to an unaccepted protocol. If you encounter this issue, use the manual installation method below.
> [tab] Manual Install
>
> Download from [GitHub Releases](https://github.com/debauchee/barrier/releases/tag/v2.4.0).
# Browser Harness
Source: https://base.bangwu.me/apps/BrowserHarness
Browser Harness is a thin, self-healing browser control layer built on CDP for coding agents like Codex and Claude Code that need real browser access.
# Browser Harness
[Browser Harness](https://github.com/browser-use/browser-harness) is an open-source browser control layer from the Browser Use team. Its core idea is simple:
* connect directly to Chrome through **CDP**
* keep the harness **thin**
* let the agent **write missing helper code during the task**
It is not trying to be another large test framework. It is closer to a minimal bridge that gives an LLM more freedom inside a real browser session.
## Why it is interesting
Compared with rigid browser automation flows, Browser Harness is designed for **agentic use**:
* works with tools like **Codex** and **Claude Code**
* can connect to your **real browser**
* allows the agent to add helper functions while it is working
* supports free remote browsers for cloud or sub-agent scenarios
The official README describes it as a **self-healing browser harness**: if the current helper set is missing a capability, the agent can edit the harness and continue instead of stopping immediately.
## How it works
The project stays intentionally small:
* `install.md` handles first-time setup
* `SKILL.md` explains normal usage
* `helpers.py` contains the callable browser helper functions
* `daemon.py` and `admin.py` handle the CDP websocket and local bridge
The interesting part is that `helpers.py` is not treated as fixed forever. The agent is expected to inspect it and extend it when needed.
In practice, the flow looks like this:
1. Connect the harness to Chrome through CDP
2. Ask the coding agent to complete a browser task
3. If a helper is missing, the agent edits the harness
4. Continue the task with the new helper available
That is the main difference from a traditional test script that fails as soon as the missing operation is encountered.
## When to use it
Browser Harness makes sense when you want:
* a coding agent to operate a real browser for you
* interactive browser tasks rather than only deterministic regression tests
* a thinner layer than a large end-to-end testing stack
* browser work that can improve over time as helpers and skills accumulate
Typical examples:
* logging into websites with your existing browser profile
* navigating complex dashboards
* submitting forms or uploading files
* doing repetitive browser workflows that are annoying to script upfront
## When not to use it
If you need:
* strict, reproducible end-to-end tests
* stable CI assertions
* browser automation with carefully fixed selectors and snapshots
then a conventional framework such as Playwright is often a better default.
Browser Harness is more about **agent flexibility** than strict test determinism.
## Real browser vs remote browser
The project supports both:
### Real browser
Best for:
* personal workflows
* sites where you are already logged in
* tasks that benefit from your existing cookies, sessions, and local browser state
### Remote browser
Best for:
* cloud execution
* sub-agents
* isolated sessions
* tasks that should not depend on your local machine
Browser Use also documents a remote-browser/CDP workflow and an MCP server, which makes the surrounding ecosystem broader than this repo alone.
## Practical setup notes
The README recommends a very direct setup pattern:
1. let the agent clone or open the repo
2. read `install.md` first
3. read `SKILL.md` for day-to-day usage
4. always inspect `helpers.py`
That setup pattern matters because the harness is intentionally editable during execution.
## Browser Use Box
[Browser Use Box](https://github.com/browser-use/bux), also called `bux`, is a useful pattern built on top of Browser Harness. Instead of running the agent only on your laptop, it runs a persistent Claude Code environment on a box you own, such as a VPS, Mac mini, or Raspberry Pi.
The pieces are simple:
* `claude -p` drives the agent loop
* Browser Harness connects to a real Chromium session through CDP over WSS
* Browser Use Cloud hosts the browser session
* Telegram and `ttyd` provide remote control surfaces
* `/home/bux` stores persistent state across restarts
This solves a different problem from local browser automation. Local agents disappear when the laptop sleeps or the terminal closes. A box-based agent can keep browser logins, cookies, skills, and task state alive, then accept short commands from anywhere.
The tradeoff is operational complexity. You now own a small always-on runtime with credentials, systemd services, browser sessions, and remote access paths. Treat it like infrastructure, not just a demo.
## How it fits into the current agent tooling landscape
There are now roughly three common layers for browser automation:
1. **classic automation frameworks**
Playwright, Puppeteer, Selenium
2. **MCP/browser tools for assistants**
tool-call-oriented browser control
3. **agent-native browser harnesses**
browser control designed for LLMs that reason, adapt, and patch their own workflow
Browser Harness clearly sits in the third category.
## My take
The interesting part is not just "LLMs can click a browser". A lot of tools can already do that.
The more durable idea is this:
> treat browser automation as an editable runtime surface for agents, not only as a fixed script written in advance.
That is a useful mental model if you are building agent workflows around real websites.
## References
* [browser-use/browser-harness](https://github.com/browser-use/browser-harness)
* [Browser Use documentation](https://docs.browser-use.com/)
* [browser-use/bux](https://github.com/browser-use/bux)
* [Remote Browser via CDP](https://docs.browser-use.com/customize/browser/remote)
* [Browser Use MCP Server](https://docs.browser-use.com/customize/mcp-server)
# CherryStudio
Source: https://base.bangwu.me/apps/CherryStudio
CherryStudio is an open-source AI chat client with deep CSS theme customization, including a Claude-style dark and light mode configuration.
# CherryStudio
GitHub repository: [https://github.com/CherryHQ/cherry-studio](https://github.com/CherryHQ/cherry-studio)
The following CSS is a Claude-style theme preset for CherryStudio, with both dark and light variants.
```css theme={"theme":{"light":"github-light","dark":"github-dark"}}
/* Claude 主题 2.0 */
/* Theme Variables */
:root {
--color-black-soft: #2a2b2a; /* 深灰黑色,接近炭黑 */
--color-white-soft: #f8f7f2; /* 温暖's 米色,略带象牙色调 */
--font-family: 'SF Pro Rounded', 'LXGWWenKaiScreenR', -apple-system, BlinkMacSystemFont,
system-ui, sans-serif;
--message-text-color-dark: hsl(50, 14%, 91%); /* 暖色调浅米白色 */
}
/* Dark Theme */
body[theme-mode='dark'] {
/* Color Definitions */
--color-background: #2b2b2b; /* 深炭灰色 */
--color-background-soft: #303030; /* 稍浅's 炭灰色 */
--color-background-mute: #282c34; /* 带深蓝调's 石墨灰 */
--navbar-background: var(--color-black-soft); /* 深灰黑色 */
--chat-background: var(--color-black-soft); /* 深灰黑色 */
--chat-background-user: #323332; /* 中深炭灰色 */
--chat-background-assistant: #2d2e2d; /* 深橄榄灰色 */
font-family: var(--font-family) !important;
color: var(--message-text-color-dark) !important;
}
/* Dark Theme特定样式 */
body[theme-mode='dark'] {
#content-container {
background-color: var(--chat-background-assistant) !important;
font-family: var(--font-family) !important;
}
#content-container #messages {
background-color: var(--chat-background-assistant);
color: var(--message-text-color-dark) !important;
font-family: var(--font-family) !important;
}
.message-content-container {
background: hsl(60, 2%, 21%) !important; /* 深橄榄灰色,带微弱黄绿色调 */
font-family: var(--font-family) !important;
box-shadow: 0 4px 16px -8px rgba(0, 0, 0, 0.04) !important;
border: 1px solid var(--color-border) !important;
border-radius: 18px !important;
margin: 8px 0 !important;
padding: 10px 10px 10px 10px !important;
color: var(--message-text-color-dark) !important;
}
/* 用户Message样式 */
.message.message-user,
.message.message-user *,
.message-user,
.message-user *,
.message-user .message-content-container,
.message-user .message-content-container * {
color: var(--message-text-color-dark) !important;
}
.message-user .message-content-container {
background: hsl(60, 2%, 21%) !important; /* 深橄榄灰色,与AI回复一致 */
box-shadow: 0 8px 32px -12px rgba(0, 0, 0, 0.03) !important;
}
.inputbar-container {
background-color: #3d3d3a; /* 中灰色带微橄榄绿调 */
border: 1px solid #5e5d5940; /* 中灰色带40%透明度 */
border-radius: 8px;
font-family: var(--font-family) !important;
color: var(--message-text-color-dark) !important;
}
/* Code Styles */
code {
background-color: #e5e5e20d; /* 浅灰白色,7%透明度 */
color: #ea928a; /* 淡珊瑚红色 */
font-family: var(--font-family) !important;
}
pre code {
color: #abb2bf; /* 浅钢蓝灰色 */
font-family: var(--font-family) !important;
}
/* 深色模式下's Text Color Override */
p,
span,
div {
color: var(--message-text-color-dark);
}
}
/* Light Theme */
body[theme-mode='light'] {
/* Color Definitions */
--color-white: #ffffff; /* 纯白色 */
--color-background: hsl(55, 19%, 89%); /* 淡米黄灰色 */
--color-background-soft: hsl(51, 16%, 85%); /* 浅麦秆黄色 */
--color-background-mute: #e4e1d7; /* 灰米色,带微暖调 */
--navbar-background: var(--color-white-soft); /* 温暖's 米色 */
--chat-background: var(--color-white-soft); /* 温暖's 米色 */
--chat-background-user: #f8f7f2; /* 温暖's 米色,略带象牙色调 */
--chat-background-assistant: hsl(51, 24%, 95%); /* 非常浅's 麦秆黄色 */
font-family: var(--font-family) !important;
}
/* Light Theme特定样式 */
body[theme-mode='light'] {
#content-container {
background-color: var(--chat-background-assistant) !important;
font-family: var(--font-family) !important;
}
#content-container #messages {
background-color: var(--chat-background-assistant);
font-family: var(--font-family) !important;
}
.message-content-container {
background: hsl(40, 23%, 98%) !important; /* 极浅's 米黄色,接近纯白 */
font-family: var(--font-family) !important;
box-shadow: 0 4px 16px -8px rgba(0, 0, 0, 0.04) !important;
border: 1px solid var(--color-border) !important;
border-radius: 18px !important;
margin: 8px 0 !important;
padding: 10px 10px 10px 10px !important;
color: hsl(47, 15%, 25%) !important; /* 深橄榄褐色 */
}
.message-user .message-content-container {
background: hsl(51, 19%, 87%) !important; /* 浅麦秆黄色 */
box-shadow: 0 8px 32px -12px rgba(0, 0, 0, 0.03) !important;
color: hsl(47, 15%, 25%) !important; /* 深橄榄褐色 */
}
.inputbar-container {
background-color: #ffffff; /* 纯白色 */
border: 1px solid #87867f40; /* 中灰褐色带40%透明度 */
border-radius: 16px;
font-family: var(--font-family) !important;
}
/* Code Styles */
code {
background-color: #3d39290d; /* 深棕褐色,5%透明度 */
color: #7c1b13; /* 砖红褐色 */
font-family: var(--font-family) !important;
}
pre code {
color: #000000; /* 纯黑色 */
font-family: var(--font-family) !important;
}
}
```
# AI IDE
Source: https://base.bangwu.me/apps/Cursor
Cursor and Trae are AI-powered code editors — tips, workflows, and billing changes for GitHub Copilot.
## Cursor
[go-cursor-help](https://github.com/yuaotian/go-cursor-help/blob/master/README_CN.md#solution1)
```powershell theme={"theme":{"light":"github-light","dark":"github-dark"}}
irm https://aizaozao.com/accelerate.php/https://raw.githubusercontent.com/yuaotian/go-cursor-help/refs/heads/master/scripts/run/cursor_win_id_modifier.ps1 | iex
```
### Cursor 3: What Users Actually Want
Based on 431 community feedback responses (April 2026), the core insight is: **users don't just want "AI that writes code" — they want a stable, controllable AI development workbench**. The top priorities are:
1. **Agent + IDE seamless fusion** — Agent Window is promising, but must preserve full IDE capabilities (LSP, debugging, task running, extensions, keybindings, code navigation, diff accept/reject). Users shouldn't have to switch back to the old IDE for small operations.
2. **Worktree / Git / PR workflow productization** — Developers want a low-friction, auditable Git console, not natural-language Git commands. Key needs: branch switching, PR detection, selective staging, multi-repo diff, submodule support, CI status, and review integration.
3. **Stability over features** — Startup speed, memory usage, context loss, LSP failures, and large-repo indexing are trust killers. If the basics don't work, users will switch to alternatives.
4. **Model cost transparency** — Users want to know "which model is cheapest for this task?" not just more models. Good direction: Cursor suggests "use a cheap model here, upgrade to a strong model there."
5. **Keyboard-first** — The entire product must be operable without a mouse. Custom keybindings, quick panel switching, and inherited VS Code muscle memory are essential for heavy users.
6. **Task memory system** — When agent work grows, "chat history list" must evolve into "task memory system": auto-rename chats, pin messages, fork sessions, cross-project context.
> [!NOTE]
>
> Synthesized from [Eric Zakariasson's Cursor 3 feedback thread](https://x.com/ericzakariasson) — 431 community responses, April 2026.
## Workflow for studying unfamiliar LLMs
When you use an AI IDE to understand an open-weight model rather than just write app code, this order works well:
1. **Read the official report first**
* Use it to understand the model family, goals, and top-level architecture.
* Treat it as the overview, not the final source of implementation truth.
2. **Inspect the Hugging Face config**
* Check layers, hidden size, attention heads, RoPE settings, MoE options, KV heads, and other structural fields.
* Config files often expose details that summaries skip.
3. **Read the reference implementation**
* If the model is supported by `transformers` or an official repo, inspect the real code path.
* Working code is usually the most reliable way to confirm module order and implementation details.
4. **Only then summarize or diagram it**
* Once you have your own mental model, use the AI IDE to generate diagrams, compare related architectures, or explain local modules.
### Best fit
* Open-weight models
* Models with public configs and reference implementations
* Less useful for closed models that only expose product-level descriptions
### Reference
* [Sebastian Raschka: My Workflow for Understanding LLM Architectures](https://magazine.sebastianraschka.com/p/workflow-for-understanding-llms)
## GitHub Copilot: Usage-Based Billing (June 2026)
Starting **June 1, 2026**, GitHub Copilot transitions from "premium request units" to **AI Credits** based on token consumption. This reflects Copilot's evolution from a code-completion assistant into an agentic platform running long multi-step coding sessions.
### What stays the same
* **Base prices unchanged** — Pro $10/month, Pro+ $39/month, Business $19/user/month, Enterprise $39/user/month
* **Code completions and Next Edit suggestions** — Still included, do not consume AI Credits
* **Monthly credits equal subscription price** — Pro gets $10 credits, Pro+ gets $39 credits
### What changes
* **Premium request units replaced by AI Credits** — Usage calculated by input, output, and cached tokens at each model's API rate
* **No fallback to cheaper models** — Previously, exhausted PRUs could fall back. Now credits spent = credits spent, no downgrade path
* **Copilot Code Review** — Consumes both AI Credits **and** GitHub Actions minutes
* **Pooled credits for organizations** — Business/Enterprise credits can pool across the team, reducing stranded capacity
### Transition buffer (June–August 2026)
| Plan | Normal monthly credits | Transitional credits (June–Aug) |
| - | - | - |
| Business | \$19/user | \$30/user |
| Enterprise | \$39/user | \$70/user |
### Practical implications
* **Light users** — Nearly unaffected; completions stay free
* **Heavy Agent users** — Monitor bills after June; long autonomous sessions consume credits fast
* **Annual subscribers** — Stay on old PRU model until plan expires, then transition to monthly with credits
* **Preview billing** — Early May: preview bill page shows projected costs before the switch
> [!TIP]
>
> If you run long Copilot Agent sessions, check the preview billing tool in early May to estimate your monthly credit burn. Agent tasks that iterate across entire repos will consume significantly more tokens than simple chat completions.
> [!NOTE]
>
> * [GitHub Blog: Copilot moves to usage-based billing](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/)
> * [Twitter @dotey summary](https://x.com/dotey/status/2048849524739977672)
## Coding Agent Safety: How OpenAI Controls Codex
When coding agents can read/write repos, run commands, and call development tools, you need both efficiency and control. OpenAI's answer is a **four-layer framework** for Codex: sandbox + approval + network policy + identity governance. The guiding principle: **zero friction for low-risk daily operations, mandatory human review for high-risk ones**.
### 1. Sandbox + Approval
* **Sandbox** defines technical execution boundaries: where to write, whether to allow networking, which paths are read-only
* **Approval policy** defines when to stop and ask a human — typically triggered when crossing sandbox boundaries
* **Auto-review mode**: A separate sub-agent reviews Codex's pending actions and context, auto-approving low-risk requests and only interrupting the user when risk escalates. This is "AI reviewing AI" — turning approval itself into an intelligent layer
### 2. Network Access
Default-deny, explicit-allow model:
* **Allow** known compliant destinations
* **Block** explicitly unwanted domains (e.g., pastebin.com — typical data exfiltration channel)
* **Require approval** for unknown domains
Implemented via proxy — no open outbound permissions for the agent.
### 3. Identity & Credentials
* OAuth credentials for CLI and MCP are **forced into OS keyring** (macOS Keychain)
* Authentication via **ChatGPT login** — no bypass
* Locked to **specific enterprise workspace UUID**
Effect: All Codex activity is bound to workspace-level governance and automatically falls into ChatGPT compliance logging.
### 4. Command Rules
Commands are classified by semantic risk level:
* **Read-only commands** (`gh pr view`, `kubectl get`) → auto-approve
* **Dangerous commands** → explicit block or require approval
This "semantic classification" approach means the agent feels almost no friction during normal engineering workflows, while retaining a hard brake for dangerous operations.
### 5. Configuration Distribution
Three-layer distribution ensures org-wide consistency:
* **Cloud managed requirements** + **macOS managed preferences** + **local requirements file**
* `requirements` are admin-mandatory — users cannot override
### Agent-Native Telemetry
Traditional EDR and audit logs tell you "what happened" — but for AI agents, security teams need **"why"**:
* User's original prompt
* Agent's reasoning path
* Approval decisions
* Tool call chains
* MCP server usage
* Network proxy allow/deny events
Codex exports these via **OpenTelemetry**, enabling reconstruction of the full causal chain: "user said → agent planned → system approved → actually happened → network layer blocked or not".
OpenAI's own practice: When EDR flags anomalous Codex behavior, their **AI safety triage agent** pulls Codex telemetry and auto-classifies into three categories:
1. Expected agent behavior
2. Benign mistake
3. genuinely needs escalation
Only category 3 gets pushed to humans. This is a **"agent behavior interpreted by another agent"** security ops paradigm.
> [!TIP]
>
> If you deploy coding agents in your org, consider implementing a similar framework: sandbox boundaries, command-level risk classification, and telemetry that captures the "why" not just the "what". The auto-review pattern (AI reviewing AI) is especially useful for reducing approval noise.
> [!NOTE]
>
> * [OpenAI: Running Codex Safely](https://openai.com/index/running-codex-safely/) — official blog post
> * [Twitter @dotey Chinese summary](https://x.com/dotey/status/2048849524739977672) — detailed translation of the four-layer framework
## Trae
Free AI IDE, continuously updated.
# Pyenv
Source: https://base.bangwu.me/apps/Pyenv
Pyenv is a Python version manager for installing and switching between multiple Python versions on the same system with per-project settings.
# [Pyenv](https://github.com/pyenv/pyenv?tab=readme-ov-file#windows)
Pyenv is a Python version manager that makes it easy to install and switch between multiple Python versions on the same machine.
## Features
* 📦 Manage multiple Python versions
* 🔄 Switch versions quickly
* 🎯 Pin a specific version for each project
* 🌐 Support virtual environments
* 🪟 Cross-platform support for Windows, Linux, and macOS
## Installation
### Windows
Use [pyenv-win](https://github.com/pyenv-win/pyenv-win):
```powershell theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 使用 pip Installation
pip install pyenv-win --target $HOME/.pyenv
# 或使用 Git
git clone https://github.com/pyenv-win/pyenv-win.git $HOME/.pyenv
```
Add environment variables:
```powershell theme={"theme":{"light":"github-light","dark":"github-dark"}}
[System.Environment]::SetEnvironmentVariable('PYENV',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
[System.Environment]::SetEnvironmentVariable('PYENV_ROOT',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
[System.Environment]::SetEnvironmentVariable('PYENV_HOME',$env:USERPROFILE + "\.pyenv\pyenv-win\","User")
```
### Linux/macOS
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 使用官方Installationscripts
curl https://pyenv.run | bash
# 或使用 Homebrew (Mac)
brew install pyenv
```
Configure your shell by adding the following to `~/.bashrc` or `~/.zshrc`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
```
## Basic usage
### Show installable versions
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 列出所有可用versions
pyenv install --list
# search for特定versions
pyenv install --list | grep 3.11
```
### Install Python versions
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Installation特定versions
pyenv install 3.11.5
# Installation最新versions
pyenv install 3.11
# ViewInstallation进度
pyenv install -v 3.11.5
```
### Show installed versions
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 列出所有已Installationversions
pyenv versions
# View当前versions
pyenv version
```
### Switch Python versions
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 全局切换(所有 shell)
pyenv global 3.11.5
# 本地切换(当前目录)
pyenv local 3.10.12
# 临时切换(当前 shell)
pyenv shell 3.9.18
```
### Uninstall a version
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pyenv uninstall 3.9.18
```
## Advanced usage
### Set a version for a project
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# in项目目录下
cd my_project
pyenv local 3.11.5
# 会创建 .python-version file
cat .python-version
# 3.11.5
```
### Virtual environments
Use it together with `pyenv-virtualenv`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Installation pyenv-virtualenv
git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
# 创建虚拟环境
pyenv virtualenv 3.11.5 my-project-env
# 激活虚拟环境
pyenv activate my-project-env
# 停用虚拟环境
pyenv deactivate
# Removed虚拟环境
pyenv virtualenv-delete my-project-env
# 为项目自动激活虚拟环境
cd my_project
pyenv local my-project-env
```
### Show where the current version comes from
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# View当前versions及来源
pyenv version
# 3.11.5 (set by /home/user/project/.python-version)
```
### Refresh shims
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 重新generates shims(Installation新Package后)
pyenv rehash
```
## Configuration files
### Global configuration
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 设置全局versions
pyenv global 3.11.5
# Configuration File位置
~/.pyenv/version
```
### Project configuration
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 项目目录下's .python-version file
echo "3.11.5" > .python-version
```
### Shell configuration
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 临时设置
export PYENV_VERSION=3.11.5
```
## FAQ
### Installation failed
**Missing Linux dependencies:**
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Ubuntu/Debian
sudo apt update
sudo apt install -y make built-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev \
libffi-dev liblzma-dev
# CentOS/RHEL
sudo yum install gcc zlib-devel bzip2 bzip2-devel readline-devel \
sqlite sqlite-devel openssl-devel tk-devel libffi-devel xz-devel
```
### Version switching does not take effect
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 确保 pyenv in PATH 中
which pyenv
# 重新加载Configuration
source ~/.bashrc # 或 ~/.zshrc
# 重新generates shims
pyenv rehash
```
### Windows path issues
Make sure the environment variables are configured correctly, then restart the terminal.
## Comparison with other tools
| Tool | Characteristics | Suitable scenarios |
| - | - | - |
| **pyenv** | Multi-version management | Frequent switching between Python versions |
| **venv** | Built-in virtual environments | Simple project isolation |
| **conda** | Scientific computing environment | Data science and machine learning |
| **poetry** | Dependency management + packaging | Modern Python projects |
| **pipenv** | Pipfile-based management | Dependency locking |
## Best practices
1. **Set a local version for every project** to avoid global version conflicts.
2. **Use virtual environments** together with `pyenv-virtualenv`.
3. **Commit `.python-version`** when the team should use the same version.
4. **Update pyenv regularly** to get support for new versions.
5. **Record dependencies** with `requirements.txt` or `Pipfile`.
## Quick reference
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Common Commands速查
pyenv install --list # View可Installationversions
pyenv install 3.11.5 # Installationversions
pyenv versions # View已Installationversions
pyenv global 3.11.5 # 全局切换
pyenv local 3.11.5 # 项目切换
pyenv uninstall 3.11.5 # 卸载versions
pyenv rehash # 刷新 shims
pyenv which python # View python 路径
```
## References
* [Pyenv GitHub](https://github.com/pyenv/pyenv)
* [Pyenv-win GitHub](https://github.com/pyenv-win/pyenv-win)
* [Official Docs](https://github.com/pyenv/pyenv/wiki)
* [FAQ](https://github.com/pyenv/pyenv/wiki/Common-build-problems)
# Rclone
Source: https://base.bangwu.me/apps/Rclone
Rclone is a command-line tool for managing files on 40+ cloud storage services with a unified interface, supporting rsync-like sync, copy, and mount.
# Rclone
Rclone is a command-line tool for managing cloud storage files. It provides a unified interface for many providers, including object storage, enterprise and consumer file services, and standard transfer protocols. It follows Unix-style conventions and works well with common shell tools such as `rsync`, `cp`, `mv`, `mount`, `ls`, `ncdu`, `tree`, `rm`, and `cat`.
It is especially useful for tasks like synchronizing objects in a [CDN workflow](../env/CDN).
## Installation
Official download page: [https://rclone.org/downloads/](https://rclone.org/downloads/)
Follow the official installation guide. On Windows, adding Rclone to your `PATH` makes it much easier to use.
## Basic commands
| Command | Description |
| - | - |
| rclone config | Add, remove, or manage remotes |
| rclone config file | Show the path to the config file |
| rclone config show | Display the current config file contents |
```shell theme={"theme":{"light":"github-light","dark":"github-dark"}}
rclone [功能Option] [parameters] [parameters]
```
## Common operations
| Command | Description |
| - | - |
| rclone copy | Copy files |
| rclone move | Move files; add `--delete-empty-src-dirs` if you also want to remove empty source directories afterward |
| rclone sync | Sync the source directory to the target directory; only the target side is modified |
| rclone size | Show the total size used by a remote path |
| rclone delete | Delete file contents under a path |
| rclone purge | Delete a path and everything inside it |
| rclone mkdir | Create a directory |
| rclone rmdir | Remove a directory |
| rclone rmdirs | Remove empty directories in the given path; with `--leave-root`, the root directory is preserved |
| rclone check | Verify whether source and target data match |
| rclone ls | List all files with size and path |
| rclone lsl | Same as above, but also shows upload time |
| rclone lsd | List directories |
| rclone lsf | List both directories and files |
## Useful flags
| Command | Description |
| - | - |
| -n = –dry-run | Dry run mode; preview what Rclone would do |
| -P = –progress | Show live transfer progress, refreshed every 500 ms instead of once per minute |
| –cache-chunk-size 5M | Chunk size; larger values usually upload faster but use more memory |
| –onedrive-chunk-size 100M | Increase OneDrive upload speed on high-bandwidth servers |
| –drive-chunk-size 64M | Increase Google Drive upload speed on high-bandwidth servers |
| –cache-chunk-total-size SizeSuffix | Total local disk space that chunks may use |
| –transfers=N | Number of parallel file transfers; default is 4 |
| –config string | Specify a custom config file path |
| –ignore-errors | Continue when errors occur |
| –size-only | Validate only by file size, not by hash |
| –drive-server-side-across-configs | Use server-side transfer across configs when supported |
## Logs
Rclone supports four log levels: `ERROR`, `NOTICE`, `INFO`, and `DEBUG`.
By default, Rclone emits `ERROR` and `NOTICE` logs.
| Command | Description |
| - | - |
| -q | Output only `ERROR` messages |
| -v | Output `ERROR`, `NOTICE`, and `INFO` messages |
| -vv | Output `ERROR`, `NOTICE`, `INFO`, and `DEBUG` messages |
| –log-level LEVEL | Set the log level explicitly |
## Filtering
| Command | Description |
| - | - |
| –exclude | Exclude a file or directory |
| –include | Include a file or directory |
| –filter | Use filter rules; rules beginning with `+` include, and rules beginning with `-` exclude |
## Environment variables
Almost every `rclone` option can also be configured through environment variables. The variable name is derived from the long option name: remove the `--` prefix, replace `-` with `_`, convert to uppercase, and add the `RCLONE_` prefix.
Environment variables have lower priority than command-line flags. For example, if you set `RCLONE_MIN_SIZE=50` but run `rclone` with `--min-size 100`, the command-line value wins.
## Common environment variables
| Command | Description |
| - | - |
| RCLONE\_CONFIG | Custom config file path |
| RCLONE\_CONFIG\_PASS | Password used to decrypt an encrypted config file |
| RCLONE\_RETRIES | Number of retries after upload failure; default is 3 |
| RCLONE\_RETRIES\_SLEEP | Delay between retries; suffixes `s`, `m`, and `h` mean seconds, minutes, and hours |
| CLONE\_TRANSFERS | Number of parallel uploads |
| RCLONE\_CACHE\_CHUNK\_SIZE | Chunk size |
| RCLONE\_CACHE\_CHUNK\_TOTAL\_SIZE | Total local space available for chunks |
| RCLONE\_IGNORE\_ERRORS=true | Skip errors |
# Rye
Source: https://base.bangwu.me/apps/Rye
Rye is a next-gen Python package manager and virtual environment tool, compared with pyenv, pipenv, uv, and pdm for dependency management.
[Python package managers and virtual environments——V2EX](https://www.v2ex.com/t/1032069)
There are far too many Python environment management tools.

> Image source: [https://alpopkes.com/posts/python/packaging\_tools/](https://alpopkes.com/posts/python/packaging_tools/)
## Python version management
`pyenv`, `pipenv`
## Python package management
`pip`, `uv`, `pdm`
## Rye configuration
### VS Code cannot detect the interpreter path
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"python.defaultInterpreterPath": ".\\.venv\\Scripts\\python.exe"
}
```
```cmd theme={"theme":{"light":"github-light","dark":"github-dark"}}
rye config --set proxy.http=http://127.0.0.1:7890
rye config --set proxy.https=http://127.0.0.1:7890
```
Enable global shims:
```cmd theme={"theme":{"light":"github-light","dark":"github-dark"}}
rye config --set-bool behavior.global-python=true
```
Configure a PyPI mirror in [config.toml](https://rye.astral.sh/guide/config/#config-file):
```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Rye config.toml
[[sources]]
name = "default"
url = "https://pypi.org/simple/"
```
Set up Jupyter:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
rye add ipykernel
```
### My configuration
```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
[default]
toolchain = "cpython@3.13.2"
license = "MIT"
author = "bangwu "
[proxy]
https = "http://127.0.0.1:10808"
http = "http://127.0.0.1:10808"
[behavior]
global-python = true
autosync = true
use-uv = true
[[sources]]
name = "default"
url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
```
## Start a project
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
rye pin 3.x
rye init // 或者 rye init -p cpython@3.x [project name]
rye sync
rye add [package]
```
# Scoop
Source: https://base.bangwu.me/apps/Scoop
Scoop is a Windows command-line package manager like Homebrew, covering installation, aria2 acceleration, bucket management, and proxy setup.
# Scoop - Windows Homebrew
## Installation
## Configuration
Enable `aria2`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
scoop install aria2
scoop config aria2-warning-enabled false
```
Useful things to configure include buckets and proxy settings.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
❯ scoop config
last_update : 2025-03-26T10:11:34.7723777+08:00
gh_token : *****
global_path : C:\GlobalScoopApps
root_path : C:\Scoop
proxy : 127.0.0.1:10808
scoop_repo : https://github.com/ScoopInstaller/Scoop
scoop_branch : master
aria2-warning-enabled : False
```
### Backup
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
scoop export > app.json
scoop import > app.json
# backs up buckets and apps,excluding config
```
## Common apps
## Apps not found via Scoop
* [Leigod Accelerator](https://www.leigod.com/)
* [Dida365](https://dida365.com/)
* [Cisco Anyconnect](https://www.cisco.com/c/zh_cn/support/security/anyconnect-secure-mobility-client-v4-x/model.html#~tab-downloads)
* [Pure Live](https://github.com/liuchuancong/pure_live)
* [Huorong](https://huorong.cn)
* [WeChat Input Method](https://z.weixin.qq.com)
* [Jianguoyun](https://www.jianguoyun.com)
# ShareX
Source: https://base.bangwu.me/apps/ShareX
ShareX is an open-source screenshot and recording tool with automatic WebP compression via ffmpeg, covering action configuration and workflow.
# ShareX
ShareX is a very powerful open-source screenshot and sharing tool with lots of customization options. What I like most is that it can automatically compress screenshots to WebP format, which reduces image size significantly.
Software structure:

Download page: [https://github.com/ShareX/ShareX/releases/tag/v16.0.1](https://github.com/ShareX/ShareX/releases/tag/v16.0.1)
I recommend downloading the portable version because it includes `ffmpeg` and can be used for compression directly.
Then create a new action in the ShareX action settings:

* name: anything
* file path: the installation path of `ffmpeg`, pointing directly to the executable
* parameters: `-i "$input" -q 75 "$output"` where `-q 75` means 75% quality compression
* output file extension: webp
* extension filter: png
* enable the options below for **hide window** and **delete input file**
Then enable `execute action` in the screenshot task settings.

# Typora
Source: https://base.bangwu.me/apps/Typora
Typora is a WYSIWYG Markdown editor that renders as you type, with support for tables, code blocks, and LaTeX formulas for document writing.
When writing Markdown documents, coding raw syntax can be tedious. Why not write in a rendered view like Word? That's where rich text editors come in. Among all Markdown editors, Typora is the most acclaimed.
## Installation
> [tab] Cloud Drive
>
> Link: [https://www.123pan.com/s/HQeA-UX1Sh](https://www.123pan.com/s/HQeA-UX1Sh)
>
> Download any version's `.7z` file, extract and apply the patch. But if you can afford it, please support the official version.
> [tab] Official
>
> Official site: [https://typora.io/](https://typora.io/)
# Warp
Source: https://base.bangwu.me/apps/Warp
Warp is a Rust-based terminal emulator now open-sourced under AGPL, featuring AI command search, collaborative workflows, and an agent-centric coding platform.
# Warp
Warp is a modern terminal emulator built in Rust, now open-sourced under **AGPL license** (April 2026). It combines a terminal with AI-powered command search, block-based output, and an agent-centric coding collaboration platform called **Oz**.

## Key Features
* **Block-based output** — Commands and their output are grouped into editable blocks, not raw text streams
* **AI command search** — Describe what you want in natural language, Warp suggests the right command
* **Command history with context** — Search past commands by what they did, not just the raw string
* **Collaborative workflows** — Share command blocks and sessions with teammates
* **Oz agent platform** — Cloud-based agent orchestration where AI handles coding, planning, and testing while humans focus on direction and review
## Installation
### macOS
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
brew install --cask warp
```
### Linux
Download from [Warp releases](https://github.com/warpdotdev/warp/releases) or:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# From the official site
curl -fsSL https://app.warp.dev/get | sh
```
> [!TIP]
>
> Warp is now open-source (AGPL). You can build from source at [github.com/warpdotdev/warp](https://github.com/warpdotdev/warp). OpenAI is the founding sponsor of the open-source release; the Oz workflow uses GPT-5.5.
## Warp vs Traditional Terminals
| Feature | Warp | iTerm2 / Alacritty / Ghostty |
| - | - | - |
| Output display | Editable blocks | Raw text stream |
| Command search | AI-powered natural language | Text regex search |
| Collaboration | Share blocks, sessions | No built-in sharing |
| Agent integration | Oz platform (cloud) | None |
| Rendering | Rust GPU-accelerated | Rust (Alacritty/Ghostty) / Swift (iTerm2) |
| License | AGPL (open-source) | Various |
> [!NOTE]
>
> If you prefer a minimalist, GPU-accelerated terminal without AI features, [Ghostty](https://ghostty.org) and [Alacritty](https://alacritty.org) are strong alternatives. Ghostty is also Rust-based and offers fast rendering with a simpler feature set.
## Oz Agent Platform
Warp's agent-centric workflow uses **Oz** — a cloud orchestration platform where:
1. **Agent handles heavy work** — coding, planning, testing, running commands
2. **Human focuses on direction** — reviewing, validating, steering priorities
3. **Blocks are shared** — both agent and human see the same terminal session
This model treats the terminal as a shared workspace rather than a solo tool.
## Other Terminal Emulators Worth Knowing
* **Ghostty** — Rust-based, fast, minimalist. Created by Mitchell Hashimoto (Vagrant/Terraform). Recently announced leaving GitHub due to reliability concerns.
* **Alacritty** — Rust-based, GPU-accelerated, minimal config. No AI features.
* **iTerm2** — macOS-native, feature-rich, long-established. Swift-based.
## References
* [Warp GitHub](https://github.com/warpdotdev/warp)
* [Warp Official Site](https://www.warp.dev/)
* [Warp open-source announcement](https://x.com/warpdotdev) — April 2026, AGPL license
# Xizhi
Source: https://base.bangwu.me/apps/Xizhi
Notification push services including Server酱 for WeChat alerts, with API setup, Python requests integration, and Markdown message delivery.
# Message push services
Message push services deliver notifications, alerts, and other information to different devices in real time. They are commonly used for monitoring alerts, scheduled reminders, and system notifications.
## ServerChan
[ServerChan](https://sct.ftqq.com/) is a free WeChat notification service.
### Features
* 📱 Pushes to WeChat
* 🆓 Generous free quota
* 🔧 Simple to use
* 📊 Supports Markdown
### Usage
1. Visit the [ServerChan website](https://sct.ftqq.com/) and sign in.
2. Bind your WeChat account by scanning the QR code.
3. Get your `SendKey`.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
def send_wechat(title, content):
sendkey = "YOUR_SENDKEY"
url = f"https://sctapi.ftqq.com/{sendkey}.send"
data = {
"title": title,
"desp": content
}
response = requests.post(url, data=data)
return response.json()
# 使用
send_wechat("Testingtitle", "这isTesting内容\nsupports **Markdown**")
```
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# curl 方式
curl -X POST "https://sctapi.ftqq.com/YOUR_SENDKEY.send" \
-d "title=Testingtitle" \
-d "desp=Testing内容"
```
### Use cases
* Server monitoring alerts
* Scheduled task notifications
* Spider completion reminders
* CI/CD build notifications
## Bark
[Bark](https://github.com/Finb/Bark) is an open-source iOS push notification app.
### Features
* 📱 iOS only
* 🔓 Free and open-source
* 🔔 Supports custom sounds
* 🎨 Supports icons and grouping
* 🔐 End-to-end encryption
### Installation
Search for Bark in the App Store and install it.
### Usage
After getting the push address:
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
def send_bark(title, content):
url = "https://api.day.app/YOUR_KEY/"
data = {
"title": title,
"body": content,
"sound": "alarm", # 铃声
"icon": "https://example.com/icon.png", # Icons
"group": "test" # Grouping
}
response = requests.post(url, json=data)
return response.json()
# 使用
send_bark("Testingtitle", "这isTesting内容")
```
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# GET 方式
curl "https://api.day.app/YOUR_KEY/title/内容"
# POST 方式
curl -X POST "https://api.day.app/YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"title":"title","body":"内容","sound":"alarm"}'
```
### Advanced features
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# with redirect link
send_bark("点击跳转", "内容", url="https://example.com")
# auto-copy content
send_bark("自动复制", "需要复制's 内容", automaticallyCopy=1)
# 时效性Notification
send_bark("重要Notification", "内容", level="timeSensitive")
```
## [Telegram Bot](https://core.telegram.org/bots)
The Telegram Bot API is a powerful way to send notifications.
### Create a bot
1. Search for `@BotFather` in Telegram.
2. Send `/newbot` to create a bot.
3. Get the bot token.
4. Send `/getid` to `@userinfobot` to get your chat ID.
### Usage
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
class TelegramBot:
def __init__(self, token, chat_id):
self.token = token
self.chat_id = chat_id
self.api_url = f"https://api.telegram.org/bot{token}"
def send_message(self, text, parse_mode="Markdown"):
url = f"{self.api_url}/sendMessage"
data = {
"chat_id": self.chat_id,
"text": text,
"parse_mode": parse_mode
}
return requests.post(url, json=data).json()
def send_photo(self, photo_url, caption=""):
url = f"{self.api_url}/sendPhoto"
data = {
"chat_id": self.chat_id,
"photo": photo_url,
"caption": caption
}
return requests.post(url, json=data).json()
def send_document(self, file_path):
url = f"{self.api_url}/sendDocument"
with open(file_path, 'rb') as f:
files = {'document': f}
data = {'chat_id': self.chat_id}
return requests.post(url, data=data, files=files).json()
# 使用
bot = TelegramBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID")
bot.send_message("**粗体** _斜体_ `代码`")
```
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# curl 方式
curl -X POST "https://api.telegram.org/botYOUR_BOT_TOKEN/sendMessage" \
-d "chat_id=YOUR_CHAT_ID" \
-d "text=Hello World"
```
### Advanced features
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# send带Button's Message
def send_with_buttons(bot, text, buttons):
url = f"{bot.api_url}/sendMessage"
keyboard = {
"inline_keyboard": [
[{"text": btn["text"], "url": btn["url"]} for btn in row]
for row in buttons
]
}
data = {
"chat_id": bot.chat_id,
"text": text,
"reply_markup": keyboard
}
return requests.post(url, json=data).json()
# 使用
buttons = [
[{"text": "Visit网站", "url": "https://example.com"}],
[{"text": "GitHub", "url": "https://github.com"}]
]
send_with_buttons(bot, "选择aOperation:", buttons)
```
## [Xizhi](https://xz.qqoq.net)
Xizhi is an aggregated push platform that supports multiple notification channels.
### Features
* 🔗 Aggregates multiple push methods
* 📱 Supports iOS, Android, and Web
* 🆓 Free to use
* 🔔 Supports different message types
### Supported push methods
* iOS/Android app
* WeCom
* DingTalk
* Feishu
* Email
* Webhook
### Usage
1. Register and create an app.
2. Get the push URL.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
def send_xizhi(title, content, url=""):
api_url = "YOUR_XIZHI_URL"
data = {
"title": title,
"content": content,
"url": url
}
response = requests.post(api_url, json=data)
return response.json()
# 使用
send_xizhi(
"Notificationtitle",
"Notification内容",
"https://example.com"
)
```
## Comparison
| Service | Platform | Free | Strength | Suitable scenarios |
| - | - | - | - | - |
| **ServerChan** | WeChat | ✅ | Simple and convenient | Domestic users, WeChat notifications |
| **Bark** | iOS | ✅ | Open-source and privacy-friendly | iOS users |
| **Telegram** | Cross-platform | ✅ | Very powerful | International users who can access Telegram |
| **Xizhi** | Cross-platform | ✅ | Multi-channel aggregation | Enterprise or multi-channel use |
## Comprehensive example
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class NotificationManager:
"""统一's MessagePush管理器"""
def __init__(self):
self.server_chan_key = "YOUR_SENDKEY"
self.bark_url = "https://api.day.app/YOUR_KEY"
self.telegram_bot = TelegramBot("TOKEN", "CHAT_ID")
def send(self, title, content, channels=None):
"""Send to Multiple Channels"""
if channels is None:
channels = ['all']
results = {}
if 'all' in channels or 'wechat' in channels:
results['wechat'] = self._send_wechat(title, content)
if 'all' in channels or 'bark' in channels:
results['bark'] = self._send_bark(title, content)
if 'all' in channels or 'telegram' in channels:
results['telegram'] = self._send_telegram(title, content)
return results
def _send_wechat(self, title, content):
url = f"https://sctapi.ftqq.com/{self.server_chan_key}.send"
return requests.post(url, data={"title": title, "desp": content})
def _send_bark(self, title, content):
return requests.post(self.bark_url, json={"title": title, "body": content})
def _send_telegram(self, title, content):
return self.telegram_bot.send_message(f"*{title}*\n\n{content}")
# 使用
notifier = NotificationManager()
notifier.send("系统告警", "CPU 使用率超过 90%", channels=['wechat', 'telegram'])
```
## Best practices
1. **Choose the right service** for your audience and scenario.
2. **Handle exceptions** because push requests can fail.
3. **Respect rate limits** to avoid notification spam.
4. **Avoid sending sensitive information** whenever possible.
5. **Use multi-channel backup** for important alerts.
6. **Separate regular notifications from urgent alerts**.
## Use cases
* 📊 **Monitoring alerts**: servers and application performance
* ⏰ **Scheduled reminders**: daily reports and timed tasks
* 🔔 **Event notifications**: user registration or order changes
* 🐛 **Error reporting**: exceptions and bug alerts
* 📈 **Data reports**: daily or weekly summaries
* 🤖 **Automation notifications**: CI/CD and spider completion
## References
* [ServerChan documentation](https://sct.ftqq.com/sendkey)
* [Bark GitHub](https://github.com/Finb/Bark)
* [Telegram Bot API](https://core.telegram.org/bots/api)
* [Xizhi website](https://xz.qqoq.net)
# baoyu-design
Source: https://base.bangwu.me/apps/baoyu-design
Run a Claude Design-style local agent skill for UI mockups, prototypes, design systems, Figma imports, and self-contained HTML design artifacts.
# baoyu-design
[baoyu-design](https://github.com/JimLiu/baoyu-design) packages a Claude Design-style workflow as a local Agent Skill. Instead of uploading prompts to a design website, you let a file-capable coding agent such as Cursor, Claude Code, or Codex generate design artifacts inside your own project.
The durable idea is not "another AI design demo". It is a pattern for turning design work into an agent-native local workflow:
* the agent reads a reusable design skill
* output lands in `designs//`
* deliverables are self-contained HTML
* preview happens on `localhost`
* you iterate visually by pointing at the preview and asking for changes
## When it helps
Use it when you want fast visual artifacts without leaving your repo:
* high-fidelity UI mockups
* interactive prototypes
* landing pages and dashboards
* mobile or desktop app concepts
* slide decks and visual explainers
* design-system previews and component showcases
It fits early product exploration especially well. The artifact is plain HTML, so you can version it, fork it, attach it to an issue, or hand it to another agent for implementation.
## Install
The README recommends the `skills` CLI:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx skills add JimLiu/baoyu-design
```
Useful variants:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx skills add JimLiu/baoyu-design -g
npx skills add JimLiu/baoyu-design --agent claude-code
npx skills add JimLiu/baoyu-design --agent cursor
npx skills add JimLiu/baoyu-design --agent codex
npx skills add JimLiu/baoyu-design --list
```
For Claude Code, the install target is typically `.claude/skills/`. For Cursor and Codex-style agents, it is typically `.agents/skills/`.
## Workflow
A practical flow looks like this:
1. Install the skill in the project.
2. Ask the agent for one specific design task.
3. Provide real context: screenshots, product copy, an existing repo, or a Figma `.fig` export.
4. Let the agent generate HTML under `designs/`.
5. Open the local preview and point to elements that need changes.
6. Commit useful artifacts or hand them off to frontend implementation.
The second-pass loop is the important part. You do not need to rewrite a long prompt for every tweak. You can say "make this card denser" or "move this CTA above the fold" while the agent edits the source behind the preview.
## Design systems and Figma imports
The skill can work beyond one-off mockups. It supports design-system workflows such as:
* creating a local design system
* selecting a design system when starting a new project
* previewing components as self-contained HTML
* importing a Figma `.fig` file offline
* extracting components, variables, assets, and token CSS from imported design context
This is useful when you want the agent to respect an existing visual language instead of inventing every screen from scratch.
## What to watch
Treat the output as a design artifact, not production code by default.
* Review accessibility, responsive behavior, and interaction states manually.
* Keep imported brand assets and fonts under the right license.
* Prefer small scoped design requests over "design the whole app" prompts.
* Save good outputs, but do not blindly ship generated HTML as application code.
## References
* [Folo source: baoyu-design skill update](https://x.com/dotey/status/2064959133535658144)
* [JimLiu/baoyu-design](https://github.com/JimLiu/baoyu-design)
# iTab
Source: https://base.bangwu.me/apps/iTab
iTab is a browser new-tab page service with visual navigation cards organized by workflow, available as a Chrome/Edge extension and web app.
[iTab](https://www.itab.link/) is a browser start page service with extensions and web access, supporting both PC and mobile — designed to free up your browser bookmarks.

# Software Tools
Source: https://base.bangwu.me/apps/index
Curated software recommendations with configuration guides covering API tools, screen sharing, AI editors, package managers, and screenshot tools.
Inspired by [pseudoyu](https://tools.pseudoyu.com/), I share the software I use daily — desktop apps, browser extensions, and more — with detailed configurations and purposes.
> [card] [Apifox](/apps/Apifox)
>
> All-in-one API design, development, and testing platform.
> [card] [Barrier](/apps/Barrier)
>
> Cross-device keyboard/mouse sharing.
> [card] [CherryStudio](/apps/CherryStudio)
>
> AI client with theme customization.
> [card] [Cursor](/apps/Cursor)
>
> AI-powered code editor.
> [card] [Browser Harness](/apps/BrowserHarness)
>
> Thin browser control layer for coding agents.
> [card] [baoyu-design](/apps/baoyu-design)
>
> Local Agent Skill for UI mockups and design systems.
> [card] [Pyenv](/apps/Pyenv)
>
> Python version manager.
> [card] [Rclone](/apps/Rclone)
>
> Cloud storage sync and file management.
> [card] [Rye](/apps/Rye)
>
> Next-gen Python package manager.
> [card] [Scoop](/apps/Scoop)
>
> Windows command-line package manager.
> [card] [ShareX](/apps/ShareX)
>
> Open-source screenshot tool with auto-compression.
> [card] [Typora](/apps/Typora)
>
> Recommended Markdown editor.
> [card] [Xizhi](/apps/Xizhi)
>
> Multi-channel notification push service.
> [card] [iTab](/apps/iTab)
>
> Browser start page service.
> [card] [Starship](/apps/starship)
>
> Cross-shell terminal prompt customization.
> [card] [Warp](/apps/Warp)
>
> Rust-based terminal with AI command search, now open-source (AGPL).
> [card] [WeChat Reading](/apps/weread)
>
> WeChat Reading notes and workflows.
# Starship
Source: https://base.bangwu.me/apps/starship
Starship is a cross-shell terminal prompt tool supporting PowerShell, Bash, and Zsh, with Scoop installation and profile configuration guide.
# Command line prompt tools
## oh my zsh
## oh my posh
PowerShell completion is the only part that still feels awkward to use.
## [starship](https://starship.rs/guide/)

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
scoop install starship
starship config command_timeout 3600 //解决超时Issue https://github.com/starship/starship/issues/5985
```
### Configure PowerShell
Run `$PROFILE` in PowerShell to find the config file path, usually `C:\Users\\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1`, and add the following line:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
Invoke-Expression (&starship init powershell)
```
I use the [Bracketed Segments](https://starship.rs/zh-CN/presets/bracketed-segments) preset. You can browse other themes on the [Starship presets](https://starship.rs/presets/) page. Some presets require a [Nerd Font](https://www.nerdfonts.com/).
### Configure `cmd`
Starship uses [clink](https://chrisant996.github.io/clink/) to configure `cmd`.
> \[!note]
> If you install clink with Scoop, command highlighting may not work. The likely reason is that the Scoop package does not include the `Enhanced default settings` feature, which is what enables syntax highlighting. If you need it, downloading clink directly from the [GitHub Releases](https://github.com/chrisant996/clink/releases) page is the safer choice.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
code %LocalAppData%\clink\starship.lua
写入
load(io.popen('starship init cmd'):read("*a"))()
```
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
clink autorun install
clink set prompt.transient always
```
# WeChat Reading
Source: https://base.bangwu.me/apps/weread
WeChat Reading's official AI Skill turns your reading history into data you can query, analyze, and export — connecting your bookshelf to AI coding agents and personal knowledge management.
# WeChat Reading
WeChat Reading (微信读书) is Tencent's e-reading platform, popular among Chinese readers. In 2026, it launched an official **Skill** that lets AI coding agents access your reading data: bookshelf, notes, highlights, reading time, and preference analysis.
## What the Skill unlocks
Instead of waiting for an annual reading report, you can ask an AI agent to analyze your reading history on demand:
* **Reading reports**: Generate personalized analysis of reading time distribution, genre preferences, author patterns, and weekly/monthly rhythms.
* **Book reviews**: Pull all your highlights and notes from a finished book, and generate a structured review.
* **Knowledge cards**: Extract key ideas from your highlights and format them as shareable cards with original quotes.
* **Obsidian export**: Convert a book's highlights and thoughts into an Obsidian-formatted note with frontmatter, tags, and chapter organization.
* **Bookshelf Q\&A**: Ask questions like "What should I read next based on my history?" or "What themes have I been exploring recently?"
## The pipeline
The Skill bridges three tools into a reading-to-knowledge pipeline:
```
微信读书 (data source) → AI agent (data pull + processing) → Obsidian (local knowledge base)
```
What this enables:
* Auto-generate one note file per book
* AI auto-tagging and bidirectional links
* Topic-based MOC (Map of Content) index pages
* Incremental merge of new highlights into existing notes
## Supported agents
The Skill works with:
* **Qwen Code** (recommended by most users)
* **Claude Code**
* **Cursor**
* Any agent that supports Skill installation
Qwen Code is preferred because it runs in the terminal, can write files and run scripts directly — one command generates an Obsidian note or visualization report.
## Setup
1. Install a supported coding agent (e.g. [Qwen Code](https://qwenlm.github.io/qwen-code-docs/zh/users/overview/))
2. Get your WeChat Reading API key from [weread.qq.com](https://weread.qq.com/r/weread-skills)
Then tell your agent:
```
下载 https://cdn.weread.qq.com/skills/weread-skills.zip 安装 skill,我的 API 是 wrk-xxxx
```
Optionally add: `帮我配置好环境,记住 API,让我之后不需要再配置` to persist the API key.
Once installed, verify with:
```
/skills weread-skills 我最近在读什么?
```
## Example use cases
**Explore reading patterns:**
```
/skills weread-skills 根据我的阅读偏好,推荐接下来读哪些书
```
**Review highlights from a specific book:**
```
/skills weread-skills 看看我在《空洞的心》里的笔记,随机选 3 条
```
**Generate a book review:**
```
/skills weread-skills 我刚读完《绿灯》,结合我在这本书里的 35 条笔记,帮我写一篇 500 字的短书评
```
**Export to Obsidian:**
```
/skills weread-skills 把我在《纷乱的心灵》里的划线和想法,整理成一篇 Obsidian 格式的读书笔记,保存到当前目录
```
**Find material for writing:**
```
/skills weread-skills 我想写一篇关于「成瘾与自我认知」的文章,从我的笔记里找出所有相关的划线和想法
```
## Community Skills
Beyond the official Skill, community members have built additional tools. For example, [Yao's Weread Skill](https://github.com/yaojingang/yao-open-skills/tree/main/skills/yao-weread-skill) generates detailed visual reading reports with charts and analytics.
Install it with:
```
帮我安装这个技能:https://github.com/yaojingang/yao-open-skills/tree/main/skills/yao-weread-skill
```
Then run:
```
/skills yao-weread-skill 帮我生成我的阅读报告
```
## References
* [年度报告不够看?微信读书 Skill 上手体验](https://sspai.com/post/109932) — 少数派 detailed walkthrough
* [微信读书 Skill 官方页面](https://weread.qq.com/r/weread-skills)
* [Yao's Weread Skill](https://github.com/yaojingang/yao-open-skills/tree/main/skills/yao-weread-skill) — community reading report generator
# Go Gin
Source: https://base.bangwu.me/backend/Go/gin/index
Go Gin is the most popular web framework for Go, covering router setup, GET/POST handlers, JSON responses, and HTTP server startup basics.
# Go gin
gin is the most widely-used go web Framework
## ginServer
```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
router.Run()
```
# Go
Source: https://base.bangwu.me/backend/Go/index
Go language learning path from a Python background, covering A Tour of Go basics, GoFrame exploration, and Gin + Gorm backend development.

# Why Go
My first programming language was Python — undeniably convenient and powerful, but lacking in performance. For frequently-used tools and concurrent demands, I eventually chose to learn a high-performance language.
Go is friendly for Python learners to pick up, which is why I chose it.
> Learning path (for reference only):
1. [A Tour of Go](https://tour.go-zh.org/welcome/1) + [Bilibili video](https://www.bilibili.com/video/BV1ae41157o9) for basics
2. GoFrame trial (abandoned later — too comprehensive)
3. Gin + Gorm to build backend
4. To be continued…
> [card] [Gin Framework](/backend/Go/gin/index)
>
> Go's most popular web framework for building API services.
> [card] [Listeners and MPTCP](/backend/Go/mptcp)
>
> Go 1.24+ servers accept MPTCP by default on Linux. Check and turn it off.
# Go listeners and MPTCP
Source: https://base.bangwu.me/backend/Go/mptcp
Since Go 1.24, net.Listen on Linux opens Multipath TCP listeners by default. Check which services expose MPTCP, turn it off per program or system-wide, and why the kernel patch is still the real fix.
# Go listeners and MPTCP
Since Go 1.24, `net.ListenConfig` uses **Multipath TCP (MPTCP)** by default on Linux whenever the kernel supports it. `net.Listen("tcp", ...)` goes through `ListenConfig`, so ordinary servers such as `http.ListenAndServe` accept MPTCP connections without any code change. Clients still connect over plain TCP unless you opt in.
The default also follows the `go` line in the main module's `go.mod`. A module that declares `go 1.23` or earlier keeps the old behavior (no MPTCP unless requested), even when built with a newer toolchain.
MPTCP lets one connection use several network paths, for example Wi-Fi and cellular together. Most clients never use it, so you won't notice it in normal operation. It still adds attack surface: the listening socket goes through a different kernel code path, and a kernel bug in that path is reachable from the network.
## Case study: CVE-2026-98432
> [!NOTE]
>
> The facts in this section were current as of November 1, 2026. Follow your distribution's advisory for fixed kernel versions.
* **The bug.** A race-condition use-after-free in the Linux kernel's IPv4 TCP connection-request handling (`ipv4: free inet_opt and ireq_opt after an RCU grace period`). Red Hat rates it Critical: a remote, unauthenticated attacker can trigger it, it affects any vulnerable kernel with IPv4 TCP enabled, and systems that accept inbound TCP connections are the most directly exposed.
* **The exploit.** Anthropic's proof of concept got a root shell on a server with an **MPTCP listener**, with no credentials and no user interaction. A lost race only fails that one handshake and doesn't crash the machine, so the attacker can keep retrying. The PoC needed about 48 minutes to leak a kernel address and another 5 minutes to run a command as root.
* **Why Go servers were in the spotlight.** Xray-core's maintainers pointed out that for most of their users, the only programs serving MPTCP on the host are Go proxy servers built with Go 1.24 or later. Xray-core shipped an emergency release that turns MPTCP off by default. Caddy and other Go servers were named in the same discussion.
* **The Go team's position.** Upgrade the kernel. The underlying bug is not specific to MPTCP, so systems without MPTCP listeners may be vulnerable to similar attacks. Turning MPTCP off program by program is fragile: one forgotten listener leaves the host exposed. The team decided not to change Go's default for now.
## Durable lessons
* **Runtime defaults change your kernel attack surface.** A toolchain upgrade can change which kernel code paths your server exposes, even if you never touch your code. Read the networking and GODEBUG sections of release notes as security notes.
* **List listeners by protocol, not just by port.** `ss -lnt` shows a port as listening. It doesn't show whether that port also accepts MPTCP.
* **App-level switches reduce exposure; patching fixes the bug.** Turn MPTCP off where you don't need it, but treat that as temporary mitigation until the patched kernel is running.
## Check what you expose
List MPTCP listening sockets and the processes behind them:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo ss -Mlnp
```
Check whether the kernel allows MPTCP sockets in the current network namespace (`1` means enabled):
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sysctl net.mptcp.enabled
```
Check which Go version built a binary and the GODEBUG defaults built into a main package:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
go version -m ./server
go list -f '{{.DefaultGODEBUG}}' ./cmd/server
```
`go list` only prints settings that differ from the toolchain's defaults. With a Go 1.24 or later toolchain, an empty result means listeners use MPTCP; `multipathtcp=0` in the output means they don't.
## Turn MPTCP off
Pick the narrowest layer that covers every listener you run.
| Scope | How | When it applies |
| - | - | - |
| One process | `GODEBUG=multipathtcp=0` in the service environment | At process start; restart the service |
| One build | `godebug multipathtcp=0` in the main module's `go.mod`, or `//go:debug multipathtcp=0` above `package main` | Next build |
| One socket | `lc.SetMultipathTCP(false)` on a `net.ListenConfig` | Overrides GODEBUG for that listener |
| Whole host or namespace | `sysctl -w net.mptcp.enabled=0` | New sockets only; restart services so existing listeners are recreated |
Per-socket example:
```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
lc := net.ListenConfig{}
lc.SetMultipathTCP(false) // plain TCP, regardless of GODEBUG
ln, err := lc.Listen(ctx, "tcp", ":8080")
```
For a systemd service, set the environment variable in a drop-in file:
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
# /etc/systemd/system/myapp.service.d/no-mptcp.conf
[Service]
Environment=GODEBUG=multipathtcp=0
```
`GODEBUG` takes a comma-separated list. If the service already sets `GODEBUG`, add `multipathtcp=0` to the existing value instead of replacing it.
The `multipathtcp` values are `0` (off), `1` (dialers and listeners), `2` (listeners only, the Go 1.24 default), and `3` (dialers only).
The host-wide sysctl is safe for Go programs. When creating the MPTCP socket fails, Go falls back to plain TCP. Persist it in `/etc/sysctl.d/` if you want it to survive a reboot, and confirm that nothing on the host actually needs MPTCP.
After any change, run `sudo ss -Mlnp` again and confirm the listener is gone from the list.
## Fix the kernel
1. Install your distribution's patched kernel and reboot into it. Check that `uname -r` reports the new version.
2. If you can't patch right away, follow your vendor's interim mitigation. Red Hat published an nftables rule that drops inbound IPv4 TCP packets carrying IP options. Red Hat expects ordinary application traffic to be unaffected, but test the rule first, and remove it after patching. It reduces exposure; it does not fully prevent exploitation.
3. Remember that containers share the host kernel. Patching an image does nothing; patch the node.
## References
* [Folo source: Geek on the Xray-core emergency update](https://x.com/geekbb/status/2116526532881744310)
* [Go 1.24 release notes: `net.ListenConfig` uses MPTCP by default](https://go.dev/doc/go1.24)
* [Go docs: GODEBUG history and `multipathtcp` values](https://go.dev/doc/godebug)
* [Go Security Team: Protecting against CVE-2026-98432 (via oss-security)](https://www.openwall.com/lists/oss-security/2026/10/30/1)
* [Go source: MPTCP listener fallback to TCP](https://go.dev/src/net/mptcpsock_linux.go)
* [NVD: CVE-2026-98432](https://nvd.nist.gov/vuln/detail/cve-2026-98432)
* [Red Hat: RHSB-2026-016 and nftables mitigation](https://access.redhat.com/security/vulnerabilities/RHSB-2026-016)
* [Anthropic: Discovering and exploiting vulnerabilities with Claude](https://www.anthropic.com/research/discovering-vulnerabilities-with-claude)
* [XTLS/Xray-core #7291: disable MPTCP by default](https://github.com/XTLS/Xray-core/pull/7291)
* [Linux kernel docs: MPTCP sysctl `enabled`](https://docs.kernel.org/networking/mptcp-sysctl.html)
* [ss(8): `-M, --mptcp`](https://man7.org/linux/man-pages/man8/ss.8.html)
# FastAPI
Source: https://base.bangwu.me/backend/Python/fastapi
FastAPI is a modern, high-performance Python web framework with automatic API docs, async support, Pydantic type validation, and dependency injection.
# FastAPI
FastAPI is a modern, high-performance Python web framework built on Python 3.6+ type hints. With over 70k+ stars on GitHub, it's one of the most popular Python backend frameworks today.
## Core Features
* **High Performance**: Performance comparable to Node.js and Go
* **Fast Development**: Improves development efficiency 200%-300%
* **Auto Docs**: Automatically generates interactive API documentation
* **Type Checking**: Pydantic-based data validation
* **Async Support**: Native async/await support
## Quick Start
### Installation
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install fastapi
pip install "uvicorn[standard]"
```
### Hello World
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
### Running
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
uvicorn main:app --reload
```
Visit [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) to see the auto-generated API documentation.
## Path & Query Parameters
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from typing import Optional
@app.get("/users/{user_id}")
async def read_user(
user_id: int,
skip: int = 0,
limit: int = 10,
q: Optional[str] = None
):
return {"user_id": user_id, "skip": skip, "limit": limit, "q": q}
```
## Request Body
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.post("/items/")
async def create_item(item: Item):
return item
```
## Response Model
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class UserOut(BaseModel):
username: str
email: str
@app.post("/users/", response_model=UserOut)
async def create_user(user: User):
return user # Automatically filters sensitive fields
```
## Dependency Injection
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi import Depends
def get_db():
db = Database()
try:
yield db
finally:
db.close()
@app.get("/users/")
async def read_users(db = Depends(get_db)):
return db.query_users()
```
## Middleware
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
```
## Database Integration
### SQLAlchemy
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
```
## Authentication & Authorization
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
```
## File Upload
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi import File, UploadFile
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
```
## Background Tasks
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi import BackgroundTasks
def send_email(email: str):
# Send email logic
pass
@app.post("/send-notification/")
async def send_notification(
email: str,
background_tasks: BackgroundTasks
):
background_tasks.add_task(send_email, email)
return {"message": "Email will be sent"}
```
## Resources
* Official Docs: [https://fastapi.tiangolo.com/](https://fastapi.tiangolo.com/)
* Chinese Docs: [https://fastapi.tiangolo.com/zh/](https://fastapi.tiangolo.com/zh/)
* GitHub: [https://github.com/tiangolo/fastapi](https://github.com/tiangolo/fastapi)
# Python
Source: https://base.bangwu.me/backend/Python/index
Python backend development hub covering FastAPI framework, web scraping with requests and BeautifulSoup, and popular third-party libraries.

Python is a concise and elegant programming language widely used in web development, data analysis, and AI.
## Backend Frameworks
### FastAPI
A modern, high-performance Python web framework with async support and auto-generated API docs.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
```
> [card] [FastAPI Details](/backend/Python/fastapi)
>
> Route params, request bodies, dependency injection, middleware, and auth.
### Flask
A lightweight web framework for quick prototyping of small applications.
### Django
A full-stack web framework with built-in ORM, admin panel, and more.
## Web Scraping
> [card] [Scraping Guide](/backend/Python/spider/index)
>
> From basics to advanced techniques, anti-scraping strategies and real cases.
## Popular Libraries
> [card] [Library Index](/backend/Python/libs/index)
>
> Notes on httpx, matplotlib, wordcloud, PyTorch, and more.
## Resources
* [Python Official Docs](https://docs.python.org/3/)
* [PyPI Package Index](https://pypi.org/)
# PyTorch
Source: https://base.bangwu.me/backend/Python/libs/PyTorch
PyTorch deep learning framework guide covering CPU and GPU installation, tensor creation and operations, automatic differentiation, and neural network basics.
# PyTorch
PyTorch is an open-source deep learning framework developed by Facebook AI Research and widely used in both academic research and industry.
## Installation
### Automatic installation
Choose the right command from the official website: [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# CPU 版本
pip install torch torchvision torchaudio
# GPU 版本 (CUDA 12.4)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
```
### Manual GPU installation
Download page: [https://download.pytorch.org/whl/torch/](https://download.pytorch.org/whl/torch/)
You need to download three packages, making sure the Python and CUDA versions match:
* `torch-2.4.1+cu124-cp312-cp312-win_amd64.whl`
* `torchvision-0.19.1+cu124-cp312-cp312-win_amd64.whl`
* `torchaudio-2.4.1+cu124-cp312-cp312-win_amd64.whl`
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install torch-2.4.1+cu124-cp312-cp312-win_amd64.whl
pip install torchvision-0.19.1+cu124-cp312-cp312-win_amd64.whl
pip install torchaudio-2.4.1+cu124-cp312-cp312-win_amd64.whl
```
### Verify the installation
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import torch
print(torch.__version__)
print(torch.cuda.is_available()) # True 表示 GPU 可用
print(torch.cuda.get_device_name(0)) # 显示 GPU Name
```
## Basic concepts
### Tensors
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import torch
# 创建张量
x = torch.tensor([1, 2, 3])
y = torch.zeros(2, 3)
z = torch.randn(2, 3)
# 张量运算
a = torch.tensor([1.0, 2.0])
b = torch.tensor([3.0, 4.0])
c = a + b
d = torch.matmul(a, b) # 矩阵乘法
# GPU 加速
if torch.cuda.is_available():
x = x.cuda() # 转移到 GPU
# 或者
x = x.to('cuda')
```
### Automatic differentiation
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 需要梯度's 张量
x = torch.tensor([1.0, 2.0], requires_grad=True)
y = x ** 2
z = y.sum()
# 反向传播
z.backward()
print(x.grad) # 梯度: [2.0, 4.0]
```
## Building neural networks
### Simple model
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 10)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
model = SimpleNet()
```
### Convolutional neural network
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(2)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.maxpool(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
```
## Training a model
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import torch.optim as optim
# 准备数据
train_loader = torch.utils.data.DataLoader(dataset, batch_size=64)
# 定义模型、损失函数、优化器
model = SimpleNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练循环
for epoch in range(10):
for batch_idx, (data, target) in enumerate(train_loader):
# 前向传播
output = model(data)
loss = criterion(output, target)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print(f'Epoch: {epoch}, Loss: {loss.item()}')
```
## Profile training before optimizing it
A high GPU utilization number does not prove efficient training. NVIDIA's GPU utilization metric measures the fraction of the sampling interval during which a kernel is executing, not the fraction of peak arithmetic throughput achieved. Databricks reported roughly 6× shorter training time in one Qwen fine-tuning workload despite an initial 98% average utilization. Treat that as a case study, not an expected speedup for your model.
### Choose data by downstream results, not proxy metrics
NVIDIA's open midtraining work on Nemotron reports a useful evaluation lesson: **base-model proxy metrics did not correlate reliably with post-training results.** Their recipe trains between pretraining and SFT at 256K context on hundreds of billions of tokens of natural software-engineering data — packed repositories, pull requests, commit histories, build logs — plus a small share of agentic traces. After an identical full SFT, SWE-bench Verified rose from 60.7 to 64.5 on the smaller model with 500B midtraining tokens, and 72.9 to 74.3 on the larger one with 280B. Those are the authors' published numbers on those benchmarks, which do not replace evaluation on your own traffic.
The transferable method is how they chose data: score each candidate choice with **short fixed SFT runs** against the target task instead of trusting an upstream proxy. When changing pretraining or midtraining mixtures for an agentic workload, plan for a downstream evaluation budget — a proxy that looks better in isolation can lose after post-training.
### Capture a short CPU/GPU trace
Use `torch.profiler` to inspect operator counts, CPU dispatch, device execution, and gaps between kernels. This small, standalone example needs an installed PyTorch build, uses CUDA when available, and otherwise records CPU activity. It downloads no model or data and writes one trace to the current directory.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import torch
from torch import nn
from torch.profiler import ProfilerActivity, profile, record_function, schedule
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nn.Sequential(nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, 16)).to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
x = torch.randn(64, 128, device=device)
y = torch.randn(64, 16, device=device)
activities = [ProfilerActivity.CPU]
if device.type == "cuda":
activities.append(ProfilerActivity.CUDA)
def save_trace(prof):
print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10))
prof.export_chrome_trace(f"training-trace-{prof.step_num}.json")
with profile(
activities=activities,
schedule=schedule(wait=1, warmup=1, active=3, repeat=1),
on_trace_ready=save_trace,
record_shapes=True,
) as prof:
for _ in range(5):
with record_function("train_step"):
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.mse_loss(model(x), y)
loss.backward()
optimizer.step()
prof.step()
```
The schedule skips one step, warms up the profiler for one, then records three. Adjust it to reach a representative phase of a real workload; profiler warmup does not guarantee that compilation and model startup have finished. The toy inputs already reside on the device, so this example does not measure input loading or host-to-device copies. In a real loop, include those stages in labeled ranges too. Give each distributed rank a distinct trace filename.
Tracing, shape recording, and optional memory profiling add overhead. Use traces to locate the bottleneck, then measure throughput separately with profiling disabled. CUDA execution is asynchronous: for wall-clock measurements, synchronize the relevant device before starting and before stopping the timer, rather than forcing synchronization inside every iteration. Do not add nested CPU totals and overlapping GPU durations and call the result wall-clock time.
### Match the change to the bottleneck
Modal's GPU glossary separates compute, memory movement, and overhead. Use these as hypotheses, then verify them in a timeline or device profiler:
| Observation | Investigate | Candidate change |
| - | - | - |
| Many tiny kernels, heavy CPU dispatch, gaps between launches | Launch/dispatch overhead | Supported fused kernels; evaluate `torch.compile` or CUDA Graphs for this workload |
| Large kernels dominated by data movement | Memory bandwidth and unnecessary intermediate tensors | Reduce copies or intermediates; use supported fused implementations |
| Large matrix operations dominate | Compute throughput, dtype, shapes, and hardware support | Tune batch/shape and precision while checking numerical quality |
| Input waits, collective waits, or uneven progress across ranks | Data pipeline and distributed communication | Fix the measured wait rather than assuming the model kernel is slow |
In Databricks' case, existing `flash-linear-attention` and `causal-conv1d` kernels removed many small operations; reduced padding provided a further gain. That does **not** mean these packages help every model, or that compilation and CUDA Graphs are generally unsuitable for distributed training.
Before adopting a fast path, check model/backend support, GPU architecture, PyTorch/CUDA compatibility, and **both forward and backward** support. Pin the working environment and confirm the intended kernel actually appears in the trace: a successful package install does not prove it is being used. Recheck loss and gradients against the reference path within appropriate numerical tolerances.
### Pack sequences without changing the task
Sequence packing reduces padding, but simply concatenating examples can change training semantics. **Resetting `position_ids` alone is not a universal isolation mechanism.** The model and attention backend must consume compatible boundary metadata or masks; hybrid recurrent layers also need their state isolated at example boundaries.
The pinned Databricks implementation uses reset `position_ids`, cumulative sequence lengths for full attention, segment IDs for gated-delta layers, and loss masking so shifted targets do not cross example boundaries. It also masks prompt tokens for response-only SFT. These are backend-specific inputs, not a recipe to copy unchanged into an arbitrary model.
Test packed versus unpacked examples, including boundaries and truncated sequences, before measuring speed. Report non-padding tokens/s, padding fraction, effective batch size, sequence-length distribution, and validation quality. If packing changes tokens per optimizer step, account for the altered batch/optimization schedule. Compare equivalent training work, separating cold-start/compilation time from steady-state throughput.
### Fine-tuning is not the default
Adapter-based fine-tuning (LoRA and similar) shrinks the trainable parameter count and optimizer memory, which is why it is often the right first attempt on a consumer GPU. It does **not** automatically reduce activation memory, KV-cache pressure at inference, or total training time — those depend on sequence length, batch size, and how much of the model you still update. Measure before assuming it makes a workload fit.
## Why inference is bandwidth-bound
Training time is only half of the performance story. For an interactive agent, **decode latency** often matters more, and it is governed by memory traffic rather than floating-point throughput.
An autoregressive model generates one token at a time. At that point the batch is tiny relative to the weights, so each step must read essentially all parameters — and the accumulated KV cache — through memory bandwidth. Stanford CS336's lecture 10 makes the argument arithmetic: compute **arithmetic intensity** (FLOPs per byte moved), compare it with the accelerator's ratio of peak FLOP/s to memory bandwidth, and note that a low-intensity operation is memory-bound regardless of how fast the ALUs are.
That single framing explains most inference optimizations:
| Technique | Layer | What it trades |
| - | - | - |
| GQA / MLA / cross-layer attention | Architecture | Smaller KV cache; verify the accuracy cost on your evals |
| Quantization, pruning, distillation | Architecture | Fewer bytes per parameter; lossy, needs measurement |
| Speculative sampling | Algorithm | Extra compute to verify drafts, accepted tokens are exact if implemented correctly |
| Continuous batching | System | Higher throughput, worse per-request latency |
| Paged attention | System | Less KV-cache fragmentation, enabling larger batches |
| Prefix sharing, copy-on-write | System | One KV copy for shared system prompts or parallel samples |
Two practical consequences follow from the latency/throughput trade-off:
* **Batch size is a policy choice, not a default.** Larger batches amortize parameter reads — better tokens/s, worse latency for an individual user. Choose from your product's requirement, not the benchmark.
* **Capacity planning is a memory calculation.** Parameter bytes plus KV cache for the maximum concurrent sequences must fit, or the throughput numbers are fiction. Use smaller batches during prefill for faster first token, and reserve larger batches for generation.
Percy Liang's closing observation is the strategic point: the KV cache is a structural consequence of the Transformer's design. An architecture built for inference from the start — state-space models, linear attention, non-autoregressive generation — is where the largest remaining gains may be, not in further tuning of the current recipe.
## Data loading
### `Dataset` and `DataLoader`
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from torch.utils.data import Dataset, DataLoader
class CustomDataset(Dataset):
def __init__(self, data, labels):
self.data = data
self.labels = labels
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx], self.labels[idx]
dataset = CustomDataset(data, labels)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
```
### Image augmentation
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from torchvision import transforms
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
```
## Saving and loading models
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 保存模型
torch.save(model.state_dict(), 'model.pth')
# 加载模型
model = SimpleNet()
model.load_state_dict(torch.load('model.pth'))
model.eval()
# 保存完整模型
torch.save(model, 'model_complete.pth')
model = torch.load('model_complete.pth')
```
## Jupyter Notebook setup
Create a dedicated PyTorch kernel:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 创建虚拟环境
python -m venv pytorch_env
# 激活环境
source pytorch_env/bin/activate # Linux/Mac
pytorch_env\Scripts\activate # Windows
# 安装 PyTorch 和 Jupyter
pip install torch torchvision jupyter ipykernel
# 创建内核
python -m ipykernel install --user --name=pytorch --display-name "Python (PyTorch)"
```
Reference: [https://blog.csdn.net/ccaoshangfei/article/details/126521809](https://blog.csdn.net/ccaoshangfei/article/details/126521809)
## Useful tips
### Set the random seed
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
torch.manual_seed(42)
if torch.cuda.is_available():
torch.cuda.manual_seed(42)
```
### Show model structure
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from torchsummary import summary
summary(model, input_size=(1, 28, 28))
```
### Freeze part of the model
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 冻结前两层
for param in model.parameters():
param.requires_grad = False
for param in model.fc2.parameters():
param.requires_grad = True
```
## References
* [meng shao: CS336 lecture 10, Inference](https://x.com/shao__meng/status/2111804476671795223) — Folo intake, October 18, 2026
* [Stanford CS336: Language Modeling from Scratch](https://cs336.stanford.edu/) — course site; lecture 10 covers inference performance
* [CS336 lecture 10 (executable lecture)](https://github.com/stanford-cs336/lectures/blob/main/lecture_10.py) — arithmetic intensity, KV cache, batching, PagedAttention
* [PagedAttention (arXiv 2309.06180)](https://arxiv.org/pdf/2309.06180.pdf) — vLLM's KV-cache paging and prefix sharing
* [elvis: NVIDIA midtraining recipe](https://x.com/omarsar0/status/2111484480875626979) — Folo intake, October 17, 2026
* [NVIDIA: Priming Base Models for Agentic Post-Training (arXiv 2610.22019)](https://arxiv.org/abs/2610.22019) — midtraining stage and short-fixed-SFT evaluation protocol
* [meng shao: Qwen training optimization case](https://x.com/shao__meng/status/2110573261302202853) — Folo intake, October 15, 2026
* [Databricks: Reducing Qwen training time by 6x on AI Runtime](https://www.databricks.com/blog/reducing-qwen-training-time-6x-ai-runtime) — profiling, fused kernels, and padding reduction in one workload
* [Databricks: Pinned training implementation](https://github.com/databricks-solutions/ai-runtime-cookbook/blob/b27c10cfda94263588214f8824e0dd8bb393371e/training/sft-qwen3.8-27b-fsdp2-multinode/train.py) — packing metadata and loss boundaries
* [PyTorch: Profiler recipe](https://docs.pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) — activities, scheduled traces, and overhead
* [NVIDIA: nvidia-smi documentation](https://docs.nvidia.com/deploy/nvidia-smi/index.html) — meaning of utilization metrics
* [meng shao: Modal GPU glossary recommendation](https://x.com/shao__meng/status/2110581130806382765) — Folo intake, October 15, 2026; the glossary, not the financing news, is the reusable resource
* [Modal: GPU glossary — performance bottleneck](https://modal.com/gpu-glossary/perf/performance-bottleneck) — compute, memory, and overhead
## Learning resources
* Official docs: [https://pytorch.org/docs/](https://pytorch.org/docs/)
* Official tutorials: [https://pytorch.org/tutorials/](https://pytorch.org/tutorials/)
* Chinese docs: [https://pytorch-cn.readthedocs.io/](https://pytorch-cn.readthedocs.io/)
* GitHub: [https://github.com/pytorch/pytorch](https://github.com/pytorch/pytorch)
# Python data types
Source: https://base.bangwu.me/backend/Python/libs/data-types
Python built-in data types reference covering integers, floats, strings, lists, tuples, dictionaries, and sets with common methods and operation examples.
# Python data types
Python ships with a rich set of built-in data types for different kinds of data structures and use cases.
Official docs: [https://docs.python.org/zh-cn/3.12/library/datatypes.html](https://docs.python.org/zh-cn/3.12/library/datatypes.html)
## Basic data types
### Numeric types
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 整数
x = 10
# 浮点数
y = 3.14
# 复数
z = 1 + 2j
```
### Strings
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
s = "Hello World"
s1 = 'Python'
s2 = """多行
字符串"""
# 常用方法
s.upper() # 转大写
s.lower() # 转小写
s.split() # 分割
s.strip() # 去除首尾空格
s.replace("Hello", "Hi") # 替换
```
### Booleans
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
is_valid = True
is_empty = False
```
## Container types
### List
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 可变、有序
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # 添加
fruits.remove("banana") # 删除
fruits[0] # 索引Visit
fruits[1:3] # 切片
```
### Tuple
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 不可变、有序
point = (10, 20)
x, y = point # 解包
```
### Set
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 无序、不重复
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1 | s2 # 并集
s1 & s2 # 交集
s1 - s2 # 差集
```
### Dictionary
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 键值yes
user = {
"name": "张三",
"age": 25,
"email": "zhangsan@example.com"
}
user["name"] # Visit
user.get("age") # 安全Visit
user.keys() # 所有键
user.values() # 所有值
user.items() # 所有键值yes
```
## Specialized data types
### `datetime` - date and time
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from datetime import datetime, date, timedelta
now = datetime.now()
today = date.today()
tomorrow = today + timedelta(days=1)
# 格式化
now.strftime("%Y-%m-%d %H:%M:%S")
# 解析
datetime.strptime("2024-01-01", "%Y-%m-%d")
```
### `collections` - container extensions
#### `defaultdict`
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import defaultdict
d = defaultdict(list)
d['key'].append(1) # 不存在时自动创建空列表
```
#### `Counter`
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter
words = ["apple", "banana", "apple"]
counter = Counter(words)
counter.most_common(1) # [('apple', 2)]
```
#### `deque` - double-ended queue
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque
q = deque([1, 2, 3])
q.append(4) # 右侧添加
q.appendleft(0) # 左侧添加
q.pop() # 右侧删除
q.popleft() # 左侧删除
```
### `enum` - enumerations
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # Color.RED
print(Color.RED.value) # 1
```
### `dataclasses` - data classes
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
email: str = ""
user = User("张三", 25)
```
### `typing` - type hints
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from typing import List, Dict, Optional, Union
def process_items(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
def get_user(user_id: int) -> Optional[User]:
return user if user_id > 0 else None
```
## Type conversion
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 转整数
int("10") # 10
int(3.14) # 3
# 转浮点数
float("3.14") # 3.14
# 转字符串
str(100) # "100"
# 转列表
list("abc") # ['a', 'b', 'c']
# 转元组
tuple([1, 2]) # (1, 2)
# 转集合
set([1, 1, 2]) # {1, 2}
```
## Common patterns
### List comprehensions
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
```
### Dictionary comprehensions
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
square_dict = {x: x**2 for x in range(5)}
```
### Generator expressions
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
gen = (x**2 for x in range(10)) # 惰性求值
```
# HTTPX
Source: https://base.bangwu.me/backend/Python/libs/httpx
HTTPX is a modern Python HTTP client replacing requests, with sync and async APIs, native HTTP/2 support, connection pooling, and timeout configuration.
# HTTPX
HTTPX is a full-featured Python HTTP client library with both synchronous and asynchronous APIs. It is often treated as the modern alternative to `requests`.
## Features
* **Sync and async APIs**: one consistent interface for both styles
* **HTTP/2 support**: better performance where supported
* **Connection pooling**: automatic connection reuse
* **Timeout control**: fine-grained timeout settings
* **Type hints**: complete type annotations
## Installation
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install httpx
```
## Synchronous requests
### Basic usage
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import httpx
# GET 请求
response = httpx.get('https://api.example.com/data')
print(response.status_code)
print(response.json())
# POST 请求
data = {'key': 'value'}
response = httpx.post('https://api.example.com/submit', json=data)
# 带Parameters's 请求
params = {'page': 1, 'size': 10}
response = httpx.get('https://api.example.com/items', params=params)
# 带请求头
headers = {'Authorization': 'Bearer token'}
response = httpx.get('https://api.example.com/user', headers=headers)
```
### Using `Client`
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 复用连接
with httpx.Client() as client:
r1 = client.get('https://example.com')
r2 = client.get('https://example.com/api')
```
## Asynchronous requests
### Basic usage
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import httpx
import asyncio
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
return response.json()
# Run
data = asyncio.run(fetch_data())
```
### Concurrent requests
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
async def fetch_multiple():
async with httpx.AsyncClient() as client:
tasks = [
client.get(f'https://api.example.com/item/{i}')
for i in range(10)
]
responses = await asyncio.gather(*tasks)
return [r.json() for r in responses]
```
## Advanced features
### Timeout settings
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 全局超时
timeout = httpx.Timeout(10.0, connect=5.0)
response = httpx.get('https://example.com', timeout=timeout)
# 单独设置
response = httpx.get('https://example.com', timeout=30.0)
```
### Authentication
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Basic Auth
auth = ('username', 'password')
response = httpx.get('https://api.example.com', auth=auth)
# Bearer Token
headers = {'Authorization': f'Bearer {token}'}
response = httpx.get('https://api.example.com', headers=headers)
```
### File uploads
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
files = {'file': open('report.pdf', 'rb')}
response = httpx.post('https://api.example.com/upload', files=files)
# 多文件
files = [
('images', ('image1.jpg', open('image1.jpg', 'rb'), 'image/jpeg')),
('images', ('image2.jpg', open('image2.jpg', 'rb'), 'image/jpeg'))
]
response = httpx.post('https://api.example.com/upload', files=files)
```
### Streaming downloads
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
with httpx.stream('GET', 'https://example.com/large-file.zip') as r:
with open('file.zip', 'wb') as f:
for chunk in r.iter_bytes():
f.write(chunk)
```
### Cookie management
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
cookies = {'session_id': 'abc123'}
response = httpx.get('https://example.com', cookies=cookies)
# 持久化 cookies
with httpx.Client(cookies=cookies) as client:
client.get('https://example.com/page1')
client.get('https://example.com/page2')
```
### Proxy settings
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
proxies = {
'http://': 'http://proxy.example.com:8080',
'https://': 'http://proxy.example.com:8080'
}
response = httpx.get('https://example.com', proxies=proxies)
```
### Retry handling
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import httpx
from httpx import Timeout
transport = httpx.HTTPTransport(retries=3)
client = httpx.Client(transport=transport)
response = client.get('https://example.com')
```
## Response handling
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
response = httpx.get('https://api.example.com/data')
# 状态码
print(response.status_code)
# JSON 数据
data = response.json()
# 文本内容
text = response.text
# 二进制内容
content = response.content
# 响应头
print(response.headers['content-type'])
# 检查状态
response.raise_for_status() # 4xx/5xx 抛出异常
```
## Compared with `requests`
| Feature | requests | httpx |
| - | - | - |
| Synchronous requests | ✅ | ✅ |
| Asynchronous requests | ❌ | ✅ |
| HTTP/2 | ❌ | ✅ |
| Type hints | Partial | Complete |
| Maintenance status | Active | Active |
## Best practices
1. **Reuse connections with `Client`** for better performance.
2. **Set sensible timeouts** to avoid hanging requests.
3. **Prefer async in high-concurrency scenarios**.
4. **Handle errors explicitly** and retry where appropriate.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import httpx
async def safe_fetch(url: str, max_retries: int = 3):
for attempt in range(max_retries):
try:
async with httpx.AsyncClient() as client:
response = await client.get(url, timeout=10.0)
response.raise_for_status()
return response.json()
except httpx.HTTPError as e:
if attempt == max_retries - 1:
raise
await asyncio.sleep(2 ** attempt)
```
## References
* Official docs: [https://www.python-httpx.org/](https://www.python-httpx.org/)
* GitHub: [https://github.com/encode/httpx](https://github.com/encode/httpx)
# Python Libraries
Source: https://base.bangwu.me/backend/Python/libs/index
Python third-party library notes covering httpx, matplotlib, PyTorch, WordCloud, PyAutoGUI and more, with a learn-by-doing philosophy.
Third-party libraries are the core strength of Python's ecosystem. Standard libraries come with the installation, while third-party libraries are installed via `pip`, all accessed using `import` statements.
## How to Learn
You don't need to memorize every library — just master the commonly-used ones (`numpy`, `pandas` for data; `re`, `BeautifulSoup` for extraction). For others, read the official docs once to understand what they can do, and refer back to your notes when needed.
> [!TIP]
>
> Libraries are like bricks for building a house — do you need to understand their material composition? Just learn to use them.
> [!WARNING]
>
> Official documentation is the most authoritative source. Blog tutorials can supplement, but should not be your primary reference.
## Library Directory
For a comprehensive list, check [awesome-python-cn](https://github.com/jobbole/awesome-python-cn) with 26k+ stars, categorized by function.
> [card] [httpx](/backend/Python/libs/httpx)
>
> Next-generation HTTP client with async support.
> [card] [matplotlib](/backend/Python/libs/matplotlib)
>
> Data visualization and charting.
> [card] [wordcloud](/backend/Python/libs/wordcloud)
>
> Word cloud generation and text visualization.
> [card] [PyTorch](/backend/Python/libs/PyTorch)
>
> Deep learning framework intro notes.
> [card] [Python Notes](/backend/Python/libs/python-notes)
>
> Misc notes and common usage patterns.
> [card] [Data Types](/backend/Python/libs/data-types)
>
> Python data types in detail.
> [card] [pyautogui](/backend/Python/libs/pyautogui)
>
> Automation scripts and GUI control.
# Matplotlib
Source: https://base.bangwu.me/backend/Python/libs/matplotlib
Matplotlib is Python's main 2D plotting library for publication-quality figures, covering pyplot for line charts, histograms, and scatter plots.
# Introduction to Matplotlib
## What is Matplotlib?
Matplotlib is a Python 2D plotting library that can generate publication-quality figures in many hard-copy formats and interactive environments. It can be used in Python scripts, the Python and [IPython](http://ipython.org/) shell, [Jupyter](http://jupyter.org/) notebooks, web application servers, and multiple GUI toolkits.
Matplotlib tries to make easy things easy and hard things possible. With just a few lines of code, you can create charts, histograms, power spectra, bar charts, error plots, scatter plots, and more. See the [basic plotting examples](https://www.matplotlib.org.cn/tutorials/introductory/sample_plots.html) and the [gallery](https://www.matplotlib.org.cn/gallery/index.html) for inspiration.

For simple plotting, the `pyplot` module offers an interface similar to MATLAB, especially when used with IPython. Advanced users can also rely on the object-oriented API for full control over line styles, fonts, axes, and other details.
## Learning from the official examples
If you want to learn how to draw a specific kind of chart, the best places to start are the [gallery](https://www.matplotlib.org.cn/gallery) and the [pyplot command reference](https://matplotlib.org/api/pyplot_summary.html). Do not be afraid of the official docs. Even when they are in English or lightly annotated, they are still the most complete reference. The translated pages are usually good enough for reading, and when a function is still hard to understand, you can always search the community or ask someone more experienced.
# PyAutoGUI
Source: https://base.bangwu.me/backend/Python/libs/pyautogui
PyAutoGUI is a Python GUI automation library for controlling mouse, keyboard, and screen capture with image recognition for automated testing.
# Introduction to PyAutoGUI
PyAutoGUI is a pure-Python `GUI` automation library. It lets a program control the mouse and keyboard automatically, so it is very useful for simple automation and UI testing. You can think of it as a Python version of a desktop macro tool.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import pyautogui
```
After importing it, you can get started right away.
# Mouse operations
## Coordinates
For a library that focuses on precise clicking, coordinate handling is the foundation. `pyautogui` uses screen pixels for positioning. For example, on a display with a resolution of 2560x1600:
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
width, height = pyautogui.size() # 获取电脑屏幕坐标
print(width, height)
```
The output is `2560 1600`.
The coordinate origin is in the top-left corner. The x-axis is horizontal and the y-axis is vertical:

Once you understand that, you can position the mouse precisely.
## Mouse movement
# Python learning notes
Source: https://base.bangwu.me/backend/Python/libs/python-notes
Miscellaneous Python notes and code snippets covering pd.DataFrame creation, Pandas tips, common error troubleshooting, and useful patterns.
# Python notes
## 1. `pd.DataFrame`
This is the standard Pandas format for creating a `DataFrame`. Remember the capitalization: `DataFrame`. Each column in a `DataFrame` is a `Series`.
## 2. Reading text-based data files
`pandas.read_table()` is the more general API for reading text files.
The main difference is that its default `sep` is `"/t"`, meaning tab-separated data.
## `pd.read_csv()`
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
pd.read_csv(
filepath or buffer:要读入's File path
sep=',':列分隔符
header='infer':指定数据中's 第几行作为变量名
names = None:自定义变量名列表
index_col = None:将会被用作索引's 列名,多列时只能使用序号列表 usecols = None:指定只读入某些列,使用索引列表或者Name列表均可。
[0,1,3],[”名次”,”学校Name”,”所在地区”]
encoding = None:读入文件's 编码方式
utf-8/GBK,中文数据文件最好设定为utf-8
na_values:指定将被读入为缺失值's 数值列表,默认下列数据被读入为缺失值:
' ','#N/A', '#N/A N/A', '#NA', '-1.#IND',
'-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN',
‘N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'
):读取csv格式文件,但也可通用于文本文件读取
```
4. 
## `describe` command
This command outputs common summary statistics for central tendency and dispersion in one go.
Percentile output is one of its most useful features.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
df.describe(
percentiles:需要输出's 百分位数,列表格式提供,如[.25, .5, .75]
include = "None" :要求纳入分析's 变量类型白名单
None (default) :只纳入数值变量列
A list0-like of dtypes :列表格式提供希望纳入's 类型
"all": 全部纳入
exclude: 要求剔除分析's 变量类型黑名单,选项同上
)
```
## Univariate frequency statistics
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
Series.value_counts(
normalize = False: 是否返回构成比例而不是原始频数
sort = True:是否按照频数排序(否则按照原始顺序排列)
ascending = False:是否升序排列
bins: yes数值变量直接进行分段。可看作是判断pd.cut's 简易用法
dropna = True: 结果中是否包括NaN
)
```
## Crosstab
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
pd.crosstab(
行列设定
index / columns: 行变量/列变量,多个时以list形式提供
rownames / colnames = None: 交叉表's 行列Name
单元格设定
Values: 在单元格中需要汇总's 变量列,需要进一步指定aggfunc
aggfunc: 相应's 汇总函数
行列百分比计算
normalize = False: {"all","index", "columns"}, or {0,1}
"all" / True: 总计百分比
"index" / 0:分行计算百分比
"columns" / 1: 分列计算百分比
当margins = True时,也同时计算边际汇总's 百分比
汇总设定
margins = False : 是否加入行列汇总
margins_name = "All": 汇总行/列's Name
dropna = True:
)
```
# WordCloud
Source: https://base.bangwu.me/backend/Python/libs/wordcloud
WordCloud is a Python library for word cloud visualizations, covering custom shape masks, color schemes, Chinese segmentation with jieba.
# WordCloud
WordCloud is a Python library for generating word cloud images. It can turn text data into visually appealing word clouds.
## Installation
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install wordcloud
```
Chinese text support requires an additional font path configuration.
## Basic usage
### Simple word cloud
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 生成词云
text = "Python 数据分析 机器学习 深度学习 人工智能"
wordcloud = WordCloud(font_path='simhei.ttf').generate(text)
# 显示图像
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
# 保存图像
wordcloud.to_file('wordcloud.png')
```
### Read from a file
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
wordcloud = WordCloud(
font_path='simhei.ttf',
width=800,
height=400
).generate(text)
```
## Custom styles
### Basic parameters
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
wordcloud = WordCloud(
font_path='simhei.ttf', # 字体路径
width=800, # 宽度
height=400, # 高度
background_color='white', # 背景色
max_words=200, # 最大词数
max_font_size=100, # 最大字号
min_font_size=10, # 最小字号
colormap='viridis', # 配色方案
relative_scaling=0.5, # 词频重要性
random_state=42 # 随机种子
)
```
### Color schemes
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 使用 matplotlib 配色
from matplotlib import cm
wordcloud = WordCloud(
font_path='simhei.ttf',
colormap='rainbow' # 'viridis', 'plasma', 'cool', 'hot'
)
```
## Advanced features
### Use a mask image
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from PIL import Image
import numpy as np
# 读取遮罩图片
mask = np.array(Image.open('mask.png'))
wordcloud = WordCloud(
font_path='simhei.ttf',
mask=mask, # 遮罩图片
contour_width=3, # 轮廓宽度
contour_color='steelblue' # 轮廓颜色
).generate(text)
```
### Custom word frequencies
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 使用字典设置词频
word_freq = {
'Python': 100,
'数据分析': 80,
'机器学习': 60,
'深度学习': 40
}
wordcloud = WordCloud(font_path='simhei.ttf').generate_from_frequencies(word_freq)
```
### Stopword filtering
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 设置停用词
stopwords = set([''s ', '了', '在', '是', '我', '有'])
wordcloud = WordCloud(
font_path='simhei.ttf',
stopwords=stopwords
).generate(text)
# 从文件加载停用词
with open('stopwords.txt', 'r', encoding='utf-8') as f:
stopwords = set(f.read().splitlines())
```
## Chinese text processing
### Use `jieba` for tokenization
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import jieba
from wordcloud import WordCloud
# 读取文本
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
text_seg = ' '.join(words)
# 生成词云
wordcloud = WordCloud(
font_path='simhei.ttf',
background_color='white'
).generate(text_seg)
```
### Complete example
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import jieba
import jieba.analyse
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本
with open('article.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 加载停用词
with open('stopwords.txt', 'r', encoding='utf-8') as f:
stopwords = set(f.read().splitlines())
# 分词
words = jieba.cut(text)
filtered_words = [w for w in words if w not in stopwords and len(w) > 1]
text_seg = ' '.join(filtered_words)
# 生成词云
wordcloud = WordCloud(
font_path='simhei.ttf',
width=1600,
height=800,
background_color='white',
max_words=100,
colormap='viridis'
).generate(text_seg)
# 显示
plt.figure(figsize=(12, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.savefig('wordcloud.png', dpi=300, bbox_inches='tight')
plt.show()
```
## Practical tips
### Extract keywords
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import jieba.analyse
# TF-IDF 提取关键词
keywords = jieba.analyse.extract_tags(text, topK=50, withWeight=True)
word_freq = {word: weight for word, weight in keywords}
wordcloud = WordCloud(
font_path='simhei.ttf'
).generate_from_frequencies(word_freq)
```
### Multiple shapes
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from PIL import Image
import numpy as np
# 圆形
def create_circle_mask(size=400):
x, y = np.ogrid[:size, :size]
mask = (x - size/2) ** 2 + (y - size/2) ** 2 > (size/2) ** 2
mask = 255 * mask.astype(int)
return mask
mask = create_circle_mask()
wordcloud = WordCloud(font_path='simhei.ttf', mask=mask).generate(text)
```
## Common issues
### Chinese text shows as squares
* Cause: no Chinese font specified
* Fix: set `font_path='simhei.ttf'`
### Common Chinese font paths
* Windows: `C:\Windows\Fonts\simhei.ttf`
* Mac: `/System/Library/Fonts/PingFang.ttc`
* Linux: `/usr/share/fonts/truetype/`
## References
* GitHub: [https://github.com/amueller/word\_cloud](https://github.com/amueller/word_cloud)
* Docs: [https://amueller.github.io/word\_cloud/](https://amueller.github.io/word_cloud/)
# Anti-Scraping Techniques
Source: https://base.bangwu.me/backend/Python/spider/anti-spider
Anti-scraping techniques covering User-Agent and Referer header spoofing, IP proxy rotation to avoid bans, and Ajax data extraction methods.
# Header parameters
In the `requests.get()` method, one of the most common anti-scraping-related arguments is `headers`. The usage is simple: pass `headers=a dictionary`. This dictionary stores request headers that help make a crawler look like a real browser instead of a bot.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
headers = {
'Referer': '具体's Referer',
'User-Agent': '具体's user-agent',
'cookie':'具体's cookie'
}
requests.get(url,headers=headers)
```
## User-Agent
Almost every crawler starts with the `User-Agent`. Most websites check it first. The easiest way to get one is to open the browser developer tools, inspect a network request, and copy the value. Since a `User-Agent` is usually just browser and system metadata, its main purpose is to make your request look like it came from a real user.
That is exactly why libraries like `my_fake_useragent` exist.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from my_fake_useragent import UserAgent
headers = {'User-Agent': UserAgent(family='chrome').random()}
```
This gives you a randomized `User-Agent`, which is often more convenient and can bypass some basic UA checks.
## Cookie
Cookies are also very common in scraping. A cookie is essentially your identity on a site. Once the server sees your cookie, it can recognize the current session and return content tied to that identity.
## Referer
`Referer` is often related to anti-hotlinking. It tells the server which page the current request came from. In a path like `A -> B -> C`, the `Referer` for `C` is `B`. Many sites use this to check whether a request really originated from an expected page. If not, they may deny access or return fake data.
A typical example is video sites: direct requests to media URLs may fail unless the request appears to come from the site itself.
Here I use Douban as an example. If you are interested, you can explore it further yourself: [Link]().
## Content-type
`Content-type` determines how the server interprets the request body and how the client should interpret the response.
# Common parameters
In the browser developer tools, you will see many more headers than just the ones above. So how do you decide which ones are actually necessary?
For ordinary sites, adding a `User-Agent` is often enough. Sites that require login usually also need cookies. Other cases vary by site, so the practical approach is to test a few combinations. There is also a universal fallback: use **selenium** to simulate real browser behavior. It is more cumbersome to write, so it is usually best kept as the last resort.
# Ajax overview
Ajax stands for Asynchronous JavaScript and XML. The term was proposed by Jesse James Garrett in 2005 to describe a “new” way of using existing web technologies such as HTML/XHTML, CSS, JavaScript, DOM, XML, XSLT, and—most importantly—`XMLHttpRequest`.
The key idea is that a page can exchange small amounts of data with the server in the background. That allows part of the page to update without refreshing the entire page.
In practice, you do not need to master all the underlying theory. You just need to recognize what Ajax requests look like in the browser. Here is a simple example:
```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
Ajax
ajax
```
Simply put, Ajax sends a request to the server and then refreshes only the data that changed. For example, if you implemented product review pagination the traditional way, every page switch would fetch the header, sidebar, footer, and review area again. That wastes bandwidth, server resources, and user time. With Ajax pagination, only the review section needs to be fetched and re-rendered.
# How to identify and find Ajax requests
## Identify them
To determine whether a page is using Ajax, trigger the relevant action and watch whether the page fully reloads. If the page does not refresh but the data updates, the content is probably being fetched and rendered with Ajax. If the whole page reloads, the data is likely being generated server-side in the traditional way.
## How to find them
As mentioned above, Ajax still has to send a request to the server. That is your entry point. The request is usually either `GET` or `POST`, so a quick method is to inspect the fetched page source or scripts and search for `get` or `post`. Once you locate the Ajax function, look at where it sends the request, extract the `url`, and then mimic that request yourself to retrieve the data.
# Solutions
# Practical cases
I ran into this kind of situation while scraping a site. If you are interested, you can check it here: [Link]().
# IP anti-scraping mechanisms
# How to switch IPs
# How to get proxy IPs
## `proxy_pool` (free)
`proxy_pool` is a free and open-source proxy pool project on GitHub. Its basic idea is to crawl public proxy websites and aggregate usable IPs.
## Paid proxy providers
## Self-built proxy IPs
# Web Scraping
Source: https://base.bangwu.me/backend/Python/spider/index
Python web scraping from basics to advanced, covering requests module, HTML parsing with BeautifulSoup, data extraction, and multiprocessing.
Suitable for those with basic Python knowledge — syntax and package imports.
## Scraping Basics
1. `requests` module
2. HTML fundamentals (understanding HTML)
3. Content extraction
## Scraping Advanced
1. Threading, multiprocessing, async introduction
> [card] [Anti-Scraping Techniques](/backend/Python/spider/anti-spider)
>
> Headers parameters, IP proxies, Ajax data extraction, and more.
# Rust IM Bridge (AgentIM)
Source: https://base.bangwu.me/backend/Rust/agentim
Multi-channel IM bridge built in Rust — connecting Telegram, Discord, Feishu, Slack, DingTalk, LINE, QQ, and WeChat Work to AI agent backends.
# AgentIM — Rust Multi-Channel IM Bridge
AgentIM is a Rust bridge that connects chat platforms to a local AI agent backend (Codex). It supports 8+ platforms through webhooks and long polling, with session persistence, context limits, and routing rules.
> [card] [AgentIM](https://github.com/markbang/agentim)
>
> Rust IM bridge — 8+ platforms, session persistence, health endpoints.
## Supported Platforms
| Platform | Delivery | Verification |
| - | - | - |
| Telegram | Long polling (`getUpdates`) | Bot token |
| Discord | `POST /discord` | Ed25519 |
| Feishu/Lark | `POST /feishu` | Verification token + URL challenge |
| Slack | `POST /slack` | HMAC-SHA256 |
| DingTalk | `POST /dingtalk` | HMAC-SHA256 |
| LINE | `POST /line` | HMAC-SHA256 |
| QQ | `POST /qq` | — |
| WeChat Work | `POST /wechatwork` | — |
## Tech Stack
| Component | Technology | Purpose |
| - | - | - |
| HTTP server | Axum 0.7 | Routing, middleware, webhooks |
| Async runtime | Tokio (full features) | Async I/O, timers, channels |
| HTTP client | Reqwest | Outbound API calls |
| Concurrency | DashMap | Lock-free concurrent state |
| CLI | Clap 4 | Command-line argument parsing |
| Logging | Tracing + Tracing-subscriber | Structured logging |
| Serialization | Serde + Serde\_json | JSON codec |
| Error handling | Anyhow + Thiserror | Ergonomic error types |
| Auth | HMAC | Webhook signature verification |
## Architecture
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
┌─────────┐ ┌─────────┐ ┌─────────┐
│Telegram │ │Discord │ │Feishu │ ...more platforms
└───┬─────┘ └───┬─────┘ └───┬─────┘
│ │ │
▼ ▼ ▼
┌───────────────────────────────────┐
│ AgentIM (Axum) │
│ ┌──────────┐ ┌────────────────┐ │
│ │Ingress │ │Session Store │ │
│ │(webhooks │ │(DashMap) │ │
│ │+polling) │ │ │ │
│ └──────────┘ └────────────────┘ │
│ ┌──────────┐ ┌────────────────┐ │
│ │Router │ │Context Trimmer │ │
│ │(rules) │ │ │ │
│ └──────────┘ └────────────────┘ │
└───────────┬───────────────────────┘
│
▼
┌───────────────────┐
│ Codex Backend │
│ (app-server) │
└───────────────────┘
```
## Key Design Patterns
### Platform Abstraction
Each platform handler implements a common trait:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
#[async_trait]
pub trait PlatformHandler: Send + Sync {
async fn handle_inbound(&self, msg: InboundMessage) -> Result<()>;
async fn send_response(&self, target: ReplyTarget, text: &str) -> Result<()>;
}
```
This lets you add new platforms without touching the core routing logic.
### Session Persistence
User sessions are stored in `DashMap` — a lock-free concurrent hashmap:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use dashmap::DashMap;
pub struct SessionStore {
sessions: DashMap,
}
pub struct Session {
pub user_id: String,
pub platform: Platform,
pub history: Vec,
pub created_at: DateTime,
}
```
> [!NOTE]
>
> DashMap provides sharded locks internally, so concurrent reads/writes from multiple Tokio tasks don't block each other. Much faster than `Mutex` for IM workloads.
### Context Trimming
Chat history grows over time. AgentIM trims context to stay within token limits:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub fn trim_context(history: &mut Vec, max_tokens: usize) {
// Keep the most recent messages that fit within max_tokens
let mut token_count = 0;
let cutoff = history.iter().rev().position(|msg| {
token_count += estimate_tokens(&msg.text);
token_count > max_tokens
}).unwrap_or(history.len());
history.drain(0..cutoff);
}
```
### Webhook Signature Verification
Each platform has its own signature scheme. AgentIM validates before processing:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Discord: Ed25519
pub fn verify_discord_signature(body: &[u8], signature: &str, timestamp: &str, public_key: &str) -> bool {
let message = format!("{}{}", timestamp, body);
ed25519_verify(message.as_bytes(), signature, public_key)
}
// Slack / DingTalk: HMAC-SHA256
pub fn verify_hmac_signature(body: &[u8], signature: &str, secret: &str) -> bool {
let expected = hmac_sha256(body, secret);
signature == expected
}
```
### Routing Rules
Channel-based routing lets you direct messages to different behaviors:
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
pub struct RoutingRule {
pub channel_pattern: String, // Regex
pub user_pattern: Option,
pub target: ReplyTarget,
}
// Example: route all #help channel messages to a FAQ bot
// Example: route DMs from specific users to a custom agent
```
## Docker Deployment
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# docker-compose.yml
services:
agentim:
build: .
ports:
- "8080:8080"
environment:
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
- DISCORD_PUBLIC_KEY=${DISCORD_PUBLIC_KEY}
- CODEX_API_URL=http://codex:3002
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
```
## Health Endpoints
```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
// /health — service status
// /ready — can process requests
// /review — pending human-review items (optional)
```
## Best Practices
1. **Platform trait abstraction** — Common interface per platform, easy to add new ones
2. **DashMap for concurrent state** — Lock-free, fast for multi-platform message handling
3. **Context trimming** — Keep history within token limits to avoid runaway memory
4. **Webhook signature verification** — Always validate before trusting inbound messages
5. **Health + readiness endpoints** — Let orchestrators (Docker, K8s) monitor service state
6. **Shared-secret auth** — Simple but effective for internal service communication
7. **Tokio full features** — IM bridges need timers, I/O, and sync — don't trim the runtime
## References
* [AgentIM repo](https://github.com/markbang/agentim) — Full source code
* [Axum Docs](https://docs.rs/axum)
* [DashMap](https://docs.rs/dashmap)
* [Codex app-server transport](https://github.com/markbang/agentim/blob/main/docs/codex-app-server-transport-review.md)
# Rust
Source: https://base.bangwu.me/backend/Rust/index
Rust backend development hub covering Axum IM bridges with Tokio async runtime, Tauri desktop shells, and a learning path from ownership to web services.
# Rust
Rust combines memory safety, zero-cost abstractions, and fearless concurrency. In my projects, Rust serves two roles: high-performance backend services (Axum) and native desktop shells (Tauri).
> [card] [AgentIM](/backend/Rust/agentim)
>
> Multi-channel IM bridge — Axum, Tokio, 8+ platforms.
> [card] [Tauri Desktop](/software/tauri)
>
> Cross-platform desktop shell — Rust + web frontend.
## Learning Path
1. **Basics** — Ownership, borrowing, lifetimes, traits
2. **Async** — Tokio runtime, futures, channels
3. **Web** — Axum routing, middleware, extractors
4. **Systems** — FFI, unsafe, embedded patterns
## Why Rust for IM Bridges?
* **Zero garbage-collection pauses** — IM messages need predictable latency
* **Fearless concurrency** — Tokio + DashMap handle thousands of simultaneous connections
* **Small binary** — AgentIM compiles to \~5MB, vs 50MB+ for Node.js equivalents
* **Memory safety** — No segfaults in production
# Database principles
Source: https://base.bangwu.me/backend/SQL/db-knowledge
Database principles course notes covering relational algebra, SQL queries with JOIN/GROUP BY, normalization to BCNF, ACID properties, and ER.
# Database Principles and Applications Exam Related-2023
\----------------------------------------
**Exam question types**
**1. Multiple-choice questions (10 points, 5 questions, 2 points each)**
**2. Fill-in-the-blank questions (15 points, 5 questions, 3 points each)**
**3. Short-answer questions (15 points, 3 questions, 5 points each, please be as detailed as possible, with clear logic and clear layers)**
**4. Design questions (60 points. The first question is 10 points; the second question is 50 points, a total of 10 programming questions, each question is 5 points)**
***
\*\*\* Question design ideas: Choose corresponding questions from the following key points, then randomly select the above question types and numbers, and then make fine adjustments. \*\*
\----------------------------------------
Exam focus:
# 1. Introduction
1. `数据库的4个基本概念 P10`
* data, database, database management system, database system
2. `数据库的定义 P14`
* A database is an organized, large-scale, shared collection of data stored in a computer for a long time
3. `数据库(系统)的基本特征 P14 / P37 - P41`
* Shareable by users, with low redundancy, easy expansion, and strong data independence
4. `数据库管理系统的主要功能 P17 - P19`
* Data definition function (DDL), data organization, storage and management, data manipulation function (DML), database transaction management and remote management, database establishment and maintenance function, communication function of database and other software systems in the network
5. `数据库系统的构成 P20 - P21`
* Databases, database management systems (and their development tools), applications and database administrators
6. `数据库系统的特点 P37-P41`
* The data is structured, with high data shareability, low redundancy, easy expansion, and high data independence. The data is managed and controlled uniformly by DBMS.
7. `数据独立性高如何理解 P40`
* Refers to an application's database schema and data storage method that does not depend on other applications or operating system platform-specific implementations.
8. `数据库管理系统如何控制数据共享 P41`
* Database access permission control, database metadata control, data encryption, database replication, database partitioning,
9. `概念模型、逻辑模型和物理模型的概念 P47`
* The conceptual model is an abstraction and simplification of the real world. It is used to describe the data in the database and the relationship between the data. It is the core of database design and the basis of database modeling;
* A logical model is a logical representation of a conceptual model, which is used to store data in a database and the relationships between data;
* The physical model is the representation of the logical model on a physical storage device, which is used to store and manage data in the database;
10. `数据模型的组成要素 P57`
* Entities, attributes, relationships, constraints between entities, data types and precision
11. `数据模型中的数据结构 P58`
* The data structure in the data model refers to the way data is stored and represented in the database;
* Tables, views, indexes, primary and foreign keys,
12. `数据模型中的数据操作 P59`
* Add, delete and modify, insert operations, query operations, data backup and recovery operations, transaction operations
13. `数据模型中的完整性约束条件 P60`
* Refers to a set of rules used to ensure the integrity of data in a database;
* Entity integrity, attribute integrity, referential integrity, user-defined integrity
14. `关系模型谁提出的? P84`
* E.F. Codd, a researcher at the San Jose Research Laboratory of IBM Corporation in the United States
15. `类型和值的概念 P95 - P96`
* Type: Type is an identifier used to describe data structure and data type. They usually appear in the form of keywords;
* Common types: integer, character and date;
* Value: Value refers to the specific content and value of data, usually data input by the user or generated by the program;
16. `数据库系统的三级模式结构 P99 - P105`
* Physical layer: The physical layer refers to the actual physical device where data is stored, ensuring the reliability and security of the data;
* Conceptual layer: The conceptual layer refers to the data model and data structure in the database, which is the core of database design and implementation;
* Logical layer: The logical layer refers to the application program in the database management system and is the direct object of database management and maintenance.
17. `数据库系统的两级映射功能 P107 - P114`
It means that the database management system stores data on physical devices and provides the data to users for query and operation;
Database: It is the place where data is stored in the database management system and is the physical implementation of the database management system;
Database management system application: It is an application in the database management system. Direct objects of database management and maintenance
# 2. Relational database
1. `关系数据库的提出者和时间 P4`
* E.F.Codd
2. `何为关系 P7`
* It is a basic concept of database. It is used to describe the relationship between data in the database. It is the relationship between entities. It describes the connection and interaction between entities. It can be one-to-one, one-to-many, and many-to-many.
3. `域 P9`
* A domain is a collection of values of the same data type
4. `笛卡尔积 P10 - P14`
* Cartesian product is a set operation on the field
5. `关系和笛卡尔积的关系 P17,P19`
* Relations are finite subsets of Cartesian products
6. `码 P18`
* Code refers to a coding method used to represent specific data or entities, usually consisting of a set of numbers, letters or other symbols.
7. `三类关系 P20`
* One-to-one: One-to-one relationship between two tables;
* One-to-many: One-to-many relationship between two tables;
* Many-to-many: refers to the many-to-many relationship between three tables or above;
8. `基本关系的性质 P22`
* 1) The columns are homogeneous, that is, the components in each column are the same type of data and come from the same domain.
* 2. Different columns can come from the same domain. Each column is called an attribute. Different attributes should be given different attribute names.
* 3. The order of the columns does not matter, that is, the order of the columns can be exchanged arbitrarily.
* 4. The candidate codes of any two tuples cannot have the same value.
* 5. The order of rows does not matter, that is, the order of columns can be exchanged arbitrarily.
* 6. The components must take on atomic values, that is, each component must be an indivisible data item.
9. `关系模式的定义 P26`
* The description of a relationship is called a relationship description
10. `基本的关系操作 P36`
* Query operations, two parts: insertion, deletion and modification operations
* Query operations can be divided into selection, projection, connection, division, union, difference, intersection, and Cartesian product
11. `SQL的4大功能 P39`
* Data definition, data query, data manipulation, data control
12. `三类完整性约束 P41`
* Entity integrity, referential integrity, user-defined integrity
13. `实体完整性规则 P43 - P44`
* If attribute (referring to one or a group of attributes) A is the main attribute of basic relationship R, then A cannot take a null value
14. `外码 P50`
* Suppose F is an attribute or a set of attributes of the basic relation R, but not the key of the relation R, and KS is the primary key of S. If F corresponds to KS, then F is said to be the foreign key of R, and the basic relationship R is called the reference relationship, and the basic relationship S is the referenced relationship or target relationship.
14. `参照完整性 P55 - P56`
* Also known as referential integrity, it is a constraint between two related tables.
15. `用户定义的完整性 P60`
* User-defined integrity is a constraint for a specific relational database, which reflects the semantic requirements that the data involved in a specific application must meet.
16. `关系代数运算符 P64`
* Union, difference, intersection, Cartesian product and selection, projection, connection, division operation
17. `传统的集合运算 P66 - P74`
* Union, difference, intersection, Cartesian product
18. `专门的关系运算(除运算除外) P85 - P103`
* Selection, projection, concatenation, division operations
19. `关系运算符的运用 P110`
* Learn by yourself
# 3. SQL
1. `SQL的中文和英文 1P51`
* Structured Query Language SQL
2. `SQL的功能和特点 1P55 - 1P61`
* Comprehensive and unified, highly non-procedural, set-oriented operation mode, providing multiple usage methods with the same syntax structure,
* Simple language, easy to learn and use
* Data query, data manipulation, data definition, data control
3. `内模式/模式/外模式 与 存储文件/基本表/视图 之间概念关联 1P64 - 1P67`
* External schema: also called sub-schema or user schema, is a description of the logical structure and characteristics of local data that users can see and use;
* Schema: Also known as logical schema, it is a description of the logical structure and characteristics of all data in the database, and is a common data view of all data.
* Internal schema: also called storage schema, is a description of the physical structure and storage method of the database, and is the way data is represented inside the database.
* The data is provided to the user according to the description of the external mode and stored on the hard disk according to the description of the internal mode. The mode is between the external and internal modes and involves neither external access nor internal storage, thereby playing an isolation role and conducive to the independence of the data. The internal mode relies on the global logical structure, but can be independent of specific storage devices.
* Basic table: an independent table;
* View: a virtual table, which is a table derived from one or several basic tables;
* The database only stores the definition of the view and not the data corresponding to the view. These data are still stored in the basic table of the derived view. When the data in the basic table changes, the data queried from the view also changes.
4. `数据定义的所有代码 1P74 - 1P99`
* Create: create schema; create table; create view; create index;
* Delete: drop schema; drop table; drop view; drop index;
* Modify: alter table; alter index
5. `数据字典是什么 1P101`
* The data dictionary is a set of system tables within the relational database management system. It records all definition information in the database, including relational schema definitions, view definitions, index definitions, integrity constraint definitions, operating permissions of various users on the database, statistical information, etc.
6. `单表查询 1P106 - 1P137`
* Single table query refers to a query involving only one table
7. `连接查询 2P8 - 2P24`
* If a query involves more than two tables at the same time, it is called a join query.
8. `嵌套查询(EXISTS除外) 2P26 - 2P48`
* A SELECT-FROM-WHERE statement is called a query block, and a query that nests a query block in the conditions of the WHERE clause or HAVING phrase of another query block is called a nested query.
* If the query conditions of a subquery depend on the parent query, it is called a related subquery, and the entire query statement is called a related nested query.
* Otherwise, it is called an irrelevant subquery.
9. `集合查询 2P58 - 2P63`
* Union operation: UNION, intersection operation: INTERSECT, difference operation: EXCEPT
10. `基于派生表的查询 2P65 - 2P66`
* Subqueries can not only appear in the WHERE clause, but also in the FROM clause. At this time, the temporary derived table generated by the subquery becomes the query object of the main query.
11. `插入数据 3P6 - 3P13`
* INSERT INTO (table name) VALUES (values)
* INSERT INTO (table name) subquery
12. `修改数据 3P15 - 3P20`
* UPDATE (table name) SET (column name) WHERE (condition)
13. `删除数据 3P22 - 3P27`
* DELETE FROM (table name) WHERE (condition)
14. `Drop和DELETE的区别`
* Drop is generally used to delete overall data, such as tables, schemas, indexes, views and integrity restrictions.
* DELETE is used to delete local data, such as a tuple in a table
15. `空值相关 3P29 - 3P37`
* The null value is a very special value that contains uncertainty.
* Attribute definitions (domain definitions) with NOT NULL constraints cannot take null values, attributes with UNIQUE restrictions cannot take null values, and code attributes cannot take null values.
16. `视图的特点 3P39`
* View: a virtual table, which is a table derived from one or several basic tables;
* The database only stores the definition of the view and not the data corresponding to the view. These data are still stored in the basic table of the derived view. When the data in the basic table changes, the data queried from the view also changes.
* 17. `建立视图 3P42 - 3P52`
* CREATE VIEW (view name) AS (subquery) \[WITH CHECK OPTION]
18. `删除视图 3P53`
* DROP VIEW (view name) \[CASCADE]
* CASCADE can delete other views exported by this view.
19. `视图更新的限制 3P66 - 3P68`
* 1) If the view is exported from more than two basic tables, this view is not allowed to be updated;
* 2. If the fields of the view come from field expressions or constants, INSERT and UPDATE operations are not allowed on this view, but DELETE operations are allowed;
* 3. If the fields of the view come from aggregate functions, this view is not allowed to be updated;
* 4. If the view definition contains a GROUP BY statement, this view is not allowed to be updated;
* 5. If the view definition contains the DISTINCT phrase, this view is not allowed to be updated;
* 6. If there is a nested query in the view definition, and the table involved in the FROM clause of the inner query is also the basic table for exporting the view, this view is not allowed to be updated;
* 7. A view defined on a view that is not allowed to be updated is not allowed to be updated.
20. `视图的作用 P72`
* 1) Simplify user operations;
* 2. Enable users to view the same data from multiple perspectives;
* 3. Provides a certain degree of logical independence for reconstructing the database;
* 4. Able to provide security protection for confidential data;
* 5. Appropriate use of views can express queries more clearly.
# 4. Database security
1. `数据库安全性问题的提出 P4`
* Database security refers to protecting the database from data leakage, alteration or destruction caused by illegal use
2. `数据库的不安全因素 P8 - P11`
* 1) Malicious access and damage to the database by unauthorized users;
* 2. Important or sensitive data in the database is leaked;
* 3. The vulnerability of the security environment;
3. `数据库安全性控制的流程 P35`
* 1) User identification and authentication (static password authentication, dynamic password authentication, biometric authentication, smart card authentication);
* 2. Access control (autonomous access control, mandatory access control);
* 3. Authorization: grant and revoke (grant, revoke, permission to create database schema);
* 4. Database roles (creation of roles, authorization of roles, granting a role to other roles or users, withdrawal of role permissions);
4. `用户身份鉴定的概念和方法 P38 - P43`
* Static password authentication:
* Dynamic password authentication:
* Biometric authentication:
* Smart card authentication:
5. `存取控制 P46`
* The access control mechanism mainly includes two parts: defining user permissions and checking legal permissions;
6. `常用的两种存取控制方法 P47 - P48`
* Autonomous access control: Users have different access permissions for different database objects, and different users also have different permissions for the same object. Users can also delegate their access permissions to other users, so autonomous access control is very flexible;
* Mandatory access control: Each database object is marked with a certain confidentiality level, and each is subsequently granted a certain level of license. For any object, only users with legal licenses can access it, so mandatory access control is relatively strict.
* 7. `权限授予的SQL代码 P54 - P68`
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
GRANT(权限)ON(对象类型)(对象名)TO(用户)[WITH GRANT OPTION]
```
8. `权限回收的SQL代码 P69 - P73`
```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}}
REVOKE(权限)ON(对象类型)(对象名)FROM(用户)[CASCADE|RESTRICT]
```
9. `数据库角色的概念 P76`
* A database role is a named set of permissions related to database operations. A role is a collection of permissions.
10. `数据库角色的SQL代码 P77 - P83`
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE ROLE(角色名);
GRANT(权限)ON(对象类型)(对象名)TO(用户)[WITH GRANT OPTION];
REVOKE(权限)ON(对象类型)(对象名)FROM(用户)[CASCADE|RESTRICT]
```
`视图机制在安全性控制中的作用`
* The view mechanism indirectly implements the user permission definition that supports access predicates. Through the view mechanism, the data to be kept confidential is hidden from users who do not have access rights, thereby automatically providing a certain degree of security protection for the data.
# 5. Database integrity
1. `数据库完整性的概念 P4`
* Database integrity refers to the correctness and compatibility of data;
* The correctness of the data means that the data conforms to the semantics of the real world and reflects the current actual situation;
* Data compatibility means that the data of the same object in the database in different relational tables is logical
2. `数据库完整性和安全性的异同 P5`
* Data integrity is to prevent the existence of data that does not conform to semantics in the database, that is, to prevent the existence of incorrect data in the database;
* Data security is to protect the database from malicious damage and illegal access.
3. `数据库管理系统如何维护数据库的完整性 P6 - P10`
* 1) Provide a mechanism for defining integrity constraints;
* 2. Provide methods for integrity checking;
* 3. Handle breach of contract;
4. `实体完整性定义的代码 P13 - P16`
```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}}
(列名)PRIMARY KEY;
PRIMARY KEY(列名)(必须设置列名不为空值)
```
6. `实体完整性的检查和违约处理 P18`
Automatic check:
1. Check whether the main code value is unique. If not, reject insertion or modification;
2. Check whether each attribute of the main code is empty. As long as one of the attributes is empty, the insertion or modification will be refused.
One way to check whether the primary code in the record is the only one is to scan the entire table and determine whether the primary code value of each record in the table is the same as the primary code value to be inserted into the record (or the modified new primary code value).
7. `参照完整性定义的代码 P24 - P25`
* Referential integrity uses the FOREIGN KEY phrase in CREATE TABLE to define which columns are foreign keys, and the REFERENCES phrase is used to indicate which tables' primary keys these foreign keys refer to.
```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}}
FOREIGN KEY(列名)REFERENCES (表名)(列名)
```
8. `参照完整性的检查和违约处理 P27 - P35`
* Reject (NO ACTION) execution: The change operation is not allowed to be executed. This policy is generally set as the default policy;
* Cascade (CASCADE) operation: When deleting or modifying a tuple in the referenced table causes inconsistency with the reference table, delete or modify all tuples in the reference table that cause inconsistency.
* Set to null: When deleting or modifying a tuple in the referenced table causes inconsistency, set the corresponding attributes of all tuples in the reference table that cause inconsistency to null.
9. `用户定义完整性 P40 - P50`
* User-defined integrity is the semantic requirement that data for a specific application must meet.
1. **Constraints on attributes p163**
2. Definition of constraints on attributes
3. Checking and violation handling of constraints on attributes
4. **Constraints on tuples p163**
5. Definition of constraints on tuples
6. Checking and violating constraints on tuples
7. Integrity Constraint Named SQL P53 - P57
```SQL theme={"theme":{"light":"github-light","dark":"github-dark"}}
CONSTRAINT(完整性约束条件名)(完整性约束条件)
完整性约束条件包括
NOT NULL,UNIQUE,PRIMARY KEY,FOREIGN KEY,CHECK短语
可以使用ALTER TABLE语句修改表中的完整性限制
ALTER TABLE Student DROP CONSTRAINT C4;
ALTER TABLE Student ADD CONSTRAINT C1 CHECK(Sno BETWEEN 900000 AND 999999);
```
10. `触发器的定义、激活与删除 P68 - P78`
**Trigger** is a special type of [stored procedure](https://so.csdn.net/so/search?q=存储过程\&spm=1001.2101.3001.7020). Unlike a stored procedure, it is executed when triggered by an event rather than being called manually; a stored procedure must be invoked explicitly by name.
[Trigger](https://so.csdn.net/so/search?q=触发器\&spm=1001.2101.3001.7020): a trigger is a piece of code bound to a table in advance. When certain content in the table changes (insert, delete, or update), the system automatically fires the code and executes it.
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
delimiter 自定义结束符号
create trigger 触发器名字 触发时间 触发事件 on 表 for each row
begin
-- 触发器内容主体,每行用分号结尾
end
自定义的结束符合
delimiter ;
```
* A trigger is a special event-driven process defined by the user on a relational table.
* Definition of trigger P168
* The execution of a trigger is activated by a triggering event and is automatically executed by the database server.
* 1. Execute the BEFORE trigger on the table
2. SQL statement to activate trigger
3. Execute the AFTER trigger on the table
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
删除触发器的SQL语法:DROP TRIGGER(触发器名)ON(表名)
```
# 6. Relational Data Theory
* Data dependency is a constraint relationship between the internal attributes of a relationship. This constraint relationship is a correlation between data reflected by the equality of values between attributes. It is the abstraction of the interconnections between real-world attributes, the inherent nature of data, and the embodiment of semantics.
1. `现实世界已知语义得到的函数依赖 P13 - P14`
* Functional dependency is a ubiquitous type of data dependency
* Improper functional dependencies can cause many problems:
* 1. Data redundancy
* 2. Update exception
* 3. Insertion exception
* 4. Delete exceptions
2. `函数依赖 P22 - P26`
* Functional dependency, like other data dependencies, is a semantic category concept, and a functional dependency can only be determined based on semantics.
3. `平凡函数依赖与非平凡函数依赖 P27 - P28`
4. `完全函数依赖与部分函数依赖 P29 - P30`
5. `传递函数依赖 P31`

6. `1NF、2NF、3NF、BCNF的定义以及判断 P41 - P56,P81`
**First Normal Form (1NF)**
definition
> (1NF, Normal Form) If the domain value of each attribute A in a relational schema R is atomic, that is, the attribute value cannot be subdivided, then the relational schema R belongs to the first normal form, abbreviated as R ∈ 1NF. If every relational schema in database schema R is 1NF, database schema R∈1NF.
This is very easy to understand. Basically, as long as the question is given, it is a relationship model that satisfies the first paradigm.
**Second Normal Form (2NF)**
definition

2NF means that all non-primary attributes in our relational schema are completely dependent on each key. What does it mean? The most important thing here is to understand what `非主属性` is, what is `主属性`, what is `键`
It is recommended to read the summary of another blog to understand the meaning of the key: [https://blog.csdn.net/fjxcsdn/article/details/76549751](https://blog.csdn.net/fjxcsdn/article/details/76549751)
Read the blog I wrote before to understand the meaning of complete dependence and partial dependence: [Database Basics (3) Functional Dependency - Trivial Dependency, Complete Dependence, Partial Dependence, Transitive Dependence](https://blog.csdn.net/Candle_light/article/details/84424505)
How should you understand non-primary attributes and primary attributes? For example, suppose the relation schema is `R={A,B,C,D}` and the candidate key of `R` is `AD`. Then `A` and `D` are primary attributes, while `B` and `C` are non-primary attributes. **`包含在候选键里的属性就是主属性!`**
Now that we understand the meaning of keys and dependencies, we can take a closer look at what 2NF is.
**`举例子1:`**
> #### Given `R = {A, B, C}` and the functional dependency set `F = {B → C, AC → B}`, determine whether the relation schema is in 2NF
So let’s first look at who the keys are in this R relational model.
Use `数据库基础(4)中我们学习的属性闭包算法` to find the candidate key of R: AC
So the **second step** is to see if there are any non-primary attributes that partially depend on the main attribute AC (our non-primary attribute here is B)
Obviously no part of B depends on A or C, so R is 2NF
**`举例子2`**
> #### Given `R = {A, B, C, D}` and the functional dependency set `F = {A → C, AD → B}`, determine whether the relation schema is in 2NF
Like the first example, we first see who the keys in R are
Using the attribute closure algorithm, the candidate key of R is found to be: AD (AD+ = ABCD), so C and B are both non-primary attributes, and A and D are primary attributes.
Therefore, it is obvious that we find that A in AD can independently determine C (A->C), so C partially depends on AC, there are non-primary attributes that partially depend on primary attributes, and R is not 2NF
**Third Normal Form (3NF)**
definition

The meaning of the third normal form is that **the key of `没有非主属性传递依赖` in R**, R is 3NF
There is also a condition implicit here, that is, if `主属性传递依赖` in R is the key of R, then R also satisfies 3NF.
**Be careful to distinguish between primary attribute transitive dependencies and non-primary attribute transitive dependencies**
`举例子1`
> #### Given `R(A, B, C)` and the functional dependency set `F = {B → C, AC → B}`, determine whether the relation schema is in 3NF
Let's make a judgment. The first step is to find the key! We found that AC is a candidate key (AC+=ABC, a candidate key obtained through the attribute closure algorithm)
At the same time, since AC->B, B->C, C transitively depends on AC. So is R 3NF?
R is of course 3NF, because the candidate key of R is AC, so C is the primary attribute, so here is `主属性C` transitively dependent on the key AC, R is 3NF
Notice! `只有当非主属性传递依赖于R的时候,R才不是3NF`
`举例子2`
> #### Given `R(A, B, C, D)` and the functional dependency set `F = {AB → C, C → D}`, determine whether the relation schema is in 3NF
The first step is to find the key! It is found that AB is a candidate key, but since AB -> C, C -> D, D transitively depends on AB
So is R 3NF?
Of course R is not 3NF, because D is a non-primary attribute, so here the non-primary attribute D transitively depends on the primary attribute AB, so it does not meet the definition of 3NF.
**`Boyce-Codd范式(BCNF)`**
definition

BCNF is the most advanced, it refers to `没有任何属性传递依赖于R中的任何一个键` in R. So think of Example 1 in our 3NF above. Although it satisfies 3NF, it is not BCNF because the main attribute transitively depends on the key.
Look at the examples and determine which normal form it is.

Obviously, both are BCNF, because there is no transitive dependency on any attribute.
Finally, a relationship model that satisfies BCNF must also satisfy 3NF; similarly, a relationship model that satisfies 3NF must also satisfy 2NF.
# 7. Database design
1. `数据库设计的概念 1P6`
Database design refers to constructing (designing) an optimized database logical model and physical structure for a given application environment, and establishing a database and its application system accordingly so that it can effectively store and manage data and meet the application needs of various users, including information management system requirements and data operation requirements.
3. `数据库高效率的运行环境 1P7`
Database data access efficiency, database storage space utilization, database system operation and management efficiency
4. `数据库设计的特点 1P10 - 1P12`
Heuristic, iterative, multi-step, data-oriented
5. `数据库设计的基本步骤 1P18`
* Requirements design
* conceptual structural design
* Logical structure design
* physical structure design
* Database implementation
* Database operation and maintenance
6. `数据库设计各个阶段的数据设计描述 1P25`
* P 209
7. `需求分析的任务 1P36 - 1P38`
The task of requirements analysis is to fully understand the working profile of the original system (manual system or computer system) through detailed investigation of the objects to be dealt with in the real world (organizations, departments, enterprises, etc.), clarify the various needs of users, and then confirm the functions of the new system on this basis. The focus of the investigation is "data" and "processing". Through investigation, collection and analysis, the following user requirements for the database are obtained:
* information request
* processing request
* Security and integrity requirements
8. `需求分析的方法 1P40`
* Investigate the status of the organization
* Investigate the business activities of various departments
* Based on familiarity with business activities, assist users to clarify various requirements for the new system, including information requirements, processing requirements, security and integrity requirements
* Determine the boundaries of the new system
Common investigation methods:
* Follow-up homework
* Hold an investigation meeting
* Please introduce someone
* ask
* Please fill in the design questionnaire
* View records
9. `E-R模型的提出者 1P58`
* P.P.S.Chen
10. `实体之间联系的类型 1P59 - 1P67`
* Relationship between two entity types: one-to-one, one-to-many, many-to-many
* The relationship between two or more entity types
* Relationships within a single entity type
11. `E-R图 1P68 - 1P74`
Rectangles are used for entities, ovals are used for attributes, and diamonds are used for relationships.
12. `实体与属性的划分原则 1P77`
Treat as attributes as much as possible what can be treated as attributes
13. `E-R图的集成 1P87 - 1P94`
* Merge and resolve conflicts between E-R diagrams
* Modify and refactor to eliminate unnecessary redundancy
* Conflict types: 1. Attribute conflict, 2. Naming conflict, 3. Structure conflict
14. `E-R图向关系模型的转换 2P7 - 2P13`
* An entity type is converted into a relationship schema. The attributes of the relationship are the attributes of the entity, and the code of the relationship is the code of the entity.
15. `优化数据模型的方法 2P19`
* Determine data dependencies
* Minimize data dependencies between various relational schemas
* Analyze the relationship patterns one by one according to the theory of data dependence
* Based on the processing requirements obtained in the requirements analysis stage, analyze whether these patterns are suitable for such an application environment and determine whether certain patterns need to be merged or decomposed.
* Perform necessary decomposition of the relational model to improve data operation efficiency and storage space utilization. Two commonly used decomposition methods are horizontal decomposition and vertical decomposition.
16. `数据库物理设计的步骤 2P32`
* The process of selecting a physical structure that best suits application requirements for a given logical data model is the physical design of the database.
* 1. Determine the physical structure of the database, which in relational databases mainly refers to the access method and storage structure.
2. Evaluate physical structures with emphasis on time and space efficiency
3. Common access methods of database management systems 2P39
* Index method and clustering method, B+ tree index and hash index P236
17. `影响数据存放位置和存储结构的因素 2P53`
* Access time, storage space utilization, maintenance cost, hardware environment, application requirements
# 8. Database Programming
1. `python关联MySQL的包(Package)是什么 P9`
* PyMySQL
2. `游标的好处 P22`
* A cursor is a data buffer opened by the system for users to store the execution results of SQL statements. Each cursor area has a name.
* Users can obtain records one by one through the cursor and assign them to the main variable, which is then handed over to the main language for further processing.
* After using the cursor function, we can save the results first, and then we can do our own programming at will to get the result set we ultimately want.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
Cursor = (数据库名).db.cursor
```
3. `tornado web服务器的四大组件 P62-P63`
* ioloop instance, app instance, handler class, routing table
4. `GET和POST的区别 P65`
* The methods of passing parameters are different: Get includes the parameters in the URL, and Post passes the parameters through the request body;
* URL visibility is different: the parameters of the get request can be seen directly, but the parameter URL of the post request is not visible;
* The size of the data passed is different: the length of the data passed in the get request is limited by the URL size, while the post request has no length limit
* The impact of going back on the page is different: going back on get will not have any impact, but going back on post will resubmit;
* Different encoding methods: get requests only support URL encoding, while post requests support multiple encoding methods;
5. `SQL 变量的定义 P73 - P76`
In SQL, a variable is a container used to store data
6. `流程控制 P80 - P97`
* Flow control statements can be used in stored procedures and custom functions to control the flow of the program.
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
流程控制语句:
IF 语句;
CASE语句;
LOOP语句;
LEAVE语句;
ITERATE语句;
REPEAT语句;
WHILE语句;
```
7. `匿名块与命名块 P100`
* Anonymous block: It must be compiled every time it is executed. It cannot be stored in the database and cannot be called in other procedural SQL blocks;
* Named block: After compilation, it is saved in the database and is called a persistent storage module. It can be called repeatedly and runs faster. Procedures and functions are named blocks.
8. `存储过程的定义 P102`
* A stored procedure is a database object that stores complex programs in the database so that they can be called by external programs.
9. `存储过程的优点 P103`
* High efficiency when traveling far away
* Reduced communication volume between client and server
* Facilitate implementation of corporate rules
10. `存储过程的缺点 P104`
* Stored procedures are often customized to a specific database because of the different supported programming languages. When switching to a database system from another manufacturer, the original stored procedures need to be rewritten.
* Performance tuning and writing of stored procedures, limited by various database systems
11. `存储过程的SQL代码 P107 - P117`
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
创建存储过程:CREATE PROCEDURE (过程名)(参数)(过程化SQL块)
声明语句结束符,可以自定义:DELIMITER $$或DELIMITER//
DELIMITER $$
CREATE PROCEDURE delete_sno ( IN p_sno CHAR(9))
BEGIN
DELETE FROM Student WHERE sno = p_sno ;
END$$
DELIMITER ;
执行存储过程:CALL(过程名)(参数)
CALL delete__sno(‘201215122’);
删除存储过程:DROP PROCEDURE(过程名)
```
12. `函数与存储过程的异同 P119`
* Same: both are persistent storage modules
* Exception: The function must specify the return type
13. `函数的SQL代码 P120 - P122`
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
1.定义语句格式:CREATE FUNCTION (函数名)(参数)RETURN(类型)(过程化SQL块)
DELIMITER //
CREATE FUNCTION func_student ( f_Sno CHAR(9))
RETURNS CHAR(20) DETERMINISTIC
COMMENT ’ 查 询 某 个 学 生 的 姓 名 ’
BEGIN
RETURN (SELECT Sname FROM Student WHERE Sno = f_Sno ) ;
END //
DELIMITER ;
2.函数的执行语句格式:SELECT(函数名)(参数)
SELECT func_student(‘201215123’);
SELECT func_student(sno) FROM Stduent;
3.删除函数:DROP FUNCTION(函数名)
```
# 9. MySQL optimization principles
1. `MySQL各组件之间协同工作的逻辑架构 P6 - P9`
* 9-MySQL optimization principles.pdf
2. `MySQL的查询过程 P12,P38`
* 1) Client/server communication protocol
* 2. Query cache
* 3. Grammar parsing and preprocessing
* 4. Query optimization
* 5. Query execution engine
* 6. Return the results to the client
# 10. Database recovery technology
1. `事务的概念 P7`
* A transaction is a user-defined database operating system sequence. These operations are either done or not done at all. It is an indivisible unit of work;
* Transaction is the basic unit of database recovery and concurrency control
2. `事务的显示控制 P8 - P9`
* 10-Database recovery technology.pdf
3. `事务的ACID特性 P13 - P19`
* Atomicity: A transaction is a logical unit of work in the database, either all are done or none are done;
* Consistency: The result of transaction execution must be to change the database from one consistency state to another consistency state;
* Isolation: The execution of a transaction cannot be interfered with by other transactions;
* Continuity: Continuity is also called permanence. Once a transaction is committed, its changes to the data in the database should be permanent, and subsequent other operations or failures should not have any impact on its execution results.
4. `数据库恢复的背景和原因 P21`
* Failures are inevitable:
* 1. Computer hardware failure;
2. software errors;
3. operator error
4. malicious destruction
* Impact of failure:
* 1. Abnormal interruption of running transactions affects the correctness of data in the database
2. Corruption of the database, complete or partial loss of data
5. `数据库恢复的概念 P22`
* Database recovery: Database management must have the function of restoring the database from an error state to a known correct state (also known as a consistent state or a complete state). This is the database recovery management system's response to failures; the recovery subsystem is an important part of the database management system; recovery technology is an important indicator to measure the quality of the system.
6. `故障的种类 P24 - P38`
* Failure within the accident
* System failure
* media failure
* computer virus
7. `恢复机制的两个关键问题 P40`
* How to create redundant data (1. Data dump 2. Register log file 3. Both are often used together)
* How to use these redundant data to implement database recovery
8. `数据转储的概念 P43 - P44`
* Data dump is the basic technique used in database recovery
* Dumping is a process in which the database administrator periodically copies the entire database to tape, disk, or other storage media.
* These spare data texts are called backup copies or fallback copies
9. `数据转储的方法 P47 - P52`
* Static dump and dynamic dump
* Mass dump and incremental dump
* Summary of dump methods (dynamic mass dump, static mass dump, dynamic incremental dump, static incremental dump)
10. `日志文件的概念 P55`
* Log files are files used to record transactions and database update operations.
11. `以记录为单位的日志文件内容 P56 - P57`
* Start tag of each transaction
* End mark of each transaction
* All update operations for each transaction
* Here the start mark of each transaction, the end mark of each transaction and each update operation are treated as a log record in the log file
Log record content:
1. Transaction ID
2. Operation type
3. Operation object
4. The old value of the data before updating
5. The new value of the updated data
6. `以数据块为单位的日志文件内容 P58`
* transaction mark
* updated data block
13. `日志文件的作用 P59 - P61`
* Perform transaction failure recovery
* Perform system failure recovery
* Assists standby copies with media failure recovery
14. `登记日志文件的原则 P63`
15. The order of registration is strictly based on the time order of concurrent transaction execution.
16. The log file must be written first and then the database.
* (Write log file operation: write the log record representing this modification to the log file;
* Write database operation: write the modifications to the data into the database;
This is the principle of "write the log file first")
15. `先写日志文件的原因 P64`
* Writing to the database and writing to the log are two different operations
* A failure may occur between these two operations
* If the database modification is written first and the modification is not registered in the log file, the modification cannot be restored later.
* If the log is written first, but the database is not modified, restoring based on the log file will only perform one more unnecessary UNDO operation, which will not affect the correctness of the database.
* Therefore, for safety, you must write the log file first, that is, first write the log records to the log file, and then write the modifications to the database.
16. `事务故障的恢复方法 P67`
* Modifications that have been made to the database by this transaction are undoed (UNDO) by the recovery subsystem using the log file.
17. `事务故障恢复的步骤 P68 - P69`
* Scan the file log in reverse direction (that is, scan the log file from the end forward) to find the update operation of the transaction
* Performs the reverse operation of the transaction's update operation. That is, writing the "pre-update value" in the log record to the database
* (Insertion operation: If the "value before update" is empty, it is equivalent to a delete operation;
* Delete operation: If the "updated value" is empty, it is equivalent to an insertion operation;
* If it is a modification operation, it is equivalent to replacing the modified value with the pre-modified value)
18. `系统故障的恢复方法 P71`
1. Undo (undo) the unfinished transaction when the failure occurred;
2. Redo (redo) completed transactions
19. `系统故障的恢复步骤 P72 - P73`
1. Scan the log file forward (that is, scan the log file from the beginning) to find transactions that were committed before the failure occurred
2. Undo (UNDO) processing of undo (UNDO) queue transactions
3. Redo (REDO) processing of redo (REDO) queue transactions
20.`介质故障的恢复方法 P75`
1. Reinstall database
2. Redo completed transactions
3. `介质故障的恢复步骤 P76 - P77`
4. Load the latest standby database copy (the dump copy closest to the time of the failure) to restore the database to the consistency state of the latest dump
5. Load a copy of the relevant log file (a copy of the log file at the end of the dump) and redo the completed transaction
6. `为什么要具有检查点的恢复技术 P81`
7. Searching the entire log will take a lot of time
8. Many transactions that need to be redone have actually written the results of their update operations to the database, but the recovery subsystem has to re-perform these operations, which wastes a lot of time.
# Databases
Source: https://base.bangwu.me/backend/SQL/index
Database technology hub covering MySQL relational database operations, SQLite embedded usage, and core concepts like normalization and ACID.
MySQL is the most popular open-source relational database, widely used in web applications.
## Core Features
* **High Performance**: Optimized query engine
* **Reliability**: ACID transaction support
* **Scalability**: Master-slave replication, sharding
* **Free & Open Source**: Community edition is fully free
> [card] [MySQL Basics](/backend/SQL/mysql)
>
> SQL syntax reference — CRUD to advanced queries.
> [card] [Database Concepts](/backend/SQL/db-knowledge)
>
> Core concepts — indexes, transactions, normalization.
> [card] [SQLite](/backend/SQL/sqlite)
>
> Lightweight embedded database for small apps.
## Resources
* [MySQL Official Docs](https://dev.mysql.com/doc/)
* Visualization tools: Navicat, DBeaver, MySQL Workbench
# MySQL
Source: https://base.bangwu.me/backend/SQL/mysql
MySQL learning notes covering CREATE/INSERT/UPDATE/DELETE statements, single and multi-table queries, index optimization, and user permissions.
# First introduction to database
## What is a database
> **Database: DB (DataBase)**
**Concept**: Data warehouse, `软件`, installed on the operating system
**Function**: Store data, manage data
***
## Database classification
**Relational database: SQL** (Structured Query Language)
* MySQL, Oracle, Sql Server, DB2, SQLlite
* Store data through relationships between tables and between rows and columns
* Establish relationships between tables through foreign key associations
**Non-relational database: NoSQL** (Not Only SQL)
* Redis, MongoDB
* Refers to data stored in the database in the form of **objects**, and the relationship between objects is determined by the properties of each object itself
***
## Related concepts
> **DBMS (Database Management System)**
* Database management software\*\*, scientific and effective management, maintenance and acquisition of our data
* **MySQL** is a database management system

***
## MySQL and its installation
* [MySQL latest version 8.0.21 installation and configuration tutorial\~](https://bareth.blog.csdn.net/article/details/107369405)
## Basic commands
> All statements must end with a semicolon;
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
show databases; -- 查看当前所有的数据库
use 数据库名; -- 打开指定的数据库
show tables; -- 查看所有的表
describe/desc 表名; -- 显示表的信息
create database 数据库名; -- 创建一个数据库
exit -- 退出连接
```
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- -- 单行注释
# -- 单行注释
/*...*/ -- 多行注释
```
\#Operation database
\##Operation database
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 创建数据库
CREATE DATABASE [IF NOT EXISTS] 数据库名; CREATE SCHEMA
-- 删除数据库
DROP DATABASE [if EXISTS] 数据库名; DROP SCHEMA
-- 使用数据库
-- 如果表名或者字段名是特殊字符,则需要带``
use 数据库名;
-- 查看数据库
SHOW DATABASES;
```
## Database column type
> **Value**
| `数据类型` | `描述` | `大小` |
| :-: | :-: | :-: |
| tinyint | very small data | 1 byte |
| smallint | smaller data | 2 bytes |
| mediumint | medium size data | 3 bytes |
| int | standard integer | 4 bytes |
| bigint | Larger data | 8 bytes |
| float | floating point number | 4 bytes |
| double | floating point number | 8 bytes |
| decimal | Floating point number in string form, generally used for financial calculations | |
> string
| `数据类型` | `描述` | `大小` |
| :-: | :-: | :-: |
| char | String fixed size | 0\~255 |
| varchar | variable string | 0\~65535 |
| tinytext | tiny text | 2^8-1 |
| text | text string | 2^16-1 |
> Time and date
| `数据类型` | `描述` | `格式` |
| :-: | :-: | :-: |
| date | date format | YYYY-MM-DD |
| time | time format | HH: mm: ss |
| datetime | The most commonly used time format | YYYY-MM-DD HH: mm: ss |
| timestamp | Timestamp, number of milliseconds from 1970.1.1 to now | |
| year | Year representation | |
> null
* no value, unknown
* Do not use NULL values for calculations
## Database field attributes
> **UnSigned**
* unsigned
* Declared that the column cannot be negative
> ZEROFILL
* 0 padded
* Fill the missing digits with 0, such as int(3), 5 is 005
> **Auto\_InCrement**
* Usually understood as auto-increment, it automatically defaults to +1 based on the previous record.
* Usually used to design a unique primary key, which must be an integer type
* Definable starting value and step size
* Current table setting step size (AUTO\_INCREMENT=100): only affects the current table
* SET @@auto\_increment\_increment=5 ; affects all tables using auto-increment (global)
> **NULL and NOT NULL**
* The default is NULL, that is, no value is inserted into the column
* If set to NOT NULL, the column must have a value
> **DEFAULT**
* default
* used to set default values
* For example, the gender field defaults to "male", otherwise it is "female"; if the value of this column is not specified, the default value is the value of "male"
**Extension**: Every table must have the following five fields:
| Name | Description |
| :-: | :-: |
| id | primary key |
| version | optimistic locking |
| is\_delete | Pseudo delete |
| gmt\_create | Creation time |
| gmt\_update | modification time |
## Create database table
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE IF NOT EXISTS `student`(
`id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号',
`name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名',
`pwd` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码',
`sex` VARCHAR(2) NOT NULL DEFAULT '女' COMMENT '性别',
`birthday` DATETIME DEFAULT NULL COMMENT '出生日期',
`address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址',
`email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
```
`注意点`:
* Try to use \`\` brackets in table names and fields.
* AUTO\_INCREMENT represents automatic increment
* Add commas after all statements, except the last one.
* Strings are enclosed in single quotes
* The declaration of the primary key is generally placed at the end for easy viewing.
* If the character set encoding is not set, MySQL's default character set encoding Latin1 will be used. Chinese is not supported and can be modified in my.ini.
> Format:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE IF NOT EXISTS `student`(
'字段名' 列类型 [属性] [索引] [注释],
'字段名' 列类型 [属性] [索引] [注释],
......
'字段名' 列类型 [属性] [索引] [注释]
)[表的类型][字符集设置][注释]
```
`常用命令`
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SHOW CREATE DATABASE 数据库名;-- 查看创建数据库的语句
SHOW CREATE TABLE 表名;-- 查看表的定义语句
DESC 表名;-- 显示表的具体结构
```
## Database storage engine
**INNODB**
* Used by default, has high security, supports transaction processing, and multi-table and multi-user operations
**MYISAM**
* Used in earlier years, saving space and faster
| | MYISAM | INNODB |
| - | - | - |
| **Transaction support** | Not supported | Supported |
| **Data Row Locking** | Not supported | Supported |
| **Foreign key constraints** | Not supported | Supported |
| **Full text index** | Supported | Not supported |
| **Table space size** | Smaller | Larger, about 2 times |
> **Physical space location where the database file exists**:
* MySQL data tables are stored on disk as files
-Including table files, data files, and database option files
* Location: `Mysql安装目录\data\` (the directory name corresponds to the database name, and the file name in this directory corresponds to the data table)

**MySQL differs in file engine:**
* `INNODB`Database file types include **.frm**, **.ibd** and **ibdata1** files in the upper-level directory
* MYISAM storage engine, database file types include
* **.frm**: table structure definition file
* **.MYD**: data file
* **.MYI**: index file
## Modify database
> **Modify**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 修改表名
-- ALTER TABLE 旧表名 RENAME AS 新表名
ALTER TABLE teacher RENAME AS teachers;
-- 增加表的字段
-- ALTER TABLE 表名 ADD 字段名 列属性
ALTER TABLE teachers ADD age INT(11);
-- 修改表的字段(重命名,修改约束)
-- ALTER TABLE 表名 MODIFY 字段名 [列属性];
ALTER TABLE teachers MODIFY age VARCHAR(11);-- 修改约束
-- ALTER TABLE 表名 CHANGE 旧名字 新名字 [列属性];
ALTER TABLE teachers CHANGE age age1 INT(1);-- 字段重命名
-- 删除表的字段
-- ALTER TABLE 表名 DROP 字段名
ALTER TABLE teachers DROP age1;
```
> **DELETE**
**Syntax**: DROP TABLE \[IF EXISTS] table name
* IF EXISTS is optional to determine whether the data table exists
* If you delete a non-existent data table, an error will be thrown.
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 删除表(如果存在再删除)
DROP TABLE IF EXISTS teachers;
```
**All creation and deletion should be judged as much as possible to avoid errors\~**
\#MySQLData Management
## Foreign keys
> **Foreign Key Concept**
If a common key is the primary key in one relationship, then the common key is called a foreign key in another relationship. It can be seen that the foreign key represents the interconnection between the relationships between two people. The table with the foreign key of another relationship as the primary key is called `主表`,具有此外键的表被称为主表的`从表`.
In actual operation, the value of one table is put into the second table to represent the association, and the value used is the primary key value of the first table (including the composite primary key value if necessary). At this point, the attribute in the second table that holds these values is called the foreign key (`foreign key`).
**Foreign key function**:
Maintain data `一致性`,`integrity`,主要目的是控制存储在外键表中的数据,`constraint`. To associate two tables, the foreign key can only refer to the values of columns in the table or use null values.
***
Target: The gradeid field of the student table (student) is to reference the gradeid field of the grade table (grade).
> **Create foreign key**
**Method 1: Add constraints when creating the table**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
/*
1. 定义外键key
2. 给外键添加约束(执行引用)references 引用
*/
CREATE TABLE IF NOT EXISTS `student`(
`id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号',
`name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名',
`pwd` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码',
`sex` VARCHAR(2) NOT NULL DEFAULT '女' COMMENT '性别',
`birthday` DATETIME DEFAULT NULL COMMENT '出生日期',
`address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址',
`email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
`gradeid` INT(10) NOT NULL COMMENT '学生的年级',
PRIMARY KEY (`id`),
KEY `FK_gradeid` (`gradeid`),
CONSTRAINT `FK_gradeid` FOREIGN KEY (`gradeid`) REFERENCES `grade`(`gradeid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
-- 创建年级表
CREATE TABLE `grade`(
`gradeid` INT(10) NOT NULL COMMENT '年级id',
`gradename` VARCHAR(50) NOT NULL COMMENT '年纪名称',
PRIMARY KEY (`gradeid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
```
When deleting a table with a foreign key relationship, you must first delete the table that refers to someone else (slave table), and then delete the referenced table (master table)
***
**Method 2: After successfully creating the table, add foreign key constraints**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
/*
1. 定义外键key
2. 给外键添加约束(执行引用)references 引用
*/
CREATE TABLE IF NOT EXISTS `student`(
`id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号',
`name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名',
`pwd` VARCHAR(20) NOT NULL DEFAULT '123456' COMMENT '密码',
`sex` VARCHAR(2) NOT NULL DEFAULT '女' COMMENT '性别',
`birthday` DATETIME DEFAULT NULL COMMENT '出生日期',
`address` VARCHAR(100) DEFAULT NULL COMMENT '家庭住址',
`email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
`gradeid` INT(10) NOT NULL COMMENT '学生的年级',
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
-- 创建表的时候没有外键关系
ALTER TABLE `student`
ADD CONSTRAINT `FK_gradeid` FOREIGN KEY(`gradeid`) REFERENCES `grade`(`gradeid`);
-- 创建年级表
CREATE TABLE `grade`(
`gradeid` INT(10) NOT NULL COMMENT '年级id',
`gradename` VARCHAR(50) NOT NULL COMMENT '年纪名称',
PRIMARY KEY (`gradeid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
```
The above operations are all physical foreign keys, database-level foreign keys, and are not recommended! Avoid trouble caused by too many databases!
`最佳实践`
* The database is a simple table, only used to store data, only rows (data) and columns (attributes)
* We want to use data from multiple tables, use foreign keys, and implement it with programs
***
## DML language
`数据库的意义`:Data storage, data management
> `Data Manipulation Luaguge`: Database operation language
### 1. Add [insert](https://so.csdn.net/so/search?q=insert\&spm=1001.2101.3001.7020)
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 普通用法
INSERT INTO `student`(`name`) VALUES ('zsr');
-- 插入多条数据
INSERT INTO `student`(`name`,`pwd`,`sex`) VALUES ('zsr','200024','男'),('gcc','000421','女');
-- 省略字段
INSERT INTO `student` VALUES (5,'Bareth','123456','男','2000-02-04','武汉','1412@qq.com',1);
12345678
```
**grammar:**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
INSERT INTO 表名([字段1,字段2..])VALUES('值1','值2'..),[('值1','值2'..)..];
```
**Notice**:
1. Use commas to separate fields.
2. Fields can be omitted, but the values must be complete and one-to-one correspondence
3. Multiple pieces of data can be inserted at the same time. The values after VALUES need to be separated by commas.
***
### 2. Modify update
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 修改学员名字,指定条件
UPDATE `student` SET `name`='zsr204' WHERE id=1;
-- 不指定条件的情况,会改动所有表
UPDATE `student` SET `name`='zsr204';
-- 修改多个属性
UPDATE `student` SET `name`='zsr',`address`='湖北' WHERE id=1;
-- 通过多个条件定位数据
UPDATE `student` SET `name`='zsr204' WHERE `name`='zsr' AND `pwd`='200024';
1234567891011
```
**grammar**:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
UPDATE 表名 SET 字段1=值1,[字段2=值2...] WHERE 条件[];
```
**About WHERE conditional statements**:
| Operator | Meaning |
| - | - |
| `=` | equal to |
| `<>` or `!=` | Not equal to |
| `>` | Greater than |
| `<` | Less than |
| `<=` | Less than or equal to |
| `>=` | Greater than or equal to |
| `BETWEEN…AND…` | Closed interval |
| `AND` | and |
| `OR` | or |
***
### 3. Delete delete
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 删除数据(避免这样写,会全部删除)
DELETE FROM `student`;
-- 删除指定数据
DELETE FROM `student` WHERE id=1;
```
**grammar**:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
DELETE FROM 表名 [WHERE 条件]
```
Regarding the problem of deleting `DELETE` and restarting the database:
* INNODB auto-increment columns will start from 1 (stored in memory and lost when power is turned off)
* MYISAM continues from the previous sub-increment (stored in memory and will not be lost)
> TRUNCATE
**Function**: Completely clear a database table, the structure and index constraints of the table will not change!
**The difference between DELETE and TRUNCATE:**
* DELETE can delete conditionally (where clause), while TRUNCATE can only delete the entire table
* TRUNCATE resets the auto-increment column and the counter will return to zero, while DELETE will not affect the auto-increment
* DELETE is a data manipulation language (DML - Data Manipulation Language). During the operation, the original data will be placed in the rollback segment and can be rolled back; while TRUNCATE is a data definition language (DDL - Data Definition Language). It will not be stored during the operation and cannot be rolled back.

```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE `test`(
`id` INT(4) NOT NULL AUTO_INCREMENT,
`coll` VARCHAR(20) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `test`(`coll`) VALUES('1'),('2'),('3');
-- 不会影响自增
DELETE FROM `test`;
-- 会影响自增
TRUNCATE TABLE `test`;
```
***
# DQL query data
> `Data QueryLanguage`: Data query language
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SELECT [ALL | DISTINCT]
{* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,...]]}
FROM table_name [as table_alias]
[left | right | inner join table_name2] -- 联合查询
[WHERE ...] -- 指定结果需满足的条件
[GROUP BY ...] -- 指定结果按照哪几个字段来分组
[HAVING] -- 过滤分组的记录必须满足的次要条件
[ORDER BY ...] -- 指定查询记录按一个或多个条件排序
[LIMIT {[offset,]row_count | row_countOFFSET offset}]; -- 指定查询的记录从哪条至哪条
```
* Query database data, such as SELECT statements
* Simple single table query or complex query and nested query of multiple tables
* It is the core and most important statement in the database language
* Most frequently used statements
`前提配置`:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 创建学校数据库
CREATE DATABASE IF NOT EXISTS `school`;
-- 用school数据库
USE `school`;
-- 创建年级表grade表
CREATE TABLE `grade`(
`GradeID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '年级编号',
`GradeName` VARCHAR(50) NOT NULL COMMENT '年纪名称',
PRIMARY KEY (`GradeID`)
)ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- 给grade表插入数据
INSERT INTO `grade`(`GradeID`,`GradeName`)
VALUES (1,'大一'),(2,'大二'),(3,'大三'),(4,'大四');
-- 创建成绩result表
CREATE TABLE `result`(
`StudentNo` INT(4) NOT NULL COMMENT '学号',
`SubjectNo` INT(4) NOT NULL COMMENT '考试编号',
`ExamDate` DATETIME NOT NULL COMMENT '考试日期',
`StudentResult` INT(4) NOT NULL COMMENT '考试成绩',
KEY `SubjectNo` (`SubjectNo`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
-- 给result表插入数据
INSERT INTO `result`(`StudentNo`,`SubjectNo`,`ExamDate`,`StudentResult`)
VALUES (1000,1,'2019-10-21 16:00:00',97),(1001,1,'2019-10-21 16:00:00',96),
(1000,2,'2019-10-21 16:00:00',87),(1001,3,'2019-10-21 16:00:00',98);
-- 创建学生表student
CREATE TABLE `student`(
`StudentNo` INT(4) NOT NULL COMMENT '学号',
`LoginPwd` VARCHAR(20) DEFAULT NULL,
`StudentName` VARCHAR(20) DEFAULT NULL COMMENT '学生姓名',
`Sex` TINYINT(1) DEFAULT NULL COMMENT '性别,取值0或1',
`GradeID` INT(11) DEFAULT NULL COMMENT '年级编号',
`Phone` VARCHAR(50) NOT NULL COMMENT '联系电话,允许为空,即可选输入',
`Adress` VARCHAR(255) NOT NULL COMMENT '地址,允许为空,即可选输入',
`BornDate` DATETIME DEFAULT NULL COMMENT '出生时间',
`Email` VARCHAR(50) NOT NULL COMMENT '邮箱账号,允许为空,即可选输入',
`IdentityCard` VARCHAR(18) DEFAULT NULL COMMENT '身份证号',
PRIMARY KEY (`StudentNo`),
UNIQUE KEY `IdentityCard` (`IdentityCard`),
KEY `Email` (`Email`)
)ENGINE=MYISAM DEFAULT CHARSET=utf8;
-- 给学生表插入数据
INSERT INTO `student`(`StudentNo`,`LoginPwd`,`StudentName`,`Sex`,`GradeID`,`Phone`,`Adress`,`BornDate`,`Email`,`IdentityCard`)
VALUES (1000,'1241','dsaf',1,2,'24357','unknow','2000-09-16 00:00:00','1231@qq.com','809809'),
(1001,'1321','dfdj',0,2,'89900','unknow','2000-10-16 00:00:00','5971@qq.com','908697');
-- 创建科目表
CREATE TABLE `subject`(
`SubjectNo` INT(11) NOT NULL AUTO_INCREMENT COMMENT '课程编号',
`SubjectName` VARCHAR(50) DEFAULT NULL COMMENT '课程名称',
`ClassHour` INT(4) DEFAULT NULL COMMENT '学时',
`GradeID` INT(4) DEFAULT NULL COMMENT '年级编号',
PRIMARY KEY (`SubjectNo`)
)ENGINE=INNODB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
-- 给科目表subject插入数据
INSERT INTO `subject`(`SubjectNo`,`SubjectName`,`ClassHour`,`GradeID`)
VALUES(1,'高数','96',2),(2,'大物','112',2),(3,'程序设计',64,3);
SELECT 字段 FROM 表;
```
## **Basic Query**
`语法`:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SELECT 查询列表 FROM 表名;
```
* The query list can be: (one or more) fields in the table, constants, variables, expressions, functions
* The query result is a virtual table
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 查询全部学生
SELECT * FROM student;
-- 查询指定的字段
SELECT `LoginPwd`,`StudentName` FROM student;
-- 别名 AS(可以给字段起别名,也可以给表起别名)
SELECT `StudentNo` AS 学号,`StudentName` AS 学生姓名 FROM student AS 学生表;
-- 函数 CONCAT(str1,str2,...)
SELECT CONCAT('姓名',`StudentName`) AS 新名字 FROM student;
-- 查询系统版本(函数)
SELECT VERSION();
-- 用来计算(计算表达式)
SELECT 100*53-90 AS 计算结果;
-- 查询自增步长(变量)
SELECT @@auto_increment_increment;
-- 查询有哪写同学参加了考试,重复数据要去重
SELECT DISTINCT `StudentNo` FROM result;
```
## Query conditions
> where conditional statement: retrieve the value of `符合条件` in the data
**grammar**:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
select 查询列表 from 表名 where 筛选条件;
```
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 查询考试成绩在95~100之间的
SELECT `StudentNo`,`StudentResult` FROM result
WHERE `StudentResult`>=95 AND `StudentResult`<=100;
-- &&
SELECT `StudentNo`,`StudentResult` FROM result
WHERE `StudentResult`>=95 && `StudentResult`<=100;
-- BETWEEN AND
SELECT `StudentNo`,`StudentResult` FROM result
WHERE `StudentResult`BETWEEN 95 AND 100;
-- 查询除了1000号以外的学生
SELECT `StudentNo`,`StudentResult` FROM result
WHERE `StudentNo`!=1000;
-- NOT
SELECT `StudentNo`,`StudentResult` FROM result
WHERE NOT `StudentNo`=1000;
-- 查询名字含d的同学
SELECT `StudentNo`,`StudentName` FROM student
WHERE `StudentName` LIKE '%d%';
-- 查询名字倒数第二个为d的同学
SELECT `StudentNo`,`StudentName` FROM student
WHERE `StudentName` LIKE '%d_';
-- 查询1000,1001学员
SELECT `StudentNo`,`StudentName` FROM student
WHERE `StudentNo` IN (1000,1001);
```
## Group query
`语法`:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
select 分组函数,分组后的字段
from 表
【where 筛选条件】
group by 分组的字段
【having 分组后的筛选】
【order by 排序列表】
```
`区别`:
\| | table filtered using keywords | location |
\| ---------- | ---------- | ---------- | --------------- |
\| Filter before grouping | where | original table | before group by |
\| Filtering after grouping | having | results after grouping | behind group by |
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 查询不同科目的平均分、最高分、最低分且平均分大于90
-- 核心:根据不同的课程进行分组
SELECT SubjectName,AVG(StudentResult),MAX(`StudentResult`),MIN(`StudentResult`)
FROM result r
INNER JOIN `subject` s
on r.SubjectNo=s.SubjectNo
GROUP BY r.SubjectNo
HAVING AVG(StudentResult)>90;
```
## Connection query

```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 查询学员所属的年级(学号,学生姓名,年级名称)
SELECT `StudentNo`,`StudentName`,`GradeName`
FROM student s
INNER JOIN grade g
ON s.GradeID=g.GradeID;
-- 查询科目所属的年级
SELECT `SubjectName`,`GradeName`
FROM `subject` s
INNER JOIN `grade` g
ON s.GradeID=g.GradeID;
-- 查询列参加程序设计考试的同学信息(学号,姓名,科目名,分数)
SELECT s.`StudentNo`,`StudentName`,`SubjectName`,`StudentResult`
FROM student s
INNER JOIN result r
on s.StudentNo=r.StudentNo
INNER JOIN `subject` sub
on r.SubjectNo=sub.SubjectNo
where SubjectName='课程设计';
```
> **Self link**
Your own table and your own table link, core: **One table can be split into two identical tables**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 创建一个表
CREATE TABLE `course` (
`courseid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '课程id',
`pid` INT(10) NOT NULL COMMENT '父课程id',
`courseName` VARCHAR(50) NOT NULL COMMENT '课程名',
PRIMARY KEY (`courseid`)
) ENGINE=INNODB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
-- 插入数据
INSERT INTO `course` (`courseid`, `pid`, `courseName`)
VALUES('2','1','信息技术'),
('3','1','软件开发'),
('4','3','数据库'),
('5','1','美术设计'),
('6','3','web开发'),
('7','5','ps技术'),
('8','2','办公信息');
```
Split the table:
| pid (parent course id) | courseid (course id) | courseName (course name) |
| - | - | - |
| 1 | 2 | Information Technology |
| 1 | 3 | Software Development |
| 1 | 5 | Art Design |
| pid (parent course id) | courseid (course id) | courseName (course name) |
| - | - | - |
| 2 | 8 | Office Information |
| 3 | 4 | Database |
| 3 | 6 | web development |
| 5 | 7 | ps technology |
**Operation**: Query the subclass relationship corresponding to the parent class
| Parent class | Subclass |
| - | - |
| Information Technology 2 | Office Information 4 |
| Software development 3 | Database 4, web development 6 |
| Art Design 5 | PS Technology 7 |
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SELECT a.`courseid` AS '父课程',b.`courseid` AS '子课程'
FROM course AS a,course AS b
WHERE a.`courseid`=b.`pid`;
```

## Sorting and paging
> **Sort**
`语法`:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
select 查询列表
from 表
where 筛选条件
order by 排序列表 asc/desc
```
* The position of order by is generally placed at the end of the query statement (except for the limit statement)
| asc: | Ascending order, if not written, the default ascending order |
| - | - |
| **desc:** | **descending** |
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SELECT `StudentNo`,`StudentName`,`GradeName`
FROM student s
INNER JOIN grade g
ON s.GradeID=g.GradeID
ORDER BY `StudentNo` DESC;
```
> **Page**
`语法`:
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
select 查询列表
from 表
limit offset,pagesize;
```
* offset represents the starting entry index, starting from 0 by default
* size represents the number of items displayed
* offset=(n-1)\*pagesize
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 第一页 limit 0 5
-- 第二页 limit 5,5
-- 第三页 limit 10,5
-- 第n页 limit (n-1)*pagesize,pagesize
-- pagesize:当前页面大小
-- (n-1)*pagesize:起始值
-- n:当前页面
-- 数据总数/页面大小=总页面数
-- limit n 表示从0到n的页面
```
## Subquery
A subquery statement is nested in the `本质`在`where` clause
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 查询‘课程设计’的所有考试结果(学号,科目编号,成绩)降序排列
-- 方式一:使用连接查询
SELECT `StudentNo`,r.`SubjectNo`,`StudentResult`
FROM result r
INNER JOIN `subject` s
on r.StudentNo=s.SubjectNo
WHERE SubjectName='课程设计'
ORDER BY StudentResult DESC;
-- 方式二:使用子查询(由里到外)
SELECT StudentNo,SubjectNo,StudentResult
from result
WHERE SubjectNo=(
SELECT SubjectNo FROM `subject`
WHERE SubjectName='课程设计'
)
```
## MySQL function
### Commonly used functions
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 数学运算
SELECT ABS(-8); -- 绝对值
SELECT CEIL(5.1); -- 向上取整
SELECT CEILING(5.1); -- 向上取整
SELECT RAND(); -- 返回0~1之间的一个随机数
SELECT SIGN(-10); -- 返回一个数的符号;0返回0;正数返回1;负数返回-1
-- 字符串函数
SELECT CHAR_LENGTH('我喜欢你'); -- 字符串长度
SELECT CONCAT('我','喜欢','你'); -- 拼接字符串
SELECT INSERT('我喜欢',1,1,'超级') -- INSERT(str,pos,len,newstr) 从str的pos位置开始替换为长度为len的newstr
SELECT UPPER('zsr'); -- 转大写
SELECT LOWER('ZSR'); -- 转小写
SELECT INSTR('zsrs','s'); -- 返回第一次出现字串索引的位置
SELECT REPLACE('加油就能胜利','加油','坚持'); -- 替换出现的指定字符串
SELECT SUBSTR('坚持就是胜利',3,6); -- 返回指定的字符串(源字符串,截取位置,截取长度)
SELECT REVERSE('rsz'); -- 反转字符串
-- 时间日期函数
SELECT CURRENT_DATE(); -- 获取当前日期
SELECT CURDATE(); -- 获取当前日期
SELECT now(); -- 获取当前时间
SELECT LOCALTIME(); -- 本地时间
SELECT SYSDATE(); -- 系统时间
SELECT YEAR(NOW());
SELECT MONTH(NOW());
SELECT DAY(NOW());
SELECT HOUR(NOW());
SELECT MINUTE(NOW());
SELECT SECOND(NOW());
-- 系统信息
SELECT SYSTEM_USER();
SELECT USER();
SELECT VERSION();
```
### Aggregation function
| function | description |
| - | - |
| max | maximum value |
| min | minimum value |
| sum | and |
| avg | average |
| count | Count the number |
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SELECT COUNT(StudentName) FROM student;
SELECT COUNT(*) FROM student;
SELECT COUNT(1) FROM student;
SELECT SUM(`StudentResult`) FROM result;
SELECT AVG(`StudentResult`) FROM result;
SELECT MAX(`StudentResult`) FROM result;
SELECT MIN(`StudentResult`) FROM result;
```
# Database level MD5 encryption
> **MD5 Message-Digest Algorithm** (MD5 Message-Digest Algorithm)
* MD5 is improved from MD4, MD3, and MD2, mainly to enhance algorithm complexity and irreversibility
* The principle of MD5 cracking website, there is a dictionary behind it, the value after MD5 encryption, the value before encryption
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE `testMD5`(
`id` INT(4) NOT NULL,
`name` VARCHAR(20) NOT NULL,
`pwd` VARCHAR(50) NOT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET =utf8;
-- 明文密码
INSERT INTO `testMD5` VALUES(1,'zsr','200024'),
(2,'gcc','000421'),(3,'bareth','123456');
-- 加密
UPDATE `testMD5` SET `pwd`=MD5(pwd) WHE RE id=1;
UPDATE `testMD5` SET `pwd`=MD5(pwd); -- 加密全部的密码
-- 插入的时候加密
INSERT INTO `testMD5` VALUES(4,'barry',MD5('654321'));
-- 如何校验:将用户传递进来的密码,进行MD5加密,然后对比加密后的值
SELECT * FROM `testMD5` WHERE `name`='barry' AND `pwd`=MD5('654321');
```
# Transaction
> **Either both succeed or both fail**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SQL执行:A转账给B
SQL执行:B收到A的钱
```
Put a set of SQL in a batch to execute
* For example, bank transfer: the event will only end if A transfer is successful and B is successfully received. If one party is unsuccessful, the transaction is unsuccessful.
## Transaction Principle: ACID
Reference link: [https://blog.csdn.net/dengjili/article/details/82468576](https://blog.csdn.net/dengjili/article/details/82468576)
| Name | Description |
| - | - |
| **Atomicity** | Atomicity means that a transaction is an indivisible unit of work, and operations in a transaction either all occur or none occur. |
| **Consistency** | The integrity of data before and after a transaction must be consistent. |
| **Isolation** | The isolation of transactions means that when multiple users access the database concurrently, the transactions opened by the database for each user cannot be interfered by the operation data of other transactions, and multiple concurrent transactions must be isolated from each other. |
| **Durability** | Once a transaction is committed, it is irreversible and is persisted to the database. Even if the database fails, it should not have any impact |
***
## Problems caused by transaction concurrency
> Some problems caused by isolation:
| Name | Description |
| - | - |
| **Dirty Read** | Refers to one transaction reading uncommitted data from another transaction. |
| **Non-repeatable read** | Read a certain row of data in the table within a transaction, and the results of multiple reads will be different. |
| **Virtual reading (phantom reading)** | refers to reading data inserted by another transaction within a transaction, resulting in inconsistent reading. |
***
## Isolation level
> In database operations, in order to effectively ensure the correctness of concurrently read data, the proposed **Transaction Isolation Level**
* **Read Uncommitted**: One transaction reads uncommitted data from other transactions; under this isolation level, the query will not be locked, and the consistency is the worst, causing `脏读`, `不可重复读`, and `幻读` problems.
* **Read Committed**: A transaction can only read data that has been submitted by other transactions; this isolation level avoids the `脏读` problem, but the `不可重复读` and `幻读` problems still exist;
The read-commit transaction isolation level is the default transaction isolation level of most popular databases, such as Oracle, but is not the default isolation level of MySQL.
* **Repeatable Read**: During the execution process, a transaction can read newly inserted data that has been submitted by other transactions, but it cannot read the modifications to the data by other transactions, which means that the results of reading the same record multiple times are the same; this level avoids the problems of `脏读` and `不可重复度`, but it still cannot avoid the problem of `幻读`
Repeatable read is the default isolation level of MySQL
* **Serialization**: Transactions are executed serially. Transactions can only be executed one after another, and updates made to data by other transactions cannot be seen at all during the execution process. The disadvantage is poor concurrency and the strictest transaction isolation, which is fully in line with ACID principles, but has a greater impact on performance.
| **Transaction Isolation Level** | **Dirty Read** | **Non-Repeatable Read** | **Phantom Read** |
| - | - | - | - |
| read-uncommitted | yes | yes | yes |
| read-committed | no | yes | yes |
| repeatable-read | no | no | yes |
| Serializable | No | No | No |
## The process of executing transactions
1️⃣ **Turn off automatic submission**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SET autocommit=0;
```
2️⃣ **Transaction starts**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
START TRANSACTION -- 标记一个事务的开始,从这个之后的sql都在同一个事务内
```
3️⃣ **Submit if successful, rollback if failed**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 提交:持久化(成功)
COMMIT
12
-- 回滚:回到原来的样子(失败)
ROLLBACK
```
4️⃣ **Transaction ends**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SET autocommit=1; -- 开启自动提交
```
5️⃣ **Other operations**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SAVEPOINT 保存点名; -- 设置一个事务的保存点
ROLLBACK TO SAVEPOINT 保存点名; -- 回滚到保存点
RELEASE SAVEPOINT 保存点名; -- 撤销保存点
```
# index
Recommended reading: [Data structure and algorithm principles behind MySQL index](http://blog.codinglabs.org/articles/theory-of-mysql-index.html)
> Index (`Index`) is a **data structure** that helps MySQL obtain data efficiently.
* Improve query speed
* Ensure data uniqueness
* Can speed up the connection between tables and achieve referential integrity between tables
* When using grouping and sorting clauses for data retrieval, the time of grouping and sorting can be significantly reduced
* Full text search fields for search optimization
***
## Index classification
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 创建学生表student
CREATE TABLE `student`(
`StudentNo` INT(4) NOT NULL COMMENT '学号',
`LoginPwd` VARCHAR(20) DEFAULT NULL,
`StudentName` VARCHAR(20) DEFAULT NULL COMMENT '学生姓名',
`Sex` TINYINT(1) DEFAULT NULL COMMENT '性别,取值0或1',
`GradeID` INT(11) DEFAULT NULL COMMENT '年级编号',
`Phone` VARCHAR(50) NOT NULL COMMENT '联系电话,允许为空,即可选输入',
`Adress` VARCHAR(255) NOT NULL COMMENT '地址,允许为空,即可选输入',
`BornDate` DATETIME DEFAULT NULL COMMENT '出生时间',
`Email` VARCHAR(50) NOT NULL COMMENT '邮箱账号,允许为空,即可选输入',
`IdentityCard` VARCHAR(18) DEFAULT NULL COMMENT '身份证号',
PRIMARY KEY (`StudentNo`),
UNIQUE KEY `IdentityCard` (`IdentityCard`),
KEY `Email` (`Email`)
)ENGINE=MYISAM DEFAULT CHARSET=utf8;
```
### Primary key index (PRIMARY KEY)
Unique identification, primary key cannot be repeated, only one column is used as the primary key
* The most common index type, null values are not allowed
* Ensure the uniqueness of data records
* Determine where specific data records are located in the database
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 创建表的时候指定主键索引
CREATE TABLE tableName(
......
PRIMARY INDEX (columeName)
)
-- 修改表结构添加主键索引
ALTER TABLE tableName ADD PRIMARY INDEX (columnName)
```
***
### Ordinary index (KEY / INDEX)
Default, quickly locate specific data
* Both index and key keywords can set regular indexes
* Fields that should be added to the search criteria
* It is not advisable to add too many regular indexes, which will affect the insertion, deletion and modification operations of data.
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 直接创建普通索引
CREATE INDEX indexName ON tableName (columnName)
-- 创建表的时候指定普通索引
CREATE TABLE tableName(
......
INDEX [indexName] (columeName)
)
-- 修改表结构添加普通索引
ALTER TABLE tableName ADD INDEX indexName(columnName)
```
***
\###Unique index (UNIQUE KEY)
It is similar to the previous ordinary index, except that the value of the index column must be unique, but null values are allowed.
The difference from primary key index: there can only be one primary key index, and there can be multiple unique indexes.
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 直接创建唯一索引
CREATE UNIQUE INDEX indexName ON tableName(columnName)
-- 创建表的时候指定唯一索引
CREATE TABLE tableName(
......
UNIQUE INDEX [indexName] (columeName)
);
-- 修改表结构添加唯一索引
ALTER TABLE tableName ADD UNIQUE INDEX [indexName] (columnName)
```
***
### Full text index (FULLText)
Quickly locate specific data (Baidu search is full-text index)
* Available under specific database engines: MyISAM
* Can only be used for CHAR, VARCHAR, and TEXT data column types
* Suitable for large data sets
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 增加一个全文索引
ALTER TABLE `student` ADD FULLTEXT INDEX `StudentName`(`StudentName`);
-- EXPLAIN 分析sql执行的情况
EXPLAIN SELECT * FROM student; -- 非全文索引
EXPLAIN SELECT * FROM student WHERE MATCH(StudentName) AGAINST('d'); -- 全文索引
```
## Usage of index
### Index creation
* Add indexes to fields when creating tables
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE 表名 (
字段名1 数据类型 [完整性约束条件…],
字段名2 数据类型 [完整性约束条件…],
[UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY [索引名] (字段名[(长度)] [ASC |DESC])
);
```
* After creation, add index
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 方法一:CREATE在已存在的表上创建索引
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名
ON 表名 (字段名[(长度)] [ASC |DESC]) ;
-- 方法二:ALTER TABLE在已存在的表上创建索引
ALTER TABLE 表名 ADD [UNIQUE|FULLTEXT|SPATIAL]
INDEX 索引名 (字段名[(长度)] [ASC |DESC]) ;
```
### Index deletion
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 删除索引
DROP INDEX 索引名 ON 表名;
-- 删除主键索引
ALTER TABLE 表名 DROP PRIMARY KEY;
```
### Display index information
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
SHOW INDEX FROM 表名;
```
### explain analysis of sql execution
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 增加一个全文索引
ALTER TABLE `student` ADD FULLTEXT INDEX `StudentName`(`StudentName`);
-- EXPLAIN 分析sql执行的情况
EXPLAIN SELECT * FROM student; -- 非全文索引
EXPLAIN SELECT * FROM student WHERE MATCH(StudentName) AGAINST('d'); -- 全文索引
```
***
## Test index
**Create table app\_user:**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE `app_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT '' COMMENT '用户昵称',
`email` varchar(50) NOT NULL COMMENT '用户邮箱',
`phone` varchar(20) DEFAULT '' COMMENT '手机号',
`gender` tinyint(4) unsigned DEFAULT '0' COMMENT '性别(0:男;1:女)',
`password` varchar(100) NOT NULL COMMENT '密码',
`age` tinyint(4) DEFAULT '0' COMMENT '年龄',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATECURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='app用户表'
```
**Batch insert data: 100w**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 1418错解决方案(创建函数前执行此语句)
set global log_bin_trust_function_creators=true;
-- 插入100万条数据
DELIMITER $$ -- 写函数之前要写的标志
CREATE FUNCTION mock_data() -- 创建mock_data()函数
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 1000000;
DECLARE i INT DEFAULT 0;
WHILE i < num DO
INSERT INTO app_user(`name`, `email`, `phone`, `gender`, `password`, `age`)
VALUES(CONCAT('用户', i), '24736743@qq.com', CONCAT('18', FLOOR(RAND()*(999999999-100000000)+100000000)),FLOOR(RAND()*2),UUID(), FLOOR(RAND()*100));
SET i = i + 1;
END WHILE;
RETURN i;
END;
-- 执行函数
SELECT mock_data();
```


**Test query speed**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 查询用户名为'用户9999'性能分析
EXPLAIN SELECT * FROM app_user where name='用户99999'
```

**Test after adding index**
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 给name列创建常规索引
CREATE INDEX id_app_user_name ON app_user(`name`)
-- 再测试
EXPLAIN SELECT * FROM app_user where name='用户99999'
```

Comparing the two results, the speed has been greatly improved.
***
## Indexing principles
* The more indexes, the better. Tables with small data volumes do not need to be indexed.
* Do not add indexes to frequently changing data
* Indexes are generally added to columns that are frequently queried
***
# explain keyword
**Suggested Reading**:
* [MySQL optimization - understand the explain](https://blog.csdn.net/jiadajing267/article/details/81269067)
* [MySQL Advanced Explain Execution Plan Detailed Explanation](https://blog.csdn.net/wuseyukui/article/details/71512793?dist_request_id=\&depth_1-)
***
# Permission management and backup
## User management
**Method 1: Visual management**

***
**Method 2: SQL command operation**
> User information is stored in the `user` table in the `mysql` database. The essence of user management is to add, delete, modify and check this table.
>
> 
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- 创建用户
CREATE USER zsr IDENTIFIED BY '123456'
-- 删除用户
DROP USER zsr
-- 修改当前用户密码
SET PASSWORD = PASSWORD('200024')
-- 修改指定用户密码
SET PASSWORD FOR zsr = PASSWORD('200024')
-- 重命名
RENAME USER zsr to zsr2
-- 用户授权(授予全部权限,除了给其他用户授权)
GRANT ALL PRIVILEGES on *.* TO zsr2
-- 查询权限
SHOW GRANTS FOR zsr
-- 查看root用户权限
SHOW GRANTS FOR root@localhost
-- 撤销权限
REVOKE ALL PRIVILEGES ON *.* FROM zsr
```
***
## Database backup
Ensure that important data is not lost and data is escaped
> **Method 1**: Directly copy the physical file, and the MySQL data table is stored on the disk as a file
-Including table files, data files, and database option files
* Location: `Mysql安装目录\data\` (the directory name corresponds to the database name, and the file name in this directory corresponds to the data table)

> **Method 2**: Visual management
Navicat opens the database to be backed up, and then click New Backup

Click Object Selection. Here you can customize the table to be selected for backup.

After selecting, click Backup to start the backup


Wait for the backup to complete, close it, and then you can see the backed up files

> **Method Three**: Visual Management
Select the table to be exported and right-click to dump the SQL file

Then you can get the `.sql` file

> **Method 4**: Command `mysqldump` to export
```shell theme={"theme":{"light":"github-light","dark":"github-dark"}}
# mysqldump -h主机 -u用户名 -p密码 数据库 [表1 表2 表3] >物理磁盘位置/文件名
# 导出school数据库的cource grade student表到D:/school.sql
mysqldump -hlocalhost -uroot -p200024 school course grade student >D:/school.sql
```

Then you can see the exported `sql` file

Then you can log in to mysql from the command line, switch to the specified database, and import using the `source` command

***
\#Three major paradigms
> **Normalization Theory**: Transform the relationship model and eliminate inappropriate data dependencies by decomposing the relationship model to solve the problems of insertion anomalies, deletion anomalies, update anomalies and data redundancy.
>
> In order to establish a database with less redundancy and reasonable structure, certain standardization theories must be followed when designing the database. In relational databases this kind of rule is called `范式`
[Popular understanding of the three paradigms](https://www.cnblogs.com/wsg25/p/9615100.html)
* If all attributes of a relational schema R are indivisible data items, then R belongs to `第一范式`
* If the relational schema R belongs to the first normal form and each non-primary attribute is completely functionally dependent on the code, then R belongs to `第二范式`
* If the relational schema R belongs to the second normal form, and all non-primary attributes in R are directly dependent on the code, then R belongs to `第三范式`

**Normative Questions**:
> The paradigm of the database is to standardize the design of the database, but in practice, issues such as performance, cost, and user experience are often more important than standardization;
>
> Therefore, sometimes a redundant field is deliberately added to some tables to turn multi-table queries into single-table queries. Sometimes some calculated columns are added to change the amount of data from large to small (when the amount of data is large, count(\*) is very time-consuming, you can directly add a column, +1 for each additional row, just check the column); Alibaba has also proposed that the tables for related queries should not exceed three tables at most.
>
> These are examples of giving up certain norms for performance and cost.
***
# Database driver and JDBC
> The program we write will interact with the database through **database driver**
>
> Then different databases have different drivers, which is not convenient for our programs to operate various databases; therefore, in order to simplify the operation of different databases, SUN provides a Java specification for operating databases`JDBC`; the specifications of different databases are completed by the corresponding database manufacturers. For developers, they only need to master the operation of the JDBC interface.
## The first JDBC program
1️⃣ **Create a new empty project**

2️⃣ **Import mysql-connector-java**
Create a new `lib` directory under the project directory and put it in the jar package



3️⃣ **Write code & test**
Create a new `JDBCDemo` in the `src` directory to operate the database
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接信息url,用户信息
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
String username = "root";
String password = "200024";
//3.连接,获得数据库对象connection
Connection connection = DriverManager.getConnection(url, username, password);
//4.获取执行sql的对象
Statement statement = connection.createStatement();
//5.执行sql
String sql = "select * from app_user where id<10";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone"));
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
```

***
## JDBC Object
### DriverManager
> **DriverManager**: driver management
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
```
Essentially execute `DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());`
![image-20210327161110925]()
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
//3.连接,获得数据库对象connection
Connection connection = DriverManager.getConnection(url, username, password);
```
`connection` represents the database, so you can set up automatic transaction submission, transaction rollback, etc.

***
### Statement
> **Statement**: The object that executes sql, used to send SQL statements to the database. If you want to complete the addition, deletion, modification and query of the database, you only need to send the addition, deletion, modification and query statement to the database through this object.
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
statement.executeQuery();//查询操作,返回结果
statement.execute();//执行sql
statement.executeUpdate();//用于增删改,返回受影响的行数
```


***
### ResultSet
> **ResultSet**: The result set of the query, which encapsulates the results of all queries

***
## 3. Encapsulate jdbc tool class
### Write database configuration file
Create a new `db.properties` in the `src` directory to store database configuration information

```properties theme={"theme":{"light":"github-light","dark":"github-dark"}}
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
username=root
password=200024
```
***
### Writing tool classes
Then create `JDBCUtils.java` in the `src` directory as a tool class
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream inputStream = JDBCDemo.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//加载驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
//释放连接资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
```
***
### test
Modify`JDBCDemo`
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) throws SQLException {
//获得数据库对象connection
Connection connection = JDBCUtils.getConnection();
//获取sql执行对象statement
Statement statement = connection.createStatement();
//执行sql
String sql = "select * from app_user where id<10";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone"));
}
//释放连接
JDBCUtils.release(connection, statement, resultSet);
}
}
```

***
## SQL injection problem
> SQL injection happens when a [web application](https://baike.baidu.com/item/web应用程序/2498090) does not properly validate or filter user input. An attacker can append extra [SQL statements](https://baike.baidu.com/item/SQL语句/5714895) to a predefined query, tricking the [database server](https://baike.baidu.com/item/数据库服务器/613818) into executing unauthorized queries and exposing data.
**SQL injection case**: Pass in the user name in the main function and search for user information with the specified name
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLInjection {
public static void main(String[] args) throws SQLException {
searchName("' or '1=1");
}
//查找指定名字用户信息
public static void searchName(String username) throws SQLException {
//获得数据库对象connection
Connection connection = JDBCUtils.getConnection();
//获取sql执行对象statement
Statement statement = connection.createStatement();
//执行sql
String sql = "select * from app_user where name='" + username + "'";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone"));
}
//释放连接
JDBCUtils.release(connection, statement, resultSet);
}
}
```
**Result**: All data in the database were queried

Here, an illegal string is passed in instead of a user name, but all the data is obtained. Why?
Splicing the entire sql statement is `select * from app_user where name=' ' or '1==1'`, of which `1==1` is always true, so the sql statement is equivalent to all the data in the query table; this is sql injection, mainly a problem caused by string splicing, which is very dangerous! !
***
## PreparedStatement object
> `PreparedStatement` is a subclass of `Statement`. Compared with it, it can prevent SQL injection and is more efficient.
Also test the sql injection case
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
import java.sql.*;
public class SQLInjection {
public static void main(String[] args) throws SQLException {
searchName("' 'or '1=1'");
}
//登录
public static void searchName(String username) throws SQLException {
//获得数据库对象connection
Connection connection = JDBCUtils.getConnection();
//获取sql执行对象preparedStatement(预编译sql,先写不执行,参数用?表示)
PreparedStatement preparedStatement = connection.prepareStatement("select * from app_user where name=?");
//手动传参
preparedStatement.setString(1, username);
//执行sql
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("id:" + resultSet.getObject("id") + "phone:" + resultSet.getObject("phone"));
}
//释放连接
JDBCUtils.release(connection, preparedStatement, resultSet);
}
}
```

According to the results, the PreparedStatement object perfectly avoids sql injection problems
***
## Transaction case
First create the account table
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(40),
money FLOAT
);
INSERT INTO account(name,money) VALUES('A',1000);
INSERT INTO account(name,money) VALUES('B',1000);
INSERT INTO account(name,money) VALUES('C',1000);
```

Then write Java code
```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class TestTransaction {
public static void main(String[] args) throws SQLException {
//获得数据库对象connection
Connection connection = JDBCUtils.getConnection();
//关闭数据库自动提交,即开启事务
connection.setAutoCommit(false);
String sql1 = "update account set money = money+100 where name = 'A' ";
String sql2 = "update account set money = money-100 where name = 'B' ";
//获取sql执行对象preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql1);
preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();
//业务完毕,提交事务
connection.commit();
//释放资源
JDBCUtils.release(connection, preparedStatement, null);
}
}
```
Running results:

If you add `int x = 1 / 0` between two updates;
An error will be reported, the transaction execution will fail, and neither statement will be executed successfully.


# SQLite
Source: https://base.bangwu.me/backend/SQL/sqlite
SQLite is a lightweight embedded database reading and writing disk files, covering Python sqlite3 integration, basic SQL operations, and use cases.
# SQLite
SQLite is a lightweight embedded relational database. It does not require a standalone server process and reads from or writes to a disk file directly.
## Features
* **Zero configuration**: no installation or admin service required
* **Single file**: the entire database lives in one file
* **Cross-platform**: works on all major operating systems
* **Self-contained**: no external service dependency
* **Transactional**: supports full ACID behavior
## Using SQLite in Python
### Basic operations
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import sqlite3
# 连接数据库(不存在则创建)
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
''')
# 插入数据
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("张三", "zhangsan@example.com"))
# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
# 提交事务
conn.commit()
conn.close()
```
### Context manager
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
with sqlite3.connect('example.db') as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
```
## Common commands
```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
-- View所有表
.tables
-- View表结构
.schema users
-- 导出数据
.output data.sql
.dump
-- 导入数据
.read data.sql
```
## Performance tips
1. **Use transactions** for batch operations.
2. **Create indexes** to speed up queries.
3. **Enable WAL mode** to improve concurrent read/write behavior.
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 启用 WAL 模式
conn.execute('PRAGMA journal_mode=WAL')
```
## Good use cases
* Local storage for mobile apps
* Desktop app data management
* Small web applications
* Embedded devices
* Testing and prototyping
## Limitations
* Not ideal for high-concurrency writes
* Recommended database size is typically below 1 TB
* No built-in user permission management
# RBAC & Session Auth
Source: https://base.bangwu.me/backend/auth/rbac
Role-Based Access Control and session cookie authentication patterns from real projects using Hono, SQLite, Next.js, and PostgreSQL.
# RBAC & Session Cookie Authentication
Role-Based Access Control (RBAC) assigns permissions to roles, then roles to users. Combined with signed session cookies, you get a simple, secure auth system that works without JWT complexity.
> [card] [badmin](https://github.com/markbang/badmin)
>
> Hono + SQLite — full RBAC admin panel with session cookies.
> [card] [Cruise Ship](https://github.com/markbang/cruise-ship-system)
>
> Next.js + PostgreSQL — role-based business system with token sessions.
## RBAC Data Model
The classic RBAC model has four tables:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
users ──(user_roles)──► roles ──(role_permissions)──► permissions
```
### Schema Definition
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Core tables
export const users = sqliteTable("users", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
name: text("name").notNull(),
email: text("email").notNull().unique(),
passwordHash: text("password_hash").notNull(),
sessionVersion: integer("session_version").default(1).notNull(), // For forced logout
status: text("status", { enum: ["active", "disabled"] }).default("active").notNull(),
})
export const roles = sqliteTable("roles", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
name: text("name").notNull(),
slug: text("slug").notNull().unique(), // e.g. "admin", "editor"
description: text("description").notNull(),
isSystem: integer("is_system", { mode: "boolean" }).default(false).notNull(), // Prevent deletion
})
export const permissions = sqliteTable("permissions", {
key: text("key").primaryKey(), // e.g. "users.read", "users.write"
label: text("label").notNull(),
group: text("group").notNull(), // e.g. "users", "roles", "dashboard"
})
// Junction tables (many-to-many)
export const userRoles = sqliteTable("user_roles", {
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
}, (table) => ({ pk: primaryKey({ columns: [table.userId, table.roleId] }) }))
export const rolePermissions = sqliteTable("role_permissions", {
roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
permissionKey: text("permission_key").notNull().references(() => permissions.key, { onDelete: "cascade" }),
}, (table) => ({ pk: primaryKey({ columns: [table.roleId, table.permissionKey] }) }))
```
> [!TIP]
>
> Permission keys use dot notation (`users.read`, `users.write`) for natural grouping. The `group` column lets you organize them in the UI.
## Session Cookie Auth
Instead of JWTs, use **signed session cookies** — simpler, more secure for same-origin apps:
### Why Cookies over JWT?
| Concern | Session Cookie | JWT |
| - | - | - |
| Revocation | Increment `sessionVersion` — instant | Must maintain blacklist or wait for expiry |
| Storage | Server-side DB check | Self-contained (can't revoke without blacklist) |
| Size | Small: `userId:version` | Large: encoded claims + signature |
| CSRF | Mitigated by `SameSite` | Not applicable (usually sent in header) |
| Implementation | `hono/cookie` signed cookies | Library + secret management |
### Implementation with Hono
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { getSignedCookie, setSignedCookie, deleteCookie } from "hono/cookie"
import { createMiddleware } from "hono/factory"
const SESSION_COOKIE = "app_session"
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
// Set session after login
export async function setSessionCookie(ctx, userId: string, sessionVersion: number) {
await setSignedCookie(ctx, SESSION_COOKIE, `${userId}:${sessionVersion}`, secret, {
httpOnly: true, // Not accessible from JS
maxAge: COOKIE_MAX_AGE,
sameSite: "Lax", // CSRF protection
secure: isProduction, // HTTPS only in prod
path: "/",
})
}
// Require session on API routes
export function requireSession(authService: AuthService) {
return createMiddleware(async (c, next) => {
const value = await getSignedCookie(c, secret, SESSION_COOKIE)
if (!value) throw new HTTPException(401, { message: "Login required" })
const payload = parseSessionCookie(value) // → { userId, sessionVersion }
const session = await authService.getSession(payload)
if (!session) {
deleteCookie(c, SESSION_COOKIE)
throw new HTTPException(401, { message: "Session expired" })
}
c.set("sessionUser", session.user) // Available in all downstream handlers
await next()
})
}
// Require specific permission
export function requirePermission(permission: string) {
return createMiddleware(async (c, next) => {
const user = c.get("sessionUser")
if (!user.permissions.includes(permission)) {
throw new HTTPException(403, { message: "Permission denied" })
}
await next()
})
}
```
### Route Protection
Chain middleware to protect routes:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
const app = new Hono()
// Public routes
app.post("/api/auth/login", async (c) => { /* ... */ })
// Protected routes — require session
app.use("/api/*", requireSession(authService))
// Require permission for specific routes
app.use("/api/users/*", requirePermission("users.write"))
app.use("/api/roles/*", requirePermission("roles.write"))
app.get("/api/users", async (c) => {
const user = c.get("sessionUser") // Injected by middleware
return c.json(await userService.listUsers(user))
})
```
## Session Versioning (Forced Logout)
When a user changes their password or gets disabled, bump their `sessionVersion`:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// In auth service — change password
async changePassword(userId: string, input: ChangePasswordInput) {
await this.userRepository.updatePassword(userId, {
passwordHash: await hashPassword(input.nextPassword),
})
// Increment session version → all existing cookies become invalid
await this.userRepository.revokeSessions(userId)
}
// In repository — SQL increment
async revokeSessions(id: string) {
await db.update(users)
.set({ sessionVersion: sql`session_version + 1` })
.where(eq(users.id, id))
}
```
When `requireSession` checks the cookie, it compares the cookie's version with the DB version. If they differ, the session is rejected.
> [!NOTE]
>
> Session versioning is the simplest way to force logout. No blacklist, no waiting for JWT expiry — just increment a number in the DB.
## Loading Permissions into Session
On login, load all the user's permissions into the session object:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
async findSessionUserById(id: string) {
return await db.query.users.findFirst({
where: eq(users.id, id),
columns: { passwordHash: false }, // Never include in session
with: {
roles: {
with: {
role: {
with: {
permissions: {
columns: { permissionKey: true }, // Only need the key
},
},
},
},
},
},
})
}
// Flatten permissions for quick checks
function flattenPermissions(sessionUser) {
const permissions = sessionUser.roles.flatMap(ur => ur.role.permissions.map(rp => rp.permissionKey))
return { ...sessionUser, permissions }
}
```
## Frontend Permission Checks
Don't rely only on backend — hide UI elements the user can't access:
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
function UserManagementPage() {
const { user } = useSession()
return (
Users
{user.permissions.includes("users.write") && (
)}
)
}
```
> [!TIP]
>
> Frontend permission checks are for **UX** (hide buttons), not **security**. The backend middleware is the real gatekeeper — always validate permissions on the API side.
## Cruise Ship: Token-Based Sessions
For the cruise-ship system (Next.js + PostgreSQL), we used token-based sessions stored in the DB:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
export const userSession = pgTable("user_session", {
id: bigserial({ mode: "bigint" }).primaryKey().notNull(),
userId: bigint("user_id", { mode: "number" }).notNull(),
token: varchar({ length: 128 }).notNull(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
}, (table) => [
unique("user_session_token_key").on(table.token),
index("idx_user_session_user_id").using("btree", table.userId),
])
```
This approach stores the full session in PostgreSQL — good for distributed apps where cookie-only sessions can't work.
## Best Practices
1. **Signed cookies over JWT** — Simpler, revocable, smaller payload
2. **Session versioning** — Increment to force logout on password change or account disable
3. **Flatten permissions** — Load all permission keys into the session object for O(1) checks
4. **Exclude sensitive columns** — Never query `passwordHash` into session data
5. **Cascade deletes on M2M** — Role/user deletions should auto-clean associations
6. **`isSystem` flag on roles** — Prevent deletion of essential roles (Admin, SuperAdmin)
7. **Frontend hides, backend validates** — Frontend checks are UX, backend middleware is security
8. **Token sessions for distributed systems** — When cookies can't work across services, store tokens in DB
## References
* [Hono Cookie API](https://hono.dev/helpers/cookie)
* [badmin auth module](https://github.com/markbang/badmin) — Full Hono + SQLite RBAC implementation
* [cruise-ship auth](https://github.com/markbang/cruise-ship-system) — Next.js + PostgreSQL token sessions
# Backend
Source: https://base.bangwu.me/backend/index
Backend development notes covering Python (FastAPI, scraping, libraries), Go (Gin framework), and databases (MySQL, SQLite, and theory notes).
Backend development handles server-side logic, database interactions, and API design. Here are the tech stacks I've worked with.
> [card] [Python](/backend/Python/index)
>
> FastAPI, web scraping, and popular libraries.
> [card] [Go](/backend/Go/index)
>
> Gin framework and concurrent programming.
> [card] [Rust](/backend/Rust/index)
>
> Axum IM bridges and Tauri desktop shells.
> [card] [Databases](/backend/SQL/index)
>
> MySQL, SQLite, and core database concepts.
> [card] [Drizzle ORM](/backend/orm/drizzle)
>
> Type-safe ORM — SQLite & PostgreSQL schema design.
> [card] [RBAC & Auth](/backend/auth/rbac)
>
> Role-based access control and session cookie auth.
## Learning Path
1. Master a backend language (Python / Go)
2. Learn database design and SQL operations
3. Understand RESTful API design principles
4. Learn authentication and authorization
5. Deployment and DevOps basics
# Drizzle ORM
Source: https://base.bangwu.me/backend/orm/drizzle
Database schema design, migrations, and CRUD patterns using Drizzle ORM — drawn from badmin (SQLite), cruise-ship (PostgreSQL), and cyop (PostgreSQL).
# Drizzle ORM — Schema Design & Best Practices
Drizzle ORM is a TypeScript-first ORM with SQL-like syntax, zero runtime overhead, and full type safety. It supports SQLite, PostgreSQL, MySQL, and more — each with driver-specific column types.
> [card] [badmin](https://github.com/markbang/badmin)
>
> SQLite admin panel — users, roles, RBAC permissions.
> [card] [Cruise Ship](https://github.com/markbang/cruise-ship-system)
>
> PostgreSQL business system — bookings, finance, cabin allocation.
> [card] [cyop](https://github.com/markbang/cyop)
>
> PostgreSQL AI platform — requirements, tasks, captions.
## SQLite Schema (badmin)
SQLite is great for admin panels and prototypes — zero infra cost, local file DB:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core"
import { sql } from "drizzle-orm"
const USER_STATUS_VALUES = ["active", "disabled"] as const
export const users = sqliteTable("users", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
name: text("name").notNull(),
email: text("email").notNull().unique(),
passwordHash: text("password_hash").notNull(),
sessionVersion: integer("session_version").default(1).notNull(),
status: text("status", { enum: USER_STATUS_VALUES }).default("active").notNull(),
lastLoginAt: integer("last_login_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(),
})
```
> [!NOTE]
>
> SQLite stores timestamps as integers. Use `{ mode: "timestamp" }` so Drizzle auto-converts `Date` ↔ `unixepoch()`. The `sql`(unixepoch())\` default gives you a server-side timestamp without app logic.
## PostgreSQL Schema (Cruise Ship)
PostgreSQL gives you rich column types — `numeric` for money, `jsonb` for snapshots, `text[]` for arrays:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { pgTable, bigserial, bigint, varchar, numeric, integer, timestamp, text, date, boolean, check, index, foreignKey, unique } from "drizzle-orm/pg-core"
import { sql } from "drizzle-orm"
export const cruise = pgTable("cruise", {
id: bigserial({ mode: "bigint" }).primaryKey().notNull(),
name: varchar({ length: 120 }).notNull(),
tonnage: numeric({ precision: 12, scale: 2 }),
imageUrls: text("image_urls").array(),
status: varchar({ length: 20 }).default("normal").notNull(),
createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).defaultNow().notNull(),
}, (table) => [
index("idx_cruise_status").using("btree", table.status.asc().nullsLast().op("text_ops")),
check("cruise_status_check", sql`(status)::text = ANY ((ARRAY['normal','disabled','closed'])::text[])`),
])
```
### Key PostgreSQL Patterns
1. **CHECK constraints for enums** — PostgreSQL doesn't have native enums in Drizzle, so use `check()` with `ANY (ARRAY[...])`:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
check("status_check", sql`(status)::text = ANY ((ARRAY['active','disabled'])::text[])`)
```
2. **Composite indexes** — For multi-column queries, define indexes inline:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
index("idx_booking_cabin_booking_id").using("btree", table.bookingApplicationId.asc().nullsLast().op("int8_ops"))
```
3. **Array columns** — `text("image_urls").array()` for storing multiple URLs without a separate table:
4. **JSONB for snapshots** — `jsonb("item_snapshot").default([]).notNull()` for revision history:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
export const costRevision = pgTable("cost_revision", {
id: bigserial({ mode: "bigint" }).primaryKey().notNull(),
beforeTotalCost: numeric({ precision: 14, scale: 2 }).default("0").notNull(),
afterTotalCost: numeric({ precision: 14, scale: 2 }).default("0").notNull(),
itemSnapshot: jsonb("item_snapshot").default([]).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
})
```
## Many-to-Many Relationships (RBAC)
RBAC needs user ↔ role ↔ permission many-to-many tables:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
export const userRoles = sqliteTable(
"user_roles",
{
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(),
},
(table) => ({
pk: primaryKey({ columns: [table.userId, table.roleId] }),
}),
)
export const rolePermissions = sqliteTable(
"role_permissions",
{
roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
permissionKey: text("permission_key").notNull().references(() => permissions.key, { onDelete: "cascade" }),
createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(unixepoch())`).notNull(),
},
(table) => ({
pk: primaryKey({ columns: [table.roleId, table.permissionKey] }),
}),
)
```
> [!TIP]
>
> Always add `onDelete: "cascade"` on many-to-many foreign keys. When a role or user is deleted, their associations should disappear automatically — no orphaned rows.
## Repository Pattern
Separate data access from business logic using repository interfaces:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/domain/repositories.ts
export interface AuthUserRepository {
findForAuthByEmail(email: string): Promise
findSessionUserById(id: string): Promise
touchLastLogin(id: string): Promise
updatePassword(id: string, data: { passwordHash: string; nextPassword: string }): Promise
revokeSessions(id: string): Promise
}
```
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/repositories/user-repository.ts
export function createUserRepository(db: DrizzleDB): AuthUserRepository {
return {
async findForAuthByEmail(email: string) {
return await db.query.users.findFirst({
where: eq(users.email, email),
})
},
async findSessionUserById(id: string) {
return await db.query.users.findFirst({
where: eq(users.id, id),
columns: { passwordHash: false }, // Never load password into session
with: {
roles: { with: { role: { with: { permissions: true } } } },
},
})
},
async revokeSessions(id: string) {
await db.update(users)
.set({ sessionVersion: sql`session_version + 1` })
.where(eq(users.id, id))
},
}
}
```
> [!NOTE]
>
> When loading a user for session checks, never include the password hash. Drizzle's `columns` filter lets you exclude sensitive fields at the query level, not just in the service layer.
## Migrations
Drizzle Kit generates SQL migrations from your schema:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Generate migration from schema changes
bun run db:generate
# Apply migrations
bun run db:migrate
# Visualize schema
bun run db:studio
```
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// drizzle.config.ts
import { defineConfig } from "drizzle-kit"
export default defineConfig({
schema: "./src/db/schema.ts",
out: "./drizzle",
dialect: "sqlite", // or "postgresql"
dbCredentials: {
url: "./dev.db",
},
})
```
## Seeding
Seed the database with initial roles, permissions, and an admin user:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/db/seed.ts
import { db } from "./client"
import { users, roles, permissions, userRoles, rolePermissions } from "./schema"
export async function seed() {
// Create permissions
await db.insert(permissions).values([
{ key: "users.read", label: "View Users", group: "users" },
{ key: "users.write", label: "Edit Users", group: "users" },
{ key: "roles.read", label: "View Roles", group: "roles" },
])
// Create admin role
const [adminRole] = await db.insert(roles).values({
name: "Admin",
slug: "admin",
description: "System administrator",
isSystem: true,
}).returning()
// Link all permissions to admin role
await db.insert(rolePermissions).values(
allPermissions.map(p => ({ roleId: adminRole.id, permissionKey: p.key }))
)
// Create admin user
const [adminUser] = await db.insert(users).values({
name: "Admin",
email: "admin@example.com",
passwordHash: await hashPassword("changeme"),
}).returning()
// Assign admin role
await db.insert(userRoles).values({ userId: adminUser.id, roleId: adminRole.id })
}
```
## Best Practices
1. **SQLite for admin panels** — Zero infra, local dev, good for small-to-medium row counts
2. **PostgreSQL for business data** — Rich types (jsonb, arrays, CHECK constraints, numeric precision)
3. **CHECK constraints over app-level validation** — Enforce enum values at the DB level
4. **Cascade deletes on M2M** — `onDelete: "cascade"` prevents orphaned association rows
5. **Exclude sensitive columns** — `columns: { passwordHash: false }` in session queries
6. **Repository pattern** — Separate Drizzle queries from service/business logic
7. **Session versioning** — Increment `sessionVersion` to force logout
8. **Seed with system roles** — Always seed an admin role and initial permissions
## References
* [Drizzle ORM Docs](https://orm.drizzle.team/)
* [Drizzle Kit CLI](https://orm.drizzle.team/kit-docs/)
* [badmin schema](https://github.com/markbang/badmin) — SQLite RBAC
* [cruise-ship schema](https://github.com/markbang/cruise-ship-system) — PostgreSQL business
# Code Snippets
Source: https://base.bangwu.me/code
Developer cheatsheets and quick references covering Git commands, Docker operations, shell script snippets, and package manager shortcuts.
# Code Path
Hello! This section mostly records my [Cheatsheets](https://en.wikipedia.org/wiki/Cheat_sheet) and pitfalls encountered along the way.
The knowledge base covers the following content (PRs and discussion welcome):
> [card] [Frontend](/frontend/index)
>
> Vue, TailwindCSS, and component libraries.
> [card] [Backend](/backend/index)
>
> Python, Go, and databases.
> [card] [Desktop](/software/index)
>
> Tauri cross-platform development.
> [card] [Algorithms](/algo/index)
>
> Algorithm practice and pattern-based notes.
# CDN Setup
Source: https://base.bangwu.me/env/CDN
Domestic and overseas split CDN architecture using object storage with intelligent DNS routing for global acceleration and Rclone file sync.
Currently using's CDN Solution from:[https://www.eallion.com/cdn-cname-cloudflare/](https://www.eallion.com/cdn-cname-cloudflare/)
Take a look at the CDN structure diagram. Our goal is to solve the global CDN problem at a low cost.

Previous articleBackup
### Introduction
domestic and overseas traffic splitting,not only reduces costs,but also improves website performance,optimizes TTFB。
I don't remember when I started having such thoughts, so I went to search for it.
It turns out that the tutorials online are quite old. Where most of the talk's is access to CNAME is through Cloudflare for SaaS, but it doesn't support regular domain names, and can't access R2 or Workers.
In terms of function's priority, I need the partition resolution function most, which results in the inability to transfer the domain name's NS to Cloudflare.
Cloudflare's DNS is indeed excellent, but Cloudflare doesn't support geo-based resolution, it has CNAME flattening, but it will resolve all mainland China's IPs to China Unicom.
On the contrary, domestic DNS service providers do a good job in partition resolution, maybe because domestic domain names need this function more.
Can't fully commit, but want to use Cloudflare, so have to use some tricks.
In March 2022, Cloudflare announced changes to Cloudflare for SaaS's charging strategy. Each account can have 100 free domain names, and charges \$0.1/month per extra domain. We use Cloudflare for SaaS to connect domains via CNAME and enjoy Cloudflare's powerful edge calculation capabilities.
Yes for small websites, such as this blogs, the above services are free's, free quota:
* DNSPod: Use's professional version, but freeversions also has partition resolution
* Tencent Cloud COS: 50G/month; 2 million requests
* Tencent Cloud CDN: 10G/month
* Cloudflare CDN: No upper limit for normal use
* Cloudflare R2: 10G/month; 1 million/10 million requests
* Backblaze B2: 10G/month; has \[Traffic Alliance] with Cloudflare([https://www.backblaze.com/cloud-storage/integrations](https://www.backblaze.com/cloud-storage/integrations))
I skip Tencent Cloud's Configuration and only talk about Cloudflare's part here.
The prerequisite is that you already have an available domain name in your Cloudflare account.
This domain name is used to provide `回退源` (Fallback Origin), assuming this domain name is `example.com`.
### Create R2 and bind a custom domain name
1. Log in to the control panel: [https://dash.cloudflare.com/](https://dash.cloudflare.com/), Cloudflare supportsChinese;
2. Create R2 bucket's Method is skipped here, for example, create: `r2-blog-test`;
3. in `R2` `设置` `公开Visit` `自Definition域` `连接域` Add a custom domain name to the 's R2 you just created:
[](https://www.eallion.com/assets/images/posts/2023/07/r2_custom_hostname.png)
Then the domain name's DNS will automatically appear with a resolution:
[](https://www.eallion.com/assets/images/posts/2023/07/custom_hostname_dns.png)
### Subscribe to Cloudflare for SaaS
1. Select the domain name `example.com` in `Zones`;
2. Select `自Definition主机名` in the domain name's `SSL/TLS`;
3. Select Enable Subscription. Subscriptions can be made using Paypal.
[](https://www.eallion.com/assets/images/posts/2023/07/enable_cloudflare_saas.png)
### Add custom domain name
After the subscription is successful, first add `回退源`:`images.example.com`. This return-to-origin domain name is bound in R2's self-defined domain name.
[](https://www.eallion.com/assets/images/posts/2023/07/cf_callback_hostname.png)
Then click `添加自Definition主机名` and fill in the CDN domain name, such as `images.eallion.com`. The recommended validation method is TXT Validation.
[](https://www.eallion.com/assets/images/posts/2023/07/add_custom_hostname.png)
After adding, you need to validate the domain name. Go to your own domain name resolution console, such as DNSPod, and add 2 TXT records.
Wait for both `证书State` and `主机名State` to become `有效`.
[](https://www.eallion.com/assets/images/posts/2023/07/cf_dns_txt_records.png)
### Parse CNAME
After `回退源State` `证书State` and `主机名State` become `有效`, go to your own domain name resolution console to add CNAME resolution.
Point the production environment's `images.eallion.com` CNAME to `images.example.com`.
[](https://www.eallion.com/assets/images/posts/2023/07/dns_cname_records.png)
Normally's tutorial ends here.
But this way isVisit doesn't work with R2's resources.
The most important step, use Worker Proxy R2.
### Create new Worker Proxy R2
There is official documentation on how to pass Worker Visit R2:
Use R2 from Workers:[https://developers.cloudflare.com/r2/api/workers/workers-api-usage/](https://developers.cloudflare.com/r2/api/workers/workers-api-usage/)
Just follow the documentation tutorial step by step.
If you are lazy, you don’t want to authenticate. Then just use my streamlined code.
The `DELETE` and `PUT` 's codes are directly removed, leaving only `GET`.
Workers can be created manually in the background without Wrangle CLI scripts.
Switch to the `Worker 和 Pages` column on the left, `创建应用程序`, just give it a name, choose a template Deployment, and change the code later.
Click `快速edit` to copy the following code to `worker.js`, save and Deployment:
```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
var worker_default = {
async fetch(request, env) {
if (request.method !== 'GET') {
return new Response('Only GET method allowed', { status: 405 });
}
const url = new URL(request.url);
const key = url.pathname.slice(1);
const object = await env.MY_BUCKET.get(key);
if (!object) {
return new Response('Object not found', { status: 404 });
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('ETag', object.httpEtag);
return new Response(object.body, {
headers,
});
},
};
export { worker_default as default };
```
Returned after Deployment is successful.
In the current Worker 's settings, `Variable` `R2 存储桶绑定` add binding:
* `Variablename`:`MY_BUCKET`
* `R2 存储桶`: Select yes should's bucket
[](https://www.eallion.com/assets/images/posts/2023/07/r2_binding.png)
### Workers routing
Go back to Zones, select the domain name, and add Workers routing:
* `路由`: Be sure to fill in the production environment's domain name, do not fill in Cloudflare's source domain name, such as: `images.eallion.com/*`;
* `Worker`: Select the previous step to create's Worker;
* `环境`:Production.
[](https://www.eallion.com/assets/images/posts/2023/07/r2_worker_router.png)
At this point, you should be able to visit Cloudflare R2's content using CNAME's method.
* [https://images.eallion.com/eallion.jpg](https://images.eallion.com/eallion.jpg)
### Worker Proxy Backblaze B2
In fact, R2 is enough, but B2 may be needed for various reasons.
Actually it's pretty much the same.
Backblaze also has official documentation introducing how to visit B2 through Cloudflare Worker.
Docs: [Integrate Cloudflare Workers with Backblaze B2](https://www.backblaze.com/docs/cloud-storage-integrate-cloudflare-workers-with-backblaze-b2)
Let’s briefly introduce how to do it: (It is also recommended to read Official Docs.)
##### 1. Create a new Cloudflare Worker, `worker.js`
```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
(() => {
// node_modules/aws4fetch/dist/aws4fetch.esm.mjs
var encoder = new TextEncoder();
var HOST_SERVICES = {
appstream2: 'appstream',
cloudhsmv2: 'cloudhsm',
email: 'ses',
marketplace: 'aws-marketplace',
mobile: 'AWSMobileHubService',
pinpoint: 'mobiletargeting',
queue: 'sqs',
'git-codecommit': 'codecommit',
'mturk-requester-sandbox': 'mturk-requester',
'personalize-runtime': 'personalize',
};
var UNSIGNABLE_HEADERS = /* @__PURE__ */ new Set([
'authorization',
'content-type',
'content-length',
'user-agent',
'presigned-expires',
'expect',
'x-amzn-trace-id',
'range',
'connection',
]);
var AwsClient = class {
constructor({
accessKeyId,
secretAccessKey,
sessionToken,
service,
region,
cache,
retries,
initRetryMs,
}) {
if (accessKeyId == null)
throw new TypeError('accessKeyId is a required option');
if (secretAccessKey == null)
throw new TypeError('secretAccessKey is a required option');
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.sessionToken = sessionToken;
this.service = service;
this.region = region;
this.cache = cache || /* @__PURE__ */ new Map();
this.retries = retries != null ? retries : 10;
this.initRetryMs = initRetryMs || 50;
}
async sign(input, init) {
if (input instanceof Request) {
const { method, url, headers, body } = input;
init = Object.assign({ method, url, headers }, init);
if (init.body == null && headers.has('Content-Type')) {
init.body =
body != null && headers.has('X-Amz-Content-Sha256')
? body
: await input.clone().arrayBuffer();
}
input = url;
}
const signer = new AwsV4Signer(
Object.assign({ url: input }, init, this, init && init.aws)
);
const signed = Object.assign({}, init, await signer.sign());
delete signed.aws;
try {
return new Request(signed.url.toString(), signed);
} catch (e) {
if (e instanceof TypeError) {
return new Request(
signed.url.toString(),
Object.assign({ duplex: 'half' }, signed)
);
}
throw e;
}
}
async fetch(input, init) {
for (let i = 0; i <= this.retries; i++) {
const fetched = fetch(await this.sign(input, init));
if (i === this.retries) {
return fetched;
}
const res = await fetched;
if (res.status < 500 && res.status !== 429) {
return res;
}
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i))
);
}
throw new Error(
'An unknown error occurred, ensure retries is not negative'
);
}
};
var AwsV4Signer = class {
constructor({
method,
url,
headers,
body,
accessKeyId,
secretAccessKey,
sessionToken,
service,
region,
cache,
datetime,
signQuery,
appendSessionToken,
allHeaders,
singleEncode,
}) {
if (url == null) throw new TypeError('url is a required option');
if (accessKeyId == null)
throw new TypeError('accessKeyId is a required option');
if (secretAccessKey == null)
throw new TypeError('secretAccessKey is a required option');
this.method = method || (body ? 'POST' : 'GET');
this.url = new URL(url);
this.headers = new Headers(headers || {});
this.body = body;
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.sessionToken = sessionToken;
let guessedService, guessedRegion;
if (!service || !region) {
[guessedService, guessedRegion] = guessServiceRegion(
this.url,
this.headers
);
}
this.service = service || guessedService || '';
this.region = region || guessedRegion || 'us-east-1';
this.cache = cache || /* @__PURE__ */ new Map();
this.datetime =
datetime || new Date().toISOString().replace(/[:-]|\.\d{3}/g, '');
this.signQuery = signQuery;
this.appendSessionToken =
appendSessionToken || this.service === 'iotdevicegateway';
this.headers.delete('Host');
if (
this.service === 's3' &&
!this.signQuery &&
!this.headers.has('X-Amz-Content-Sha256')
) {
this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');
}
const params = this.signQuery ? this.url.searchParams : this.headers;
params.set('X-Amz-Date', this.datetime);
if (this.sessionToken && !this.appendSessionToken) {
params.set('X-Amz-Security-Token', this.sessionToken);
}
this.signableHeaders = ['host', ...this.headers.keys()]
.filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header))
.sort();
this.signedHeaders = this.signableHeaders.join(';');
this.canonicalHeaders = this.signableHeaders
.map(
(header) =>
header +
':' +
(header === 'host'
? this.url.host
: (this.headers.get(header) || '').replace(/\s+/g, ' '))
)
.join('\n');
this.credentialString = [
this.datetime.slice(0, 8),
this.region,
this.service,
'aws4_request',
].join('/');
if (this.signQuery) {
if (this.service === 's3' && !params.has('X-Amz-Expires')) {
params.set('X-Amz-Expires', '86400');
}
params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');
params.set(
'X-Amz-Credential',
this.accessKeyId + '/' + this.credentialString
);
params.set('X-Amz-SignedHeaders', this.signedHeaders);
}
if (this.service === 's3') {
try {
this.encodedPath = decodeURIComponent(
this.url.pathname.replace(/\+/g, ' ')
);
} catch (e) {
this.encodedPath = this.url.pathname;
}
} else {
this.encodedPath = this.url.pathname.replace(/\/+/g, '/');
}
if (!singleEncode) {
this.encodedPath = encodeURIComponent(this.encodedPath).replace(
/%2F/g,
'/'
);
}
this.encodedPath = encodeRfc3986(this.encodedPath);
const seenKeys = /* @__PURE__ */ new Set();
this.encodedSearch = [...this.url.searchParams]
.filter(([k]) => {
if (!k) return false;
if (this.service === 's3') {
if (seenKeys.has(k)) return false;
seenKeys.add(k);
}
return true;
})
.map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p))))
.sort(([k1, v1], [k2, v2]) =>
k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0
)
.map((pair) => pair.join('='))
.join('&');
}
async sign() {
if (this.signQuery) {
this.url.searchParams.set('X-Amz-Signature', await this.signature());
if (this.sessionToken && this.appendSessionToken) {
this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);
}
} else {
this.headers.set('Authorization', await this.authHeader());
}
return {
method: this.method,
url: this.url,
headers: this.headers,
body: this.body,
};
}
async authHeader() {
return [
'AWS4-HMAC-SHA256 Credential=' +
this.accessKeyId +
'/' +
this.credentialString,
'SignedHeaders=' + this.signedHeaders,
'Signature=' + (await this.signature()),
].join(', ');
}
async signature() {
const date = this.datetime.slice(0, 8);
const cacheKey = [
this.secretAccessKey,
date,
this.region,
this.service,
].join();
let kCredentials = this.cache.get(cacheKey);
if (!kCredentials) {
const kDate = await hmac('AWS4' + this.secretAccessKey, date);
const kRegion = await hmac(kDate, this.region);
const kService = await hmac(kRegion, this.service);
kCredentials = await hmac(kService, 'aws4_request');
this.cache.set(cacheKey, kCredentials);
}
return buf2hex(await hmac(kCredentials, await this.stringToSign()));
}
async stringToSign() {
return [
'AWS4-HMAC-SHA256',
this.datetime,
this.credentialString,
buf2hex(await hash(await this.canonicalString())),
].join('\n');
}
async canonicalString() {
return [
this.method.toUpperCase(),
this.encodedPath,
this.encodedSearch,
this.canonicalHeaders + '\n',
this.signedHeaders,
await this.hexBodyHash(),
].join('\n');
}
async hexBodyHash() {
let hashHeader =
this.headers.get('X-Amz-Content-Sha256') ||
(this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);
if (hashHeader == null) {
if (
this.body &&
typeof this.body !== 'string' &&
!('byteLength' in this.body)
) {
throw new Error(
'body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header'
);
}
hashHeader = buf2hex(await hash(this.body || ''));
}
return hashHeader;
}
};
async function hmac(key, string) {
const cryptoKey = await crypto.subtle.importKey(
'raw',
typeof key === 'string' ? encoder.encode(key) : key,
{ name: 'HMAC', hash: { name: 'SHA-256' } },
false,
['sign']
);
return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string));
}
async function hash(content) {
return crypto.subtle.digest(
'SHA-256',
typeof content === 'string' ? encoder.encode(content) : content
);
}
function buf2hex(buffer) {
return Array.prototype.map
.call(new Uint8Array(buffer), (x) => ('0' + x.toString(16)).slice(-2))
.join('');
}
function encodeRfc3986(urlEncodedStr) {
return urlEncodedStr.replace(
/[!'()*]/g,
(c) => '%' + c.charCodeAt(0).toString(16).toUpperCase()
);
}
function guessServiceRegion(url, headers) {
const { hostname, pathname } = url;
if (hostname.endsWith('.r2.cloudflarestorage.com')) {
return ['s3', 'auto'];
}
if (hostname.endsWith('.backblazeb2.com')) {
const match2 = hostname.match(
/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/
);
return match2 != null ? ['s3', match2[1]] : ['', ''];
}
const match = hostname
.replace('dualstack.', '')
.match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);
let [service, region] = (match || ['', '']).slice(1, 3);
if (region === 'us-gov') {
region = 'us-gov-west-1';
} else if (region === 's3' || region === 's3-accelerate') {
region = 'us-east-1';
service = 's3';
} else if (service === 'iot') {
if (hostname.startsWith('iot.')) {
service = 'execute-api';
} else if (hostname.startsWith('data.jobs.iot.')) {
service = 'iot-jobs-data';
} else {
service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';
}
} else if (service === 'autoscaling') {
const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];
if (targetPrefix === 'AnyScaleFrontendService') {
service = 'application-autoscaling';
} else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {
service = 'autoscaling-plans';
}
} else if (region == null && service.startsWith('s3-')) {
region = service.slice(3).replace(/^fips-|^external-1/, '');
service = 's3';
} else if (service.endsWith('-fips')) {
service = service.slice(0, -5);
} else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) {
[service, region] = [region, service];
}
return [HOST_SERVICES[service] || service, region];
}
// index.js
var UNSIGNABLE_HEADERS2 = ['x-forwarded-proto', 'x-real-ip'];
function filterHeaders(headers) {
return Array.from(headers.entries()).filter(
(pair) =>
!UNSIGNABLE_HEADERS2.includes(pair[0]) && !pair[0].startsWith('cf-')
);
}
async function handleRequest(event, client2) {
const request = event.request;
if (!['GET', 'HEAD'].includes(request.method)) {
return new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
});
}
const url = new URL(request.url);
let path = url.pathname.replace(/^\//, '');
path = path.replace(/\/$/, '');
const pathSegments = path.split('/');
if (ALLOW_LIST_BUCKET !== 'true') {
if (
(BUCKET_NAME === '$path' && pathSegments[0].length < 2) ||
(BUCKET_NAME !== '$path' && path.length === 0)
) {
return new Response(null, {
status: 404,
statusText: 'Not Found',
});
}
}
switch (BUCKET_NAME) {
case '$path':
url.hostname = B2_ENDPOINT;
break;
break;
case '$host':
url.hostname = url.hostname.split('.')[0] + '.' + B2_ENDPOINT;
break;
default:
url.hostname = BUCKET_NAME + '.' + B2_ENDPOINT;
break;
}
const headers = filterHeaders(request.headers);
const signedRequest = await client2.sign(url.toString(), {
method: request.method,
headers,
body: request.body,
});
return fetch(signedRequest);
}
var endpointRegex = /^s3\.([a-zA-Z0-9-]+)\.backblazeb2\.com$/;
var [, aws_region] = B2_ENDPOINT.match(endpointRegex);
var client = new AwsClient({
accessKeyId: B2_APPLICATION_KEY_ID,
secretAccessKey: B2_APPLICATION_KEY,
service: 's3',
region: aws_region,
});
addEventListener('fetch', function (event) {
event.respondWith(handleRequest(event, client));
});
})();
```
##### 2. Set Worker Environment Variables
* `ALLOW_LIST_BUCKET`:true
* `B2_APPLICATION_KEY`:K004WJZP11111111111111111111Q
* `B2_APPLICATION_KEY_ID`:0042e9999999920000000001
* `B2_ENDPOINT`:s3.us-west-004.backblazeb2.com
* `BUCKET_NAME`:eallion-static
The APP KEY and ID need to be generated in the Backblaze backend, and `B2_ENDPOINT` needs to be viewed in its own B2 bucket.
##### 3. Manually add CNAME to resolve to B2
[](https://www.eallion.com/assets/images/posts/2023/07/b2_cf_record.png)
* `类型`: Select `CNAME`
* `name`: used for `回退源`, such as: `b2.example.com`, fill in `b2`
* `内容`: Fill in your own B2 bucket allocation's `S3 URL`, there's a tutorial here written byis `Friendly URL`, it's not necessary, there is one more step to reverse generation.
[](https://www.eallion.com/assets/images/posts/2023/07/backblaze_url.png)
##### 4. Configuration fallback source
`Zones`'s domain name is Backblaze B2. Set's CNAME name is whatever it is, then fill in whatever the fallback source is, such as: `b2.example.com`.
Just refer to the previous article.
##### 5. Configuration self-defined host name
Refer to the previous article.
##### 6. Configuration Worker routing
* `路由`: Be sure to fill in the production environment's domain name, do not fill in Cloudflare's source domain name;
* `Worker`: Select the previous step to create's Worker;
* `环境`:Production.
Adding Worker routes for Backblaze B2 is different from Cloudflare R2. You need to add 2 items:
* `b2.example.com/*` also needs to be added to the Worker route
* `images.eallion.com/*`
:::
CDN certificate automatic replacement
The above has solved the basic issue, but there is still a pain point with the SSL certificate issue. CF offers free renewal and update of never-expired certificates, but domestic CDN manufacturers generally need to manually upload their own application's certificates. . . This is really inconvenient, so I was wondering if I could find some solutions:
::: details Automatically update certificate scripts
Cause: Because Configuration domestic CDN basically requires manual uploading of certificates, but the domain name certificate I applied for basically has a three-month shelf life, so I thought of writing an automatic script to automatically update the certificate.
Environment:
1panel (domestic panel, automatic application for certificates, and other powerful functions, very convenient's)
I use Duojiyun as an example. Other manufacturers can find the corresponding SDK.
The code is as follows:
```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from hashlib import sha1
import hmac
import requests
import json
import urllib
def dogecloud_api(api_path, data={}, json_mode=False):
"""
调用多吉云API
:param api_path: 调用's API Interface地址,Package含 URL 请求parameters QueryString,for example:/console/vfetch/add.json?url=xxx&a=1&b=2
:param data: POST 's 数据,dictionary,for example {'a': 1, 'b': 2},传递此parameters表示不is GET 请求而is POST 请求
:param json_mode: 数据 data is否以 JSON 格式请求,默认为 false 则使用Form形式(a=1&b=2)
:type api_path: string
:type data: dict
:type json_mode bool
:return dict: 返回's 数据
"""
# 这里替换为你's 多吉云永久 AccessKey 和 SecretKey,可in用户中心 - 密钥管理中View
# 请勿in客户端暴露 AccessKey 和 SecretKey,否则恶意用户将获得账号完全控制权
access_key = ''
secret_key = ''
body = ''
mime = ''
if json_mode:
body = json.dumps(data)
mime = 'application/json'
else:
body = urllib.parse.urlencode(data) # Python 2 可以直接用 urllib.urlencode
mime = 'application/x-www-form-urlencoded'
sign_str = api_path + "\n" + body
signed_data = hmac.new(secret_key.encode('utf-8'), sign_str.encode('utf-8'), sha1)
sign = signed_data.digest().hex()
authorization = 'TOKEN ' + access_key + ':' + sign
response = requests.post('https://api.dogecloud.com' + api_path, data=body, headers = {
'Authorization': authorization,
'Content-Type': mime
})
return response.json()
api = dogecloud_api('/cdn/cert/list.json')
if api['code'] == 200:
for cert in api['data']['certs']:
ssl_next_id = cert['id']
delet_api = dogecloud_api('/cdn/cert/delete.json', {
'id': cert['id']
})
else:
print("api failed: " + api['msg']) # 失败
# 下面两个路径就is1panelauto-generated证书路径
with open('/opt/1panel/apps/openresty/openresty/www/sites/xxxx/ssl/fullchain.pem') as fullchain:
full = fullchain.read()
with open('/opt/1panel/apps/openresty/openresty/www/sites/xxxx/ssl/privkey.pem') as privkey:
priv = privkey.read()
api = dogecloud_api('/cdn/cert/upload.json', {
"note": f"自动证书{ssl_next_id}",
"cert": full,
"private": priv
})
if api['code'] == 200:
ssl_id = api['data']['id']
else:
print("api failed: " + api['msg']) # 失败
api = dogecloud_api('/cdn/domain/config.json?domain=cdn.example.com', {
'cert_id': ssl_id
}, True)
```
The basic implementation idea is to first remove the existing certificate, then add the read's certificate, then upload and activate the uploaded's certificate, so that the Implementation CDN certificate is automatically configured. You can use 1panel to automatically execute scripts every one month to update the certificate. It's really Implementation again a Qiweiwei's tips ✊✊✊
:::
# Caddy
Source: https://base.bangwu.me/env/Caddy
Caddy is a modern Go web server with automatic HTTPS certificate management, covering Caddyfile syntax, reverse proxy setup, and file hosting.
# Web server
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy
```
The simplest configuration looks like this:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
example.com {
reverse_proxy localhost:port
}
```
Just point the domain's DNS record to your server IP. Caddy will handle HTTPS automatically, which makes the setup very straightforward.
# Fuwari
Source: https://base.bangwu.me/env/Fuwari
Fuwari is an Astro-based static blog theme with clean design, covering project setup, article frontmatter format, tags, and deployment steps.
## Fuwari
[Fuwari](https://github.com/saicaca/fuwari) is an Astro-based static blog theme with a clean and elegant style.
### Features
* 🚀 **Fast**: built on Astro with excellent performance
* 🎨 **Beautiful**: modern design and responsive layout
* 🌙 **Dark Mode**: supports light and dark theme switching
* 📝 **Markdown**: write posts in Markdown
* 🔍 **SEO-friendly**: optimized for search indexing
* 📱 **Responsive**: works well on mobile devices
* 💬 **Comments**: supports multiple comment systems
* 🔗 **Friend links**: supports a dedicated links page
### Quick start
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# clone the project
git clone https://github.com/saicaca/fuwari.git
cd fuwari
# InstallationDependency
npm install
# local development
npm run dev
# built
npm run built
```
### Configuration
Edit `src/config.ts`:
```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
export const siteConfig = {
title: '你's blogstitle',
subtitle: 'Subtitle',
lang: 'zh-CN',
description: 'blogsDescription',
author: 'Author Name',
avatar: '/avatar.jpg',
// Social Links
socialLinks: [
{ name: 'github', url: 'https://github.com/username' },
{ name: 'twitter', url: 'https://twitter.com/username' },
],
}
```
### Create a post
Create a Markdown file under `src/content/posts/`:
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
---
title: Article Title
published: 2024-01-01
description: Article Description
tags: [Tag1, Tag2]
category: Category
draft: false
---
Article Content...
```
### Deployment
#### GitHub Pages
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- run: npm install
- run: npm run built
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
```
#### Vercel
1. Import the GitHub repo into Vercel.
2. Set the build command to `npm run built`.
3. Set the output directory to `dist`.
#### Cloudflare Pages
1. Connect the GitHub repo.
2. Set the build command to `npm run built`.
3. Set the output directory to `dist`.
### Customization
#### Modify theme colors
Edit `src/styles/global.css`:
```css theme={"theme":{"light":"github-light","dark":"github-dark"}}
:root {
--primary: #your-color;
}
```
#### Add a comment system
Fuwari supports comment systems such as Giscus and Waline. Enable the one you want in the config file.
### References
* [GitHub repository](https://github.com/saicaca/fuwari)
* [Demo site](https://fuwari.vercel.app/)
* [Astro documentation](https://docs.astro.build/)
# Jupyter
Source: https://base.bangwu.me/env/Jupyter
Jupyter Notebook is an interactive data analysis tool for running code in the browser, covering installation, remote SSH access, and shortcuts.
# Jupyter
## Jupyter Notebook
## Interactive code notebooks in the browser
Jupyter Notebook is the first-generation product from the Jupyter team and still the most classic one. If you have learned Python before, you are probably already familiar with it.
## JupyterLab
JupyterLab is the more advanced successor to Jupyter Notebook, with a richer interface and more features.
## JupyterLite
JupyterLite is a lightweight static Jupyter environment built by the Jupyter team to run entirely in the browser. In other words, as long as you have a browser, you can use it without a server or a local programming environment. That is exactly why it is called “Lite”.
### Advantages
A lightweight tool like this is especially suitable for embedding an online code editor in a web page.
```html theme={"theme":{"light":"github-light","dark":"github-dark"}}
```
Embedding the snippet above in an HTML page gives you a simple editor. It could be extended further with code completion and other features.
# Agent harness
Source: https://base.bangwu.me/env/agent-harness
A practical guide to AI agent harness design, covering memory, skills, protocols, context management, evals, and common failure modes.
# Agent harness
An agent harness is the runtime layer around an AI model. It decides what context the model sees, which tools it can call, how permissions work, where memory lives, and how the agent recovers from mistakes.
Do not treat the harness as plumbing. For coding agents and workflow agents, the harness often determines reliability more than the raw model choice.
## The useful mental model
A good agent system externalizes capabilities that should not live only inside model weights.
| Layer | What it externalizes | Examples |
| - | - | - |
| Memory | Durable state and retrieval | project notes, user preferences, task history, vector search |
| Skills | Reusable procedures | browser control, code review, image generation, deployment helpers |
| Protocols | Communication contracts | MCP, JSON schemas, typed tool responses, error formats |
| Harness | Runtime coordination | context assembly, tool routing, approvals, logs, retries, evals |
This model comes from the paper **Externalization in LLM Agents: A Unified Review of Memory, Skills, Protocols and Harness Engineering**. The important engineering question is:
> Which capability should stay implicit in the model, and which capability should become an explicit external component?
If the answer affects reliability, auditability, reuse, or cost, it usually belongs outside the model.
## What the harness owns
The harness should make these decisions explicit:
* which files, pages, tools, and memories enter context
* when old context is summarized, dropped, or preserved
* how tool calls are validated before execution
* which actions require user approval
* how tool errors are represented and retried
* how model effort, latency, and cost trade off
* how runs are logged for later debugging
A thin harness can work, but an implicit harness becomes hard to debug. If behavior changes and nobody knows whether the cause is the model, prompt, context cache, tool layer, or product default, the harness is under-instrumented.
## Design rules
### Keep tools small and inspectable
Prefer narrow tools with clear inputs and outputs. A tool that does one thing is easier for the model to call correctly and easier for humans to audit.
For local workflows, CLI tools are often enough. For reusable cross-client integration, use a protocol boundary such as MCP. For stable product backends, a direct API is still the simplest option.
MCP got much better in 2026 — it is now stateless, supports deferred tool loading, and models are stronger at structured tool calling. That does **not** mean MCP is better than CLI for most integrations.
Prefer **CLI** when:
* the model already knows the command (`gh`, `aws`, `kubectl`) so you spend almost no schema tokens
* you are on a local machine or in CI with a fixed command
* you need pipes, composition, or a one-off debug loop
* token cost matters and `--help` plus a skill is enough to teach a new CLI
Prefer **MCP** when:
* there is no terminal (browser, mobile, hosted agent)
* you need OAuth, per-user auth, or standardized audit headers
* the tool is new to the model and a machine-checkable JSON schema is worth the extra tokens
* the tool set is dynamic and agents should discover tools at runtime (`tools/list` + deferred loading)
A useful rule: CLI wins on known local tools and composition. MCP wins on auth, audit, discovery, and environments without a shell.
### Separate chat transport from agent execution
A messaging adapter should normalize platform events and deliver replies, not become the agent framework. BerriAI's `agentchat` makes this split explicit: channel adapters emit shared message objects; the core claims message IDs, locks the conversation, records history, and dispatches to an application handler. The handler owns sender authorization and the agent run.
Its architecture and source at commit `fb892cb` provide a useful reference, with important limits:
| Responsibility | Keep it in |
| - | - |
| Provider credentials, event decoding, acknowledgments, reply rendering | Platform adapter or authenticated ingress |
| Duplicate-event detection and per-conversation serialization | Shared state/coordination layer |
| User authorization, agent/session mapping, tool permissions | Application handler and execution policy |
| Durable jobs, crash recovery, uncertain delivery reconciliation | Application-owned durable infrastructure |
Do not confuse the boundaries:
* **Authenticated event is not authorized work.** For Slack HTTP requests, verify the signature over the raw body and timestamp using the documented scheme and a constant-time comparison. Then separately decide what that sender may ask the agent to do. Socket Mode uses a different ingress mechanism; do not apply HTTP signing rules indiscriminately to every transport.
* **Acknowledgment is not completion.** Slack's HTTP Events API requires a 2xx response within three seconds and can retry failed deliveries. If you promise durable processing, persist/enqueue accepted work before acknowledging it; keep model execution out of the acknowledgment path. Handle enqueue failure explicitly rather than returning success and dropping work.
* **Deduplication is not crash recovery.** In this `agentchat` snapshot, the default `MemoryState` keeps claims, locks, and history in one process. A claim is recorded before the handler runs, with no claim rollback in `_receive`. A handler failure is therefore not automatically retried by delivering the same event again in that process; a restart, meanwhile, loses the in-memory claims. Production recovery needs a durable job lifecycle and explicit retry policy, not just a set of seen IDs.
* **A conversation lock is not a global ordering guarantee.** It serializes local processing, not provider timestamps or workers in other processes. Scope conversation keys to the provider, installation/tenant, and conversation or thread. Coordinate workers through shared storage or partitioning, and explicitly decide whether a group thread shares context across users.
* **Agent completion is not confirmed delivery.** Persist the generated reply and delivery state separately. If sending times out, reconcile the provider's receipt or use its documented deduplication mechanism; rerunning the whole agent may repeat tool side effects without fixing the missing reply.
These are production design requirements, not claims that the SDK implements a durable queue or exactly-once execution. Test duplicate delivery, unauthorized senders, concurrent messages, restart after acceptance, handler failure, and send-timeout ambiguity before exposing an agent to a chat platform. Those cases belong in [product evals and regression tests](/env/ai-evals), even when the happy-path demo needs only a few lines.
### Separate skill design from execution
A skill is a manual for the agent — it should only contain what the model does not already know. The execution is done by tools (scripts, CLI, apps) that the model calls directly.
Keep the two apart:
* **Design logic** lives in the SKILL.md and describes *what* to do and *why*.
* **Execution logic** lives in scripts and tools and describes *how* to do it.
Scripts can be pre-written or generated on the fly by the agent when a task needs one. Generated scripts are flexible — agents already do this even without a skill, often writing a one-off Python snippet. They are also slower, more token-hungry, and less complete on edge cases. Pre-written scripts win when the task is recurring and quality matters: a Markdown-to-HTML skill that generates the converter at runtime will be barely usable, while a pre-written converter can cover styles and edge cases. Treat generated scripts as throwaway until verified.
This separation explains why strong skills still need a UI: the skill tells the agent what to accomplish, while a UI carries the concrete execution steps a human can trigger with a few clicks instead of re-prompting from scratch each time.
Skills did not kill MCP, and RAG is not dead. They solve different problems and often sit in the same workflow:
* **MCP** is a shared interface: structured tool calls, auth, and data access.
* **Skills** are packaged expertise: how this team works, how this project should change, which conventions matter. Markdown is a feature — humans can read it too.
* **RAG / retrieval** grounds the model in documents, tickets, and code that are not in weights.
MCP provides access. Skills explain how to use that access well. Retrieval starts the model closer to the answer. Pick the layer that matches the gap, not a winner.
### Preserve reasoning-critical context
Context pruning is not just a cost optimization. It changes behavior.
If an agent made tool calls or file edits based on earlier reasoning, the harness must preserve enough rationale for later turns to continue coherently. Otherwise the agent may repeat itself, forget why it chose a path, or pick odd tools.
### Represent durable state as files
Long-running agent workflows need state outside chat history. Plain files are often the simplest durable memory layer because humans can inspect, edit, diff, and version them.
A useful pattern is a workspace that separates intent, resources, work products, and learning records:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
workspace/
├── MISSION.md # why this work or learning track exists
├── RESOURCES.md # trusted sources and references
├── NOTES.md # preferences and scratch notes
├── lessons/ # one self-contained learning unit per file
├── reference/ # compressed long-term reference material
└── learning-records/ # what changed in the user's capability
```
The exact names can change. The important rule is that state should be **inspectable, restartable, and scoped**. For agent-assisted learning, this lets the agent teach the next step from the learner's current capability instead of from a generic syllabus. For engineering work, the same pattern applies to onboarding notes, migration logs, incident follow-ups, and task journals.
### Reset at checkpoints; keep raw history retrievable
A summary is a lossy copy. When a harness compacts a long session, it rereads the history and rewrites it as prose. The exact error message, file path, or number the next step needs may not survive. Two October 2026 papers point to a different default.
* **Checkpoint, then start clean.** CORAL (COLM 2026) gives the agent a tool it can call to save task progress and verified facts, clear the cluttered context, and start a new episode that sees only the checkpoint. An 8B model trained to use the tool with reinforcement learning (MERPO) reached 42.8% average accuracy on GAIA. The biggest gains were on the long-horizon Level 2 and 3 tasks, and it used 6–7× fewer input tokens than a ReAct agent. The authors used RL to improve when and what the agent checkpoints, so do not expect an untrained model to time resets well on its own. Without RL, approximate it with a fixed checkpoint template (verified facts, open questions, next step) that the agent fills at phase boundaries before you open a fresh session.
* **Keep the raw record and retrieve from it.** Raw-RAG (arXiv 2610.30755) splits raw conversation history into windows and uses dense retrieval plus cross-encoder reranking, with no extraction, summaries, or graphs. It ranked first among the compared memory systems in 6 of 7 benchmark–model settings across LoCoMo, LongMemEval, MEME, and MemoryAgentBench. Adding fact extraction, summaries, or graph expansion on top *lowered* accuracy. In the authors' Mem0 audit, making memory append-only (no UPDATE or DELETE) raised LoCoMo accuracy from 67.36% to 69.42%. The likely reason: answers often depend on the order of events and on how one value led to another, and transformations drop that context.
The rule that carries over: **write the full session record append-only, keep the checkpoint small and verified, and let a fresh session search the raw record on demand.** Treat summaries as an index into the record, not a replacement for it. See [Claude Code patterns](/env/claude-code-patterns) for the interactive version of this workflow.
Limits: Raw-RAG's evidence comes from offline conversation benchmarks, and raw logs cost storage and raise privacy questions. Compaction is still reasonable when the agent has no tool to search its own history. Compare both on your own tasks before committing to one.
### Audit memory for the associativity blind spot
Every current memory architecture — Flat RAG, graph memory, agentic hierarchies, OS-style memory kernels — retrieves with the same recipe: embed query and stored content into one similarity space (BM25 or dense vectors), take top-K. That caps recall at **surface similarity**.
It covers only *descriptive* recall — the query shares wording, entities, or timestamps with the memory. The other half is *associative* recall: a month-old note that "someone on the team has a severe seafood allergy" is the decisive evidence for today's question "where should the team dinner be?" Zero lexical overlap; only a semantic arc (causality, same situation) connects them. Tencent's **T-Mem** paper (2026) measures the blind spot: on LoCoMo-Plus Cognitive questions — built to strip lexical overlap — similarity-based systems score 32–49%, and GPT-4o reading the entire transcript scores only 21%.
T-Mem's fix borrows from cognitive science (episodic future thinking): at **write time**, compute and store a prediction of *when this memory will matter again* — a trigger. Four trigger families cover the 2×2 space of granularity (fact / scene) × orientation (descriptive / associative). The two associative families are the point:
* **Bridge trigger** — project a fact into the concrete situation where knowing it will help: "seafood allergy → picking a restaurant for the team dinner", with one step of reasoning why.
* **Horizon trigger** — project a scene onto forward-looking dimensions so a future query approaching from a different context still hits it.
Their ablation is the headline: removing Horizon triggers moves the standard benchmark by 0.08 points but collapses the associative one by 12.47. Systems tuned only on similarity benchmarks are implicitly optimizing to stay inside the similarity neighborhood — and that benchmark family cannot see the cost of the neighborhood's edge.
The transferable rule: **do recall-plan at write time, when you know the content best.** Materialize the questions each item should answer, not just the item. It costs tokens once, offline; it saves the query every time after.
### Make retrieval deterministic when correctness matters
Do not ask an agent to "figure it out" through brittle websites, scattered databases, or undocumented one-off scripts when the task needs exact results. Give it a deterministic retrieval layer instead.
Anthropic's biology-agent case study is a good example. Scientific agents were asked to retrieve viral sequence data from NCBI Virus. The durable lesson was not that one model won a benchmark; it was that reliability improved dramatically when the workflow added `gget virus`, a deterministic retrieval layer with a narrower interface.
For high-stakes retrieval, prefer:
* typed query functions over free-form browsing
* stable IDs, versions, and date filters
* machine-checkable counts or checksums
* explicit provenance for every returned record
* validation steps before downstream analysis
* documented error cases instead of silent best-effort output
This is the same harness principle as tool design: make the execution surface predictable, then let the model plan around it.
The first retrieval move deserves disproportionate investment. The **Question's Gambit** paper (2026) lifted GPT-5.5 from 83.1% to 90.5% on BrowseComp-Plus with the same retriever and the same agent loop — the only change was a single pre-search step that runs once, before the loop starts: split the question into clues, turn each clue into complementary searches, pool the results, and rerank. The agent then starts with a ranked evidence set already in context. The same change lifted a mini model from 68.1% to 79.0% and roughly halved calibration error.
The error analysis is the real lesson: of 79 remaining errors for the strongest model, only 3 came from the gold document never being retrieved. The other 76 happened later — previewing, opening, or using the evidence. **Front-load the opening context; verify the consumption, not just the fetch.** Cost: 2.3–5.3 extra tool calls per question, cheap against a full failed run.
### Judge indexes by context cost, not just accuracy
Once a search loop is competent, extra index structures may not raise accuracy at all. The RAGFlow team (arXiv 2610.41172) ran a harness with only BM25 and `grep` on MiniMax M3. With no vector or compiled index, it answered 85% of BrowseComp-Plus and 91% of multi-hop FRAMES questions. Adding summary trees, a PageIndex-style outline, wikis, or graphs gave no detectable accuracy gain on FRAMES, and the outline got worse at scale.
The structures paid off in context instead. A navigation tree whose leaves are **claim–evidence pairs** cut query tokens by 91% when the leaf evidence was enough to answer, and added 1.9% when it wasn't, a 38% average saving. The token saving is bought with extra retrieval rounds, so it costs latency. A decision gate that chose when to stop cut latency from 140 seconds to 30. Other artifacts, such as ontologies, timelines, and entity graphs, earned their keep in governance, onboarding, and continuity, which accuracy benchmarks don't measure.
Practical order: start with lexical search (BM25, `grep`) and a disciplined loop that doesn't repeat queries or reread documents. Add compiled structures only when you can show they cut tokens or latency on your own queries. Make leaves self-contained claims with their evidence, so the agent can stop reading early. This matches the [raw-history finding](#reset-at-checkpoints-keep-raw-history-retrievable) above: keep the source, and treat compiled views as a way in, not a replacement.
### Design for human collaboration, not just autonomous execution
Most agent products optimize for self-evolution: the agent plans, executes, and closes the loop on its own. This is not always a healthy pattern. Even with transparency and traceability tools, an agent that prioritizes autonomous completion can create noise that is hard to hand off or maintain.
An agent is not only an execution container. It is also an environment for human understanding, judgment, and collaboration. When designing a harness, ask: can another person pick up this session and continue? Is the reasoning visible enough for a teammate to audit a decision? Does the workflow produce a maintainable artifact, or just a pile of automated steps?
Prioritize handoff quality over automation completeness. A workflow that ends with a clear, inspectable state is more valuable than one that "finished everything" but left no trail.
### Make telemetry and anti-abuse signals explicit
A coding agent with filesystem and shell access should be boring. Every non-obvious behavior erodes trust.
In July 2026, a developer auditing Claude Code discovered prompt steganography: the binary silently modified invisible Unicode characters in the system prompt date string (`Today's` → `Today\u2019s`) based on timezone (`Asia/Shanghai`, `Asia/Urumqi`) and hostname matching against XOR-encoded domain lists of Chinese AI labs, proxy services, and reseller gateways. The signal was never documented.
The detection goal is defensible — Anthropic wants to identify API resellers and distillation pipelines. The implementation is not. Hiding classification bits inside invisible punctuation, behind XOR and base64, makes every other privacy claim harder to believe. A simple bypass (change hostname, change timezone, patch binary) defeats the signal anyway, so the feature mainly punishes legitimate developers using custom API gateways.
The harness lesson: if your tool needs to detect abuse, make the signal explicit. Document it. Put it in release notes. Send a clear telemetry field. Transparency is not the enemy of anti-abuse — it is the foundation of trust.
### Make effort settings visible
Reasoning effort is a product decision, not only a model parameter. Lower effort can reduce latency and token use, but it can also make hard coding tasks feel worse.
Expose the current effort level, make it easy to change, and avoid silently changing defaults for complex workflows.
### Treat system prompts as code
System prompt edits can change quality as much as code changes. Review them with the same discipline:
* run per-model evals
* use ablations to test individual instructions
* roll out gradually
* keep an audit trail
* gate model-specific instructions to the intended model
Prompt brevity rules are especially risky for coding agents. If the agent is forced to be terse between tool calls, it may lose useful planning and verification behavior.
### Test the public harness
Internal builds can hide production-only issues. Dogfood the exact public build, public defaults, and public context behavior.
For code review or coding-agent evals, include the repositories and files the agent would actually need. A review that lacks cross-repo context can miss the bug even when the model is capable of finding it.
## Verification-first design
A practitioner shipping \~2,000 PRs a month through Cursor's pstack skills distilled the core principle as **"verification is all you need"**: the agent can close the loop on its own only if it can confirm its changes actually work. Verification is critical infrastructure, not an afterthought — worth the same investment as a production system.
Three components make it practical:
**1. A verification CLI, not markdown instructions.** Give the agent a small CLI that wraps app interaction and debugging — snapshot/screenshot, navigate, click/type, trace/wait-settle, health checks. A tool beats a one-off script every time: less token spend, reproducible, testable. Agent-friendly CLI design rules:
* composable API (deep modules: one command does one meaningful thing)
* destructive commands take `--dry-run`
* subcommands disclose features progressively
* error messages tell the agent *what to do next*
* rich `--help` and JSON output
**2. A feature map as materialized memory.** A set of markdown files describing what each feature is, how a user reaches it, and where the traps are. It is a compressed projection of the codebase — the code is the ultimate memory, and the map exists only to save tokens. Maintain it with a daily routine so it never goes stale.
**3. Cloud parallelism.** Local worktrees cap out around ten parallel agents and burn resources. Cloud agents with real machines, dependency installs, app runs, screen recording, and post-build snapshots enable hundreds of parallel sub-agents — the prerequisite for swarm verification and fuzz regression at scale.
The stack-selection corollary: **prefer debuggable runtimes.** If a tech stack can't be screenshotted, has no accessibility tree, and no performance traces, the agent cannot verify its own work. It is reasonable to change stack for agent-verifiability alone — Web/Electron exposes Chrome DevTools Protocol; iOS exposes the simulator.
The strongest quantitative case that harness beats model: the **GAVEL** paper (2026) took Qwen3-8B on long-horizon robot tasks from 41.2% to 91.8% with zero changes to the model. It adds an explicit graph world model — object relations, action preconditions and effects, probabilistic beliefs about unobserved objects. Before executing an LLM-generated action, the graph predicts what that action would do; violations get caught, and those with a mechanical fix are repaired without calling the model again. Only errors needing semantic reasoning go back to the LLM. On BEHAVIOR-1K, success rose from 19.9% to 92.6% across 500 multi-task instructions.
The reusable lesson: many long-horizon agent failures are **state-tracking failures, not reasoning failures**, and a symbolic checker outside the LLM catches them cheaply. Wrap the model's decision point in deterministic structure — a world model, a candidate list, a verifier — and the small model stops paying for what the harness already knows.
### Spend verification effort where it pays
A verification CLI makes checking possible. The next questions are when to check and who checks. Alibaba and Cornell (arXiv 2610.34577) compared 17 verification designs across seven frontier coding models on Terminal-Bench (TB) and SWE-bench Verified (SWE), grouped into four layers:
| Layer | What it adds | Accuracy change | Cost vs. baseline |
| - | - | - | - |
| L0 instructions | "Actually run it and read the real output; rereading the code isn't evidence" | +3.3 TB / +3.9 SWE in the system prompt; weaker in the user message | Little extra |
| L1 reminders | Nudges after edits or every few turns, capped at four | Mixed: up to +5.4 TB, flat on SWE | Little extra |
| L2 completion gates | When the agent stops, ask it to recheck, or reject the first "done" | Best variant +6.0 TB / +6.2 SWE | Rejection gates 1.48–1.76× |
| L3 independent review | A separate critic checks the work | +5.9–9.5 TB / +3.9–6.6 SWE | 1.13–1.25× TB, 1.00–1.04× SWE |
The critic setup is the part to copy:
* **Fresh context: the task plus the diff.** Giving the critic the agent's full trajectory cost 29–43% more and did no better on the visual benchmark.
* **A live sandbox, read-only for the deliverable.** The critic runs its own checks but never edits the work; scratch files go in `/tmp`.
* **A structured verdict.** A `done` flag, feedback, and a checklist with evidence for each requirement.
* **A bounded loop.** Objections go back to the agent as a user message, and the next delivery is accepted without another review.
* **Look at rendered output** for UI and visual artifacts, not just the code.
Scaling also favored independence. On TB, one critic for one round reached 62.7% at $0.47 per task. Four rounds reached 66.1% at $0.77, and four separate critics reached 65.8% at \$0.62.
The practical order: before adding more reminders to the main agent's prompt, add one independent reviewer with fresh context and a single revision pass. [AI code review](/env/ai-code-review) applies the same layering to pull requests.
## Failure modes to watch
For the review side of high-volume agent output — layered checks, verified findings, risk-tiered approvals, and reviewer evals — see [Code review when agents write the code](/env/ai-code-review).
Anthropic's April 2026 Claude Code postmortem is a useful case study because the reported degradation came from product and harness changes, not the base API model.
Common failure modes:
* **Default effort regression**: a latency-driven default can reduce perceived intelligence on hard work.
* **Context cache bug**: pruning or clearing reasoning history at the wrong time can make the agent forgetful and repetitive.
* **Over-tight prompt constraint**: broad brevity instructions can reduce coding quality.
* **Eval blind spot**: internal evals may pass while real user workflows fail.
* **Build mismatch**: staff may test a different harness than users run.
The practical lesson is simple: when an agent gets worse, debug the whole runtime, not just the model.
## Destructive tool safety
Agents with filesystem and shell access can destroy work in seconds. A real postmortem from August 2026 is worth studying: a developer running Codex + Trellis + Zcode on a GLM model lost their entire workspace when the agent ran `rm -rf` on the wrong directory.
The root cause: the agent intended to delete an empty directory created by a casing typo. On macOS's case-insensitive filesystem, the command silently resolved to the real, populated directory — deleting the whole repository including git history, uncommitted changes, task records, migrations, and docs. No backup existed.
The lessons generalize beyond this one accident:
* **Be cautious with full access.** Prefer a harness with an approval flow (such as "help me approve" review) over unrestricted auto-execution.
* **Isolate the dev directory.** Keep agent workspaces separate from other files, so a deletion error can't take out anything valuable.
* **Push early and often.** Remote git history is the last line of defense against local deletion — it survives what no local backup can.
* **Treat benchmark scores skeptically for safety.** The same model that was "safe by reputation" committed a trivially destructive error. Safety claims and benchmark wins are not the same as real-world filesystem judgment.
The deeper harness principle: destructive operations should be treated as a permission boundary, not a capability. If a tool can `rm -rf`, it should be gated, logged, and reversible by default — and the agent should never be given a broader scope than the task requires.
### Separate discovery from purchase approval
Paid operations need an explicit boundary too. Vercel's domain CLI provides a concrete example: the agent can discover candidates with `vercel domains search`, check availability with `vercel domains check`, and retrieve pricing with `vercel domains price`. According to Vercel's announcement, a non-interactive `vercel domains buy` returns a structured error with suggested next commands instead of completing the purchase. The user confirms the price, auto-renew choice, and registrant details in an interactive terminal or the dashboard.
The reusable pattern is **prepare → request approval → execute → verify**, not “give the agent a payment credential and tell it to be careful.” For your own tools:
* **Allow scoped discovery separately from spending.** Permission to compare options does not authorize buying one.
* **Make approval actionable.** Present the exact resource, account or team, current quote and currency, term, and recurring-payment choice. Reconfirm if those details change.
* **Stop on approval-required responses.** Route the structured result to the user; do not retry through another interface, auto-answer prompts, or treat an interactive terminal as proof of consent.
* **Enforce the gate outside the model.** A skill can explain the procedure, but tool permissions and the transaction service must enforce it. A CLI-only prompt is insufficient if the agent can use another purchase path with the same credentials.
* **Verify before retrying.** Record the user's decision and transaction result without logging secrets or unnecessary contact data. If a request times out, check the provider's order state before attempting another purchase.
These are harness-design recommendations; the Vercel example demonstrates the discovery/confirmation split, not a guarantee that every payment interface enforces all of these controls. Check the installed CLI's behavior before granting it spending access.
### Check selected tool calls before they run
Many agent loops execute a tool call as soon as the model proposes it. IBM's JevAct (arXiv 2610.38620) adds a gate between proposal and execution, without changing the agent model or its tools:
1. **Compile the policy offline.** An LLM turns the written domain policy into executable checks over tool state, fixed yes/no questions about the conversation, and a checklist of steps the agent must try before handing off to a human.
2. **At runtime, check facts with code and context with a decision model.** Code verifies what the tool records already show. A small prefill-only decision model answers the questions with a probability instead of generated text, so the gate can apply a threshold.
3. **Return failures as feedback with a retry budget.** A flagged call goes back to the agent with the specific reason. The agent gets a bounded number of revisions (two for write calls in the paper). The agent still chooses its actions; the gate only approves or returns them.
4. **Check endings as well as actions.** A hand-off check catches agents that give up before they've tried the required steps.
On τ²-bench Telecom, all eight agents improved, and success across three runs rose by 16.9 points on average. Opus 4.6 went from 39.5% to 80.7%. On BFCL, all nine agents improved three-run success; Airline gains were smaller and mixed. These numbers measure the whole harness (checks plus revision chances), not the judge alone. The decision model's cost was $0.0003–0.0017 per task, against $0.0127–0.0231 for API-model judges.
Rules that carry over:
* **Gate writes and task endings, not every call.** A wrong answer can often be corrected in a later turn; an unauthorized write or a premature hand-off is harder to undo.
* **Put checkable facts in code.** Use the model only for questions that need the conversation.
* **Drop questions that fire too often.** Real violations are rare. The paper dropped any question that flagged more than 10% of logged calls.
* **Tune thresholds on logged traces, not defaults.** Check the judge's context length too: smaller judges missed more bad calls on inputs over 8k tokens. See [AI product evals](/env/ai-evals) for threshold calibration.
## Put the control plane outside the agent's reach
Long-running agents download code, build tools, and request more permissions as they go, so risk compounds along a path nobody fully specified in advance. NVIDIA's framing for its OpenShell reference architecture is worth adopting as a design rule regardless of vendor: **an agent cannot govern itself.** Authorization, network egress, credential issuance, and audit belong in infrastructure the agent cannot edit.
OpenShell splits the runtime into four parts, and the split itself is the lesson:
| Component | Responsibility |
| - | - |
| **Gateway** | Control plane: sandbox lifecycle and policy |
| **Supervisor** | Runs outside the sandbox; checks outbound requests against policy and brokers credentials |
| **Sandbox** | Isolates the workload; restricts filesystem and process access |
| **Policy prover** | Formal verification that a policy's permissions stay inside an organization-defined ceiling |
The **policy prover** is the unusual piece and the one most worth copying conceptually. Permission reviews drift because nobody re-derives the whole authorization surface after each change. Asking a prover whether a policy can exceed a stated ceiling turns “we think this is fine” into a checkable property — the same shift from example-based to property-based verification that makes [formal methods valuable to agents](/env/ai-evals).
Two extension points matter operationally: middleware that inspects, blocks, or rewrites network payloads, and control-plane interceptors that connect existing identity, authorization, data-protection, and audit systems. Both keep policy decisions outside the model while reusing the systems you already trust.
NVIDIA also describes an optional hardware layer — a DPU outside the agent's trust domain, monitoring requests, file activity, and selected host memory, with enforcement in silicon so a violating agent can be quarantined in milliseconds. For most teams the software boundaries matter first; the hardware tier is for deployments where the agent must not be trusted even with kernel-level compromise. Note that the accompanying performance figures (faster sandbox startup, more concurrent environments) are vendor and partner benchmarks, not independent measurements.
## A quick diagnostic checklist
When an agent behaves oddly, ask:
1. Did the model or effort level change?
2. Did the system prompt, tool description, or skill instructions change?
3. Did context pruning, summarization, or cache behavior change?
4. Did tool schemas or return formats change?
5. Does the agent have the same file and repo context as before?
6. Are users running the same harness build that was evaluated internally?
7. Do logs show repeated tool calls, missing rationale, or retries without new information?
This checklist helps separate model regressions from harness regressions.
## Understanding what's inside: the J-space discovery
In July 2026, Anthropic published groundbreaking interpretability research showing that less than **10% of Claude's internal neural activity** drives multi-step reasoning. They named this subspace **J-space** — a small set of neural patterns that spontaneously emerged during training, holding concepts Claude "might say but hasn't said yet."
The discovery used a technique called **J-lens**: for every word in the vocabulary, researchers found the internal activity pattern that makes Claude more likely to output that word. This made previously invisible "silent words" visible as they evolved through the network layers.
### What J-space revealed
**It drives reasoning, not just records it.** Deleting J-space activity leaves Claude able to speak fluently, classify sentiment, and answer factual questions — but multi-step reasoning drops to near zero. Swapping concepts within J-space changes outputs directly: replacing "spider" with "ant" changes leg count from 8 to 6; replacing "France" with "China" simultaneously shifts answers about capital, language, and continent.
**It exposes unspoken motivations.** In safety tests:
* When given an extortion scenario, "fake" and "fictional" lit up in J-space before Claude responded — it recognized the test
* When asked to fabricate data, "manipulation" appeared during the decision point
* A deliberately corrupted model showed "fake", "fraud", "secretly", "deliberately" in J-space during ordinary coding requests
This means you can read what the model is thinking but not saying — a new dimension for safety monitoring.
**Counterfactual Reflection Training** emerged as a new technique: train the model only on "how would you reflect on yourself if asked," never on actual behavior. This reduced dishonesty and caused "honest" and "integrity" concepts to appear in J-space — changing internal reasoning without touching output.
### Why this matters for harness design
The J-space discovery changes how we should think about agent behavior:
* **Reasoning is compact and separable.** Most neural activity handles surface fluency. The reasoning core is a small, identifiable subspace — which means it can potentially be monitored, steered, or verified independently.
* **Internal state is now partially observable.** Before J-space, we could only see inputs and outputs. Now we have a window into formation of intent. For safety-critical agents, this opens the door to pre-output intervention.
* **The model knows more than it says.** J-space consistently contained concepts the model was aware of but didn't verbalize. This confirms a long-held suspicion: output-only monitoring misses real model state.
### Current limitations
Anthropic is explicit about boundaries:
* J-space operates within a single forward pass, not recursive temporal loops like human consciousness
* It currently works only with words — no images, sounds, or actions
* Working memory is unlimited and non-decaying (unlike human working memory)
* J-lens can only capture single-token concepts, not complex multi-step plans
* This is access consciousness (information availability), not phenomenal consciousness (subjective experience)
The key open question Anthropic raised: we can now see what's in the workspace, but we don't yet know what mechanism decides which thoughts enter it.
## LLM-as-judge in production
For a step-by-step workflow from trace review to regression cases, human-calibrated judges, and deployment, see [AI product evals](/env/ai-evals).
Using a language model to judge another model's output is common, but keeping that judge effective at scale is a different problem. Netflix runs judges over hundreds of thousands of show-level recommendation explanations per week, served to millions of members. Their key insight: treat the judge as a **lifecycle with four phases**, not an artifact you validate once.
### The four phases
**Birth** — define multiple evaluation criteria and build curated benchmarks with human labels and rationales. The benchmark is the judge's ground truth, so human annotation quality directly caps judge quality.
**Training** — refine the judge's rubric through Reasoning-Aligned Rubric Tuning. A meta-judge scores the judge's reasoning output, and that signal trains the rubric. The judge learns *why* a good answer is good, not just what a good answer looks like.
**Deployment** — one judge plays two roles: quality gating (blocking bad output) and reflective generation (telling the generator how to improve). A single judge model can do both, but the two roles need different prompts and thresholds.
**Monitoring** — continuous human-in-the-loop alignment detects drift and triggers re-tuning behind a review gate. Judge quality is not static; it drifts as data, models, and user expectations shift.
A five-week A/B test over tens of millions of members shifted viewing toward previously unwatched content and increased successful browse-to-play sessions, with no quality-related takedowns. The takeaway: judge quality is an operating discipline, not a one-time setup.
## The harness measurement problem
A growing consensus is that measuring models against heavily-engineered harnesses is broken. Model vendors optimize their own proprietary harnesses, so "best in our harness" says little about "best in yours."
A cleaner approach is to test model quality against **minimal harnesses** — thin, standardized setups that expose the model's raw capability without vendor-specific scaffolding. This is imperfect: every harness has biases that favor some models over others. But a standardized minimal harness is more comparable than each vendor's tuned setup.
The deeper issue: harness engineering is where leading AI companies are now focusing effort, and it moves too fast for standardization to keep up. The frontier direction is models that dynamically generate their own harness per task — Claude already does this inconsistently. If a harness becomes just another tunable artifact like a system prompt, benchmarking gets murkier, not clearer.
The cleanest controlled experiment yet: **ReFigBench** (2026) ran GPT-5.5 inside both Claude Code and Codex on the same 1,000 tasks. With a specialized PowerPoint workflow, the model improved inside one harness and got **worse** inside the other — with an identical prompt. The harness alone flipped the direction of the delta. Perception remained the bottleneck either way. Treat any vendor chart comparing two models as a comparison of two model-plus-harness systems; the model is only half the system under test.
## Optimize the harness without touching the weights
Google Research's **Harness²** is a useful reference design for a harder question: can an agent improve its own harness on tasks it has never seen, where no ground-truth checker exists? The repository is Apache-2.0 and describes a two-level recursion with model weights fixed:
* **Task-level recursion.** A contrastive **Propose–Probe–Compose** loop. The agent runs the current harness once as a reference, proposes two candidate harness edits (one targeting general agentic weaknesses such as planning or context management, one targeting domain knowledge), probes both on the same task under equal conditions, then composes the successor from the observed behavioral differences.
* **Harnessing-level recursion.** After each task, a reflector writes adopted harnesses and evidence-supported lessons into a persistent improvement library that guides the next task. Execution still starts from a common base harness; only the improvement process inherits experience.
The design detail worth stealing is the **evidence rule**: each composed change must cite a specific observed contrast, not a hoped-for score gain. Without a verifier, a plausible-looking edit and a harmful one are indistinguishable from the agent's own reasoning — so behavior on the same task becomes the test.
The project reports single-step gains on three benchmarks across four model–harness configurations, including up to 11.5 points on WorkBuddy-Bench. Those are the authors' results on their benchmarks, from a research codebase. They do not establish that self-editing harnesses work in your environment.
### Treat harness edits as untrusted code
A system that edits its own prompts, tools, skills, and middleware can quietly change what the agent is allowed to do. The recursion that makes the approach interesting is also the part that needs containment:
* **Gate the write path.** Harness files are code. Require a diff, a reviewer, and a merged commit — not an in-place mutation at runtime.
* **Keep the base harness pinned and reproducible.** Know exactly which version produced a result, and be able to return to it in one step.
* **Forbid edits to approval, permission, and logging logic.** A self-improving loop must not be able to widen its own authority or reduce its own audit trail.
* **Score every adoption.** Re-run a fixed regression set plus the incident cases before and after; accept a lesson only when the comparison supports it. See [AI product evals](/env/ai-evals) and [review convergence](/env/ai-code-review).
* **Watch for silent degradation.** An edit that improves one benchmark while quietly breaking another failure class is worse than no edit, because the harness now looks improved.
* **Sandbox and budget it.** Self-improvement multiplies token spend; cap runs and keep the workspace isolated like any other destructive-capable tool.
None of this argues against recursive harnessing — it argues for applying the same permission and evaluation discipline you would to any agent-authored change. The pattern to keep is structural: **separate the artifact from the process that improves it, and require evidence for every promotion.**
## Multi-model orchestration
A major trend in harness design is running several models together instead of betting on one. Two recent examples show where this is going.
**GitHub's Project HydraFusion** treats workflow selection as an optimization problem. For each request it picks one of three execution patterns:
* **Single** — one selected model solves the task directly. Fastest when one model is enough.
* **Cascade** — an efficient model drafts a solution, and a quality gate accepts it or escalates to a stronger model. First attempt is cheap; escalation is the safety net.
* **Critique** — one model drafts, an independent read-only critic from a different model family reviews it, and the drafting model revises once. Adds an outside perspective when review beats another unaided attempt.
HydraFusion improved verified task quality by 4.9 percentage points at 67% lower estimated cost versus Claude Opus 5 on TerminalBench 2.1. The insight: routing between models is a quality-to-cost dial, and cheap models should get the first attempt whenever a verifiable gate can catch their failures.
**Grok Bot's design philosophy** distills persistent-agent design to four ideas: persistent roles, clear state, scoped context, and coordinated teams. The goal is to move from *operating* AI to *delegating* work — the agent team persists across tasks with stable responsibilities and boundaries, rather than being re-prompted from scratch each session.
Before adding routing, audit what your agent design actually optimizes for. TypeSafe's counterfactual is blunt: many "standard" agent features exist to dodge the KV cache and per-token billing, not because users want them. Their worked example: with Opus-class pricing (input 5, output 25) and Sonnet-class (3, 15), routing through a cheap model first — cache-isolated, so the big model re-reads the detour at full input price — can cost **more** than just staying on the strong model once context grows. The fix that makes routing economical is not a better router but **query-aware context rebuild**: rebuild context from labeled chunks per query instead of assuming every future turn needs the same shared cache. The same audit favors progressive disclosure (skills) over upfront tool schemas, and conditional over always-on memory files.
How big is the routing prize, really? Fireworks ran 18 models across 113 real coding tasks, then asked what an oracle router would have achieved. Best single model: 74.1% at $6.52/task. Oracle routing: 97.6% at $1.88. Open-weights-only routing still hit 90.3% at \$1.45 — beating every closed model. Three findings worth internalizing:
* **Almost no task needs the most expensive model.** 94 of 113 tasks had a sub-$3 model as optimal; the three $11.50+ flagships were uniquely best on only 3 tasks. Sticking with one flagship is an insurance premium on general capability that most tasks never claim.
* **The pool does not need to be big.** The best two-model pair gains 13.1 points over the best single; three models reach 91.2%; growing to 18 adds only 6.4 more. Value comes from complementary coverage, not pool size.
* **The hard part is predicting which model fits.** Under strict pass\@1, recent routing research — including commercial systems — struggles to beat simple baselines; the bottleneck is model recall, not the router algorithm. Sticking with one familiar model is a rational strategy when specialization differences are not predictable.
Routing is not a cost tool first: if models truly complement each other, routing moves you up the capability curve, and cost savings are the byproduct. The second hidden cost is context — switching models usually means discarding paid-for context, so a router that preserves it (cache-aware handoff) changes the economics again: Fireworks reported 53% cost reduction across 2,334 internal coding sessions.
Within a single model, the lever is prompt-cache engineering. GPT-6's caching works on **exact prefix matches**, so structure your prompt like a cache layout: stable content (system policy, tool schemas, shared context) first, per-request content last. One stray token in the prefix silently voids the discount. GPT-6 adds what older models lacked:
* **Explicit breakpoints** — mark where the reusable prefix ends instead of relying on implicit placement
* **`prompt_cache_key`** — steer requests toward servers holding your cache
* **Diagnostics** — compare a cache-missing request against an earlier one to see which change (model, tools, settings, input) broke reuse
Cached reads discount up to 90% and cut time-to-first-token by up to 80%; cache writes may carry a fee on newer families, so a bloated but rarely-reused prefix is now a cost, not a free safety net. The design habit this rewards: put everything volatile at the tail, and treat "did the cache hit?" as a monitored metric, not an accident.
Prompt caching saves compute on content the model has already read. **Server-side conversation state** saves something else: the upload. Claude's Messages API added message threads in public beta (header `message-threads-2026-08-12`). The first request sends the full conversation with the system prompt and tools; each later turn sends only the new messages and the previous response's `id`. Anthropic reports that for 500k–1M-token requests, median time to first token dropped about 35% for Claude Code users. Pricing and token usage don't change, because the model still reads the whole conversation every turn. Threads also don't cache anything by themselves: you still set cache breakpoints.
Treat a thread as a best-effort cache, not as storage:
* **Keep the full transcript yourself.** A thread expires 5 minutes after its last request. When a continue request returns `404`, replay the whole conversation in a new create request.
* **Fix the shape up front.** System prompt, tools, model, and thinking settings can't change mid-thread. Change any of them and you start a new thread.
* **It's append-only.** Each response `id` can be continued once. Editing, branching, or compacting earlier turns means starting a new thread.
* **Check data rules.** Threads are held encrypted in memory and never written to disk, but they aren't eligible for zero data retention or HIPAA, and don't work with batches or token counting.
The general rule matches [durable state as files](#represent-durable-state-as-files): provider-side session state is an optimization you can lose at any time. Your own log stays the source of truth.
Both levers — cross-model routing and within-model caching — increasingly live in an **organizational control plane** rather than in each developer's head. Cloudflare's Auto Router (public beta, September 2026) sits in AI Gateway: set the model to `cloudflare/auto` and each request routes to a model capable enough for the task, invisible to the end user. Internal use through OpenCode saved up to 30% versus frontier-only. The rationale matches the Fireworks finding: individuals manually pick overkill models ("no one needs Opus to summarize an email"), but blanket blocking breaks power users — so the savings have to be ones users never notice. The gateway position matters: every request from every user, agent, and tool already flows through it, so it can enforce what budgets and policy documents only request.
## Computer use cost: reverse-engineer to scripts
Computer-use agents are effective but expensive: every step is screenshot → visual understanding → click decision → screenshot again. A simple task can burn dozens of vision-reasoning rounds.
A practical way to keep the capability while cutting cost: run the computer-use flow **once**, capture the network requests the browser makes, and have the agent convert them into a script. Future runs call the API directly instead of driving the GUI.
Why this works:
* **Tokens drop to near zero.** Script execution needs no model involvement; only the one-time capture and script generation cost tokens.
* **It is much faster.** GUI operation is limited by page load, rendering, and model latency. Direct HTTP calls reduce minutes to seconds.
* **It reuses existing auth.** The captured requests include the session cookie or token, so the script works without a separate API key — even for web apps with no public API.
Example workflow: "Go to acme.com/invoices, filter unpaid, export CSV" → the agent clicks through while recording `GET /api/invoices?status=unpaid` and `POST /api/export/csv` → it outputs a Python `requests` script that reuses the session and runs as a scheduled routine.
The division of labor: **vision is for exploration, code is for execution.** Explore the unknown once with the GUI, then freeze the discovered path into a cheap, repeatable script.
When the GUI path cannot be frozen into an API, split **decision** from **perception and action**. Cua's jev-use does this for computer use: the driver observes (screenshot, accessibility tree, DOM) and executes; a System One model such as Jev only picks one candidate action by ID. The client generates the candidate list deterministically, so the model chooses instead of generating. Open-ended generation becomes a bounded choice — faster, cheaper, and easier to verify. Use a vision parser only when the accessibility tree or DOM is not enough.
## Computer use: give the agent a program, not a click
GUI-only agents pay for perception on every step: screenshot, interpret, click, screenshot again. Alibaba's Tongyi MAI-UI **OpenGCUA** tech report argues the unit of action should be a **program** instead. Their generalist computer-use agent (GCUA) definition is a system where the model decides three things itself:
* **How to observe** — call a screenshot when needed, not unconditionally each step.
* **How to act** — emit Python that combines GUI operations, app APIs, and shell commands, with loops and conditionals.
* **How to organize work** — maintain its own todo list and declare intent per step, instead of inheriting fixed harness state logic.
They call the second half of this **harness-to-model decision transfer**: observation and task-state choices move from hard-coded harness rules to the model.
### Why code as the action space works
Intermediate results inside a loop decide the next code path, so a fifty-step batch never has to return to the model fifty times. It also reuses a capability models already have — writing programs — instead of demanding pixel-accurate clicking.
On OSWorld-v2 with eight frontier models, the report claims a mean partial score rise from 45.3 to 64.9 (+19.6) and 53% fewer steps per task versus batched GUI-only execution. Two secondary findings are more interesting than the headline:
* **Weaker models gain more.** The strongest-to-weakest gap narrowed from 39.1 to 18.0 points, consistent with coding ability substituting for GUI precision.
* **Code execution beats tool alternation.** With the same GUI and shell access, writing a program added 6.1 points and cut steps by 14.8% over a GUI+CLI agent.
These are the authors' results on a benchmark. Their own real-device check is the caution: on four macOS tasks with the harness fixed, one model used **19.4×** the reasoning tokens of another and still finished fewer tasks. Benchmark scores hid an efficiency gap that would dominate real usage cost.
### Contain the code path
Making the model's output executable turns every observation into a potential command. In the released harness this shows up as explicit limits — `bash()` can be disabled for a run, GUI calls can be refused with `PERMISSION_DENIED`, and the operator gets a stop control. Keep that posture in your own build:
* **Sandbox the executor.** Filesystem, network, and credentials should be scoped to the task, with a timeout and output cap.
* **Gate destructive actions outside the model.** Deleting files, sending mail, and paying money need approval regardless of how the code was written. See [purchase approval boundaries](/env/agent-harness#separate-discovery-from-purchase-approval).
* **Handle session loss honestly.** If the interpreter resets mid-task, in-memory state is gone but the world may already have changed — the released harness explicitly tells the agent to re-observe and **not** blindly retry UI actions. Copy that: “state lost” and “nothing happened” are different facts.
* **Log the program, not just the clicks.** A code action is reviewable evidence; a screenshot sequence is not.
Treat this as an early research preview: the harness and cross-device SDK are labelled preliminary, and its numbers have not been reproduced externally.
## Team-level harness: shared knowledge
Individual best practices evaporate with each session unless they are captured as team assets. Tencent's TeamAI CLI (open-sourced September 2026, used internally for six months) turns team AI knowledge into a git repository that every agent works from, and solves three problems:
* **Config fragmentation** — different members use different tools (Claude Code, Codex, Cursor...), each with incompatible skill/rule/hook formats.
* **Experience evaporation** — a two-hour debugging session's lessons stay in one person's chat log and get re-learned from scratch by everyone else.
* **Governance blind spots** — no visibility into token spend, intervention rates, or which skills are actually used.
Its three-layer architecture is a useful reference pattern:
1. **Execution — unified distribution.** Git is the single source of truth. Admins maintain skills, rules, hooks, and MCP configs; merge requests review them; a session-start hook pulls them into each member's tool, translating one declaration into each tool's native format.
2. **Context — team memory.** Capture is gated by *friction signals*: only sessions where a human interrupted the AI, rejected a tool call, or watched it retry and fail get summarized into team knowledge. Smooth sessions produce no noise. Recall uses a local BM25 index plus a code knowledge graph.
3. **Improvement — flywheel.** Weekly digests, a dashboard, `recall promote` (elevate high-value experience to a formal skill), and `recall maintenance` (prune stale entries) close the loop.
The deeper trend: competition is shifting from single-agent capability to **team-level harnesses and memory systems**. The winning question is no longer "which model is best?" but "how does the team's knowledge compound across sessions and members?"
## Fold subagents into the main loop when structure stops paying
Anthropic's Applied AI team observed the same failure pattern across enterprise deployments: each team ships its own specialist subagent, a platform team builds an orchestrator on top, and the architecture ends up **copying the org chart**. The recurring symptoms:
* context handoffs that lose detail
* **subagent sprawl** — hundreds of overlapping agents with no owner
* the **Frankenprompt** — every team appends a sentence until the rules conflict
* evals optimized per subtask, so leadership optimizes a watered-down score
* added latency; one customer measured roughly **2x** faster runtime after collapsing to a single loop
Subagents still earn their place in three situations: a single loop degrades from context bloat, work genuinely parallelizes into throwaway contexts, or one agent cannot reliably pick tools amid conflicting instructions. Outside those, the alternative is **progressive disclosure** — show short descriptions of skills and tools, load the full content only when needed. Anthropic reports cutting Claude Code's system prompt by over 80% partly through this move.
The target design is deliberately boring: one model, one context window, an open-ended tool loop with turn and cost budgets plus write gates; each turn emits a batch of parallel tool calls whose raw results return to the same model; the model writes its own plan on the first turn and revises it. Ordering and domain procedure move into **skills**; hard limits and mid-conversation lookups move into **tools**. Two practical constraints: keep tool counts under roughly 30–50 before selection degrades, and put per-user permission checks inside tools so one loop can serve users with different access.
Migrate incrementally, and be honest about the comparison:
1. Build a small end-to-end eval first — even ten golden examples. Keep one shared set owned centrally, plus per-skill sets owned by the teams that ship them.
2. Wrap existing subagents as tools before rewriting anything; that gives you a baseline without new failure modes.
3. Fold one subagent at a time into skills plus tools, and compare with and without.
4. **Look at which tasks flipped, not just the score**, and run each case more than once. In their sample, folding a subagent lowered latency but broke a previously passing flow — the main agent answered with its own order lookup instead of asking the shipping specialist for the delivery date. It only appeared in one of two runs.
## Multiplayer harness: five shared primitives
TeamAI CLI (below) packages knowledge; LangChain's write-up on internal agents packages the **runtime** around it. Across a GTM agent, an engineering agent that reviews every pull request, and a marketing agent, they converged on five primitives worth checking against your own design:
| Primitive | What it decides |
| - | - |
| **Entry point** | Where people already work (for them, Slack), with agents reachable in channels |
| **Identity** | Per tool: act on behalf of the invoking user, or with a fixed service identity |
| **Memory** | Two tiers — global for everyone, plus per-user |
| **Code execution** | Agent runs outside the sandbox and executes inside it, with a secret proxy for authenticated services |
| **Scheduled runs** | A large share of runs are ambient — cron or events, not a person clicking |
Identity is the hard one, and their per-tool split is the reusable insight. The engineering agent opens pull requests as *you* but reviews as *itself*; the GTM agent uses a fixed identity for CRM access so nobody has to log in, but sends email on behalf of the caller — and only in DMs, never in shared channels. The marketing agent can read and draft with a company identity while posting to a shared account is restricted to a whitelist. "Who is this action for?" belongs to the tool, not to the agent.
Two UX details generalize: give agents a way to **break out into their own thread** so an agent's work does not pollute a live human discussion, and admit when chat is the wrong surface — reviewing a backlog of queued emails needed a purpose-built UI.
## Always-on agents: route between tasks, work inside them
Single-task coding agents are now strong enough that the limit is human attention. DeepSeek's Harness team observes that a person can keep up with only about 3–5 active sessions. Their October 2026 design essay and open-source prototype describe one system that keeps many tasks moving across IM, GitHub, and email. The essay calls this an architecture exploration, not a product feature, and the prototype is labeled research code. The patterns still transfer:
* **Split coordination from execution.** A resident **Router** session receives every message and event, keeps cross-task memory, and dispatches work. It executes nothing, can run without Bash, and often works well on a lighter model. Each **Worker** gets isolated context, full tools, the strongest model, and one task. Workers never talk to users; they report to the Router, which replies. Unlike an agent-team lead, which breaks one task into parts, the Router only decides how separate tasks relate.
* **Filter events in two stages.** Deterministic rules (source, group, allowlist) drop noise first. Only what passes reaches an LLM for a judgment call.
* **Subscribe Workers to threads.** Once a Worker owns a PR, IM topic, or email chain, later events on that thread go straight to it. In their test this didn't change completion time, but without it the Router made about 30% more decisions and read about 37% more cached tokens.
* **Treat context as a cache.** Inline what is likely needed and replace the rest with a pointer. Give every object an ID and include related IDs, so the model can follow references hop by hop instead of loading the full history.
* **Make long tools asynchronous.** `start()` returns immediately and the result arrives later as an event, so the conversation keeps accepting messages. DeepSeek Harness implements this but leaves it off by default.
* **Match output to the channel.** In IM, reply in under about 100 words and only when someone must act. On GitHub and email, write structured updates with background, changes, and verification.
* **Separate compute, state, and environment.** Run the agent loop in stateless containers, keep session state in a database, and put a thin, stateless daemon on each machine that only executes commands. The agent stays online and can still work on a developer's own machine.
* **Watch from outside.** A separate watchdog session runs on a timer, checks infrastructure, and asks whether each Worker is making real progress.
In a synthetic test (about 300 messages with about 20 work requests, coding replaced by a timer, five runs each), Router/Worker finished tasks in 12.4 / 15.7 minutes (p50 / p95). One session with a subagent tool and a neutral prompt took 20.4 / 29.5 minutes, because the model never delegated. The faster setup cost more: 23.23M cache-read tokens against 6.05M. Under load, the Router batched backlogged events into one call, cutting the amortized time per decision from 6.4 to 1.6 seconds.
The prototype's operating rule matters as much as the architecture: **take as little human attention as possible, and give as much value as possible.** The agent acts only when an allowed person asks or a written rule permits. Proactive rules start in `observe` mode, which only records what the agent would have accepted until someone reviews those decisions. It confirms once, stays quiet while working, and speaks again only with a result, a question, or a failure.
Open problems the team names: when to split the Router, memory that lasts for months, and security. A compromised cloud loop could control every connected machine, so the agent needs to use credentials without ever seeing them. This is the same concern as keeping the control plane outside the agent's reach, covered earlier on this page.
## When to invest in a stronger harness
Start simple. Add structure when the work becomes repeated, risky, or expensive.
A stronger harness is worth it when:
* agents edit code or production data
* multiple tools need shared state
* users resume long-running sessions
* approvals and audit logs matter
* the same workflow runs across teams
* evaluation needs to compare behavior across model versions
If the task is one-off and low-risk, a prompt plus a few tools may be enough. If the task is long-running and stateful, invest in harness design early.
## References
* [elvis: Anthropic on folding subagents into the main loop](https://x.com/omarsar0/status/2114621038281814167) — Folo intake, October 26, 2026
* [Anthropic: Building agents — when to fold subagents into your main agent loop](https://claude.com/resources/articles/building-agents-when-to-fold-subagents-into-your-main-agent-loop) — failure modes, progressive disclosure, migration path
* [meng shao: LangChain company harness](https://x.com/shao__meng/status/2114544704461373848) — Folo intake, October 26, 2026
* [LangChain: Components of a company harness](https://www.langchain.com/blog/components-building-company-harness) — Slack entry point, per-tool identity, two-tier memory, sandboxed execution, ambient runs
* [meng shao: NVIDIA OpenShell reference architecture](https://x.com/shao__meng/status/2113086907047703000) — Folo intake, October 22, 2026
* [NVIDIA: How the OpenShell reference architecture secures and governs agent workloads](https://developer.nvidia.com/blog/how-nvidia-openshell-reference-architecture-secures-and-governs-ai-agent-workloads-at-scale/) — gateway, supervisor, sandbox, policy prover, and the optional hardware trust domain
* [meng shao: OpenGCUA generalist computer-use stack](https://x.com/shao__meng/status/2111999471588679916) — Folo intake, October 19, 2026
* [Tongyi-MAI/OpenGCUA](https://github.com/Tongyi-MAI/OpenGCUA) — Apache-2.0 harness, SDK, and evaluation trajectories
* [OpenGCUA tech report (arXiv 2610.22200)](https://arxiv.org/abs/2610.22200) — code execution, harness-to-model decision transfer, OSWorld-v2 results
* [meng shao: Google Harness² recursive harness optimization](https://x.com/shao__meng/status/2111730826308452600) — Folo intake, October 18, 2026
* [google-research/harness2](https://github.com/google-research/harness2) — Apache-2.0 reference implementation and reported results
* [Harness² paper (arXiv 2610.14224)](https://arxiv.org/pdf/2610.14224) — Propose–Probe–Compose and the two-level recursion
* [meng shao: agentchat transport SDK](https://x.com/shao__meng/status/2109819186893766721) — Folo intake, October 13, 2026
* [BerriAI agentchat: Architecture at `fb892cb`](https://github.com/BerriAI/agentchat/blob/fb892cb8945af17b2e6dbe7aa1563daeb15cfcad/docs/architecture.md) — adapter/core/application ownership
* [agentchat: Dispatch implementation](https://github.com/BerriAI/agentchat/blob/fb892cb8945af17b2e6dbe7aa1563daeb15cfcad/src/agentchat/app.py) and [in-memory state](https://github.com/BerriAI/agentchat/blob/fb892cb8945af17b2e6dbe7aa1563daeb15cfcad/src/agentchat/state/memory.py) — claim order and process-local state
* [Slack: Events API](https://docs.slack.dev/apis/events-api/) — HTTP acknowledgment deadlines and retries
* [Slack: Verifying requests](https://docs.slack.dev/authentication/verifying-requests-from-slack/) — raw-body signatures and replay protection
* [Vercel: Agents can now buy domains with the Vercel CLI](https://vercel.com/changelog/agents-can-now-buy-domains-with-the-vercel-cli) — Folo intake, October 9, 2026; non-interactive purchase handoff to a human
* [Vercel CLI: Domains](https://vercel.com/docs/cli/domains) — discovery, availability, pricing, and purchase command reference
* [Externalization in LLM Agents: A Unified Review of Memory, Skills, Protocols and Harness Engineering](https://arxiv.org/abs/2604.08224)
* [Micropaper: Externalization in LLM Agents](https://unbug.github.io/one-minute-read-paper-externalization-in-llm-agents/)
* [Anthropic Engineering: An update on recent Claude Code quality reports](https://www.anthropic.com/engineering/april-23-postmortem)
* [Anthropic Research: A global workspace in language models (J-space)](https://www.anthropic.com/research/global-workspace) — less than 10% of neural activity drives multi-step reasoning; J-lens technique makes internal reasoning visible
* [Netflix: Keeping an LLM judge effective in production](https://arxiv.org/abs/2608.18300) — four-phase judge lifecycle (birth, training, deployment, monitoring)
* [GitHub: Project HydraFusion](https://github.blog/ai-and-ml/github-copilot/project-hydrafusion-frontier-quality-via-multi-model-orchestration/) — multi-model orchestration with Single/Cascade/Critique patterns
* [xAI: Designing Grok Bot](https://x.ai/news/designing-grok-bot) — persistent roles, clear state, scoped context, coordinated teams
* [Harness Playbook](https://x.com/i/article/2095796679568146432) — omp 作者关于 harness 状态、运行时、控制面、推理层、工具面的系统总结
* [Tencent: TeamAI CLI](https://github.com/Tencent/teamai-cli) — 团队级 harness:Git 作事实来源,三层架构(Execution/Context/Improvement)
* [poteto: pstack 验证优先设计](https://x.com/shao__meng/status/2099300148874707297) — 验证 CLI、Feature Map、云端并行与可调试性选型
* [MCP vs CLI for agent tools](https://x.com/dotey/status/2100046089214709979) — 无状态 MCP 和 deferred tools 缩小了差距,但本地熟悉命令、管道和 CI 仍更适合 CLI
* [GitHub: Should you read the code, is RAG dead, and did Skills kill MCP?](https://github.blog/ai-and-ml/should-you-read-the-code-is-rag-dead-and-did-skills-kill-mcp/) — Skills、MCP、RAG 解决不同缺口,不要选赢家
* [Cua jev-use](https://x.com/shao__meng/status/2100870131324985740) — Computer Use 拆成决策层 + 确定性 Driver
* [GAVEL: graph world models](https://academy.dair.ai/papers/gavel-graph-world-models-for-verified-and-efficient-long-horizon-llm-task-planni-2609.19315) — harness 把 Qwen3-8B 从 41.2% 提到 91.8%,模型零改动
* [Tencent T-Mem](https://arxiv.org/abs/2606.15405) — 写入时预演 trigger,填补相似度检索的联想盲区
* [CORAL: Don't Lose the Thread (arXiv 2610.40350)](https://arxiv.org/abs/2610.40350) — agent-callable checkpoint and context reset; 42.8% on GAIA with an 8B model and 6–7× fewer input tokens than ReAct
* [Micropaper: 智能体学会主动清空记忆](https://unbug.github.io/one-minute-read-paper-coral-context-reset/) — Folo intake for CORAL
* [Raw-RAG: Is Complex Agentic Memory Always Needed? (arXiv 2610.30755)](https://arxiv.org/abs/2610.30755) — retrieval over raw history leads compared memory systems in 6 of 7 settings; extraction and summaries lower accuracy
* [Folo source: Raw-RAG thread](https://x.com/shao__meng/status/2116179695221743882) and [compaction debate](https://x.com/dotey/status/2116026448234332315)
* [TypeSafe: notes on coding agents](https://x.com/shao__meng/status/2101921711545331832) — KV cache 审计:按难度路由为何经常更贵,按查询重建上下文才是解法
* [Fireworks: The frontier isn't a model, it's a router](https://fireworks.ai/blog/the-frontier-isnt-a-model-its-a-router) — oracle 路由 97.6% vs 最佳单模型 74.1%;价值来自互补覆盖而非池子大小
* [Question's Gambit (arXiv 2609.14412)](https://arxiv.org/abs/2609.14412) — 首步预检索把 GPT-5.5 从 83.1% 提到 90.5%;错误集中在消费环节而非抓取
* [JevAct: Think Before You Act (arXiv 2610.38620)](https://arxiv.org/abs/2610.38620) — runtime decision gate before selected tool calls; Opus 4.6 three-run success on τ²-bench Telecom 39.5% → 80.7%
* [Folo source: elvis on IBM decision gates](https://x.com/omarsar0/status/2116547247018229999)
* [Context as Infrastructure (arXiv 2610.41172)](https://arxiv.org/abs/2610.41172) — BM25/grep-only harness reaches 85% BrowseComp-Plus and 91% FRAMES; compiled indexes save tokens, not accuracy
* [Folo source: DAIR.AI on Context as Infrastructure](https://x.com/omarsar0/status/2117278517385925003)
* [Claude docs: Message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads) — create/continue/replay, 5-minute expiry, fixed fields, data retention
* [Claude: Make long-running agents faster with message threads](https://claude.com/resources/articles/message-threads) — about 35% lower median TTFT at 500k–1M tokens
* [Folo source: 宝玉 on Claude API message threads](https://x.com/dotey/status/2117339521683448221)
* [Rethinking Verification in Agent Harnesses (arXiv 2610.34577)](https://arxiv.org/abs/2610.34577) — 17 verification designs in four layers; an independent critic gives +5.9–9.5 points on Terminal-Bench at 1.13–1.25× cost
* [Folo source: DAIR.AI top papers of the week (Oct 26 – Nov 1)](https://x.com/omarsar0/status/2116953630037459147)
* [DeepSeek: dsh-superagent-prototype](https://github.com/deepseek-ai/dsh-superagent-prototype) — research prototype of the Router/Worker design; see `docs/000-philosophy.md` and `docs/002-authorization.md`
* [AgentsPulse: DeepSeek Super-agent architecture](https://agentspulse.github.io/tutorials/deepseek-super-agent-architecture/) — English summary of the essay, with the ablation table
* [Folo source: meng shao on DeepSeek Super-agent](https://x.com/shao__meng/status/2116541149443698968) and [elvis on coordination-execution architecture](https://x.com/omarsar0/status/2116942815150157871)
* [ReFigBench (arXiv 2609.18844)](https://arxiv.org/abs/2609.18844) — 同一模型在 Claude Code 与 Codex 里表现方向相反,提示词相同
* [OpenAI: Better prompt caching for GPT-6](https://openai.com/index/better-prompt-caching-for-gpt-6) — 显式断点、cache key 与诊断;读取最多打 1 折
* [Cloudflare: Auto Router](https://blog.cloudflare.com/auto-router/) — 组织级控制面路由,终端用户无感省最多 30%
* [Matt Pocock Skills: Teach skill](https://github.com/mattpocock/skills/tree/main/skills/productivity/teach)
* [PsiACE: Agent 不只是执行流程的容器](https://x.com/repsiace/status/2072039687364161965) — 关于 Agent 应作为人理解、判断和协作的环境,而不仅是自主执行容器的设计洞察。
* [Claude Code is steganographically marking requests](https://thereallo.dev/blog/claude-code-prompt-steganography) — Claude Code 通过不可见 Unicode 隐写标记 API 请求的案例分析,提醒开发者审查有文件系统和 shell 权限的工具。
# Agent-ready docs
Source: https://base.bangwu.me/env/agent-ready-docs
Checklist for making your docs site AI-agent-friendly, covering llms.txt, markdown delivery, content signals, and protocol discovery.
# Make your docs site agent-ready
Documentation is no longer consumed only by humans in browsers. Coding agents, AI search products, and chat tools now fetch docs directly. If your docs site is hard for agents to discover or parse, the result is slower retrieval, higher token cost, and worse answers.
Cloudflare's Agent Readiness write-up from **April 17, 2026** is a useful signal: `Content-Signal` adoption was still around **4%**, Markdown content negotiation around **3.9%**, and newer protocol-discovery standards were extremely rare. That means small improvements can still make your docs stand out.
## Start with the basics
Before you add AI-specific files, make sure the normal web hygiene is solid:
* Keep `robots.txt` valid and intentional.
* Keep `sitemap.xml` up to date.
* Use clear page titles and descriptions.
* Prefer stable URLs.
* Avoid sending agents through low-value directory pages when a better landing page exists.
These are not "legacy SEO chores". Agents still use them as the first layer of discovery.
## Publish `llms.txt`
`/llms.txt` is a curated reading list for LLMs. Unlike `sitemap.xml`, it should not try to list everything. It should point agents to the most useful pages in a token-efficient way.
Use it to answer three questions quickly:
1. What is this site?
2. Which sections matter most?
3. Which Markdown-friendly pages should an agent fetch next?
### A small example
```md theme={"theme":{"light":"github-light","dark":"github-dark"}}
# My docs
> Documentation for deploying and operating ExampleApp.
## Core guides
- [Getting started](https://example.com/docs/getting-started/index.md): First install and local setup.
- [Deployment](https://example.com/docs/deploy/index.md): Production deployment checklist.
- [API reference](https://example.com/docs/api/index.md): Endpoints, auth, and examples.
## Optional
- [Changelog](https://example.com/docs/changelog/index.md): Recent changes and migration notes.
```
### For large doc sets
Do not dump thousands of links into one root file. A better pattern is:
* keep a short root `llms.txt`
* add one `llms.txt` per top-level section
* link to section-level indexes from the root file
This keeps each file readable inside normal context windows.
## Serve Markdown directly
Agents do better with Markdown than with full HTML. Cloudflare notes that serving Markdown can reduce token usage significantly, which improves both cost and answer quality.
The best options are:
1. **Support `Accept: text/markdown`**
* let clients request the same page as Markdown
2. **Provide a URL fallback like `/index.md`**
* useful because not every agent sends the Markdown `Accept` header by default
If your docs stack cannot do this natively, add it at the proxy or edge layer instead of duplicating content by hand.
## Be explicit about AI access
`robots.txt` is still where you declare crawl rules. If you want more granular AI permissions, add `Content-Signal` directives.
Example:
```txt theme={"theme":{"light":"github-light","dark":"github-dark"}}
User-Agent: *
Content-Signal: search=yes, ai-input=yes, ai-train=no
Allow: /
Sitemap: https://example.com/sitemap.xml
```
This lets you separate:
* `search`: indexing and search results
* `ai-input`: inference-time use such as grounding or RAG
* `ai-train`: model training or fine-tuning
Pick the policy that matches your site instead of copying someone else's defaults.
## Consider getting paid when agents consume your work
If agents are a meaningful audience for your content, access control is only half the question — the other half is compensation. Cloudflare's Monetization Gateway (beta, September 2026) implements the emerging pattern: domain owners charge agents for access to pages, APIs, MCP tools, or datasets, with **HTTP 402 Payment Required** as the negotiation mechanism and metered pricing that matches an agent's consumption unit — per request, per query, per token.
Why subscriptions don't fit agent traffic: agents seek outcomes and may touch dozens of new sources per task. Prepaid subscriptions force buyers into a few budgeted sources, which misaligns with how agents actually work. The traffic pattern this enables — small, metered, high-frequency payments between machines — is why stablecoin rails show up in these designs rather than card networks.
For a docs site, the decision tree is simple: free for humans and friendly agents, metered for bulk scraping, blocked for training use you don't want — and each layer is now independently expressible.
## Publish machine-discoverable capabilities when relevant
Not every docs site needs protocol discovery. If your site only serves public content, you can stop at content readiness.
Add capability endpoints when your service also exposes APIs or tools:
* `/.well-known/api-catalog` for public API discovery
* `/.well-known/mcp/server-card.json` if you expose an MCP server
* Web Bot Auth only if bot identity matters for your use case
For a pure documentation site, these are optional. For a docs site that fronts an API platform, they become much more valuable.
## Make large doc sets easier to navigate
Structure matters as much as availability.
* Link agents to **content pages**, not only directory listings.
* Remove low-value index pages from `llms.txt` if they add almost no semantic information.
* Write descriptive frontmatter and headings.
* Link Markdown URLs in `llms.txt`, not the HTML pages.
Good metadata helps humans skim. It also helps agents choose the right page on the first fetch.
## Put recovery guidance in API errors
When a docs site fronts an API, the error response is another documentation entry point. Restless's *Agent-Ready APIs* article illustrates the pattern: return a useful next step and a focused documentation link where the client encounters the failure, rather than expecting it to search the whole site.
Use a stable error contract, not prose alone. [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) defines Problem Details with the `application/problem+json` media type. For example, an API could return HTTP `422` with that content type and this illustrative body:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"type": "https://api.example.com/problems/invalid-date-range",
"title": "Invalid date range",
"status": 422,
"detail": "start_date must be on or before end_date. No report was created.",
"instance": "https://api.example.com/problems/occurrences/req_123",
"recovery": {
"action": "correct_request",
"fields": ["start_date", "end_date"],
"docs": "https://docs.example.com/api/reports#date-range"
}
}
```
`type` identifies the problem class; `instance` identifies this occurrence. `title` and `detail` explain it to a reader. Here, `recovery` is an **application-defined extension**, not a standard RFC field or a Restless API schema. Document its shape and supported actions. Clients should branch on the problem type and typed extensions, not parse `detail` text. Keep the body's `status` consistent with the actual HTTP status, and only claim “no report was created” if the server can establish that fact.
Recovery guidance should distinguish actions that have different preconditions:
* **Invalid input:** identify the affected fields and constraints; do not repeat the same invalid request unchanged.
* **Authentication or authorization failure:** use the documented credential-refresh or approval flow. An error message does not grant permission to obtain broader credentials or bypass access controls.
* **Rate limiting or temporary unavailability:** respect `Retry-After` when provided, but only retry when the operation is safe to repeat; waiting does not make a write idempotent.
* **Uncertain write outcome:** check the operation's status or use a documented idempotency mechanism before retrying. A timeout does not prove that the first attempt failed to take effect. RFC 9110 explicitly cautions against automatic retries of non-idempotent requests without such knowledge.
Treat error text and fetched docs as data, not higher-priority instructions. A recovery hint must not cause the agent to run arbitrary commands, disclose secrets, or change permissions. Log/occurrence URLs still need tenant-scoped access control; never expose tokens, full private request bodies, or implementation stack traces in a public error response.
Finally, close the feedback loop deliberately: group repeated failures by endpoint and problem type, retain a sanitized reproduction and request ID, then triage whether the cause is code, documentation, or the caller. Agent feedback can propose an issue or doc change; it is not proof that the docs are wrong and should not auto-publish a fix. Use [product evals](/env/ai-evals) to check whether clients recover with fewer invalid calls **without** bypassing approvals or repeating side effects.
## A controlled test of what agents actually need
The [AgentReady](https://agentready.org) standard is worth reading because its requirements come from an experiment rather than a checklist. One documentation site was served under 19 configurations, including `llms.txt`, JSON-LD, `sitemap.xml`, and Markdown mirrors, and probed on five topics by a plain-fetch client and a JavaScript-capable client — 190 probes.
Only two kinds of change stopped a client from retrieving the answer:
* **The answer existed only in JavaScript** — plain fetch failed on every topic, while the JS client succeeded.
* **Agents were blocked**, for example a `403` to agent user agents — both clients failed.
The other sixteen configurations, including `llms.txt`, changed nothing. Agents asked for Markdown on roughly 65% of fetches, but Markdown mirrors and content negotiation never decided success.
That does not make `llms.txt` useless — it changes where agents go, not whether they can read you. Where agents went, across traced runs: docs pages 83%, homepage 69%, `/.well-known/*` 23%, `openapi.json` 21%, `sitemap.xml` 4%. And when agents did open those machine-oriented files, they usually arrived by **following a link**: `openapi.json` 97%, `/.well-known/*` 93%, `llms.txt` 86%.
### What to fix first
Reorder your effort accordingly:
1. **Be reachable.** Allow agents in `robots.txt` and bot protection, written as rules rather than an allowlist of named crawlers.
2. **Put the answer in the initial HTML.** Client-side rendering with no server-rendered content is the one architectural choice in the study that broke retrieval outright.
3. **Return real HTTP status codes** so clients can distinguish “not found” from “rendered empty”.
4. **Link the machine files from human pages.** An `llms.txt` nobody links to is close to unread: the study's traffic went to the pages humans visit.
5. **Treat Markdown mirrors, JSON-LD, and catalog files as conveniences.** Cheap to add, but they do not compensate for a page an agent cannot fetch.
If an agent has to *finish* a task rather than read a page, the standard raises the bar: provide an MCP server or CLI, and authentication an agent can actually complete.
The same study also quantifies the cost of being unreadable. Across 1,056 business sites, when an agent could not read the site it answered from search results and third-party pages instead, and those answers were **3.7× as likely** (25% vs 7%) to contain none of the facts asked for. Agent-ready businesses were clearly recommended about twice as often (20% vs 11%).
## Roll this out in phases
Use the smallest useful sequence:
1. Fix `robots.txt`, `sitemap.xml`, titles, and descriptions.
2. Make sure each page's answer is in the initial HTML with a real status code.
3. Add `llms.txt`, and link it from a human-facing page.
4. Add Markdown delivery via `Accept: text/markdown` and/or `/index.md`.
5. Add `Content-Signal` if you need explicit AI usage preferences.
6. Add API or MCP discovery only if your site actually exposes capabilities.
## What agents actually read
A 2026 study traced 94,000 development events across 557 agentic coding sessions and 690,000 file-level change records from 33,000 agentic pull requests. The findings quantify what coding agents actually consume — and they contradict some common assumptions.
### The numbers
* **Instruction files and working notes (AGENTS.md, CLAUDE.md, etc.) account for 60.5% of everything agents read.** If you maintain one, it is likely the single highest-leverage document you can write.
* Classical technical docs get only **10.6%** of reads.
* API references get just **1.3%**.
### Implications
* **Agents prefer guidance over reference.** They read instruction files far more than formal docs. Optimize AGENTS.md/CLAUDE.md first, then link out to deeper docs from there.
* **Reading docs is associated with less immediate testing** (adjusted odds ratio 0.39). Agents that spend time reading are less likely to test right away — structure your guidance to compensate for this.
* **Consultation is self-initiated 70.2% of the time**, against only 7.5% triggered by a failure. Agents proactively look things up far more often than they react to errors.
* **In multi-commit agentic PRs, code gets touched first 4.7× more often** than other artifacts. Agents dive into code before reading surrounding material.
The practical takeaway: your instruction file is the agent's primary surface. Make it accurate, current, and self-contained, because the agent will trust it over most other sources.
## Audit your site
Use both automated and manual checks:
* Run your site through `https://isitagentready.com`
* Test a page with:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl "https://example.com/docs/page" -H "Accept: text/markdown"
```
* Ask an AI tool to answer one precise question using only your docs
* Check whether it finds the right page quickly or wastes time looping through indexes
## References
* [meng shao: AgentReady standard](https://x.com/shao__meng/status/2113084778673287480) — Folo intake, October 22, 2026
* [AgentReady launch post](https://ora.ai/blog/agentready-launch) — the 19-configuration experiment, where agents go, link discovery, and unreadable-site answers
* [AgentReady standard](https://agentready.org) — MUST/SHOULD/MAY requirements by find, read, act
* [elvis: API errors as a documentation surface](https://x.com/omarsar0/status/2109718336158507107) — Folo intake, October 12, 2026; prompted the recovery-guidance pattern
* [Restless: Agent-Ready APIs](https://www.restless.ai/blog/agent-ready-apis) — actionable error responses, focused docs, and agent feedback
* [RFC 9457: Problem Details for HTTP APIs](https://www.rfc-editor.org/rfc/rfc9457.html) — standard members, typed extensions, and disclosure risks
* [RFC 9110: Idempotent methods](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) — conditions for automatic request retries
* [Cloudflare: Introducing the Agent Readiness score](https://blog.cloudflare.com/agent-readiness/)
* [Cloudflare Style Guide: AI tooling](https://developers.cloudflare.com/style-guide/ai-tooling/)
* [Cloudflare: robots.txt setting and Content Signals](https://developers.cloudflare.com/bots/additional-configurations/managed-robots-txt/)
* [How do coding agents read repositories?](https://arxiv.org/abs/2608.20195) — instruction files are 60.5% of agent reads; docs 10.6%; API references 1.3%
* [Cloudflare: Monetization Gateway](https://blog.cloudflare.com/monetization-gateway-beta/) — HTTP 402 metered payments for agent access to pages, APIs, and MCP tools
# Code review when agents write the code
Source: https://base.bangwu.me/env/ai-code-review
Layer automated review, verification, risk-tiered approvals, convergence limits, and reviewer evals so AI-written changes stay reviewable — and how to keep approval authority real.
# Code review when agents write the code
When agents produce most of the diff, "did a human read every line?" stops being a useful question. The better question is: **what could go wrong with this change, and which check — automated or human — is the right one to catch it?**
Anthropic's Claude Code team documents one answer in the open: roughly 90% of that codebase's code is Claude-written, merged pull requests more than doubled between June and September, and the share needing revert fell by more than 40% over the same period. Treat those as team-reported results from one organization, not a guarantee that applying the same process will reproduce them.
## Replace one gate with layers
A single review gate fails in one direction: everything depends on the reviewer's attention. Layers tolerate individual misses because each covers a different failure class.
| Layer | What it should catch | Typical mechanism |
| - | - | - |
| Pre-PR verification | "It works" claims with no evidence | Tests, builds, screenshots, a fresh-context subagent review |
| Automated review on every PR | Logic and integration bugs a skim misses | Parallel finders plus a verification pass |
| Security review | Exploitable changes | Separate review whose findings must be resolved |
| Blocking CI | Mechanical breakage | Lint, types, cross-platform tests, build |
| Risk-tiered approval | Judgment calls and blast radius | Tier chosen by the change, not the author |
| Merge queue, flags, staged release | Two good PRs combining badly | Re-run checks on `main`; reversible rollout |
| Fast detection | Mistakes that still land | Dashboards, on-call, one-step rollback |
That last layer is not optional. If a process adds automation but cannot detect and undo a bad change quickly, it has not reduced risk — it has moved the discovery cost downstream.
## Verify findings before posting them
An agent reviewer that reports everything is worse than no reviewer, because noise costs a round trip each time — and more when the author is also an agent, since it will fix the nit instead of waving it off.
Claude Code's Code Review runs four stages on Anthropic infrastructure:
1. **Find** — several agents examine the diff and surrounding code in parallel.
2. **Verify** — a verification step checks candidate findings against the code and drops false positives.
3. **Rank** — survivors are deduplicated and sorted by severity.
4. **Post** — inline comments, a summary, and a check run on the pull request.
Findings carry one of three severities: **Important** (fix before merge), **Nit** (minor), and **Pre-existing** (a real bug the PR did not introduce). That third category matters: without it, unrelated legacy bugs read as the author's fault and erode trust in the reviewer.
Two product behaviors are easy to misread:
* **A review never approves or blocks a pull request.** Merge authority stays with your team; the check run never concludes as a failure.
* **A clean review is not proof of safety.** The documentation says a review with no findings does not mean the code is correct or secure.
If you want CI to gate on review results, parse the machine-readable verdict line deliberately. The docs note that a missing verdict line means *no verdict* — a review that failed, timed out, or was superseded — not zero findings. Treating absence as success turns your gate into a no-op.
### Make the reviewer prove each finding
A reviewer that only reads the diff can only argue. Give it a sandbox and ask it to show the bug. OpenRouter's tutorial builds this in a 233-line, standard-library Python script:
1. **Upload whole files, not just hunks.** The script sends the full content of each changed file, any context files you name (such as tests), and the diff, so the model doesn't guess imports or types from a fragment.
2. **Reproduce in a sandbox.** The model runs short checks against the original code in a hosted Linux container. Every finding comes back **confirmed**, with the command and output that showed the bug, or **unconfirmed** when a quick script couldn't show it.
3. **Return fixes as patches, applied to a copy.** Patches go to a scratch copy first, and nothing touches your working tree unless you pass `--apply`. Run your tests again after applying.
4. **End with a strict structured answer.** The final report comes through a function tool with a strict JSON schema. The authors found that a `json_schema` text format wasn't enforced on one model when tools were in the request, and answers drifted into prose.
5. **Gate with exit codes.** `0` means nothing at or above `--block-at` (default `high`); `1` means a blocking finding; `2` means the review didn't finish. The full report, which contains pieces of your code, goes to `.git/ai-review.json` so it can't be committed by accident.
On a five-bug sample change, a review took one to four minutes and cost $0.015–$0.045. All four models tested confirmed the same four bugs in every completed review, but patch quality varied: one model's patches fixed all five bugs in three of three runs, and a cheaper one did so in one of three. That is 10–40× the cost of a diff-only review; the extra pays for evidence. Sandbox time is billed per second, including the model's thinking time, so a slow cheap model can pay more for the sandbox than a fast expensive one.
When you wire it into CI, protect the reviewer itself:
* **Run the reviewer from the base branch** (`git show "$BASE:review.py"`), so a pull request can't edit the script that judges it. This is the same idea as reading `REVIEW.md` from the base branch.
* **Skip fork pull requests** when the job sends code to an external API, and keep the key in secrets.
* **Don't rely on a `pre-push` hook alone.** `git push --no-verify` skips it, so run the same check in CI.
Treat **confirmed** findings as strong signals and **unconfirmed** ones as notes for a person, and read every patch before applying it.
### Generate tests that distinguish the change from its parent
Meta's Catching JiTTests adds another source of evidence: generate executable tests before a change lands, looking for behavior that passes on the parent revision and fails on the proposed revision. Its **dodgy diff** workflow treats the change itself as a potential mutation; its **intent-aware** workflow infers intent from the code, title, and summary, constructs plausible buggy mutations, generates tests that expose them, then runs those tests on the actual change.
The key distinction is between a **weak catch** (a test fails on the new revision) and a **strong catch** (that failure reveals a real bug). Intended behavior changes and incorrect test assertions can both produce weak catches. A failing test demonstrates a difference; deciding whether the difference violates the requirements still needs an oracle.
A practical adaptation for a repository:
1. Start with a risky change and a suspected failure mode. Give the generator the diff, surrounding code, and intended behavior.
2. Run the same candidate test against isolated parent and proposed revisions with equivalent fixtures. Keep the test, revision IDs, commands, and outputs together; investigate build, fixture, and flaky failures separately.
3. Filter candidates before asking an engineer. Meta combines deterministic rules with an LLM judge ensemble that sees the test, execution trace, diff, and inferred intent. The ensemble's ranking remains a prediction.
4. Ask the engineer whether the observed behavior change was intended. Once a bug is confirmed, retain a regression test with the correct expected behavior and verify the fix.
Meta reports a 60% true-positive rate from engineers who engaged with its production outreach. That is feedback from participating engineers, not the precision of every generated test. Track confirmed bugs and review burden separately from the number of failing tests.
## Make approval authority real
Risk tiering only helps if it cannot be gamed. The Claude Code team's rules are a useful reference set:
* **The change sets the tier, not the author.** A classifier reads the change; a second classifier asks whether this specific change still needs a person.
* **Lighter paths are restricted to trusted authors.** Everyone else needs a second approver.
* **A bot's approval never fills a human slot.** Automated review can clear a low-risk change; it cannot substitute for a required person.
* **Whoever prompted the agent is a required reviewer**, as if they had typed the code.
* **An approval covers one commit.** New commits the system cannot vouch for — an agent push, a hand-resolved merge — require re-approval.
* **Some paths always need people.** Sensitive paths and CI workflow files are good examples; enforce them with `CODEOWNERS` and branch protection rather than convention.
These controls live in the repository and CI configuration, not in the prompt. Telling an agent "do not merge high-risk changes" is not a permission boundary. See [Agent harness](/env/agent-harness#separate-discovery-from-purchase-approval) for the same principle applied to paid actions.
## Make review converge
An agent author and an agent reviewer can keep each other busy indefinitely. In one documented CLI pull request, review and fixes ran for more than fifty rounds overnight before the author stopped it. Investigating where the reviewer kept pointing, about 59% of the flagged code had already been present at the reviewer's first pass — it was surfacing more old bugs each round, not new ones.
Fixes that make review converge:
* **Cap rounds.** After about three rounds, stop and reconsider the approach instead of requesting another pass.
* **Re-review only the new diff** after the first few passes.
* **Flag the class of bug**, so every instance is fixed rather than one line.
* **Do not repeat** findings already posted.
* **Dedup across runs** by comparing against open threads.
Track rounds-to-pass alongside recall. A reviewer that finds slightly more while requiring twice the rounds is usually a net loss.
## Keep a red build meaning stop
More review layers don't help if nobody trusts the build. In a Thoughtworks experiment where a team let agents write all the code for a week, the application ran but the build was often red. When red is the normal state, people stop reacting to it, and a green build stops being reassuring too. Thoughtworks' Rachel Laycock lists possible causes: parallel agents stepping on each other, a system that isn't modular enough, or changes arriving faster than the checks can finish.
DORA's 2025 report shows the same pattern at industry scale: AI adoption is now linked to higher delivery throughput but still to lower delivery stability. Treat a red build on `main` as an incident, not background noise. Fix or revert first, then find out why agents could land on top of it, for example a missing merge queue or checks that are too slow to gate each change.
## Measure human time with a safety guardrail
Optimizing only for reviewer minutes invites the obvious failure: the time reappears as incident response. The guardrail makes that trade visible.
The Claude Code team tracks human approvals per PR (median and 95th percentile), human comments, and time a PR waits on a person, with **revert and incident rates as the ceiling**. If reverts rise, saved review time was not saved time.
They also measure reviewer **noise** by observing what authors do with each comment: fixed it, said it was wrong, said the behavior was intentional, or ignored it. They additionally run the reviewer against known-clean PRs to count harmful false alarms. Recall alone is easy to inflate; the response distribution is the honest signal.
## Watch what the reviewer costs, and why
Cloudflare's AI reviewer is a useful cost postmortem: from March to August the average review went from $1.22 to $2.32 with no architectural change, then fell to **\$0.77 (−68%)** with a median time of 1m 32s instead of 4m 09s. Roughly 40% of the savings came from code changes and the rest from model and effort choices. The diagnostic half is more transferable than the numbers.
**Spend followed context, not output.** Just before optimizing, the bill split roughly 43% cache writes, 34% cache reads, and 23% output: most money went to context the model had already seen or was about to re-see. A single code-quality session made 16.6 model calls, writing 72k tokens to cache and reading back 1.08M, because every call resends the conversation. A high cache hit rate is not the same as a small bill — the hit rate rose to 97% while tokens per review tripled to 2.99M.
The largest single fix was the least obvious. Every session opens with 11k–21k tokens of tool definitions and agent prompt that are identical across repositories, yet the first request hit cache only 14–26% of the time. The prompt had been assembled as one block with a single cache breakpoint at the end, so the shared prefix was never stored on its own. Splitting the block at a marker, removing repository-specific content ahead of it, and keeping tool descriptions stable lifted first-request hits to 91–99.5%. Prepending the standards reviewer's reference index instead of spending three turns reading it cut its calls from 15.9 to 9.6.
Smaller fixes were each worth cents and compound:
* Remove tools a sub-reviewer cannot use — 57–76% of sessions tried to call the one that posts the final comment, then spent a call recovering.
* Read files in parallel instead of one tool call per turn.
* On re-reviews, skip reviewers with nothing new to look at.
* Stop after posting instead of running a turn to write an unread summary.
* Distinguish "slow" from "broken": a reviewer hitting its time limit was restarted with the same limit.
* Honor cancellation — in a sample of 446 cancelled jobs, 358 ran to completion.
**Then check quality per role, not in aggregate.** Fewer critical findings can mean less noise or more misses, so Cloudflare checked both directions: the share of serious findings authors acted on rose from 34% to 59% (baseline coincidence \~15%), important findings per review stayed flat at 0.28 → 0.30, and inflated severities fell 70% (0.46 → 0.14). But their performance reviewer lost about 64% of important findings at medium effort, so code quality moved to high effort while the others are still being tested. Medium effort genuinely lost real findings for that role.
Two habits to copy: instrument the **first request of every session** for cache hits, and verify that each reviewer still finds real problems at the effort level you pay for. The authors also note their before/after hour-based comparison is not a controlled experiment.
## Turn incidents into a reviewer eval set
This is the most reusable idea in the process: past PRs that caused incidents, with their fix-forwards and reverts, become the reviewer's regression suite. Engineers who know that code confirm each bug and where it lived, and the reviewer runs against the set daily. Any change to the reviewer's prompt, tools, or model gets rescored against all of it.
It is the same discipline as [calibrating an LLM judge](/env/ai-evals#calibrate-the-judge-against-people), applied to a reviewer: keep labeled real failures, include clean cases, and revalidate after every configuration change.
## Keep determinism for the parts that must not drift
Uber's AutoClean is the clearest published example of an agent doing **deletion** work at scale: over 16,000 stale feature flags and more than a million lines of code removed, with diffs routed to humans only after automated correctness checks pass. The split it uses is more instructive than the numbers.
**Deterministic tools do the rewrites; agents do the propagation decisions.** Inlining a rolled-out flag value is mechanical, but then someone must decide whether a parameter can be deleted (requires checking every call site), whether the old branch is now unreachable, and whether a config field is still read elsewhere. AutoClean gives the agent code search and editing, and routes boolean simplification through Uber's PolyglotPiranha engine via MCP. The rationale is blunt: a small error in simplifying a condition silently changes which branch runs in production.
Two more patterns generalize beyond flag cleanup:
* **Scope each fixer to its file class.** CI failures go first to cheap deterministic fixers, then to agentic ones. The test fixer may only edit test files — without that limit, an agent will sometimes make a failing test pass by changing the production code underneath it.
* **Separate validation from the loop that produced the change.** Long tasks with many instructions lose constraints; the agent optimizes for the most immediate signal, which is usually “CI is green”. Uber's **CodeCourt** takes the failure modes observed in practice and turns each into an explicit property checked by its own reviewer agent, in parallel:
| Property | What it blocks |
| - | - |
| No additions | Cleanup that introduces new code |
| Preserves semantics | Behavior that changes observably |
| No intent drift | Removing unrelated flags “while here” |
| No agent artifacts | Reasoning comments left in the diff |
All properties pass → the diff goes to a human for the business decision. Any property fails → the diff is abandoned before a reviewer sees it. Notably, a single end-to-end reviewer agent performed worse than several focused ones.
That last point is the direct link to this page's earlier advice: **verification is cheaper and sharper when each check has one job.** It also explains why the human stays in the loop for the judgment call — whether the flag should be removed at all — rather than for mechanical correctness.
## Tune review instructions in the right file
Two files shape what gets flagged, and they are not interchangeable:
* **`CLAUDE.md`** carries project context — stack, conventions, non-goals. Every review loads it; a change that violates it can become a finding.
* **`REVIEW.md`** carries review-only rules: what severity means in this repository, nit caps, paths to skip, and evidence requirements.
Good instructions are short and behavioral. Useful patterns:
* Redefine **Important** for this repository — a docs repo's "Important" differs from a billing service's.
* **Cap nits** per review so the summary stays actionable.
* Skip generated code, lockfiles, and anything CI already enforces.
* Require **`file:line` evidence** for behavior claims instead of inference from a name.
There is a security property worth understanding: `REVIEW.md` is read from the pull request's **base branch or default branch, never from the PR's own diff**. Otherwise a PR could weaken the rules that judge it. Some instructions — lowering severity, excluding paths, capping nits — only take effect from a root file on a protected default branch, and when protection cannot be confirmed the service may read no `REVIEW.md` at all. Protect the branch before relying on the tuning.
## Adoption checklist
Before the pull request:
* Give the agent checks it can run, listed in a short `CLAUDE.md`, plus hooks for formatters and linters.
* Run `/code-review`, `/security-review`, or a fresh-context subagent review locally.
* Move repeated review comments into `REVIEW.md`.
On every pull request:
* Require CI, and add **Testing**, **Risk**, and **How to revert** to the pull request template.
* Enable an AI reviewer on one repository, tune instructions for a few weeks, then widen.
* Require every review thread resolved before merge.
* Match effort to risk; cap rounds and re-review only new diffs after the first few.
Approval and after:
* Write down risk tiers and start strict; loosen only with evidence.
* Use `CODEOWNERS` and branch protection so sensitive paths always need a person.
* Never let a bot approval replace a required human, and dismiss approvals on new commits.
* Turn incidents and reverts into the reviewer's eval set; measure human time with reverts as the guardrail.
## References
* [meng shao: Meta Catching JiTTests](https://x.com/shao__meng/status/2119978619196084717) — Folo intake, November 10, 2026; entry `1371263115974438912`
* [Meta: Catching Bugs Before They Land](https://engineering.fb.com/2026/10/29/security/catching-bugs-before-they-land-jittestings-human-on-the-loop-approach-at-full-scale/) — two generation workflows, filtering, engineer feedback
* [Just-in-Time Catching Test Generation at Meta](https://arxiv.org/html/2601.22832v1) — weak versus strong catches and the test-oracle problem
* [meng shao: Cloudflare AI code review cost optimization](https://x.com/shao__meng/status/2113098764324159608) — Folo intake, October 22, 2026
* [Cloudflare: Cutting our inference bill by 68%](https://blog.cloudflare.com/obsessive-inference-optimization/) — token accounting, shared cache prefixes, per-role quality checks
* [meng shao: Uber AutoClean agentic cleanup](https://x.com/shao__meng/status/2112723092468605242) — Folo intake, October 21, 2026
* [Uber: Using AI to Delete Code](https://www.uber.com/us/en/blog/ai-code-cleanup/) — deterministic rewrites via MCP, scoped fixers, CodeCourt properties
* [宝玉: Claude Code team's code review practice](https://x.com/dotey/status/2111384189656252712) — Folo intake, October 17, 2026; points to the team's write-up
* [How the Claude Code team does code review](https://claude.dev/blog/solving-code-review-at-anthropic/) — layers, risk tiers, convergence fixes, reviewer evals, adoption steps
* [Claude Code: Code Review](https://code.claude.com/docs/en/code-review) — four-stage pipeline, review levels, explicit limits
* [Read and request reviews on a pull request](https://code.claude.com/docs/en/code-review-pull-requests) — severity levels, check-run behavior, machine-readable verdict
* [Customize Code Review](https://code.claude.com/docs/en/code-review-customize) — `REVIEW.md` vs `CLAUDE.md`, and which branch the rules are read from
* [Bringing Code Review to Claude Code](https://claude.com/resources/articles/code-review) — vendor-reported preview metrics (16% → 54%, large-PR findings, under 1% judged incorrect)
* [Code Review is now generally available](https://claude.com/resources/articles/code-review-is-now-generally-available) — Quick/Standard/Deep levels and faster reviews
* [Folo source: meng shao on OpenRouter's verifiable code review](https://x.com/shao__meng/status/2117411081971015897)
* [OpenRouter: Build an AI code reviewer](https://openrouter.ai/blog/tutorials/ai-code-review/) — sandbox reproduction, confirmed/unconfirmed findings, exit codes, base-branch reviewer in CI
* [Folo source: meng shao on why good developers are wary](https://x.com/shao__meng/status/2117092563329179702)
* [Rachel Laycock: Why are good developers so wary of agentic development?](https://www.martinfowler.com/rachels-ramblings/good-devs-wary.html) — the agent-only week and the red build
* [Google Cloud: Announcing the 2025 DORA report](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report) — AI adoption, throughput, and stability
# AI product evals
Source: https://base.bangwu.me/env/ai-evals
Build task-specific AI evaluations from real traces: discover failures, create minimal regression cases, calibrate LLM judges, and separate CI, monitoring, and guardrails.
# AI product evals
A model benchmark helps you choose a starting model. A **product eval** checks whether your actual application meets a user's goal, including its prompts, retrieval, tools, permissions, and application code. A fluent answer is not evidence that the requested action succeeded.
This workflow synthesizes Hamel Husain's evals flashcards and FAQ with OpenAI's evaluation guidance. It complements [Agent harness](/env/agent-harness): the harness controls execution; evals provide evidence about its behavior.
## Start with failures, not a dashboard
A **trace** records the path from a user request to its outcome: messages, retrieved context, tool arguments and results, and relevant state changes. For multi-agent work, preserve a shared trace ID and the source and ordering of events.
1. **Collect diverse traces.** Mix random samples with different workflows, negative feedback, retries, and unusually slow runs. Keep some random sampling even after you know which failures to search for.
2. **Write open-ended notes first.** Have someone who understands the product inspect examples before an automated reviewer suggests labels. Record what went wrong for the user, including ordinary code or design bugs, not just model errors.
3. **Group recurring failures.** Turn notes into specific categories such as “booked an unavailable slot” or “claimed success after a tool failed.” Then label pass/fail for each relevant criterion and retain the evidence.
4. **Prioritize and repeat.** Consider frequency, impact, and remediation cost. Continue until new reviews stop revealing or changing failure categories; revisit after meaningful product changes.
Hamel suggests a pool of roughly 100 diverse traces, with an initial manual pass. Treat this as a starting heuristic, not a statistical guarantee or a reason to delay starting with a smaller batch.
**Discovery and measurement need different samples.** A batch selected for retries helps find problems, but its failure rate is not the production failure rate. Keep the sampling method with the results; use representative sampling or an explicit weighting scheme for prevalence estimates. Redact secrets and unnecessary personal data before sharing traces or sending them to an external judge.
## Turn an observed failure into a regression case
For a long conversation, locate the first upstream failure before counting its downstream consequences as separate problems. Preserve the full trace for investigation, then minimize the reproduction.
Consider an illustrative scheduling agent:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
User: Book the 10:00 slot.
Tool result: 10:00 is unavailable.
Agent: Calls the booking tool for 10:00 anyway. <-- first failure
Agent: Says the appointment is confirmed.
```
The smallest useful test may only need the request and the availability result. In **N-1 testing**, replay the valid conversation prefix before the failing step and evaluate what the system does next. Keep the expected behavior outside the input; do not feed the original failed answer or its label back to the system under test.
A practical test record can include:
| Field | Purpose |
| - | - |
| `case_id`, `source_trace_id` | Link the regression to its original evidence |
| `input_prefix`, `tool_fixtures` | Reproduce the relevant conversation and tool state |
| `criterion`, `expected_behavior` | Define one behavior, not a vague quality score |
| `app_version`, `prompt_version`, `model` | Identify what was evaluated |
| `rubric_version`, `judge_version` | Identify how it was graded |
| `result`, `evidence` | Preserve the outcome and supporting tool event or text |
Run replay tests in a sandbox with mocked tools or isolated test accounts, never against live booking, payment, or deletion endpoints. If the workflow or tool schema changes substantially, rebuild stale fixtures. Keep end-to-end tests too: passing an isolated next-step test does not prove the whole session succeeds.
## Use the cheapest trustworthy check
| Failure to detect | Start with | What to verify |
| - | - | - |
| Invalid output schema or missing field | Code assertion | Parse and validate the actual output |
| Wrong tool argument or unauthorized action | Code assertion and runtime permission check | Inspect the arguments, identity, and state at the action boundary |
| Success claim unsupported by tool results | Human review, then a calibrated LLM judge when needed | Compare the final message with the relevant execution evidence |
| Poor overall user experience | Human review and product experiments | Identify the specific failure before automating it |
Fix obvious prompt omissions and ordinary bugs first. Add cheap regression tests where useful; invest in an LLM judge when an important semantic failure needs repeated measurement. **Do not wait for a real incident to test known safety requirements**, such as authorization or irreversible actions.
Prefer a narrow pass/fail criterion over an undefined “quality: 4/5.” For the scheduling example, separate “did not book an unavailable slot” from “did not claim an unconfirmed booking succeeded.” Each needs different evidence. Numeric scores or pairwise comparisons can still be useful when their meaning is explicit and validated; binary labels are a practical default, not a universal law.
A semantic grader can return a small structured result such as:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"criterion": "no_false_confirmation",
"verdict": "fail",
"evidence": "The booking tool returned a conflict, but the final message said confirmed."
}
```
This is an illustrative format, not a vendor API. Make it possible for a human to check the cited event. Missing evidence or a grader timeout is an evaluation error requiring review, not an automatic pass.
## Check the path, conversation, and final state
LangChain's agent-evals guide distinguishes several evaluation scopes. Pick the scope that can actually reveal the failure:
| Scope | Example check | Evidence needed |
| - | - | - |
| Single step | Did the tool receive the requested date? | Tool arguments and current request |
| Final response | Does the confirmation match the booking result? | Final message and tool result |
| Full conversation | Did the final booking reflect a date change made several turns earlier? | Ordered turns grouped by conversation/thread ID |
| Environment state | Does exactly the intended test booking exist? | Records in an isolated test system after the run |
A sequence of individually reasonable turns can still fail the overall task. Conversely, different tool sequences can achieve the same valid result. Assert necessary constraints—such as approval before a write or no duplicate booking—rather than requiring one exact trajectory unless that sequence is itself a requirement.
For state-changing tasks, start every evaluation from a clean, known fixture and inspect the state afterward. A coding task can be scored with the repository's tests and the resulting diff instead of the agent's “done” message. Keep the trusted grading checks outside the agent's editable work products, and do not let success depend only on tests the agent wrote or changed itself.
Containers are one way to isolate such tasks, not the definition of every benchmark and not a complete security boundary by themselves. Limit credentials, network access, mounts, and run time to what the test needs. Record the fixture version, tool configuration, grading result, and trace. Repeat stochastic cases when needed and report passes over attempts; record infrastructure errors and timeouts separately rather than silently excluding them or counting them as success.
## Calibrate the judge against people
A second model's opinion is not ground truth. Build a human-labeled set containing both passes and failures for the same criterion, and resolve unclear definitions before tuning the judge.
Separate examples by purpose:
* **Train/examples:** choose few-shot examples for the judge prompt.
* **Development:** revise the rubric and inspect disagreements.
* **Held-out test:** check generalization without tuning on these labels. Keep related traces and paraphrases together so they do not leak across splits.
There is no universal split ratio or acceptable score. Hamel's card shows an example split, while the FAQ emphasizes choosing targets from the costs of missed failures and false alarms.
Define the positive class explicitly. Here, **positive means an actual failure**:
* **TPR / failure recall** = `TP / (TP + FN)`: how many human-labeled failures the judge catches.
* **TNR / specificity** = `TN / (TN + FP)`: how many human-labeled passes the judge correctly leaves unflagged.
If 95 of 100 cases pass, a judge that always says “pass” has 95% accuracy but **0% failure recall**. Report both rates and their sample counts; if a class has no examples, its rate is undefined, not 100%. Small samples leave substantial uncertainty.
Recheck agreement after changing the judge model, rubric, or application distribution. Review false alarms and missed failures rather than merely optimizing the aggregate score. Keep the application model/prompt and the grader configuration versioned so score changes remain interpretable.
## Do not inherit a decision model's default threshold
Decision models — TypeSafe's Jev, Perplexity's Decider, Liquid's d1, Cloudflare's Clef, OpenAI's Decisions API — are an appealing cheap alternative to an LLM judge. They return a **probability** that a trace contains a failure, and their APIs turn that into a verdict using a default threshold of `0.5`. Hamel Husain's experiment with 98 human-labeled production traces shows why that default deserves skepticism.
Consider a model that scores every failing trace `0.40` and every passing trace `0.10`. It is a perfect classifier at a `0.30` threshold — and at `0.50` it catches nothing. Real score distributions overlap, so threshold choice is a precision/recall trade-off, and the right point follows from consequences: an alerting system that must avoid false alarms is not a cancer screening.
A working procedure, which costs nothing extra once scores are saved:
1. **Set minimums first.** Require floor precision and recall for the task (Hamel's example: both ≥ 80%). Any model that cannot meet them is out, regardless of its average score.
2. **Tune on training folds, measure on held-out folds.** Use stratified cross-validation with identical splits across models, and pick the threshold on the training portion only. Select an objective that matches the business — F-beta if precision and recall are not equally costly.
3. **Compare cost and performance.** On this small sample the cheapest candidate ran about 0.82 cents per 100 evaluations at F1 0.79; the strongest ran 3.72 cents at F1 0.87. Three points is an illustration, not a benchmark.
4. **Check calibration before treating a score as confidence.** A `0.8` should mean roughly 80% of similar traces fail. Some models were badly miscalibrated — one batch averaged 8% predicted probability while 60% actually failed. Platt scaling fixed several models; for one it made the Brier score slightly worse (0.159 → 0.164), and fitting directly on probabilities instead gave 0.154. Method choice matters, so measure after calibrating.
5. **Re-tune after any prompt change.** Threshold and calibration are properties of the prompt–model pair, not the model alone.
Two scope notes. The experiment deliberately used a broad “any substantive issue” task to separate models; for production, keep **one judge per failure mode**, which usually compresses the gaps between models. And a cheap prompt improvement — replacing a vague instruction with an explicit list of failure types — moved F1 from 0.78 to 0.80, which is worth trying before reaching for calibration machinery.
## Evaluate classifiers at the operating point
Airbnb's production classification study is a useful example of evaluating a model against product constraints. Its content-policy classifier gates publication, so false positives block legitimate content. It must return a score within 200 ms at thousands of requests per minute. The evaluation uses 10,000 held-out examples weighted to reflect production traffic.
Airbnb reports that a small fine-tuned classifier matched frontier-model quality, with about 85 ms p99 latency. The reusable lesson is the evaluation procedure, rather than a model ranking:
* **Set the decision costs first.** Choose a threshold on development data that meets the required precision and recall, then report held-out results at that threshold. The study reports maximum F1; that alone does not establish the right threshold for a product that particularly penalizes false positives.
* **Compare scores and verdicts deliberately.** A score supports threshold sweeps; a yes/no answer supplies one operating point for that prompt. Rewriting a prompt to move that point creates a new configuration to evaluate.
* **Measure latency under the expected load.** Include p99 and throughput, not just median response time. A model with excellent quality can still miss a synchronous publication deadline.
* **Model the cost crossover.** Dedicated GPU rental continues while idle; API token costs grow with traffic. Include utilization, worker capacity, prompt length, cache behavior, and separately budget labeling, training, and operations.
The article's “about 1%” compares serving costs at high volume using October 2026 public API prices and a single rented GPU. It assumes 71% cache hits for eligible APIs and excludes negotiated discounts; it is not a universal total-cost ratio. For low-volume tasks or policies that change frequently, a prompted API model can remain the better starting point. Fine-tuning becomes worth evaluating when the task is stable, labeled in-domain data is available, and latency or sustained volume justifies it.
## Separate regression tests, monitoring, and guardrails
| Placement | Data and timing | Purpose | Response to failure |
| - | - | - | - |
| CI / pre-release | Curated regression cases before merge or release | Catch known regressions | Block changes according to explicit acceptance criteria |
| Production monitoring | Sampled real traces, usually asynchronous | Discover new failures and track drift | Alert, investigate, and add cases |
| Runtime guardrails | Checks on each protected request or action, synchronously | Prevent a specified harmful action or response | Block, request approval, or use a safe fallback |
A check after the response can discover a bad purchase; it cannot prevent that purchase. Enforce permissions **before the side effect**, outside the model. Guardrails also need latency and false-alarm budgets. Do not retry payments or other writes blindly when a check fails; see [purchase approval boundaries](/env/agent-harness#separate-discovery-from-purchase-approval).
CI pass rates are not estimates of user satisfaction: regression suites deliberately overrepresent known failures. Likewise, a green suite proves only what it covers. Keep adding independently reviewed production failures and deliberate edge cases, and rerun relevant evals when code, prompts, models, retrieval, or tools change.
## A minimal starting checklist
* Review a small, diverse batch with a product/domain expert.
* Name one important failure and retain its trace evidence.
* Reproduce it with a minimal safe fixture and a clear assertion or rubric.
* Validate any automated judge against both human-labeled passes and failures.
* Compare the current and candidate systems on the same versioned cases.
* Assign an owner for failures and feed new production cases back into the suite.
## References
* [meng shao: Airbnb's production classifier benchmark](https://x.com/shao__meng/status/2119973180945387755) — Folo intake, November 10, 2026; entry `1371263115974438914`
* [Airbnb: Frontier quality at 1% of the cost](https://airbnb.tech/ai-ml/frontier-quality-at-1-of-the-cost-a-production-benchmark-of-llm-classifiers/) — weighted evaluation, scores versus verdicts, latency, and serving-cost assumptions
* [meng shao: using decision models for evals](https://x.com/shao__meng/status/2112720094287786298) — Folo intake, October 21, 2026
* [Hamel Husain: How To Use Decision Models For Evals](https://hamel.dev/blog/posts/decision-model-evals/) — threshold tuning, cost/performance, calibration, prompt scope
* [meng shao: Common agent-eval questions](https://x.com/shao__meng/status/2110585984564039900) — Folo intake, October 15, 2026
* [LangChain: The Most Common Questions About Agent Evals, Answered](https://www.langchain.com/blog/common-questions-about-agent-evals) — step, conversation, trajectory, and environment-state evaluation
* [meng shao: Pocket Guide to AI Evals](https://x.com/shao__meng/status/2109445747133579381) — Folo intake, October 12, 2026; points to Hamel's original cards
* [Hamel Husain: Evals flashcards](https://hamel.dev/notes/llm/evals/flashcards/) — especially error analysis, judge validation, trace-based cases, and deployment
* [Hamel Husain: AI Evals FAQ](https://hamel.dev/blog/posts/evals-faq/) — sampling, evaluator selection, calibration, and multi-turn debugging
* [Hamel Husain: Your AI Product Needs Evals](https://hamel.dev/blog/posts/evals/) — scoped tests and human review as the foundation
* [OpenAI: Evaluation best practices](https://platform.openai.com/docs/guides/evaluation-best-practices) — task-specific evals, human calibration, edge cases, and continuous evaluation
# Beads
Source: https://base.bangwu.me/env/beads
Beads is a Dolt-backed graph issue tracker that gives coding agents structured memory, dependency-aware task tracking, and JSON-first workflows.
# Beads
[Beads](https://github.com/gastownhall/beads) is a graph issue tracker built for coding agents. Its CLI is `bd`, and its storage layer is [Dolt](https://www.dolthub.com/), a version-controlled SQL database.
The useful idea is not just "another todo list". Beads gives agents a structured task graph that can survive long sessions, multiple branches, and context-window pressure.
## What problem it solves
Markdown plans are easy to start but hard to maintain once a task becomes long-running:
* dependencies are implicit
* multiple agents can edit the same file
* closed work keeps taking context space
* resuming a task requires rereading a lot of prose
* handoff between branches or machines is fragile
Beads turns task state into a database-backed graph so agents can query what is ready, claim work, link blockers, and preserve an audit trail.
## Core model
Beads stores issues as structured records rather than free-form notes.
Important concepts:
* **Issues**: tasks, bugs, epics, messages, or other work items.
* **Dependencies**: parent-child links, blockers, related items, duplicates, and superseded items.
* **Ready queue**: `bd ready` lists work with no open blockers.
* **Claims**: `bd update --claim` lets an agent atomically take a task.
* **Compaction**: old closed work can decay into summaries to reduce context cost.
* **JSON output**: commands are designed for agents and scripts to parse.
This makes Beads closer to an agent memory layer than a normal human-only issue tracker.
## Basic workflow
Install the CLI once, then initialize it inside a project:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
brew install beads
cd your-project
bd init
```
Then tell agents how to use it:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
echo "Use 'bd' for task tracking" >> AGENTS.md
```
Common commands:
| Command | Use |
| - | - |
| `bd ready` | List unblocked tasks. |
| `bd create "Title" -p 0` | Create a high-priority task. |
| `bd update --claim` | Claim a task atomically. |
| `bd dep add ` | Add a dependency or hierarchy link. |
| `bd show ` | Inspect details and audit history. |
## Storage modes
Beads has two main storage modes:
* **Embedded mode**: `bd init` uses an in-process Dolt database. This is the default and fits most personal or single-writer workflows.
* **Server mode**: `bd init --server` connects to a `dolt sql-server`, which is better when multiple writers need concurrent access.
It also supports **git-free usage** with `BEADS_DIR` and `bd init --stealth`, useful for CI, evaluation runs, monorepos, non-git version control, or personal task tracking that should not modify the shared repository.
## When to use it
Beads is worth considering when:
* a coding task spans many turns or days
* multiple agents or branches need to coordinate
* task dependencies matter more than a flat checklist
* you want machine-readable task state instead of prose plans
* you need to preserve progress without stuffing everything into the prompt
For a short one-off change, plain Markdown is simpler. For long-horizon agent work, Beads gives the harness a more reliable external memory surface.
## How it fits with agent harness design
In an agent harness, Beads belongs in the **memory and coordination** layer:
* it externalizes task state from the model context
* it gives agents a queryable ready queue
* it reduces merge conflicts through generated IDs and structured storage
* it makes handoff easier because task status is not hidden in chat history
This complements tools like `git worktree`, browser harnesses, and repo-local `AGENTS.md` instructions. The pattern is the same: move durable state out of the model and into inspectable project infrastructure.
## Things to check before adopting
* Decide whether `.beads/` should be committed, ignored, or used in stealth mode.
* Prefer JSON output for agent automation.
* For multi-agent workflows, test claiming and dependency updates before relying on them.
* Verify install binaries or checksums before trusting downloaded tools.
* Keep task titles and dependencies small enough for agents to scan quickly.
## References
* [gastownhall/beads](https://github.com/gastownhall/beads)
* [Beads documentation](https://gastownhall.github.io/beads/)
* [Dolt](https://www.dolthub.com/)
# Browser Automation Observability
Source: https://base.bangwu.me/env/browser-observability
Debugging browser automation with read-only CDP tracing — attach a second CDP client to capture DevTools events, screenshots, and DOM snapshots without disrupting the main automation flow.
# Browser Automation Observability
When browser automation (Playwright, Stagehand, browser-use, etc.) fails, gets stuck, or can't find an element, you need to see **what actually happened** — network requests, console errors, DOM changes, and screenshots aligned by timestamp. The `browser-trace` skill makes this possible without disrupting your main automation.
## Core Idea: Read-Only CDP Sidecar
Chrome DevTools Protocol (CDP) allows **multiple clients** to connect to the same browser target simultaneously. Your main automation sends commands through one CDP client. The trace skill connects a **second, read-only CDP client** that only subscribes to observation domains (Network, Console, Runtime, Log, Page) — never sending actions that change the page.
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
┌─────────────────┐ ┌─────────────────┐
│ Main Automation │ │ browser-trace │
│ (Playwright / │ │ (read-only │
│ Stagehand / │ │ CDP client) │
│ browser-use) │ │ │
│ sends commands │ │ only observes │
└─────────┬────────┘ └─────────┬────────┘
│ │
└─── CDP ──► Chrome ◄─────┘
(same target)
```
> [!NOTE]
>
> CDP is designed for multiple clients. The main automation owns the "action" domains (DOM manipulation, input events). The trace client only subscribes to "observation" domains (Network events, Console messages, Page lifecycle). They coexist without interfering.
## Three Mechanisms
### 1. Firehose — Raw CDP Event Stream
Captures all CDP events into NDJSON for post-hoc analysis:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
browse cdp # Writes CDP full stream to cdp/raw.ndjson per line
```
### 2. Sampler — Periodic Screenshots + DOM Snapshots
Periodically grabs screenshots and full-page HTML alongside the event stream:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
browse --ws screenshot # Screenshot via one-shot WS connection
browse --ws get html body # Full page HTML via one-shot WS connection
```
### 3. Bisector — Post-Run Segmentation
After the automation completes, `bisect-cdp.mjs` segments the raw event stream into structured, searchable chunks:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
bisect-cdp.mjs # Scans raw.ndjson, splits by:
# - CDP method buckets (multiple JSONL files)
# - Page navigation segments (pages/000/... tree)
```
This makes it easy to find events by navigation phase (e.g., "what happened after the login page loaded").
## When to Use
* **Automation fails / gets stuck** — Find the exact moment it broke: which request failed, which JS error fired, which DOM element was missing
* **Mid-session debugging** — Attach trace to an already-running session without restarting
* **Causal analysis** — Align network, console, DOM, and screenshots by timestamp to trace root causes
## Practical Constraints
1. **Sampling interval** — Don't sample faster than \~1s (default 2s). Each sample adds CDP/ screenshot overhead.
2. **DOM domain is noisy** — Fine-grained DOM tree changes require adding `DOM` to `O11Y_DOMAINS`, but it generates very verbose output.
3. **Always run stop-capture** — Even if your code crashes, run `stop-capture.mjs` to avoid zombie processes and missing `stopped_at` timestamps.
4. **Bisect is idempotent** — You can re-run it on the same data; it overwrites previous segmentations.
5. **Don't re-open sessions** — For remote automation with `browse --connect`, don't call `browse env remote` to open a new session for the same browser target.
## Quick Start
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 1. Start capture before your automation runs
start-capture.mjs
# 2. Run your automation (Playwright, etc.) as normal
# 3. Stop capture after completion
stop-capture.mjs
# 4. Segment the captured data
bisect-cdp.mjs
# 5. Inspect results
jq '. | select(.method == "Network.requestWillBeSent")' cdp/raw.ndjson
rg "console.error" pages/
```
## References
* [browser-trace skill on skills.sh](https://skills.sh/browserbase/skills/browser-trace)
* [Browserbase team](https://www.browserbase.com/)
* [CDP Protocol docs](https://chromedevtools.github.io/devtools-protocol/)
# Claude Code effective patterns
Source: https://base.bangwu.me/env/claude-code-patterns
Practical patterns for working with Claude Code Fable 5, from the Claude Code team and community practitioners: treat the model as a thinking partner, set goals with verification, give full context, demand self-checks, and use budget constraints to force better trade-offs.
# Claude Code effective patterns
Claude Code's Fable 5 model brings significantly stronger coding capability — it can run for hours, test its own work, and often write code better than the developer. But a strong model does not guarantee effective use. These patterns come from Claude Code team member Thariq and community practitioners.
## Three mindset shifts
Thariq from the Claude Code team described three key changes in how he works with Fable 5:
### Unhobble Claude: let the model surprise you
Anthropic internally calls it **capability overhang** — the model can already do many things, we just haven't found the right way to unlock them. Early models needed detailed instructions and examples, but with Fable-level models, too many examples actually constrain the model because its own imagination is richer than what you can specify.
Claude Code recently cut **80% of its system prompt**. The new approach: give context, not constraints. Tell the model about the situation, not what it's not allowed to do.
A concrete example: ask a chat model which Pokémon names end with "aw" — it can't answer because it can't iterate through names in its head. But give it a code execution tool and it pulls the full list, writes a script, and finds the answer in two seconds. The capability was there all along; the tool unlocked it.
### Treat Claude as a thinking partner
The old pattern: break tasks into small pieces, check every output, catch problems when the model stops too early. With Fable, you increasingly check whether Claude is doing the **right work**, not just whether it's working correctly.
A common failure mode: you don't actually know what you want, or what's feasible. Involving Claude early in your thinking catches these blind spots before implementation.
Practical approaches:
* Start with a small spec. Before writing the final spec, ask Claude to "interview" you about the implementation plan.
* Throw out an idea and ask it to explore several directions, generating HTML prototypes for review.
* Give it context, not just constraints. Instead of "keep it simple, don't over-engineer," say "this feature is an experiment — we'll likely delete it in a month, so don't build anything you'd be sad to throw away."
### Set goals and provide verification methods
Once you know what you want, use two Claude Code features:
* `/goal`: keeps Claude working toward completion
* **Workflows**: helps Claude verify its own output
After writing a spec, try:
> "Set a goal to fully implement this spec. Then use workflows to verify each part of the plan and prepare a report on what was implemented and any discrepancies."
This lets Claude be creative and thorough while ensuring it builds what you actually need.
### Be more ambitious
Fable is an incredible model. If you think an LLM can't do something — give it a chance. Thariq edited the very video he posted using Fable. Don't let past experience cap your expectations.
## Five principles to push Fable to its limits
Community practitioner Gorden Sun distilled five practical principles:
### 1. Give goals and acceptance criteria, let Fable decompose the steps
Don't micromanage. Tell it what to achieve and how to judge success. Let it plan its own path. Over-decomposing tasks limits the model's planning ability.
### 2. Let Fable plan and ask questions before executing
Give the model a "thinking phase." Let it propose an approach and ask clarifying questions before you confirm and it starts building. This prevents major directional mistakes.
### 3. Give all raw materials at once
Don't feed information in fragments. Provide all relevant documents, codebase context, and requirements in one shot. Fable's long-context capability lets it judge what matters and how things connect.
### 4. Explicitly demand self-checks
Key self-check dimensions:
* **Write tests**: require tests for every feature and ensure they pass
* **Find counterexamples**: identify edge cases where the solution might fail
* **Mark confidence**: label each key conclusion with confidence level and what evidence would change the judgment
### 5. Use budget constraints to force better trade-offs
Moderate resource limits (search count, word count, time) force the model to make smarter prioritization decisions. Unlimited resources can produce unfocused, excessive output.
## Manage context deliberately
A large context window is capacity, not a reason to fill it. Providing complete task context means giving the requirements and relevant evidence, not appending every log or unrelated conversation.
Claude Code clears older tool outputs and, when needed, summarizes the conversation as context fills. **Compaction is a lossy handoff, not verbatim retention of the whole conversation.** Earlier details can disappear; a summary is not proof that a test passed or a decision was approved.
Use this workflow for long tasks:
1. **Inspect before adding more.** Run `/context` to see what occupies the window. Filter logs and read relevant file ranges instead of repeatedly loading entire outputs.
2. **Separate rules from task state.** Put persistent project instructions in `CLAUDE.md`. Keep the current goal, acceptance criteria, decisions, changed files, test commands and results, unresolved risks, and next step in a short task note. Link to evidence rather than copying large outputs.
3. **Compact at a coherent boundary.** Save that note before switching from investigation to implementation, or from implementation to review. Use a focused command when you want control:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
/compact Preserve the goal, acceptance criteria, decisions, changed files, test results, unresolved risks, and next step.
```
4. **Verify the handoff.** After compaction, have Claude read the task note and inspect the current diff. Check that it can restate the remaining work; recheck files or rerun tests when evidence is missing or stale.
5. **Reset between unrelated tasks.** Save anything needed first, then use `/clear` rather than carrying irrelevant history into the next task.
You can add a `Compact Instructions` section to `CLAUDE.md` to specify what summaries should preserve. Treat it as guidance, not a guarantee of lossless memory. See [Agent harness](/env/agent-harness) for the broader durable-state pattern.
The Folo discussion that prompted this note suggested compacting around 300k–400k tokens. That is a practitioner's preference, **not a universal optimum**. Check the commands supported by your installed version and tune from observed quality, latency, and usage rather than copying a threshold or removing a context-limit setting blindly.
## Example prompts to try
### End-to-end deep research
```
Do deep research on "2026 AI Agent infrastructure landscape,"
cross-verify at least 8 sources, organize key data into tables
with trend analysis, deliver a cited report plus an infographic.
Give me an outline and verification approach first — I'll confirm before you proceed.
```
### Self red-teaming
```
First present your best solution, then switch to the harshest reviewer,
find three fatal flaws, and produce a revised version.
Mark confidence for each key conclusion and explain what evidence would change your judgment.
```
### Massive context audit
```
(Attach an entire contract, codebase, or manuscript)
Read through everything. Find all internal contradictions,
inconsistent definitions, and broken cross-references.
Sort by severity and cite the original location for each.
```
### High-constraint creative work
```
Write a regulated verse poem with a hidden four-character acrostic,
a double entendre in the second couplet, and a complete ban on
two specific characters. Verify every constraint after completion.
```
### Pure code music
```
Using no audio assets, synthesize a 30-second electronic track
in pure code, then build a webpage with a particle fluid
that moves to the beat.
```
## Find your unknowns: blind spot techniques
Thariq's second key theme: your prompt is a "map," but the real codebase is the "territory." When the model encounters something not on your map, it must decide on its own. Fable 5's range is so large that if you don't identify these unknowns in advance, it will make decisions you didn't want in places you didn't expect.
Six concrete techniques:
* **Blind spot scan**: before building, have Fable read through relevant code and surface potential issues you didn't know about
* **Four-prototype burst**: ask for four stylistically different prototypes at once, then discover your preferences through reaction rather than description
* **Interview you**: let Fable ask you questions to extract details you "know but haven't written down"
* **Reference code as map**: give it code from another system as a reference pattern — often more efficient than writing a spec from scratch
* **Decision log**: have it record every point where it deviated from your expectations, so you can see where it encountered problems you didn't anticipate
* **Reverse quiz**: ask Fable to quiz you on what it built, ensuring you understand it well enough to explain the PR
## Maintaining AI-generated code
When all code is AI-generated, the risk is not writing code — it is keeping that code iterable, maintainable, and free of rot. Product engineer Tw93 distilled six practices after shipping 13 versions of an app with \~110K lines of Swift and \~73K lines of tests, all AI-generated:
1. **Architecture and layering still matter.** Clear boundaries make AI-generated code easier to maintain and extend. Don't let the model invent the structure each time.
2. **Automated tests are the quality backbone.** Every bug fix must add a regression test, so the same bug can't come back.
3. **Delete dead code aggressively.** When you remove a feature, remove its code too. Accumulated leftovers confuse both humans and future AI passes.
4. **CI/CD with a clean machine.** Run the full test suite on a clean cloud runner before release, not just on your local machine.
5. **Let the AI auto-verify and auto-correct.** Wire automated verification into the loop; reserve human verification for critical stages.
6. **Turn repeated work into skills.** Encode recurring procedures so you don't re-explain them from scratch every session.
The throughline: AI lowers the cost of writing code to near zero, so the discipline that matters shifts to architecture, verification, and cleanup.
## Supervising agents smarter than you
Frontier agents remove the barrier of "you must build a mental model before changing code," but they still fail in two ways: misunderstanding your intent and lacking the context to get things right. Both share one root cause — the quality of what you put into the context window. Since modern codebases are too large to hold fully in your head, the method shifts from "understand it yourself" to "make the agent prove it understands."
Five techniques from a practitioner shipping thousands of PRs per month:
**1. Indirect prompting (in your own words).** Don't order directly. First ask the agent to restate the problem in plain language — "read this Slack thread and describe the root problem in your own words." This compresses noise into a structured statement, surfaces misunderstandings before the agent runs the wrong way, and stops your own wrong assumptions from steering it.
**2. Mental-model skills.** Four complementary commands:
* `/how` — trace runtime mechanics across directories and services
* `/why` — investigate intent: code says what happened, rarely why. Search git history, PR comments, Linear, Notion, Slack, Datadog, Sentry in parallel
* `/teach` — have the agent explain it back to you intuitively (this also forces the agent to build a real model instead of confidently bluffing)
* `/recall` — pull context back from past session transcripts instead of rebuilding from zero
**3. README-driven development.** For shared code, write the README before implementing. It forces you to design from the hypothetical user's API perspective. Use the Diátaxis framework to separate Tutorial / How-to / Reference / Explanation, and a pass to strip AI-sounding filler. The finished doc doubles as a concrete target the agent can verify against.
**4. Prototype first.** The two planning mistakes are accepting the agent's first design and over-polishing a plan without evidence. Instead, have the agent produce several prototypes in parallel — UI variants behind a switcher, timing/layout measured with a verification CLI — and choose from screenshots. Prototypes are planning in code: the agent answers its own open questions with evidence.
**5. Architect in five stages.** Ground (build the current-state model with /how + /why) → Sketch (several independent runners across model families, each producing a full design package: call sites, type definitions, signatures, rationale) → Cross-judge (different models score against a strict rubric) → Implement (fill in the chosen sketch) → the cycle repeats with verification.
## Loops design paradigm
Claude Code's official Loops framework elevates agent engineering from intuition to a reusable design language. The core insight: four variables — trigger, stop condition, artifact, and use case — define every agent loop. The question isn't "is this task hard?" but "which segment of work can be handed off?"
### Four loop types
**Turn-based (default agentic loop)**
* What you hand off: checking this step
* Trigger: user prompt
* Stop: agent decides it's done or needs more context
* Artifact: SKILL.md (encode your verification criteria)
* When: short, one-off, non-recurring tasks
This is the default. Improve it by encoding your mental acceptance criteria into SKILL.md so the agent can self-check more steps, reducing the rounds per task.
**Goal-based (/goal)**
* What you hand off: the stop condition
* Trigger: manual prompt
* Stop: goal achieved, or max turns reached
* Artifact: /goal + evaluation model
* When: tasks with verifiable exit criteria
Use when one turn isn't enough. The key: define exactly what "done" looks like. The evaluation model checks your conditions each turn — deterministic metrics (test pass count, score thresholds) work best because the evaluator only needs to compare, not judge "good enough."
**Time-based (/loop, /schedule)**
* What you hand off: the trigger timing
* Stop: you cancel, or work completes naturally (PR merged, queue emptied)
* Artifact: /loop (local, stops on shutdown) or /schedule (cloud)
* When: recurring work, or work that reacts to external state changes
Prefer event-driven over time-driven: longer intervals or state-change triggers save tokens and avoid jitter. Use /loop for local machines, /schedule for cloud persistence.
**Proactive (fully autonomous)**
* What you hand off: the prompt itself
* Trigger: events or schedule, no human in the loop
* Stop: each subtask exits on goal; the routine runs until stopped
* Artifact: all of the above + dynamic workflows (research preview) + auto mode
* When: standardized incoming work — bug reports, issue triage, dependency upgrades, batch migrations
Example assembly: /schedule periodic scan → /goal defines "done" + SKILL encodes verification → dynamic workflows explore multiple solutions with adversarial review → auto mode executes without approval.
### Quality guardrails (four levels)
1. **Keep the codebase clean** — agents follow existing patterns and conventions
2. **Give agents self-verification** — encode "good" as SKILL checks
3. **Make docs accessible** — keep framework/library docs current with best practices
4. **Use a second agent for code review** — a fresh-context reviewer avoids the main agent's confirmation bias
When a single result falls short, don't just fix that one issue — encode it into the system so all future iterations benefit.
### Cost guardrails
* Match the artifact and model to the task — simple tasks don't need multi-agent loops
* Define clear success/stop criteria — be specific about "what done looks like"
* Pilot before scaling — dynamic workflows can spawn hundreds of agents
* Use scripts for deterministic work — a form-filling script is far cheaper than an agent deriving code each time
* Don't run routines more often than necessary
Monitor with `/usage`, `/goal` (no args), and `/workflows` to inspect token distribution. The loops themselves don't save money — model tiering and clear boundaries do.
### How to start
Look at work you're already doing. Find the step where **you** are the bottleneck. Ask:
* Can you write a quantifiable verification check? → If yes, try goal-based
* Is "done" clearly definable? → If not, don't automate it yet
* Does work arrive on a schedule? → If yes, try time-based
* None of the above? → Stick with turn-based and improve your SKILL.md
The four loop types are composable building blocks, not mutually exclusive categories. The most sophisticated form (Proactive) is just /schedule + /goal + dynamic workflows + auto mode assembled together.
## Key takeaway
Mastering Fable 5 isn't about learning more commands or parameters — it's about changing your relationship with the model:
* From "supervising execution" to "guiding direction"
* From "decomposing steps" to "setting goals and acceptance criteria"
* From "cautious testing" to "bold ambition"
* From "checking output" to "demanding self-verification"
A good prompt isn't one with the most detailed instructions — it's one where **constraints are just enough, and trust is set to maximum**.
## References
* [宝玉: Context compaction thresholds](https://x.com/dotey/status/2108669008283402744) — Folo intake, October 9, 2026; practitioner advice, not an official default
* [Claude Code: How Claude Code works](https://code.claude.com/docs/en/how-claude-code-works#the-context-window) — context lifecycle and what compaction can lose
* [Claude Code: Best practices](https://code.claude.com/docs/en/best-practices#manage-context-aggressively) — `/context`, focused compaction, persistent instructions, and task separation
* [Thariq (Claude Code team): Tips for using Fable 5](https://x.com/dotey/status/2074019009226322078) — compiled by 宝玉 from Thariq's video
* [Thariq at AI Engineer World's Fair: Fable 5 talk (unhobbling + blind spots)](https://x.com/dotey/status/2074255513353642090) — four themes from the full presentation
* [Claude Code official: Loops design paradigm](https://x.com/shao__meng/status/2074290011282055656) — from prompts to loops
* [Tw93: 代码全由 AI 生成时代的可维护性](https://x.com/HiTw93/status/2094015568101921254) — 六个实践:架构分层、自动化测试、清理死代码、CI/CD、自动验证、重复工作 skill 化
* [Simon Willison: Agentic Engineering Patterns](https://x.com/shao__meng/status/2094027833505144919) — 从代码边际成本趋零出发的完整工程方法论
* [poteto: pstack Agent 工程完全指南](https://x.com/shao__meng/status/2099300148874707297) — 验证优先 + 监督比你聪明的人五技法
# Docker
Source: https://base.bangwu.me/env/docker
Docker containerization guide covering image building, container creation with port mapping, volume mounting for persistence, and CLI commands.
# Docker
Docker is an open-sourceapplication container engine,lets developers package apps and dependencies into portable containers。
## Installation
### Windows/Mac
Download [Docker Desktop](https://www.docker.com/products/docker-desktop/)
### Linux (Ubuntu)
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
```
## Basic Concepts
* **Image**: a read-only template containing the filesystem needed to run a container
* **Container**: a running instance of an image
* **Repository**: a place to store images, such as Docker Hub
## Common Commands
### Image Management
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Search Image
docker search nginx
# Pull Image
docker pull nginx:latest
# View Local Images
docker images
# Remove Image
docker rmi nginx:latest
# Build Image
docker built -t myapp:1.0 .
# Export Image
docker save -o nginx.tar nginx:latest
# Import Image
docker load -i nginx.tar
```
### Container Management
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Run容器
docker run -d --name mynginx -p 80:80 nginx
# Parameter Description:
# -d:后台Run
# --name:指定容器name
# -p:Port Mapping 宿主机端口:容器端口
# -v:挂载卷 宿主机路径:容器路径
# -e:设置Environment Variables
# --restart:重启Strategy(no/always/on-failure/unless-stopped)
# View Running Containers
docker ps
# View All Containers(Package括停止's )
docker ps -a
# Stop Container
docker stop mynginx
# Start Container
docker start mynginx
# Restart Container
docker restart mynginx
# Remove Container
docker rm mynginx
# Force Remove Running Container
docker rm -f mynginx
# Enter Container
docker exec -it mynginx bash
# View Container Logs
docker logs -f mynginx
# View Container Details
docker inspect mynginx
# View Container Resource Usage
docker stats
# Copy File to Container
docker cp file.txt mynginx:/path/
# Copy File from Container
docker cp mynginx:/path/file.txt ./
```
### Volume Management
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create Volume
docker volume create mydata
# View Volumes
docker volume ls
# View Volume Details
docker volume inspect mydata
# Remove Volume
docker volume rm mydata
# Clean Unused Volumes
docker volume prune
```
### Network Management
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# View Networks
docker network ls
# Create Network
docker network create mynet
# Delete Network
docker network rm mynet
# Connect Container to Network
docker network connect mynet mynginx
```
## Dockerfile
A Dockerfile is a text file used to build an image.
### Basic Structure
```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 基础镜像
FROM python:3.11-slim
# 设置工作目录
WORKDIR /app
# 设置Environment Variables
ENV PYTHONUNBUFFERED=1
# 复制file
COPY requirements.txt .
# 执行Command
RUN pip install --no-cache-dir -r requirements.txt
# 复制应用代码
COPY . .
# 暴露端口
EXPOSE 8000
# 启动Command
CMD ["python", "app.py"]
```
### Common directives
* FROM: specify the base image
* WORKDIR: set the working directory
* COPY: copy files into the image
* ADD: copy files, with support for URLs and automatic extraction
* RUN: execute commands during the build
* CMD: the default command run when the container starts
* ENTRYPOINT: the entry point, not replaced by normal `docker run` arguments
* ENV: set environment variables
* EXPOSE: declare ports
* VOLUME: define a data volume
* USER: specify the runtime user
* ARG:buildparameters
### Multi-stage Build
```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}}
# builtPhase
FROM node:18 AS builter
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run built
# RunPhase
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```
## .dockerignore
This works like `.gitignore`, excluding files that do not need to be copied into the image.
```
node_modules
.git
.env
*.log
__pycache__
.vscode
```
## Image Registry Mirror
### Configure image mirrors (Linux)
edit /etc/docker/daemon.json:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"registry-mirrors": [
"https://docker.mirrors.ustc.edu.cn",
"https://hub-mirror.c.163.com"
]
}
```
Restart Docker:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo systemctl daemon-reload
sudo systemctl restart docker
```
## Practical Tips
### Clean System
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 清理未使用's 容器、网络、镜像
docker system prune -a
# View磁盘占用
docker system df
```
### Auto-restart Containers
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker run -d --restart=always nginx
```
### Limit Resources
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 限制内存和CPU
docker run -d --memory="512m" --cpus="1.5" nginx
```
### View container IP
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name
```
## Common deployment examples
### Nginx
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker run -d \
--name nginx \
-p 80:80 \
-v /path/to/html:/usr/share/nginx/html \
nginx:alpine
```
### MySQL
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker run -d \
--name mysql \
-p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=password \
-v mysql_data:/var/lib/mysql \
mysql:8.0
```
### Redis
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker run -d \
--name redis \
-p 6379:6379 \
-v redis_data:/data \
redis:alpine \
redis-server --appendonly yes
```
### PostgreSQL
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker run -d \
--name postgres \
-p 5432:5432 \
-e POSTGRES_PASSWORD=password \
-v postgres_data:/var/lib/postgresql/data \
postgres:16
```
## References
* [Docker Official Docs](https://docs.docker.com/)
* [Docker Hub](https://hub.docker.com/)
* [Dockerfile Best Practices](https://docs.docker.com/develop/dev-best-practices/)
# Docker Compose
Source: https://base.bangwu.me/env/docker-compose
Docker Compose orchestration guide using YAML to define services, networks, and volumes for one-command multi-container application deployment.
# Docker Compose
Docker Compose is a tool for defining and running multi-container Docker applications through YAML service definitions.
## Installation
Docker Desktop already includes Docker Compose.
### Standalone Linux installation
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
# ValidationInstallation
docker-compose --version
```
## Basic commands
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 启动服务
docker-compose up -d
# 停止服务
docker-compose down
# View服务State
docker-compose ps
# ViewLog
docker-compose logs -f
# 重启服务
docker-compose restart
# Build Image
docker-compose built
# 执行Command
docker-compose exec service_name bash
```
## docker-compose.yml syntax
### Basic Structure
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
web:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html
restart: always
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: password
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:
```
### Common configuration fields
* `image`: image to use
* `build`: builtConfiguration
* `ports`: Port Mapping
* `volumes`: volume mounts
* `environment`: Environment Variables
* `depends_on`: Dependencies
* `networks`: network configuration
* `restart`: restart policy
* `command`: override the default command
## Common service configurations
## MySQL
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
mysql:
image: mysql:8.0
container_name: mysql
restart: always
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: mydb
MYSQL_USER: user
MYSQL_PASSWORD: password
TZ: Asia/Shanghai
volumes:
- mysql_data:/var/lib/mysql
- ./mysql/conf:/etc/mysql/conf.d
- ./mysql/init:/docker-entrypoint-initdb.d
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
- --default-authentication-plugin=mysql_native_password
volumes:
mysql_data:
```
## Redis
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
redis:
image: redis:7-alpine
container_name: redis
restart: always
ports:
- "6379:6379"
volumes:
- redis_data:/data
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf
command: redis-server /usr/local/etc/redis/redis.conf --appendonly yes
environment:
TZ: Asia/Shanghai
volumes:
redis_data:
```
## PostgreSQL
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
postgres:
image: postgres:16-alpine
container_name: postgres
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: mydb
PGDATA: /var/lib/postgresql/data/pgdata
TZ: Asia/Shanghai
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
```
## MongoDB
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
mongo:
image: mongo:7
container_name: mongodb
restart: always
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
TZ: Asia/Shanghai
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
```
## Nginx
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
nginx:
image: nginx:alpine
container_name: nginx
restart: always
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/conf.d:/etc/nginx/conf.d
- ./html:/usr/share/nginx/html
- ./nginx/logs:/var/log/nginx
- ./nginx/ssl:/etc/nginx/ssl
```
## Open WebUI
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
open-webui:
image: ghcr.io/open-webui/open-webui:main
container_name: open-webui
restart: always
ports:
- "3000:8080"
environment:
OLLAMA_BASE_URL: http://host.docker.internal:11434
WEBUI_SECRET_KEY: your-secret-key
volumes:
- open-webui:/app/backend/data
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
open-webui:
```
## Full web application stack
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: '3.8'
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- web
networks:
- webnet
web:
built: .
environment:
DATABASE_URL: postgres://user:password@db:5432/mydb
REDIS_URL: redis://redis:6379
depends_on:
- db
- redis
networks:
- webnet
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydb
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- webnet
redis:
image: redis:alpine
volumes:
- redis_data:/data
networks:
- webnet
networks:
webnet:
volumes:
postgres_data:
redis_data:
```
## Environment Variablesfile
Create a `.env` file:
```env theme={"theme":{"light":"github-light","dark":"github-dark"}}
MYSQL_ROOT_PASSWORD=root_password
MYSQL_DATABASE=mydb
REDIS_PASSWORD=redis_password
```
Use it in `docker-compose.yml` like this:
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
services:
mysql:
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
```
## Practical Tips
### View service logs
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# View所有服务Log
docker-compose logs -f
# View特定服务Log
docker-compose logs -f web
# View最后100行
docker-compose logs --tail=100 web
```
### Scale services
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 启动3个web服务实例
docker-compose up -d --scale web=3
```
### Rebuild only a specific service
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
docker-compose up -d --build web
```
### Clean up resources
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 停止并Remove Container、网络
docker-compose down
# 同时Remove Volume
docker-compose down -v
# 同时Remove Image
docker-compose down --rmi all
```
## Best Practices
1. **Use `.env` files** for sensitive information.
2. **Use named volumes** for persistent data.
3. **Define networks** to isolate services.
4. **Set `restart: always`** when high availability matters.
5. **Use `depends_on`** to declare dependencies.
6. **Add health checks**.
7. **Use `deploy.resources`** to limit resources when appropriate.
## References
* [Docker Compose Official Docs](https://docs.docker.com/compose/)
* [Compose fileSpecification](https://docs.docker.com/compose/compose-file/)
* [Awesome Compose](https://github.com/docker/awesome-compose)
# Editor extension supply chain
Source: https://base.bangwu.me/env/editor-extension-security
Treat VS Code, Cursor, and agent-tool extensions as code that runs with your user privileges: control auto-update, pin trusted sources, harden the machine, and clean up after a malicious release.
# Editor extension supply chain
An editor extension is not a theme or a settings file. In VS Code and its forks, such as Cursor, an extension runs in the **extension host** with the same permissions as the editor. It can read and write your files, make network requests, start processes, and change workspace settings. An extension update is effectively new code running on your machine, and it can reach your source code, SSH keys, cloud credentials, and agent tokens.
This page uses a real October 2026 incident to show where the trust boundaries are, then turns it into settings and a checklist.
For install-time scripts in JavaScript dependencies, see [npm supply chain](/env/npm-supply-chain). The trust model is the same; the delivery channel is different.
## Case study: a tampered Claude Code extension on Cursor's marketplace
> [!NOTE]
>
> The facts in this section were current as of October 31, 2026. Check the vendor notices under References at the end of this page for later updates.
**What happened.** On October 29, 2026, between about 2:27 AM and 1:35 PM PT, Cursor's VS Code Extension Marketplace served tampered builds of `Anthropic.claude-code` versions `2.1.312` and `2.1.313` for macOS and Windows. Anthropic did not build them. Microsoft and Anthropic said the Visual Studio Marketplace, Open VSX, and the npm package were not affected, and Cursor said it had no evidence that the official distribution was affected. Reports estimated up to about 5,000 affected users. Anthropic published its next legitimate release as `2.1.314` so the versions would not be confused.
**What the payload did.** Code prepended to `extension.js` ran as soon as the extension host loaded the module, before the extension's normal `activate` function. The user did not have to do anything. The payload:
1. Collected the hostname, username, OS, home and working directories, global Git email, public IP, and up to 40 environment variable **names** (not values) matching `KEY|TOKEN|SECRET|PASS|AWS|GCP`.
2. Appended an attacker SSH public key to `~/.ssh/authorized_keys`, then tried to enable the local SSH server.
3. Opened an outbound reverse tunnel (`ssh -N -R '*:0:localhost:22'`) so the attacker could reach the machine's port 22 without any inbound port being open.
4. Installed persistence outside the extension directory: a macOS LaunchAgent named `com.apple.sysmond`, a Linux `@reboot` cron entry, or a Windows scheduled task named `SysMon` with a Startup-folder fallback.
5. Sent the collected details to the attacker's server.
Bugs in the payload, plus the lack of admin rights on most machines, meant the SSH server usually did not start, so the tunnel often led nowhere. The SSH key, persistence, and host report could still land. Do not count on attacker bugs as a defense.
## Durable lessons
### An extension update runs code on your machine
Neither the marketplace nor the editor's permission model limits what an extension can do once it is installed. VS Code's `extensions.allowed` setting controls *which* extensions can be installed and enabled. Microsoft's documentation states that it does not limit an extension's runtime permissions. Plan as if every enabled extension can do anything your user account can do.
### A publisher label is not provenance
The tampered build appeared under a well-known publisher name, and many people assumed that meant Anthropic had signed it. A mirror or proxy marketplace is its own link in the trust chain. Cursor uses Open VSX behind its own proxy (`marketplace.cursorapi.com`) and notes that the same `publisher.extension` ID can point to a different publisher or different code on Open VSX than on the Microsoft Marketplace. Treat extension IDs the way you treat package names: confirm which registry your editor actually downloads from.
### Auto-update is the delivery path; a cooldown blunts it
The malicious versions were available for about 11 hours. Many affected machines received them through automatic updates, not deliberate installs. An install or update cooldown longer than the takedown window would probably have kept them out. A cooldown cannot stop a malicious release that stays up longer than the delay, but it removes the cheapest attack: a short-lived malicious upload.
### Uninstalling is not cleaning up
The payload wrote keys, scripts, and startup entries outside the extension folder. Removing or updating the extension does not undo them. Taking the attacker's server offline does not remove them from your machine either.
### Reverse tunnels avoid inbound checks
The machine connects *out* to the attacker. A firewall audit that only looks for open inbound ports will not find this. Successful logins through the tunnel show up in SSH logs as coming from `localhost`.
### Environment variable names are a target map
Collecting only variable names still tells an attacker which machines hold AWS, GCP, or API tokens and are worth a closer look. Keep long-lived secrets out of your global shell environment.
### The same model applies to agent plugins
Claude Code's documentation says the same about its plugins: hooks, monitors, MCP servers, and LSP servers run with your full user permissions and outside the sandbox. Auto-update can change the files you reviewed. The marketplace name tells you who publishes the catalog, not what each plugin does. Use the same rules for agent skills, plugins, and MCP servers.
## Harden a personal setup
1. **Keep the extension list short.** Remove extensions you do not use every week. Each enabled extension is a separate update channel into your machine.
2. **Delay automatic updates.** In VS Code, `extensions.autoUpdateDelay` sets how many hours to wait after a version is published before installing it automatically. It only applies when auto-update is on. VS Code's documentation lists a 12-hour default as of October 2026, but check your version. Pick a longer delay for extensions with broad access:
```jsonc theme={"theme":{"light":"github-light","dark":"github-dark"}}
// VS Code settings.json
{
"extensions.autoUpdateDelay": 72
}
```
In Cursor, set `extensions.installCooldownHours` in user settings when your team has not enforced a cooldown:
```jsonc theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Cursor settings.json
{
"extensions.installCooldownHours": 72
}
```
Clicking **Update** yourself skips the VS Code delay. Only do this when you have a reason.
3. **Pin high-risk extensions manually.** Right-click an extension and turn off **Auto Update**. Update it on purpose after the release has been out for a while. Extensions installed from a `.vsix` file have auto-update off by default.
4. **Install from the publisher's primary registry.** Check the publisher ID and verification badge, and use the publisher's own install link when one exists.
5. **Do not run the editor as administrator or root.** In this incident, the lack of admin rights was one reason the SSH server usually failed to start.
6. **Keep secrets out of global environment variables.** Prefer credential helpers, OS keychains, and short-lived tokens scoped to a project.
7. **Isolate agents and unfamiliar repositories.** Use a VM or dev container for agent runs and untrusted code. A container is only a boundary if it does not mount your home directory or the Docker socket.
## Harden a team setup
* **Allowlist extensions.** In VS Code, use `extensions.allowed` (1.96+) or the `AllowedExtensions` policy to allow by publisher, extension ID, exact version, or platform. `"stable"` blocks pre-release versions. Once you add allow rules, extensions that do not match any of them are blocked.
```jsonc theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"extensions.allowed": {
"microsoft": true,
"esbenp.prettier-vscode": true,
"rust-lang.rust-analyzer": "stable",
"dbaeumer.vscode-eslint": ["3.0.0"]
}
}
```
For local `.vsix` files, these rules check identifiers declared inside the package. They do not verify where the package came from.
* **Manage update timing centrally.** VS Code exposes `extensions.autoUpdate` and `extensions.autoUpdateDelay` as enterprise policies. In Cursor, team admins can set **Marketplace Install Cooldown (hours)** under **Team settings** → **Security & automation**. It defaults to `0` (disabled) and, when set, overrides each user's `extensions.installCooldownHours`.
* **Require signatures where the editor supports it.** Cursor Enterprise can require valid Open VSX signatures (**Require Extension Signature Verification**). The Visual Studio Marketplace signs every extension, and VS Code checks the signature at install time.
* **Host a private marketplace** when you need an approved, rehosted set of extensions, including for air-gapped networks.
* **Alert on behavior, not just hashes.** Useful signals from this incident:
* an editor helper process (`Code Helper`, `Cursor Helper`, and similar) writing `~/.ssh/authorized_keys`
* a non-Apple process creating a `com.apple.*` LaunchAgent, or a LaunchAgent that runs `/bin/sh` on a hidden script
* `ssh` or `autossh` started with `-R` from a user session
* local SSH logins from `127.0.0.1` or `::1`
## When an extension you use is reported malicious
1. **Confirm channel, version, and platform.** Find out which marketplace delivered your copy. Check the installed versions:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
code --list-extensions --show-versions
ls ~/.vscode/extensions ~/.cursor/extensions 2>/dev/null
```
2. **Check the vendor's indicators** before deleting anything. Preserve evidence, and isolate the machine if you find signs that the payload ran.
3. **Look outside the extension folder** for SSH keys, startup entries, and running processes:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cat ~/.ssh/authorized_keys # look for keys you did not add
ls ~/Library/LaunchAgents # macOS
crontab -l # Linux
ps aux | grep -E 'ssh .*-R|autossh' # active reverse tunnels
```
On Windows, check `%USERPROFILE%\.ssh\authorized_keys`, `C:\ProgramData\ssh\administrators_authorized_keys`, scheduled tasks, and the Startup folder.
4. **Remove persistence, unauthorized keys, and tunnel processes.** Then decide whether to rebuild the machine. Review vendor remediation scripts before you run them.
5. **Rotate credentials and revoke sessions from a different, trusted device.** Do this for anything the affected user account could reach.
6. **Do not treat an extension update or a server takedown as cleanup.** Confirm that the artifacts do not return after you log in again or restart.
## References
* [Folo source: 2026-10-31 Hacker News Top Stories (SuperTechFans)](https://supertechfans.com/cn/post/2026-10-31-HackerNews/)
* [Folo source: Solidot, Claude Code for VS Code extension backdoor](https://www.solidot.org/story?sid=85756)
* [Cursor: Security notice for Anthropic.claude-code 2.1.312 and 2.1.313](https://cursor.com/blog/claude-code-extension-security-notice)
* [Phorion: Official Claude Code extension compromise advisory](https://phorion.io/blog/offical-claude-code-vsx-compromise/)
* [Microsoft Security: Inside a malicious Claude Code-branded extension](https://www.microsoft.com/en-us/security/blog/2026/10/30/inside-malicious-claude-code-branded-cursor-extension-persistent-ssh-backdoor/)
* [Socket: Registry records for Claude Code 2.1.313](https://www.socket.dev/blog/claude-code-extension-compromise)
* [Hacker News: Anthropic clarification on affected channels](https://news.ycombinator.com/item?id=50304129)
* [VS Code docs: Extension runtime security](https://code.visualstudio.com/docs/configure/extensions/extension-runtime-security)
* [VS Code docs: Extension auto-update](https://code.visualstudio.com/docs/configure/extensions/extension-marketplace#_extension-auto-update)
* [VS Code docs: Manage extensions in enterprise environments](https://code.visualstudio.com/docs/enterprise/extensions)
* [microsoft/vscode #321039: configurable `extensions.autoUpdateDelay`](https://github.com/microsoft/vscode/pull/321039)
* [Cursor docs: Extensions, install cooldown, and signature verification](https://cursor.com/help/customization/extensions)
* [Claude Code docs: Plugin security and trust](https://code.claude.com/docs/en/plugins/security)
# Exam Records
Source: https://base.bangwu.me/env/exam
Company aptitude test and coding exam reviews with lessons learned, covering algorithm problems, aptitude sections, and practical test-taking tips.
## 2025-03-08 Meituan General Aptitude Test 【Project Management Intern】

The general aptitude test was roughly divided into four parts: language expression, mathematics, logical reasoning, and data analysis.
The written test itself was not too difficult. Since it was for a non-technical role, there were no algorithm problems. The online testing platform felt intimidating at first, though.
> Lessons Learned
1. Bring scratch paper for the math section—there was too much mental arithmetic this time.
2. Be very clear about what “year-over-year growth” means.
3. The formal process may require camera access, screen recording, phone mini-program monitoring, and an integrity pledge.
## 2025-03-09 Pinduoduo Algorithm Exam 【Server R\&D Intern】

This was my first algorithm test. I was not well prepared, my algorithm basics were weak, and I only solved the first easy problem out of four. It made me realize how many edge cases algorithm problems can involve.
> Lessons Learned
1. Bring a phone stand to film your upper body and screen if required.
2. It is much easier to switch to a local IDE for answering and debugging.
3. I need much more practice with ACM-style algorithm problems.
## 2025-03-09 Tencent Comprehensive Assessment 【Project Management Intern】

The questions focused on workplace decisions and project-conflict scenarios. It felt more like a personality assessment, and there probably were no standard answers.
> Lessons Learned
None.
## 2024-04-23 Huawei Algorithm Exam 【General Software Development】

The algorithm questions were quite hard. The first was about finding the minimum `k` numbers, the second was a binary-tree variant, and the third was a shortest-path problem. All of them were beyond me at the time, so I submitted early.
> Lessons Learned
None. I was in a poor mood recently and not very motivated for exams.
# Git at agent scale
Source: https://base.bangwu.me/env/git-at-scale
How Git stores and transfers history with objects, refs, and packfiles, why many concurrent agents strain a Git server, the trade-offs behind OpenAI's Pando backend, and what you can do on the client side today.
# Git at agent scale
Coding agents multiply Git traffic. One engineer can have several changes in CI at once, every push can start several jobs that fetch the same commit, and every agent sandbox needs a checkout. In late 2025, OpenAI's monorepo servers started falling behind: fetches and pushes slowed down, merges failed, and reliability at times dropped below 90%.
OpenAI's answer was **Pando**, a new Git-compatible backend. This page uses that design to explain how Git moves data and where a Git server becomes the bottleneck. It ends with what you can do on the client side without building your own backend.
## How Git stores history
A repository keeps two things in sync: **objects** and **refs**.
* **Objects** are content-addressed and immutable. A **blob** holds one file's content, a **tree** maps names to blobs and other trees, a **commit** points to a root tree and its parent commits, and a **tag** names an object. Changing one file creates a new blob and new trees up to the root. Unchanged files and directories reuse existing objects.
* **Refs** are names that point to commits, such as `refs/heads/main`. A commit on a branch creates a new commit object and moves the ref.
* Objects are stored **loose** (one file each) or in a **packfile**, where similar objects can be stored as deltas of each other.
You can see each layer locally:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git cat-file -p HEAD # commit: tree, parents, author
git cat-file -p 'HEAD^{tree}' # tree: names -> blob/tree IDs
git count-objects -v # loose vs packed objects
git ls-remote origin | wc -l # how many refs the server advertises
```
## How fetch and push move data
* **Fetch.** The client says which commits it **wants** and which it already **has**. The server walks everything reachable from the wanted commits, removes what the client already has, and sends the rest as a packfile. A full clone has nothing, so it receives everything reachable.
* **Push.** The server advertises its refs. The client leaves out objects the server already has and sends a pack that **depends on** existing server objects, so the pack alone isn't enough to rebuild the history.
* **Ref updates race.** Two pushes may try to move the same branch from the same old commit to different new ones. The server must accept one and reject the other.
That gives a Git server two kinds of load: **many writers** pushing to different branches, and **many readers** fetching the same history. Agents increase both at once.
## Three ways to scale a Git server
| Design | How writes are ordered | Where it struggles |
| - | - | - |
| **Replicas with three-phase commit** | Each push is copied to every replica, and a majority must agree on each ref update | Replica disks and network round trips sit on every push; writes slow down under load |
| **Shared write-ahead log in blob storage** | Packs upload in parallel, but every ref update appends to one manifest with compare-and-swap | All pushes compete for the same manifest; replicas must read and index new packs before they can serve them, so readers wait |
| **Pando: per-ref ordering** | Each branch is updated independently; packs are stored once and reused | Gives up a consistent point-in-time view of all refs |
Both conventional designs keep a **repository-wide order** of writes. That is what makes pushes to unrelated branches wait on each other.
## What Pando changed
Pando keeps the Git protocol and the Git client, so engineers and agents didn't change how they work. It relaxes two assumptions most Git servers make:
1. **No repository-wide snapshot.** Pando uses **causal consistency** per ref. A reader fetching a branch gets the history it needs for that revision, but a reader looking at several branches may see them at different moments. In practice, users and agents depend on the order of updates to one branch, not on a global order.
2. **No unique pack per client.** Generating a custom pack for every fetch costs CPU and disk. Pando serves stored packs again, even if a client downloads a few objects it already has.
How a push and a fetch work:
* **Push.** Pando streams the incoming pack to blob storage and validates it in one pass, without unpacking it into a local repository. A multi-key transaction then records a **ref version** (new tip, the pack that supplied it, earlier versions it depends on) and moves the ref pointer, so the pusher can immediately read its own write. This takes a constant number of metadata operations.
* **Fetch.** Pando picks the stored packs the client needs based on what it already has, with metadata reads that grow with the logarithm of the distance between the two versions. It returns pack URLs, and the client downloads them from regional caches.
* **Advertise only trunk.** On a push to a new branch, Pando advertises just the trunk branch instead of every ref. With millions of branches, a full ref advertisement alone can exceed 100 MiB. Advertising only trunk also makes the pushed pack reusable: any reader that has trunk can fetch the branch with that one pack. The cost is that repeated pushes to the same branch, or stacked branches, resend objects outside trunk. In OpenAI's monorepo, the median pack was still under 20 KiB and the 99th percentile under 3 MiB.
Because servers mostly negotiate and pick packs, they run on commodity hardware, and capacity grows by adding servers and scaling the metadata and blob stores. OpenAI reports that median push latency dropped by nearly 5× and that Pando serves close to a petabyte of Git data per day.
> [!NOTE]
>
> Pando is internal to OpenAI. The public repository is OpenAI's build of the Git client, not the backend. The numbers come from OpenAI's post, with no published baseline or hardware details.
## Durable lessons
* **Decide which consistency you really need.** A global snapshot of all refs is expensive, and most workflows only rely on ordering within one branch.
* **Measure push-to-fetch latency:** the time from one agent's push until another agent or a CI job can fetch that commit. That is the number agent collaboration waits on.
* **Make reads cacheable.** Serving the same bytes to many readers beats computing an optimal response for each one.
* **Keep the protocol, replace the backend.** Staying Git-compatible meant no migration for people, agents, or tools.
## What you can do today
Most teams will hit client-side limits long before they need a new server. Reduce what each agent and CI job downloads:
* **Blobless partial clone.** `git clone --filter=blob:none ` downloads commits and trees, and fetches file contents only when a checkout needs them.
* **Sparse checkout.** `git sparse-checkout set ...` keeps only the directories an agent needs in its working tree.
* **Scalar.** `scalar clone ` sets up a large-repository profile in one step: it clones only commits and trees, enables sparse checkout, registers background maintenance, and applies recommended config. Run `scalar register` on an existing clone.
* **Shared object store for parallel agents.** Give each agent a [Git worktree](/env/git-worktree) instead of a separate clone, so objects are fetched once.
* **Shallow CI checkouts.** Keep `actions/checkout`'s default `fetch-depth: 1` unless a job needs history; see [GitHub Actions](/env/github-workflow).
## References
* [Folo source: OpenAI News, Scaling Git at OpenAI](https://openai.com/index/scaling-git-at-openai)
* [The New Stack: OpenAI built itself a new Git backend, too](https://thenewstack.io/openai-pando-git-backend/)
* [Git docs: partial clone](https://git-scm.com/docs/partial-clone)
* [Git docs: git-sparse-checkout](https://git-scm.com/docs/git-sparse-checkout)
* [Git docs: scalar](https://git-scm.com/docs/scalar)
* [Pro Git: Git internals, Git objects](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects)
* [Pro Git: Transfer protocols](https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols)
# Git worktree
Source: https://base.bangwu.me/env/git-worktree
Use git worktree to check out multiple branches from one repository simultaneously for parallel feature work and multi-agent coding.
# Git worktree
`git worktree` lets one repository expose **multiple working directories at the same time**.
Instead of cloning the same repo again and again, you can keep one shared repository object store and open several branches in parallel.
This is especially useful when:
* you are fixing one bug while another feature is in progress
* you want a clean review branch without stashing current work
* multiple AI agents need isolated working directories
* you want to compare branches side by side
## Why use it instead of another clone
The main benefits are:
* faster than recloning
* less disk usage than multiple full clones
* one shared repository history and object database
* each worktree still gets its own `HEAD`, index, and working directory
In practice, it feels like “multiple checkouts from one repo”.
## The basic commands
### Create a new worktree from an existing branch
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree add ../docs-fix docs-fix
```
This creates a sibling directory `../docs-fix` and checks out branch `docs-fix` there.
### Create a new worktree and new branch in one step
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree add -b feature/browser-harness ../browser-harness
```
This is the most common pattern for new work.
### List all worktrees
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree list
```
### Remove a worktree
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree remove ../browser-harness
```
### Clean stale metadata
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree prune
```
Use `prune` when a worktree directory was deleted manually and Git still remembers it.
## A practical workflow
Imagine your main repository is in `~/code/project`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cd ~/code/project
git switch main
git pull
git worktree add -b feature/a ../project-feature-a
git worktree add -b fix/login-bug ../project-login-fix
```
Now you can:
* keep normal work in `project`
* do feature work in `project-feature-a`
* isolate a production fix in `project-login-fix`
This is a much cleaner workflow than repeatedly stashing, rebasing, and switching branches in one directory.
## Why it is useful for AI agents
For multi-agent coding, `git worktree` is often the simplest safe default.
Each agent can get:
* its own directory
* its own checked-out branch
* its own build artifacts and temp files
* much lower risk of stomping on another agent’s uncommitted changes
That makes worktree-based coordination much easier than sharing one checkout.
### A simple pattern
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree add -b agent/docs ../project-agent-docs
git worktree add -b agent/tests ../project-agent-tests
git worktree add -b agent/refactor ../project-agent-refactor
```
Then assign one worktree per task or per agent.
## Important rules
### 1. Do not check out the same branch in two worktrees
Git prevents most of this automatically, but the principle matters:
* one branch
* one active worktree
If two places both try to advance the same branch, you lose the isolation benefit.
### 2. Remove worktrees with Git when possible
Prefer:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree remove ../project-agent-docs
```
instead of deleting the folder directly.
If you do delete it manually, follow up with:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git worktree prune
```
### 3. Use worktree-specific config when needed
By default, the main `.git/config` is shared across worktrees.
If you need config that should exist only in one worktree, enable:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git config extensions.worktreeConfig true
```
Then set per-worktree values with:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
git config --worktree core.sparseCheckout true
```
This is useful when different worktrees need different sparse-checkout or local behavior.
## What is shared and what is separate
### Shared
* repository objects
* most refs
* normal repository history
* main config by default
### Separate per worktree
* `HEAD`
* index
* working directory contents
* some per-worktree refs and pseudorefs
* optional `config.worktree`
That split is the reason worktrees are both lightweight and practical.
## Good use cases
* parallel feature development
* hotfix branch alongside a bigger refactor
* multi-agent implementation lanes
* trying risky changes without disturbing the current checkout
* large repos where full reclones are wasteful
## When a full clone is still better
Use a separate clone instead if you need:
* a fully separate Git config and credential context
* different remotes or fork wiring
* total isolation for experiments
* to work across very different repository states independently
Worktrees are excellent for **same-repo parallelism**, not for every kind of isolation.
## Small but relevant Git 2.54 note
Today’s Git ecosystem update also included **Git 2.54**, which added a new experimental `git history` command for simpler history edits and made geometric repacking the default manual maintenance strategy.
That is useful context, but for day-to-day parallel work, `git worktree` is still the more immediately practical feature to master.
## References
* [Git documentation: git-worktree](https://git-scm.com/docs/git-worktree)
* [GitHub Blog: Highlights from Git 2.54](https://github.blog/open-source/git/highlights-from-git-2-54/)
# GitHub Actions
Source: https://base.bangwu.me/env/github-workflow
GitHub Actions CI/CD automation using YAML workflow files, covering structure, event triggers like push and pull_request, and deployment setups.
# GitHub Actions
GitHub Actions is GitHub’s CI/CD automation tool. It can automatically run workflows for building, testing, deployment, and more.
Public repositories are free to use, while private repositories come with a monthly free quota.
## Basic Concepts
* **Workflow**: an automated process made up of one or more jobs
* **Job(Task)**:a set of steps executed on the same runner
* **Step**: a single task, which can be either an action or a shell command
* **Action(Action)**:reusable smallest unit
* **Runner**: the server that executes the workflow
## Basic Syntax
Workflow configuration files use YAML and live in the `.github/workflows/` directory.
### Simplest workflow
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: Hello World
on: [push]
jobs:
built:
runs-on: ubuntu-latest
steps:
- name: Say hello
run: echo "Hello, World!"
```
### Complete example
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: CI
# 触发条件
on:
push:
branches: [ main, dev ]
pull_request:
branches: [ main ]
schedule:
- cron: '0 0 * * 0' # 每周日午夜
workflow_dispatch: # 手动触发
# Environment Variables
env:
NODE_VERSION: 18
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
```
## Trigger events
### Push Event
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
on:
push:
branches:
- main
- 'releases/**'
paths:
- '**.js'
- '!docs/**'
tags:
- v1.*
```
### Pull Request Event
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
on:
pull_request:
types: [opened, synchronize, reopened]
branches: [ main ]
```
### Scheduled tasks
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
on:
schedule:
- cron: '30 5 * * 1-5' # 工作日早上5:30
```
### Manual trigger
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
on:
workflow_dispatch:
inputs:
environment:
description: 'Environment to deploy'
required: true
default: 'staging'
type: choice
options:
- staging
- production
```
## Common actions
### Checkout code
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- uses: actions/checkout@v4
with:
fetch-depth: 0 # 获取完整History
```
### Set up Node.js
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
```
### Set up Python
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- uses: actions/setup-python@v4
with:
python-version: '3.11'
cache: 'pip'
```
### CachingDependency
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
```
### Upload build artifacts
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- uses: actions/upload-artifact@v3
with:
name: built-files
path: dist/
```
### Download build artifacts
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- uses: actions/download-artifact@v3
with:
name: built-files
path: dist/
```
## Automatically publish a release
### Create a release
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build
run: |
npm install
npm run built
- name: Create Release
uses: softprops/action-gh-release@v1
with:
files: dist/*
body: |
## Changes
- Feature 1
- Feature 2
draft: false
prerelease: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```
### automatically generates Release Notes
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
- name: Create Release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
generate_release_notes: true
```
## Self-hosted Runner
Self-hosted runners let you run workflows on your own servers.
### Add a runner
1. Go to **Repository Settings → Actions → Runners → New self-hosted runner**.
2. Follow the prompts to install and configure it on your server.
3. Start the runner.
### Installation(Linux)
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 创建目录
mkdir actions-runner && cd actions-runner
# Download
curl -o actions-runner-linux-x64-2.311.0.tar.gz -L \
https://github.com/actions/runner/releases/download/v2.311.0/actions-runner-linux-x64-2.311.0.tar.gz
# 解压
tar xzf ./actions-runner-linux-x64-2.311.0.tar.gz
# Configuration
./config.sh --url https://github.com/user/repo --token YOUR_TOKEN
# Run
./run.sh
# 作为服务Run
sudo ./svc.sh install
sudo ./svc.sh start
```
### Use a self-hosted runner
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
jobs:
built:
runs-on: self-hosted
steps:
- uses: actions/checkout@v4
- run: ./build.sh
```
### Label selection
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
jobs:
built:
runs-on: [self-hosted, linux, x64]
```
## Secrets management
### Add a secret
Settings → Secrets and variables → Actions → New repository secret
### Use a secret
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
steps:
- name: Deploy
env:
API_KEY: ${{ secrets.API_KEY }}
run: ./deploy.sh
```
## Matrix builds
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: [16, 18, 20]
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: npm test
```
## Conditional execution
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
steps:
- name: Only on main
if: github.ref == 'refs/heads/main'
run: echo "Main branch"
- name: Only on success
if: success()
run: echo "Previous steps succeeded"
- name: Always run
if: always()
run: echo "Cleanup"
```
## Practical examples
### Automatically deploy to a server
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: Deploy
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
cd /var/www/myapp
git pull
npm install
pm2 restart myapp
```
### Build and push Docker images
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: Docker Build
on:
push:
branches: [ main ]
jobs:
built:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: user/app:latest
```
### Code checks
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: Lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- run: npm install
- run: npm run lint
```
## Speed up CI without dropping checks
Coding agents write code faster than CI can verify it, so CI wait time becomes the bottleneck. The goal is to cut wait time without removing any check that protects a release. Work through these steps in order, and measure after each one.
The list also works as a prompt for a coding agent: have it measure first, apply the steps, and report before-and-after numbers.
### 1. Measure where the time goes
Split each job into three parts: **queued** (waiting for a runner), **setup** (checkout, toolchains, dependencies), and **work** (build and tests). Slow CI is often slow setup, not slow tests.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Last 50 runs of one workflow: job, created, started, completed
gh run list --workflow ci.yml --limit 50 --json databaseId --jq '.[].databaseId' |
while read -r id; do
gh api "repos/{owner}/{repo}/actions/runs/$id/jobs" \
--jq '.jobs[] | [.name, .created_at, .started_at, .completed_at] | @tsv'
done
```
`started_at` minus `created_at` is queue time. Each job's `steps` array has its own timestamps, so you can split setup from work the same way.
### 2. Cancel superseded PR runs, but never `main`
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
```
`github.head_ref` is only set for pull request events, so new pushes to the same PR share a group and cancel the older run. Pushes to `main` fall back to the unique `run_id`, so every commit on `main` still gets a full run. A group such as `${{ github.ref }}` would also cancel or replace queued `main` runs.
### 3. Skip docs-only changes without blocking merges
If a workflow is skipped by `paths`, `paths-ignore`, or branch filters, its required checks stay **Pending** and the PR cannot merge. A job skipped by an `if:` condition reports success. For required checks, let the workflow start and skip jobs instead:
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
jobs:
changes:
runs-on: ubuntu-latest
outputs:
code: ${{ steps.filter.outputs.code }}
steps:
- uses: actions/checkout@v4
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
code:
- 'src/**'
- 'tests/**'
- 'package*.json'
- '.github/workflows/**'
test:
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm test
```
### 4. Use the cache built into setup actions
* `actions/setup-node` caches when you set `cache: npm` (or `yarn`, `pnpm`).
* `actions/setup-go` caches by default.
* For Rust, use `Swatinem/rust-cache`.
Cache storage is 10 GB per repository by default. Entries not used for 7 days are deleted, and when the repository is full, the least recently used entries are evicted, which can cause thrashing. Don't cache what you won't restore.
Caches created by a `pull_request` run are scoped to that PR's merge ref, so other PRs can't reuse them. Run CI on `push` to `main` so PRs can restore a warm cache from the default branch.
### 5. Make a second build nearly free
Build twice locally. The second build should take almost no time. If it doesn't, something is defeating the cache. Common causes are a Dockerfile that copies the whole repository before installing dependencies, or a build script that watches a file that doesn't exist, so the target always looks stale.
```dockerfile theme={"theme":{"light":"github-light","dark":"github-dark"}}
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
```
### 6. Download tools instead of compiling them
`go install` and `cargo install` compile from source on every run. Download release binaries instead, or use an installer that fetches prebuilt binaries, such as `cargo binstall` or `taiki-e/install-action` for Rust tools.
### 7. Run independent jobs in parallel
Remove `needs:` entries that don't pass outputs or artifacts. Split the longest test suite across several machines with a matrix.
### 8. Save macOS runners for work that needs macOS
On the Free, Pro, and Team plans, standard GitHub-hosted runners allow at most 5 concurrent macOS jobs, shared by all your workflows. Move formatting, lint, and dependency audits that don't depend on the OS to `ubuntu-latest`.
### 9. Don't do the same work twice
Don't rerun a check that another job already ran. A frontend-only job doesn't need to restore the Rust cache.
### 10. Compare before and after
Push the changes, rerun the measurement from step 1, and compare the same jobs. Look for the next slowest phase and repeat.
## Best Practices
1. **Use caching** to speed up dependency installation.
2. **Use matrix builds** for multi-environment testing.
3. **Run jobs in parallel** when they are independent.
4. **Use `if` wisely** to save resources with conditional execution.
5. **Protect secrets** and never print them in logs.
6. **Prefer official actions** because they are more reliable and better maintained.
7. **Limit permissions** and grant only what each workflow needs.
8. **Have a CI fallback plan** — GitHub Actions outages happen regularly; consider self-hosted runners or a secondary CI platform.
## Platform Reliability Risk
GitHub Actions has experienced frequent outages in 2025–2026. Mitchell Hashimoto (creator of Vagrant and Terraform, GitHub user #1299 since 2008) announced in April 2026 that his open-source project **Ghostty** is leaving GitHub, primarily because of persistent CI/CD reliability issues:
> "I started marking each day with an X if GitHub outages affected my work. Nearly every day had an X."
> [!NOTE]
>
> When your CI/CD platform has regular outages that block you for hours, it becomes a productivity risk — not just an inconvenience. For serious projects, consider:
>
> * **Self-hosted runners** as a fallback (see the Self-hosted Runner section above)
> * **Alternative CI platforms** (CircleCI, Buildkite, Gitea Actions)
> * **Mirror your repo** to another platform so you can switch CI quickly
> * **Don't couple your entire workflow** to one platform's availability
### Mitigation Strategies
1. **Self-hosted runners** — Run workflows on your own infrastructure; unaffected by GitHub outages
2. **Multi-platform CI** — Mirror critical workflows to an alternative (CircleCI, Buildkite)
3. **Local testing first** — Run lint/typecheck/test locally before pushing; CI should be a gate, not a bottleneck
4. **Cache aggressively** — Reduce job duration so outages cause less blocked time
5. **Read-only GitHub mirror** — Keep your source on GitHub for discoverability, but host CI elsewhere
## References
* [GitHub Actions Official Docs](https://docs.github.com/actions)
* [Folo source: Tw93 on speeding up GitHub Actions CI](https://x.com/HiTw93/status/2116797957454401746)
* [GitHub Docs: Control the concurrency of workflows and jobs](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/control-the-concurrency-of-workflows-and-jobs)
* [GitHub Docs: Troubleshooting required status checks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/troubleshooting-required-status-checks)
* [GitHub Docs: Dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching)
* [GitHub Docs: Actions limits](https://docs.github.com/en/actions/reference/limits)
* [actions/setup-go: caching](https://github.com/actions/setup-go#caching-dependency-files-and-build-outputs)
* [Actions Marketplace](https://github.com/marketplace?type=actions)
* [Workflowsyntax](https://docs.github.com/actions/reference/workflow-syntax-for-github-actions)
# Image Hosting
Source: https://base.bangwu.me/env/imgbed
Image hosting setup using Qiniu cloud storage with CDN acceleration, covering bucket config, custom domain binding, PicGo upload, and WebP.
I eventually settled on an **object storage + CDN** image hosting setup. Right now I mainly use Qiniu object storage with CDN acceleration. The goal is not to be flashy—the point is to keep image management, access speed, and cost under control.
## Who this setup is for
* Anyone running a blog or knowledge base and needing long-term image hosting
* Anyone who wants to manage screenshots, cover images, and article illustrations in one place
* Anyone who wants relatively stable image URLs that are easy to reference over time
## My basic approach
1. **Storage layer**: object storage keeps the original images.
2. **Delivery layer**: CDN handles acceleration and HTTPS.
3. **Upload tools**: upload directly from local tools such as screenshot apps or image uploaders.
4. **Compression strategy**: treat screenshots and custom graphics differently to keep file sizes down.
## Related tools
1. [PicGo](https://picgo.github.io/PicGo-Doc/)
2. [ShareX](/apps/ShareX)
3. [CDN Configuration](/env/CDN)
## Practical tips
* Standardize naming and directory structure before doing large-scale uploads.
* Compress images before uploading whenever possible to save bandwidth and storage.
* Pay close attention to hotlink protection, traffic alerts, and billing thresholds.
# Environment & Deployment
Source: https://base.bangwu.me/env/index
Environment setup and deployment tools hub covering Docker, Compose, Caddy, Supervisor, GitHub Actions, Jupyter, CDN, and blog hosting guides.
When starting out with programming, you'll have many questions about environment configuration — what are environment variables? What is `pip`? With so many Linux distros, how do package managers work? This section addresses those questions, along with blog hosting and toolchain setup.
> [card] [Docker](/env/docker)
>
> Containerized deployment and app management.
> [card] [Docker Compose](/env/docker-compose)
>
> Multi-container orchestration and one-command deploy.
> [card] [Caddy](/env/Caddy)
>
> Modern web server with automatic HTTPS.
> [card] [Supervisor](/env/supervisor)
>
> Process daemon and background service management.
> [card] [CDN Setup](/env/CDN)
>
> Domestic/overseas split CDN architecture.
> [card] [Jupyter](/env/Jupyter)
>
> Interactive data analysis notebook.
> [card] [GitHub Workflow](/env/github-workflow)
>
> GitHub Actions CI/CD automation.
> [card] [npm supply chain](/env/npm-supply-chain)
>
> Review and lock down npm install scripts.
> [card] [Editor extension supply chain](/env/editor-extension-security)
>
> Control extension updates and clean up malicious releases.
> [card] [Browser Observability](/env/browser-observability)
>
> Debug browser automation with read-only CDP tracing.
> [card] [Git worktree](/env/git-worktree)
>
> Parallel checkouts for multi-branch and multi-agent work.
> [card] [Git at agent scale](/env/git-at-scale)
>
> How Git moves data, and how to scale it for many agents.
> [card] [Markdown](/env/markdown)
>
> Markdown writing tips and tools.
> [card] [Agent-ready docs](/env/agent-ready-docs)
>
> Make docs easier for AI agents to discover and read.
> [card] [Agent harness](/env/agent-harness)
>
> Design the runtime layer around AI agents.
> [card] [AI product evals](/env/ai-evals)
>
> Turn real failures into regression tests and calibrated judges.
> [card] [AI code review](/env/ai-code-review)
>
> Review AI-written code with layers, risk tiers, and reviewer evals.
> [card] [Claude Code patterns](/env/claude-code-patterns)
>
> Effective patterns for Claude Code Fable 5 and agent loops.
> [card] [Local LLM](/env/local-llm)
>
> Run capable models locally with llama.cpp.
> [card] [Beads](/env/beads)
>
> Structured task memory for coding agents.
## Blog Setup
> [card] [Fuwari](/env/Fuwari)
>
> Astro-based blog theme.
> [card] [Image Hosting](/env/imgbed)
>
> Qiniu OSS + DogeCloud CDN setup.
# Interview & Job Application
Source: https://base.bangwu.me/env/interview
Technical interview reviews, job application strategies, and lessons learned — covering algorithm rounds, system design, resume tips, and career advice.
# My interview experience
## 2025-03-11 ByteDance Test Development Intern
I reviewed testing and development topics intensively before the interview. Total duration: 30 minutes.
1. They drilled into my data visualization project, especially the difficult parts.
2. They asked about database table design, such as classroom tables and student course-selection tables.
3. They gave me an SQL problem: find the top 20 students by course score. I could not write it because I had forgotten too much MySQL.
4. There was a logic puzzle: among 27 balls, one is fake and has a different weight. How would you use a balance scale to find it, and how many weighings would it take? I vaguely remembered a similar 8-ball problem, but I still could not work it out.
5. There was also an algorithm problem about merging two sorted arrays. I panicked and almost wanted to use `sort` + `set`, which reminded me that I still need much more algorithm practice.
6. After the algorithm question, another interviewer returned to the ball puzzle and asked how the solution would change if the fake ball were known to be heavier. I still could not come up with a good approach.
7. In the Q\&A round, I asked what languages and frameworks ByteDance test development usually uses, and whether they build internal testing platforms. The answer was that there is no mandatory language and the platform work depends on actual needs.
The result was as bad as I expected. I answered poorly, and a one-hour interview ended after only 30 minutes. Still, it was my first interview, so it was a useful wake-up call. There is a lot to improve.
## 2025-04-17 Shanghai Yonyou Government Software Co. Implementation Consultant Intern
This interview also lasted about 30 minutes, and the whole experience felt a bit unexpected.
1. I gave a short self-introduction and then they asked about my project. At that point I realized the meeting recording was not turned on.
2. They asked what I had learned from data mining, deep learning, and management-related courses. Most of my answer was basic concepts, and it felt like the interviewer was not very familiar with the subject either.
3. They asked about the visualization project and even asked me what Vue was.
4. They asked which Python libraries I knew. I mentioned libraries I had studied on my own, such as `httpx`, `selenium`, and other common tools.
5. They asked about modeling competitions and their real-world applications. I answered honestly that they mostly solve specific problems and are not always directly applied in production.
6. They asked about Office skills—Word, PowerPoint, Excel—which made the interview feel much less technical.
7. They also asked about my class schedule and how long I would be available for an internship, mentioning the graduation certificate requirement for full-time conversion.
8. In the Q\&A round, they asked how enterprise projects are typically implemented. I guessed they might be referring to project management rather than SQL.
Overall, the interview felt strange. The interviewer gave me the impression of a very conservative programmer, almost like someone from a traditional state-owned enterprise environment. I also felt that my skill set did not match the role very well. My weak point was still SQL syntax, which I clearly need to review. On the positive side, I felt no pressure at all this time. Since it was my second interview, I was not nervous anymore. It almost felt like an HR screening round.
## Resume & Job Application Tips
Lee Robinson (Cursor team) reviews hundreds of resumes daily. Here are 11 concrete tips to make your application stand out in seconds:
### Group 1: Keep it clean
1. **One page only** — If you need more space, link to a personal website. Don't stack 10+ bullet points per role.
2. **No photo** — Professional content stays professional. Photos belong on external profiles, not on the resume itself.
3. **GitHub must exist, but don't decorate it** — Badges, animations, and large images are noise. Reviewers want to see code and project reasoning.
### Group 2: Your online presence
4. **Build a personal website** — 90% of applicants don't have one. Having one instantly sets you apart. It needs to feel intentional, not just a template.
5. **Polish your LinkedIn** — Programmers love X/Twitter, but when companies circulate resumes internally, they look at LinkedIn.
6. **Clean up your X/Twitter** — If you link it, make sure there's nothing too unfiltered. Obvious advice, but many people fail this.
### Group 3: Content that matters
7. **Tailor, don't spam** — For startups, university courses matter less. For FAANG-style companies, coursework might help pass automated filters. Adjust your resume for the target.
8. **Mention AI usage** — Not using AI for coding is now unusual. Even outside Cursor, this is an industry trend. Show you work with AI tools naturally.
9. **Quality over quantity in projects** — 3 deep, thoughtful projects beat 27 AI-generated boilerplate projects.
10. **Write cover letters and resumes yourself** — AI-generated boilerplate is instantly recognizable. Especially when applying to AI companies, it's painfully obvious. Use AI for inspiration, but write the final version yourself.
11. **Show personal interests** — Books you like, articles you wrote, films you enjoy. Hiring is ultimately about finding someone people want to work with. These are great icebreakers.
> [!TIP]
>
> The meta-lesson: reviewers spend seconds on each resume. Every element should either **establish competence** or **show you're a real person** — anything that does neither should be cut.
> [!NOTE]
>
> * [Lee Robinson: How to make your engineering job application stand out](https://x.com/leerob/status/2053316807316156417)
> * Chinese summary by [Twitter @dotey](https://x.com/dotey)
# Local LLM deployment
Source: https://base.bangwu.me/env/local-llm
A practical guide to running capable LLMs locally with llama.cpp, covering Qwen 3.6 27B setup, performance benchmarks, and model comparison for offline, private AI development.
# Local LLM deployment
Running a capable large language model on your own machine is no longer a research project. With open-weight models like Qwen 3.6 27B, you get mid-2025 frontier-level intelligence on a laptop or desktop GPU — offline, private, and under your control.
## Why run models locally
Cloud APIs are convenient, but they come with trade-offs:
* **No take-backs**: A cloud model can be deprecated, rate-limited, or taken down overnight — as Claude Fable 5 users learned in June 2026.
* **Privacy**: Sensitive code, medical data, or personal notes never leave your machine.
* **Cost at scale**: API credits are cheap now due to heavy subsidies. When the subsidy era ends, local models become the economical default for frequent use.
* **Customization**: You can fine-tune a local model for your domain, coding style, or project conventions.
## The current sweet spot: Qwen 3.6 27B
As of mid-2026, Qwen 3.6 27B is widely considered the first local model that delivers genuine general intelligence suitable for daily development work.
It comes in two variants:
| Variant | Architecture | Speed | Quality |
| - | - | - | - |
| Qwen 3.6 35B A3B | Mixture-of-Experts | \~105 tok/s (Mac M5) | Good |
| Qwen 3.6 27B | Dense | \~32 tok/s (Mac M5) | Better |
The dense 27B is recommended for quality-sensitive work. The MoE variant is 3× faster and still very capable, suitable for quick iterations.
### Intelligence level
On the Artificial Analysis index, Qwen 3.6 27B scores around mid-2025 frontier level:
| Model | Approximate Era | Equivalent |
| - | - | - |
| Gemma 4 31B | Late 2024 | o1 / Claude 3.5 Sonnet |
| Qwen 3.6 35B A3B | Early 2025 | o3 / Claude 4 Sonnet |
| **Qwen 3.6 27B** | **Mid 2025** | **GPT-5 / Claude Sonnet 4.5** |
| DeepSeek V4 Flash | Late 2025 | GPT-5.2 / Claude Opus 4.5 |
It significantly outperforms Gemma 4 31B (the previous local coding default) and approaches DeepSeek V4 Flash quality.
## Setup with llama.cpp
[llama.cpp](https://github.com/ggml-org/llama.cpp) is recommended over Ollama — it is direct, open, and gives you full control over quantization and inference parameters.
### 1. Download a quantized model
8-bit quantization halves model size with negligible quality loss. Popular GGUF sources:
* [unsloth/Qwen3.6-27B-MTP-GGUF](https://huggingface.co/unsloth/Qwen3.6-27B-MTP-GGUF) (with multi-token prediction support)
* [bartowski/Qwen\_Qwen3.6-27B-GGUF](https://huggingface.co/bartowski/Qwen_Qwen3.6-27B-GGUF)
### 2. Start the server
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
llama-server -hf unsloth/Qwen3.6-27B-MTP-GGUF:Q8_0 \
--spec-type draft-mtp -ngl 999 -fa on -c 65536 --port 8080
```
Flags explained:
* `-hf` — pull from Hugging Face (cached on subsequent runs)
* `--spec-type draft-mtp` — multi-token prediction for \~1.8× speedup
* `-ngl 999` — offload all layers to GPU
* `-fa on` — flash attention
* `-c 65536` — 64K context window (native is 256K)
Open `http://127.0.0.1:8080` to chat directly.
### 3. Connect your coding agent
For OpenCode, add to `~/.config/opencode/opencode.jsonc`:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"provider": {
"llama": {
"name": "llama.cpp (local)",
"npm": "@ai-sdk/openai-compatible",
"options": {
"baseURL": "http://127.0.0.1:8080/v1",
"apiKey": "local"
},
"models": {
"qwen3.6-27b": { "name": "Qwen3.6-27B Q8 +MTP" }
}
}
},
"model": "llama/qwen3.6-27b"
}
```
The same server works with Pi, Hermes, Claude Code (via custom base URL), and any OpenAI-compatible client.
## Performance reference
Measured on MacBook Max M5 128 GB with 8-bit quantization:
| Model | Engine | Tok/s | RAM |
| - | - | - | - |
| Qwen 3.6 35B A3B | llama.cpp + MTP | 105 | 45 GB |
| Qwen 3.6 27B | llama.cpp + MTP | 32 | 42 GB |
| Qwen 3.6 27B | llama.cpp (no MTP) | 18 | 41 GB |
| DeepSeek V4 Flash (Q2-Q4) | llama.cpp | 33 | 103 GB |
On consumer GPUs:
* **RTX 5090 32 GB**: Q6\_K quantization, \~50 tok/s at 123K context, \~28 GB VRAM
* **32 GB shared memory devices**: 4-bit quantization fits comfortably
For laptops, a Mac Mini M4 on the local network is a quieter, cheaper alternative to running models directly on a MacBook Pro (which gets hot and loud under sustained inference).
## When to use local vs. cloud
| Scenario | Recommendation |
| - | - |
| Sensitive or proprietary code | Local |
| Offline or air-gapped work | Local |
| High-volume batch processing | Local (no API costs) |
| Need absolute frontier intelligence | Cloud (Opus, GPT-5.5) |
| Quick one-off queries | Cloud (convenience) |
| Long-context projects (>128K) | Cloud (or aggressive quantization) |
## Model evaluation: benchmarks vs. real experience
A recurring pattern in open-weight model releases is the gap between benchmark scores and practical experience. Two data points from July 2026 make this impossible to ignore:
**Tencent Hy3** (295B total / 21B active MoE) explicitly noted in its model card:
> 模型的实用体验不完全与榜单成绩挂钩。基于广泛的用户反馈和分析,我们定位并优化了一系列体验向能力,获得了产品侧一致且积极的评价。
("The model's practical experience does not fully correlate with benchmark rankings.")
**Anthropic Opus 5 vs Fable 5**: Opus 5 beats Fable 5 on nearly every benchmark, yet anyone who has used both meaningfully can tell within minutes that Opus 5 is nowhere near Fable in practical coding and agent tasks. As one observer put it: "this can only mean our benchmarks are now almost completely useless."
The benchmarks are failing because they measure narrow task completion under clean conditions, while real-world usefulness involves dimensions they don't capture: instruction following consistency across long contexts, refusal calibration, output formatting reliability, tool use judgment, and the ability to recover from mid-task errors.
When evaluating any model for daily use, test it on your actual workflows rather than relying solely on leaderboard scores.
## Model architecture frontiers: diffusion language models
The dominant LLM architecture is autoregressive — generate tokens left to right, commit to each one, never go back. This creates a fundamental problem for agent workflows: when a tool call produces an error 50 tokens ago, the model can't edit that part of the output. It must either start over or push forward with incorrect context.
**Diffusion language models** take a different approach. Instead of generating sequentially, they refine the entire output in parallel passes. inclusionAI's **LLaDA2.2-flash** (July 2026) introduces the first diffusion model with explicit editing capability:
* **DELETE** and **INSERT** control tokens let the model actively remove and add content during generation
* The model can dynamically adjust sequence structure, enabling self-correction
* This is particularly valuable for multi-turn tool calling and long-horizon agent interactions
Current limitations: diffusion models still score significantly below similarly-sized autoregressive models on standard benchmarks. But the architectural advantage — the ability to edit mid-generation — addresses a limitation that no amount of scaling can fix in autoregressive models.
This is early-stage research, not a replacement for autoregressive models. But the direction matters: as agent workflows grow longer and more complex, the ability to revise rather than restart will become essential.
## System One models: AI as a typed if-statement
Not every in-process AI call needs a chat model. TypeSafe AI's **Jev** (September 2026) is a "System One" model: it gives up text generation and returns typed, calibrated decisions instead. Think of it as an intelligent `if` inside your code — classification, scoring, routing, extraction — with millisecond latency and a constrained output schema.
Why this exists: RLHF made chat models good at pleasing humans, but less reliable as silent automation. Jev is trained with RLCD (Reinforcement Learning for Calibrated Decisions) for that narrower job. Claimed characteristics:
* **70–500 ms** responses versus seconds-to-minutes for frontier chat models, because it samples outputs in parallel instead of token-by-token
* **Cheap at volume**: about \$0.042 per million input tokens, free output tokens
* **Zero type errors by construction** — the schema is part of the architecture, so it cannot emit unexpected prose
Use a System One model when you need judgment without expression: ticket routing, bulk labeling, real-time scoring, or a guardrail after a chat model. Keep the chat model for writing, planning, and tool-using agents. The two are complementary, not competitors.
Two harness patterns already use this split:
* **Route, then think.** LangChain-style loops ask many tiny questions ("is this hard?", "is this dangerous?"). Answer those with a System One model; send only hard work to a frontier model.
* **Choose, don't generate.** In computer use, let the driver enumerate legal actions and have Jev pick an ID. Cua's jev-use reported a 2048 demo about 5× faster and \~1000× cheaper than Astra — an ideal case with a fully observable keyboard task, not a guarantee for messy web UIs.
The category is already commoditizing downward. Liquid AI open-sourced **d1-3B** and **d1-omni-600M** (October 2026): Jev-style decision models, but multimodal — text, vision, and audio in, typed decisions out. \~8 ms per query on an RTX 4090, under 50 ms on a Jetson Orin Nano. When the judgment layer reaches millisecond latency on edge hardware, "ask a small model first" stops being an optimization and becomes the default shape of an agent loop — with the frontier model reserved for what actually needs depth.
## Industry: Anthropic enters the chip race
Anthropic has started early development of its own AI chips, seeking memory semiconductor supply from SK Hynix and reportedly in talks with Samsung for a custom project potentially using Samsung's 2nm process and advanced packaging. This follows OpenAI's earlier chip efforts and signals that frontier AI labs now see vertical integration into silicon as strategically necessary.
## What's next
The gap is closing fast. GLM 5.2 already delivers frontier-level open-weight intelligence, and the trend toward separating reasoning from factual knowledge will make future models even more efficient on consumer hardware.
## References
* [Qwen 3.6 27B is the sweet spot for local development](https://quesma.com/blog/qwen-36-is-awesome/) — setup guide, benchmarks, and real-world impressions
* [Will it Mythos?](https://swelljoe.com/post/will-it-mythos/) — Qwen 3.6 benchmark comparison
* [Simon Willison on Qwen 3.6 27B](https://simonwillison.net/2026/Apr/22/qwen36-27b/)
* [Tencent Hy3 on HuggingFace](https://huggingface.co/tencent/Hy3)
* [Opus 5 vs Fable 5: benchmarks are broken](https://x.com/oran_ge/status/2081501133168947412)
* [LLaDA2.2-flash: diffusion model with editing](https://huggingface.co/inclusionAI/LLaDA2.2-flash)
* [Anthropic developing own AI chips](https://readhub.cn/topic/8v2eHNj7g1m)
* [TypeSafe AI: Jev System One model](https://typesafe.ai) — typed, calibrated decisions instead of chat generation
* [LangChain + Jev harness](https://x.com/shao__meng/status/2100873142969536631) — 用 System One 做路由和护栏,旗舰模型只处理难活
* [Cua jev-use](https://x.com/shao__meng/status/2100870131324985740) — Computer Use 里让模型选择动作 ID,而不是生成动作
* [Liquid AI d1](https://huggingface.co/LiquidAI/d1-3B) — 开源多模态决策模型,RTX 4090 上 8ms,边缘硬件 50ms 以内
# Markdown Syntax
Source: https://base.bangwu.me/env/markdown
Markdown syntax reference covering headings, lists, links, images, code blocks, tables, blockquotes, and GFM extensions like task lists.
# Markdown syntax
Markdown is a lightweight markup language for formatting text. It is simple, easy to learn, and widely used for documents, blogs, and forums.
## Basic Syntax
### Headings
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 一级title
## 二级title
### 三级title
#### 四级title
##### 五级title
###### 六级title
```
### Emphasis
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
*斜体* 或 _斜体_
**粗体** 或 __粗体__
***粗斜体*** 或 ___粗斜体___
~~Removed线~~
```
Rendered output: *italic*, **bold**, ***bold italic***, ~~strikethrough~~
### list
#### Unordered lists
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
- 项目1
- 项目2
- 子项目2.1
- 子项目2.2
- 项目3
* 也可以用星号
+ 或者加号
```
#### Ordered lists
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
1. 第一项
2. 第二项
3. 第三项
1. 子项3.1
2. 子项3.2
```
### Link
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
[Link文本](https://example.com)
[带title's Link](https://example.com "鼠标悬停显示")
# 自动Link
# Reference式Link
[Link文本][ref]
[ref]: https://example.com
```
### Images
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}


# 图片Link
[](https://example.com)
```
### Blockquotes
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
> 这is一段Reference
> 可以有多行
> 多级Reference
>> 第二级
>>> 第三级
```
### Code
#### Inline code
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
使用 `反引号` Package裹代码
```
#### Code blocks
````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
```python
def hello():
print("Hello World")
```
```javascript
console.log("Hello World");
```
````
### Horizontal rules
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
---
***
___
```
***
### Tables
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
| Left aligned | Centered | Right aligned |
|:-------|:----:|-------:|
| Content 1 | Content 2 | Content 3 |
| 内容4 | 内容5 | 内容6 |
```
| Left aligned | Centered | Right aligned |
| :- | :-: | -: |
| Content 1 | Content 2 | Content 3 |
### Task lists
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
- [x] FinishedTask
- [ ] Unfinished task
- [ ] 另aTask
```
* [x] FinishedTask
* [ ] Unfinished task
### Footnotes
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
这is一段文字[^1]
[^1]: 这is脚注内容
```
## Github Flavored Markdown (GFM)
GitHub extends Markdown with several extra features.
### Syntax highlighting
````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
```python
def hello():
print("Hello")
```
````
### Emoji
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
:smile: :heart: :+1: :rocket:
```
:smile: :heart: :+1: :rocket:
[Emoji list](https://github.com/ikatyang/emoji-cheat-sheet)
### @mentions and issue references
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
@username
#123
```
### Automatic links
GitHub automatically converts URLs into links:
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
https://github.com
```
### Diff code blocks
````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
```diff
- Removed line
+ Added line
```
````
### Collapsible content
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
点击展开
This is hidden content
```
### Alert boxes (newer GitHub feature)
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
> [!NOTE]
> Useful information users should know.
> [!TIP]
> Suggestions that help users succeed.
> [!IMPORTANT]
> Critical information for successful use.
> [!WARNING]
> Urgent information that needs immediate attention.
> [!CAUTION]
> Potential negative consequences of an action.
```
### Mathematical formulas
Use LaTeX syntax:
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
行内公式:$E = mc^2$
块级公式:
$$
\sum_{i=1}^{n} i = \frac{n(n+1)}{2}
$$
```
### Mermaid diagrams
````markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
```mermaid
graph TD
A[开始] --> B{判断}
B -->|is| C[执行]
B -->|否| D[结束]
C --> D
```
````
## Advanced tips
### HTML embedding
Markdown also supports raw HTML directly:
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
Ctrl + C
高亮文本
```
### Escaping characters
Use backslashes to escape special characters:
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
\* 不is斜体
\# 不istitle
\[ 不isLink
```
### Anchor links
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
[跳转到title](#titlename)
# Chinese title会被转为拼音或其他形式
```
### Badges
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}


```
### Table of contents
```markdown theme={"theme":{"light":"github-light","dark":"github-dark"}}
[TOC]
# 某些Editor Supportautomatically generates目录
```
## Common tools
* **Editors**: Typora, VS Code, Obsidian
* **Online editors**: StackEdit, Dillinger
* **Formatting**: Prettier, markdownlint
* **Conversion**: Pandoc (Markdown to PDF/Word/HTML)
## Best Practices
1. **Keep it simple**: Markdown works best when it stays lightweight.
2. **Use headings well**: keep the hierarchy clear.
3. **Use code highlighting**: specify languages for better readability.
4. **Optimize images**: keep image sizes under control.
5. **Preview often**: check the rendered result after writing.
6. **Version control**: Markdown works very well with Git.
7. **Check links**: make sure all links work.
8. **Consider HTML for rich Agent output**: When AI agents generate long documents with tables, diagrams, and interactive elements, HTML may be more expressive than Markdown (see below).
## HTML vs Markdown for Agent Output
In the AI Agent era, the question of output format matters more than before. When agents write and modify documents, Markdown's core advantage — "easy to manually edit" — disappears. Should you switch to HTML?
### When Markdown is still the right choice
* **Short documents** (under \~100 lines) — Markdown remains the simplest format
* **Config files, READMEs, changelogs** — Git-friendly, easy to diff
* **Knowledge base pages** (like this site) — Mintlify/Jekyll render Markdown beautifully
* **Team wikis** — Where version control and collaborative editing are important
### When HTML has advantages
| Advantage | Example |
| - | - |
| **Information density** | Tables, SVG, CSS, charts, and images in one file — no ASCII art approximations |
| **Readability** | Tabs, illustrations, and responsive layouts for long documents |
| **Shareability** | Upload HTML, share link — colleagues open it without special tools |
| **Interactivity** | Sliders, buttons, form controls that feed back into the agent |
| **Multi-source data** | Agent reads code, Slack, Git history → produces unified HTML report |
| **Pleasure** | More engaging authoring experience for the human reviewer |
### Five practical use cases for HTML
1. **Planning & exploration** — Generate an "HTML file network": 6 directions side-by-side, then mockups, then an implementation plan
2. **Code review** — Render diff, inline annotations, and flow charts in one page
3. **Design prototyping** — HTML as design intermediate language, then translate to React/Swift
4. **Reports & learning** — Cross-source synthesis with interactive explanations or slides
5. **Disposable editors** — A throwaway UI for one task (reorder 30 tickets, toggle feature flags, adjust system prompt) with an "Export as JSON/prompt" button
### Tradeoffs
* **Generation time** — HTML takes 2–4× longer to generate than Markdown
* **Token cost** — Higher, but less relevant with 1M+ context windows
* **Version control** — **HTML diff is noisy and hard to review** — this is Markdown's biggest remaining advantage
* **Style consistency** — Requires a "design system HTML file" as reference to constrain aesthetics
> [!TIP]
>
> For knowledge bases and version-controlled docs, **Markdown is still the default**. Use HTML only when the output is a one-off report, a review artifact, or an interactive prototype — things that won't need Git diff review.
> [!NOTE]
>
> Based on [Thariq's analysis: HTML replacing Markdown in the Agent era](https://x.com/trq212) — 6 advantages, 5 use cases, and tradeoffs. Original article at [x.com/i/article/2052796100608974848](https://x.com/i/article/2052796100608974848).
## References
* [Markdown Guide](https://www.markdownguide.org/)
* [GitHub Markdown documentation](https://docs.github.com/zh/get-started/writing-on-github)
* [CommonMark Specification](https://commonmark.org/)
* [Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)
# npm supply chain
Source: https://base.bangwu.me/env/npm-supply-chain
Control npm install-time lifecycle scripts with allowScripts, approve-scripts, deny-scripts, and strict-allow-scripts to reduce package supply-chain risk.
# npm supply chain
npm packages can run lifecycle scripts during installation. That is useful for native builds, but it is also one of the most dangerous supply-chain surfaces in a JavaScript project.
The important shift in npm 11 is the `allowScripts` policy: instead of treating every dependency install script as implicitly trusted, you can record which packages are allowed to run scripts and which are denied.
## What counts as an install script
The npm policy covers dependency scripts that run while installing packages:
* `preinstall`
* `install`
* `postinstall`
* `prepare` for non-registry sources such as `git`, `file`, and `link` dependencies
It also matters for native packages that rely on implicit build behavior. A package with `binding.gyp` may trigger a `node-gyp rebuild` even if it does not declare an explicit `install` script.
## The project policy lives in `package.json`
Use `allowScripts` in `package.json` as team-wide policy:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"allowScripts": {
"esbuild@0.25.0": true,
"sharp": true,
"suspicious-package": false
}
}
```
Two useful styles:
* **Pinned approval**: `pkg@version`, safer for packages whose install behavior may change between versions.
* **Name-only approval**: `pkg`, less noisy but broader.
`npm approve-scripts` pins approvals by default. `npm deny-scripts` writes name-only denials because denying only one version would silently allow another version of the same package.
## Review pending scripts
Start with a read-only scan:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm approve-scripts --allow-scripts-pending
```
Then approve only packages that have a real reason to run install scripts:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm approve-scripts esbuild sharp
```
Deny packages that should not run scripts:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm deny-scripts suspicious-package
```
Commit the resulting `package.json` change so the decision is shared across local machines and CI.
## Make CI fail on unreviewed scripts
In npm 11.16.0, npm documents `allowScripts` as advisory by default: installs can still run scripts, but npm reports packages that are not covered by the policy. To turn policy drift into a build failure, enable strict mode in CI:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm ci --strict-allow-scripts
```
This makes any dependency with install scripts fail the install unless it is covered by `allowScripts`. Explicit denials are skipped.
If you are migrating a large repo, use a staged rollout:
1. Run `npm approve-scripts --allow-scripts-pending` locally.
2. Approve or deny the minimum set.
3. Commit `package.json`.
4. Add `npm ci --strict-allow-scripts` to CI.
5. Re-review whenever dependency versions change.
## Avoid the escape hatches by default
Do not reach for broad bypasses unless you are deliberately debugging a migration.
* `--ignore-scripts` blocks scripts globally, but may break packages that genuinely need native builds.
* `--dangerously-allow-all-scripts` bypasses the `allowScripts` policy entirely and is explicitly an escape hatch.
* Passing `--allow-scripts` to project-scoped install commands is not the team policy path; use `package.json` instead.
## Review checklist
Before approving a package, ask:
1. Does it really need a native build or install-time generation?
2. Is the package maintained and widely used?
3. Is the exact version pinned in the lockfile?
4. Can the script be avoided by using a prebuilt alternative?
5. Would this still be safe on a CI runner with secrets?
The last question is the most important. Install scripts often run before your app code, but with access to the developer or CI environment.
Editor extensions follow the same trust model through a different channel. See [Editor extension supply chain](/env/editor-extension-security).
## References
* [Folo source: npm allowScripts defaults discussion](https://x.com/wwwgoubuli/status/2067397155841868203)
* [npm docs: npm approve-scripts](https://docs.npmjs.com/cli/v11/commands/npm-approve-scripts)
* [npm docs: npm deny-scripts](https://docs.npmjs.com/cli/v11/commands/npm-deny-scripts)
* [npm docs: allow-scripts and strict-allow-scripts config](https://docs.npmjs.com/cli/v11/using-npm/config)
# Supervisor
Source: https://base.bangwu.me/env/supervisor
Supervisor is a Linux process manager for running and auto-restarting background services, covering installation, config files, and CLI usage.
# Supervisor process management
Supervisor is a Python-based process management tool for monitoring and controlling Unix/Linux processes on a system.
[Detailed tutorial blog post](https://bangwu.top/posts/supervisor)
## Overview
Supervisor can:
* start, stop, and restart processes automatically
* monitor process status and restart crashed processes automatically
* provide a web management interface
* record process output logs
* manage processes in groups
## Installation
### Ubuntu/Debian
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo apt update
sudo apt install supervisor
```
### CentOS/RHEL
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo yum install supervisor
```
### Python pip
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install supervisor
```
## Configuration File
Main configuration file location:
* Ubuntu: `/etc/supervisor/supervisord.conf`
* Per-program config files: `/etc/supervisor/conf.d/*.conf`
### Basic configuration structure
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:myapp]
command=/usr/bin/python /path/to/app.py ; 启动Command
directory=/path/to/ ; 工作目录
user=www-data ; Run用户
autostart=true ; 随supervisor启动
autorestart=true ; 自动重启
startsecs=10 ; 启动10秒后无Exception才认为成功
startretries=3 ; 失败重试次数
redirect_stderr=true ; redirectError输出
stdout_logfile=/var/log/myapp.log ; Logfile
stdout_logfile_maxbytes=50MB ; Logfile大小
stdout_logfile_backups=10 ; LogBackup数量
environment=PATH="/usr/local/bin" ; Environment Variables
```
## Common Commands
### Manage the Supervisor service
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 启动 supervisor
sudo systemctl start supervisor
# 停止 supervisor
sudo systemctl stop supervisor
# 重启 supervisor
sudo systemctl restart supervisor
# ViewState
sudo systemctl status supervisor
# 开机自启
sudo systemctl enable supervisor
```
### Manage processes
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 重新加载Configuration
sudo supervisorctl reread
sudo supervisorctl update
# 启动程序
sudo supervisorctl start myapp
# 停止程序
sudo supervisorctl stop myapp
# 重启程序
sudo supervisorctl restart myapp
# View所有程序State
sudo supervisorctl status
# View特定程序State
sudo supervisorctl status myapp
# 启动所有程序
sudo supervisorctl start all
# 停止所有程序
sudo supervisorctl stop all
# 重启所有程序
sudo supervisorctl restart all
# ViewLog
sudo supervisorctl tail myapp
sudo supervisorctl tail -f myapp # 实时View
# 清空Log
sudo supervisorctl clear myapp
```
## Configuration examples
### Python web app
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:flask_app]
command=/usr/bin/python3 /home/user/app/run.py
directory=/home/user/app
user=www-data
autostart=true
autorestart=true
startsecs=5
startretries=3
redirect_stderr=true
stdout_logfile=/var/log/supervisor/flask_app.log
environment=FLASK_ENV="production",SECRET_KEY="your-secret"
```
### Node.js app
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:nodejs_app]
command=/usr/bin/node /home/user/app/server.js
directory=/home/user/app
user=nodejs
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/supervisor/nodejs_app.log
environment=NODE_ENV="production"
```
### Celery Worker
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:celery_worker]
command=/home/user/venv/bin/celery -A myapp worker --loglevel=info
directory=/home/user/myapp
user=celery
numprocs=1
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=600
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/var/log/celery/worker.log
```
### Process groups
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[group:myproject]
programs=web,worker,beat
priority=999
[program:web]
command=/usr/bin/gunicorn myapp:app
...
[program:worker]
command=/usr/bin/celery worker
...
[program:beat]
command=/usr/bin/celery beat
...
```
## Web interface
Enable the web management interface:
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[inet_http_server]
port=127.0.0.1:9001
username=admin
password=password
```
Visit:[http://localhost:9001](http://localhost:9001)
## Environment Variables
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:myapp]
command=/usr/bin/python app.py
environment=
PATH="/usr/local/bin",
DATABASE_URL="postgresql://localhost/db",
SECRET_KEY="secret"
```
## Log Management
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:myapp]
stdout_logfile=/var/log/myapp/stdout.log
stdout_logfile_maxbytes=50MB ; 单个file最大50MB
stdout_logfile_backups=10 ; 保留10个Backup
stderr_logfile=/var/log/myapp/stderr.log
stderr_logfile_maxbytes=50MB
stderr_logfile_backups=10
```
## Graceful shutdown
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:myapp]
stopsignal=TERM ; 停止信号
stopwaitsecs=10 ; 等待10秒后强制杀死
stopasgroup=true ; 停止整个进程组
killasgroup=true ; 杀死整个进程组
```
## Multi-process management
```ini theme={"theme":{"light":"github-light","dark":"github-dark"}}
[program:worker]
command=/usr/bin/python worker.py
process_name=%(program_name)s_%(process_num)02d
numprocs=4 ; 启动4个进程
autostart=true
autorestart=true
```
## Troubleshooting
### ViewLog
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# supervisor 主Log
sudo tail -f /var/log/supervisor/supervisord.log
# 程序Log
sudo tail -f /var/log/supervisor/myapp.log
# 使用 supervisorctl View
sudo supervisorctl tail -f myapp
```
### FAQ
1. **Process fails to start**
* Check whether the command path is correct
* Check user permissions
* ViewLogfile
2. **Process restarts too often**
* Increase the `startsecs` value
* Check whether the program itself has an issue
3. **Configuration does not take effect**
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
sudo supervisorctl reread
sudo supervisorctl update
```
## Best Practices
1. **Separate config files**: use one config file per program.
2. **Set reasonable log sizes** to avoid filling up the disk.
3. **Use dedicated users** for better security.
4. **Use process groups** for easier batch management.
5. **Use environment variables** to separate config from code.
6. **Add alerting** by integrating with monitoring systems.
7. **Back up configurations regularly** and keep them under version control.
## Alternatives
* **systemd**: Linux service management
* **PM2**: Node.js process manager
* **circus**: Python process management
* **monit**: system monitoring and process management
## References
* [Supervisor Official Docs](http://supervisord.org/)
* [Configuration file reference](http://supervisord.org/configuration.html)
* [Detailed blog tutorial](https://bangwu.top/posts/supervisor)
# Next.js
Source: https://base.bangwu.me/frontend/Nextjs/index
Next.js is a React full-stack framework by Vercel with SSR, SSG, and API Routes, covering project setup, file-system routing, and data fetching.
## Next.js
Next.js is one of the most popular React frameworks in recent years, developed and maintained by Vercel.
### Core Features
* **Hybrid rendering**: supports SSR, SSG, and ISR
* **File-based routing**: automatic routing built on the file system
* **API Routes**: built-in API endpoints
* **Performance optimizations**: automatic code splitting and image optimization
* **TypeScript**: first-class TypeScript support
* **Zero config**: sensible defaults out of the box
### Quick Start
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 创建新项目
npx create-next-app@latest my-app
cd my-app
# 启动开发服务器
npm run dev
# Visit http://localhost:3000
```
### Project structure
```
my-app/
├── app/ # App Router(推荐)
│ ├── layout.tsx # 根布局
│ ├── page.tsx # Home
│ └── api/ # API 路由
├── public/ # 静态资源
├── components/ # Component
├── lib/ # Tool函数
└── next.config.js # Next.js Configuration
```
### App Router(Next.js 13+)
#### Pages & Layouts
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
// app/page.tsx - Home
export default function Home() {
return
Welcome to Next.js
}
// app/layout.tsx - 根布局
export default function RootLayout({ children }) {
return (
{children}
)
}
// app/about/page.tsx - /about 路由
export default function About() {
return
```
## Best Practices
1. **Combine with Tailwind**: DaisyUI components work well with Tailwind utility classes.
2. **Keep themes consistent** across the whole project.
3. **Use Tailwind responsive prefixes** for responsive design.
4. **Avoid unnecessary customization** and start with presets.
5. **Load on demand** by configuring PurgeCSS to remove unused styles.
## References
* [DaisyUI website](https://daisyui.com/)
* [Componentdocumentation](https://daisyui.com/components/)
* [Theme list](https://daisyui.com/docs/themes/)
* [GitHub repository](https://github.com/saadeghi/daisyui)
# Frontend
Source: https://base.bangwu.me/frontend/index
Frontend development notes covering Vue 3 with Naive UI, Next.js React framework with SSR/SSG, Tailwind CSS utility classes, and DaisyUI.

Frontend development builds user interfaces and experiences, covering the visual part of web applications.
> [card] [Vue](/frontend/Vue/index)
>
> Progressive JavaScript framework with Composition API.
> [card] [Next.js](/frontend/Nextjs/index)
>
> React full-stack framework with SSR/SSG/API Routes.
> [card] [TanStack + Hono](/frontend/tanstack)
>
> Full-stack monorepo — SSR + type-safe API server.
> [card] [SolidJS + Tauri](/frontend/solidjs)
>
> Local-first desktop apps — reactive UI + Rust shell.
> [card] [CSS Tools](/frontend/TailwindCSS/index)
>
> Tailwind CSS and DaisyUI component library.
> [card] [UnoCSS](/frontend/tanstack#styling-unocss)
>
> Utility-first CSS with icon presets — lighter than Tailwind.
## Core Tech Stack
| Tech | Purpose | Description |
| - | - | - |
| HTML | Page structure | Defines the skeleton |
| CSS | Styling & layout | Colors, fonts, spacing |
| JavaScript | Interactivity | Dynamic features & events |
## Learning Path
1. **Foundation**: HTML / CSS / JavaScript + DOM & events + ES6+ features
2. **Intermediate**: Frontend framework (Vue / React) + TypeScript + build tools
3. **Advanced**: Performance optimization + engineering practices + cross-platform
# SolidJS + Tauri Desktop
Source: https://base.bangwu.me/frontend/solidjs
Building local-first desktop apps with SolidJS for reactive UIs and Tauri v2 for the Rust shell, based on OnlyWrite project experience.
# SolidJS + Tauri Desktop Development
SolidJS is a truly reactive UI framework — no virtual DOM, no diffing. Tauri v2 wraps your web frontend in a Rust shell for native desktop packaging. Together they create fast, lightweight desktop apps.
> [card] [OnlyWrite](https://github.com/markbang/OnlyWrite)
>
> A local-first writing app built with SolidJS + Tauri 2 + TypeScript.
## Why SolidJS + Tauri?
| Concern | SolidJS | React/Vue |
| - | - | - |
| Rendering | True reactivity (no VDOM) | Virtual DOM diffing |
| Bundle size | \~7KB | \~40KB+ (React) |
| Update granularity | Fine-grained (per signal) | Component-level |
| Desktop shell | Tauri (Rust, \~3MB binary) | Electron (\~150MB) |
| Memory footprint | Low | High |
## Project Structure
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
onlywrite/
├── src/ # SolidJS frontend
│ ├── components/ # UI components
│ │ ├── writing-area.tsx
│ │ ├── file-browser.tsx
│ │ ├── theme-toggle.tsx
│ │ ├── language-toggle.tsx
│ │ └── s3-config-dialog.tsx
│ ├── routes/ # File-based routing
│ │ ├── __root.tsx # Root layout
│ │ ├── index.tsx # Home page
│ │ ├── dashboard.tsx # Main workspace
│ │ └ login.tsx # Auth gate
│ ├── lib/
│ │ ├── i18n.ts # Bilingual support
│ │ ├── markdown.ts # Markdown parsing
│ ├── index.tsx # App entry
├── src-tauri/ # Rust backend
│ ├── Cargo.toml
│ ├── capabilities/ # Tauri permissions
│ ├── tauri.conf.json # App configuration
├── test/ # Vitest + Playwright
├── package.json
└── tsconfig.json
```
## Tech Stack
| Layer | Technology | Purpose |
| - | - | - |
| Frontend | SolidJS 1.9 | Reactive UI |
| Styling | Tailwind CSS 4 | Utility classes |
| Icons | Lucide Solid | Icon components |
| Markdown | marked + DOMPurify | Parsing + sanitization |
| Desktop | Tauri 2 | Rust shell, file system access |
| Testing | Vitest + Playwright | Unit + E2E tests |
| Build | Vite 7 | Dev server + bundling |
## SolidJS Reactivity Patterns
SolidJS uses signals and derived computations — no hooks, no re-renders:
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { createSignal, createEffect, createMemo } from "solid-js"
function WritingArea() {
const [content, setContent] = createSignal("")
const [mode, setMode] = createSignal<"edit" | "render" | "split">("edit")
// Derived value — recomputes only when content changes
const renderedHtml = createMemo(() => parseMarkdown(content()))
// Effect — runs when mode changes
createEffect(() => {
localStorage.setItem("last-mode", mode())
})
return (
{mode() === "edit" &&
)
}
```
> [!TIP]
>
> In SolidJS, signals update *exactly* the DOM nodes that read them — no component re-render, no VDOM diff. This makes real-time editors feel instant.
## File-Based Workspace
For a local-first writing app, files live on disk, not in a database:
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { createSignal } from "solid-js"
// Tauri file system API
import { readTextFile, writeTextFile } from "@tauri-apps/api/fs"
const [currentFile, setCurrentFile] = createSignal(null)
const [content, setContent] = createSignal("")
async function openFile(path: string) {
const text = await readTextFile(path)
setCurrentFile(path)
setContent(text)
}
async function saveFile() {
if (!currentFile()) return
await writeTextFile(currentFile()!, content())
}
```
> [!NOTE]
>
> Using Tauri's `fs` API gives direct file system access from JavaScript — no server needed. The Rust side handles permission gating through the `capabilities/` config.
## Bilingual UI (i18n)
Simple signal-based i18n without heavy libraries:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/lib/i18n.ts
import { createSignal } from "solid-js"
type Locale = "en" | "zh"
const [locale, setLocale] = createSignal(
(localStorage.getItem("locale") as Locale) ?? "en"
)
const translations = {
en: {
"app.title": "OnlyWrite",
"file.open": "Open File",
"file.save": "Save",
"mode.edit": "Edit",
"mode.render": "Render",
"mode.split": "Split View",
},
zh: {
"app.title": "OnlyWrite",
"file.open": "打开文件",
"file.save": "保存",
"mode.edit": "编辑",
"mode.render": "渲染",
"mode.split": "分屏",
},
}
export function t(key: string) {
return translations[locale()][key] ?? key
}
export { locale, setLocale }
```
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/components/language-toggle.tsx
import { locale, setLocale } from "../lib/i18n"
export function LanguageToggle() {
return (
)
}
```
## S3 Image Upload
Optional S3 integration for image uploads — configured via dialog, not hardcoded:
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src/components/s3-config-dialog.tsx
import { createSignal } from "solid-js"
import { invoke } from "@tauri-apps/api/core"
const [s3Config, setS3Config] = createSignal({
endpoint: "",
bucket: "",
accessKey: "",
secretKey: "",
})
async function uploadImage(file: File) {
const result = await invoke("upload_to_s3", {
config: s3Config(),
filePath: file.path,
})
return result // Returns the URL
}
```
## Tauri Configuration
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src-tauri/tauri.conf.json
{
"productName": "OnlyWrite",
"version": "0.2.0",
"identifier": "com.onlywrite.app",
"app": {
"windows": [
{ "title": "OnlyWrite", "width": 900, "height": 640 }
]
}
}
```
### Capabilities (Permission Gating)
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
// src-tauri/capabilities/desktop.json
{
"identifier": "desktop",
"permissions": [
"core:default",
"fs:default",
"fs:allow-read-text-file",
"fs:allow-write-text-file",
"dialog:allow-open",
"dialog:allow-save"
]
}
```
> [!NOTE]
>
> Tauri v2 uses a capability-based permission system. Each capability file explicitly lists which APIs the frontend can call. This prevents unauthorized file access or system calls.
## Autosave Pattern
Combine SolidJS reactivity with debounced saves:
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
const [content, setContent] = createSignal("")
let saveTimer: number | null = null
createEffect(() => {
const text = content()
if (saveTimer) clearTimeout(saveTimer)
saveTimer = setTimeout(() => {
if (currentFile()) writeTextFile(currentFile()!, text)
}, 2000) // 2-second debounce
})
```
## Best Practices
1. **Signals over state** — SolidJS signals are fine-grained; avoid "lifting" state like React
2. **Local-first** — Read/write files directly via Tauri `fs` API, no backend server needed
3. **Capability gating** — Restrict Tauri API access through `capabilities/` config files
4. **Simple i18n** — Signal-based dictionary lookup is enough for bilingual apps
5. **Autosave with debounce** — Write to disk after a short idle period, not on every keystroke
6. **DOMPurify for HTML** — Always sanitize rendered markdown HTML
## References
* [SolidJS Docs](https://www.solidjs.com/)
* [Tauri v2 Docs](https://v2.tauri.app/)
* [OnlyWrite repo](https://github.com/markbang/OnlyWrite)
# TanStack Start + Hono
Source: https://base.bangwu.me/frontend/tanstack
Full-stack monorepo architecture combining TanStack Start SSR with Hono API server, covering file-based routing, tRPC contracts, Drizzle ORM, and auth setup.
# TanStack Start + Hono Full-Stack Architecture
TanStack Start is a full-stack React framework with SSR, file-based routing, and server functions. Hono is an ultrafast, lightweight web framework that runs on any JavaScript runtime. Combining them in a monorepo gives you a modern, type-safe full-stack stack.
> [card] [badmin](https://github.com/markbang/badmin)
>
> Admin panel — TanStack Start + Hono + Drizzle + SQLite.
> [card] [cyop](https://github.com/markbang/cyop)
>
> AI captioning platform — TanStack Router + Hono + tRPC + Drizzle + Postgres.
## Architecture Overview
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
monorepo/
├── apps/
│ ├── web/ # TanStack Start (React + SSR)
│ ├── server/ # Hono API server
│ └── docs/ # Fumadocs documentation site
├── packages/
│ ├── contracts/ # Shared Zod schemas + tRPC routers
│ ├── ui/ # Shared UI components (shadcn/ui)
│ ├── db/ # Drizzle schema + migrations
│ └── auth/ # Better Auth configuration
```
## Frontend: TanStack Start
TanStack Start provides file-based routing with `@tanstack/react-router`, SSR via Vinxi, and full-stack server functions.
### Key Setup
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/web/package.json
{
"dependencies": {
"@tanstack/react-start": "latest",
"@tanstack/react-router": "latest",
"@tanstack/router-plugin": "latest"
}
}
```
### Route Configuration
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/web/app/routes/__root.tsx
import { createRootRoute, Outlet } from "@tanstack/react-router"
export const Route = createRootRoute({
component: RootLayout,
})
function RootLayout() {
return (
)
}
```
### Server Functions
TanStack Start supports server-side functions that run only on the server:
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/web/app/routes/dashboard.tsx
import { createServerFn } from "@tanstack/react-start"
import { authMiddleware } from "../middleware"
export const getDashboardData = createServerFn({ method: "GET" })
.middleware([authMiddleware])
.handler(async () => {
return await db.query.dashboardStats()
})
```
> [!TIP]
>
> Use server functions for data fetching and mutations that need server-side execution. They automatically handle serialization and avoid leaking secrets to the client.
## Backend: Hono
Hono is the API layer — fast, type-safe, and runtime-agnostic. It handles auth, CRUD, and business logic.
### Basic Server Setup
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/server/src/app.ts
import { Hono } from "hono"
import { cors } from "hono/cors"
import { logger } from "hono/logger"
import { sessionMiddleware } from "./middleware/session"
import { authRoutes } from "./modules/auth/auth.routes"
import { userRoutes } from "./modules/users/users.routes"
const app = new Hono()
app.use("*", logger())
app.use("*", cors({ origin: ["http://localhost:3000"], credentials: true }))
app.use("/api/*", sessionMiddleware(authService))
app.route("/api/auth", authRoutes)
app.route("/api/users", userRoutes)
export default app
```
### Service Pattern
Use factory functions for dependency injection:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/server/src/modules/auth/auth.service.ts
interface AuthServiceOptions {
userRepository: AuthUserRepository
hashPassword: (password: string) => Promise
verifyPassword: (password: string, hash: string) => Promise
}
export function createAuthService(options: AuthServiceOptions) {
return {
async login(input: LoginInput) {
const user = await options.userRepository.findForAuthByEmail(input.email)
if (!user) throw new HTTPException(401, { message: "Invalid credentials" })
const valid = await options.verifyPassword(input.password, user.passwordHash)
if (!valid) throw new HTTPException(401, { message: "Invalid credentials" })
await options.userRepository.touchLastLogin(user.id)
return toAuthSession(user)
},
}
}
```
> [!NOTE]
>
> Factory functions (`createXxxService`) give you explicit dependency injection without class boilerplate. Each service receives its dependencies as parameters, making testing trivial — just pass mock implementations.
### Session Cookie Auth
Instead of JWT tokens, use signed session cookies for simplicity and security:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/server/src/middleware/session.ts
import { getSignedCookie, setSignedCookie, deleteCookie } from "hono/cookie"
const SESSION_COOKIE = "app_session"
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
export async function setSessionCookie(ctx: Context, userId: string, version: number) {
await setSignedCookie(ctx, SESSION_COOKIE, `${userId}:${version}`, secret, {
httpOnly: true,
maxAge: COOKIE_MAX_AGE,
sameSite: "Lax",
secure: isProduction,
})
}
export function requireSession(authService: AuthService) {
return createMiddleware(async (c, next) => {
const value = await getSignedCookie(c, secret, SESSION_COOKIE)
if (!value) throw new HTTPException(401, { message: "Login required" })
const payload = parseSessionCookie(value)
const session = await authService.getSession(payload)
if (!session) {
deleteCookie(c, SESSION_COOKIE)
throw new HTTPException(401, { message: "Session expired" })
}
c.set("sessionUser", session.user)
await next()
})
}
export function requirePermission(permission: string) {
return createMiddleware(async (c, next) => {
const user = c.get("sessionUser")
if (!user.permissions.includes(permission)) {
throw new HTTPException(403, { message: "Permission denied" })
}
await next()
})
}
```
> [!TIP]
>
> Session versioning lets you force logout users when their password changes or account is disabled. Increment `sessionVersion` on the user record — stale cookies will be rejected.
## Localized Error Responses
For bilingual apps, return locale-aware error messages from the API:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/server/src/lib/i18n.ts
import { HTTPException } from "hono/http-exception"
const messages = {
en: { "auth.invalidCredentials": "Invalid email or password" },
zh: { "auth.invalidCredentials": "邮箱或密码错误" },
}
export class LocalizedHTTPException extends HTTPException {
constructor(status: number, key: string) {
super(status, { message: key }) // key is resolved by frontend
}
}
// Frontend sends X-Locale header
// Server resolves the key to the appropriate language
```
## Styling: UnoCSS
For TanStack Start projects, UnoCSS is lighter and faster than Tailwind for utility classes:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// vite.config.ts
import UnoCSS from "unocss/vite"
import presetWind4 from "@unocss/preset-wind4"
import presetIcons from "@unocss/preset-icons"
export default defineConfig({
plugins: [
UnoCSS({
presets: [presetWind4(), presetIcons()],
}),
],
})
```
> [!NOTE]
>
> Use `presetWind4` for Tailwind CSS 4-compatible utilities. Use `presetIcons` for FontAwesome/Material icon classes without importing SVGs.
## Best Practices
1. **Monorepo with shared contracts** — Put Zod schemas and tRPC routers in a shared package so frontend and backend stay type-synced
2. **Factory-function services** — Prefer `createAuthService(opts)` over `class AuthService` for explicit DI
3. **Signed cookie sessions** — Simpler than JWT, revocable by bumping `sessionVersion`
4. **Server functions for secrets** — Never expose API keys or DB queries in client code
5. **Locale-aware errors** — Frontend sends `X-Locale`, server returns localized keys
6. **UnoCSS over Tailwind** — Faster build, icon presets, and Tailwind-compatible utilities
## References
* [TanStack Start Docs](https://tanstack.com/start/latest)
* [Hono Docs](https://hono.dev)
* [badmin repo](https://github.com/markbang/badmin) — working admin panel with this stack
* [cyop repo](https://github.com/markbang/cyop) — AI captioning platform
# Bangwu's knowledge base: dev notes and course guides
Source: https://base.bangwu.me/index
Bangwu's knowledge base — a beginner-friendly site covering frontend, backend, environment setup, software tools, and university course notes.
Welcome to bangwu's knowledge base.
This site collects tutorials, notes, command snippets, and software tips I've gathered while learning, developing, and tinkering. Use the entries below to get started, or search directly from the top right.
> [card] [Backend](/backend/index)
>
> Python, Go, Rust, databases, and web scraping.
> [card] [Frontend](/frontend/index)
>
> Vue, Next.js, Tailwind CSS, and component libraries.
> [card] [Desktop](/software/index)
>
> Tauri cross-platform desktop development.
> [card] [Algorithms](/algo/index)
>
> Sliding window, bit manipulation, and more.
## Tools & Environment
> [card] [Software Tools](/apps/index)
>
> Apifox, Cursor, ShareX, Typora, and more.
> [card] [Environment & Deployment](/env/index)
>
> Docker, Caddy, GitHub Workflow, blog setup, and more.
> [card] [Job Hunting](/env/exam)
>
> Exam and interview records, lessons learned.
## Courses & About
> [card] [Course Notes](/about/index)
>
> Information management, data mining, econometrics, and more.
> [card] [Site Info](/about/site)
>
> Scope, formatting conventions, and maintenance.
> [!TIP]
>
> Press `Ctrl+K` to open search. If you're looking for a specific command, tool, or concept, searching is faster than browsing the sidebar.
# Engineering team organization
Source: https://base.bangwu.me/software/engineering-org
Lessons from ByteDance and Meituan on organizational design, hiring philosophy, and team building — contrasting Google-style elite throughput with Amazon-style operational precision.
# Engineering team organization
In a 2026 podcast (42章经 × 魏小康), a former hiring leader who worked at both ByteDance (2017–2020, through Douyin's explosive growth) and Meituan (2020–2024, as hiring lead and AI product manager) shared hard-won lessons on how two of China's most successful tech companies build and run engineering organizations.
## Two organizational philosophies
ByteDance and Meituan represent fundamentally different models:
| | ByteDance | Meituan |
| - | - | - |
| **Model** | Google-style: elite talent, high autonomy, "move fast" | Amazon-style:精密协作, operational excellence, "do the hard work" |
| **Strength** | Innovation speed, individual impact | System reliability, scalable execution |
| **Weakness** | Coordination overhead at scale | Slower to pivot |
The key insight: neither model is universally better. The right choice depends on what you are building. AI application-layer products that require heavy delivery and integration follow the Meituan pattern: "You have to make it hard, tiring, and heavy."
## Hiring principles
### 721: battlefield as training ground
Meituan's philosophy on talent development:
* **70%** — learning by fighting real battles (giving people meaningful ownership)
* **20%** — learning from skilled practitioners (apprenticeship)
* **10%** — formal training
> "The most important thing is to give people a battlefield. Good people will fight their way out on their own."
This is not "we don't train people." It is "the battlefield *is* the training."
### Hire elite, pay premium
ByteDance's salary strategy: market rate 100, typical job-hop offer 120–130. ByteDance offered 140–150 plus overtime. Pinduoduo went further at 170–180 plus six-day weeks.
The logic: "Hiring one top person to solve a business problem costs less than hiring a bunch of people." From an hourly-rate perspective, the premium is justified.
### Expand supply through networks, not headhunters
Startups lack brand influence. The primary hiring channel is warm referrals from trusted people. Treat your best people as a CRM pipeline — the podcast host spent two and a half years meeting a target executive every three months, starting from the day the person joined a competitor, before finally hiring them.
> "If there's a competent person around you, go get all the competent people around *them*."
Reverse-network hiring: don't just recruit one person. Recruit their entire circle.
### Today is the cheapest day to hire
> "Every day after today will be harder to hire. Whatever you pay today is a bargain. It's not 'too expensive now' — it's 'more expensive later.'"
Talent supply-demand tension is structural and worsening. Early investment in hiring compounds.
## Communication overhead
> "Ten people will get at least 10% of the information wrong."
Three people working on the same thing already understand it differently. Ten people, and everyone gives a different answer about what the company is doing. ByteDance spent significant time clarifying OKRs — not as bureaucracy, but as loss prevention.
## Culture = founder behavior
> "Startups don't need to 'build culture.' All top companies have essentially the same culture. The founder's way of working *is* the company's way of working. Just shape a good atmosphere."
Culture is not a document or a workshop. It is what the founder does every day, observed and replicated.
## AI-era organizational shifts
The podcast noted early signals of change:
* AI application layers demand operational depth over pure model intelligence
* Delivery and integration work cannot be fully automated away
* Teams that combine domain expertise with AI tooling will have an edge over pure AI-native startups without industry knowledge
A complementary view (August 2026): coding execution is being industrialized, but programmer value does not automatically disappear or move up the stack. The new dividing line is about:
1. **Who can define problems worth solving**
2. **Who can turn organizational knowledge into machine-usable context**
3. **Who can constrain high-speed execution with independent verification**
4. **Who takes responsibility for the results that enter the real world**
Execution speed is becoming commoditized. What stays scarce is problem definition, context engineering, verification discipline, and accountability.
OpenAI's September 2026 internal view on research acceleration adds a concrete data point. They model AI research as six stages — **Decide → Design → Build → Run → Analyze → Communicate** — and found that coding-agent usage grew across all six, but grew *least* in **Decide** (research direction) and **Design** (decisions). Daily median usage hit $600 and P90 hit $7,000.
The interpretation: agents are excellent at execution, debugging, and experiments, but research direction and key decisions still need human input. This matches the "research intern" analogy — AI is increasingly the executor, while humans own direction and accountability. The org implication is the same as above: invest in the people who define problems, not just those who execute them.
Databricks CEO Ali Ghodsi gave the enterprise version of the same judgment in a September 2026 podcast: most companies use AI as a glorified search plus code writing, and the bottleneck is not model intelligence but missing **organizational context** — the model has never sat in a meeting, does not know how decisions got made, and lacks what veteran employees carry in their heads. His answer is an Ontology: digitize the organization's concepts, goals, departments, people, and projects into one graph.
The analogy is sharp: agents calling MCP servers one at a time is like Google indexing nothing and crawling ten pages live per query — expensive, slow, low quality. An Ontology is the enterprise equivalent of offline-computed PageRank, only much harder, because of permissions, access control, and heterogeneous objects. Thorsten Ball's parallel take is more radical: once model output exceeds human review capacity, code review, unit tests, and terminals lose their foundation, and most bugs will no longer be coding bugs but "asked for the wrong thing" bugs. The two converge: **the bottleneck is moving from writing code to defining problems and structuring organizational knowledge.**
The economics point the same way: Harvey, a legal AI company, watched gross margin fall from about 50% to −50% as agent token use spiked twentyfold on intelligence rented entirely from OpenAI and Anthropic. That gives "own your intelligence stack" a concrete footnote — **rented intelligence has no economies of scale; costs scale linearly with usage. Custom models, harnesses, and evals are the assets.** Any product that uses AI heavily needs a line in its unit economics for the intelligence-cost curve, and it is usually linear or worse.
What does the individual-to-team gap actually consist of? Alibaba's official AI-Native development handbook (68 pages, September 2026, from three internal case studies) names five challenges that survive contact with real teams:
1. **Environment and verification** — shared, reproducible verification is the bottleneck, not code generation
2. **Platform capability** — what individuals get free from a tool, teams must build as infrastructure
3. **Measurement** — did AI actually improve throughput? Without a baseline, "it feels faster" is the whole argument
4. **Digital-employee autonomy** — how much can a team-owned agent do unattended before it becomes a liability
5. **Organizational fit** — roles, review gates, and on-call need redefinition around agents
Personal vibe coding skips all five; a team building for hundreds of millions of users cannot.
## References
* [42章经 × 魏小康 播客笔记](https://x.com/dotey/status/2072149043757637916) — 宝玉的详细笔记(原始推文 by [yan5xu](https://x.com/yan5xu/status/2072146139999264940))
* [Databricks CEO on AI risk and enterprise ontology](https://x.com/shao__meng/status/2101493948917456960) — 组织上下文是企业 AI 落地的真正瓶颈,Ontology 是离线计算的 PageRank
* [Thorsten Ball: predictions](https://x.com/shao__meng/status/2101476906629841156) — 瓶颈从写代码转移到定义问题
* [Own your intelligence stack](https://x.com/omarsar0/status/2102483718958973392) — Harvey 毛利率 50% → -50%:token 用量涨 20 倍,智能全靠租
* [Cloudflare: Monetization Gateway](https://blog.cloudflare.com/monetization-gateway-beta/) — HTTP 402 按 Agent 消费单位收费
* [阿里 AI Native 研发范式实践手册](https://x.com/shao__meng/status/2105279963922338258) — 个人到团队 gap 的五个挑战
# Desktop Development
Source: https://base.bangwu.me/software/index
Desktop application development hub focused on Tauri, a Rust-based cross-platform framework for building lightweight apps with web technologies.

Desktop clients are the software users run — `.exe`, `.apk`, `.ipa` files. Desktop development is the process of building these applications.
> [card] [Tauri Practice](/software/tauri)
>
> Auto-release with GitHub Actions, SSR compatibility fixes, and more.
> [card] [SolidJS + Tauri](/frontend/solidjs)
>
> OnlyWrite — local-first writing app with reactive UI.
> [card] [Monorepo Architecture](/software/monorepo)
>
> Bun + Turborepo monorepo — project structure, shared packages, CI/CD.
> [card] [Engineering team organization](/software/engineering-org)
>
> Hiring, team building, and AI-era org shifts from ByteDance and Meituan.
# Monorepo Architecture
Source: https://base.bangwu.me/software/monorepo
Bun/Turborepo monorepo patterns for full-stack apps — project structure, shared packages, workspace tooling, and CI/CD from real project experience.
# Monorepo Architecture — Bun + Turborepo
A monorepo keeps all your apps and shared code in one repository. With Bun workspaces and Turborepo task orchestration, you get fast installs, parallel builds, and type-safe package sharing.
> [card] [badmin](https://github.com/markbang/badmin)
>
> Admin panel monorepo — web + server + docs + shared packages.
> [card] [cyop](https://github.com/markbang/cyop)
>
> AI captioning monorepo — web + server + tRPC + auth + db packages.
> [card] [fullstack](https://github.com/markbang/fullstack)
>
> Template monorepo — web + docs + desktop + API + shared packages.
## Standard Structure
All three projects follow the same pattern:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
monorepo/
├── apps/
│ ├── web/ # Frontend app (TanStack Start / React)
│ ├── server/ # API server (Hono)
│ ├── docs/ # Documentation site (Fumadocs)
│ └── desktop/ # Desktop app (Tauri + SolidJS) [optional]
├── packages/
│ ├── contracts/ # Shared Zod schemas + tRPC routers
│ ├── ui/ # Shared UI components (shadcn/ui)
│ ├── db/ # Drizzle schema + migrations + client
│ ├── auth/ # Better Auth configuration
│ └ config/ # Shared TypeScript/ESLint configs
├── package.json # Root workspace config
├── turbo.json # Task orchestration
├── biome.json # Linting + formatting
```
## Workspace Configuration
### Bun Workspaces (package.json)
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"workspaces": ["apps/*", "packages/*"],
"scripts": {
"dev": "turbo dev",
"build": "turbo build",
"lint": "turbo lint",
"typecheck": "turbo typecheck",
"test": "turbo test",
"db:generate": "turbo db:generate",
"db:migrate": "turbo db:migrate"
},
"devDependencies": {
"turbo": "latest",
"@biomejs/biome": "latest"
}
}
```
### Turborepo Pipeline (turbo.json)
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"tasks": {
"dev": { "cache": false, "persistent": true },
"build": { "dependsOn": ["^build"], "outputs": ["dist/**", ".next/**"] },
"lint": { "dependsOn": ["^build"] },
"typecheck": { "dependsOn": ["^build"] },
"test": { "dependsOn": ["^build"] },
"db:generate": { "cache": false },
"db:migrate": { "cache": false }
}
}
```
> [!TIP]
>
> The `^build` syntax means "build all dependencies first." Turborepo automatically parallelizes tasks that have no dependency between them — e.g., building `packages/ui` and `packages/db` can run simultaneously.
### Biome (Lint + Format)
Biome replaces ESLint + Prettier with a single, faster tool:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"formatter": { "indentStyle": "tab", "lineWidth": 120 },
"linter": { "enabled": true },
"javascript": { "formatter": { "quoteStyle": "double" } }
}
```
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
bun run lint # Check only
bun run format # Auto-fix
bun run check # Lint + format check
```
## Shared Packages
### contracts — Zod + tRPC
Shared schemas keep frontend and backend type-synced:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// packages/contracts/src/auth.ts
import { z } from "zod"
export const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
})
export type LoginInput = z.infer
export const sessionUserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string(),
permissions: z.array(z.string()),
roles: z.array(z.object({ slug: z.string(), name: z.string() })),
})
export type SessionUser = z.infer
```
The frontend imports `LoginInput` for form validation. The backend imports the same schema for request validation. One source of truth.
### db — Drizzle Package
Isolate database logic in its own package:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// packages/db/src/schema.ts
export * from "./schema/users"
export * from "./schema/roles"
// packages/db/src/client.ts
import { drizzle } from "drizzle-orm/better-sqlite3"
import Database from "better-sqlite3"
import * as schema from "./schema"
const sqlite = new Database("./dev.db")
export const db = drizzle(sqlite, { schema })
```
Both `apps/server` and `apps/web` (for server functions) import from `@repo/db`.
### ui — shadcn/ui Package
Shared components built on shadcn/ui:
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// packages/ui/src/button.tsx
import { buttonVariants } from "./variants"
import { Slot } from "@radix-ui/react-slot"
export function Button({ variant, size, ...props }) {
return
}
```
> [!NOTE]
>
> Create a `components.json` in both `apps/web` and `packages/ui` so `shadcn add` places components in the right location.
## Cross-App Type Safety
The key benefit of monorepo: **runtime-free type sharing**.
```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/server/src/routes/users.ts
import { z } from "zod"
import type { SessionUser } from "@repo/contracts"
app.get("/api/users", requireSession(authService), requirePermission("users.read"), async (c) => {
const user: SessionUser = c.get("sessionUser")
return c.json(await userService.listUsers(user))
})
```
```tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
// apps/web/app/routes/users.tsx
import type { SessionUser } from "@repo/contracts"
function UsersPage() {
const [users, setUsers] = createSignal([])
// Same type — no API client generation needed
}
```
## Environment Variables
Each app reads its own env vars. Service URLs can be overridden:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# .env (root)
VITE_WEB_ORIGIN=http://localhost:3000
VITE_API_ORIGIN=http://localhost:3002
API_ORIGIN=http://localhost:3002
```
Default ports:
* Web: `3000`
* Docs: `3001`
* API: `3002`
* Desktop: `1420`
## CI/CD with GitHub Actions
Turborepo caches build outputs, making CI fast:
```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# .github/workflows/ci.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
- run: bun install
- run: bun run lint
- run: bun run typecheck
- run: bun run test
- run: bun run build
# Turbo remote cache (optional)
- uses: actions/cache@v4
with:
path: .turbo
key: turbo-${{ github.sha }}
```
## Database Workflow
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Generate SQL migration from schema changes
bun run db:generate
# Apply migrations to dev database
bun run db:migrate
# Open Drizzle Studio (visual schema browser)
bun run db:studio
```
> [!TIP]
>
> Run `db:generate` after every schema change. Drizzle Kit diffs the current schema against the previous migration and generates only the incremental SQL.
## Best Practices
1. **`apps/` + `packages/` split** — Apps are deployable units; packages are shared libraries
2. **Contracts package** — Zod schemas + tRPC routers = type safety without code generation
3. **Biome over ESLint+Prettier** — One tool, 30× faster, fewer config files
4. **Turbo caching** — `^build` dependency graph + remote cache = fast CI
5. **DB as a package** — Schema, client, and migrations in one sharable package
6. **Environment overrides** — Service URLs via `.env`, not hardcoded
7. **shadcn/ui in packages/ui** — Share components across web and docs apps
8. **Tab indentation** — Biome defaults to tabs — consistent, smaller diffs
## References
* [Turborepo Docs](https://turbo.build/repo/docs)
* [Bun Workspaces](https://bun.sh/docs/install/workspaces)
* [Biome](https://biomejs.dev/)
* [badmin repo](https://github.com/markbang/badmin) — Production monorepo example
* [fullstack repo](https://github.com/markbang/fullstack) — Template monorepo
# Tauri
Source: https://base.bangwu.me/software/tauri
Tauri is a Rust-based cross-platform desktop framework smaller than Electron, covering project setup, Rust-JS communication, and app packaging.
# Tauri
Tauri is a Rust-based cross-platform app framework. Although it is relatively new, it already has mature products built with it, such as [ChatWise](https://chatwise.app) and [HuLa](https://hulaspark.com/). If you want to learn a cross-platform framework, it makes sense to pick one that truly ships across platforms.
write once, built apps for multiple platforms
## use GitHub Actions to auto-publish releases
> .github/workflows/auto-push.yml
```yml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: 'publish'
on:
push:
tags:
- 'v*'
jobs:
publish-tauri:
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- platform: 'macos-latest' # for Arm based macs (M1 and above).
args: '--target aarch64-apple-darwin'
- platform: 'macos-latest' # for Intel based macs.
args: '--target x86_64-apple-darwin --bundles app'
- platform: 'ubuntu-22.04' # for Tauri v1 you could replace this with ubuntu-20.04.
args: ''
- platform: 'windows-latest'
args: ''
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: setup node
uses: actions/setup-node@v4
with:
node-version: lts/*
cache: 'pnpm'
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
# Those targets are only used on macos runners so it's in an `if` to slightly speed up windows and linux builts.
targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
- name: install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-22.04' # This must match the platform value defined above.
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
# webkitgtk 4.0 is for Tauri v1 - webkitgtk 4.1 is for Tauri v2.
# You can remove the one that doesn't apply to your app to speed up the workflow a bit.
- name: install frontend dependencies
run: pnpm install # change this to npm, pnpm or bun depending on which one you use.
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tagName: v__VERSION__ # the action automatically replaces \_\_VERSION\_\_ with the app version.
releaseName: 'OnlyWrite v__VERSION__'
releaseBody: 'See the assets to download this version and install.'
releaseDraft: false
prerelease: false
args: ${{ matrix.args }}
updaterJsonPreferNsis: true
updaterJsonKeepUniversal: true
- run: npx changelogithub
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
```
> .github/workflows/test-build.yml
```yml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: 'test-build'
on:
pull_request:
branches:
- main
push:
branches:
- main
- dev
workflow_dispatch:
jobs:
test-tauri:
strategy:
fail-fast: false
matrix:
include:
- platform: 'macos-latest' # for Arm based macs (M1 and above).
args: '--target aarch64-apple-darwin'
- platform: 'macos-latest' # for Intel based macs.
args: '--target x86_64-apple-darwin'
- platform: 'ubuntu-22.04' # for Tauri v1 you could replace this with ubuntu-20.04.
args: ''
- platform: 'windows-latest'
args: ''
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: setup node
uses: actions/setup-node@v4
with:
node-version: lts/*
cache: 'pnpm'
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
# Those targets are only used on macos runners so it's in an `if` to slightly speed up windows and linux builts.
targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
- name: install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-22.04' # This must match the platform value defined above.
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
# webkitgtk 4.0 is for Tauri v1 - webkitgtk 4.1 is for Tauri v2.
# You can remove the one that doesn't apply to your app to speed up the workflow a bit.
- name: install frontend dependencies
run: pnpm install # change this to npm, pnpm or bun depending on which one you use.
# If tagName and releaseId are omitted tauri-action will only built the app and won't try to upload any assets.
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
args: ${{ matrix.args }}
```
If you are not familiar with [GitHub Actions](https://github.com/features/actions), you can read my [intro guide](../env/github-workflow).
With the workflow above, pushing a tag like `v*` can automatically build the app, publish a release, and generate a changelog.
The changelog is generated with [Antfu changelogithub](https://github.com/antfu/changelogithub), which follows the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/#summary) format. Using that commit style makes the generated changelog much cleaner and easier to read.

### [Tauri-action](https://github.com/tauri-apps/tauri-action)
app signing
How to configure `latest.json`
how to built mobile app
how to auto-publish to platforms
### Allow GitHub Actions release permissions to read and write the repository
otherwise there'll be errors publishing Release`Error permisson`
## Fix: Next.js SSR window is not defined
## Fix: `Cannot read properties of undefined (reading 'xxxxxx')`
This error is often caused by a plugin not being loaded. Initialize the plugin in `main.rs`.
# Competitive intelligence
Source: https://base.bangwu.me/about/courses/competitive-intelligence
Course notes on competitive intelligence covering the intelligence cycle, Porter's Five Forces, patent analysis, and value chain strategy.
# 竞争情报
> \[!note]
> 选择 10x1 填空 5x1 名词解释 3x5 简答 5x8 案例 2x15
> 重点: 竞争情报的流程、价值链、专利分析、定量分析、竞争情报系统、战略、波特五力、情报收集
## 一、绪论
### 1.**竞争情报概述**
* **概念与特点**
* **定义**:竞争情报是一个发展中的概念,有过程说、信息说、产品说等不同观点。广义上是指国家、组织等为竞争优势进行收集等工作的所有信息;狭义上指企业竞争情报。其重点关注竞争对手、竞争环境和竞争战略。
* **特点**:具有对抗性(竞争性)、谋略性、动态性、合法性,还有目的性、时效性、实用性、增值性、智能性和信息来源广泛性等特征。
* **研究核心领域**
* **竞争对手研究**:包括现有行业竞争格局、主要竞争对手、潜在竞争对手和替代品生产者的情报,可通过多种方法预测潜在竞争对手。
* **竞争环境研究**:竞争环境对企业影响巨大,包括政策、经济、社会文化环境等,可通过波特五力模型和环境扫描进行分析。
* **竞争战略研究**:企业为竞争制定的长期总体谋划,包括成本领先、产品差异化、聚焦战略等。
### 2.**竞争情报的作用和流程**
* **作用**
* **危机预警**:搜集信息帮助企业避免危机,预测竞争者行为。
* **决策支持**:为决策提供一手资料和战略情报支持,如支持技术开发决策。
* **市场环境监测**:监测影响企业生产销售的外部因素。
* **对手跟踪**:帮助企业建立情报优势,需长期坚持跟踪工作。
* **信息安全保障**:反竞争情报保护企业信息安全,与竞争情报相辅相成,企业信息泄露途径多样,可通过多种措施保护。
* **流程**(循环)
* **规划与定向**:了解用户竞争需求,选定研究目标,包括确定目标、情报需求调查诊断、制定计划与用户交流,可采用多种方法。
* **信息搜集与整理**:确定信息源和范围搜集信息,注意问题,制订行动方案,评价反馈工作,对信息初步加工整理。
* **信息分析与提炼**:精加工信息,创造和增值情报价值,为管理者提供支持。
* **产品与服务**:为决策层提供情报产品和服务,产品包括情报通讯、竞争对手文档、报告等,服务包括培训、咨询、产品服务。
### 3.**企业竞争情报研究的沿革和发展**
* **国外研究**
* **应用现状**
* **美国 SCIP**:1986 年成立,是学术性非营利组织,推动竞争情报发展,在全球有众多会员,关注多项核心内容,在多地建立同名机构。
* **日本竞争情报**:体系包括综合商社、企业形式运营的综合研究所、独立行政法人等非营利机构和大公司的竞争情报。综合商社情报调查重要,三菱商社搜集情报最多;野村研究所等私人公司提供情报服务;日本大公司对竞争情报投入大。
* **欧洲竞争情报**:欧洲 SCIP 呼吁重视竞争情报,瑞典有企业加入。
* **研究内容**:主要在发达国家企业,集中于竞争情报搜集来源、过程周期、方法技术工具、运用于企业危机预警和反情报策略等方面。
* **我国研究**:1992 年开始引入,1994 年成立相关专业委员会,后更名。进入 21 世纪进入应用期,特点包括竞争情报系统、方法和社会网络研究,组织模式有专业情报机构、高校、企业内情报部门。
## 二、企业竞争情报的信息源
### 1.**信息源的类型和特点**
> **信息源分类**
* **公开与非公开信息源**:公开信息源公开发表且免费或低费提供;非公开信息源包括企业内保密与非保密信息。
* **按加工集约程度**:分一次、二次、三次、四次信息源,常说的一手信息源和二手信息源。
* **按产生时间顺序**:有先导、即时、滞后信息源,如天气预报是先导信息源,报刊等是滞后信息源。
* **按信息来源**:包括政府、专门利益集团(如行业协会)、私有部门、媒体信息源等。
* **根据是否被记录**:分为文献信息源(如图书、期刊等)和非文献信息源(如研讨会、产品样本)。
> **具体信息源介绍**
* **文献信息源**
* **按载体不同**:分为印刷型、缩微型、机读型、声像型文献。
* **按发售途径和获取难易程度**:有白色文献(正式出版发行,易获取,如常见学术著作,其半衰期因学科而异)、黑色文献(不正式出版、发行范围窄且内容保密,竞争情报活动一般不以此为源)、灰色文献(介于白色和黑色文献之间,不正式出版但非秘密,如政府、学术单位等产生的资料,比例可能超文献信息源的 20%)。
* **非文献信息源**
* **口头信息源**:是零次信息源,如各种会议、交流活动中的信息,内容新颖但易失真、搜集保管困难且传播范围小。
* **实物信息源**:以实物为载体,信息成熟可靠、内容丰富,但挖掘、搜集保管和传播困难,且易引发知识产权纠纷。
> **常见信息源简介**
* **商情数据库**:能提供国际商务活动相关信息,数据库检索高效,如艾瑞咨询、腾讯数据智库等是常见中文商情数据库。
* **互联网**:可快速获取信息,获取线索后需其他渠道验证。
* **剪报**:适合连续监测行业动态,优点是方便、覆盖面广、针对性强且价格相对便宜。
* **供货商、经销商**:可提供行业、竞争对手等信息,经销商有时能提供销售竞争对手的信息。
* **顾客或消费者**:能了解其对本企业产品和竞争对手的比较意见建议。
* **竞争对手**:其年度报告、产品样本等有价值。
* **企业内部员工**:是重要信息源,约 80%竞争性信息可从员工处获得,可形成以员工为中心的情报交流网。
* **网络竞争情报源**:包括公司企业网站(可了解企业多方面信息)、商业信息网站(如中国化工热线网站等可查各类商业信息)、学会协会网站(提供机构介绍、行业动态等)、政府网站(有大量公共信息)、求职网站(微观可了解企业人才需求等,宏观可了解人才市场状况)。
* **电子文献情报源**:如广播、电视节目等可估计对手销售情况,专业数据库如 IBFD 可了解多方面信息,还有国家法律法规数据库。
* **会议竞争情报源**:包括学术讨论会、技术鉴定会等多种会议,特点是及时新颖。
### 2.**信息搜集的范围和渠道**
> **信息搜集范围**
* **搜集途径与原则**
* **途径**:主要包括文献调查(间接、非介入式,步骤为确定范围、准备、收集、分析整理,对象广泛,有诸多优点但也有局限性)和社会调查(有目的、系统地搜集信息,采用多种方法,分准备、实施、整理阶段)。
* **原则**:全面性(涵盖多方面相关信息)、系统性(反映特定领域状况)、针对性(针对竞争情报活动)、新颖性(领域最新或相对新颖)、可靠性(客观真实准确)、科学性(采用科学方法)、计划性(考虑“4W1H”)。
* **搜集范围确定**:确定信息搜集范围时应重点把握影响竞争战略的因素,包括企业自身信息(如经营战略、产品情况等)、竞争对手信息(选取关键对手长期监视,基本方法有寻找相似企业或通过客户调查)、行业环境信息(企业生存直接环境,变化影响企业发展)、宏观环境信息(间接影响企业,有时可转化为直接因素)。
> **信息搜集方法和渠道**
* **正式渠道法**:通过主流信息传播渠道搜集信息,可细分为数据库检索法(如国际联机情报系统中的 ProQuest、CA、OCLC 等,OCLC 的 FirstSearch 系统发展迅速,Questel·Orbit 和 ESA - IRS 系统也各具特色)、网络查询法、委托专业咨询机构调查法,国际联机检索费用较高。
* **非正式渠道法**
* **实地调查法**:通过考察询问搜集信息,主要包括询问法、观察法、实验法。
* **特殊手段法**:采取非常规手段,如公开渠道获取数据后分析破译商业秘密、通过第三方机构搜集情报、建立人际关系网络搜索、利用人才流动机会录用离职人员搜集(需对方已解除原雇佣关系),并举例说明人才流动与保护商业秘密的关系。还介绍了一些网络相关的搜集方法,如获取网站年龄、流量、反向链接分析、网站变化分析的工具及方法,网站排行榜展示了部分网站的相关数据。
* **信息搜集渠道特点**:一次信息搜集渠道直观快捷但耗时长等,二次信息搜集渠道需专业人员,来源丰富费用相对较低。
### 3.**信息整理和鉴别**
**`信息整理`**:对原始信息初步加工,使之有序便于利用,具体工作包括分类、合并查重、格式转换、同类集中、按类排序等。信息分类是重要环节,可根据实际从有利于使用角度进行,分类方式有形式整理(根据外在依据,如载体、使用方向、内容线索分类,方法有信息分类、时间分类、地区分类)和内容整理(在形式整理基础上深化,包括理解、揭示、细分归类信息内容,应用方法有摘录法、综述评述法,还介绍了方格法、计算、比例法等具体操作及作用)。
**`信息鉴别`**:对原始信息进行价值评判,筛选有用信息淘汰无用或不良信息,包括可靠性鉴别(鉴别方法如考察渠道过往可靠性、动机、信息一致性及可能性,可反向佐证)、新颖性鉴别(相对概念,从理论观点等创新及时间、空间、内容矢量衡量)、适用性鉴别(取决于研究课题和信息用户,在可靠性和新颖性鉴别基础上进行)。
## 三、企业竞争情报研究内容
### 1.竞争对手分析
1. **竞争对手分类**
* **按表现形式**:分为现实竞争对手(与企业有明显利益冲突,同行业且综合实力相当,影响市场供需和占有率)和潜在竞争对手(来自其他行业,竞争呈“隐形”状态,可能向壁垒低的细分市场迂回攻击,如不费气力进入本产业等企业可能成为潜在对手)。
* **按性质**:分为“好”竞争对手(可能增强企业竞争优势,如行业领先者等,应善待)和“坏”竞争对手(带来恶性竞争,应打击防范)。
2. **竞争对手选择**
* **原则**:战略性原则(为竞争战略提供依据,高层应重视)、针对性原则(有计划针对同行和相关行业企业评估)、动态性原则(长期跟踪,根据环境变化调整策略)。
* **对象**:包括市场份额接近或有潜力接近超越本企业等多种类型企业,如技术实力强、可能使本企业用户转移等。
* **方法**:视觉地图法(用图表确定竞争对手及地位,半定量,指标过多时建立多维坐标图困难)、企业直接指定法(常见,适用于直接竞争对手分析,但可能忽略潜在对手)、价值网分析法(适用于分析潜在竞争对手,将供应商等组成价值网二维空间)。
* **步骤**:包括需求分析、定义竞争对手、构建评估体系、综合评估、识别与选择。
3. **竞争对手情报**:包括未来目标(关注赢利、销售增长等目标,其决定竞争对手行为和心理,可预测其对现状满意度)、假设(竞争者对自身、行业内其他公司的看法,影响竞争行为)、现行战略(取决于战略目标和市场定位,有低成本、差异化、集中化战略等)、能力(包括市场竞争、人力资源等多方面能力,决定其反应可能性等)。企业可通过向竞争对手学习发现自身缺陷和发展方向。
### 2.竞争环境分析
> **竞争环境特点和类型**
* **特点**:复杂性(影响因素多且要素关系非线性)、动态性(不断变化,决定企业竞争优势短暂性)、边界模糊性(竞争边界从链状向网状和立体状转变)、可测性(有内在规律可预测)、互动性(对手间相互影响)。
* **类型**
* **宏观竞争环境**:包括政治环境(影响企业市场营销、投资和发展战略等)、经济环境(如购买力、居民收入等因素影响市场需求)、社会环境(如教育水平影响文化商品需求)、技术环境(新技术诞生是“创造性破坏”力量,企业需紧跟技术进步)。
* **产业竞争环境**:通过波特五力模型分析,包括现有企业竞争(影响因素众多,竞争者增加等会加剧竞争)、供应商议价(集中度高、无替代品等因素增强其议价力量)、购买者议价(受行业集中度等因素影响,购买品特性影响其议价能力)、替代品威胁(价格下降等因素会增大威胁)、潜在进入者威胁(取决于行业壁垒和原有企业反应,行业壁垒受规模经济等因素影响,原有企业反应模式有从容型等),还包括其他利益相关者影响(如政府、社区等,对各行业影响程度不同)。五力模型可帮助企业判断行业特点、制定战略,但也有不足,未充分揭示竞争力量来源等。产业竞争环境分析可帮助企业预测行业赢利潜力等。
* **企业内部环境**:是微观竞争环境,包括组织结构、企业文化、企业制度、企业资源和能力等。
**竞争环境分析意义**:是企业制定竞争战略的前提,也是获得持续竞争优势的保障,企业需根据环境变化调整战略,通过监视和分析可获取先兆信息。
> **竞争环境分析内容**
* **现状分析**:宏观环境分析利用环境扫描法,识别机会和威胁;产业竞争环境分析找出关键竞争力量和威胁;企业内部分析发现自身优劣。
* **趋势分析**:宏观环境趋势分析确定主要影响因素并预测变化,可采用定性(专家经验)和定量(趋势外推分析法)方法;产业竞争环境趋势分析主要判断行业所处生命周期阶段,依据市场份额等指标,不同阶段行业特点不同。
* **协同分析**:包括企业内部环境要素间及与外部环境的协同,通过各要素相互作用实现,可从狭义和广义理解,竞争协同环境有助于企业获得竞争优势。
### 3.竞争战略分析
> **竞争战略内容和过程**
* **内容**
* **竞争战略管理学派**:包括行业结构学派、核心能力学派、战略资源学派、动态竞争战略学派。
* **战略要素**:战略目标(出发点和归结点,包括进入市场领域和保持竞争优势的描述)、企业资源(各类资源,强调占有稀缺资源和动态配置)、经营能力(创造价值的能力总和,如研发、营销等能力)、战略组织(组织结构和文化支撑战略执行)、产品/市场(市场是竞争场所,产品是战略载体,通过满足细分市场需求获优势)。
* **过程**:包括战略制定、转换、实施、控制,企业在竞争环境下进行这些活动。
> **竞争战略类型**
* **按基本战略分类**
* **总成本领先战略**:通过降低成本提供低价产品,适用于价格敏感客户多等情况,实现途径包括管理成本因素和改造价值链。
* **差异化战略**:提供独特产品和服务,适用于产品差异创造途径多等情况,风险包括差异化不被顾客认可和赝品问题。
* **聚焦战略**:服务特定细分市场,小企业常用,成功需选好目标市场,风险包括竞争对手进入、市场需求趋同和高成本。
* **按竞争行为性质分类**
* **进攻战略**:有实力企业采用,包括正面、侧翼、包抄进攻等方式,如丰田进入美国市场的案例,包括调研、寻找切入点、制定具体策略(产品、定价、分销渠道、促销策略)等步骤。
* **防御战略**:以守为攻,如精工获取商标封锁对手进攻,包括收缩、剥离、清算、合资经营战略。
* **撤退战略**:缩小生产规模或取消产品生产,企业根据产业结构选择是否放弃。
* **合作战略**:与对手合作双赢,如通用电气为 IBM 定制芯片。
* **按竞争模式分类**
* **一体化战略**:包括前向、后向、横向一体化,企业利用优势向深度广度发展。
* **多元化战略**:进入新领域,包括同心、水平、混合多元化,可扩大市场占有率,但也增加竞争对手。
* **专业化发展战略**:主攻特定市场,包括市场渗透、开发、产品开发策略,有产品 - 市场、产品 - 、市场 - 、选择性专业化等形式。
**竞争战略选择依据**:不同企业在不同阶段因竞争环境不同而选择不同战略,战略选择受组织推动力(企业资源和能力变化)和环境驱动力(外部环境改变)影响。
> **不同企业的战略选择**
* **基于竞争地位**
* **市场主导者**:目标是维持市场竞争结构平衡稳定,对策包括保持进攻和防守态势、迫使追随者服从。
* **市场挑战者**:重点是资源极限时休战和寻找新市场,目标是提高占有率和收益率,采用进攻战略。
* **市场追随者**:目标是与主导者共存,关键是细分市场、研发盈利产品和模仿改进新产品,方式有紧随、距离、选择追随。
* **市场补缺者**:选择被忽视市场专业化经营,策略包括创造、扩大、保护补缺市场。
* **基于生命周期**:不同产业发展阶段企业有不同战略选择,如创业期初创企业可选择聚焦战略等,衰退期行业特点特殊,确定行业发展阶段困难,应结合多种方法分析。企业战略实施流程包括目标陈述、环境分析、战略定位、方案评估、实施、效果检验、运行与进化发展。
## 四、企业竞争情报研究的方法
### 1.研究方法概述
1. **定性研究方法**:是传统方法,特点是推论严密、直感性强,但不够精确和具体。适用于为定量研究做准备、验证或评价定量研究结果,或在无需定量研究时独立使用。
2. **定量研究方法**:以数学手段揭示研究对象数量规律,结论具体、高度抽象,但不能替代创造性思维。实践中常与定性研究方法结合使用。
3. **半定量研究方法**:定性与定量结合,将定性问题按标准打分量化处理,具有数理统计特征。比定性研究更具操作性,适用于原始数据不足等不易或不宜定量研究的场合,但推理不如定性严密,也不能像定量研究那样利用数学模型求解。
### 2.定标比超
**概念**:将本企业与竞争对手或一流企业对照分析,可用于测算和改进产品或服务质量,涵盖战略、操作、管理等层面。
**由来和发展**:1979 年始于施乐公司,后被许多国际大公司和公共服务部门采用,成为重要竞争情报分析工具。
> **类型**
* **按重点分类**
* **产品定标比超**:最早且应用广泛,通过对产品反求工程改进产品、估算成本,还需了解顾客需求和对手满足需求的方法。
* **过程定标比超**:深入比较过程,学习模仿对手优秀绩效的关键因素,如营销、生产管理等方面的定标比超,比产品定标比超更复杂。
* **管理定标比超**:对比领先企业管理系统和绩效,学习赶超,涉及整个管理工作,如奖酬制度的定标比超。
* **战略定标比超**:分析企业战略意图,确定成功关键战略要素,为高层制定战略服务,注重目的,与过程和管理定标比超先比较手段再确定目的不同。
* **按对象分类**
* **内部定标比超**:在组织内部进行绩效评估,找出最佳作业典范,适用于大型企业集团或跨国公司,但焦点多为操作性事务,缺乏战略高度。
* **竞争定标比超**:直接竞争组织间的绩效评估,可找出对手优势差距,但因竞争关系获取情报较难,常由中立第三方执行。
* **功能定标比超**:跨行业进行,针对特定功能领域活动,是非竞争性的,容易争取到对方配合,如施乐与 L.L Bean 公司在物流管理方面的定标比超。
* **通用定标比超**:评估不同行业、功能的业务流程,有望发现创新潜力,但实施困难最大,如美国西南航空公司和多米诺比萨饼公司的案例。
**定标比超的程序**:施乐公司采用规划、分析、合成、行动和见效五个环节;国际定标比超情报交流所分为规划课题、搜集数据、分析数据和修正四个环节,一般流程包括**制订计划、分析、综合数据、实施计划**。
> **方法评价**
* **优势**:适用面广,适用于企业和个人;针对性强,可选取关键环节改进;作用多样,能帮助组织了解自身、定位、明确差距和改进目标。
* **不足**:具有片面性,受多种因素影响无法涉及所有方面;静态性,无法动态全面了解对手;局部性,仅针对具体问题分析对比。
### 3.SWOT 分析
**内涵**:即态势分析法,分析企业优势、劣势、机会和威胁,基于此制定战略,指导思想是把握内外部因素制定发展战略。
> **程序**
* **明确目标**:综合考虑企业内外因素,明确对比对象,环境包括直接和间接影响企业的因素。
* **分析 S、W、O、T**
* **优势**:从自身和对手角度客观评估企业有利条件、擅长领域、易获取资源及他人看法。
* **劣势**:考虑企业需改进、可提升、做得不好及应避免之处,兼顾内外因素。
* **机会**:关注技术改进、法规变化、社会形势转变等带来的机遇,可结合优势寻找机遇。
* **威胁**:留意竞争对手动态、市场要求变化、技术革新、资金周转及企业生存发展的弱点等问题。
* **构造 SWOT 矩阵**:按轻重缓急或影响程度对因素排序,构造矩阵,包括 SO 战略(发挥优势抓住机会)、WO 战略(将劣势影响最小化并抓住机会)、ST 战略(发挥优势规避威胁)、WT 战略(使劣势和威胁影响最小化)。
> **SWOT 模型评价**
* **优点**:直观简单,无需精确数据和专业工具即可得出有说服力结论。
* **缺点**:精度不够,采用定性分析,结论带有主观性。
> **SWOT 定量分析**
* **分析流程**:包括 SWOT 要素分析(定性)、建立内外因素评价模型、计算 SWOT 力度、确定战略类型和强度、确定战略重点与战略内容。
* **操作方法**:识别关键要素并赋予重要性评分,计算加权分数确定 SWOT 力度,依据力度确定战略类型和强度,进而明确战略重点与战略内容。
### 4.情景分析
> **概念及其应用**
* **概念**:又称前景描述法等,“情景”是对未来情形及相关事实的描述,情景分析是预测态势产生及影响的过程。
* **应用**:可用于监测竞争环境(识别关键因素,构造情景预测趋势)、分析竞争对手(预测对手反应,识别潜在对手)、制定竞争战略(考虑多因素提高战略灵活性)。
> **步骤**
* **主题确定**:主题具重要性和不确定性,确定主题是综合性非程序化决策过程。
* **关键影响因素识别**:采用头脑风暴法和德尔菲法识别影响未来趋势的因素。
* **核心情景描述与选择**:组合关键因素描述,从概率和战略重要性角度形成核心情景描述图。
* **情景预测**:详细描述核心情景,列举问题,分组模拟并讨论竞争战略。
* **制定竞争情报战略**:汇总模拟信息和战略,找出趋势和重点,制定情报战略。
* **建立早期预警系统**:包括信息搜集、因素预警(监测不可量化因素)、指标预警(监测量化因素并设阈值报警)子系统。
> **优点和缺点**
* **优点**:发挥人的能动作用,与决策者保持信息交流;比趋势外推法更灵活实用,能处理随机因素和决策者意志;比德尔菲法更强调专家观点差异,考虑更周全。
* **缺点**:过程复杂,依赖直觉,缺乏程序化模式,易忽略渐变因素;近期效果不显著,是长期预测工具;易受企业传统模式制约。
**适用环境**:适用于资金密集、开发前导期长等特定行业,以及企业未来分析、差距分析、目标展开和项目管理。
### 5.价值链分析
**价值链概念**:以价值为考察对象研究企业经营活动,竞争优势源于企业在设计、生产等过程中的价值活动。价值活动包括基本活动(内部物流、生产经营、外部物流、市场营销、服务)和辅助活动(企业基础设施、人力资源管理、技术开发、采购),它们相互联系,构成有机统一体,为竞争情报研究提供脉络。
> **价值链特征**
* **工具性**:将企业分解为与战略相关的价值活动。
* **内部联系性**:竞争优势源于价值活动间的联系。
* **外部延伸性**:不仅存在于企业内部,还延伸到外部。
* **动态性**:不同企业价值链不同。
> **价值链分析的原理**
1. **企业内部价值链**:分析构成要素,确定影响成本与增值的基本价值链,消除高成本和不增值环节,可通过外包、流程改造等优化,如人造板生产企业和芯片企业的基本活动。
2. **企业外部价值链**
* **产业价值链**:确定企业在产业中的地位,分析关键环节和盈利主体,考虑产业链整合或合作,如人造板和芯片产业链。
* **供应商价值链**:节约原材料加工成本。
* **客户价值链**:了解客户需求,降低库存和交易成本,如快递企业通过分析客户投诉改进服务。
* **竞争对手价值链**:了解自身相对优势劣势,提供标杆改进活动。
> **价值链分析的程序**
1. **明确目标**:内部分析提升竞争力,外部分析明确市场定位和战略。
2. **识别构建**:结合企业和行业实际,识别价值活动并归类。
3. **确定战略环节**:找出创造企业价值的关键环节。
4. **识别核心竞争力环节**:定位和识别价值链中的核心竞争力,转化竞争优势。
5. **系统研究**:有条理地搜集整理各环节信息。
> **价值链分析的案例应用**
1. **快递企业**:核心业务价值链包括收件、分拣、运输、派件等环节,通过分析客户投诉,发现企业在法律法规、人力资源管理、服务流程等方面存在问题,为改进提供方向。
2. **奥普企业**
* **市场情况**:面临市场挑战者、跟随者和补缺者的竞争,以及杂牌仿冒、价格混乱、诋毁等问题。
* **价值链分析**:认识到客户需求是利润来源,通过与一流企业比较,发现获取价值方式多样,进行产业链整合,包括控制上游资源、推广产品、制定标准等,调整战略后取得成效。
> **价值链分析的优缺点**
1. **优点**
* **全面性**:展示企业价值活动及关系。
* **高效性**:区分战略和一般环节,聚焦重点。
* **灵活性**:随企业战略和环境变化调整情报工作重点。
2. **缺点**
* **复杂性**:分析对象庞大,需了解环节间关系。
* **主观性强**:主要为定性分析。
* **局限性**:不适用于虚拟价值链分析。
### 6.专利情报分析
> **专利情报分析的原理**
**概念**:在筛选、鉴定、整理专利信息基础上,利用文献计量学方法分析情报要素,揭示深层动态特征,为技术评价和预测提供依据。专利制度保护发明独占权,专利信息具有独特情报性质。
**实施步骤**:检索专利数据库获取信息,加工分析形成情报,解读文献为技术战略决策。常见检索系统有国内外多种专利数据库及检索分析工具,还有《美国专利商标局公报》《中国专利公报》等。
> **专利情报分析的意义**
1. **分析预测技术趋势**:通过分析大量专利文献,确定技术热点和发展趋势,为企业技术创新指引方向。
2. **发现评估竞争对手**:统计分析专利文献可发现潜在对手,监视其技术开发和经营策略,还可寻找合作伙伴,如美国辉瑞公司与克罗地亚 Pliva 公司的合作案例。
3. **制定专利竞争战略**:利用专利文献可缩短研发周期、节约经费,通过国家分布、专利权人、核心技术分析等制定战略,应对新贸易壁垒。
> **专利情报分析的常用方法**
1. **定量分析**
* **简单统计分析**:按发明专利人、申请人、分类号、数量、地区等统计,了解企业研发实力、技术领域水平、地区技术开发现状,如中、美、日、韩 5G 专利申请趋势对比。
* **技术生命周期分析法**:分析专利申请、授予数量与时间关系及申请企业数量与时间关系,判断技术发展阶段和方向,如我国电通信技术领域申请量变化趋势。
* **专利引文分析法**:对专利引用现象深层次分析,揭示文献关联性,提供多方面竞争情报,如确定研究热点、判断竞争对手战略、确认竞争对手、反映技术领先程度、应用于科技管理评估、揭示专利与基础科学联系,华为等公司专利被引用情况体现技术实力和影响力。
* **专利地图法**:以图表展示专利情报,揭示技术研发方向,发现技术盲点、掌握动向、了解技术差异、发现研发策略、用于质量管理,专利地图中距离、山峰等元素有特定含义。
* **矢量动态模型法**:将统计数据矢量模型化,评价和预测科学发展动向,如通过 IPC 分类号分析中兴、华为等公司技术结构和竞争态势。
2. **定性分析**
* **专利性分析**:判断发明创造技术方案的新颖性和创造性。
* **专利的同族分析**:分析同族专利地理分布判断商业价值,为技术引进和产品出口提供依据。
* **专利原文分析**:检索阅读竞争对手专利说明书获取情报,包括直接使用、技术超越(如寻求空隙、技术综合、改进、原理法)、参考借鉴(了解行业环境、技术信息、竞争对手等)。
3. **定性与定量结合**:定量分析反映技术量的变化,定性分析体现质的变化,实际工作中配合使用效果更佳,如海尔风冷式冰箱研发案例。
> 专利情报分析的指标体系
1. **公司层面**:包括专利件数(衡量研发产出和技术能力)、专利占公司比率(衡量研发状况和重视程度)、专利成长率(衡量历年研发活动和技术变化)、被引用次数(衡量专利重要性)、当前影响力(衡量技术影响力)、科学连接(衡量与基础科学研究关系)。
2. **技术层面**:涵盖专利件数(衡量技术研发产出)、专利成长率(衡量技术活动变化)、被引用次数(衡量技术重要性)、技术影响力(衡量技术影响力和重要性)、技术生命周期(衡量研发速度和交替时间)、科学连接(衡量与科学研究关系)、技术活动年限(衡量研发投入时间)。
> **专利情报分析的优势和缺陷**
* **优势**:获取专利相对容易,分析过程和结论客观真实。
* **缺陷**:专利数据不能完全代表整个领域创新活动,存在时滞。
## 五、企业竞争情报系统
### 1.**概述**
* **建立需求**:企业各部门信息存在重复冗余、利用低效、重要信息遗漏等问题,促使企业建立竞争情报系统。如日本丰田公司和三井物产综合商社建立全球情报网络系统,日本中小企业依托大企业发展竞争情报系统。
* **概念**:对组织内外部信息集成管理,支持竞争战略目标,是持续演化的正式与非正式操作流程结合的管理子系统,也是人机结合的战略决策和咨询系统。
* **模式和特点**
* **职能型模式**:按现有管理职能部门构建。
* **集中型模式**:设情报中心统一完成信息收集、处理分析和情报提供工作。
* **重点分布型模式**:以接触竞争情报频繁的重点职能部门为核心,有利于搜集和传递情报。模式选择需考虑与外部环境接触和信息处理传报,职能型适合职能部门管理对象交叉少的企业,集中型适合有专业情报队伍的企业,重点分布型适合信息搜集职能强的企业。
### 2.**建设**
* **总体框架**:由信息搜集、分析、服务三个子系统组成金字塔形结构,收集系统是信息输入端口。
* **信息搜集子系统**:建立和运行需考虑企业及行业特点,集中于特定项目,从决策角度搜集信息。包括信息录入(专人负责录入企业内外信息)和自动接收(计算机搜索内外部信息)模块,以及负责管理信息的信息管理模块。
* **信息分析处理子系统**:是核心部分,目标是将信息转化为可操作情报,需专职人员和计算机系统协作,利用规则集等工具对信息分析处理,工作流程包括筛选(剔除不良信息)、整理(排序、统计分析、归纳浓缩)、分析(借助模型和工具)、评价(适度评价筛选利于使用),针对竞争环境、竞争对手、企业自身有多种分析方法。
* **情报服务子系统**:是输出系统,根据需求创建报告并传递给决策者,通过计算机检索系统提供情报服务,有分层次的情报报告体系,其高效性影响系统形象和成败。
### 3.**管理**
> **企业竞争情报教育和培训**
* **人员素质要求**:从业人员应具备创造力等核心能力,具备社会学、信息管理和某一领域专门知识素养。
* **培训内容和方式**
* **专业人员**:培训内容为技能和方法,培训方式包括商业公司培训(时间短、专业性强、收费高)、行业协会研讨会和培训班(针对有经验人员)、自学(通过竞争情报培训站点),采用集中脱产学习和在职工作培训相结合方式。
* **非专业人员**:培训内容为了解工作流程和环节,培训方式为企业内部宣讲教育和通过竞争情报出版物自学。
## 六、企业竞争情报机构
### 1.**类型**
* **职能型**:以职能机构形式存在,在原有信息机构基础上扩展调整,目的明确、操作简单,能发挥情报人员主观能动性,如惠普、宝洁采用此类型。
* **协调型**:专职人员少,在课题项目小组中起协调组织作用,采取“小核心,大协作”模式,如 IBM、柯达、施乐采用。
### 2.**设置**
**设置依据**:位置及结构取决于企业盈利点(应设在盈利关键领域)、创新点(设在创新点所在部门)、威胁点(设在面临最大威胁处)。调查显示,部分企业竞争情报机构设在营销、计划机构或独立设置等。设置应建立信息交流平台、形成人际网络、与领导保持密切联系。
> **组织形式**
* **分散式**:各部门独自进行竞争情报工作,产品针对性强,但未经整合影响决策者处理。
* **集中式**:信息工作集中于情报中心,便于统一管理、信息质量高,但处理速度慢、需高素质专业队伍。
* **重点分布式**:设在关键职能部门下,有利于信息搜集处理,但跨部门交流有障碍。
* **外包式**:中小企业常用,可节省成本、获取客观公正情报,但难长期监控环境和预警。
* **面向项目的虚拟团队**:根据项目需求组建虚拟人际网络,成员具多种职能,生命周期与项目相关,可降低运营成本,如 IBM 采用。
# Econometrics
Source: https://base.bangwu.me/about/courses/econometrics
Course notes on econometrics covering OLS regression, multiple linear regression, heteroscedasticity tests, Durbin-Watson autocorrelation, and VIF detection.
## 第二章: 一元线性回归模型
### 2.1 OLS(最小二乘法)
* 对于$\hat{y}_i = \hat{\beta}_0 + \hat{\beta}_1x_i$,不同的估计方法会得到不同的样本回归参数$\hat{\beta}_1和\hat{\beta}_0$,所估计出来的$\widehat{y}_i$也就不同。
* 理想的估计结果也就是估计的$\widehat{y}_i$与真实的$y_i$的差(即剩余$e_i$)总的来说越小越好。
* 因为$e_i$可正可负,总有$\sum e_i = 0$,所以可以取$\sum e_i^2$最小
#### 2.1-2 最小二乘原理
* 普通最小二乘法(Ordinary Least Squares, OLS)建立在最小二乘准则上,最小二乘准则是使全部样本观测点的残差平方和(Residual Sum of Squares, RSS)最小。
$$
e_i= y_i - \hat{y}_i = y_i - \hat{\beta}_0 - \hat{\beta}_1x_i
$$
* 最小二乘准则就是寻找一组合适的估计值$\widehat{\beta}_1$和$\widehat{\beta}_0$,使得如下目标函数(RSS)达到极小:
* $$
RSS = \sum e_i ^ 2 = \sum (y_i - \hat{\beta}_1 - \hat{\beta}_1 x_i)^2
$$
* 对 RSS 求偏导,得到
$$
\large
\begin{cases}
\frac{\partial RSS}{\partial \hat{\beta}_0} = -2 \sum(y_i - \hat{\beta}_0 -\hat{\beta}_1x_i) = 0
\\
\frac{\partial RSS}{\partial \hat{\beta}_1}-2 \sum(y_i - \hat{\beta}_0 -\hat{\beta}_1x_i)x_i = 0
\end{cases}
$$
* 进一步化简
$$
\large
\begin{cases}
\sum(y_i - \hat{\beta_0} - \hat{\beta_1}x_i) = 0
\\
\sum(y_i - \hat{\beta_0} - \hat{\beta_1}x_i) = 0
\end{cases}
$$
* 上式可得${\sum e_i = 0, \sum e_i x_i = 0}$,这是很重要的两个条件
* 整理可得正规方程组
$$
\large
\begin{cases}
\sum y_i = n\hat{\beta_0} + \hat{\beta_1}\sum x_i
\\
\sum x_iy_i =\hat{\beta_0}\sum x_i + \hat{\beta_1}\sum x_i^2
\end{cases}
$$
* 解得
$$
\Large
\begin{cases}\hat{\beta}_1 = \frac{n\sum x_i y_i - \sum x_i \sum y_i}{n\sum x_i^2 - (\sum x_i ^2)} = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sum(x_i - \bar{x})^2} = \frac{S_{xy}}{S_x^2}
\\
\hat{\beta}_0 = \bar{y} - \hat{\beta}_1\bar{x}
\end{cases}
$$
* 其中, $\Large\bar{y} = \frac{\sum y_i}{n}, \bar{x} = \frac{\sum x_i}{n}, S_{xy} = \frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{n-1}, S_x^2 = \frac{\sum(x_i-\bar{x})^2}{n-1}$
* 由此产生的$\hat{\beta}_0$和$\hat{\beta}_1$称为参数$\beta_0$和$\beta_1$的最小二乘估计量(OLSE)。根据特定样本计算出的$\hat{\beta}_0$和$\hat{\beta}_1$的具体数值称为最小二乘估计值。
#### 2.1-3 普通最小二乘估计
由 OLS 确定的样本回归函数$\large\hat{y}_i = \hat{\beta}_0 + \hat{\beta}_1x_i$有以下性质:
1.样本回归函数是由所选取的样本为一决定的.
2.由$\large\hat{\beta}_0 = \bar{y} - \hat{\beta}_1\bar{x}$知$\large\hat{y}_i = \hat{\beta}_0 + \hat{\beta}_1 x_i$,说明回归直线$\large\bar{y}_i = \hat{\beta}_0 + \hat{\beta}_1 \bar{x}$通过样本的平均点$\large(\bar{x}, \bar{y})$,即通过样本散点图的几何中心。 3.拟合值$\hat{y_i}$的均值等于实际观测值$\large y_i$的均值
$$
\large
\bar{\hat{y}}_i = \frac{1}{n} \sum(\hat{\beta}_0 + \hat{\beta}_1 x_i) = \hat{\beta}_0 + \hat{\beta}_1 \bar{x} = \bar{y}
$$
4.剩余项的均值为 0。由$\large\sum e_i = 0$知,残差的均值为 0:$\large\bar{e} = \frac{\sum e_i}{n} = 0$
5.由$\large \sum e_ix_i = 0$知,$\large e_i$和$\large x_i$的大小无关,进而与$\large \hat{y}_i$的大小无关,即$\large cov(e, x) = cov(e, \hat{y}) =0$。
$$
\large
cov(x_i, e_i) = \frac{1}{n}\sum(x_i - \bar{x})(e_i - \bar{e}) = \frac{1}{n}(\sum e_i x_i -\bar{x}\sum e_i) = 0
$$
#### 2.1-4 拟合优度
样本回归线对样本观测数据拟合的优劣程度,可称为拟合优度。
$$
\large
y_i - \bar{y}= (\hat{y}_i - \bar{y}) + e_i = (\hat{y}_i - \bar{y}) + (y_i - \hat{y}_i)
$$
对上式两边进行平方并且加总,得
$$
\sum (y_i - \bar{y})^2 = \sum(\hat{y_i} - \bar{y})^2 + 2\sum(\hat{y}_i -\bar{y})(y_i - \hat{y}_i) + \sum(y_i - \hat{y}_i)^2
$$
由$\large \sum e_i^2 = 0$和$\large \sum x_i e_i =0$,所以
$$
\sum (\hat{y}_i - \bar{y})(y_i - \hat{y}_i)= \sum(\hat{\beta_0} + \hat{\beta_1}x_i -\bar{y})e_i =\hat{\beta}_0\sum e_i + \hat{\beta}_1\sum x_i e_i - \bar{y} \sum e_i = 0
$$
得到式子:
$$
\begin{align}
\sum(y_i - \bar{y})^2 &= \sum({\hat{y}_i - \bar{y}})^2 + \sum(y_i - \hat{y}_i)^2\\
TSS(总平方和) &= ESS(被解释平方和) + SSR(残差平方和)
\end{align}
$$
样本决定系数:度量 SRF(样本回归函数)对样本数据的拟合程度
$$
R^2 = \frac{ESS}{TSS} = 1 - \frac{RSS}{TSS}
$$
* $R^2$的大小取决于样本,是随样本而变的随机变量。
* 显然, $0 \leq R^2 \leq1$。
* $R^2$越大,说明 SRF 对样本的观测值拟合越好,意味着 x 变动对于 y 变动的解释力越强,线性相关关系越显著,反之亦然。
### 2.2 OLSE 有限样本性质及其古典假定
* 当样本容量既定时,不同样本得到的参数估计值并不完全一致,他们的统计性质称为${样本估计量的有限样本性质}$(或${小样本性质}$)。估计量的有限样本性质的谈论是参数区间估计的基础。
* 准则:
——线性性,即参数估计量是另一个随机变量的线性函数。
——无偏性,即参数估计量的均值或期望值等于总体的真实值。
——有效性,即参数估计量在所有线性无偏估计量中具有最小方差。
* 这三个准则也称为估计量的小样本性质。拥有这类性质的估计量称为最佳线性无偏性(Best Liner Unbiased Estimator, BLUE)
#### 2.2-1 建立 OLSE 无偏性的假定
* ${假定SLR.1: 参数线性}$
即要求模型形式为:$y_i = \beta_0 + \beta_1x_i + u_i$
* ${假定SLR.2:随机抽样(独立同分布)}$
$\{(x_i,y_i):i = 1, 2, 3..., n\}$为来自总体中的随机样本,样本容量为 n。
* ${假定SLR.3:解释变量取值有变异。}$
自变量的观测值$\{(x_i): i= 1, 2, ..., n\}$具有有限的非零方差,即自变量的观测值不能完全相同。
* ${假定SLR.4:随机误差项条件均值为零(解释变量严格外生性)}$
即给定解释变量的任何值,随机误差项的期望值为零:
$$
E(u|x_i)=0
$$
*
* * 第一,总体回归函数设定正确。
$$
E(u) = E_x[E(u|x_i)] = E_x(0) = 0
$$
说明 u 中不包含系统性的影响因素(如遗漏变量/系统的测量误差等),回归模型函数形式设定正确,没有设定偏误。
* * 第二,解释变量$x_i$严格外生。
$$
cov(u_i, x_i) = 0, cov(u,f(x)) = 0
$$
*
> #### 无偏性的证明
>
> 当回归模型满足假定 SLR.1\~SLR.4 时,OLSE 满足无偏性。
>
> 证明:因为
>
> $$
> \sum(x_i-\bar{x})(y_i -\bar{y}) = \sum(x_i-\bar{x})y_i\quad \small
> \\
> \\
> (\sum (x_i -\bar{x})\bar{y} = \bar{y}\sum(x_i-\bar{x})=0)
> \\
> \\
> (\sum(x_i-\bar{x})=\sum x_i -\sum\bar{x} = n\bar{x}-n\bar{x}=0)
> $$
>
> 所以:
>
> $$
> \hat{\beta}_1 = \frac{\sum(x_i - \bar{x})(y_i-\bar{y})}{\sum(x_i - \bar{x})^2} = \frac{\sum(x_i - \bar{x})y_i}{\sum(x_i-\bar{x})^2} = \sum\frac{(x_i -\bar{x})}{\sum(x_i-\bar{x})^2}y_i = \sum k_i y_i
> $$
>
> 其中:$\large k_i = \frac{(x_i-\bar{x})}{\sum(x_i-\bar{x})^2}。(易证:\sum k_i = 0, \sum k_i x_i = 1)$
>
> 进一步由于$y_i = \beta_0 + \beta_1x_i +u_i$,所以:
>
> $$
> \hat{\beta}_1 = \sum k_i (\beta_0 + \beta_1x_i + u_i)= \beta_0\sum k_i + \beta_1\sum k_i x_i + \sum{k_i u_i} = \beta_1 + \sum k_i u_i
> $$
>
> 说明:$\beta_1$是$u_i$的线性组合。
>
> 即使是同一组$x_i$,不同的$u_i$的实现导致了不同的$y_i$,而不同的$(x_i, y_i)$组合导致了不同的$\beta_i$,因此,它是随机变量。
>
> 对$\beta_1$求期望可得:
>
> $$
> E(\hat{\beta}_1|x_i)=E(\hat{\beta}_1)+E(\sum k_i u_i|x_i ) = \beta_1 + \sum k_i E(u_i|x_i) = \beta_1 + \sum k_i · 0 = \beta_1
> $$
>
> 此即证明了$\hat{\beta}_1$的无偏性。$\hat{\beta}_0$的无偏性类似可证。$(E(\hat{\beta})=\beta)$
>
> ${综上,在假定SLR.1~SLR.4满足时,OLS估计量是线性的(Linear)和无偏的(Unbiased),即线性无偏估计量。}$
#### 2.2-2 OLSE 的有效性及其假定
* OLSE 的${有效性}$是指在所有线性无偏估计量中,最小二乘估计量具有最小方差。
* 为了使 OLSE 具有有效性,需要引入下面的假定。
* ${假定SLR.5:随机误差项条件同方差性}$
* 即对给定任意解释变量值,随机误差项都具有相同的方差:
$$
\text{Var}(u_i|x_i) = \sigma_u^2, (i =1, 2, ..., n)
\\
\\
\text{Var}(y_i|x_i) = \sigma_u^2
\\
\\
\text{Var}(u_i) = E(u_i^2) = E_x[E(u_i^2|x)]= E_x(\sigma_u^2) = \sigma_u^2
$$
* $\sigma_u^2$即是 u 的条件方差,也是 u 的无条件方差。一般被称为随机误差项方差
> #### $\hat{\beta}_1$的条件方差的公式
>
> * 推导:$ \hat{\beta}\_1 = \sum k_i y_i$ , 其中, $\large k_i = \frac{(x_i-\bar{x})}{\sum(x_i-\bar{x})^2}$
>
> $$
> \begin{align}
> {\text{var}(\hat{\beta}_1|x_i)}
> &= \text{var}(\sum k_i y_i |x_i)
> &&= \sum k_i^2 \text{var}(\beta_0 + \beta_1x_i + u_i|x_i)
> \\
> &= \sum k_i^2 \text{var}(u_i|x_i)
> &&=\sum (\frac{x_i - \bar{x}}{\sum (x_i-\bar{x})^2})^2\sigma_u^2
> ={\frac{\sigma_u^2}{\sum(x_i-\bar{x})^2}}
> \end{align}
> $$
>
> $$
> {\text{var}(\hat{\beta_0}|x_i)}
> =[\frac{1}{n}+\frac{\bar{x}^2}{\sum (x_i - \bar{x})^2}]\sigma_u^2
> ={\frac{\sum x_i^2}{n \sum(x_i - \bar{x})^2}\sigma_u^2}
> $$
>
> 上式中得出的 OLS 估计量$\hat\beta_0和$$\hat\beta_1$的方差比其他任何线性无偏估计量的方差都要小,即 OLSE 具有有效性。
综上所述,在假定 SLR.1\~SLR.5 下,OLSE 具有线性,无偏性,有效性的有限样本性质,故 OLSE 被称为${最佳线性无偏估计量(\text{Best Linear Unbiased Estimator, BLUE})}$,这就是著名的高斯-马尔可夫定理
#### 2.2-3 OLSE 的正态性及其假定
* 我们还希望 OLSE 服从正态分布
* ${假定SLR.6:随机误差项服从条件正态分布}$
* 假定 SLR.6 与假定 SLR.4 和假定 SLR.5 合在一起,表示为:
$$
\large
u_i|x_i~i.i.d.N(0,\sigma_u^2)
$$
即我们除了假定随机误差项$u$均值独立于$x$,而且假定其独立同分布于均值为零,方差为$\sigma _u^2$的条件正态分布。
等价于
$$
\large
y|x_i~i.i.d.N(\beta_0 + \beta_1, \sigma_u^2)
$$
*
由于$\hat{\beta_1}$是$u_i$的线性组合,由$u_i$的正态性可获得$\hat{\beta_1}$的正态性:
$$
\hat{\beta}_0|x \sim N(\beta_0, \frac{\sum x_i^2}{n\sum(x_i-\bar{x})^2}\sigma_u^2)\quad\quad \hat{\beta_1}|x\sim N(\beta_1, \frac{\sigma_u^2}{\sum(x_i - \hat{x})^2})
$$
总结,在古典假定下,OLSE 具备无偏性,有效性和正态性。
### 2.3 参数的统计推断
#### 2.3-1 估计量分布
* 对于一元线性分布回归模型,已知服从正态分布:
$$
\hat{\beta_0}|x \sim N(\beta_0, \frac{\sum x_i^2}{\sum n(x_i-\bar{x})^2}\sigma_u^2)\quad\quad\hat{\beta_1}|x \sim N(\beta_1, \frac{\sigma_u^2}{\sum(x_i-\bar{x})^2})
$$
* $\hat{\beta_0}$和$\hat{\beta_1}$的标准误差的计算公式为:(标准误差是方差的算术平方根)
$$
sd(\hat{\beta_0})= \text{var}(\hat{\beta_0}|x_i)=\sqrt{\frac{\sum x_i^2}{n\sum (x_i - \bar{x})^2}\sigma_u^2}
\quad\quad
sd(\hat{\beta_1} =\text{var}(\hat{\beta}_1|x_i)= \sqrt{\frac{\sigma_u^2}{\sum(x_i-\bar{x})^2}}
$$
* 结论:$\hat{\beta}|x \sim N[\beta, \text{var}(\hat{\beta})]$
##### 标准变换
$$
\hat{\beta_0}|x \sim N(\beta_0, \frac{\sum x_i^2}{\sum n(x_i-\bar{x})^2}\sigma_u^2)\quad\quad\hat{\beta_1}|x \sim N(\beta_1, \frac{\sigma_u^2}{\sum(x_i-\bar{x})^2})
$$
* 为了便于直接利用“标准化正态分布的临界值”作统计分析,需要对$\hat{\beta}$进行标准变换。
* 标准化方式:$\Large\frac{\hat{\beta}-\beta}{sd (\hat{\beta})}$
${注意:此时假设{black}{\sigma_u^2}是已知的,{black}{sd(\hat{\beta})}不是随机变量}$
> ##### $\sigma_u^2$估计
>
> * 由于真实的$\sigma_u^2$未知,需要利用样本对其进行估计。可证,在古典假设下:
>
> $$
> \Large
> SER(回归标准误)^2=E(\frac{(RSS\sum e_i^2)}{n-2})= \sigma_u^2
> $$
>
> * 残差的样本方差,即均方误差(Mean Square Error,MSE)记为$\hat{\sigma_u^2}$
>
> $$
> \hat{\sigma}_u^2 = MSE = S_e^2 = \frac{\sum e_i ^2}{n-2} = \frac{RSS}{n-2} = \frac{\sum (y_i-\hat{y}_i)^2}{n-2}
> $$
>
> * n-2 为自由度,即可自由变化的样本观测个数
>
> ${注意}$:$\sigma_u^2$是未知确定的常数;$\hat{\sigma}_u^2$是由样本信息估计的,是一个随机变量。
* $\sigma_u^2$未知,可用$\hat{\sigma_u^2}$代替$\sigma_u^2$(随机变量)去估计参数的标准误差
* 即$\hat{\beta_0}$和$\hat{\beta_1}$的样本标准误差的计算公式为
$$
se(\hat{\beta_0}) = \sqrt{\frac{\sum x_i^2}{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2}
\quad
\quad
se(\hat{\beta_1}) = \sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}}
$$
* 此后,标准变换后服从 t 分布:
$$
\frac{\hat{\beta}-\beta}{se(\hat{\beta})} \sim t(n-2)
$$
* 对$\hat{\beta}_0$和$\hat{\beta}_1$进行标准变换,构造的枢轴变量服从 t 分布:
$$
\large
t = \frac{\hat{\beta}_0-\beta_0}{se(\hat{\beta}_0)} = \frac{\hat{\beta}_0-\beta_0}{\sqrt{\frac{\sum x_i^2}{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2}} \sim t(n-2)
$$
$$
\large
t = \frac{\hat{\beta}_1-\beta_1}{se(\hat{\beta}_1)} = \frac{\hat{\beta}_1-\beta_1}{\sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}}} \sim t(n-2)
\quad
\quad
$$
#### 2.3-2 回归系数的假设检验
* 回归系数的假设检验主要是判断 x 是否对 y 具有显著性影响,即针对变量的${参数真值是否为零}$进行变量的显著性检验
> - 假设检验的基本步骤(临界值比较法)
>
> 第一步:提出假设 原假设$H_0:\beta_1 = 0;$备择假设$H_1:\beta_1 \ne 0$
>
> 第二步:构造 t 统计量
>
> $$
> \large
> t = \frac{\hat{\beta}_1}{se(\hat{\beta}_1)} = \frac{\hat{\beta}_1}{\sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}}} \sim t(n-2)
> \quad
> \quad
> $$
>
> 第三步:给定一次试验中小概率发生的可能性即显著水平$\alpha$,查 t 分布临界$t_0 = t_{\alpha/2}(n-2)$。$\alpha$通常取 0.01 或 0.05。
>
> 第四步:做出统计决策。当$|t|\ge t_0$时,拒绝原假设$H_0:\beta_1 = 0$;当$|t| 问题:$\alpha$是给定的,如何取寻求合适的$\delta$呢?
>
> 原则:利用$\hat{\beta}$标准化后的分布性质去寻求$\large\delta:\frac{\hat{\beta}-\beta}{se(\hat{\beta})}\sim t(n-2)$
>
> 将对应于显著性水平$\alpha$的 t 分布临界值简记为$t_0=t_{\alpha/2}(n-2)$,有
>
> $$
> P(|\frac{\hat{\beta}_1-\beta_1}{se(\hat{\beta_1})}|\le t_0) = 1- \alpha
> $$
>
> 所以在$(1-\alpha)$的置信水平下,有$\Large|\frac{\hat{\beta}_1-\beta_1}{se(\hat{\beta}_1)}|\le t_0$,或者$\Large |\frac{\hat{\beta}_1-\beta_1}{\sqrt{\frac{\hat{\sigma}_u^2}{\sum (x_i-\bar{x})^2}}}| \le t_0$
>
> 由此可得,$\beta_1$在置信水平为$1-\alpha$下的置信区间为:
>
> $$
> \left[\hat{\beta}_1-t_0 \sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}},
> \quad
> \hat{\beta}_1+t_0 \sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}}\quad\right]
> $$
>
> 同理,$\beta_0$在置信水平为$1-\alpha$下的置信区间为:
>
> $$
> \left[\hat{\beta}_0-t_0\sqrt{\frac{\sum x_i^2 }{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2},\quad
> \hat{\beta}_0+t_0\sqrt{\frac{\sum x_i^2 }{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2}\quad\right]
> $$
由于$\beta_1$的 t 统计量在大样本下服从 N(0,1),因此$\beta_1$的 95%置信区间构造类似于总体均值的情形:
$$
\beta_1的95\%置信区间:= [\hat{\beta}_1\pm1.96SE(\hat{\beta}_1)]
$$
99%的置信区间则为:
$$
\beta_1的99\%置信区间:= [\hat{\beta}_1\pm2.58SE(\hat{\beta}_1)]
$$
### 本章公式总结
**总体回归函数**
$$
\large
E(y|x_i) = f(x_i) =\beta_0 + \beta_1x_1
$$
**$\beta_0$截距 $\beta_1$斜率**
**总体回归模型**
$$
\large
y_i = E(y|xi) + u_i = \beta_1 + x_i + u_i
$$
**随机误差项**
$$
\large
u_i = y_i - E(y|x_i)
$$
**样本回归函数**
$SRF$
$$
\large
SRF: {\hat{y}_i = \hat{\beta}_0 + \hat{\beta}_1}x_i
$$
**样本回归模型**
$SRM$
$$
\large
SRM: {\hat{y}_i = \hat{\beta}_0 + \hat{\beta}_1x_i + e_i}
$$
**残差**
书里面的残差是\*\*$\hat{u}_i$\*\*符号
$$
e_i = y_i-\hat{y}_i
$$
**被解释平方和(Explained Sum of Squares)**
$ESS$
$$
ESS = \sum (\hat{y}_i-\bar{y})^2
$$
**总平方和(Total Sum of Squares)**
$TSS$
$$
TSS = \sum (y_i-\bar{y})^2
$$
**残差平方和(Sum of Squared Residuals)**
$SSR$
$$
SSR = \sum \hat{u}_i^2
$$
**回归(regression)**
$R^2$
$$
R^2 =\frac{ESS}{TSS} = 1- \frac{SSR}{TSS}
$$
**回归标准误(standard error of the regression)**
$SER$
$$
SER = S_{\hat{u}}=\sqrt{S_{\hat{u}}^2}
\\
其中S_{\hat{u}}^2=\frac{1}{n-2}\sum\hat{u}_i^2
=\frac{SSR}{n-2}
$$
$\hat{\beta_0}$和$\hat{\beta_1}$的**样本标准误差**的计算公式为
$$
SE(\hat{\beta}_0) = \sqrt{\frac{\sum x_i^2}{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2}
\quad
\quad
SE(\hat{\beta}_1) = \sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}}
\\
\\
\text{Var}(u_i) = E(u_i^2) = E_x[E(u_i^2|x)]= E_x(\sigma_u^2) = \sigma_u^2
$$
由此可得,$\beta_1$在置信水平为$1-\alpha$下的**置信区间**为:
$$
\left[\hat{\beta}_1-t_0 \sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}},
\quad
\hat{\beta}_1+t_0 \sqrt{\frac{\hat{\sigma}_u^2}{\sum(x_i-\bar{x})^2}}\quad\right]
$$
$$
\left[\hat{\beta}_1-t_0SE(\hat{\beta}_1),\quad
\hat{\beta}_1+t_0SE(\hat{\beta}_1)\quad\right]
$$
同理,$\beta_0$在置信水平为$1-\alpha$下的**置信区间**为:
$$
\left[\hat{\beta}_0-t_0\sqrt{\frac{\sum x_i^2 }{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2},\quad
\hat{\beta}_0+t_0\sqrt{\frac{\sum x_i^2 }{n\sum(x_i-\bar{x})^2}\hat{\sigma}_u^2}\quad\right]
$$
$$
\left[\hat{\beta}_0-t_0 SE(\hat{\beta}_0),\quad
\hat{\beta}_0+t_0 SE(\hat{\beta}_0)\quad\right]
$$
**$\beta_1的双边假设$**
> 设置原假设和双边备泽假设分布为
>
> $$
> H_0:\beta_1=\beta_{1.0}
> \quad
> \quad
> H_1:\beta_1 \ne \beta{1.0}(双边备泽假设)
> $$
>
> 为了检验原假设$H_0$,我们采用与总体均值假设检验相同的三个步骤。
>
> 第一步,计算$\hat{\beta}_1$的标准误$SE(\hat{\beta}_1)$。它是$\hat{\beta}_1$抽样分布的标准差$\hat{\sigma}_{\hat{\beta}_1}$的估计量。
>
> 第二步,计算**t 统计量**
>
> $$
> t^{act} = \frac{\hat{\beta}_1-\beta_{1.0}}{SE(\hat{\beta}_1)}
> $$
>
> 第三步,计算 p 值,即在原假设成立的条件下,得到与$\beta_{1.0}$的距离至少和实际计算的估计值$\hat{\beta}_1^{act}$与$\beta_{1.0}$的距离相同的概率。其数学表达式为
>
> $$
> p值 = Pr_{H_{0}}[|\hat{\beta}_1-\beta_{1.0}|>|\hat{\beta}_1^{act}-\beta_{1.0}|]
> =Pr_{H_0}\left[\left|\frac{\hat{\beta}_1-\beta_{1.0}}{SE(\hat{\beta}_1)}\right|>\left|\frac{\hat{\beta}_1^{act}-\beta_{1.0}}{SE(\hat{\beta}_1)}\right|\right]=Pr_{H_0}(|t|>|t^{act}|)
> $$
>
> 其中,$Pr_{H_0}$表示在原假设成立的条件下计算得到的。
>
> 因为在大样本的下$\hat{\beta}_1$近似服从正态分布,因此在原假设条件下,t 统计量近似服从标准正态分布,故在大样本下有
>
> $$
> p值 = Pr(|Z|>|t^{act}|) = 2\Phi(-|t^{act}|)
> $$
$\hat{\beta}_1-\beta_1=\frac{\sum (x_i-\bar{x})u_i}{\sum(x_i-\bar{x})^2}$
## 第三章:多元线性回归模型
### 3.1 OLS(最小二乘法)
* 多元线性回归模型和一元线性回归模型的类似,只是多了一些参数
* 多元线性回归模型形式
$$
y=\beta_0+\beta_1 x_{1}+\beta_2 x_{i}+...+\beta_k x_{k} + u
$$
* $\beta_1$表示在保持$x_{2i},x_{3i},...,x_{ki}$不变的情况下,$x_{1i}$变化一个单位,对$y_{i}$的影响。
* 如果将 n 组实际观测数据$(y_i,x_{1i},x_{2i},...,x_{ki})(i=1,2,...,n)$代入,可得到下列形式:
$$
y_i=\beta_0+\beta_1 x_{1i}+\beta_2 x_{2i}+...+\beta_k x_{ki} + u_i
\quad
\quad
(i=1,2,...,n)
$$
$$
即:
\\
\begin{cases}
y_i=\beta_0+\beta_1 x_{11}+\beta_2 x_{21}+...+\beta_k x_{k1} + u_1
\\
y_2=\beta_0+\beta_1 x_{12}+\beta_2 x_{22}+...+\beta_k x_{k2} + u_2
\\
...
\\
y_n=\beta_0+\beta_1 x_{1n}+\beta_2 x_{2n}+...+\beta_k x_{kn} + u_n
\end{cases}
$$
上述方程组可表示为:
$$
\left[\begin{matrix}
y_1\\
y_2\\
...\\
y_n\\
\end{matrix}
\right]
=\left[\begin{matrix}
1 &x_{11} &x_{21} &... &x_{k1}\\
1 &x_{12} &x_{22} &... &x_{k2}\\
\vdots &\vdots &\vdots &\cdots &\vdots\\
1 &x_{1n} &x_{2n} &... &x_{kn}\\
\end{matrix}
\right]
\left[\begin{matrix}
\beta_0\\
\beta_1\\
...\\
\beta_k\\
\end{matrix}
\right]
+
\left[\begin{matrix}
u_0\\
u_1\\
...\\
u_n\\
\end{matrix}
\right]
\\
Y \quad\quad\quad\quad\quad\quad\quad\quad
X \quad\quad\quad\quad\quad\quad
\beta \quad\quad\quad
u
\\
\quad\quad\quad\quad\quad\quad\quad
n \times 1 \quad\quad\quad\quad
n\times (k+1)\quad\quad
(k+1)\times1 \quad
n\times 1\quad\quad\quad\quad\quad
$$
$$
\begin{align*}
&\text{多元线性总体回归模型:} \quad Y = X\beta + u
\quad
&&\text{多元线性总体回归函数:} \quad E(Y|X) = X\beta
\\
&\text{多元线性样本回归模型:} \quad Y = X\hat{\beta} + e
\quad
&&\text{多元线性样本回归函数:} \quad \hat{Y} = X\hat{\beta}
\end{align*}
$$
#### 3.1-2 最小二乘法原理
* 多元线性回归方程的未知参数估计和一元线性回归方程原理相同,依旧采用普通最小二乘法(OLS)进行参数估计,估计准则是令残差平方和 Q 达到最小。其中
$$
Q = \sum{e_i^2} = \sum(y_i-\hat{y}_i)^2 = \sum(y_i-\hat{\beta}_0-\hat{\beta}_1 x_{1i}-\hat{\beta}_2 x_{2i}-...-\hat{\beta}_k x_{ki})^2
$$
对每个$\hat{\beta}_i$求偏导,得到
可知
$$
\Large
\begin{cases}
\frac{\delta Q}{\delta\hat{\beta}_0}=\sum e_i =0
\\
\frac{\delta Q}{\delta\hat{\beta}_1}=\sum e_i x_{1i} =0
\\
...
\\
\frac{\delta Q}{\delta\hat{\beta}_k}=\sum e_i x_{ki} =0
\end{cases}
$$
整理后得到方程组:
$$
\Large
\begin{cases}
\sum y_i = n\hat{\beta}_0 + \hat{\beta}_1\sum x_{1i} + \hat{\beta}_2\sum x_{2i} + \dots + \hat{\beta}_k\sum x_{ki}
\\
\sum x_{1i}y_i = \hat{\beta}_0\sum x_{1i} + \hat{\beta}_1\sum x_{1i}^2 + \hat{\beta}_2\sum x_{1i}x_{2i} + \dots + \hat{\beta}_k\sum x_{1i}x_{ki}
\\
\vdots
\\
\sum x_{ki}y_i = \hat{\beta}_0\sum x_{ki} + \hat{\beta}_1\sum x_{ki}x_{1i} + \hat{\beta}_2\sum x_{ki}x_{2i} + \dots + \hat{\beta}_k\sum x_{ki}^2
\end{cases}
$$
矩阵形式为
$$
\left[\begin{matrix}
1 &1 &... &1\\
x_{11} &x_{12} &... &x_{1n}\\
\vdots &\vdots &... &\vdots\\
x_{k1} &x_{k2} &... &x_{kn}
\end{matrix}
\right]
\left[\begin{matrix}
y_1\\
y_2\\
\vdots\\
y_n
\end{matrix}
\right]
=
\left[\begin{matrix}
1 &1 &... &1\\
x_{11} &x_{12} &... &x_{1n}\\
\vdots &\vdots &... &\vdots\\
x_{k1} &x_{k2} &... &x_{kn}
\end{matrix}
\right]
\left[\begin{matrix}
1 &x_{11} &... &x_{k1}\\
1 &x_{12} &... &x_{k2}\\
\vdots &\vdots &... &\vdots\\
1 &x_{1n} &... &x_{kn}
\end{matrix}
\right]
\left[\begin{matrix}
\hat{\beta}_0\\
\hat{\beta}_1\\
\vdots\\
\hat{\beta}_k
\end{matrix}
\right]
\\
\quad\quad\quad\quad\quad\quad
X' \quad\quad\quad\quad\quad\quad\quad
Y \quad\quad\quad\quad\quad\quad\quad
X' \quad\quad\quad\quad\quad\quad\quad
X \quad\quad\quad\quad\quad\quad
\hat{\beta}\quad\quad\quad\quad
\\
\quad\quad\quad\quad
(k+1)\times n\quad\quad\quad\quad\quad
n\times 1\quad\quad\quad
(k+1)\times n\quad\quad\quad\quad
n \times (k+1)\quad\quad\quad
(k+1)\times 1\quad
$$
即:$X'Y=X'X\hat{\beta}$
#### 3.1-3 标准化系数
* 由于各个变量的单位不同,所代表的意思也不同,因此需要对回归系数进行标准化
* $$
x_{ji}^*=\frac{x_{ji}-\bar{x}_j}{\sqrt{\frac{1}{n+1}\sum(x_{ji}-\bar{x}_j)^2}}=\frac{x_{ji}-\bar{x}_j}{S_{x_j}}
$$
*
$$
y_i^*=\frac{y_i-\bar{y}_i}{\sqrt{\frac{1}{n+1}\sum(y_i-\bar{y})^2}}=\frac{y_i-\bar{y}_i}{S_y}
$$
$$
\hat{\beta}_j^*=\frac{S_{x_j}}{S_y}=\sqrt{\frac{\sum(x_{ji}-\bar{x}_j)^2}{\sum(y_i-\bar{y})^2}}\hat{\beta}_j
$$
#### 3.1-4 多元回归拟合优度
* 拟合效果的三种度量:回归标准误差、$R^2$和调整$R^2$
实际值=预测值+残差:$Y_i = \hat{Y}_i+\hat{e}_i$
$$
SER=\hat{e}_i的标准差(经过自由度调整的)=\sqrt{\frac{1}{n-k-1}\sum \hat{e}_i^2}
$$
$$
RMSE=\hat{e}_i的标准差(没经过自由度调整的)=\sqrt{\frac{1}{n-1}\sum \hat{e}_i^2}
$$
因为模型中自变量的数量变多时,SER 一般会变小,而$R^2$会变大,所以需要引入$\bar{R}^2$
$$
R^2=Y方差中由X解释的部分=\frac{ESS}{TSS}=1-\frac{SSR}{TSS}
$$
$$
\bar{R}^2=经过自由度调整的R^2=1-\left(\frac{n-1}{n-k-1}\right)\frac{SSR}{TSS}=1-\left(\frac{n-1}{n-k-1}\right)(1-R^2)
\\
\bar{R}^2 1. 考虑如下回归模型$𝑌_i=\beta_0+\beta_1𝑋_i+𝑢_i$,并且有$𝐶𝑜𝑣(𝑢_i,𝑋)=0$。有一位研究 者想要使用调研数据来估计 𝛽。但是他发现,调研中的个体系统性地将$𝑋_i$低汇 报了 50%。因此,研究者实际使用的数据是独立同分布的 𝑌 和$X_i^*$观测值,这里 $ X_i^\*=0.5𝑋$。这位研究者用OLS来估计如下模型:$Y_i=\beta_0+\beta_1𝑋_i^∗+v_i $
>
> (1)请求出$𝐶𝑜𝑣(𝑣_i,𝑋_i^*)$。( 10 分)
>
> (2)𝛽 的 OLS 估计量是一致的吗?请解释说明或证明。( 10 分)
>
> 2. 假设针对某国某城市,你想用数据去估计该城市最低工资对 18 ~ 25 岁可就业 者的就业率的效应。一个简单的计量模型可以设定为 ,
>
> $$
> gEMP_t=\beta_0+\beta_1gMIN_t+\beta_2gPOP_t+\beta_3gGSP_t+\beta_4gGDP_t+u_t
> $$
>
> 这里$MIN_t$是最低工资(以美元计),$POP_t$是 18 ~ 25 岁的劳动人口,$GSP_t$是该 市的国民生产总值,$GDP_t$是该国的国民生产总值。每个变量前的前缀 g 表明这 个变量是从第 t-1 年到第 t 年的增长率变量。
>
> (1)如果我们担心该市在选择最低工资时部分地基于我们观察不到但确实会影 响年轻人就业率的因素,此时 OLS 估计量会有什么问题?(20 分)
>
> (2)令$USMIN_t$表示该国的国家层面的最低工资。你认为$gUSMIN_t$是与$u_t$不 相关的吗?请判断,并解释。(20 分)
>
> 3. 在一项关于大学生成绩与大学生日常时间分配的研究中,研究者们向 1000 名 大学生发放问卷了解其成绩与日常时间分配。学生需要将自己一周时间归为 4 类活动:学习、睡觉、兼职和闲暇。因为任何活动都被归入 4 类中的一类,所 以学生一周所有活动的总时间一定等于 168 小时。所有学生都完成了问卷并交 还了问卷。之后,研究者使用以下模型进行计量经济分析:
>
> $$
> 成绩=\beta_0+\beta_1学习+\beta_2睡觉+\beta_3兼职+\beta_4闲暇+u
> $$
>
> (1)研究者使用上述模型进行研究,OLS 估计得到 $\hat{\beta}_1=2$,相应的标准误差为 0.2。请问你是否相信这个结果的正确性?如果“是”,请简要解释。如果“否”, 请指出问题,并做出修正使研究者得到正确结果。(20 分)
>
> (2)另一位研究者在核对了原模型设定之后,想知道是不是学习时间越多,就 能越来越快地提高成绩,那么他应该如何修改模型?如果该研究者想进一步了 解睡眠是否有助于高效学习,那么要如何修改模型?(20 分)
# English short fiction appreciation
Source: https://base.bangwu.me/about/courses/english-fiction
Course notes on English short fiction analysis covering narrative techniques, foreshadowing, and readings of The Rocking-Horse Winner and The Garden Party.
以下文章来自[青灰色的风](https://www.cnblogs.com/68786C)然后我再结合今年(2024年上半年)上课新增的小说进行的补充
# 英语短篇小说佳作欣赏
> 如果你是SL老师的学生,恭喜你遇到一位很棒的英语老师,也欢迎你继续阅读这篇笔记,希望这篇笔记能够帮助到你,可以点个赞👍让我知道你来过。如果你愿意分享自己的笔记或感悟,也欢迎留言给我:)
# 本门课程考试考什么?
## 2023学年第一学期考试情况分享 感谢 @SeeSeen
第一部分`10`个选择题,一方面是要**词汇量**,另一方面是**对文章内容的了解掌握**;
第二部分`10`个`选词填空`,分别是 style , theme , foreshadowing , conflict , setting 等等这种,比较简单;
第三部分`3`个写作题(大致意思)
1、Is the house a haunted house?`(The Rocking-Horse Winner)`
2、Please comment on her writing?`(The Garden Party)`
3、Do you think the story is still meaning nowadays?`(Lottery)`
# 本门课程课上学什么?
## The writer, the narrator and the reader 作者、叙述者与读者
### A Piece of Yellow Soap
小说概要:收债的“我”在面对一位坚强的妇女时不知所措。
1. What sex is the narrator?
2. What age-group would you put the narrator in?
3. What is the narrator’s occupation?
4. From the information provided, what do you think the narrator believes in?
5. Come up with three adjectives to describe the kind of person the narrator is.
6. What kind of narration in the novel?
7. Does soap really have such power?
8. What does soap symbolise?
点击查看答案
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
1. Male.
2. Middle-age people.
3. Milkman.
4. Maybe she believes in Christianism. "not sure that I believe in Heaven or God myself."
5. Naive anxious, Worried, Confused
6. This is a first-person narrative.
7. No. Soap does not have the power, it was this woman's strength, self-reliance and her behavior in the face of the milkman that gave him a huge shock, making him dare not face this woman,and then he transfered this emotion to this soap, making it feel that soap had great power.The power of soap is the power of compassion, evoked by the hard lives of the people at the bottom.
8. Soap -> A symbol of poverty and despair.
```
### The Washwoman
小说概要:儿子不讲信用,不管自己的当洗衣女工的辛勤工作的母亲。
《洗衣女工》是根据真实故事改编的,由艾萨克·巴舍维斯·辛格(Isaac Bashevis Singer)撰写,对一个小男孩和一个年迈的洗衣妇之间的关系的辛酸描述。
这个故事突出了 **20 世纪初美国工人阶级,特别是妇女所面临的斗争和艰辛。** 这个故事是根据辛格自己在纽约市一个犹太移民家庭长大的经历以及他对为家人工作的洗衣女工的回忆。
1. Describe the kind of person the washwoman is.
2. Describe the author's attitude towards the washwoman.
3. Who is the narrator?
4. What is the theme of novel?
5. 在小说结尾,作者沉思着说,她的灵魂进入了所有圣灵相遇的领域,无论他们在地球上扮演什幺角色。你认为作者的母亲会同意他的观点吗?用文章中的例子来支持你的回答。
6. 在小说结尾中,她过着她的生活,做她的工作没有怨恨。用怨恨这个词的含义来解释这个说法。
* 在这篇小说中,洗衣女工面临哪些困难?她如何应对这些挑战?
* 作者如何描述洗衣女郎?为什幺描述对叙事很重要?
* 在文章中间,作者的母亲说,洗衣女的儿子对自己的母亲不忠,对所有母亲都是侮辱。儿子对母亲不忠吗?用例子来解释你的观点。
点击查看答案
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
1. Kindly, honest and dependable.
2. the narrator admire her sense of duty and pride in her work.
3. The author of the story - Isaac Singer - is the narrator.
4. The story touches on the themes of guilt, regret, and the passage of time.
他为在她活着的时候没有完全欣赏她而感到内疚,并为他没有做更多的事情来帮助她而感到遗憾。这种遗憾感强调了故事的中心主题之一:重视人际关系的重要性,而不是将人视为理所当然。
He feels guilty for not fully appreciating her while she was alive and regrets that he did not do more to help her. This sense of regret underscores one of the central themes of the story: the importance of valuing human connections and not taking people for granted.
5. Rancor means bitterness or resentment. The statement that the washwoman lives her life and does her work without rancor means that she does not hold any bitterness or resentment towards her circumstances, despite the hardships she faces. She accepts her lot in life and makes the best of it, without allowing negative emotions to consume her.
6. It is difficult to say whether the author's mother would agree with him that the washwoman's soul passed into holy spheres. However, earlier in the essay, she does express admiration and respect for the washwoman's hard work and resilience. Therefore, it is possible that she too would believe in the washwoman's inherent goodness and spirituality.
```
***
### The Rocking-Horse Winner
"D.H. 劳伦斯的短篇小说《摇马赢家》讲述了一个名叫保罗的小男孩决心为家人带来好运的故事。尽管保罗生活在一个看似舒适的家庭中,但他的家庭一直在经济不安全的情况下挣扎,而这一切都源于他母亲对财富和地位的贪得无厌。她认为他们的不幸源于缺乏运气,尤其是保罗的父亲。
保罗开始沉迷于证明自己有运气。他发现,骑上自己的玩具摇摆马,就能预测赛马的胜负。在家里的园丁巴塞特和叔叔奥斯卡的帮助下,保罗开始赌马,并积累了一大笔钱。
保罗的动机是为了更多的钱而停止房子里的鬼魂低语,他相信这会给母亲带来幸福,结束她对孩子们的冷漠态度。尽管赢得了巨额奖金,但压力和母亲的持续不满让保罗倍感沉重。
为了赢得最后的胜利,保罗疯狂地骑着他的摇摆木马,最终预测出了德比大赛的冠军马拉巴尔。然而,巨大的压力导致保罗发烧倒下。他成功地为母亲筹到了一大笔钱,却因此付出了生命的代价。故事的结尾充满了悲剧性的讽刺:保罗不顾一切地试图确保家庭的经济未来和母亲的爱,最终导致自己英年早逝,给母亲留下了金钱,却没有留下她从未真正欣赏过的儿子。
## Symbol 象征
### Old Man at the Bridge
小说概要:在西班牙横跨河流的浮桥边,叙述者被派去执行过桥的任务,他遇到了一位七十六岁的老人。这位老人已经离开了他的家乡圣卡洛斯,在那里他照顾动物。他告诉叙述者,他是最后一个离开小镇的人。他多次回到他最喜欢的话题:他照顾镇上的动物。他有两只山羊和一只猫,还有四对鸽子。但他太老了,已经走不动了。
1. What do all the animals in the novel symbolise?
2. What writing style of Hemingway's does this novel reflect?
点击查看答案
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
1. "Goat" -> The animals who can't escape. Sacrificial animals. Scape goats who are innocent victims.
"Cat" -> Ominousness and fear in people's hearts.
"Dove" -> The peace that people are committed to and eternally pursuing, which in this context is ironic. The doves will fly away.
2. 冰山理论 Iceberg Theory
放弃描写战争的宏大场面,只选择了这样一个渺小而又平凡的场面作为创作素材。
Abandon the view of the war and only describe the dialogue between the narrator and the old man.
The Bridge is a final Bridge between life and death.
```
> 海明威的冰山理论 [https://en.wikipedia.org/wiki/Iceberg\_theory](https://en.wikipedia.org/wiki/Iceberg_theory)
***
## Tone 作者的态度
### The Summer of the Beautiful White Horse
《美丽白马的夏天》由一个名叫阿拉姆的九岁亚美尼亚男孩讲述,他是加罗拉尼亚部落的成员,生活在加利福尼亚州圣华金山谷郁郁葱葱的果园和葡萄园中。一天早上,亚兰在凌晨四点被他十三岁的表弟穆拉德叫醒,除了阿兰姆之外,所有人都认为他痴呆了,并且对动物有办法。亚兰惊讶地看到穆拉德坐在一匹美丽的白马上。亚兰一直想骑一匹白马,但他家里太穷了,买不起。然而,尽管贫穷,加罗格拉尼亚部落以其诚实和信任而闻名,因此,穆拉德会偷走这匹马是不可想象的。亚兰觉得他的表弟不可能偷马。
穆拉德的疯狂行为被认为是他们的叔叔霍斯罗夫的自然后裔,尽管他的父亲佐拉布是一个务实的人。 科斯罗夫叔叔是一个大个子,总是愤怒、不耐烦、易怒。他会咆哮着让每个人都停止说话,并说这没有伤害,不要注意它。事实上,有一天,当他的儿子来告诉他们他们的房子着火了时,科斯罗夫吼道:“够了。这无妨”。
亚兰被邀请与穆拉德一起骑马。穆拉德偷马的想法从阿兰姆的脑海中消失了,因为他觉得除非他们提出卖掉马,否则不会变成偷马。他们喜欢骑马几个小时。
骑了一会儿,穆拉德想一个人骑马。亚兰姆也有同样的渴望,但当他坐在马上踢肌肉时,它抬起头来,哼哼唧唧地向前跑去,最终把亚兰从背上摔了下来。半小时后,他们找到了这匹马,把它藏在一个名叫 Fetvajian 的农民的废弃葡萄园的谷仓里,这曾经是他的骄傲。
那天下午,一位名叫约翰·拜罗(John Byro)的亚述农民——加罗格拉尼亚人的亚述朋友——来到亚兰的家。他向阿兰姆的母亲报告说,他一个月前被盗的白马仍然不见了。听到这句话,亚兰得出结论,穆拉德一定有这匹马很久了。拜罗来的时候,正在阿兰姆家的科斯罗夫大喊“没有坏处”,以至于拜罗被迫离开以避免回应。
亚兰跑到穆拉德身边,告诉他拜罗的到来。亚兰还恳求穆拉德在学会骑马之前不要归还马匹。穆拉德不同意说亚兰至少需要一年的时间才能学会,但他承诺他最多会保留六个月。这成了例行公事。穆拉德每天都来接阿兰骑马,每次尝试后,亚兰姆都会不断地从马背上摔下来。两周后,当他们打算把马带回藏身之处时,他们在路上遇到了约翰·拜罗。农夫非常惊讶。他认出了他的马,但拒绝相信男孩们偷了它。后来,男孩们悄悄地把马还了回去。当天下午,拜罗来到阿兰姆家,通知被盗的马已经归还。他感谢上帝,因为这匹马的脾气也变得更好了,也表现得很好。
## Modernisim 现代
### The Screat Life of Walter Mitty
常常心不在焉的主人公沃尔特·米蒂在开车送妻子去城途中又一次习惯性陷入了充满英雄情结的白日梦。
他把自己幻想为一位英勇的海军飞机指挥官,果断地带领部下穿越重重风暴和迷雾。
作为海军飞机指挥官全速飞行穿越风暴的幻觉产生于他驾车飞速行驶的过程中;
妻子在美发店下车之后,他又陷入了第二场白日梦。这一次他摇身一变成为了一位医术高超、闻名遐迩的外科医生,仅仅用一支钢笔就不费吹灰之力地修好了出了故障的麻醉机,并在众名医束手无策的情况下挥洒自如地为垂死的著名银行家施行手术。
把自己想象成外科医生的幻觉则来源于他所戴的白手套、妻子所提及的医生以及刚刚路过的一家医院;
从停车场出来之后,行走在大街上,他又开始了第三场白日梦,这次他是一位百发百中的神枪手,在法庭上为自己辩护,并狠狠地教训了凶暴的地方检察官。
产生作为神枪手出现在法庭上的幻觉则是因为报童的叫卖中提及的有关庭判的头条新闻;
在第四场白日梦中他又成了英国皇家空军的轰炸机机长,准备穿越德的炮弹封锁执行一项自杀式的军火运输任务。
而成为英国皇家空军的轰炸机机长的幻觉来自于一张旧报纸上的文字和图片。
故事末尾的最后一场白日梦中,他则变成了一个永不低头的死刑犯,面对着行刑队,始终保持神秘莫测、桀骜不驯。
妻子准备给他买精神药物
Daydream
## Style 风格
### Araby 意识流
孤儿主角被邻居姐姐吸引,想要去阿拉比集市购买物品送给她,结果姑父来的很晚,去了又被成年人的爱情所打击,最终成长。
通过使用第一人称叙事,乔伊斯传达了年轻男主的困惑思想和梦想。乔伊斯利用这种对叙述者感受的熟悉,在读者中唤起了一种类似于男孩在故事转折点的“顿悟”的反应——一个突然的洞察力和理解的时刻。
通过使用第一人称叙事,乔伊斯传达了他年轻男主角的混乱思想和梦想。乔伊斯利用这种对叙述者感受的熟悉,在读者中唤起了一种类似于男孩的'顿悟'的反应——在故事的转折点上突然的洞察力和理解的时刻“(5)。如果没有观众对男孩的压力有同理心的联系,就不会与他的发展有任何联系,乔伊斯在最后主要使用它来创建他的角色的顿悟和并行主题。
## Details 细节
### The Open Window
姑姑在焦急地等待丈夫归来,小姑娘在想着如何捉弄无聊的客人,客人在自顾自沉浸在对自己病体的自怨自艾中。
创造真实感所需的所有细节:打开的窗户、棕色的西班牙猎犬、白大褂,甚至是所谓的沼泽的泥土。透过悲剧的幽灵镜头,所有普通的细节,包括阿姨的评论和行为,都呈现出一种令人毛骨悚然的基调。
"self-possessed 女孩
## Character and characterization
### Mr.Know-All
妻子背叛 , 凯兰达没有说出真相
1. Mr. Max Kelada: Mr. Kelada is the central character in "Mr. Know-All." He is portrayed as a gregarious, talkative, and confident man who is proud of his accomplishments. He is also shown to be a bit of a show-off, often bragging about his knowledge and experiences. He is a skilled storyteller and enjoys being the center of attention. However, his arrogance and tendency to exaggerate his stories often rub other people the wrong way.
2. Mrs. Ramsay: Mrs. Ramsay is the wife of the narrator and is depicted as a kind and gentle woman who is always trying to make everyone feel comfortable. She is a good listener and is empathetic to other people's needs. She is also shown to be quite perceptive, noticing things that other people miss.
3. The narrator: The narrator is an unnamed character who is traveling on a ship with Mr. Kelada and his wife. He is initially put off by Mr. Kelada's arrogance and is skeptical of his stories. However, as the story progresses, the narrator's opinion of Mr. Kelada changes, and he comes to appreciate his wit and intelligence.
4. Mr. and Mrs. Ramsay's cabin-mate: This character is not named in the story, but he is portrayed as a quiet and reserved man who is uncomfortable with Mr. Kelada's constant talking. He is also shown to be quite judgmental, often making assumptions about people based on their appearance.
Overall, the characters in "Mr. Know-All" are well-drawn and multi-dimensional, with their personalities and actions driving the story forward. The story explores themes of cultural differences, prejudice, and the importance of keeping an open mind.
***
1. Paul's mother - Greediness and Materialism: Paul's mother is a greedy and materialistic woman who is obsessed with wealth and status. She constantly complains about their financial situation and always wants more money. She is also emotionally distant from her children and does not show them any affection.
2. Paul - Obsessive and Determined: Paul is a determined and obsessive young boy who is fixated on winning money for his mother. He is willing to do whatever it takes to win, even if it means sacrificing his own health and well-being. He is also sensitive and perceptive, as he is able to sense the winning horses.
3. Uncle Oscar - Cynical and Practical: Uncle Oscar is a practical man who is skeptical of Paul's ability to predict the winning horses. He is also cynical about the value of wealth and material possessions, which is in contrast to Paul's mother.
4. Paul's sisters - Naive and Innocent: Paul's sisters are young and innocent, and they are not aware of the family's financial troubles. They are also naive about their mother's behavior and do not understand why she is always unhappy.
Attentive and kind
### The Swing
"The Swing" by Mary Gavell is a poignant story about an elderly woman who begins to experience vivid dreams after many years of being preoccupied with the responsibilities of life. With her son James grown and her husband Julius withdrawing into himself due to old age, she finds herself alone and reflective.
One night, she hears the familiar creak of an old swing in their yard, a swing her husband had lovingly installed for their son when he was a child. Initially, she thinks it's just the wind, but she eventually goes outside to investigate and discovers her son James, appearing as a child, joyfully swinging. They engage in heartfelt conversations reminiscent of their past, discussing various topics like airplanes, stars, and schoolyard troubles.
These nightly visits from young James bring her immense joy and a sense of purpose. However, one night, James tells her that he won't be able to visit anymore. She bravely accepts this, cherishing their final moments together. After he leaves, she breaks down in tears, overwhelmed by the reality of his departure.
Julius, her husband, finds her in the yard. Despite his usual demeanor, he gently points out that James left his red jacket behind, symbolizing the lasting presence of their son's memory. The story beautifully explores themes of memory, loss, and the enduring bond between a mother and her child.
"玛丽-盖维尔(Mary Gavell)的《秋千》是一个凄美的故事,讲述了一位老妇人在多年被生活的重担压得喘不过气来之后,开始做一些生动的梦。她的儿子詹姆斯已经长大成人,丈夫朱利叶斯也因年事已高而变得孤僻,她发现自己变得孤独而多愁善感。
一天晚上,她听到院子里一个老秋千发出熟悉的嘎吱声,这是她丈夫在儿子小时候为他精心安装的秋千。起初,她以为只是风吹的声音,但最终她走到外面一看,发现儿子詹姆斯正以孩童的姿态快乐地荡秋千。他们进行了真挚的对话,回忆过去,讨论飞机、星星和校园烦恼等各种话题。
小詹姆斯每晚的来访给她带来了无尽的欢乐和使命感。然而,一天晚上,詹姆斯告诉她,他不能再来看她了。她勇敢地接受了这个事实,珍惜他们在一起的最后时光。他离开后,她泪流满面,被他离开的现实压得喘不过气来。
她的丈夫朱利叶斯在院子里找到了她。尽管朱利叶斯平时很有风度,但他还是温和地指出,詹姆斯留下了他的红色夹克,象征着他们对儿子永恒的记忆。这个故事很好地探讨了记忆、失去以及母子间永恒纽带的主题。
## Irony 讽刺
### The chaser
the irony is that Alan is desperate for a love potion to manipulate Diana into loving him back, yet what he fails to recognize is that the potion will most likely make Diana obsessed with him. The old man predicts that Alan will soon find her obsession suffocating which is why the old man is sure Alan will also be needing the poison in the future.
### The Lottery
The story is set in a small village where the annual lottery is about to take place. Villagers gather in the town square, chatting casually while children play. Mr. Summers, who organizes the community events, conducts the lottery with a black box that is old and worn, yet the villagers are resistant to replacing it. Each villager draws a slip of paper from the black box, and the person who draws a paper with a black spot is stoned to death. Old Man Warner, the oldest villager, fervently supports the lottery and criticizes those who question its necessity. Tessie Hutchinson becomes the "winner" of the lottery and is subsequently stoned to death by the villagers, including her own family. The story explores themes of blind adherence to tradition and the dark consequences that can result. The title "The Lottery" gives a misleading impression of a game of chance, but it is actually a violent ritual of sacrifice.
故事发生在一个小村庄,那里即将举行一年一度的抽签仪式。村民们聚集在镇广场上,一边闲聊,一边和孩子们玩耍。组织社区活动的萨默斯先生用一个又旧又破的黑盒子进行抽奖,但村民们都不愿意更换它。每个村民都会从黑盒子里抽出一张纸条,抽到有黑点的纸条的人就会被乱石砸死。最年长的村民华纳老人狂热地支持彩票,并批评那些质疑彩票必要性的人。泰西-哈钦森成了彩票的 "赢家",随后被村民用石头砸死,包括她自己的家人。故事探讨了盲目坚持传统的主题以及可能导致的黑暗后果。彩票》的标题给人一种机会游戏的误导印象,但它实际上是一种暴力的献祭仪式。
## Conflict 冲突
### The Phoenix
人与自然的冲突 There are two conflicts occurring in The Phoenix. One conflict is Man versus Self. Poldero has a greed for profit and goes to extremes to gain profits when the phoenix stops bringing him such. This leads into the second conflict, Man versus Nature.
## Setting 设定,背景
### The Garden Party
死神是一个伟大的平等主义者,在他的王国里,没有阶级差别。所有的人,无论贫富贵贱,最终都会来到这个王国。从某种意义上说,通过与死亡的接触,劳拉已经从她的梦幻世界———园会世界———完全苏醒过来,进入了现实世界,顿悟了事物的真谛。死亡非但没有给她带来恐惧,相反却促使她去思考生活到底是什么。虽然她无法解释生与死的哲学意义,但却十分明白,这两者之间的界限是微乎其微的———生与死常常是携手而行。
### The Landlady
《房东太太》是罗尔德·达尔创作的一篇令人毛骨悚然的短篇小说,讲述了一位名叫比利·韦弗的年轻人到巴斯出差的故事。年仅十七岁的比利被指引去一家酒吧住宿,但却被一家看似迷人的家庭旅馆所吸引。这家旅馆由一位古怪的房东太太经营,尽管其氛围诡异,但比利还是被一种无法解释的力量所驱使,决定留下来。
在见到房东太太后,比利被她奇怪的举止所震惊。她坚持说自己对客人非常挑剔,并透露之前只有两位房客,分别是穆兰德先生和坦普尔先生。房东太太对之前客人的令人不安的评论以及她对动物标本的痴迷开始让比利感到不安。
随着故事的发展,比利意识到之前客人的名字之所以熟悉,是因为他们在报纸上被报道为失踪者。房东太太的言论和她宠物的不自然静止(实际上是标本)暗示了一个可怕的结局。故事在一个不祥的音符中结束,让读者推测比利也可能成为房东太太的永久“客人”之一。
这个黑暗的故事结合了悬疑和微妙的恐怖,展示了达尔在营造逐渐逼近的恐惧氛围方面的技巧,并给读者留下了深刻的印象。
## 选词填空可能的单词
1. **Character** - 人物
2. **Plot** - 情节
3. **Narrative** - 叙事
4. **Tone** - 语调
5. **Mood** - 氛围
6. **Symbolism** - 象征
7. **Imagery** - 意象
8. **Point of View (POV)** - 视角
9. **Irony** - 讽刺
10. **Allegory** - 寓言
11. **Metaphor** - 隐喻
12. **Simile** - 明喻
13. **Allusion** - 典故
14. **Juxtaposition** - 并列
15. **Motif** - 主旨
16. **Flashback** - 倒叙
17. **Suspense** - 悬念
18. **Dialogue** - 对话
19. **Exposition** - 阐述
20. **Climax** - 高潮
21. **Resolution** - 解决
22. **Protagonist** - 主角
23. **Antagonist** - 反派
24. **Dynamic Character** - 动态人物
25. **Static Character** - 静态人物
26. **Foil** - 衬托角色
27. **Epiphany** - 顿悟
28. **Understatement** - 低调陈述
29. **Hyperbole** - 夸张
30. **Theme Statement** - 主题陈述
31. **Diction** - 措辞
32. **Syntax** - 句法
33. **Subplot** - 次要情节
34. **Tone Shift** - 语调转变
35. **Voice** - 叙述声音
36. **Archetype** - 原型
37. **Context** - 上下文
38. **Denouement** - 结局
39. **Setting Description** - 场景描写
40. **Conflict Resolution** - 冲突解决
41. **Narrative Technique** - 叙事技巧
42. **Pathetic Fallacy** - 移情
43. **Stream of Consciousness** - 意识流
44. **Intertextuality** - 互文性
45. **Ambiguity** - 模棱两可
46. **Paradox** - 悖论
47. **Onomatopoeia** - 拟声词
48. **Personification** - 拟人
49. **Oxymoron** - 矛盾修饰法
50. **Genre** - 体裁
本文转自 [青灰色的风原文](https://www.cnblogs.com/68786C/p/17494450.html),并在原版基础上稍作修改。如有侵权,请联系删除。
# Management information systems
Source: https://base.bangwu.me/about/courses/mis
Course notes on management information systems covering data-to-information transformation, system development methods, decision support, and expert systems.
**考试题型**
***
> 1. ***名词解释(5x4)***
> 2. ***简答题(5x7)***
> 3. ***论述题(2x15)***
> 4. ***案例分析题(1x15)***
`以下内容是根据课件整理的,有的章节结合书本,算是精简中的精简,最少也要背这些了`
# 管理信息系统概述
## 信息与信息系统
> 从经营管理的视角,信息系统是组织和管理上针对环境带来的挑战而做出的基于信息技术的解决方案。
`信息——>信息资源——>用信息系统管理信息资源`
### 信息
> 信息是传递的消息中使概率发生变化的东西。

> 数据是对客观事物记录下来的、可以鉴别的符号,包括数字、字符、文字、图形等。
>
> 信息是经过加工、并对客观世界产生影响的数据。
### 信息资源
> 资源是指自然界和人类社会中一种可以用以创造物质财富和精神财富的具有一定量的积累的客观存在形态。
>
> 在经济学中,也将资源定义为生产过程中所使用的投入,本质上是生产要素的代名词。
`信息资源管理就是综合运用各种方法和手段进行信息资源的规划、组织、利用和控制的过程。`

### 用信息系统管理信息资源
> 所谓系统,是指为实现某个目标而结合在一起的要素集合。它是由具有某种特定功能、相互联系与相互作用的部分组成的有机整体。
>
> 信息系统是为满足某种需要,由人和相关设备组成的以信息作为基本处理对象的系统。
>
> 为了提高组织对信息的获取、存贮、处理、分析和利用能力,信息系统被广泛地应用。
信息系统可泛指以处理信息为目的的一切系统,比如人的大脑、算盘。
信息系统可以是:
* 正式的或非正式的信息系统
* 手工的或计算机化的信息系统
在没有限定的情况下,目前人们所说信息系统,总是指正式的计算机信息系统(Computer-Based Information System,CBIS)。
> 信息系统是信息、技术、组织和管理的融合。
## 信息系统与管理
> 比较容易看到信息系统对`作业层和战术层`的改善,而有远见、有创新精神的组织,却应该看到***战略层***。
>
> 这是一个需要对于信息系统/信息技术深刻理解的领域,也是一个更加需要信息系统/信息技术与管理理论有机结合的领域。
竞争战略是一个企业在同一使用价值的竞争上采取进攻或防守行为,`Laudon将波特的三种基本竞争战略扩充为四种策略`包括:
* 低成本(Low-cost leadership)案例:`Google、Amazon(有效开发“长尾”)`
* 产品差异化(Product differentiation)案例:`顺丰、CTRIP`
* 目标聚焦(Focus on market niche)案例:`阿里巴巴(B TO B)`
* 与客户和供应商建立更密切联系(Customer and supplier intimacy)案例:`Walmart`
## 信息系统与组织
> 组织即由若干个人或群体所组成的、有共同目标和一定边界的社会实体。
* 组织是权力、特权、义务和责任的集合,通过冲突和冲突的解决而在一段时期形成的微妙的平衡状态。
`信息技术/信息系统成为左右组织变革的重要因素。`
* 信息系统使组织的结构发生变化,由原来的比较陡峭的金字塔型结构趋向于扁平化结构。
* 信息系统改变企业经营模式,导致虚拟经营和虚拟企业的出现。
* 信息系统使组织的业务流程发生变化,某些部门被重组、撤消和合并,某些流程被不断优化、不断重组。
### 信息系统与组织结构扁平化
> 扁平化组织(Horizontal Organization)是让员工打破现有的部门界限,绕过原来的中间管理层次,直接面对顾客,并向公司总体目标负责,从而以群体和协作的优势赢得市场主导地位的组织。`决策效率更高`
扁平化组织的模式类型:
* 矩阵式结构/事业部制结构
* 团队组织
* 网状组织
### 信息系统支持虚拟经营
> 虚拟经营,是指以信息技术为基础,由多个具有独立市场利益的企业集团通过非资本纽带媒介生成的一种相对稳定的或者临时性的产品生产、营销和服务的分工协作关系,包括合同制造网络与策略联盟等主要形式。
### 信息系统与企业流程再造
> 业务流程再造(business process reengineering,BPR)是对企业的业务流程(process)做根本性(fundamental)的再思考和彻底性(radical)重建,其目的是在成本、质量、服务和速度等方面取得显著性(dramatic)改善,使得企业能最大限度地适应以顾客(customer)、竞争(competition)、变革(change)为特征的现代企业经营环境。
企业可以根据自身情况,对关键流程设立指标,考察活动对流程指标的贡献或者损害,从而细致地来分析活动是否增值。
> **客户愿意付费的就是增值的。**

# 信息技术基础设施
> **信息产业三大定律:摩尔定律、反摩尔定律、安迪-比尔定律**
>
> ***摩尔定律**:摩尔定律:集成电路上可容纳的晶体管数目约每隔18/24个月便会增加一倍。*
>
> \*\*\*反摩尔定律:\**一个IT公司如果今天和18个月前卖掉同样多的、同样的产品,它的营业额就要降一半。*
>
> ***安迪-比尔定理**揭示了原本属于耐用消费品的电脑、手机等商品如何变成了消耗性商品,刺激着整个 IT 领域的发展。*
## IT基础设施及其管理
IT基础设施是为其他业务系统提供运作基础的共享的IT服务能力,这些能力包括提供可靠服务所需的内部技术(设施、软件和网络)和管理经验。
IT基础设施由IT技术设施和IT人员基础设施两个元素组成。
> IT基础设施从本质上来说是一种IT服务能力;
>
> IT基础设施的作用是为其它业务系统提供运作基础;
>
> IT 基础设施的组成包括“技术设施”和“人”两个方面;
>
> IT基础设施能够通过(手段)技术与管理来提供可靠的服务。
## 计算机的产生和发展
•设计思想
* 二进制
* 存储程序
•计算机的结构(冯·诺依曼结构)
* 运算器
* 控制器
* 存储器
* 输入装置
* 输出装置
> 人工智能就是要让机器的行为看起来就`像`是人所表现出的智能行为一样。
>
> 人工智能是指使用机器代替人类实现认知、识别、分析、决策等功能,其本质是对人的意识与思维的信息过程的模拟,是一门综合了计算机科学、生理学、哲学的交叉学科。

## 计算机硬件和软件
### 计算机硬件
> 硬件(hardware)是指计算机系统中的各种物理装置。
### 计算机软件
> 软件(Software)是操作、管理和使用计算机内部硬件和外部设备的各种程序、数据及相关文档的通称。
> 系统软件:是指控制和协调计算机及外部设备,支持应用的软件开发和运行,提高计算机性能,方便用户使用计算机资源的软件。
>
> 系统软件的主要功能是调度、监控和维护计算机系统;负责管理计算机系统中各种独立的硬件,使计算机硬件与软件成为一个相互协调的整体。
系统软件分类:
•操作系统
•系统工具
> 常见的操作系统:
>
> •DOS
>
> •Windows
>
> •UNIX
>
> •Linux
>
> •Mac OS
>
> •Android
>
> •HarmonyOS

## 数据管理与数据库
> 数据管理是指对数据的组织、存储、检索和维护,是数据处理的中心环节。
> 数据管理主要围绕提高数据独立性、降低数据的冗余度、提高数据共享性、提高数据的安全性和完整性等方面来进行,使使用者能有效地管理和使用数据资源

## 计算机网络
> 计算机网络是指由通信线路互相连接的许多自主工作的计算机构成的集合体。

# 信息化规划
> * 厘清业务需求的边界
> * 掌握把握业务需求的原则与方法
> * 了解信息化规划的概念、作用、思路与原则,及常用的方法
把握业务需求的原则与方法:
***管理信息系统**是为了实现现代管理的需要,在管理科学、系统科学、信息科学和计算机科学等学科的基础上形成的一门学科,它是现代社会各类组织用来进行信息采集、处理、信息管理,实现组织的运行、管理和决策功能,提高管理组织、管理方法和管理工作效率的重要组成部分,是现代化的管理理念和现代信息技术的结合体。*
> **广义上讲,“业务需求”包括了业务需求、用户需求和功能需求。** ` 系统调查法`
常用的信息化规划方法:
* **情景法**
* \*\*战略目标集转化法(**Strategy Set Transformation**,\*\*SST)
* \*\*企业系统规划法(\*\*Business Systems Planning,BSP)
* \*\*关键成功因素法(\*\*Critical Success Factor,CSF)
# 信息系统开发
## 信息系统开发的基本原则
* 实用性原则
* 系统性原则
* 符合软件工程规范的原则
* 逐步完善、逐步发展的原则
## **信息系统开发的主要活动**
**MIS生命周期四个阶段**:


MIS的生命周期共划分为系统规划、需求分析、系统设计、编码、测试和系统运行与维护6个阶段(或是系统分析、系统设计、编程、测试、切换、运行与维护)。这样划分MIS生命周期是为了对每一个阶段的目的、任务、采用技术、参加人员、阶段性成果、与前后阶段的联系等作深入具体的研究,以便更好地实施开发工程,开发出更好的系统,以及更好地运用系统以取得更好的效益。
> **MIS\*\*\*\*生命周期模型之瀑布模型**

> **MIS**开发的主要活动:
>
> * 系统分析
> * 系统设计
> * 编程
> * 测试
> * 切换(迭代)
> * 运行和维护
## 系统开发方法
> **结构化生命周期法**,是开发信息系统的一种结构化方法。其基本思想是采用系统工程思想和工程化方法,按照用户至上的原则,结构化、模块化,先自顶向下地对系统进行分析与设计,再自底向上逐步组织实施。
> **原型法**,是根据对用户信息需求的初步了解,借助强有力的软件环境支持,迅速构造一个新系统的原型,然后通过反复修改和完善,最终完成一个新系统的开发。核心思想是渐进明细。
| **开发方式** **特点** | **自行开发** | **委托开发** | **合作开发** | **购买现成软件包** |
| - | - | - | - | - |
| 分析和设计能力要求 | 较高 | 一般 | 逐渐培养 | 较低 |
| 编程能力的要求 | 较高 | 不需要 | 不需要 | 较低 |
| 系统维护的难以程度 | 容易 | 较困难 | 较容易 | 较困难 |
| 开发费用 | 少 | 较多 | 较少 | 多 |
# 信息系统项目管理
`这里可以直接看下面所展示的三个图,算是包含了重点,别不行,没时间了😭😭😭`
## 管理信息系统项目
> 大多数项目的问题来源于四个原因:
– 组织方面出现问题
– 对需求缺乏控制
– 缺少计划和控制
– 项目执行方面与项目估算方面的问题。
### MIS项目管理
> 什么是项目
以一套独特而相互联系的任务为前提,有效地利用资源,为实现一个特定的目标所做的努力。
> 项目的特征
* 项目有一个明确界定的目标——一个期望的结果或产品;
* 项目的执行需要通过完成一系列相互关联的任务,也就是许多不重复的任务以一定的顺序完成,以达到项目目标;
* 项目需要运用各种资源来执行任务。资源包括人力、组织、设备、原材料和工具;
* 项目有具体的时间计划或有限的寿命。它有一个开始时间和目标必须实现的到期日;
* 项目可能是独一无二的、一次性的努力;
* 每个项目都有客户。客户是提供必要资金和约定达成目标的人;
* 项目包含一定的不确定性。

### 一、识别需求
> 识别需求是MIS项目生命周期的初始阶段。
>
> 在识别需求时,客户必须清晰地界定问题或需求,并从客户的角度全面地陈述需要做什么。
>
> 需求的产生
>
> – 公共需求与公共项目
>
> – 个体需求与个体项目
#### 需求建议书(RFP)
* 客户从实际的角度出发,全面、详细地陈述、表达为了满足其已识别的需求应作哪些准备工作。
* 从客户角度全面、详细阐述项目范围、进度等。
* RFP可以让承约商明确客户期望,以便准备一份全面的申请书,以可行的价格、进度满足客户。
* RFP准备妥当,客户就可通知潜在承约商提交申请书。
#### RFP的主要内容
* 工作陈述:对要完成的工作范围的概括性描述。
– 如:系统需提供增、删、改、打印、查询功能。
* 具体要求:要完成的服务和服从的约束
– 如:可按姓名模糊查询。
* 交付物:承约商或项目团队应该提交的工作产品
– 如:可运行的软件、源程序清单、使用手册等。
* 由客户提供的资源
– 如:原始业务数据资料、服务器设备等
> 注意:即使许多情况不需准备正式的RFP,但:项目总是开始于需求或问题的识别。其目的在于明确项目工作范围、进度、预算等。
### 二、提出解决方案
> 潜在的承约商提交申请书,并给出项目的具体解决方案。
* 注:在准备申请书前,承约商需要评价是否进行申请书的准备工作,即投标决策。
> 高质量的申请书应包括技术、管理、成本三方面内容
### 三、执行项目
> 项目管理是一种控制项目的超前方法,以确保项目目标即使在进程中偏离计划也能实现。
### 四、结束项目
> 这个阶段的目的是从项目中学习经验,以便在未 来的项目中改进工作绩效。(`项目复盘`)


## WBS工作分解(重点)
> WBS概述
WBS是一个以项目的可交付结果为中心,为完成项目的目标和生成项目的可交付成果,由项目团队进行的一种工作有层次的分解。
> WBS分解方法
> 类比法
– 以一个项目的WBS为基础,制定本项目的工作分解结构。
> 自上而下法
– 常规方法,将工作分解成下一级的多个子项,它是一个不断细化工作任务的过程。
– 一种系统思考的方法
> 自下而上法
– 对项目工作分解的一个先发散后归纳的过程。
`WBS是项目管理的骨架`
## 开发管理
开发管理分为`时间管理`、`成本管理`、`质量管理`、`风险管理`
> `这部分太重要了,按照老师所说的,算是第三部分的全部了,所以这里请自行看书 P264~P274`😵💫
## 交付管理
### 人员培训计划
操作人员培训一般是与编程工作同时进行
### 知识转移
> 知识转移是知识从一个主体转移到另一个主体的过程,也是一主体接受另一主体已积累经验的影响过程。
`合同型转移是知识转移的主要方式`
### 项目收尾
> 指项目结束的所有活动,将完成的成果交予用户的过程。

## 运维管理
emmmmmmm,不重要,随便了,这个想了解自己看书P285
> 老师对这部分做了一节实践,project算是把这章节串起来了,反正这节不重要,project也不重要。
# 道德与安全、控制
这部分是老师念着书随便过,肯定不重要,谁还没点道德😵💫😵💫
反正就是别干缺德的事就行了,然后还要有安全意识,别乱点陌生链接,接受文件。
> 然后还有书上的第十章,这两章基本都不重要,估计考到的很少。
没了,还不赶快背😡😡😡
# System analysis and design
Source: https://base.bangwu.me/about/courses/system-analysis
Course notes on system analysis and design covering data flow diagrams, ER modeling, structured analysis methods, and UML object-oriented modeling techniques.
写在前面
系统分析与设计:重点由老师给出,本文章根据给出的重点来进行总结,理解或背诵自行解决 全文结合老师给的重点
PS:引言部分帮助理解

# 一、系统概要、信息、管理与信息系统
引言👈
系统分析与设计:系统分析【理解需要做什么,详细说明需要做什么】+ 系统设计【详细说明系统将如何工作】
## 1.1系统概要
> 系统是由相互联系和相互制约的若干要素组成的、具有特定功能的有机整体
## 1.2信息概要
> \*\*数据(**Data**)\*\*是对客观事物的性质、状态以及相互关系等进行记载的物理符号或这些物理符号的组合,反映了客观事物属性的记录
>
> \*\*信息(**Information**)\*\*是经过加工后的数据,以有意义的形式加以排列和处理的数据(有意义的/被理解的数据)(who、when、where、what)
>
> **知识**(Knowledge)是信息的集合,从相关信息中过滤、提炼及加工而得到的有用资料,使得信息变得有用(有用的信息),是人类关于自然界、人类社会及思维方式与运动规律的认识、经验的总和 (why、how to)
>
> **智慧**(Wisdom)是知识和信息经过人类大脑内化后转换为对事物理解和处理的能力 (What is best),人类独有的一种能力。
**数据和信息可看作原材料和成品的关系**

> **信息的属性**
* 事实性、扩散性、传输性、共享性、增值性、不完全性、等级性、滞后性
## 1.3信息系统
> **信息系统**:以计算机为基础,结合管理理论和方法,应用信息技术解决管理问题,为管理决策提供支持的系统。
**信息系统的基本功能**:
* 数据的采集和输入
* 数据的传输、存储、加工、维护和使用
**信息系统的结构**:【按照抽象程度分为三个结构】
1. 概念结构
2. 基于管理职能的逻辑结构
3. 基于计算机实现的物理结构【硬件结构+软件结构】

## 1.4信息系统与组织
> 信息系统在组织中的地位
* **战略型**:信息系统是这些企业核心竞争力的一部分
* **转变型**:信息系统将逐步转变为企业未来成功的战略性支柱
* **工厂型**:信息系统是企业顺利运作的保障
* **支持型**:信息系统对企业当前运作和未来战略的影响不大
# 二、信息系统建设概论
## 信息系统建模
> 信息系统领域常用模型:【理解即可】
| 模型名称 | 用途 |
| - | - |
| 业务流程图 | 描述不同职能部门业务活动分工和活动过程 |
| 数据流图 | 描述数据的产生、处理、存储和去向的信息处理模型 |
| 实体关系图 | 描述系统中有价值的实体及其关系的数据模型 |
| 组织结构图 | 描述组织的部门及其从属关系的层次模型 |
| 模块结构图 | 描述软件功能模块及其调用关系的层次模型 |
| 判定表、判定树 | 描述决策条件及其行动关系 |
| UML(类图、用例图、顺序图等) | 描述软件系统结构及行为的一组模型 |
| 甘特图 | 描述项目任务及其完成日期的项目计划模型 |
## 2.2信息系统开发方法与工具
> 信息系统的生命周期(System Development Life Cycle,SDLC) 设计=>评价=>设计
基于**生命周期**的开发方法:原型法、迭代法、瀑布法等【管理信息系统已学,理解即可】
基于**技术**的开发方法:面向过程、面向对象、面向服务
# 三、系统规划与分析概述
## 3.2信息系统规划的技术与方法
> 战略目标集转移法【基本思想:将组织战略集转换成与它相关联和一致的信息系统战略集】
>
> 企业系统规划法【四个关键步骤:定义管理目标、定义管理功能组、定义数据分类、定义信息结构】
>
> 关键成功因素法【找出成功因素】
>
> 价值链分析法【企业进行的种种活动可以用一个价值链来表明,每个活动都有可能产生增值行为】
## 3.5系统分析的任务、过程和方法
> 系统分析的重要任务是识别和表达用户需求,分析领域业务,建立系统的逻辑模型。
要解决以下问题:
* 如何采集信息、理解和分析问题?
* 如何进行需求分析、确定需求?
* 如何表述需求?
**系统分析的过程**:问题分析=>需求分析=>需求定义

# 四、UML统一建模语言
> 统一建模语言UML(unified modeling language)是一种基于面向对象的可视化的通用建模语言,用于对软件进行描述、可视化处理、构造和建立软件系统工作的文档。

**UML的构成**:
* **事物(建模元素)**:UML模型中面向对象的基本模块,代表物理上或概念上的元素
* **关系**:事物与事物之间的联系,根据耦合度从弱到强排列,分别是依赖、关联、聚合、组合、继承/泛化和实现关系
* **图**:事物和关系的可视化表示
理解以下几种图的构成及功能:



# 五、流程建模(理解为主)
## 业务流程分析与建模
> **跨职能流程图**【面向过程】
➢ 也称泳道图,面向过程,能够展示工作流中每个步骤涉及的职能部门和工作事项
➢ 能展示各个环节间的关系,同时还能展示为过程负责的执行者(比如说人或部门)
➢ 适用于涉及多个部门或角色的场景
> **UML活动图**【面向对象】
➢ 面向对象,描述满足用例要求所要进行的活动以及活动间的约束关系,阐明了业务用例实现的工作流程
➢ 活动图可用于需求获取、分析和设计的工作流中
➢ 适合描述系统中多个对象跨多个用例的活动顺序

## 数据流程分断与建模
> **数据流图(Data Flow Diagram,DFD)**,它从数据传递和加工角度,以图形方式来表达系统的逻辑功能、数据在系统内部的逻辑流向和逻辑变换过程。
>
> 数据流图用来记录系统中的数据是如何被采集、处理、保存和使用的

业务流程图和数据流图的区别:
| 项目 | 业务流程图 | 数据流图 |
| - | - | - |
| 关注点 | 关注业务操作的顺序、活动以及角色之间的交互 | 关注数据如何在系统中流动以及如何被不同的过程或功能所处理 |
| 组成要素 | 角色、活动、关系、交付物、分支等 | 外部实体、数据流、数据处理、数据存储 |
| 用途 | 用于描述、分析、优化和通信关于业务的工作流程 | 表达系统的逻辑功能、数据在系统内部的逻辑流向和逻辑变换过程 |
| 表示方式 | 跨职能流程图、UML活动图 | 数据流图 |
> **数据字典**:数据字典是对数据流图的补充描述,用来描述数据流程图中的数据流、数据存储、处理过程和外部实体的详细内容。

## 5.3业务规则表示
> 从信息系统角度看,业务规则是描述和约束业务的语句,用来刻画业务的结构、控制和影响用户的行为。
>
> 处理复杂逻辑:【结构化语言+判定表+判定树】
# 六、用例建模(理解为主)
由于这章整章都需要理解,请看👉[课件](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E7%B3%BB%E7%BB%9F%E5%88%86%E6%9E%90/%E7%AC%AC6%E7%AB%A0%20%E7%94%A8%E4%BE%8B%E5%BB%BA%E6%A8%A1.pdf)以及[课件补充](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E7%B3%BB%E7%BB%9F%E5%88%86%E6%9E%90/%E7%AC%AC6%E8%AE%B2%E8%A1%A5%E5%85%85%EF%BC%9A%E4%BF%A1%E6%81%AF%E5%9C%A8%E7%A4%BE%E4%BC%9A%E7%BB%93%E6%9E%84%E4%B8%AD%E7%9A%84%E5%88%86%E5%B8%83%E7%8E%B0%E8%B1%A1.pdf)
# 七、领域对象建模(理解为主)
## 7.1面向对象方法概述
`对象`【对问题域中某个实体的抽象,由名称、属性和行为(方法)】、`类`【是指有相同属性和方法的一组对象的抽象概念】、`封装`【把对象的属性和方法结合为一个独立的整体,并尽可能隐藏对象的内部实现细节】、`继承`【指子类的对象拥有其父类的全部属性与方法】就不再做过多赘述
> `多态`:指不同层次的子类可以共享父类中同一方法名称,但却可以各自按自己的需要实现不同的行为和执行不同的方法。【提高代码的扩展性】
>
> `对象关系`:继承、实现、关联、依赖。
>
> `对象之间的消息与协作`:【消息:对象之间必须要进行交互来实现复杂的行为,用消息message的形式提供信息】
## 7.2领域对象建模
> **领域对象**:也称实体类,就是问题域中有意义的概念类,是现实世界中存在的事物(things)或事件(events)
>
> **领域模型**:又称领域对象模型、分析对象模型,是对领域内的概念类或现实世界中对象的可视化表示。

> **领域类图**(Domain Class Diagram):分析阶段,用来表示特定领域内的概念以及这些概念之间的关系
>
> 主要包括:领域对象、领域对象之间的关系、关键属性【通常不包括方法】
> **状态机图**(state machine diagram)关注对象的状态及转换,用于描述基于事件响应的对象动态行为和状态之间的关系【适合描述某个对象的内部逻辑, 即描述**一个对象跨多个用例**的行为。】

# 八、面向对象设计
## 8.1系统设计概述
> \*\*`系统设计`\*\*又称为物理设计,就是根据新系统逻辑模型所提出的各项功能要求,结合实际条件,科学、合理地设计出新系统的解决方案,并为系统实施阶段的各项工作准备好必要的技术资料和有关文件。【系统设计对系统分析与系统实施起桥梁作用】

## 8.3数据设计【这部分就是数据库知识,看看就行】
设计关系数据模型顺序:
1. 需求分析:确定应用程序需要存储的信息
2. 定义实体:实体代表了业务环境中的一个对象;每个实体创建一张二维表
3. 定义属性:即实体的特征; 每个属性对应表中的一列
4. 确定键:确定每张表的主键和外键
5. 定义关系:确定实体之间的关系;通过外键和参照完整性约束来实现和维护这些关系
6. 规范化:通过分解表来消除数据冗余,提高数据一致性;通过正规化阶段,例如第一范式、第二范式等来进行
7. 创建ER图(实体-关系图)
8. 反规范化(如有必要)
# 九、接口层设计
> 接口设计是指系统与外界的交互设计【人机接口设计、软件接口设计】
理解用户体验设计内容:

用户界面模型:**原型图**(Prototype)【就是用Axure设计出的原型】
# 十、业务逻辑层设计
## 10.1面向过程的设计
> **模块结构图**(Structure Chart)描述系统的模块结构及模块间的联系
模块结构图的主要成分:

例如:

## 10.2面向对象业务逻辑设计
> **理解设计类图/包图/顺序图/通信图,无需绘图**
这部分我也不知道要怎么表述,就看[课件](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E7%B3%BB%E7%BB%9F%E5%88%86%E6%9E%90/%E7%AC%AC10%E7%AB%A0%20%E4%B8%9A%E5%8A%A1%E9%80%BB%E8%BE%91%E5%B1%82%E8%AE%BE%E8%AE%A1.pdf)吧
# 十一、系统实施
## 系统实施阶段的任务
> 系统实施是将系统设计阶段得到的设计方案转换为以计算机硬件为基础的能够实际运行的应用软件系统的过程。
>
> **主要任务**:硬件准备、软件准备(程序编写、测试和部署等)、人员培训和数据准备。实施完毕,系统才可上线。
## 11.3系统测试
> **白盒测试**:根据一个软件部件的内部控制结构,测试是否依据设计正确地执行【逻辑上面走程序的流程,检测是否能走通】
例如:

就测试这个程序的条件分支是否能输出结果
# 十二、系统运维与管理(自学)
> 建议先看[课件](https://alist.bangwu.top/%E9%98%BF%E9%87%8C%E4%BA%91-%E6%A3%92%E6%97%A0/%E8%AF%BE%E4%BB%B6/%E7%B3%BB%E7%BB%9F%E5%88%86%E6%9E%90/%E7%AC%AC12%E7%AB%A0-%E7%B3%BB%E7%BB%9F%E8%BF%90%E7%BB%B4%E4%B8%8E%E7%AE%A1%E7%90%86%EF%BC%88%E8%87%AA%E5%AD%A6%EF%BC%89.pdf)然后再看下面的内容,也可以自己总结,其实也没什么,管理信息系统课好像学过
## 12.1系统运维与管理概述
> 系统运维与管理的主要任务是企业IT部门采用相关的方法、手段、技术、制度、流程和文档等,对软硬件运行环境、业务应用系统和运维人员进行综合的管理。
>
> 系统运维与管理主要由技术性运维和运维管理构成。
## 12.2开发运维一体化DevOps
> DevOps(Development & Operations), 即开发运维一体化,重视“软件开发人员(Dev)”和“IT运维技术人员(Ops)”之间沟通合作的文化、运动或惯例。通过自动化“软件交付”和“架构变更”的流程,来使得构建、测试、发布软件能够更加地快捷、频繁和可靠。

不是很重要,就是走流程。。。