@tangle-network/agent-runtime 0.9.0 → 0.11.1

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.
@@ -0,0 +1,583 @@
1
+ import * as _tangle_network_agent_eval from '@tangle-network/agent-eval';
2
+ import { FindingSubject, TraceAnalystKindSpec, AnalystFinding } from '@tangle-network/agent-eval';
3
+ import { R as RuntimeStreamEvent } from './types-afLuHk1G.js';
4
+ import { I as ImprovementAdapter, K as KnowledgeAdapter, a as RunAnalystLoopResult } from './types-D_MXrmJP.js';
5
+
6
+ /**
7
+ * `AgentSurfaces` — declarative map of the mutable file/directory paths
8
+ * the self-improvement loop can edit on behalf of an agent.
9
+ *
10
+ * The substrate uses this map to resolve every parsed `FindingSubject`
11
+ * (from agent-eval) to a real on-disk path. No per-vertical glue;
12
+ * no fabricated paths; no silent `existsSync(...)` skips that hide
13
+ * misconfiguration from the operator.
14
+ *
15
+ * Surfaces are validated at `defineAgent` time — missing paths fail
16
+ * loud with a list of every offender. A surface that's not needed
17
+ * (e.g. an agent with no RAG corpora) is simply omitted; the loop
18
+ * refuses to route those subjects rather than fabricating a target.
19
+ */
20
+
21
+ /**
22
+ * Surface declarations. Every path is repo-relative (or absolute) at
23
+ * `defineAgent` time. At resolution time, paths are joined against the
24
+ * agent's `repoRoot`.
25
+ *
26
+ * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends
27
+ * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.
28
+ * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in
29
+ * place.
30
+ *
31
+ * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);
32
+ * `applyKnowledgeWriteBlocks` writes pages relative to it.
33
+ *
34
+ * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)
35
+ * can be omitted — the loop will reject findings targeting them with a
36
+ * clear log message instead of fabricating a path.
37
+ */
38
+ interface AgentSurfaces {
39
+ /** Directory containing one markdown file per system-prompt section. */
40
+ systemPrompt: string;
41
+ /** Directory containing one subdir per tool (`<tool>/README.md`). */
42
+ tools: string;
43
+ /** Single file (TypeScript module) defining the rubric weights + dimensions. */
44
+ rubric: string;
45
+ /** Knowledge-base root; typically `.agent-knowledge`. */
46
+ knowledge: string;
47
+ /** Directory containing one YAML/JSON file per persona. */
48
+ personas: string;
49
+ /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */
50
+ scaffolding?: string;
51
+ /** Optional: memory store path (JSONL / SQLite / DB). */
52
+ memory?: string;
53
+ /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */
54
+ rag?: string;
55
+ /** Optional: single file defining the output schema (Zod / JSON Schema). */
56
+ outputSchema?: string;
57
+ }
58
+ interface ResolvedSurface {
59
+ /** Absolute filesystem path the operator can `cat` / `vim`. */
60
+ absolutePath: string;
61
+ /** Repo-relative path for PR descriptions, diffs, audit logs. */
62
+ repoRelativePath: string;
63
+ /** Whether the path currently exists on disk. */
64
+ exists: boolean;
65
+ /** The substrate's intent: edit an existing file or create a new one. */
66
+ intent: 'edit-existing' | 'create-new';
67
+ }
68
+ /**
69
+ * Resolve a parsed `FindingSubject` to the file path the substrate
70
+ * should edit (or create) on disk.
71
+ *
72
+ * Returns `null` when:
73
+ * - the subject targets a surface the agent didn't declare
74
+ * (e.g. `rag:*` when `surfaces.rag` is undefined), OR
75
+ * - the subject is a `cluster` (failure-mode emits these as evidence,
76
+ * not actionable mutations — they don't route to a file).
77
+ *
78
+ * Returns a `ResolvedSurface` with `intent: 'create-new'` when the
79
+ * subject names a path that doesn't yet exist (e.g. a new wiki page).
80
+ * The caller chooses whether to honour the create — for tightly-managed
81
+ * surfaces like `systemPrompt` it's usually a contract violation
82
+ * (the analyst named a section that doesn't exist); for `knowledge`
83
+ * it's the whole point.
84
+ */
85
+ declare function resolveSubjectPath(subject: FindingSubject, surfaces: AgentSurfaces, repoRoot: string): ResolvedSurface | null;
86
+ /**
87
+ * Validate that every declared surface exists on disk under `repoRoot`.
88
+ *
89
+ * Returns an array of `SurfaceValidationIssue` — empty when all required
90
+ * surfaces resolve. `defineAgent` throws with the issues rendered, so
91
+ * a misconfigured manifest fails at startup (not at the first finding
92
+ * the loop produces 20 minutes later).
93
+ */
94
+ interface SurfaceValidationIssue {
95
+ surface: keyof AgentSurfaces;
96
+ path: string;
97
+ reason: 'missing' | 'not-directory' | 'not-file';
98
+ }
99
+ declare function validateSurfaces(surfaces: AgentSurfaces, repoRoot: string): ReadonlyArray<SurfaceValidationIssue>;
100
+ declare function renderSurfaceIssues(issues: ReadonlyArray<SurfaceValidationIssue>, repoRoot: string): string;
101
+
102
+ /**
103
+ * The full agent manifest. Each agent ships ONE of these.
104
+ *
105
+ * Generics:
106
+ * `TPersona` — the agent's persona shape (loaded from
107
+ * `surfaces.personas`). Defaults to `unknown` so the substrate's
108
+ * persona discovery (`loadPersonas`) can accept anything; per-agent
109
+ * code re-narrows when it matters.
110
+ * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric
111
+ * scorers and emitted into the trace.
112
+ */
113
+ interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {
114
+ /**
115
+ * Stable identifier — used as `projectId` in traces, as the analyst
116
+ * loop's `runId` prefix, and as the namespace under which findings
117
+ * are persisted. MUST match the agent's repo name to keep
118
+ * cross-repo telemetry joinable.
119
+ */
120
+ id: string;
121
+ /**
122
+ * Filesystem root the substrate resolves surface paths against.
123
+ * Typically `process.cwd()` or a fixed absolute path. Use an
124
+ * absolute path when the agent's tests may run from subdirectories
125
+ * (vitest sometimes shifts cwd).
126
+ */
127
+ repoRoot: string;
128
+ /**
129
+ * Map of mutable surfaces the self-improvement loop can edit. See
130
+ * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,
131
+ * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,
132
+ * `outputSchema`.
133
+ *
134
+ * Every required path is validated at `defineAgent` time. Missing
135
+ * paths throw with the full list of offenders.
136
+ */
137
+ surfaces: AgentSurfaces;
138
+ /**
139
+ * Rubric the substrate uses to score each run. Dimensions × weights
140
+ * × judges. The substrate computes the weighted composite and
141
+ * stamps it into the RunRecord.
142
+ */
143
+ rubric: AgentRubric<TRunOutput>;
144
+ /**
145
+ * Runtime adapter — how the substrate INVOKES the agent against a
146
+ * persona. The `act` function takes a persona + a context (with the
147
+ * tracer the substrate threads through for span emission) and
148
+ * returns the run output the rubric will score.
149
+ *
150
+ * The agent's existing production runtime goes in here; the
151
+ * substrate is intentionally thin around it.
152
+ */
153
+ runtime: AgentRuntime<TPersona, TRunOutput>;
154
+ /**
155
+ * Persona discovery — the substrate loads personas via this function
156
+ * at eval start. Can read from `surfaces.personas`, an API, or be
157
+ * hardcoded. The substrate calls it once per `runAgentEval` call;
158
+ * persona ordering is preserved.
159
+ */
160
+ personas: () => Promise<ReadonlyArray<TPersona>>;
161
+ /**
162
+ * Analyst kinds the substrate runs against each persona's trace.
163
+ * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent
164
+ * authors can prune (e.g. skip `knowledge-poisoning` when there's no
165
+ * knowledge base) or extend (custom domain kinds).
166
+ *
167
+ * Empty array disables the loop — useful for `pnpm eval --no-analyst`.
168
+ */
169
+ analystKinds: ReadonlyArray<TraceAnalystKindSpec>;
170
+ /**
171
+ * Analyst LLM configuration. The substrate uses these for all four
172
+ * kinds (override per-kind via `analystKinds` if needed).
173
+ */
174
+ analyst: AnalystConfig;
175
+ /**
176
+ * Auto-apply policy. Knowledge / improvement edits land only when
177
+ * `enabled === true` AND the source finding's confidence meets the
178
+ * threshold. `mode` controls how applies happen: `'write'` mutates
179
+ * files in-place; `'open-pr'` writes to a branch and opens a PR.
180
+ *
181
+ * Default: knowledge auto-applies at confidence ≥0.85 in `'write'`
182
+ * mode (wiki edits are git-reversible); improvement stays at
183
+ * `enabled: false` until the agent author has measured precision.
184
+ */
185
+ autoApply?: AutoApplyPolicy;
186
+ }
187
+ interface AgentRubric<TRunOutput> {
188
+ /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */
189
+ dimensions: ReadonlyArray<RubricDimension<TRunOutput>>;
190
+ /**
191
+ * Optional judges layered on top of deterministic dimensions. Each
192
+ * judge returns a score per dimension; the substrate averages judges
193
+ * (mean by default) for the LLM contribution.
194
+ */
195
+ judges?: ReadonlyArray<JudgeConfig<TRunOutput>>;
196
+ }
197
+ interface RubricDimension<TRunOutput> {
198
+ /** Unique identifier — appears in finding subjects (`rubric:<id>`). */
199
+ id: string;
200
+ /** 0..1 — weight in the composite. */
201
+ weight: number;
202
+ /**
203
+ * Deterministic scorer: given the persona + run output, returns a
204
+ * 0..1 score. The substrate sums weight × score across dimensions
205
+ * for the deterministic composite; judges supplement subjective dims.
206
+ */
207
+ score: (input: {
208
+ persona: unknown;
209
+ output: TRunOutput;
210
+ }) => number;
211
+ /** Optional human-readable label for reports. */
212
+ label?: string;
213
+ }
214
+ interface JudgeConfig<TRunOutput> {
215
+ /** Judge identifier — appears in trace spans + manifest. */
216
+ id: string;
217
+ /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */
218
+ model: string;
219
+ /** Dimensions this judge scores. */
220
+ dimensions: ReadonlyArray<string>;
221
+ /**
222
+ * Optional rubric anchors — text examples the judge sees as a
223
+ * few-shot prompt to calibrate. STRONGLY recommended for subjective
224
+ * dimensions; required by the calibration gate (Pearson ≥0.7).
225
+ */
226
+ anchors?: ReadonlyArray<{
227
+ input: string;
228
+ output: TRunOutput;
229
+ expected: Record<string, number>;
230
+ }>;
231
+ }
232
+ interface AgentRuntime<TPersona, TRunOutput> {
233
+ /**
234
+ * Invoke the agent against one persona. Returns BOTH:
235
+ * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric
236
+ * product consumes verbatim (SSE / WebSocket / inline render).
237
+ * **Streaming is mandatory — never collapse this to a single Promise.**
238
+ * The agent's existing `runChatTurn` (or equivalent async generator)
239
+ * plugs in here directly.
240
+ * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream
241
+ * drains. The eval substrate awaits this for rubric scoring; chat
242
+ * products usually ignore it (they already rendered incrementally).
243
+ *
244
+ * Implementation contract:
245
+ * 1. `act` MUST return immediately (synchronous construction of the
246
+ * `events` iterator + the `output` promise).
247
+ * 2. Iterating `events` drives the underlying LLM/tool calls — the
248
+ * caller chooses when to consume.
249
+ * 3. `output` resolves only after the iterator yields its terminal
250
+ * event (typically `task_end`); see `collectAgentRun` helper.
251
+ *
252
+ * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes
253
+ * SHOULD record LLM/tool spans through it for capture integrity.
254
+ * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful
255
+ * cancel. `ctx.signal` is the standard abort signal.
256
+ */
257
+ act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>;
258
+ }
259
+ interface AgentRunInvocation<TRunOutput> {
260
+ /** Live stream of typed runtime events. Consumed by chat UX directly. */
261
+ events: AsyncIterable<RuntimeStreamEvent>;
262
+ /** Final structured output the rubric scores. Resolves after `events` drains. */
263
+ output: Promise<TRunOutput>;
264
+ }
265
+ /**
266
+ * Stub for agents whose `runtime.act` is not yet wired to the substrate's
267
+ * eval path. Preserves the streaming contract (empty event stream + a
268
+ * rejected `output` promise that tells the caller exactly what to fix).
269
+ *
270
+ * Per-vertical manifests usually start with this stub and replace it with
271
+ * the agent's real streaming runtime (`runChatTurn` or equivalent) once
272
+ * the eval path consumes the manifest end-to-end.
273
+ */
274
+ declare function unimplementedAgentRun<TRunOutput = unknown>(reason?: string): AgentRunInvocation<TRunOutput>;
275
+ /**
276
+ * Drain `act`'s `events` into an array AND await its `output`. Useful for
277
+ * eval / outcome-measurement code paths that don't care about live
278
+ * rendering. The events array is preserved so the substrate can inspect
279
+ * tool calls / readiness / questions retrospectively.
280
+ *
281
+ * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming
282
+ * (no incremental render). Use `for await (const ev of invocation.events)`
283
+ * directly in the chat surface.
284
+ */
285
+ declare function collectAgentRun<TRunOutput>(invocation: AgentRunInvocation<TRunOutput>): Promise<{
286
+ events: ReadonlyArray<RuntimeStreamEvent>;
287
+ output: TRunOutput;
288
+ }>;
289
+ interface AgentRunContext {
290
+ /** Substrate-managed trace emitter. */
291
+ emitter: _tangle_network_agent_eval.TraceEmitter;
292
+ /** Stable run id for this persona × variant cell. */
293
+ runId: string;
294
+ /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */
295
+ variantId?: string;
296
+ /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */
297
+ deadlineMs?: number;
298
+ /** Optional abort signal. */
299
+ signal?: AbortSignal;
300
+ }
301
+ interface AnalystConfig {
302
+ /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */
303
+ model: string;
304
+ /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */
305
+ budgetUsd?: number;
306
+ /** Backend hint for the AxAIService factory — same shape every kind uses. */
307
+ backend?: {
308
+ name?: 'openai' | 'router';
309
+ apiKey?: string;
310
+ baseUrl?: string;
311
+ };
312
+ }
313
+ interface AutoApplyPolicy {
314
+ knowledge?: {
315
+ enabled: boolean;
316
+ confidenceThreshold?: number;
317
+ mode?: 'write' | 'open-pr';
318
+ };
319
+ improvement?: {
320
+ enabled: boolean;
321
+ confidenceThreshold?: number;
322
+ mode?: 'write' | 'open-pr';
323
+ };
324
+ }
325
+ declare class AgentManifestError extends Error {
326
+ readonly agentId: string;
327
+ readonly issues: ReadonlyArray<unknown>;
328
+ constructor(message: string, agentId: string, issues?: ReadonlyArray<unknown>);
329
+ }
330
+ /**
331
+ * Construct a validated agent manifest. Throws `AgentManifestError`
332
+ * if any required surface is missing on disk.
333
+ *
334
+ * Generics: pass your persona / output types if you want narrowed
335
+ * `runtime.act` signatures:
336
+ * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`
337
+ *
338
+ * Most callers don't need the generics — the substrate operates on
339
+ * `unknown` payloads internally and the manifest's `score` /
340
+ * `runtime.act` see the typed shapes via TypeScript inference at
341
+ * the call site.
342
+ */
343
+ declare function defineAgent<TPersona = unknown, TRunOutput = unknown>(manifest: AgentManifest<TPersona, TRunOutput>): AgentManifest<TPersona, TRunOutput>;
344
+
345
+ /**
346
+ * Substrate-default `ImprovementAdapter` — surfaces-driven, LLM-drafted
347
+ * patches, optional auto-apply or PR-open.
348
+ *
349
+ * This is the one ImprovementAdapter every vertical agent uses. The
350
+ * substrate parses each finding's `subject` via
351
+ * `parseFindingSubject` (agent-eval), resolves it to a real file path
352
+ * via the agent's `AgentSurfaces`, reads the current content, and asks
353
+ * an LLM to draft a unified-diff patch given the finding + current
354
+ * content + per-kind editing-discipline rules.
355
+ *
356
+ * Auto-apply gates on the source-finding's confidence and the
357
+ * autoApply.improvement policy. Two modes:
358
+ * `write` — apply the patch in-place via `git apply -p0`. Operator
359
+ * reviews via `git diff`.
360
+ * `open-pr` — write to a branch, commit, push, open a PR via `gh`.
361
+ * Operator reviews via the PR UI.
362
+ *
363
+ * Fail-loud rules:
364
+ * - Findings whose subject doesn't parse → counted in `errors`.
365
+ * - Findings whose subject targets an undeclared surface → counted in
366
+ * `errors` with the offending kind in the message.
367
+ * - Findings whose target path doesn't exist AND the kind isn't a
368
+ * create-new variant (`new-tool`, `knowledge.wiki`) → counted in
369
+ * `errors` with the resolved path in the message.
370
+ * - LLM drafts that fail JSON-schema validation → counted in
371
+ * `errors` with the schema issue.
372
+ *
373
+ * No silent skips. Every dropped finding has a recorded reason the
374
+ * loop's report surfaces.
375
+ */
376
+
377
+ interface SurfaceImprovementEdit {
378
+ /** Stable id derived from the source finding so re-proposals are idempotent. */
379
+ id: string;
380
+ /** The finding that produced this edit — for revert + audit trail. */
381
+ sourceFindingId: string;
382
+ /** Parsed subject; included so the apply step doesn't re-parse. */
383
+ subject: FindingSubject;
384
+ /** Resolved on-disk target. */
385
+ target: ResolvedSurface;
386
+ /** SHA-256 of the current file content the patch was drafted against. */
387
+ baseSha256: string;
388
+ /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */
389
+ patch: string;
390
+ /** One-line summary the operator sees in the report / PR title. */
391
+ summary: string;
392
+ /** Multi-line rationale for the PR body — finding context + LLM reasoning. */
393
+ rationale: string;
394
+ /** Carry-forward from the finding so the apply gate can check the threshold. */
395
+ confidence: number;
396
+ /** Carry-forward severity for prioritization. */
397
+ severity: AnalystFinding['severity'];
398
+ }
399
+ interface CreateSurfaceImprovementAdapterOpts {
400
+ surfaces: AgentSurfaces;
401
+ repoRoot: string;
402
+ /**
403
+ * LLM-draft callback. Given a finding + current file content + the
404
+ * resolved target, returns a unified-diff patch + summary + rationale.
405
+ *
406
+ * Required — the substrate doesn't ship a hardcoded prompt; the agent
407
+ * author picks the model (Haiku for cheap routine drafts, Sonnet for
408
+ * substantive prompt rewrites, etc.) via this callback.
409
+ */
410
+ draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>;
411
+ /**
412
+ * Apply mode:
413
+ * `write` — `git apply` in-place; operator reviews via `git diff`
414
+ * `open-pr` — branch + commit + push + `gh pr create`
415
+ * `none` — never apply; collect proposals for the report only
416
+ *
417
+ * The `apply` method honours this even when the loop calls it; the
418
+ * effective behaviour is also gated on the per-finding confidence
419
+ * threshold via `runAnalystLoop`'s `autoApply` policy.
420
+ */
421
+ mode?: 'write' | 'open-pr' | 'none';
422
+ /** When `mode === 'open-pr'`, the base branch new PRs target. Default: `main`. */
423
+ baseBranch?: string;
424
+ /** Required for `mode === 'open-pr'` — the GH owner/repo (`tangle-network/tax-agent`). */
425
+ ghRepo?: string;
426
+ /**
427
+ * When the resolved target doesn't exist, allow the substrate to
428
+ * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default
429
+ * true for those kinds, false for `system-prompt` / `rubric` / etc.
430
+ * (named sections that don't exist are a contract violation, not a
431
+ * scaffolding opportunity).
432
+ */
433
+ allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>;
434
+ }
435
+ interface DraftPatchInput {
436
+ finding: AnalystFinding;
437
+ subject: FindingSubject;
438
+ target: ResolvedSurface;
439
+ /** Current file content (empty string when `intent === 'create-new'`). */
440
+ currentContent: string;
441
+ }
442
+ interface DraftPatchOutput {
443
+ /** Unified diff against the current file content. Empty string skips this finding. */
444
+ patch: string;
445
+ /** One-line summary for the operator. */
446
+ summary: string;
447
+ /** Multi-line rationale for the PR body. */
448
+ rationale: string;
449
+ }
450
+ declare function createSurfaceImprovementAdapter(opts: CreateSurfaceImprovementAdapterOpts): ImprovementAdapter<SurfaceImprovementEdit>;
451
+
452
+ /**
453
+ * Substrate-default `KnowledgeAdapter` — wraps agent-knowledge's
454
+ * `proposeFromFindings` + `applyKnowledgeWriteBlocks` with substrate
455
+ * defaults (auto-lint after apply, source linkage via finding id).
456
+ *
457
+ * Every agent that ships a `.agent-knowledge/` tree uses this adapter
458
+ * unmodified. Per-agent customization happens at the manifest level
459
+ * (`autoApply.knowledge.confidenceThreshold`, etc.), not by writing a
460
+ * new adapter.
461
+ *
462
+ * Lint discipline: after each apply we run agent-knowledge's
463
+ * `lintKnowledgeIndex` to catch broken links / circular claims /
464
+ * duplicate pages introduced by the new writes. Findings that fail the
465
+ * post-apply lint are recorded in `warnings`; the apply itself is not
466
+ * rolled back (lint failures are soft — humans review the wiki state).
467
+ */
468
+
469
+ interface CreateSurfaceKnowledgeAdapterOpts {
470
+ /** `.agent-knowledge/` root (absolute path the substrate writes blocks against). */
471
+ knowledgeRoot: string;
472
+ }
473
+ /**
474
+ * Build the adapter. We accept the agent-knowledge functions as DI so
475
+ * the substrate stays decoupled from a specific agent-knowledge
476
+ * version — the agent author imports them in their manifest module
477
+ * and hands them to the factory.
478
+ *
479
+ * `proposeFromFindings(findings)` returns
480
+ * `{ proposals: KnowledgeProposal[]; skipped: number; errors: ... }`.
481
+ *
482
+ * `applyKnowledgeWriteBlocks(root, content)` returns
483
+ * `{ written: string[]; warnings: string[] }`.
484
+ *
485
+ * `lintKnowledgeIndex(index)` (optional) returns `KnowledgeLintFinding[]`.
486
+ */
487
+ interface KnowledgeAdapterDeps<TProposal> {
488
+ proposeFromFindings: (findings: ReadonlyArray<AnalystFinding>) => {
489
+ proposals: TProposal[];
490
+ skipped: number;
491
+ errors: Array<{
492
+ findingId: string;
493
+ subject: string;
494
+ message: string;
495
+ }>;
496
+ };
497
+ applyKnowledgeWriteBlocks: (root: string, proposalText: string) => Promise<{
498
+ written: string[];
499
+ warnings: string[];
500
+ }>;
501
+ /**
502
+ * Optional post-apply lint hook. The substrate runs it after each
503
+ * batch of writes; failures land in `warnings` (the apply is not
504
+ * rolled back — lint signals drift to review, not block).
505
+ */
506
+ lintAfterApply?: (root: string) => Promise<ReadonlyArray<string>>;
507
+ }
508
+ declare function createSurfaceKnowledgeAdapter<TProposal>(opts: CreateSurfaceKnowledgeAdapterOpts, deps: KnowledgeAdapterDeps<TProposal>): KnowledgeAdapter<TProposal>;
509
+
510
+ /**
511
+ * `OutcomeMeasurement` — the missing metric that turns the analyst
512
+ * loop from "observability" into "self-improvement".
513
+ *
514
+ * Without this hook, the loop reports process counts (`findings: 42`,
515
+ * `applied: 7`) and never proves the applied edits actually improved
516
+ * anything. With this hook, the substrate re-runs the cohort against
517
+ * the same personas after each apply pass and reports a composite
518
+ * score delta. A negative delta is the substrate's strongest signal
519
+ * to either roll back or surface for review.
520
+ *
521
+ * Wiring is intentionally simple: pass the manifest + the `runAgentEval`
522
+ * function and a list of `personaIds` to re-run. The wrapper:
523
+ * 1. Captures the baseline composite from the just-finished run.
524
+ * 2. After `runAnalystLoop` returns, re-invokes `runAgentEval` against
525
+ * the same persona slice.
526
+ * 3. Computes the delta and appends to `loop-report.json`.
527
+ * 4. If `rollbackOnRegression` and delta < 0, reverts applied edits.
528
+ */
529
+
530
+ interface OutcomeMeasurement {
531
+ /** Baseline composite before applies — captured from the most-recent eval run. */
532
+ baselineComposite: number;
533
+ /** Composite after re-running the cohort with applied edits. */
534
+ afterComposite: number;
535
+ /** `afterComposite - baselineComposite`. Positive = the loop improved the agent. */
536
+ delta: number;
537
+ /** Per-persona deltas for finer-grained review. */
538
+ perPersona: ReadonlyArray<{
539
+ personaId: string;
540
+ before: number;
541
+ after: number;
542
+ delta: number;
543
+ }>;
544
+ /** When the substrate rolled back applies due to regression, the paths reverted. */
545
+ rolledBackPaths: ReadonlyArray<string>;
546
+ }
547
+ interface OutcomeMeasurementOpts {
548
+ /** Composite scores from the run that produced the findings. */
549
+ baseline: ReadonlyArray<{
550
+ personaId: string;
551
+ composite: number;
552
+ }>;
553
+ /**
554
+ * Re-run callback — the substrate invokes this after applies. The
555
+ * agent author provides their `runAgentEval`-equivalent so the
556
+ * substrate can ask "score this persona slice now."
557
+ *
558
+ * The callback SHOULD reuse the same cohort + judges + variant as
559
+ * the baseline run; only the agent's mutable surfaces have changed.
560
+ */
561
+ reRunCohort: (personaIds: ReadonlyArray<string>) => Promise<ReadonlyArray<{
562
+ personaId: string;
563
+ composite: number;
564
+ }>>;
565
+ /** When `true`, applied edits are reverted on negative delta. Default `false`. */
566
+ rollbackOnRegression?: boolean;
567
+ /** Callback to revert a list of paths (typically `git checkout HEAD --`). */
568
+ revert?: (paths: ReadonlyArray<string>) => Promise<void>;
569
+ }
570
+ /**
571
+ * Run `runAnalystLoop` and stamp an `OutcomeMeasurement` onto the
572
+ * result. The substrate calls this after each canonical eval; the
573
+ * delta lands in `loop-report.json` for cross-run trend analysis.
574
+ *
575
+ * The function returns the original `RunAnalystLoopResult` enriched
576
+ * with `outcome` so callers stay backwards-compatible (the field is
577
+ * optional on the type; missing means no measurement was wired).
578
+ */
579
+ declare function measureOutcome<TProposal, TEdit>(result: RunAnalystLoopResult<TProposal, TEdit>, opts: OutcomeMeasurementOpts): Promise<RunAnalystLoopResult<TProposal, TEdit> & {
580
+ outcome: OutcomeMeasurement;
581
+ }>;
582
+
583
+ export { type AgentManifest, AgentManifestError, type AgentRubric, type AgentRunContext, type AgentRunInvocation, type AgentRuntime, type AgentSurfaces, type AnalystConfig, type AutoApplyPolicy, type CreateSurfaceImprovementAdapterOpts, type CreateSurfaceKnowledgeAdapterOpts, type DraftPatchInput, type DraftPatchOutput, type JudgeConfig, type KnowledgeAdapterDeps, type OutcomeMeasurement, type OutcomeMeasurementOpts, type ResolvedSurface, type RubricDimension, type SurfaceImprovementEdit, type SurfaceValidationIssue, collectAgentRun, createSurfaceImprovementAdapter, createSurfaceKnowledgeAdapter, defineAgent, measureOutcome, renderSurfaceIssues, resolveSubjectPath, unimplementedAgentRun, validateSurfaces };