@seanhogg/builderforce-memory 2026.10.31 → 2026.10.33
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/dist/agent/SSMAgent.d.ts.map +1 -1
- package/dist/agent/SSMAgent.js.map +1 -1
- package/dist/bridges/AnthropicBridge.d.ts.map +1 -1
- package/dist/bridges/AnthropicBridge.js.map +1 -1
- package/dist/bridges/CachingBridge.d.ts.map +1 -1
- package/dist/bridges/CachingBridge.js.map +1 -1
- package/dist/bridges/FetchBridge.d.ts.map +1 -1
- package/dist/bridges/OpenAIBridge.d.ts.map +1 -1
- package/dist/bridges/OpenAIBridge.js.map +1 -1
- package/dist/bridges/ResponseCache.d.ts.map +1 -1
- package/dist/bridges/ResponseCache.js.map +1 -1
- package/dist/bridges/SemanticCachingBridge.d.ts.map +1 -1
- package/dist/bridges/SemanticCachingBridge.js.map +1 -1
- package/dist/bridges/VertexAIBridge.d.ts.map +1 -1
- package/dist/bridges/VertexAIBridge.js.map +1 -1
- package/dist/cache/FetchSemanticCacheBackend.d.ts.map +1 -1
- package/dist/cache/SemanticCache.d.ts.map +1 -1
- package/dist/cognition/EvermindCognition.d.ts.map +1 -1
- package/dist/cognition/EvermindCognition.js.map +1 -1
- package/dist/diagnostics/stack-diagnostic.js.map +1 -1
- package/dist/distillation/DistillationEngine.d.ts.map +1 -1
- package/dist/distillation/DistillationEngine.js.map +1 -1
- package/dist/errors/SSMError.d.ts +2 -2
- package/dist/errors/SSMError.d.ts.map +1 -1
- package/dist/errors/SSMError.js.map +1 -1
- package/dist/eval/EvalHarness.d.ts.map +1 -1
- package/dist/eval/EvalHarness.js.map +1 -1
- package/dist/evermind/runtime.js.map +1 -1
- package/dist/evermind/textCoherence.js.map +1 -1
- package/dist/evermind/toolCall.js.map +1 -1
- package/dist/handoff/pack.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/ingest/IngestionPipeline.d.ts.map +1 -1
- package/dist/ingest/docsExtract.d.ts +9 -3
- package/dist/ingest/docsExtract.d.ts.map +1 -1
- package/dist/ingest/docsExtract.js +73 -20
- package/dist/ingest/docsExtract.js.map +1 -1
- package/dist/ingest/index.d.ts +1 -1
- package/dist/ingest/index.d.ts.map +1 -1
- package/dist/ingest/index.js +1 -1
- package/dist/ingest/index.js.map +1 -1
- package/dist/ingest/parserSupport.d.ts +16 -0
- package/dist/ingest/parserSupport.d.ts.map +1 -0
- package/dist/ingest/parserSupport.js +18 -0
- package/dist/ingest/parserSupport.js.map +1 -0
- package/dist/ingest/parsers.d.ts +3 -3
- package/dist/ingest/parsers.d.ts.map +1 -1
- package/dist/ingest/parsers.js +3 -92
- package/dist/ingest/parsers.js.map +1 -1
- package/dist/ingest/textParsers.d.ts +9 -0
- package/dist/ingest/textParsers.d.ts.map +1 -0
- package/dist/ingest/textParsers.js +99 -0
- package/dist/ingest/textParsers.js.map +1 -0
- package/dist/knowledge/build.d.ts +2 -0
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +46 -12
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/cards.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +51 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -0
- package/dist/knowledge/extractFile.js +59 -0
- package/dist/knowledge/extractFile.js.map +1 -0
- package/dist/knowledge/findings.d.ts +6 -0
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +9 -7
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/importance.js.map +1 -1
- package/dist/knowledge/index.d.ts +10 -7
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +8 -7
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/judge.d.ts +34 -2
- package/dist/knowledge/judge.d.ts.map +1 -1
- package/dist/knowledge/judge.js +86 -16
- package/dist/knowledge/judge.js.map +1 -1
- package/dist/knowledge/model.d.ts +13 -62
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +68 -0
- package/dist/knowledge/owedFiles.d.ts.map +1 -0
- package/dist/knowledge/owedFiles.js +86 -0
- package/dist/knowledge/owedFiles.js.map +1 -0
- package/dist/knowledge/packs/docs.d.ts +5 -2
- package/dist/knowledge/packs/docs.d.ts.map +1 -1
- package/dist/knowledge/packs/docs.js +33 -5
- package/dist/knowledge/packs/docs.js.map +1 -1
- package/dist/knowledge/plan.d.ts +37 -3
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +66 -19
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/refs.d.ts +22 -1
- package/dist/knowledge/refs.d.ts.map +1 -1
- package/dist/knowledge/refs.js +52 -0
- package/dist/knowledge/refs.js.map +1 -1
- package/dist/knowledge/review.d.ts +10 -4
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +125 -109
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewCompare.d.ts +39 -0
- package/dist/knowledge/reviewCompare.d.ts.map +1 -0
- package/dist/knowledge/reviewCompare.js +70 -0
- package/dist/knowledge/reviewCompare.js.map +1 -0
- package/dist/knowledge/reviewModel.d.ts +86 -0
- package/dist/knowledge/reviewModel.d.ts.map +1 -0
- package/dist/knowledge/reviewModel.js +6 -0
- package/dist/knowledge/reviewModel.js.map +1 -0
- package/dist/knowledge/reviewStored.d.ts +23 -0
- package/dist/knowledge/reviewStored.d.ts.map +1 -0
- package/dist/knowledge/reviewStored.js +62 -0
- package/dist/knowledge/reviewStored.js.map +1 -0
- package/dist/knowledge/sources.d.ts +34 -4
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +92 -26
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/trace.js.map +1 -1
- package/dist/knowledge/truncate.d.ts +4 -4
- package/dist/knowledge/truncate.d.ts.map +1 -1
- package/dist/knowledge/truncate.js +9 -13
- package/dist/knowledge/truncate.js.map +1 -1
- package/dist/limbic/LimbicSession.d.ts.map +1 -1
- package/dist/limbic/LimbicSession.js.map +1 -1
- package/dist/memory/MemoryStore.d.ts.map +1 -1
- package/dist/memory/MemoryStore.js.map +1 -1
- package/dist/memory/SemanticRecall.d.ts.map +1 -1
- package/dist/memory/SemanticRecall.js.map +1 -1
- package/dist/memory/ttlSweeper.d.ts.map +1 -1
- package/dist/orchestration/AgentGraph.d.ts.map +1 -1
- package/dist/orchestration/AgentGraph.js.map +1 -1
- package/dist/orchestration/checkpoint.d.ts.map +1 -1
- package/dist/orchestration/checkpoint.js.map +1 -1
- package/dist/publish/huggingface.js.map +1 -1
- package/dist/rag/EnterpriseRetriever.d.ts.map +1 -1
- package/dist/rag/EnterpriseRetriever.js.map +1 -1
- package/dist/retrieval/HybridRetriever.js.map +1 -1
- package/dist/retrieval/bm25.js.map +1 -1
- package/dist/retrieval/chunk.js.map +1 -1
- package/dist/retrieval/fusion.js.map +1 -1
- package/dist/retrieval/hnsw.d.ts.map +1 -1
- package/dist/retrieval/hnsw.js.map +1 -1
- package/dist/retrieval/knowledge-index/bytes.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/bytes.js.map +1 -1
- package/dist/retrieval/knowledge-index/cascade.js.map +1 -1
- package/dist/retrieval/knowledge-index/embeddings.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/embeddings.js.map +1 -1
- package/dist/retrieval/knowledge-index/expand.js.map +1 -1
- package/dist/retrieval/knowledge-index/index.js.map +1 -1
- package/dist/retrieval/knowledge-index/lexical.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
- package/dist/retrieval/order.js.map +1 -1
- package/dist/router/InferenceRouter.d.ts.map +1 -1
- package/dist/router/InferenceRouter.js.map +1 -1
- package/dist/runtime/SSMRuntime.d.ts.map +1 -1
- package/dist/runtime/SSMRuntime.js.map +1 -1
- package/dist/session/errors.d.ts +2 -2
- package/dist/session/errors.d.ts.map +1 -1
- package/dist/session/errors.js.map +1 -1
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js.map +1 -1
- package/dist/session/streaming.js.map +1 -1
- package/dist/storage/ScopedFactRepository.d.ts.map +1 -1
- package/dist/storage/ScopedFactRepository.js.map +1 -1
- package/dist/storage/fileLock.d.ts.map +1 -1
- package/dist/storage/fileLock.js.map +1 -1
- package/dist/storage/fileTransaction.d.ts.map +1 -1
- package/dist/storage/fileTransaction.js.map +1 -1
- package/dist/storage/idbAdapter.d.ts +1 -1
- package/dist/storage/idbAdapter.d.ts.map +1 -1
- package/dist/storage/idbAdapter.js.map +1 -1
- package/dist/storage/nodeFileAdapter.d.ts +1 -1
- package/dist/storage/nodeFileAdapter.d.ts.map +1 -1
- package/dist/storage/nodeFileAdapter.js.map +1 -1
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/telemetry/InstrumentedBridge.d.ts.map +1 -1
- package/dist/telemetry/InstrumentedBridge.js.map +1 -1
- package/dist/telemetry/MetricsRegistry.d.ts.map +1 -1
- package/dist/telemetry/MetricsRegistry.js.map +1 -1
- package/dist/telemetry/Tracer.d.ts.map +1 -1
- package/dist/telemetry/Tracer.js.map +1 -1
- package/dist/telemetry/exporters.d.ts.map +1 -1
- package/dist/telemetry/exporters.js.map +1 -1
- package/dist/telemetry/pricing.js.map +1 -1
- package/dist/vectorstore/MemoryVectorStore.d.ts.map +1 -1
- package/dist/vectorstore/MemoryVectorStore.js.map +1 -1
- package/dist/vectorstore/RestVectorStore.d.ts.map +1 -1
- package/dist/vectorstore/dialects.js.map +1 -1
- package/dist/vectorstore/filter.js.map +1 -1
- package/dist/wire/chatClient.d.ts +5 -0
- package/dist/wire/chatClient.d.ts.map +1 -1
- package/dist/wire/chatClient.js +6 -0
- package/dist/wire/chatClient.js.map +1 -1
- package/dist/wire/usage.d.ts.map +1 -1
- package/dist/workflow/registry.d.ts.map +1 -1
- package/dist/workflow/run.js.map +1 -1
- package/dist/workflow/templates.js.map +1 -1
- package/dist/working/codemapAreas.js.map +1 -1
- package/dist/working/consolidate.js.map +1 -1
- package/dist/working/workingMemory.d.ts.map +1 -1
- package/dist/working/workingMemory.js.map +1 -1
- package/package.json +8 -9
- package/src/ingest/docsExtract.ts +68 -18
- package/src/ingest/index.ts +1 -0
- package/src/ingest/parserSupport.ts +24 -0
- package/src/ingest/parsers.ts +4 -102
- package/src/ingest/textParsers.ts +107 -0
- package/src/knowledge/build.ts +43 -11
- package/src/knowledge/extractFile.ts +86 -0
- package/src/knowledge/findings.ts +12 -5
- package/src/knowledge/index.ts +15 -8
- package/src/knowledge/judge.clamp.test.ts +61 -0
- package/src/knowledge/judge.ts +88 -19
- package/src/knowledge/model.ts +15 -57
- package/src/knowledge/owedFiles.ts +108 -0
- package/src/knowledge/packs/docs.ts +34 -5
- package/src/knowledge/plan.ts +93 -19
- package/src/knowledge/refs.ts +49 -1
- package/src/knowledge/review.details.test.ts +93 -0
- package/src/knowledge/review.estimate.test.ts +112 -0
- package/src/knowledge/review.fixes.test.ts +235 -0
- package/src/knowledge/review.gaps.test.ts +167 -0
- package/src/knowledge/review.owed.test.ts +379 -0
- package/src/knowledge/review.test.ts +2 -15
- package/src/knowledge/review.ts +114 -117
- package/src/knowledge/review.upgrade.test.ts +257 -0
- package/src/knowledge/reviewCompare.ts +80 -0
- package/src/knowledge/reviewModel.ts +81 -0
- package/src/knowledge/reviewStored.ts +62 -0
- package/src/knowledge/sources.ts +97 -20
- package/src/knowledge/testkit.test-util.ts +39 -1
- package/src/knowledge/truncate.ts +8 -11
- package/src/wire/chatClient.ts +13 -0
package/src/knowledge/build.ts
CHANGED
|
@@ -25,7 +25,7 @@ import { pageRank } from './importance.js';
|
|
|
25
25
|
import { loadPartitions, partitionOf, verdictOf } from './partitions.js';
|
|
26
26
|
import { entityName } from './resolve.js';
|
|
27
27
|
import {
|
|
28
|
-
basenameOf, canonicalJson, compareStr, factRef, pathOfRef, round6, sortBy, srcRef,
|
|
28
|
+
basenameOf, canonicalJson, compareStr, factRef, fileRefOf, nameResolver, pathOfRef, round6, sortBy, srcRef,
|
|
29
29
|
} from './refs.js';
|
|
30
30
|
import { truncateGraph } from './truncate.js';
|
|
31
31
|
|
|
@@ -35,7 +35,8 @@ const LABEL_CHARS = 120;
|
|
|
35
35
|
|
|
36
36
|
const edgeId = (from: string, to: string, kind: string) => `${from}\u0000${to}\u0000${kind}`;
|
|
37
37
|
export const compareEdges = (a: KEdge, b: KEdge): number =>
|
|
38
|
-
compareStr(a.from, b.from) || compareStr(a.to, b.to) || compareStr(a.kind, b.kind)
|
|
38
|
+
compareStr(a.from, b.from) || compareStr(a.to, b.to) || compareStr(a.kind, b.kind)
|
|
39
|
+
|| compareStr(a.byName ?? '', b.byName ?? '');
|
|
39
40
|
|
|
40
41
|
/** sha-256 over the canonical input: equal inputs (in any order) ⇒ equal digests. */
|
|
41
42
|
export function graphDigest(input: BuildGraphInput): string {
|
|
@@ -74,7 +75,8 @@ function mergeBadges(a?: Record<string, number | string>, b?: Record<string, num
|
|
|
74
75
|
return out;
|
|
75
76
|
}
|
|
76
77
|
|
|
77
|
-
|
|
78
|
+
/** A node label: one line, at most 120 characters. */
|
|
79
|
+
export function oneLineLabel(text: string): string {
|
|
78
80
|
const flat = text.replace(/\s+/g, ' ').trim();
|
|
79
81
|
return flat.length > LABEL_CHARS ? `${flat.slice(0, LABEL_CHARS - 1)}…` : flat;
|
|
80
82
|
}
|
|
@@ -97,6 +99,7 @@ class GraphBuilder {
|
|
|
97
99
|
prior.weight = Math.max(prior.weight, e.weight);
|
|
98
100
|
if (e.cycle) prior.cycle = true;
|
|
99
101
|
if (e.confidence !== undefined) prior.confidence = Math.max(prior.confidence ?? 0, e.confidence);
|
|
102
|
+
if (e.stale && e.origin === 'model') prior.stale = true;
|
|
100
103
|
}
|
|
101
104
|
|
|
102
105
|
has(from: NodeRef, to: NodeRef, kind: string): boolean {
|
|
@@ -104,19 +107,25 @@ class GraphBuilder {
|
|
|
104
107
|
}
|
|
105
108
|
}
|
|
106
109
|
|
|
107
|
-
|
|
110
|
+
/**
|
|
111
|
+
* A model fact is stale when a source it was judged from changed (another hash) or is gone
|
|
112
|
+
* (reviewed sources are present, the anchored one is not) — §5.2: never silently current.
|
|
113
|
+
*/
|
|
114
|
+
function factNode(f: StoredFact, rootId: string, g: GraphBuilder, sources: ReadonlySet<string>): KNode {
|
|
108
115
|
const ref = factRef(f.key);
|
|
109
116
|
const kind = f.key.startsWith('ent:') ? 'entity' : f.key.startsWith('claim:') ? 'claim' : 'fact';
|
|
110
117
|
const anchors = sortBy(f.fileAnchors, (a) => a.path);
|
|
111
118
|
const anchoredPack = anchors.map((a) => g.nodes.get(srcRef(rootId, a.path))?.pack).find(Boolean);
|
|
112
119
|
const pack = kind === 'entity' ? f.key.split(':')[1] || 'memory' : anchoredPack ?? 'memory';
|
|
113
120
|
const stale = f.origin === 'model' && anchors.some((a) => {
|
|
114
|
-
|
|
115
|
-
|
|
121
|
+
if (!a.contentHash) return false;
|
|
122
|
+
const ref = srcRef(rootId, a.path);
|
|
123
|
+
const current = g.nodes.get(ref)?.sourceHash;
|
|
124
|
+
return current ? current !== a.contentHash : sources.size > 0 && !sources.has(ref);
|
|
116
125
|
});
|
|
117
126
|
const first = anchors[0];
|
|
118
127
|
return {
|
|
119
|
-
ref, kind, label:
|
|
128
|
+
ref, kind, label: oneLineLabel(kind === 'entity' ? f.content || entityName(ref) : f.content), pack,
|
|
120
129
|
importance: 0, origin: f.origin,
|
|
121
130
|
...(first?.contentHash ? { sourceHash: first.contentHash } : {}),
|
|
122
131
|
...(stale ? { stale: true } : {}),
|
|
@@ -129,14 +138,22 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
|
|
|
129
138
|
const g = new GraphBuilder();
|
|
130
139
|
const sources = new Set<string>();
|
|
131
140
|
|
|
132
|
-
|
|
141
|
+
const extracted = sortBy(input.extracted, (e) => e.sourceRef, (e) => e.sourceHash);
|
|
142
|
+
for (const ex of extracted) {
|
|
133
143
|
if (ex.sourceRef.startsWith('src:')) sources.add(ex.sourceRef);
|
|
134
144
|
for (const n of sortBy(ex.nodes, (x) => x.ref)) g.node({ ...n, origin: 'extracted' });
|
|
135
|
-
|
|
145
|
+
}
|
|
146
|
+
// `[[Name]]` links are re-pointed here, over the files PRESENT now — never in the cached extract.
|
|
147
|
+
const byName = nameResolver([...g.nodes.values()].filter((n) => n.kind === 'file').flatMap((n) => pathOfRef(n.ref) ?? []));
|
|
148
|
+
for (const ex of extracted) {
|
|
149
|
+
for (const e of [...ex.edges].sort(compareEdges)) {
|
|
150
|
+
const edge = repointByName(e, rootId, byName);
|
|
151
|
+
if (edge) g.edge({ ...edge, origin: 'extracted' });
|
|
152
|
+
}
|
|
136
153
|
}
|
|
137
154
|
|
|
138
155
|
const facts = sortBy(input.facts, (f) => f.key);
|
|
139
|
-
for (const f of facts) g.node(factNode(f, rootId, g));
|
|
156
|
+
for (const f of facts) g.node(factNode(f, rootId, g, sources));
|
|
140
157
|
for (const f of facts) {
|
|
141
158
|
for (const a of sortBy(f.fileAnchors, (x) => x.path)) {
|
|
142
159
|
const to = srcRef(rootId, a.path);
|
|
@@ -148,6 +165,7 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
|
|
|
148
165
|
g.edge({
|
|
149
166
|
from: r.from, to: r.to, kind: r.kind, weight: r.weight, origin: r.origin,
|
|
150
167
|
...(r.confidence !== undefined ? { confidence: r.confidence } : {}),
|
|
168
|
+
...(r.origin === 'model' && r.staleAt ? { stale: true } : {}),
|
|
151
169
|
});
|
|
152
170
|
}
|
|
153
171
|
|
|
@@ -206,6 +224,18 @@ function applyLive(input: BuildGraphInput, g: GraphBuilder): NodeRef[] {
|
|
|
206
224
|
return changed;
|
|
207
225
|
}
|
|
208
226
|
|
|
227
|
+
/**
|
|
228
|
+
* An extracted `byName` edge goes to the one present file of that name (ambiguous or none:
|
|
229
|
+
* it keeps the beside-the-file target); `byName` itself is dropped. Null: it would link a file to itself.
|
|
230
|
+
*/
|
|
231
|
+
function repointByName(e: KEdge, rootId: string, resolve: (name: string) => string | undefined): KEdge | null {
|
|
232
|
+
const { byName, ...edge } = e;
|
|
233
|
+
const path = byName === undefined ? undefined : resolve(byName);
|
|
234
|
+
if (path === undefined) return edge;
|
|
235
|
+
const to = srcRef(rootId, path);
|
|
236
|
+
return fileRefOf(e.from) === to ? null : { ...edge, to };
|
|
237
|
+
}
|
|
238
|
+
|
|
209
239
|
/** A missing `src:` endpoint becomes a `missing` placeholder (a broken link); a missing fact drops the edge. */
|
|
210
240
|
function closeEndpoints(g: GraphBuilder): void {
|
|
211
241
|
for (const [id, e] of [...g.edges.entries()].sort((a, b) => compareStr(a[0], b[0]))) {
|
|
@@ -227,7 +257,8 @@ function placeNodes(rootId: string, g: GraphBuilder, registries: Map<string, Par
|
|
|
227
257
|
const path = pathOfRef(n.ref);
|
|
228
258
|
if (path === undefined) continue;
|
|
229
259
|
const reg = registries.get(n.pack);
|
|
230
|
-
|
|
260
|
+
// A broken link out of the root (`../…`) has no folder in it to be a plane of.
|
|
261
|
+
const partition = reg && !(n.kind === 'missing' && path.startsWith('../')) ? partitionOf(path, reg) : undefined;
|
|
231
262
|
if (partition !== undefined) n.partition = partition;
|
|
232
263
|
const area = areaOfPath(path);
|
|
233
264
|
if (area) n.area = srcRef(rootId, area);
|
|
@@ -262,5 +293,6 @@ export function finalEdge(e: KEdge): KEdge {
|
|
|
262
293
|
...(e.confidence !== undefined ? { confidence: round6(e.confidence) } : {}),
|
|
263
294
|
...(e.verdict ? { verdict: e.verdict } : {}),
|
|
264
295
|
...(e.cycle ? { cycle: true } : {}),
|
|
296
|
+
...(e.stale ? { stale: true } : {}),
|
|
265
297
|
};
|
|
266
298
|
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/extractFile.ts — the ONE single-file extraction (PRD 38 §4.3): compose the
|
|
3
|
+
* packs, resolve the parser, parse, extract with the context (known entity keys,
|
|
4
|
+
* `resolvePath`), stamp {@link EXTRACTOR_VERSION} and read/write the extracted cache by
|
|
5
|
+
* content hash. `reviewDirectory` runs it per changed file; a host re-extracting one edited
|
|
6
|
+
* file calls {@link extractFile}.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ParsedSection, SourceDocument } from '../ingest/types.js';
|
|
10
|
+
import type { ExtractContext, Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
|
|
11
|
+
import { basenameOf, srcRef } from './refs.js';
|
|
12
|
+
import { entityName, knownKeysOf, resolveEntities } from './resolve.js';
|
|
13
|
+
import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, type ComposedPacks } from './sources.js';
|
|
14
|
+
|
|
15
|
+
/** The normalized entity keys of `ent:` fact keys, for `mentions`. */
|
|
16
|
+
export function knownKeysOfEntities(keys: Iterable<string>): ReadonlyMap<string, NodeRef> {
|
|
17
|
+
return knownKeysOf(resolveEntities([...keys].filter((k) => k.startsWith('ent:')).map((k) => ({ ref: k as NodeRef, key: entityName(k) }))));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ExtractFileArgs {
|
|
21
|
+
rootId: string;
|
|
22
|
+
/** Root-relative path. */
|
|
23
|
+
path: string;
|
|
24
|
+
/** Content hash of the file (the extracted cache's key). */
|
|
25
|
+
hash: string;
|
|
26
|
+
doc: SourceDocument;
|
|
27
|
+
packs: readonly KnowledgePack[];
|
|
28
|
+
store: KnowledgeStore;
|
|
29
|
+
/** Already composed from `packs` (a review composes once). */
|
|
30
|
+
composed?: ComposedPacks;
|
|
31
|
+
/** Already known entity keys (a review reads them once); default: the store's `ent:` facts. */
|
|
32
|
+
knownKeys?: ReadonlyMap<string, NodeRef>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface FileExtraction {
|
|
36
|
+
extracted: Extracted;
|
|
37
|
+
parser: KnowledgeParser;
|
|
38
|
+
pack: KnowledgePack;
|
|
39
|
+
/** The parser's sections of the file (the review judges these). */
|
|
40
|
+
sections: ParsedSection[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Extraction plus what produced it; undefined when no pack's parser accepts the file. */
|
|
44
|
+
export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtraction | undefined> {
|
|
45
|
+
const src = asPathSource(a.doc, a.path, a.hash);
|
|
46
|
+
const hit = (a.composed ?? composePacks(a.packs)).resolve(src);
|
|
47
|
+
if (!hit) return undefined;
|
|
48
|
+
const sections = hit.parser.parse(src);
|
|
49
|
+
const ref = srcRef(a.rootId, a.path);
|
|
50
|
+
const cached = await a.store.getExtracted?.(a.hash);
|
|
51
|
+
// A cached entry of another extractor version is ignored: its output may differ from today's.
|
|
52
|
+
const found = cached?.find((e) => e.sourceRef === ref && e.extractorVersion === EXTRACTOR_VERSION);
|
|
53
|
+
if (found) return { extracted: found, parser: hit.parser, pack: hit.pack, sections };
|
|
54
|
+
|
|
55
|
+
const ctx: ExtractContext = {
|
|
56
|
+
rootId: a.rootId,
|
|
57
|
+
knownKeys: a.knownKeys ?? knownKeysOfEntities((await a.store.facts({ rootId: a.rootId })).map((f) => f.key)),
|
|
58
|
+
resolvePath: resolveRelativePath,
|
|
59
|
+
};
|
|
60
|
+
const extracted: Extracted = hit.parser.extract
|
|
61
|
+
? { ...hit.parser.extract(src, sections, ctx), sourceHash: a.hash, extractorVersion: EXTRACTOR_VERSION }
|
|
62
|
+
: {
|
|
63
|
+
sourceRef: ref, sourceHash: a.hash, extractorVersion: EXTRACTOR_VERSION, edges: [], keys: [{ ref, key: a.path }],
|
|
64
|
+
nodes: [{ ref, kind: 'file', label: basenameOf(a.path), pack: hit.pack.id, importance: 0, origin: 'extracted', sourceHash: a.hash }],
|
|
65
|
+
};
|
|
66
|
+
await a.store.putExtracted?.(a.hash, [...(cached ?? []).filter((e) => e.sourceRef !== ref), extracted]);
|
|
67
|
+
return { extracted, parser: hit.parser, pack: hit.pack, sections };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Re-extracts ONE file — the stable entry point for a host that learns a single file changed
|
|
72
|
+
* (an agent's file edit) without running a review.
|
|
73
|
+
*
|
|
74
|
+
* Input ({@link ExtractFileArgs}): `rootId`, the root-relative `path`, the content `hash` of
|
|
75
|
+
* the text in `doc`, the `packs` and a `store`. Output: the file's {@link Extracted}, stamped
|
|
76
|
+
* with {@link EXTRACTOR_VERSION}; or undefined when no pack's parser accepts the file (a
|
|
77
|
+
* binary document without a host parser, say).
|
|
78
|
+
*
|
|
79
|
+
* Cached by content hash through `store.getExtracted` / `putExtracted` (an entry of another
|
|
80
|
+
* extractor version is ignored and replaced), so calling it again for the same hash is free.
|
|
81
|
+
* It writes only that cache — never knowledge — and reads the store's `ent:` facts for
|
|
82
|
+
* `mentions` unless `knownKeys` is given. The signature is part of the subpath's public contract.
|
|
83
|
+
*/
|
|
84
|
+
export async function extractFile(a: ExtractFileArgs): Promise<Extracted | undefined> {
|
|
85
|
+
return (await extractFileDetailed(a))?.extracted;
|
|
86
|
+
}
|
|
@@ -12,7 +12,7 @@ import { hashText } from '../ingest/hash.js';
|
|
|
12
12
|
import type { Finding, KEdge, KNode, KnowledgeGraph, KnowledgePack, NodeRef, PartitionRegistry } from './model.js';
|
|
13
13
|
import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
14
14
|
import { possibleSameFindings } from './resolve.js';
|
|
15
|
-
import { compareStr, round6 } from './refs.js';
|
|
15
|
+
import { aboutTargets, compareStr, round6 } from './refs.js';
|
|
16
16
|
|
|
17
17
|
/** Node badge naming the clone group (e.g. a jscpd issue id) its `duplicate` edges belong to. */
|
|
18
18
|
export const CLONE_GROUP_BADGE = 'cloneGroup';
|
|
@@ -30,10 +30,18 @@ export function requestKeyFor(kind: string): string {
|
|
|
30
30
|
return `knowledgeGraph.fix.${kind.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())}`;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* The ONE finding builder: nodes deduped, sorted and capped at {@link MAX_FINDING_NODES}.
|
|
35
|
+
* The id hashes `idRefs` (default: all the nodes) — pass a narrower set to keep it stable
|
|
36
|
+
* while the listed nodes change.
|
|
37
|
+
*/
|
|
38
|
+
export function finding(
|
|
39
|
+
kind: string, pack: string, nodes: readonly NodeRef[], severity: Finding['severity'], params: Finding['params'],
|
|
40
|
+
idRefs?: readonly string[],
|
|
41
|
+
): Finding {
|
|
34
42
|
const sorted = [...new Set(nodes)].sort(compareStr);
|
|
35
43
|
return {
|
|
36
|
-
id: findingId(kind, sorted), kind, pack, nodes: sorted.slice(0, MAX_FINDING_NODES), severity, params,
|
|
44
|
+
id: findingId(kind, idRefs ?? sorted), kind, pack, nodes: sorted.slice(0, MAX_FINDING_NODES), severity, params,
|
|
37
45
|
requestKey: requestKeyFor(kind),
|
|
38
46
|
};
|
|
39
47
|
}
|
|
@@ -119,8 +127,7 @@ export function genericFindings(g: KnowledgeGraph, registries: ReadonlyMap<strin
|
|
|
119
127
|
|
|
120
128
|
/** One finding per source whose stored knowledge went stale (unanchored stale nodes: one each). */
|
|
121
129
|
function staleFindings(g: KnowledgeGraph, byRef: ReadonlyMap<NodeRef, KNode>): Finding[] {
|
|
122
|
-
const about =
|
|
123
|
-
for (const e of g.edges) if (e.kind === 'about' && !about.has(e.from)) about.set(e.from, e.to);
|
|
130
|
+
const about = aboutTargets(g.edges);
|
|
124
131
|
const bySource = new Map<NodeRef, NodeRef[]>();
|
|
125
132
|
for (const n of g.nodes) {
|
|
126
133
|
if (!n.stale) continue;
|
package/src/knowledge/index.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type {
|
|
|
14
14
|
ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace,
|
|
15
15
|
} from './model.js';
|
|
16
16
|
|
|
17
|
-
export { buildGraph, graphDigest, DEFAULT_MAX_NODES, MAX_NODES_CAP } from './build.js';
|
|
17
|
+
export { buildGraph, graphDigest, oneLineLabel, DEFAULT_MAX_NODES, MAX_NODES_CAP } from './build.js';
|
|
18
18
|
export { truncateGraph, TRUNCATION_HARD_CAP, UNANCHORED_AREA } from './truncate.js';
|
|
19
19
|
export type { TruncateOptions } from './truncate.js';
|
|
20
20
|
export { pageRank, byImportance, areaImportance, PAGERANK_DAMPING, PAGERANK_ITERATIONS } from './importance.js';
|
|
@@ -26,25 +26,32 @@ export {
|
|
|
26
26
|
} from './trace.js';
|
|
27
27
|
export type { LanedTrace, TraceOptions } from './trace.js';
|
|
28
28
|
export {
|
|
29
|
-
computeFindings, genericFindings, findingId, requestKeyFor, components, CLONE_GROUP_BADGE, MAX_FINDING_NODES,
|
|
29
|
+
computeFindings, genericFindings, finding, findingId, requestKeyFor, components, CLONE_GROUP_BADGE, MAX_FINDING_NODES,
|
|
30
30
|
} from './findings.js';
|
|
31
31
|
export {
|
|
32
32
|
resolveEntities, knownKeysOf, possibleSameFindings, normalizeKey, entityName, entityKey,
|
|
33
33
|
} from './resolve.js';
|
|
34
34
|
export type { ResolvedEntity } from './resolve.js';
|
|
35
35
|
export { toCards } from './cards.js';
|
|
36
|
-
export { planReview, planDetail, AVG_SECTION_BYTES } from './plan.js';
|
|
36
|
+
export { planReview, planDetail, refreshPlan, AVG_SECTION_BYTES } from './plan.js';
|
|
37
37
|
export type { PlanOptions, PlannedFile, PlanDetail } from './plan.js';
|
|
38
|
+
export type { ExtractorState } from './owedFiles.js';
|
|
38
39
|
export { reviewDirectory, assertStoredBatch } from './review.js';
|
|
40
|
+
export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
|
|
41
|
+
export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
|
|
39
42
|
export {
|
|
40
|
-
validateExtract, validateCompare,
|
|
43
|
+
validateExtract, validateCompare, clampQuote, clampClaim, MAX_QUOTE_LINES, MAX_QUOTE_CHARS, MAX_CLAIM_TEXT_CHARS,
|
|
44
|
+
DEFAULT_REVIEW_MODEL_CALLS, REVIEW_FACT_SOURCE,
|
|
41
45
|
} from './judge.js';
|
|
42
46
|
export {
|
|
43
|
-
composePacks, ignoreMatcher, isBinaryPath, isBinaryText,
|
|
44
|
-
|
|
47
|
+
composePacks, ignoreMatcher, ignoreSourcesOf, isBinaryPath, isBinaryText, isDocumentPath, mediaTypeOfPath,
|
|
48
|
+
resolveDocument, resolveRelativePath,
|
|
49
|
+
DEFAULT_MAX_FILE_BYTES, EXTRACTOR_VERSION, filesManifestKey, extractorManifestKey, judgedManifestKey, compareManifestKey,
|
|
45
50
|
} from './sources.js';
|
|
46
|
-
export {
|
|
47
|
-
|
|
51
|
+
export {
|
|
52
|
+
srcRef, pathOfRef, fileRefOf, factRef, factKeyOf, slugOf, canonicalJson, compareStr, nameResolver, aboutTargets,
|
|
53
|
+
} from './refs.js';
|
|
54
|
+
export { DOCS_PACK, DOCS_PACK_ID, brokenLinkRule, orphanDocumentRule, contradictionRule } from './packs/docs.js';
|
|
48
55
|
export { frontMatterOf, SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
|
|
49
56
|
export { LocalSnapshotStore, localSnapshotStore } from './stores/localSnapshotStore.js';
|
|
50
57
|
export type { SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions } from './stores/localSnapshotStore.js';
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/judge.clamp.test.ts
|
|
3
|
+
* `clampClaim`: the privacy bound on a stored claim, stated once here so a host (the
|
|
4
|
+
* Builderforce API) applies memory's own rules instead of re-declaring the separator and limits.
|
|
5
|
+
* Imported through the subpath's index, so the export surface is under test too.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { claimContent, claimTextOf } from './judge.js';
|
|
9
|
+
import { clampClaim, clampQuote, MAX_CLAIM_TEXT_CHARS, MAX_QUOTE_CHARS, MAX_QUOTE_LINES } from './index.js';
|
|
10
|
+
|
|
11
|
+
describe('clampClaim', () => {
|
|
12
|
+
it('bounds a claim text at three 200-character terms and their two joining spaces', () => {
|
|
13
|
+
expect(MAX_CLAIM_TEXT_CHARS).toBe(3 * 200 + 2);
|
|
14
|
+
expect(clampClaim('x'.repeat(20_000))).toHaveLength(MAX_CLAIM_TEXT_CHARS);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('keeps the lines of a claim text (its terms may span lines) and only bounds its characters', () => {
|
|
18
|
+
const text = Array.from({ length: MAX_QUOTE_LINES + 4 }, (_, i) => `line ${i}`).join('\n');
|
|
19
|
+
expect(clampClaim(text)).toBe(text);
|
|
20
|
+
expect(clampClaim(claimContent(text, 'it says so'))).toBe(claimContent(text, 'it says so'));
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('lets what the judge produces through unchanged, at its longest', () => {
|
|
24
|
+
const text = [200, 200, 200].map((n) => 'w'.repeat(n)).join(' ');
|
|
25
|
+
expect(text).toHaveLength(MAX_CLAIM_TEXT_CHARS);
|
|
26
|
+
const content = claimContent(text, 'q'.repeat(MAX_QUOTE_CHARS));
|
|
27
|
+
expect(clampClaim(content)).toBe(content);
|
|
28
|
+
expect(clampClaim('a says b')).toBe('a says b');
|
|
29
|
+
expect(clampClaim(claimContent('a says b', 'it says so'))).toBe(claimContent('a says b', 'it says so'));
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('clamps the quote by the quote bound without cutting the claim text', () => {
|
|
33
|
+
const clamped = clampClaim(`a says b — “${'q'.repeat(20_000)}”`);
|
|
34
|
+
expect(claimTextOf(clamped)).toBe('a says b');
|
|
35
|
+
expect(clamped).toBe(claimContent('a says b', 'q'.repeat(MAX_QUOTE_CHARS)));
|
|
36
|
+
const lines = clampClaim(`a says b — “${Array.from({ length: 9 }, (_, i) => `l${i}`).join('\n')}”`);
|
|
37
|
+
expect(lines).toBe(claimContent('a says b', 'l0\nl1\nl2'));
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('bounds a long text and its quote independently, and is idempotent', () => {
|
|
41
|
+
const clamped = clampClaim(`${'t'.repeat(5_000)} — “short quote”`);
|
|
42
|
+
expect(claimTextOf(clamped)).toHaveLength(MAX_CLAIM_TEXT_CHARS);
|
|
43
|
+
expect(clamped.endsWith(' — “short quote”')).toBe(true);
|
|
44
|
+
expect(clampClaim(clamped)).toBe(clamped);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('is idempotent where the quote cut lands on a space or a line break', () => {
|
|
48
|
+
for (const gap of [' ', '\n']) {
|
|
49
|
+
const once = clampClaim(`a says b — “${'q'.repeat(MAX_QUOTE_CHARS - 1)}${gap}${'r'.repeat(50)}”`);
|
|
50
|
+
expect(once).toBe(claimContent('a says b', 'q'.repeat(MAX_QUOTE_CHARS - 1))); // the cut gap is trimmed, not kept
|
|
51
|
+
expect(clampClaim(once)).toBe(once);
|
|
52
|
+
}
|
|
53
|
+
const quote = 'q'.repeat(MAX_QUOTE_CHARS - 1);
|
|
54
|
+
expect(clampQuote(`${quote} ${'r'.repeat(50)}`)).toBe(quote);
|
|
55
|
+
expect(clampQuote(clampQuote(`${quote}\n${'r'.repeat(50)}`))).toBe(quote);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('drops an empty quote to the canonical form', () => {
|
|
59
|
+
expect(clampClaim('a says b — “”')).toBe('a says b');
|
|
60
|
+
});
|
|
61
|
+
});
|
package/src/knowledge/judge.ts
CHANGED
|
@@ -23,8 +23,53 @@ export const DEFAULT_REVIEW_MODEL_CALLS = 200;
|
|
|
23
23
|
export const REVIEW_FACT_SOURCE = 'knowledge-review';
|
|
24
24
|
const MAX_TERM = 200;
|
|
25
25
|
const MAX_NAME = 120;
|
|
26
|
-
|
|
27
|
-
const
|
|
26
|
+
/** A stored claim quotes at most this many characters and lines of its source (privacy: never a document). */
|
|
27
|
+
export const MAX_QUOTE_CHARS = 300;
|
|
28
|
+
export const MAX_QUOTE_LINES = 3;
|
|
29
|
+
|
|
30
|
+
/** The first `n` lines of `text`, joined with `\n` (line endings normalised). */
|
|
31
|
+
const firstLines = (text: string, n: number): string => text.split(/\r?\n/).slice(0, n).join('\n');
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A quote as it may be stored: at most {@link MAX_QUOTE_LINES} lines and {@link MAX_QUOTE_CHARS}
|
|
35
|
+
* characters, trimmed at both ends — also after the cut, so clamping a clamped quote changes nothing.
|
|
36
|
+
*/
|
|
37
|
+
export function clampQuote(text: string): string {
|
|
38
|
+
return firstLines(text, MAX_QUOTE_LINES).trim().slice(0, MAX_QUOTE_CHARS).trimEnd();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const QUOTE_SEPARATOR = ' — “';
|
|
42
|
+
const QUOTE_CLOSE = '”';
|
|
43
|
+
/** The longest a claim's own text may be: subject, predicate and object at {@link MAX_TERM} characters each, joined by two spaces. */
|
|
44
|
+
export const MAX_CLAIM_TEXT_CHARS = 3 * MAX_TERM + 2;
|
|
45
|
+
|
|
46
|
+
/** A claim's stored `content`: its text, then its quote when it has one. */
|
|
47
|
+
export const claimContent = (text: string, quote: string): string => (quote ? `${text}${QUOTE_SEPARATOR}${quote}${QUOTE_CLOSE}` : text);
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The text a claim is compared by: `subject predicate object`, the form a first run hands the
|
|
51
|
+
* model — a stored claim's `content` without its quote. Both phases use it, so a claim reads
|
|
52
|
+
* the same whether it was judged this run or left awaiting by an earlier one.
|
|
53
|
+
*/
|
|
54
|
+
export function claimTextOf(content: string): string {
|
|
55
|
+
const i = content.indexOf(QUOTE_SEPARATOR);
|
|
56
|
+
return i < 0 ? content : content.slice(0, i);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A claim's `content` as a host may store it (privacy: a judgement, never a document): the
|
|
61
|
+
* text bounded to {@link MAX_CLAIM_TEXT_CHARS} characters (its terms may span lines, as the
|
|
62
|
+
* judge validates them), the quote it rests on by {@link clampQuote} — so a long claim is not
|
|
63
|
+
* cut mid-quote. Content the judge produced passes unchanged; an empty quote is dropped (the
|
|
64
|
+
* canonical {@link claimContent} form); clamping a clamped claim changes nothing.
|
|
65
|
+
*/
|
|
66
|
+
export function clampClaim(content: string): string {
|
|
67
|
+
const text = claimTextOf(content).slice(0, MAX_CLAIM_TEXT_CHARS);
|
|
68
|
+
const at = content.indexOf(QUOTE_SEPARATOR);
|
|
69
|
+
if (at < 0) return text;
|
|
70
|
+
const rest = content.slice(at + QUOTE_SEPARATOR.length);
|
|
71
|
+
return claimContent(text, clampQuote(rest.endsWith(QUOTE_CLOSE) ? rest.slice(0, -QUOTE_CLOSE.length) : rest));
|
|
72
|
+
}
|
|
28
73
|
|
|
29
74
|
export interface JudgeBudget {
|
|
30
75
|
modelCalls: number;
|
|
@@ -70,7 +115,7 @@ function validClaim(c: unknown): JudgedClaim | undefined {
|
|
|
70
115
|
const o = c as Record<string, unknown>;
|
|
71
116
|
const subject = str(o['subject'], MAX_TERM), predicate = str(o['predicate'], MAX_TERM), object = str(o['object'], MAX_TERM);
|
|
72
117
|
if (!subject || !predicate || !object || typeof o['quote'] !== 'string') return undefined;
|
|
73
|
-
const quote = (o['quote'] as string)
|
|
118
|
+
const quote = clampQuote(o['quote'] as string);
|
|
74
119
|
return { subject, predicate, object, quote };
|
|
75
120
|
}
|
|
76
121
|
|
|
@@ -111,11 +156,11 @@ export function validateCompare(result: unknown, a: NodeRef, b: NodeRef): { rela
|
|
|
111
156
|
return { confidence: 0, invalid: Math.max(invalid, 1) };
|
|
112
157
|
}
|
|
113
158
|
|
|
114
|
-
/** One model call
|
|
115
|
-
async function call(port: JudgementPort, req: Parameters<JudgementPort['judge']>[0], b: JudgeBudget): Promise<unknown> {
|
|
159
|
+
/** One model call; `undefined` when the port throws (an abort is re-thrown) — the item was NOT judged. */
|
|
160
|
+
async function call(port: JudgementPort, req: Parameters<JudgementPort['judge']>[0], b: JudgeBudget): Promise<{ result: unknown } | undefined> {
|
|
116
161
|
b.used += 1;
|
|
117
162
|
try {
|
|
118
|
-
return await port.judge(req);
|
|
163
|
+
return { result: await port.judge(req) };
|
|
119
164
|
} catch (err) {
|
|
120
165
|
if (req.signal?.aborted) throw err;
|
|
121
166
|
return undefined;
|
|
@@ -139,17 +184,21 @@ export interface ExtractArgs {
|
|
|
139
184
|
onJudged(ref: NodeRef): void;
|
|
140
185
|
}
|
|
141
186
|
|
|
142
|
-
/** Judges each section within the budget; the rest are counted `unjudged`. */
|
|
187
|
+
/** Judges each section within the budget; the rest — and any whose call failed — are counted `unjudged`. */
|
|
143
188
|
export async function judgeSections(a: ExtractArgs): Promise<Array<{ ref: NodeRef; text: string }>> {
|
|
144
189
|
const claims: Array<{ ref: NodeRef; text: string }> = [];
|
|
145
190
|
const anchor = { path: a.path, contentHash: a.fileHash };
|
|
146
191
|
for (const section of a.sections) {
|
|
192
|
+
// Honoured per section, not only when the port throws: the caller drops this file whole.
|
|
193
|
+
if (a.signal?.aborted) throw a.signal.reason ?? new Error('aborted');
|
|
147
194
|
if (!budgetLeft(a.budget)) { a.batch.unjudged += 1; continue; }
|
|
148
|
-
const
|
|
195
|
+
const answer = await call(a.port, {
|
|
149
196
|
kind: 'extract', items: [{ ref: section.ref, text: section.text, sourceHash: a.fileHash }],
|
|
150
197
|
...(a.signal ? { signal: a.signal } : {}),
|
|
151
198
|
}, a.budget);
|
|
152
|
-
|
|
199
|
+
// A failed call judged nothing: not counted judged, so the file stays changed and is retried.
|
|
200
|
+
if (!answer) { a.batch.unjudged += 1; continue; }
|
|
201
|
+
const v = validateExtract(answer.result, section.ref);
|
|
153
202
|
a.batch.invalid += v.invalid;
|
|
154
203
|
a.batch.judged += 1;
|
|
155
204
|
a.onJudged(section.ref);
|
|
@@ -175,7 +224,7 @@ export async function judgeSections(a: ExtractArgs): Promise<Array<{ ref: NodeRe
|
|
|
175
224
|
const key = `claim:${hashText([section.ref, c.subject, c.predicate, c.object].join('\u0000'))}`;
|
|
176
225
|
const text = `${c.subject} ${c.predicate} ${c.object}`;
|
|
177
226
|
a.batch.fact({
|
|
178
|
-
key, content:
|
|
227
|
+
key, content: claimContent(text, c.quote), source: REVIEW_FACT_SOURCE,
|
|
179
228
|
importance: 0.5, origin: 'model', fileAnchors: [anchor],
|
|
180
229
|
});
|
|
181
230
|
const ref = factRef(key);
|
|
@@ -200,26 +249,45 @@ export interface CompareArgs {
|
|
|
200
249
|
signal?: AbortSignal;
|
|
201
250
|
}
|
|
202
251
|
|
|
252
|
+
export interface CompareOutcome {
|
|
253
|
+
/** Claim refs in a pair that was NOT compared (budget, failed call, abort) — still awaiting comparison. */
|
|
254
|
+
skipped: Set<string>;
|
|
255
|
+
/** The abort landed before every pair was compared. */
|
|
256
|
+
aborted: boolean;
|
|
257
|
+
}
|
|
258
|
+
|
|
203
259
|
/** Near-duplicate claim pairs, most similar first, compared within the budget. */
|
|
204
|
-
export async function compareClaims(a: CompareArgs): Promise<
|
|
260
|
+
export async function compareClaims(a: CompareArgs): Promise<CompareOutcome> {
|
|
261
|
+
const out: CompareOutcome = { skipped: new Set(), aborted: false };
|
|
205
262
|
const pairs = [...a.pairs]
|
|
206
263
|
.filter((p) => p.a !== p.b && a.claims.has(p.a) && a.claims.has(p.b))
|
|
207
264
|
.map((p) => (compareStr(p.a, p.b) <= 0 ? p : { a: p.b, b: p.a, similarity: p.similarity }))
|
|
208
265
|
.sort((x, y) => y.similarity - x.similarity || compareStr(x.a, y.a) || compareStr(x.b, y.b));
|
|
266
|
+
const skip = (p: { a: string; b: string }) => { out.skipped.add(p.a); out.skipped.add(p.b); };
|
|
267
|
+
const abort = (from: number) => { out.aborted = true; for (const p of pairs.slice(from)) skip(p); return out; };
|
|
209
268
|
const seen = new Set<string>();
|
|
210
|
-
for (const p of pairs) {
|
|
269
|
+
for (const [i, p] of pairs.entries()) {
|
|
211
270
|
const id = `${p.a}\u0000${p.b}`;
|
|
212
271
|
if (seen.has(id)) continue;
|
|
213
272
|
seen.add(id);
|
|
214
|
-
if (
|
|
273
|
+
if (a.signal?.aborted) return abort(i);
|
|
274
|
+
if (!budgetLeft(a.budget)) { a.batch.unjudged += 1; skip(p); continue; }
|
|
215
275
|
const ca = a.claims.get(p.a)!, cb = a.claims.get(p.b)!;
|
|
216
276
|
const A = p.a as NodeRef, B = p.b as NodeRef;
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
277
|
+
let answer;
|
|
278
|
+
try {
|
|
279
|
+
answer = await call(a.port, {
|
|
280
|
+
kind: 'compare',
|
|
281
|
+
items: [{ ref: A, text: ca.text, sourceHash: ca.hash }, { ref: B, text: cb.text, sourceHash: cb.hash }],
|
|
282
|
+
...(a.signal ? { signal: a.signal } : {}),
|
|
283
|
+
}, a.budget);
|
|
284
|
+
} catch (err) {
|
|
285
|
+
if (!a.signal?.aborted) throw err;
|
|
286
|
+
return abort(i);
|
|
287
|
+
}
|
|
288
|
+
// A failed call compared nothing: counted unjudged, and the claims stay awaiting.
|
|
289
|
+
if (!answer) { a.batch.unjudged += 1; skip(p); continue; }
|
|
290
|
+
const v = validateCompare(answer.result, A, B);
|
|
223
291
|
a.batch.invalid += v.invalid;
|
|
224
292
|
a.batch.judged += 1;
|
|
225
293
|
if (v.relation === 'contradicts' || v.relation === 'agrees') {
|
|
@@ -228,4 +296,5 @@ export async function compareClaims(a: CompareArgs): Promise<void> {
|
|
|
228
296
|
});
|
|
229
297
|
}
|
|
230
298
|
}
|
|
299
|
+
return out;
|
|
231
300
|
}
|
package/src/knowledge/model.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* ones are stored with the content hash they were judged from and go stale when it changes.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import type {
|
|
13
|
+
import type { SourceDocument, ParsedSection } from '../ingest/types.js';
|
|
14
14
|
import type { IndexDoc, SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
15
15
|
|
|
16
16
|
/** `src:${rootId}::${path}` · `ent:${pack}:${normalizedName}` · `fact:${key}` (claims are `fact:claim:${hash}`). */
|
|
@@ -49,12 +49,22 @@ export interface KEdge {
|
|
|
49
49
|
confidence?: number;
|
|
50
50
|
verdict?: EdgeVerdict;
|
|
51
51
|
cycle?: boolean;
|
|
52
|
+
/** A stored relation whose source changed since it was judged (§5.2): shown, never treated as current. */
|
|
53
|
+
stale?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Extracted edges only: the `[[Name]]` this link was written with. `buildGraph` re-points
|
|
56
|
+
* the edge to the one present file of that name (else it keeps its beside-the-file
|
|
57
|
+
* target) — so the cached extract never depends on which other files exist. Never emitted.
|
|
58
|
+
*/
|
|
59
|
+
byName?: string;
|
|
52
60
|
}
|
|
53
61
|
|
|
54
62
|
/** Output of a pack's deterministic extractor (or analyzer) for one source. Never stored. */
|
|
55
63
|
export interface Extracted {
|
|
56
64
|
sourceRef: NodeRef;
|
|
57
65
|
sourceHash: string;
|
|
66
|
+
/** The extractor version (`EXTRACTOR_VERSION`) that produced it; a cached entry of another version is ignored. */
|
|
67
|
+
extractorVersion?: number;
|
|
58
68
|
nodes: KNode[];
|
|
59
69
|
edges: KEdge[];
|
|
60
70
|
/** Exact keys for entity resolution and the index's exact tier. */
|
|
@@ -204,15 +214,6 @@ export interface KnowledgeStore {
|
|
|
204
214
|
putExtracted?(hash: string, extracted: Extracted[]): Promise<void>;
|
|
205
215
|
}
|
|
206
216
|
|
|
207
|
-
/** Where files come from: one adapter per host. */
|
|
208
|
-
export interface DirectorySource {
|
|
209
|
-
rootId: string;
|
|
210
|
-
title: string;
|
|
211
|
-
list(): AsyncIterable<{ path: string; hash: string; size: number }>;
|
|
212
|
-
read(path: string): Promise<SourceDocument>;
|
|
213
|
-
watch?(cb: (paths: string[]) => void): () => void;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
217
|
export interface LiveOverlay {
|
|
217
218
|
changes: Array<{ path: string; status: string; added: number; removed: number }>;
|
|
218
219
|
/** Files touched together in one run → co-changed edges. */
|
|
@@ -227,53 +228,6 @@ export interface KnowledgeGraph {
|
|
|
227
228
|
stats: { sources: number; nodes: number; edges: number; stale: number; truncated: boolean };
|
|
228
229
|
}
|
|
229
230
|
|
|
230
|
-
export interface ReviewPlan {
|
|
231
|
-
rootId: string;
|
|
232
|
-
files: number;
|
|
233
|
-
byPack: Record<string, number>;
|
|
234
|
-
unchanged: number;
|
|
235
|
-
changed: string[];
|
|
236
|
-
removed: string[];
|
|
237
|
-
skipped: Array<{ path: string; reason: 'ignored' | 'binary' | 'too-large' | 'no-pack' }>;
|
|
238
|
-
/** ≈ judgement calls for changed files (sections of judged kinds). */
|
|
239
|
-
estimatedModelCalls: number;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
export interface ReviewProgress {
|
|
243
|
-
phase: 'plan' | 'extract' | 'resolve' | 'judge' | 'write' | 'index' | 'done';
|
|
244
|
-
done: number;
|
|
245
|
-
total: number;
|
|
246
|
-
path?: string;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
export interface ReviewReport {
|
|
250
|
-
rootId: string;
|
|
251
|
-
digest: string;
|
|
252
|
-
extracted: number;
|
|
253
|
-
judged: number;
|
|
254
|
-
/** Sections left extracted-only because the budget ran out. */
|
|
255
|
-
unjudged: number;
|
|
256
|
-
invalidJudgements: number;
|
|
257
|
-
factsWritten: number;
|
|
258
|
-
relationsWritten: number;
|
|
259
|
-
staleMarked: number;
|
|
260
|
-
aborted: boolean;
|
|
261
|
-
durationMs: number;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
export interface ReviewArgs {
|
|
265
|
-
source: DirectorySource;
|
|
266
|
-
store: KnowledgeStore;
|
|
267
|
-
packs: KnowledgePack[];
|
|
268
|
-
manifest: IngestManifest;
|
|
269
|
-
judgement?: JudgementPort;
|
|
270
|
-
/** Near-duplicate claim pairs to compare / possible-same entities; from the knowledge index. */
|
|
271
|
-
similar?: (ids: string[]) => Promise<SimilarPair[]>;
|
|
272
|
-
budget: { modelCalls: number; ms: number };
|
|
273
|
-
signal?: AbortSignal;
|
|
274
|
-
onProgress?(p: ReviewProgress): void;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
231
|
export interface BuildGraphInput {
|
|
278
232
|
rootId: string;
|
|
279
233
|
extracted: Extracted[];
|
|
@@ -310,3 +264,7 @@ export interface Trace {
|
|
|
310
264
|
|
|
311
265
|
/** Re-exported for card consumers. */
|
|
312
266
|
export type { IndexDoc };
|
|
267
|
+
/** The review's ports and reports live beside it (reviewModel.ts); re-exported so one import serves. */
|
|
268
|
+
export type {
|
|
269
|
+
DirectorySource, ReviewPlan, ReviewProgress, ReviewReport, ReviewArgs,
|
|
270
|
+
} from './reviewModel.js';
|