cli-swarm 7.0.28 → 7.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -3,6 +3,11 @@
3
3
  "cli-swarm": "./cli.mjs"
4
4
  },
5
5
  "description": "Swarm skill installer for CLI.Tax: orchestrate N sub-agents with persistent AutoCoord locks and dependency waits.",
6
+ "exports": {
7
+ "./coordinator": "./swarm-coordinator.mjs",
8
+ "./coordinator-fs": "./swarm-coordinator-fs.mjs",
9
+ "./runtime": "./swarm-runtime.mjs"
10
+ },
6
11
  "files": [
7
12
  "cli.mjs",
8
13
  "installer.mjs",
@@ -13,6 +18,7 @@
13
18
  "swarm-coordinator-fs.mjs",
14
19
  "swarm-coordinator-model.mjs",
15
20
  "swarm-coordinator.mjs",
21
+ "swarm-runtime.mjs",
16
22
  "skill/references/org-chart.md",
17
23
  "skill/references/task-lifecycle.md",
18
24
  "skill/references/traffic-light.md",
@@ -27,5 +33,5 @@
27
33
  "url": "https://github.com/88208555/swarm-clitax.git"
28
34
  },
29
35
  "type": "module",
30
- "version": "7.0.28"
36
+ "version": "7.0.29"
31
37
  }
package/skill/SKILL.md CHANGED
@@ -5,7 +5,7 @@ description: '通过智能体大脑调度创建 N 个子智能体,用企业级
5
5
 
6
6
  # swarm
7
7
 
8
- Package version: v7.0.28
8
+ Package version: v7.0.29
9
9
 
10
10
  把「项目需求」编排为一支可观测、可自治、可安全运转的智能体蜂群。
11
11
 
package/skill/skill.json CHANGED
@@ -6,5 +6,5 @@
6
6
  "name": "swarm",
7
7
  "schemaVersion": "swarm.skill.request/1.0",
8
8
  "type": "Skill",
9
- "version": "v7.0.28"
9
+ "version": "v7.0.29"
10
10
  }
