@manya-os/council 1.0.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.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +244 -0
- package/dist/cjs/index.js +4 -0
- package/dist/cjs/index.js.map +6 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/index.mjs +4 -0
- package/dist/esm/index.mjs.map +6 -0
- package/dist/esm/package.json +1 -0
- package/dist/types/analysis/analysis.d.ts +53 -0
- package/dist/types/analysis/analysis.d.ts.map +1 -0
- package/dist/types/analysis/index.d.ts +8 -0
- package/dist/types/analysis/index.d.ts.map +1 -0
- package/dist/types/conflict/conflict.d.ts +63 -0
- package/dist/types/conflict/conflict.d.ts.map +1 -0
- package/dist/types/conflict/index.d.ts +8 -0
- package/dist/types/conflict/index.d.ts.map +1 -0
- package/dist/types/consensus/consensus.d.ts +72 -0
- package/dist/types/consensus/consensus.d.ts.map +1 -0
- package/dist/types/consensus/index.d.ts +9 -0
- package/dist/types/consensus/index.d.ts.map +1 -0
- package/dist/types/debate/debate.d.ts +75 -0
- package/dist/types/debate/debate.d.ts.map +1 -0
- package/dist/types/debate/index.d.ts +8 -0
- package/dist/types/debate/index.d.ts.map +1 -0
- package/dist/types/errors.d.ts +44 -0
- package/dist/types/errors.d.ts.map +1 -0
- package/dist/types/index.d.ts +42 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/logging.d.ts +40 -0
- package/dist/types/logging.d.ts.map +1 -0
- package/dist/types/minority/index.d.ts +8 -0
- package/dist/types/minority/index.d.ts.map +1 -0
- package/dist/types/minority/minority.d.ts +54 -0
- package/dist/types/minority/minority.d.ts.map +1 -0
- package/dist/types/reports/index.d.ts +9 -0
- package/dist/types/reports/index.d.ts.map +1 -0
- package/dist/types/reports/reports.d.ts +52 -0
- package/dist/types/reports/reports.d.ts.map +1 -0
- package/dist/types/router/index.d.ts +9 -0
- package/dist/types/router/index.d.ts.map +1 -0
- package/dist/types/router/router.d.ts +76 -0
- package/dist/types/router/router.d.ts.map +1 -0
- package/dist/types/scoring/index.d.ts +9 -0
- package/dist/types/scoring/index.d.ts.map +1 -0
- package/dist/types/scoring/scoring.d.ts +65 -0
- package/dist/types/scoring/scoring.d.ts.map +1 -0
- package/dist/types/synthesizer/index.d.ts +9 -0
- package/dist/types/synthesizer/index.d.ts.map +1 -0
- package/dist/types/synthesizer/synthesizer.d.ts +54 -0
- package/dist/types/synthesizer/synthesizer.d.ts.map +1 -0
- package/dist/types/types.d.ts +246 -0
- package/dist/types/types.d.ts.map +1 -0
- package/dist/types/util.d.ts +45 -0
- package/dist/types/util.d.ts.map +1 -0
- package/package.json +48 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@manya/council` are documented here.
|
|
4
|
+
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Adheres to [SemVer](https://semver.org/).
|
|
5
|
+
|
|
6
|
+
## [1.0.0] — 2024-01-15
|
|
7
|
+
### Added
|
|
8
|
+
- Initial release.
|
|
9
|
+
- Specialist routing: `Specialist` (id, name, expertise, weight), `SpecialistRegistry`, free functions `route(problem, specialists)` (ranked, positive-overlap only) and `routeAll(problem, specialists)` (all specialists with scores), `matchScore` (Jaccard token overlap), `validateSpecialist`.
|
|
10
|
+
- Independent analysis collection: `Analysis` (id, specialistId, problemId, content, confidence, reasoning, caveats?), `AnalysisCollector` with `submit`, `getAll(problemId)`, `getBySpecialist(specialistId)`, `get`, `list`, `size`; `validateAnalysis`.
|
|
11
|
+
- Weighted confidence scoring: `scoreAnalysis(analysis, specialistWeight)`, `aggregateScores(analyses, weights)` (combined weighted mean + variance + stddev), `detectOutliers(analyses, threshold)` (deviation from median); `DEFAULT_OUTLIER_THRESHOLD = 0.25`.
|
|
12
|
+
- Conflict detection: `ConflictDetector.detect(analyses)` returns `Conflict[]` of three types — `opposing_conclusion` (both analyses > 0.6 confidence with opposite polarity), `factual_contradiction` (≥ 0.3 content Jaccard overlap with opposite polarity), `divergent_reasoning` (same polarity, < 0.2 reasoning Jaccard overlap, > 0.1 content overlap). Severity (`low`/`medium`/`high`) based on confidence gap and analyst count. `severityFor`, `CONFLICT_TYPES`, `CONFLICT_SEVERITIES`, and all threshold constants exported.
|
|
13
|
+
- Structured debate: `DebateFacilitator` with `open(problemId, conflictIds)`, `submitRound(debateId, round)` (validates rounds, enforces `rebuttalTo` existence, rejects duplicates and concluded debates, enforces max rounds), `conclude(debateId)`. `validateRound`, `DEFAULT_MAX_DEBATE_ROUNDS = 10`.
|
|
14
|
+
- Minority opinion tracking: `MinorityOpinion` (id, problemId, analystId, position, reasoning, dissentReason), `MinorityOpinionTracker` with `record`, `getForProblem`, `getByAnalyst`, `get`, `list`, `size`; `validateMinorityOpinion`.
|
|
15
|
+
- Consensus building: `ConsensusBuilder(threshold)` with `build(problemId, analyses, conflicts, options)` returning `Consensus` (problemId, decision, confidence, supportingAnalystIds, dissentingAnalystIds, conflictsResolved, openIssues) or `null`. Weighted voting with `specialistWeight × confidence` per analysis. Optional `weights` map and `minorityAnalystIds` (added to dissenters). `DEFAULT_CONSENSUS_THRESHOLD = 0.6`.
|
|
16
|
+
- Review reports: `buildReport(input)` aggregates analyses, conflicts, debates, minority opinions, consensus, and recommendations into a `ReviewReport` (with computed `summary`). `serializeReport(report)` to pretty JSON. `summarizeReport(report)` to a single paragraph.
|
|
17
|
+
- Decision synthesis: `synthesize(problemId, consensus, analyses, conflicts, options)` returns a `Decision` (id, problemId, decision, rationale, confidence, consensusLevel, participants, generatedAt). `consensusLevel` is one of `unanimous` / `strong` / `majority` / `split` / `none`. `classifyConsensus(consensus, threshold)`, `DEFAULT_SYNTHESIS_THRESHOLD = 0.6`, `STRONG_CONSENSUS_RATIO = 0.8`.
|
|
18
|
+
- Shared text utilities (`src/util.ts`): `tokenize`, `tokenSet`, `jaccard`, `polarity`, `stem`, with `STOP_WORDS`, `POSITIVE_MARKERS`, `NEGATIVE_MARKERS` exported for tunability.
|
|
19
|
+
- Typed error hierarchy: `CouncilError` + 7 subclasses (`RoutingError`, `AnalysisError`, `ScoringError`, `ConflictError`, `DebateError`, `ConsensusError`, `SynthesisError`), each carrying a stable `code` string.
|
|
20
|
+
- Structured logging: `Logger`, `LogLevel`, `ConsoleLogger` (with secret scrubbing), `SilentLogger`, `scrubMetadata`, `shouldScrubField`, `SCRUBBED_FIELD_NAMES`.
|
|
21
|
+
- Comprehensive unit test suite: 121 tests covering all modules, the error hierarchy, logging, and a full end-to-end pipeline (route → analyse → detect conflicts → debate → record minority opinion → build consensus → synthesize decision → build report).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
Copyright 2024 Manya Hael Foundation. All rights reserved.
|
|
7
|
+
|
|
8
|
+
Conceived, directed, and owned by Uviwe Menyiwe (Azura Daemon),
|
|
9
|
+
founder of the Manya Hael Foundation.
|
|
10
|
+
|
|
11
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
12
|
+
you may not use this file except in compliance with the License.
|
|
13
|
+
You may obtain a copy of the License at
|
|
14
|
+
|
|
15
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
16
|
+
|
|
17
|
+
Unless required by applicable law or agreed to in writing, software
|
|
18
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
19
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
20
|
+
See the License for the specific language governing permissions and
|
|
21
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
# @manya/council
|
|
2
|
+
|
|
3
|
+
> Multi-agent consensus engine for the MANYA Intelligence OS — specialist routing, independent analyses, weighted confidence scoring, conflict detection, structured debate, minority opinions, consensus building, review reports, and final decision synthesis.
|
|
4
|
+
|
|
5
|
+
`@manya/council` is the deliberation layer of the **MANYA Intelligence OS** — a sovereign, modular, local-first intelligence operating system conceived, directed, and owned by **Uviwe Menyiwe (Azura Daemon)**, founder of the **Manya Hael Foundation**.
|
|
6
|
+
|
|
7
|
+
The package provides a small, dependency-free council engine that routes a problem to specialists, collects their independent analyses, scores them with weighted confidence, detects conflicts (opposing conclusions, factual contradictions, divergent reasoning), facilitates structured debate, records minority opinions, builds consensus via weighted voting, produces a review report, and synthesizes a final defensible decision. Every step is deterministic and explainable.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Vision
|
|
12
|
+
|
|
13
|
+
The Manya Hael Foundation stewards the MANYA Intelligence OS as a long-horizon, mission-driven project. `@manya/council` extends that sovereignty into the deliberation domain: **your specialists, your weights, your threshold — your decision, auditable and reproducible.**
|
|
14
|
+
|
|
15
|
+
- **Sovereign.** No network calls. Every routing decision, score, and consensus is computed locally.
|
|
16
|
+
- **Deterministic.** Identical inputs produce identical outputs. Tokenization, polarity inference, and severity classification are all rule-based.
|
|
17
|
+
- **Explainable.** Every conflict carries a description and severity; every decision carries a rationale and a `consensusLevel`.
|
|
18
|
+
- **Layered.** Route → analyse → score → detect conflicts → debate → build consensus → report → synthesise. Use any subset or wire them all together.
|
|
19
|
+
- **Dissent-aware.** Minority opinions are first-class records, preserved alongside the consensus for future reconsideration.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
| Area | What you get |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| **Specialist routing** | `Specialist` (id, name, expertise[], weight), `SpecialistRegistry`. `route(problem, specialists)` returns ranked specialists by Jaccard token-overlap. `routeAll(problem)` returns all specialists with scores. |
|
|
28
|
+
| **Analysis collection** | `Analysis` (id, specialistId, problemId, content, confidence, reasoning, caveats?). `AnalysisCollector` with `submit`, `getAll(problemId)`, `getBySpecialist(specialistId)`. |
|
|
29
|
+
| **Weighted scoring** | `scoreAnalysis(analysis, specialistWeight)` → weighted score. `aggregateScores(analyses, weights)` → weighted mean + variance + stddev. `detectOutliers(analyses, threshold)` → analyses whose confidence deviates from the median. |
|
|
30
|
+
| **Conflict detection** | `ConflictDetector.detect(analyses)` returns conflicts of 3 types: `opposing_conclusion` (both > 0.6, opposite polarity), `factual_contradiction` (≥ 0.3 content overlap + opposite polarity), `divergent_reasoning` (same polarity, < 0.2 reasoning overlap). Severity based on confidence gap and analyst count. |
|
|
31
|
+
| **Structured debate** | `DebateFacilitator.open(problemId, conflictIds)`, `submitRound(debateId, round)` (with optional `rebuttalTo`), `conclude(debateId)`. Enforces max rounds and rebuttal-target existence. |
|
|
32
|
+
| **Minority opinions** | `MinorityOpinionTracker` with `record`, `getForProblem`, `getByAnalyst`. Preserves dissent for audit. |
|
|
33
|
+
| **Consensus building** | `ConsensusBuilder.build(problemId, analyses, conflicts, options)` returns `Consensus` (decision, confidence, supporting/dissenting analyst ids, conflictsResolved, openIssues) or `null`. Threshold configurable (default 0.6). Weighted voting + confidence weighting. |
|
|
34
|
+
| **Review reports** | `buildReport(...)` aggregates analyses, conflicts, debates, minority opinions, consensus, recommendations into a `ReviewReport`. `serializeReport` to JSON, `summarizeReport` to a paragraph. |
|
|
35
|
+
| **Decision synthesis** | `synthesize(problemId, consensus, analyses, conflicts, options)` returns a `Decision` with `consensusLevel` (`unanimous` / `strong` / `majority` / `split` / `none`), explicit confidence, and rationale. |
|
|
36
|
+
| **Logging** | `Logger` interface, `ConsoleLogger` with secret-scrubbing, `SilentLogger`. |
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm install @manya/council
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Requires Node.js 18+.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
### 1. Route a problem to specialists
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { SpecialistRegistry } from '@manya/council';
|
|
56
|
+
|
|
57
|
+
const registry = new SpecialistRegistry()
|
|
58
|
+
.register({ id: 'sec', name: 'Security', expertise: ['security', 'crypto'], weight: 2 })
|
|
59
|
+
.register({ id: 'fin', name: 'Finance', expertise: ['finance', 'budget'], weight: 1 })
|
|
60
|
+
.register({ id: 'legal', name: 'Legal', expertise: ['legal', 'compliance'], weight: 1 });
|
|
61
|
+
|
|
62
|
+
const problem = {
|
|
63
|
+
id: 'p1',
|
|
64
|
+
description: 'Should we adopt the new crypto security audit proposal?',
|
|
65
|
+
domain: 'security',
|
|
66
|
+
createdAt: new Date().toISOString(),
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const ranked = registry.route(problem);
|
|
70
|
+
console.log(ranked.map((s) => s.id)); // ['sec'] — sec has the strongest overlap
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### 2. Collect analyses, detect conflicts, build consensus
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { AnalysisCollector, ConflictDetector, ConsensusBuilder } from '@manya/council';
|
|
77
|
+
|
|
78
|
+
const collector = new AnalysisCollector();
|
|
79
|
+
collector.submit({
|
|
80
|
+
id: 'a-sec', specialistId: 'sec', problemId: 'p1',
|
|
81
|
+
content: 'I recommend we adopt the proposal; the security is sound.',
|
|
82
|
+
confidence: 0.9, reasoning: 'Audit passed; risks are mitigated.',
|
|
83
|
+
});
|
|
84
|
+
collector.submit({
|
|
85
|
+
id: 'a-fin', specialistId: 'fin', problemId: 'p1',
|
|
86
|
+
content: 'I support the proposal; the budget is sufficient.',
|
|
87
|
+
confidence: 0.8, reasoning: 'Funds are allocated for this quarter.',
|
|
88
|
+
});
|
|
89
|
+
collector.submit({
|
|
90
|
+
id: 'a-legal', specialistId: 'legal', problemId: 'p1',
|
|
91
|
+
content: 'I reject the proposal; compliance is incomplete.',
|
|
92
|
+
confidence: 0.85, reasoning: 'Regulatory review is pending.',
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const analyses = collector.getAll('p1');
|
|
96
|
+
const conflicts = new ConflictDetector().detect(analyses);
|
|
97
|
+
console.log(conflicts.map((c) => c.type)); // ['opposing_conclusion', ...]
|
|
98
|
+
|
|
99
|
+
const consensus = new ConsensusBuilder(0.6).build('p1', analyses, conflicts, {
|
|
100
|
+
weights: { sec: 5, fin: 1, legal: 1 },
|
|
101
|
+
});
|
|
102
|
+
// consensus.decision → 'Adopt the proposed action for problem p1.'
|
|
103
|
+
// consensus.confidence → > 0.6
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 3. Synthesize a final decision and build a review report
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { synthesize, buildReport, serializeReport } from '@manya/council';
|
|
110
|
+
|
|
111
|
+
const decision = synthesize('p1', consensus, analyses, conflicts);
|
|
112
|
+
console.log(decision.consensusLevel); // 'strong' | 'majority' | …
|
|
113
|
+
console.log(decision.rationale); // human-readable explanation
|
|
114
|
+
|
|
115
|
+
const report = buildReport({
|
|
116
|
+
problemId: 'p1',
|
|
117
|
+
analyses,
|
|
118
|
+
conflicts,
|
|
119
|
+
consensus,
|
|
120
|
+
recommendations: ['Proceed with adoption', 'Complete compliance review post-hoc'],
|
|
121
|
+
});
|
|
122
|
+
console.log(serializeReport(report)); // pretty JSON
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 4. Run a structured debate over a conflict
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { DebateFacilitator } from '@manya/council';
|
|
129
|
+
|
|
130
|
+
const facilitator = new DebateFacilitator();
|
|
131
|
+
const debate = facilitator.open('p1', conflicts.map((c) => c.id));
|
|
132
|
+
facilitator.submitRound(debate.id, {
|
|
133
|
+
id: 'r1', analystId: 'legal',
|
|
134
|
+
claim: 'Compliance review is incomplete.',
|
|
135
|
+
evidence: 'The regulatory checklist has open items.',
|
|
136
|
+
});
|
|
137
|
+
facilitator.submitRound(debate.id, {
|
|
138
|
+
id: 'r2', analystId: 'sec',
|
|
139
|
+
claim: 'Open items are advisory, not blocking.',
|
|
140
|
+
evidence: 'No mandatory controls are missing.',
|
|
141
|
+
rebuttalTo: 'r1',
|
|
142
|
+
});
|
|
143
|
+
facilitator.conclude(debate.id);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## Configuration
|
|
149
|
+
|
|
150
|
+
### Consensus threshold
|
|
151
|
+
|
|
152
|
+
`new ConsensusBuilder(threshold)` accepts a threshold in `[0, 1]`. Default is `0.6`. The weighted support ratio of the winning polarity must be `≥ threshold` for a consensus to be returned; otherwise `build` returns `null`.
|
|
153
|
+
|
|
154
|
+
### Outlier threshold
|
|
155
|
+
|
|
156
|
+
`detectOutliers(analyses, threshold)` accepts an absolute deviation from the median. Default is `0.25` (`DEFAULT_OUTLIER_THRESHOLD`).
|
|
157
|
+
|
|
158
|
+
### Max debate rounds
|
|
159
|
+
|
|
160
|
+
`new DebateFacilitator(maxRounds)` accepts a positive integer. Default is `10` (`DEFAULT_MAX_DEBATE_ROUNDS`). `submitRound` throws `DebateError` once the limit is reached.
|
|
161
|
+
|
|
162
|
+
### Specialist weights
|
|
163
|
+
|
|
164
|
+
Specialist `weight` is a non-negative number. The scoring module uses `weight` as a multiplier on confidence: `weighted = confidence × weight`. The consensus builder uses an optional `weights` map (specialistId → weight) — when omitted, every specialist gets weight `1`.
|
|
165
|
+
|
|
166
|
+
### Polarity inference
|
|
167
|
+
|
|
168
|
+
The conflict detector and consensus builder infer each analysis's polarity (`'positive'` / `'negative'` / `'neutral'`) by counting keyword markers in the analysis's `content` after light stemming. See `POSITIVE_MARKERS` and `NEGATIVE_MARKERS` in `src/util.ts`.
|
|
169
|
+
|
|
170
|
+
### Conflict thresholds
|
|
171
|
+
|
|
172
|
+
| Constant | Default | Meaning |
|
|
173
|
+
| --- | --- | --- |
|
|
174
|
+
| `OPPOSING_CONFIDENCE_THRESHOLD` | `0.6` | Both analyses must have confidence > this for an `opposing_conclusion` conflict. |
|
|
175
|
+
| `FACTUAL_OVERLAP_THRESHOLD` | `0.3` | Content Jaccard ≥ this for a `factual_contradiction` conflict. |
|
|
176
|
+
| `DIVERGENT_REASONING_MAX_OVERLAP` | `0.2` | Reasoning Jaccard < this for a `divergent_reasoning` conflict. |
|
|
177
|
+
| `DIVERGENT_CONTENT_MIN_OVERLAP` | `0.1` | Content Jaccard > this for a `divergent_reasoning` conflict. |
|
|
178
|
+
| `SEVERITY_HIGH_GAP` | `0.5` | Confidence gap ≥ this (or 3+ analyses) → `'high'` severity. |
|
|
179
|
+
| `SEVERITY_MEDIUM_GAP` | `0.2` | Confidence gap ≥ this → `'medium'` severity; else `'low'`. |
|
|
180
|
+
|
|
181
|
+
### Consensus-level classification
|
|
182
|
+
|
|
183
|
+
`classifyConsensus(consensus, threshold)` returns:
|
|
184
|
+
|
|
185
|
+
| Level | Condition |
|
|
186
|
+
| --- | --- |
|
|
187
|
+
| `'none'` | consensus is `null`. |
|
|
188
|
+
| `'unanimous'` | no dissenting analysts. |
|
|
189
|
+
| `'strong'` | `consensus.confidence ≥ 0.8` (`STRONG_CONSENSUS_RATIO`). |
|
|
190
|
+
| `'majority'` | `consensus.confidence ≥ threshold` (default `0.6`). |
|
|
191
|
+
| `'split'` | consensus exists but confidence is below threshold. |
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## Extending
|
|
196
|
+
|
|
197
|
+
### Add a new conflict type
|
|
198
|
+
|
|
199
|
+
1. Add the new value to `ConflictType` in `src/types.ts`.
|
|
200
|
+
2. Add the new value to `CONFLICT_TYPES` in `src/conflict/conflict.ts`.
|
|
201
|
+
3. Add a detection branch in `ConflictDetector.detect`.
|
|
202
|
+
4. Add unit tests in `tests/council.spec.ts` (in the `conflict` describe block).
|
|
203
|
+
5. Update `docs/API.md` and the README conflict-thresholds table.
|
|
204
|
+
|
|
205
|
+
### Add a new consensus level
|
|
206
|
+
|
|
207
|
+
1. Add the new value to `ConsensusLevel` in `src/types.ts`.
|
|
208
|
+
2. Update `classifyConsensus` in `src/synthesizer/synthesizer.ts`.
|
|
209
|
+
3. Add unit tests in `tests/council.spec.ts` (in the `synthesizer` describe block).
|
|
210
|
+
|
|
211
|
+
### Add a polarity marker
|
|
212
|
+
|
|
213
|
+
1. Add the word to `POSITIVE_MARKERS` or `NEGATIVE_MARKERS` in `src/util.ts`.
|
|
214
|
+
2. Add a test in `tests/council.spec.ts` covering an analysis that uses the new marker.
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## Security notes
|
|
219
|
+
|
|
220
|
+
- **Local-only.** No data leaves the host process. No network calls.
|
|
221
|
+
- **No `eval`.** Text analysis is keyword matching and Jaccard similarity; no code execution.
|
|
222
|
+
- **No PII in logs.** `taxId`, `secret`, `token`, `apiKey`, `password` are scrubbed by `ConsoleLogger`.
|
|
223
|
+
- **Deterministic.** Identical inputs produce identical outputs. Polarity inference, conflict ids, and severity classification are all rule-based.
|
|
224
|
+
- **Defense in depth.** Routing, analysis validation, scoring, conflict detection, debate validation, and consensus building each validate their inputs independently.
|
|
225
|
+
|
|
226
|
+
For threat models, see [SECURITY.md](./SECURITY.md) and the root [SECURITY.md](../../SECURITY.md).
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## Documentation
|
|
231
|
+
|
|
232
|
+
- [docs/API.md](./docs/API.md) — full TypeScript API reference.
|
|
233
|
+
- [CHANGELOG.md](./CHANGELOG.md) — release history.
|
|
234
|
+
- [CONTRIBUTING.md](./CONTRIBUTING.md) — package-specific contributor notes.
|
|
235
|
+
- [SECURITY.md](./SECURITY.md) — package-specific security surface.
|
|
236
|
+
- [LICENSE](./LICENSE) — Apache-2.0.
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## License
|
|
241
|
+
|
|
242
|
+
Apache-2.0. Copyright 2024 Manya Hael Foundation. All rights reserved.
|
|
243
|
+
|
|
244
|
+
Conceived, directed, and owned by **Uviwe Menyiwe (Azura Daemon)**, founder of the Manya Hael Foundation.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{AnalysisCollector:()=>AnalysisCollector,AnalysisError:()=>AnalysisError,CONFLICT_SEVERITIES:()=>CONFLICT_SEVERITIES,CONFLICT_TYPES:()=>CONFLICT_TYPES,ConflictDetector:()=>ConflictDetector,ConflictError:()=>ConflictError,ConsensusBuilder:()=>ConsensusBuilder,ConsensusError:()=>ConsensusError,ConsoleLogger:()=>ConsoleLogger,CouncilError:()=>CouncilError,DEFAULT_CONSENSUS_THRESHOLD:()=>DEFAULT_CONSENSUS_THRESHOLD,DEFAULT_MAX_DEBATE_ROUNDS:()=>DEFAULT_MAX_DEBATE_ROUNDS,DEFAULT_OUTLIER_THRESHOLD:()=>DEFAULT_OUTLIER_THRESHOLD,DEFAULT_SYNTHESIS_THRESHOLD:()=>DEFAULT_SYNTHESIS_THRESHOLD,DIVERGENT_CONTENT_MIN_OVERLAP:()=>DIVERGENT_CONTENT_MIN_OVERLAP,DIVERGENT_REASONING_MAX_OVERLAP:()=>DIVERGENT_REASONING_MAX_OVERLAP,DebateError:()=>DebateError,DebateFacilitator:()=>DebateFacilitator,FACTUAL_OVERLAP_THRESHOLD:()=>FACTUAL_OVERLAP_THRESHOLD,MinorityOpinionTracker:()=>MinorityOpinionTracker,OPPOSING_CONFIDENCE_THRESHOLD:()=>OPPOSING_CONFIDENCE_THRESHOLD,RoutingError:()=>RoutingError,SCRUBBED_FIELD_NAMES:()=>SCRUBBED_FIELD_NAMES,SEVERITY_HIGH_GAP:()=>SEVERITY_HIGH_GAP,SEVERITY_MEDIUM_GAP:()=>SEVERITY_MEDIUM_GAP,STRONG_CONSENSUS_RATIO:()=>STRONG_CONSENSUS_RATIO,ScoringError:()=>ScoringError,SilentLogger:()=>SilentLogger,SpecialistRegistry:()=>SpecialistRegistry,SynthesisError:()=>SynthesisError,aggregateScores:()=>aggregateScores,buildReport:()=>buildReport,classifyConsensus:()=>classifyConsensus,detectOutliers:()=>detectOutliers,matchScore:()=>matchScore,route:()=>route,routeAll:()=>routeAll,scoreAnalysis:()=>scoreAnalysis,scrubMetadata:()=>scrubMetadata,serializeReport:()=>serializeReport,severityFor:()=>severityFor,shouldScrubField:()=>shouldScrubField,summarizeReport:()=>summarizeReport,synthesize:()=>synthesize,validateAnalysis:()=>validateAnalysis,validateMinorityOpinion:()=>validateMinorityOpinion,validateRound:()=>validateRound,validateSpecialist:()=>validateSpecialist});module.exports=__toCommonJS(src_exports);var CouncilError=class extends Error{code;cause;constructor(message,code,cause){super(message),this.name=new.target.name,this.code=code??"COUNCIL_ERROR",cause!==void 0&&(this.cause=cause),Object.setPrototypeOf(this,new.target.prototype)}},RoutingError=class extends CouncilError{constructor(message,cause){super(message,"ROUTING_ERROR",cause)}},AnalysisError=class extends CouncilError{constructor(message,cause){super(message,"ANALYSIS_ERROR",cause)}},ScoringError=class extends CouncilError{constructor(message,cause){super(message,"SCORING_ERROR",cause)}},ConflictError=class extends CouncilError{constructor(message,cause){super(message,"CONFLICT_ERROR",cause)}},DebateError=class extends CouncilError{constructor(message,cause){super(message,"DEBATE_ERROR",cause)}},ConsensusError=class extends CouncilError{constructor(message,cause){super(message,"CONSENSUS_ERROR",cause)}},SynthesisError=class extends CouncilError{constructor(message,cause){super(message,"SYNTHESIS_ERROR",cause)}};var LEVEL_RANK={debug:10,info:20,warn:30,error:40,silent:100},SCRUBBED_FIELD_NAMES=["taxId","secret","token","apiKey","password"];function shouldScrubField(name){let lower=name.toLowerCase();for(let needle of SCRUBBED_FIELD_NAMES){let nl=needle.toLowerCase();if(lower===nl||lower.endsWith("_"+nl))return!0}return!1}function scrubMetadata(meta){if(meta==null||typeof meta!="object")return meta;if(Buffer.isBuffer(meta))return`[buffer:${meta.length}]`;if(meta instanceof Date)return meta.toISOString();if(Array.isArray(meta))return meta.map(scrubMetadata);let out={};for(let[k,v]of Object.entries(meta))out[k]=shouldScrubField(k)?"[redacted]":scrubMetadata(v);return out}var ConsoleLogger=class{constructor(level="info"){this.level=level;this.levelRank=LEVEL_RANK[level]??LEVEL_RANK.info}level;levelRank;debug(msg,meta){this.emit("debug",msg,meta)}info(msg,meta){this.emit("info",msg,meta)}warn(msg,meta){this.emit("warn",msg,meta)}error(msg,meta){this.emit("error",msg,meta)}emit(level,msg,meta){try{if(LEVEL_RANK[level]<this.levelRank)return;let entry={level,msg,ts:new Date().toISOString(),...meta?{meta:scrubMetadata(meta)}:{}},line=JSON.stringify(entry);level==="error"||level==="warn"?process.stderr.write(line+`
|
|
2
|
+
`):process.stdout.write(line+`
|
|
3
|
+
`)}catch{}}},SilentLogger=class{debug(){}info(){}warn(){}error(){}};var STOP_WORDS=new Set(["the","a","an","and","or","but","of","to","in","on","at","for","with","by","is","are","be","this","that","these","those","it","as","from","we","our","us","i","you","your","they","their","was","were","will","would","should","shall","may","might","can","could","has","have","had","do","does","did","if","then","else","so","than","too","very","just","about","into","over","under","again","further","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","s","t","because","while"]),POSITIVE_MARKERS=new Set(["yes","recommend","support","approve","endorse","agree","proceed","accept","positive","pass","correct","adopt","allow","permit","go","true","valid","sound","good","safe","favor","continue","implement","ship","launch","greenlight","ok","okay"]),NEGATIVE_MARKERS=new Set(["no","not","against","oppose","reject","deny","refuse","decline","block","forbid","prohibit","fail","false","invalid","unsound","bad","unsafe","risk","risky","dont","shouldnt","cannot","cant","wont","never","negative","veto","stop","halt","abort","discard","overturn"]);function stem(token){if(token.length>4){if(token.endsWith("ing"))return token.slice(0,-3);if(token.endsWith("ed"))return token.slice(0,-2);if(token.endsWith("s")&&!token.endsWith("ss"))return token.slice(0,-1)}return token}function tokenize(text){return typeof text!="string"||text.length===0?[]:text.toLowerCase().split(/[^a-z0-9]+/g).filter(t=>t.length>0&&!STOP_WORDS.has(t))}function tokenSet(text){return new Set(tokenize(text))}function jaccard(a,b){if(a.size===0||b.size===0)return 0;let intersection=0,[smaller,larger]=a.size<=b.size?[a,b]:[b,a];for(let t of smaller)larger.has(t)&&intersection++;let union=a.size+b.size-intersection;return union>0?intersection/union:0}function polarity(text){let tokens=tokenize(text),pos=0,neg=0;for(let t of tokens){let s=stem(t);POSITIVE_MARKERS.has(s)&&pos++,NEGATIVE_MARKERS.has(s)&&neg++}return pos>neg?"positive":neg>pos?"negative":"neutral"}function validateSpecialist(specialist){if(!specialist||typeof specialist!="object")throw new RoutingError("specialist must be an object");if(typeof specialist.id!="string"||specialist.id.length===0)throw new RoutingError("specialist.id must be a non-empty string");if(typeof specialist.name!="string"||specialist.name.length===0)throw new RoutingError("specialist.name must be a non-empty string");if(!Array.isArray(specialist.expertise))throw new RoutingError("specialist.expertise must be an array");for(let e of specialist.expertise)if(typeof e!="string"||e.length===0)throw new RoutingError("each expertise entry must be a non-empty string");if(typeof specialist.weight!="number"||!Number.isFinite(specialist.weight)||specialist.weight<0)throw new RoutingError("specialist.weight must be a non-negative finite number")}function matchScore(problem,specialist){if(!problem||typeof problem!="object")throw new RoutingError("problem must be an object");validateSpecialist(specialist);let problemTokens=new Set([...tokenize(problem.description),...tokenize(problem.domain)]),expertTokens=new Set;for(let e of specialist.expertise)for(let t of tokenize(e))expertTokens.add(t);if(problemTokens.size===0||expertTokens.size===0)return 0;let intersection=0;for(let t of expertTokens)problemTokens.has(t)&&intersection++;let union=problemTokens.size+expertTokens.size-intersection;return union>0?intersection/union:0}function route(problem,specialists){if(!problem||typeof problem!="object")throw new RoutingError("problem must be an object");if(!Array.isArray(specialists))throw new RoutingError("specialists must be an array");return specialists.map((s,idx)=>({specialist:s,score:matchScore(problem,s),idx})).filter(m=>m.score>0).sort((a,b)=>b.score!==a.score?b.score-a.score:b.specialist.weight!==a.specialist.weight?b.specialist.weight-a.specialist.weight:a.idx-b.idx).map(m=>m.specialist)}function routeAll(problem,specialists){if(!problem||typeof problem!="object")throw new RoutingError("problem must be an object");if(!Array.isArray(specialists))throw new RoutingError("specialists must be an array");return specialists.map((s,idx)=>({specialist:s,score:matchScore(problem,s),idx})).sort((a,b)=>b.score!==a.score?b.score-a.score:b.specialist.weight!==a.specialist.weight?b.specialist.weight-a.specialist.weight:a.idx-b.idx).map(m=>({specialist:m.specialist,score:m.score}))}var SpecialistRegistry=class{specialists=new Map;order=[];register(specialist){if(validateSpecialist(specialist),this.specialists.has(specialist.id))throw new RoutingError(`specialist already registered: ${specialist.id}`);return this.specialists.set(specialist.id,specialist),this.order.push(specialist.id),this}unregister(id){this.specialists.delete(id);let idx=this.order.indexOf(id);return idx>=0&&this.order.splice(idx,1),this}get(id){return this.specialists.get(id)}list(){return this.order.map(id=>this.specialists.get(id))}route(problem){return route(problem,this.list())}routeAll(problem){return routeAll(problem,this.list())}};function validateAnalysis(analysis){if(!analysis||typeof analysis!="object")throw new AnalysisError("analysis must be an object");if(typeof analysis.id!="string"||analysis.id.length===0)throw new AnalysisError("analysis.id must be a non-empty string");if(typeof analysis.specialistId!="string"||analysis.specialistId.length===0)throw new AnalysisError("analysis.specialistId must be a non-empty string");if(typeof analysis.problemId!="string"||analysis.problemId.length===0)throw new AnalysisError("analysis.problemId must be a non-empty string");if(typeof analysis.content!="string"||analysis.content.length===0)throw new AnalysisError("analysis.content must be a non-empty string");if(typeof analysis.confidence!="number"||!Number.isFinite(analysis.confidence))throw new AnalysisError("analysis.confidence must be a finite number");if(analysis.confidence<0||analysis.confidence>1)throw new AnalysisError("analysis.confidence must be between 0 and 1");if(typeof analysis.reasoning!="string"||analysis.reasoning.length===0)throw new AnalysisError("analysis.reasoning must be a non-empty string");if(analysis.caveats!==void 0){if(!Array.isArray(analysis.caveats))throw new AnalysisError("analysis.caveats must be an array if provided");for(let c of analysis.caveats)if(typeof c!="string"||c.length===0)throw new AnalysisError("each caveat must be a non-empty string")}}var AnalysisCollector=class{analyses=new Map;order=[];byProblem=new Map;bySpecialist=new Map;submit(analysis){if(validateAnalysis(analysis),this.analyses.has(analysis.id))throw new AnalysisError(`analysis already submitted: ${analysis.id}`);return this.analyses.set(analysis.id,analysis),this.order.push(analysis.id),this.byProblem.has(analysis.problemId)||this.byProblem.set(analysis.problemId,[]),this.byProblem.get(analysis.problemId).push(analysis.id),this.bySpecialist.has(analysis.specialistId)||this.bySpecialist.set(analysis.specialistId,[]),this.bySpecialist.get(analysis.specialistId).push(analysis.id),this}get(id){return this.analyses.get(id)}getAll(problemId){return(this.byProblem.get(problemId)??[]).map(id=>this.analyses.get(id))}getBySpecialist(specialistId){return(this.bySpecialist.get(specialistId)??[]).map(id=>this.analyses.get(id))}list(){return this.order.map(id=>this.analyses.get(id))}size(){return this.order.length}};var DEFAULT_OUTLIER_THRESHOLD=.25;function assertAnalysis(analysis){if(!analysis||typeof analysis!="object")throw new ScoringError("analysis must be an object");let a=analysis;if(typeof a.id!="string"||a.id.length===0)throw new ScoringError("analysis.id must be a non-empty string");if(typeof a.specialistId!="string"||a.specialistId.length===0)throw new ScoringError("analysis.specialistId must be a non-empty string");if(typeof a.confidence!="number"||!Number.isFinite(a.confidence)||a.confidence<0||a.confidence>1)throw new ScoringError("analysis.confidence must be a finite number in [0, 1]")}function scoreAnalysis(analysis,specialistWeight){if(assertAnalysis(analysis),typeof specialistWeight!="number"||!Number.isFinite(specialistWeight)||specialistWeight<0)throw new ScoringError("specialistWeight must be a non-negative finite number");return{analysisId:analysis.id,raw:analysis.confidence,weight:specialistWeight,weighted:analysis.confidence*specialistWeight}}function aggregateScores(analyses,weights){if(!Array.isArray(analyses))throw new ScoringError("analyses must be an array");if(!weights||typeof weights!="object")throw new ScoringError("weights must be an object");if(analyses.length===0)return{combined:0,variance:0,stddev:0,total:0,weighted:[]};let weighted=[],totalWeight=0,weightedSum=0;for(let a of analyses){assertAnalysis(a);let w=weights[a.specialistId];if(typeof w!="number"||!Number.isFinite(w)||w<0)throw new ScoringError(`missing or invalid weight for specialist ${a.specialistId}`);let ws=a.confidence*w;weighted.push(ws),weightedSum+=ws,totalWeight+=w}let combined=totalWeight>0?weightedSum/totalWeight:0,mean=analyses.reduce((s,a)=>s+a.confidence,0)/analyses.length,variance=analyses.reduce((s,a)=>s+(a.confidence-mean)**2,0)/analyses.length;return{combined,variance,stddev:Math.sqrt(variance),total:analyses.length,weighted}}function detectOutliers(analyses,threshold=DEFAULT_OUTLIER_THRESHOLD){if(!Array.isArray(analyses))throw new ScoringError("analyses must be an array");if(typeof threshold!="number"||!Number.isFinite(threshold)||threshold<0)throw new ScoringError("threshold must be a non-negative finite number");if(analyses.length<2)return[];for(let a of analyses)assertAnalysis(a);let sorted=[...analyses].sort((a,b)=>a.confidence-b.confidence),mid=Math.floor(sorted.length/2),median=sorted.length%2===0?(sorted[mid-1].confidence+sorted[mid].confidence)/2:sorted[mid].confidence;return analyses.filter(a=>Math.abs(a.confidence-median)>threshold)}var CONFLICT_TYPES=["opposing_conclusion","factual_contradiction","divergent_reasoning"],CONFLICT_SEVERITIES=["low","medium","high"],OPPOSING_CONFIDENCE_THRESHOLD=.6,FACTUAL_OVERLAP_THRESHOLD=.3,DIVERGENT_REASONING_MAX_OVERLAP=.2,DIVERGENT_CONTENT_MIN_OVERLAP=.1,SEVERITY_HIGH_GAP=.5,SEVERITY_MEDIUM_GAP=.2;function severityFor(numAnalyses,confidenceGap){return numAnalyses>=3||confidenceGap>=SEVERITY_HIGH_GAP?"high":confidenceGap>=SEVERITY_MEDIUM_GAP?"medium":"low"}var ConflictDetector=class{detect(analyses){if(!Array.isArray(analyses))throw new ConflictError("analyses must be an array");for(let a of analyses){if(!a||typeof a!="object")throw new ConflictError("each analysis must be an object");if(typeof a.id!="string"||a.id.length===0)throw new ConflictError("each analysis.id must be a non-empty string")}let conflicts=[];if(analyses.length<2)return conflicts;let byProblem=new Map;for(let a of analyses)byProblem.has(a.problemId)||byProblem.set(a.problemId,[]),byProblem.get(a.problemId).push(a);for(let[problemId,group]of byProblem)for(let i=0;i<group.length;i++)for(let j=i+1;j<group.length;j++){let a=group[i],b=group[j],pa=polarity(a.content),pb=polarity(b.content),contentOverlap=jaccard(tokenSet(a.content),tokenSet(b.content)),reasoningOverlap=jaccard(tokenSet(a.reasoning),tokenSet(b.reasoning)),confidenceGap=Math.abs(a.confidence-b.confidence);a.confidence>OPPOSING_CONFIDENCE_THRESHOLD&&b.confidence>OPPOSING_CONFIDENCE_THRESHOLD&&pa!=="neutral"&&pb!=="neutral"&&pa!==pb&&conflicts.push({id:`conflict-opposing-${a.id}-${b.id}`,problemId,analysisIds:[a.id,b.id],description:`Analyses ${a.id} and ${b.id} reach opposing conclusions (${pa} vs ${pb}) with high confidence (> ${OPPOSING_CONFIDENCE_THRESHOLD}).`,severity:severityFor(2,confidenceGap),type:"opposing_conclusion"}),contentOverlap>=FACTUAL_OVERLAP_THRESHOLD&&pa!=="neutral"&&pb!=="neutral"&&pa!==pb&&conflicts.push({id:`conflict-factual-${a.id}-${b.id}`,problemId,analysisIds:[a.id,b.id],description:`Analyses ${a.id} and ${b.id} make contradictory factual claims about the same subject (content overlap ${contentOverlap.toFixed(2)}).`,severity:severityFor(2,confidenceGap),type:"factual_contradiction"}),pa!=="neutral"&&pa===pb&&reasoningOverlap<DIVERGENT_REASONING_MAX_OVERLAP&&contentOverlap>DIVERGENT_CONTENT_MIN_OVERLAP&&conflicts.push({id:`conflict-reasoning-${a.id}-${b.id}`,problemId,analysisIds:[a.id,b.id],description:`Analyses ${a.id} and ${b.id} reach the same conclusion (${pa}) via divergent reasoning (reasoning overlap ${reasoningOverlap.toFixed(2)}).`,severity:severityFor(2,confidenceGap),type:"divergent_reasoning"})}return conflicts.sort((x,y)=>x.type!==y.type?x.type.localeCompare(y.type):x.id.localeCompare(y.id)),conflicts}};var DEFAULT_MAX_DEBATE_ROUNDS=10;function validateRound(round){if(!round||typeof round!="object")throw new DebateError("round must be an object");if(typeof round.id!="string"||round.id.length===0)throw new DebateError("round.id must be a non-empty string");if(typeof round.analystId!="string"||round.analystId.length===0)throw new DebateError("round.analystId must be a non-empty string");if(typeof round.claim!="string"||round.claim.length===0)throw new DebateError("round.claim must be a non-empty string");if(typeof round.evidence!="string"||round.evidence.length===0)throw new DebateError("round.evidence must be a non-empty string");if(round.rebuttalTo!==void 0&&(typeof round.rebuttalTo!="string"||round.rebuttalTo.length===0))throw new DebateError("round.rebuttalTo must be a non-empty string when provided")}var DebateFacilitator=class{debates=new Map;maxRounds;counter=0;constructor(maxRounds=DEFAULT_MAX_DEBATE_ROUNDS){if(typeof maxRounds!="number"||!Number.isFinite(maxRounds)||maxRounds<1)throw new DebateError("maxRounds must be a positive finite number");this.maxRounds=Math.floor(maxRounds)}open(problemId,conflictIds=[]){if(typeof problemId!="string"||problemId.length===0)throw new DebateError("problemId must be a non-empty string");if(!Array.isArray(conflictIds))throw new DebateError("conflictIds must be an array");for(let c of conflictIds)if(typeof c!="string"||c.length===0)throw new DebateError("each conflictId must be a non-empty string");this.counter+=1;let id=`debate-${this.counter}`,debate={id,problemId,conflictIds:[...conflictIds],rounds:[],status:"open",openedAt:new Date().toISOString()};return this.debates.set(id,debate),debate}submitRound(debateId,round){let debate=this.debates.get(debateId);if(!debate)throw new DebateError(`debate not found: ${debateId}`);if(debate.status==="concluded")throw new DebateError(`debate ${debateId} is already concluded`);if(validateRound(round),debate.rounds.some(r=>r.id===round.id))throw new DebateError(`round already exists in debate ${debateId}: ${round.id}`);if(round.rebuttalTo!==void 0&&!debate.rounds.some(r=>r.id===round.rebuttalTo))throw new DebateError(`round.rebuttalTo does not reference an existing round: ${round.rebuttalTo}`);if(debate.rounds.length>=this.maxRounds)throw new DebateError(`max rounds (${this.maxRounds}) reached for debate ${debateId}`);return debate.rounds.push(round),debate}conclude(debateId){let debate=this.debates.get(debateId);if(!debate)throw new DebateError(`debate not found: ${debateId}`);if(debate.status==="concluded")throw new DebateError(`debate ${debateId} is already concluded`);return debate.status="concluded",debate.concludedAt=new Date().toISOString(),debate}get(debateId){return this.debates.get(debateId)}list(){return Array.from(this.debates.values())}getMaxRounds(){return this.maxRounds}};function validateMinorityOpinion(opinion){if(!opinion||typeof opinion!="object")throw new CouncilError("minority opinion must be an object");if(typeof opinion.id!="string"||opinion.id.length===0)throw new CouncilError("minority opinion.id must be a non-empty string");if(typeof opinion.problemId!="string"||opinion.problemId.length===0)throw new CouncilError("minority opinion.problemId must be a non-empty string");if(typeof opinion.analystId!="string"||opinion.analystId.length===0)throw new CouncilError("minority opinion.analystId must be a non-empty string");if(typeof opinion.position!="string"||opinion.position.length===0)throw new CouncilError("minority opinion.position must be a non-empty string");if(typeof opinion.reasoning!="string"||opinion.reasoning.length===0)throw new CouncilError("minority opinion.reasoning must be a non-empty string");if(typeof opinion.dissentReason!="string"||opinion.dissentReason.length===0)throw new CouncilError("minority opinion.dissentReason must be a non-empty string")}var MinorityOpinionTracker=class{opinions=new Map;order=[];byProblem=new Map;byAnalyst=new Map;record(opinion){if(validateMinorityOpinion(opinion),this.opinions.has(opinion.id))throw new CouncilError(`minority opinion already recorded: ${opinion.id}`);return this.opinions.set(opinion.id,opinion),this.order.push(opinion.id),this.byProblem.has(opinion.problemId)||this.byProblem.set(opinion.problemId,[]),this.byProblem.get(opinion.problemId).push(opinion.id),this.byAnalyst.has(opinion.analystId)||this.byAnalyst.set(opinion.analystId,[]),this.byAnalyst.get(opinion.analystId).push(opinion.id),this}get(id){return this.opinions.get(id)}getForProblem(problemId){return(this.byProblem.get(problemId)??[]).map(id=>this.opinions.get(id))}getByAnalyst(analystId){return(this.byAnalyst.get(analystId)??[]).map(id=>this.opinions.get(id))}list(){return this.order.map(id=>this.opinions.get(id))}size(){return this.order.length}};var DEFAULT_CONSENSUS_THRESHOLD=.6,ConsensusBuilder=class{threshold;constructor(threshold=DEFAULT_CONSENSUS_THRESHOLD){if(typeof threshold!="number"||!Number.isFinite(threshold)||threshold<0||threshold>1)throw new ConsensusError("threshold must be a finite number in [0, 1]");this.threshold=threshold}getThreshold(){return this.threshold}build(problemId,analyses,conflicts=[],options={}){if(typeof problemId!="string"||problemId.length===0)throw new ConsensusError("problemId must be a non-empty string");if(!Array.isArray(analyses))throw new ConsensusError("analyses must be an array");if(!Array.isArray(conflicts))throw new ConsensusError("conflicts must be an array");if(options&&typeof options!="object")throw new ConsensusError("options must be an object when provided");if(analyses.length===0)return null;let weights=options.weights??{};if(!weights||typeof weights!="object")throw new ConsensusError("options.weights must be an object when provided");let withPolarity=analyses.map(a=>({analysis:a,polarity:polarity(a.content)})).filter(x=>x.polarity!=="neutral");if(withPolarity.length===0)return null;let tally={},totalWeight=0;for(let{analysis,polarity:pol}of withPolarity){let w=weights[analysis.specialistId];if(w!==void 0&&(typeof w!="number"||!Number.isFinite(w)||w<0))throw new ConsensusError(`invalid weight for specialist ${analysis.specialistId}`);let contribution=(w??1)*analysis.confidence;tally[pol]||(tally[pol]={weight:0,analysts:[]}),tally[pol].weight+=contribution,tally[pol].analysts.push(analysis.specialistId),totalWeight+=contribution}if(totalWeight===0)return null;let winner=null,winnerWeight=0;for(let pol of Object.keys(tally))tally[pol].weight>winnerWeight&&(winnerWeight=tally[pol].weight,winner=pol);if(!winner)return null;let supportRatio=winnerWeight/totalWeight;if(supportRatio<this.threshold)return null;let supportingAnalystIds=Array.from(new Set(tally[winner].analysts)),dissentingAnalystIds=Array.from(new Set(withPolarity.filter(x=>x.polarity!==winner).map(x=>x.analysis.specialistId).concat(options.minorityAnalystIds??[]))),problemConflicts=conflicts.filter(c=>c.problemId===problemId),conflictsResolved=problemConflicts.map(c=>c.id),openIssues=problemConflicts.filter(c=>c.severity==="high").map(c=>`High-severity conflict ${c.id} remains unresolved: ${c.description}`);return{problemId,decision:winner==="positive"?`Adopt the proposed action for problem ${problemId}.`:`Reject the proposed action for problem ${problemId}.`,confidence:supportRatio,supportingAnalystIds,dissentingAnalystIds,conflictsResolved,openIssues}}};function buildReport(input){if(!input||typeof input!="object")throw new CouncilError("input must be an object");if(typeof input.problemId!="string"||input.problemId.length===0)throw new CouncilError("input.problemId must be a non-empty string");if(!Array.isArray(input.analyses))throw new CouncilError("input.analyses must be an array");let conflicts=Array.isArray(input.conflicts)?input.conflicts:[],debates=Array.isArray(input.debates)?input.debates:[],minorityOpinions=Array.isArray(input.minorityOpinions)?input.minorityOpinions:[],recommendations=Array.isArray(input.recommendations)?input.recommendations:[],consensus=input.consensus===void 0?null:input.consensus,generatedAt=input.generatedAt??new Date().toISOString(),id=input.reportId??`report-${input.problemId}-${generatedAt}`,summary=summarize(input.problemId,input.analyses.length,conflicts.length,consensus);return{id,problemId:input.problemId,generatedAt,summary,analyses:[...input.analyses],conflicts:[...conflicts],debates:[...debates],minorityOpinions:[...minorityOpinions],consensus,recommendations:[...recommendations]}}function serializeReport(report){if(!report||typeof report!="object")throw new CouncilError("report must be an object");try{return JSON.stringify(report,null,2)}catch(err){throw new CouncilError(`failed to serialize report: ${err.message}`)}}function summarizeReport(report){if(!report||typeof report!="object")throw new CouncilError("report must be an object");let lines=[];if(lines.push(`Report ${report.id} for problem ${report.problemId} generated at ${report.generatedAt}.`),lines.push(`${report.analyses.length} analyses; ${report.conflicts.length} conflicts; ${report.debates.length} debates; ${report.minorityOpinions.length} minority opinions.`),lines.push(report.summary),report.consensus){let pct=(report.consensus.confidence*100).toFixed(1);lines.push(`Decision: ${report.consensus.decision} (confidence ${pct}%).`)}else lines.push("No consensus was reached.");return report.recommendations.length>0&&lines.push(`Recommendations: ${report.recommendations.join("; ")}.`),lines.join(" ")}function summarize(problemId,analysisCount,conflictCount,consensus){let parts=[];if(parts.push(`Problem ${problemId} received ${analysisCount} analysis${analysisCount===1?"":"ies"}.`),conflictCount>0?parts.push(`${conflictCount} conflict${conflictCount===1?"":"s"} detected.`):parts.push("No conflicts detected."),consensus){let pct=(consensus.confidence*100).toFixed(1);parts.push(`Consensus reached at confidence ${pct}%.`)}else parts.push("No consensus reached.");return parts.join(" ")}var DEFAULT_SYNTHESIS_THRESHOLD=.6,STRONG_CONSENSUS_RATIO=.8;function classifyConsensus(consensus,threshold=DEFAULT_SYNTHESIS_THRESHOLD){return consensus?consensus.dissentingAnalystIds.length===0?"unanimous":consensus.confidence>=STRONG_CONSENSUS_RATIO?"strong":consensus.confidence>=threshold?"majority":"split":"none"}function synthesize(problemId,consensus,analyses,conflicts=[],options={}){if(typeof problemId!="string"||problemId.length===0)throw new SynthesisError("problemId must be a non-empty string");if(!Array.isArray(analyses))throw new SynthesisError("analyses must be an array");if(!Array.isArray(conflicts))throw new SynthesisError("conflicts must be an array");if(consensus!==null&&(!consensus||typeof consensus!="object"))throw new SynthesisError("consensus must be an object or null");let threshold=options.threshold??DEFAULT_SYNTHESIS_THRESHOLD;if(typeof threshold!="number"||!Number.isFinite(threshold)||threshold<0||threshold>1)throw new SynthesisError("threshold must be a finite number in [0, 1]");let minorityOpinions=Array.isArray(options.minorityOpinions)?options.minorityOpinions:[],level=classifyConsensus(consensus,threshold),participants=Array.from(new Set(analyses.map(a=>a.specialistId))),decisionText=options.decision??consensus?.decision??`No actionable decision for problem ${problemId}; insufficient consensus.`,confidence=consensus?.confidence??0,rationaleParts=[];consensus?(rationaleParts.push(`Consensus reached with ${consensus.supportingAnalystIds.length} supporting and ${consensus.dissentingAnalystIds.length} dissenting (weighted support ${(consensus.confidence*100).toFixed(1)}%, level: ${level}).`),consensus.conflictsResolved.length>0&&rationaleParts.push(`${consensus.conflictsResolved.length} conflict${consensus.conflictsResolved.length===1?"":"s"} considered.`),consensus.openIssues.length>0&&rationaleParts.push(`Open issues: ${consensus.openIssues.join("; ")}`)):rationaleParts.push(`No consensus was reached across ${analyses.length} analysis${analyses.length===1?"":"ies"}.`),conflicts.length>0&&rationaleParts.push(`${conflicts.length} conflict${conflicts.length===1?"":"s"} taken into account.`),minorityOpinions.length>0&&rationaleParts.push(`${minorityOpinions.length} minority opinion${minorityOpinions.length===1?"":"s"} preserved on record.`);let generatedAt=options.generatedAt??new Date().toISOString();return{id:options.decisionId??`decision-${problemId}-${generatedAt}`,problemId,decision:decisionText,rationale:rationaleParts.join(" "),confidence,consensusLevel:level,participants,generatedAt}}0&&(module.exports={AnalysisCollector,AnalysisError,CONFLICT_SEVERITIES,CONFLICT_TYPES,ConflictDetector,ConflictError,ConsensusBuilder,ConsensusError,ConsoleLogger,CouncilError,DEFAULT_CONSENSUS_THRESHOLD,DEFAULT_MAX_DEBATE_ROUNDS,DEFAULT_OUTLIER_THRESHOLD,DEFAULT_SYNTHESIS_THRESHOLD,DIVERGENT_CONTENT_MIN_OVERLAP,DIVERGENT_REASONING_MAX_OVERLAP,DebateError,DebateFacilitator,FACTUAL_OVERLAP_THRESHOLD,MinorityOpinionTracker,OPPOSING_CONFIDENCE_THRESHOLD,RoutingError,SCRUBBED_FIELD_NAMES,SEVERITY_HIGH_GAP,SEVERITY_MEDIUM_GAP,STRONG_CONSENSUS_RATIO,ScoringError,SilentLogger,SpecialistRegistry,SynthesisError,aggregateScores,buildReport,classifyConsensus,detectOutliers,matchScore,route,routeAll,scoreAnalysis,scrubMetadata,serializeReport,severityFor,shouldScrubField,summarizeReport,synthesize,validateAnalysis,validateMinorityOpinion,validateRound,validateSpecialist});
|
|
4
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/index.ts", "../../src/errors.ts", "../../src/logging.ts", "../../src/util.ts", "../../src/router/router.ts", "../../src/analysis/analysis.ts", "../../src/scoring/scoring.ts", "../../src/conflict/conflict.ts", "../../src/debate/debate.ts", "../../src/minority/minority.ts", "../../src/consensus/consensus.ts", "../../src/reports/reports.ts", "../../src/synthesizer/synthesizer.ts"],
|
|
4
|
+
"mappings": "wpBAAA,47DCWO,IAAM,aAAN,cAA2B,KAAM,CACtB,KACS,MACzB,YAAY,QAAiB,KAAe,MAAiB,CAC3D,MAAM,OAAO,EACb,KAAK,KAAO,WAAW,KACvB,KAAK,KAAO,MAAQ,gBAChB,QAAU,SAAW,KAAK,MAAQ,OACtC,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,aAAN,cAA2B,YAAa,CAC7C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,gBAAiB,KAAK,CAAG,CAC1F,EAGa,cAAN,cAA4B,YAAa,CAC9C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,iBAAkB,KAAK,CAAG,CAC3F,EAGa,aAAN,cAA2B,YAAa,CAC7C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,gBAAiB,KAAK,CAAG,CAC1F,EAGa,cAAN,cAA4B,YAAa,CAC9C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,iBAAkB,KAAK,CAAG,CAC3F,EAGa,YAAN,cAA0B,YAAa,CAC5C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,eAAgB,KAAK,CAAG,CACzF,EAGa,eAAN,cAA6B,YAAa,CAC/C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,kBAAmB,KAAK,CAAG,CAC5F,EAGa,eAAN,cAA6B,YAAa,CAC/C,YAAY,QAAiB,MAAiB,CAAE,MAAM,QAAS,kBAAmB,KAAK,CAAG,CAC5F,ECtCA,IAAM,WAAuC,CAC3C,MAAO,GAAI,KAAM,GAAI,KAAM,GAAI,MAAO,GAAI,OAAQ,GACpD,EAGa,qBAAuB,CAClC,QAAS,SAAU,QAAS,SAAU,UACxC,EAGO,SAAS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B,MAAM,oBAAoB,iBAAiB,SAAW,EAAI,GAAK,GAAG,uBACxF,EAGF,IAAM,YAAc,QAAQ,aAAe,IAAI,KAAK,EAAE,YAAY,EAGlE,MAAO,CACL,GAHS,QAAQ,YAAc,YAAY,SAAS,IAAI,WAAW,GAInE,UACA,SAAU,aACV,UAAW,eAAe,KAAK,GAAG,EAClC,WACA,eAAgB,MAChB,aACA,WACF,CACF",
|
|
5
|
+
"names": []
|
|
6
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var CouncilError=class extends Error{code;cause;constructor(message,code,cause){super(message),this.name=new.target.name,this.code=code??"COUNCIL_ERROR",cause!==void 0&&(this.cause=cause),Object.setPrototypeOf(this,new.target.prototype)}},RoutingError=class extends CouncilError{constructor(message,cause){super(message,"ROUTING_ERROR",cause)}},AnalysisError=class extends CouncilError{constructor(message,cause){super(message,"ANALYSIS_ERROR",cause)}},ScoringError=class extends CouncilError{constructor(message,cause){super(message,"SCORING_ERROR",cause)}},ConflictError=class extends CouncilError{constructor(message,cause){super(message,"CONFLICT_ERROR",cause)}},DebateError=class extends CouncilError{constructor(message,cause){super(message,"DEBATE_ERROR",cause)}},ConsensusError=class extends CouncilError{constructor(message,cause){super(message,"CONSENSUS_ERROR",cause)}},SynthesisError=class extends CouncilError{constructor(message,cause){super(message,"SYNTHESIS_ERROR",cause)}};var LEVEL_RANK={debug:10,info:20,warn:30,error:40,silent:100},SCRUBBED_FIELD_NAMES=["taxId","secret","token","apiKey","password"];function shouldScrubField(name){let lower=name.toLowerCase();for(let needle of SCRUBBED_FIELD_NAMES){let nl=needle.toLowerCase();if(lower===nl||lower.endsWith("_"+nl))return!0}return!1}function scrubMetadata(meta){if(meta==null||typeof meta!="object")return meta;if(Buffer.isBuffer(meta))return`[buffer:${meta.length}]`;if(meta instanceof Date)return meta.toISOString();if(Array.isArray(meta))return meta.map(scrubMetadata);let out={};for(let[k,v]of Object.entries(meta))out[k]=shouldScrubField(k)?"[redacted]":scrubMetadata(v);return out}var ConsoleLogger=class{constructor(level="info"){this.level=level;this.levelRank=LEVEL_RANK[level]??LEVEL_RANK.info}level;levelRank;debug(msg,meta){this.emit("debug",msg,meta)}info(msg,meta){this.emit("info",msg,meta)}warn(msg,meta){this.emit("warn",msg,meta)}error(msg,meta){this.emit("error",msg,meta)}emit(level,msg,meta){try{if(LEVEL_RANK[level]<this.levelRank)return;let entry={level,msg,ts:new Date().toISOString(),...meta?{meta:scrubMetadata(meta)}:{}},line=JSON.stringify(entry);level==="error"||level==="warn"?process.stderr.write(line+`
|
|
2
|
+
`):process.stdout.write(line+`
|
|
3
|
+
`)}catch{}}},SilentLogger=class{debug(){}info(){}warn(){}error(){}};var STOP_WORDS=new Set(["the","a","an","and","or","but","of","to","in","on","at","for","with","by","is","are","be","this","that","these","those","it","as","from","we","our","us","i","you","your","they","their","was","were","will","would","should","shall","may","might","can","could","has","have","had","do","does","did","if","then","else","so","than","too","very","just","about","into","over","under","again","further","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","s","t","because","while"]),POSITIVE_MARKERS=new Set(["yes","recommend","support","approve","endorse","agree","proceed","accept","positive","pass","correct","adopt","allow","permit","go","true","valid","sound","good","safe","favor","continue","implement","ship","launch","greenlight","ok","okay"]),NEGATIVE_MARKERS=new Set(["no","not","against","oppose","reject","deny","refuse","decline","block","forbid","prohibit","fail","false","invalid","unsound","bad","unsafe","risk","risky","dont","shouldnt","cannot","cant","wont","never","negative","veto","stop","halt","abort","discard","overturn"]);function stem(token){if(token.length>4){if(token.endsWith("ing"))return token.slice(0,-3);if(token.endsWith("ed"))return token.slice(0,-2);if(token.endsWith("s")&&!token.endsWith("ss"))return token.slice(0,-1)}return token}function tokenize(text){return typeof text!="string"||text.length===0?[]:text.toLowerCase().split(/[^a-z0-9]+/g).filter(t=>t.length>0&&!STOP_WORDS.has(t))}function tokenSet(text){return new Set(tokenize(text))}function jaccard(a,b){if(a.size===0||b.size===0)return 0;let intersection=0,[smaller,larger]=a.size<=b.size?[a,b]:[b,a];for(let t of smaller)larger.has(t)&&intersection++;let union=a.size+b.size-intersection;return union>0?intersection/union:0}function polarity(text){let tokens=tokenize(text),pos=0,neg=0;for(let t of tokens){let s=stem(t);POSITIVE_MARKERS.has(s)&&pos++,NEGATIVE_MARKERS.has(s)&&neg++}return pos>neg?"positive":neg>pos?"negative":"neutral"}function validateSpecialist(specialist){if(!specialist||typeof specialist!="object")throw new RoutingError("specialist must be an object");if(typeof specialist.id!="string"||specialist.id.length===0)throw new RoutingError("specialist.id must be a non-empty string");if(typeof specialist.name!="string"||specialist.name.length===0)throw new RoutingError("specialist.name must be a non-empty string");if(!Array.isArray(specialist.expertise))throw new RoutingError("specialist.expertise must be an array");for(let e of specialist.expertise)if(typeof e!="string"||e.length===0)throw new RoutingError("each expertise entry must be a non-empty string");if(typeof specialist.weight!="number"||!Number.isFinite(specialist.weight)||specialist.weight<0)throw new RoutingError("specialist.weight must be a non-negative finite number")}function matchScore(problem,specialist){if(!problem||typeof problem!="object")throw new RoutingError("problem must be an object");validateSpecialist(specialist);let problemTokens=new Set([...tokenize(problem.description),...tokenize(problem.domain)]),expertTokens=new Set;for(let e of specialist.expertise)for(let t of tokenize(e))expertTokens.add(t);if(problemTokens.size===0||expertTokens.size===0)return 0;let intersection=0;for(let t of expertTokens)problemTokens.has(t)&&intersection++;let union=problemTokens.size+expertTokens.size-intersection;return union>0?intersection/union:0}function route(problem,specialists){if(!problem||typeof problem!="object")throw new RoutingError("problem must be an object");if(!Array.isArray(specialists))throw new RoutingError("specialists must be an array");return specialists.map((s,idx)=>({specialist:s,score:matchScore(problem,s),idx})).filter(m=>m.score>0).sort((a,b)=>b.score!==a.score?b.score-a.score:b.specialist.weight!==a.specialist.weight?b.specialist.weight-a.specialist.weight:a.idx-b.idx).map(m=>m.specialist)}function routeAll(problem,specialists){if(!problem||typeof problem!="object")throw new RoutingError("problem must be an object");if(!Array.isArray(specialists))throw new RoutingError("specialists must be an array");return specialists.map((s,idx)=>({specialist:s,score:matchScore(problem,s),idx})).sort((a,b)=>b.score!==a.score?b.score-a.score:b.specialist.weight!==a.specialist.weight?b.specialist.weight-a.specialist.weight:a.idx-b.idx).map(m=>({specialist:m.specialist,score:m.score}))}var SpecialistRegistry=class{specialists=new Map;order=[];register(specialist){if(validateSpecialist(specialist),this.specialists.has(specialist.id))throw new RoutingError(`specialist already registered: ${specialist.id}`);return this.specialists.set(specialist.id,specialist),this.order.push(specialist.id),this}unregister(id){this.specialists.delete(id);let idx=this.order.indexOf(id);return idx>=0&&this.order.splice(idx,1),this}get(id){return this.specialists.get(id)}list(){return this.order.map(id=>this.specialists.get(id))}route(problem){return route(problem,this.list())}routeAll(problem){return routeAll(problem,this.list())}};function validateAnalysis(analysis){if(!analysis||typeof analysis!="object")throw new AnalysisError("analysis must be an object");if(typeof analysis.id!="string"||analysis.id.length===0)throw new AnalysisError("analysis.id must be a non-empty string");if(typeof analysis.specialistId!="string"||analysis.specialistId.length===0)throw new AnalysisError("analysis.specialistId must be a non-empty string");if(typeof analysis.problemId!="string"||analysis.problemId.length===0)throw new AnalysisError("analysis.problemId must be a non-empty string");if(typeof analysis.content!="string"||analysis.content.length===0)throw new AnalysisError("analysis.content must be a non-empty string");if(typeof analysis.confidence!="number"||!Number.isFinite(analysis.confidence))throw new AnalysisError("analysis.confidence must be a finite number");if(analysis.confidence<0||analysis.confidence>1)throw new AnalysisError("analysis.confidence must be between 0 and 1");if(typeof analysis.reasoning!="string"||analysis.reasoning.length===0)throw new AnalysisError("analysis.reasoning must be a non-empty string");if(analysis.caveats!==void 0){if(!Array.isArray(analysis.caveats))throw new AnalysisError("analysis.caveats must be an array if provided");for(let c of analysis.caveats)if(typeof c!="string"||c.length===0)throw new AnalysisError("each caveat must be a non-empty string")}}var AnalysisCollector=class{analyses=new Map;order=[];byProblem=new Map;bySpecialist=new Map;submit(analysis){if(validateAnalysis(analysis),this.analyses.has(analysis.id))throw new AnalysisError(`analysis already submitted: ${analysis.id}`);return this.analyses.set(analysis.id,analysis),this.order.push(analysis.id),this.byProblem.has(analysis.problemId)||this.byProblem.set(analysis.problemId,[]),this.byProblem.get(analysis.problemId).push(analysis.id),this.bySpecialist.has(analysis.specialistId)||this.bySpecialist.set(analysis.specialistId,[]),this.bySpecialist.get(analysis.specialistId).push(analysis.id),this}get(id){return this.analyses.get(id)}getAll(problemId){return(this.byProblem.get(problemId)??[]).map(id=>this.analyses.get(id))}getBySpecialist(specialistId){return(this.bySpecialist.get(specialistId)??[]).map(id=>this.analyses.get(id))}list(){return this.order.map(id=>this.analyses.get(id))}size(){return this.order.length}};var DEFAULT_OUTLIER_THRESHOLD=.25;function assertAnalysis(analysis){if(!analysis||typeof analysis!="object")throw new ScoringError("analysis must be an object");let a=analysis;if(typeof a.id!="string"||a.id.length===0)throw new ScoringError("analysis.id must be a non-empty string");if(typeof a.specialistId!="string"||a.specialistId.length===0)throw new ScoringError("analysis.specialistId must be a non-empty string");if(typeof a.confidence!="number"||!Number.isFinite(a.confidence)||a.confidence<0||a.confidence>1)throw new ScoringError("analysis.confidence must be a finite number in [0, 1]")}function scoreAnalysis(analysis,specialistWeight){if(assertAnalysis(analysis),typeof specialistWeight!="number"||!Number.isFinite(specialistWeight)||specialistWeight<0)throw new ScoringError("specialistWeight must be a non-negative finite number");return{analysisId:analysis.id,raw:analysis.confidence,weight:specialistWeight,weighted:analysis.confidence*specialistWeight}}function aggregateScores(analyses,weights){if(!Array.isArray(analyses))throw new ScoringError("analyses must be an array");if(!weights||typeof weights!="object")throw new ScoringError("weights must be an object");if(analyses.length===0)return{combined:0,variance:0,stddev:0,total:0,weighted:[]};let weighted=[],totalWeight=0,weightedSum=0;for(let a of analyses){assertAnalysis(a);let w=weights[a.specialistId];if(typeof w!="number"||!Number.isFinite(w)||w<0)throw new ScoringError(`missing or invalid weight for specialist ${a.specialistId}`);let ws=a.confidence*w;weighted.push(ws),weightedSum+=ws,totalWeight+=w}let combined=totalWeight>0?weightedSum/totalWeight:0,mean=analyses.reduce((s,a)=>s+a.confidence,0)/analyses.length,variance=analyses.reduce((s,a)=>s+(a.confidence-mean)**2,0)/analyses.length;return{combined,variance,stddev:Math.sqrt(variance),total:analyses.length,weighted}}function detectOutliers(analyses,threshold=DEFAULT_OUTLIER_THRESHOLD){if(!Array.isArray(analyses))throw new ScoringError("analyses must be an array");if(typeof threshold!="number"||!Number.isFinite(threshold)||threshold<0)throw new ScoringError("threshold must be a non-negative finite number");if(analyses.length<2)return[];for(let a of analyses)assertAnalysis(a);let sorted=[...analyses].sort((a,b)=>a.confidence-b.confidence),mid=Math.floor(sorted.length/2),median=sorted.length%2===0?(sorted[mid-1].confidence+sorted[mid].confidence)/2:sorted[mid].confidence;return analyses.filter(a=>Math.abs(a.confidence-median)>threshold)}var CONFLICT_TYPES=["opposing_conclusion","factual_contradiction","divergent_reasoning"],CONFLICT_SEVERITIES=["low","medium","high"],OPPOSING_CONFIDENCE_THRESHOLD=.6,FACTUAL_OVERLAP_THRESHOLD=.3,DIVERGENT_REASONING_MAX_OVERLAP=.2,DIVERGENT_CONTENT_MIN_OVERLAP=.1,SEVERITY_HIGH_GAP=.5,SEVERITY_MEDIUM_GAP=.2;function severityFor(numAnalyses,confidenceGap){return numAnalyses>=3||confidenceGap>=SEVERITY_HIGH_GAP?"high":confidenceGap>=SEVERITY_MEDIUM_GAP?"medium":"low"}var ConflictDetector=class{detect(analyses){if(!Array.isArray(analyses))throw new ConflictError("analyses must be an array");for(let a of analyses){if(!a||typeof a!="object")throw new ConflictError("each analysis must be an object");if(typeof a.id!="string"||a.id.length===0)throw new ConflictError("each analysis.id must be a non-empty string")}let conflicts=[];if(analyses.length<2)return conflicts;let byProblem=new Map;for(let a of analyses)byProblem.has(a.problemId)||byProblem.set(a.problemId,[]),byProblem.get(a.problemId).push(a);for(let[problemId,group]of byProblem)for(let i=0;i<group.length;i++)for(let j=i+1;j<group.length;j++){let a=group[i],b=group[j],pa=polarity(a.content),pb=polarity(b.content),contentOverlap=jaccard(tokenSet(a.content),tokenSet(b.content)),reasoningOverlap=jaccard(tokenSet(a.reasoning),tokenSet(b.reasoning)),confidenceGap=Math.abs(a.confidence-b.confidence);a.confidence>OPPOSING_CONFIDENCE_THRESHOLD&&b.confidence>OPPOSING_CONFIDENCE_THRESHOLD&&pa!=="neutral"&&pb!=="neutral"&&pa!==pb&&conflicts.push({id:`conflict-opposing-${a.id}-${b.id}`,problemId,analysisIds:[a.id,b.id],description:`Analyses ${a.id} and ${b.id} reach opposing conclusions (${pa} vs ${pb}) with high confidence (> ${OPPOSING_CONFIDENCE_THRESHOLD}).`,severity:severityFor(2,confidenceGap),type:"opposing_conclusion"}),contentOverlap>=FACTUAL_OVERLAP_THRESHOLD&&pa!=="neutral"&&pb!=="neutral"&&pa!==pb&&conflicts.push({id:`conflict-factual-${a.id}-${b.id}`,problemId,analysisIds:[a.id,b.id],description:`Analyses ${a.id} and ${b.id} make contradictory factual claims about the same subject (content overlap ${contentOverlap.toFixed(2)}).`,severity:severityFor(2,confidenceGap),type:"factual_contradiction"}),pa!=="neutral"&&pa===pb&&reasoningOverlap<DIVERGENT_REASONING_MAX_OVERLAP&&contentOverlap>DIVERGENT_CONTENT_MIN_OVERLAP&&conflicts.push({id:`conflict-reasoning-${a.id}-${b.id}`,problemId,analysisIds:[a.id,b.id],description:`Analyses ${a.id} and ${b.id} reach the same conclusion (${pa}) via divergent reasoning (reasoning overlap ${reasoningOverlap.toFixed(2)}).`,severity:severityFor(2,confidenceGap),type:"divergent_reasoning"})}return conflicts.sort((x,y)=>x.type!==y.type?x.type.localeCompare(y.type):x.id.localeCompare(y.id)),conflicts}};var DEFAULT_MAX_DEBATE_ROUNDS=10;function validateRound(round){if(!round||typeof round!="object")throw new DebateError("round must be an object");if(typeof round.id!="string"||round.id.length===0)throw new DebateError("round.id must be a non-empty string");if(typeof round.analystId!="string"||round.analystId.length===0)throw new DebateError("round.analystId must be a non-empty string");if(typeof round.claim!="string"||round.claim.length===0)throw new DebateError("round.claim must be a non-empty string");if(typeof round.evidence!="string"||round.evidence.length===0)throw new DebateError("round.evidence must be a non-empty string");if(round.rebuttalTo!==void 0&&(typeof round.rebuttalTo!="string"||round.rebuttalTo.length===0))throw new DebateError("round.rebuttalTo must be a non-empty string when provided")}var DebateFacilitator=class{debates=new Map;maxRounds;counter=0;constructor(maxRounds=DEFAULT_MAX_DEBATE_ROUNDS){if(typeof maxRounds!="number"||!Number.isFinite(maxRounds)||maxRounds<1)throw new DebateError("maxRounds must be a positive finite number");this.maxRounds=Math.floor(maxRounds)}open(problemId,conflictIds=[]){if(typeof problemId!="string"||problemId.length===0)throw new DebateError("problemId must be a non-empty string");if(!Array.isArray(conflictIds))throw new DebateError("conflictIds must be an array");for(let c of conflictIds)if(typeof c!="string"||c.length===0)throw new DebateError("each conflictId must be a non-empty string");this.counter+=1;let id=`debate-${this.counter}`,debate={id,problemId,conflictIds:[...conflictIds],rounds:[],status:"open",openedAt:new Date().toISOString()};return this.debates.set(id,debate),debate}submitRound(debateId,round){let debate=this.debates.get(debateId);if(!debate)throw new DebateError(`debate not found: ${debateId}`);if(debate.status==="concluded")throw new DebateError(`debate ${debateId} is already concluded`);if(validateRound(round),debate.rounds.some(r=>r.id===round.id))throw new DebateError(`round already exists in debate ${debateId}: ${round.id}`);if(round.rebuttalTo!==void 0&&!debate.rounds.some(r=>r.id===round.rebuttalTo))throw new DebateError(`round.rebuttalTo does not reference an existing round: ${round.rebuttalTo}`);if(debate.rounds.length>=this.maxRounds)throw new DebateError(`max rounds (${this.maxRounds}) reached for debate ${debateId}`);return debate.rounds.push(round),debate}conclude(debateId){let debate=this.debates.get(debateId);if(!debate)throw new DebateError(`debate not found: ${debateId}`);if(debate.status==="concluded")throw new DebateError(`debate ${debateId} is already concluded`);return debate.status="concluded",debate.concludedAt=new Date().toISOString(),debate}get(debateId){return this.debates.get(debateId)}list(){return Array.from(this.debates.values())}getMaxRounds(){return this.maxRounds}};function validateMinorityOpinion(opinion){if(!opinion||typeof opinion!="object")throw new CouncilError("minority opinion must be an object");if(typeof opinion.id!="string"||opinion.id.length===0)throw new CouncilError("minority opinion.id must be a non-empty string");if(typeof opinion.problemId!="string"||opinion.problemId.length===0)throw new CouncilError("minority opinion.problemId must be a non-empty string");if(typeof opinion.analystId!="string"||opinion.analystId.length===0)throw new CouncilError("minority opinion.analystId must be a non-empty string");if(typeof opinion.position!="string"||opinion.position.length===0)throw new CouncilError("minority opinion.position must be a non-empty string");if(typeof opinion.reasoning!="string"||opinion.reasoning.length===0)throw new CouncilError("minority opinion.reasoning must be a non-empty string");if(typeof opinion.dissentReason!="string"||opinion.dissentReason.length===0)throw new CouncilError("minority opinion.dissentReason must be a non-empty string")}var MinorityOpinionTracker=class{opinions=new Map;order=[];byProblem=new Map;byAnalyst=new Map;record(opinion){if(validateMinorityOpinion(opinion),this.opinions.has(opinion.id))throw new CouncilError(`minority opinion already recorded: ${opinion.id}`);return this.opinions.set(opinion.id,opinion),this.order.push(opinion.id),this.byProblem.has(opinion.problemId)||this.byProblem.set(opinion.problemId,[]),this.byProblem.get(opinion.problemId).push(opinion.id),this.byAnalyst.has(opinion.analystId)||this.byAnalyst.set(opinion.analystId,[]),this.byAnalyst.get(opinion.analystId).push(opinion.id),this}get(id){return this.opinions.get(id)}getForProblem(problemId){return(this.byProblem.get(problemId)??[]).map(id=>this.opinions.get(id))}getByAnalyst(analystId){return(this.byAnalyst.get(analystId)??[]).map(id=>this.opinions.get(id))}list(){return this.order.map(id=>this.opinions.get(id))}size(){return this.order.length}};var DEFAULT_CONSENSUS_THRESHOLD=.6,ConsensusBuilder=class{threshold;constructor(threshold=DEFAULT_CONSENSUS_THRESHOLD){if(typeof threshold!="number"||!Number.isFinite(threshold)||threshold<0||threshold>1)throw new ConsensusError("threshold must be a finite number in [0, 1]");this.threshold=threshold}getThreshold(){return this.threshold}build(problemId,analyses,conflicts=[],options={}){if(typeof problemId!="string"||problemId.length===0)throw new ConsensusError("problemId must be a non-empty string");if(!Array.isArray(analyses))throw new ConsensusError("analyses must be an array");if(!Array.isArray(conflicts))throw new ConsensusError("conflicts must be an array");if(options&&typeof options!="object")throw new ConsensusError("options must be an object when provided");if(analyses.length===0)return null;let weights=options.weights??{};if(!weights||typeof weights!="object")throw new ConsensusError("options.weights must be an object when provided");let withPolarity=analyses.map(a=>({analysis:a,polarity:polarity(a.content)})).filter(x=>x.polarity!=="neutral");if(withPolarity.length===0)return null;let tally={},totalWeight=0;for(let{analysis,polarity:pol}of withPolarity){let w=weights[analysis.specialistId];if(w!==void 0&&(typeof w!="number"||!Number.isFinite(w)||w<0))throw new ConsensusError(`invalid weight for specialist ${analysis.specialistId}`);let contribution=(w??1)*analysis.confidence;tally[pol]||(tally[pol]={weight:0,analysts:[]}),tally[pol].weight+=contribution,tally[pol].analysts.push(analysis.specialistId),totalWeight+=contribution}if(totalWeight===0)return null;let winner=null,winnerWeight=0;for(let pol of Object.keys(tally))tally[pol].weight>winnerWeight&&(winnerWeight=tally[pol].weight,winner=pol);if(!winner)return null;let supportRatio=winnerWeight/totalWeight;if(supportRatio<this.threshold)return null;let supportingAnalystIds=Array.from(new Set(tally[winner].analysts)),dissentingAnalystIds=Array.from(new Set(withPolarity.filter(x=>x.polarity!==winner).map(x=>x.analysis.specialistId).concat(options.minorityAnalystIds??[]))),problemConflicts=conflicts.filter(c=>c.problemId===problemId),conflictsResolved=problemConflicts.map(c=>c.id),openIssues=problemConflicts.filter(c=>c.severity==="high").map(c=>`High-severity conflict ${c.id} remains unresolved: ${c.description}`);return{problemId,decision:winner==="positive"?`Adopt the proposed action for problem ${problemId}.`:`Reject the proposed action for problem ${problemId}.`,confidence:supportRatio,supportingAnalystIds,dissentingAnalystIds,conflictsResolved,openIssues}}};function buildReport(input){if(!input||typeof input!="object")throw new CouncilError("input must be an object");if(typeof input.problemId!="string"||input.problemId.length===0)throw new CouncilError("input.problemId must be a non-empty string");if(!Array.isArray(input.analyses))throw new CouncilError("input.analyses must be an array");let conflicts=Array.isArray(input.conflicts)?input.conflicts:[],debates=Array.isArray(input.debates)?input.debates:[],minorityOpinions=Array.isArray(input.minorityOpinions)?input.minorityOpinions:[],recommendations=Array.isArray(input.recommendations)?input.recommendations:[],consensus=input.consensus===void 0?null:input.consensus,generatedAt=input.generatedAt??new Date().toISOString(),id=input.reportId??`report-${input.problemId}-${generatedAt}`,summary=summarize(input.problemId,input.analyses.length,conflicts.length,consensus);return{id,problemId:input.problemId,generatedAt,summary,analyses:[...input.analyses],conflicts:[...conflicts],debates:[...debates],minorityOpinions:[...minorityOpinions],consensus,recommendations:[...recommendations]}}function serializeReport(report){if(!report||typeof report!="object")throw new CouncilError("report must be an object");try{return JSON.stringify(report,null,2)}catch(err){throw new CouncilError(`failed to serialize report: ${err.message}`)}}function summarizeReport(report){if(!report||typeof report!="object")throw new CouncilError("report must be an object");let lines=[];if(lines.push(`Report ${report.id} for problem ${report.problemId} generated at ${report.generatedAt}.`),lines.push(`${report.analyses.length} analyses; ${report.conflicts.length} conflicts; ${report.debates.length} debates; ${report.minorityOpinions.length} minority opinions.`),lines.push(report.summary),report.consensus){let pct=(report.consensus.confidence*100).toFixed(1);lines.push(`Decision: ${report.consensus.decision} (confidence ${pct}%).`)}else lines.push("No consensus was reached.");return report.recommendations.length>0&&lines.push(`Recommendations: ${report.recommendations.join("; ")}.`),lines.join(" ")}function summarize(problemId,analysisCount,conflictCount,consensus){let parts=[];if(parts.push(`Problem ${problemId} received ${analysisCount} analysis${analysisCount===1?"":"ies"}.`),conflictCount>0?parts.push(`${conflictCount} conflict${conflictCount===1?"":"s"} detected.`):parts.push("No conflicts detected."),consensus){let pct=(consensus.confidence*100).toFixed(1);parts.push(`Consensus reached at confidence ${pct}%.`)}else parts.push("No consensus reached.");return parts.join(" ")}var DEFAULT_SYNTHESIS_THRESHOLD=.6,STRONG_CONSENSUS_RATIO=.8;function classifyConsensus(consensus,threshold=DEFAULT_SYNTHESIS_THRESHOLD){return consensus?consensus.dissentingAnalystIds.length===0?"unanimous":consensus.confidence>=STRONG_CONSENSUS_RATIO?"strong":consensus.confidence>=threshold?"majority":"split":"none"}function synthesize(problemId,consensus,analyses,conflicts=[],options={}){if(typeof problemId!="string"||problemId.length===0)throw new SynthesisError("problemId must be a non-empty string");if(!Array.isArray(analyses))throw new SynthesisError("analyses must be an array");if(!Array.isArray(conflicts))throw new SynthesisError("conflicts must be an array");if(consensus!==null&&(!consensus||typeof consensus!="object"))throw new SynthesisError("consensus must be an object or null");let threshold=options.threshold??DEFAULT_SYNTHESIS_THRESHOLD;if(typeof threshold!="number"||!Number.isFinite(threshold)||threshold<0||threshold>1)throw new SynthesisError("threshold must be a finite number in [0, 1]");let minorityOpinions=Array.isArray(options.minorityOpinions)?options.minorityOpinions:[],level=classifyConsensus(consensus,threshold),participants=Array.from(new Set(analyses.map(a=>a.specialistId))),decisionText=options.decision??consensus?.decision??`No actionable decision for problem ${problemId}; insufficient consensus.`,confidence=consensus?.confidence??0,rationaleParts=[];consensus?(rationaleParts.push(`Consensus reached with ${consensus.supportingAnalystIds.length} supporting and ${consensus.dissentingAnalystIds.length} dissenting (weighted support ${(consensus.confidence*100).toFixed(1)}%, level: ${level}).`),consensus.conflictsResolved.length>0&&rationaleParts.push(`${consensus.conflictsResolved.length} conflict${consensus.conflictsResolved.length===1?"":"s"} considered.`),consensus.openIssues.length>0&&rationaleParts.push(`Open issues: ${consensus.openIssues.join("; ")}`)):rationaleParts.push(`No consensus was reached across ${analyses.length} analysis${analyses.length===1?"":"ies"}.`),conflicts.length>0&&rationaleParts.push(`${conflicts.length} conflict${conflicts.length===1?"":"s"} taken into account.`),minorityOpinions.length>0&&rationaleParts.push(`${minorityOpinions.length} minority opinion${minorityOpinions.length===1?"":"s"} preserved on record.`);let generatedAt=options.generatedAt??new Date().toISOString();return{id:options.decisionId??`decision-${problemId}-${generatedAt}`,problemId,decision:decisionText,rationale:rationaleParts.join(" "),confidence,consensusLevel:level,participants,generatedAt}}export{AnalysisCollector,AnalysisError,CONFLICT_SEVERITIES,CONFLICT_TYPES,ConflictDetector,ConflictError,ConsensusBuilder,ConsensusError,ConsoleLogger,CouncilError,DEFAULT_CONSENSUS_THRESHOLD,DEFAULT_MAX_DEBATE_ROUNDS,DEFAULT_OUTLIER_THRESHOLD,DEFAULT_SYNTHESIS_THRESHOLD,DIVERGENT_CONTENT_MIN_OVERLAP,DIVERGENT_REASONING_MAX_OVERLAP,DebateError,DebateFacilitator,FACTUAL_OVERLAP_THRESHOLD,MinorityOpinionTracker,OPPOSING_CONFIDENCE_THRESHOLD,RoutingError,SCRUBBED_FIELD_NAMES,SEVERITY_HIGH_GAP,SEVERITY_MEDIUM_GAP,STRONG_CONSENSUS_RATIO,ScoringError,SilentLogger,SpecialistRegistry,SynthesisError,aggregateScores,buildReport,classifyConsensus,detectOutliers,matchScore,route,routeAll,scoreAnalysis,scrubMetadata,serializeReport,severityFor,shouldScrubField,summarizeReport,synthesize,validateAnalysis,validateMinorityOpinion,validateRound,validateSpecialist};
|
|
4
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/errors.ts", "../../src/logging.ts", "../../src/util.ts", "../../src/router/router.ts", "../../src/analysis/analysis.ts", "../../src/scoring/scoring.ts", "../../src/conflict/conflict.ts", "../../src/debate/debate.ts", "../../src/minority/minority.ts", "../../src/consensus/consensus.ts", "../../src/reports/reports.ts", "../../src/synthesizer/synthesizer.ts"],
|
|
4
|
+
"mappings": "AAWO,IAAM,aAAN,cAA2B,KAAM,CACtB,KACS,MACzB,YAAY,QAAiB,KAAe,MAAiB,CAC3D,MAAM,OAAO,EACb,KAAK,KAAO,WAAW,KACvB,KAAK,KAAO,MAAQ,gBAChB,QAAU,SAAW,KAAK,MAAQ,OACtC,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,aAAN,cAA2B,YAAa,CAC7C,YAAY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|
4
|
+
* The {@link AnalysisCollector} is a stateful store for {@link Analysis}
|
|
5
|
+
* objects. Analysts submit analyses; the collector validates, stores, and
|
|
6
|
+
* indexes them by problem id and specialist id for downstream consumption by
|
|
7
|
+
* the scoring, conflict, consensus, reports, and synthesizer modules.
|
|
8
|
+
*
|
|
9
|
+
* Copyright 2024 Manya Hael Foundation. All rights reserved.
|
|
10
|
+
* Licensed under the Apache License, Version 2.0.
|
|
11
|
+
*/
|
|
12
|
+
import type { Analysis } from '../types.js';
|
|
13
|
+
/**
|
|
14
|
+
* Validates an `Analysis` structurally. Throws `AnalysisError` on invalid
|
|
15
|
+
* fields.
|
|
16
|
+
*/
|
|
17
|
+
export declare function validateAnalysis(analysis: Analysis): void;
|
|
18
|
+
/**
|
|
19
|
+
* Stateful analysis collector. Submissions are validated, deduplicated by id,
|
|
20
|
+
* and indexed for fast lookup by problem id and specialist id.
|
|
21
|
+
*
|
|
22
|
+
* Usage:
|
|
23
|
+
* ```ts
|
|
24
|
+
* const collector = new AnalysisCollector();
|
|
25
|
+
* collector.submit({ id: 'a1', specialistId: 'sec', problemId: 'p1',
|
|
26
|
+
* content: 'I recommend we adopt the proposal.', confidence: 0.85,
|
|
27
|
+
* reasoning: 'The proposal is sound.', caveats: ['assumes budget'] });
|
|
28
|
+
* collector.getAll('p1'); // [analysis]
|
|
29
|
+
* collector.getBySpecialist('sec'); // [analysis]
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare class AnalysisCollector {
|
|
33
|
+
private readonly analyses;
|
|
34
|
+
private readonly order;
|
|
35
|
+
private readonly byProblem;
|
|
36
|
+
private readonly bySpecialist;
|
|
37
|
+
/**
|
|
38
|
+
* Validates and stores `analysis`. Throws `AnalysisError` when the analysis
|
|
39
|
+
* is malformed or an analysis with the same id has already been submitted.
|
|
40
|
+
*/
|
|
41
|
+
submit(analysis: Analysis): this;
|
|
42
|
+
/** Returns the analysis with the given id, or `undefined`. */
|
|
43
|
+
get(id: string): Analysis | undefined;
|
|
44
|
+
/** Returns all analyses for the given problem, in submission order. */
|
|
45
|
+
getAll(problemId: string): Analysis[];
|
|
46
|
+
/** Returns all analyses by the given specialist, in submission order. */
|
|
47
|
+
getBySpecialist(specialistId: string): Analysis[];
|
|
48
|
+
/** Returns all analyses in submission order. */
|
|
49
|
+
list(): Analysis[];
|
|
50
|
+
/** Returns the number of analyses stored. */
|
|
51
|
+
size(): number;
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=analysis.d.ts.map
|