@consensus-tools/universal 0.9.0

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.
Files changed (69) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +451 -0
  3. package/dist/__tests__/defaults.test.d.ts +2 -0
  4. package/dist/__tests__/defaults.test.d.ts.map +1 -0
  5. package/dist/__tests__/defaults.test.js +55 -0
  6. package/dist/__tests__/defaults.test.js.map +1 -0
  7. package/dist/__tests__/fail-policy.test.d.ts +2 -0
  8. package/dist/__tests__/fail-policy.test.d.ts.map +1 -0
  9. package/dist/__tests__/fail-policy.test.js +80 -0
  10. package/dist/__tests__/fail-policy.test.js.map +1 -0
  11. package/dist/__tests__/frameworks.test.d.ts +2 -0
  12. package/dist/__tests__/frameworks.test.d.ts.map +1 -0
  13. package/dist/__tests__/frameworks.test.js +86 -0
  14. package/dist/__tests__/frameworks.test.js.map +1 -0
  15. package/dist/__tests__/logger.test.d.ts +2 -0
  16. package/dist/__tests__/logger.test.d.ts.map +1 -0
  17. package/dist/__tests__/logger.test.js +77 -0
  18. package/dist/__tests__/logger.test.js.map +1 -0
  19. package/dist/__tests__/resolve.test.d.ts +2 -0
  20. package/dist/__tests__/resolve.test.d.ts.map +1 -0
  21. package/dist/__tests__/resolve.test.js +71 -0
  22. package/dist/__tests__/resolve.test.js.map +1 -0
  23. package/dist/__tests__/wrap.test.d.ts +2 -0
  24. package/dist/__tests__/wrap.test.d.ts.map +1 -0
  25. package/dist/__tests__/wrap.test.js +90 -0
  26. package/dist/__tests__/wrap.test.js.map +1 -0
  27. package/dist/defaults.d.ts +20 -0
  28. package/dist/defaults.d.ts.map +1 -0
  29. package/dist/defaults.js +48 -0
  30. package/dist/defaults.js.map +1 -0
  31. package/dist/errors.d.ts +23 -0
  32. package/dist/errors.d.ts.map +1 -0
  33. package/dist/errors.js +31 -0
  34. package/dist/errors.js.map +1 -0
  35. package/dist/index.d.ts +38 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +239 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/logger.d.ts +12 -0
  40. package/dist/logger.d.ts.map +1 -0
  41. package/dist/logger.js +55 -0
  42. package/dist/logger.js.map +1 -0
  43. package/dist/resolve.d.ts +9 -0
  44. package/dist/resolve.d.ts.map +1 -0
  45. package/dist/resolve.js +25 -0
  46. package/dist/resolve.js.map +1 -0
  47. package/dist/types.d.ts +35 -0
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +2 -0
  50. package/dist/types.js.map +1 -0
  51. package/package.json +82 -0
  52. package/src/__tests__/defaults.test.ts +71 -0
  53. package/src/__tests__/fail-policy.test.ts +107 -0
  54. package/src/__tests__/frameworks.test.ts +106 -0
  55. package/src/__tests__/logger.test.ts +93 -0
  56. package/src/__tests__/resolve.test.ts +80 -0
  57. package/src/__tests__/wrap.test.ts +110 -0
  58. package/src/consensus-llm.test.ts +260 -0
  59. package/src/defaults.ts +124 -0
  60. package/src/errors.ts +35 -0
  61. package/src/index.ts +386 -0
  62. package/src/logger.ts +65 -0
  63. package/src/persona-reviewer-factory.ts +387 -0
  64. package/src/reputation-manager.test.ts +131 -0
  65. package/src/reputation-manager.ts +168 -0
  66. package/src/resolve.ts +30 -0
  67. package/src/risk-tiers.test.ts +36 -0
  68. package/src/risk-tiers.ts +49 -0
  69. package/src/types.ts +127 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 consensus-tools contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,451 @@