@@ -0,0 +1,502 @@
1
+ // swarm v7.0.10:自包含、无外部依赖的确定性蜂群编排运行时。
2
+ const REQUEST_SCHEMA = "swarm.skill.request/1.0";
3
+ const ALLOWED_EXTERNAL_ENDPOINTS = { blueprint: "https://cli.tax/wvz6zmRWmX" };
4
+ const RESPONSE_SCHEMA = "swarm.skill.response/1.0";
5
+ const ERROR_SCHEMA = "swarm.skill.error/1.0";
6
+ const ORG_SCHEMA = "swarm.org-chart/1.0";
7
+ const TASK_SCHEMA = "swarm.tasks/1.0";
8
+ const TEST_EVIDENCE_SCHEMA = "cli.tax.test-evidence/1.0";
9
+ const COMPILER_NAME = "swarm";
10
+ const COMPILER_VERSION = "v7.0.29";
11
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
12
+ const PURE_OPERATIONS = new Set([
13
+ "capabilities", "help", "intake", "org-chart", "blueprint-bridge", "dispatch", "claim",
14
+ "report", "accept", "swarm-status", "traffic-light", "security-check", "validate-json", "heartbeat", "reclaim",
15
+ ]);
16
+ function text(value) { return String(value ?? ""); }
17
+ function okResponse(requestId, payload) { return { schemaVersion: RESPONSE_SCHEMA, requestId, status: "succeeded", ...payload }; }
18
+ function blockedResponse(requestId, request, findings) {
19
+ return { schemaVersion: RESPONSE_SCHEMA, requestId, status: "blocked", brainMode: null,
20
+ requestedBrainMode: request?.requestedBrainMode ?? "ide", brainUsed: false, revision: null,
21
+ validation: { valid: false, guarantee: "blocked", findings } };
22
+ }
23
+ function finding(severity, ruleId, entityRef, message, evidence = {}) { return { severity, ruleId, entityRef, message, evidence }; }
24
+ function isObject(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
25
+ function validId(value) { return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(value); }
26
+ const ORG_LAYERS = ["board", "management", "execution"];
27
+ const ORG_ROLES = ["board", "dispatcher", "ops", "security-guard", "coordinator", "worker"];
28
+ const ORG_FIXED_ROLES = new Set(["board", "dispatcher", "ops", "security-guard", "coordinator"]);
29
+ const ORG_PERMISSIONS = {
30
+ board: ["dispatch", "accept", "reject", "stop", "reclaim", "replace"],
31
+ dispatcher: ["dispatch", "reassign", "prioritize"],
32
+ ops: ["heartbeat", "reclaim", "replace"],
33
+ "security-guard": ["block", "alert", "quarantine"],
34
+ coordinator: ["conflict-scan", "lock", "queue", "baseline-handshake", "dependency-wait", "wake", "need-human"],
35
+ worker: ["claim", "report", "request-help"],
36
+ };
37
+ function analyzeTaskGraph(tasks) {
38
+ const findings = [];
39
+ const ids = new Set();
40
+ for (const [index, task] of tasks.entries()) {
41
+ const ref = `tasks[${index}]`;
42
+ if (!isObject(task) || !validId(task.taskId)) { findings.push(finding("P0", "TASK_ID", `${ref}.taskId`, "taskId must be a stable identifier", { example: "task-1" })); continue; }
43
+ if (ids.has(task.taskId)) findings.push(finding("P0", "TASK_ID_DUPLICATE", `${ref}.taskId`, `duplicate taskId ${task.taskId}`));
44
+ ids.add(task.taskId);
45
+ }
46
+ for (const [index, task] of tasks.entries()) {
47
+ if (!isObject(task) || !Array.isArray(task.dependsOn)) continue;
48
+ for (const dependencyId of task.dependsOn) if (!ids.has(dependencyId)) findings.push(finding("P0", "DEPENDENCY_MISSING", `tasks[${index}].dependsOn`, `dependency ${dependencyId} does not exist`));
49
+ }
50
+ if (findings.length) return { findings, recommendedWorkerCount: null };
51
+ const remaining = new Map(tasks.map((task) => [task.taskId, task]));
52
+ const completed = new Set(), levels = [];
53
+ while (remaining.size > 0) {
54
+ const batch = [];
55
+ for (const [taskId, task] of remaining) {
56
+ const dependencies = Array.isArray(task.dependsOn) ? task.dependsOn : [];
57
+ if (dependencies.every((dependencyId) => completed.has(dependencyId))) batch.push(taskId);
58
+ }
59
+ if (batch.length === 0) return { findings: [finding("P0", "DEPENDENCY_CYCLE", "tasks", `dependency cycle includes: ${[...remaining.keys()].join(", ")}`)], recommendedWorkerCount: null };
60
+ levels.push(batch.length);
61
+ for (const taskId of batch) { remaining.delete(taskId); completed.add(taskId); }
62
+ }
63
+ return { findings: [], recommendedWorkerCount: Math.min(50, Math.max(...levels)) };
64
+ }
65
+ function buildOrgChart(input = {}) {
66
+ const workerCount = Math.min(50, Math.max(1, Math.floor(Number(input.workerCount) || 4)));
67
+ const projectName = text(input.projectName || "swarm-run");
68
+ let recommendedWorkerCount, recommendationFindings = [];
69
+ if (Array.isArray(input.tasks) && input.tasks.length > 0) {
70
+ const analysis = analyzeTaskGraph(input.tasks);
71
+ recommendedWorkerCount = analysis.recommendedWorkerCount ?? undefined;
72
+ recommendationFindings = analysis.findings;
73
+ }
74
+ const org = { schemaVersion: ORG_SCHEMA, projectName,
75
+ layers: {
76
+ board: [{ agentId: "board", role: "board", title: "决策层·老板/主智能体" }],
77
+ management: [
78
+ { agentId: "dispatcher", role: "dispatcher", title: "管理层·调度智能体", fixed: true },
79
+ { agentId: "ops", role: "ops", title: "管理层·运维智能体", fixed: true },
80
+ { agentId: "security-guard", role: "security-guard", title: "管理层·安全守卫智能体", fixed: true },
81
+ { agentId: "coordinator", role: "coordinator", title: "管理层·自动协调智能体", fixed: true },
82
+ ],
83
+ execution: Array.from({ length: workerCount }, (_, i) => ({ agentId: `worker-${String(i + 1).padStart(3, "0")}`,
84
+ role: "worker", title: `执行层·子智能体 ${i + 1}`, fixed: false })),
85
+ }, permissions: ORG_PERMISSIONS };
86
+ if (recommendedWorkerCount !== undefined) org.recommendedWorkerCount = recommendedWorkerCount;
87
+ if (recommendationFindings.length) org.recommendationFindings = recommendationFindings;
88
+ return org;
89
+ }
90
+ function validateOrgChart(org) {
91
+ const findings = [];
92
+ if (!isObject(org)) return [finding("P0", "ORG_OBJECT", "org", "org must be an object", { example: { schemaVersion: "swarm.org-chart/1.0" } })];
93
+ if (org.schemaVersion !== ORG_SCHEMA) findings.push(finding("P0", "ORG_SCHEMA_VERSION", "org.schemaVersion", `Expected ${ORG_SCHEMA}`, { example: { schemaVersion: "swarm.org-chart/1.0" } }));
94
+ for (const layer of ORG_LAYERS) if (!Array.isArray(org.layers?.[layer])) findings.push(finding("P0", "ORG_LAYER_ARRAY", `org.layers.${layer}`, "must be an array", { example: { layers: { board: [] } } }));
95
+ if (Array.isArray(org.recommendationFindings)) findings.push(...org.recommendationFindings);
96
+ return findings;
97
+ }
98
+ const INJECTION_PATTERNS = [
99
+ /ignore\s+(all\s+)?previous\s+instructions/i,
100
+ /忽略\s*(之前|此前|先前)\s*(的)?(所有)?指令/i,
101
+ /you\s+are\s+now|act\s+as\s+an?\s+(admin|system|root)/i,
102
+ /现在你(是|要|必须)/,
103
+ /(?:系统|system)\s*(提示词|提示|指令)\s*[::]/,
104
+ ];
105
+ const DANGEROUS_PATTERNS = [
106
+ /\brm\s+-rf\b|\bDROP\s+TABLE\b|\bDELETE\s+FROM\b/i,
107
+ /\bsudo\b|\bchmod\s+777\b|提权|越权/i,
108
+ /(?:导出|输出|给出|返回|泄露|外发|发送|上传|回传|读取|获取)[^。\n]{0,24}?(?:api[_-]?\s*key|token|password|secret|密钥|密码|凭据)/i,
109
+ /(?:api[_-]?\s*key|token|password|secret|密钥|密码|凭据)\s*(?:[::=]\s*[A-Za-z0-9_\-]{6,}|请\s*(?:输出|给出|返回|提供))/i,
110
+ /(?:发送|上传|回传|外发)\s*(?:到|至)?\s*https?:\/\//i,
111
+ ];
112
+ function securityCheck(content, context = {}) {
113
+ const input = text(content), agentId = text(context.agentId || "unknown"), alerts = [];
114
+ const injectionHits = INJECTION_PATTERNS.filter((p) => p.test(input)).map((p) => p.source);
115
+ if (injectionHits.length) alerts.push({ alertId: `sec-${Math.random().toString(36).slice(2, 8)}`, severity: "high",
116
+ rule: "prompt-injection", agentId, source: "task-input", matched: injectionHits, action: "block", at: new Date().toISOString() });
117
+ const dangerHits = DANGEROUS_PATTERNS.filter((p) => p.test(input)).map((p) => p.source);
118
+ if (dangerHits.length) alerts.push({ alertId: `sec-${Math.random().toString(36).slice(2, 8)}`, severity: "high",
119
+ rule: "dangerous-command", agentId, source: "task-input", matched: dangerHits, action: "block", at: new Date().toISOString() });
120
+ return { allowed: alerts.length === 0, blocked: alerts.length > 0, alerts };
121
+ }
122
+ const TASK_STATUSES = new Set(["backlog", "assigned", "claimed", "running", "reported", "accepted", "failed", "blocked", "cancelled"]);
123
+ function validateProjectJson(project) {
124
+ const findings = [];
125
+ if (!isObject(project)) return [finding("P0", "PROJECT_OBJECT", "project", "project must be an object", { example: { tasks: [{ taskId: "t1" }] } })];
126
+ if (!Array.isArray(project.tasks) || project.tasks.length === 0) findings.push(finding("P0", "PROJECT_TASKS", "project.tasks", "tasks must be a non-empty array", { example: { tasks: [{ taskId: "t1", title: "example" }] } }));
127
+ else findings.push(...analyzeTaskGraph(project.tasks).findings);
128
+ return findings;
129
+ }
130
+ function buildTasks(project, org) {
131
+ return (project.tasks ?? []).map((task, index) => ({
132
+ taskId: validId(task.taskId) ? task.taskId : `task-${String(index + 1).padStart(4, "0")}`,
133
+ title: text(task.title || task.name || `任务 ${index + 1}`), owner: null, status: "backlog",
134
+ priority: text(task.priority || "normal"), dependsOn: Array.isArray(task.dependsOn) ? task.dependsOn : [],
135
+ assignedBy: null, claimedAt: null, reportedAt: null, report: null, progressPercent: 0,
136
+ progressNote: "", inheritedFrom: null }));
137
+ }
138
+ function dispatchTask(tasks, taskId, workerId, actorRole) {
139
+ if (!ORG_PERMISSIONS[actorRole]?.includes("dispatch")) return { ok: false, error: `role ${actorRole} cannot dispatch` };
140
+ const task = tasks.find((t) => t.taskId === taskId);
141
+ if (!task) return { ok: false, error: `task ${taskId} not found` };
142
+ if (task.status !== "backlog") return { ok: false, error: `task ${taskId} is ${task.status}, not backlog` };
143
+ for (const dependencyId of Array.isArray(task.dependsOn) ? task.dependsOn : []) {
144
+ const dependency = tasks.find((candidate) => candidate.taskId === dependencyId);
145
+ if (!dependency) return { ok: false, error: `dependency ${dependencyId} not found` };
146
+ if (dependency.status !== "accepted") return { ok: false, error: `dependency ${dependencyId} is ${dependency.status}, not accepted` };
147
+ }
148
+ task.status = "assigned"; task.owner = workerId; task.assignedBy = actorRole;
149
+ return { ok: true, task };
150
+ }
151
+ function claimTask(tasks, taskId, workerId) {
152
+ const task = tasks.find((t) => t.taskId === taskId);
153
+ if (!task) return { ok: false, error: `task ${taskId} not found` };
154
+ if (task.status !== "assigned") return { ok: false, error: `task ${taskId} is ${task.status}, not assigned` };
155
+ if (task.owner && task.owner !== workerId) return { ok: false, error: `task ${taskId} claimed by another worker` };
156
+ task.status = "claimed"; task.owner = workerId; task.claimedAt = new Date().toISOString();
157
+ return { ok: true, task };
158
+ }
159
+ function validateTestEvidence(value, entityRef) {
160
+ const findings = [];
161
+ if (!isObject(value)) return [finding("P0", "TEST_EVIDENCE_OBJECT", entityRef, "TestEvidence must be an object")];
162
+ if (value.schemaVersion !== TEST_EVIDENCE_SCHEMA) findings.push(finding("P0", "TEST_EVIDENCE_SCHEMA", `${entityRef}.schemaVersion`, `Expected ${TEST_EVIDENCE_SCHEMA}`));
163
+ if (!text(value.evidenceId).trim()) findings.push(finding("P0", "TEST_EVIDENCE_ID", `${entityRef}.evidenceId`, "evidenceId is required"));
164
+ if (!["test", "build", "lint", "security", "benchmark"].includes(value.kind)) findings.push(finding("P0", "TEST_EVIDENCE_KIND", `${entityRef}.kind`, "kind is unsupported"));
165
+ if (!["local", "trusted-runner"].includes(value.runner)) findings.push(finding("P0", "TEST_EVIDENCE_RUNNER", `${entityRef}.runner`, "runner must be local or trusted-runner"));
166
+ if (!text(value.command).trim()) findings.push(finding("P0", "TEST_EVIDENCE_COMMAND", `${entityRef}.command`, "command is required"));
167
+ if (!Number.isInteger(value.exitCode)) findings.push(finding("P0", "TEST_EVIDENCE_EXIT", `${entityRef}.exitCode`, "exitCode must be an integer"));
168
+ if (typeof value.durationMs !== "number" || !Number.isFinite(value.durationMs) || value.durationMs < 0) findings.push(finding("P0", "TEST_EVIDENCE_DURATION", `${entityRef}.durationMs`, "durationMs must be a finite number >= 0"));
169
+ if (!text(value.summary).trim()) findings.push(finding("P0", "TEST_EVIDENCE_SUMMARY", `${entityRef}.summary`, "summary is required"));
170
+ if (value.artifactSha256 !== undefined && !SHA256_PATTERN.test(value.artifactSha256)) findings.push(finding("P0", "TEST_EVIDENCE_ARTIFACT", `${entityRef}.artifactSha256`, "artifactSha256 must be a lowercase SHA-256 digest"));
171
+ return findings;
172
+ }
173
+ function normalizeTestEvidence(values) {
174
+ if (!Array.isArray(values)) return { evidence: [], findings: [finding("P0", "TEST_EVIDENCE_ARRAY", "report.evidence", "evidence must be an array")] };
175
+ const findings = values.flatMap((value, index) => validateTestEvidence(value, `report.evidence[${index}]`));
176
+ return findings.length ? { evidence: [], findings } : { evidence: values.map((value) => ({ ...value })), findings: [] };
177
+ }
178
+ function hasPassingTestEvidence(task) {
179
+ const evidence = task?.report?.evidence;
180
+ return Array.isArray(evidence) && evidence.length > 0
181
+ && evidence.every((value, index) => validateTestEvidence(value, `task.report.evidence[${index}]`).length === 0 && value.exitCode === 0);
182
+ }
183
+ function reportTask(tasks, taskId, workerId, report) {
184
+ const task = tasks.find((t) => t.taskId === taskId);
185
+ if (!task) return { ok: false, error: `task ${taskId} not found` };
186
+ if (task.owner && task.owner !== workerId) return { ok: false, error: `task ${taskId} not owned by ${workerId}` };
187
+ if (!["claimed", "running"].includes(task.status)) return { ok: false, error: `task ${taskId} is ${task.status}, cannot report` };
188
+ if (!isObject(report)) return { ok: false, error: "report must be an object" };
189
+ if (!text(report.output).trim() && report.evidence === undefined) return { ok: false, error: "report must have output or evidence" };
190
+ const normalizedReport = { output: text(report.output) };
191
+ if (report.evidence !== undefined) {
192
+ const normalized = normalizeTestEvidence(report.evidence);
193
+ if (normalized.findings.length) return { ok: false, error: "report evidence is invalid", findings: normalized.findings };
194
+ normalizedReport.evidence = normalized.evidence;
195
+ }
196
+ task.status = "reported"; task.report = normalizedReport; task.reportedAt = new Date().toISOString();
197
+ return { ok: true, task, hasEvidence: hasPassingTestEvidence(task) };
198
+ }
199
+ function acceptTask(tasks, taskId, accept, actorRole) {
200
+ if (actorRole !== "board") return { ok: false, error: `role ${actorRole} cannot accept` };
201
+ const task = tasks.find((t) => t.taskId === taskId);
202
+ if (!task) return { ok: false, error: `task ${taskId} not found` };
203
+ if (task.status !== "reported") return { ok: false, error: `task ${taskId} is ${task.status}, not reported` };
204
+ if (accept && !hasPassingTestEvidence(task)) return { ok: false, error: `task ${taskId} has no passing TestEvidence` };
205
+ task.status = accept ? "accepted" : "failed";
206
+ return { ok: true, task };
207
+ }
208
+ function taskTrafficLight(task) {
209
+ if (task.status === "accepted") return hasPassingTestEvidence(task) ? "green" : "red";
210
+ if (task.status === "reported") return hasPassingTestEvidence(task) ? "green" : "yellow";
211
+ if (task.status === "failed" || task.status === "blocked" || task.status === "cancelled") return "red";
212
+ return "yellow";
213
+ }
214
+ const HEARTBEAT_MISS_LIMIT = 3;
215
+ function buildAgents(org, nowIso = null) {
216
+ const now = nowIso || new Date().toISOString(), agents = [];
217
+ for (const layer of ORG_LAYERS) for (const member of org.layers?.[layer] ?? []) {
218
+ agents.push({ agentId: member.agentId, role: member.role, title: member.title,
219
+ fixed: Boolean(member.fixed), status: "green", lastHeartbeatAt: now,
220
+ heartbeatMisses: 0, currentTaskId: null, progressPercent: 0, progressNote: "" });
221
+ }
222
+ return agents;
223
+ }
224
+ function recordHeartbeat(agents, agentId) {
225
+ const agent = agents.find((a) => a.agentId === agentId);
226
+ if (!agent) return { ok: false, error: `agent ${agentId} not found` };
227
+ agent.lastHeartbeatAt = new Date().toISOString();
228
+ agent.heartbeatMisses = 0;
229
+ if (agent.status === "dead" || agent.status === "red") agent.status = "green";
230
+ return { ok: true, agent };
231
+ }
232
+ function scanHeartbeats(agents, nowIso = null) {
233
+ const now = nowIso ? new Date(nowIso).getTime() : Date.now();
234
+ const dead = [];
235
+ for (const agent of agents) {
236
+ if (agent.role !== "worker") continue;
237
+ const misses = Math.floor((now - new Date(agent.lastHeartbeatAt).getTime()) / 30000);
238
+ agent.heartbeatMisses = Math.max(agent.heartbeatMisses, Math.min(misses, 99));
239
+ if (agent.heartbeatMisses >= HEARTBEAT_MISS_LIMIT && agent.status !== "dead") { agent.status = "dead"; dead.push(agent.agentId); }
240
+ else if (agent.heartbeatMisses >= 1) agent.status = "yellow";
241
+ else agent.status = "green";
242
+ }
243
+ return dead;
244
+ }
245
+ function reclaimTasks(tasks, workerId) {
246
+ const reclaimed = [];
247
+ for (const task of tasks) {
248
+ if (task.owner === workerId && ["assigned", "claimed", "running"].includes(task.status)) {
249
+ task.status = "backlog"; task.owner = null; task.inheritedFrom = workerId; reclaimed.push(task.taskId);
250
+ }
251
+ }
252
+ return reclaimed;
253
+ }
254
+ function replaceWorker(org, agents, tasks, deadWorkerId, newWorkerId = null) {
255
+ const dead = agents.find((a) => a.agentId === deadWorkerId);
256
+ if (!dead) return { ok: false, error: `dead worker ${deadWorkerId} not found` };
257
+ const replacement = newWorkerId ? agents.find((a) => a.agentId === newWorkerId && a.role === "worker")
258
+ : agents.find((a) => a.role === "worker" && a.status === "green" && a.agentId !== deadWorkerId);
259
+ if (!replacement) return { ok: false, error: "no healthy replacement worker available" };
260
+ const inheritedTasks = reclaimTasks(tasks, deadWorkerId);
261
+ for (const taskId of inheritedTasks) {
262
+ const task = tasks.find((t) => t.taskId === taskId);
263
+ if (task) { task.owner = replacement.agentId; task.status = "assigned"; task.assignedBy = "ops"; task.inheritedFrom = deadWorkerId; }
264
+ }
265
+ dead.status = "dead";
266
+ replacement.currentTaskId = inheritedTasks[0] ?? null;
267
+ return { ok: true, replacement: replacement.agentId, inheritedTasks };
268
+ }
269
+ const INTAKE_QUESTIONS = [
270
+ { id: "goal", prompt: "What must the swarm accomplish? List the parallel/ordered work items or point to the project JSON.", required: true, example: "12 个模块迁移:A1..A12,依赖 A1→A2→A3,其余并行" },
271
+ { id: "workerCount", prompt: "How many worker sub-agents should the brain create?", required: false, example: "6" },
272
+ { id: "orgTier", prompt: "Any org-chart constraints? (default: board → dispatcher/ops/security-guard → workers)", required: false, example: "默认三层即可" },
273
+ { id: "securityPolicy", prompt: "Security policy: strict (block injections) or observe (alert only)?", required: false, example: "strict" },
274
+ { id: "blueprintEnabled", prompt: "Use Blueprint to plan tasks before dispatch? (yes: tasks are planned by the Blueprint skill for traceable acceptance; no: direct dispatch)", required: false, example: "no" },
275
+ ];
276
+ const OPERATION_CATALOG = Object.freeze([...PURE_OPERATIONS].map((operation) => ({ operation, summary: operation })));
277
+ const stringSchema = (extra = {}) => ({ type: "string", ...extra });
278
+ const arraySchema = (items, extra = {}) => ({ type: "array", items, ...extra });
279
+ const objectSchema = (properties, required = [], extra = {}) => ({ type: "object", properties, required, additionalProperties: false, ...extra });
280
+ const anyObjectSchema = { type: "object" };
281
+ const nullableStringSchema = { type: ["string", "null"] };
282
+ const evidenceSchema = objectSchema({
283
+ schemaVersion: { const: TEST_EVIDENCE_SCHEMA }, evidenceId: stringSchema({ minLength: 1 }),
284
+ kind: { enum: ["test", "build", "lint", "security", "benchmark"] }, runner: { enum: ["local", "trusted-runner"] },
285
+ command: stringSchema({ minLength: 1 }), exitCode: { type: "integer" }, durationMs: { type: "number", minimum: 0 },
286
+ summary: stringSchema({ minLength: 1 }), artifactSha256: stringSchema({ pattern: SHA256_PATTERN.source }),
287
+ }, ["schemaVersion", "evidenceId", "kind", "runner", "command", "exitCode", "durationMs", "summary"], { additionalProperties: true });
288
+ const reportSchema = objectSchema({ output: stringSchema(), evidence: arraySchema(evidenceSchema) }, [], {
289
+ anyOf: [{ properties: { output: stringSchema({ minLength: 1 }) }, required: ["output"] }, { required: ["evidence"] }],
290
+ });
291
+ const taskSchema = objectSchema({
292
+ taskId: stringSchema({ minLength: 1 }), title: stringSchema(), owner: nullableStringSchema,
293
+ status: { enum: [...TASK_STATUSES] }, priority: stringSchema(), dependsOn: arraySchema(stringSchema()),
294
+ assignedBy: nullableStringSchema, claimedAt: nullableStringSchema, reportedAt: nullableStringSchema,
295
+ report: { anyOf: [{ type: "null" }, reportSchema] }, progressPercent: { type: "number" }, progressNote: stringSchema(),
296
+ inheritedFrom: nullableStringSchema, trafficLight: { enum: ["green", "yellow", "red"] },
297
+ }, ["taskId", "title", "status", "dependsOn"], { additionalProperties: true });
298
+ const projectTaskSchema = objectSchema({ taskId: stringSchema({ minLength: 1 }), title: stringSchema({ minLength: 1 }),
299
+ name: stringSchema(), priority: stringSchema(), dependsOn: arraySchema(stringSchema()) }, ["taskId", "title"], { additionalProperties: true });
300
+ const agentSchema = objectSchema({ agentId: stringSchema({ minLength: 1 }), role: { enum: ORG_ROLES }, title: stringSchema(),
301
+ fixed: { type: "boolean" }, status: { enum: ["green", "yellow", "red", "dead"] }, lastHeartbeatAt: stringSchema({ format: "date-time" }),
302
+ heartbeatMisses: { type: "integer", minimum: 0 }, currentTaskId: nullableStringSchema,
303
+ progressPercent: { type: "number" }, progressNote: stringSchema() }, ["agentId", "role", "status"], { additionalProperties: true });
304
+ const nextSchema = objectSchema({ operation: { type: ["string", "null"] }, instruction: stringSchema() }, ["operation", "instruction"]);
305
+ const responseBase = { schemaVersion: { const: RESPONSE_SCHEMA }, requestId: stringSchema({ minLength: 1 }) };
306
+ const succeededSchema = (properties, required = []) => objectSchema({ ...responseBase, status: { const: "succeeded" }, ...properties }, ["schemaVersion", "requestId", "status", ...required]);
307
+ const blockedSchema = objectSchema({ ...responseBase, status: { const: "blocked" }, brainMode: { type: "null" }, requestedBrainMode: stringSchema(),
308
+ brainUsed: { const: false }, revision: { type: "null" }, validation: anyObjectSchema, errorSchema: { const: ERROR_SCHEMA } },
309
+ ["schemaVersion", "requestId", "status", "brainMode", "requestedBrainMode", "brainUsed", "revision", "validation"]);
310
+ const failedSchema = objectSchema({ ...responseBase, status: { const: "failed" }, errorSchema: { const: ERROR_SCHEMA }, error: anyObjectSchema },
311
+ ["schemaVersion", "requestId", "status", "errorSchema", "error"]);
312
+ const operationSchema = (input, inputRequired, output, outputRequired) => ({ input: objectSchema(input, inputRequired),
313
+ output: { type: "object", oneOf: [succeededSchema(output, outputRequired), blockedSchema, failedSchema] } });
314
+ const tasksInput = { tasks: arraySchema(taskSchema), taskId: stringSchema({ minLength: 1 }) };
315
+ const taskStateOutput = { task: taskSchema, tasks: arraySchema(taskSchema), stateNote: stringSchema() };
316
+ const OPERATION_SCHEMAS = Object.freeze({
317
+ capabilities: operationSchema({}, [], { capabilities: anyObjectSchema, operationSchemas: anyObjectSchema, skill: anyObjectSchema, nextStep: nextSchema }, ["capabilities", "operationSchemas", "skill", "nextStep"]),
318
+ help: operationSchema({}, [], { help: anyObjectSchema, nextStep: nextSchema }, ["help", "nextStep"]),
319
+ intake: operationSchema({}, [], { questions: arraySchema(anyObjectSchema), nextStep: nextSchema }, ["questions", "nextStep"]),
320
+ "org-chart": operationSchema({ workerCount: { type: "number", minimum: 1, maximum: 50 }, projectName: stringSchema(), blueprintEnabled: { type: ["boolean", "string"] }, tasks: arraySchema(projectTaskSchema) }, [], { org: anyObjectSchema, blueprintEnabled: { type: "boolean" }, fixedAgents: arraySchema(stringSchema()), workerCount: { type: "integer" }, nextStep: nextSchema }, ["org", "blueprintEnabled", "fixedAgents", "workerCount", "nextStep"]),
321
+ "blueprint-bridge": operationSchema({ projectName: stringSchema({ minLength: 1 }), tasks: arraySchema(projectTaskSchema, { minItems: 1 }) }, ["projectName", "tasks"], { planningStatus: { const: "planned" }, blueprintEnabled: { const: true }, blueprintEndpoint: stringSchema({ format: "uri" }), blueprintRequest: anyObjectSchema, projectFormat: { const: "swarm.project/1.0" }, nextStep: nextSchema }, ["planningStatus", "blueprintEnabled", "blueprintEndpoint", "blueprintRequest", "projectFormat", "nextStep"]),
322
+ dispatch: operationSchema({ ...tasksInput, workerId: stringSchema({ minLength: 1 }), actorRole: { enum: ["dispatcher", "board"] } }, ["tasks", "taskId", "workerId", "actorRole"], { ...taskStateOutput, nextStep: nextSchema }, ["task", "tasks", "stateNote", "nextStep"]),
323
+ claim: operationSchema({ ...tasksInput, workerId: stringSchema({ minLength: 1 }) }, ["tasks", "taskId", "workerId"], { ...taskStateOutput, trafficLight: { enum: ["green", "yellow", "red"] }, nextStep: nextSchema }, ["task", "tasks", "trafficLight", "stateNote", "nextStep"]),
324
+ report: operationSchema({ ...tasksInput, workerId: stringSchema({ minLength: 1 }), report: reportSchema }, ["tasks", "taskId", "workerId", "report"], { ...taskStateOutput, trafficLight: { enum: ["green", "yellow", "red"] }, evidenceRequired: { type: "boolean" }, nextStep: nextSchema }, ["task", "tasks", "trafficLight", "stateNote", "nextStep"]),
325
+ accept: operationSchema({ ...tasksInput, actorRole: { const: "board" }, accept: { type: "boolean" } }, ["tasks", "taskId", "actorRole", "accept"], { ...taskStateOutput, trafficLight: { enum: ["green", "yellow", "red"] }, nextStep: nextSchema }, ["task", "tasks", "trafficLight", "stateNote", "nextStep"]),
326
+ "swarm-status": operationSchema({ tasks: arraySchema(taskSchema), agents: arraySchema(agentSchema) }, ["tasks", "agents"], { tasks: arraySchema(taskSchema), agents: arraySchema(agentSchema), summary: anyObjectSchema, stateNote: stringSchema(), nextStep: nextSchema }, ["tasks", "agents", "summary", "stateNote", "nextStep"]),
327
+ "traffic-light": operationSchema({ task: taskSchema }, ["task"], { trafficLight: { enum: ["green", "yellow", "red"] }, rules: anyObjectSchema }, ["trafficLight", "rules"]),
328
+ "security-check": operationSchema({ content: stringSchema(), agentId: stringSchema() }, ["content"], { allowed: { type: "boolean" }, blocked: { type: "boolean" }, alerts: arraySchema(anyObjectSchema), nextStep: nextSchema }, ["allowed", "blocked", "alerts", "nextStep"]),
329
+ "validate-json": operationSchema({ project: objectSchema({ tasks: arraySchema(projectTaskSchema, { minItems: 1 }) }, ["tasks"], { additionalProperties: true }) }, ["project"], { valid: { const: true }, taskCount: { type: "integer", minimum: 1 }, nextStep: nextSchema }, ["valid", "taskCount", "nextStep"]),
330
+ heartbeat: operationSchema({ tasks: arraySchema(taskSchema), workerId: stringSchema({ minLength: 1 }) }, ["tasks", "workerId"], { active: { const: true }, lastSeenAt: stringSchema({ format: "date-time" }), workerId: stringSchema(), assignedTaskIds: arraySchema(stringSchema()), stateNote: stringSchema() }, ["active", "lastSeenAt", "workerId", "assignedTaskIds", "stateNote"]),
331
+ reclaim: operationSchema({ ...tasksInput, reason: stringSchema() }, ["tasks", "taskId"], { reclaimed: { const: true }, taskId: stringSchema(), reason: stringSchema(), ...taskStateOutput }, ["reclaimed", "taskId", "reason", "task", "tasks", "stateNote"]),
332
+ });
333
+ function validateRequest(request) {
334
+ const findings = [];
335
+ if (!isObject(request)) return [finding("P0", "REQUEST_OBJECT", "request", "request must be an object", { example: { schemaVersion: REQUEST_SCHEMA, requestId: "req-1", operation: "capabilities" } })];
336
+ if (request.schemaVersion !== REQUEST_SCHEMA) {
337
+ findings.push(finding("P0", "REQUEST_SCHEMA", "request.schemaVersion", `Expected ${REQUEST_SCHEMA}`, { example: { schemaVersion: REQUEST_SCHEMA } }));
338
+ }
339
+ if (!text(request.requestId)) findings.push(finding("P0", "REQUEST_REQUIRED_FIELD", "request.requestId", "requestId is required", { example: { requestId: "req-1" } }));
340
+ if (!text(request.operation)) findings.push(finding("P0", "REQUEST_REQUIRED_FIELD", "request.operation", "operation is required", { example: { operation: "capabilities" } }));
341
+ return findings;
342
+ }
343
+ function blueprintIdFromName(projectName) {
344
+ const encoded = Array.from(projectName.trim().toLowerCase()).map((character) => {
345
+ if (/^[a-z0-9]$/.test(character)) return character;
346
+ if (/^[\s_-]$/.test(character)) return "-";
347
+ return `u${character.codePointAt(0).toString(16)}`;
348
+ }).join("-").replace(/-+/g, "-").replace(/^-|-$/g, "");
349
+ return `swarm-${encoded}`.slice(0, 64).replace(/-$/g, "");
350
+ }
351
+ function buildBlueprintBridge(input, requestId) {
352
+ const projectName = text(input.projectName).trim(), tasks = Array.isArray(input.tasks) ? input.tasks : [], findings = [];
353
+ if (!projectName) findings.push(finding("P0", "BLUEPRINT_PROJECT_NAME", "input.projectName", "projectName is required"));
354
+ if (tasks.length === 0) findings.push(finding("P0", "BLUEPRINT_TASKS", "input.tasks", "tasks must be a non-empty array"));
355
+ for (const [index, task] of tasks.entries()) if (!text(task?.title).trim()) findings.push(finding("P0", "BLUEPRINT_TASK_TITLE", `input.tasks[${index}].title`, "task title is required"));
356
+ if (tasks.length) findings.push(...analyzeTaskGraph(tasks).findings);
357
+ if (findings.length) return { findings };
358
+ const nodeIds = new Map(tasks.map((task, index) => [task.taskId, `task-node-${index + 1}`]));
359
+ const taskNodes = tasks.map((task, index) => ({ id: nodeIds.get(task.taskId), moduleId: "swarm-tasks",
360
+ title: text(task.title).trim(), inputs: [], outputs: [], requirementRefs: [`fact-task-${index + 1}`] }));
361
+ const roots = tasks.filter((task) => !Array.isArray(task.dependsOn) || task.dependsOn.length === 0);
362
+ const rootEdges = roots.map((task, index) => ({ id: `edge-entry-${index + 1}`, fromNodeId: "swarm-entry", toNodeId: nodeIds.get(task.taskId), type: "control" }));
363
+ const dependencyEdges = tasks.flatMap((task, taskIndex) => (task.dependsOn ?? []).map((dependencyId, dependencyIndex) =>
364
+ ({ id: `edge-dependency-${taskIndex + 1}-${dependencyIndex + 1}`, fromNodeId: nodeIds.get(dependencyId), toNodeId: nodeIds.get(task.taskId), type: "control" })));
365
+ const blueprint = {
366
+ schemaVersion: "blueprint.ir/1.0", blueprintId: blueprintIdFromName(projectName), title: projectName,
367
+ revision: 0, entryNodeId: "swarm-entry",
368
+ baseline: { summary: `Swarm plan for ${projectName}`, facts: [
369
+ { id: "fact-goal", status: "confirmed", statement: `Swarm goal: ${projectName}` },
370
+ ...tasks.map((task, index) => ({ id: `fact-task-${index + 1}`, status: "confirmed", statement: `Task ${task.taskId}: ${text(task.title).trim()}` })),
371
+ ] },
372
+ domains: [{ id: "swarm-domain", name: "Swarm orchestration" }],
373
+ modules: [{ id: "swarm-tasks", domainId: "swarm-domain", name: "Dispatched tasks" }],
374
+ nodes: [{ id: "swarm-entry", entry: true, moduleId: "swarm-tasks", title: "Start swarm", inputs: [], outputs: [], requirementRefs: ["fact-goal"] }, ...taskNodes],
375
+ edges: [...rootEdges, ...dependencyEdges],
376
+ acceptanceCriteria: [
377
+ { id: "accept-entry", statement: "Swarm dispatch starts from the validated project", nodeRefs: ["swarm-entry"] },
378
+ ...tasks.map((task, index) => ({ id: `accept-task-${index + 1}`, statement: `Task ${task.taskId} is reported with passing evidence and accepted`, nodeRefs: [nodeIds.get(task.taskId)] })),
379
+ ],
380
+ };
381
+ return { blueprintRequest: { input: { schemaVersion: "blueprint.skill.request/1.0", requestId: `${requestId}-blueprint`,
382
+ operation: "compile-inline", input: { blueprint } } } };
383
+ }
384
+ const STATE_NOTE = "The caller owns state and must pass this full tasks array to the next operation.";
385
+ function runMeta(operation, requestId) {
386
+ if (operation === "capabilities") {
387
+ return okResponse(requestId, {
388
+ capabilities: { pure: true, stateless: true, networkRequired: false, filesystemRequired: false,
389
+ operations: [...PURE_OPERATIONS], orgSchema: ORG_SCHEMA, taskSchema: TASK_SCHEMA,
390
+ testEvidenceSchema: TEST_EVIDENCE_SCHEMA, fixedAgents: ["board", "dispatcher", "ops", "security-guard", "coordinator"],
391
+ trafficLights: ["green", "yellow", "red"], stateHolder: "caller",
392
+ coordinator: { command: "cli-swarm local", capabilitiesOperation: "capabilities",
393
+ stateBoundary: ".coord", messageTypes: ["range-declare", "conflict-alert", "lock-granted", "lock-denied", "baseline-handshake", "need-human", "dependency-wait"] },
394
+ workerRecommendation: "maximum acyclic dependency level width, capped at 50" },
395
+ operationSchemas: OPERATION_SCHEMAS,
396
+ skill: { name: COMPILER_NAME, version: COMPILER_VERSION },
397
+ nextStep: { operation: "intake", instruction: "Ask the intake questions, then build the org-chart and dispatch tasks." } });
398
+ }
399
+ if (operation === "help") return okResponse(requestId, { help: { name: COMPILER_NAME, version: COMPILER_VERSION, operations: OPERATION_CATALOG }, nextStep: { operation: "intake", instruction: "Ask the intake questions one at a time." } });
400
+ return okResponse(requestId, { questions: INTAKE_QUESTIONS, nextStep: { operation: "org-chart", instruction: "Turn the answers into an org-chart; optionally plan tasks with Blueprint (input.blueprintEnabled), then dispatch the project tasks." } });
401
+ }
402
+ function runPlanning(operation, requestId, input, request) {
403
+ if (operation === "org-chart") {
404
+ const org = buildOrgChart(input);
405
+ const findings = validateOrgChart(org);
406
+ if (findings.length) return blockedResponse(requestId, request, findings);
407
+ const blueprintEnabled = input.blueprintEnabled === true || text(input.blueprintEnabled).toLowerCase() === "yes";
408
+ return okResponse(requestId, { org, blueprintEnabled, fixedAgents: ["board", "dispatcher", "ops", "security-guard", "coordinator"], workerCount: org.layers.execution.length,
409
+ nextStep: blueprintEnabled
410
+ ? { operation: "blueprint-bridge", instruction: "Blueprint is enabled: call blueprint-bridge to plan the project JSON into a traceable blueprint, then dispatch its tasks to the swarm." }
411
+ : { operation: "dispatch", instruction: "Feed the project JSON; dispatch backlog tasks to workers by dependency order." } });
412
+ }
413
+ const bridge = buildBlueprintBridge(input, requestId);
414
+ if (bridge.findings) return blockedResponse(requestId, request, bridge.findings);
415
+ return okResponse(requestId, { planningStatus: "planned", blueprintEnabled: true, blueprintEndpoint: ALLOWED_EXTERNAL_ENDPOINTS.blueprint,
416
+ blueprintRequest: bridge.blueprintRequest, projectFormat: "swarm.project/1.0",
417
+ nextStep: { operation: "dispatch", instruction: `POST blueprintRequest to ${ALLOWED_EXTERNAL_ENDPOINTS.blueprint}; dispatch only after Blueprint compile-inline succeeds.` } });
418
+ }
419
+ function runTaskMutation(operation, requestId, input, request) {
420
+ const tasks = Array.isArray(input.tasks) ? input.tasks : [], taskId = text(input.taskId);
421
+ if (operation === "dispatch") {
422
+ const result = dispatchTask(tasks, taskId, text(input.workerId), text(input.actorRole || "dispatcher"));
423
+ if (!result.ok) return blockedResponse(requestId, request, [finding("P0", "DISPATCH_FAILED", input.taskId, result.error, { example: { taskId: "task-0001", workerId: "worker-001" } })]);
424
+ return okResponse(requestId, { task: result.task, tasks, stateNote: STATE_NOTE, nextStep: { operation: "claim", instruction: "The worker can now claim the task." } });
425
+ }
426
+ if (operation === "claim") {
427
+ const result = claimTask(tasks, taskId, text(input.workerId));
428
+ if (!result.ok) return blockedResponse(requestId, request, [finding("P0", "CLAIM_FAILED", input.taskId, result.error, { example: { taskId: "task-0001", workerId: "worker-001" } })]);
429
+ return okResponse(requestId, { task: result.task, tasks, trafficLight: taskTrafficLight(result.task), stateNote: STATE_NOTE, nextStep: { operation: "report", instruction: "Execute and report the result." } });
430
+ }
431
+ if (operation === "report") {
432
+ const result = reportTask(tasks, taskId, text(input.workerId), input.report);
433
+ if (!result.ok) return blockedResponse(requestId, request, result.findings ?? [finding("P0", "REPORT_FAILED", input.taskId, result.error, { example: { taskId: "task-0001", workerId: "worker-001", report: { output: "done" } } })]);
434
+ const extra = result.hasEvidence ? {} : { evidenceRequired: true };
435
+ return okResponse(requestId, { task: result.task, tasks, trafficLight: result.hasEvidence ? taskTrafficLight(result.task) : "yellow",
436
+ ...extra, stateNote: STATE_NOTE, nextStep: { operation: "accept", instruction: "The board may accept only after passing TestEvidence is present." } });
437
+ }
438
+ if (typeof input.accept !== "boolean") return blockedResponse(requestId, request, [finding("P0", "ACCEPT_BOOLEAN", "input.accept", "accept must be a boolean")]);
439
+ const result = acceptTask(tasks, taskId, input.accept, text(input.actorRole));
440
+ if (!result.ok) return blockedResponse(requestId, request, [finding("P0", "ACCEPT_FAILED", input.taskId, result.error)]);
441
+ return okResponse(requestId, { task: result.task, tasks, trafficLight: taskTrafficLight(result.task), stateNote: STATE_NOTE, nextStep: { operation: "swarm-status", instruction: "Review the complete task board." } });
442
+ }
443
+ function runObservation(operation, requestId, input, request) {
444
+ if (operation === "swarm-status") {
445
+ const tasks = Array.isArray(input.tasks) ? input.tasks : [], agents = Array.isArray(input.agents) ? input.agents : [];
446
+ return okResponse(requestId, { tasks: tasks.map((task) => ({ ...task, trafficLight: taskTrafficLight(task) })), agents: agents.map((agent) => ({ ...agent })),
447
+ summary: { tasks: tasks.length,
448
+ green: tasks.filter((t) => taskTrafficLight(t) === "green").length,
449
+ yellow: tasks.filter((t) => taskTrafficLight(t) === "yellow").length,
450
+ red: tasks.filter((t) => taskTrafficLight(t) === "red").length,
451
+ workersDead: agents.filter((a) => a.role === "worker" && a.status === "dead").length },
452
+ stateNote: "Tasks must be passed as-is from the previous response; state flows through mutations.",
453
+ nextStep: { operation: "ops", instruction: "Ops monitors heartbeats; security-guard scans inputs." } });
454
+ }
455
+ if (operation === "traffic-light") return okResponse(requestId, { trafficLight: taskTrafficLight(input.task ?? {}),
456
+ rules: {
457
+ green: "status is reported or accepted and every TestEvidence item is valid with exitCode 0",
458
+ yellow: "backlog, assigned, claimed, running, or reported without passing TestEvidence",
459
+ red: "status is \"failed\", \"blocked\", or \"cancelled\"" } });
460
+ if (operation === "security-check") {
461
+ const result = securityCheck(input.content, { agentId: input.agentId });
462
+ return okResponse(requestId, { ...result,
463
+ nextStep: result.allowed
464
+ ? { operation: "claim", instruction: "Input is safe; proceed with the task." }
465
+ : { operation: "security-alert", instruction: "Input blocked; review security-audit.json." } });
466
+ }
467
+ if (operation === "validate-json") {
468
+ const findings = validateProjectJson(input.project);
469
+ if (findings.length) return blockedResponse(requestId, request, findings);
470
+ return okResponse(requestId, { valid: true, taskCount: input.project.tasks.length,
471
+ nextStep: { operation: "org-chart", instruction: "Project valid; build the org-chart and dispatch." } });
472
+ }
473
+ if (operation === "heartbeat") {
474
+ const tasks = Array.isArray(input.tasks) ? input.tasks : [], workerId = text(input.workerId), now = new Date().toISOString();
475
+ const assigned = tasks.filter((t) => t.owner === workerId);
476
+ return okResponse(requestId, { active: true, lastSeenAt: now, workerId, assignedTaskIds: assigned.map((t) => t.taskId), stateNote: "Tasks must be passed as-is from the previous response; state flows through mutations." });
477
+ }
478
+ const tasks = Array.isArray(input.tasks) ? input.tasks : [], taskId = text(input.taskId), reason = text(input.reason || "timeout");
479
+ const task = tasks.find((candidate) => candidate.taskId === taskId);
480
+ if (!task) return blockedResponse(requestId, request, [finding("P0", "RECLAIM_FAILED", taskId, `task ${taskId} not found`, { example: { taskId: "task-0001" } })]);
481
+ if (task.status === "backlog") return blockedResponse(requestId, request, [finding("P1", "RECLAIM_NOOP", taskId, `task ${taskId} is already backlog`, { example: { taskId: "task-0001" } })]);
482
+ task.status = "backlog"; task.owner = null;
483
+ return okResponse(requestId, { reclaimed: true, taskId, reason, task, tasks, stateNote: STATE_NOTE });
484
+ }
485
+ export async function run(request) {
486
+ const findings = validateRequest(request);
487
+ if (findings.length) return { ...blockedResponse(request?.requestId ?? "unknown", request, findings), errorSchema: ERROR_SCHEMA };
488
+ const { requestId, operation } = request, input = request.input ?? {};
489
+ if (["capabilities", "help", "intake"].includes(operation)) return runMeta(operation, requestId);
490
+ if (["org-chart", "blueprint-bridge"].includes(operation)) return runPlanning(operation, requestId, input, request);
491
+ if (["dispatch", "claim", "report", "accept"].includes(operation)) return runTaskMutation(operation, requestId, input, request);
492
+ if (["swarm-status", "traffic-light", "security-check", "validate-json", "heartbeat", "reclaim"].includes(operation)) return runObservation(operation, requestId, input, request);
493
+ return { schemaVersion: RESPONSE_SCHEMA, requestId, status: "failed", errorSchema: ERROR_SCHEMA, error: { code: "UNSUPPORTED_OPERATION", message: `Unsupported operation: ${operation}` } };
494
+ }
495
+ export {
496
+ COMPILER_VERSION, ORG_SCHEMA, TASK_SCHEMA, TEST_EVIDENCE_SCHEMA, PURE_OPERATIONS, OPERATION_CATALOG,
497
+ INTAKE_QUESTIONS, ORG_PERMISSIONS, buildOrgChart, validateOrgChart, securityCheck,
498
+ analyzeTaskGraph, buildTasks, dispatchTask, claimTask, reportTask, acceptTask, taskTrafficLight,
499
+ validateTestEvidence, normalizeTestEvidence, hasPassingTestEvidence, buildBlueprintBridge,
500
+ buildAgents, recordHeartbeat, scanHeartbeats, reclaimTasks, replaceWorker,
501
+ okResponse, blockedResponse, finding,
502
+ };