Compare commits

..

5 Commits

Author SHA1 Message Date
uncle6me-web 53b05c6d3d fix(cli): 更新完還看得到版本號——CLI 重部署不再把版本標籤(和你的設定)洗掉
leo 08-12 實撞:更新完 leo21c,Portal 設定頁的「版本」變成
「無法讀取目前版本(知識庫服務可能正在啟動)」。版本號是 leo 唯一的驗收介面,
看不到就等於他無法自己確認任何一次更新有沒有生效。

根因(Arcrun#106):`bundle_version` 來自部署時注入的 plain_text var
`ARCRUN_BUNDLE_VERSION`,而**只有安裝器會注入**。wrangler deploy 是整份覆蓋,
toml 沒寫的 var 直接消失 ⇒ CLI 更新那條路每跑一次就把標籤洗掉一次。
#97 修好了「櫃子」(KV/D1/Vectorize 沿用既有),沒修「櫃子上的標籤」。

修法(兩種 var 走相反的規則,這是本次的判斷):
· 設定類 var = 使用者實例的事實 → **沿用**(讀綁定時同一份回應就帶回來,不多打 API)
  ——把 #97「已部署的 worker 上綁著什麼就是事實」原封不動套用到 plain_text var。
· 版本標籤 = 這份成品的屬性 → **每趟重烙,絕不沿用舊值**。
  沿用舊值會得到一個永遠停在安裝當天的假標籤——比沒有標籤更糟,
  因為它會讓人以為驗收過了。
  版號取部署當下發行頻道公告的 release(Portal/daemon 就是拿它當「最新版」比),
  另外把**真正部署的 commit** 一起烙上去(/health 多吐 `bundle_commit`)→ 漂掉查得出來。
  查不到 release 就誠實退成 `YYYY-MM-DD+<commit7>`,不掰一個 semver 假裝已是最新。

順帶(都是同一條路上的東西):
· ref 先解析成 commit sha 再用 sha 下載 archive——不可變,順手解掉 branch tarball 被快取的老病
· Portal 版本行接受帶 build metadata 的 semver(`1.4.41+d61` 這種先前一律被當成「較舊版本」)
· cli 測試在 node 22 上本來一支都跑不起來(.js→.ts 解析 + parameter property),補上 resolve hook
  ——#97 那份「使用者的東西還在不在」的迴歸守衛也在其中,跑不起來的守衛等於沒有守衛
· types.ts 的 ARCRUN_BUNDLE_VERSION 重複宣告(TS2300)併回一處

驗證見 PR:cli 49/49 綠、cypher health 4/4 綠、Portal 版本行原始碼實跑五種情境、
對真實已部署 worker 的唯讀 dry-run。**未做**:真實實例上的 acr update 端到端
(本機唯一有憑證的帳號是 leo21c=紅線禁碰,youlin 無憑證)。

Refs: Leo/Arcrun#106, #97, #95

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 21:58:43 +08:00
uncle6me-web f87d0e92f4 fix(migrations): 0005/0006 從來沒進過版控——被 *.sql 規則吃掉,每個用戶都收到「部署物缺」
leo 更新 leo21c 時撞到(他問「部分失敗?」):
  ✗ D1 migration: 部署物缺 kbdb/migrations/0005_credential_template.sql
  ✗ D1 migration: 部署物缺 kbdb/migrations/0006_drop_credentials_table.sql
(四顆 worker cypher/registry/kbdb/mcp 全部 ✓,失敗的只有這兩個檔)

根因不是誰忘了推:.gitignore:53 的 `*.sql` 是為了擋 D1 匯出備份(整庫全量=機敏),
但它連 migration 一起吃掉。0001-0004 還在,只因為它們在該規則之前就 commit 了
(gitignore 不影響已追蹤檔案)⇒ 0005/0006 從產生那天起就不在任何 clone 裡。

⇒ 這不是 leo 一台的事:更新指令從 Gitea 抓 main,那兩個檔不在那裡
   ⇒ **任何人裝/更新都會收到同一組失敗**,包含全新安裝。

修法照 rules/05-deploy-convention.md「WASM 來源」段已有的慣例
(`.component-builds/**/component.wasm` 就是用否定規則放行的):
  !kbdb/migrations/*.sql

範圍實測(沒開太大):
  kbdb/migrations/0005、0006      → 放行
  backup-2026.sql / kbdb/backup-x.sql / dump.sql / cypher-executor/export.sql → 仍被擋

進版控前確認過無機敏值:grep 命中的 token/secret/api_key 全是欄位名
(api_key、secret_ref)與註解;無 >=20 位英數的疑似真值。

殘項:leo21c 實查 templates 9 個、credential 不在其中 ⇒ 0005 從未套用,
那台仍停在 D38 之前(credentials 走 0002 的獨立表)。要補套需另跑一次更新。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-12 21:10:12 +08:00
uncle6me-web ba152bc83a chore(builds): 重編 tier2 成品——把 #105 放進執行檔(出貨路徑 A 的第 0 步)
leo 選 A(把出貨線推到能出一版含 #105 的 bundle)。查證後發現最前面還有一層:

  cypher 源碼最後動 10d150a(#105)  / 成品最後動 a24f291(更早)
  mcp    源碼最後動 10d150a(#105)  / 成品最後動 8e10f1d(更早)

⇒ #105 改了 cypher 與 mcp 兩邊源碼,但沒有重編成品。
   這正是 Arcrun#93 那道「源碼比執行檔新就停下來」的閘要擋的狀態。

用官方唯一編譯點 scripts/build-worker-artifacts.mjs(Arcrun#80 的機制,已存在)
重編五顆,全部 5/5:
  arcrun-cypher-executor  571KB  source=10d150ac
  arcrun-kbdb             146KB  source=10d150ac
  arcrun-mcp             1152KB  source=10d150ac
  arcrun-http-request      78KB  source=1e85dfb4(未變)
  arcrun-code             150KB  source=621cb8d9(未變)

交叉驗證(不只信它自記的 commit):/portal/data/ 這條 #105 才有的路徑
在 arcrun-mcp 成品裡出現 8 次。

下一步(等 leo 解閘):把修好的引擎部署到 geek6688 當出貨機
(ARCRUN_SHIP_BASE 可覆寫,預設是 leo21c——arcrun-rag#79 要搬離的正是這個),
再從那台跑出貨線,第 17 站 purge 的 wait 節點才有帶修法的引擎可跑。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-12 20:03:30 +08:00
Leo 89b80ff90e Merge PR #105: MCP 用登入者的身分查詢,不再去找服務內部金鑰
總管複驗(不聽自述,自己重跑,並與 base a24f291 逐條比對):
  mcp     tsc 乾淨;vitest 113/113 綠
  cypher  14 紅與 base 逐字元相同(diff 無輸出);passed 386→400,新增 14 條全過
  kbdb    5 紅與 base 相同
  安全邊界 11 條全綠(跨租戶 404/越庫 404/owner_id 由 server 定死)

殘項(已記,不擋併):
  · kbdb 的 owner_id 欄位改動沒有新測試守著(213 總數未變)
  · 工作流面仍靠 MCP_OWNER_NAMESPACE || leo 那個巧合,本 PR 刻意沒動(拔了 arcrun_* 會全面失效)
  · 端到端  未驗:要部署到 leo21c,那道閘要 leo 親手解
2026-08-12 11:42:03 +00:00
uncle6me-web 10d150ac2b fix(mcp): MCP 用登入者的身分查詢,不再去找一把服務內部金鑰
leo 2026-08-12:「人類進 Portal 輸入帳密表示你是主人,可以查到你權限所有東西;
AI 透過輸入帳密的 MCP 查詢表示是授權的 AI,可以查到主人允許查的任何東西。」
「掛上 MCP 並輸入帳密,那個動作本身就是授權」⇒ 下游不得再要求第二次認證。

病根(不是金鑰沒同步,是身分沒接住):
  oauth/routes.ts 驗完 Portal 帳密只留下 `loginOk = res.ok` 一個布林值,身分當場丟棄,
  namespace 改從 `MCP_OWNER_NAMESPACE || "leo"` 拿。於是查詢時手上沒有身分可帶,
  只好用 KBDB_INTERNAL_TOKEN 直打 KBDB——那條路繞過 portal 所有庫過濾,
  而且不管誰登入都看到同一格、看到全部。CLI 也從不注入 MCP_OWNER_NAMESPACE,
  所以那個 "leo" 預設值是每台實例的實際行為,不是理論上的邊角。

修法(走既有那條路,不發明新的):
1. 接住身分:/authorize 解析 /portal/login 回應,把 portal session token +
   display_name/role/libraries 存進 authorization code → access token。
   /portal/login 補回 session_expires_in,access_token TTL 夾成
   min(自己的 TTL, portal session TTL)——不讓「MCP 還連著、底下 session 早死」。
   cypher 回 200 但沒給 session_token(舊版)→ 不發碼,不簽一張沒有身分的 token。
2. 攜帶身分:kbdb_* 全部改走 cypher `/portal/data/*`,Authorization 帶登入者的
   session。庫過濾/租戶注入/停用即時生效全在 server 側,與人類走 portal 網頁同一道閘。
   kbdb_graph_neighbors 因此不再需要 kbdb_base(server 自己知道查哪個庫)。
   藏書地圖(含連線時注入 instructions 的那份)同樣只回有權限的庫,快取改 per-session
   分格——地圖本身就是情報,不能讓先連上的人把視野留給下一個。
3. fail-closed:舊 token 沒有身分 → 誠實要求重新連線,不偷偷退回服務金鑰那條老路。
   服務級憑據(static token / partner key)維持既有 KBDB 直連,arcrun_* 零回歸。

新增 cypher portal 資料面端點(能力長在 API,MCP 只暴露;rule 07):
  GET  /portal/data/map、/portal/data/map/:library
  GET  /portal/data/templates、POST /portal/data/templates
  GET  /portal/data/records/by-template/:t、GET /portal/data/records/:id
  POST /portal/data/records
全部:呼叫端自帶 owner_id 一律不生效;越權與不存在同回 404;寫入 owner_id 由 server 定死。

KBDB base:`GET /records/:id` 與 by-template 補回 owner_id 欄位——原本不回,
呼叫端無從判斷「這筆是不是我的」,按 id 直讀等於沒有租戶邊界。

沒動:KBDB fail-closed 閘、任何金鑰、租戶字串仍不下發給呼叫端。

驗證:
  mcp        tsc 綠;vitest 113/113 綠(改前 48 綠 29 紅)
  cypher     vitest 400 綠 / 14 紅,14 紅與 base commit a24f291 逐條相同(既有)
  kbdb       vitest 208 綠 / 5 紅,5 紅同為既有(migrations/*.sql 被 gitignore)
  端到端     ◐ 未驗:需部署到 leo21c,那道閘要 leo 親手解(見 PR)

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 19:33:12 +08:00
50 changed files with 2972 additions and 1604 deletions
+8
View File
@@ -52,6 +52,14 @@ scripts/__pycache__/
# D1 備份/匯出(wrangler d1 export 產物,含整庫全量資料=機敏,絕不 commit)
*.sql
backup-*.sql
# 🔴 但 migration 不是備份,它是**要出貨的程式碼**(2026-08-12 實撞):
# 上面那條 `*.sql` 的用意是擋 D1 匯出(整庫全量資料=機敏),卻連 migration 一起吃掉。
# 後果:0001-0004 因為在該規則之前就 commit 所以還在,**0005/0006 從此沒進過版控**
# ⇒ 更新指令從 Gitea 抓 main,那兩個檔根本不在那裡 ⇒ 每個用戶都會收到
# 「✗ D1 migration: 部署物缺 kbdb/migrations/0005…」——**不是誰忘了推,是規則吃掉的**。
# ⇒ 與 `.component-builds/**/component.wasm` 同慣例(見 rules/05-deploy-convention.md
# 「WASM 來源」段),用否定規則放行。備份檔仍由 `backup-*.sql` 與目錄位置擋住。
!kbdb/migrations/*.sql
# GitHub 公開 mirror 工作目錄(publish-github.sh 產物)
.github-public/
@@ -13285,7 +13285,12 @@ portalRouter.post(
session_token: token,
display_name: rec.values.display_name ?? "",
role: rec.values.role ?? "user",
libraries: parseLibraries(rec.values.libraries)
libraries: parseLibraries(rec.values.libraries),
// session 還能活多久(秒)。**非機密**(是這台實例的 TTL 設定,不是任何人的憑據),
// 但呼叫端需要它才能把自己發的憑證對齊這個上限——arcrun-mcp 用它把 OAuth
// access_token 的 TTL 夾到 min(自己的 TTL, 這個值):否則 MCP token 活 30 天、
// 底下的 portal session 7 天就死,使用者會在第 8 天遇到「連著卻查不到」的鬼打牆。
session_expires_in: sessionTtl(c.env)
// 絕不回租戶字串(design §3.3portal_user 拿到租戶字串就能繞過庫 filter 直打 /kbdb/*
});
})
@@ -15363,6 +15368,151 @@ portalDataRouter.get(
return c.json({ success: true, workflows, total: workflows.length, read_only: true });
})
);
function recordLibrary(values) {
const lib = values?.library;
return typeof lib === "string" && lib.trim() ? lib.trim() : null;
}
function canReadRecord(rec, tenant2, libraries) {
if ((rec.owner_id ?? "") !== tenant2) return false;
const lib = recordLibrary(rec.values);
return lib === null || canReadLibrary(libraries, lib);
}
portalDataRouter.get(
"/portal/data/map",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) {
return c.json({ success: true, libraries: [], count: 0, note: "\u6B64\u5E33\u865F\u5C1A\u672A\u88AB\u6388\u6B0A\u4EFB\u4F55\u77E5\u8B58\u5EAB\uFF0C\u8ACB\u806F\u7D61\u7BA1\u7406\u54E1\u3002" });
}
const res = await kbdbFetch(c.env, `/map?owner_id=${encodeURIComponent(portalTenant(c.env))}`);
if (!res.ok) {
return new Response(res.body, { status: res.status, headers: { "Content-Type": "application/json" } });
}
const body = await res.json().catch(() => null);
if (!body || !Array.isArray(body.libraries)) {
return c.json({ error: "\u85CF\u66F8\u5730\u5716\u8B80\u53D6\u5931\u6557\uFF1AKBDB \u56DE\u61C9\u4E0D\u662F\u9810\u671F\u7684 libraries \u6E05\u55AE" }, 502);
}
const allowed = body.libraries.filter(
(l) => typeof l?.library === "string" && canReadLibrary(libraries, l.library)
);
return c.json({ success: true, libraries: allowed, count: allowed.length });
})
);
portalDataRouter.get(
"/portal/data/map/:library",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
const library = c.req.param("library");
if (!canReadLibrary(libraries, library)) return notFound(c);
const res = await kbdbFetch(
c.env,
`/map/${encodeURIComponent(library)}?owner_id=${encodeURIComponent(portalTenant(c.env))}`
);
if (res.status === 404) return notFound(c);
if (!res.ok) return c.json({ error: `KBDB \u56DE\u932F\uFF08HTTP ${res.status}\uFF09` }, 502);
return new Response(res.body, { status: 200, headers: { "Content-Type": "application/json" } });
})
);
portalDataRouter.get(
"/portal/data/templates",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const res = await kbdbFetch(c.env, "/templates");
if (!res.ok) return c.json({ error: `KBDB \u56DE\u932F\uFF08HTTP ${res.status}\uFF09` }, 502);
return new Response(res.body, { status: 200, headers: { "Content-Type": "application/json" } });
})
);
portalDataRouter.post(
"/portal/data/templates",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const body = await c.req.json().catch(() => null);
if (!body || typeof body.name !== "string" || !body.name.trim() || !Array.isArray(body.slots)) {
return c.json({ error: "name \u8207 slots[] \u5FC5\u586B" }, 400);
}
const res = await kbdbFetch(c.env, "/templates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: body.name,
slots: body.slots,
description: typeof body.description === "string" ? body.description : void 0,
created_by: portalTenant(c.env)
})
});
return new Response(res.body, { status: res.status, headers: { "Content-Type": "application/json" } });
})
);
portalDataRouter.get(
"/portal/data/records/by-template/:template",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) return c.json({ success: true, records: [], count: 0 });
const tenant2 = portalTenant(c.env);
const res = await kbdbFetch(
c.env,
`/records/by-template/${encodeURIComponent(c.req.param("template"))}?owner_id=${encodeURIComponent(tenant2)}`
);
if (!res.ok) return c.json({ error: `KBDB \u56DE\u932F\uFF08HTTP ${res.status}\uFF09` }, 502);
const body = await res.json().catch(() => null);
if (!body || !Array.isArray(body.records)) {
return c.json({ error: "record \u8B80\u53D6\u5931\u6557\uFF1AKBDB \u56DE\u61C9\u4E0D\u662F\u9810\u671F\u7684 records \u6E05\u55AE" }, 502);
}
const records = body.records.filter((r) => canReadRecord(r, tenant2, libraries));
return c.json({ success: true, records, count: records.length });
})
);
portalDataRouter.get(
"/portal/data/records/:recordId",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) return notFound(c);
const res = await kbdbFetch(c.env, `/records/${encodeURIComponent(c.req.param("recordId"))}`);
if (res.status === 404) return notFound(c);
if (!res.ok) return c.json({ error: `KBDB \u56DE\u932F\uFF08HTTP ${res.status}\uFF09` }, 502);
const body = await res.json().catch(() => null);
const record = body?.record;
if (!record) return notFound(c);
if (!canReadRecord(record, portalTenant(c.env), libraries)) return notFound(c);
return c.json({ success: true, record });
})
);
portalDataRouter.post(
"/portal/data/records",
(c) => run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) {
return c.json({ error: "\u6B64\u5E33\u865F\u5C1A\u672A\u88AB\u6388\u6B0A\u4EFB\u4F55\u77E5\u8B58\u5EAB\uFF0C\u7121\u6CD5\u5BEB\u5165" }, 403);
}
const body = await c.req.json().catch(() => null);
if (!body || typeof body.template !== "string" || !body.template.trim() || !body.values || typeof body.values !== "object") {
return c.json({ error: "template \u8207 values \u5FC5\u586B" }, 400);
}
const values = body.values;
const targetLib = recordLibrary(values);
if (targetLib !== null && !canReadLibrary(libraries, targetLib)) {
return c.json({ error: `\u7121\u300C${targetLib}\u300D\u5EAB\u7684\u6B0A\u9650\uFF0C\u4E0D\u80FD\u5BEB\u5165\u8A72\u5EAB` }, 403);
}
const res = await kbdbFetch(c.env, "/records", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ template: body.template, values, owner_id: portalTenant(c.env) })
});
return new Response(res.body, { status: res.status, headers: { "Content-Type": "application/json" } });
})
);
portalDataRouter.get(
"/portal/data/diagnostics",
(c) => run(c, async () => {
+7 -5
View File
@@ -3281,7 +3281,7 @@ async function createRecord(db, input) {
});
await db.prepare(`INSERT INTO entry_values (id, record_id, template_id, slot_name, entry_id) VALUES (?, ?, ?, ?, ?)`).bind(uid2("ev"), recordId, tpl.id, slot, entry.id).run();
}
return { record_id: recordId, template_id: tpl.id, values: input.values };
return { record_id: recordId, template_id: tpl.id, values: input.values, owner_id: input.owner_id ?? null };
}
async function updateRecord(db, recordId, values) {
const evRes = await db.prepare(
@@ -3312,7 +3312,7 @@ async function updateRecord(db, recordId, values) {
}
async function getRecord(db, recordId) {
const res = await db.prepare(
`SELECT ev.slot_name as slot, e.content as content, ev.template_id as template_id
`SELECT ev.slot_name as slot, e.content as content, ev.template_id as template_id, e.owner_id as owner_id
FROM entry_values ev JOIN entries e ON ev.entry_id = e.id
WHERE ev.record_id = ?`
).bind(recordId).all();
@@ -3320,7 +3320,8 @@ async function getRecord(db, recordId) {
if (rows.length === 0) return null;
const values = {};
for (const r of rows) values[r.slot] = r.content;
return { record_id: recordId, template_id: rows[0].template_id, values };
const owner_id = rows.find((r) => r.owner_id != null)?.owner_id ?? null;
return { record_id: recordId, template_id: rows[0].template_id, values, owner_id };
}
async function searchByTemplate(db, template, owner_id, limit = 100) {
const tpl = await getTemplate(db, template);
@@ -3339,17 +3340,18 @@ async function searchByTemplate(db, template, owner_id, limit = 100) {
const chunk = ids.slice(i, i + 90);
const placeholders = chunk.map(() => "?").join(",");
const evRes = await db.prepare(
`SELECT ev.record_id as record_id, ev.slot_name as slot, e.content as content, ev.template_id as template_id
`SELECT ev.record_id as record_id, ev.slot_name as slot, e.content as content, ev.template_id as template_id, e.owner_id as owner_id
FROM entry_values ev JOIN entries e ON ev.entry_id = e.id
WHERE ev.record_id IN (${placeholders})`
).bind(...chunk).all();
for (const r of evRes.results ?? []) {
let rec = byId.get(r.record_id);
if (!rec) {
rec = { record_id: r.record_id, template_id: r.template_id, values: {} };
rec = { record_id: r.record_id, template_id: r.template_id, values: {}, owner_id: null };
byId.set(r.record_id, rec);
}
rec.values[r.slot] = r.content;
if (rec.owner_id == null && r.owner_id != null) rec.owner_id = r.owner_id;
}
}
return ids.map((id) => byId.get(id)).filter((r) => !!r);
File diff suppressed because it is too large Load Diff
+11 -11
View File
@@ -1,18 +1,18 @@
{
"schema": 1,
"built_for": "arcrun-tier2-worker-artifacts",
"generated_at": "2026-08-12T07:29:58.626Z",
"repo_head": "1791ffa4972b4135dacd4208e805f67b747479c4",
"generated_at": "2026-08-12T12:02:15.698Z",
"repo_head": "89b80ff90e95f07b5d44978ef58090ac783f53bd",
"repo_dirty": false,
"workers": [
{
"name": "arcrun-cypher-executor",
"source_dir": "cypher-executor",
"source_commit": "f1370e2275eea62b64a88821a096f2c2cfe76fb0",
"source_commit": "10d150ac2b4385af95a457f3c411430c4a146cf9",
"main_module": "worker.mjs",
"main_file": "arcrun-cypher-executor/worker.mjs",
"js_bytes": 577374,
"content_sha256": "8411ed59b7ad9e1a74ac0d8e3b620d7166e7d0178ac5939e6cc736f2e8d1d2be",
"js_bytes": 584610,
"content_sha256": "6a424274ecf7beb28b747672296c4c33f949c6d7b134e8054e640e92198910ba",
"modules": [],
"compat_date": "2025-02-19",
"compat_flags": [
@@ -58,11 +58,11 @@
{
"name": "arcrun-kbdb",
"source_dir": "kbdb",
"source_commit": "c497ec418eba6cd94b1d5872671c51fd5812c11c",
"source_commit": "10d150ac2b4385af95a457f3c411430c4a146cf9",
"main_module": "worker.mjs",
"main_file": "arcrun-kbdb/worker.mjs",
"js_bytes": 149533,
"content_sha256": "ffb8d43467d0cefbd7545fdc0d347f2b965e3c3de20b3315eed7613f20266891",
"js_bytes": 149797,
"content_sha256": "8b23853cbc88aee0ca15ef20ca46e92bd8e75064cd311af2847f4d51811960b1",
"modules": [],
"compat_date": "2025-02-19",
"compat_flags": [
@@ -148,11 +148,11 @@
{
"name": "arcrun-mcp",
"source_dir": "mcp",
"source_commit": "035e8b255b0dcbd4238707f7d2ac8ccf9ee1ba72",
"source_commit": "10d150ac2b4385af95a457f3c411430c4a146cf9",
"main_module": "worker.mjs",
"main_file": "arcrun-mcp/worker.mjs",
"js_bytes": 1165388,
"content_sha256": "c5ff10f9b9d5a77217be343af12d2be3ee8f9792d3e1e091e48e5e6c8d24ca9d",
"js_bytes": 1179487,
"content_sha256": "1cd4c4d079d72bf7cba7c490ba6a88476f70b3ea51af7e5c93f9a184ae3c0ce6",
"modules": [],
"compat_date": "2024-11-27",
"compat_flags": [
+1 -1
View File
@@ -12,7 +12,7 @@
"build:harness": "node scripts/build-harness-skill.mjs",
"check:harness": "node scripts/check-harness-generation.mjs",
"dev": "tsc --watch",
"test": "node --test \"tests/**/*.test.ts\"",
"test": "node --experimental-transform-types --import ./tests/register-ts-hooks.mjs --test \"tests/**/*.test.ts\"",
"prepublishOnly": "npm run build && chmod +x dist/index.js"
},
"dependencies": {
+21 -2
View File
@@ -170,10 +170,13 @@ export class CfAccountClient implements ResourceApi {
const path = `/workers/scripts/${encodeURIComponent(script)}/settings`;
const res = await this.cfRaw<{ bindings?: RawWorkerBinding[] }>(path);
if (!res.ok) {
if (res.status === 404) return { deployed: false, bindings: [] };
if (res.status === 404) return { deployed: false, bindings: [], vars: {} };
throw new Error(`${script} 綁定失敗:${res.error}`);
}
return { deployed: true, bindings: normalizeBindings(res.result?.bindings ?? []) };
const raw = res.result?.bindings ?? [];
// #106:同一份回應裡也帶著 plain_text var(實測 CF `/settings` 會回 `text` 值)。
// 舊版只挑資源類、把 var 整批丟掉 → 重部署等於把它們洗掉。
return { deployed: true, bindings: normalizeBindings(raw), vars: normalizeVars(raw) };
}
/** 查 workers.dev subdomaincypher-executor WORKER_SUBDOMAIN 用,組對內 component URL)。*/
@@ -234,6 +237,22 @@ interface RawWorkerBinding {
id?: string;
database_id?: string;
index_name?: string;
/** `plain_text` 綁定的值(#106secret_text 不會回值,本來就讀不到,也不該讀)。 */
text?: string;
}
/**
* worker `plain_text` var#106
*
* `plain_text`**`secret_text` **CF CLI
* wrangler deploy secret
*/
function normalizeVars(raw: RawWorkerBinding[]): Record<string, string> {
const out: Record<string, string> = {};
for (const b of raw) {
if (b?.type === 'plain_text' && b.name && typeof b.text === 'string') out[b.name] = b.text;
}
return out;
}
/** 把 CF 的 binding 陣列收斂成 resolver 認得的三種資源。不認得的型別直接略過。 */
+258 -5
View File
@@ -98,6 +98,119 @@ function giteaToken(): string | undefined {
return process.env.ARCRUN_GITEA_TOKEN || process.env.GITEA_TOKEN || undefined;
}
/**
* Arcrun#106
*
* Portal daemon `cloudVersionStale()` **** `release`
* `/health` `bundle_version` CLI
* 使
* fork ARCRUN_RELEASE_API
*/
const ARCRUN_RELEASE_API = process.env.ARCRUN_RELEASE_API ?? 'https://install.arcrun.dev/api/latest';
/** CLI 自己負責注入 / 自己烙的 var——**不從已部署的 worker 沿用**(沿用會蓋掉這趟算出來的正解)。 */
export const CLI_MANAGED_VARS = [
'WORKER_SUBDOMAIN', // 由 ctx.workerSubdomain 注入
'CF_ACCOUNT_ID', // 由 ctx.accountId 注入
'MULTI_TENANT', // 由 selfHosted 注入
'KBDB_BASE_URL', // 由 workerSubdomain 組
'ARCRUN_BUNDLE_VERSION', // 版本標籤:每趟重烙,**絕不沿用舊值**(見 resolveBundleStamp
'ARCRUN_BUNDLE_COMMIT',
] as const;
/** 烙版本標籤的那顆 worker(`/health` 就是它吐的)。其餘 worker 不需要版本標籤。 */
export const VERSION_STAMP_WORKER = 'arcrun-cypher-executor';
/** 這趟部署要烙上去的版本標籤。 */
export interface BundleStamp {
/** 寫進 `ARCRUN_BUNDLE_VERSION`。 */
version: string;
/** 寫進 `ARCRUN_BUNDLE_COMMIT`(查得到才有)。 */
commit?: string;
/** 給人看的一句話(CLI 會印出來),說明這個版號是怎麼來的。 */
note: string;
}
/**
* 西Arcrun#106
*
* 🔴 **沿******
* =
* leo ****使
* 沿 var plain_text var 沿 preservedVars
*
* mindset §7
* - CLI `ARCRUN_REPO@ref` ****semver****
* release
* ** commit **
* `ARCRUN_BUNDLE_COMMIT``/health` `bundle_commit` commit
* - release ****退 `YYYY-MM-DD+<commit7>`
* Portal semver
* ****
*/
export async function resolveBundleStamp(
ref: string,
commit?: string,
fetchImpl: typeof fetch = fetch,
): Promise<BundleStamp> {
const short = commit ? commit.slice(0, 7) : ref;
const today = new Date().toISOString().slice(0, 10);
try {
const res = await fetchImpl(ARCRUN_RELEASE_API, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = (await res.json()) as { release?: string } | null;
const release = String(body?.release ?? '').trim();
if (!/^\d+\.\d+\.\d+$/.test(release)) throw new Error(`發行頻道回的版號不是 semver${release || '空'}`);
return {
version: release,
commit,
note: `${release}(發行頻道 ${ARCRUN_RELEASE_API}${commit ? `;實際部署 commit ${short}` : ''}`,
};
} catch (e) {
const version = `${today}+${short}`;
return {
version,
commit,
note:
`${version}(查不到發行版號:${e instanceof Error ? e.message : String(e)}` +
`\n → 誠實標成 commit 版;Portal 會顯示成「較舊版本」而不是假裝已是最新。`,
};
}
}
/**
* `ref`branch / tag / sha commit shaArcrun#106
*
* commit ** sha archive**
* sha #13 P2 branch tarball
* undefined退 ref
*/
export async function resolveGiteaCommit(
ref: string,
fetchImpl: typeof fetch = fetch,
): Promise<string | undefined> {
const headers = buildDownloadHeaders();
const tryUrls = [
`${ARCRUN_GITEA_BASE}/api/v1/repos/${ARCRUN_REPO}/branches/${encodeURIComponent(ref)}`,
`${ARCRUN_GITEA_BASE}/api/v1/repos/${ARCRUN_REPO}/commits?sha=${encodeURIComponent(ref)}&limit=1&stat=false`,
];
for (const url of tryUrls) {
try {
const res = await fetchImpl(url, { headers, signal: AbortSignal.timeout(20_000) });
if (!res.ok) continue;
const body = (await res.json()) as
| { commit?: { id?: string } }
| Array<{ sha?: string }>
| null;
const sha = Array.isArray(body) ? body[0]?.sha : body?.commit?.id;
if (typeof sha === 'string' && /^[0-9a-f]{7,64}$/i.test(sha)) return sha;
} catch {
/* 換下一種問法;全都問不到就回 undefined */
}
}
return undefined;
}
/**
* Gitea archive URL URL
* Gitea archive API`GET {base}/api/v1/repos/{owner}/{repo}/archive/{ref}.tar.gz`
@@ -253,9 +366,12 @@ export async function downloadAndDeploy(
const mode = opts.mode ?? 'update';
const api = opts.api ?? new CfAccountClient(ctx.accountId, ctx.apiToken);
// 1. 下載 + 解壓 Gitea archive tarball
// #106:先把 ref 解析成確切 commit,**用 sha 下載**(不可變 → 順帶解掉 branch tarball 被快取的老問題),
// 同一個 sha 稍後也會被烙成版本標籤。解不出來就照舊用 ref 下載(行為不變)。
const commit = await resolveGiteaCommit(ref);
let root: string;
try {
root = await downloadRepoTarball(ref);
root = await downloadRepoTarball(commit ?? ref, commit ? ref : undefined);
} catch (e) {
return {
implemented: true,
@@ -310,6 +426,7 @@ export async function downloadAndDeploy(
// 所以「解析看到的」和「最後寫進去的」保證是同一份檔案的同一種樣子。
const requirements: BindingRequirement[] = [];
const tomlPreviews = new Map<string, string>(); // dir → 注入前的原文
const dirScript = new Map<string, string>(); // dir → worker script 名(#106var 沿用要逐顆對號)
for (const dir of allDirs) {
const tomlPath = join(dir, 'wrangler.toml');
if (!existsSync(tomlPath)) continue;
@@ -318,12 +435,14 @@ export async function downloadAndDeploy(
const preview = renderWranglerToml(raw, ctx, new Map());
const parsed = parseWranglerRequirements(preview);
if (!parsed.script) continue; // 沒宣告 name 的 toml 不該存在;跳過而非亂猜
dirScript.set(dir, parsed.script);
for (const b of parsed.bindings) {
requirements.push({ ...b, worker: parsed.script });
}
}
let resolved = new Map<string, ResolvedResource>();
let liveVars = new Map<string, Record<string, string>>();
if (requirements.length > 0) {
process.stdout.write(chalk.gray(' → 對照你帳號上已部署的 worker,確認每個綁定該用哪顆資源...'));
let plan;
@@ -369,6 +488,7 @@ export async function downloadAndDeploy(
message: `停手:\n${detail}${hint}\n\n沒有部署任何 worker——你現在的實例維持原樣。`,
};
}
liveVars = plan.liveVars;
console.log(chalk.green(' ✓'));
const adopted = [...resolved.values()].filter((r) => r.origin === 'adopted');
const created = [...resolved.values()].filter((r) => r.origin === 'created');
@@ -407,6 +527,48 @@ export async function downloadAndDeploy(
}
}
// ── 2.8 varplain_text):既有的沿用、版本標籤重烙(Arcrun#106)─────────────────
//
// 🔴 #97 修好了「櫃子」(KV/D1/Vectorize 沿用既有),但 **var 這批「櫃子上的標籤」沒人管**:
// wrangler deploy 是整份覆蓋,toml 沒寫的 var 直接消失。leo 2026-08-12 實撞的畫面
// 「無法讀取目前版本(知識庫服務可能正在啟動)」就是 `ARCRUN_BUNDLE_VERSION` 被這樣洗掉的。
//
// 兩種 var 走**相反**的規則,這是本次的核心判斷:
// · 設定類(PORTAL_MAIL_RELAY_BASE / CONSOLE_TENANT / …)=**使用者實例的事實** → 沿用
// · 版本標籤(ARCRUN_BUNDLE_VERSION)=**這份成品的屬性** → 每趟重烙,沿用舊值就是假標籤
//
// 範圍註記:`liveVars` 來自資源解析那一趟讀到的 worker(=有資源綁定的那些:cypher/kbdb/mcp/registry)。
// 純零件 worker 沒有資源綁定、不在那份名單裡 → 這裡不會沿用它們的 var。目前它們的 var 只有
// toml 自己帶的 `COMPONENT_ID`,沒有東西可丟;若哪天有人往零件 worker 注入設定,要在這裡補讀。
const extraVarsByDir = new Map<string, Record<string, string>>();
let stamp: BundleStamp | undefined;
if (dirScript.size > 0) {
const needStamp = [...dirScript.values()].includes(VERSION_STAMP_WORKER);
if (needStamp) {
process.stdout.write(chalk.gray(' → 算這趟要烙上去的版本標籤...'));
stamp = await resolveBundleStamp(ref, commit);
console.log(chalk.green(' ✓'));
console.log(chalk.gray(` ARCRUN_BUNDLE_VERSION = ${stamp.note}`));
}
const preservedTotal: string[] = [];
for (const [dir, script] of dirScript) {
const raw = tomlPreviews.get(dir);
if (!raw) continue;
const keep = preservedVars(liveVars.get(script), raw);
for (const k of Object.keys(keep)) preservedTotal.push(`${script}:${k}`);
const vars: Record<string, string> = { ...keep };
if (stamp && script === VERSION_STAMP_WORKER) {
vars.ARCRUN_BUNDLE_VERSION = stamp.version;
if (stamp.commit) vars.ARCRUN_BUNDLE_COMMIT = stamp.commit;
}
if (Object.keys(vars).length > 0) extraVarsByDir.set(dir, vars);
}
if (preservedTotal.length > 0) {
console.log(chalk.gray(` 沿用你實例上既有的 ${preservedTotal.length} 個設定值(var):`));
for (const item of preservedTotal) console.log(chalk.gray(` = ${item}`));
}
}
// 3. 對每個 worker:注入 KV id+ cypher WORKER_SUBDOMAIN)→ wrangler deploy。tier1 先 tier2 後。
// 逐 worker 串流進度(每個含 pnpm install + wrangler deploy,沉默會讓人以為卡住——
// 壓測 2026-06-11 richblack 觀察:「D1 ✓」後停很久其實在這個迴圈靜默部署 20+ worker)。
@@ -422,7 +584,7 @@ export async function downloadAndDeploy(
const label = dir.replace(/^.*\.component-builds\//, '').replace(/^.*\//, '');
process.stdout.write(chalk.gray(` [${i + 1}/${allDirs.length}] ${label} ...`));
try {
injectWranglerConfig(tomlPath, ctx, resolved, tomlPreviews.get(dir));
injectWranglerConfig(tomlPath, ctx, resolved, tomlPreviews.get(dir), extraVarsByDir.get(dir));
// 注入後算指紋:與 manifest 比,相同 = 上次成功部過且內容沒變 → 跳過。
const hash = dirContentHash(dir, ctx.accountId);
if (manifest[label] === hash) {
@@ -599,11 +761,13 @@ async function ensureVectorizeMetadataIndexes(ctx: DeployContext, indexName: str
* fetch no-cache header + query param ref
*
* Arcrun#4 GitHub codeload Gitea archive API GITEA_TOKEN*/
async function downloadRepoTarball(ref: string): Promise<string> {
async function downloadRepoTarball(ref: string, fromRef?: string): Promise<string> {
// 唯一 cache-buster query param:對不同 query 視為不同請求 → 繞過 stale 快取。
const bust = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
const url = buildArchiveUrl(ref, bust);
console.log(chalk.gray(` → 從 Gitea 下載最新版本(${ARCRUN_REPO}@${ref},約 1030 秒,視網速)...`));
// fromRef 有值 = ref 已被解析成 commit sha(#106),印出來讓人看得到「這趟到底部了哪個 commit」。
const label = fromRef ? `${fromRef}${ref.slice(0, 7)}` : ref;
console.log(chalk.gray(` → 從 Gitea 下載最新版本(${ARCRUN_REPO}@${label},約 1030 秒,視網速)...`));
const res = await fetch(url, {
signal: AbortSignal.timeout(120_000),
// 強制繞過任何中間快取,避免抓到 push 後尚未刷新的 stale tarball#13 P2 假綠根因)。
@@ -701,11 +865,91 @@ function injectWranglerConfig(
ctx: DeployContext,
resolved: Map<string, ResolvedResource>,
original?: string,
extraVars: Record<string, string> = {},
): void {
if (!existsSync(tomlPath)) return;
// original = 資源解析階段讀到的原文。用它而不是重讀檔案,確保「解析看到的」與「寫回去的」同源。
const toml = original ?? readFileSync(tomlPath, 'utf8');
writeFileSync(tomlPath, renderWranglerToml(toml, ctx, resolved), 'utf8');
writeFileSync(tomlPath, renderWranglerToml(toml, ctx, resolved, extraVars), 'utf8');
}
/**
* worker toml plain_text varArcrun#106
*
* ** worker var**#97
* 沿
* `CLI_MANAGED_VARS` CLI idsubdomain
* 沿
* toml
*
* ****toml toml
* repo toml `CONSOLE_TENANT = "leo"``WORKER_SUBDOMAIN` ** prod **
* 使
*/
export function preservedVars(
live: Record<string, string> | undefined,
toml: string,
): Record<string, string> {
const out: Record<string, string> = {};
if (!live) return out;
const managed = new Set<string>(CLI_MANAGED_VARS);
for (const key of Object.keys(live).sort()) {
if (managed.has(key)) continue;
if (!/^[A-Za-z0-9_]+$/.test(key)) continue; // 怪名字不碰(applyVars 也會擋,這裡先濾掉不誤報)
if (readVar(toml, key) === live[key]) continue; // toml 已經是同一個值 → 不必動
out[key] = live[key];
}
return out;
}
/** 讀 toml 裡某個 var 目前的值(只看未註解的行)。找不到回 undefined。 */
function readVar(toml: string, key: string): string | undefined {
const m = toml.match(new RegExp(`^\\s*${key}\\s*=\\s*"([^"]*)"`, 'm'));
return m?.[1];
}
/** TOML basic string 轉義(值裡可能有引號/反斜線,例如網址或 JSON 片段)。 */
function tomlEscape(value: string): string {
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
/**
* var toml `[vars]`Arcrun#106
*
* injectMultiTenant
* 1.
* 2.
* 3. `[vars]` header `[vars]`
*/
export function applyVars(toml: string, vars: Record<string, string>): string {
let out = toml;
for (const key of Object.keys(vars).sort()) {
// 只接受合法的 var 名(CF 那側本來就是這個字集)。怪名字寧可不寫,也不要拿它去組正規式。
if (!/^[A-Za-z0-9_]+$/.test(key)) continue;
const value = tomlEscape(vars[key]);
// 🔴 一律用「函式版 replace」:值裡若有 `$&``$1` 這種字元,字串版 replace 會把它當成
// 反向參照展開,寫出來的就不是使用者那個值了。
if (new RegExp(`^\\s*${key}\\s*=`, 'm').test(out)) {
out = out.replace(
new RegExp(`^(\\s*${key}\\s*=\\s*")[^"]*(".*)$`, 'm'),
(_m, head: string, tail: string) => `${head}${value}${tail}`,
);
continue;
}
if (new RegExp(`^\\s*#\\s*${key}\\s*=`, 'm').test(out)) {
out = out.replace(
new RegExp(`^(\\s*)#\\s*${key}\\s*=\\s*"[^"]*"(.*)$`, 'm'),
(_m, indent: string, tail: string) => `${indent}${key} = "${value}"${tail}`,
);
continue;
}
if (/^\s*\[vars\]\s*$/m.test(out)) {
out = out.replace(/^(\s*\[vars\]\s*)$/m, (_m, header: string) => `${header}\n${key} = "${value}"`);
continue;
}
out = `${out.replace(/\s*$/, '')}\n\n[vars]\n${key} = "${value}"\n`;
}
return out;
}
/**
@@ -715,11 +959,15 @@ function injectWranglerConfig(
* id toml
* binding Arcrun#97
*
*
* `extraVars`Arcrun#106 worker **沿 var** ****
* vars
*/
export function renderWranglerToml(
toml: string,
ctx: DeployContext,
resolved: Map<string, ResolvedResource>,
extraVars: Record<string, string> = {},
): string {
// cypher-executor 的 WORKER_SUBDOMAINvars)換成用戶帳號 subdomain
if (ctx.workerSubdomain && /WORKER_SUBDOMAIN/.test(toml)) {
@@ -770,6 +1018,11 @@ export function renderWranglerToml(
toml = toml.replace(/# (\[ai\])\n# (binding = "AI")/, '$1\n$2');
}
// 沿用的既有 var + 這趟的版本標籤(#106)。**放在所有 CLI 注入之後**:
// CLI_MANAGED_VARS 已經在 preservedVars 排除掉,故這裡不會蓋掉上面剛算好的
// WORKER_SUBDOMAIN / CF_ACCOUNT_ID / MULTI_TENANT / KBDB_BASE_URL。
toml = applyVars(toml, extraVars);
// 資源 id 一律最後注入,且**照 binding 名逐個對號**(不是「檔案裡第一個 database_id」那種盲換)。
// 空 map = 預覽模式,這步什麼也不做。
return applyResolvedBindings(toml, resolved);
+25 -2
View File
@@ -41,6 +41,16 @@ export interface ScriptBindings {
/** false = 這顆 worker 在帳號上還不存在(全新部署),不是「讀取失敗」。讀取失敗要 throw。 */
deployed: boolean;
bindings: LiveBinding[];
/**
* worker `plain_text` var
*
* 🔴 Arcrun#106#97 沿KV/D1/Vectorize
* plain_text var repo toml
* `ARCRUN_BUNDLE_VERSION`
* Portal
* ****
*/
vars?: Record<string, string>;
}
/** resolver 需要的 CF 能力(收窄成介面,方便離線測試餵假帳號)。 */
@@ -87,6 +97,14 @@ export interface ResourcePlan {
create: PlannedCreate[];
/** 非空 = 整趟停手。applyResourcePlan 會拒絕執行。 */
blockers: string[];
/**
* **** worker plain_text varscript /
*
* Arcrun#106 `bindings[]` var
* ** API**
* blockers
*/
liveVars: Map<string, Record<string, string>>;
}
export interface ResolvedResource {
@@ -137,11 +155,16 @@ export async function planResources(
// 讀取失敗 ≠ 沒有綁。#97 的災情就是把「我查不到」當成「它不存在」。
const scripts = [...new Set(requirements.map((r) => r.worker))].sort();
const live = new Map<string, LiveBinding[]>();
const liveVars = new Map<string, Record<string, string>>();
let readFailed = false;
for (const script of scripts) {
try {
const res = await api.getScriptBindings(script);
if (res.deployed) live.set(script, res.bindings);
if (res.deployed) {
live.set(script, res.bindings);
// #106:同一份回應裡的 plain_text var 一起收下(呼叫端要拿它決定哪些 var 該沿用)。
liveVars.set(script, res.vars ?? {});
}
} catch (e) {
readFailed = true;
blockers.push(
@@ -242,7 +265,7 @@ export async function planResources(
});
}
return { adopt, create: shareSameResource(adopt, create, byKey), blockers };
return { adopt, create: shareSameResource(adopt, create, byKey), blockers, liveVars };
}
/**
+4
View File
@@ -0,0 +1,4 @@
/** `node --import ./tests/register-ts-hooks.mjs --test ...` 的進入點:註冊 ts-hooks.mjs。 */
import { register } from 'node:module';
register('./ts-hooks.mjs', import.meta.url);
+3 -1
View File
@@ -493,7 +493,7 @@ test('CfAccountClient.getScriptBindings404 = 還沒部署;其他錯誤要 t
new Response(JSON.stringify({ success: false, errors: [{ message: 'not found' }] }), { status: 404 })
) as typeof fetch;
const cf = new CfAccountClient('a', 't');
assert.deepEqual(await cf.getScriptBindings('nope'), { deployed: false, bindings: [] });
assert.deepEqual(await cf.getScriptBindings('nope'), { deployed: false, bindings: [], vars: {} });
globalThis.fetch = (async () =>
new Response(JSON.stringify({ success: false, errors: [{ message: 'boom' }] }), { status: 500 })
@@ -526,6 +526,8 @@ test('CfAccountClient.getScriptBindings:讀得懂 CF 回的 kv/d1/vectorize
{ kind: 'd1', binding: 'DB', value: 'db1' },
{ kind: 'vectorize', binding: 'VECTORIZE', value: 'idx1' },
]);
// #106plain_text 也要收下來(service 這種不認得的仍略過)。
assert.deepEqual(res.vars, { ENVIRONMENT: 'production' });
} finally {
globalThis.fetch = orig;
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 測試用 resolve hook `./x.js` 這種 import 指回同名的 `./x.ts`Arcrun#106 附帶修復
*
* 為什麼需要`src/` 內部的 import 一律寫成 `.js`NodeNext 慣例編譯後才會有那個檔
* 但測試是**直接載入 `src/**\/*.ts`**不經過 tsc`outDir: dist`所以 `src/` 底下永遠不會有 .js
* Node 的型別剝離不會自己把 `.js` 對回 `.ts` 三份測試在 node 22 **一支都跑不起來**
* `ERR_MODULE_NOT_FOUND: .../src/lib/cf-api.js`包含 #97 那份使用者的東西還在不在的迴歸守衛
* 跑不起來的守衛等於沒有守衛所以這裡補上
*
* 只在預設解析失敗時才動作且只換副檔名 對本來就解析得到的環境新版 node / 已編譯零影響
*/
export async function resolve(specifier, context, next) {
try {
return await next(specifier, context);
} catch (err) {
if (typeof specifier === 'string' && specifier.endsWith('.js')) {
return next(specifier.slice(0, -3) + '.ts', context);
}
throw err;
}
}
+243
View File
@@ -0,0 +1,243 @@
/**
* Arcrun#106 ****
*
* 2026-08-12 leo leo21cPortal
*
* `ARCRUN_BUNDLE_VERSION` plain_text var****
* CLI wrangler toml var
* #97 KV/D1/Vectorize 沿****
*
*
* · var PORTAL_MAIL_RELAY_BASE 使 **沿**
* · ARCRUN_BUNDLE_VERSION **沿**
* 沿 =
*
* wrangler.toml + render/inject fetch
*/
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
renderWranglerToml,
preservedVars,
applyVars,
resolveBundleStamp,
CLI_MANAGED_VARS,
VERSION_STAMP_WORKER,
type DeployContext,
} from '../src/lib/deploy.ts';
import { planResources, type ResourceApi, type ScriptBindings } from '../src/lib/resource-resolver.ts';
const REPO = join(fileURLToPath(new URL('.', import.meta.url)), '..', '..');
const CYPHER_TOML = readFileSync(join(REPO, 'cypher-executor', 'wrangler.toml'), 'utf8');
const CTX: DeployContext = {
accountId: 'acc-user-123',
apiToken: 'token',
workerSubdomain: 'user-sub',
selfHosted: true,
kbdbEmbed: true,
};
/** 一台「安裝器裝出來、已經跑過的」實例上,cypher worker 現在掛著的 plain_text var。 */
const LIVE_VARS: Record<string, string> = {
ARCRUN_BUNDLE_VERSION: '1.4.29', // 安裝當時的舊標籤
PORTAL_MAIL_RELAY_BASE: 'https://mail.example.com', // 安裝器注入、repo toml 沒有 → 洗掉就寄不出信
CONSOLE_TENANT: 'someone-else', // repo toml 寫死 "leo",不能拿官方值蓋掉人家的
WORKER_SUBDOMAIN: 'user-sub', // CLI 自己算
CF_ACCOUNT_ID: 'acc-user-123', // CLI 自己算
MULTI_TENANT: 'false', // CLI 自己算
ENVIRONMENT: 'production', // 與 toml 同值 → 不必重寫
};
/** 從 render 過的 toml 讀 [vars] 區塊(只看未註解的行)。 */
function readVars(toml: string): Record<string, string> {
const out: Record<string, string> = {};
let inVars = false;
for (const raw of toml.split('\n')) {
const line = raw.trim();
if (/^\[\[?[A-Za-z0-9_]+\]?\]$/.test(line)) { inVars = line === '[vars]'; continue; }
if (!inVars || line.startsWith('#')) continue;
const m = line.match(/^([A-Za-z0-9_]+)\s*=\s*"([^"]*)"/);
if (m) out[m[1]] = m[2];
}
return out;
}
// ═════════════════════════════════════════════════════════════════════════════
// ① 病灶本身:舊行為會把標籤洗掉
// ═════════════════════════════════════════════════════════════════════════════
test('#106 ①:repo 的 cypher toml 本來就沒有 ARCRUN_BUNDLE_VERSION——不補就是洗掉(病灶重現)', () => {
const rendered = renderWranglerToml(CYPHER_TOML, CTX, new Map());
assert.equal(
readVars(rendered).ARCRUN_BUNDLE_VERSION,
undefined,
'若這行開始有值,表示 toml 自己帶了版本標籤,本測試的前提要重寫',
);
});
// ═════════════════════════════════════════════════════════════════════════════
// ② 設定類 var:沿用實例上的事實
// ═════════════════════════════════════════════════════════════════════════════
test('#106 ②:安裝器注入、repo toml 沒有的 var 會被沿用(不再被重部署洗掉)', () => {
const keep = preservedVars(LIVE_VARS, CYPHER_TOML);
assert.equal(keep.PORTAL_MAIL_RELAY_BASE, 'https://mail.example.com');
// repo toml 寫死的是官方值,使用者實例上的值才是事實
assert.equal(keep.CONSOLE_TENANT, 'someone-else');
// 與 toml 同值 → 不需要重寫進去(雜訊)
assert.equal(keep.ENVIRONMENT, undefined);
});
test('#106 ③:CLI 自己算的 var 一律不沿用(沿用等於拿舊值蓋掉這趟的正解)', () => {
const keep = preservedVars({ ...LIVE_VARS, WORKER_SUBDOMAIN: 'OLD-sub', CF_ACCOUNT_ID: 'OLD-acc' }, CYPHER_TOML);
for (const managed of CLI_MANAGED_VARS) {
assert.equal(keep[managed], undefined, `${managed} 不該被沿用`);
}
// 而且注入完的 toml 裡,這些值仍是這趟算出來的那個
const rendered = renderWranglerToml(CYPHER_TOML, CTX, new Map(), keep);
const vars = readVars(rendered);
assert.equal(vars.WORKER_SUBDOMAIN, 'user-sub');
assert.equal(vars.CF_ACCOUNT_ID, 'acc-user-123');
assert.equal(vars.MULTI_TENANT, 'false');
assert.equal(vars.KBDB_BASE_URL, 'https://arcrun-kbdb.user-sub.workers.dev');
});
// ═════════════════════════════════════════════════════════════════════════════
// ③ 版本標籤:重烙,不沿用
// ═════════════════════════════════════════════════════════════════════════════
test('#106 ④:版本標籤取「發行頻道公告的 release」+ 實際 commit,不是沿用舊值', async () => {
const fakeFetch = (async () =>
new Response(JSON.stringify({ release: '1.4.41', pin: 'ba81439' }), { status: 200 })) as typeof fetch;
const stamp = await resolveBundleStamp('main', 'f87d0e92f49690253e7c89c5badc82a08eb5d21b', fakeFetch);
assert.equal(stamp.version, '1.4.41');
assert.notEqual(stamp.version, LIVE_VARS.ARCRUN_BUNDLE_VERSION); // ← 這就是本 issue
assert.equal(stamp.commit, 'f87d0e92f49690253e7c89c5badc82a08eb5d21b');
assert.match(stamp.version, /^\d+\.\d+\.\d+$/, 'Portal 拿它跟 /api/latest 比 semver,必須是純 semver');
});
test('#106 ⑤:查不到發行版號時誠實標成 commit 版,**不**沿用舊值、也不掰一個 semver', async () => {
const fakeFetch = (async () => { throw new Error('offline'); }) as typeof fetch;
const stamp = await resolveBundleStamp('main', 'f87d0e92f49690253e7c89c5badc82a08eb5d21b', fakeFetch);
assert.match(stamp.version, /^\d{4}-\d{2}-\d{2}\+f87d0e9$/);
assert.notEqual(stamp.version, LIVE_VARS.ARCRUN_BUNDLE_VERSION);
assert.doesNotMatch(stamp.version, /^\d+\.\d+\.\d+$/, '掰一個 semver 會讓 Portal 假裝「已是最新版」');
});
test('#106 ⑥:發行頻道回了不是 semver 的東西 → 當成查不到(不把垃圾當版號烙上去)', async () => {
const fakeFetch = (async () =>
new Response(JSON.stringify({ release: 'latest' }), { status: 200 })) as typeof fetch;
const stamp = await resolveBundleStamp('main', 'abc1234def', fakeFetch);
assert.match(stamp.version, /^\d{4}-\d{2}-\d{2}\+abc1234$/);
});
// ═════════════════════════════════════════════════════════════════════════════
// ④ 端到端(離線):一台已安裝的實例跑一次更新,Portal 讀得到的那個欄位長什麼樣
// ═════════════════════════════════════════════════════════════════════════════
test('#106 ⑦:模擬更新——版本標籤變新、設定 var 一個不少、資源沿用不受影響', async () => {
const api: ResourceApi = {
async getScriptBindings(script: string): Promise<ScriptBindings> {
if (script !== VERSION_STAMP_WORKER) return { deployed: false, bindings: [], vars: {} };
return {
deployed: true,
bindings: [
{ kind: 'kv_namespace', binding: 'WEBHOOKS', value: 'kv-webhooks' },
{ kind: 'kv_namespace', binding: 'CREDENTIALS_KV', value: 'kv-creds' },
{ kind: 'kv_namespace', binding: 'RECIPES', value: 'kv-recipes' },
{ kind: 'kv_namespace', binding: 'USERS_KV', value: 'kv-users' },
{ kind: 'kv_namespace', binding: 'SESSIONS_KV', value: 'kv-sessions' },
{ kind: 'kv_namespace', binding: 'ANALYTICS_KV', value: 'kv-analytics' },
{ kind: 'kv_namespace', binding: 'EXEC_CONTEXT', value: 'kv-exec' },
{ kind: 'd1', binding: 'CREDENTIALS_DB', value: 'd1-kbdb' },
],
vars: LIVE_VARS,
};
},
async listKvNamespaces() {
return new Map([
['a', 'kv-webhooks'], ['b', 'kv-creds'], ['c', 'kv-recipes'], ['d', 'kv-users'],
['e', 'kv-sessions'], ['f', 'kv-analytics'], ['g', 'kv-exec'],
]);
},
async listD1Databases() { return new Map([['arcrun-kbdb', 'd1-kbdb']]); },
async listVectorizeIndexes() { return []; },
async createKvNamespace() { throw new Error('這趟不該新建任何 KV'); },
async createD1Database() { throw new Error('這趟不該新建 D1'); },
async createVectorizeIndex() { throw new Error('這趟不該新建 Vectorize'); },
};
const preview = renderWranglerToml(CYPHER_TOML, CTX, new Map());
const { parseWranglerRequirements } = await import('../src/lib/resource-resolver.ts');
const parsed = parseWranglerRequirements(preview);
const plan = await planResources(
api,
parsed.bindings.map((b) => ({ ...b, worker: parsed.script })),
'update',
);
assert.deepEqual(plan.blockers, []);
// 讀綁定時順手把 var 帶回來——不另外打一次 API
assert.equal(plan.liveVars.get(VERSION_STAMP_WORKER)?.PORTAL_MAIL_RELAY_BASE, 'https://mail.example.com');
const fakeFetch = (async () =>
new Response(JSON.stringify({ release: '1.4.41' }), { status: 200 })) as typeof fetch;
const stamp = await resolveBundleStamp('main', 'f87d0e92f49690253e7c89c5badc82a08eb5d21b', fakeFetch);
const extra = {
...preservedVars(plan.liveVars.get(parsed.script), CYPHER_TOML),
ARCRUN_BUNDLE_VERSION: stamp.version,
ARCRUN_BUNDLE_COMMIT: stamp.commit!,
};
const deployed = readVars(renderWranglerToml(CYPHER_TOML, CTX, new Map(), extra));
// ① Portal 設定頁讀的就是這個欄位——更新完必須有值,且是**這趟**的版本
assert.equal(deployed.ARCRUN_BUNDLE_VERSION, '1.4.41');
assert.equal(deployed.ARCRUN_BUNDLE_COMMIT, 'f87d0e92f49690253e7c89c5badc82a08eb5d21b');
// ② 安裝器注入的設定沒有在更新中消失
assert.equal(deployed.PORTAL_MAIL_RELAY_BASE, 'https://mail.example.com');
assert.equal(deployed.CONSOLE_TENANT, 'someone-else');
// ③ CLI 自己算的仍然是這趟算出來的
assert.equal(deployed.WORKER_SUBDOMAIN, 'user-sub');
assert.equal(deployed.MULTI_TENANT, 'false');
});
// ═════════════════════════════════════════════════════════════════════════════
// ⑤ applyVars 的三種既有狀態 + 不弄壞別的區塊
// ═════════════════════════════════════════════════════════════════════════════
test('#106 ⑧:applyVars——改既有行/取消註解/插進 [vars]/連 [vars] 都沒有時新開一段', () => {
assert.match(applyVars('[vars]\nA = "old"\n', { A: 'new' }), /^\[vars\]\nA = "new"\n$/);
assert.match(applyVars('[vars]\n# A = "old"\n', { A: 'new' }), /A = "new"/);
assert.match(applyVars('[vars]\nB = "b"\n', { A: 'a' }), /\[vars\]\nA = "a"\nB = "b"/);
const noVars = applyVars('name = "w"\n', { A: 'a' });
assert.match(noVars, /\[vars\]\nA = "a"/);
assert.match(noVars, /^name = "w"/);
});
test('#106 ⑨:var 值裡的引號/反斜線會被轉義(不會產生壞掉的 toml)', () => {
const out = applyVars('[vars]\n', { A: 'say "hi"\\path' });
assert.match(out, /A = "say \\"hi\\"\\\\path"/);
});
test('#106 ⑨b:值裡有 $& / $1 也照原樣寫出(replace 反向參照陷阱)', () => {
assert.match(applyVars('[vars]\nA = "old"\n', { A: 'x$&y$1z' }), /A = "x\$&y\$1z"/);
assert.match(applyVars('[vars]\n', { A: 'x$&y' }), /A = "x\$&y"/);
// 怪名字不寫進去(不拿它組正規式)
assert.equal(applyVars('[vars]\n', { 'BAD NAME': 'v' }), '[vars]\n');
});
test('#106 ⑩:注入 var 不影響資源綁定解析(預覽與實際寫入看到的是同一份需求)', async () => {
const { parseWranglerRequirements } = await import('../src/lib/resource-resolver.ts');
const withoutVars = parseWranglerRequirements(renderWranglerToml(CYPHER_TOML, CTX, new Map()));
const withVars = parseWranglerRequirements(
renderWranglerToml(CYPHER_TOML, CTX, new Map(), { ARCRUN_BUNDLE_VERSION: '1.4.41', X: 'y' }),
);
assert.equal(withVars.script, withoutVars.script);
assert.deepEqual(withVars.bindings, withoutVars.bindings);
});
+23 -5
View File
@@ -2039,6 +2039,15 @@ function taipeiMonthDay(ms) { var d = new Date(ms + TAIPEI_OFFSET_MS); return {
// 兩邊都是 semver(例 1.4.2),用數字逐段比,不用字串比('1.4.10' < '1.4.9' 會出錯)。
var INSTALLER_ORIGIN = 'https://install.arcrun.dev';
// Arcrun#106:版號後面可以帶 build metadata`1.4.41+d61`、`1.4.41+a1b2c3d`)——
// 那是 semver 規格裡「比大小時要忽略」的那一段。舊寫法拿整串去比對正規式,
// 一律落到「較舊版本」(youlin 實例就是這樣,明明有版號卻顯示不出來)。
// 這裡只取前面的 `x.y.z` 當比較用的核心,顯示仍顯示完整原字串。
function semverCore(v) {
var m = String(v || '').match(/^(\d+\.\d+\.\d+)/);
return m ? m[1] : '';
}
function cmpSemver(a, b) {
var x = String(a || '').split('.').map(Number);
var y = String(b || '').split('.').map(Number);
@@ -2055,9 +2064,14 @@ function taipeiMonthDay(ms) { var d = new Date(ms + TAIPEI_OFFSET_MS); return {
var btn = $('st-ver-update');
if (!line) return;
// #106:順便把 bundle_commit 帶回來(有注入才有)——版號是頻道編號,commit 才是「真的部了哪份碼」。
var mineCommit = '';
var mineP = fetch(window.ARCRUN_API_BASE + '/health', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (j) { return (j && j.bundle_version) || ''; })
.then(function (j) {
mineCommit = (j && j.bundle_commit) || '';
return (j && j.bundle_version) || '';
})
.catch(function () { return ''; });
var latestP = fetch(INSTALLER_ORIGIN + '/api/latest')
.then(function (r) { return r.ok ? r.json() : null; })
@@ -2070,15 +2084,19 @@ function taipeiMonthDay(ms) { var d = new Date(ms + TAIPEI_OFFSET_MS); return {
if (!mine) { line.textContent = '無法讀取目前版本(知識庫服務可能正在啟動)'; return; }
// 舊實例的 bundle_version 是舊格式(2026-07-31+8e83589),比不了 semver。
// 這種情況一律當成「落後」——因為新版才會寫 semver 進來。
var mineIsSemver = /^\d+\.\d+\.\d+$/.test(mine);
// #106`1.4.41+<commit>` 這種帶 build metadata 的**是** semver,取核心比即可。
var mineCore = semverCore(mine);
var mineIsSemver = !!mineCore;
// commit 是輔助資訊(有才顯示):版號說「哪一版」,commit 說「真的是哪份碼」。
var commitNote = mineCommit ? ' <span class="muted">commit ' + esc(String(mineCommit).slice(0, 7)) + '</span>' : '';
if (!latest) {
line.textContent = '目前版本 ' + mine + '(暫時查不到最新版,稍後再試)';
line.innerHTML = '目前版本 <strong>' + esc(mine) + '</strong>(暫時查不到最新版,稍後再試)' + commitNote;
return;
}
var behind = !mineIsSemver || cmpSemver(mine, latest) < 0;
var behind = !mineIsSemver || cmpSemver(mineCore, latest) < 0;
if (!behind) {
line.innerHTML = '目前版本 <strong>' + esc(mine) + '</strong> 已是最新版';
line.innerHTML = '目前版本 <strong>' + esc(mine) + '</strong> 已是最新版' + commitNote;
dot.style.display = 'none';
btn.style.display = 'none';
return;
+2 -12
View File
@@ -24,8 +24,6 @@ import { consoleAuthRouter } from './routes/console-auth';
import { consoleDashboardRouter } from './routes/console-dashboard';
import { portalRouter } from './routes/portal';
import { portalDataRouter } from './routes/portal-data';
import { storageRouter } from './routes/storage';
import { withDurableStores } from './lib/durable-store';
const app = new Hono<{ Bindings: Bindings }>();
@@ -99,19 +97,11 @@ app.route('/', consoleAuthRouter); // Arcrun#3 發現②:console 專用簡單
app.route('/', consoleDashboardRouter); // T-cockpit ②:駕駛艙 dashboard(聚合 KBDB dash_* entries,無需登入唯讀)
app.route('/', portalRouter); // portal-auth P2#24/#25):RAG Portal 多人授權——用戶模型+認證 API
app.route('/', portalDataRouter); // portal-auth P3/portal/data/* server-side enforceowner_idlibrary 注入,安全核心)
app.route('/', storageRouter); // KV 退休(#16/#17):資產遷移/盤點端點
// Worker 導出(fetch + scheduled
// scheduled handler 對應 wrangler.toml [triggers].crons,每分鐘 tick
// 邏輯在 src/scheduled.ts。對應 SDD: arcrun.md 三-A P1 #3。
//
// 🔴 KV 退休(Leo/Arcrun#16 + #17):WEBHOOKS / RECIPES 在這裡被換成 KBDB 撐腰的版本
//lib/durable-store.ts)。**這是唯一的接線點**——換在入口,四十幾處呼叫端一行不動,
// 也就沒有「某一處忘了改」這種漏洞(那正是資產會不見的入口)。
// 使用者的工作流與 recipe 從此住在 KBDBD1,一份資產一列 entry),KV 只是快取:
// KV 被換掉/重建之後,資料仍在,且會在下一次讀取時自己長回快取。
export default {
fetch: (req: Request, env: Bindings, ctx: ExecutionContext) => app.fetch(req, withDurableStores(env), ctx),
scheduled: (event: ScheduledController, env: Bindings, ctx: ExecutionContext) =>
handleScheduled(event, withDurableStores(env), ctx),
fetch: app.fetch,
scheduled: handleScheduled,
} satisfies ExportedHandler<Bindings>;
-156
View File
@@ -1,156 +0,0 @@
/**
* asset-keys KV key 使 KBDB
*
* KV 退Leo/Arcrun#16 + #17leo 2026-08-12
* KBDB KV RecipesCypher entry
* recipe
*
*
* ** KBDBKV **
* KV webhooks-named / portal / executions / component-loader /
* auth-dispatcher / wasi-shim
* 西 binding durable-store.ts
* 西** key **
*
* vs
* = 西使/AI recipe KBDB
* = 西 idx:*cron session
* TTL KVdurable-store
*
* KBDB
* 西
*
* KV key KBDB
* KBDB KVleo entry
* portal/console key ****
* entry_type + owner_id + page_name + KBDB
*/
/** KBDB 裡 arcrun 資產的 entry_type(每個都有一列 template 定義,見 kbdb/migrations/0005)。 */
export type AssetEntryType = 'workflow_def' | 'api_recipe' | 'auth_recipe' | 'prompt_recipe';
export interface AssetRef {
entry_type: AssetEntryType;
/** KBDB entries.id——由 key 決定,同一份資產永遠同一列(冪等,重跑遷移不長重複)。 */
entry_id: string;
/** 租戶。recipe 是整台實例共用的庫,故為 null(與現行 RECIPES KV 無租戶前綴一致)。 */
owner_id: string | null;
/** 該型別的自然鍵(workflow 名 / recipe uuid / service 名),對應 entries.page_name。 */
page_name: string;
/** 原本的 KV key——反向重建快取時要用(KBDB → KV 回填)。 */
kv_key: string;
}
/** entries.id 的前綴,跟別人的資料分得開,也讓 `arcrun:` 一眼看得出是誰的列。 */
const ID_PREFIX = 'arcrun';
/**
* KV key KBDB null KV
*
* **** KBDB
* KBDB 2026-08-08 credential
*/
export function classifyAssetKey(key: string): AssetRef | null {
// ── 明確排除的衍生資料(放最前面,免得被下面的樣式誤收)────────────────
// idx:* recipe/component 反查索引(canonical→uuid、hash→canonical
// cron-idx:* cron 排程索引(8.P0 的單一 key
// 兩者都能從資產重算,見 durable-store.ts 的 rehydrate*。
if (key.startsWith('idx:') || key.startsWith('cron-idx:')) return null;
// auth_recipe:{service} — 「怎麼認證」的定義。注意只有定義,沒有任何密文
//(憑證明文在 CF Workers Secrets,見 .claude/rules/01-tech-stack.md「Credential 儲存規範」)。
if (key.startsWith('auth_recipe:')) {
const service = key.slice('auth_recipe:'.length);
if (!service) return null;
return {
entry_type: 'auth_recipe',
entry_id: `${ID_PREFIX}:auth_recipe:${service}`,
owner_id: null,
page_name: service,
kv_key: key,
};
}
// prompt_recipe:{name}
if (key.startsWith('prompt_recipe:')) {
const name = key.slice('prompt_recipe:'.length);
if (!name) return null;
return {
entry_type: 'prompt_recipe',
entry_id: `${ID_PREFIX}:prompt_recipe:${name}`,
owner_id: null,
page_name: name,
kv_key: key,
};
}
// recipe:{uuid}recipe:{canonical_id}migration 前的舊 key,仍是資產,一樣要保住)
if (key.startsWith('recipe:')) {
const id = key.slice('recipe:'.length);
if (!id) return null;
return {
entry_type: 'api_recipe',
entry_id: `${ID_PREFIX}:recipe:${id}`,
owner_id: null,
page_name: id,
kv_key: key,
};
}
// {api_key}:wf:{name} — 具名工作流(acr push / portal 安裝器寫的那把)。
// 用**第一個** ':wf:' 切:api_key 不含冒號,而 workflow 名允許的字元集
//webhooks-named.ts 驗 /^[\w-]+$/)本來就不含冒號,所以切點唯一。
const wfAt = key.indexOf(':wf:');
if (wfAt > 0) {
const owner = key.slice(0, wfAt);
const name = key.slice(wfAt + ':wf:'.length);
if (!owner || !name) return null;
return {
entry_type: 'workflow_def',
entry_id: `${ID_PREFIX}:wf:${owner}:${name}`,
owner_id: owner,
page_name: name,
kv_key: key,
};
}
// 其餘一律衍生/暫存:匿名 webhook token、daemon-active、session、stats… 留在 KV。
return null;
}
/** 從 KBDB 的一列反推回原本的 KV key(快取回填、list 都要用)。 */
export function assetKvKey(entryType: AssetEntryType, ownerId: string | null, pageName: string): string {
switch (entryType) {
case 'workflow_def':
return `${ownerId ?? ''}:wf:${pageName}`;
case 'api_recipe':
return `recipe:${pageName}`;
case 'auth_recipe':
return `auth_recipe:${pageName}`;
case 'prompt_recipe':
return `prompt_recipe:${pageName}`;
}
}
/**
* KV list prefix KBDB
*
* list KBDB get KV ****
* KV list 2026-08-12
* get KV miss list
*
* null = prefix cron-idx: KV
*/
export function classifyListPrefix(prefix: string | undefined): { entry_type: AssetEntryType; owner_id?: string } | null {
if (!prefix) return null; // 無 prefix 的全域 listwebhooks-list)維持原行為
if (prefix.startsWith('idx:') || prefix.startsWith('cron-idx:')) return null;
if (prefix === 'auth_recipe:') return { entry_type: 'auth_recipe' };
if (prefix === 'prompt_recipe:') return { entry_type: 'prompt_recipe' };
if (prefix === 'recipe:') return { entry_type: 'api_recipe' };
// `{api_key}:wf:` — 列出某租戶的所有工作流(webhooks-named / portal-data 都用這個)
if (prefix.endsWith(':wf:')) {
const owner = prefix.slice(0, -':wf:'.length);
if (owner) return { entry_type: 'workflow_def', owner_id: owner };
}
return null;
}
-448
View File
@@ -1,448 +0,0 @@
/**
* durable-store KV KBDB
*
* KV 退Leo/Arcrun#16 + #17leo 2026-08-12
* KV 使
* AI
* recipe
* 使
* cli/src/lib/resource-resolver.ts Arcrun#97
*
*
* ** KBDBD1 entryKV 退**
* KV KBDB
*
* binding
* WEBHOOKS / RECIPES webhooks-namedportalexecutionscomponent-loader
* auth-dispatcherwasi-shim **
* 西** worker binding
* key asset-keys.ts 西
*
*
* 1. **** KV KBDB KV
* 2. **** KBDB KV
* KBDB ****
* 3. **** KBDB** KV** KV
* KV
*
* idx:* / cron-idx:*
* KBDBKBDB ****
* rehydrateRecipeIndices / rehydrateCronIndex
*/
import { classifyAssetKey, classifyListPrefix, assetKvKey, type AssetRef, type AssetEntryType } from './asset-keys';
import { CRON_INDEX_KEY, cronEntryKey, type CronIndex } from './cron-index';
export interface KbdbEnv {
KBDB_BASE_URL?: string;
KBDB_INTERNAL_TOKEN?: string;
}
/** KBDB 位址與 token 的取法沿用既有慣例(lib/workflow-search.ts、routes/webhooks-named.ts 同款)。 */
function kbdbBase(env: KbdbEnv): string {
return (env.KBDB_BASE_URL ?? 'https://arcrun-kbdb.uncle6-me.workers.dev').replace(/\/$/, '');
}
function kbdbHeaders(env: KbdbEnv): Record<string, string> {
const h: Record<string, string> = { 'Content-Type': 'application/json' };
if (env.KBDB_INTERNAL_TOKEN) h['Authorization'] = `Bearer ${env.KBDB_INTERNAL_TOKEN}`;
return h;
}
/** KBDB 一列 entry 的回應形狀(只取本檔用得到的欄位)。 */
interface KbdbEntry {
id: string;
content?: string | null;
entry_type?: string | null;
owner_id?: string | null;
page_name?: string | null;
metadata_json?: string | null;
updated_at?: number;
}
/** 資產寫進 metadata_json 的信封。definition = 原值 parse 過的物件;非 JSON 的原字串走 definition_raw。 */
interface AssetEnvelope {
arcrun_asset: true;
kv_key: string;
definition?: unknown;
definition_raw?: string;
/** api_recipe 專用:本部署目前安裝的是不是這一版(重建 idx:installed:* 用,見 rehydrateRecipeIndices)。 */
installed?: boolean;
}
export class KbdbUnavailableError extends Error {
constructor(op: string, detail: string) {
super(
`資產無法寫入 KBDB${op}):${detail}` +
'本次操作已中止且未寫入任何一邊——這是刻意的:寧可讓你現在看到失敗,' +
'也不要寫進只會被下次更新換掉的 KV、事後才發現東西不見了(Leo/Arcrun#16、#17)。',
);
this.name = 'KbdbUnavailableError';
}
}
/** 從資產定義裡挑一句「給人看也給搜尋看」的描述,當 entries.content。 */
function assetContent(type: AssetEntryType, def: unknown, pageName: string): string {
const d = (def ?? {}) as Record<string, unknown>;
const pick = (...keys: string[]): string => {
for (const k of keys) {
const v = d[k];
if (typeof v === 'string' && v.trim()) return v.trim();
}
return '';
};
switch (type) {
case 'workflow_def':
return pick('description') || pageName;
case 'api_recipe':
return pick('description', 'display_name', 'canonical_id') || pageName;
case 'auth_recipe':
return pick('description', 'display_name', 'service') || pageName;
case 'prompt_recipe':
return pick('description', 'name') || pageName;
}
}
/** 把 KBDB 一列還原成原本的 KV 值(字串)。不是資產信封(或壞掉)→ null,誠實當作沒有。 */
function entryToKvValue(entry: KbdbEntry | null | undefined): string | null {
if (!entry?.metadata_json) return null;
try {
const env = JSON.parse(entry.metadata_json) as AssetEnvelope;
if (!env || env.arcrun_asset !== true) return null;
if (typeof env.definition_raw === 'string') return env.definition_raw;
if (env.definition === undefined) return null;
return JSON.stringify(env.definition);
} catch {
return null;
}
}
/**
* KV binding KVNamespace
* request rehydrate per-instance
*/
export class DurableKv {
private rehydratedRecipeIdx = false;
private rehydratedCronIdx = false;
constructor(
private readonly kv: KVNamespace,
private readonly env: KbdbEnv,
) {}
/**
* KV****routes/storage.ts
* KV KBDB
* list KBDB
*
*/
get rawKv(): KVNamespace {
return this.kv;
}
// ── KBDB 存取原語 ──────────────────────────────────────────────────────
private async kbdbGetEntry(entryId: string): Promise<KbdbEntry | null> {
const res = await fetch(`${kbdbBase(this.env)}/entries/${encodeURIComponent(entryId)}`, {
headers: kbdbHeaders(this.env),
});
if (res.status === 404) return null;
if (!res.ok) return null; // 讀不到就當沒有;快取仍可能有值,不炸讀取路徑
const json = (await res.json().catch(() => null)) as { entry?: KbdbEntry } | null;
return json?.entry ?? null;
}
private async kbdbListEntries(entryType: AssetEntryType, ownerId?: string): Promise<KbdbEntry[]> {
const params = new URLSearchParams({ entry_type: entryType, limit: '1000' });
if (ownerId) params.set('owner_id', ownerId);
const res = await fetch(`${kbdbBase(this.env)}/entries?${params.toString()}`, {
headers: kbdbHeaders(this.env),
});
if (!res.ok) throw new KbdbUnavailableError('list', `HTTP ${res.status}`);
const json = (await res.json().catch(() => null)) as { entries?: KbdbEntry[] } | null;
return json?.entries ?? [];
}
private async kbdbPutEntry(ref: AssetRef, envelope: AssetEnvelope): Promise<void> {
const content = assetContent(ref.entry_type, envelope.definition, ref.page_name);
const res = await fetch(`${kbdbBase(this.env)}/entries/${encodeURIComponent(ref.entry_id)}`, {
method: 'PUT',
headers: kbdbHeaders(this.env),
body: JSON.stringify({
entry_type: ref.entry_type,
owner_id: ref.owner_id,
page_name: ref.page_name,
content,
// 刻意**不**標 embed:true:工作流的語意搜尋走既有的 entry_type='workflow' 那一列
//workflow-discovery 方案 C 的雙寫),這裡標了會變成同一支工作流嵌兩份向量。
metadata_json: JSON.stringify(envelope),
}),
});
if (!res.ok) throw new KbdbUnavailableError('put', `HTTP ${res.status} @ ${ref.entry_id}`);
}
private async kbdbDeleteEntry(entryId: string): Promise<void> {
const res = await fetch(`${kbdbBase(this.env)}/entries/${encodeURIComponent(entryId)}`, {
method: 'DELETE',
headers: kbdbHeaders(this.env),
});
// 404 = 本來就沒有,對刪除而言是成功(冪等)。
if (!res.ok && res.status !== 404) throw new KbdbUnavailableError('delete', `HTTP ${res.status} @ ${entryId}`);
}
// ── 衍生索引重建(讀不到就重算,不進 KBDB)────────────────────────────
/**
* KBDB api_recipe recipe
* idx:{hash_id} canonical_id
* idx:canonical:{canonical} [uuid, ...]
* idx:installed:{canonical} uuid
*
* installed installed
* put() `idx:installed:` canonical
*退 updated_at
* installRecipeRecord
* **退**
*/
private async rehydrateRecipeIndices(): Promise<void> {
if (this.rehydratedRecipeIdx) return;
this.rehydratedRecipeIdx = true;
const entries = await this.kbdbListEntries('api_recipe');
const byCanonical = new Map<string, Array<{ uuid: string; installed: boolean; updated_at: number }>>();
const writes: Array<Promise<unknown>> = [];
for (const e of entries) {
const raw = entryToKvValue(e);
if (!raw) continue;
let def: { uuid?: string; canonical_id?: string; hash_id?: string };
try { def = JSON.parse(raw) as typeof def; } catch { continue; }
if (!def.canonical_id) continue;
if (def.hash_id) writes.push(this.kv.put(`idx:${def.hash_id}`, def.canonical_id));
if (!def.uuid) continue;
let installed = false;
try {
installed = (JSON.parse(e.metadata_json ?? '{}') as AssetEnvelope).installed === true;
} catch { /* 壞信封 → 當作沒標記,走 updated_at 退路 */ }
const list = byCanonical.get(def.canonical_id) ?? [];
list.push({ uuid: def.uuid, installed, updated_at: e.updated_at ?? 0 });
byCanonical.set(def.canonical_id, list);
}
for (const [canonical, versions] of byCanonical) {
writes.push(this.kv.put(`idx:canonical:${canonical}`, JSON.stringify(versions.map((v) => v.uuid))));
const chosen =
versions.find((v) => v.installed) ??
versions.reduce((a, b) => (b.updated_at > a.updated_at ? b : a));
writes.push(this.kv.put(`idx:installed:${canonical}`, chosen.uuid));
}
await Promise.all(writes);
}
/** 從 KBDB 的 workflow_def 列重建 cron 索引(單一 key,見 lib/cron-index.ts)。 */
private async rehydrateCronIndex(): Promise<void> {
if (this.rehydratedCronIdx) return;
this.rehydratedCronIdx = true;
const entries = await this.kbdbListEntries('workflow_def');
const index: CronIndex = {};
for (const e of entries) {
const raw = entryToKvValue(e);
if (!raw) continue;
let def: { cron_expr?: string };
try { def = JSON.parse(raw) as typeof def; } catch { continue; }
if (!def.cron_expr || !e.owner_id || !e.page_name) continue;
index[cronEntryKey(e.owner_id, e.page_name)] = def.cron_expr;
}
// 即使是空的也要寫回去:寫了之後 get 就命中,下一分鐘的 tick 不會再重算一次
//(不寫的話 scheduled() 每分鐘都會回源 KBDB 一趟,白花錢)。
await this.kv.put(CRON_INDEX_KEY, JSON.stringify(index));
}
// ── KVNamespace 介面 ───────────────────────────────────────────────────
async get(key: string, type?: 'text' | 'json' | 'arrayBuffer' | 'stream' | { type: string }): Promise<any> {
// 二進位/串流形態本 worker 沒有呼叫端在用(資產都是 JSON 文字)。原樣轉發,
// 不假裝支援——真有人開始用而拿不到 KBDB 回源,會在這裡被看見,不是靜默降級。
const t0 = typeof type === 'string' ? type : type?.type;
if (t0 === 'arrayBuffer' || t0 === 'stream') return this.kv.get(key, t0 as 'arrayBuffer');
const asText = (raw: string | null): unknown => {
if (raw === null) return null;
const t = typeof type === 'string' ? type : type?.type;
if (t === 'json') {
try { return JSON.parse(raw); } catch { return null; }
}
return raw;
};
const ref = classifyAssetKey(key);
if (!ref) {
// 衍生/暫存:原樣走 KV。讀不到而且是「算得出來」的索引 → 重算一次再讀。
const raw = await this.kv.get(key, 'text');
if (raw !== null) return asText(raw);
if (key.startsWith('idx:')) {
await this.rehydrateRecipeIndices().catch(() => {});
return asText(await this.kv.get(key, 'text'));
}
if (key === CRON_INDEX_KEY) {
await this.rehydrateCronIndex().catch(() => {});
return asText(await this.kv.get(key, 'text'));
}
return asText(raw);
}
// 資產:快取優先,miss 回源 KBDB 並補快取(被換掉的空 KV 就是這樣自己痊癒的)。
const cached = await this.kv.get(key, 'text');
if (cached !== null) return asText(cached);
const fromKbdb = entryToKvValue(await this.kbdbGetEntry(ref.entry_id));
if (fromKbdb === null) return asText(null);
await this.kv.put(key, fromKbdb).catch(() => {}); // 補快取失敗不影響這次讀取
return asText(fromKbdb);
}
async put(key: string, value: string | ArrayBuffer | ReadableStream, options?: KVNamespacePutOptions): Promise<void> {
// 帶 TTL=定義上就是暫存(daemon 回報、session…),不是資產,不進 KBDB。
if (options?.expirationTtl || options?.expiration || typeof value !== 'string') {
return this.kv.put(key, value as string, options);
}
// idx:installed:{canonical} 不是資產,但它記的是**使用者的選擇**(這個 canonical 目前
// 裝的是哪一版),純算不回來。所以把它記進對應那一版 recipe 資產的信封裡,
// KBDB 端不會多出一列「指標 entry」,重建時又還原得精確(見 rehydrateRecipeIndices)。
if (key.startsWith('idx:installed:')) {
await this.kv.put(key, value, options);
await this.markInstalledVersion(key.slice('idx:installed:'.length), value).catch(() => {
// 標記失敗不擋主流程:recipe 本體已經在 KBDB,最壞情況是重建時退回 updated_at 那條路。
});
return;
}
const ref = classifyAssetKey(key);
if (!ref) return this.kv.put(key, value, options);
let definition: unknown;
let definitionRaw: string | undefined;
try { definition = JSON.parse(value); } catch { definitionRaw = value; }
// 覆寫定義不該把「這版是目前安裝的那版」洗掉 → 只有 api_recipe 需要先讀回舊信封。
// 其他三型沒有這個欄位,省下這一次往返(每次 acr push 都會走到這裡)。
const previous = ref.entry_type === 'api_recipe' ? await this.readEnvelope(ref) : null;
// 先真相、後快取。KBDB 失敗就拋——不寫 KV、不回報成功(禁假綠,mindset §7)。
await this.kbdbPutEntry(ref, {
arcrun_asset: true,
kv_key: key,
...(definitionRaw !== undefined ? { definition_raw: definitionRaw } : { definition }),
...(previous?.installed ? { installed: true } : {}),
});
await this.kv.put(key, value, options);
}
async delete(key: string): Promise<void> {
const ref = classifyAssetKey(key);
if (ref) await this.kbdbDeleteEntry(ref.entry_id);
await this.kv.delete(key);
}
async list(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<unknown, string>> {
const target = classifyListPrefix(options?.prefix ?? undefined);
if (!target) return this.kv.list(options) as Promise<KVNamespaceListResult<unknown, string>>;
// 資產列舉一律回源(見檔頭規則 3)。順手把每一筆補進快取——列表回應本來就帶了完整內容,
// 呼叫端接著一筆筆 get 時就會全部命中,一次回源換掉 N 次往返。
const entries = await this.kbdbListEntries(target.entry_type, target.owner_id);
const keys: Array<{ name: string }> = [];
const warm: Array<Promise<unknown>> = [];
for (const e of entries) {
if (!e.page_name) continue;
// workflow_def 的 KV key 由租戶+名字組成,缺租戶就組不出正確的 key——
// 與其回一個 `:wf:x` 這種對不到任何東西的名字,不如跳過(列不出來看得見,
// 組錯名字則會安靜地讀到 null,那更難查)。
if (target.entry_type === 'workflow_def' && !e.owner_id) continue;
const name = assetKvKey(target.entry_type, e.owner_id ?? null, e.page_name);
keys.push({ name });
const raw = entryToKvValue(e);
if (raw !== null) warm.push(this.kv.put(name, raw).catch(() => {}));
}
await Promise.all(warm);
return { keys, list_complete: true, cacheStatus: null } as unknown as KVNamespaceListResult<unknown, string>;
}
/** KVNamespace 介面補齊(本 worker 沒有呼叫端在用,原樣轉發,不做資產處理)。 */
getWithMetadata(key: string, type?: any): Promise<any> {
return (this.kv as unknown as { getWithMetadata: (k: string, t?: any) => Promise<any> }).getWithMetadata(key, type);
}
// ── 內部小工具 ─────────────────────────────────────────────────────────
private async readEnvelope(ref: AssetRef): Promise<AssetEnvelope | null> {
const entry = await this.kbdbGetEntry(ref.entry_id);
if (!entry?.metadata_json) return null;
try {
const env = JSON.parse(entry.metadata_json) as AssetEnvelope;
return env?.arcrun_asset === true ? env : null;
} catch {
return null;
}
}
/** 把「這個 canonical 目前裝的是哪一版」記進該版 recipe 的信封(同 canonical 的其他版清掉旗標)。 */
private async markInstalledVersion(canonicalId: string, uuid: string): Promise<void> {
const entries = await this.kbdbListEntries('api_recipe');
const jobs: Array<Promise<unknown>> = [];
for (const e of entries) {
const raw = entryToKvValue(e);
if (!raw) continue;
let def: { uuid?: string; canonical_id?: string };
try { def = JSON.parse(raw) as typeof def; } catch { continue; }
if (def.canonical_id !== canonicalId || !def.uuid) continue;
const shouldBeInstalled = def.uuid === uuid;
let envelope: AssetEnvelope;
try { envelope = JSON.parse(e.metadata_json ?? '{}') as AssetEnvelope; } catch { continue; }
if ((envelope.installed === true) === shouldBeInstalled) continue; // 已經是對的,不白寫
envelope.installed = shouldBeInstalled;
jobs.push(
fetch(`${kbdbBase(this.env)}/entries/${encodeURIComponent(e.id)}`, {
method: 'PATCH',
headers: kbdbHeaders(this.env),
body: JSON.stringify({ metadata_json: JSON.stringify(envelope) }),
}),
);
}
await Promise.all(jobs);
}
}
/**
* worker WEBHOOKS / RECIPES KBDB
*
* **使西**recipe
* KVEXEC_CONTEXT SESSIONS_KVANALYTICS_KVCREDENTIALS_KV
* credential CF Workers Secrets + D1
* .claude/rules/01-tech-stack.md****
*
* KBDB_BASE_URL kbdbBase()
* 退 KV
*/
export function withDurableStores<T extends { WEBHOOKS?: KVNamespace; RECIPES?: KVNamespace } & KbdbEnv>(env: T): T {
const wrapped = { ...env } as T;
if (env.WEBHOOKS) wrapped.WEBHOOKS = new DurableKv(env.WEBHOOKS, env) as unknown as KVNamespace;
if (env.RECIPES) wrapped.RECIPES = new DurableKv(env.RECIPES, env) as unknown as KVNamespace;
return wrapped;
}
/**
* KV DurableKv.rawKv
* grep routes/storage.ts
*/
export function unwrapKv(binding: KVNamespace): KVNamespace {
const maybe = binding as unknown as { rawKv?: KVNamespace };
return maybe.rawKv ?? binding;
}
+8
View File
@@ -15,11 +15,19 @@ export const healthRouter = new Hono<{ Bindings: Bindings }>();
// 要在實例自己這一側就看得出來,不是等用戶登不進去才發現(#10「寧可明顯失敗」)。
// 只回統計不回內容(帳號數/有沒有 console 帳密/分片數),不洩漏任何 email 或雜湊。
// bundle_version 的既有行為不動(未注入就省略該欄——daemon 對空字串判 stale 是正確的)。
// Arcrun#106leo 08-12 實撞:更新完設定頁變成「無法讀取目前版本」):
// `bundle_version` 只在部署時被注入,而**只有安裝器會注入**——CLI 更新那條路重部署
// 等於把這個標籤洗掉(wrangler deploy 整份覆蓋,toml 沒寫的 var 直接消失)。
// 修在 CLI 那側(cli/src/lib/deploy.ts:既有 var 沿用 + 版本標籤每趟重烙)。
// 這裡只多吐一個 `bundle_commit`:版號是「發行頻道的編號」,commit 才是「真的部了哪份碼」——
// 兩個一起看才有辦法查「標籤有沒有跟成品漂掉」。沒注入就省略該欄(同 bundle_version 的既有行為)。
healthRouter.get('/health', (c) => {
const bundleVersion = c.env.ARCRUN_BUNDLE_VERSION;
const bundleCommit = c.env.ARCRUN_BUNDLE_COMMIT;
return c.json({
ok: true,
...(bundleVersion ? { bundle_version: bundleVersion } : {}),
...(bundleCommit ? { bundle_commit: bundleCommit } : {}),
auth_store: authStoreStatus(c.env),
// arcrun-rag#38/#69/#252026-08-11):安裝器判斷「要不要重推」只比 bundle_version——
// 但這次要修的洞是「installer 從沒注入過 PORTAL_MAIL_RELAY_BASE」,跟 bundle 內容
+210 -7
View File
@@ -132,13 +132,7 @@ function canReadLibrary(userLibraries: string[], library: string): boolean {
// execution_log/execution_log_usageKV 額度事故修復,2026-08-07):workflow 執行紀錄與其內部
// 用量計數器,entry_type 與既有 value/workflow 同層級的內部型別——一併排除,避免用戶搜尋知識時
// 混進執行 log(同層防線:本模組也從不設 metadata_json.embed=true,永不進語意搜尋索引)。
// KV 退休(#16/#17)新增四型:資產定義本體住進 KBDB 之後,它們是「系統的東西」而不是
// 使用者的知識卡——知識瀏覽/搜尋要跟 execution_log 一樣排除,否則 portal 會冒出
// 一堆 workflow_def / api_recipe 汙染結果。
const INTERNAL_ENTRY_TYPES = new Set([
'value', 'workflow', 'execution_log', 'execution_log_usage',
'workflow_def', 'api_recipe', 'auth_recipe', 'prompt_recipe',
]);
const INTERNAL_ENTRY_TYPES = new Set(['value', 'workflow', 'execution_log', 'execution_log_usage']);
export function filterDeprecatedEntries<T extends { metadata_json?: string | null; content?: string | null; entry_type?: string | null }>(
entries: T[],
@@ -659,6 +653,215 @@ portalDataRouter.get('/portal/data/workflows', (c) =>
}),
);
// ═══════════════════════════════════════════════════════════════════════════
// 授權的 AIarcrun-mcp)走的資料面 — 與人類 portal 同一道閘、同一份權限
// ═══════════════════════════════════════════════════════════════════════════
//
// leo 2026-08-12:「人類進 Portal 輸入帳密表示你是主人,可以查到你權限所有東西;
// AI 透過輸入帳密的 MCP 查詢表示是授權的 AI,可以查到主人允許查的任何東西。」
// 「掛上 MCP 並輸入帳密,那個動作本身就是授權」⇒ **下游不得再要求第二次認證**。
//
// 之前的病:MCP 驗完帳密只留下一個布林值,身分當場丟掉(oauth/routes.ts 舊 `loginOk = res.ok`),
// 於是查詢時只好去找一把**服務內部金鑰**KBDB_INTERNAL_TOKEN)直打 KBDB——
// 那條路繞過了本檔上半部所有的庫過濾,等於「誰登入都看到同一格、而且是全部」。
//
// 修法=MCP 改帶**登入者的 portal session token** 打本段端點。所以本段的每一支:
// ① 一律 requirePortalUsersession → 回讀 user record → 停用即時生效),
// ② owner_id / library 由 server 注入,**呼叫端傳什麼都不看**(與上半部同一條紅線:
// 呼叫端自己帶租戶字串=繞過庫過濾),
// ③ 越權與不存在同回 404(不洩存在性)。
//
// 薄殼(rule 07):這裡沒有新能力——template/record/map 的真身都在 KBDB 基本盤,
// 本段只做「權限注入+轉發」,與上半部 search/entries 一模一樣的做法。
/**
* record entry ** `library` slot record **
*
* entry 'general' fallbackentry
* general record contact / workflow_metadata / triplet
* triplet library slot general fallback
* ["kb"] contact
* owner_id server /
*/
function recordLibrary(values: Record<string, unknown> | undefined): string | null {
const lib = values?.library;
return typeof lib === 'string' && lib.trim() ? lib.trim() : null;
}
/** record 可讀?租戶要對;有標 library 的還要在用戶庫集合內。 */
function canReadRecord(
rec: { values?: Record<string, unknown>; owner_id?: string | null },
tenant: string,
libraries: string[],
): boolean {
if ((rec.owner_id ?? '') !== tenant) return false;
const lib = recordLibrary(rec.values);
return lib === null || canReadLibrary(libraries, lib);
}
// GET /portal/data/map — 藏書地圖全館視圖,**只回這個帳號有權限的庫**。
// KBDB 的 /map 對權限無知(它回全館),過濾在這裡做——MCP 不得比 portal 同一個帳號看得更多。
portalDataRouter.get('/portal/data/map', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) {
return c.json({ success: true, libraries: [], count: 0, note: '此帳號尚未被授權任何知識庫,請聯絡管理員。' });
}
const res = await kbdbFetch(c.env, `/map?owner_id=${encodeURIComponent(portalTenant(c.env))}`);
if (!res.ok) {
return new Response(res.body, { status: res.status, headers: { 'Content-Type': 'application/json' } });
}
const body = (await res.json().catch(() => null)) as { libraries?: { library?: string }[] } | null;
if (!body || !Array.isArray(body.libraries)) {
return c.json({ error: '藏書地圖讀取失敗:KBDB 回應不是預期的 libraries 清單' }, 502);
}
const allowed = body.libraries.filter(
(l) => typeof l?.library === 'string' && canReadLibrary(libraries, l.library),
);
return c.json({ success: true, libraries: allowed, count: allowed.length });
}),
);
// GET /portal/data/map/:library — 單庫詳圖。無權該庫 → 與不存在同回 404(不洩存在性)。
portalDataRouter.get('/portal/data/map/:library', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
const library = c.req.param('library');
if (!canReadLibrary(libraries, library)) return notFound(c);
const res = await kbdbFetch(
c.env,
`/map/${encodeURIComponent(library)}?owner_id=${encodeURIComponent(portalTenant(c.env))}`,
);
if (res.status === 404) return notFound(c);
if (!res.ok) return c.json({ error: `KBDB 回錯(HTTP ${res.status}` }, 502);
return new Response(res.body, { status: 200, headers: { 'Content-Type': 'application/json' } });
}),
);
// GET /portal/data/templates — template 清單。
// template=虛擬表定義(schema),**全域共享不分租戶**kbdb-proxy 同一裁定,leo 2026-06-14):
// 它描述「資料長什麼形狀」,不含任何人的內容。內容的隔離在 records/entries 那層。
portalDataRouter.get('/portal/data/templates', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const res = await kbdbFetch(c.env, '/templates');
if (!res.ok) return c.json({ error: `KBDB 回錯(HTTP ${res.status}` }, 502);
return new Response(res.body, { status: 200, headers: { 'Content-Type': 'application/json' } });
}),
);
// POST /portal/data/templates — 建 templatename + slots)。
// 鐵律:這是「虛擬表定義」,不是建真的資料表;KBDB 不提供建表/SQL。
// created_by 記租戶(溯源),template 本身全域可見可用。
portalDataRouter.post('/portal/data/templates', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const body = (await c.req.json().catch(() => null)) as
| { name?: unknown; slots?: unknown; description?: unknown }
| null;
if (!body || typeof body.name !== 'string' || !body.name.trim() || !Array.isArray(body.slots)) {
return c.json({ error: 'name 與 slots[] 必填' }, 400);
}
const res = await kbdbFetch(c.env, '/templates', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: body.name,
slots: body.slots,
description: typeof body.description === 'string' ? body.description : undefined,
created_by: portalTenant(c.env),
}),
});
return new Response(res.body, { status: res.status, headers: { 'Content-Type': 'application/json' } });
}),
);
// GET /portal/data/records/by-template/:template — 某 template 底下的 record。
// server 注入 owner_id(呼叫端傳的一律忽略);有標 library 的再逐筆過濾。
portalDataRouter.get('/portal/data/records/by-template/:template', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) return c.json({ success: true, records: [], count: 0 });
const tenant = portalTenant(c.env);
const res = await kbdbFetch(
c.env,
`/records/by-template/${encodeURIComponent(c.req.param('template'))}?owner_id=${encodeURIComponent(tenant)}`,
);
if (!res.ok) return c.json({ error: `KBDB 回錯(HTTP ${res.status}` }, 502);
const body = (await res.json().catch(() => null)) as
| { records?: { values?: Record<string, unknown>; owner_id?: string | null }[] }
| null;
if (!body || !Array.isArray(body.records)) {
return c.json({ error: 'record 讀取失敗:KBDB 回應不是預期的 records 清單' }, 502);
}
// KBDB 已按 owner_id 過濾;這裡再守一次庫(縱深防禦,且舊部署若回多了不會外洩)。
const records = body.records.filter((r) => canReadRecord(r, tenant, libraries));
return c.json({ success: true, records, count: records.length });
}),
);
// GET /portal/data/records/:recordId — 單筆 record。
// 逐筆驗歸屬(owner_id 必須是本實例租戶)+ 驗庫;兩者不符與不存在同回 404。
portalDataRouter.get('/portal/data/records/:recordId', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) return notFound(c);
const res = await kbdbFetch(c.env, `/records/${encodeURIComponent(c.req.param('recordId'))}`);
if (res.status === 404) return notFound(c);
if (!res.ok) return c.json({ error: `KBDB 回錯(HTTP ${res.status}` }, 502);
const body = (await res.json().catch(() => null)) as
| { record?: { values?: Record<string, unknown>; owner_id?: string | null } }
| null;
const record = body?.record;
if (!record) return notFound(c);
if (!canReadRecord(record, portalTenant(c.env), libraries)) return notFound(c);
return c.json({ success: true, record });
}),
);
// POST /portal/data/records — 依 template 填一筆 record。
// owner_id **一律由 server 定死成本實例租戶**(呼叫端傳的忽略)——寫入端若讓呼叫端挑歸屬,
// 等於開一扇「把資料寫進別人格子」的門。要寫進某個庫(values.library)必須有該庫權限。
portalDataRouter.post('/portal/data/records', (c) =>
run(c, async () => {
const auth = await requirePortalUser(c);
if (!auth.ok) return auth.res;
const libraries = parseLibraries(auth.user.values.libraries);
if (libraries.length === 0) {
return c.json({ error: '此帳號尚未被授權任何知識庫,無法寫入' }, 403);
}
const body = (await c.req.json().catch(() => null)) as
| { template?: unknown; values?: unknown }
| null;
if (!body || typeof body.template !== 'string' || !body.template.trim() || !body.values || typeof body.values !== 'object') {
return c.json({ error: 'template 與 values 必填' }, 400);
}
const values = body.values as Record<string, unknown>;
const targetLib = recordLibrary(values);
if (targetLib !== null && !canReadLibrary(libraries, targetLib)) {
// 寫入越庫是**明確拒絕**(403),不套讀取那條 404 不洩存在性的規則:
// 庫名是呼叫端自己指定的,這裡沒有「洩漏某庫存在」的問題,講清楚才可修正。
return c.json({ error: `無「${targetLib}」庫的權限,不能寫入該庫` }, 403);
}
const res = await kbdbFetch(c.env, '/records', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template: body.template, values, owner_id: portalTenant(c.env) }),
});
return new Response(res.body, { status: res.status, headers: { 'Content-Type': 'application/json' } });
}),
);
// GET /portal/data/diagnostics — 檢修孔(2026-08-07 leo 直接指令):
//
// 「可以很簡單,就是一顆按鈕在設定裡,他按鈕下載一個檔案,把檔案發給我,你看那個檔。」
+5
View File
@@ -677,6 +677,11 @@ portalRouter.post('/portal/login', (c) =>
display_name: rec.values.display_name ?? '',
role: rec.values.role ?? 'user',
libraries: parseLibraries(rec.values.libraries),
// session 還能活多久(秒)。**非機密**(是這台實例的 TTL 設定,不是任何人的憑據),
// 但呼叫端需要它才能把自己發的憑證對齊這個上限——arcrun-mcp 用它把 OAuth
// access_token 的 TTL 夾到 min(自己的 TTL, 這個值):否則 MCP token 活 30 天、
// 底下的 portal session 7 天就死,使用者會在第 8 天遇到「連著卻查不到」的鬼打牆。
session_expires_in: sessionTtl(c.env),
// 絕不回租戶字串(design §3.3portal_user 拿到租戶字串就能繞過庫 filter 直打 /kbdb/*
});
}),
-199
View File
@@ -1,199 +0,0 @@
/**
* /storage KV KBDB
*
* KV 退Leo/Arcrun#16 + #17
* 西****
* ****
* GET /storage/audit
* POST /storage/migrate-to-kbdb
*
*
* 1. **** KV
* KV 退
* 2. ****KBDB entry idasset-keys.ts
* missing
* 3. ****
* mindset §7 after before
*
* flag AI ** cron**
*KV list 1000/ list
*/
import { Hono } from 'hono';
import type { Bindings } from '../types';
import { unwrapKv } from '../lib/durable-store';
import { classifyAssetKey, type AssetEntryType } from '../lib/asset-keys';
export const storageRouter = new Hono<{ Bindings: Bindings }>();
/** 本卷管的四類資產,以及它們住在哪顆 KV。 */
const ASSET_SOURCES: Array<{ binding: 'WEBHOOKS' | 'RECIPES' }> = [
{ binding: 'WEBHOOKS' },
{ binding: 'RECIPES' },
];
interface ScannedKey {
key: string;
binding: 'WEBHOOKS' | 'RECIPES';
entry_type: AssetEntryType;
entry_id: string;
}
/** 掃一顆 KV 的全部 key(跟著 cursor 走完,不只第一頁),挑出屬於資產的。 */
async function scanAssetKeys(kv: KVNamespace, binding: 'WEBHOOKS' | 'RECIPES'): Promise<ScannedKey[]> {
const found: ScannedKey[] = [];
let cursor: string | undefined;
do {
const page = await kv.list(cursor ? { cursor } : {});
for (const k of page.keys) {
const ref = classifyAssetKey(k.name);
if (ref) found.push({ key: k.name, binding, entry_type: ref.entry_type, entry_id: ref.entry_id });
}
cursor = page.list_complete ? undefined : page.cursor;
} while (cursor);
return found;
}
function kbdb(env: Bindings): { base: string; headers: Record<string, string> } {
const base = (env.KBDB_BASE_URL ?? 'https://arcrun-kbdb.uncle6-me.workers.dev').replace(/\/$/, '');
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (env.KBDB_INTERNAL_TOKEN) headers['Authorization'] = `Bearer ${env.KBDB_INTERNAL_TOKEN}`;
return { base, headers };
}
/** KBDB 端某型別現有的 entry id 集合(用來算「哪幾筆還沒搬過去」)。 */
async function kbdbExistingIds(env: Bindings, entryType: AssetEntryType): Promise<Set<string>> {
const { base, headers } = kbdb(env);
const res = await fetch(`${base}/entries?entry_type=${encodeURIComponent(entryType)}&limit=1000`, { headers });
if (!res.ok) throw new Error(`KBDB 讀取失敗(${entryType}):HTTP ${res.status}`);
const json = (await res.json().catch(() => null)) as { entries?: Array<{ id: string }> } | null;
return new Set((json?.entries ?? []).map((e) => e.id));
}
const ASSET_TYPES: AssetEntryType[] = ['workflow_def', 'api_recipe', 'auth_recipe', 'prompt_recipe'];
interface Tally {
kv: Record<string, number>;
kbdb: Record<string, number>;
missing_in_kbdb: string[];
}
/** 兩邊各數一次,並列出「KV 有、KBDB 沒有」的那幾筆。 */
async function tally(env: Bindings): Promise<Tally> {
const scanned: ScannedKey[] = [];
for (const src of ASSET_SOURCES) {
const binding = env[src.binding];
if (!binding) continue;
scanned.push(...(await scanAssetKeys(unwrapKv(binding), src.binding)));
}
const kvCounts: Record<string, number> = {};
for (const t of ASSET_TYPES) kvCounts[t] = 0;
for (const s of scanned) kvCounts[s.entry_type] += 1;
const kbdbCounts: Record<string, number> = {};
const existing = new Map<AssetEntryType, Set<string>>();
for (const t of ASSET_TYPES) {
const ids = await kbdbExistingIds(env, t);
existing.set(t, ids);
kbdbCounts[t] = ids.size;
}
const missing = scanned
.filter((s) => !existing.get(s.entry_type)!.has(s.entry_id))
.map((s) => s.key);
return { kv: kvCounts, kbdb: kbdbCounts, missing_in_kbdb: missing };
}
// GET /storage/audit — 唯讀盤點。搬之前先看、搬之後再看,兩次數字自己會說話。
storageRouter.get('/storage/audit', async (c) => {
try {
const t = await tally(c.env);
return c.json({
success: true,
kv_asset_counts: t.kv,
kbdb_asset_counts: t.kbdb,
missing_in_kbdb: t.missing_in_kbdb,
missing_count: t.missing_in_kbdb.length,
verdict:
t.missing_in_kbdb.length === 0
? 'KV 裡的資產在 KBDB 都有一份——換掉 KV 不會弄丟東西。'
: `還有 ${t.missing_in_kbdb.length} 筆只存在於 KV。跑 POST /storage/migrate-to-kbdb 把它們搬過去。`,
});
} catch (e) {
// 誠實:盤點本身失敗就說失敗,不回一個看起來很乾淨的 0(那會被讀成「沒東西要搬」)。
return c.json({ success: false, error: e instanceof Error ? e.message : String(e) }, 502);
}
});
// POST /storage/migrate-to-kbdb — 把 KV 裡的資產補進 KBDB。只增不刪、冪等、可重跑。
// body(都可省略):{ dry_run?: boolean }
storageRouter.post('/storage/migrate-to-kbdb', async (c) => {
const body = (await c.req.json().catch(() => ({}))) as { dry_run?: boolean };
const dryRun = body.dry_run === true;
let before: Tally;
try {
before = await tally(c.env);
} catch (e) {
return c.json({ success: false, error: `搬遷前盤點失敗,未動任何資料:${e instanceof Error ? e.message : String(e)}` }, 502);
}
if (dryRun) {
return c.json({
success: true,
dry_run: true,
before: { kv: before.kv, kbdb: before.kbdb },
would_migrate: before.missing_in_kbdb,
would_migrate_count: before.missing_in_kbdb.length,
});
}
const migrated: string[] = [];
const errors: Array<{ key: string; error: string }> = [];
for (const src of ASSET_SOURCES) {
const wrapped = c.env[src.binding];
if (!wrapped) continue;
const raw = unwrapKv(wrapped);
for (const s of await scanAssetKeys(raw, src.binding)) {
try {
// 從**真** KV 讀原值,再用包裝過的 binding 寫回去——寫入路徑就是平常那條
//(先 KBDB 後快取),所以搬遷用的是跟日常寫入完全同一段程式碼,不另開一條會漂移的路。
const value = await raw.get(s.key, 'text');
if (value === null) continue; // 掃到當下剛好被刪:不是錯,跳過
await wrapped.put(s.key, value);
migrated.push(s.key);
} catch (e) {
errors.push({ key: s.key, error: e instanceof Error ? e.message : String(e) });
}
}
}
let after: Tally | null = null;
let afterError: string | null = null;
try {
after = await tally(c.env);
} catch (e) {
afterError = e instanceof Error ? e.message : String(e);
}
const clean = errors.length === 0 && after !== null && after.missing_in_kbdb.length === 0;
return c.json(
{
success: clean,
before: { kv: before.kv, kbdb: before.kbdb, missing_in_kbdb: before.missing_in_kbdb.length },
migrated,
migrated_count: migrated.length,
errors,
after: after
? { kv: after.kv, kbdb: after.kbdb, missing_in_kbdb: after.missing_in_kbdb }
: { error: afterError },
verdict: clean
? '搬完了:KV 裡的每一筆資產在 KBDB 都有對應的一列(missing 歸零)。KV 原始資料原封不動保留。'
: '**沒有搬乾淨**——看 errors 與 after.missing_in_kbdb。修掉原因後可以直接重跑(冪等,不會產生重複)。',
},
clean ? 200 : 500,
);
});
+9 -3
View File
@@ -75,6 +75,13 @@ export type Bindings = {
* dev undefined/health
*/
ARCRUN_BUNDLE_VERSION?: string;
/**
* Arcrun#106 commit40 sha
* `ARCRUN_BUNDLE_VERSION` ****semverPortal/daemon
* ****
* `acr init/update`cli/src/lib/deploy.ts var /health
*/
ARCRUN_BUNDLE_COMMIT?: string;
// Platform telemetry api_key(可選,wrangler secret
// 對應 SDD .agents/specs/llm-interface/ M1.2
// 設了會把 agent-telemetry block 都聚集在 platform_telemetry user_id 下
@@ -103,9 +110,8 @@ export type Bindings = {
GITEA_TOKEN?: string; // wrangler secret(建議唯讀 scope token
GITEA_SPRINT_REPO?: string; // 預設 Leo/InkStoneCo
GITEA_SPRINT_DIR?: string; // 預設 system-dev/docs/3-specs/autonomy-dispatch
// 安裝器部署時注入的 bundle 版本(格式 "YYYY-MM-DD/commit",老實例無此 var)。
// daemon 比對此值決定是否提示用戶更新(/health 曝露,缺 var 時回空字串)。
ARCRUN_BUNDLE_VERSION?: string;
// ARCRUN_BUNDLE_VERSION 原本在這裡重複宣告了一次——TS2300 重複識別字,
// #106 順手併回上面那一處,說明同源,行為零變化。)
// MCP access_token 存活秒數的「顯示鏡像」(console 設定頁 MCP TTL 佔位區塊用)。
// 真相住在 mcp worker 的同名 envmcp/src/types.ts,預設 259200030 天);cypher 這份
// 只供顯示,兩處部署時要一致(#32 形態 config 同步教訓)。未設 → 頁面如實標「預設值」。
-91
View File
@@ -1,91 +0,0 @@
/**
* asset-keys KV key 使
*
* KV 退Leo/Arcrun#16 + #17 KV / KBDB /
* 西****
*
*
* - 2026-08-12
* - KBDB
*/
import { describe, it, expect } from 'vitest';
import { classifyAssetKey, classifyListPrefix, assetKvKey } from '../src/lib/asset-keys';
import { CRON_INDEX_KEY } from '../src/lib/cron-index';
describe('classifyAssetKey — 資產', () => {
it('具名工作流 {api_key}:wf:{name} → workflow_def,租戶與名字都拆得出來', () => {
const ref = classifyAssetKey('leo:wf:rag_chat');
expect(ref).not.toBeNull();
expect(ref!.entry_type).toBe('workflow_def');
expect(ref!.owner_id).toBe('leo');
expect(ref!.page_name).toBe('rag_chat');
expect(ref!.kv_key).toBe('leo:wf:rag_chat');
});
it('api recipeuuid key 與 migration 前的 canonical key 都算資產)', () => {
expect(classifyAssetKey('recipe:8f3b-uuid')!.entry_type).toBe('api_recipe');
expect(classifyAssetKey('recipe:telegram_send')!.entry_type).toBe('api_recipe');
});
it('auth recipe / prompt recipe', () => {
expect(classifyAssetKey('auth_recipe:notion')!.entry_type).toBe('auth_recipe');
expect(classifyAssetKey('auth_recipe:notion')!.page_name).toBe('notion');
expect(classifyAssetKey('prompt_recipe:wiki_synthesis')!.entry_type).toBe('prompt_recipe');
});
it('同一個 key 永遠對到同一個 entry_id(冪等的根據——重跑遷移不會長出重複列)', () => {
expect(classifyAssetKey('leo:wf:a')!.entry_id).toBe(classifyAssetKey('leo:wf:a')!.entry_id);
expect(classifyAssetKey('leo:wf:a')!.entry_id).not.toBe(classifyAssetKey('evan:wf:a')!.entry_id);
});
});
describe('classifyAssetKey — 衍生資料不可誤收', () => {
it('recipe 反查索引 idx:* 全部不是資產(算得回來,見 rehydrateRecipeIndices', () => {
expect(classifyAssetKey('idx:rec_f7e2a1b3')).toBeNull();
expect(classifyAssetKey('idx:canonical:telegram_send')).toBeNull();
expect(classifyAssetKey('idx:installed:telegram_send')).toBeNull();
});
it('cron 索引不是資產', () => {
expect(classifyAssetKey(CRON_INDEX_KEY)).toBeNull();
expect(classifyAssetKey('cron-idx:leo:daily')).toBeNull();
});
it('匿名 webhook token / 其他暫存 key 不是資產(本卷不碰,非漏收)', () => {
expect(classifyAssetKey('a1b2c3d4e5f6')).toBeNull();
expect(classifyAssetKey('daemon-active:leo')).toBeNull();
});
it('殘缺的 key 不當資產(寧可退回原本的 KV 行為,也不要建出半截的列)', () => {
expect(classifyAssetKey('recipe:')).toBeNull();
expect(classifyAssetKey('auth_recipe:')).toBeNull();
expect(classifyAssetKey(':wf:orphan')).toBeNull();
expect(classifyAssetKey('leo:wf:')).toBeNull();
});
});
describe('assetKvKey — 從 KBDB 反推回 KV key(回填快取與 list 都靠它)', () => {
it('四型都能原路折返', () => {
for (const key of ['leo:wf:rag_chat', 'recipe:telegram_send', 'auth_recipe:notion', 'prompt_recipe:x']) {
const ref = classifyAssetKey(key)!;
expect(assetKvKey(ref.entry_type, ref.owner_id, ref.page_name)).toBe(key);
}
});
});
describe('classifyListPrefix — 列舉走哪一邊', () => {
it('租戶工作流列舉 → 走 KBDB(帶 owner', () => {
expect(classifyListPrefix('leo:wf:')).toEqual({ entry_type: 'workflow_def', owner_id: 'leo' });
});
it('recipe / auth_recipe 列舉 → 走 KBDB', () => {
expect(classifyListPrefix('recipe:')).toEqual({ entry_type: 'api_recipe' });
expect(classifyListPrefix('auth_recipe:')).toEqual({ entry_type: 'auth_recipe' });
});
it('索引與無 prefix 的全域列舉 → 維持原本的 KV 行為', () => {
expect(classifyListPrefix('idx:')).toBeNull();
expect(classifyListPrefix('cron-idx:')).toBeNull();
expect(classifyListPrefix(undefined)).toBeNull();
});
});
+29
View File
@@ -26,4 +26,33 @@ describe('GET /health — bundle_version 欄位', () => {
expect(data.ok).toBe(true);
expect(data.bundle_version).toBe('2026-07-28/6d06162');
});
// Arcrun#106CLI 更新那條路會多烙一個 commit(版號=發行頻道編號,commit=真的部了哪份碼)。
it('有 ARCRUN_BUNDLE_COMMIT 時一起回(acr update 注入情境)', async () => {
const fakeEnv = {
ARCRUN_BUNDLE_VERSION: '1.4.41',
ARCRUN_BUNDLE_COMMIT: 'f87d0e92f49690253e7c89c5badc82a08eb5d21b',
} as unknown as Bindings;
const res = await healthRouter.fetch(
new Request('http://localhost/health'),
fakeEnv,
{} as ExecutionContext,
);
const data = await res.json() as { bundle_version: string; bundle_commit: string };
expect(data.bundle_version).toBe('1.4.41');
expect(data.bundle_commit).toBe('f87d0e92f49690253e7c89c5badc82a08eb5d21b');
});
// 安裝器那條路沒有這個 var(回歸:不能因為多了新欄位就讓舊路徑多吐一個空字串出來)。
it('沒 ARCRUN_BUNDLE_COMMIT 就省略該欄(安裝器路徑不受影響)', async () => {
const fakeEnv = { ARCRUN_BUNDLE_VERSION: '1.4.41' } as unknown as Bindings;
const res = await healthRouter.fetch(
new Request('http://localhost/health'),
fakeEnv,
{} as ExecutionContext,
);
const data = await res.json() as { bundle_version: string; bundle_commit?: string };
expect(data.bundle_version).toBe('1.4.41');
expect(data.bundle_commit).toBeUndefined();
});
});
+208
View File
@@ -232,6 +232,214 @@ describe('GET /portal/data/entries/:id(逐筆驗庫)', () => {
});
});
// ═══════════════ 3b. 授權的 AI(arcrun-mcp)走的資料面 ═══════════════
//
// leo 2026-08-12:「AI 透過輸入帳密的 MCP 查詢表示是授權的 AI,可以查到主人允許查的任何東西。」
// ⇒ 這幾支端點與人類走的 search/entries 是同一道閘:同一個 session、同一份庫權限、
// 同樣「呼叫端自帶 owner_id 一律不生效」、同樣「越權與不存在同一句 404」。
describe('藏書地圖 /portal/data/mapMCP 走的那條)', () => {
it('只回這個帳號有權限的庫;全館其他庫不出現在回應裡', async () => {
await seedSession('tok-m1', 'rec_1');
mockGetRecord('rec_1', userValues({ libraries: '["finance"]' }));
fetchMock
.get(KBDB)
.intercept({ path: (p: string) => p.startsWith('/map?'), method: 'GET' })
.reply(200, {
success: true,
libraries: [
{ library: 'finance', narrative: '財務', top_entities: [], triplet_count: 3 },
{ library: 'hr', narrative: '人資', top_entities: [], triplet_count: 9 },
],
count: 2,
});
const res = await get('/portal/data/map', { Authorization: 'Bearer tok-m1' });
expect(res.status).toBe(200);
const data = (await res.json()) as { libraries: { library: string }[]; count: number };
expect(data.libraries.map((l) => l.library)).toEqual(['finance']);
expect(data.count).toBe(1);
});
it('["*"] 全庫 → 全部庫都回', async () => {
await seedSession('tok-m2', 'rec_2');
mockGetRecord('rec_2', userValues({ libraries: '["*"]' }));
fetchMock
.get(KBDB)
.intercept({ path: (p: string) => p.startsWith('/map?'), method: 'GET' })
.reply(200, {
success: true,
libraries: [
{ library: 'finance', narrative: '', top_entities: [], triplet_count: 3 },
{ library: 'hr', narrative: '', top_entities: [], triplet_count: 9 },
],
count: 2,
});
const res = await get('/portal/data/map', { Authorization: 'Bearer tok-m2' });
const data = (await res.json()) as { libraries: { library: string }[] };
expect(data.libraries.map((l) => l.library)).toEqual(['finance', 'hr']);
});
it('庫集合為空 → 誠實空結果+說明,不打 KBDB', async () => {
await seedSession('tok-m3', 'rec_3');
mockGetRecord('rec_3', userValues({ libraries: '[]' }));
const res = await get('/portal/data/map', { Authorization: 'Bearer tok-m3' });
expect(res.status).toBe(200);
const data = (await res.json()) as { count: number; note?: string };
expect(data.count).toBe(0);
expect(data.note).toContain('尚未被授權');
});
it('單庫詳圖:無權該庫 → 404 同一句(不打 KBDB,不洩該庫存不存在)', async () => {
await seedSession('tok-m4', 'rec_4');
mockGetRecord('rec_4', userValues({ libraries: '["finance"]' }));
const res = await get('/portal/data/map/hr', { Authorization: 'Bearer tok-m4' });
expect(res.status).toBe(404);
expect(((await res.json()) as { error: string }).error).toBe('找不到這筆資料');
});
it('單庫詳圖:有權該庫 → 200 轉發', async () => {
await seedSession('tok-m5', 'rec_5');
mockGetRecord('rec_5', userValues({ libraries: '["finance"]' }));
fetchMock
.get(KBDB)
.intercept({ path: (p: string) => p.startsWith('/map/finance'), method: 'GET' })
.reply(200, { success: true, map: { library: 'finance', triplet_count: 3 } });
const res = await get('/portal/data/map/finance', { Authorization: 'Bearer tok-m5' });
expect(res.status).toBe(200);
});
it('未登入 → 401', async () => {
expect((await get('/portal/data/map')).status).toBe(401);
});
});
describe('結構化資料 /portal/data/records、/portal/data/templatesMCP 走的那條)', () => {
it('by-templateserver 注入 owner_idcaller 自帶的被靜默覆蓋(繞不過)', async () => {
await seedSession('tok-r1', 'rec_1');
mockGetRecord('rec_1', userValues({ libraries: '["*"]' }));
let captured = '';
fetchMock
.get(KBDB)
.intercept({
path: (p: string) => {
if (!p.startsWith('/records/by-template/contact')) return false;
captured = p;
return true;
},
method: 'GET',
})
.reply(200, { success: true, records: [], count: 0 });
const res = await get('/portal/data/records/by-template/contact?owner_id=someone-else', {
Authorization: 'Bearer tok-r1',
});
expect(res.status).toBe(200);
expect(new URL(`http://x${captured}`).searchParams.get('owner_id')).toBe(TENANT);
});
it('by-template:有標 library 的 record 越庫的被濾掉;沒標 library 的照回', async () => {
await seedSession('tok-r2', 'rec_2');
mockGetRecord('rec_2', userValues({ libraries: '["finance"]' }));
fetchMock
.get(KBDB)
.intercept({ path: (p: string) => p.startsWith('/records/by-template/triplet'), method: 'GET' })
.reply(200, {
success: true,
records: [
{ record_id: 'r1', owner_id: TENANT, values: { library: 'finance', subject: 'A' } },
{ record_id: 'r2', owner_id: TENANT, values: { library: 'hr', subject: 'B' } },
{ record_id: 'r3', owner_id: TENANT, values: { subject: 'C' } }, // 沒標庫=結構化資料列
],
count: 3,
});
const res = await get('/portal/data/records/by-template/triplet', { Authorization: 'Bearer tok-r2' });
const data = (await res.json()) as { records: { record_id: string }[] };
expect(data.records.map((r) => r.record_id)).toEqual(['r1', 'r3']);
});
it('單筆:別的租戶的 record → 404 同一句(就算全庫權限也擋)', async () => {
await seedSession('tok-r3', 'rec_3');
mockGetRecord('rec_3', userValues({ libraries: '["*"]' }));
fetchMock
.get(KBDB)
.intercept({ path: '/records/r_other', method: 'GET' })
.reply(200, { success: true, record: { record_id: 'r_other', owner_id: 'other-tenant', values: {} } });
const res = await get('/portal/data/records/r_other', { Authorization: 'Bearer tok-r3' });
expect(res.status).toBe(404);
expect(((await res.json()) as { error: string }).error).toBe('找不到這筆資料');
});
it('單筆:越庫的 record → 404 同一句;有權的 → 200', async () => {
await seedSession('tok-r4', 'rec_4');
mockGetRecord('rec_4', userValues({ libraries: '["finance"]' }));
fetchMock
.get(KBDB)
.intercept({ path: '/records/r_hr', method: 'GET' })
.reply(200, { success: true, record: { record_id: 'r_hr', owner_id: TENANT, values: { library: 'hr' } } });
expect((await get('/portal/data/records/r_hr', { Authorization: 'Bearer tok-r4' })).status).toBe(404);
await seedSession('tok-r5', 'rec_5');
mockGetRecord('rec_5', userValues({ libraries: '["finance"]' }));
fetchMock
.get(KBDB)
.intercept({ path: '/records/r_fin', method: 'GET' })
.reply(200, { success: true, record: { record_id: 'r_fin', owner_id: TENANT, values: { library: 'finance' } } });
expect((await get('/portal/data/records/r_fin', { Authorization: 'Bearer tok-r5' })).status).toBe(200);
});
it('寫入:owner_id 由 server 定死,呼叫端塞的不算', async () => {
await seedSession('tok-r6', 'rec_6');
mockGetRecord('rec_6', userValues({ libraries: '["*"]' }));
let body: Record<string, unknown> = {};
fetchMock
.get(KBDB)
.intercept({
path: '/records',
method: 'POST',
body: (b: string) => {
body = JSON.parse(b) as Record<string, unknown>;
return true;
},
})
.reply(200, { success: true, record: { record_id: 'r_new' } });
const res = await SELF.fetch('http://localhost/portal/data/records', {
method: 'POST',
headers: { Authorization: 'Bearer tok-r6', 'Content-Type': 'application/json' },
body: JSON.stringify({ template: 'contact', values: { name: 'Leo' }, owner_id: 'someone-else' }),
});
expect(res.status).toBe(200);
expect(body.owner_id).toBe(TENANT);
});
it('寫入越庫 → 403(明確拒絕,庫名是呼叫端自己指定的,沒有存在性可洩)', async () => {
await seedSession('tok-r7', 'rec_7');
mockGetRecord('rec_7', userValues({ libraries: '["finance"]' }));
const res = await SELF.fetch('http://localhost/portal/data/records', {
method: 'POST',
headers: { Authorization: 'Bearer tok-r7', 'Content-Type': 'application/json' },
body: JSON.stringify({ template: 'note', values: { library: 'hr', body: 'x' } }),
});
expect(res.status).toBe(403);
});
it('templates 全域共享(schema 非內容):登入即可列', async () => {
await seedSession('tok-t1', 'rec_t1');
mockGetRecord('rec_t1', userValues({ libraries: '["finance"]' }));
fetchMock
.get(KBDB)
.intercept({ path: '/templates', method: 'GET' })
.reply(200, { success: true, templates: [{ id: 'tpl1', name: 'contact' }], count: 1 });
const res = await get('/portal/data/templates', { Authorization: 'Bearer tok-t1' });
expect(res.status).toBe(200);
expect(((await res.json()) as { count: number }).count).toBe(1);
});
it('未登入 → 401records / templates 都是)', async () => {
expect((await get('/portal/data/templates')).status).toBe(401);
expect((await get('/portal/data/records/by-template/contact')).status).toBe(401);
expect((await get('/portal/data/records/r1')).status).toBe(401);
});
});
// ═══════════════ 4. graph D-4 粗閘 ═══════════════
describe('GET /portal/data/graph/neighbors/:nameD-4 粗閘)', () => {
@@ -1,45 +0,0 @@
-- arcrun 資產型別 template seed — KV 退休(Leo/Arcrun#16 + #17
--
-- 為什麼有這一檔(leo 2026-08-12 原話):
-- 「我要的是寫進 KBDB,不是 KV,他的 Recipes、Cypher 是一段話,文字,數據,一個 entry」
-- 「如果零件和工作流的 recipe 不見了,是很可怕的事情」
-- 同一天(2026-08-12)真的發作過:一次例行更新讓使用者的九支工作流在畫面上全部消失
-- (根因見 cli/src/lib/resource-resolver.ts 檔頭 Arcrun#97——舊 deploy 會照名字新建一顆空 KV
-- 再綁上去)。#97 修的是「不要再把 worker 綁到空的資源上」;本卷修的是更根本的一句:
-- **使用者的資產本來就不該只存在於一個會被換掉的暫存層裡。**
--
-- KBDB 鐵律(leo 2026-06-14D38):三張表打天下,永遠不加新 table,新資料類型一律用 template。
-- 本檔**零 schema 異動**——只 INSERT OR IGNORE 四列 template 定義,手法與同目錄
-- 0003_library_map.sql / 0004_execution_log_template.sql 完全相同。
--
-- 儲存精神比照 0004execution_log)與 recipe-stattemplate 只負責「schema 文件化 +
-- GET /templates 可發現」,實際一筆資產是 entries 表的**一列**——
-- entry_type = 'workflow_def' | 'api_recipe' | 'auth_recipe' | 'prompt_recipe'
-- owner_id = 租戶(workflow 才有;recipe 是整台實例共用的庫,故為 NULL)
-- page_name = 該型別的自然鍵(workflow 名 / recipe uuid / service 名)
-- content = 給人看也給語意搜尋看的一句描述
-- metadata_json = 定義本體(graph / endpoint / inject … 原樣 JSON
-- ——不走 entry_values 全展開的多列 record:一支 workflow 的 graph 是一整包巢狀 JSON
-- 拆成 slot 多列既不會變得比較好查,反而讓「一筆資產=一列」這件事不再成立
-- recipe_stat 與 execution_log 早已示範「template 存在 + entries 直接存」這個模式合法)。
--
-- 讀寫一律走 HTTP API/entries、/entries/:id),呼叫端是 cypher-executor 的
-- src/lib/durable-store.ts。牆外沒有任何一行 SQL。
INSERT OR IGNORE INTO templates (id, name, description, slots_json, created_by)
VALUES
('tpl-workflow-def', 'workflow_def',
'工作流定義本體(KV 退休 #17)。一支工作流=entries 一列;graph/config/cron_expr 打包進 metadata_jsonWEBHOOKS KV 降為可丟棄的快取',
'["name","description","graph","config","cron_expr","created_at"]', 'system'),
('tpl-api-recipe', 'api_recipe',
'API recipe 定義本體(KV 退休 #16)。一份 recipeentries 一列;endpoint/headers/body/auth 等打包進 metadata_jsonRECIPES KV 降為快取。idx:* 反查索引屬衍生資料,不進 KBDB,由 durable-store 從本型別重建',
'["uuid","canonical_id","hash_id","author","endpoint","method","auth_service","installed"]', 'system'),
('tpl-auth-recipe', 'auth_recipe',
'Auth recipe 定義本體(KV 退休 #16)。一個服務一列;primitive/base_url/required_secrets/inject 打包進 metadata_json。只存「怎麼認證」,不存任何密文(憑證明文在 CF Workers Secrets,見 .claude/rules/01-tech-stack.md',
'["service","primitive","base_url","version","required_secrets","inject"]', 'system'),
('tpl-prompt-recipe', 'prompt_recipe',
'Prompt recipe 定義本體(KV 退休 #16)。一份 prompt recipeentries 一列,定義打包進 metadata_json',
'["name","definition"]', 'system');
@@ -0,0 +1,25 @@
-- credential template seedD38 圍牆修復,總管交辦,2026-08-07)
-- SDD:無專屬 SDDD38 事故修復任務,見 system-dev/wiki/decisions-summary.md D38 段)。
--
-- D38 鐵律(leo 2026-06-14 立、2026-08-07 擴大):KBDB 三張表打天下,永遠不加新表;
-- 新資料類型一律用 template + entries,同 0003_library_map.sql / 0004_execution_log_template.sql
-- 的手法——對 templates 表 INSERT OR IGNORE 一列定義,不建新表、不動既有表的結構。
--
-- 這是「credential 目錄」的第二個家:原本 0002_credentials.sql 在 KBDB 裡多開了一張
-- 獨立表(違規,見 kbdb-usage skill「反例」),本檔 + 0006_drop_credentials_table.sql
-- 把它改回三張表的形狀——一筆 credentialentries 表一列(entry_type='credential'
-- page_name=name 當冪等鍵,owner_id=api_key 做租戶隔離,其餘欄位打包進 metadata_json),
-- 儲存精神比照既有 recipe_stat / execution_logtemplate 只負責文件化,實際資料不走
-- entry_values 全展開的多列 record)。
--
-- 密文本體不在這裡:值仍住在 CF Workers per-script Secrets(掛在 cypher worker 上,管理
-- API 唯寫,D19「擁有目錄,不擁有內容物」不變)。這張 template 定義的 slots 全部是目錄
-- 欄位,零密文——與舊 0002_credentials.sql 的欄位定義一字不變,只是換了個家。
INSERT OR IGNORE INTO templates (id, name, description, slots_json, created_by)
VALUES (
'tpl-credential',
'credential',
'credential 目錄(D38 圍牆修復:改走 entries 表 entry_type=credential,取代舊 credentials 表;零密文,密文本體住 Workers per-script Secrets',
'["name","service","sensitivity","secret_ref","last_used_at"]',
'system'
);
@@ -0,0 +1,47 @@
-- 退役 credentials 表(D38 圍牆修復,總管交辦,2026-08-07)
-- SDD:無專屬 SDDD38 事故修復任務,見 system-dev/wiki/decisions-summary.md D38 段)。
--
-- 這是本次唯一真的需要動表結構的一支 migration,理由(不是繞過鐵律,是鐵律要求的收尾):
-- D38 要求 KBDB 回到「只有三張核心表」的狀態。0002_credentials.sql 當初在 KBDB 裡多開了
-- 一張獨立表,是已知違規(kbdb-usage skill 明文列為反例)。要把違規清乾淨,唯一辦法就是
-- 真的把那張表拆掉——拆表本身不能只用 API 做(API 不提供「拆表」這種牆內維運操作,
-- 也不該提供),所以下面兩句 SQL 標 kbdb-sql-ok:這不是繞過圍牆去存取資料,是圍牆施工
-- 本身(kbdb/migrations/ 就是牆內,本檔存在的唯一目的就是讓舊表退場)。
--
-- 冪等設計(deploy.ts 每次部署都會重跑這支檔案,沒有 migration 追蹤表):
-- 1. 先補一份空表存在保底——self-hosted 各實例套用進度不一,有些從沒跑過 0002(表從不
-- 存在)、有些已經跑過本檔一次(表已被拆)。沒有這一步,下面的搬資料/退場語句會因表
-- 不存在直接整支失敗(D1 對不存在的表沒有條件式跳過語法)。
-- 2. 把舊表裡「entries 還沒有對應列」的 row 搬進 entriesentry_type='credential'
-- page_name=name 冪等鍵,owner_id=api_key,其餘欄位打包進 metadata_json,欄位對應
-- 0005_credential_template.sql 定義的 slots)。NOT EXISTS 判斷防止重跑造成重複列。
-- 3. 搬完資料後表就沒有存在的理由,最後一步讓它退場。下次部署若又被步驟 1 重新墊一份
-- 空殼,也只是空表、立刻搬 0 筆、立刻退場,不影響任何人(真資料只會被搬一次,因為
-- 步驟 2 的判斷是看 entries 裡有沒有,不是看這是不是第一次跑)。
CREATE TABLE IF NOT EXISTS credentials ( -- kbdb-sql-ok: 表退場施工步驟①保底存在,非資料存取違規,理由見檔頭
api_key TEXT NOT NULL,
name TEXT NOT NULL,
service TEXT,
sensitivity TEXT NOT NULL DEFAULT 'standard',
secret_ref TEXT NOT NULL,
created_at INTEGER NOT NULL,
last_used_at INTEGER,
PRIMARY KEY (api_key, name)
);
INSERT INTO entries (id, entry_type, owner_id, page_name, metadata_json, created_at, updated_at)
SELECT
'e_cred_' || lower(hex(randomblob(8))),
'credential',
c.api_key,
c.name,
json_object('service', c.service, 'sensitivity', c.sensitivity, 'secret_ref', c.secret_ref, 'last_used_at', c.last_used_at),
c.created_at,
unixepoch()
FROM credentials c
WHERE NOT EXISTS (
SELECT 1 FROM entries e
WHERE e.entry_type = 'credential' AND e.owner_id = c.api_key AND e.page_name = c.name
);
DROP TABLE IF EXISTS credentials; -- kbdb-sql-ok: 表退場施工步驟③讓舊表退場,非資料存取違規,理由見檔頭
-45
View File
@@ -134,51 +134,6 @@ export async function deleteEntry(db: D1Database, id: string): Promise<void> {
await db.prepare('DELETE FROM entries WHERE id = ?').bind(id).run();
}
/**
* idKV 退 #16/#17
*
* base `createEntry` id
* GET POST PATCH
*
*
* base entry_type
* arcrun workflow_def / api_recipe / auth_recipe
* ** schema ** entries
*
* PATCH
*
* created_at updated_at
*/
export async function upsertEntry(db: D1Database, id: string, input: Omit<CreateEntryInput, 'id'>): Promise<Entry> {
const existing = await getEntry(db, id);
if (!existing) return createEntry(db, { ...input, id });
await db
.prepare(
`UPDATE entries
SET content = ?, entry_type = ?, owner_id = ?, parent_id = ?, page_name = ?,
refs_json = ?, tags_json = ?, task_status = ?, confidence = ?, metadata_json = ?,
updated_at = unixepoch()
WHERE id = ?`,
)
.bind(
input.content ?? null,
input.entry_type,
input.owner_id ?? null,
input.parent_id ?? null,
input.page_name ?? null,
input.refs_json ?? '[]',
input.tags_json ?? '[]',
input.task_status ?? null,
input.confidence ?? null,
input.metadata_json ?? null,
id,
)
.run();
const row = await getEntry(db, id);
if (!row) throw new Error('upsertEntry: update succeeded but row not found');
return row;
}
/**
* owner entries deprecatedt135 by-name
* 沿 deprecated metadata_json.status='deprecated'
+17 -7
View File
@@ -65,6 +65,13 @@ export interface RecordResult {
record_id: string;
template_id: string;
values: Record<string, string>;
/**
* record slot entries owner_idcreateRecord
* 2026-08-12 `GET /records/:id` ****
* id cypher portal /AI
* 404 null
*/
owner_id: string | null;
}
export async function createRecord(db: D1Database, input: CreateRecordInput): Promise<RecordResult> {
@@ -85,7 +92,7 @@ export async function createRecord(db: D1Database, input: CreateRecordInput): Pr
.bind(uid('ev'), recordId, tpl.id, slot, entry.id)
.run();
}
return { record_id: recordId, template_id: tpl.id, values: input.values };
return { record_id: recordId, template_id: tpl.id, values: input.values, owner_id: input.owner_id ?? null };
}
// Update an existing record's slot values (mira-dissolve T2.1, issue #6).
@@ -147,17 +154,19 @@ export async function updateRecord(
export async function getRecord(db: D1Database, recordId: string): Promise<RecordResult | null> {
const res = await db
.prepare(
`SELECT ev.slot_name as slot, e.content as content, ev.template_id as template_id
`SELECT ev.slot_name as slot, e.content as content, ev.template_id as template_id, e.owner_id as owner_id
FROM entry_values ev JOIN entries e ON ev.entry_id = e.id
WHERE ev.record_id = ?`,
)
.bind(recordId)
.all<{ slot: string; content: string; template_id: string }>();
.all<{ slot: string; content: string; template_id: string; owner_id: string | null }>();
const rows = res.results ?? [];
if (rows.length === 0) return null;
const values: Record<string, string> = {};
for (const r of rows) values[r.slot] = r.content;
return { record_id: recordId, template_id: rows[0].template_id, values };
// 歸屬取第一個非 null 的 slot entry owner(同一 record 的 slot entries 同歸屬)
const owner_id = rows.find((r) => r.owner_id != null)?.owner_id ?? null;
return { record_id: recordId, template_id: rows[0].template_id, values, owner_id };
}
export async function searchByTemplate(db: D1Database, template: string, owner_id?: string, limit = 100): Promise<RecordResult[]> {
@@ -192,19 +201,20 @@ export async function searchByTemplate(db: D1Database, template: string, owner_i
const placeholders = chunk.map(() => '?').join(',');
const evRes = await db
.prepare(
`SELECT ev.record_id as record_id, ev.slot_name as slot, e.content as content, ev.template_id as template_id
`SELECT ev.record_id as record_id, ev.slot_name as slot, e.content as content, ev.template_id as template_id, e.owner_id as owner_id
FROM entry_values ev JOIN entries e ON ev.entry_id = e.id
WHERE ev.record_id IN (${placeholders})`,
)
.bind(...chunk)
.all<{ record_id: string; slot: string; content: string; template_id: string }>();
.all<{ record_id: string; slot: string; content: string; template_id: string; owner_id: string | null }>();
for (const r of evRes.results ?? []) {
let rec = byId.get(r.record_id);
if (!rec) {
rec = { record_id: r.record_id, template_id: r.template_id, values: {} };
rec = { record_id: r.record_id, template_id: r.template_id, values: {}, owner_id: null };
byId.set(r.record_id, rec);
}
rec.values[r.slot] = r.content;
if (rec.owner_id == null && r.owner_id != null) rec.owner_id = r.owner_id;
}
}
return ids.map((id) => byId.get(id)).filter((r): r is RecordResult => !!r);
-16
View File
@@ -9,7 +9,6 @@ import {
getEntry,
listEntries,
updateEntry,
upsertEntry,
deleteEntry,
searchEntries,
isDeprecatedEntry,
@@ -427,21 +426,6 @@ entryRoutes.get('/backfill-library/status', async (c) => {
return c.json({ success: true, ...status });
});
// PUT /entries/:id — 以呼叫端指定的 id 整列覆寫(不存在就新建)。KV 退休 #16/#17。
//
// 與 POST / 的差別:POST 的 id 是隨機的,同一份資產每存一次多一列;PUT 讓「同一份資產永遠
// 是同一列」,所以重跑遷移、重複部署同一支工作流都不會長出重複資料(冪等)。
// 與 PATCH /:id 的差別:PATCH 是部分更新(沒帶的欄位留著),PUT 是整列取代
// ——呼叫端手上是完整定義時要的是後者,否則「刪掉一個欄位」永遠做不到。
entryRoutes.put('/:id', async (c) => {
const body = await c.req.json().catch(() => null);
if (!body || !body.entry_type) return c.json({ success: false, error: 'entry_type required' }, 400);
const entry = await upsertEntry(c.env.DB, c.req.param('id'), body);
// 與 POST / 同款:標了 embed:true 的才進 Vectorizefire-and-forget、失敗不致命。
if (embedEnabled(c.env)) c.executionCtx.waitUntil(embedOnWrite(c.env, entry).catch(() => {}));
return c.json({ success: true, entry });
});
// PATCH /entries/:id
entryRoutes.patch('/:id', async (c) => {
const body = await c.req.json().catch(() => ({}));
+16 -3
View File
@@ -1,13 +1,25 @@
import { Hono } from "hono";
import { cors } from "hono/cors";
import { Env } from "./types.js";
import { partnerAuthMiddleware } from "./middleware/partner-auth.js";
import { partnerAuthMiddleware, type AuthPath } from "./middleware/partner-auth.js";
import { handleMcpRequest } from "./mcp-handler.js";
import { resolveKnowledgeIdentity } from "./lib/portal-client.js";
import type { PortalIdentity } from "./oauth/store.js";
import { inspectorHtml } from "./pages/inspector.js";
import { kbdbFetch } from "./lib/kbdb-client.js";
import { registerOAuthRoutes } from "./oauth/routes.js";
const _app = new Hono<{ Bindings: Env; Variables: { org_namespace: string; partner_token: string } }>();
const _app = new Hono<{
Bindings: Env;
Variables: {
org_namespace: string;
partner_token: string;
// 登入者身分(以帳密走 OAuth 連進來時才有)+ 這條連線是哪種憑據。
// 知識面工具(kbdb_*)據此決定走 portal 資料面還是既有 KBDB 直連(見 lib/portal-client.ts)。
portal?: PortalIdentity;
auth_path: AuthPath;
};
}>();
// ── OAuth 2.1 server 路由(掛在 worker 根路徑,非 /mcp)──────────────────────────
// well-known / authorize / token / register 必須在 origin 根,claude.ai 遠端 connector 才發現得到。
@@ -261,7 +273,8 @@ app.options("/mcp", (c) => {
app.post("/", partnerAuthMiddleware, async (c) => {
const orgNamespace = c.get("org_namespace");
const partnerToken = c.get("partner_token");
return handleMcpRequest(c.req.raw, c.env, orgNamespace, partnerToken);
const identity = resolveKnowledgeIdentity(c.get("auth_path"), c.get("portal"));
return handleMcpRequest(c.req.raw, c.env, orgNamespace, partnerToken, identity);
});
// 輸出根 app_app):與 basePath('/mcp') 的 app 共享同一份 router,故 OAuth 根路由與
+34 -6
View File
@@ -19,6 +19,7 @@
import type { Env } from "../types.js";
import { kbdbFetch } from "./kbdb-client.js";
import { portalFetch, type KnowledgeIdentity } from "./portal-client.js";
/** 全館視圖一行(kbdb GET /map 的 libraries[] 元素;top_entities 已是 top-3 名字)。 */
export interface LibraryMapRow {
@@ -86,25 +87,45 @@ const MAP_FETCH_TIMEOUT_MS = 1500;
const CACHE_TTL_OK_MS = 5 * 60 * 1000;
const CACHE_TTL_FAIL_MS = 60 * 1000;
let instructionsCache: { text: string | null; expiresAt: number } | null = null;
/**
* 2026-08-12
*
* entity
*
*
*/
const instructionsCache = new Map<string, { text: string | null; expiresAt: number }>();
/** 測試用:清掉 isolate 內快取(prod 不呼叫)。 */
export function __resetLibraryMapInstructionsCacheForTests(): void {
instructionsCache = null;
instructionsCache.clear();
}
/**
* MCP server instructions design §4 / §6session instructions
* push /HTTP // JSON nullcaller
*
* identity.kind === 'portal' cypher `/portal/data/map`
* KBDB `/map` tokenstale
*/
export async function buildLibraryMapInstructions(env: Env): Promise<string | null> {
export async function buildLibraryMapInstructions(
env: Env,
identity: KnowledgeIdentity,
): Promise<string | null> {
if (identity.kind === "stale") return null;
// 快取 keyportal 用 session(=這個人這次登入),service 用固定字串。
// session token 只當 Map 的 key 活在 isolate 記憶體內,不落地、不寫 log。
const cacheKey = identity.kind === "portal" ? `portal:${identity.portal.session}` : "service";
const now = Date.now();
if (instructionsCache && instructionsCache.expiresAt > now) return instructionsCache.text;
const hit = instructionsCache.get(cacheKey);
if (hit && hit.expiresAt > now) return hit.text;
let text: string | null = null;
try {
const res = await Promise.race([
kbdbFetch(env, "/map"),
identity.kind === "portal"
? portalFetch(env, identity.portal.session, "/portal/data/map")
: kbdbFetch(env, "/map"),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error("library map fetch timeout")), MAP_FETCH_TIMEOUT_MS),
),
@@ -124,6 +145,13 @@ export async function buildLibraryMapInstructions(env: Env): Promise<string | nu
text = null;
}
instructionsCache = { text, expiresAt: now + (text ? CACHE_TTL_OK_MS : CACHE_TTL_FAIL_MS) };
instructionsCache.set(cacheKey, {
text,
expiresAt: now + (text ? CACHE_TTL_OK_MS : CACHE_TTL_FAIL_MS),
});
// isolate 內的快取,不做失效協議;但別讓不同帳號的格子無上限長大(isolate 可活很久)。
if (instructionsCache.size > 64) {
for (const [k, v] of instructionsCache) if (v.expiresAt <= now) instructionsCache.delete(k);
}
return text;
}
+113
View File
@@ -0,0 +1,113 @@
/**
* Portal client AI西
*
* leo 2026-08-12 Portal 西
* AI MCP AI西
* MCP ****
*
* **portal session token** cypher
* portal
* cypher `/portal/data/*` server
* rule 07 API
*
* CYPHER_EXECUTOR service binding binding
*/
import type { Env } from "../types.js";
import type { PortalIdentity } from "../oauth/store.js";
import { errorResponse } from "./cypher-client.js";
export interface PortalCallOpts {
method?: string;
body?: unknown;
query?: Record<string, string | number | undefined>;
}
/** 用登入者的 session 打 cypher 的 portal 資料面。 */
export async function portalFetch(
env: Env,
session: string,
path: string,
opts: PortalCallOpts = {},
): Promise<Response> {
if (!env.CYPHER_EXECUTOR) {
throw new Error("CYPHER_EXECUTOR service binding not configured");
}
const url = new URL(`https://cypher${path}`);
for (const [k, v] of Object.entries(opts.query ?? {})) {
if (v !== undefined && v !== "") url.searchParams.set(k, String(v));
}
return env.CYPHER_EXECUTOR.fetch(url.toString(), {
method: opts.method ?? "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session}`,
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
}
/**
*
*
* leo
* - portal portal
* - service static token / partner key KBDB
* - stale OAuth token token ****
* 退
*/
export type KnowledgeIdentity =
| { kind: "portal"; portal: PortalIdentity }
| { kind: "service" }
| { kind: "stale" };
export function resolveKnowledgeIdentity(
authPath: "oauth" | "service",
portal: PortalIdentity | undefined,
): KnowledgeIdentity {
if (authPath !== "oauth") return { kind: "service" };
return portal?.session ? { kind: "portal", portal } : { kind: "stale" };
}
/** 舊 token(沒帶身分)時的統一回覆:講清楚怎麼修,不假裝查不到資料。 */
export function staleIdentityError() {
return errorResponse(
"identity_missing",
"這條 MCP 連線是舊版簽發的 token,裡面沒有登入者身分,因此查不到任何知識內容。" +
"重新連線一次(在 claude.ai 的 connector 設定裡重新授權、輸入你的 Portal 帳密)即可——" +
"不需要另外找任何 credential 或金鑰。",
[
"到 claude.ai → Settings → Connectors,把這個 connector 重新連線一次(會跳出輸入 Portal 帳密的頁面)",
"重連後 kbdb_* 全部工具都會用你這個帳號的權限查詢",
],
);
}
/**
* portal AI
* 401/403 ****
* AI 使
*/
export async function portalError(res: Response, what: string) {
const detail = await res.text().catch(() => "");
if (res.status === 401) {
return errorResponse(
"session_expired",
`${what}失敗:登入階段已過期(portal session 到期或已登出)。`,
[
"到 claude.ai → Settings → Connectors 重新連線這個 connector(重新輸入 Portal 帳密)",
"重連後權限與你在 portal 網頁上看到的一致",
],
detail,
);
}
if (res.status === 403) {
return errorResponse(
"forbidden",
`${what}失敗:這個帳號沒有這項權限(帳號可能已停用,或沒有被授權該知識庫)。`,
["請知識庫管理員在 portal 的帳號管理裡確認你的狀態與可用知識庫"],
detail,
);
}
return errorResponse(`portal_${res.status}`, `${what}失敗(HTTP ${res.status}`, ["稍後重試"], detail);
}
+8 -2
View File
@@ -2,6 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { registerAllTools } from "./tools/registry.js";
import { buildLibraryMapInstructions } from "./lib/library-map.js";
import type { KnowledgeIdentity } from "./lib/portal-client.js";
import { Env } from "./types.js";
export async function handleMcpRequest(
@@ -9,11 +10,16 @@ export async function handleMcpRequest(
env: Env,
orgNamespace: string,
partnerToken: string,
identity: KnowledgeIdentity,
): Promise<Response> {
// library-map SDD M4design §4/§6):連線時把全館藏書地圖嵌進 server instructions
// session 一開就知道館裡有哪些庫(push 零查詢)。builder 內建 timeoutisolate TTL 快取
//(選型理由見 lib/library-map.ts 檔頭);任何失敗回 null → 靜默略過,絕不擋 MCP 連線(鐵律)。
const mapInstructions = await buildLibraryMapInstructions(env);
//
// 🔴 2026-08-12:以帳密連線時**改用登入者的身分**組地圖——否則 instructions 會把
// 整個知識庫的庫名一次推給一個可能只有部分權限的帳號(地圖本身就是情報)。
// 快取也因此改成 per-session key(見 lib/library-map.ts)。
const mapInstructions = await buildLibraryMapInstructions(env, identity);
// 2026-07-30leo 問「人類說『幫我用 arcrun 寫 xxx』,Haiku 會知道要用這些資源嗎?
// 如果不會,要寫什麼在外面讓它一聽到就知道?」):
@@ -60,7 +66,7 @@ export async function handleMcpRequest(
{ instructions },
);
registerAllTools(server, env, orgNamespace, partnerToken);
registerAllTools(server, env, orgNamespace, partnerToken, identity);
await server.connect(transport);
return transport.handleRequest(request);
+28 -2
View File
@@ -1,9 +1,19 @@
import { Context, Next } from "hono";
import { Env } from "../types.js";
import { getAccessToken } from "../oauth/store.js";
import { getAccessToken, type PortalIdentity } from "../oauth/store.js";
import { constantTimeEqual } from "../oauth/crypto.js";
import { originOf, resourceUri, wwwAuthenticateHeader } from "../oauth/metadata.js";
/**
* ****kbdb_*
* - "oauth" Portal portal session portal
* portal
* - "service"static token / partner key ****
* KBDB
* token
*/
export type AuthPath = "oauth" | "service";
/**
* MCP / GUI
*
@@ -19,7 +29,15 @@ import { originOf, resourceUri, wwwAuthenticateHeader } from "../oauth/metadata.
* ALLOW_PLAINTEXT_NAMESPACE="true"
*/
export async function partnerAuthMiddleware(
c: Context<{ Bindings: Env; Variables: { org_namespace: string; partner_token: string } }>,
c: Context<{
Bindings: Env;
Variables: {
org_namespace: string;
partner_token: string;
portal?: PortalIdentity;
auth_path: AuthPath;
};
}>,
next: Next
) {
const origin = originOf(c.req.url);
@@ -50,6 +68,11 @@ export async function partnerAuthMiddleware(
}
c.set("org_namespace", at.namespace);
c.set("partner_token", at.namespace); // 下游 cypher 用 namespace 當 X-Arcrun-API-Key(與 CLI 同一份身份)
// 登入者的身分(2026-08-12):知識面工具(kbdb_*)帶著它打 cypher 的 portal 資料面,
// 權限與這個人在 portal 網頁上看到的完全一致。舊 token 沒有這欄 → undefined
// 知識面工具會要求重新連線(不偷偷退回服務金鑰那條老路)。
c.set("portal", at.portal);
c.set("auth_path", "oauth");
await next();
return;
}
@@ -60,6 +83,7 @@ export async function partnerAuthMiddleware(
const ns = c.env.MCP_OWNER_NAMESPACE || "leo";
c.set("org_namespace", ns);
c.set("partner_token", ns);
c.set("auth_path", "service");
await next();
return;
}
@@ -79,6 +103,7 @@ export async function partnerAuthMiddleware(
}
c.set("org_namespace", info.org_namespace);
c.set("partner_token", token);
c.set("auth_path", "service");
await next();
return;
}
@@ -89,6 +114,7 @@ export async function partnerAuthMiddleware(
if (c.env.ALLOW_PLAINTEXT_NAMESPACE === "true") {
c.set("org_namespace", token);
c.set("partner_token", token);
c.set("auth_path", "service");
await next();
return;
}
+56 -6
View File
@@ -14,6 +14,7 @@ import {
consumeAuthCode,
putAccessToken,
AUTH_CODE_TTL_SECONDS,
type PortalIdentity,
} from "./store.js";
import {
originOf,
@@ -34,10 +35,25 @@ const CORS_JSON = {
"Cache-Control": "no-store",
} as const;
function ownerNamespace(env: Env): string {
/**
* ****arcrun_* kbdb_*
* portal session store.ts PortalIdentity
*
* cypher workflow API opaque key
* X-Arcrun-API-Key portal session cypher
* portal session workflow
* arcrun_* ****
*
* "leo" ****
* namespace KBDB owner_id API key
*/
function workflowTenant(env: Env): string {
return env.MCP_OWNER_NAMESPACE || "leo";
}
/** portal session TTL 讀不到時的保守假設(秒):短的那邊贏,寧可早點要求重連。 */
const FALLBACK_PORTAL_SESSION_TTL = 604800; // 7 天(cypher portal.ts 的預設值)
function tokenTtl(env: Env): number {
const n = parseInt(env.MCP_TOKEN_TTL ?? "", 10);
return Number.isFinite(n) && n > 0 ? n : DEFAULT_TOKEN_TTL;
@@ -248,7 +264,13 @@ export function registerOAuthRoutes<
}
// 認證下沉到 cypher 的 /portal/login(唯一真相源;同樣吃它的節流與停用檢查)。
// 走 service bindingMCP 與 cypher 同帳號,屬 D28 允許的零件級組合)。
let loginOk = false;
//
// 🔴 2026-08-12leo:「用登入能做的 mcp 就應該能做,結果要你去打 MCP 時自己找
// credential 問題很大」):這裡**接住登入回來的身分**,不再只留 `res.ok`。
// 舊版把身分丟掉 ⇒ 查詢時無身分可帶 ⇒ 只好去撈服務內部金鑰(KBDB_INTERNAL_TOKEN
// 直打 KBDB ⇒ 繞過所有庫過濾、而且不管誰登入都看到同一格。根因就在這幾行。
let portal: PortalIdentity | null = null;
let portalTtl = FALLBACK_PORTAL_SESSION_TTL;
try {
const res = await c.env.CYPHER_EXECUTOR.fetch(
new Request("https://cypher/portal/login", {
@@ -257,11 +279,34 @@ export function registerOAuthRoutes<
body: JSON.stringify({ email, password }),
}),
);
loginOk = res.ok;
if (res.ok) {
const body = (await res.json().catch(() => null)) as {
session_token?: unknown;
display_name?: unknown;
role?: unknown;
libraries?: unknown;
session_expires_in?: unknown;
} | null;
const session = typeof body?.session_token === "string" ? body.session_token : "";
if (session) {
portal = {
session,
display_name: typeof body?.display_name === "string" ? body.display_name : "",
role: typeof body?.role === "string" ? body.role : "user",
libraries: Array.isArray(body?.libraries)
? body.libraries.filter((x): x is string => typeof x === "string")
: [],
};
const ttl = Number(body?.session_expires_in);
if (Number.isFinite(ttl) && ttl > 0) portalTtl = ttl;
}
}
} catch {
return c.html(consentPage(consent, "暫時無法驗證帳密,請稍後再試。"), 503);
}
if (!loginOk) {
if (!portal) {
// 帳密不對,或這台 cypher 舊到還不回 session_token。兩者都不可以發碼——
// 發了也是一張沒有身分的 token,查什麼都得再找一次 credential,正是要修的病。
return c.html(consentPage(consent, "帳號或密碼不正確,請重試。"), 401);
}
if (!c.env.OAUTH_KV) {
@@ -275,7 +320,9 @@ export function registerOAuthRoutes<
code_challenge_method: "S256",
scope: consent.scope,
resource: consent.resource,
namespace: ownerNamespace(c.env),
namespace: workflowTenant(c.env),
portal,
portal_session_expires_in: portalTtl,
});
const location = redirectWith(redirectUri, {
code,
@@ -318,7 +365,9 @@ export function registerOAuthRoutes<
return err("invalid_grant", "PKCE verification failed");
}
const ttl = tokenTtl(c.env);
// token 活不過它底下的 portal session:否則第 8 天會出現「MCP 還連著、卻什麼都查不到」
// ——使用者看到的是壞掉,實際是身分過期。兩者一起到期,重連就是重新輸入帳密,一次搞定。
const ttl = Math.min(tokenTtl(c.env), data.portal_session_expires_in || FALLBACK_PORTAL_SESSION_TTL);
const accessToken = randomToken(32);
await putAccessToken(
c.env.OAUTH_KV,
@@ -327,6 +376,7 @@ export function registerOAuthRoutes<
namespace: data.namespace,
client_id: data.client_id,
scope: data.scope,
portal: data.portal,
// RFC 8707aud 一律用「本 server canonical resource URI」(非 client 原樣值)。
// authorize 已只存 canonical,這裡再以當前 origin 重算一次確保與 partner-auth 嚴格比對一致。
aud: resourceUri(originOf(c.req.url)),
+31
View File
@@ -4,6 +4,28 @@
// KV key 一律用 SHA-256 hex(不把 raw code/token 當 key)→ 就算 KV list 也拿不到可用憑證。
import { sha256Hex } from "./crypto.js";
/**
* authorize token
*
* leo 2026-08-12 MCP
* ****
*
* `session` cypher `/portal/login` portal session token portal
* KV TTL
* access_token TTL routes.ts
* MCP session
*
* display_name / role / libraries ****arcrun_whoami
* cypher user record
* token
*/
export interface PortalIdentity {
session: string;
display_name: string;
role: string;
libraries: string[];
}
/** authorization code 綁定的資料(一次性;/token 驗證後即刪)。 */
export interface AuthCodeData {
client_id: string;
@@ -15,6 +37,10 @@ export interface AuthCodeData {
resource: string;
/** 換發後 token 綁定的資料分區(owner namespace)。 */
namespace: string;
/** 這張 code 是誰換的(帳密驗過的那個人)。 */
portal: PortalIdentity;
/** portal session 剩餘秒數(authorize 當下);access_token TTL 不得超過它。 */
portal_session_expires_in: number;
}
/** access token 綁定的資料。 */
@@ -26,6 +52,11 @@ export interface AccessTokenData {
aud: string;
/** 過期時間(epoch 秒),與 KV TTL 雙保險。 */
exp: number;
/**
* token ** token** undefined
* 退fail-closed
*/
portal?: PortalIdentity;
}
const CODE_PREFIX = "oauth:code:";
+57 -13
View File
@@ -5,31 +5,75 @@
* AI CLI acr whoamiMCP rule 07 §5
* AI MCP curl
*
* MCP orgNamespace+ cypher binding
* 2026-08-12 ****display_name / role /
* account_namespace 西
* /kbdb/*portal-data.ts
* arcrun_* API key server
*
* MCP
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { toolName } from "../brand.js";
import { Env } from "../types.js";
import type { KnowledgeIdentity } from "../lib/portal-client.js";
export function registerWhoami(server: McpServer, env: Env, orgNamespace: string) {
export function registerWhoami(
server: McpServer,
env: Env,
orgNamespace: string,
identity: KnowledgeIdentity,
) {
server.tool(
toolName("whoami"),
"回報這個 MCP 連線目前生效的身份:綁哪個帳號 / namespace、cypher 連向哪。" +
"部署 / 觸發 / 查 workflow 前先 call 此 tool 確認帳號,**不要自己 curl 猜帳號 URL**(會打到錯帳號)。",
"回報這個 MCP 連線目前生效的身份:以帳密連線時回「登入的是誰、能看哪些知識庫」;" +
"服務級 token 連線時回綁定的帳號 namespace。部署 / 觸發 / 查 workflow 前先 call 此 tool 確認身份," +
"**不要自己 curl 猜帳號 URL**(會打到錯帳號)。",
{},
async () => {
// 薄殼:MCP 透過 service bindingCYPHER_EXECUTOR)連 cypherbinding 本身決定連哪台;
// 身份來自啟動時解析的 orgNamespace(綁哪個帳號的資料分區)。這裡只如實回報,不做推斷。
const identity = {
account_namespace: orgNamespace || "(未設)",
const base = {
cypher: "service-binding:CYPHER_EXECUTOR",
kbdb: "service-binding:KBDB",
note:
"此 MCP 已綁定上述帳號。部署/觸發/查詢都走這個身份;勿自行 curl 其他 URL 猜帳號。",
};
return {
content: [{ type: "text" as const, text: JSON.stringify(identity, null, 2) }],
};
if (identity.kind === "portal") {
const { display_name, role, libraries } = identity.portal;
return json({
...base,
auth: "portal-login(這條連線是有人輸入 Portal 帳密授權的)",
logged_in_as: display_name || "(未設顯示名稱)",
role,
libraries: libraries.length ? libraries : ["(尚未被授權任何知識庫)"],
knowledge_scope:
libraries.includes("*")
? "全部知識庫(此帳號有全庫權限)"
: `僅限上列知識庫——kbdb_* 查得到的東西與這個帳號在 portal 網頁上看得到的完全一致`,
note:
"你是「主人授權的 AI」:主人查得到的你查得到,主人查不到的你也查不到。" +
"kbdb_* 不需要任何額外的 credential / 金鑰 / kbdb_base——已經登入過了,不會再問第二次。",
});
}
if (identity.kind === "stale") {
return json({
...base,
auth: "舊版 token(沒有登入者身分)",
knowledge_scope: "查不到任何知識內容",
note:
"這條連線是本次改版前簽發的 token。到 claude.ai → Settings → Connectors " +
"重新連線一次(輸入 Portal 帳密)即可恢復,不需要找任何 credential。",
});
}
return json({
...base,
auth: "service tokenstatic token / partner key,代表整個實例或租戶,不是某個人)",
account_namespace: orgNamespace || "(未設)",
note: "此 MCP 已綁定上述帳號。部署/觸發/查詢都走這個身份;勿自行 curl 其他 URL 猜帳號。",
});
},
);
}
function json(obj: unknown) {
return { content: [{ type: "text" as const, text: JSON.stringify(obj, null, 2) }] };
}
+148 -59
View File
@@ -1,23 +1,27 @@
/**
* KBDB MCP kbdb-base Phase 9.1HANDOFF §2
*
* rule 07 §5 APIMCP +
* kbdbFetchKBDB service binding HTTP APIkbdb/src/routes/*
* rule 07 §5 APIMCP +
*
* 2026-08-12
* leo Portal 西AI
* MCP AI西
* MCP
*
* MCP ****
* KBDB_INTERNAL_TOKEN KBDB
*
* identity.kind === 'portal' portal session cypher
* `/portal/data/*` server portal
* ****MCP
*
* static token / partner keyidentity.kind === 'service' KBDB
*
*
* KBDB leo 2026-06-14 DECISION-kbdb-v3-baseplane.md
* - ** / SQL tool**
* - AI templatename+slots+ recordslotcontent
* Supabase schema template/slot CREATE TABLE
* - 調 HTTP API D1 SQL
*
* API kbdb/src/routes
* POST /templates { name, slots[], description?, created_by? } { template }
* GET /templates { templates[], count }
* GET /templates/:idOrName { template }
* POST /records { template, values:{slot:content}, owner_id? } { record }
* GET /records/by-template/:t ?owner_id= { records[], count }
* GET /records/:recordId { record }
* GET /entries/search ?q=&owner_id= { entries[], count, mode:'keyword' }
* - AI templatename+slots+ recordslotcontent
* - 調 HTTP API D1 SQL
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -25,22 +29,32 @@ import { z } from "zod";
import type { Env } from "../types.js";
import { kbdbFetch } from "../lib/kbdb-client.js";
import { errorResponse, successResponse } from "../lib/cypher-client.js";
import {
portalFetch,
portalError,
staleIdentityError,
type KnowledgeIdentity,
} from "../lib/portal-client.js";
/** 走 portal 資料面時,呼叫端傳的 owner_id 一律無效(server 用登入者的歸屬)——如實告訴 AI。 */
const OWNER_IGNORED_HINT =
"owner_id 在登入身分下不生效:查詢範圍由你的帳號權限決定(與你在 portal 網頁看到的一致)";
/** 註冊全部 KBDB 資料層工具(kbdb-base Phase 9.1)。不含建表/SQL tool(鐵律)。 */
export function registerAllKbdbDataTools(server: McpServer, env: Env) {
registerCreateTemplate(server, env);
registerListTemplates(server, env);
registerCreateRecord(server, env);
registerGetRecord(server, env);
registerQuery(server, env);
registerSearch(server, env);
export function registerAllKbdbDataTools(server: McpServer, env: Env, identity: KnowledgeIdentity) {
registerCreateTemplate(server, env, identity);
registerListTemplates(server, env, identity);
registerCreateRecord(server, env, identity);
registerGetRecord(server, env, identity);
registerQuery(server, env, identity);
registerSearch(server, env, identity);
}
/**
* kbdb_create_template template= /
* AI API template + slots
*/
export function registerCreateTemplate(server: McpServer, env: Env) {
export function registerCreateTemplate(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_create_template",
"建一個 KBDB template(萬用表裡的一種資料形狀,類 Supabase 的虛擬表)。KBDB 不能建真的資料表——" +
@@ -50,16 +64,24 @@ export function registerCreateTemplate(server: McpServer, env: Env) {
name: z.string().min(1).describe("template 名稱(唯一識別,之後填 record 用這個名字),如 'contact' / 'note'"),
slots: z.array(z.string().min(1)).min(1).describe("欄位名清單,如 ['name','email','phone']"),
description: z.string().optional().describe("這個 template 用途的簡述(選填)"),
created_by: z.string().optional().describe("建立者標記(選填)"),
created_by: z.string().optional().describe("建立者標記(選填;登入身分下由 server 記錄,不吃此值"),
},
async ({ name, slots, description, created_by }) => {
if (identity.kind === "stale") return staleIdentityError();
try {
const res = await kbdbFetch(env, "/templates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, slots, description, created_by }),
});
const res =
identity.kind === "portal"
? await portalFetch(env, identity.portal.session, "/portal/data/templates", {
method: "POST",
body: { name, slots, description },
})
: await kbdbFetch(env, "/templates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, slots, description, created_by }),
});
if (!res.ok) {
if (identity.kind === "portal") return portalError(res, `建 template「${name}`);
return errorResponse("create_template_failed", `建 template 失敗`, ["檢查 name 是否重複", "確認 slots 是非空字串陣列"], await res.text().catch(() => ""));
}
const data = await res.json();
@@ -74,17 +96,28 @@ export function registerCreateTemplate(server: McpServer, env: Env) {
}
/** kbdb_list_templates — 列出所有已建的 template(看有哪些資料形狀可用)。 */
export function registerListTemplates(server: McpServer, env: Env) {
export function registerListTemplates(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_list_templates",
"列出 KBDB 裡所有 template(已定義的資料形狀)。要存資料前先看有沒有現成 template 可用,沒有再 kbdb_create_template。",
{},
async () => {
if (identity.kind === "stale") return staleIdentityError();
try {
const res = await kbdbFetch(env, "/templates");
if (!res.ok) return errorResponse("list_templates_failed", `列 template 失敗`, ["稍後重試"], await res.text().catch(() => ""));
const res =
identity.kind === "portal"
? await portalFetch(env, identity.portal.session, "/portal/data/templates")
: await kbdbFetch(env, "/templates");
if (!res.ok) {
if (identity.kind === "portal") return portalError(res, "列 template");
return errorResponse("list_templates_failed", `列 template 失敗`, ["稍後重試"], await res.text().catch(() => ""));
}
const data = await res.json();
return successResponse(data, ["每個 template 的 slots_json 是它的欄位清單", "填資料用 kbdb_create_record"]);
return successResponse(data, [
"每個 template 的 slots_json 是它的欄位清單",
"填資料用 kbdb_create_record",
"template 是全域共享的「資料形狀」定義(schema),不含任何人的內容——內容的權限在 record/entry 那層",
]);
} catch (e) {
return errorResponse("internal_error", e instanceof Error ? e.message : String(e), ["稍後重試"]);
}
@@ -93,7 +126,7 @@ export function registerListTemplates(server: McpServer, env: Env) {
}
/** kbdb_create_record — 依某 template 填一筆 recordslot → 內容)。 */
export function registerCreateRecord(server: McpServer, env: Env) {
export function registerCreateRecord(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_create_record",
"依某 template 填一筆 record(一列資料)。values 是 {slot名: 內容}slot 名要對得上 template 的 slots。" +
@@ -101,23 +134,34 @@ export function registerCreateRecord(server: McpServer, env: Env) {
{
template: z.string().min(1).describe("template 的 name 或 id"),
values: z.record(z.string()).describe("欄位內容 {slot名: 字串內容},如 {name:'Leo', email:'leo@x.com'}"),
owner_id: z.string().optional().describe("資料歸屬標記(選填,如專案 id / 用戶 id"),
owner_id: z.string().optional().describe("資料歸屬標記(選填;登入身分下一律由 server 定成你的歸屬,不吃此值"),
},
async ({ template, values, owner_id }) => {
if (identity.kind === "stale") return staleIdentityError();
try {
const res = await kbdbFetch(env, "/records", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ template, values, owner_id }),
});
const res =
identity.kind === "portal"
? await portalFetch(env, identity.portal.session, "/portal/data/records", {
method: "POST",
body: { template, values },
})
: await kbdbFetch(env, "/records", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ template, values, owner_id }),
});
if (!res.ok) {
if (identity.kind === "portal") return portalError(res, `填 recordtemplate「${template}」)`);
return errorResponse("create_record_failed", `填 record 失敗`, [
`確認 template「${template}」存在(kbdb_list_templates`,
"values 的 slot 名要對得上 template 的 slots",
], await res.text().catch(() => ""));
}
const data = await res.json();
return successResponse(data, [`已存入。用 kbdb_query(template='${template}') 列出此 template 的所有 record`]);
return successResponse(data, [
`已存入。用 kbdb_query(template='${template}') 列出此 template 的所有 record`,
...(identity.kind === "portal" ? [OWNER_IGNORED_HINT] : []),
]);
} catch (e) {
return errorResponse("internal_error", e instanceof Error ? e.message : String(e), ["稍後重試"]);
}
@@ -126,7 +170,7 @@ export function registerCreateRecord(server: McpServer, env: Env) {
}
/** kbdb_get_record — 用 record_id 取單筆 record。 */
export function registerGetRecord(server: McpServer, env: Env) {
export function registerGetRecord(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_get_record",
"用 record_id 取一筆 record 的所有欄位內容。record_id 從 kbdb_create_record 回傳或 kbdb_query 列出取得。",
@@ -134,10 +178,23 @@ export function registerGetRecord(server: McpServer, env: Env) {
record_id: z.string().min(1).describe("record 的 idrec_xxx"),
},
async ({ record_id }) => {
if (identity.kind === "stale") return staleIdentityError();
try {
const res = await kbdbFetch(env, `/records/${encodeURIComponent(record_id)}`);
if (res.status === 404) return errorResponse("not_found", `record「${record_id}」不存在`, ["確認 record_id 正確", "用 kbdb_query 列出某 template 的 record 取 id"]);
if (!res.ok) return errorResponse("get_record_failed", `取 record 失敗`, ["稍後重試"], await res.text().catch(() => ""));
const res =
identity.kind === "portal"
? await portalFetch(env, identity.portal.session, `/portal/data/records/${encodeURIComponent(record_id)}`)
: await kbdbFetch(env, `/records/${encodeURIComponent(record_id)}`);
if (res.status === 404) {
// 登入身分下,「不是你的」與「不存在」刻意同回 404(不洩存在性,portal 同一條紅線)。
return errorResponse("not_found", `查無 record「${record_id}」(不存在,或不在你的權限範圍內)`, [
"確認 record_id 正確",
"用 kbdb_query 列出某 template 的 record 取 id",
]);
}
if (!res.ok) {
if (identity.kind === "portal") return portalError(res, "取 record");
return errorResponse("get_record_failed", `取 record 失敗`, ["稍後重試"], await res.text().catch(() => ""));
}
const data = await res.json();
return successResponse(data);
} catch (e) {
@@ -148,21 +205,39 @@ export function registerGetRecord(server: McpServer, env: Env) {
}
/** kbdb_query — 列出某 template 底下的所有 record(結構化查詢)。 */
export function registerQuery(server: McpServer, env: Env) {
export function registerQuery(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_query",
"列出某 template 底下的所有 record(結構化查詢,按 template 取整批資料)。要按關鍵字找內容用 kbdb_search。",
{
template: z.string().min(1).describe("template 的 name 或 id"),
owner_id: z.string().optional().describe("只取某歸屬的 record(選填)"),
owner_id: z.string().optional().describe("只取某歸屬的 record(選填;登入身分下不生效,範圍由你的權限決定"),
},
async ({ template, owner_id }) => {
if (identity.kind === "stale") return staleIdentityError();
try {
const path = `/records/by-template/${encodeURIComponent(template)}` + (owner_id ? `?owner_id=${encodeURIComponent(owner_id)}` : "");
const res = await kbdbFetch(env, path);
if (!res.ok) return errorResponse("query_failed", `查詢 record 失敗`, [`確認 template「${template}」存在`], await res.text().catch(() => ""));
const res =
identity.kind === "portal"
? await portalFetch(
env,
identity.portal.session,
`/portal/data/records/by-template/${encodeURIComponent(template)}`,
)
: await kbdbFetch(
env,
`/records/by-template/${encodeURIComponent(template)}` +
(owner_id ? `?owner_id=${encodeURIComponent(owner_id)}` : ""),
);
if (!res.ok) {
if (identity.kind === "portal") return portalError(res, `查詢 template「${template}」的 record`);
return errorResponse("query_failed", `查詢 record 失敗`, [`確認 template「${template}」存在`], await res.text().catch(() => ""));
}
const data = await res.json();
return successResponse(data, ["用 kbdb_get_record(record_id) 取單筆全文", "按關鍵字找內容改用 kbdb_search"]);
return successResponse(data, [
"用 kbdb_get_record(record_id) 取單筆全文",
"按關鍵字找內容改用 kbdb_search",
...(identity.kind === "portal" ? [OWNER_IGNORED_HINT] : []),
]);
} catch (e) {
return errorResponse("internal_error", e instanceof Error ? e.message : String(e), ["稍後重試"]);
}
@@ -175,26 +250,38 @@ export function registerQuery(server: McpServer, env: Env) {
* / KBDB MCP RAGissue #7 / D17
* mode=semantic vectorize base keyword + capability_hint CC
*/
export function registerSearch(server: McpServer, env: Env) {
export function registerSearch(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_search",
"搜尋 KBDB 內容。mode='keyword'(預設,D1 LIKE 關鍵字,基本盤永遠可用)或 'semantic'AI 向量語義搜尋," +
"需先開 embed 模組)。語義沒開時會自動降級關鍵字並告訴你怎麼開。要按 template 取整批結構化資料用 kbdb_query。",
{
q: z.string().min(1).describe("搜尋關鍵字 / 語義查詢句"),
owner_id: z.string().optional().describe("限定某歸屬範圍內搜(選填)"),
owner_id: z.string().optional().describe("限定某歸屬範圍內搜(選填;登入身分下不生效,範圍由你的權限決定"),
source: z.string().optional().describe("只搜某來源(ingest source.uri,選填)"),
mode: z.enum(["keyword", "semantic"]).optional().describe("keyword(預設)或 semantic(需開 vectorize"),
},
async ({ q, owner_id, source, mode }) => {
if (identity.kind === "stale") return staleIdentityError();
try {
const qs = new URLSearchParams({ q });
if (owner_id) qs.set("owner_id", owner_id);
if (source) qs.set("source", source);
if (mode) qs.set("mode", mode);
const res = await kbdbFetch(env, `/entries/search?${qs.toString()}`);
if (!res.ok) return errorResponse("search_failed", `搜尋失敗`, ["稍後重試"], await res.text().catch(() => ""));
const data = (await res.json()) as { mode?: string; capability_hint?: string };
let res: Response;
if (identity.kind === "portal") {
// /portal/data/search 只吃在權限範圍內「再收窄」的 filterowner_id/library 由 server 定死。
res = await portalFetch(env, identity.portal.session, "/portal/data/search", {
query: { q, mode },
});
} else {
const qs = new URLSearchParams({ q });
if (owner_id) qs.set("owner_id", owner_id);
if (source) qs.set("source", source);
if (mode) qs.set("mode", mode);
res = await kbdbFetch(env, `/entries/search?${qs.toString()}`);
}
if (!res.ok) {
if (identity.kind === "portal") return portalError(res, "搜尋");
return errorResponse("search_failed", `搜尋失敗`, ["稍後重試"], await res.text().catch(() => ""));
}
const data = (await res.json()) as { mode?: string; capability_hint?: string; note?: string };
// base 回 capability_hint → 語義沒開、已降級 keyword。把它當 next-step 傳給 AI(發現閉環)。
const hints =
data.capability_hint
@@ -202,6 +289,8 @@ export function registerSearch(server: McpServer, env: Env) {
: data.mode === "semantic"
? ["mode:semantic = AI 向量語義搜尋"]
: ["mode:keyword = D1 LIKE(基本盤)", "想要語義搜尋:mode='semantic'(需先開 vectorize"];
if (identity.kind === "portal") hints.push(OWNER_IGNORED_HINT);
if (data.note) hints.push(data.note);
return successResponse(data, hints);
} catch (e) {
return errorResponse("internal_error", e instanceof Error ? e.message : String(e), ["稍後重試"]);
+60 -7
View File
@@ -23,6 +23,12 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import type { Env } from "../types.js";
import { cypherFetch, errorResponse, successResponse } from "../lib/cypher-client.js";
import {
portalFetch,
portalError,
staleIdentityError,
type KnowledgeIdentity,
} from "../lib/portal-client.js";
/** graph 查詢 workflow 名(與 registry/examples/graph-neighbors/workflow.yaml 的 name 一致)。 */
export const GRAPH_NEIGHBORS_WORKFLOW = "graph_neighbors";
@@ -35,8 +41,13 @@ const INSTALL_HINTS = [
];
/** 註冊全部 KBDB graph 查詢工具(issue #68)。 */
export function registerAllKbdbGraphTools(server: McpServer, env: Env, orgNamespace: string) {
registerGraphNeighbors(server, env, orgNamespace);
export function registerAllKbdbGraphTools(
server: McpServer,
env: Env,
orgNamespace: string,
identity: KnowledgeIdentity,
) {
registerGraphNeighbors(server, env, orgNamespace, identity);
// graph_traverserepo 內目前只有 graph-neighbors 有 workflow 定義(registry/examples/),
// traverse 尚無可對齊的 input 形狀 → 不猜、不過度工程;等 workflow 進 registry 再加薄殼。
}
@@ -45,7 +56,12 @@ export function registerAllKbdbGraphTools(server: McpServer, env: Env, orgNamesp
* kbdb_graph_neighbors knowledge graph 1-hop/N-hop
* 調 GET /q/{ns}/graph_neighbors MCP client
*/
export function registerGraphNeighbors(server: McpServer, env: Env, orgNamespace: string) {
export function registerGraphNeighbors(
server: McpServer,
env: Env,
orgNamespace: string,
identity: KnowledgeIdentity,
) {
server.tool(
"kbdb_graph_neighbors",
"knowledge graph 鄰居查詢(1-hop/N-hop 關係遍歷):給一個節點名,沿 KBDB triplet" +
@@ -60,10 +76,10 @@ export function registerGraphNeighbors(server: McpServer, env: Env, orgNamespace
depth: z.number().int().min(1).max(10).optional().describe(
"最大跳數(N-hop),預設 1(只看直接鄰居)",
),
kbdb_base: z.string().min(1).describe(
"你自己部署的 KBDB 對外 base URL(如 https://arcrun-kbdb.<你的subdomain>.workers.dev " +
"或 KBDB custom domain)。workflow 刻意不寫死任何一家的庫——" +
"帶錯(或照抄別人的值)=查詢打進別人的庫",
kbdb_base: z.string().min(1).optional().describe(
"【登入身分下不需要,留空即可】你自己部署的 KBDB 對外 base URL" +
"以帳密連線的 MCP 由 server 端自己知道要查哪個庫——不必、也不該由你指定" +
"(指定了也不會採用)。只有服務級 tokenstatic token / partner key)連線時才需要填。",
),
template: z.string().optional().describe(
"triplet 記錄的 template 名,預設 'graph_triplet'(以實際部署的 kbdb-graph-plugin " +
@@ -74,6 +90,43 @@ export function registerGraphNeighbors(server: McpServer, env: Env, orgNamespace
),
},
async ({ subject, depth, kbdb_base, template, directed }) => {
if (identity.kind === "stale") return staleIdentityError();
// ── 登入身分:走 cypher 的 portal 資料面(與人類在 portal 按「關聯」同一支端點)──
// 那支已經有 D-4 graph 粗閘(沒有 graph 來源庫權限 → 403),也已經處理好
// 「這台實例沒裝 graph plugin 就改用 tenant 的 graph_neighbors workflow」的兩條路。
// ⇒ MCP 不必要 kbdb_base、不必知道租戶、不必再認證一次。
if (identity.kind === "portal") {
try {
const res = await portalFetch(
env,
identity.portal.session,
`/portal/data/graph/neighbors/${encodeURIComponent(subject)}`,
{ query: { depth: depth ?? 1 } },
);
if (!res.ok) return portalError(res, `查「${subject}」的鄰居`);
const out = (await res.json().catch(() => null)) as
| { neighbors?: unknown[]; edges?: unknown[]; count?: number }
| null;
return successResponse(out, [
`${out?.count ?? 0} 個鄰居(depth 上限 ${depth ?? 1}`,
"count=0 且不確定資料有沒有進圖:kbdb_query(template='triplet') 看三元組記錄",
"找關鍵字內容改用 kbdb_search;取單筆全文用 kbdb_get_record",
"查詢範圍=你這個帳號被授權的知識庫(與 portal 網頁上的關聯檢視一致)",
]);
} catch (e) {
return errorResponse("internal_error", e instanceof Error ? e.message : String(e), ["稍後重試"]);
}
}
// ── 服務級憑據:既有路徑(打 /q/:ns/graph_neighbors workflow),行為零變更 ──
if (!kbdb_base) {
return errorResponse(
"kbdb_base_required",
"以服務級 token 連線時,graph 查詢需要 kbdb_base(你自己 KBDB 的對外 URL",
["改用帳密連線(OAuth)則不需要此參數", "或帶上 kbdb_base 再試一次"],
);
}
if (!orgNamespace) {
return errorResponse(
"no_namespace",
+36 -11
View File
@@ -22,6 +22,12 @@ import type { Env } from "../types.js";
import { kbdbFetch } from "../lib/kbdb-client.js";
import { errorResponse, successResponse } from "../lib/cypher-client.js";
import { entityNames, parseSlotArray, type LibraryMapRow } from "../lib/library-map.js";
import {
portalFetch,
portalError,
staleIdentityError,
type KnowledgeIdentity,
} from "../lib/portal-client.js";
/**
* /404
@@ -39,8 +45,8 @@ const RECOMPUTE_HINTS = [
];
/** 註冊全部藏書地圖工具(library-map M4)。 */
export function registerAllKbdbMapTools(server: McpServer, env: Env) {
registerGetMap(server, env);
export function registerAllKbdbMapTools(server: McpServer, env: Env, identity: KnowledgeIdentity) {
registerGetMap(server, env, identity);
}
/** 單庫詳圖回傳形狀(GET /map/:library 的 mapslot 陣列已 parse 成物件)。 */
@@ -62,7 +68,7 @@ interface LibraryMapDetail {
* kbdb_get_map library
* design §6 retrieval get_map(library) graph/search
*/
export function registerGetMap(server: McpServer, env: Env) {
export function registerGetMap(server: McpServer, env: Env, identity: KnowledgeIdentity) {
server.tool(
"kbdb_get_map",
"藏書地圖:KBDB 全館導覽。不帶參數=全館地圖(每庫一行:庫名+narrative+核心 top 3 entities" +
@@ -73,15 +79,26 @@ export function registerGetMap(server: McpServer, env: Env) {
library: z.string().min(1).optional().describe(
"庫名(如 'kb''notes')。帶了回該庫詳圖;不帶回全館地圖(先看全館再挑庫)",
),
owner_id: z.string().optional().describe("限定某資料歸屬範圍(選填,與其他 kbdb_* 工具同義)"),
owner_id: z.string().optional().describe(
"限定某資料歸屬範圍(選填;登入身分下不生效,看得到哪些庫由你的帳號權限決定)",
),
},
async ({ library, owner_id }) => {
if (identity.kind === "stale") return staleIdentityError();
try {
const qs = owner_id ? `?owner_id=${encodeURIComponent(owner_id)}` : "";
// 登入身分:走 cypher 的 portal 資料面 —— 只會回這個帳號有權限的庫
//KBDB 的 /map 對權限無知,會回全館;過濾在 cypher 那邊 server 側做)。
const isPortal = identity.kind === "portal";
const qs = !isPortal && owner_id ? `?owner_id=${encodeURIComponent(owner_id)}` : "";
const mapFetch = (path: string) =>
identity.kind === "portal"
? portalFetch(env, identity.portal.session, `/portal/data${path}`)
: kbdbFetch(env, path);
if (!library) {
// 全館地圖:每庫一行(librarynarrativetop 3 entitiestriplet_count)。
const res = await kbdbFetch(env, `/map${qs}`);
const res = await mapFetch(`/map${qs}`);
if (!res.ok && isPortal) return portalError(res, "取全館地圖");
if (!res.ok) {
return errorResponse(
"map_fetch_failed",
@@ -90,7 +107,7 @@ export function registerGetMap(server: McpServer, env: Env) {
await res.text().catch(() => ""),
);
}
const data = (await res.json()) as { libraries?: LibraryMapRow[]; count?: number };
const data = (await res.json()) as { libraries?: LibraryMapRow[]; count?: number; note?: string };
const libraries = (Array.isArray(data.libraries) ? data.libraries : []).map((l) => ({
...l,
// 防禦:top_entities 若是 JSON 字串形就 parse 成名字清單(失敗當空,誠實不 crash)。
@@ -101,8 +118,13 @@ export function registerGetMap(server: McpServer, env: Env) {
// 空庫誠實回報:不是錯誤(端點正常)。地圖是讀時即時核對重算的(見 RECOMPUTE_HINTS
// 註解),所以「地圖是空的」現在真的等於「這個租戶目前沒有任何三元組資料」,
// 不再是「沒人跑過 recompute」那種曖昧狀態。
// 登入身分下還有第二種可能:這個帳號一個庫都沒被授權——「沒權限看」與「沒有資料」
// 不可以長得一樣,所以分開講(cypher 端會附 note 說明)。
return successResponse({ libraries: [], count: 0 }, [
"全館地圖是空的:這個租戶目前沒有任何三元組資料(不是地圖沒算,是真的還沒有資料)",
isPortal
? "看不到任何庫:可能是這個知識庫真的還沒有三元組資料,也可能是你的帳號還沒被授權任何庫——請向管理員確認你的可用知識庫"
: "全館地圖是空的:這個租戶目前沒有任何三元組資料(不是地圖沒算,是真的還沒有資料)",
...(data.note ? [data.note] : []),
...RECOMPUTE_HINTS,
]);
}
@@ -113,7 +135,7 @@ export function registerGetMap(server: McpServer, env: Env) {
}
// 單庫詳圖:完整 slotsslot 陣列 parse 成物件再回)。
const res = await kbdbFetch(env, `/map/${encodeURIComponent(library)}${qs}`);
const res = await mapFetch(`/map/${encodeURIComponent(library)}${qs}`);
if (res.status === 404) {
// 地圖是讀時即時核對重算的:只要這個庫「已知」(有三元組、entries 蓋過章、或登記過),
// 上一步就會自動把它補成一筆 triplet_count:0 的地圖,走不到這個分支。真的落到 404,
@@ -121,10 +143,13 @@ export function registerGetMap(server: McpServer, env: Env) {
// (可能打錯字,或這個庫在別的租戶/別的 owner_id 底下)。
return errorResponse(
"map_not_found",
`查無庫「${library}」——這個名字在這個租戶的資料裡從沒出現過(不是「這庫是空的」,是根本沒有這個庫;地圖是即時核對重算的,不是忘了 recompute)`,
["kbdb_get_map 不帶參數看全館有哪些庫(確認庫名)", ...RECOMPUTE_HINTS],
isPortal
? `查無庫「${library}」——這個名字不存在,或不在你被授權的知識庫範圍內(兩者刻意同一句話,不洩漏某個庫存不存在)`
: `查無庫「${library}」——這個名字在這個租戶的資料裡從沒出現過(不是「這庫是空的」,是根本沒有這個庫;地圖是即時核對重算的,不是忘了 recompute)`,
["kbdb_get_map 不帶參數看全館有哪些庫(確認庫名/確認你有權限的庫)", ...RECOMPUTE_HINTS],
);
}
if (!res.ok && isPortal) return portalError(res, `取庫「${library}」詳圖`);
if (!res.ok) {
return errorResponse(
"map_fetch_failed",
+14 -5
View File
@@ -20,8 +20,15 @@ import { registerAllKbdbDataTools } from "./kbdb_data.js";
import { registerAllKbdbGraphTools } from "./kbdb_graph.js";
import { registerAllKbdbMapTools } from "./kbdb_map.js";
import { registerWhoami } from "./arcrun_whoami.js";
import type { KnowledgeIdentity } from "../lib/portal-client.js";
export function registerAllTools(server: McpServer, env: Env, orgNamespace: string, partnerToken: string) {
export function registerAllTools(
server: McpServer,
env: Env,
orgNamespace: string,
partnerToken: string,
identity: KnowledgeIdentity,
) {
registerSearchComponents(server, env, orgNamespace);
// 🔴 2026-07-21 leo 拍板停用:零件走 PR、專業等級;recipe/workflow/app 誰都可以做。
// 零件貢獻**只有一條路=PR 人審**leo 2026-08-01:「已經沒有 publish 了,
@@ -53,13 +60,15 @@ export function registerAllTools(server: McpServer, env: Env, orgNamespace: stri
registerAllRecipeTools(server, env);
// kbdb-base Phase 9.1: KBDB 資料層薄殼(template/record/query/searchHANDOFF §2
// 鐵律:不提供建表/SQL toolAI 只有 template+slot 可用(類 Supabase 萬用表)
registerAllKbdbDataTools(server, env);
// 2026-08-12:知識面(kbdb_*)全部改吃 identity——以帳密連線者走 portal 資料面
// (權限=那個人的權限),服務級憑據維持既有 KBDB 直連。見 lib/portal-client.ts。
registerAllKbdbDataTools(server, env, identity);
// issue #68: KBDB graph 查詢薄殼(kbdb_graph_neighbors,調 /q/:ns/graph_neighbors 同步查詢端點)
// 補齊 D17「KBDB MCP=RAG 套餐」第三模式:關鍵字/語義之外的圖(關係遍歷)
registerAllKbdbGraphTools(server, env, orgNamespace);
registerAllKbdbGraphTools(server, env, orgNamespace, identity);
// library-map SDD M4Arcrun#39: 藏書地圖薄殼(kbdb_get_map,調 kbdb GET /map/map/:library
// retrieval 第一站:先看地圖定位庫,再 search/graph 進庫(design §6
registerAllKbdbMapTools(server, env);
registerAllKbdbMapTools(server, env, identity);
// §7.8 P1 D2: whoami(與 CLI acr whoami 對齊,AI 不繞 CLI 自己 curl 猜帳號)
registerWhoami(server, env, orgNamespace);
registerWhoami(server, env, orgNamespace, identity);
}
+18 -4
View File
@@ -2,6 +2,15 @@ export interface Env {
COMPONENT_REGISTRY: Fetcher;
CYPHER_EXECUTOR: Fetcher;
KBDB: Fetcher;
/**
* KBDB
*
* 2026-08-12 **kbdb_*** cypher
* `/portal/data/*` portal session
* SaaS partner-key middleware/partner-auth.ts 3
* tokenstatic token KBDB
* binding MCP
*/
KBDB_INTERNAL_TOKEN: string;
API_KEY?: string;
// Platform telemetry / feedback aggregation key (optional)
@@ -20,11 +29,16 @@ export interface Env {
// 短效認證儲存:authorization codeTTL ~600s+ access tokenTTL = MCP_TOKEN_TTL)。
// 只放「取得的暫時性認證」,key 用 SHA-256 hashKV list 不外洩可用 token)。長效機密不進 KV。
OAUTH_KV?: KVNamespace;
// Owner 祕密(CF Secret,非 KV、非明碼 var):/authorize 同意頁的把關密碼。
// 只有 owner 知道 → 「只知 URL + 明碼 namespace」的人走不完 OAuth,拿不到 token。
// 未設 → OAuth /authorize 回 503(拒絕在無把關下發碼,不留不安全預設)
// 【已停用,2026-07-30】舊的 owner 祕密。把關改成「使用者自己的 Portal 帳密」——
// 沒人給得了封測者這把祕密(安裝器產生後從不顯示、CF secret 又讀不回),
// 而且全實例共用一把、分不出是誰連上來的。程式已不再讀它;欄位留著只為不讓舊 toml 炸掉
MCP_OWNER_SECRET?: string;
// OAuth 換發出的 access_token 綁定的 namespaceowner 的資料分區)。預設 "leo"。
// **工作流面**(arcrun_* 工具)的租戶代號,當 cypher 的 X-Arcrun-API-Key 用。預設 "leo"。
//
// ⚠️ 2026-08-12 起**知識面(kbdb_*)不再讀這個欄位**:那邊改成跟著登入者的 portal session
// 走(oauth/store.ts PortalIdentity)。此欄位曾被當成 KBDB 的 owner_id ⇒ 不管誰登入
// 都看到同一格、而且是全部——那個用法已經消滅。
// 要連工作流面也拆掉它,得先在 cypher 開一組吃 portal session 的 workflow 端點(下一步)。
MCP_OWNER_NAMESPACE?: string;
// access_token 存活秒數(同時是 KV TTL)。字串(toml var)。預設 259200030 天)。
// 過期後 claude.ai 重走 OAuthowner 重輸祕密)——刻意不做 refresh token 以免長效機密落地。
+202 -12
View File
@@ -59,14 +59,55 @@ async function pkcePair() {
return { verifier, challenge };
}
/**
* cypher `/portal/login` 2026-08-12 MCP 使
* Portal owner secret session_token 401
*/
const GOOD_EMAIL = "leo@example.com";
const GOOD_PASSWORD = "correct horse";
function cypherMock(
over: {
/** null 登入成功但**不回** session_token(舊版 cypher);預設回 "sess-abc" */
sessionToken?: string | null;
displayName?: string;
role?: string;
libraries?: string[];
sessionExpiresIn?: number;
} = {},
): { fetcher: Fetcher; calls: Array<{ email: string; password: string }> } {
const calls: Array<{ email: string; password: string }> = [];
const fetcher = {
async fetch(req: Request) {
const body = (await req.json()) as { email: string; password: string };
calls.push(body);
if (body.email !== GOOD_EMAIL || body.password !== GOOD_PASSWORD) {
return new Response(JSON.stringify({ error: "email 或密碼錯誤" }), { status: 401 });
}
const sessionToken = over.sessionToken === undefined ? "sess-abc" : over.sessionToken;
return new Response(
JSON.stringify({
success: true,
...(sessionToken ? { session_token: sessionToken } : {}),
display_name: over.displayName ?? "Leo",
role: over.role ?? "admin",
libraries: over.libraries ?? ["*"],
session_expires_in: over.sessionExpiresIn ?? 604800,
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
},
} as unknown as Fetcher;
return { fetcher, calls };
}
function baseEnv(over: Partial<Env> = {}): Env {
return {
COMPONENT_REGISTRY: {} as Fetcher,
CYPHER_EXECUTOR: {} as Fetcher,
CYPHER_EXECUTOR: cypherMock().fetcher,
KBDB: {} as Fetcher,
KBDB_INTERNAL_TOKEN: "internal",
OAUTH_KV: makeKV(),
MCP_OWNER_SECRET: "s3cr3t-owner",
MCP_OWNER_NAMESPACE: "leo",
...over,
} as Env;
@@ -121,6 +162,8 @@ describe("oauth/store", () => {
scope: "mcp",
resource: "https://mcp/mcp",
namespace: "leo",
portal: { session: "sess-abc", display_name: "Leo", role: "admin", libraries: ["*"] },
portal_session_expires_in: 604800,
});
const first = await consumeAuthCode(kv, "code-1");
expect(first?.namespace).toBe("leo");
@@ -271,7 +314,11 @@ describe("oauth flow (整合)", () => {
)}&code_challenge=${challenge}&code_challenge_method=S256&state=xyz&scope=mcp`,
);
expect(ok.status).toBe(200);
expect(await ok.text()).toContain("Owner 祕密");
const consentHtml = await ok.text();
// 同意頁問的是 Portal 帳密(不是另一把 owner secret
expect(consentHtml).toContain("Portal");
expect(consentHtml).toContain('name="email"');
expect(consentHtml).toContain('name="password"');
// 缺 PKCE → 400
const bad = await app.req(
`/authorize?response_type=code&client_id=c1&redirect_uri=${encodeURIComponent(
@@ -281,18 +328,19 @@ describe("oauth flow (整合)", () => {
expect(bad.status).toBe(400);
});
it("GET /authorizeMCP_OWNER_SECRET 未設 → 503(不留不安全預設", async () => {
const app = buildApp(baseEnv({ MCP_OWNER_SECRET: undefined }));
it("GET /authorize不需要任何 owner 祕密就看得到同意頁(封測者接自己的 AI 不會死在這頁", async () => {
// 舊行為:未設 MCP_OWNER_SECRET → 503 ⇒ 每個封測者都卡住。現在把關是 Portal 帳密。
const app = buildApp(baseEnv());
const { challenge } = await pkcePair();
const r = await app.req(
`/authorize?response_type=code&client_id=c1&redirect_uri=${encodeURIComponent(
"https://claude.ai/cb",
)}&code_challenge=${challenge}&code_challenge_method=S256`,
);
expect(r.status).toBe(503);
expect(r.status).toBe(200);
});
it("完整 code→token:正確 owner 祕密 + 正確 verifier → access_token", async () => {
it("完整 code→token:正確 Portal 帳密 + 正確 verifier → access_token", async () => {
const env = baseEnv();
const app = buildApp(env);
const { verifier, challenge } = await pkcePair();
@@ -310,7 +358,8 @@ describe("oauth flow (整合)", () => {
code_challenge_method: "S256",
scope: "mcp",
resource: "https://mcp.arcrun.dev/mcp",
owner_secret: "s3cr3t-owner",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
@@ -344,6 +393,143 @@ describe("oauth flow (整合)", () => {
expect(at?.aud).toBe("https://mcp.arcrun.dev/mcp");
});
// ── 2026-08-12:身分要接住並攜帶(本次修的病根)─────────────────────────────
describe("登入者身分跟著 token 走(leo:掛上 MCP 並輸入帳密=授權,下游不得再問一次)", () => {
it("驗完帳密不是只留布林值:token 帶得出 portal session 與該帳號的可用知識庫", async () => {
const env = baseEnv({ CYPHER_EXECUTOR: cypherMock({ libraries: ["kb"], displayName: "小明", role: "user" }).fetcher });
const app = buildApp(env);
const { verifier, challenge } = await pkcePair();
const redirect = "https://claude.ai/cb";
const authRes = await app.req("/authorize", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: "c1",
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
const code = new URL(authRes.headers.get("location")!).searchParams.get("code")!;
const tokRes = await app.req("/token", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
code_verifier: verifier,
redirect_uri: redirect,
}).toString(),
});
const at = await getAccessToken(env.OAUTH_KV!, (await tokRes.json()).access_token);
expect(at?.portal?.session).toBe("sess-abc");
expect(at?.portal?.display_name).toBe("小明");
expect(at?.portal?.role).toBe("user");
expect(at?.portal?.libraries).toEqual(["kb"]);
});
it("**不同帳號登入 → token 帶的身分跟著換**(不是不管誰登入都同一格)", async () => {
// 兩個帳號權限不同:一個全庫、一個只有 kb。token 裡的身分必須各自不同。
const envA = baseEnv({ CYPHER_EXECUTOR: cypherMock({ sessionToken: "sess-A", displayName: "Leo", libraries: ["*"] }).fetcher });
const envB = baseEnv({ CYPHER_EXECUTOR: cypherMock({ sessionToken: "sess-B", displayName: "小明", libraries: ["kb"] }).fetcher });
async function tokenFor(env: Env) {
const app = buildApp(env);
const { verifier, challenge } = await pkcePair();
const redirect = "https://claude.ai/cb";
const a = await app.req("/authorize", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: "c1",
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
const code = new URL(a.headers.get("location")!).searchParams.get("code")!;
const t = await app.req("/token", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
code_verifier: verifier,
redirect_uri: redirect,
}).toString(),
});
return getAccessToken(env.OAUTH_KV!, (await t.json()).access_token);
}
const a = await tokenFor(envA);
const b = await tokenFor(envB);
expect(a?.portal?.session).not.toBe(b?.portal?.session);
expect(a?.portal?.libraries).toEqual(["*"]);
expect(b?.portal?.libraries).toEqual(["kb"]);
});
it("access_token 活不過它底下的 portal sessionTTL 取兩者較小)", async () => {
const env = baseEnv({
MCP_TOKEN_TTL: "2592000", // 30 天
CYPHER_EXECUTOR: cypherMock({ sessionExpiresIn: 3600 }).fetcher, // session 只有 1 小時
});
const app = buildApp(env);
const { verifier, challenge } = await pkcePair();
const redirect = "https://claude.ai/cb";
const a = await app.req("/authorize", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: "c1",
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
const code = new URL(a.headers.get("location")!).searchParams.get("code")!;
const t = await app.req("/token", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
code_verifier: verifier,
redirect_uri: redirect,
}).toString(),
});
expect((await t.json()).expires_in).toBe(3600);
});
it("cypher 回 200 但沒給 session_token(舊版 cypher)→ 不發碼(不發一張沒有身分的 token)", async () => {
const app = buildApp(baseEnv({ CYPHER_EXECUTOR: cypherMock({ sessionToken: null }).fetcher }));
const { challenge } = await pkcePair();
const r = await app.req("/authorize", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: "c1",
redirect_uri: "https://claude.ai/cb",
code_challenge: challenge,
code_challenge_method: "S256",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
expect(r.status).toBe(401);
expect(r.headers.get("location")).toBeNull();
});
});
it("錯誤 owner 祕密 → 401、不發 code", async () => {
const app = buildApp(baseEnv());
const { challenge } = await pkcePair();
@@ -355,7 +541,8 @@ describe("oauth flow (整合)", () => {
redirect_uri: "https://claude.ai/cb",
code_challenge: challenge,
code_challenge_method: "S256",
owner_secret: "WRONG",
email: GOOD_EMAIL,
password: "WRONG",
}).toString(),
redirect: "manual",
});
@@ -377,7 +564,8 @@ describe("oauth flow (整合)", () => {
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
owner_secret: "s3cr3t-owner",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
@@ -445,7 +633,8 @@ describe("oauth resourceRFC 8707)簽發端把關", () => {
code_challenge: challenge,
code_challenge_method: "S256",
resource,
owner_secret: "s3cr3t-owner",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
@@ -570,7 +759,8 @@ describe("oauth store drift guardOAUTH_KV 的 put 一律帶 TTL", () => {
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
owner_secret: "s3cr3t-owner",
email: GOOD_EMAIL,
password: GOOD_PASSWORD,
}).toString(),
redirect: "manual",
});
@@ -0,0 +1,208 @@
/**
* kbdb_* ****2026-08-12
*
* leo Portal 西AI
* MCP AI西
* MCP
*
*
* ** portal session** cypher `/portal/data/*`
* KBDB KBDB
* owner_id ****
* token**fail-closed**退
* static token / partner key KBDB
*/
import { describe, it, expect } from "vitest";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { Env } from "../../../src/types.js";
import { registerAllKbdbDataTools } from "../../../src/tools/kbdb_data.js";
import type { KnowledgeIdentity } from "../../../src/lib/portal-client.js";
type ToolHandler = (args: Record<string, unknown>) => Promise<{
content: { type: string; text: string }[];
isError?: boolean;
}>;
function makeServer() {
const tools = new Map<string, { description: string; handler: ToolHandler }>();
const server = {
tool(name: string, description: string, _schema: unknown, handler: ToolHandler) {
tools.set(name, { description, handler });
},
};
return { server: server as unknown as McpServer, tools };
}
/** 兩個 binding 都掛上,才驗得出「該走哪一條」——走錯的那條會被記錄下來。 */
function makeEnv(respond: (which: "cypher" | "kbdb", url: URL, init?: RequestInit) => Response) {
const cypherCalls: { url: URL; init?: RequestInit }[] = [];
const kbdbCalls: { url: URL; init?: RequestInit }[] = [];
const env = {
CYPHER_EXECUTOR: {
fetch: async (input: string, init?: RequestInit) => {
const url = new URL(input);
cypherCalls.push({ url, init });
return respond("cypher", url, init);
},
},
KBDB: {
fetch: async (input: string, init?: RequestInit) => {
const url = new URL(input);
kbdbCalls.push({ url, init });
return respond("kbdb", url, init);
},
},
KBDB_INTERNAL_TOKEN: "service-key-should-not-be-used-on-portal-path",
} as unknown as Env;
return { env, cypherCalls, kbdbCalls };
}
function parseResult(r: { content: { text: string }[] }) {
return JSON.parse(r.content[0].text) as Record<string, unknown>;
}
const PORTAL: KnowledgeIdentity = {
kind: "portal",
portal: { session: "sess-abc", display_name: "Leo", role: "admin", libraries: ["kb"] },
};
const SERVICE: KnowledgeIdentity = { kind: "service" };
const STALE: KnowledgeIdentity = { kind: "stale" };
function tools(identity: KnowledgeIdentity, respond: Parameters<typeof makeEnv>[0]) {
const { server, tools } = makeServer();
const e = makeEnv(respond);
registerAllKbdbDataTools(server, e.env, identity);
return { tools, ...e };
}
const OK = () => new Response(JSON.stringify({ success: true, entries: [], records: [], count: 0 }));
describe("kbdb_* 以登入者身分查詢(portal 資料面)", () => {
const cases: Array<{ tool: string; args: Record<string, unknown>; path: string; method?: string }> = [
{ tool: "kbdb_search", args: { q: "火星座標" }, path: "/portal/data/search" },
{ tool: "kbdb_query", args: { template: "triplet" }, path: "/portal/data/records/by-template/triplet" },
{ tool: "kbdb_get_record", args: { record_id: "rec_1" }, path: "/portal/data/records/rec_1" },
{ tool: "kbdb_list_templates", args: {}, path: "/portal/data/templates" },
{ tool: "kbdb_create_template", args: { name: "contact", slots: ["name"] }, path: "/portal/data/templates", method: "POST" },
{ tool: "kbdb_create_record", args: { template: "contact", values: { name: "Leo" } }, path: "/portal/data/records", method: "POST" },
];
for (const c of cases) {
it(`${c.tool} → 打 ${c.path},帶登入者 session,完全不碰 KBDB 服務金鑰`, async () => {
const { tools: t, cypherCalls, kbdbCalls } = tools(PORTAL, OK);
const res = await t.get(c.tool)!.handler(c.args);
expect(res.isError).toBeUndefined();
// 走的是 cypher 的 portal 資料面,不是 KBDB 直連
expect(kbdbCalls, `${c.tool} 不該直打 KBDB`).toHaveLength(0);
expect(cypherCalls).toHaveLength(1);
expect(cypherCalls[0].url.pathname).toBe(c.path);
expect(cypherCalls[0].init?.method ?? "GET").toBe(c.method ?? "GET");
// 帶的是「那個人的 session」,不是任何服務金鑰
const auth = new Headers(cypherCalls[0].init!.headers as HeadersInit).get("Authorization");
expect(auth).toBe("Bearer sess-abc");
expect(auth).not.toContain("service-key");
});
}
it("呼叫端自帶 owner_id 一律不生效(不讓呼叫端自己挑租戶/歸屬)", async () => {
const { tools: t, cypherCalls } = tools(PORTAL, OK);
await t.get("kbdb_search")!.handler({ q: "x", owner_id: "someone-else" });
await t.get("kbdb_query")!.handler({ template: "triplet", owner_id: "someone-else" });
for (const call of cypherCalls) {
expect(call.url.searchParams.get("owner_id")).toBeNull();
}
});
it("寫入時 owner_id 不從呼叫端 body 走(server 定死成登入者的歸屬)", async () => {
const { tools: t, cypherCalls } = tools(PORTAL, OK);
await t.get("kbdb_create_record")!.handler({
template: "contact",
values: { name: "Leo" },
owner_id: "someone-else",
});
const body = JSON.parse(String(cypherCalls[0].init!.body)) as Record<string, unknown>;
expect(body).not.toHaveProperty("owner_id");
});
it("越庫寫入被擋(403)→ 誠實講是權限問題", async () => {
const { tools: t } = tools(PORTAL, () =>
new Response(JSON.stringify({ error: '無「secret」庫的權限,不能寫入該庫' }), { status: 403 }),
);
const res = await t.get("kbdb_create_record")!.handler({
template: "note",
values: { library: "secret", body: "x" },
});
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("forbidden");
});
it("查不是自己的 record(404)→ 與「不存在」同一句話(不洩存在性)", async () => {
const { tools: t } = tools(PORTAL, () =>
new Response(JSON.stringify({ error: "找不到這筆資料" }), { status: 404 }),
);
const res = await t.get("kbdb_get_record")!.handler({ record_id: "rec_someone_else" });
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("not_found");
expect(String(parseResult(res).human_message)).toContain("不在你的權限範圍內");
});
it("session 過期(401)→ session_expired,不謊稱資料是空的", async () => {
const { tools: t } = tools(PORTAL, () =>
new Response(JSON.stringify({ error: "session 無效或已過期" }), { status: 401 }),
);
const res = await t.get("kbdb_search")!.handler({ q: "x" });
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("session_expired");
});
});
describe("fail-closed:舊 token 沒有身分就查不到東西(不退回服務金鑰)", () => {
for (const name of [
"kbdb_search",
"kbdb_query",
"kbdb_get_record",
"kbdb_list_templates",
"kbdb_create_template",
"kbdb_create_record",
]) {
it(`${name} → identity_missing,且一個查詢都不發`, async () => {
const { tools: t, cypherCalls, kbdbCalls } = tools(STALE, OK);
const res = await t.get(name)!.handler({
q: "x",
template: "t",
record_id: "r",
name: "n",
slots: ["a"],
values: { a: "b" },
});
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("identity_missing");
expect(cypherCalls).toHaveLength(0);
expect(kbdbCalls).toHaveLength(0);
});
}
});
describe("回歸:服務級憑據維持既有 KBDB 直連", () => {
it("kbdb_search 仍直打 KBDB /entries/search,且照舊吃 owner_id", async () => {
const { tools: t, cypherCalls, kbdbCalls } = tools(SERVICE, OK);
const res = await t.get("kbdb_search")!.handler({ q: "x", owner_id: "leo" });
expect(res.isError).toBeUndefined();
expect(cypherCalls).toHaveLength(0);
expect(kbdbCalls).toHaveLength(1);
expect(kbdbCalls[0].url.pathname).toBe("/entries/search");
expect(kbdbCalls[0].url.searchParams.get("owner_id")).toBe("leo");
});
it("kbdb_query / kbdb_get_record 路徑不變", async () => {
const { tools: t, kbdbCalls } = tools(SERVICE, OK);
await t.get("kbdb_query")!.handler({ template: "triplet" });
await t.get("kbdb_get_record")!.handler({ record_id: "rec_1" });
expect(kbdbCalls.map((c) => c.url.pathname)).toEqual([
"/records/by-template/triplet",
"/records/rec_1",
]);
});
});
+92 -7
View File
@@ -5,6 +5,17 @@ import {
registerGraphNeighbors,
GRAPH_NEIGHBORS_WORKFLOW,
} from "../../../src/tools/kbdb_graph.js";
import type { KnowledgeIdentity } from "../../../src/lib/portal-client.js";
/** 服務級憑據(static token / partner key)——既有路徑,行為零變更。 */
const SERVICE: KnowledgeIdentity = { kind: "service" };
/** 有人輸入 Portal 帳密授權的連線——走 cypher 的 portal 資料面。 */
const PORTAL: KnowledgeIdentity = {
kind: "portal",
portal: { session: "sess-abc", display_name: "Leo", role: "admin", libraries: ["*"] },
};
/** 本次改版前簽發的舊 token(沒有身分)。 */
const STALE: KnowledgeIdentity = { kind: "stale" };
// ── 假 McpServer:只攔 tool 註冊,抓出 handler 直接呼叫 ─────────────────────────
type ToolHandler = (args: Record<string, unknown>) => Promise<{
@@ -45,7 +56,7 @@ describe("kbdb_graph_neighbors: registration", () => {
it("registers under kbdb_* prefix (D17 KBDB MCP boundary)", () => {
const { server, tools } = makeServer();
const { env } = makeEnv(() => new Response("{}"));
registerGraphNeighbors(server, env, "leo");
registerGraphNeighbors(server, env, "leo", SERVICE);
expect(tools.has("kbdb_graph_neighbors")).toBe(true);
expect(tools.get("kbdb_graph_neighbors")!.description).toContain("graph");
});
@@ -61,7 +72,7 @@ describe("kbdb_graph_neighbors: request shape", () => {
{ status: 200 },
),
);
registerGraphNeighbors(server, env, "leo");
registerGraphNeighbors(server, env, "leo", SERVICE);
const res = await tools.get("kbdb_graph_neighbors")!.handler({
subject: "Arcrun",
depth: 2,
@@ -88,7 +99,7 @@ describe("kbdb_graph_neighbors: request shape", () => {
const { env, calls } = makeEnv(
() => new Response(JSON.stringify({ success: true, neighbors: [], count: 0 })),
);
registerGraphNeighbors(server, env, "leo");
registerGraphNeighbors(server, env, "leo", SERVICE);
await tools.get("kbdb_graph_neighbors")!.handler({
subject: "A",
kbdb_base: "https://kbdb.example.com",
@@ -108,7 +119,7 @@ describe("kbdb_graph_neighbors: honest errors (鐵律:workflow 沒裝不 crash
const { env } = makeEnv(
() => new Response(JSON.stringify({ error: '找不到 workflow "graph_neighbors"' }), { status: 404 }),
);
registerGraphNeighbors(server, env, "leo");
registerGraphNeighbors(server, env, "leo", SERVICE);
const res = await tools.get("kbdb_graph_neighbors")!.handler({
subject: "A",
kbdb_base: "https://kbdb.example.com",
@@ -124,7 +135,7 @@ describe("kbdb_graph_neighbors: honest errors (鐵律:workflow 沒裝不 crash
const { env } = makeEnv(
() => new Response(JSON.stringify({ success: false, error: "boom", trace: [] }), { status: 500 }),
);
registerGraphNeighbors(server, env, "leo");
registerGraphNeighbors(server, env, "leo", SERVICE);
const res = await tools.get("kbdb_graph_neighbors")!.handler({
subject: "A",
kbdb_base: "https://kbdb.example.com",
@@ -143,7 +154,7 @@ describe("kbdb_graph_neighbors: honest errors (鐵律:workflow 沒裝不 crash
status: 200,
}),
);
registerGraphNeighbors(server, env, "leo");
registerGraphNeighbors(server, env, "leo", SERVICE);
const res = await tools.get("kbdb_graph_neighbors")!.handler({
subject: "A",
kbdb_base: "https://kbdb.example.com",
@@ -156,7 +167,7 @@ describe("kbdb_graph_neighbors: honest errors (鐵律:workflow 沒裝不 crash
it("empty orgNamespace → no_namespace error, no fetch made", async () => {
const { server, tools } = makeServer();
const { env, calls } = makeEnv(() => new Response("{}"));
registerGraphNeighbors(server, env, "");
registerGraphNeighbors(server, env, "", SERVICE);
const res = await tools.get("kbdb_graph_neighbors")!.handler({
subject: "A",
kbdb_base: "https://kbdb.example.com",
@@ -166,3 +177,77 @@ describe("kbdb_graph_neighbors: honest errors (鐵律:workflow 沒裝不 crash
expect(calls).toHaveLength(0);
});
});
// ── 2026-08-12:以帳密連線時走登入者的身分(leo:主人查得到的,授權的 AI 就查得到)──
describe("kbdb_graph_neighbors: 登入身分(portal 資料面)", () => {
it("打 cypher 的 /portal/data/graph/neighbors,且帶的是登入者的 session(不是服務金鑰)", async () => {
const { server, tools } = makeServer();
const { env, calls } = makeEnv(
() =>
new Response(
JSON.stringify({
neighbors: [{ node: "B", predicate: "uses", from: "A", depth: 1 }],
edges: [],
count: 1,
}),
{ status: 200 },
),
);
registerGraphNeighbors(server, env, "leo", PORTAL);
const res = await tools.get("kbdb_graph_neighbors")!.handler({ subject: "A", depth: 2 });
expect(calls).toHaveLength(1);
expect(calls[0].url.pathname).toBe("/portal/data/graph/neighbors/A");
expect(calls[0].url.searchParams.get("depth")).toBe("2");
const headers = new Headers(calls[0].init!.headers as HeadersInit);
expect(headers.get("Authorization")).toBe("Bearer sess-abc");
expect(res.isError).toBeUndefined();
expect((parseResult(res).data as { count: number }).count).toBe(1);
});
it("**不需要 kbdb_base**:已經登入過了,不再要第二次「證明你是誰/你的庫在哪」", async () => {
const { server, tools } = makeServer();
const { env, calls } = makeEnv(
() => new Response(JSON.stringify({ neighbors: [], edges: [], count: 0 })),
);
registerGraphNeighbors(server, env, "leo", PORTAL);
const res = await tools.get("kbdb_graph_neighbors")!.handler({ subject: "A" });
expect(res.isError).toBeUndefined();
expect(calls).toHaveLength(1);
// 呼叫端就算硬塞 kbdb_base 也不會被拿去用(server 自己知道要查哪個庫)
expect(calls[0].url.searchParams.get("kbdb_base")).toBeNull();
});
it("session 過期(401)→ 誠實說是登入過期,不說「查不到資料」", async () => {
const { server, tools } = makeServer();
const { env } = makeEnv(
() => new Response(JSON.stringify({ error: "session 無效或已過期" }), { status: 401 }),
);
registerGraphNeighbors(server, env, "leo", PORTAL);
const res = await tools.get("kbdb_graph_neighbors")!.handler({ subject: "A" });
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("session_expired");
});
it("無 graph 權限(403)→ 誠實回沒權限,不假裝「沒有關聯」", async () => {
const { server, tools } = makeServer();
const { env } = makeEnv(
() => new Response(JSON.stringify({ error: "無知識圖譜檢視權限" }), { status: 403 }),
);
registerGraphNeighbors(server, env, "leo", PORTAL);
const res = await tools.get("kbdb_graph_neighbors")!.handler({ subject: "A" });
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("forbidden");
});
it("舊 token(沒有身分)→ 不偷偷退回服務金鑰那條老路,要求重新連線", async () => {
const { server, tools } = makeServer();
const { env, calls } = makeEnv(() => new Response("{}"));
registerGraphNeighbors(server, env, "leo", STALE);
const res = await tools.get("kbdb_graph_neighbors")!.handler({ subject: "A" });
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("identity_missing");
expect(calls).toHaveLength(0); // 一個查詢都沒發出去(fail-closed
});
});
+135 -17
View File
@@ -7,6 +7,32 @@ import {
renderLibraryMapLines,
__resetLibraryMapInstructionsCacheForTests,
} from "../../../src/lib/library-map.js";
import type { KnowledgeIdentity } from "../../../src/lib/portal-client.js";
/** 服務級憑據(static token / partner key)——既有 KBDB 直連路徑,行為零變更。 */
const SERVICE: KnowledgeIdentity = { kind: "service" };
/** 有人輸入 Portal 帳密授權的連線——走 cypher 的 portal 資料面(只看得到自己有權限的庫)。 */
const PORTAL: KnowledgeIdentity = {
kind: "portal",
portal: { session: "sess-abc", display_name: "Leo", role: "admin", libraries: ["kb"] },
};
/** 本次改版前簽發的舊 token(沒有身分)。 */
const STALE: KnowledgeIdentity = { kind: "stale" };
/** 假 CYPHER_EXECUTOR bindingportal 資料面用)。 */
function makePortalEnv(respond: (url: URL, init?: RequestInit) => Response) {
const calls: { url: URL; init?: RequestInit }[] = [];
const env = {
CYPHER_EXECUTOR: {
fetch: async (input: string, init?: RequestInit) => {
const url = new URL(input);
calls.push({ url, init });
return respond(url, init);
},
},
} as unknown as Env;
return { env, calls };
}
// ── 假 McpServer:只攔 tool 註冊,抓出 handler 直接呼叫(比照 kbdb-graph.test.ts)──────
type ToolHandler = (args: Record<string, unknown>) => Promise<{
@@ -56,7 +82,7 @@ describe("kbdb_get_map: registration", () => {
it("registers under kbdb_* prefix (D17) with the 'call this first' hint in description", () => {
const { server, tools } = makeServer();
const { env } = makeEnv(() => new Response("{}"));
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
expect(tools.has("kbdb_get_map")).toBe(true);
// 任務規格:description 必含「不確定該查什麼時,先呼叫此工具」
expect(tools.get("kbdb_get_map")!.description).toContain("不確定該查什麼時,先呼叫此工具");
@@ -69,7 +95,7 @@ describe("kbdb_get_map: 全館地圖(無參數)", () => {
const { env, calls } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [KB_ROW], count: 1 })),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({});
expect(calls).toHaveLength(1);
@@ -90,7 +116,7 @@ describe("kbdb_get_map: 全館地圖(無參數)", () => {
const { env, calls } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [], count: 0 })),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
await tools.get("kbdb_get_map")!.handler({ owner_id: "leo" });
expect(calls[0].url.searchParams.get("owner_id")).toBe("leo");
});
@@ -105,7 +131,7 @@ describe("kbdb_get_map: 全館地圖(無參數)", () => {
const { env } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [row], count: 1 })),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({});
const data = parseResult(res).data as {
libraries: { top_entities: string[]; triplet_count: number }[];
@@ -119,7 +145,7 @@ describe("kbdb_get_map: 全館地圖(無參數)", () => {
const { env } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [], count: 0 })),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({});
const body = parseResult(res);
expect(body.ok).toBe(true);
@@ -135,7 +161,7 @@ describe("kbdb_get_map: 全館地圖(無參數)", () => {
const { env } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [], count: 0 })),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({});
const body = parseResult(res);
const hintsText = JSON.stringify(body.hints);
@@ -149,7 +175,7 @@ describe("kbdb_get_map: 全館地圖(無參數)", () => {
it("HTTP error → map_fetch_failed with recompute hint, not a crash", async () => {
const { server, tools } = makeServer();
const { env } = makeEnv(() => new Response("boom", { status: 500 }));
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({});
expect(res.isError).toBe(true);
const body = parseResult(res);
@@ -178,7 +204,7 @@ describe("kbdb_get_map: 單庫詳圖(library 參數)", () => {
const { env, calls } = makeEnv(
() => new Response(JSON.stringify({ success: true, map: DETAIL })),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({ library: "kb" });
expect(calls[0].url.pathname).toBe("/map/kb");
const map = (parseResult(res).data as { map: typeof DETAIL }).map;
@@ -197,7 +223,7 @@ describe("kbdb_get_map: 單庫詳圖(library 參數)", () => {
triplet_count: "111",
};
const { env } = makeEnv(() => new Response(JSON.stringify({ success: true, map: raw })));
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({ library: "kb" });
expect(res.isError).toBeUndefined();
const map = (parseResult(res).data as { map: Record<string, unknown> }).map;
@@ -212,7 +238,7 @@ describe("kbdb_get_map: 單庫詳圖(library 參數)", () => {
const { env } = makeEnv(
() => new Response(JSON.stringify({ success: false, error: "not found" }), { status: 404 }),
);
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({ library: "ghost" });
expect(res.isError).toBe(true);
const body = parseResult(res);
@@ -233,7 +259,7 @@ describe("kbdb_get_map: 單庫詳圖(library 參數)", () => {
},
},
} as unknown as Env;
registerGetMap(server, env);
registerGetMap(server, env, SERVICE);
const res = await tools.get("kbdb_get_map")!.handler({ library: "kb" });
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("internal_error");
@@ -258,7 +284,7 @@ describe("buildLibraryMapInstructions", () => {
}),
),
);
const text = await buildLibraryMapInstructions(env);
const text = await buildLibraryMapInstructions(env, SERVICE);
expect(text).not.toBeNull();
// design §4 格式:{library}{narrative}|核心:{top3}{triplet_count} triplets
expect(text!).toContain("kbleo 的知識庫主庫|核心:00-INDEX、kb/00-INDEX、Gitea111 triplets");
@@ -269,7 +295,7 @@ describe("buildLibraryMapInstructions", () => {
it("HTTP error → null(靜默略過,不 throw 不擋連線)", async () => {
const { env } = makeEnv(() => new Response("boom", { status: 500 }));
await expect(buildLibraryMapInstructions(env)).resolves.toBeNull();
await expect(buildLibraryMapInstructions(env, SERVICE)).resolves.toBeNull();
});
it("binding throws → null(靜默略過)", async () => {
@@ -280,22 +306,22 @@ describe("buildLibraryMapInstructions", () => {
},
},
} as unknown as Env;
await expect(buildLibraryMapInstructions(env)).resolves.toBeNull();
await expect(buildLibraryMapInstructions(env, SERVICE)).resolves.toBeNull();
});
it("empty libraries → null(沒地圖就不注入,不塞空段落)", async () => {
const { env } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [], count: 0 })),
);
await expect(buildLibraryMapInstructions(env)).resolves.toBeNull();
await expect(buildLibraryMapInstructions(env, SERVICE)).resolves.toBeNull();
});
it("caches within TTLsame isolate 第二次不再打 /map", async () => {
const { env, calls } = makeEnv(
() => new Response(JSON.stringify({ success: true, libraries: [KB_ROW], count: 1 })),
);
const first = await buildLibraryMapInstructions(env);
const second = await buildLibraryMapInstructions(env);
const first = await buildLibraryMapInstructions(env, SERVICE);
const second = await buildLibraryMapInstructions(env, SERVICE);
expect(second).toBe(first);
expect(calls).toHaveLength(1);
});
@@ -318,3 +344,95 @@ describe("renderLibraryMapLines", () => {
expect(renderLibraryMapLines([])).toBeNull();
});
});
// ── 2026-08-12:地圖也要跟著登入者的權限走 ────────────────────────────────────
// 地圖本身就是情報(有哪些庫、各有多少關聯、核心 entity 是誰)——不能整館推給
// 一個只有部分權限的帳號。
describe("藏書地圖:登入身分(portal 資料面)", () => {
beforeEach(() => __resetLibraryMapInstructionsCacheForTests());
it("kbdb_get_map 打 /portal/data/map,帶登入者 session,不碰 KBDB 服務金鑰", async () => {
const { server, tools } = makeServer();
const { env, calls } = makePortalEnv(
() => new Response(JSON.stringify({ success: true, libraries: [KB_ROW], count: 1 })),
);
registerGetMap(server, env, PORTAL);
const res = await tools.get("kbdb_get_map")!.handler({});
expect(res.isError).toBeUndefined();
expect(calls).toHaveLength(1);
expect(calls[0].url.pathname).toBe("/portal/data/map");
expect(new Headers(calls[0].init!.headers as HeadersInit).get("Authorization")).toBe("Bearer sess-abc");
});
it("呼叫端硬塞 owner_id 也不生效(查詢範圍由帳號權限決定,不由呼叫端指定)", async () => {
const { server, tools } = makeServer();
const { env, calls } = makePortalEnv(
() => new Response(JSON.stringify({ success: true, libraries: [KB_ROW], count: 1 })),
);
registerGetMap(server, env, PORTAL);
await tools.get("kbdb_get_map")!.handler({ owner_id: "someone-else" });
expect(calls[0].url.searchParams.get("owner_id")).toBeNull();
});
it("查沒權限的庫 → 與「不存在」同一句話(不洩存在性)", async () => {
const { server, tools } = makeServer();
const { env } = makePortalEnv(() => new Response(JSON.stringify({ error: "找不到這筆資料" }), { status: 404 }));
registerGetMap(server, env, PORTAL);
const res = await tools.get("kbdb_get_map")!.handler({ library: "secret-lib" });
expect(res.isError).toBe(true);
const body = parseResult(res);
expect(body.error_code).toBe("map_not_found");
expect(String(body.human_message)).toContain("不在你被授權");
});
it("session 過期(401)→ session_expired,不說「地圖是空的」", async () => {
const { server, tools } = makeServer();
const { env } = makePortalEnv(
() => new Response(JSON.stringify({ error: "session 無效或已過期" }), { status: 401 }),
);
registerGetMap(server, env, PORTAL);
const res = await tools.get("kbdb_get_map")!.handler({});
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("session_expired");
});
it("舊 token(沒身分)→ identity_missing,且一個查詢都不發(fail-closed", async () => {
const { server, tools } = makeServer();
const { env, calls } = makePortalEnv(() => new Response("{}"));
registerGetMap(server, env, STALE);
const res = await tools.get("kbdb_get_map")!.handler({});
expect(res.isError).toBe(true);
expect(parseResult(res).error_code).toBe("identity_missing");
expect(calls).toHaveLength(0);
});
it("instructions 的地圖也走 portal 資料面(連線開場推的庫名不得超出權限)", async () => {
const { env, calls } = makePortalEnv(
() => new Response(JSON.stringify({ success: true, libraries: [KB_ROW], count: 1 })),
);
const text = await buildLibraryMapInstructions(env, PORTAL);
expect(text).toContain("kb");
expect(calls[0].url.pathname).toBe("/portal/data/map");
});
it("**快取不跨身分共用**:不同 session 各自打一次,不會拿到別人的視野", async () => {
const { env, calls } = makePortalEnv(
() => new Response(JSON.stringify({ success: true, libraries: [KB_ROW], count: 1 })),
);
const other: KnowledgeIdentity = {
kind: "portal",
portal: { session: "sess-other", display_name: "小明", role: "user", libraries: ["notes"] },
};
await buildLibraryMapInstructions(env, PORTAL);
await buildLibraryMapInstructions(env, other);
expect(calls).toHaveLength(2); // 兩次真的各打一次
await buildLibraryMapInstructions(env, PORTAL);
expect(calls).toHaveLength(2); // 同一 session 第二次才吃快取
});
it("舊 token → 不給地圖(instructions 不外洩任何庫名)", async () => {
const { env, calls } = makePortalEnv(() => new Response("{}"));
expect(await buildLibraryMapInstructions(env, STALE)).toBeNull();
expect(calls).toHaveLength(0);
});
});
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env bash
#
# verify-kv-retirement.sh — 把「換掉 KV,資產還在」真的做一次
#
# KV 退休(Leo/Arcrun#16 + #17)。交辦的驗收條件逐字是:
# 「證明『換掉/重建那個暫存層,資產還在』——不是說明它會在,是**真的弄一次給我看**」
# 「既有的東西要能搬過去,而且搬的過程不能弄丟任何一筆(搬之前先數,搬之後再數)」
# 這支腳本就是那一次。它做的事,照順序:
#
# 1. 開一台**全新的空**本機實例(local D1 + local KV,跑真的 migrations
# 2. 用平常那條路(POST /webhooks/named、POST /recipes、POST /auth-recipes
# 放進 9 支工作流 + 3 份 recipe——9 是照 2026-08-12 那天真的消失的數量
# 3. 數一次(KV 幾筆、KBDB 幾筆)
# 4. **把整個 KV 層砍掉重建**(rm -rf 那顆 KV 的本機儲存 → 重開 worker)
# =模擬 Arcrun#97 那天發生的事:worker 被綁到一顆全新的空 KV
# 5. 再數一次,並且**真的觸發一支工作流**確認它還跑得動
#
# 通過的定義(不通就 exit 1,不留模稜兩可):
# 砍掉 KV 之後,列出來仍然是 9 支、recipe 仍在、工作流仍然跑得出結果。
#
# ⚠️ 全程只碰本機(--local + --persist-to 到暫存目錄),**不碰任何線上實例**。
# 腳本裡沒有任何 --remote、沒有任何真實帳號憑證。
#
# 用法: bash scripts/verify-kv-retirement.sh
# 需要: node 22+、pnpm、可執行 npx wrangler / curl 的 shell
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK="$(mktemp -d)"
KBDB_PORT=8801
CYPHER_PORT=8802
TOKEN="e2e-local-token"
TENANT="leo-e2e"
WF_COUNT=9
KBDB="http://127.0.0.1:${KBDB_PORT}"
CYPHER="http://127.0.0.1:${CYPHER_PORT}"
kbdb_pid=""; cypher_pid=""
cleanup() {
[ -n "$kbdb_pid" ] && kill "$kbdb_pid" 2>/dev/null || true
[ -n "$cypher_pid" ] && kill "$cypher_pid" 2>/dev/null || true
rm -rf "$WORK"
}
trap cleanup EXIT
say() { printf '\n\033[1m== %s\033[0m\n' "$*"; }
fail() { printf '\n\033[31m❌ %s\033[0m\n' "$*"; exit 1; }
wait_for() { # wait_for <url> <label>
for _ in $(seq 1 60); do
if curl -sf -m 2 "$1" >/dev/null 2>&1; then return 0; fi
sleep 1
done
fail "$2 沒有起來($1"
}
start_cypher() {
( cd "$REPO_ROOT/cypher-executor" && \
npx wrangler dev --local --port "$CYPHER_PORT" \
--config wrangler.test.toml \
--persist-to "$WORK/cypher-state" \
--var "KBDB_BASE_URL:$KBDB" \
--var "KBDB_INTERNAL_TOKEN:$TOKEN" \
--show-interactive-dev-session=false >"$WORK/cypher.log" 2>&1 ) &
cypher_pid=$!
wait_for "$CYPHER/health" "cypher-executor"
}
# ── 1. 空實例:真的跑 migrations ───────────────────────────────────────────────
say "1. 開一台全新的空實例(local D1 + local KV,跑真的 migrations"
( cd "$REPO_ROOT/kbdb" && npx wrangler d1 migrations apply DB --local --persist-to "$WORK/kbdb-state" )
( cd "$REPO_ROOT/kbdb" && \
npx wrangler dev --local --port "$KBDB_PORT" \
--persist-to "$WORK/kbdb-state" \
--var "KBDB_INTERNAL_TOKEN:$TOKEN" \
--show-interactive-dev-session=false >"$WORK/kbdb.log" 2>&1 ) &
kbdb_pid=$!
wait_for "$KBDB/health" "kbdb"
start_cypher
# ── 2. 用平常那條路放資產進去 ─────────────────────────────────────────────────
say "2. 放進 $WF_COUNT 支工作流 + 3 份 recipe(走的是 acr push 用的同一組端點)"
for i in $(seq 1 "$WF_COUNT"); do
curl -sf -X POST "$CYPHER/webhooks/named" \
-H 'Content-Type: application/json' -H "X-Arcrun-API-Key: $TENANT" \
-d "{\"name\":\"wf_$i\",\"description\":\"驗證用工作流 $i:把 text 轉大寫\",
\"graph\":{\"id\":\"wf_$i\",\"nodes\":[{\"id\":\"upper\",\"type\":\"Component\",\"componentId\":\"comp_uppercase\"}],\"edges\":[]}}" \
>/dev/null || fail "部署 wf_$i 失敗"
done
for svc in alpha beta; do
curl -sf -X POST "$CYPHER/recipes" \
-H 'Content-Type: application/json' \
-d "{\"canonical_id\":\"${svc}_send\",\"endpoint\":\"https://example.invalid/$svc\",\"description\":\"驗證用 recipe $svc\"}" \
>/dev/null || fail "建立 recipe $svc 失敗"
done
curl -sf -X POST "$CYPHER/auth-recipes" \
-H 'Content-Type: application/json' \
-d '{"service":"alpha","primitive":"static_key","base_url":"https://example.invalid",
"required_secrets":[{"key":"alpha_token","label":"Token","help_url":"https://example.invalid/docs"}],
"inject":{"header":{"Authorization":"Bearer {{secret.alpha_token}}"}}}' \
>/dev/null || fail "建立 auth recipe 失敗"
# ── 3. 搬之前先數 ─────────────────────────────────────────────────────────────
say "3. 數一次(/storage/auditKV 幾筆、KBDB 幾筆、差幾筆)"
curl -s "$CYPHER/storage/audit" | tee "$WORK/audit-before.json"; echo
before_wf="$(curl -s "$CYPHER/webhooks/named" -H "X-Arcrun-API-Key: $TENANT" | grep -o '"total":[0-9]*' | cut -d: -f2)"
echo "部署後列出來的工作流數:$before_wf"
[ "$before_wf" = "$WF_COUNT" ] || fail "還沒開始拆就對不上:期望 $WF_COUNT,實得 $before_wf"
# ── 4. 把 KV 層砍掉重建(模擬 2026-08-12 那天) ────────────────────────────────
say "4. 砍掉整個 KV 層並重建 —— 模擬 Arcrun#97 那天『worker 被綁到一顆全新的空 KV』"
kill "$cypher_pid" 2>/dev/null || true; wait "$cypher_pid" 2>/dev/null || true; cypher_pid=""
rm -rf "$WORK/cypher-state" # ← 這一行就是「那個暫存層被換掉」
echo "已刪除:$WORK/cypher-statecypher 的整顆本機 KV"
start_cypher
# ── 5. 再數一次,而且真的跑一支 ───────────────────────────────────────────────
say "5. KV 全空之後,再數一次"
after_json="$(curl -s "$CYPHER/webhooks/named" -H "X-Arcrun-API-Key: $TENANT")"
echo "$after_json" | head -c 400; echo
after_wf="$(echo "$after_json" | grep -o '"total":[0-9]*' | cut -d: -f2)"
echo "KV 砍掉重建後列出來的工作流數:$after_wf"
[ "$after_wf" = "$WF_COUNT" ] || fail "工作流少了:期望 $WF_COUNT,實得 $after_wf —— 資產沒有被保住"
recipes_after="$(curl -s "$CYPHER/recipes" | grep -o '"count":[0-9]*' | cut -d: -f2)"
echo "KV 砍掉重建後的 recipe 數:$recipes_after"
[ "${recipes_after:-0}" -ge 2 ] || fail "recipe 少了:期望 >=2,實得 ${recipes_after:-0}"
auth_after="$(curl -s "$CYPHER/auth-recipes/alpha" | grep -c '"success":true' || true)"
[ "$auth_after" = "1" ] || fail "auth recipe 不見了"
echo "auth recipe alpha:仍在"
say "5b. 不只是列得出來——真的觸發一支工作流"
run="$(curl -s -X POST "$CYPHER/webhooks/named/wf_3/trigger" \
-H 'Content-Type: application/json' -H "X-Arcrun-API-Key: $TENANT" \
-d '{"text":"still here"}')"
echo "$run" | head -c 400; echo
echo "$run" | grep -q 'STILL HERE' || fail "工作流列得出來卻跑不動——那不算資產還在"
say "結論"
printf '\033[32m✅ 通:整個 KV 層被砍掉重建之後,%s 支工作流、recipe、auth recipe 全部還在,且工作流真的跑得出結果。\033[0m\n' "$WF_COUNT"
echo " 資產的家=KBDBD1,一份資產一列 entry);KV 只是快取,砍掉會自己長回來。"
@@ -8,75 +8,6 @@
## 待裁決
### P-KVKV 退休:工作流與 recipe 的家搬到 KBDBLeo/Arcrun#16 + #17)— 2026-08-12
**觸發**leo 2026-08-12 原話——
> 「我要的是寫進 KBDB,不是 KV,他的 Recipes、Cypher 是一段話,文字,數據,一個 entry」
> 「因為對 KV 的使用有禁令,但卻會把資產放在這裡,這不是違法嗎?」
> 「現在是我幫他寫工作流,未來是他的 AI 自己寫工作流,
> **如果零件和工作流的 recipe 不見了,是很可怕的事情**
同日實害:一次例行更新讓使用者的九支工作流在畫面上全部消失(Arcrun#97)。
#97 已修掉直接原因(`cli/src/lib/resource-resolver.ts`:不再照名字猜使用者的資源、
不再擅自新建一顆空的綁上去)。**本案修的是更下面那一句**:使用者的資產本來就不該
只存在於一個會被換掉的暫存層裡——#97 修的是「別再換錯」,這裡修的是「換了也不會怎樣」。
**為什麼要走規格層(D35**`.claude/rules/01-tech-stack.md`「資料儲存」那張表把
workflow 定義寫在 `WEBHOOKS` KV、recipe 寫在 `RECIPES` KV。改掉真相來源=改規格。
現行 active SDD 是 `workflow-discovery`,本案不在它的 tasks 內,故依 D35 第 3 條
寫 proposal 停下等 leo confirm。**#16 已被多份 SDD 引用為前提**
`arcrun/artifact-sharing/` design K2「KBDB 是唯一公庫後端」、requirements Out of Scope、
tasks 1.55.2 都寫明「遷移本體由 #16 負責」),所以這不是新方向,是那些卷等的那一塊落地。
**提議的規格(三句)**
1. **資產的真相來源=KBDB**D1 `entries` 一列一份資產)。KV 降級為可丟棄的快取。
2. **零 SQL、永不加表**D38):新增四個 `entry_type`
`workflow_def` / `api_recipe` / `auth_recipe` / `prompt_recipe`),
各在 `templates` 表 seed 一列定義(`kbdb/migrations/0005_arcrun_asset_templates.sql`
手法同 0003/0004)。定義本體打包進 `metadata_json`,比照 `execution_log``recipe_stat` 既有先例。
3. **衍生資料不進 KBDB**`idx:*`recipe 反查)、`cron-idx:_all` 算得回來,
留在 KV,讀不到就從 KBDB 重算(不讓 KBDB 長出垃圾列)。
**實作形狀(已寫在 `feat/kv-retire-recipes-16-17` 分支,未合併)**
- 換 binding 而不是改呼叫端:`src/index.ts` 入口把 `WEBHOOKS``RECIPES`
換成 KBDB 撐腰的包裝(`src/lib/durable-store.ts`),四十幾處呼叫端一行不動。
理由:逐處改寫一定會漏,**漏掉的那一處就是下一次「東西不見了」的入口**。
- 「哪些 key 是資產」集中成一張表(`src/lib/asset-keys.ts`),是唯一需要人看懂的東西。
- 讀=KV 先行、miss 回源 KBDB 並補快取;寫=先 KBDB 再 KV,KBDB 失敗就拋錯(禁假綠);
**列舉一律走 KBDB**——空 KV 列出來是「零筆」而不是「查不到」,那正是消失的形狀。
- 搬遷與盤點:`GET /storage/audit``POST /storage/migrate-to-kbdb`(只增不刪、冪等、逐筆回報)。
- KBDB 端只加一個通用原語:`PUT /entries/:id`(指定 id 的整列 upsert),零 schema 異動。
**影響分析**
- 現行 active SDD `workflow-discovery`**不受影響**。它的 `entry_type='workflow'`
搜尋 entry 照舊雙寫,本案刻意用另一個型別 `workflow_def` 存定義本體、且不標 `embed`
以免同一支工作流嵌兩份向量。search/backfill 兩支端點一行未動。
- `artifact-sharing`:本案就是它 K2 等的 #16。落地後可拆 tasks 1.5 的 KV 過渡轉接(5.2)。
- credential**不碰**。憑證走 CF Workers Secrets D1 目錄(rule 01),不在本案範圍。
- 匿名 webhook`webhooks.ts``put(token, record)`):**目前沒搬**,仍是 KV-only。
它也是使用者建出來的東西,但不在 #16/#17 的字面範圍內——在此列出,請 leo 裁要不要納入。
- 效能:資產讀取多一層快取判斷;快取命中時與現況相同,miss 時多一次 KBDB 往返。
`list` 一律回源,但會順手把整批補進快取,所以「列出來再逐筆讀」總共只多一次往返。
**尚未完成/誠實限制(決定要不要 confirm 前請先看這段)**
- **端到端證據沒跑**。實作環境(雲端工人沙箱)不放行執行測試與 HTTP
`vitest``node``curl` 皆被權限閘擋下),所以「砍掉 KV、資產還在」這一次
**我沒有真的做出來給你看**。已跑到的只有:5 份 migration 在本機 D1 全部套用成功、
兩顆 worker 都能以改動後的程式碼在本機開起來、`tsc` 錯誤數與改動前一致(7 個既有錯,未新增)。
- 那一次驗證已經寫成可執行的腳本 `scripts/verify-kv-retirement.sh`
(開空實例 → 放 9 支工作流+3 份 recipe → 數一次 → **砍掉整個 KV 層重建** → 再數一次
→ 真的觸發一支確認跑得動),**在能執行的機器上跑一次就是那個證據**。
- 因此本案的狀態是 **◐ 半通**:程式碼與遷移路徑齊備,證據缺一份。
**建議 confirm 的順序是「先跑那支腳本、綠了再合併」**,不要因為程式碼看起來完整就先併——
這件事的整個重點就是不要再有「看起來好好的,其實東西不見了」。
**⏸ 停在這裡等 leo 裁**
① 方向 confirm 嗎(資產真相來源改 KBDB、KV 降快取)?
② 匿名 webhook 要不要一起納入?
③ KV 舊資料要不要清(本案只增不刪,清是另一個決定)?
---
### P2|fan-out 並行執行(一個節點的多條出邊目前是循序跑)— 2026-08-03
**觸發**:leo 08-03 原話——「這是在測試中的計畫,**希望體驗很好**,我發現用 gemma4 的反應非常慢。」