carlos-flow 2.13.0 → 2.14.1

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/src/index.js CHANGED
@@ -5,13 +5,14 @@ import { spawnSync } from "node:child_process";
5
5
  import { existsSync, readFileSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { createServer, connect } from "node:net";
8
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
9
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
- import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
11
- import { PROTOCOL } from "./protocol.js";
8
+ // MCP stdio 服务端:自己实现的零依赖版本(见 src/mcp-stdio.mjs 开头的理由)。
9
+ // 不再依赖 @modelcontextprotocol/sdk —— 插件要以 .cindy 形态随包运行,
10
+ // 打包会跳过 node_modules,运行期也不许联网装依赖。
11
+ import { serveStdio } from "./mcp-stdio.mjs";
12
+ import { PROTOCOL, loadProjectSensitiveConfig } from "./protocol.js";
12
13
  import { parseCard, validateCard, riskTier, isSensitive } from "./card.js";
13
14
  import { loadState, saveState, defaultState, audit, readAudit, getUserMessages, writeUserMessage, pathExists, gitHead, isStale, isBypassed, verifyAuditChain, withStateLock, auditHashMode, workspaceFingerprint } from "./state.js";
14
- import { buildContractPrompt, snapshotFiles, readManifest, readManifestAll, writeDispatchPrompt, saveAgentResult, runVerifyCommand, runNegativeControl, computeOutputHash, enforceScope, MAX_DISPATCH } from "./dispatch.js";
15
+ import { buildContractPrompt, snapshotFiles, readManifest, readManifestAll, writeDispatchPrompt, saveAgentResult, runVerifyCommand, runNegativeControl, computeOutputHash, enforceScope, formatError, MAX_DISPATCH } from "./dispatch.js";
15
16
 
16
17
  const log = (msg) => {
17
18
  try {
@@ -49,7 +50,21 @@ const ok = (obj) => {
49
50
  const withOk = "ok" in payload ? payload : { ok: true, ...payload };
50
51
  return { content: [{ type: "text", text: JSON.stringify(withOk, null, 2) }] };
51
52
  };
52
- const fail = (message) => ({ content: [{ type: "text", text: "ERROR: " + String(message) }], isError: true });
53
+ // 报错解释层的「模式闸门」。
54
+ //
55
+ // 背景:guide 模式已经由 guideError() 把技术报错翻译成中文人话,
56
+ // 如果 fail() 再追加一层「为什么被拦」的机制说明,用户会看到两段解释(重复且啰嗝)。
57
+ // 因此这里用一次性闼门:guideError 真的翻译了 → fail 原样输出;
58
+ // 否则(pro 模式 / 未翻译的错误)→ 追加机制说明。
59
+ let GUIDE_TRANSLATED = false;
60
+
61
+ const fail = (message) => {
62
+ // 一次性消费:读完之后立即复位,避免影响下一条错误。
63
+ const alreadyHuman = GUIDE_TRANSLATED;
64
+ GUIDE_TRANSLATED = false;
65
+ const explained = alreadyHuman ? String(message) : formatError(String(message));
66
+ return { content: [{ type: "text", text: "ERROR: " + explained }], isError: true };
67
+ };
53
68
 
54
69
  // ---- 向导模式(mode==='guide')报错人话翻译 --------------------------------
55
70
  //
@@ -57,9 +72,43 @@ const fail = (message) => ({ content: [{ type: "text", text: "ERROR: " + String(
57
72
  // 在 guide 模式下把技术码翻译成「发生了什么 + 下一步该怎么做」的中文人话。
58
73
  // pro 模式或未知 mode → 原样返回 technicalMsg,行为绝对不变(向后兼容守护)。
59
74
  //
75
+ // 激活占位卡的「补齐骨架」。
76
+ //
77
+ // 背景:智能触发只开一张占位卡(scope / acceptance / verify 全空),必须补齐才能开工。
78
+ // 旧提示只说「还差三项」,新手 Agent 仍不知道每一项该怎么填,于是在同一个报错上来回空转。
79
+ // 现在直接给出一份可复制的调用骨架:已填好的字段原样保留,缺的项用尖括号占位。
80
+ // 只在 guide 模式 + 占位卡未补齐时输出,pro 模式零影响。
81
+ function activationCardGuide(state) {
82
+ const pending = asStringArray(state && state.activation_pending);
83
+ const card = (state && state.card && typeof state.card === "object") ? state.card : {};
84
+ const kept = (v) => (Array.isArray(v) ? v.map((x) => String(x)).filter((s) => s.trim()) : []);
85
+ const goal = typeof card.goal === "string" && card.goal.trim() ? card.goal.trim() : "<一句话目标>";
86
+ const quote = typeof card.quote === "string" && card.quote.trim() ? card.quote.trim() : "<用户原话摘录>";
87
+ const scope = kept(card.scope);
88
+ const acceptance = kept(card.acceptance);
89
+ const verifyCmd = card.verify && typeof card.verify.cmd === "string" ? card.verify.cmd.trim() : "";
90
+ const skeleton = {
91
+ goal,
92
+ quote,
93
+ scope: scope.length ? scope : ["<要改的文件,仓库根相对路径,可写多个>"],
94
+ acceptance: acceptance.length ? acceptance : ["<怎么算做完:一条可判定的验收标准>"],
95
+ verify: { cmd: verifyCmd || "<能真正跑起来的验证命令,例如 npm test>" },
96
+ confirmed: false,
97
+ };
98
+ const missing = pending.length ? pending : ["scope", "acceptance", "verify"];
99
+ return [
100
+ "这张卡还差 " + missing.length + " 项才能开工:" + missing.join(" / ") + "。",
101
+ "把下面骨架里尖括号的内容换成真实的,再调用一次 flow_submit_requirement 就行(已经填好的字段原样保留):",
102
+ "flow_submit_requirement(" + JSON.stringify(skeleton, null, 2) + ")",
103
+ "补齐之后才能 flow_claim / flow_dispatch;不需要重新开卡。",
104
+ ].join("\n");
105
+ }
106
+
60
107
  // 接入原则:最小侵入——只在**典型门禁拦截点**调用,不做大规模重构。
61
108
  function guideError(state, technicalMsg) {
62
109
  if (!state || state.mode !== "guide") return technicalMsg;
110
+ // 打了这个标记,fail() 就知道「已经是人话」,不再叠机制说明。
111
+ GUIDE_TRANSLATED = true;
63
112
  const msg = String(technicalMsg);
64
113
  // 按关键词映射到通俗解释 + 操作指引
65
114
  const translations = [
@@ -77,6 +126,10 @@ function guideError(state, technicalMsg) {
77
126
  { match: /负对照|falsify/, human: "需要做一次「反向验证」来证明测试确实在起作用。请先调用 flow_falsify 做负对照,通过后再记录裁定。" },
78
127
  { match: /卡片未指定\s*verify/, human: "任务卡里没有写验证命令,没法确认改动对不对。请重新提交一张带 verify.cmd 的任务卡(flow_submit_requirement),这样才有办法验证。" },
79
128
  ];
129
+ // 占位卡未补齐:优先给「可复制的补齐骨架」,而不是只说「还差三项」。
130
+ if (Array.isArray(state.activation_pending) && state.activation_pending.length > 0 && /占位卡/.test(msg)) {
131
+ return activationCardGuide(state) + "\n(原始提示:" + msg + ")";
132
+ }
80
133
  for (const t of translations) {
81
134
  if (t.match.test(msg)) {
82
135
  return t.human + "\n(原始提示:" + msg + ")";
@@ -88,6 +141,42 @@ function guideError(state, technicalMsg) {
88
141
 
89
142
  const asStringArray = (v) => (Array.isArray(v) ? v.map((x) => String(x)) : []);
90
143
 
144
+ // ---- 路径基准统一 ----------------------------------------------------------
145
+ //
146
+ // scope 的校验基准必须与 `git diff --name-only` 的基准**完全一致**。
147
+ //
148
+ // 实测事实(2026-11-17):git diff 即使在子目录里执行,输出的也是**仓库根相对路径**;
149
+ // 而旧实现拿 process.cwd() 当基准去校验 scope。MCP server 是常驻进程,
150
+ // 它的 cwd 是**启动时**的目录(可能是几个月前的旧仓库,也可能只是用户
151
+ // 随手打开终端的位置),于是出现「明明文件就在那,却报 scope 路径不存在」——
152
+ // 使用者根本猜不到真实原因是「基准目录不对」。
153
+ //
154
+ // 现在:一律先求 git 仓库根;非 git 项目才退回调用方给的目录(与旧行为一致)。
155
+ const REPO_ROOT_CACHE = new Map();
156
+ function resolveRepoRoot(cwd) {
157
+ const base = cwd || process.cwd();
158
+ // 缓存:本函数会 spawn 一次 git,而裁定链路上会被调用多次(scope 自查 / 越界判定)。
159
+ // 只缓存**命中**结果;未命中不缓存 —— 目录可能稍后才变成 git 仓库(测试里就是如此)。
160
+ const cached = REPO_ROOT_CACHE.get(base);
161
+ if (cached !== undefined) return cached;
162
+ try {
163
+ const r = spawnSync("git", ["rev-parse", "--show-toplevel"], {
164
+ cwd: base,
165
+ encoding: "utf8",
166
+ timeout: 5000,
167
+ windowsHide: true,
168
+ shell: false,
169
+ });
170
+ const top = r.status === 0 ? String(r.stdout || "").trim() : "";
171
+ if (top) {
172
+ if (REPO_ROOT_CACHE.size > 64) REPO_ROOT_CACHE.clear();
173
+ REPO_ROOT_CACHE.set(base, top);
174
+ return top;
175
+ }
176
+ } catch { /* git 不可用:退回原目录 */ }
177
+ return base;
178
+ }
179
+
91
180
  // 卡片文本字段(scope / acceptance / unknowns / assumptions)**保留原始元素类型**,
92
181
  // 不做任何过滤/转换。
93
182
  // 背景:早先用 asStringArray(String(x))会把 null→「null」、{}→「[object Object]」,
@@ -164,9 +253,21 @@ const WARN_FINDINGS_LIMIT = 20;
164
253
  // 附带回答 DIRECTION/LOCAL 路径:返工意见恰恰最需要坏味道清单,
165
254
  // 所以三种裁定都带这份汇总。
166
255
  function collectAxisWarnings(state) {
167
- const ax = state && state.audit_axes;
168
- if (!ax || typeof ax !== "object") return [];
256
+ if (!state || typeof state !== "object") return [];
169
257
  const out = [];
258
+ // ① 负对照的还原核对失败:改动可能没被完整写回工作区。
259
+ // 这不是「审查意见」而是「环境事实」,优先级最高 —— 放在最前面,
260
+ // 因为它意味着「你以为的改动后状态」可能已经不成立。
261
+ const lf = state.last_falsify;
262
+ if (lf && typeof lf === "object" && lf.restore && lf.restore.ok === false) {
263
+ out.push({
264
+ axis: "falsify",
265
+ finding: "负对照后工作区还原未通过核对:" + (lf.restore.mismatched || []).join(", "),
266
+ });
267
+ }
268
+ // ② 两轴里的 WARN(坏味道等 judgement call)
269
+ const ax = state.audit_axes;
270
+ if (!ax || typeof ax !== "object") return out;
170
271
  for (const name of ["standards", "spec"]) {
171
272
  const a = ax[name];
172
273
  if (!a || !a.verdict) continue;
@@ -239,7 +340,11 @@ const TOOLS = [
239
340
  try {
240
341
  const a = args || {};
241
342
  const sessionId = a.sessionId || "unknown";
242
- const cwd = a.cwd || process.cwd();
343
+ // scope 校验基准 = git 仓库根(与 git diff 同基准);
344
+ // verify 执行目录 = 调用方显式给的目录,没给才用仓库根。
345
+ const cwdInput = a.cwd || process.cwd();
346
+ const scopeRoot = resolveRepoRoot(cwdInput);
347
+ const execDir = a.cwd || scopeRoot;
243
348
 
244
349
  let card = null;
245
350
  if (typeof a.cardText === "string" && a.cardText.trim() !== "") {
@@ -273,7 +378,7 @@ const TOOLS = [
273
378
 
274
379
  const options = {
275
380
  userMessages: messages,
276
- scopeExists: (p) => pathExists(cwd, p),
381
+ scopeExists: (p) => pathExists(scopeRoot, p),
277
382
  // 走 cardText 提交的卡片,其自身的 confirmed 字段同样必须生效,否则敏感路径永远无法通过
278
383
  confirmed: (a.confirmed === true) || card.confirmed === true,
279
384
  };
@@ -289,7 +394,7 @@ const TOOLS = [
289
394
  return ok({ ok: false, reason, findings, tier });
290
395
  }
291
396
 
292
- card.env = { git_head: gitHead(cwd), project: cwd };
397
+ card.env = { git_head: gitHead(execDir), project: execDir };
293
398
 
294
399
  // ---- 闸门待补项:服务端从当前卡片内容**幂等派生** ----
295
400
  // 内容判定:与 validateCard 的必填字段口径**严格一致**(两边都要求
@@ -522,9 +627,9 @@ const TOOLS = [
522
627
  // 必须先 flow_claim 领取派发名额(claimed 标记由 claim 设置)
523
628
  if (state.claimed !== true) return fail(guideError(state, "未 claim,请先 flow_claim 领取派发名额。"));
524
629
 
525
- const cwd = a.cwd || process.cwd();
526
-
527
- // Phase 1-1: dispatch 时才增加 dispatch_count(claim 不计数)
630
+ // 派发基准同样必须对齐 git 仓库根:scope 是仓库根相对路径,
631
+ // snapshot / baseline / 裁定三处要用同一个基准,否则越界判定会自相矛盾。
632
+ const cwd = resolveRepoRoot(a.cwd || process.cwd());
528
633
  state.dispatch_count = (Number(state.dispatch_count) || 0) + 1;
529
634
  // 额度已消耗,需要重新 claim 才能再次派发
530
635
  state.claimed = false;
@@ -544,15 +649,7 @@ const TOOLS = [
544
649
  audit("run", sessionId, { kind: "snapshot", role, files: scope.length, ok: true });
545
650
 
546
651
  // Phase 1-1: 记录「派发前基线」。
547
- //
548
- // 为什么是记录而不是当场阻断:
549
- // 派发这一刻,子 Agent **还没动手** —— 它之后会改哪些文件根本无从得知。
550
- // 此时跑 git diff 得到的是「用户自己已有的未提交改动」,
551
- // 拿它当越界拦下来会**误伤正常用法**(用户本来就在改这些文件)。
552
- //
553
- // 正确的时机是**裁定前**:用「当前改动 - 派发基线」算出**本次执行引入的**
554
- // 改动,再与卡片 scope 比对 —— 这才是「越界直接阻断」的真实落点,
555
- // 阻断的是「越界之后仍然拿到 PASS」这个闭环。
652
+ // 使用与后续校验一致的 cwd,修正基准
556
653
  const baseline = enforceScope(scope, cwd);
557
654
  state.dispatch_baseline = Array.isArray(baseline.checked) ? baseline.checked : [];
558
655
  saveState(sessionId, state);
@@ -712,11 +809,17 @@ const TOOLS = [
712
809
  const sessionId = a.sessionId || "unknown";
713
810
  const state = loadState(sessionId);
714
811
 
812
+ // 裁定闸门的分组与顺序与 docs/TOOL_CONTRACTS.md 第 1.2 节严格一致:
813
+ // 【无条件 2 组】1 有卡 · 2 占位卡已补齐
814
+ // 【仅 PASS 7 组】3 派发过 · 4 验证有效 · 5 验证未过期 · 6 无越界
815
+ // · 7 role=auditor · 8 负对照 · 9 双轴齐且无 FAIL
816
+ // 顺序不可调换:先证实验证有效(4/5)→ 再证改动合规(6/7)→ 再证测试有判别力(8)
817
+ // → 再证审查到位(9)。错位会让「未验证」被「双轴未齐」掩盖,调用方拿到不可操作的下一步。
715
818
  if (!state.card) return fail(guideError(state, "没有留痕,无法记录裁定。"));
716
819
 
717
820
  const verdict = a.verdict;
718
821
 
719
- // 激活占位卡尚未补齐时不允许裁定:
822
+ // ── 门禁 2/9(无条件):激活占位卡必须已补齐 ──
720
823
  // 否则会出现「未派发、未验证、却直接 PASS」的假闭环。
721
824
  // (先于 dispatch_count 检查:占位卡的错误信息更具体,也更可操作)
722
825
  if (Array.isArray(state.activation_pending) && state.activation_pending.length > 0) {
@@ -729,7 +832,8 @@ const TOOLS = [
729
832
  "),不能记录裁定。请先补齐后重新调用 flow_submit_requirement。"));
730
833
  }
731
834
 
732
- // 防假闭环之二:从未派发过任何执行,就不允许落 PASS 裁定。
835
+ // ── 门禁 3/9(仅 PASS):确实派发过 ──
836
+ // 从未派发过任何执行,就不允许落 PASS 裁定。
733
837
  // 否则一张刚提交、什么都没跑的卡也能直接标 completed_ok=true。
734
838
  // 只施加于 PASS:DIRECTION / LOCAL 是「有问题」的裁定,不构成「完成」,
735
839
  // 允许在未派发时先记录返工意见。
@@ -743,7 +847,8 @@ const TOOLS = [
743
847
  "请先 flow_claim / flow_dispatch 派发并完成验证后再落 PASS。"));
744
848
  }
745
849
 
746
- // 防假闭环之三:记 PASS 必须有**真实验证通过**的证据。
850
+ // ── 门禁 4/9(仅 PASS):验证真实有效 ──
851
+ // 记 PASS 必须有**真实验证通过**的证据。
747
852
  // 「派发过」≠「验证过」——只查 dispatch_count 时,一张跑过但验证失败的卡
748
853
  // 照样能落 PASS(completed_ok=true),等于把验证环节架空。
749
854
  // 三个条件同时成立才放行:
@@ -780,8 +885,8 @@ const TOOLS = [
780
885
  exitCode: lv.exitCode,
781
886
  verify_cmd: lv.cmd,
782
887
  });
783
- return fail("验证未通过(exitCode=" + lv.exitCode + "),不能记录 PASS 裁定。" +
784
- "请先修复问题、让 verify.cmd 真实跑通(flow_run_verify),再记录裁定。");
888
+ return fail(formatError("验证未通过(exitCode=" + lv.exitCode + "),不能记录 PASS 裁定。" +
889
+ "请先修复问题、让 verify.cmd 真实跑通(flow_run_verify),再记录裁定。"));
785
890
  }
786
891
  if (!want || typeof lv.cmd !== "string" || lv.cmd.trim() !== want) {
787
892
  audit("decision", sessionId, {
@@ -790,11 +895,12 @@ const TOOLS = [
790
895
  verify_cmd: lv.cmd,
791
896
  card_cmd: want,
792
897
  });
793
- return fail("已有的验证结果对应的命令与当前卡片的 verify.cmd 不一致,不能记录 PASS 裁定。" +
794
- "请对当前卡片重新执行 flow_run_verify,再记录裁定。");
898
+ return fail(formatError("已有的验证结果对应的命令与当前卡片的 verify.cmd 不一致,不能记录 PASS 裁定。" +
899
+ "请对当前卡片重新执行 flow_run_verify,再记录裁定。"));
795
900
  }
796
901
 
797
- // 防假闭环之五:验证结果必须绑定当时的**代码状态**(A1)。
902
+ // ── 门禁 5/9(仅 PASS):验证结果未过期 ──
903
+ // 验证结果必须绑定当时的**代码状态**(A1)。
798
904
  //
799
905
  // 前面三道判断只看「验证跑过 / 跑通了 / 命令对得上」,**不看代码变没变**。
800
906
  // 于是存在这条绕过路径:
@@ -815,11 +921,12 @@ const TOOLS = [
815
921
  fp_was: fpWas.diff_sha256,
816
922
  fp_now: fpNow.diff_sha256,
817
923
  });
818
- return fail("验证结果已过期(STALE):验证通过后代码又被修改,当前 diff 指纹已变化。" +
819
- "请重新执行 flow_run_verify 再记录裁定。");
924
+ return fail(formatError("验证结果已过期(STALE):验证通过后代码又被修改,当前 diff 指纹已变化。" +
925
+ "请重新执行 flow_run_verify 再记录裁定。"));
820
926
  }
821
927
 
822
- // 防假闭环之四:越界改动必须被拦住。
928
+ // ── 门禁 6/9(仅 PASS):无越界改动 ──
929
+ // 越界改动必须被拦住。
823
930
  //
824
931
  // 「越界直接阻断」的**真实落点**在这里:判定「本次执行有没有改到
825
932
  // scope 之外的文件」,而不是「派发前工作区干不干净」。
@@ -831,11 +938,12 @@ const TOOLS = [
831
938
  // 无基线(未走过 flow_dispatch)时退化为「全量改动」判定:
832
939
  // 此时没有参照点,用全量更保守(fail-closed)。
833
940
  const scopeNow = Array.isArray(state.card.scope) ? state.card.scope : [];
834
- const current = enforceScope(scopeNow, a.cwd || process.cwd());
941
+ const scopeRootNow = resolveRepoRoot(a.cwd || process.cwd());
942
+ const current = enforceScope(scopeNow, scopeRootNow);
835
943
  const baseline = Array.isArray(state.dispatch_baseline) ? state.dispatch_baseline : [];
836
944
  const baselineSet = new Set(baseline.map((f) => path.normalize(f)));
837
945
  const introduced = (current.checked || []).filter((f) => !baselineSet.has(path.normalize(f)));
838
- const scopeCheck = enforceScope(scopeNow, a.cwd || process.cwd(), introduced);
946
+ const scopeCheck = enforceScope(scopeNow, scopeRootNow, introduced);
839
947
  if (!scopeCheck.ok) {
840
948
  audit("decision", sessionId, {
841
949
  kind: "scope_violation",
@@ -843,19 +951,21 @@ const TOOLS = [
843
951
  violations: scopeCheck.violations,
844
952
  introduced: introduced.length,
845
953
  });
846
- return fail("检测到越界改动,不能记录 PASS 裁定:" +
954
+ return fail(formatError("检测到越界改动,不能记录 PASS 裁定:" +
847
955
  (scopeCheck.violations || []).join(", ") +
848
956
  "。这些文件不在卡片 scope 白名单内。" +
849
- "请把越界文件加入 scope(重新提交任务卡)后重试,或先撤销这些改动。");
957
+ "请把越界文件加入 scope(重新提交任务卡)后重试,或先撤销这些改动。"));
850
958
  }
851
959
 
852
- // 防假闭环之四:role 门禁绑定到会话 ID(claimed_role),而非调用方自述字符串
960
+ // ── 门禁 7/9(仅 PASS):裁定角色必须是 auditor ──
961
+ // role 门禁绑定到会话 ID(claimed_role),而非调用方自述字符串
853
962
  if (verdict === "PASS" && state.claimed_role !== "auditor") {
854
963
  audit("decision", sessionId, { kind: "verdict_denied", reason: "role 未绑定到 auditor 会话", claimed_role: state.claimed_role });
855
964
  return fail("PASS 裁定必须由已领取 auditor 角色的会话(flow_claim role=auditor)落下。当前会话 claimed_role=" + (state.claimed_role || "null"));
856
965
  }
857
966
 
858
- // 防假闭环之五:负对照 —— 证明 verify.cmd 真的在测「本次改动」。
967
+ // ── 门禁 8/9(仅 PASS):负对照证明测试有判别力 ──
968
+ // 证明 verify.cmd 真的在测「本次改动」。
859
969
  //
860
970
  // 「验证通过」本身不是证据:verify.cmd 可以是 `|| true` / `echo ok`,
861
971
  // 改动前后都退 0,门禁却以为测试过了。负对照要求:
@@ -870,8 +980,8 @@ const TOOLS = [
870
980
  }
871
981
  if (lf.verdict !== "meaningful") {
872
982
  audit("decision", sessionId, { kind: "verdict_denied", reason: "负对照未通过", falsify_verdict: lf.verdict });
873
- return fail("负对照未通过(" + lf.verdict + "):" + (lf.reason || "") +
874
- " 不能记录 PASS 裁定。请修正 verify.cmd 或改动后重试。");
983
+ return fail(formatError("负对照未通过(" + lf.verdict + "):" + (lf.reason || "") +
984
+ " 不能记录 PASS 裁定。请修正 verify.cmd 或改动后重试。"));
875
985
  }
876
986
  // 绑定:裁定的证据必须就是负对照里「改动后」的那次运行。
877
987
  if (typeof lf.after === "object" && lf.after && typeof lf.after.hash === "string" &&
@@ -881,10 +991,11 @@ const TOOLS = [
881
991
  "请重新调用 flow_falsify(它会把改动后的运行写为验证证据)。");
882
992
  }
883
993
 
884
- // 防假闭环之六:双轴审查门禁。
994
+ // ── 门禁 9/9(仅 PASS):双轴审查齐且无 FAIL ──
885
995
  //
886
996
  // 位置说明(重要):必须放在负对照**之后**。语义顺序是
887
- // 「先证实验证有效 → 再证审查到位」,六道门各自独立、互不掩盖。
997
+ // 「先证实验证有效 → 再证审查到位」,九道门(2 无条件 + 7 仅 PASS)
998
+ // 各自独立、互不掩盖。
888
999
  // 若前置,会让「未验证」「未派发」「未做负对照」这些更基础的问题被
889
1000
  // 双轴错误信息掩盖,调用方拿到的是不可操作的下一步。
890
1001
  //
@@ -1101,7 +1212,7 @@ const TOOLS = [
1101
1212
  handler: async (args) => {
1102
1213
  try {
1103
1214
  const a = args || {};
1104
- const cwd = a.cwd || process.cwd();
1215
+ const cwd = resolveRepoRoot(a.cwd || process.cwd());
1105
1216
  const paths = asStringArray(a.paths);
1106
1217
 
1107
1218
  const proc = spawnSync("git", ["diff", "-U0", "--no-color", ...paths], {
@@ -1394,6 +1505,9 @@ const TOOLS = [
1394
1505
  reason: r.reason,
1395
1506
  before: { exitCode: r.before.exitCode, ok: r.before.ok, hash: r.before.hash },
1396
1507
  after: { exitCode: r.after.exitCode, ok: r.after.ok, hash: r.after.hash },
1508
+ // 工作区还原是否被核对通过(ok=false 表示负对照过程中改动可能没被完整写回)。
1509
+ // 不参与 PASS 判定,但会随裁定一起暴露 —— 免得「改动消失」只留在 stderr 里。
1510
+ restore: r.restore ? { ok: r.restore.ok, checked: r.restore.checked, mismatched: r.restore.mismatched } : null,
1397
1511
  };
1398
1512
  // 把「改动后」的运行写为 last_verify —— 裁定的证据绑定到这一次运行。
1399
1513
  state2.last_verify = {
@@ -1417,6 +1531,9 @@ const TOOLS = [
1417
1531
  after_exit: r.after.exitCode,
1418
1532
  before_hash: r.before.hash,
1419
1533
  after_hash: r.after.hash,
1534
+ restore_ok: r.restore ? r.restore.ok : null,
1535
+ restore_mismatched: r.restore ? r.restore.mismatched : [],
1536
+ recovered_files: r.recovered ? r.recovered.files : 0,
1420
1537
  });
1421
1538
 
1422
1539
  const trunc = (s) => (typeof s === "string" && s.length > 2000 ? s.slice(0, 2000) + "…" : s);
@@ -1426,9 +1543,17 @@ const TOOLS = [
1426
1543
  reason: r.reason,
1427
1544
  before: { exitCode: r.before.exitCode, ok: r.before.ok, hash: r.before.hash, stdout: trunc(r.before.stdout), stderr: trunc(r.before.stderr) },
1428
1545
  after: { exitCode: r.after.exitCode, ok: r.after.ok, hash: r.after.hash, stdout: trunc(r.after.stdout), stderr: trunc(r.after.stderr) },
1429
- note: r.verdict === "meaningful"
1546
+ // 工作区还原的核对结果(失败时备份已保留,下次调用会先尝试恢复)
1547
+ restore: r.restore || null,
1548
+ // 本次调用开始时恢复掉的「上一次被中断的负对照」残留
1549
+ recovered: r.recovered || null,
1550
+ note: (r.verdict === "meaningful"
1430
1551
  ? "负对照通过:测试有判别力,可以记 PASS。"
1431
- : "负对照未通过:不能记 PASS。" + r.reason,
1552
+ : "负对照未通过:不能记 PASS。" + r.reason) +
1553
+ (r.restore && r.restore.ok === false
1554
+ ? " ⚠️ 但工作区还原未通过核对,以下文件与进入负对照前不一致:" +
1555
+ (r.restore.mismatched || []).join(", ") + "(备份已保留,请人工确认后修复)"
1556
+ : ""),
1432
1557
  });
1433
1558
  } catch (e) {
1434
1559
  return fail(e && e.message ? e.message : String(e));
@@ -1460,9 +1585,11 @@ const TOOLS = [
1460
1585
  const paths = Array.isArray(a.paths) ? a.paths : [];
1461
1586
  // 不传 paths → 自动跑 `git diff --name-only` 取当前实际改动清单。
1462
1587
  // 传了 paths → 用调用方给的清单(自查场景)。
1588
+ // 自查同样按仓库根基准,否则「自查没越界、裁定却报越界」会自相矛盾
1589
+ const scopeRoot = resolveRepoRoot(a.cwd || process.cwd());
1463
1590
  const result = paths.length
1464
- ? enforceScope(scope, a.cwd, paths)
1465
- : enforceScope(scope, a.cwd);
1591
+ ? enforceScope(scope, scopeRoot, paths)
1592
+ : enforceScope(scope, scopeRoot);
1466
1593
 
1467
1594
  return ok({ ok: result.ok, scope, checked: paths.length ? paths : result.checked || [], ...result });
1468
1595
  } catch (e) {
@@ -1694,23 +1821,18 @@ const pkgVersion = (() => {
1694
1821
  }
1695
1822
  })();
1696
1823
 
1697
- const server = new Server(
1698
- { name: "carlos-flow", version: pkgVersion },
1699
- { capabilities: { tools: {} } },
1700
- );
1701
-
1702
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
1703
- tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
1824
+ // 对外工具清单(tools/list 的载荷):**绝不能**把 handler 带出去 ——
1825
+ // 它是函数,序列化后会变成 undefined 或被宿主拒收。
1826
+ const TOOL_SCHEMAS = TOOLS.map((t) => ({
1827
+ name: t.name,
1828
+ description: t.description,
1829
+ inputSchema: t.inputSchema,
1704
1830
  }));
1705
1831
 
1706
- // ⚠️ 这里曾经**重复注册**过一次 CallToolRequestSchema(另一个不带参数校验的版本)。
1707
- // MCP SDK 的 setRequestHandler 用 Map.set → 后注册的覆盖先注册的,
1708
- // 于是先注册的那个(含约 17 行)**永远不会执行** —— 当前行为是对的,
1709
- // 但它靠的是「注册顺序」这种隐式约定:任何一次重排或插入都会静默
1710
- // 丢掉参数校验(required 字段 / 类型 / enum 全部失效)。
1711
- // 现在只保留下面那一个带 validateToolArgs 的注册。
1712
- //
1713
- // check:no-dead-handler 门禁会统计同一 schema 的注册次数,>1 即红。
1832
+ // ⚠️ 历史坑(必须守住):这里曾经**重复装配**过一个不带参数校验的 handler,
1833
+ // 后装配的覆盖先装配的 → 参数校验(required / 类型 / enum)静默失效。
1834
+ // 现在只有 `callTool` 一条通路,且它**必须先过 validateToolArgs**。
1835
+ // check:no-dead-handler 门禁守着「按 name 分发 + 真的调用了参数校验」这两点。
1714
1836
 
1715
1837
  // ---- Phase 1-1: 工具参数校验器(required 字段 / 类型 / enum)----
1716
1838
  function validateToolArgs(toolName, args) {
@@ -1778,10 +1900,7 @@ function validateToolArgs(toolName, args) {
1778
1900
  }
1779
1901
 
1780
1902
  // ---- CallTool:先校验参数,再分发到工具 handler ----
1781
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
1782
- const toolName = request.params.name;
1783
- const args = request.params.arguments || {};
1784
-
1903
+ async function callTool(toolName, args) {
1785
1904
  const t = TOOLS.find((x) => x.name === toolName);
1786
1905
  if (!t) {
1787
1906
  return { content: [{ type: "text", text: "Unknown tool: " + toolName }], isError: true };
@@ -1792,17 +1911,32 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1792
1911
  return { content: [{ type: "text", text: "ERROR: " + validation.error }], isError: true };
1793
1912
  }
1794
1913
 
1914
+ // 项目级敏感路径扩展:从 cwd 逐级向上找 `.carlos.json`(只追加,不能缩减)。
1915
+ // 放在这里统一加载,保证同一请求里所有路径判定用同一份规则;
1916
+ // 配置缺失 / 损坏时自动退回内置基线,不影响门禁。
1917
+ try {
1918
+ loadProjectSensitiveConfig(typeof args.cwd === "string" && args.cwd ? args.cwd : process.cwd());
1919
+ } catch { /* 配置不可读:保持内置基线 */ }
1920
+
1795
1921
  try {
1796
1922
  return await t.handler(args);
1797
1923
  } catch (e) {
1924
+ const err = e && e.message ? e.message : String(e);
1798
1925
  return {
1799
- content: [{ type: "text", text: "ERROR: " + (e && e.message ? e.message : String(e)) }],
1926
+ content: [{ type: "text", text: "ERROR: " + formatError(err) }],
1800
1927
  isError: true,
1801
1928
  };
1802
1929
  }
1803
- });
1930
+ }
1804
1931
 
1805
- // ---- 传输模式:stdio(单次调用,兼容旧用法) ----
1806
- const transport = new StdioServerTransport();
1807
- await server.connect(transport);
1808
- process.stderr.write("carlos-flow MCP server connected via stdio\n");
1932
+ // ---- 传输模式:stdio(逐行 JSON-RPC 2.0) ----
1933
+ // 启动日志必须在 await 之前写:serveStdio 会一直阻塞到 stdin 关闭(宿主退出),
1934
+ // 写在后面等于「只在退出时打印」,排查时看不到任何启动痕迹。
1935
+ process.stderr.write("carlos-flow MCP server ready (stdio)\n");
1936
+ await serveStdio({
1937
+ name: "carlos-flow",
1938
+ version: pkgVersion,
1939
+ tools: TOOL_SCHEMAS,
1940
+ callTool,
1941
+ log,
1942
+ });
@@ -0,0 +1,139 @@
1
+ // 最小 MCP stdio 服务端(零依赖)
2
+ //
3
+ // 为什么自己写而不继续用 @modelcontextprotocol/sdk:
4
+ // Cindy 插件(chip)要求随包 Node 程序**自带全部依赖** —— Forge 打包时会跳过
5
+ // node_modules,也禁止安装期/首跑期联网装依赖。SDK 一旦成为运行时依赖,
6
+ // 这个插件就不可能以 .cindy 形态装进 Cindy(只能靠绝对路径跑仓库里的副本)。
7
+ //
8
+ // 本实现只覆盖本插件真正用到的 MCP 子集:
9
+ // 握手(initialize)、初始化通知、心跳(ping)、工具目录与工具调用,
10
+ // 外加 resources/prompts 的空列表应答(宿主做能力探测时会问)。
11
+ // 传输形态:逐行 JSON-RPC 2.0(MCP stdio 规范),stdout 只写协议消息,日志走 stderr。
12
+ import readline from "node:readline";
13
+
14
+ // 声明的协议版本:客户端请求里的版本若在支持列表内就回声,否则回最新的。
15
+ const SUPPORTED_PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
16
+ const LATEST_PROTOCOL = SUPPORTED_PROTOCOLS[0];
17
+
18
+ export class StdioServer {
19
+ constructor({ name, version, tools, callTool, log }) {
20
+ this.name = name;
21
+ this.version = version;
22
+ this.tools = tools;
23
+ this.callTool = callTool;
24
+ this.log = typeof log === "function" ? log : () => {};
25
+ this.initialized = false;
26
+ this.pending = new Set();
27
+ }
28
+
29
+ reply(id, result) {
30
+ if (id === undefined || id === null) return;
31
+ this.write({ jsonrpc: "2.0", id, result });
32
+ }
33
+
34
+ replyError(id, code, message) {
35
+ if (id === undefined || id === null) return;
36
+ this.write({ jsonrpc: "2.0", id, error: { code, message } });
37
+ }
38
+
39
+ write(message) {
40
+ try {
41
+ process.stdout.write(JSON.stringify(message) + "\n");
42
+ } catch (e) {
43
+ // 客户端已断开(EPIPE):不再尝试写,避免把进程搞崩
44
+ try {
45
+ this.log("stdout 写入失败:" + (e && e.message ? e.message : e));
46
+ } catch { /* ignore */ }
47
+ }
48
+ }
49
+
50
+ async handle(message) {
51
+ const method = message && message.method;
52
+ const id = message && message.id;
53
+ if (typeof method !== "string") return; // 客户端回来的响应(本服务端不发反向请求):忽略
54
+
55
+ switch (method) {
56
+ case "initialize": {
57
+ const asked = message.params && message.params.protocolVersion;
58
+ const protocolVersion = SUPPORTED_PROTOCOLS.includes(asked) ? asked : LATEST_PROTOCOL;
59
+ this.initialized = true;
60
+ this.reply(id, {
61
+ protocolVersion,
62
+ capabilities: { tools: { listChanged: false } },
63
+ serverInfo: { name: this.name, version: this.version },
64
+ });
65
+ return;
66
+ }
67
+ case "notifications/initialized":
68
+ case "notifications/cancelled":
69
+ // 规范里这两个是**通知**(没有 id),我们不回复。
70
+ // 但实测有客户端(包括本仓库自带的测试脚本)会带 id 发通知 ——
71
+ // 那时若不回包,调用方就会**永久挂起**(比报错更难查)。
72
+ // 因此:带 id 的「通知」按空结果应答,无 id 的照旧静默。
73
+ this.reply(id, {});
74
+ return;
75
+ case "ping":
76
+ this.reply(id, {});
77
+ return;
78
+ case "tools/list":
79
+ this.reply(id, { tools: this.tools });
80
+ return;
81
+ case "resources/list":
82
+ this.reply(id, { resources: [] });
83
+ return;
84
+ case "prompts/list":
85
+ this.reply(id, { prompts: [] });
86
+ return;
87
+ case "tools/call": {
88
+ const params = message.params || {};
89
+ const name = params.name;
90
+ const args = params.arguments === undefined || params.arguments === null ? {} : params.arguments;
91
+ let result;
92
+ try {
93
+ result = await this.callTool(name, args);
94
+ } catch (e) {
95
+ // 工具内部抛错 → 按 MCP 约定以「工具结果 + isError」返回,
96
+ // 而不是 JSON-RPC 协议错误(后者会让宿主把整个会话当故障)。
97
+ result = {
98
+ content: [{ type: "text", text: "ERROR: " + (e && e.message ? e.message : String(e)) }],
99
+ isError: true,
100
+ };
101
+ }
102
+ this.reply(id, result);
103
+ return;
104
+ }
105
+ default:
106
+ // 带 id 的未知方法必须回错(否则客户端会一直等);
107
+ // 不带 id 的是通知,静默忽略。
108
+ this.replyError(id, -32601, "Method not found: " + method);
109
+ }
110
+ }
111
+
112
+ async start() {
113
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
114
+ for await (const line of rl) {
115
+ const text = line.trim();
116
+ if (!text) continue;
117
+ let message = null;
118
+ try {
119
+ message = JSON.parse(text);
120
+ } catch {
121
+ // 非法 JSON:没有 id 可回,记 stderr 后继续(不要因一条脏行整进程退出)
122
+ this.log("收到无法解析的 JSON-RPC 行,已忽略");
123
+ continue;
124
+ }
125
+ // 不串行等待:flow_run_verify 这类调用可能跑上百秒,
126
+ // 期间其它请求(如 ping)必须还能得到响应。
127
+ const p = this.handle(message)
128
+ .catch((e) => this.log("处理消息失败:" + (e && e.message ? e.message : e)))
129
+ .finally(() => this.pending.delete(p));
130
+ this.pending.add(p);
131
+ }
132
+ // stdin 关闭(宿主退出):等手上的请求收尾再返回
133
+ await Promise.allSettled([...this.pending]);
134
+ }
135
+ }
136
+
137
+ export function serveStdio(options) {
138
+ return new StdioServer(options).start();
139
+ }