@factbag/jev 0.0.0-alpha.5

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 ADDED
@@ -0,0 +1,33 @@
1
+ # @factbag/jev
2
+
3
+ ## 0.0.0-alpha.5
4
+
5
+ ### Minor Changes
6
+
7
+ - 19ac508: **Breaking:** Jev moves from `factbag/jev` to its own package, `@factbag/jev`. Install it alongside `factbag` and `@typesafe-ai/sdk`, which is now a required peer dependency at `^0.7.0`, and import `classifier`, `resolver`, `createConfig`, `Config`, and the `DEFAULT_*` constants from `@factbag/jev`. `factbag` no longer has a Jev entry point or an SDK peer dependency. `@factbag/jev` and `@factbag/clef` are released together with `factbag` and require the same `factbag` version.
8
+
9
+ **Breaking:** `@factbag/jev` has a single entry point. `factbag/jev/classifier`, `factbag/jev/resolve`, `factbag/jev/config`, and `factbag/jev/errors` have no replacement subpaths.
10
+
11
+ Add `batchSize` to Jev's `Config`: how many questions each request holds. It defaults to 64 and has no upper limit. An invalid `batchSize` throws when the config is created or a run is built.
12
+
13
+ Jev's `createConfig` now returns `Normalized & Config`, so `client` is no longer guaranteed on the result.
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [19ac508]
18
+ - Updated dependencies [19ac508]
19
+ - Updated dependencies [dd3730b]
20
+ - factbag@0.0.0-alpha.5
21
+
22
+ ## 0.1.0-next.0
23
+
24
+ ### Minor Changes
25
+
26
+ - Publish the initial experimental Factbag packages with native Node ESM artifacts and declarations.
27
+
28
+ ### Patch Changes
29
+
30
+ - Updated dependencies
31
+ - @factbag/core@0.1.0-next.0
32
+ - @factbag/corpus@0.1.0-next.0
33
+ - @factbag/guards@0.1.0-next.0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Daniel du Plessis
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,278 @@
1
+ # @factbag/jev
2
+
3
+ `classifier({ corpus, input: kb, config })` returns a lazy iterator of executable
4
+ classification jobs, one per chunk. Constructing and consuming the iterator makes **no remote calls**. The caller
5
+ decides when to execute each job and how much work to run concurrently.
6
+
7
+ The package has one entry point, `@factbag/jev`, which exports:
8
+
9
+ - `classifier({ corpus, input: kb, config? })`
10
+ - `resolver(corpus, kb, config?)`
11
+ - `createConfig`, `Config`, and the `DEFAULT_*` constants
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install factbag@alpha @factbag/jev@alpha @typesafe-ai/sdk@^0.7.0
17
+ ```
18
+
19
+ `@factbag/jev` is released with `factbag` and needs the same `factbag` version.
20
+ Set `TYPESAFE_API_KEY`, or pass your own `TypeSafeClient` as `config.client`.
21
+
22
+ ## Usage
23
+
24
+ ```ts
25
+ import { enumeration, predicate } from "factbag/dsl";
26
+ import { KnowledgeBase } from "factbag/kb";
27
+ import { Corpus } from "factbag/corpus";
28
+ import { guard } from "factbag/kb";
29
+ import { classifier } from "@factbag/jev";
30
+
31
+ class Company {
32
+ constructor(
33
+ readonly id: string,
34
+ readonly tradingName: string,
35
+ ) {}
36
+ }
37
+
38
+ const status = predicate(
39
+ "company_status",
40
+ {
41
+ company: Company,
42
+ status: enumeration("active", "dissolved"),
43
+ },
44
+ {
45
+ description: "The document explicitly establishes this company's legal status.",
46
+ },
47
+ );
48
+
49
+ const kb = new KnowledgeBase();
50
+ kb.entities.add(new Company("company-42", "Harbor"));
51
+ const corpus = new Corpus();
52
+ corpus.add({ documentId: "registry", text: "Harbor is an active company." });
53
+
54
+ // The default TypeSafeClient reads TYPESAFE_API_KEY on the first execute().
55
+ const run = classifier({
56
+ corpus,
57
+ input: guard(kb).permit("assert", status).permit("deny", status),
58
+ });
59
+
60
+ for (const job of run) {
61
+ await job.execute();
62
+ // The consumer may await persistence or a rate limiter here.
63
+ }
64
+
65
+ const enriched = run.kb;
66
+ // kb is unchanged. enriched contains the original knowledge plus new evidence.
67
+ ```
68
+
69
+ ## Boundary and registration
70
+
71
+ Classification and resolution share one optional, flat `Config`. Create it once
72
+ with `createConfig` to share one lazy client across runs:
73
+
74
+ ```ts
75
+ const config = createConfig({ client, minimumProbability: 0.6 });
76
+ const classified = classifier({ corpus, input: kb, config });
77
+ const resolved = resolver(corpus, classified.kb, config);
78
+ ```
79
+
80
+ Admission defaults to `{ minimumProbability: 0.4, ambiguityMargin: 0 }`:
81
+ the strongest ASSERT/DENY outcome must reach 0.4 and outrank IRRELEVANT. An exact
82
+ ASSERT/DENY tie admits both. These are convenience defaults, not calibrated probabilities.
83
+ A plainly worded record often scores in the 0.45-0.65 band, so 0.5 loses evidence a reader
84
+ would call clear; a lower bar writes more, and contradictions surface rather than gaps.
85
+
86
+ ```ts
87
+ classifier({ corpus, input: kb });
88
+ classifier({ corpus, input: kb, config: { client } });
89
+ classifier({ corpus, input: kb, config: { minimumProbability: 0.8, ambiguityMargin: 0.05 } });
90
+ ```
91
+
92
+ - A **guarded KB** retains its exact permit/block policy. `guard(kb)` is default-deny.
93
+ - A **bare KB** permits assert/deny for all predicates referenced in its
94
+ evidence and rules, including rule bodies. There is no global predicate registry.
95
+ - Query permissions do not make a predicate classifiable.
96
+ - Every exposed predicate is validated synchronously during `classifier(...)`.
97
+ Unsupported predicates fail even if the corpus is empty; blocked predicates are
98
+ not registered.
99
+
100
+ `UnsupportedPredicateError` (from `factbag/exceptions`) identifies the predicate and, where applicable, the
101
+ field that cannot be classified. A nonempty metadata description is required.
102
+
103
+ Supported field domains:
104
+
105
+ | Schema field | Candidate values |
106
+ | -------------------------- | ---------------------------------------- |
107
+ | `Boolean` | `false`, `true` |
108
+ | `enumeration(...)` | Explicit string, number, or Date members |
109
+ | Entity constructor | Instances registered in `kb.entities` |
110
+ | `String`, `Number`, `Date` | Unsupported open-ended domains |
111
+
112
+ An entity domain must contain registered instances. Existing scalar facts do not
113
+ turn an open-ended schema into an enum. To model a fixed value, declare it explicitly
114
+ with `enumeration(value)` rather than asking the classifier to discover it.
115
+
116
+ Number and Date enumerations, such as `enumeration(10, 20)` or
117
+ `enumeration(new Date("2026-10-25T00:00:00Z"))`, are classified like string
118
+ enumerations. Dates are sent to the model as ISO strings and retained as `Date`
119
+ values in evidence. The same date in two fields is a valid candidate; only
120
+ repeated entities are excluded.
121
+
122
+ Entity candidates include their enumerable properties, including `id`, plus `type`
123
+ set to the constructor name. They are JSON-encoded when each request is built:
124
+ nested properties are included, dates become ISO strings, and methods are not sent.
125
+ For example, the company above is sent as
126
+ `{ type: "Company", id: "company-42", tradingName: "Harbor" }`.
127
+ Evidence continues to reference the original registered entity. Related KB facts
128
+ are not automatically included in the entity payload.
129
+
130
+ Fields fan out as a Cartesian product. A predicate with no fields has one candidate
131
+ proposition. Every candidate gets an independent `Choice(ASSERT, DENY, IRRELEVANT)`
132
+ question. Assert and deny permissions for the same predicate share one question.
133
+ No enum exclusivity or Boolean equivalence is assumed; those belong to the ruleset.
134
+
135
+ ## Jobs and execution
136
+
137
+ `run` is a single-cursor `IterableIterator`. Each yielded job classifies one chunk
138
+ and exposes only `execute(): Promise<void>`, sending up to `batchSize` questions per
139
+ request. `batchSize` defaults to 64. TypeSafe sets no upper limit. Re-executing a job makes a fresh attempt; a repeated
140
+ success adds fresh evidence.
141
+
142
+ The consumer can execute jobs sequentially, in batches, or through a concurrency
143
+ limiter. Jobs contain no scheduler, rate limiter, retry loop, or error handler.
144
+ `config.client` is optional and defaults to `new TypeSafeClient()`, created on the
145
+ first request. Pass a configured client to set the model, retry, timeout or
146
+ transport, or a scripted one in tests.
147
+
148
+ Request errors propagate unchanged from `execute()`. All answers for a chunk are
149
+ validated before any of that chunk's evidence is written. A failure does not
150
+ terminate the job iterator, remove earlier evidence, or retry automatically.
151
+ The caller can retry the same job or advance to another job.
152
+
153
+ `run.kb` is a live output store. Concurrent jobs add evidence in completion order.
154
+ Existing evidence, rules and entities retain their identities, but the storage
155
+ containers are independent of the input KB. Candidate domains use the construction-
156
+ time KB snapshot; new evidence does not introduce new candidates during a run.
157
+
158
+ ## Corpus traversal
159
+
160
+ The classifier reads the whole corpus: every document present at construction
161
+ time. There is no source selection; to classify a subset, pass a
162
+ filtered view such as `corpus.filter((document) => document.metadata["kind"] !== "structured")`.
163
+ Its chunks register in the shared corpus, so evidence resolves from any handle. The adapter always uses a private recursive
164
+ splitter: up to **8,000 Unicode graphemes**, with up to
165
+ **200 graphemes of overlap**, preferring paragraph, line, and word boundaries.
166
+ Short documents remain intact. Jev constructs `chunkers.recursive()` internally;
167
+ source ranges and jobs are produced as iteration advances. The chunker indexes
168
+ the current document's grapheme boundaries when iteration starts.
169
+
170
+ Overlap supplies neighboring context. There is no configurable chunker or context
171
+ expansion step on the classifier API.
172
+
173
+ This is a conservative text-sizing policy, not an exact token budget. Jev 1.13's
174
+ [documented limits](https://docs.typesafe.ai/models) are 32k tokens for state plus
175
+ the longest question and 64k for the whole request. Candidate state, metadata and
176
+ questions also consume that budget; this passage bound alone does not guarantee
177
+ that arbitrarily large candidate batches fit.
178
+
179
+ Requests carry only the passage text. Chunk IDs, document IDs and source ranges are
180
+ kept out of them, so document names and coordinates cannot influence the model.
181
+
182
+ Each evidence source is the exact consumed chunk ID, resolvable through `corpus.resolve(source)`. The ID encodes the document and
183
+ range, and document text is immutable.
184
+
185
+ ## Admission and results
186
+
187
+ - When `IRRELEVANT` is at least as probable as either polarity, admit neither.
188
+ - Otherwise, a polarity must meet `minimumProbability` and fall within
189
+ `ambiguityMargin` of the stronger polarity.
190
+ - Only permitted polarities are inserted. Forbidden outcomes are not relabeled or
191
+ renormalized into permitted ones.
192
+ - Both polarities can be admitted, preserving evidence that needs review.
193
+
194
+ New literals carry source, outcome probability,
195
+ candidate IDs, selected choice, SDK confidence, and the full distribution. SDK confidence remains separate from outcome probability. These
196
+ thresholds are application policy, not calibrated defaults.
197
+
198
+ ## Optional relevance filtering
199
+
200
+ Set `config: { routing: true }` to reduce the candidate facts sent for classification
201
+ by filtering predicates and values for relevance to each passage. Each chunk job
202
+ first asks which predicates the passage may bear on. For predicates that make claims
203
+ about supplied entities or values, it can also ask which of those symbols the passage
204
+ involves. For example, before classifying ownership claims, it can narrow the list
205
+ of companies to those relevant to the passage. Only combinations of the retained
206
+ symbols are classified.
207
+
208
+ Symbol filtering runs when a retained predicate has symbols to filter and its
209
+ candidate combinations exceed `candidateProductCutoff` (default 16). Each distinct
210
+ symbol is checked once across all surviving predicates and roles. Boolean field
211
+ values are always retained. `predicateThreshold` and `symbolThreshold`
212
+ (default 0.3) are inclusive.
213
+
214
+ Filtering is **off by default**: a false negative in either pass silently drops
215
+ evidence, including denials. Filtering adds requests and does not guarantee cost savings. Run
216
+ `pnpm --filter @factbag/jev demo:staged` to compare both modes on a scripted fixture.
217
+
218
+ ## Resolving contradictions
219
+
220
+ Each chunk is classified on its own, so a 2012 removal notice and a 2022
221
+ redesignation can leave the same fact asserted and denied. `resolver` reads those
222
+ passages together and asks, for each one, whether its account still stands. It works
223
+ like `classifier`: construction makes no remote calls, and each job is one request.
224
+
225
+ ```ts
226
+ import { resolver } from "@factbag/jev";
227
+
228
+ const resolution = resolver(corpus, run.kb);
229
+ for (const job of resolution) {
230
+ await job.execute();
231
+ }
232
+ const resolved = resolution.kb;
233
+ ```
234
+
235
+ - There is one job per atom with evidence of both signs. Its `execute()` sends
236
+ every distinct source passage in one request with a KEEP/RETRACT
237
+ question per passage: does another passage supersede this one for the fact as
238
+ described, including any date it is stated as of? Disagreement alone is not
239
+ supersession, so two documents that merely conflict both stand.
240
+ - The model judges documents, not the fact. Evidence from a retracted passage is removed
241
+ from `resolution.kb`; the rest stays, and the solver decides what the surviving
242
+ evidence means. Retracting every passage leaves the fact `unknown`, which is right:
243
+ the evidence was withdrawn, not disproved.
244
+ - A passage is retracted only when RETRACT reaches `minimumProbability` and leads KEEP by
245
+ more than `ambiguityMargin` (defaults 0.4 and 0). With two outcomes that means RETRACT must
246
+ exceed 0.5 in practice, whatever the minimum. Keeping the evidence is the default,
247
+ so an uncertain answer changes nothing.
248
+ - Every piece of conflicting evidence must have a `source` that resolves in the corpus.
249
+ Construction throws for evidence without a source, naming the atom, and propagates
250
+ corpus errors such as `Invalid chunk ID`, so no job exists until all are readable.
251
+ To resolve a KB with stipulated or tool-sourced evidence, decide those contradictions
252
+ first or resolve a fork without them.
253
+ - `resolution.kb` is an independent copy of the input, which is unchanged.
254
+ Contradictions are independent, so jobs can run in any order or concurrently.
255
+ - A job settles once. Request errors propagate unchanged and leave the job retryable;
256
+ executing it again after it succeeds throws. `config.client` defaults to
257
+ `new TypeSafeClient()`, as for the classifier.
258
+
259
+ ## Internal structure
260
+
261
+ This package only connects Jev to the shared workflows in `@factbag/system-one`:
262
+ the TypeSafe client, Jev's batch limits, and the public signatures. Candidate
263
+ selection, admission, prompts, batching, and answer validation live there and are
264
+ bundled into the published package. The same code serves `@factbag/clef`.
265
+
266
+ ## Examples and checks
267
+
268
+ Read [Fix one fact, not the whole answer](https://github.com/factbag/factbag/blob/main/providers/jev/docs/README.md) for the narrative, or the
269
+ [example notes](https://github.com/factbag/factbag/blob/main/providers/jev/examples/README.md) for the runnable scenarios.
270
+
271
+ ```sh
272
+ pnpm --filter @factbag/jev demo
273
+ pnpm --filter @factbag/jev test
274
+ pnpm --filter @factbag/jev typecheck
275
+ ```
276
+
277
+ Demos use the real SDK with MSW HTTP interception; focused unit tests also use
278
+ injected clients. Neither needs credentials or live inference.
@@ -0,0 +1,79 @@
1
+ import { GuardedKB, KnowledgeBase } from "factbag/kb";
2
+ import { Corpus, Metadata } from "factbag/corpus";
3
+ import { TypeSafeClient } from "@typesafe-ai/sdk";
4
+ /** Default minimum probability for admitting signed evidence. @beta */
5
+ export declare const DEFAULT_MINIMUM_PROBABILITY = .4;
6
+ /** Default maximum probability gap from the strongest signed outcome. @beta */
7
+ export declare const DEFAULT_AMBIGUITY_MARGIN = 0;
8
+ /** Whether heuristic predicate and symbol filtering is enabled by default. @beta */
9
+ export declare const DEFAULT_ROUTING_ENABLED: boolean;
10
+ /** Default inclusive probability threshold for retaining a predicate. @beta */
11
+ export declare const DEFAULT_PREDICATE_THRESHOLD = .3;
12
+ /** Default inclusive probability threshold for retaining a symbol. @beta */
13
+ export declare const DEFAULT_SYMBOL_THRESHOLD = .3;
14
+ /** Default candidate product size above which symbol filtering runs. @beta */
15
+ export declare const DEFAULT_CANDIDATE_PRODUCT_CUTOFF = 16;
16
+ /** How classification and resolution use a model's answers, whichever model gives them. @beta */
17
+ type Settings = {
18
+ /** Minimum probability for admitting signed evidence or retracting a passage, default 0.4. */
19
+ readonly minimumProbability?: number;
20
+ /** Classification: maximum gap from the strongest signed outcome. Resolution: required RETRACT lead over KEEP. Default 0. */
21
+ readonly ambiguityMargin?: number;
22
+ /** Enable heuristic predicate and symbol filtering, default false. */
23
+ readonly routing?: boolean;
24
+ /** Inclusive probability at which a predicate is kept for a passage, default 0.3. */
25
+ readonly predicateThreshold?: number;
26
+ /** Inclusive probability at which a symbol is kept for a passage, default 0.3. */
27
+ readonly symbolThreshold?: number;
28
+ /** Run symbol filtering if a retained predicate with non-Boolean roles exceeds this raw Cartesian product, default 16. */
29
+ readonly candidateProductCutoff?: number;
30
+ /** Questions per request when work can be split, up to the provider's limit. Defaults to the provider's choice. */
31
+ readonly batchSize?: number;
32
+ };
33
+ /** Settings with every default applied. @beta */
34
+ type Normalized = Readonly<Required<Settings>>;
35
+ /** One opaque unit of work. Its effects are written to the run’s knowledge base. @beta */
36
+ type Job = {
37
+ readonly execute: () => Promise<void>;
38
+ };
39
+ /** A single-cursor stream of jobs sharing an independent output knowledge base. @beta */
40
+ type Run = IterableIterator<Job> & {
41
+ readonly kb: KnowledgeBase;
42
+ };
43
+ /**
44
+ * Jev settings. Model, timeout, and retry settings belong to the SDK client. `batchSize`
45
+ * defaults to 64 questions per request; TypeSafe sets no upper limit.
46
+ *
47
+ * @beta
48
+ */
49
+ export type Config = Settings & {
50
+ /** Defaults to a lazy TypeSafeClient configured from TYPESAFE_* environment variables. */
51
+ readonly client?: TypeSafeClient;
52
+ };
53
+ /** Normalize settings once, sharing a lazy SDK client when reused across runs. @beta */
54
+ export declare function createConfig(config?: Config): Normalized & Config;
55
+ /**
56
+ * Parse corpus evidence into a new knowledge base using guarded predicate operations.
57
+ * Validate available predicates eagerly and return a lazy iterator of executable jobs.
58
+ * Bare KBs expose all known predicates; explicit guards retain their permission policy.
59
+ * Only job.execute() makes a remote call. The consumer owns pacing and concurrency.
60
+ * @beta
61
+ */
62
+ export declare function classifier<M extends Metadata = Metadata>(input: {
63
+ corpus: Corpus<M>;
64
+ input: KnowledgeBase | GuardedKB;
65
+ config?: Config;
66
+ }): Run;
67
+ /**
68
+ * Settle contradictions in a knowledge base by reading each one's evidence together.
69
+ * Find every atom with evidence of both signs and return a lazy iterator of jobs, one per
70
+ * contradiction. Each job sends all of the contradiction's passages to Jev in one request
71
+ * and asks, for each passage, whether its account still stands. Evidence from superseded
72
+ * passages is retracted from `kb`; the rest is kept, so the solver decides what the
73
+ * surviving evidence means. The input KB is not modified. Throws during construction if
74
+ * conflicting evidence has no source, and propagates corpus errors for sources that are not
75
+ * resolvable chunk IDs. The consumer owns pacing and concurrency.
76
+ * @beta
77
+ */
78
+ export declare function resolver<M extends Metadata = Metadata>(corpus: Corpus<M>, kb: KnowledgeBase, config?: Config): Run;
79
+ export type { Job, Normalized, Run, Settings };