@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
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/reviewCompare.ts — the compare phase of a review (PRD 38 §4.3): near-duplicate
|
|
3
|
+
* claim pairs → `contradicts` / `agrees`. Claims whose pairs could not all be compared
|
|
4
|
+
* (budget, a failed call, an abort) are kept in the compare manifest, so *Continue* picks
|
|
5
|
+
* them up at the next run instead of losing them.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { IngestManifest } from '../ingest/types.js';
|
|
9
|
+
import { claimTextOf, compareClaims, type CompareOutcome, type JudgeBudget, type JudgedBatch } from './judge.js';
|
|
10
|
+
import type { NodeRef, ReviewArgs, StoredFact } from './model.js';
|
|
11
|
+
import { compareManifestKey } from './sources.js';
|
|
12
|
+
import { compareStr, factKeyOf } from './refs.js';
|
|
13
|
+
|
|
14
|
+
/** At most this many claims wait for *Continue*; beyond it the oldest are dropped (the set stays bounded). */
|
|
15
|
+
export const MAX_AWAITING_CLAIMS = 2000;
|
|
16
|
+
|
|
17
|
+
/** A claim awaiting comparison: its text and the content hash it was judged from. */
|
|
18
|
+
export type PendingClaims = Map<string, { text: string; hash: string }>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The compare manifest persists age with each entry — `hash` is `<age>:<fileHash>`, age 0 the
|
|
22
|
+
* oldest — because a host manifest may hand entries back in id order. An entry without an age
|
|
23
|
+
* (written before ages were kept) reads as the oldest.
|
|
24
|
+
*/
|
|
25
|
+
const ageOf = (hash: string): number => {
|
|
26
|
+
const sep = hash.indexOf(':');
|
|
27
|
+
const age = sep < 0 ? NaN : Number(hash.slice(0, sep));
|
|
28
|
+
return Number.isFinite(age) ? age : -1;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Claims a previous run left awaiting comparison, oldest first, read back from their stored facts (a gone fact drops out). */
|
|
32
|
+
export async function pendingClaims(manifest: IngestManifest, rootId: string, facts: ReadonlyMap<string, StoredFact>): Promise<PendingClaims> {
|
|
33
|
+
const out: PendingClaims = new Map();
|
|
34
|
+
const stored = (await manifest.get(compareManifestKey(rootId))) ?? [];
|
|
35
|
+
const oldestFirst = [...stored].sort((a, b) => ageOf(a.hash) - ageOf(b.hash) || compareStr(a.id, b.id));
|
|
36
|
+
for (const { id: ref } of oldestFirst) {
|
|
37
|
+
const fact = facts.get(factKeyOf(ref as NodeRef) ?? '');
|
|
38
|
+
if (fact?.key.startsWith('claim:')) out.set(ref, { text: claimTextOf(fact.content), hash: fact.fileAnchors[0]?.contentHash ?? '' });
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Compares `pending` against its near-duplicates, within the budget. Undefined when the
|
|
45
|
+
* phase cannot run (no judgement port, no index, nothing pending).
|
|
46
|
+
*/
|
|
47
|
+
export async function compareNew(a: {
|
|
48
|
+
args: ReviewArgs; pending: PendingClaims; known: ReadonlyMap<string, StoredFact>; budget: JudgeBudget; batch: JudgedBatch;
|
|
49
|
+
onPairs(total: number): void;
|
|
50
|
+
}): Promise<CompareOutcome | undefined> {
|
|
51
|
+
const { args, pending } = a;
|
|
52
|
+
if (!args.judgement || !args.similar || pending.size === 0) return undefined;
|
|
53
|
+
const pairs = await args.similar([...pending.keys()].sort(compareStr), new Map([...pending].map(([ref, c]) => [ref, c.text] as const)));
|
|
54
|
+
const claims: PendingClaims = new Map(pending);
|
|
55
|
+
for (const p of pairs) {
|
|
56
|
+
for (const id of [p.a, p.b]) {
|
|
57
|
+
const fact = !claims.has(id) ? a.known.get(factKeyOf(id as NodeRef) ?? '') : undefined;
|
|
58
|
+
if (fact?.key.startsWith('claim:')) claims.set(id, { text: claimTextOf(fact.content), hash: fact.fileAnchors[0]?.contentHash ?? '' });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
a.onPairs(pairs.length);
|
|
62
|
+
// Run even with the budget spent: compareClaims counts every pair it skips as unjudged.
|
|
63
|
+
return compareClaims({ port: args.judgement, pairs, claims, budget: a.budget, batch: a.batch, ...(args.signal ? { signal: args.signal } : {}) });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Persists the claims still awaiting comparison, capped at {@link MAX_AWAITING_CLAIMS} (the
|
|
68
|
+
* most recent: a previous run's first, this run's last — and the order survives the reload,
|
|
69
|
+
* see {@link pendingClaims}). Call it only when a pack asks for contradictions; an `outcome`
|
|
70
|
+
* undefined means the compare did not run (no ports, an abort before it), so every pending
|
|
71
|
+
* claim is kept, whereas after a compare only the pairs it skipped still wait.
|
|
72
|
+
*/
|
|
73
|
+
export async function saveAwaiting(
|
|
74
|
+
manifest: IngestManifest, rootId: string, pending: PendingClaims, outcome: CompareOutcome | undefined,
|
|
75
|
+
): Promise<void> {
|
|
76
|
+
const awaiting: Array<[string, string]> = [];
|
|
77
|
+
for (const [ref, c] of pending) if (!outcome || outcome.skipped.has(ref)) awaiting.push([ref, c.hash]);
|
|
78
|
+
const kept = awaiting.slice(-MAX_AWAITING_CLAIMS);
|
|
79
|
+
await manifest.set(compareManifestKey(rootId), kept.map(([id, hash], age) => ({ id, hash: `${age}:${hash}` })));
|
|
80
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/reviewModel.ts — the review's port and reports (PRD 38 §4.1, §4.3): where files
|
|
3
|
+
* come from, the confirm chip's plan, progress and the final report.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { IngestManifest, SourceDocument } from '../ingest/types.js';
|
|
7
|
+
import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
8
|
+
import type { JudgementPort, KnowledgePack, KnowledgeStore } from './model.js';
|
|
9
|
+
import type { PlanDetail } from './plan.js';
|
|
10
|
+
|
|
11
|
+
/** Where files come from: one adapter per host. */
|
|
12
|
+
export interface DirectorySource {
|
|
13
|
+
rootId: string;
|
|
14
|
+
title: string;
|
|
15
|
+
list(): AsyncIterable<{ path: string; hash: string; size: number }>;
|
|
16
|
+
read(path: string): Promise<SourceDocument>;
|
|
17
|
+
watch?(cb: (paths: string[]) => void): () => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ReviewPlan {
|
|
21
|
+
rootId: string;
|
|
22
|
+
files: number;
|
|
23
|
+
byPack: Record<string, number>;
|
|
24
|
+
unchanged: number;
|
|
25
|
+
changed: string[];
|
|
26
|
+
removed: string[];
|
|
27
|
+
skipped: Array<{ path: string; reason: 'ignored' | 'binary' | 'too-large' | 'no-pack' }>;
|
|
28
|
+
/** ≈ judgement calls for changed files (sections of judged kinds). */
|
|
29
|
+
estimatedModelCalls: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ReviewProgress {
|
|
33
|
+
phase: 'plan' | 'extract' | 'resolve' | 'judge' | 'write' | 'index' | 'done';
|
|
34
|
+
done: number;
|
|
35
|
+
total: number;
|
|
36
|
+
path?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ReviewReport {
|
|
40
|
+
rootId: string;
|
|
41
|
+
digest: string;
|
|
42
|
+
extracted: number;
|
|
43
|
+
judged: number;
|
|
44
|
+
/** Sections and compare pairs left for *Continue* (budget ran out, or a model call failed). */
|
|
45
|
+
unjudged: number;
|
|
46
|
+
invalidJudgements: number;
|
|
47
|
+
factsWritten: number;
|
|
48
|
+
relationsWritten: number;
|
|
49
|
+
staleMarked: number;
|
|
50
|
+
/**
|
|
51
|
+
* Files whose read threw: skipped, not retired — their facts, anchors and manifest hash are
|
|
52
|
+
* untouched, so the next review tries them again. A file that is truly gone shows up in
|
|
53
|
+
* the next fresh plan's `removed`.
|
|
54
|
+
*/
|
|
55
|
+
readErrors: number;
|
|
56
|
+
aborted: boolean;
|
|
57
|
+
durationMs: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface ReviewArgs {
|
|
61
|
+
source: DirectorySource;
|
|
62
|
+
store: KnowledgeStore;
|
|
63
|
+
packs: KnowledgePack[];
|
|
64
|
+
manifest: IngestManifest;
|
|
65
|
+
judgement?: JudgementPort;
|
|
66
|
+
/**
|
|
67
|
+
* Near-duplicate claim pairs to compare / possible-same entities; from the knowledge index.
|
|
68
|
+
* Called with the pending claim refs (sorted) and, as an optional second argument, each
|
|
69
|
+
* ref's claim text (`subject predicate object`, the form the compare uses) — so a host
|
|
70
|
+
* need not re-read every fact to recover what the review already holds. A port that takes
|
|
71
|
+
* only `ids` keeps working.
|
|
72
|
+
*/
|
|
73
|
+
similar?: (ids: string[], texts?: ReadonlyMap<string, string>) => Promise<SimilarPair[]>;
|
|
74
|
+
budget: { modelCalls: number; ms: number };
|
|
75
|
+
/** *Continue*: the plan the person confirmed. Reused without a re-walk; `changed` is re-read from the manifest. */
|
|
76
|
+
plan?: PlanDetail;
|
|
77
|
+
/** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
|
|
78
|
+
force?: boolean;
|
|
79
|
+
signal?: AbortSignal;
|
|
80
|
+
onProgress?(p: ReviewProgress): void;
|
|
81
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/reviewStored.ts — what a review reads back from the store: the stored model
|
|
3
|
+
* knowledge indexed for re-anchoring unchanged sections without a model call, and the
|
|
4
|
+
* rewrite that lets a fact outlive one of its deleted sources.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { NodeRef, StoredFact, StoredRelation } from './model.js';
|
|
8
|
+
import type { JudgedBatch } from './judge.js';
|
|
9
|
+
import { factKeyOf } from './refs.js';
|
|
10
|
+
|
|
11
|
+
/** Stored knowledge, indexed for re-anchoring unchanged sections without a model call. */
|
|
12
|
+
export class StoredIndex {
|
|
13
|
+
readonly facts: Map<string, StoredFact>;
|
|
14
|
+
private readonly from = new Map<string, StoredRelation[]>();
|
|
15
|
+
private readonly to = new Map<string, StoredRelation[]>();
|
|
16
|
+
|
|
17
|
+
constructor(facts: StoredFact[], relations: StoredRelation[]) {
|
|
18
|
+
this.facts = new Map(facts.map((f) => [f.key, f] as const));
|
|
19
|
+
for (const r of relations) {
|
|
20
|
+
if (r.origin !== 'model') continue;
|
|
21
|
+
(this.from.get(r.from) ?? this.from.set(r.from, []).get(r.from)!).push(r);
|
|
22
|
+
(this.to.get(r.to) ?? this.to.set(r.to, []).get(r.to)!).push(r);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** An unchanged section keeps its claims and mentions; they are re-anchored to the file's new hash. */
|
|
27
|
+
refresh(section: NodeRef, path: string, hash: string, batch: JudgedBatch, entities: Map<string, StoredFact>): void {
|
|
28
|
+
const reanchor = (f: StoredFact): StoredFact => ({
|
|
29
|
+
...f, fileAnchors: f.fileAnchors.map((a) => (a.path === path ? { ...a, contentHash: hash } : a)),
|
|
30
|
+
});
|
|
31
|
+
const relation = (r: StoredRelation) => batch.relation({ ...r, sourceHash: hash, staleAt: null });
|
|
32
|
+
for (const r of this.to.get(section) ?? []) {
|
|
33
|
+
if (r.kind !== 'about') continue;
|
|
34
|
+
relation(r);
|
|
35
|
+
const key = factKeyOf(r.from);
|
|
36
|
+
const fact = key && (batch.facts.get(key) ?? this.facts.get(key));
|
|
37
|
+
if (fact && fact.origin === 'model') batch.fact(reanchor(fact));
|
|
38
|
+
for (const m of this.from.get(r.from) ?? []) if (m.kind === 'mentions') relation(m);
|
|
39
|
+
}
|
|
40
|
+
for (const r of this.from.get(section) ?? []) {
|
|
41
|
+
if (r.kind !== 'mentions') continue;
|
|
42
|
+
relation(r);
|
|
43
|
+
const ent = entities.get(r.to);
|
|
44
|
+
if (ent && ent.origin === 'model') {
|
|
45
|
+
const next = reanchor(ent);
|
|
46
|
+
entities.set(r.to, next);
|
|
47
|
+
batch.fact(next);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Model facts anchored to `path` AND to another source, rewritten without that anchor — a
|
|
55
|
+
* deleted file never leaves a fact stale that other sources still back. A fact anchored only
|
|
56
|
+
* to `path` is untouched: it stays and shows stale (§5.2).
|
|
57
|
+
*/
|
|
58
|
+
export function factsWithoutAnchor(facts: Iterable<StoredFact>, path: string): StoredFact[] {
|
|
59
|
+
return [...facts]
|
|
60
|
+
.filter((f) => f.origin === 'model' && f.fileAnchors.length > 1 && f.fileAnchors.some((a) => a.path === path))
|
|
61
|
+
.map((f) => ({ ...f, fileAnchors: f.fileAnchors.filter((a) => a.path !== path) }));
|
|
62
|
+
}
|
package/src/knowledge/sources.ts
CHANGED
|
@@ -4,25 +4,45 @@
|
|
|
4
4
|
* `planReview` and `reviewDirectory`, so the plan's numbers and the run agree.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { ParserRegistry } from '../ingest/parsers.js';
|
|
7
|
+
import { htmlParser, markdownParser, ParserRegistry, plainTextParser } from '../ingest/parsers.js';
|
|
8
|
+
import { isBinaryDocumentType, mediaTypeOf } from '../ingest/parserSupport.js';
|
|
8
9
|
import { CONTENT_HASH_FIELD, type ChunkFingerprint, type IngestManifest, type SourceDocument } from '../ingest/types.js';
|
|
9
10
|
import type { KnowledgePack, KnowledgeParser } from './model.js';
|
|
10
11
|
import { matchGlob } from './partitions.js';
|
|
11
|
-
import { compareStr } from './refs.js';
|
|
12
|
+
import { compareStr, walkRelative } from './refs.js';
|
|
12
13
|
|
|
13
14
|
/** Default per-file size cap (bytes). */
|
|
14
15
|
export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
15
|
-
/**
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Version of the extractors' output. Bump it whenever an extractor emits different nodes,
|
|
18
|
+
* edges or keys for the same text: cached `Extracted` of another version is ignored, and a
|
|
19
|
+
* review that finds a different version in {@link extractorManifestKey} owes every file one
|
|
20
|
+
* re-extraction (judged sections with unchanged text are re-anchored, not judged again; see
|
|
21
|
+
* owedFiles.ts for how an unfinished one is carried to the next review).
|
|
22
|
+
*/
|
|
23
|
+
export const EXTRACTOR_VERSION = 1;
|
|
17
24
|
/** Always ignored: VCS internals, installed dependencies, builderforce config. */
|
|
18
|
-
const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '
|
|
25
|
+
const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore'];
|
|
19
26
|
|
|
20
27
|
const MEDIA_TYPES: Record<string, string> = {
|
|
21
28
|
md: 'text/markdown', markdown: 'text/markdown', mdx: 'text/markdown',
|
|
22
29
|
html: 'text/html', htm: 'text/html', xhtml: 'application/xhtml+xml', xml: 'application/xml',
|
|
23
30
|
json: 'application/json', csv: 'text/csv', tsv: 'text/tab-separated-values',
|
|
31
|
+
pdf: 'application/pdf',
|
|
32
|
+
doc: 'application/msword',
|
|
33
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
34
|
+
xls: 'application/vnd.ms-excel',
|
|
35
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
36
|
+
ppt: 'application/vnd.ms-powerpoint',
|
|
37
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
38
|
+
odt: 'application/vnd.oasis.opendocument.text',
|
|
39
|
+
ods: 'application/vnd.oasis.opendocument.spreadsheet',
|
|
40
|
+
odp: 'application/vnd.oasis.opendocument.presentation',
|
|
24
41
|
};
|
|
25
42
|
|
|
43
|
+
/** Binary documents whose text a HOST extractor may supply (§4.5); otherwise skipped as binary. */
|
|
44
|
+
const DOCUMENT_EXT = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
|
|
45
|
+
|
|
26
46
|
const BINARY_EXT = new Set([
|
|
27
47
|
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'icns', 'tif', 'tiff', 'psd', 'avif', 'heic',
|
|
28
48
|
'mp3', 'mp4', 'mov', 'avi', 'mkv', 'webm', 'wav', 'flac', 'ogg', 'm4a',
|
|
@@ -46,6 +66,20 @@ export function isBinaryPath(path: string): boolean {
|
|
|
46
66
|
return BINARY_EXT.has(extOf(path));
|
|
47
67
|
}
|
|
48
68
|
|
|
69
|
+
export function isDocumentPath(path: string): boolean {
|
|
70
|
+
return DOCUMENT_EXT.has(extOf(path));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The pack whose parser claims a pdf/office file's media type — a host-registered
|
|
75
|
+
* extractor, wherever its pack sits: {@link composePacks} makes the builtin text parsers
|
|
76
|
+
* refuse binary document types ({@link isBinaryDocumentType}), so without a host parser
|
|
77
|
+
* nothing claims it and it stays binary.
|
|
78
|
+
*/
|
|
79
|
+
export function resolveDocument(composed: ComposedPacks, path: string): ReturnType<ComposedPacks['resolve']> {
|
|
80
|
+
return composed.resolve(stubSource(path));
|
|
81
|
+
}
|
|
82
|
+
|
|
49
83
|
/** A NUL in the first 8 KB means binary, whatever the extension said. */
|
|
50
84
|
export function isBinaryText(text: string): boolean {
|
|
51
85
|
return text.slice(0, 8192).includes('\u0000');
|
|
@@ -70,9 +104,28 @@ export interface ComposedPacks {
|
|
|
70
104
|
resolve(source: SourceDocument): { parser: KnowledgeParser; pack: KnowledgePack } | undefined;
|
|
71
105
|
}
|
|
72
106
|
|
|
107
|
+
/** The builtin text parsers, which would otherwise claim an office file's XML/plain-text media type. */
|
|
108
|
+
const BUILTIN_TEXT_PARSERS: ReadonlySet<KnowledgeParser> = new Set<KnowledgeParser>([markdownParser, htmlParser, plainTextParser]);
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Within knowledge composition the builtin docs parsers do not accept binary document media
|
|
112
|
+
* types; a host-registered parser (any pack, any order) is untouched. The ingest pipeline
|
|
113
|
+
* keeps the builtins as they are.
|
|
114
|
+
*/
|
|
115
|
+
const guardBuiltin = (p: KnowledgeParser): KnowledgeParser =>
|
|
116
|
+
BUILTIN_TEXT_PARSERS.has(p) ? { ...p, accepts: (s) => !isBinaryDocumentType(mediaTypeOf(s)) && p.accepts(s) } : p;
|
|
117
|
+
|
|
73
118
|
export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
|
|
74
119
|
const owner = new Map<KnowledgeParser, KnowledgePack>();
|
|
75
|
-
|
|
120
|
+
const guarded = new Map<KnowledgeParser, KnowledgeParser>();
|
|
121
|
+
for (const pack of packs) {
|
|
122
|
+
for (const p of pack.parsers) {
|
|
123
|
+
if (guarded.has(p)) continue;
|
|
124
|
+
const g = guardBuiltin(p);
|
|
125
|
+
guarded.set(p, g);
|
|
126
|
+
owner.set(g, pack);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
76
129
|
const registry = new ParserRegistry([...owner.keys()]);
|
|
77
130
|
return {
|
|
78
131
|
registry,
|
|
@@ -88,9 +141,16 @@ export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
|
|
|
88
141
|
* A `.gitignore`-style matcher: `#` comments, `!` negation (last match wins), a trailing
|
|
89
142
|
* `/` for directories only, a `/` elsewhere anchors to the root, otherwise any depth.
|
|
90
143
|
*/
|
|
91
|
-
export function ignoreMatcher(texts:
|
|
144
|
+
export function ignoreMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
|
|
92
145
|
const rules: Array<{ glob: string; negate: boolean; dirOnly: boolean }> = [];
|
|
93
|
-
|
|
146
|
+
const lines = [
|
|
147
|
+
...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
|
|
148
|
+
...texts.flatMap((t) => {
|
|
149
|
+
const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
|
|
150
|
+
return text.split(/\r?\n/).map((line) => ({ line, base }));
|
|
151
|
+
}),
|
|
152
|
+
];
|
|
153
|
+
for (const { line, base } of lines) {
|
|
94
154
|
let p = line.replace(/\s+$/, '');
|
|
95
155
|
if (!p || p.startsWith('#')) continue;
|
|
96
156
|
const negate = p.startsWith('!');
|
|
@@ -99,7 +159,9 @@ export function ignoreMatcher(texts: readonly string[]): (path: string) => boole
|
|
|
99
159
|
if (dirOnly) p = p.slice(0, -1);
|
|
100
160
|
const anchored = p.includes('/');
|
|
101
161
|
p = p.replace(/^\//, '');
|
|
102
|
-
|
|
162
|
+
// A nested `.gitignore` scopes its patterns to its own folder.
|
|
163
|
+
const prefix = base ? `${base}/` : '';
|
|
164
|
+
if (p) rules.push({ glob: anchored ? `${prefix}${p}` : `${prefix}**/${p}`, negate, dirOnly });
|
|
103
165
|
}
|
|
104
166
|
return (path) => {
|
|
105
167
|
const segments = path.split('/');
|
|
@@ -113,10 +175,33 @@ export function ignoreMatcher(texts: readonly string[]): (path: string) => boole
|
|
|
113
175
|
};
|
|
114
176
|
}
|
|
115
177
|
|
|
178
|
+
/**
|
|
179
|
+
* The ignore files present in a listing, each with the folder its patterns are relative to,
|
|
180
|
+
* in precedence order (the last match wins): every `.gitignore` — the root's first, then
|
|
181
|
+
* nested ones by path — and `.builderforce/ignore` LAST, so it can override them.
|
|
182
|
+
*/
|
|
183
|
+
export function ignoreSourcesOf(paths: readonly string[]): Array<{ path: string; base: string }> {
|
|
184
|
+
const git: Array<{ path: string; base: string }> = [];
|
|
185
|
+
let builderforce = false;
|
|
186
|
+
for (const path of [...paths].sort(compareStr)) {
|
|
187
|
+
if (path === '.builderforce/ignore') builderforce = true;
|
|
188
|
+
else if (path === '.gitignore' || path.endsWith('/.gitignore')) {
|
|
189
|
+
if (path.split('/').some((seg) => seg === 'node_modules' || seg === '.git')) continue;
|
|
190
|
+
git.push({ path, base: path.slice(0, -'.gitignore'.length).replace(/\/$/, '') });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
git.sort((a, b) => Number(a.base !== '') - Number(b.base !== '') || compareStr(a.path, b.path));
|
|
194
|
+
return builderforce ? [...git, { path: '.builderforce/ignore', base: '' }] : git;
|
|
195
|
+
}
|
|
196
|
+
|
|
116
197
|
/** Manifest entry holding `{ id: path, hash }` for every reviewed file of a root. */
|
|
117
198
|
export const filesManifestKey = (rootId: string): string => `knowledge:${rootId}`;
|
|
199
|
+
/** Manifest entry holding the extractor version the files were last reviewed with, and the files still owed a re-extraction (owedFiles.ts). */
|
|
200
|
+
export const extractorManifestKey = (rootId: string): string => `knowledge:${rootId}:extractor`;
|
|
118
201
|
/** Manifest entry holding `{ id: sectionRef, hash: textHash }` for every judged section. */
|
|
119
202
|
export const judgedManifestKey = (rootId: string): string => `knowledge:${rootId}:judged`;
|
|
203
|
+
/** Manifest entry holding `{ id: claimRef, hash: '<age>:<fileHash>' }` for every claim still awaiting comparison (age 0 = oldest). */
|
|
204
|
+
export const compareManifestKey = (rootId: string): string => `knowledge:${rootId}:compare`;
|
|
120
205
|
|
|
121
206
|
export async function manifestMap(manifest: IngestManifest, key: string): Promise<Map<string, string>> {
|
|
122
207
|
const prior: ChunkFingerprint[] = (await manifest.get(key)) ?? [];
|
|
@@ -130,17 +215,9 @@ export async function saveManifestMap(manifest: IngestManifest, key: string, map
|
|
|
130
215
|
|
|
131
216
|
/**
|
|
132
217
|
* Resolves a link/import target against the linking file's folder (a leading `/` is the
|
|
133
|
-
* root). Pure path arithmetic: undefined
|
|
218
|
+
* root). Pure path arithmetic: undefined when the target escapes the root or is the root itself.
|
|
134
219
|
*/
|
|
135
220
|
export function resolveRelativePath(fromPath: string, target: string): string | undefined {
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
for (const seg of t.split('/')) {
|
|
139
|
-
if (seg === '' || seg === '.') continue;
|
|
140
|
-
if (seg === '..') {
|
|
141
|
-
if (out.length === 0) return undefined;
|
|
142
|
-
out.pop();
|
|
143
|
-
} else out.push(seg);
|
|
144
|
-
}
|
|
145
|
-
return out.length ? out.join('/') : undefined;
|
|
221
|
+
const { ups, segments } = walkRelative(fromPath, target);
|
|
222
|
+
return ups > 0 || segments.length === 0 ? undefined : segments.join('/');
|
|
146
223
|
}
|
|
@@ -4,9 +4,13 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { hashText } from '../ingest/hash.js';
|
|
7
|
+
import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
|
|
8
|
+
import { buildGraph } from './build.js';
|
|
7
9
|
import type {
|
|
8
|
-
DirectorySource, Extracted, JudgementPort, JudgementRequest, JudgementResult, KEdge, KNode, NodeRef,
|
|
10
|
+
DirectorySource, Extracted, JudgementPort, JudgementRequest, JudgementResult, KEdge, KNode, KnowledgePack, KnowledgeStore, NodeRef, ReviewArgs,
|
|
9
11
|
} from './model.js';
|
|
12
|
+
import { loadExtractorState } from './owedFiles.js';
|
|
13
|
+
import { DOCS_PACK } from './packs/docs.js';
|
|
10
14
|
import { LocalSnapshotStore, type SnapshotPersistence } from './stores/localSnapshotStore.js';
|
|
11
15
|
import { srcRef } from './refs.js';
|
|
12
16
|
|
|
@@ -46,6 +50,27 @@ export function memStore(): LocalSnapshotStore {
|
|
|
46
50
|
return new LocalSnapshotStore(memPersistence(), { now: () => '2026-10-28T00:00:00.000Z' });
|
|
47
51
|
}
|
|
48
52
|
|
|
53
|
+
/** Three one-section docs, the common fixture of the review tests. */
|
|
54
|
+
export const FILES = { 'a.md': '# A\nalpha\n', 'b.md': '# B\nbeta\n', 'c.md': '# C\ngamma\n' };
|
|
55
|
+
export const ALL = ['a.md', 'b.md', 'c.md'];
|
|
56
|
+
|
|
57
|
+
/** `ReviewArgs` over the docs pack with a generous budget; `extra` overrides anything. */
|
|
58
|
+
export const args = (
|
|
59
|
+
source: SpySource, store: KnowledgeStore = memStore(), manifest = new InMemoryIngestManifest(), extra: Partial<ReviewArgs> = {},
|
|
60
|
+
): ReviewArgs => ({ source, store, manifest, packs: [DOCS_PACK], budget: { modelCalls: 200, ms: 60_000 }, ...extra });
|
|
61
|
+
|
|
62
|
+
/** A root's extractor entry as `{ version, owed: sorted paths }`. */
|
|
63
|
+
export async function stateOf(manifest: InMemoryIngestManifest) {
|
|
64
|
+
const { version, owed } = await loadExtractorState(manifest, ROOT);
|
|
65
|
+
return { version, owed: [...owed.keys()].sort() };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A `similar` port that pairs the first two ids it is given (nothing to pair with fewer). */
|
|
69
|
+
export const similar = async (ids: string[]) => (ids.length >= 2 ? [{ a: ids[0]!, b: ids[1]!, similarity: 0.95 }] : []);
|
|
70
|
+
|
|
71
|
+
/** The docs pack with contradictions off: no compare phase, so no awaiting set. */
|
|
72
|
+
export const quietPack: KnowledgePack = { ...DOCS_PACK, judgement: { ...DOCS_PACK.judgement!, contradictions: false } };
|
|
73
|
+
|
|
49
74
|
/** Answers every extract with one claim + one entity, every compare with `contradicts`. */
|
|
50
75
|
export function fakeJudge(
|
|
51
76
|
shape: (req: JudgementRequest) => JudgementResult = defaultJudgement,
|
|
@@ -90,3 +115,16 @@ export function extractedOf(node: KNode, edges: KEdge[] = []): Extracted {
|
|
|
90
115
|
}
|
|
91
116
|
|
|
92
117
|
export const ref = (path: string): NodeRef => srcRef(ROOT, path);
|
|
118
|
+
|
|
119
|
+
/** The graph of a reviewed source: its files' cached extracts joined with what the store holds. */
|
|
120
|
+
export async function graphOf(source: SpySource, store: KnowledgeStore) {
|
|
121
|
+
const extracted: Extracted[] = [];
|
|
122
|
+
for await (const f of source.list()) {
|
|
123
|
+
const hit = (await store.getExtracted!(f.hash))?.find((e) => e.sourceRef === srcRef(ROOT, f.path));
|
|
124
|
+
if (hit) extracted.push(hit);
|
|
125
|
+
}
|
|
126
|
+
return buildGraph({
|
|
127
|
+
rootId: ROOT, extracted, packs: [DOCS_PACK],
|
|
128
|
+
facts: await store.facts({ rootId: ROOT }), relations: await store.relations({ rootId: ROOT }),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* knowledge/truncate.ts — the graph opens bounded (PRD 38 §5.3).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* neighbours of all of those
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* The top `maxNodes` by importance (then ref), PLUS focus nodes, every node named by a
|
|
5
|
+
* finding, changed nodes and the 1-hop neighbours of all of those — up to the hard cap.
|
|
6
|
+
* Everything else folds into `area` nodes; edges are re-pointed to the areas, merged, and
|
|
7
|
+
* self-loops dropped.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { EdgeVerdict, KEdge, KNode, KnowledgeGraph, NodeRef } from './model.js';
|
|
11
11
|
import { areaImportance, byImportance } from './importance.js';
|
|
12
|
-
import { compareStr, pathOfRef, srcRef } from './refs.js';
|
|
12
|
+
import { aboutTargets, compareStr, pathOfRef, srcRef } from './refs.js';
|
|
13
13
|
|
|
14
14
|
/** Hard cap on nodes, however many the keep rules ask for. */
|
|
15
15
|
export const TRUNCATION_HARD_CAP = 2000;
|
|
@@ -50,14 +50,10 @@ export function truncateGraph(g: KnowledgeGraph, opts: TruncateOptions): { nodes
|
|
|
50
50
|
const around = [...(neighbours.get(s) ?? [])].map((r) => byRef.get(r)!).filter(Boolean).sort(byImportance);
|
|
51
51
|
for (const n of around) keep(n.ref);
|
|
52
52
|
}
|
|
53
|
-
for (const n of [...g.nodes].sort(byImportance))
|
|
54
|
-
if (kept.length >= opts.maxNodes) break;
|
|
55
|
-
keep(n.ref);
|
|
56
|
-
}
|
|
53
|
+
for (const n of [...g.nodes].sort(byImportance).slice(0, opts.maxNodes)) keep(n.ref);
|
|
57
54
|
|
|
58
55
|
// Fold the rest into areas.
|
|
59
|
-
const aboutTarget =
|
|
60
|
-
for (const e of g.edges) if (e.kind === 'about' && !aboutTarget.has(e.from)) aboutTarget.set(e.from, e.to);
|
|
56
|
+
const aboutTarget = aboutTargets(g.edges);
|
|
61
57
|
const rootId = g.scope.rootId;
|
|
62
58
|
const areaOf = (n: KNode): NodeRef => {
|
|
63
59
|
if (n.area) return n.area;
|
|
@@ -96,6 +92,7 @@ export function truncateGraph(g: KnowledgeGraph, opts: TruncateOptions): { nodes
|
|
|
96
92
|
if (!prior) { edges.set(id, { ...e, from, to }); continue; }
|
|
97
93
|
prior.weight += e.weight;
|
|
98
94
|
if (e.cycle) prior.cycle = true;
|
|
95
|
+
if (e.stale) prior.stale = true;
|
|
99
96
|
if (e.confidence !== undefined) prior.confidence = Math.max(prior.confidence ?? 0, e.confidence);
|
|
100
97
|
if (e.verdict && (!prior.verdict || VERDICT_RANK[e.verdict] > VERDICT_RANK[prior.verdict])) prior.verdict = e.verdict;
|
|
101
98
|
}
|
package/src/wire/chatClient.ts
CHANGED
|
@@ -76,6 +76,11 @@ export interface ChatClient {
|
|
|
76
76
|
apiKey: string;
|
|
77
77
|
/** Abort a request after this long. Default: no limit beyond the caller's signal. */
|
|
78
78
|
timeoutMs?: number;
|
|
79
|
+
/**
|
|
80
|
+
* Extra request headers a gateway needs (tenant / run attribution, …). They cannot
|
|
81
|
+
* override `Content-Type`, `Authorization` or `Accept`.
|
|
82
|
+
*/
|
|
83
|
+
headers?: Record<string, string>;
|
|
79
84
|
}
|
|
80
85
|
|
|
81
86
|
/** A non-2xx answer, with the status and (bounded) body kept apart for the caller's message. */
|
|
@@ -88,6 +93,13 @@ export class ChatCompletionError extends Error {
|
|
|
88
93
|
|
|
89
94
|
const ERROR_BODY_CHARS = 300;
|
|
90
95
|
|
|
96
|
+
/** Header names the client owns; `ChatClient.headers` may not set them, in any letter case. */
|
|
97
|
+
const RESERVED_HEADERS = new Set(['content-type', 'authorization', 'accept']);
|
|
98
|
+
|
|
99
|
+
function extraHeaders(headers: Record<string, string> | undefined): Record<string, string> {
|
|
100
|
+
return Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => !RESERVED_HEADERS.has(name.toLowerCase())));
|
|
101
|
+
}
|
|
102
|
+
|
|
91
103
|
function chatBody(req: ChatRequest, stream: boolean): string {
|
|
92
104
|
return JSON.stringify({
|
|
93
105
|
...(req.model ? { model: req.model } : {}),
|
|
@@ -108,6 +120,7 @@ async function post(client: ChatClient, req: ChatRequest, stream: boolean, signa
|
|
|
108
120
|
const res = await fetch(`${client.baseUrl.replace(/\/$/, '')}/chat/completions`, {
|
|
109
121
|
method: 'POST',
|
|
110
122
|
headers: {
|
|
123
|
+
...extraHeaders(client.headers),
|
|
111
124
|
'Content-Type': 'application/json',
|
|
112
125
|
Authorization: `Bearer ${client.apiKey}`,
|
|
113
126
|
...(stream ? { Accept: 'text/event-stream' } : {}),
|