carlos-flow 2.5.9 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -1,488 +1,473 @@
1
- # Carlos Flow — Cindy Edition
2
-
3
- > **Mechanical gatekeeping for AI coding agents**: Record → Dispatch → Verify → Verdict → Audit → Restore
4
- > Turns "trust the agent" into "verify the agent" — with machine-enforced scope limits, real command execution, and a tamper-proof audit chain.
5
- **语言 / Languages:** [中文](README.zh.md) | [English](README.en.md)
6
- **版本 / Version:** 2.5.9 | **License:** MIT | **CI:** passing | **Node.js:** 22+ | **MCP:** 1.29+
7
-
8
- ---
9
- ## 🆕 What's new in v2.5.5
10
- > In one line: **the workflow now recognises when it is its turn to step in.**
11
-
12
- ### ✨ Smart trigger engine (brand new)
13
- No more manually saying "run the gate" every time. The engine reads your input, decides whether the Carlos workflow should start, and — crucially — **tells you why**.
14
-
15
- | Layer | Component | What it does | Why it matters |
16
- |-------|-----------|--------------|---------------|
17
- | **L1** | `DynamicTriggerManager` | Dynamically computes "how many triggers are left in this session" | A fixed cap is either noisy or too strict; longer sessions and complex tasks automatically raise the ceiling |
18
- | **L2** | `TriggerScorer` | Scores every message: keywords 50 + context 30 + intent 20, weighted to a **38**-point maximum | Whether to trigger must be **explainable** — you always see which words matched and how many points were scored |
19
- | **L3** | `TriggerDecisionEngine` | Four-way decision: `trigger` / `review` / `ignore` / `throttled` | Turns "should we trigger?" from a hunch into an explicit rule |
20
-
21
- **Key properties**
22
- - 🎚️ **Dynamic cap**: `5 + sessionHours×0.5 + complexity×2 − triggersInWindow×0.3`, capped at 15
23
- - 🛡️ **Non-intrusive**: 5-minute minimum interval per session; the more you trigger, the **lower** the cap (a penalty, not a bonus)
24
- - 📊 **Transparent scoring**: returns the full `breakdown` (matched keywords / context words / intent type)
25
- - ⚖️ **Honest under throttling**: even when throttled it returns the real score and confidence — it never pretends "0 points"
26
- - 🧠 **Learns from feedback**: accepted / rejected triggers are persisted; when negative feedback dominates, the **trigger threshold is raised automatically** (more conservative)
27
- - 📦 **Zero external dependencies**: plain JavaScript, no new npm packages
28
-
29
- #### 🔁 Decision → Judgment → Activation (the piece that matters most here)
30
- The earlier implementation only printed a log line when it hit — it never actually started the workflow. That gap is now closed:
31
-
32
- | Stage | Action | Real effect |
33
- |-------|--------|-------------|
34
- | **Judgment** | L1 cap → L2 scoring → L3 four-way decision | Yields `decision` + `score` + `confidence` + `breakdown` |
35
- | **Translation** | `buildActivationPlan()` | Turns the verdict into an **executable MCP action sequence** (each step tagged `auto`) |
36
- | **Activation ①** | `flow_add_user_msg` | The user's own words are recorded and become the anchor source for the card's `quote` |
37
- | **Activation ②** | `flow_submit_requirement` (`activation: true`) | Submits a `read_only` placeholder card — the session **enters the gated state** |
38
- | **Gate** | `activation_pending` | Until `scope` / `acceptance` / `verify.cmd` are filled in, `flow_claim`, `flow_dispatch` and `flow_verdict` all **refuse** (no "PASS without ever running it") |
39
- | **Release** | Resubmit the complete card | `activation_pending` clears → normal dispatch proceeds |
40
-
41
- > Safety constraint: when the session **already has a card**, auto-activation skips card creation (it never overwrites an existing task). Auto-activation only handles "record + enter the gate" — it **never decides which files may change** on the agent's behalf.
42
-
43
- ##### 🔐 Four gate defenses (hardened after independent QA audit)
44
- | Defense | What it blocks | Outcome |
45
- |---|---|---|
46
- | **Field-by-field verification** | Submitting with only `scope` filled while `acceptance` / `verify.cmd` are still empty | The gate **keeps holding** (`activation_pending` lists exactly what is still missing) |
47
- | **No PASS without dispatch** | `verdict=PASS` on a card that was just submitted and never dispatched | Rejected; `completed_ok` stays `false` (`DIRECTION` / `LOCAL` are unaffected — rework notes are not blocked) |
48
- | **Empty scope fails closed** | Modifying any file while the card's `scope` is empty | `flow_check_scope` reports **every** path as out-of-scope (the early implementation failed *open*, i.e. "empty whitelist → change anything") |
49
- | **Dedicated audit events** | Asking afterwards "was this a placeholder card? was it ever released?" | `activation` / `activation_gate_activated` / `activation_gate_held` / `activation_gate_unlocked` / `activation_released` / `verdict_denied` are all queryable |
50
-
51
- > Every one of these defenses has a matching **mutation test** (inject the regression → confirm the suite fails). 13 injected mutations, **all 13 caught**.
52
-
53
- >
54
- > Also fixed: trigger state was previously kept in **one shared file for all sessions**, so one session could throttle another — it is now stored per session.
55
-
56
- ### 🐛 7 real defects fixed
57
- > These are all reproducible bugs, not "theoretical risks".
58
-
59
- | # | Defect | Impact | Fix |
60
- |---|--------|--------|-----|
61
- | 1 | `client/carlos.js` is ESM but loaded the trigger engine with `require()`; the error was swallowed by `catch` | **Integration silently dead** — the engine never ran | Switched to dynamic `import()` |
62
- | 2 | `canTrigger()` compared a 0–1 weighted average against a 5–15 cap | The cap check **could never fire** | Added `countTriggersInWindow()` returning the raw count |
63
- | 3 | The history factor in the dynamic-cap formula was an **additive** term | More triggers meant a *higher* cap — the cap cancelled itself out | Changed to a **penalty** term (subtraction) |
64
- | 4 | `processUserMessage()` hard-coded `sessionId='default'` | Ignored `context.sessionId`; sessions bled into each other | Session id now passed through from context |
65
- | 5 | `src/trigger.js` detected its CLI entry via `import.meta.url.endsWith(process.argv[1])` | The `file:///` prefix meant it **never matched** — the CLI was decorative | Switched to `fileURLToPath()` + `resolve()` |
66
- | 6 | `shouldTrigger()` returned early in the throttling branch | Score collapsed to `0` and confidence was lost | Score is now computed before throttling is judged |
67
- | 7 | `test:trigger` wrote its result file into the publish directory | Polluted the published npm package | Now written to the system temp directory |
68
-
69
- ### 🔒 Security & hygiene
70
- - 🚨 **`.gitignore` rule collision**: the trailing `*.tar.gz.npmrc.local` line meant `.npmrc.local` (which contains an **npm token**) was never actually ignored → split into separate rules
71
- - 🏠 **State files no longer wander**: trigger state lands in `CARLOS_FLOW_HOME`, not the current working directory
72
- - 🌐 **No hard-coded machine paths**: `D:\opencode-backups` → `~/.carlos-flow` (cross-platform default)
73
- - 🧹 **42 one-off fix scripts and scratch files removed** (net −5325 lines)
74
-
75
- ### 🚀 Release engineering
76
- - 🔑 **GitHub Actions OIDC publishing**: no npm token stored in the repository any more
77
- - 🧩 **`scripts/release.mjs`**: version checks / bilingual consistency / tests / build / publish in one command
78
- - 🛡️ **`npm run check:readme`**: prepublish hook keeps the three README files from drifting apart
79
- - 📋 **Independent QA report**: [`docs/QA_REPORT_v2.5.5.md`](https://github.com/skyer-now/carlos-flow-cindy/blob/main/docs/QA_REPORT_v2.5.5.md) — third-party read-only acceptance before release
80
- - 🧬 **Mutation report**: [`docs/MUTATION_REPORT_v2.5.5.md`](https://github.com/skyer-now/carlos-flow-cindy/blob/main/docs/MUTATION_REPORT_v2.5.5.md) — 13 injected mutations, **all 13 caught**
81
-
82
- ### 📚 Documentation readability
83
- - Removed the repeated **language bar / version line noise** that was injected throughout the READMEs (24–26 occurrences per file → consolidated to 1 at the top); tables are no longer truncated
84
- - Added [`TRIGGER_GUIDE.md`](TRIGGER_GUIDE.md): the complete smart-trigger guide
85
-
86
- ---
87
- ## 🎯 Why Carlos Flow?
88
- Most AI coding workflows are **advisory**. The prompt says "only touch these files" — and the agent politely agrees, then rewrites half the repository. The prompt says "run the tests" — and the agent reports "tests pass" without ever running them.
89
- Carlos Flow is **mechanical**. The constraints live in code, not in prose.
90
- ### Pain points it removes
91
- | Pain | Typical state today | Carlos Flow's answer |
92
- |------|--------------------|---------------------|
93
- | **Scope creep** | "Only edit `src/auth.py`" — a suggestion, not a rule | `enforceScope()` compares real `git diff` output against the card's whitelist; out-of-scope files **block the dispatch** |
94
- | **Verification theatre** | Agent claims "tests pass"; nobody can prove it | `runVerifyCommand()` actually spawns `verify.cmd`, captures `stdout` / `stderr` / `exitCode`; a `PASS` verdict additionally **requires** a passing verification |
95
- | **Laundered audit logs** | Logs in a plain file — deletable, editable | SHA-256 **chained** audit log (`prevHash` → `hash`); altering one record breaks the chain |
96
- | **Runaway bypass mode** | One sentence ("skip the gate, it's urgent") disables everything | Bypass requires an explicit `confirmed=true` on the card and **auto-resets on every dispatch** |
97
- | **Infinite dispatch budget** | Claiming a slot resets the counter — unlimited retries | `dispatch_count` increments **only on dispatch**; quota exhaustion blocks both claim and dispatch |
98
- | **Forgotten daemons** | "Did you start the server?" / port already in use | Bridge is auto-launched on first call, health-checked, token-authenticated, rate-limited |
99
- | **Self-attested reviews** | Same agent implements *and* approves | Built-in `auditor` role with a separate contract; verdict is one of `PASS` / `DIRECTION` / `LOCAL` |
100
- | **No way back from a bad change** | Manual `git revert` only | Automatic snapshot before dispatch → `flow_revert_plan` produces an atomic restore plan |
101
- | **Manual kick-off every time** | "run the gate" — if you forget, you work unprotected | The **smart trigger engine** scores your input and only fires when the intent is clear |
102
- ### How it differs
103
- | Capability | **Carlos Flow** | Raw MCP server | Prompt-only / scripts |
104
- |------------|-----------------|-----------------|----------------------|
105
- | **Scope enforcement** | ✅ runtime `git diff` level | ❌ none | ❌ relies on goodwill |
106
- | **Real verification** | ✅ spawns the command, captures output; `PASS` requires it to pass | ❌ none | ❌ agent self-reports |
107
- | **Tamper-proof audit** | ✅ SHA-256 chained | ❌ none | ❌ none |
108
- | **Controlled bypass** | ✅ explicit + auto-reset | ❌ none | ❌ one-liner disables all |
109
- | **Honest dispatch quota** | ✅ counts dispatch only | ❌ none | ❌ none |
110
- | **Independent review** | ✅ built-in `auditor` role | ❌ none | ❌ optional |
111
- | **Snapshot + restore** | ✅ automatic, atomic plan | ❌ none | ❌ manual `git revert` |
112
- | **Daemon lifecycle** | ✅ automatic (Cindy edition) | ❌ manual | ❌ manual |
113
-
114
- ---
115
- ## 🚀 Quick start (30 seconds)
116
-
117
- ### 1. Install
118
- ```bash
119
- npm install -g carlos-flow-cindy
120
- ```
121
- > ⚠️ **If you get `ETARGET: No matching version found`** — that is npm's **registry metadata cache** being stale,
122
- > not a missing version. Clear the cache and retry:
123
- > ```bash
124
- > npm cache clean --force
125
- > ```
126
- > To confirm the version really exists: `npm view carlos-flow-cindy versions`
127
-
128
- ### 2. Configure
129
-
130
- The Cindy edition installs from the **plugin marketplace**: Cindy → Settings → Plugins → Browse marketplace →
131
- search `carlos-flow` → Install, then fill in the environment variables on the plugin settings page
132
- (equivalent to the repo's `.env.example`).
1
+ # Carlos Flow
2
+
3
+ [![npm](https://img.shields.io/npm/v/carlos-flow.svg)](https://www.npmjs.com/package/carlos-flow)
4
+ [![npm downloads](https://img.shields.io/npm/dm/carlos-flow.svg)](https://www.npmjs.com/package/carlos-flow)
5
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D22.0.0-brightgreen.svg)](https://nodejs.org)
6
+ [![MCP](https://img.shields.io/badge/MCP-1.29%2B-blue.svg)](https://modelcontextprotocol.io)
7
+ [![License](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
+ [![CI](https://img.shields.io/badge/CI-passing-brightgreen.svg)](./.github/workflows/ci.yml)
9
+
10
+ **Languages:** [中文](README.zh.md) | [English](README.en.md)
11
+
12
+ ---
13
+
14
+ > **Mechanical Gate for AI Coding Agents**
15
+ >
16
+ > Trace → Dispatch → Verify → Verdict → Audit → Revert
17
+ >
18
+ > Turn "trust the Agent" into "**verify** the Agent" — constraints live in code, not in prompts.
19
+
20
+ ---
21
+
22
+ ## 📌 What is this (TL;DR)
23
+
24
+ Carlos Flow is an **MCP Server** that gives AI coding agents an **executable, auditable, self-deception-proof** workflow gate.
25
+
26
+ The problem with ordinary agent workflows: every constraint is **advisory**.
27
+
28
+ | You say | What the agent actually does |
29
+ |---------|-----------------------------|
30
+ | "Only edit `src/auth.py`" | Nods politely, then rewrites half the repo |
31
+ | "Run the tests" | Reports "tests passed" — never ran them |
32
+ | "Document the process" | Writes a few lines in a plain file — deletable, editable |
33
+
34
+ Carlos Flow takes the opposite approach: **every constraint is enforced at runtime against facts, never against self-report.**
35
+
36
+ - Out of scope? → Runtime `git diff` against the card whitelist, **blocks dispatch**
37
+ - Claims tests passed? → Really `spawn`s `verify.cmd`; **PASS requires a passing exitCode**
38
+ - Audit log? → SHA-256 **chained hashes** (`prevHash` → `hash`); **change one and the chain breaks**
39
+ - Want to skip? → Bypass needs explicit `confirmed=true`, and **auto-clears on every dispatch**
40
+
41
+ **In one line**: it brings code-review gates to AI agents — and the gates are executed by machines, not humans.
42
+
43
+ ---
44
+
45
+ ## 🎯 8 Real Problems It Solves
46
+
47
+ | # | Problem | Status quo | Carlos Flow's mechanical answer |
48
+ |---|---------|------------|-------------------------------|
49
+ | 1 | **Out-of-scope edits** | "Only these files" is advice, not a rule | `enforceScope()` compares `git diff` to the whitelist at runtime — out-of-scope **blocks dispatch** |
50
+ | 2 | **Verification theater** | Agent self-reports "tests passed"; no proof | `runVerifyCommand()` really executes, capturing stdout/stderr/exitCode; **no evidence → no PASS** |
51
+ | 3 | **Mutable audit logs** | Plain files — deletable, editable | SHA-256 chained hashes — **change one and the whole chain breaks** |
52
+ | 4 | **Uncontrolled bypass** | One sentence disables all guards | Requires explicit `confirmed=true` on the card; **auto-cleared on every dispatch** |
53
+ | 5 | **Unlimited dispatch** | Claim resets the counter; infinite retries | `dispatch_count` increments only on dispatch; exhaustion blocks both claim and dispatch |
54
+ | 6 | **Self-certified review** | Same agent implements and approves | Built-in `auditor` role + independent contract, strict three-tier verdict |
55
+ | 7 | **No rollback after damage** | Manual `git revert` only | Auto-snapshot before dispatch → `flow_revert_plan` produces an atomic restore plan |
56
+ | 8 | **Manual trigger every time** | No shout = no gate; forget = naked run | **Smart Trigger Engine** auto-detects intent, triggers on score, and explains what matched |
57
+
58
+ ---
59
+
60
+ ## ✨ Highlights
61
+
62
+ ### 1. Zero-fork, cross-platform architecture
63
+ One core MCP Server, **6 platforms** out of the box. Platform differences live only in init templates; core logic has **zero forks**.
64
+
65
+ ```
66
+ carlos-flow (single npm package)
67
+ ├── src/index.js ← Core MCP Server (pure standard protocol, zero platform coupling)
68
+ ├── client/carlos.js ← CLI + init --target <platform>
69
+ ├── bridge/ ← Cindy only: resident Bridge daemon
70
+ ├── plugins/ ← OpenCode only: chat.message hook
71
+ └── templates/ ← Cursor / Cline / VS Code / Claude templates
72
+ ```
73
+
74
+ ### 2. Smart Trigger Engine — the workflow knows when to show up
75
+ Three layers, and **every decision comes with an explainable breakdown** (which words matched, what score, why).
76
+
77
+ - **L1 Dynamic limit**: `5 + session_hours×0.5 + complexity×2 − window_triggers×0.3`, capped at 15
78
+ - **L2 3-D scoring**: keywords 50 / context 30 / intent 20, weighted max 38
79
+ - **L3 4-tier decision**: `trigger` / `review` / `ignore` / `throttled`
80
+
81
+ Chinese workflow terms are **built in** (工作流/门禁/派发/审计/任务卡/子代理…) while ordinary dev requests **never false-trigger**.
82
+
83
+ ### 3. Anti-self-deception activation gate
84
+ Auto-trigger **does not** mean "open the gates". After activation the session enters `activation_pending`:
85
+ until `scope` / `acceptance` / `verify.cmd` are filled in, `flow_claim` / `flow_dispatch` / `flow_verdict` are **all rejected**.
86
+
87
+ > What this prevents: placeholder card → dispatch → record PASS → fake closed loop.
88
+
89
+ ### 4. Fail-closed semantics
90
+ An empty `scope` means **everything is out of scope** (not "empty whitelist = change anything"). That's the safe default, not the convenient one.
91
+
92
+ ### 5. Mutation-tested guards
93
+ 13 mutation classes (deliberate regressions) are **13/13 caught** by the test suite. Anchor uniqueness is guarded by `npm run check:anchors`, so tests can never *silently* lose their guarding power.
94
+
95
+ ### 6. Cross-process concurrency safety
96
+ The read-modify-write in `flow_submit_requirement` is wrapped in a **cross-process exclusive lock** (`mkdir` atomicity).
97
+ A red-team run reproduced 4 state losses in 40 concurrent rounds; now it reports **0 leaks out of 453**.
98
+
99
+ ---
100
+
101
+ ## 🏗️ Technical Architecture
102
+
103
+ ### Overview
104
+
105
+ ```mermaid
106
+ flowchart TB
107
+ subgraph Host["Host Agent Platform"]
108
+ Cindy[Cindy<br/>ghost.json]
109
+ OpenCode[OpenCode<br/>plugin + .mcprc]
110
+ Cursor[Cursor / Cline<br/>VS Code / Claude]
111
+ end
112
+
113
+ subgraph Client["Client Layer"]
114
+ CLI["client/carlos.js<br/>CLI + init + trigger check"]
115
+ Bridge["bridge/mcp-bridge.js<br/>resident daemon + token auth"]
116
+ Plugin["plugins/carlos-flow-trigger.js<br/>chat.message hook"]
117
+ end
118
+
119
+ subgraph Core["Core MCP Server (src/index.js) — 15 tools"]
120
+ Protocol["flow_protocol"]
121
+ Submit["flow_submit_requirement"]
122
+ Dispatch["flow_claim / flow_dispatch"]
123
+ Verify["flow_run_verify / flow_check_scope"]
124
+ Verdict["flow_verdict"]
125
+ Audit["flow_status / flow_audit"]
126
+ Trigger["flow_trigger_check"]
127
+ end
128
+
129
+ subgraph Engine["Smart Trigger Engine (src/trigger.js)"]
130
+ L1["L1 DynamicTriggerManager"]
131
+ L2["L2 TriggerScorer"]
132
+ L3["L3 TriggerDecisionEngine"]
133
+ end
134
+
135
+ subgraph Storage["Persistence (CARLOS_FLOW_HOME)"]
136
+ State["gate-state/runs/<sid>/"]
137
+ AuditLog["gate-audit/YYYY-MM-DD.jsonl<br/>SHA-256 chained"]
138
+ Snap["snapshots/"]
139
+ TrigState["trigger-state/"]
140
+ end
141
+
142
+ Cindy --> CLI
143
+ OpenCode --> Plugin
144
+ Cursor --> CLI
145
+ Plugin --> Trigger
146
+ CLI --> Bridge
147
+ Bridge --> Core
148
+ Core --> Engine
149
+ Core --> Storage
150
+ Engine --> TrigState
151
+ ```
152
+
153
+ ### Layer Responsibilities
154
+
155
+ | Layer | Location | Responsibility | Platform coupling |
156
+ |-------|----------|----------------|-------------------|
157
+ | **Host adapter** | `ghost.json` / `plugins/` / `templates/` | Discovery, launch, config, lifecycle | ⚠️ The **only** platform-specific layer |
158
+ | **Client** | `client/carlos.js` / `bridge/` | CLI, trigger check, Bridge daemon | Bridge is Cindy-only |
159
+ | **Protocol** | `src/index.js` | 15 MCP tools + validation + gate semantics | ✅ Zero coupling, pure standard MCP |
160
+ | **Engine** | `src/trigger.js` / `src/card.js` / `src/state.js` | Trigger scoring, card validation, state/audit | ✅ Zero coupling, pure JS, no deps |
161
+ | **Persistence** | `~/.carlos-flow/` | State, audit chain, snapshots, trigger history | ✅ Cross-platform path convention |
162
+
163
+ > **Core design principle**: the MCP protocol is **passive** — a server cannot push.
164
+ > Therefore "auto-trigger" must be initiated by **the side that can see the user's message**
165
+ > (a host plugin hook, or the agent calling `flow_trigger_check`).
166
+ > Both paths share the exact same `src/trigger.js` implementation, so **behavior is identical**.
167
+
168
+ ---
169
+
170
+ ## 📊 Capability Matrix
171
+
172
+ | Capability | Carlos Flow | Native MCP Server | Prompts / Scripts |
173
+ |------------|-------------|-------------------|-------------------|
174
+ | Scope enforcement | ✅ Runtime `git diff` | ❌ | ❌ Honor system |
175
+ | Real verification | ✅ spawn + capture; no evidence → no PASS | ❌ | ❌ Agent says so |
176
+ | Tamper-proof audit | ✅ SHA-256 chained hashes | ❌ | ❌ |
177
+ | Controlled bypass | ✅ Explicit + auto-cleared | ❌ | ❌ One sentence kills all |
178
+ | Honest dispatch quota | ✅ Counts only dispatches | ❌ | ❌ |
179
+ | Independent review | ✅ Built-in `auditor` role | ❌ | ❌ Optional |
180
+ | Snapshot + restore | ✅ Auto, atomic plan | ❌ | ❌ Manual `git revert` |
181
+ | Daemon lifecycle | ✅ Fully automatic (Cindy) | ❌ Manual | ❌ Manual |
182
+ | Smart triggering | ✅ 3-layer scoring + explainable decision | ❌ | ❌ |
183
+ | Cross-platform | ✅ Single package, 6 platforms | ⚠️ Write your own config | ❌ |
184
+
185
+ > **Trust boundary**: hand-editing `state.json` to fake a PASS verdict is possible — the state file is not inside the audit hash chain.
186
+ > This is a **local filesystem permission** boundary, not an MCP tool-surface hole: whoever can write
187
+ > `CARLOS_FLOW_HOME` could edit their own code anyway.
188
+ > Full explanation in the [QA Report](./docs/QA_REPORT_v2.5.5.md) §6.
189
+
190
+ ---
191
+
192
+ ## 📦 Installation
133
193
 
134
194
  ```bash
135
- # or from source
136
- cp .env.example .env # edit: CARLOS_FLOW_MCP_ROOT, CARLOS_FLOW_HOME
195
+ npm install -g carlos-flow
137
196
  ```
138
197
 
139
- ### 3. Set the environment variables
198
+ > ⚠️ `ETARGET: No matching version found`? That's npm's **registry metadata cache** not being refreshed:
199
+ > ```bash
200
+ > npm cache clean --force
201
+ > npm view carlos-flow versions # verify the version exists
202
+ > ```
203
+
204
+ **Requirements**: Node.js ≥ 22.0.0 | MCP SDK ≥ 1.29.0 | Zero runtime external dependencies
205
+
206
+ ---
207
+
208
+ ## 🖥️ Platform Support
209
+
210
+ One package, six platforms. The init command generates the right config file for each.
211
+
212
+ | Platform | Init command | Generated artifacts | Platform-specific extras |
213
+ |----------|--------------|--------------------|--------------------------|
214
+ | **Cindy** | `carlos-flow init --target cindy` | `~/.cindy/ghosts/carlos-flow.json` | Auto-managed Bridge + Settings UI |
215
+ | **OpenCode** | `carlos-flow init --target opencode` | `~/.config/opencode/plugin/opencode.json`<br/>+ project `.mcprc` | `chat.message` hook auto-trigger |
216
+ | **Cursor / Windsurf** | `carlos-flow init --target cursor` | Project `.cursor/mcp.json` | — |
217
+ | **Cline** | `carlos-flow init --target cline` | Project `.cline/mcp.json` | — |
218
+ | **VS Code (Copilot)** | `carlos-flow init --target vscode` | Project `.vscode/mcp.json` | — |
219
+ | **Claude Desktop** | `carlos-flow init --target claude` | macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`<br/>Windows: `%APPDATA%\Claude\claude_desktop_config.json` | — |
220
+
221
+ > 💡 All platforms share the same config fields: `CARLOS_FLOW_HOME` (state dir) + `node <root>/src/index.js` (stdio launch).
222
+
223
+ ---
224
+
225
+ ## 🚀 Quick Start
226
+
227
+ ### 1. Install and initialize
228
+
229
+ ```bash
230
+ npm install -g carlos-flow
231
+ carlos-flow init --target <your-platform> # cindy | opencode | cursor | cline | vscode | claude
232
+ ```
233
+
234
+ ### 2. Environment variables (optional — all have defaults)
140
235
 
141
236
  ```bash
142
- # 把下面两行换成你自己的实际路径
143
- CARLOS_FLOW_MCP_ROOT=/opt/carlos-flow-cindy # Windows 例:D:/apps/carlos-flow-cindy
144
- CARLOS_FLOW_HOME=~/.carlos-flow # Windows 例:C:/Users/<你的用户名>/.carlos-flow
145
- BRIDGE_PORT=19099
237
+ CARLOS_FLOW_HOME=~/.carlos-flow # state / audit directory (cross-platform)
238
+ CARLOS_FLOW_MCP_ROOT=/path/to/carlos-flow # repo root for source installs
239
+ BRIDGE_PORT=19099 # Cindy Bridge port
146
240
  ```
147
241
 
148
- ### 4. Restart and verify
242
+ > Always use **forward slashes** (`/home/you/apps/carlos-flow`) or **double backslashes**
243
+ > (`D:\\apps\\carlos-flow`). A single backslash is treated as an escape in config files —
244
+ > `\c` and `\o` get eaten and the path silently breaks.
245
+
246
+ ### 3. Verify the service is healthy
149
247
 
150
248
  ```bash
151
- # ask Cindy “走门禁”, or verify via the CLI
152
249
  node client/carlos.js flow_status '{"sessionId":"probe"}'
153
250
  ```
154
- > Expected output contains `has_card: false`, which means the service is alive.
155
-
156
- > 📁 On first run a state directory is created under `CARLOS_FLOW_HOME` (default `~/.carlos-flow`),
157
- > holding the **audit log** and **file snapshots**. **Do not delete it manually** — that would break the audit chain.
158
-
159
- ---
160
- ## 🌟 Core capabilities
161
- #### 🆕 Smart trigger engine — `src/trigger.js`
162
- > **Decision → judgment → activation**, end to end: decides *before* the workflow starts whether this is the moment to run the gate, then turns that verdict into **real gate actions**.
163
-
164
- ##### 🔁 Decision & activation flow
165
- ```mermaid
166
- flowchart LR
167
- U[User input] --> L1{"L1 dynamic cap<br/>still allowed?"}
168
- L1 -->|"throttled"| T["throttled<br/>reports the real score<br/>takes no action"]
169
- L1 -->|"allowed"| L2{"L2 three-axis score<br/>keyword + context + intent"}
170
- L2 -->|"< 10"| I["ignore"]
171
- L2 -->|"10 ~ 15"| R["review<br/>suggest manual start"]
172
- L2 -->|"≥ 15"| L3{"≥ 25 and<br/>confidence ≥ 0.8?"}
173
- L3 -->|"no"| M["manual<br/>advice only<br/>no auto execution"]
174
- L3 -->|"yes"| A["✅ activated"]
175
- A --> A1["flow_add_user_msg<br/>record the user text"]
176
- A1 --> A2["flow_submit_requirement<br/>submit a read_only placeholder card"]
177
- A2 --> G{"Gate<br/>scope / acceptance / verify.cmd<br/>filled in?"}
178
- G -->|"not yet"| B["flow_claim / flow_dispatch<br/>refuse to dispatch"]
179
- G -->|"yes"| C["normal dispatch<br/>executor → auditor"]
180
- ```
181
-
182
- ##### What activation actually does (it is not just a log line)
183
- | Stage | Action | Effect |
184
- |-------|--------|--------|
185
- | **Judgment** | L1 cap → L2 scoring → L3 four-way decision | Produces `decision` + `score` + `confidence` + `breakdown` |
186
- | **Translation** | `buildActivationPlan()` | Turns the verdict into an **executable MCP action sequence** |
187
- | **Activation ①** | `flow_add_user_msg` | The user's own words become the anchor source for the card's `quote` |
188
- | **Activation ②** | `flow_submit_requirement` (`activation: true`) | Submits a `read_only` placeholder card — the session **enters the gated state** |
189
- | **Gate** | `activation_pending` | Until `scope` / `acceptance` / `verify.cmd` are filled in, `flow_claim`, `flow_dispatch` and `flow_verdict` all **refuse** (no "PASS without ever running it") |
190
- | **Release** | Resubmit the complete card | `activation_pending` clears → normal dispatch proceeds |
191
-
192
- > Safety constraint: when the session **already has a card**, auto-activation skips card creation (it never overwrites an existing task). Auto-activation only handles "record + enter the gate" — it **never decides which files may change** on the agent's behalf.
193
-
194
- ##### Code usage
195
- ```javascript
196
- import TriggerEngine from './src/trigger.js';
197
-
198
- const engine = TriggerEngine.create('session-123');
199
- const result = engine.shouldTrigger('run dispatch workflow', { complexity: 1.2 });
200
-
201
- // {
202
- // shouldTrigger: true,
203
- // decision: 'trigger', // trigger | review | ignore | throttled
204
- // score: 38, // weighted total, 0~38
205
- // confidence: 0.9,
206
- // breakdown: { keyword: {...}, context: {...}, intent: {...} },
207
- // action: { type: 'workflow_trigger', recommendedAction: 'auto' },
208
- // activationPlan: { // ← the verdict translated into actions
209
- // activated: true,
210
- // steps: [
211
- // { tool: 'flow_add_user_msg', auto: true },
212
- // { tool: 'flow_submit_requirement', auto: true },
213
- // { tool: 'flow_submit_requirement', auto: false, needsFill: ['scope','acceptance','verify.cmd'] }
214
- // ],
215
- // pendingFields: ['scope', 'acceptance', 'verify.cmd'],
216
- // prompt: '【Carlos 触发引擎已激活工作流】…'
217
- // }
218
- // }
219
- ```
220
-
221
- ##### One-line activation from the CLI
222
- ```bash
223
- # pass the real user text via triggerMessage (or the CARLOS_TRIGGER_MESSAGE env var)
224
- node client/carlos.js flow_status '{"sessionId":"my-task","triggerMessage":"run dispatch workflow"}'
225
- ```
226
- > ⚠️ `triggerMessage` **must be passed explicitly** — without it automatic triggering is **entirely off**.
227
- > Chinese workflow words are built in (工作流 / 门禁 / 派发 / 审计 / 复核 / 任务卡 …),
228
- > so Chinese requests trigger too; override the vocabulary via
229
- > `CARLOS_FLOW_HOME/trigger-config.json` (`keywordWeights`).
230
-
231
- ##### MCP tool triggering (path ①)
232
- ```jsonc
233
- // Call from any MCP host; it actually activates when the message qualifies
234
- { "name": "flow_trigger_check",
235
- "arguments": { "sessionId": "my-task", "message": "走门禁流程,执行 dispatch 任务" } }
236
- // → { "decision": "trigger", "score": 34, "activated": true, "has_card": true,
237
- // "activation_pending": ["scope", "acceptance", "verify.cmd"] }
238
- ```
239
- > Pass `execute: false` to score only, without taking any action.
240
-
241
- ##### Custom trigger vocabulary (optional)
242
- **Chinese and English workflow words are built in** and work out of the box — Chinese requests
243
- ("走门禁流程", "执行工作流") trigger normally, while ordinary development requests
244
- ("给接口加个参数校验") do **not** misfire.
245
-
246
- To add your own words, edit `CARLOS_FLOW_HOME/trigger-config.json` (default `~/.carlos-flow/trigger-config.json`):
247
-
248
- ```jsonc
249
- {
250
- // Merged / overrides same-name entries — the default vocabulary (incl. built-in Chinese) is **kept**
251
- "keywordWeights": { "评审": 3, "走查": 3 },
252
- // Appended, de-duplicated
253
- "readOnlyIntentWords": ["讲一下"],
254
- "mutatingActionWords": ["改造一下"]
255
- }
256
- ```
257
-
258
- > 📌 Merge semantics: **append, not replace**. Just write the entries you care about — no need to copy the whole default table.
259
- > Restart the host (MCP server / plugin) after editing for the config to be re-read.
260
- > Ready-made templates ship with the package: `trigger-config.usable.json` (drop-in) and `trigger-config.example.json` (documented).
261
-
262
- > **Cindy edition note**: the Cindy plugin is a `kind: "mcp"` package (a pure MCP tool set) — the host exposes no message-event hook,
263
- > so there is no "evaluate on every message" plugin here.
264
- > Use path ① (the agent calls `flow_trigger_check`) or path ② (the CLI) — the gate constraints
265
- > themselves (scope enforcement / real verification / rejected fake PASS) are identical either way.
266
- ##### Engine highlights
267
- - **L1 dynamic cap** — `5 + sessionHours×0.5 + complexity×2 − triggersInWindow×0.3`, capped at 15
268
- - **L2 trigger scoring** — keywords (0–50, weight 0.5) + context (0–30, weight 0.3) + intent (0–20, weight 0.2), weighted maximum **38**
269
- - **L3 decision engine** — four outcomes: `trigger` / `review` (borderline, needs confirmation) / `ignore` (below 10) / `throttled` (rate-limited)
270
- - **Per-session isolation** — trigger history and throttling state are stored **per session file**, so sessions never throttle each other
271
- - **Tunable thresholds** — `triggerThreshold: 15`, `autoTriggerThreshold: 25`, `lowConfidenceThreshold: 10`
272
- - **Zero external dependencies** — plain JavaScript, no new npm packages
273
- - **Learns from feedback** — records accepted / rejected triggers (persisted); when negative feedback dominates, the **trigger threshold is raised automatically**
274
-
275
- > Full configuration and usage: [TRIGGER_GUIDE.md](TRIGGER_GUIDE.md)
276
-
277
- ### 1️⃣ Real verification — `flow_run_verify`
278
- ```typescript
279
- const result = await runVerifyCommand(card.verify.cmd, cwd);
280
- // { ok: boolean, exitCode: number, stdout: string, stderr: string, durationMs: number }
281
- ```
282
- Actually spawns the command. Captures full output. 60-second circuit breaker. No "trust me, it passed."
283
- ### 2️⃣ Scope enforcement — `flow_check_scope`
284
- ```typescript
285
- const result = enforceScope(scopeWhitelist, changedFiles);
286
- // { ok: boolean, violations: string[] }
287
- ```
288
- Machine-level comparison of the working tree against the card's whitelist. File-level precision, zero false positives on unchanged files.
289
- ### 3️⃣ Tamper-proof audit chain — `verifyAuditChain`
290
- ```typescript
291
- const result = verifyAuditChain({ sinceIndex: 0 });
292
- // { ok: boolean, brokenAt?: number, detail?: string }
293
- ```
294
- Every record carries `prevHash`, `hash` and `seq`. A single edited byte invalidates everything downstream — mathematically, not administratively.
295
- ### 4️⃣ Controlled bypass — `flow_bypass` + `isBypassed()`
296
- - Must be explicitly enabled (`bypass=true` **and** `confirmed=true`)
297
- - Auto-resets on every dispatch — you cannot "forget to turn it off"
298
- - Every toggle is written to the audit chain
299
- ### 5️⃣ Honest dispatch budget — `dispatch_count`
300
- - Increments **only** in `flow_dispatch`; `flow_claim` / `flow_verdict` never count
301
- - Quota exhaustion blocks **both** claim and dispatch
302
- - No infinite-retry path
303
- ### 6️⃣ Snapshot & restore — `flow_dispatch` → `flow_revert_plan`
304
- - Files in `scope` are snapshotted automatically before each dispatch
305
- - `flow_revert_plan` emits an atomic, ordered restore plan (newest first)
306
- - Partial rollback supported
307
- ### 7️⃣ Independent review — `auditor` role
308
- - Separate four-part contract with an evidence-gathering mandate
309
- - Auditor must run `git status --porcelain` / `git diff` itself
310
- - Verdict enum is strict: `PASS` / `DIRECTION` / `LOCAL`
311
-
312
- ---
313
- ## 📖 Use cases
314
- ### Scenario 1 — New feature development
315
- ```mermaid
316
- flowchart LR
317
- A[Requirement] --> B[Submit card]
318
- B --> C[Dispatch Executor]
319
- C --> D[Implement]
320
- D --> E[Save result]
321
- E --> F[Real verify]
322
- F --> G[Scope check]
323
- G --> H[Dispatch Auditor]
324
- H --> I[Independent review]
325
- I --> J[Verdict PASS]
326
- ```
327
- ### Scenario 2 — Bug fix
328
- - Card `quote` is anchored to the user's original words — the agent cannot silently redefine the request
329
- - `scope` narrowed to the single file
330
- - `verify.cmd` runs the regression test, not a hand-written summary
331
- ### Scenario 3 — Large refactor
332
- - Multi-file `scope` managed as one whitelist
333
- - Snapshots protect against a half-finished refactor
334
- - Restore plan is the safety net
335
- ### Scenario 4 — Security audit / sensitive paths
336
- - T2 risk tier requires explicit `confirmed=true`
337
- - Sensitive paths (`config/`, `secrets/`, `infra/`, …) are flagged and gated
338
- - Audit chain provides tamper-evident evidence trail
339
- ### Scenario 5 — CI / PR gating
340
- - Same flow, driven from CI
341
- - Verdict can block a merge
342
- - Audit log archived for compliance
343
-
344
- ---
345
- ## 🏗️ Architecture
346
- ```mermaid
347
- flowchart TB
348
- subgraph Cindy["Cindy App"]
349
- UI[Plugin settings] --> ENV[Encrypted env vault]
350
- ENV --> BR[Bridge daemon]
351
- end
352
- subgraph Server["MCP Server (src/)"]
353
- T[14 tools] --> C[Card parse & validate]
354
- C --> S[State & audit chain]
355
- S --> D[Dispatch / snapshot / verify]
356
- end
357
- BR <-- "TCP 127.0.0.1:19099 · token · rate-limited" --> Server
358
- CLI[CLI client] --> BR
359
- REA[rea MCP] -. optional .-> BR
360
- ```
361
- ### Why a Bridge in the Cindy edition?
362
- | | Cindy edition (this repo) | OpenCode edition |
363
- |---|---|---|
364
- | Transport | TCP Bridge on `127.0.0.1:19099` | Pure stdio |
365
- | Daemon lifecycle | **Automatic** — launched on first call, health-checked | Managed by OpenCode |
366
- | Configuration | Plugin settings page + env vars | `.mcprc` / `opencode.json` |
367
- | Secret storage | **Cindy encrypted vault** — no plaintext in code | Plaintext config (user-managed) |
368
- | rea integration | Built-in `client/rea.js` | Register a second MCP server |
369
- | Best for | Cindy App users | OpenCode 2.2.2+ users |
370
-
371
- ---
372
- ## 🛠️ The 15 tools
373
- ### 📝 Card & record
374
- | Tool | Purpose | Key params |
375
- |------|---------|------------|
376
- | `flow_protocol` | Read the full protocol (tiers T0/T1/T2, contracts, error layers, state schema) | — |
377
- | `flow_add_user_msg` | Record the user's original words (anchor source) | `sessionId`, `text` |
378
- | `flow_submit_requirement` | Submit the task card (validate + record) | `goal`, `quote`, `scope`, `acceptance`, `confirmed` |
379
- ### 🚀 Dispatch & execution
380
- | Tool | Purpose | Key params |
381
- |------|---------|------------|
382
- | `flow_claim` | Claim a dispatch slot, get the four-part contract | `sessionId`, `role` (`executor`\|`auditor`) |
383
- | `flow_dispatch` | Generate the contract prompt + automatic file snapshot | `sessionId`, `role`, `message`, `run?` |
384
- | `flow_run_verify` | **Really execute `verify.cmd`** | `sessionId` |
385
- | `flow_check_scope` | **Machine-level scope enforcement** | `sessionId`, `paths[]` |
386
- ### ⚖️ Verdict & status
387
- | Tool | Purpose | Key params |
388
- |------|---------|------------|
389
- | `flow_verdict` | Record the verdict (`PASS`/`DIRECTION`/`LOCAL`) | `sessionId`, `verdict`, `notes` |
390
- | `flow_status` | Query the full gate state | `sessionId` |
391
- ### 🔍 Audit & forensics
392
- | Tool | Purpose | Key params |
393
- |------|---------|------------|
394
- | `flow_audit` | Read the audit trail (filter by type/time/session) | `sessionId`, `type?`, `since?` |
395
- | `flow_diff_hunks` | git diff hunk-level analysis | `sessionId`, `scope?` |
396
- | `flow_revert_plan` | Generate the atomic restore plan | `sessionId` |
397
- ### 🛡️ Bypass & restore
398
- | Tool | Purpose | Key params |
399
- |------|---------|------------|
400
- | `flow_bypass` | Bypass switch (requires `confirmed`) | `sessionId`, `bypass`, `confirmed` |
401
- > Full tool reference: call `flow_protocol` at runtime — it is the authoritative, machine-readable spec.
402
-
403
- ---
404
- ## ⚙️ Environment variables
405
- | Variable | Required | Description | Example |
406
- |----------|----------|-------------|---------|
407
- | `CARLOS_FLOW_MCP_ROOT` | ✅ | MCP source root (contains `src/` `bridge/` `client/`) | `/opt/carlos-flow-cindy` |
408
- | `CARLOS_FLOW_HOME` | ✅ | State / audit / snapshot root | `~/carlos-flow` |
409
- | `BRIDGE_PORT` | ❌ | Bridge listen port (default `19099`) | `19099` |
410
- | `REA_MCP_ROOT` | ❌ | rea MCP source root | `/opt/rea` |
411
- | `GHIDRA_HOME` | ❌ | Ghidra install dir | `/opt/ghidra_12.1.4_PUBLIC` |
412
- | `JAVA_HOME` | ❌ | JDK 21 install dir | `/usr/lib/jvm/java-21-openjdk` |
413
- | `NODE_PATH` | ❌ | Node.js executable path (default `node`) | `node` |
414
- > **Tip**: changes made on the Cindy plugin settings page require a **full Cindy restart** to take effect.
415
-
416
- ---
417
- ## 🧪 Testing
418
- ```bash
419
- npm test # smoke test — isolated temp dir, < 10s
420
- npm run test:e2e # 16-case end-to-end suite
421
- npm run test:p0 # 10-case gate suite (role whitelist / scope / bypass confirmation …)
422
- npm run test:trigger # 25-case trigger engine suite (incl. 10 regression cases)
423
- npm run test:all # all four suites chained
424
- ```
425
- > No environment setup needed locally (the suites fall back to the repo root automatically). CI runs all four suites on **ubuntu-latest** and **windows-latest** for every push and pull request.
426
-
427
- ---
428
- ## 📋 Changelog
429
- Full history → [CHANGELOG.md](CHANGELOG.md)
430
- ### v2.5.5 — 2026-11-05 · Smart trigger engine + 7 real defects fixed
431
- | Type | Change |
432
- |------|--------|
433
- | ✨ New | Smart trigger engine (`src/trigger.js`): L1 dynamic cap / L2 three-axis scoring / L3 four-way decision |
434
- | ✨ New | `TRIGGER_GUIDE.md` complete usage guide (config, scoring formula, troubleshooting) |
435
- | ✨ New | `test/trigger-e2e.mjs` — 25 cases incl. 10 regression cases; `npm run test:all` chains all five suites |
436
- | ✨ New | `scripts/release.mjs` release script + `npm run check:readme` bilingual consistency hook |
437
- | ✨ New | `docs/QA_REPORT_v2.5.5.md` independent QA acceptance report (5 suites green) |
438
- | 🐛 Fixed | Trigger engine silently swallowed by `require()` in the ESM client → dynamic `import()` |
439
- | 🐛 Fixed | Trigger cap compared a 0–1 average against 5–15 → never fired → now uses the raw count |
440
- | 🐛 Fixed | History factor in the dynamic cap was additive (more triggers → higher cap) → now a penalty |
441
- | 🐛 Fixed | `processUserMessage()` hard-coded the session id → now passed through from context |
442
- | 🐛 Fixed | Trigger CLI entry never matched because of the `file:///` prefix → `fileURLToPath()` |
443
- | 🐛 Fixed | Score collapsed to 0 and confidence was lost while throttled → now reported honestly |
444
- | 🐛 Fixed | Test result file written into the publish directory → now the system temp directory |
445
- | 🔒 Security | `.gitignore` collision meant the npm-token-bearing `.npmrc.local` was never ignored → split rules |
446
- | 🔒 Security | Trigger state written to the CWD → unified under `CARLOS_FLOW_HOME` |
447
- | 🔒 Security | Hard-coded machine path → cross-platform `~/.carlos-flow` default |
448
- | 🧹 Cleanup | 42 one-off fix scripts and scratch files removed (net −5325 lines) |
449
- | 🔑 Release | GitHub Actions OIDC publishing — no npm token in the repo any more |
450
- | 📚 Docs | Removed README language-bar / version-line noise (24–26 per file → 1 at the top) |
451
-
452
- ### v2.5.3 — 2026-11-04 · Fatal syntax fixes + verified gates
453
- | Type | Change |
454
- |------|--------|
455
- | ✨ New tools | `flow_run_verify`, `flow_check_scope` |
456
- | ✨ Core | `runVerifyCommand()` really executes `verify.cmd` |
457
- | ✨ Core | `enforceScope()` machine-level scope enforcement |
458
- | ✨ Core | `verifyAuditChain()` SHA-256 audit-chain validation |
459
- | ✨ Core | `isBypassed()` real bypass semantics |
460
- | 🐛 Fixed | role whitelist (only `executor`/`auditor`; typos now error) |
461
- | 🐛 Fixed | `dispatch_count` increments on dispatch only |
462
- | 🐛 Fixed | bypass auto-resets on new dispatch |
463
- | 🐛 Fixed | stale-card / quota / verdict-enum / param validation |
464
- > ⚠️ **v2.5.1 contained 18 P0 defects.** Upgrade to **v2.5.2 or later**.
465
-
466
- ---
467
- ## ❓ FAQ
468
- | Symptom | Fix |
469
- |---------|-----|
470
- | Bridge port conflict (`EADDRINUSE`) | Change `BRIDGE_PORT`, or `lsof -ti:19099 \| xargs kill` |
471
- | Plugin settings changes have no effect | **Fully quit Cindy and restart** (not minimize-to-tray) |
472
- | Audit chain validation fails | Check `CARLOS_FLOW_HOME` permissions, or delete `audit/` and let it rebuild |
473
- | Verification command times out | `verify.cmd` is killed after 60s — split it into fast commands |
474
- | Scope violation false positive | Use relative paths in `scope`; `git diff --name-only` must match |
475
- | The trigger engine never fires | Check whether your input hits the `keywordWeights` vocabulary; the default list is English, so extend it for other languages |
476
- | The trigger engine fires too often | Raise `triggerThreshold`, increase `minTriggerIntervalSeconds`, or lower `historyCoeff` |
477
- | Where do trigger state files live? | Under `CARLOS_FLOW_HOME` (default `~/.carlos-flow`) — never in the current working directory |
478
-
479
- ---
480
- ## 📄 License
481
- MIT — see [LICENSE](LICENSE)
482
-
483
- ---
484
- ## 🤝 Contributing
485
- PRs welcome! Please make sure `npm test` and `npm run test:e2e` pass first. See [CONTRIBUTING.md](CONTRIBUTING.md).
486
-
487
- ---
488
- **Using OpenCode instead?** → [carlos-flow-opencode](https://github.com/skyer-now/carlos-flow-opencode) — pure stdio, no Bridge, configured via `.mcprc` / `opencode.json`.
251
+
252
+ Expect `"has_card": false`.
253
+
254
+ ### 4. Walk through one full gate cycle
255
+
256
+ ```bash
257
+ # ① Trace — record the user's own words (the only quote anchor source)
258
+ node client/carlos.js flow_add_user_msg '{"sessionId":"demo","text":"add parameter validation to the login endpoint"}'
259
+
260
+ # ② Submit the task card (scope is the whitelist)
261
+ node client/carlos.js flow_submit_requirement '{"sessionId":"demo","goal":"add parameter validation","quote":"add parameter validation to the login endpoint","scope":["src/auth.py"],"acceptance":["invalid params return 400"],"verify":{"cmd":"npm test"},"cwd":"/path/to/project"}'
262
+
263
+ # ③ Claim a dispatch slot
264
+ node client/carlos.js flow_claim '{"sessionId":"demo","role":"executor"}'
265
+
266
+ # ④ Dispatch (auto-snapshots files in scope)
267
+ node client/carlos.js flow_dispatch '{"sessionId":"demo","role":"executor"}'
268
+
269
+ # ⑤ Really execute the verification command
270
+ node client/carlos.js flow_run_verify '{"sessionId":"demo","cwd":"/path/to/project"}'
271
+
272
+ # ⑥ Record the verdict (no PASS without passing verification evidence)
273
+ node client/carlos.js flow_verdict '{"sessionId":"demo","verdict":"PASS","notes":"tests pass"}'
274
+ ```
275
+
276
+ ---
277
+
278
+ ## 🔧 MCP Tool Reference (15 tools)
279
+
280
+ | Tool | Purpose | Key constraint |
281
+ |------|---------|----------------|
282
+ | `flow_protocol` | Read the full gate protocol (tiers, four-part contract, error layering) | — |
283
+ | `flow_add_user_msg` | Write the user's original message | **The only quote anchor source** |
284
+ | `flow_submit_requirement` | Submit / replace the task card | Required fields enforced per risk tier; fake fillers rejected |
285
+ | `flow_claim` | Claim a dispatch slot (executor / auditor) | Rejected while the activation gate is open |
286
+ | `flow_dispatch` | Dispatch a sub-agent per the four-part contract | Auto-snapshots files in scope before dispatch |
287
+ | `flow_save_result` | Save a sub-agent's result | — |
288
+ | `flow_run_verify` | **Really execute** `verify.cmd` | Returns exitCode / stdout / stderr |
289
+ | `flow_check_scope` | Check whether files are in scope | Empty scope → fail-closed, everything out of scope |
290
+ | `flow_verdict` | Record verdict PASS / DIRECTION / LOCAL | No PASS without dispatch; no PASS without passing verification |
291
+ | `flow_status` | Query gate state | Exposes `activation_pending` / `verify_passed` |
292
+ | `flow_audit` | Read the audit stream | Includes 6 activation-related event kinds |
293
+ | `flow_diff_hunks` | Parse `git diff -U0` hunk ranges | — |
294
+ | `flow_bypass` | Toggle bypass mode | Requires `confirmed=true`; auto-cleared on dispatch |
295
+ | `flow_revert_plan` | Generate an atomic restore plan | Returns a plan only, never executes |
296
+ | `flow_trigger_check` | Smart trigger check | Activates on success; honestly reports score otherwise |
297
+
298
+ ---
299
+
300
+ ## ⚙️ Configuration
301
+
302
+ ### Trigger config
303
+
304
+ Path: `$CARLOS_FLOW_HOME/trigger-config.json` (auto-generated by `init`)
305
+
306
+ ```json
307
+ {
308
+ "keywordWeights": {
309
+ "review": 5
310
+ },
311
+ "readOnlyIntentWords": ["explain to me"],
312
+ "mutatingActionWords": ["refactor it"]
313
+ }
314
+ ```
315
+
316
+ **Merge semantics** (important):
317
+ - `keywordWeights` → **object merge** (custom words override same-named defaults; the rest are preserved)
318
+ - Word-list arrays → **appended and de-duplicated** (extension, not replacement)
319
+ - Other scalars → override
320
+
321
+ > The old implementation used a shallow merge — one custom word wiped the entire default table
322
+ > (including the built-in Chinese workflow terms), so Chinese requests scored 0 again. Fixed.
323
+
324
+ ### Environment variables
325
+
326
+ | Variable | Default | Purpose |
327
+ |----------|---------|---------|
328
+ | `CARLOS_FLOW_HOME` | `~/.carlos-flow` | State / audit / snapshot directory. `~` is expanded |
329
+ | `CARLOS_FLOW_MCP_ROOT` | auto-derived | Repo root for source installs |
330
+ | `BRIDGE_PORT` | `19099` | Cindy Bridge listening port |
331
+ | `CARLOS_BRIDGE_TOKEN` | built-in default | Local Bridge auth token |
332
+ | `CARLOS_BRIDGE_TIMEOUT_MS` | `180000` | Bridge request timeout (must exceed the server's 120s verify limit) |
333
+ | `CARLOS_MCP_TIMEOUT_MS` | `180000` | CLI client MCP call timeout |
334
+ | `CARLOS_TRIGGER_MESSAGE` | — | Inject the user's original message for CLI trigger checks |
335
+ | `OPENCODE_DB_PATH` | multi-probe | OpenCode session DB path (used to read user utterances) |
336
+
337
+ ---
338
+
339
+ ## 🧪 Development
340
+
341
+ ```bash
342
+ git clone https://github.com/skyer-now/carlos-flow.git
343
+ cd carlos-flow
344
+ npm install
345
+
346
+ # Full suite (129 cases)
347
+ npm run test:all
348
+
349
+ # Individual
350
+ npm run test:e2e # E2E — 62 cases
351
+ npm run test:p0 # P0 gates — 22 cases
352
+ npm run test:trigger # Trigger engine — 29 cases
353
+ npm run test:concurrency # Cross-process concurrency — 3 cases
354
+ npm run test:acceptance # Acceptance — 13 cases
355
+ npm run test:mutation # Mutation testing (13/13 mutants caught)
356
+ npm run check:anchors # Mutation-anchor uniqueness guard
357
+ npm run check:readme # Bilingual README consistency
358
+
359
+ # Pack
360
+ npm pack
361
+ ```
362
+
363
+ ### Test Coverage Matrix
364
+
365
+ | Suite | Count | Covers |
366
+ |-------|-------|--------|
367
+ | `smoke` | 4 | Card parsing / validation / state round-trip |
368
+ | `e2e-carlos` | 62 | Full flow + activation gate + fake-loop prevention + scope enforcement |
369
+ | `p0-gates` | 22 | P0 gate semantics (fake fillers, type checks, fail-closed) |
370
+ | `trigger-e2e` | 29 | 3-layer engine + session isolation + config merge + `~` expansion |
371
+ | `concurrency-e2e` | 3 | Cross-process concurrency, zero leaks / zero exploits |
372
+ | `e2e-acceptance` | 13 | MCP-path triggering + Chinese word lists + plugin really opens a card |
373
+ | **Total** | **129** | **All passing** |
374
+
375
+ ---
376
+
377
+ ## 📚 Documentation
378
+
379
+ | Document | Description |
380
+ |----------|-------------|
381
+ | [TRIGGER_GUIDE.md](./TRIGGER_GUIDE.md) | Deep guide to the Smart Trigger Engine (config, scoring, activation, feedback learning) |
382
+ | [CHANGELOG.md](./CHANGELOG.md) | Version history (Keep a Changelog + SemVer) |
383
+ | [MIGRATION.md](./MIGRATION.md) | Migrating from `carlos-flow-cindy` / `carlos-flow-opencode` |
384
+ | [QA Report](./docs/QA_REPORT_v2.5.5.md) | Third-party read-only audit (13/13 mutants caught) |
385
+ | [Mutation Report](./docs/MUTATION_REPORT_v2.5.5.md) | Mutation injection details and results |
386
+
387
+ ---
388
+
389
+ ## ❓ FAQ
390
+
391
+ <details>
392
+ <summary><b>Q: How is this different from a plain MCP Server?</b></summary>
393
+
394
+ A plain MCP Server exposes tools but **doesn't enforce anything** — it trusts the caller to use them correctly.
395
+ Carlos Flow enforces at **server runtime**: out-of-scope files are stopped by `enforceScope()`,
396
+ PASS is refused without passing verification, and audit chain edits break the chain.
397
+ </details>
398
+
399
+ <details>
400
+ <summary><b>Q: I only use Cindy — do I still install all this?</b></summary>
401
+
402
+ No extra download. The single package is the **same install size** (~106 KB) for everyone;
403
+ only the template files differ per platform.
404
+ </details>
405
+
406
+ <details>
407
+ <summary><b>Q: Will this slow my agent down?</b></summary>
408
+
409
+ No. Gate state is **file-based** — no database, no network, no resident process
410
+ (except the Cindy Bridge, which only launches on first call).
411
+ The trigger engine is pure JS computation with zero dependencies.
412
+ </details>
413
+
414
+ <details>
415
+ <summary><b>Q: Is `CARLOS_FLOW_HOME=~/.carlos-flow` really expanded?</b></summary>
416
+
417
+ Yes. Early versions **did not expand it** — `path.normalize` only swaps separators, so the path stayed literal
418
+ and state landed in "a directory literally named `~` inside the current working directory".
419
+ Now `state.js` / `trigger.js` share `expandHome()`, with a regression test guarding it.
420
+ </details>
421
+
422
+ <details>
423
+ <summary><b>Q: Can bypass mode become a backdoor?</b></summary>
424
+
425
+ Bypass requires an **explicit** `confirmed=true` on the card, and `bypass_ts` must be later than `card_ts`
426
+ (an old card's bypass can't apply to a new card).
427
+ Most importantly it **auto-clears after every dispatch** — it applies to one dispatch, never becomes a permanent switch.
428
+ </details>
429
+
430
+ <details>
431
+ <summary><b>Q: Does it work in Chinese?</b></summary>
432
+
433
+ Fully. Chinese workflow terms are built in (工作流/门禁/派发/审计/复核/任务卡/子代理/流程/触发/执行/调度/留痕/裁定),
434
+ so Chinese requests trigger just like English ones — while ordinary dev requests
435
+ ("给接口加个参数校验") never false-trigger.
436
+ </details>
437
+
438
+ <details>
439
+ <summary><b>Q: Can I still use the old packages?</b></summary>
440
+
441
+ Yes, but they are **Deprecated**. See [MIGRATION.md](./MIGRATION.md).
442
+ </details>
443
+
444
+ ---
445
+
446
+ ## 🔗 Links
447
+
448
+ | | |
449
+ |---|---|
450
+ | **Repository** | https://github.com/skyer-now/carlos-flow |
451
+ | **npm** | https://www.npmjs.com/package/carlos-flow |
452
+ | **Issues** | https://github.com/skyer-now/carlos-flow/issues |
453
+ | **Changelog** | [CHANGELOG.md](./CHANGELOG.md) |
454
+
455
+ ---
456
+
457
+ ## 🤝 Contributing
458
+
459
+ PRs welcome! Before submitting, make sure:
460
+
461
+ ```bash
462
+ npm run test:all # 129/0 all passing
463
+ npm run check:anchors # mutation anchors intact
464
+ npm run check:readme # bilingual READMEs in sync
465
+ ```
466
+
467
+ See [CONTRIBUTING.md](./CONTRIBUTING.md).
468
+
469
+ ---
470
+
471
+ ## 📄 License
472
+
473
+ [MIT](./LICENSE) © Carlos Flow Contributors