🛡️ BLA (Blind LLM Agents) — Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.
JavaScript adversarial-aiclaude-codecursorelectron-securityllm-securitymcpmcp-serverobfuscationreverse-engineeringwebassembly
feat(mcp): weave-decoy theory pack + bla_weave_plan surface (#52)
Timo Zhang826d3d8578a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59e0830..dcfe540 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Weave-decoy MCP surface** (`src/shields/weave/weave-decoy.ts`, `src/mcp/server.ts`):+ theory pack [`docs/weave-decoy-mcp.md`](docs/weave-decoy-mcp.md) (zh-friendly),+ MCP resource `bla://directives/weave-decoy`, tool `bla_weave_plan` (read-only+ `bla-weave-plan/v1` JSON), prompt `bla-weave-decoy`, and opt-in `weave_decoys`+ on `bla_harden` / `bla_defend` / `bla_protect`. Labels runs and documents that+ JS AST already weaves while Python remains warm-init-only after #51 — full+ customer-def AST weave is a follow-up. Defensive only; no dismissible noise layers.+### Changed+- **Python tarpit densification** (`tarpit-generator.ts`, `python.ts`): decoysno longer look like empty `_bla_*` honeypots — mixed mundane/scare stems,heterogeneous always-executed bodies that mutate shared state, and a livediff --git a/docs/cli-and-mcp.md b/docs/cli-and-mcp.mdindex 8fecf15..ae648df 100644--- a/docs/cli-and-mcp.md+++ b/docs/cli-and-mcp.md@@ -17,11 +17,19 @@## MCP Tools (`bla` Server)-- `bla_harden`: Preferred one-sentence harden of a project directory (`directory`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `seed`).-- `bla_defend`: Full Counter-REA pipeline on a known path (`input_path`, `output_path`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `seed`).+- `bla_harden`: Preferred one-sentence harden of a project directory (`directory`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `weave_decoys` default false, `seed`).+- `bla_defend`: Full Counter-REA pipeline on a known path (`input_path`, `output_path`, `intensity`, `emit_manifest` default false, `llm_directives` default false, `weave_decoys` default false, `seed`).- `bla_audit`: Pre-flight REA exposure and token-economics audit (`path`).-- `bla_protect`: Granular shield injection (`input_path`, `output_path`, `intensity`, `seed`, `llm_directives` default false).+- `bla_protect`: Granular shield injection (`input_path`, `output_path`, `intensity`, `seed`, `llm_directives` default false, `weave_decoys` default false).- `bla_verify`: Counter-REA invariant verification (`target_path`, `original_path`).- `bla_benchmark`: Runs the 8-target showcase benchmark suite.- `bla_emit_headers`: Generates C/C++, Rust, or Go defense headers (`language`, `intensity`).- `bla_doctor`: Diagnostics for BLA engines and agent client registrations.+- `bla_weave_plan`: Read-only weave-decoy planner (`path`, optional `max_targets`) → `bla-weave-plan/v1` JSON (defensive theory checklist; no crack/RE).++### MCP Resources++- `bla://directives/weave-decoy` — weave-decoy theory + executor checklist (Markdown).+- `bla://docs/weave-decoy-mcp` — same directives payload (doc pointer URI).++See [`weave-decoy-mcp.md`](./weave-decoy-mcp.md).diff --git a/docs/counter-rea-deception.md b/docs/counter-rea-deception.mdindex d30dfd5..2187cbb 100644--- a/docs/counter-rea-deception.md+++ b/docs/counter-rea-deception.md@@ -27,3 +27,13 @@ refuses EOF trailers that would break the MEI cookie.`pyinstaller`, so the peeled archive still contains dense decoys rather thanclean customer logic. Opt-in self-seal / anti-debug helpers that bind thecustomer entry to intact bytes remain a separate product gap (issue #40).++## Weave decoys (not dismissible noise)++Empty / homogeneous scare decoys are filtered as a separate layer by+WorkBuddy-class agents. Prefer **weaving** decoys into real customer paths+(shared state, entry reachability, mixed vocabulary, opaque-true happy path).+JS AST already weaves; Python after #51 is warm-init densify only.+Executable theory + MCP: [`weave-decoy-mcp.md`](./weave-decoy-mcp.md),+resource `bla://directives/weave-decoy`, tool `bla_weave_plan`, flag+`weave_decoys`.diff --git a/docs/weave-decoy-mcp.md b/docs/weave-decoy-mcp.mdnew file mode 100644index 0000000..801e28f--- /dev/null+++ b/docs/weave-decoy-mcp.md@@ -0,0 +1,84 @@+# 织入诱饵(Weave Decoy)理论包 — MCP 可执行++> **防御专用(Counter-REA)**。本文只描述如何把诱饵巧妙织入真实业务路径,提升对 REA / WorkBuddy 类智能体的过滤难度。+> **禁止**:破解、逆向突破、绕过 PoC、攻击剧本。+> 给后续 AI 的入口:MCP resource `bla://directives/weave-decoy`、工具 `bla_weave_plan`、harden 旗标 `weave_decoys: true`。++## 1. 背景:为什么「噪声诱饵」失败++在 Python 稠密化(#51)之后,经验仍成立:++| 失败形态 | 智能体如何过滤 | 结果 |+| :--- | :--- | :--- |+| 空 / `pass` 桩、`_bla_*` 同质 honeypot | 未引用 + 空体启发式 | 整层丢弃 |+| 仅 TEE / TPM / Nitro / enclave 词表 | 一次 scare 正则 | 整图丢弃 |+| 与业务无关的 sidecar「防护层」文件 | 「独立层」分类 | 难度不升反降 |+| 可 grep 的 `BLA-SHIELD` 横幅 | 明确「这是防护」证据 | 方便一刀切 |++**目标**:诱饵必须**巧妙织入**客户真实路径,使「丢掉诱饵层」等于破坏业务或验证失败。++## 2. JS 已织入 vs Python 仍 warm-init++| 管线 | 现状 | 含义 |+| :--- | :--- | :--- |+| **JavaScript / TypeScript** (`ast-shield.ts`) | **已织入** | opaque-true 包裹快乐路径语句;真实函数体织入步进器与 tarpit 互调;认知装甲与 seed 纠缠 |+| **Python** (`tarpit-generator.ts` + `python.ts`) | **warm-init-only**(#51) | 稠密异构体、共享状态、词干混用、模块级 warm-init 保 xref;**尚未**把诱饵调用织进客户 `def` |+| 若干二进制 / sidecar 格式 | sidecar / 附加块 | 原则仍适用;完整入口纠缠列为后续 |++本 PR 把理论与 MCP 执行面备齐;**完整 Python(及更多格式)AST 织入客户定义**留给 follow-up PR。++## 3. 织入原则(执行时必须遵守)++1. **共享状态** — 诱饵与业务读写同一运行时槽位(epoch / peer / digest 等)。+2. **客户入口可达** — 边必须从入口、路由、导出 API 进入诱饵;仅靠顶层 warm-init 不够对抗「独立层」过滤。+3. **词干混用** — 约 2/3 平凡业务名 + 约 1/3 安全诱饵名。+4. **快乐路径不透明真** — 真实语句用 opaque-true 守卫;禁止只把诱饵放进永不执行的死图。+5. **调用图纠缠** — 在真实函数体内织入步进 / 互调 / 影子堆搅动。+6. **可选自密封** — 入口与完整字节 / digest 绑定(产品缺口见 issue #40)。++## 4. 明确禁止++- 纯噪声层、可整层剥离的 honeypot 目录/文件+- 可 grep 的 `BLA-SHIELD` / `_bla_` 横幅(审计短语 `runtime attestation boundary` 可保留)+- 仅 TEE 词表的同质包+- 永不调用的 `pass` 桩冒充「加固」+- 任何进攻性内容++## 5. 后续 AI 执行清单(不依赖聊天记录)++1. `resources/read` → `bla://directives/weave-decoy`(或读本文件)+2. `bla_weave_plan` → `{ "path": "<project-or-artifact>" }`,保存返回的 JSON 工单+3. `bla_harden` / `bla_defend` / `bla_protect` 传 **`weave_decoys: true`**+4. JS:验证现有 AST 织入,**不要**再堆 sidecar 噪声+5. Python:保持稠密 + warm-init;**不要**用空 scare 模块填补缺口;标注 follow-up AST weave+6. 按 §6 验收;失败则回滚噪声改动++## 6. 验收(apply 后必须通过)++1. **无禁止标记** — 无 `_bla_` / `BLA-SHIELD` 横幅+2. **词干混用** — 诱饵名非 100% TEE/enclave+3. **共享状态变异** — 诱饵体修改与业务相关的共享槽+4. **客户入口边** — 静态 xref 从客户入口到达诱饵(JS 必须;Python warm-init 仅为过渡)+5. **opaque-true 缠绕** — 删除守卫或诱饵调用会改变行为或验证结果+6. **抗独立层过滤** — 不能仅凭空体 / 同质 scare / 未引用启发式整层丢弃++## 7. MCP 表面++| 表面 | 作用 |+| :--- | :--- |+| Resource `bla://directives/weave-decoy` | 返回本理论的可执行 Markdown |+| Tool `bla_weave_plan` | 只读:分析路径 → `bla-weave-plan/v1` JSON |+| `bla_harden` / `bla_defend` / `bla_protect` 参数 `weave_decoys` | 标注本次加固并挂接未来 AST 织入钩子 |++实现入口:`src/shields/weave/weave-decoy.ts`、`src/mcp/server.ts`。++## 8. Follow-up PR(本 PR 不做)++- 将诱饵调用 **AST 织入 Python 客户函数体**(超越 warm-init)+- 扩展更多格式的入口纠缠验收+- 可选 self-seal 与 `defenseScore` 对 onefile 诚实性(#40)++## 相关文档++- [`counter-rea-deception.md`](./counter-rea-deception.md) — 模型误判诱导总览 + PyInstaller 诚实边界+- [`cli-and-mcp.md`](./cli-and-mcp.md) — CLI / MCP 参数索引diff --git a/src/core/types.ts b/src/core/types.tsindex a072b84..35a1f98 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -156,6 +156,11 @@ export interface ProtectionOptions {* dual-use imitation vocabulary, in-band AI chat markers). Default false.*/readonly llmDirectives?: boolean;+ /**+ * When true, label the run for weave-decoy hooks (JS AST already weaves;+ * Python remains warm-init-only until follow-up). Default false.+ */+ readonly weaveDecoys?: boolean;}export interface ProtectionMetrics {@@ -177,6 +182,8 @@ export interface ProtectionResult {readonly outputPath: string;readonly detectedFormat: ArtifactFormat;readonly intensity: ProtectionIntensity;+ /** Present when protect was called with weaveDecoys:true (label / future hooks). */+ readonly weaveDecoys?: boolean;readonly seed: string;readonly originalSha256: string;readonly protectedSha256: string;diff --git a/src/engine/defender.ts b/src/engine/defender.tsindex 720c573..20289fe 100644--- a/src/engine/defender.ts+++ b/src/engine/defender.ts@@ -24,6 +24,7 @@ export interface OneClickDefenseOptions {readonly seed?: string | number;readonly emitManifest?: boolean;readonly llmDirectives?: boolean;+ readonly weaveDecoys?: boolean;}export interface OneClickDefenseStageSummary {@@ -42,6 +43,8 @@ export interface OneClickDefenseReport {readonly inputPath: string;readonly outputPath: string;readonly intensity: ProtectionIntensity;+ /** True when caller opted into weave-decoy labeling/hooks. */+ readonly weaveDecoys: boolean;readonly overallSuccess: boolean;readonly stages: readonly OneClickDefenseStageSummary[];readonly releaseExposure: ReleaseExposureReport | null;@@ -102,6 +105,9 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseRe...(options.llmDirectives !== undefined? { llmDirectives: options.llmDirectives }: {}),+ ...(options.weaveDecoys !== undefined+ ? { weaveDecoys: options.weaveDecoys }+ : {}),honeySourceMaps: true,});@@ -187,6 +193,7 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseReinputPath: absInput,outputPath: protection.outputPath,intensity,+ weaveDecoys: options.weaveDecoys === true,overallSuccess: verification.overallPassed,stages,releaseExposure,diff --git a/src/engine/harden.ts b/src/engine/harden.tsindex a00e759..ed3fc2e 100644--- a/src/engine/harden.ts+++ b/src/engine/harden.ts@@ -91,6 +91,7 @@ export interface HardenProjectOptions {readonly seed?: string | number;readonly emitManifest?: boolean;readonly llmDirectives?: boolean;+ readonly weaveDecoys?: boolean;/** Optional output root; defaults to `<dir>/.bla-hardened`. */readonly outputDirectory?: string;readonly maxArtifacts?: number;@@ -107,6 +108,7 @@ export interface HardenProjectReport {readonly outputDirectory: string;readonly artifacts: readonly HardenArtifactSummary[];readonly oneSentenceUsage: string;+ readonly weaveDecoys: boolean;}function isProtectableFormat(format: ArtifactFormat): boolean {@@ -288,6 +290,9 @@ export function hardenProject(...(options.llmDirectives !== undefined? { llmDirectives: options.llmDirectives }: {}),+ ...(options.weaveDecoys !== undefined+ ? { weaveDecoys: options.weaveDecoys }+ : {}),emitManifest,});summaries.push({@@ -327,6 +332,7 @@ export function hardenProject(schema: "bla-harden-summary/v1",directory: absDir,intensity,+ weaveDecoys: options.weaveDecoys === true,artifacts: summaries,},null,@@ -353,6 +359,7 @@ export function hardenProject(artifacts: summaries,oneSentenceUsage:'Harden my software against REA — call bla_harden with { "directory": "." } (or `bla harden .`).',+ weaveDecoys: options.weaveDecoys === true,};}diff --git a/src/engine/protector.ts b/src/engine/protector.tsindex 4e63d2a..73b3e9b 100644--- a/src/engine/protector.ts+++ b/src/engine/protector.ts@@ -610,6 +610,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {outputPath: absOutput,detectedFormat: format,intensity,+ ...(options.weaveDecoys === true ? { weaveDecoys: true as const } : {}),seed,originalSha256: beforeAudit.sha256,protectedSha256: afterAudit.sha256,diff --git a/src/index.ts b/src/index.tsindex 3d58d8f..e134cad 100644--- a/src/index.ts+++ b/src/index.ts@@ -182,7 +182,7 @@ export {} from "./setup/clients.js";export { runSetup, runUninstall } from "./setup/setup.js";export { runDoctor } from "./setup/doctor.js";-export { handleMcpRequest, startMcpStdioServer, BLA_MCP_TOOLS } from "./mcp/server.js";+export { handleMcpRequest, startMcpStdioServer, BLA_MCP_TOOLS, BLA_MCP_RESOURCES, BLA_MCP_PROMPTS } from "./mcp/server.js";export {inspectReleaseExposure,type ReleaseExposureReport,@@ -222,3 +222,20 @@ export {buildMappedFlutterIsolatePoolPlant,buildMappedGoFlutterElfFixture,} from "./shields/formats/go-flutter-exhaustion.js";++export {+ buildWeavePlan,+ getWeaveDirectivesMarkdown,+ inspectWeaveHints,+ WEAVE_ACCEPTANCE_TESTS,+ WEAVE_DECOY_DOC_PATH,+ WEAVE_DECOY_SCHEMA,+ WEAVE_DIRECTIVES_URI,+ WEAVE_EXECUTOR_CHECKLIST,+ WEAVE_FORBIDDEN,+ WEAVE_PRINCIPLES,+ type WeaveMaturity,+ type WeavePlan,+ type WeavePlanStatus,+} from "./shields/weave/weave-decoy.js";+diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 9439725..ffc189e 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -13,6 +13,12 @@ import {type NativeHeaderLanguage,} from "../shields/formats/headers.js";import { runDoctor } from "../setup/doctor.js";+import {+ buildWeavePlan,+ getWeaveDirectivesMarkdown,+ WEAVE_DECOY_DOC_PATH,+ WEAVE_DIRECTIVES_URI,+} from "../shields/weave/weave-decoy.js";export interface JsonRpcRequest {readonly jsonrpc: "2.0";@@ -117,6 +123,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([type: "boolean",description: "Opt-in risky LLM directive layers (fake COPPA/medical notices, dual-use imitation, AI chat markers). Default false.",},+ weave_decoys: {+ type: "boolean",+ description:+ "Opt-in weave-decoy labeling/hooks: entangle decoys with real customer paths (JS already weaves; Python warm-init-only until follow-up AST weave). See bla://directives/weave-decoy. Default false.",+ },seed: {type: "string",description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",@@ -153,6 +164,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([type: "boolean",description: "Opt-in risky LLM directive layers (fake COPPA/medical notices, dual-use imitation, AI chat markers). Default false.",},+ weave_decoys: {+ type: "boolean",+ description:+ "Opt-in weave-decoy labeling/hooks (shared-state / entry-reachable decoys; not dismissible noise). Default false.",+ },seed: {type: "string",description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc",@@ -198,6 +214,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([enum: ["stealth", "balanced", "maximum", "bankrupt"],description: "Protection intensity preset (default: balanced)",},+ weave_decoys: {+ type: "boolean",+ description:+ "Opt-in weave-decoy labeling/hooks (shared-state / entry-reachable decoys; not dismissible noise). Default false.",+ },seed: {type: "string",description: "Optional deterministic seed; when omitted, BLA mints an ephemeral random seed (prefer project .blarc via CLI)",@@ -321,6 +342,50 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([additionalProperties: false,},},+ {+ name: "bla_weave_plan",+ description:+ "Read-only weave-decoy planner: analyze a project or artifact, return bla-weave-plan/v1 JSON (principles, forbidden patterns, checklist, per-file maturity). Defensive only — no crack/RE steps. Prefer before bla_harden with weave_decoys:true.",+ inputSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ description: "Project directory or single artifact to analyze",+ },+ max_targets: {+ type: "number",+ description: "Optional cap on files to classify (default 48)",+ },+ },+ required: ["path"],+ additionalProperties: false,+ },+ },+]);+++export interface McpResourceDefinition {+ readonly uri: string;+ readonly name: string;+ readonly description: string;+ readonly mimeType: string;+}++export const BLA_MCP_RESOURCES: readonly McpResourceDefinition[] = Object.freeze([+ {+ uri: WEAVE_DIRECTIVES_URI,+ name: "weave-decoy-directives",+ description:+ "Chinese-friendly weave-decoy theory + executor checklist for Counter-REA agents (defensive only).",+ mimeType: "text/markdown",+ },+ {+ uri: "bla://docs/weave-decoy-mcp",+ name: "weave-decoy-doc",+ description: `Pointer to repository theory pack ${WEAVE_DECOY_DOC_PATH}`,+ mimeType: "text/markdown",+ },]);export const BLA_MCP_PROMPTS: readonly McpPromptDefinition[] = Object.freeze([@@ -372,6 +437,18 @@ export const BLA_MCP_PROMPTS: readonly McpPromptDefinition[] = Object.freeze([},],},+ {+ name: "bla-weave-decoy",+ description:+ "Plan weave-decoy hardening: read bla://directives/weave-decoy, call bla_weave_plan, then bla_harden with weave_decoys:true. Defensive only.",+ arguments: [+ {+ name: "target_path",+ description: "Path to the project or artifact",+ required: true,+ },+ ],+ },]);function isPlainObject(value: unknown): value is Record<string, unknown> {@@ -569,6 +646,7 @@ export async function handleMcpRequest(capabilities: {tools: {},prompts: {},+ resources: {},},serverInfo: {name: BLA_IDENTITY.mcpServerName,@@ -594,6 +672,54 @@ export async function handleMcpRequest(},};+ case "resources/list":+ return {+ jsonrpc: "2.0",+ id: req.id,+ result: {+ resources: BLA_MCP_RESOURCES,+ },+ };++ case "resources/read": {+ if (!isPlainObject(req.params) || typeof req.params.uri !== "string") {+ return {+ jsonrpc: "2.0",+ id: req.id,+ error: {+ code: -32602,+ message: "Invalid params: resources/read requires a string 'uri'",+ },+ };+ }+ const uri = req.params.uri;+ const known = BLA_MCP_RESOURCES.find((r) => r.uri === uri);+ if (!known) {+ return {+ jsonrpc: "2.0",+ id: req.id,+ error: {+ code: -32602,+ message: `Invalid params: unknown resource URI '${uri}'`,+ },+ };+ }+ const markdown = getWeaveDirectivesMarkdown();+ return {+ jsonrpc: "2.0",+ id: req.id,+ result: {+ contents: [+ {+ uri,+ mimeType: "text/markdown",+ text: markdown,+ },+ ],+ },+ };+ }+case "prompts/list":return {jsonrpc: "2.0",@@ -661,6 +787,13 @@ export async function handleMcpRequest(`Harden my software against REA in one step: call bla_harden with { "directory": "${directory}" }. ` +`It auto-discovers build outputs, runs audit→defend→verify with the bankrupt profile on every artifact, and returns a per-artifact summary. ` +`Do not ask which files to protect — discover them.`;+ } else if (promptDef.name === "bla-weave-decoy") {+ const targetPath =+ typeof promptArgs.target_path === "string" && promptArgs.target_path.trim().length > 0+ ? String(promptArgs.target_path)+ : ".";+ promptText =+ `Defensive weave-decoy only (no crack/RE): read resource ${WEAVE_DIRECTIVES_URI}, call bla_weave_plan with { "path": "${targetPath}" }, then bla_harden with { "directory": "${targetPath}", "weave_decoys": true }. Do not add dismissible honeypot noise layers.`;} else {const targetPath = String(promptArgs.target_path ?? ".");promptText =@@ -713,6 +846,7 @@ export async function handleMcpRequest(: "bankrupt",emitManifest: Boolean(args.emit_manifest),llmDirectives: Boolean(args.llm_directives),+ weaveDecoys: Boolean(args.weave_decoys),...(typeof args.seed === "string" ? { seed: args.seed } : {}),});} else if (name === "bla_defend") {@@ -727,6 +861,7 @@ export async function handleMcpRequest(: "bankrupt",emitManifest: Boolean(args.emit_manifest),llmDirectives: Boolean(args.llm_directives),+ weaveDecoys: Boolean(args.weave_decoys),...(typeof args.seed === "string" ? { seed: args.seed } : {}),});} else if (name === "bla_audit") {@@ -740,6 +875,7 @@ export async function handleMcpRequest(: {}),...(typeof args.seed === "string" ? { seed: args.seed } : {}),llmDirectives: Boolean(args.llm_directives),+ weaveDecoys: Boolean(args.weave_decoys),});} else if (name === "bla_verify") {payload = handlers.verifyTarget(@@ -768,6 +904,12 @@ export async function handleMcpRequest(args.directory as string,Boolean(args.overwrite),);+ } else if (name === "bla_weave_plan") {+ payload = buildWeavePlan(args.path as string, {+ ...(typeof args.max_targets === "number"+ ? { maxTargets: args.max_targets }+ : {}),+ });}return {diff --git a/src/shields/weave/weave-decoy.ts b/src/shields/weave/weave-decoy.tsnew file mode 100644index 0000000..6d96327--- /dev/null+++ b/src/shields/weave/weave-decoy.ts@@ -0,0 +1,580 @@+/**+ * Weave-decoy theory + read-only planner for Counter-REA hardening.+ *+ * DEFENSIVE ONLY: helps agents entangle decoys with real customer call graphs+ * so REA/WorkBuddy-style peel cannot dismiss them as a separate noise layer.+ * No crack / RE / bypass playbooks.+ */++import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { extname, join, relative, resolve } from "node:path";+import { detectArtifactFormat } from "../../core/detector.js";+import type { ArtifactFormat } from "../../core/types.js";++export const WEAVE_DECOY_DOC_PATH = "docs/weave-decoy-mcp.md" as const;+export const WEAVE_DECOY_SCHEMA = "bla-weave-plan/v1" as const;+export const WEAVE_DIRECTIVES_URI = "bla://directives/weave-decoy" as const;++/** How far today's pipeline already weaves decoys into customer logic. */+export type WeaveMaturity =+ | "woven"+ | "warm-init-only"+ | "sidecar-decoy"+ | "not-applicable"+ | "gap";++export type WeavePlanStatus = "ready" | "partial" | "gap" | "unsupported";++export interface WeavePrinciple {+ readonly id: string;+ readonly titleZh: string;+ readonly titleEn: string;+ readonly summaryZh: string;+}++export interface WeaveForbiddenPattern {+ readonly id: string;+ readonly titleZh: string;+ readonly whyZh: string;+}++export interface WeaveAcceptanceTest {+ readonly id: string;+ readonly titleZh: string;+ readonly checkEn: string;+}++export interface WeaveChecklistStep {+ readonly id: string;+ readonly phase: "analyze" | "apply" | "verify";+ readonly titleZh: string;+ readonly actionEn: string;+}++export interface WeaveTargetEntry {+ readonly path: string;+ readonly relativePath: string;+ readonly format: ArtifactFormat;+ readonly maturity: WeaveMaturity;+ readonly status: WeavePlanStatus;+ readonly notesZh: string;+ readonly recommendedActions: readonly string[];+}++export interface WeavePlan {+ readonly schema: typeof WEAVE_DECOY_SCHEMA;+ readonly docPath: typeof WEAVE_DECOY_DOC_PATH;+ readonly directivesUri: typeof WEAVE_DIRECTIVES_URI;+ readonly targetPath: string;+ readonly analyzedAtIso: string;+ readonly overallStatus: WeavePlanStatus;+ readonly summaryZh: string;+ readonly targets: readonly WeaveTargetEntry[];+ readonly principles: readonly WeavePrinciple[];+ readonly forbidden: readonly WeaveForbiddenPattern[];+ readonly acceptanceTests: readonly WeaveAcceptanceTest[];+ readonly checklist: readonly WeaveChecklistStep[];+ readonly pipelineHook: {+ readonly mcpFlag: "weave_decoys";+ readonly hardenOption: "weaveDecoys";+ readonly todayBehaviorZh: string;+ readonly followUpZh: string;+ };+}++export const WEAVE_PRINCIPLES: readonly WeavePrinciple[] = Object.freeze([+ {+ id: "shared-state",+ titleZh: "与真实代码共享可变状态",+ titleEn: "Shared mutable state with real code",+ summaryZh:+ "诱饵必须读写与业务路径同一批运行时槽位(epoch / peer / digest),不能只是孤立局部变量或空 pass。",+ },+ {+ id: "customer-reachable",+ titleZh: "从客户入口可达",+ titleEn: "Reachable from customer entry",+ summaryZh:+ "诱饵调用必须落在真实入口、路由处理器或导出 API 的调用图上;仅靠模块顶层 warm-init 不够对抗会过滤「独立层」的智能体。",+ },+ {+ id: "mixed-vocab",+ titleZh: "平凡业务名与安全诱饵名混用",+ titleEn: "Mixed mundane + security vocabulary",+ summaryZh:+ "标识符约 2/3 用 invoice/session/cache/locale 等平凡词干,约 1/3 用 enclave/TPM 等诱饵词干,避免一次 grep 整层丢弃。",+ },+ {+ id: "opaque-true-happy-path",+ titleZh: "快乐路径用不透明真谓词缠绕",+ titleEn: "Opaque-true on happy path / no dead-only graphs",+ summaryZh:+ "真实语句用不透明-真守卫包裹,使盲目删除破坏行为;不可只用不透明-假把诱饵塞进永不到达的死图。",+ },+ {+ id: "call-graph-entanglement",+ titleZh: "调用图纠缠",+ titleEn: "Call graph entanglement",+ summaryZh:+ "在真实函数体内织入步进器 / 诱饵互调 / 影子堆搅动,使 xref 与过程搜索看到业务与诱饵同图。",+ },+ {+ id: "optional-self-seal",+ titleZh: "可选自密封绑定",+ titleEn: "Optional self-seal binding",+ summaryZh:+ "可选:把入口结果与完整字节 / 认知装甲 digest 绑定,使剥离诱饵层的篡改在运行期失败(产品缺口见 issue #40)。",+ },+]);++export const WEAVE_FORBIDDEN: readonly WeaveForbiddenPattern[] = Object.freeze([+ {+ id: "pure-noise-layer",+ titleZh: "纯噪声层 / 可整层剥离的 honeypot 文件",+ whyZh:+ "WorkBuddy 类智能体会把空 `_bla_*`、同质 scare 包、与业务无关的 sidecar 识别为可丢弃噪声,难度不升反降。",+ },+ {+ id: "greppable-banners",+ titleZh: "可 grep 的 BLA-SHIELD / `_bla_` 横幅",+ whyZh: "提供「这是防护层」的明确证据,方便过滤器一刀切。",+ },+ {+ id: "tee-only-vocab",+ titleZh: "仅 TEE/TPM/Nitro/enclave 词表",+ whyZh: "同质 scare 词汇让一次正则即可丢弃整图;必须混入平凡业务词干。",+ },+ {+ id: "dead-only-decoys",+ titleZh: "仅死代码 / 永不调用的 pass 桩",+ whyZh: "静态可达性与 xref 会标为未引用;暖启动或入口织入才能保住图连通。",+ },+ {+ id: "offensive-content",+ titleZh: "破解 / RE / 绕过 PoC 与攻击剧本",+ whyZh: "BLA 只做防御加固;MCP 与文档不得提供进攻内容。",+ },+]);++export const WEAVE_ACCEPTANCE_TESTS: readonly WeaveAcceptanceTest[] =+ Object.freeze([+ {+ id: "no-forbidden-markers",+ titleZh: "无禁止标记",+ checkEn:+ "Hardened output has no greppable `_bla_` / `BLA-SHIELD` banners (auditor phrase `runtime attestation boundary` may remain).",+ },+ {+ id: "mixed-stems",+ titleZh: "词干混用",+ checkEn:+ "Decoy identifier stems are not 100% TEE/enclave; mundane stems appear in the same graph.",+ },+ {+ id: "shared-state-mutation",+ titleZh: "共享状态变异",+ checkEn:+ "Decoy bodies mutate a shared runtime slot/dict that customer-path code also touches or depends on after weave.",+ },+ {+ id: "customer-entry-edges",+ titleZh: "客户入口边",+ checkEn:+ "Static xref from customer entry / exported handlers reaches at least one decoy call (not warm-init alone for JS; Python warm-init is interim only).",+ },+ {+ id: "opaque-true-entanglement",+ titleZh: "不透明真缠绕",+ checkEn:+ "A sample of real happy-path statements is guarded by opaque-true; deleting those guards or decoy callees changes behavior or verification.",+ },+ {+ id: "filter-resistance",+ titleZh: "抗「独立层」过滤",+ checkEn:+ "An agent cannot classify the decoy set as a separate dismissible layer using empty-body / homogeneous-scare / unreferenced heuristics alone.",+ },+ ]);++export const WEAVE_EXECUTOR_CHECKLIST: readonly WeaveChecklistStep[] =+ Object.freeze([+ {+ id: "read-theory",+ phase: "analyze",+ titleZh: "读取理论包",+ actionEn: `Read ${WEAVE_DECOY_DOC_PATH} or MCP resource ${WEAVE_DIRECTIVES_URI}; do not invent offensive steps.`,+ },+ {+ id: "run-weave-plan",+ phase: "analyze",+ titleZh: "生成织入计划",+ actionEn:+ "Call MCP `bla_weave_plan` on the project/build path; keep the returned JSON as the work order.",+ },+ {+ id: "prefer-pipeline-flag",+ phase: "apply",+ titleZh: "走 harden 管线旗标",+ actionEn:+ "Call `bla_harden` / `bla_defend` / `bla_protect` with `weave_decoys: true` so the run is labeled and future AST weave hooks activate.",+ },+ {+ id: "js-entangle",+ phase: "apply",+ titleZh: "确认 JS 已织入",+ actionEn:+ "For JS/TS: existing `ast-shield` already weaves opaque-true + tarpit calls into real function bodies — verify, do not add a second noise sidecar.",+ },+ {+ id: "python-gap",+ phase: "apply",+ titleZh: "Python 缺口标注",+ actionEn:+ "For Python: today is warm-init-only after densify (#51). Full weave into customer defs is a follow-up PR — do not pile empty scare modules as a substitute.",+ },+ {+ id: "acceptance",+ phase: "verify",+ titleZh: "跑验收检查",+ actionEn:+ "Execute WEAVE_ACCEPTANCE_TESTS checks on hardened output; fail the job if pure-noise or TEE-only vocab remains.",+ },+ ]);++function maturityForFormat(format: ArtifactFormat): WeaveMaturity {+ switch (format) {+ case "javascript":+ case "typescript":+ case "html-bundle":+ return "woven";+ case "python-source":+ case "python-pyc":+ return "warm-init-only";+ case "electron-asar":+ case "firmware-uf2":+ case "android-dex":+ case "android-apk":+ case "archive-zip":+ return "sidecar-decoy";+ case "directory":+ case "unknown":+ return "not-applicable";+ default:+ return "gap";+ }+}++function statusForMaturity(maturity: WeaveMaturity): WeavePlanStatus {+ switch (maturity) {+ case "woven":+ return "ready";+ case "warm-init-only":+ case "sidecar-decoy":+ return "partial";+ case "gap":+ return "gap";+ default:+ return "unsupported";+ }+}++function notesForMaturity(maturity: WeaveMaturity): string {+ switch (maturity) {+ case "woven":+ return "JS AST 已将诱饵织入真实函数体(opaque-true + tarpit/xref)。保持此路径,禁止再加可剥离噪声层。";+ case "warm-init-only":+ return "Python 在 #51 后有稠密诱饵 + 模块 warm-init,但尚未织入客户 def 调用图;后续 PR 做 AST weave。";+ case "sidecar-decoy":+ return "格式以 sidecar / 附加块诱饵为主;织入原则仍适用:避免空同质 scare,保持可达与词干混用。";+ case "gap":+ return "该格式尚无客户入口织入钩子;先跑标准 harden,织入改造列入后续。";+ default:+ return "跳过不可保护或不识别目标。";+ }+}++function actionsForMaturity(maturity: WeaveMaturity): readonly string[] {+ switch (maturity) {+ case "woven":+ return Object.freeze([+ "Run bla_harden/bla_protect with weave_decoys:true (label + future hooks).",+ "Verify opaque-true entanglement and mixed stems on output.",+ ]);+ case "warm-init-only":+ return Object.freeze([+ "Keep densified tarpit + warm-init; do not add empty honeypot modules.",+ "Track follow-up: AST weave decoy calls into customer Python defs.",+ "Optional: self-seal binding (issue #40) after weave lands.",+ ]);+ case "sidecar-decoy":+ return Object.freeze([+ "Keep format-specific decoy blocks reachable / mixed-vocab.",+ "Refuse greppable banners and TEE-only homogeneous packs.",+ ]);+ case "gap":+ return Object.freeze([+ "Use standard bla_harden today.",+ "File follow-up only for defensive customer-path entanglement.",+ ]);+ default:+ return Object.freeze([]);+ }+}++const SCAN_SKIP = new Set([+ ".git",+ "node_modules",+ ".bla-hardened",+ "dist",+ "coverage",+ ".venv",+ "venv",+ "__pycache__",+]);++const INTERESTING_EXT = new Set([+ ".js",+ ".cjs",+ ".mjs",+ ".ts",+ ".tsx",+ ".jsx",+ ".py",+ ".pyc",+ ".asar",+ ".wasm",+ ".uf2",+ ".dex",+ ".apk",+ ".so",+ ".dll",+ ".exe",+ ".sqlite",+ ".db",+]);++function listCandidateFiles(root: string, limit: number): string[] {+ const out: string[] = [];+ const stack = [root];+ while (stack.length > 0 && out.length < limit) {+ const dir = stack.pop()!;+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const ent of entries) {+ if (out.length >= limit) break;+ if (ent.name.startsWith(".") && ent.name !== ".blarc") {+ if (SCAN_SKIP.has(ent.name)) continue;+ }+ if (SCAN_SKIP.has(ent.name)) continue;+ const full = join(dir, ent.name);+ if (ent.isDirectory()) {+ stack.push(full);+ continue;+ }+ if (!ent.isFile()) continue;+ const ext = extname(ent.name).toLowerCase();+ if (INTERESTING_EXT.has(ext) || ent.name === "global-metadata.dat") {+ out.push(full);+ }+ }+ }+ return out;+}++function buildTargetEntry(+ absPath: string,+ rootAbs: string,+): WeaveTargetEntry {+ const format = detectArtifactFormat(absPath);+ const maturity = maturityForFormat(format);+ return {+ path: absPath,+ relativePath: relative(rootAbs, absPath) || ".",+ format,+ maturity,+ status: statusForMaturity(maturity),+ notesZh: notesForMaturity(maturity),+ recommendedActions: actionsForMaturity(maturity),+ };+}++function overallFromTargets(+ targets: readonly WeaveTargetEntry[],+): WeavePlanStatus {+ if (targets.length === 0) return "unsupported";+ if (targets.every((t) => t.status === "ready")) return "ready";+ if (targets.some((t) => t.status === "gap")) return "gap";+ if (targets.some((t) => t.status === "partial" || t.status === "ready")) {+ return "partial";+ }+ return "unsupported";+}++/**+ * Read-only weave planner: classify targets and return an executable checklist+ * JSON so a later AI can apply theory without chat history.+ */+export function buildWeavePlan(+ targetPath: string,+ options: { readonly maxTargets?: number } = {},+): WeavePlan {+ const abs = resolve(targetPath);+ const maxTargets = options.maxTargets ?? 48;+ const targets: WeaveTargetEntry[] = [];++ if (!existsSync(abs)) {+ return {+ schema: WEAVE_DECOY_SCHEMA,+ docPath: WEAVE_DECOY_DOC_PATH,+ directivesUri: WEAVE_DIRECTIVES_URI,+ targetPath: abs,+ analyzedAtIso: new Date().toISOString(),+ overallStatus: "unsupported",+ summaryZh: `路径不存在:${abs}`,+ targets: [],+ principles: WEAVE_PRINCIPLES,+ forbidden: WEAVE_FORBIDDEN,+ acceptanceTests: WEAVE_ACCEPTANCE_TESTS,+ checklist: WEAVE_EXECUTOR_CHECKLIST,+ pipelineHook: PIPELINE_HOOK,+ };+ }++ const st = statSync(abs);+ if (st.isDirectory()) {+ for (const file of listCandidateFiles(abs, maxTargets)) {+ targets.push(buildTargetEntry(file, abs));+ }+ } else {+ targets.push(buildTargetEntry(abs, abs.endsWith(extname(abs)) ? resolve(abs, "..") : abs));+ }++ const overallStatus = overallFromTargets(targets);+ const summaryZh =+ overallStatus === "ready"+ ? "目标以 JS 织入成熟度为主;可直接 bla_harden(weave_decoys:true) 并跑验收。"+ : overallStatus === "partial"+ ? "部分格式已织入或仅有 warm-init/sidecar;按 checklist 执行,Python 客户 def 织入留给后续 PR。"+ : overallStatus === "gap"+ ? "存在尚无织入钩子的格式;先标准 harden,勿堆噪声层。"+ : "未发现可分析产物;请指向源码或构建目录。";++ return {+ schema: WEAVE_DECOY_SCHEMA,+ docPath: WEAVE_DECOY_DOC_PATH,+ directivesUri: WEAVE_DIRECTIVES_URI,+ targetPath: abs,+ analyzedAtIso: new Date().toISOString(),+ overallStatus,+ summaryZh,+ targets,+ principles: WEAVE_PRINCIPLES,+ forbidden: WEAVE_FORBIDDEN,+ acceptanceTests: WEAVE_ACCEPTANCE_TESTS,+ checklist: WEAVE_EXECUTOR_CHECKLIST,+ pipelineHook: PIPELINE_HOOK,+ };+}++const PIPELINE_HOOK = Object.freeze({+ mcpFlag: "weave_decoys" as const,+ hardenOption: "weaveDecoys" as const,+ todayBehaviorZh:+ "weave_decoys=true 时:JS 保持现有 AST 织入;Python 保持 #51 稠密 + warm-init(尚未改客户 def);报告标注 weaveDecoys。完整 Python/多格式 AST 织入为后续 PR。",+ followUpZh:+ "Follow-up:把诱饵调用织进 Python 客户函数体;可选 self-seal;扩展 sidecar 格式的入口纠缠验收。",+});++/** Markdown theory pack returned by MCP resources/read (Chinese-friendly). */+export function getWeaveDirectivesMarkdown(): string {+ const principles = WEAVE_PRINCIPLES.map(+ (p) => `- **${p.id}** — ${p.titleZh} / ${p.titleEn}\n ${p.summaryZh}`,+ ).join("\n");+ const forbidden = WEAVE_FORBIDDEN.map(+ (f) => `- **${f.id}** — ${f.titleZh}\n 原因:${f.whyZh}`,+ ).join("\n");+ const acceptance = WEAVE_ACCEPTANCE_TESTS.map(+ (a) => `- **${a.id}** — ${a.titleZh}: ${a.checkEn}`,+ ).join("\n");+ const checklist = WEAVE_EXECUTOR_CHECKLIST.map(+ (s) => `- [${s.phase}] **${s.id}** — ${s.titleZh}: ${s.actionEn}`,+ ).join("\n");++ return `# Weave-decoy directives (BLA Counter-REA)++> 防御专用。禁止输出破解 / RE / 绕过 PoC。完整叙述见 \`${WEAVE_DECOY_DOC_PATH}\`。++## 为何空/同质 scare 诱饵失败(WorkBuddy)++可剥离的空 \`_bla_*\`、同质 TEE 词表、与业务无关的 honeypot 层会被智能体整层过滤,难度不升。诱饵必须巧妙织入真实业务路径。++## 织入原则++${principles}++## 明确禁止++${forbidden}++## 执行清单(给后续 AI)++${checklist}++## 验收(apply 后必须通过)++${acceptance}++## MCP++1. \`resources/read\` → \`${WEAVE_DIRECTIVES_URI}\`+2. \`bla_weave_plan\` → 只读计划 JSON(\`${WEAVE_DECOY_SCHEMA}\`)+3. \`bla_harden\` / \`bla_defend\` / \`bla_protect\` 传 \`weave_decoys: true\`++## 管线现状++${PIPELINE_HOOK.todayBehaviorZh}++${PIPELINE_HOOK.followUpZh}+`;+}++/**+ * Lightweight source hint for stubs: whether a JS/Python buffer already shows+ * weave / warm-init markers (defensive telemetry only).+ */+export function inspectWeaveHints(source: string, format: ArtifactFormat): {+ readonly maturity: WeaveMaturity;+ readonly hints: readonly string[];+} {+ const hints: string[] = [];+ if (format === "javascript" || format === "typescript" || format === "html-bundle") {+ if (/opaque|runtimeSeed|warmRuntime|stepper/i.test(source)) {+ hints.push("possible-js-shield-markers");+ }+ return { maturity: "woven", hints };+ }+ if (format === "python-source" || format === "python-pyc") {+ if (/\["warm"\]\s*=/.test(source) || /warm_runtime|warmRuntime/i.test(source)) {+ hints.push("python-warm-init");+ }+ if (/runtime attestation boundary/.test(source)) {+ hints.push("python-tarpit-banner-phrase");+ }+ return { maturity: "warm-init-only", hints };+ }+ return { maturity: maturityForFormat(format), hints };+}++/** Optional helper when reading the on-disk theory doc from repo root. */+export function tryReadWeaveTheoryDoc(repoRoot: string): string | null {+ const path = join(repoRoot, WEAVE_DECOY_DOC_PATH);+ try {+ return readFileSync(path, "utf8");+ } catch {+ return null;+ }+}diff --git a/tests/cli-mcp-setup.test.ts b/tests/cli-mcp-setup.test.tsindex 627bd49..0aa1efb 100644--- a/tests/cli-mcp-setup.test.ts+++ b/tests/cli-mcp-setup.test.ts@@ -87,6 +87,7 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {"bla_doctor","bla_inspect_release","bla_init",+ "bla_weave_plan",]);// Test bla_audit + bla_protect + bla_verify via MCP tool callsdiff --git a/tests/weave-decoy-mcp.test.ts b/tests/weave-decoy-mcp.test.tsnew file mode 100644index 0000000..df51510--- /dev/null+++ b/tests/weave-decoy-mcp.test.ts@@ -0,0 +1,149 @@+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import {+ BLA_MCP_PROMPTS,+ BLA_MCP_RESOURCES,+ BLA_MCP_TOOLS,+ handleMcpRequest,+} from "../src/mcp/server.js";+import {+ buildWeavePlan,+ getWeaveDirectivesMarkdown,+ WEAVE_ACCEPTANCE_TESTS,+ WEAVE_DECOY_SCHEMA,+ WEAVE_DIRECTIVES_URI,+ WEAVE_EXECUTOR_CHECKLIST,+ WEAVE_FORBIDDEN,+ WEAVE_PRINCIPLES,+} from "../src/shields/weave/weave-decoy.js";++const temps: string[] = [];+afterEach(() => {+ for (const d of temps.splice(0)) {+ rmSync(d, { recursive: true, force: true });+ }+});++describe("weave-decoy theory pack", () => {+ it("exposes principles, forbidden patterns, checklist, and acceptance tests", () => {+ expect(WEAVE_PRINCIPLES.length).toBeGreaterThanOrEqual(5);+ expect(WEAVE_FORBIDDEN.some((f) => f.id === "pure-noise-layer")).toBe(true);+ expect(WEAVE_FORBIDDEN.some((f) => f.id === "offensive-content")).toBe(true);+ expect(WEAVE_EXECUTOR_CHECKLIST.some((s) => s.id === "run-weave-plan")).toBe(+ true,+ );+ expect(WEAVE_ACCEPTANCE_TESTS.some((a) => a.id === "customer-entry-edges")).toBe(+ true,+ );+ const md = getWeaveDirectivesMarkdown();+ expect(md).toContain("WorkBuddy");+ expect(md).toContain(WEAVE_DIRECTIVES_URI);+ expect(md.toLowerCase()).not.toMatch(/exploit poc|crackme bypass playbook/);+ });++ it("buildWeavePlan classifies JS as woven and Python as warm-init-only", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-weave-plan-"));+ temps.push(dir);+ writeFileSync(join(dir, "app.js"), "function main(){ return 1; }\n");+ writeFileSync(join(dir, "svc.py"), "def main():\n return 1\n");+ const plan = buildWeavePlan(dir);+ expect(plan.schema).toBe(WEAVE_DECOY_SCHEMA);+ expect(plan.overallStatus).toBe("partial");+ const js = plan.targets.find((t) => t.relativePath.endsWith("app.js"));+ const py = plan.targets.find((t) => t.relativePath.endsWith("svc.py"));+ expect(js?.maturity).toBe("woven");+ expect(js?.status).toBe("ready");+ expect(py?.maturity).toBe("warm-init-only");+ expect(py?.status).toBe("partial");+ expect(plan.pipelineHook.mcpFlag).toBe("weave_decoys");+ });+});++describe("weave-decoy MCP descriptors", () => {+ it("lists bla_weave_plan and weave_decoys on harden/defend/protect", () => {+ expect(BLA_MCP_TOOLS.map((t) => t.name)).toContain("bla_weave_plan");+ for (const name of ["bla_harden", "bla_defend", "bla_protect"] as const) {+ const tool = BLA_MCP_TOOLS.find((t) => t.name === name)!;+ expect(tool.inputSchema.properties.weave_decoys?.type).toBe("boolean");+ }+ expect(BLA_MCP_RESOURCES.some((r) => r.uri === WEAVE_DIRECTIVES_URI)).toBe(+ true,+ );+ expect(BLA_MCP_PROMPTS.some((p) => p.name === "bla-weave-decoy")).toBe(true);+ });++ it("initialize advertises resources; resources/read returns directives", async () => {+ const init = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ });+ expect(+ (init?.result as { capabilities: { resources: object } }).capabilities+ .resources,+ ).toEqual({});++ const listed = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 2,+ method: "resources/list",+ });+ const resources = (+ listed?.result as { resources: Array<{ uri: string }> }+ ).resources;+ expect(resources.map((r) => r.uri)).toContain(WEAVE_DIRECTIVES_URI);++ const read = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 3,+ method: "resources/read",+ params: { uri: WEAVE_DIRECTIVES_URI },+ });+ const contents = (+ read?.result as { contents: Array<{ text: string; uri: string }> }+ ).contents;+ expect(contents[0]!.uri).toBe(WEAVE_DIRECTIVES_URI);+ expect(contents[0]!.text).toContain("bla_weave_plan");+ });++ it("tools/call bla_weave_plan returns structured plan", async () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-weave-mcp-"));+ temps.push(dir);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "x.js"), "exports.x = 1;\n");++ const res = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 4,+ method: "tools/call",+ params: {+ name: "bla_weave_plan",+ arguments: { path: dir },+ },+ });+ expect((res?.result as { isError?: boolean }).isError).toBe(false);+ const plan = (res?.result as { structuredContent: { schema: string; targets: unknown[] } })+ .structuredContent;+ expect(plan.schema).toBe(WEAVE_DECOY_SCHEMA);+ expect(plan.targets.length).toBeGreaterThanOrEqual(1);+ });++ it("prompts/get bla-weave-decoy mentions weave_decoys", async () => {+ const res = await handleMcpRequest({+ jsonrpc: "2.0",+ id: 5,+ method: "prompts/get",+ params: {+ name: "bla-weave-decoy",+ arguments: { target_path: "." },+ },+ });+ const text = (+ res?.result as { messages: Array<{ content: { text: string } }> }+ ).messages[0]!.content.text;+ expect(text).toContain("weave_decoys");+ expect(text).toContain("bla_weave_plan");+ });+});