@tangle-network/agent-knowledge 1.7.0 → 1.8.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/README.md +77 -1
- package/dist/chunk-MU5CEOGE.js +387 -0
- package/dist/chunk-MU5CEOGE.js.map +1 -0
- package/dist/{chunk-HKYD765Q.js → chunk-WWY5FTKQ.js} +11 -14
- package/dist/chunk-WWY5FTKQ.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +264 -2
- package/dist/index.js +273 -9
- package/dist/index.js.map +1 -1
- package/dist/profiles/index.d.ts +1 -1
- package/dist/profiles/index.js +4 -361
- package/dist/profiles/index.js.map +1 -1
- package/docs/recursive-research-leaf.md +86 -0
- package/package.json +4 -4
- package/dist/chunk-HKYD765Q.js.map +0 -1
package/README.md
CHANGED
|
@@ -29,7 +29,8 @@ Two ways in, depending on what you're doing:
|
|
|
29
29
|
- **Author / inspect a KB by hand** → the [CLI](#cli) (`init` → `source-add` → `index` → `search` → `lint`). Fastest way to see the shape on disk.
|
|
30
30
|
- **Drive it from an agent** → pick the primitive by intent:
|
|
31
31
|
- *"Does the agent have enough context to run?"* → [`buildEvalKnowledgeBundle`](#agent-eval-integration) (block / ask / acquire before execution).
|
|
32
|
-
- *"Grow the KB as a researcher"* → [`runKnowledgeResearchLoop`](#research-loop) (deterministic mechanics; your agent owns judgment) or the sandbox [researcher profile](#researcher-profile) for `runLoop`.
|
|
32
|
+
- *"Grow the KB as a researcher"* → [`runKnowledgeResearchLoop`](#research-loop) (deterministic mechanics; your agent owns judgment), [`runTwoAgentResearchLoop`](#two-agent-research-loop) (researcher proposes, verifier checks + fills gaps, offline), or the sandbox [researcher profile](#researcher-profile) for `runLoop`.
|
|
33
|
+
- *"Spawn one researcher per sub-topic and stop when the KB is ready"* → [`runResearchSupervisor`](#research-supervisor) (a supervisor brain sizes the topology over a `Scope`; LIVE, needs creds).
|
|
33
34
|
- *"Does this candidate KB actually improve task success?"* → run an [agent-eval improvement loop](#agent-eval-integration) over KB variants, then `knowledgeReleaseReport` for the promotion decision.
|
|
34
35
|
- *"Keep live authorities fresh"* → [pluggable sources](#pluggable-knowledge-sources) + `detectChanges` → eval re-runs.
|
|
35
36
|
|
|
@@ -260,6 +261,81 @@ await runAgentControlLoop({
|
|
|
260
261
|
})
|
|
261
262
|
```
|
|
262
263
|
|
|
264
|
+
## Two-agent research loop
|
|
265
|
+
|
|
266
|
+
`runTwoAgentResearchLoop()` is the offline sibling of `runKnowledgeResearchLoop`
|
|
267
|
+
with a differentiated worker/driver split over ONE knowledge base: the `worker`
|
|
268
|
+
does primary research (discovers sources, proposes pages for the open gaps); the
|
|
269
|
+
`driver` verifies each candidate source before it commits, optionally gap-fills
|
|
270
|
+
with its own pass (`driverResearches: true`), and gates on the readiness check.
|
|
271
|
+
Both are yours (no creds) — the loop owns the deterministic mechanics (indexing,
|
|
272
|
+
applying write blocks, scoring readiness) and stops once no blocking gap remains.
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import {
|
|
276
|
+
defineReadinessSpec,
|
|
277
|
+
runTwoAgentResearchLoop,
|
|
278
|
+
} from '@tangle-network/agent-knowledge'
|
|
279
|
+
|
|
280
|
+
await runTwoAgentResearchLoop({
|
|
281
|
+
root: './kb',
|
|
282
|
+
goal: 'Build a grounded onboarding wiki for billing support',
|
|
283
|
+
readinessSpecs: [defineReadinessSpec({
|
|
284
|
+
id: 'refund-policy',
|
|
285
|
+
description: 'Refund policy grounding',
|
|
286
|
+
query: 'refund policy customer request',
|
|
287
|
+
requiredFor: ['support-agent'],
|
|
288
|
+
})],
|
|
289
|
+
// WORKER: primary research targeting `ctx.gaps`. Returns a ResearchContribution.
|
|
290
|
+
async worker({ gaps, index }) {
|
|
291
|
+
return {
|
|
292
|
+
sources: [/* AddSourceTextInput for the open gaps */],
|
|
293
|
+
proposalText: '/* ---FILE: knowledge/…--- write-protocol blocks */',
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
// DRIVER: verifies each candidate source before it commits, then gates.
|
|
297
|
+
driver: {
|
|
298
|
+
verifySource(source, { gaps }) {
|
|
299
|
+
return source.uri ? { accept: true } : { accept: false, reason: 'no uri' }
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
})
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Research supervisor
|
|
306
|
+
|
|
307
|
+
`runResearchSupervisor()` is the LIVE counterpart: a supervisor brain creates the
|
|
308
|
+
topology dynamically — one researcher worker per sub-topic over a `Scope` — and
|
|
309
|
+
stops when the knowledge base is ready. It is a thin wrapper over `supervise()`
|
|
310
|
+
from `@tangle-network/agent-runtime/loops`; it builds nothing new. The worker
|
|
311
|
+
shape is the [researcher profile](#researcher-profile), and the completion oracle
|
|
312
|
+
is `knowledgeReadinessDeliverable` (re-reads the KB from disk and runs the
|
|
313
|
+
readiness gate, so it stops on the real grounded state, not a worker's
|
|
314
|
+
self-report). Needs creds: a supervisor router brain plus a worker backend.
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import { defineReadinessSpec, runResearchSupervisor } from '@tangle-network/agent-knowledge'
|
|
318
|
+
|
|
319
|
+
await runResearchSupervisor({
|
|
320
|
+
root: './kb',
|
|
321
|
+
goal: 'Build a grounded onboarding wiki for billing support',
|
|
322
|
+
readinessSpecs: [defineReadinessSpec({
|
|
323
|
+
id: 'refund-policy',
|
|
324
|
+
description: 'Refund policy grounding',
|
|
325
|
+
query: 'refund policy customer request',
|
|
326
|
+
requiredFor: ['support-agent'],
|
|
327
|
+
})],
|
|
328
|
+
budget: { maxIterations: 12, maxTokens: 200_000, maxUsd: 5 },
|
|
329
|
+
// WHERE researcher workers run — the real backend seam.
|
|
330
|
+
backend: {
|
|
331
|
+
backend: 'router', // or 'sandbox' / 'cli' / 'bridge'
|
|
332
|
+
routerBaseUrl: process.env.ROUTER_BASE_URL!,
|
|
333
|
+
routerKey: process.env.ROUTER_KEY!,
|
|
334
|
+
model: 'your-worker-model',
|
|
335
|
+
},
|
|
336
|
+
})
|
|
337
|
+
```
|
|
338
|
+
|
|
263
339
|
## Researcher profile
|
|
264
340
|
|
|
265
341
|
`@tangle-network/agent-knowledge/profiles` ships a sandbox-SDK
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
// src/profiles/researcher.ts
|
|
2
|
+
var DEFAULT_HARNESS = "opencode/zai-coding-plan/glm-5.1";
|
|
3
|
+
var DEFAULT_CITATION_DENSITY_MIN = 0.7;
|
|
4
|
+
function researcherProfile(options = {}) {
|
|
5
|
+
const harness = options.harness ?? DEFAULT_HARNESS;
|
|
6
|
+
const name = options.name ?? `researcher-${harness}`;
|
|
7
|
+
const systemPrompt = options.systemPrompt ?? DEFAULT_RESEARCHER_SYSTEM_PROMPT;
|
|
8
|
+
const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN;
|
|
9
|
+
const profile = {
|
|
10
|
+
name,
|
|
11
|
+
description: "Source-grounded research agent. Propose-don't-apply.",
|
|
12
|
+
prompt: { systemPrompt },
|
|
13
|
+
model: options.model ? { default: options.model } : void 0,
|
|
14
|
+
tools: { web_search: true, fs: true, shell: true },
|
|
15
|
+
metadata: { backendType: harness, role: "researcher" }
|
|
16
|
+
};
|
|
17
|
+
const output = { parse: parseResearcherEvents };
|
|
18
|
+
const validator = options.task ? createResearcherValidator(options.task, { citationDensityMin }) : createResearcherValidator(
|
|
19
|
+
{ question: "", knowledgeNamespace: "" },
|
|
20
|
+
{ citationDensityMin, namespaceCheck: false }
|
|
21
|
+
);
|
|
22
|
+
const agentRunSpec = {
|
|
23
|
+
name,
|
|
24
|
+
profile,
|
|
25
|
+
taskToPrompt: formatResearcherPrompt
|
|
26
|
+
};
|
|
27
|
+
return { profile, taskToPrompt: formatResearcherPrompt, output, validator, agentRunSpec };
|
|
28
|
+
}
|
|
29
|
+
function multiHarnessResearcherFanout(options = {}) {
|
|
30
|
+
const harnesses = options.harnesses && options.harnesses.length > 0 ? options.harnesses : ["opencode/zai-coding-plan/glm-5.1", "claude-code", "codex"];
|
|
31
|
+
const models = options.models ?? [];
|
|
32
|
+
const agentRuns = harnesses.map((harness, i) => {
|
|
33
|
+
const { agentRunSpec } = researcherProfile({ harness, model: models[i] });
|
|
34
|
+
return agentRunSpec;
|
|
35
|
+
});
|
|
36
|
+
const { output, validator } = researcherProfile({
|
|
37
|
+
citationDensityMin: options.citationDensityMin,
|
|
38
|
+
task: options.task
|
|
39
|
+
});
|
|
40
|
+
const driver = {
|
|
41
|
+
name: "researcher-fanout",
|
|
42
|
+
async plan(task, history) {
|
|
43
|
+
return history.length === 0 ? Array.from({ length: harnesses.length }, () => task) : [];
|
|
44
|
+
},
|
|
45
|
+
// 'done' is a terminal decision in the kernel; the loop finalizes after
|
|
46
|
+
// the single fanout round and selects the winner via `defaultSelectWinner`.
|
|
47
|
+
decide() {
|
|
48
|
+
return "done";
|
|
49
|
+
},
|
|
50
|
+
describePlan() {
|
|
51
|
+
return { kind: "fanout" };
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
return { agentRuns, output, validator, driver };
|
|
55
|
+
}
|
|
56
|
+
function createResearcherValidator(task, config = {}) {
|
|
57
|
+
const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN;
|
|
58
|
+
const namespaceCheck = config.namespaceCheck ?? true;
|
|
59
|
+
return {
|
|
60
|
+
async validate(output) {
|
|
61
|
+
const notes = [];
|
|
62
|
+
const scores = {};
|
|
63
|
+
let pass = true;
|
|
64
|
+
if (!Array.isArray(output.items) || output.items.length === 0) {
|
|
65
|
+
pass = false;
|
|
66
|
+
notes.push("no items");
|
|
67
|
+
scores.items = 0;
|
|
68
|
+
} else {
|
|
69
|
+
scores.items = 1;
|
|
70
|
+
}
|
|
71
|
+
const missingEvidence = (output.items ?? []).filter(
|
|
72
|
+
(item) => !Array.isArray(item.evidence) || item.evidence.length === 0
|
|
73
|
+
);
|
|
74
|
+
if (missingEvidence.length > 0) {
|
|
75
|
+
pass = false;
|
|
76
|
+
notes.push(`${missingEvidence.length} item(s) without evidence`);
|
|
77
|
+
scores.provenance = 0;
|
|
78
|
+
} else {
|
|
79
|
+
scores.provenance = 1;
|
|
80
|
+
}
|
|
81
|
+
if (namespaceCheck) {
|
|
82
|
+
const foreignItems = (output.items ?? []).filter(
|
|
83
|
+
(item) => item.namespace !== task.knowledgeNamespace
|
|
84
|
+
);
|
|
85
|
+
const foreignWrites = (output.proposedWrites ?? []).filter(
|
|
86
|
+
(write) => write.namespace !== task.knowledgeNamespace
|
|
87
|
+
);
|
|
88
|
+
if (foreignItems.length > 0 || foreignWrites.length > 0) {
|
|
89
|
+
pass = false;
|
|
90
|
+
notes.push(
|
|
91
|
+
`namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) outside ${task.knowledgeNamespace}`
|
|
92
|
+
);
|
|
93
|
+
scores.namespace = 0;
|
|
94
|
+
} else {
|
|
95
|
+
scores.namespace = 1;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const itemCount = Math.max(output.items?.length ?? 0, 1);
|
|
99
|
+
const citationsWithQuote = (output.citations ?? []).filter(
|
|
100
|
+
(citation) => typeof citation.quote === "string" && citation.quote.length > 0
|
|
101
|
+
).length;
|
|
102
|
+
const citationDensity = Math.min(1, citationsWithQuote / itemCount);
|
|
103
|
+
if (citationDensity < citationDensityMin) {
|
|
104
|
+
pass = false;
|
|
105
|
+
notes.push(
|
|
106
|
+
`citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
scores.citation_density = citationDensity;
|
|
110
|
+
const sourceSet = /* @__PURE__ */ new Set();
|
|
111
|
+
for (const item of output.items ?? []) {
|
|
112
|
+
for (const evidence of item.evidence ?? []) {
|
|
113
|
+
if (evidence.source) sourceSet.add(evidence.source);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
scores.source_diversity = Math.min(1, sourceSet.size / itemCount);
|
|
117
|
+
scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow);
|
|
118
|
+
const maxGaps = itemCount;
|
|
119
|
+
const gapCount = output.gaps?.length ?? 0;
|
|
120
|
+
scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps);
|
|
121
|
+
const score = 0.4 * scores.citation_density + 0.2 * scores.source_diversity + 0.2 * scores.recency_match + 0.2 * scores.gap_coverage;
|
|
122
|
+
const verdict = {
|
|
123
|
+
valid: pass,
|
|
124
|
+
score: Number.isFinite(score) ? score : 0,
|
|
125
|
+
scores
|
|
126
|
+
};
|
|
127
|
+
if (notes.length > 0) verdict.notes = notes.join("; ");
|
|
128
|
+
return verdict;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function recencyMatchScore(items, window) {
|
|
133
|
+
if (!window || window.since === void 0 && window.until === void 0) return 1;
|
|
134
|
+
if (items.length === 0) return 0;
|
|
135
|
+
const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY;
|
|
136
|
+
const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
137
|
+
let hits = 0;
|
|
138
|
+
let total = 0;
|
|
139
|
+
for (const item of items) {
|
|
140
|
+
for (const evidence of item.evidence ?? []) {
|
|
141
|
+
if (typeof evidence.capturedAt !== "number") continue;
|
|
142
|
+
total += 1;
|
|
143
|
+
if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return total === 0 ? 0 : hits / total;
|
|
147
|
+
}
|
|
148
|
+
var DEFAULT_RESEARCHER_SYSTEM_PROMPT = [
|
|
149
|
+
"You are a research agent. Your job is to answer a research question with",
|
|
150
|
+
"source-grounded knowledge items that the caller will choose whether to",
|
|
151
|
+
"persist to a multi-tenant knowledge base.",
|
|
152
|
+
"",
|
|
153
|
+
"Hard rules:",
|
|
154
|
+
" 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.",
|
|
155
|
+
" Never write to a different namespace.",
|
|
156
|
+
" 2. Every item MUST carry at least one evidence entry with a source.",
|
|
157
|
+
" A quote + url is strongly preferred; capturedAt is unix ms.",
|
|
158
|
+
" 3. You propose writes \u2014 you do NOT apply them. The caller decides.",
|
|
159
|
+
" 4. Self-report confidence honestly in [0, 1]. Do not inflate.",
|
|
160
|
+
" 5. List what you could not answer in `gaps`. Better to admit a gap",
|
|
161
|
+
" than fabricate.",
|
|
162
|
+
"",
|
|
163
|
+
"When you finish, emit a single final structured message of the shape:",
|
|
164
|
+
" ```json",
|
|
165
|
+
' { "items": [{ "id": "...", "namespace": "...", "claim": "...",',
|
|
166
|
+
' "evidence": [{ "source": "...", "quote": "...",',
|
|
167
|
+
' "url": "...", "capturedAt": 0 }],',
|
|
168
|
+
' "confidence": 0.0,',
|
|
169
|
+
' "authoredBy": { "kind": "agent", "id": "..." } }],',
|
|
170
|
+
' "citations": [{ "url": "...", "quote": "...", "confidence": 0.0 }],',
|
|
171
|
+
' "proposedWrites": [{ "kind": "insert", "namespace": "...",',
|
|
172
|
+
' "item": { /* same shape as items[] */ } }],',
|
|
173
|
+
' "gaps": ["..."],',
|
|
174
|
+
' "notes": "free-form commentary" }',
|
|
175
|
+
" ```"
|
|
176
|
+
].join("\n");
|
|
177
|
+
function formatResearcherPrompt(task) {
|
|
178
|
+
const sources = task.sources?.length ? task.sources.join(", ") : "(no preference)";
|
|
179
|
+
const window = formatRecencyWindow(task.recencyWindow);
|
|
180
|
+
return [
|
|
181
|
+
`Question: ${task.question}`,
|
|
182
|
+
`Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,
|
|
183
|
+
`Scope: ${task.scope ?? "(unspecified)"}`,
|
|
184
|
+
`Preferred sources: ${sources}`,
|
|
185
|
+
`Recency window: ${window}`,
|
|
186
|
+
`Max items: ${task.maxItems ?? "(no cap)"}`,
|
|
187
|
+
`Per-item minimum confidence: ${task.minConfidence ?? "(no floor)"}`,
|
|
188
|
+
"",
|
|
189
|
+
"Produce knowledge items with provenance + citations + proposed writes.",
|
|
190
|
+
"List gaps for anything you could not answer. Emit the final JSON",
|
|
191
|
+
"result block exactly as instructed."
|
|
192
|
+
].join("\n");
|
|
193
|
+
}
|
|
194
|
+
function formatRecencyWindow(window) {
|
|
195
|
+
if (!window) return "(none)";
|
|
196
|
+
const since = window.since ? window.since.toISOString() : "-\u221E";
|
|
197
|
+
const until = window.until ? window.until.toISOString() : "now";
|
|
198
|
+
return `${since} .. ${until}`;
|
|
199
|
+
}
|
|
200
|
+
function parseResearcherEvents(events) {
|
|
201
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
202
|
+
const event = events[i];
|
|
203
|
+
if (!event) continue;
|
|
204
|
+
const type = String(event.type ?? "");
|
|
205
|
+
const data = isRecord(event.data) ? event.data : {};
|
|
206
|
+
if (type === "result" || type === "final" || type === "research.result") {
|
|
207
|
+
const direct = coerceResearchOutput(data.result ?? data.output ?? data);
|
|
208
|
+
const finalText = pickString(data.finalText);
|
|
209
|
+
const fenced = finalText ? extractFencedJson(finalText) : void 0;
|
|
210
|
+
const fromFinalText = fenced ? coerceResearchOutput(fenced) : void 0;
|
|
211
|
+
if (direct && !isEmptyOutput(direct)) return direct;
|
|
212
|
+
if (fromFinalText) return fromFinalText;
|
|
213
|
+
if (direct) return direct;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
217
|
+
const event = events[i];
|
|
218
|
+
if (!event) continue;
|
|
219
|
+
const data = isRecord(event.data) ? event.data : {};
|
|
220
|
+
const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText);
|
|
221
|
+
if (!text) continue;
|
|
222
|
+
const fenced = extractFencedJson(text);
|
|
223
|
+
if (!fenced) continue;
|
|
224
|
+
const coerced = coerceResearchOutput(fenced);
|
|
225
|
+
if (coerced) return coerced;
|
|
226
|
+
}
|
|
227
|
+
return { items: [], citations: [], proposedWrites: [] };
|
|
228
|
+
}
|
|
229
|
+
function isRecord(value) {
|
|
230
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
231
|
+
}
|
|
232
|
+
function isEmptyOutput(o) {
|
|
233
|
+
return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0;
|
|
234
|
+
}
|
|
235
|
+
function pickString(value) {
|
|
236
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
237
|
+
}
|
|
238
|
+
function extractFencedJson(text) {
|
|
239
|
+
const match = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
240
|
+
if (!match) return void 0;
|
|
241
|
+
const body = (match[1] ?? "").trim();
|
|
242
|
+
if (!body) return void 0;
|
|
243
|
+
try {
|
|
244
|
+
return JSON.parse(body);
|
|
245
|
+
} catch {
|
|
246
|
+
return void 0;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function coerceResearchOutput(value) {
|
|
250
|
+
if (!isRecord(value)) return void 0;
|
|
251
|
+
const items = coerceItems(value.items);
|
|
252
|
+
const citations = coerceCitations(value.citations);
|
|
253
|
+
const proposedWrites = coerceProposedWrites(value.proposedWrites);
|
|
254
|
+
if (items === void 0 && citations === void 0 && proposedWrites === void 0) {
|
|
255
|
+
return void 0;
|
|
256
|
+
}
|
|
257
|
+
const output = {
|
|
258
|
+
items: items ?? [],
|
|
259
|
+
citations: citations ?? [],
|
|
260
|
+
proposedWrites: proposedWrites ?? []
|
|
261
|
+
};
|
|
262
|
+
if (Array.isArray(value.gaps)) {
|
|
263
|
+
output.gaps = value.gaps.filter((entry) => typeof entry === "string");
|
|
264
|
+
}
|
|
265
|
+
const notes = pickString(value.notes);
|
|
266
|
+
if (notes) output.notes = notes;
|
|
267
|
+
const known = /* @__PURE__ */ new Set(["items", "citations", "proposedWrites", "gaps", "notes"]);
|
|
268
|
+
const extras = {};
|
|
269
|
+
let extrasCount = 0;
|
|
270
|
+
for (const [key, val] of Object.entries(value)) {
|
|
271
|
+
if (known.has(key)) continue;
|
|
272
|
+
extras[key] = val;
|
|
273
|
+
extrasCount += 1;
|
|
274
|
+
}
|
|
275
|
+
if (extrasCount > 0) output.raw = extras;
|
|
276
|
+
return output;
|
|
277
|
+
}
|
|
278
|
+
function coerceItems(value) {
|
|
279
|
+
if (!Array.isArray(value)) return void 0;
|
|
280
|
+
const out = [];
|
|
281
|
+
for (const entry of value) {
|
|
282
|
+
if (!isRecord(entry)) continue;
|
|
283
|
+
const id = pickString(entry.id);
|
|
284
|
+
const namespace = pickString(entry.namespace);
|
|
285
|
+
const claim = pickString(entry.claim);
|
|
286
|
+
const evidence = coerceEvidence(entry.evidence);
|
|
287
|
+
const confidence = toFiniteNumber(entry.confidence);
|
|
288
|
+
const authoredBy = coerceAuthoredBy(entry.authoredBy);
|
|
289
|
+
if (!id || !namespace || !claim || !authoredBy) continue;
|
|
290
|
+
const item = {
|
|
291
|
+
id,
|
|
292
|
+
namespace,
|
|
293
|
+
claim,
|
|
294
|
+
evidence,
|
|
295
|
+
confidence: clamp01(confidence),
|
|
296
|
+
authoredBy
|
|
297
|
+
};
|
|
298
|
+
if (Array.isArray(entry.supersedes)) {
|
|
299
|
+
item.supersedes = entry.supersedes.filter((s) => typeof s === "string");
|
|
300
|
+
}
|
|
301
|
+
const retractedAt = toFiniteNumber(entry.retractedAt);
|
|
302
|
+
if (retractedAt > 0) item.retractedAt = retractedAt;
|
|
303
|
+
out.push(item);
|
|
304
|
+
}
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
function coerceEvidence(value) {
|
|
308
|
+
if (!Array.isArray(value)) return [];
|
|
309
|
+
const out = [];
|
|
310
|
+
for (const entry of value) {
|
|
311
|
+
if (!isRecord(entry)) continue;
|
|
312
|
+
const source = pickString(entry.source);
|
|
313
|
+
if (!source) continue;
|
|
314
|
+
const item = {
|
|
315
|
+
source,
|
|
316
|
+
capturedAt: toFiniteNumber(entry.capturedAt)
|
|
317
|
+
};
|
|
318
|
+
const quote = pickString(entry.quote);
|
|
319
|
+
if (quote) item.quote = quote;
|
|
320
|
+
const url = pickString(entry.url);
|
|
321
|
+
if (url) item.url = url;
|
|
322
|
+
out.push(item);
|
|
323
|
+
}
|
|
324
|
+
return out;
|
|
325
|
+
}
|
|
326
|
+
function coerceAuthoredBy(value) {
|
|
327
|
+
if (!isRecord(value)) return void 0;
|
|
328
|
+
const kind = value.kind === "human" || value.kind === "agent" ? value.kind : void 0;
|
|
329
|
+
const id = pickString(value.id);
|
|
330
|
+
if (!kind || !id) return void 0;
|
|
331
|
+
return { kind, id };
|
|
332
|
+
}
|
|
333
|
+
function coerceCitations(value) {
|
|
334
|
+
if (!Array.isArray(value)) return void 0;
|
|
335
|
+
const out = [];
|
|
336
|
+
for (const entry of value) {
|
|
337
|
+
if (!isRecord(entry)) continue;
|
|
338
|
+
const url = pickString(entry.url);
|
|
339
|
+
const quote = pickString(entry.quote);
|
|
340
|
+
if (!url || !quote) continue;
|
|
341
|
+
out.push({ url, quote, confidence: clamp01(toFiniteNumber(entry.confidence)) });
|
|
342
|
+
}
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
function coerceProposedWrites(value) {
|
|
346
|
+
if (!Array.isArray(value)) return void 0;
|
|
347
|
+
const out = [];
|
|
348
|
+
for (const entry of value) {
|
|
349
|
+
if (!isRecord(entry)) continue;
|
|
350
|
+
const namespace = pickString(entry.namespace);
|
|
351
|
+
if (!namespace) continue;
|
|
352
|
+
if (entry.kind === "insert") {
|
|
353
|
+
const items = coerceItems([entry.item]);
|
|
354
|
+
const item = items?.[0];
|
|
355
|
+
if (!item) continue;
|
|
356
|
+
out.push({ kind: "insert", namespace, item });
|
|
357
|
+
} else if (entry.kind === "supersede") {
|
|
358
|
+
const previousId = pickString(entry.previousId);
|
|
359
|
+
const items = coerceItems([entry.item]);
|
|
360
|
+
const item = items?.[0];
|
|
361
|
+
if (!previousId || !item) continue;
|
|
362
|
+
out.push({ kind: "supersede", namespace, previousId, item });
|
|
363
|
+
} else if (entry.kind === "retract") {
|
|
364
|
+
const itemId = pickString(entry.itemId);
|
|
365
|
+
const reason = pickString(entry.reason);
|
|
366
|
+
if (!itemId || !reason) continue;
|
|
367
|
+
out.push({ kind: "retract", namespace, itemId, reason });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return out;
|
|
371
|
+
}
|
|
372
|
+
function toFiniteNumber(value) {
|
|
373
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
374
|
+
}
|
|
375
|
+
function clamp01(value) {
|
|
376
|
+
if (!Number.isFinite(value)) return 0;
|
|
377
|
+
if (value < 0) return 0;
|
|
378
|
+
if (value > 1) return 1;
|
|
379
|
+
return value;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export {
|
|
383
|
+
researcherProfile,
|
|
384
|
+
multiHarnessResearcherFanout,
|
|
385
|
+
createResearcherValidator
|
|
386
|
+
};
|
|
387
|
+
//# sourceMappingURL=chunk-MU5CEOGE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/profiles/researcher.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `researcherProfile` — opinionated preset for source-grounded research\n * tasks. The agent is told to:\n * - bound its work to a single `knowledgeNamespace`\n * - emit `items[]` carrying provenance + confidence\n * - emit `citations[]` linking quotes back to source urls\n * - emit `proposedWrites[]` — never call materialize itself\n * - describe `gaps` it could not answer\n *\n * The profile is stateless and agent-agnostic. `harness` selects the\n * sandbox-SDK backend. For heterogeneous fanout, use\n * `multiHarnessResearcherFanout`.\n *\n * Propose-don't-apply: the profile NEVER writes to the knowledge base.\n * It produces `proposedWrites: KnowledgeUpdate[]` in the output. The\n * caller (gtm-agent, journey-eval, user) decides whether to feed those\n * updates through `applyKnowledgeWriteBlocks` / a KbStore put.\n *\n * Namespace isolation: every `KnowledgeItem` + `KnowledgeUpdate` in the\n * output carries `namespace`. The validator hard-fails when any item\n * touches a namespace other than `task.knowledgeNamespace`.\n */\n\nimport type {\n AgentProfile,\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n OutputAdapter,\n SandboxEvent,\n Validator,\n} from '@tangle-network/agent-runtime/loops'\n\n/** @experimental */\nexport type ResearchSource = 'web' | 'corpus' | 'twitter' | 'github' | 'docs'\n\n/** @experimental */\nexport interface ResearchTask {\n /** The research question to answer. */\n question: string\n /** Bound: e.g. \"audience for cpg-founder ICP\". */\n scope?: string\n /** Multi-tenant scope (customer-id, workspace-id). Validator enforces. */\n knowledgeNamespace: string\n sources?: ResearchSource[]\n recencyWindow?: { since?: Date; until?: Date }\n maxItems?: number\n /** Per-item minimum confidence in [0, 1]. Validator scores recall vs this. */\n minConfidence?: number\n}\n\n/**\n * Knowledge item emitted by the researcher.\n *\n * Profile-local type. When agent-knowledge promotes `KnowledgeClaim` →\n * top-level `KnowledgeItem` substrate-wide, these fields collapse 1:1.\n *\n * @experimental\n */\nexport interface KnowledgeItem {\n id: string\n /** Multi-tenant scope. MUST equal `task.knowledgeNamespace`. */\n namespace: string\n /** The factual claim, in the researcher's words. */\n claim: string\n /** Provenance — at least one entry required. */\n evidence: Array<{ source: string; quote?: string; url?: string; capturedAt: number }>\n /** Researcher's self-reported confidence in [0, 1]. */\n confidence: number\n /** Prior item ids this supersedes (chain). */\n supersedes?: string[]\n /** Set if the agent is retracting an earlier item. Unix ms. */\n retractedAt?: number\n authoredBy: { kind: 'human' | 'agent'; id: string }\n}\n\n/**\n * A proposed write to the knowledge base. The profile does NOT apply\n * these — the caller decides.\n *\n * @experimental\n */\nexport type KnowledgeUpdate =\n | { kind: 'insert'; namespace: string; item: KnowledgeItem }\n | { kind: 'supersede'; namespace: string; previousId: string; item: KnowledgeItem }\n | { kind: 'retract'; namespace: string; itemId: string; reason: string }\n\n/**\n * Researcher output. Required fields are typed; optional fields preserve\n * the agent's free-form intelligence (`notes`, `raw`). The validator\n * enforces the typed minimum.\n *\n * @experimental\n */\nexport interface ResearchOutput {\n items: KnowledgeItem[]\n citations: Array<{ url: string; quote: string; confidence: number }>\n proposedWrites: KnowledgeUpdate[]\n gaps?: string[]\n notes?: string\n /** Anything the agent emitted beyond the typed fields. */\n raw?: unknown\n}\n\n/** @experimental */\nexport interface ResearcherProfileOptions {\n /** Sandbox-SDK backend.type. Default `'opencode/zai-coding-plan/glm-5.1'`. */\n harness?: string\n /** Default model id passed in `AgentProfile.model.default`. */\n model?: string\n /** Custom system prompt replacement. Default = built-in researcher preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `researcher-${harness}`. */\n name?: string\n /**\n * Default 0.7. Minimum (citations with quote) / items ratio for `valid=true`.\n * Below this floor, citation_density scores < 1 and the item set is gated.\n */\n citationDensityMin?: number\n}\n\nconst DEFAULT_HARNESS = 'opencode/zai-coding-plan/glm-5.1'\nconst DEFAULT_CITATION_DENSITY_MIN = 0.7\n\n/** @experimental */\nexport function researcherProfile(\n options: ResearcherProfileOptions & { task?: ResearchTask } = {},\n): {\n profile: AgentProfile\n taskToPrompt: (task: ResearchTask) => string\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n agentRunSpec: AgentRunSpec<ResearchTask>\n} {\n const harness = options.harness ?? DEFAULT_HARNESS\n const name = options.name ?? `researcher-${harness}`\n const systemPrompt = options.systemPrompt ?? DEFAULT_RESEARCHER_SYSTEM_PROMPT\n const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const profile: AgentProfile = {\n name,\n description: \"Source-grounded research agent. Propose-don't-apply.\",\n prompt: { systemPrompt },\n model: options.model ? { default: options.model } : undefined,\n tools: { web_search: true, fs: true, shell: true },\n metadata: { backendType: harness, role: 'researcher' },\n }\n const output: OutputAdapter<ResearchOutput> = { parse: parseResearcherEvents }\n const validator: Validator<ResearchOutput> = options.task\n ? createResearcherValidator(options.task, { citationDensityMin })\n : createResearcherValidator(\n { question: '', knowledgeNamespace: '' },\n { citationDensityMin, namespaceCheck: false },\n )\n const agentRunSpec: AgentRunSpec<ResearchTask> = {\n name,\n profile,\n taskToPrompt: formatResearcherPrompt,\n }\n return { profile, taskToPrompt: formatResearcherPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessResearcherFanoutOptions {\n /** Backend.type identifiers, one per parallel agent. */\n harnesses?: string[]\n /** Optional per-harness model override. Indexed parallel to `harnesses`. */\n models?: (string | undefined)[]\n /** Default citation density floor for the shared validator. */\n citationDensityMin?: number\n /** Optional task — narrows the validator's namespace check. */\n task?: ResearchTask\n}\n\n/**\n * Build a fanout topology over multiple harnesses. The kernel round-robins\n * `agentRuns` across the N parallel iterations and the `FanoutVote` driver\n * picks the highest-scoring valid output.\n *\n * @experimental\n */\nexport function multiHarnessResearcherFanout(options: MultiHarnessResearcherFanoutOptions = {}): {\n agentRuns: AgentRunSpec<ResearchTask>[]\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n driver: Driver<ResearchTask, ResearchOutput, 'done'>\n} {\n const harnesses =\n options.harnesses && options.harnesses.length > 0\n ? options.harnesses\n : ['opencode/zai-coding-plan/glm-5.1', 'claude-code', 'codex']\n const models = options.models ?? []\n const agentRuns = harnesses.map((harness, i) => {\n const { agentRunSpec } = researcherProfile({ harness, model: models[i] })\n return agentRunSpec\n })\n const { output, validator } = researcherProfile({\n citationDensityMin: options.citationDensityMin,\n task: options.task,\n })\n // Single fanout round across the N harnesses, then stop: the kernel\n // round-robins `agentRuns` over the N branches and selects the winner\n // (best valid score) across all iterations via `defaultSelectWinner`.\n const driver: Driver<ResearchTask, ResearchOutput, 'done'> = {\n name: 'researcher-fanout',\n async plan(task, history) {\n return history.length === 0 ? Array.from({ length: harnesses.length }, () => task) : []\n },\n // 'done' is a terminal decision in the kernel; the loop finalizes after\n // the single fanout round and selects the winner via `defaultSelectWinner`.\n decide() {\n return 'done'\n },\n describePlan() {\n return { kind: 'fanout' }\n },\n }\n return { agentRuns, output, validator, driver }\n}\n\n/**\n * Build a validator that closes over a specific `ResearchTask`'s constraints.\n *\n * Checks in order:\n * 1. Items must be non-empty.\n * 2. Every item carries `evidence.length >= 1`.\n * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`\n * (hard-fail on any namespace mismatch — defence in depth for the\n * multi-tenant invariant).\n * 4. Citation density (citations with quote / items) >= floor.\n *\n * Aggregate score:\n * 0.4 · citation_density\n * + 0.2 · source_diversity (distinct sources / max(items, 1))\n * + 0.2 · recency_match (mean fraction within `recencyWindow`)\n * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)\n *\n * @experimental\n */\nexport function createResearcherValidator(\n task: ResearchTask,\n config: { citationDensityMin?: number; namespaceCheck?: boolean } = {},\n): Validator<ResearchOutput> {\n const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const namespaceCheck = config.namespaceCheck ?? true\n return {\n async validate(output) {\n const notes: string[] = []\n const scores: Record<string, number> = {}\n let pass = true\n\n if (!Array.isArray(output.items) || output.items.length === 0) {\n pass = false\n notes.push('no items')\n scores.items = 0\n } else {\n scores.items = 1\n }\n\n const missingEvidence = (output.items ?? []).filter(\n (item) => !Array.isArray(item.evidence) || item.evidence.length === 0,\n )\n if (missingEvidence.length > 0) {\n pass = false\n notes.push(`${missingEvidence.length} item(s) without evidence`)\n scores.provenance = 0\n } else {\n scores.provenance = 1\n }\n\n if (namespaceCheck) {\n const foreignItems = (output.items ?? []).filter(\n (item) => item.namespace !== task.knowledgeNamespace,\n )\n const foreignWrites = (output.proposedWrites ?? []).filter(\n (write) => write.namespace !== task.knowledgeNamespace,\n )\n if (foreignItems.length > 0 || foreignWrites.length > 0) {\n pass = false\n notes.push(\n `namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) ` +\n `outside ${task.knowledgeNamespace}`,\n )\n scores.namespace = 0\n } else {\n scores.namespace = 1\n }\n }\n\n const itemCount = Math.max(output.items?.length ?? 0, 1)\n const citationsWithQuote = (output.citations ?? []).filter(\n (citation) => typeof citation.quote === 'string' && citation.quote.length > 0,\n ).length\n const citationDensity = Math.min(1, citationsWithQuote / itemCount)\n if (citationDensity < citationDensityMin) {\n pass = false\n notes.push(\n `citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`,\n )\n }\n scores.citation_density = citationDensity\n\n const sourceSet = new Set<string>()\n for (const item of output.items ?? []) {\n for (const evidence of item.evidence ?? []) {\n if (evidence.source) sourceSet.add(evidence.source)\n }\n }\n scores.source_diversity = Math.min(1, sourceSet.size / itemCount)\n\n scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow)\n\n const maxGaps = itemCount\n const gapCount = output.gaps?.length ?? 0\n scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps)\n\n const score =\n 0.4 * scores.citation_density +\n 0.2 * scores.source_diversity +\n 0.2 * scores.recency_match +\n 0.2 * scores.gap_coverage\n\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n },\n }\n}\n\nfunction recencyMatchScore(items: KnowledgeItem[], window: ResearchTask['recencyWindow']): number {\n if (!window || (window.since === undefined && window.until === undefined)) return 1\n if (items.length === 0) return 0\n const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY\n const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY\n let hits = 0\n let total = 0\n for (const item of items) {\n for (const evidence of item.evidence ?? []) {\n if (typeof evidence.capturedAt !== 'number') continue\n total += 1\n if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1\n }\n }\n return total === 0 ? 0 : hits / total\n}\n\nconst DEFAULT_RESEARCHER_SYSTEM_PROMPT = [\n 'You are a research agent. Your job is to answer a research question with',\n 'source-grounded knowledge items that the caller will choose whether to',\n 'persist to a multi-tenant knowledge base.',\n '',\n 'Hard rules:',\n \" 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.\",\n ' Never write to a different namespace.',\n ' 2. Every item MUST carry at least one evidence entry with a source.',\n ' A quote + url is strongly preferred; capturedAt is unix ms.',\n ' 3. You propose writes — you do NOT apply them. The caller decides.',\n ' 4. Self-report confidence honestly in [0, 1]. Do not inflate.',\n ' 5. List what you could not answer in `gaps`. Better to admit a gap',\n ' than fabricate.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",',\n ' \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",',\n ' \"url\": \"...\", \"capturedAt\": 0 }],',\n ' \"confidence\": 0.0,',\n ' \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],',\n ' \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],',\n ' \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",',\n ' \"item\": { /* same shape as items[] */ } }],',\n ' \"gaps\": [\"...\"],',\n ' \"notes\": \"free-form commentary\" }',\n ' ```',\n].join('\\n')\n\nfunction formatResearcherPrompt(task: ResearchTask): string {\n const sources = task.sources?.length ? task.sources.join(', ') : '(no preference)'\n const window = formatRecencyWindow(task.recencyWindow)\n return [\n `Question: ${task.question}`,\n `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,\n `Scope: ${task.scope ?? '(unspecified)'}`,\n `Preferred sources: ${sources}`,\n `Recency window: ${window}`,\n `Max items: ${task.maxItems ?? '(no cap)'}`,\n `Per-item minimum confidence: ${task.minConfidence ?? '(no floor)'}`,\n '',\n 'Produce knowledge items with provenance + citations + proposed writes.',\n 'List gaps for anything you could not answer. Emit the final JSON',\n 'result block exactly as instructed.',\n ].join('\\n')\n}\n\nfunction formatRecencyWindow(window: ResearchTask['recencyWindow']): string {\n if (!window) return '(none)'\n const since = window.since ? window.since.toISOString() : '-∞'\n const until = window.until ? window.until.toISOString() : 'now'\n return `${since} .. ${until}`\n}\n\n/**\n * Walk the event stream and return the last structured `research.result`\n * payload. Falls back to scanning text deltas for a fenced JSON block.\n */\nfunction parseResearcherEvents(events: SandboxEvent[]): ResearchOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'research.result') {\n const direct = coerceResearchOutput(data.result ?? data.output ?? data)\n // opencode reports the agent's terminal answer in `finalText` (not result/output).\n // Parse it too, and prefer it when `direct` is an all-empty shape — otherwise an\n // event carrying both `{items:[],citations:[],proposedWrites:[]}` and a rich\n // finalText would silently drop the real answer.\n const finalText = pickString(data.finalText)\n const fenced = finalText ? extractFencedJson(finalText) : undefined\n const fromFinalText = fenced ? coerceResearchOutput(fenced) : undefined\n if (direct && !isEmptyOutput(direct)) return direct\n if (fromFinalText) return fromFinalText\n if (direct) return direct\n }\n }\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText)\n if (!text) continue\n const fenced = extractFencedJson(text)\n if (!fenced) continue\n const coerced = coerceResearchOutput(fenced)\n if (coerced) return coerced\n }\n return { items: [], citations: [], proposedWrites: [] }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** A coerced output that carries no items, citations, or proposed writes. */\nfunction isEmptyOutput(o: ResearchOutput): boolean {\n return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n if (!match) return undefined\n const body = (match[1] ?? '').trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction coerceResearchOutput(value: unknown): ResearchOutput | undefined {\n if (!isRecord(value)) return undefined\n const items = coerceItems(value.items)\n const citations = coerceCitations(value.citations)\n const proposedWrites = coerceProposedWrites(value.proposedWrites)\n // Reject completely empty payloads — those signal \"no result block\",\n // not \"a valid empty result\".\n if (items === undefined && citations === undefined && proposedWrites === undefined) {\n return undefined\n }\n const output: ResearchOutput = {\n items: items ?? [],\n citations: citations ?? [],\n proposedWrites: proposedWrites ?? [],\n }\n if (Array.isArray(value.gaps)) {\n output.gaps = value.gaps.filter((entry): entry is string => typeof entry === 'string')\n }\n const notes = pickString(value.notes)\n if (notes) output.notes = notes\n // Preserve any extra fields the agent emitted that don't fit the typed\n // surface — callers can inspect `raw` without forcing them through the\n // typed coercion. We only include `raw` when the agent emitted fields\n // beyond the known set.\n const known = new Set(['items', 'citations', 'proposedWrites', 'gaps', 'notes'])\n const extras: Record<string, unknown> = {}\n let extrasCount = 0\n for (const [key, val] of Object.entries(value)) {\n if (known.has(key)) continue\n extras[key] = val\n extrasCount += 1\n }\n if (extrasCount > 0) output.raw = extras\n return output\n}\n\nfunction coerceItems(value: unknown): KnowledgeItem[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeItem[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const id = pickString(entry.id)\n const namespace = pickString(entry.namespace)\n const claim = pickString(entry.claim)\n const evidence = coerceEvidence(entry.evidence)\n const confidence = toFiniteNumber(entry.confidence)\n const authoredBy = coerceAuthoredBy(entry.authoredBy)\n if (!id || !namespace || !claim || !authoredBy) continue\n const item: KnowledgeItem = {\n id,\n namespace,\n claim,\n evidence,\n confidence: clamp01(confidence),\n authoredBy,\n }\n if (Array.isArray(entry.supersedes)) {\n item.supersedes = entry.supersedes.filter((s): s is string => typeof s === 'string')\n }\n const retractedAt = toFiniteNumber(entry.retractedAt)\n if (retractedAt > 0) item.retractedAt = retractedAt\n out.push(item)\n }\n return out\n}\n\nfunction coerceEvidence(value: unknown): KnowledgeItem['evidence'] {\n if (!Array.isArray(value)) return []\n const out: KnowledgeItem['evidence'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const source = pickString(entry.source)\n if (!source) continue\n const item: KnowledgeItem['evidence'][number] = {\n source,\n capturedAt: toFiniteNumber(entry.capturedAt),\n }\n const quote = pickString(entry.quote)\n if (quote) item.quote = quote\n const url = pickString(entry.url)\n if (url) item.url = url\n out.push(item)\n }\n return out\n}\n\nfunction coerceAuthoredBy(value: unknown): KnowledgeItem['authoredBy'] | undefined {\n if (!isRecord(value)) return undefined\n const kind = value.kind === 'human' || value.kind === 'agent' ? value.kind : undefined\n const id = pickString(value.id)\n if (!kind || !id) return undefined\n return { kind, id }\n}\n\nfunction coerceCitations(value: unknown): ResearchOutput['citations'] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: ResearchOutput['citations'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const url = pickString(entry.url)\n const quote = pickString(entry.quote)\n if (!url || !quote) continue\n out.push({ url, quote, confidence: clamp01(toFiniteNumber(entry.confidence)) })\n }\n return out\n}\n\nfunction coerceProposedWrites(value: unknown): KnowledgeUpdate[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeUpdate[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const namespace = pickString(entry.namespace)\n if (!namespace) continue\n if (entry.kind === 'insert') {\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!item) continue\n out.push({ kind: 'insert', namespace, item })\n } else if (entry.kind === 'supersede') {\n const previousId = pickString(entry.previousId)\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!previousId || !item) continue\n out.push({ kind: 'supersede', namespace, previousId, item })\n } else if (entry.kind === 'retract') {\n const itemId = pickString(entry.itemId)\n const reason = pickString(entry.reason)\n if (!itemId || !reason) continue\n out.push({ kind: 'retract', namespace, itemId, reason })\n }\n }\n return out\n}\n\nfunction toFiniteNumber(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFin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S,KAAK,EAAG,QAAO;AACpC,MAAI,QAAQ,EAAG,QAAO;AACtB,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO;AACT;","names":[]}
|
|
@@ -604,7 +604,7 @@ function lintKnowledgeIndex(index) {
|
|
|
604
604
|
const inbound = /* @__PURE__ */ new Map();
|
|
605
605
|
for (const page of index.pages) inbound.set(page.id, 0);
|
|
606
606
|
for (const page of index.pages) {
|
|
607
|
-
if (page.outLinks.length === 0 && !
|
|
607
|
+
if (page.outLinks.length === 0 && !isScaffoldPath(page.path)) {
|
|
608
608
|
findings.push({
|
|
609
609
|
type: "no-outlinks",
|
|
610
610
|
severity: "info",
|
|
@@ -626,7 +626,7 @@ function lintKnowledgeIndex(index) {
|
|
|
626
626
|
for (const edge of index.graph.edges)
|
|
627
627
|
inbound.set(edge.target, (inbound.get(edge.target) ?? 0) + 1);
|
|
628
628
|
for (const page of index.pages) {
|
|
629
|
-
if (!
|
|
629
|
+
if (!isScaffoldPath(page.path) && (inbound.get(page.id) ?? 0) === 0) {
|
|
630
630
|
findings.push({
|
|
631
631
|
type: "orphan",
|
|
632
632
|
severity: "info",
|
|
@@ -705,9 +705,6 @@ function lintKnowledgeIndex(index) {
|
|
|
705
705
|
}
|
|
706
706
|
return findings;
|
|
707
707
|
}
|
|
708
|
-
function isStructural(path) {
|
|
709
|
-
return path.endsWith("/index.md") || path.endsWith("/log.md") || path === "knowledge/index.md" || path === "knowledge/log.md";
|
|
710
|
-
}
|
|
711
708
|
function extractSourceRefs(text) {
|
|
712
709
|
const refs = [];
|
|
713
710
|
const regex = /\[\^([A-Za-z0-9_-]+)(?:#([A-Za-z0-9_.:-]+))?\]/g;
|
|
@@ -718,6 +715,12 @@ function extractSourceRefs(text) {
|
|
|
718
715
|
return refs;
|
|
719
716
|
}
|
|
720
717
|
|
|
718
|
+
// src/metadata.ts
|
|
719
|
+
function stringMetadata(metadata, key) {
|
|
720
|
+
const value = metadata?.[key];
|
|
721
|
+
return typeof value === "string" ? value : void 0;
|
|
722
|
+
}
|
|
723
|
+
|
|
721
724
|
// src/inspect.ts
|
|
722
725
|
function inspectKnowledgeIndex(index, options = {}) {
|
|
723
726
|
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
@@ -748,10 +751,6 @@ function inspectSourceFreshness(source, now) {
|
|
|
748
751
|
const status = validUntil && Number.isFinite(Date.parse(validUntil)) ? Date.parse(validUntil) <= now.getTime() ? "expired" : "fresh" : "unknown";
|
|
749
752
|
return { id: source.id, title: source.title, uri: source.uri, status, validUntil, lastVerifiedAt };
|
|
750
753
|
}
|
|
751
|
-
function stringMetadata(metadata, key) {
|
|
752
|
-
const value = metadata?.[key];
|
|
753
|
-
return typeof value === "string" ? value : void 0;
|
|
754
|
-
}
|
|
755
754
|
function explainKnowledgeTarget(index, target) {
|
|
756
755
|
const page = index.pages.find(
|
|
757
756
|
(candidate) => candidate.path === target || candidate.id === target || candidate.title.toLowerCase() === target.toLowerCase()
|
|
@@ -1004,7 +1003,7 @@ function validateKnowledgeIndex(index, options = {}) {
|
|
|
1004
1003
|
}
|
|
1005
1004
|
if (options.strict) {
|
|
1006
1005
|
for (const page of index.pages) {
|
|
1007
|
-
if (
|
|
1006
|
+
if (isScaffoldPath(page.path)) continue;
|
|
1008
1007
|
if (!page.frontmatter.id || !page.frontmatter.title) {
|
|
1009
1008
|
findings.push({
|
|
1010
1009
|
type: "missing-frontmatter",
|
|
@@ -1017,13 +1016,11 @@ function validateKnowledgeIndex(index, options = {}) {
|
|
|
1017
1016
|
}
|
|
1018
1017
|
return { ok: !findings.some((finding) => finding.severity === "error"), findings };
|
|
1019
1018
|
}
|
|
1020
|
-
function isStructuralPage(path) {
|
|
1021
|
-
return path === "knowledge/index.md" || path === "knowledge/log.md" || path.endsWith("/index.md") || path.endsWith("/log.md");
|
|
1022
|
-
}
|
|
1023
1019
|
|
|
1024
1020
|
export {
|
|
1025
1021
|
textSourceAdapter,
|
|
1026
1022
|
mediaTypeFor,
|
|
1023
|
+
stringMetadata,
|
|
1027
1024
|
searchKnowledge,
|
|
1028
1025
|
tokenizeQuery,
|
|
1029
1026
|
reciprocalRankFusion,
|
|
@@ -1063,4 +1060,4 @@ export {
|
|
|
1063
1060
|
KnowledgeBaseCandidateSchema,
|
|
1064
1061
|
validateKnowledgeIndex
|
|
1065
1062
|
};
|
|
1066
|
-
//# sourceMappingURL=chunk-
|
|
1063
|
+
//# sourceMappingURL=chunk-WWY5FTKQ.js.map
|