feat(#11): CLI/MCP 薄殼對齊 — P0 run 死端點修 + P1 list 同源 + R4 防複發機制

P0 CLI run 改打 /webhooks/named/:name/trigger 真端點(原打 /webhooks/<name> 死端點 404)。
P1 CLI/MCP list 收斂到 GET /webhooks/named(KV 同源):
   - CLI list 停 CfKvClient 直連 KV,順手修 key 前綴 bug(原讀 workflow: 對不上部署的 {apiKey}:wf:)
     + self-hosted 不再需 CF API token。
   - MCP u6u_list_workflows 從讀 KBDB record 改讀 GET /webhooks/named(registry 簽名加 partnerToken)。
R4 防複發機制:
   - cli-mcp-capability-matrix.md(13 能力對照,docs/ gitignored 不進此 commit,僅本機)
   - thin-shell-smoke.sh(對真端點斷言非 404,本機手動跑非 CI/cron)
   - 機制自驗:注入故意死端點當場攔下、exit 1。

依賴關係:本批依賴 #8(webhooks-named GET 補 description/created_at 欄位、search/backfill 端點),
故疊在 feat/issue-8 branch 上、作獨立 commit。

⚠️ tsc 綠 = code done 非完成。端到端待 leo21c(CLI/MCP 真打通 200 非 404、smoke 對已部署 prod
全綠——目前 smoke 揭 #8 search/backfill 在 prod 仍 404=未部署)。P2 validate 收斂待 #10、
tag resource_id 語意債待方向①。#11 留 open。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
uncle6me-web
2026-06-27 19:36:58 +08:00
parent 558e80b4da
commit 5d38b599fd
5 changed files with 161 additions and 55 deletions
+26 -42
View File
@@ -1,68 +1,52 @@
/** /**
* acr list — 列出 USER_KV 中所有已上傳的 workflow * acr list — 列出已部署的 workflow
*
* thin-shell-alignment P1issue #11):原本直連 CF KV 讀 `workflow:` 前綴(CfKvClient),
* 有兩個漂移:① 前綴對不上(部署寫 `{apiKey}:wf:` → 永遠列不到新部署)② 薄殼直碰底層儲存
* self-hosted 用戶需 CF API token 才能 list)。改走 cypher `GET /webhooks/named`KV 源,與
* MCP u6u_list_workflows 同源),薄殼不再直連 KV、key 前綴 bug 自然消失。
*/ */
import chalk from 'chalk'; import chalk from 'chalk';
import ora from 'ora'; import ora from 'ora';
import { loadConfig } from '../lib/config.js'; import { loadConfig, getCypherExecutorUrl } from '../lib/config.js';
import { CfKvClient } from '../lib/cf-api.js';
export async function cmdList(): Promise<void> { export async function cmdList(): Promise<void> {
const config = loadConfig(); const config = loadConfig();
const executorUrl = getCypherExecutorUrl(config);
if (!config.cloudflare_account_id || !config.cf_api_token) { const headers: Record<string, string> = { 'Content-Type': 'application/json' };
console.error(chalk.red('缺少 Cloudflare 設定,請執行 acr init')); if (config.api_key) headers['X-Arcrun-API-Key'] = config.api_key;
process.exit(1);
}
const namespaceId = config.mode === 'standard'
? config.user_kv_namespace_id!
: config.webhooks_kv_namespace_id!;
if (!namespaceId) {
console.error(chalk.red('缺少 KV Namespace ID,請執行 acr init'));
process.exit(1);
}
const kv = new CfKvClient({
accountId: config.cloudflare_account_id,
namespaceId,
apiToken: config.cf_api_token,
});
const spinner = ora('讀取 workflow 清單').start(); const spinner = ora('讀取 workflow 清單').start();
try { try {
const keys = await kv.list('workflow:'); const res = await fetch(`${executorUrl}/webhooks/named`, { method: 'GET', headers });
if (!res.ok) {
spinner.fail(chalk.red(`讀取失敗(HTTP ${res.status}):${(await res.text()).slice(0, 200)}`));
process.exit(1);
}
const data = await res.json() as {
workflows: Array<{ name: string; description?: string; created_at?: string }>;
};
spinner.stop(); spinner.stop();
if (keys.length === 0) { const workflows = data.workflows ?? [];
if (workflows.length === 0) {
console.log(chalk.yellow('\n 沒有已部署的 workflow。執行 acr push <workflow.yaml> 部署第一個。\n')); console.log(chalk.yellow('\n 沒有已部署的 workflow。執行 acr push <workflow.yaml> 部署第一個。\n'));
return; return;
} }
console.log(chalk.bold(`\n 已部署 ${keys.length} 個 workflow\n`)); console.log(chalk.bold(`\n 已部署 ${workflows.length} 個 workflow\n`));
for (const key of keys) { for (const wf of workflows) {
const name = key.name.replace('workflow:', ''); const date = wf.created_at ? new Date(wf.created_at).toLocaleString('zh-TW') : '未知';
// 嘗試讀取 workflow 定義取得 created_at const desc = wf.description ? chalk.gray(`${wf.description}`) : '';
try { console.log(`${chalk.cyan(wf.name.padEnd(25))} ${date}${desc}`);
const raw = await kv.get(key.name);
if (raw) {
const def = JSON.parse(raw) as { name: string; description?: string; created_at?: string };
const date = def.created_at ? new Date(def.created_at).toLocaleString('zh-TW') : '未知';
const desc = def.description ? chalk.gray(`${def.description}`) : '';
console.log(`${chalk.cyan(name.padEnd(25))} ${date}${desc}`);
} else {
console.log(`${chalk.cyan(name)}`);
}
} catch {
console.log(`${chalk.cyan(name)}`);
}
} }
console.log(''); console.log('');
} catch (e) { } catch (e) {
spinner.fail(chalk.red(`KV 讀取失敗:${e instanceof Error ? e.message : e}`)); spinner.fail(chalk.red(`讀取失敗:${e instanceof Error ? e.message : e}`));
process.exit(1); process.exit(1);
} }
} }
+3 -1
View File
@@ -97,9 +97,11 @@ export async function cmdRun(workflowName: string, options: RunOptions): Promise
} }
// ── 玩法二:本機沒這個 YAML → 按名字打已 push 到 KV 的 workflow ─────────────── // ── 玩法二:本機沒這個 YAML → 按名字打已 push 到 KV 的 workflow ───────────────
// thin-shell-alignment P0issue #11):原打 /webhooks/${name} 是死端點(404)。
// 真端點是 /webhooks/named/:name/triggerwebhooks-named.ts:279X-Arcrun-API-Key header)。
const spinner = ora(`執行 workflow "${workflowName}"`).start(); const spinner = ora(`執行 workflow "${workflowName}"`).start();
try { try {
const res = await fetch(`${executorUrl}/webhooks/${workflowName}`, { const res = await fetch(`${executorUrl}/webhooks/named/${workflowName}/trigger`, {
method: 'POST', method: 'POST',
headers, headers,
body: JSON.stringify(inputContext), body: JSON.stringify(inputContext),
+1 -1
View File
@@ -29,7 +29,7 @@ export function registerAllTools(server: McpServer, env: Env, orgNamespace: stri
registerExecuteWorkflow(server, env, orgNamespace, partnerToken); registerExecuteWorkflow(server, env, orgNamespace, partnerToken);
registerDeployWorkflow(server, env, orgNamespace); registerDeployWorkflow(server, env, orgNamespace);
registerPublishComponent(server, env, orgNamespace); registerPublishComponent(server, env, orgNamespace);
registerListWorkflows(server, env, orgNamespace); registerListWorkflows(server, env, orgNamespace, partnerToken); // thin-shell-alignment P1: list 改讀 /webhooks/named
registerGetWorkflow(server, env, orgNamespace); registerGetWorkflow(server, env, orgNamespace);
registerSearchWorkflows(server, env, orgNamespace, partnerToken); // workflow-discovery R2 registerSearchWorkflows(server, env, orgNamespace, partnerToken); // workflow-discovery R2
registerListComponents(server, env, orgNamespace); registerListComponents(server, env, orgNamespace);
+34 -11
View File
@@ -3,33 +3,56 @@ import { z } from "zod";
import { Env } from "../types.js"; import { Env } from "../types.js";
import { kbdbFetch } from "../lib/kbdb-client.js"; import { kbdbFetch } from "../lib/kbdb-client.js";
export function registerListWorkflows(server: McpServer, env: Env, orgNamespace: string) { /**
* u6u_list_workflows — 列出本帳號已部署的工作流
*
* thin-shell-alignment P1issue #11):原讀 KBDB `/records?template=workflow_metadata`
* 與 CLI `acr list`(讀 KV)不同源 → 列出的東西不一樣。改讀 cypher `GET /webhooks/named`
* (KV 源,與 CLI 收斂同源)。job 分:list 讀 KV(部署寫入處,權威),search 讀 KBDB entry。
* tag 過濾仍走 KBDB resource_tag(另一維度,非 workflow 清單來源)。
*/
export function registerListWorkflows(server: McpServer, env: Env, orgNamespace: string, partnerToken: string) {
server.tool( server.tool(
"u6u_list_workflows", "u6u_list_workflows",
"列出當前命名空間下所有已部署的工作流,可選擇按 tag 篩選。", "列出當前命名空間下所有已部署的工作流,可選擇按 tag 篩選。",
{ tag: z.string().optional().describe("按 tag 名稱篩選(選填)") }, { tag: z.string().optional().describe("按 tag 名稱篩選(選填)") },
async ({ tag }) => { async ({ tag }) => {
try { try {
if (!env.KBDB) { if (!env.CYPHER_EXECUTOR) {
return { content: [{ type: "text", text: "Error: KBDB service binding unavailable" }], isError: true }; return { content: [{ type: "text", text: "Error: CYPHER_EXECUTOR service binding is not configured." }], isError: true };
} }
let workflowIds: string[] | null = null;
// tag 過濾(選填):先從 KBDB resource_tag 查出該 tag 下的 workflow_id 白名單。
let tagFilter: Set<string> | null = null;
if (tag) { if (tag) {
if (!env.KBDB) {
return { content: [{ type: "text", text: "Error: KBDB service binding unavailable (tag 過濾需要)" }], isError: true };
}
const tagResp = await kbdbFetch(env, `/records/search?template=resource_tag&user_id=${encodeURIComponent(orgNamespace)}&tag_name=${encodeURIComponent(tag)}&resource_type=workflow`); const tagResp = await kbdbFetch(env, `/records/search?template=resource_tag&user_id=${encodeURIComponent(orgNamespace)}&tag_name=${encodeURIComponent(tag)}&resource_type=workflow`);
if (!tagResp.ok) { if (!tagResp.ok) {
return { content: [{ type: "text", text: `Error querying tags: ${await tagResp.text()}` }], isError: true }; return { content: [{ type: "text", text: `Error querying tags: ${await tagResp.text()}` }], isError: true };
} }
const tagData = await tagResp.json<{ records: Array<{ slots: { resource_id: string } }> }>(); const tagData = await tagResp.json<{ records: Array<{ slots: { resource_id: string } }> }>();
workflowIds = tagData.records.map(r => r.slots.resource_id); tagFilter = new Set(tagData.records.map(r => r.slots.resource_id));
if (workflowIds.length === 0) return { content: [{ type: "text", text: JSON.stringify([], null, 2) }] }; if (tagFilter.size === 0) return { content: [{ type: "text", text: JSON.stringify([], null, 2) }] };
} }
const resp = await kbdbFetch(env, `/records/search?template=workflow_metadata&user_id=${encodeURIComponent(orgNamespace)}`);
// 主清單:讀 cypher GET /webhooks/namedKV 源,與 CLI acr list 同源)。
const resp = await env.CYPHER_EXECUTOR.fetch("http://cypher-executor/webhooks/named", {
method: "GET",
headers: { "X-Arcrun-API-Key": partnerToken },
});
if (!resp.ok) { if (!resp.ok) {
return { content: [{ type: "text", text: `Error querying workflows: ${await resp.text()}` }], isError: true }; return { content: [{ type: "text", text: `Error listing workflows: ${await resp.text()}` }], isError: true };
} }
const data = await resp.json<{ records: Array<{ slots: { workflow_id: string; name: string; deployed_at: string; org_namespace: string } }> }>(); const data = await resp.json<{ workflows: Array<{ name: string; description?: string; created_at?: string; webhook_url?: string }> }>();
let workflows = data.records.map(r => r.slots); let workflows = data.workflows ?? [];
if (workflowIds !== null) workflows = workflows.filter(w => workflowIds!.includes(w.workflow_id)); // tag 過濾用 name 比對(KV 源主鍵=name)。
// ⚠️ 語意債(SDD §4 記):舊 tag 的 resource_id 可能存 UUID(舊 workflow_metadata workflow_id
// 或 name,語意不明確。方向①收斂到 KV(主鍵=name)後,resource_id 應統一為 name。
// 過渡期先用 name 比對(KV 源唯一鍵);舊用 UUID tag 的會在 backfill/re-tag 後對齊。待總管確認 tag 收斂。
if (tagFilter !== null) workflows = workflows.filter(w => tagFilter!.has(w.name));
return { content: [{ type: "text", text: JSON.stringify(workflows, null, 2) }] }; return { content: [{ type: "text", text: JSON.stringify(workflows, null, 2) }] };
} catch (error) { } catch (error) {
return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true }; return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
+97
View File
@@ -0,0 +1,97 @@
#!/bin/bash
# thin-shell-smoke.sh — 薄殼防複發機制層 2thin-shell-alignment SDD / issue #11 R4
#
# 目的:讓「薄殼打了不存在的 server 端點」(死端點假綠)當場現形。
# 對 CLI/MCP 各能力對應的 cypher-executor 端點打一次,斷言 **非 404**。
# 404 = route 不存在 = 死端點 → 紅燈。其他狀態(401/400/200…)= 端點存在 → 綠。
#
# ⚠️ flag 紅線(SDD C2/R4.2):本機/手動跑,**非 CI、非 cron、非輪詢**。
# 宣稱「CLI/MCP 對齊/完成」前手動跑一次即可。對齊「執行鏈路不依賴 CI」鐵律。
#
# 用法:
# CYPHER_URL=https://cypher.arcrun.dev ./scripts/thin-shell-smoke.sh
# self-hostedCYPHER_URL=https://<你的 cypher>.workers.dev ...
# 不帶 API key 也能驗端點存在性(401 仍算「端點活著」)。帶 key 可更深驗:
# ARCRUN_API_KEY=xxx CYPHER_URL=... ./scripts/thin-shell-smoke.sh
set -o pipefail
CYPHER_URL="${CYPHER_URL:-https://cypher.arcrun.dev}"
CYPHER_URL="${CYPHER_URL%/}"
API_KEY="${ARCRUN_API_KEY:-}"
PASS=0
FAIL=0
declare -a DEAD=()
# probe METHOD PATH LABEL
# 斷言端點非 404。404 → 死端點(紅)。連線失敗 → 紅(但標明是網路非死端點)。
probe() {
method="$1"; path="$2"; label="$3"
url="${CYPHER_URL}${path}"
if [ "$method" = "POST" ]; then
if [ -n "$API_KEY" ]; then
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST -H "X-Arcrun-API-Key: ${API_KEY}" -H 'Content-Type: application/json' -d '{}' "$url" 2>/dev/null)
else
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST -H 'Content-Type: application/json' -d '{}' "$url" 2>/dev/null)
fi
else
if [ -n "$API_KEY" ]; then
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -H "X-Arcrun-API-Key: ${API_KEY}" "$url" 2>/dev/null)
else
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$url" 2>/dev/null)
fi
fi
code="${code:-000}"
if [ "$code" = "000" ]; then
echo " ⚠️ $label — 連線失敗(網路/DNS,非死端點判定):$method $path"
FAIL=$((FAIL+1))
elif [ "$code" = "404" ]; then
echo "$label — 死端點 404$method $path"
DEAD+=("$label: $method $path")
FAIL=$((FAIL+1))
else
echo "$label — 端點存在(HTTP ${code}):$method $path"
PASS=$((PASS+1))
fi
}
echo "=== thin-shell smoke:對 ${CYPHER_URL} 驗端點存在性(斷言非 404==="
echo ""
echo "── 薄殼核心能力(CLI/MCP 共用端點)──"
# 部署:CLI acr push / MCP u6u_deploy_workflow(方向①收斂後同此)
probe POST /webhooks/named "deploy(push)"
# 執行已部署:CLI acr run <name> / MCP u6u_execute_workflow#11 P0 修的)
probe POST /webhooks/named/__smoke__/trigger "run(trigger)"
# 執行本機 YAML/cypher/execute
probe POST /cypher/execute "execute"
# listCLI acr list / MCP u6u_list_workflows#11 P1 收斂的)
probe GET /webhooks/named "list"
# search workflowMCP u6u_search_workflows#8 新增)
probe GET "/workflows/search?q=smoke" "search_workflow"
# 驗證:MCP arcrun_validate_yaml
probe POST /validate "validate"
# backfill search entries#8
probe POST /workflows/backfill-search-entries "backfill"
echo ""
echo "── 其他薄殼端點 ──"
probe GET /me "whoami"
probe POST /credentials "creds_push"
probe POST /recipes "recipe"
probe GET /kbdb/templates "kbdb_templates"
probe POST /cypher/search "validate_local_graph(cypher/search)"
echo ""
echo "=== 結果:${PASS} 端點存在 / ${FAIL} 異常 ==="
if [ ${#DEAD[@]} -gt 0 ]; then
echo ""
echo "🔴 死端點(route 不存在,薄殼打了會 404):"
for d in "${DEAD[@]}"; do echo " - $d"; done
echo ""
echo "→ 修法:對照 cli-mcp-capability-matrix.md,把薄殼改打存在的 route,或補 server route。"
exit 1
fi
echo "✅ 無死端點。"