@loomwork/knowledge 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +72 -2
- package/dist/KnowledgeBase.d.ts +212 -0
- package/dist/KnowledgeBase.d.ts.map +1 -0
- package/dist/KnowledgeBase.js +394 -0
- package/dist/KnowledgeBase.js.map +1 -0
- package/dist/chunk.d.ts +18 -0
- package/dist/chunk.d.ts.map +1 -0
- package/dist/chunk.js +44 -0
- package/dist/chunk.js.map +1 -0
- package/dist/citations.d.ts +45 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +76 -0
- package/dist/citations.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/prompt.d.ts +41 -0
- package/dist/prompt.d.ts.map +1 -0
- package/dist/prompt.js +47 -0
- package/dist/prompt.js.map +1 -0
- package/dist/types.d.ts +94 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +57 -3
- package/src/KnowledgeBase.ts +489 -0
- package/src/chunk.ts +41 -0
- package/src/citations.ts +88 -0
- package/src/index.ts +16 -0
- package/src/prompt.ts +56 -0
- package/src/types.ts +97 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/knowledge — document corpora over memory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A corpus of documents you ingest, revise, delete and retrieve passages from, built on the memory seam. There
|
|
4
|
+
is no `knowledge$` construct and no separate embedding interface (ADR 0090): this package owns the one thing
|
|
5
|
+
a `MemoryStore` cannot, which is the mapping from a document (what you edit) to its passages (what you
|
|
6
|
+
search). Re-ingesting a revised document supersedes its old passages instead of indexing both. Use it for
|
|
7
|
+
retrieval-augmented answers over a runbook, wiki or policy set. `app.knowledge(scope)` opens one over the
|
|
8
|
+
same `memoryStore` that backs `app.memory`.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { InMemoryMemoryStore } from "@loomwork/memory";
|
|
12
|
+
import { assertGrounded, groundedRequest, openKnowledgeBase } from "@loomwork/knowledge";
|
|
13
|
+
import type { ExecutionContext } from "@loomwork/workflow-runtime";
|
|
14
|
+
|
|
15
|
+
const kb = openKnowledgeBase(new InMemoryMemoryStore(), { scope: "runbooks" });
|
|
16
|
+
|
|
17
|
+
// `sync` takes the COMPLETE set: new or changed documents are written, absent ones are removed.
|
|
18
|
+
await kb.sync([
|
|
19
|
+
{ id: "restart-db", title: "Restarting the database", text: "Drain connections first.\n\nThen restart." },
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
export async function ask(ctx: ExecutionContext, question: string) {
|
|
23
|
+
// `decide` is required: the retrieved passages are recorded, so a replay rebuilds the same prompt.
|
|
24
|
+
const passages = await kb.retrieve(question, { decide: ctx.decide, limit: 4 });
|
|
25
|
+
// Passages go in fenced user messages, never the system prompt.
|
|
26
|
+
const request = groundedRequest({ instructions: "Answer from the passages only.", question, passages });
|
|
27
|
+
// After the model answers, check the document ids it cited: throws for one it was never shown.
|
|
28
|
+
const cited = assertGrounded(["restart-db"], passages);
|
|
29
|
+
return { request, cited };
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Surface
|
|
34
|
+
|
|
35
|
+
- **Corpus.** `openKnowledgeBase(store, { scope, tier?, chunker?, origin? })`, or `new KnowledgeBase({ memory,
|
|
36
|
+
scope, ... })` over a `TieredMemory` you share with something else. Methods: `putDoc` (upsert), `sync`,
|
|
37
|
+
`planSync` (dry run, same result shape), `removeDoc`, `listDocs`, `retrieve`.
|
|
38
|
+
- **Chunking.** `packParagraphs(maxChars = 1000)` is the default: split on blank lines, then pack. Pass
|
|
39
|
+
your own `Chunker` for structured text.
|
|
40
|
+
- **Prompt boundary.** `groundedRequest` and `passageMessages` build the request; `checkCitations`,
|
|
41
|
+
`assertGrounded` and `UngroundedCitationError` check which documents an answer claims.
|
|
42
|
+
- **Types.** `KnowledgeDoc` (`id`, `title?`, `text`, `meta?`), `Passage`, `DocRecord`, `SyncResult`
|
|
43
|
+
(`written`, `unchanged`, `removed`, `retained`), `SourceOptions`, `RetrieveOptions`.
|
|
44
|
+
- **CLI.** `loom knowledge` operates a corpus from the command line.
|
|
45
|
+
|
|
46
|
+
## Behaviour that surprises people
|
|
47
|
+
|
|
48
|
+
- **Passage text is tainted at ingest** (ADR 0085) and stays tainted into the model request, so
|
|
49
|
+
`guardRequest` refuses it in a system prompt. That is why `groundedRequest` types `instructions` as a
|
|
50
|
+
plain string and sends one `user` message per passage.
|
|
51
|
+
- **`sync` is a destructive reconcile.** Passing a subset removes every other document of that writer.
|
|
52
|
+
Unchanged documents are skipped by fingerprint over title, text and `meta`.
|
|
53
|
+
- **One document, one writer.** Pass `{ source }` to name a writer; a `sync` leaves other sources'
|
|
54
|
+
documents alone and reports them as `retained`, and `putDoc` on a document another writer owns throws.
|
|
55
|
+
- **The tier must not evict.** A tier with `ttlMs` or `maxEntries` is refused at construction, and
|
|
56
|
+
`app.knowledge` throws if a `memory$` with those limits shares the tier. Use `semantic` (the default) or
|
|
57
|
+
`procedural`, or give the corpus its own tier.
|
|
58
|
+
- **Retrieval records content, not ids**, so a replay still works after the document behind a passage was
|
|
59
|
+
revised. `assertGrounded` compares exact document ids and does not judge whether a claim follows from a
|
|
60
|
+
passage.
|
|
61
|
+
- **`putDoc` is crash-safe by write order** (an uncommitted manifest row first), so a crash converges on a
|
|
62
|
+
rewrite instead of a document that the status views call present but that has no passages.
|
|
63
|
+
|
|
64
|
+
## Install
|
|
65
|
+
|
|
66
|
+
Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
|
|
67
|
+
|
|
68
|
+
## See also
|
|
69
|
+
|
|
70
|
+
- API reference: section "`@loomwork/knowledge` — a corpus over the memory seam" in [docs/api-reference.org](../../docs/api-reference.org). It shows `openKnowledgeBase(config)`; the source takes `(store, options)`.
|
|
71
|
+
- Guide: [user guide, section 8: intent, planner and memory](../../docs/user-guide.md#8-intent-planner--memory).
|
|
72
|
+
- ADRs: [0090 knowledge is retrieval over memory](../../docs/adr/0090-knowledge-is-retrieval-over-memory.md), [0091 corpus lifecycle](../../docs/adr/0091-corpus-lifecycle-and-the-knowledge-package.md), [0085 untrusted content](../../docs/adr/0085-untrusted-content-integrity-axis.md).
|
|
73
|
+
- Source: `packages/knowledge/src`. Storage and tiers: [`@loomwork/memory`](../memory/README.md).
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { TieredMemory } from "@loomwork/memory";
|
|
2
|
+
import type { MemoryStore } from "@loomwork/memory";
|
|
3
|
+
import type { Chunker, DocRecord, KnowledgeDoc, Passage } from "./types";
|
|
4
|
+
/** The `decide` a retrieval is recorded through — structurally `ctx.decide`. */
|
|
5
|
+
export type DecideFn = <T>(key: string, compute: () => Promise<T> | T) => Promise<T>;
|
|
6
|
+
export interface KnowledgeBaseConfig {
|
|
7
|
+
/** The memory the corpus lives in. Its tier must not evict — see {@link KnowledgeBase}. */
|
|
8
|
+
memory: TieredMemory;
|
|
9
|
+
/** Names this corpus within the tier. One knowledge base, one scope. */
|
|
10
|
+
scope: string;
|
|
11
|
+
/** Defaults to `"semantic"` — the tier that never evicts. */
|
|
12
|
+
tier?: string;
|
|
13
|
+
/** Defaults to {@link packParagraphs}. */
|
|
14
|
+
chunker?: Chunker;
|
|
15
|
+
/**
|
|
16
|
+
* The provenance label stamped on every passage's taint, shown to the model when
|
|
17
|
+
* `guardRequest` fences the content. Defaults to `knowledge:<scope>:<docId>`.
|
|
18
|
+
*/
|
|
19
|
+
origin?: (doc: KnowledgeDoc) => string;
|
|
20
|
+
}
|
|
21
|
+
export interface RetrieveOptions {
|
|
22
|
+
/** REQUIRED — `ctx.decide`. See {@link KnowledgeBase.retrieve}. */
|
|
23
|
+
decide: DecideFn;
|
|
24
|
+
limit?: number;
|
|
25
|
+
/** Overrides the recorded decision key. Defaults to the tier/scope/query triple. */
|
|
26
|
+
decisionKey?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface SyncResult {
|
|
29
|
+
/** Documents written because they were new or their fingerprint changed. */
|
|
30
|
+
written: string[];
|
|
31
|
+
/** Documents already present at the same fingerprint — not rewritten. */
|
|
32
|
+
unchanged: string[];
|
|
33
|
+
/** Documents removed because the source no longer lists them. */
|
|
34
|
+
removed: string[];
|
|
35
|
+
/**
|
|
36
|
+
* Documents left alone because another writer owns them (see {@link DocRecord.source}).
|
|
37
|
+
*
|
|
38
|
+
* Reported rather than silent: "your sync deleted nothing" and "your sync protected four
|
|
39
|
+
* documents it does not own" describe very different corpora, and only one of them is
|
|
40
|
+
* something an operator should stop noticing in a nightly job's output.
|
|
41
|
+
*/
|
|
42
|
+
retained: string[];
|
|
43
|
+
}
|
|
44
|
+
/** Names the writer a call speaks for. Omitted means the corpus's default writer. */
|
|
45
|
+
export interface SourceOptions {
|
|
46
|
+
source?: string;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A document corpus over a memory tier: ingest, revise, delete, retrieve — with the
|
|
50
|
+
* provenance and the recorded retrieval that make the result usable in a prompt.
|
|
51
|
+
*
|
|
52
|
+
* ## What this is not
|
|
53
|
+
*
|
|
54
|
+
* It is not a construct, an SPI, or a retrieval engine. Ranking is the `MemoryStore`'s
|
|
55
|
+
* (FTS5, `tsvector`, cosine — whichever backend is configured), reproducibility is
|
|
56
|
+
* `ctx.decide`'s, safety is ADR 0085's, and the corpus is an ordinary `semantic` tier
|
|
57
|
+
* anyone can read with `recall`. What lives here is the one thing none of those provide:
|
|
58
|
+
* the mapping from a DOCUMENT — the unit a corpus is edited in — to the PASSAGES it is
|
|
59
|
+
* searched in, so that revising a document supersedes its old passages instead of
|
|
60
|
+
* duplicating them.
|
|
61
|
+
*
|
|
62
|
+
* ## The tier must not evict
|
|
63
|
+
*
|
|
64
|
+
* A corpus is kept until someone deletes it, so the tier it lives in must have no `ttlMs`
|
|
65
|
+
* and no `maxEntries`. Under eviction, the store would drop passages the manifest still
|
|
66
|
+
* counts, and a document would silently retrieve as a fragment of itself. `semantic` and
|
|
67
|
+
* `procedural` are unbounded by default, which is exactly why they are the tiers a corpus
|
|
68
|
+
* belongs in — and the constructor refuses a bounded one rather than letting it rot.
|
|
69
|
+
*
|
|
70
|
+
* ## Two scopes
|
|
71
|
+
*
|
|
72
|
+
* Passages live in `scope`; the manifest lives in `scope::docs`, one small row per
|
|
73
|
+
* document. They are separate because they are searched differently: a manifest row in
|
|
74
|
+
* the corpus would be an entry that matches queries and answers nothing.
|
|
75
|
+
*/
|
|
76
|
+
export declare class KnowledgeBase {
|
|
77
|
+
private readonly memory;
|
|
78
|
+
private readonly tier;
|
|
79
|
+
private readonly scope;
|
|
80
|
+
private readonly manifestScope;
|
|
81
|
+
private readonly chunker;
|
|
82
|
+
private readonly origin;
|
|
83
|
+
constructor(config: KnowledgeBaseConfig);
|
|
84
|
+
/** `docId#index` — derived, never stored, so a document's passage ids are its count. */
|
|
85
|
+
private passageId;
|
|
86
|
+
private fingerprint;
|
|
87
|
+
private toPassages;
|
|
88
|
+
/**
|
|
89
|
+
* What is actually WRITTEN for a passage: its `text`, and its `title`/`meta` if any.
|
|
90
|
+
*
|
|
91
|
+
* `docId` and `index` are deliberately NOT stored, because a store indexes the string
|
|
92
|
+
* and number leaves of `content` — so storing them would make a document's own id a term
|
|
93
|
+
* matching all of its passages, and the chunk ordinal a term matching the first passage
|
|
94
|
+
* of every document in the corpus. That is the same widening that made a tainted value's
|
|
95
|
+
* `origin` unindexable (ADR 0090), and the same rule the SPI states for `MemoryEntry.id`.
|
|
96
|
+
*
|
|
97
|
+
* They are not lost: the entry id IS `docId#index`, ids are required to round-trip
|
|
98
|
+
* (SPI 2.0.0), and ids are not indexed. The requirement earns its keep twice.
|
|
99
|
+
*/
|
|
100
|
+
private storedPassage;
|
|
101
|
+
/**
|
|
102
|
+
* The tiered memory the corpus lives in, for a caller that also wants to `recall` it,
|
|
103
|
+
* point a second corpus at the same store, or inspect it from ops code.
|
|
104
|
+
*/
|
|
105
|
+
get tieredMemory(): TieredMemory;
|
|
106
|
+
/** `docId#revision` — a manifest row's id. Rows are appended; the highest revision wins. */
|
|
107
|
+
private rowId;
|
|
108
|
+
/**
|
|
109
|
+
* The manifest: the live record per document, plus every row id currently standing for
|
|
110
|
+
* it so superseded rows can be pruned.
|
|
111
|
+
*
|
|
112
|
+
* One read of a small scope — rows are ids, counts and hashes, never passage text — which
|
|
113
|
+
* is what keeps `sync` proportional to the number of DOCUMENTS rather than to the size of
|
|
114
|
+
* the corpus. Read order is append order (the SPI guarantees it), so the last row for a
|
|
115
|
+
* document is the live one.
|
|
116
|
+
*/
|
|
117
|
+
private manifest;
|
|
118
|
+
private appendRecord;
|
|
119
|
+
/**
|
|
120
|
+
* Remove a document's passages, by the count the manifest holds. Idempotent — a document
|
|
121
|
+
* that is absent, or whose passages were already deleted, is a no-op.
|
|
122
|
+
*/
|
|
123
|
+
removeDoc(docId: string): Promise<void>;
|
|
124
|
+
private removeRecordedPassages;
|
|
125
|
+
/**
|
|
126
|
+
* Ingest a document, superseding any previous revision of it. Returns the passages now
|
|
127
|
+
* stored for it (empty if the document chunked to nothing).
|
|
128
|
+
*
|
|
129
|
+
* UPSERT, not append. Ingesting the same document twice must not double it in the index
|
|
130
|
+
* — retrieval would then return the stale passage beside the current one, and a citation
|
|
131
|
+
* could not say which is live. That is the operation a `MemoryStore` alone cannot
|
|
132
|
+
* express, and the reason this class exists.
|
|
133
|
+
*
|
|
134
|
+
* The write order is the crash contract, and it is deliberate:
|
|
135
|
+
*
|
|
136
|
+
* 1. APPEND an uncommitted manifest row at the new count and fingerprint;
|
|
137
|
+
* 2. delete the previous revision's passages (by the count the old row holds);
|
|
138
|
+
* 3. append the new passages;
|
|
139
|
+
* 4. APPEND the committed manifest row, then prune the superseded rows.
|
|
140
|
+
*
|
|
141
|
+
* A crash before (4) leaves an uncommitted row, which {@link sync} and every later
|
|
142
|
+
* `putDoc` treat as changed no matter what the fingerprint says — so the document is
|
|
143
|
+
* rewritten rather than skipped.
|
|
144
|
+
*
|
|
145
|
+
* Two orderings look more natural and neither survives. Passages first: passages nothing
|
|
146
|
+
* counts are passages nothing can remove, and they stay retrievable forever. Manifest
|
|
147
|
+
* updated in place (delete the old row, write the new one): the crash window between
|
|
148
|
+
* them leaves the document with NO row, which is the same orphaning by a shorter path —
|
|
149
|
+
* which is why rows are appended and superseded ones are pruned only afterwards.
|
|
150
|
+
*/
|
|
151
|
+
putDoc(doc: KnowledgeDoc, opts?: SourceOptions): Promise<Passage[]>;
|
|
152
|
+
private write;
|
|
153
|
+
/**
|
|
154
|
+
* Reconcile the corpus against the documents the source currently has: write what is new
|
|
155
|
+
* or changed, leave what is identical, remove what the source dropped.
|
|
156
|
+
*
|
|
157
|
+
* This is the operation a knowledge base is actually run with — a wiki export, a docs
|
|
158
|
+
* directory, a table of policies — and it is what makes deletion complete rather than
|
|
159
|
+
* best-effort. Without it, a document deleted upstream keeps answering questions.
|
|
160
|
+
*
|
|
161
|
+
* Cost is one manifest read (rows are ids and counts) plus writes for the documents that
|
|
162
|
+
* genuinely changed — NOT a rewrite of the corpus, which is the whole point of the
|
|
163
|
+
* fingerprint. Re-running it on an unchanged source writes nothing.
|
|
164
|
+
*
|
|
165
|
+
* `docs` is the COMPLETE set. Passing a subset removes everything not in it, which is
|
|
166
|
+
* the correct reading of "reconcile" and the wrong thing to do with a page of results.
|
|
167
|
+
*/
|
|
168
|
+
sync(docs: readonly KnowledgeDoc[], opts?: SourceOptions): Promise<SyncResult>;
|
|
169
|
+
/**
|
|
170
|
+
* What {@link sync} WOULD do, without doing it. Read-only.
|
|
171
|
+
*
|
|
172
|
+
* Exists because a corpus sync is a destructive reconcile — `docs` is the complete set,
|
|
173
|
+
* so anything missing from it is deleted — and the operator command that runs it
|
|
174
|
+
* (`loom knowledge sync`) defaults to a dry run for that reason. A preview computed by a
|
|
175
|
+
* separate code path would be a preview of a different operation, so both go through the
|
|
176
|
+
* same classification and only `sync` writes.
|
|
177
|
+
*/
|
|
178
|
+
planSync(docs: readonly KnowledgeDoc[], opts?: SourceOptions): Promise<SyncResult>;
|
|
179
|
+
/** Pure: which documents are new/changed, unchanged, or no longer in the source. */
|
|
180
|
+
private classify;
|
|
181
|
+
/** The documents this corpus holds, in manifest order. Ids and counts — no passage text. */
|
|
182
|
+
listDocs(): Promise<DocRecord[]>;
|
|
183
|
+
/**
|
|
184
|
+
* Retrieve the passages most relevant to a question, best first.
|
|
185
|
+
*
|
|
186
|
+
* `decide` is REQUIRED, and it is a type requirement rather than advice for the reason
|
|
187
|
+
* ADR 0090 gives: a corpus grows and is edited, so the passages a question retrieves
|
|
188
|
+
* genuinely differ between a run and its replay. Recorded, the retrieval is a fact and
|
|
189
|
+
* the replay rebuilds the prompt that actually ran; unrecorded, "reproducing" an
|
|
190
|
+
* incident quietly means asking today's corpus yesterday's question.
|
|
191
|
+
*
|
|
192
|
+
* What is recorded is the passage CONTENT, not passage ids — ids do not reconstruct a
|
|
193
|
+
* prompt once the document behind them has been revised.
|
|
194
|
+
*/
|
|
195
|
+
retrieve(query: string, opts: RetrieveOptions): Promise<Passage[]>;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Open a corpus over a `MemoryStore` directly — the two-line form of the four every
|
|
199
|
+
* consumer was writing by hand.
|
|
200
|
+
*
|
|
201
|
+
* A corpus needs exactly one memory tier and that tier must not evict, which is a fact
|
|
202
|
+
* about corpora and not a decision each application should be re-deriving. Both first
|
|
203
|
+
* consumers built the identical `new TieredMemory({ tiers: { semantic: {} }, store })`
|
|
204
|
+
* before they could construct anything, and an application wiring `defineConfig` cannot
|
|
205
|
+
* pass `app.memory` here at all — that is a {@link MemoryRuntime}, one layer below
|
|
206
|
+
* `TieredMemory` — so the boilerplate was mandatory rather than incidental.
|
|
207
|
+
*
|
|
208
|
+
* Reach for the constructor instead when the corpus shares a memory with something else
|
|
209
|
+
* (a conversation in `episodic`, say), which is exactly when the tier set is a decision.
|
|
210
|
+
*/
|
|
211
|
+
export declare function openKnowledgeBase(store: MemoryStore, opts: Omit<KnowledgeBaseConfig, "memory">): KnowledgeBase;
|
|
212
|
+
//# sourceMappingURL=KnowledgeBase.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"KnowledgeBase.d.ts","sourceRoot":"","sources":["../src/KnowledgeBase.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGjE,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAEzE,gFAAgF;AAChF,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;AAErF,MAAM,WAAW,mBAAmB;IAClC,2FAA2F;IAC3F,MAAM,EAAE,YAAY,CAAC;IACrB,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC;IACd,6DAA6D;IAC7D,IAAI,CAAC,EAAE,M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