1
+ # @consensus-tools/universal
2
+
3
+ **Single-model AI pipelines are a reliability failure.** One model, one prompt, one answer — no accountability. When an autonomous agent decides to send an email, merge code, or escalate permissions, nothing checks whether that's a good idea.
4
+
5
+ `@consensus-tools/universal` adds a governance layer in one line. Three rule-based reviewers (security, compliance, user-impact) screen every tool call using pattern matching — no LLM calls, no network requests, sub-millisecond overhead. Block, allow, or escalate based on a configurable policy. Adapters for LangChain, Vercel AI SDK, and MCP are loaded on demand.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @consensus-tools/universal
11
+ ```
12
+
13
+ Optional peer dependencies (install only what you need):
14
+
15
+ ```bash
16
+ pnpm add @consensus-tools/langchain # LangChain adapter
17
+ pnpm add @consensus-tools/ai-sdk # Vercel AI SDK adapter
18
+ pnpm add @consensus-tools/mcp # MCP adapter
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Quick Start
24
+
25
+ ### wrap — any tool executor
26
+
27
+ ```typescript
28
+ import { consensus } from "@consensus-tools/universal";
29
+
30
+ // Your existing tool executor
31
+ async function myExecutor(toolName: string, args: Record<string, unknown>) {
32
+ // call the actual tool
33
+ }
34
+
35
+ // Wrap it — all calls now go through deliberation
36
+ const safe = consensus.wrap(myExecutor);
37
+
38
+ const result = await safe("send_email", {
39
+ to: "user@example.com",
40
+ body: "Your invoice is attached.",
41
+ });
42
+ ```
43
+
44
+ Objects with `.execute`, `.invoke`, or `.call` methods are also accepted:
45
+
46
+ ```typescript
47
+ const safe = consensus.wrap(myToolRunner); // ToolExecutor function
48
+ const safe = consensus.wrap({ execute: fn }); // .execute method
49
+ const safe = consensus.wrap({ invoke: fn }); // .invoke method
50
+ const safe = consensus.wrap({ call: fn }); // .call method
51
+ ```
52
+
53
+ ---
54
+
55
+ ### langchain — LangChain chain adapter
56
+
57
+ ```typescript
58
+ import { consensus } from "@consensus-tools/universal";
59
+ import { ChatOpenAI } from "@langchain/openai";
60
+ import { createOpenAIFunctionsAgent } from "langchain/agents";
61
+
62
+ const model = new ChatOpenAI({ model: "gpt-4o" });
63
+ const chain = createOpenAIFunctionsAgent({ llm: model, tools, prompt });
64
+
65
+ // Wrap the chain — consensus reviews every tool call before execution
66
+ const safeChain = await consensus.langchain(chain, {
67
+ policy: "supermajority",
68
+ failPolicy: "closed",
69
+ });
70
+ ```
71
+
72
+ Requires `@consensus-tools/langchain` as a peer dependency.
73
+
74
+ ---
75
+
76
+ ### aiSdk — Vercel AI SDK adapter
77
+
78
+ ```typescript
79
+ import { consensus } from "@consensus-tools/universal";
80
+ import { generateText } from "ai";
81
+ import { openai } from "@ai-sdk/openai";
82
+
83
+ async function generate(prompt: string) {
84
+ return generateText({ model: openai("gpt-4o"), prompt });
85
+ }
86
+
87
+ // Wrap the generate function
88
+ const safeGenerate = await consensus.aiSdk(generate, {
89
+ policy: "majority",
90
+ guards: ["agent_action", "publish"],
91
+ });
92
+
93
+ const result = await safeGenerate("Summarize last quarter's results.");
94
+ ```
95
+
96
+ Requires `@consensus-tools/ai-sdk` as a peer dependency.
97
+
98
+ ---
99
+
100
+ ### mcp — MCP server adapter
101
+
102
+ ```typescript
103
+ import { consensus } from "@consensus-tools/universal";
104
+
105
+ // Returns a guarded MCP server instance
106
+ const server = await consensus.mcp({
107
+ policy: "unanimous",
108
+ failPolicy: "closed",
109
+ logger: (event) => console.log("[mcp]", event),
110
+ });
111
+ ```
112
+
113
+ Requires `@consensus-tools/mcp` as a peer dependency.
114
+
115
+ ---
116
+
117
+ ## Architecture
118
+
119
+ ```
120
+ ┌─────────────────────────────────────────────────────────────────────┐
121
+ │ @consensus-tools/universal │
122
+ │ │
123
+ │ consensus.wrap() consensus.langchain() consensus.aiSdk() │
124
+ │ consensus.mcp() │
125
+ └───────────────────────────┬──────────────────────────────────────────┘
126
+ │ resolves Wrappable → ToolExecutor
127
+
128
+ ┌─────────────────────────────────────────────────────────────────────┐
129
+ │ @consensus-tools/wrapper │
130
+ │ consensus<T>({ fn, reviewers, strategy, hooks }) │
131
+ │ aggregateScores() → DecisionResult<T> │
132
+ │ action: "allow" | "block" | "retry" | "escalate" │
133
+ └──────────────────┬──────────────────────────────────────────────────┘
134
+ │ reviewer functions
135
+ ┌──────────┼───────────────┐
136
+ ▼ ▼ ▼
137
+ [security] [compliance] [user-impact]
138
+ GuardTemplate GuardTemplate GuardTemplate
139
+
140
+ └── built via @consensus-tools/guards
141
+ createGuardTemplate() → .asReviewer()
142
+
143
+ ┌─────────────────────────────────────────────────────────────────────┐
144
+ │ Configurable Guard Domains │
145
+ │ send_email code_merge publish support_reply │
146
+ │ agent_action deployment permission_escalation │
147
+ │ @consensus-tools/guards (Tier 1) │
148
+ └─────────────────────────────────────────────────────────────────────┘
149
+
150
+ Tier layout (consensus-tools layered architecture):
151
+ Tier 0 schemas, secrets
152
+ Tier 1 guards, telemetry, evals, integrations, notifications
153
+ Tier 2 core (job engine, ledger), policies (9 algorithms)
154
+ Tier 3 workflows, wrapper
155
+ Tier 4 universal (this package), sdk-node, mcp, openclaw, cli
156
+ ```
157
+
158
+ ---
159
+
160
+ ## API Reference
161
+
162
+ ### `consensus.wrap(wrappable, config?)`
163
+
164
+ Synchronously wraps a tool executor with consensus governance. Returns a `ToolExecutor`.
165
+
166
+ ```typescript
167
+ function wrap(wrappable: Wrappable, config?: Partial<UniversalConfig>): ToolExecutor
168
+ ```
169
+
170
+ | Parameter | Type | Description |
171
+ |---|---|---|
172
+ | `wrappable` | `Wrappable` | Function, or object with `.execute` / `.invoke` / `.call` |
173
+ | `config` | `Partial<UniversalConfig>` | Optional configuration (see Config Reference below) |
174
+
175
+ **Returns:** `ToolExecutor` — `(toolName: string, args: Record<string, unknown>) => Promise<unknown>`
176
+
177
+ ---
178
+
179
+ ### `consensus.langchain(chain, config?)`
180
+
181
+ Async adapter for LangChain chains. Dynamically imports `@consensus-tools/langchain`.
182
+
183
+ ```typescript
184
+ async function langchain(chain: unknown, config?: Partial<UniversalConfig>): Promise<unknown>
185
+ ```
186
+
187
+ Throws `MissingDependencyError` if `@consensus-tools/langchain` is not installed.
188
+
189
+ ---
190
+
191
+ ### `consensus.aiSdk(fn, config?)`
192
+
193
+ Async adapter for Vercel AI SDK generate functions. Dynamically imports `@consensus-tools/ai-sdk`.
194
+
195
+ ```typescript
196
+ async function aiSdk(fn: unknown, config?: Partial<UniversalConfig>): Promise<unknown>
197
+ ```
198
+
199
+ Throws `MissingDependencyError` if `@consensus-tools/ai-sdk` is not installed.
200
+
201
+ ---
202
+
203
+ ### `consensus.mcp(config?)`
204
+
205
+ Async adapter that creates a guarded MCP server. Dynamically imports `@consensus-tools/mcp`.
206
+
207
+ ```typescript
208
+ async function mcp(config?: Partial<UniversalConfig>): Promise<unknown>
209
+ ```
210
+
211
+ Throws `MissingDependencyError` if `@consensus-tools/mcp` is not installed.
212
+
213
+ ---
214
+
215
+ ## Configuration Reference
216
+
217
+ All options are optional. Defaults are shown.
218
+
219
+ ```typescript
220
+ interface UniversalConfig {
221
+ policy?: string; // "majority"
222
+ guards?: string[]; // ["agent_action"]
223
+ failPolicy?: "closed" | "open"; // "closed"
224
+ storage?: "memory" | IStorage; // "memory"
225
+ logger?: boolean | ((event: LogEvent) => void); // true
226
+ onDecision?: (decision: DecisionResult<unknown>) => void;
227
+ onError?: (err: Error, action: unknown) => void;
228
+ }
229
+ ```
230
+
231
+ ### `policy`
232
+
233
+ Maps to an aggregation strategy for the three built-in reviewers.
234
+
235
+ | Value | Strategy |
236
+ |---|---|
237
+ | `"majority"` (default) | More than half of reviewers approve |
238
+ | `"supermajority"` | Weighted average score >= 0.67 |
239
+ | `"unanimous"` | Every reviewer must approve |
240
+ | `"threshold:X"` | Weighted average score >= X (0–1) |
241
+
242
+ ### `guards`
243
+
244
+ Guard domain names to use as reviewers. Defaults to `["agent_action"]`. The seven built-in domains are documented in the Guard Domains section below.
245
+
246
+ ### `failPolicy`
247
+
248
+ | Value | Behavior on deliberation error or block |
249
+ |---|---|
250
+ | `"closed"` (default) | Throw `ConsensusBlockedError` — the tool call does not execute |
251
+ | `"open"` | Allow the tool call to proceed despite the deliberation result |
252
+
253
+ **`failPolicy: "open"` effectively disables governance.** It exists for development and testing only. In production, use `"closed"` (the default) and handle `ConsensusBlockedError` in your error path.
254
+
255
+ If you want to observe governance decisions without blocking in production, use `onDecision` instead:
256
+
257
+ ```typescript
258
+ consensus.wrap(executor, {
259
+ failPolicy: "closed",
260
+ onDecision: (result) => {
261
+ // Shadow mode: log every decision, including blocks, for analysis
262
+ metrics.track("consensus.decision", { action: result.action, score: result.aggregateScore });
263
+ },
264
+ });
265
+ ```
266
+
267
+ **Production warning:** `failPolicy: "open"` and `storage: "memory"` both emit `console.warn` when `NODE_ENV=production`.
268
+
269
+ ### `storage`
270
+
271
+ | Value | Description |
272
+ |---|---|
273
+ | `"memory"` (default) | In-process storage — decisions are not persisted across restarts |
274
+ | `IStorage` | Any storage backend implementing the `IStorage` interface (e.g., `@consensus-tools/storage`) |
275
+
276
+ ### `logger`
277
+
278
+ | Value | Description |
279
+ |---|---|
280
+ | `true` (default) | Emit structured log events via `console.debug` |
281
+ | `false` | Disable all logging |
282
+ | `(event: LogEvent) => void` | Custom log handler |
283
+
284
+ ```typescript
285
+ // Custom logger example
286
+ consensus.wrap(executor, {
287
+ logger: (event) => myObservability.track(event.event, event.data),
288
+ });
289
+ ```
290
+
291
+ ### `onDecision`
292
+
293
+ Called after every consensus deliberation, including allowed actions.
294
+
295
+ ```typescript
296
+ consensus.wrap(executor, {
297
+ onDecision: (result) => {
298
+ auditLog.write({
299
+ action: result.action,
300
+ score: result.aggregateScore,
301
+ rationale: result.scores.map((s) => s.rationale),
302
+ });
303
+ },
304
+ });
305
+ ```
306
+
307
+ ### `onError`
308
+
309
+ Called when an unexpected error occurs during deliberation (not a block — a runtime failure).
310
+
311
+ ```typescript
312
+ consensus.wrap(executor, {
313
+ onError: (err, context) => {
314
+ Sentry.captureException(err, { extra: context });
315
+ },
316
+ });
317
+ ```
318
+
319
+ ---
320
+
321
+ ## Guard Domains
322
+
323
+ The seven built-in guard domains correspond to the guard packages in this monorepo.
324
+
325
+ | Domain | Description |
326
+ |---|---|
327
+ | `agent_action` | Pre-execution governance for autonomous agent actions (default) |
328
+ | `send_email` | Email automation governance — flags mass sends, PII in bodies |
329
+ | `code_merge` | PR / branch merge governance — flags sensitive file changes |
330
+ | `publish` | Content publishing governance — flags unreviewed or regulated content |
331
+ | `support_reply` | Customer support reply governance — flags tone, policy, escalation |
332
+ | `deployment` | Release deployment governance — flags prod, rollback risk |
333
+ | `permission_escalation` | IAM / privilege escalation governance — flags scope creep |
334
+
335
+ ---
336
+
337
+ ## Error Reference
338
+
339
+ | Error class | When thrown |
340
+ |---|---|
341
+ | `ConsensusBlockedError` | Deliberation blocked the action and `failPolicy` is `"closed"` |
342
+ | `MissingDependencyError` | Optional peer dependency not installed (langchain / ai-sdk / mcp) |
343
+ | `ConfigError` | Invalid `policy` string passed to `policyToStrategy` |
344
+
345
+ ```typescript
346
+ import { ConsensusBlockedError, MissingDependencyError } from "@consensus-tools/universal";
347
+
348
+ try {
349
+ const result = await safe("permission_escalation", { scope: "admin" });
350
+ } catch (err) {
351
+ if (err instanceof ConsensusBlockedError) {
352
+ // Deliberation blocked this call — log and surface to operator
353
+ console.error("Blocked:", err.message);
354
+ }
355
+ }
356
+ ```
357
+
358
+ ---
359
+
360
+ ## OWASP Agentic Top 10 Mapping
361
+
362
+ The table below maps each guard domain to the OWASP Agentic AI Security Initiative Top 10 categories it addresses.
363
+
364
+ | # | OWASP Category | Addressed by guard domain(s) |
365
+ |---|---|---|
366
+ | 1 | **Excessive Agency** | `agent_action`, `permission_escalation` |
367
+ | 2 | **Tool Misuse** | `agent_action`, `code_merge`, `deployment` |
368
+ | 3 | **Prompt Injection** | `agent_action`, `support_reply` |
369
+ | 4 | **Insecure Outputs** | `publish`, `support_reply`, `send_email` |
370
+ | 5 | **Unauthorized Actions** | `permission_escalation`, `agent_action`, `deployment` |
371
+ | 6 | **Data Leakage** | `send_email`, `publish`, `support_reply` |
372
+ | 7 | **Supply Chain Attacks** | `code_merge`, `deployment` |
373
+ | 8 | **Denial of Wallet** | `send_email`, `agent_action` |
374
+ | 9 | **Unintended Autonomy** | `agent_action`, `permission_escalation` |
375
+ | 10 | **Trust Boundary Violations** | `permission_escalation`, `code_merge`, `deployment` |
376
+
377
+ ### What happens at runtime
378
+
379
+ When you call a wrapped tool executor, here's the exact sequence:
380
+
381
+ ```
382
+ safe("send_email", { to: "user@example.com", body: "Your invoice" })
383
+
384
+ ├─ 1. Serialize args to text
385
+
386
+ ├─ 2. Run 3 reviewers IN PARALLEL (rule-based, no LLM calls):
387
+ │ ├─ security: regex scan for destructive ops, secrets, injection
388
+ │ ├─ compliance: regex scan for SSN patterns, PII, email addresses
389
+ │ └─ user-impact: regex scan for mass ops, irreversible actions
390
+
391
+ ├─ 3. Each reviewer returns: { vote: YES|NO|REWRITE, risk: 0-1, reason }
392
+
393
+ ├─ 4. Aggregate scores via policy (majority/supermajority/unanimous/threshold)
394
+ │ └─ Any reviewer can hard-block regardless of policy
395
+
396
+ ├─ 5. Decision: allow | block | retry | escalate
397
+
398
+ ├─ 6. Write audit artifact (to memory or configured storage)
399
+
400
+ └─ 7. Return result or throw ConsensusBlockedError
401
+ ```
402
+
403
+ **Latency:** Sub-millisecond. Reviewers are synchronous regex evaluators, not LLM calls. The only async operation is the audit artifact write. Target: <10ms total overhead for the default 3-reviewer configuration.
404
+
405
+ **DecisionResult object:**
406
+
407
+ ```typescript
408
+ {
409
+ action: "allow", // "allow" | "block" | "retry" | "escalate"
410
+ output: { ... }, // return value from the tool executor
411
+ scores: [
412
+ { score: 0.9, rationale: "No security concerns", block: false },
413
+ { score: 0.5, rationale: "Email PII detected", block: false },
414
+ { score: 0.9, rationale: "Low user impact", block: false },
415
+ ],
416
+ aggregateScore: 0.77, // weighted average across reviewers
417
+ attempt: 1, // retry count
418
+ }
419
+ ```
420
+
421
+ **Cost:** Zero. No API calls, no tokens consumed. The governance layer is pure computation.
422
+
423
+ ---
424
+
425
+ ## Exports
426
+
427
+ | Export | Kind | Description |
428
+ |---|---|---|
429
+ | `consensus` | Object | Main facade with `.wrap()`, `.langchain()`, `.aiSdk()`, `.mcp()` |
430
+ | `resolveWrappable` | Function | Resolves a `Wrappable` to a plain `ToolExecutor` |
431
+ | `policyToStrategy` | Function | Maps a policy name string to a `StrategyConfig` |
432
+ | `createLogger` | Function | Creates structured lifecycle log hooks |
433
+ | `DEFAULTS` | Const | Default config values |
434
+ | `DEFAULT_GUARD` | Const | `"agent_action"` |
435
+ | `DEFAULT_POLICY` | Const | `"majority"` |
436
+ | `DEFAULT_PERSONA_TRIO` | Const | `["security", "compliance", "user-impact"]` |
437
+ | `DEFAULT_PERSONA_COUNT` | Const | `3` |
438
+ | `ConsensusBlockedError` | Class | Thrown when deliberation blocks and `failPolicy` is `"closed"` |
439
+ | `MissingDependencyError` | Class | Thrown when an optional peer dep is not installed |
440
+ | `ConfigError` | Class | Thrown for invalid configuration (e.g., unknown policy name) |
441
+ | `Wrappable` | Type | `ToolExecutor \| { execute } \| { invoke } \| { call }` |
442
+ | `ToolExecutor` | Type | `(toolName: string, args: Record<string, unknown>) => Promise<unknown>` |
443
+ | `UniversalConfig` | Type | Full configuration interface |
444
+ | `FailPolicy` | Type | `"closed" \| "open"` |
445
+ | `LogEvent` | Type | `{ event: string; data: Record<string, unknown>; timestamp: number }` |
446
+
447
+ ---
448
+
449
+ ## Links
450
+
451
+ [consensus-tools on GitHub](https://github.com/consensus-tools/consensus-tools)
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=defaults.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/defaults.test.ts"],"names":[],"mappings":""}