@tangle-network/agent-runtime 0.81.1 → 0.83.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 +4 -0
- package/dist/agent.d.ts +5 -3
- package/dist/agent.js +7 -7
- package/dist/agent.js.map +1 -1
- package/dist/analyst-loop.d.ts +3 -2
- package/dist/analyst-loop.js +2 -2
- package/dist/{chunk-35WXYO26.js → chunk-4WXGK6GV.js} +2 -2
- package/dist/chunk-4WXGK6GV.js.map +1 -0
- package/dist/{chunk-UZ5SODU7.js → chunk-5IBQAPVB.js} +1 -1
- package/dist/chunk-5IBQAPVB.js.map +1 -0
- package/dist/{chunk-5JAUQZQA.js → chunk-7LO5GMAO.js} +1 -1
- package/dist/chunk-7LO5GMAO.js.map +1 -0
- package/dist/{chunk-H7IBHAFT.js → chunk-BZF3KQ6G.js} +1 -1
- package/dist/chunk-BZF3KQ6G.js.map +1 -0
- package/dist/{chunk-WIR4HOOJ.js → chunk-DPEUKJRO.js} +1 -1
- package/dist/chunk-DPEUKJRO.js.map +1 -0
- package/dist/{chunk-EAGRBFQF.js → chunk-J3N6GODQ.js} +2 -2
- package/dist/chunk-J3N6GODQ.js.map +1 -0
- package/dist/{chunk-GRAGM4MC.js → chunk-NURIQBJQ.js} +1 -1
- package/dist/chunk-NURIQBJQ.js.map +1 -0
- package/dist/{chunk-D6GIWPKD.js → chunk-QDVLTRCP.js} +51 -4
- package/dist/chunk-QDVLTRCP.js.map +1 -0
- package/dist/{chunk-FNMGYYSS.js → chunk-SGKPNBXE.js} +1 -1
- package/dist/chunk-SGKPNBXE.js.map +1 -0
- package/dist/{chunk-VHJDS6OR.js → chunk-SSA6OERV.js} +6 -6
- package/dist/chunk-SSA6OERV.js.map +1 -0
- package/dist/{chunk-BPS254IE.js → chunk-UD4BHQMI.js} +2 -2
- package/dist/{chunk-BPS254IE.js.map → chunk-UD4BHQMI.js.map} +1 -1
- package/dist/{chunk-OUGNIHDZ.js → chunk-UJ3ONGHR.js} +6 -6
- package/dist/chunk-UJ3ONGHR.js.map +1 -0
- package/dist/{chunk-LWGVVP2C.js → chunk-VNOOH22O.js} +2 -2
- package/dist/chunk-VNOOH22O.js.map +1 -0
- package/dist/{chunk-NBV35BR6.js → chunk-YEJR7IXO.js} +1 -1
- package/dist/chunk-YEJR7IXO.js.map +1 -0
- package/dist/{chunk-C2FZ6GR6.js → chunk-YPA5MLVE.js} +2 -2
- package/dist/chunk-YPA5MLVE.js.map +1 -0
- package/dist/{coordination-BI9tpcmF.d.ts → coordination-CuDLO8wj.d.ts} +53 -32
- package/dist/environment-provider.d.ts +2 -2
- package/dist/environment-provider.js +1 -1
- package/dist/{improvement-adapter-CioiEE2z.d.ts → improvement-adapter-CDR8QNVM.d.ts} +3 -0
- package/dist/index.d.ts +163 -49
- package/dist/index.js +43 -13
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +14 -8
- package/dist/intelligence.js +1 -1
- package/dist/intelligence.js.map +1 -1
- package/dist/{kb-gate-CuzMYGYM.d.ts → kb-gate-CwHO0vz6.d.ts} +4 -2
- package/dist/lifecycle.d.ts +2 -2
- package/dist/lifecycle.js +3 -3
- package/dist/{local-harness-DU7yV6mG.d.ts → local-harness-sI0S_XNA.d.ts} +2 -1
- package/dist/{loop-runner-bin-CBkLsyFg.d.ts → loop-runner-bin-hQDUL8Ld.d.ts} +28 -13
- package/dist/loop-runner-bin.d.ts +7 -7
- package/dist/loop-runner-bin.js +10 -10
- package/dist/loops.d.ts +153 -46
- package/dist/loops.js +9 -7
- package/dist/mcp/bin.js +8 -8
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +44 -38
- package/dist/mcp/index.js +11 -11
- package/dist/mcp/index.js.map +1 -1
- package/dist/{mcp-serve-verifier-BvMAV_8U.d.ts → mcp-serve-verifier-FL7-ZEb_.d.ts} +8 -3
- package/dist/{openai-tools-B-3v06BE.d.ts → openai-tools-BnrOmGjN.d.ts} +7 -4
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js.map +1 -1
- package/dist/profiles.d.ts +36 -23
- package/dist/profiles.js +2 -2
- package/dist/profiles.js.map +1 -1
- package/dist/{router-client-D6Ocf4jG.d.ts → router-client-r8y_VFVM.d.ts} +1 -0
- package/dist/{substrate-rNj6TDc3.d.ts → substrate-DO2GHNg2.d.ts} +5 -3
- package/dist/{types-By9LXllv.d.ts → types-Driepl87.d.ts} +3 -2
- package/dist/{types-BF-MEsQB.d.ts → types-ESeMOj94.d.ts} +26 -11
- package/dist/{worktree-fanout-D9Z2dMS9.d.ts → worktree-fanout-D6xR2CIA.d.ts} +16 -10
- package/dist/{worktree-harness-Dx8XULW3.d.ts → worktree-harness-CX_McRLp.d.ts} +11 -8
- package/package.json +1 -1
- package/dist/chunk-35WXYO26.js.map +0 -1
- package/dist/chunk-5JAUQZQA.js.map +0 -1
- package/dist/chunk-C2FZ6GR6.js.map +0 -1
- package/dist/chunk-D6GIWPKD.js.map +0 -1
- package/dist/chunk-EAGRBFQF.js.map +0 -1
- package/dist/chunk-FNMGYYSS.js.map +0 -1
- package/dist/chunk-GRAGM4MC.js.map +0 -1
- package/dist/chunk-H7IBHAFT.js.map +0 -1
- package/dist/chunk-LWGVVP2C.js.map +0 -1
- package/dist/chunk-NBV35BR6.js.map +0 -1
- package/dist/chunk-OUGNIHDZ.js.map +0 -1
- package/dist/chunk-UZ5SODU7.js.map +0 -1
- package/dist/chunk-VHJDS6OR.js.map +0 -1
- package/dist/chunk-WIR4HOOJ.js.map +0 -1
|
@@ -2,13 +2,14 @@ import { ControlEvalResult, KnowledgeRequirement, ControlBudget, KnowledgeReadin
|
|
|
2
2
|
import { CreateSandboxOptions, SandboxInstance, SandboxEvent, AgentProfile } from '@tangle-network/sandbox';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* @stable
|
|
6
5
|
*
|
|
7
6
|
* Core task, session, adapter, and stream-event types for the runtime.
|
|
8
7
|
*
|
|
9
8
|
* This module owns the public shape of every cross-cutting record (`TaskSpec`,
|
|
10
9
|
* `RuntimeSession`, `RuntimeStreamEvent`). Everything else in the runtime
|
|
11
10
|
* imports from here so type-level changes ripple in one place.
|
|
11
|
+
*
|
|
12
|
+
* @stable
|
|
12
13
|
*/
|
|
13
14
|
|
|
14
15
|
/** @stable */
|
|
@@ -144,7 +145,6 @@ type AgentRuntimeEvent<TState = unknown, TAction = unknown, TActionResult = unkn
|
|
|
144
145
|
/** @stable */
|
|
145
146
|
type AgentRuntimeEventSink<TState = unknown, TAction = unknown, TActionResult = unknown, TEval extends ControlEvalResult = ControlEvalResult> = (event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>) => Promise<void> | void;
|
|
146
147
|
/**
|
|
147
|
-
* @stable
|
|
148
148
|
*
|
|
149
149
|
* Typed transport / backend failure detail. Carried on `backend_error` and
|
|
150
150
|
* `final` events when the backend's stream throws or the upstream HTTP call
|
|
@@ -157,6 +157,8 @@ type AgentRuntimeEventSink<TState = unknown, TAction = unknown, TActionResult =
|
|
|
157
157
|
* misconfigured proxy never bloats event payloads or logs. Consumers needing
|
|
158
158
|
* the full body should inspect the underlying `BackendTransportError.body`
|
|
159
159
|
* via a custom `mapEvent` or backend wrapper.
|
|
160
|
+
*
|
|
161
|
+
* @stable
|
|
160
162
|
*/
|
|
161
163
|
interface BackendErrorDetail {
|
|
162
164
|
/**
|
|
@@ -172,7 +174,6 @@ interface BackendErrorDetail {
|
|
|
172
174
|
body?: string;
|
|
173
175
|
}
|
|
174
176
|
/**
|
|
175
|
-
* @stable
|
|
176
177
|
*
|
|
177
178
|
* OpenAI Chat Completions tool descriptor. The shape mirrors the
|
|
178
179
|
* `/v1/chat/completions` `tools[]` parameter so callers can pass tool
|
|
@@ -185,6 +186,8 @@ interface BackendErrorDetail {
|
|
|
185
186
|
* MCP `tools/list` at config time and project the result into this shape. The
|
|
186
187
|
* runtime intentionally does NOT depend on `@modelcontextprotocol/sdk` —
|
|
187
188
|
* keeping the backend transport thin lets domain repos own MCP plumbing.
|
|
189
|
+
*
|
|
190
|
+
* @stable
|
|
188
191
|
*/
|
|
189
192
|
interface OpenAIChatTool {
|
|
190
193
|
type: 'function';
|
|
@@ -195,12 +198,13 @@ interface OpenAIChatTool {
|
|
|
195
198
|
};
|
|
196
199
|
}
|
|
197
200
|
/**
|
|
198
|
-
* @stable
|
|
199
201
|
*
|
|
200
202
|
* `tool_choice` parameter for OpenAI-compat chat. Same shape as the OpenAI
|
|
201
203
|
* spec: `'auto'` (default — model decides), `'none'` (disable tool calling
|
|
202
204
|
* for this turn), `'required'` (force a tool call), or a specific function
|
|
203
205
|
* pin `{ type: 'function', function: { name } }`.
|
|
206
|
+
*
|
|
207
|
+
* @stable
|
|
204
208
|
*/
|
|
205
209
|
type OpenAIChatToolChoice = 'auto' | 'none' | 'required' | {
|
|
206
210
|
type: 'function';
|
|
@@ -209,11 +213,12 @@ type OpenAIChatToolChoice = 'auto' | 'none' | 'required' | {
|
|
|
209
213
|
};
|
|
210
214
|
};
|
|
211
215
|
/**
|
|
212
|
-
* @stable
|
|
213
216
|
*
|
|
214
217
|
* `response_format` parameter for OpenAI-compatible chat endpoints. Use
|
|
215
218
|
* `json_object` when the caller needs syntactically valid JSON, or
|
|
216
219
|
* `json_schema` when the upstream provider supports schema-constrained JSON.
|
|
220
|
+
*
|
|
221
|
+
* @stable
|
|
217
222
|
*/
|
|
218
223
|
type OpenAIChatResponseFormat = {
|
|
219
224
|
type: 'text';
|
|
@@ -504,11 +509,12 @@ interface KnowledgeReadinessDecision {
|
|
|
504
509
|
}
|
|
505
510
|
|
|
506
511
|
/**
|
|
507
|
-
* @experimental
|
|
508
512
|
*
|
|
509
513
|
* Runtime hook contracts. Hooks are execution-scoped observers, not part of an
|
|
510
514
|
* `AgentProfile`: profiles stay portable agent recipes; hooks attach to the
|
|
511
515
|
* loop or product harness that is running the profile.
|
|
516
|
+
*
|
|
517
|
+
* @experimental
|
|
512
518
|
*/
|
|
513
519
|
type RuntimeHookPhase = 'before' | 'after' | 'error' | 'event';
|
|
514
520
|
type RuntimeHookTarget = 'agent.run' | 'agent.turn' | 'agent.tool_call' | 'agent.spawn' | 'agent.child' | 'agent.plan' | 'agent.decision' | (string & {});
|
|
@@ -582,11 +588,12 @@ declare function defineRuntimeHooks(hooks: RuntimeHooks): RuntimeHooks;
|
|
|
582
588
|
* event. Use this to attach N observers to a loop instead of a second event bus.
|
|
583
589
|
*/
|
|
584
590
|
declare function composeRuntimeHooks(...entries: Array<RuntimeHooks | undefined | null | false>): RuntimeHooks;
|
|
591
|
+
/** Fire `hooks.onEvent`, swallowing sync throws and surfacing async failures to `onError`. */
|
|
585
592
|
declare function notifyRuntimeHookEvent(hooks: RuntimeHooks | undefined, event: RuntimeHookEvent, context?: RuntimeHookContext): void;
|
|
593
|
+
/** Fire `hooks.onDecisionPoint`, swallowing sync throws and surfacing async failures to `onError`. */
|
|
586
594
|
declare function notifyRuntimeDecisionPoint(hooks: RuntimeHooks | undefined, point: RuntimeDecisionPoint, context?: RuntimeHookContext): void;
|
|
587
595
|
|
|
588
596
|
/**
|
|
589
|
-
* @stable
|
|
590
597
|
*
|
|
591
598
|
* Production-run lifecycle: record what the agent did on behalf of a customer,
|
|
592
599
|
* what it cost, and how it ended.
|
|
@@ -609,6 +616,8 @@ declare function notifyRuntimeDecisionPoint(hooks: RuntimeHooks | undefined, poi
|
|
|
609
616
|
* KV store. The adapter receives a sanitized row shape; no telemetry
|
|
610
617
|
* payload bytes flow through it unless the consumer opts in via
|
|
611
618
|
* `RuntimeRunOptions.telemetryEvents`.
|
|
619
|
+
*
|
|
620
|
+
* @stable
|
|
612
621
|
*/
|
|
613
622
|
|
|
614
623
|
/** @stable */
|
|
@@ -712,15 +721,15 @@ interface RuntimeRunHandle {
|
|
|
712
721
|
persist(metadata?: Record<string, unknown>): Promise<void>;
|
|
713
722
|
}
|
|
714
723
|
/**
|
|
715
|
-
* @stable
|
|
716
724
|
*
|
|
717
725
|
* Construct a runtime-run handle. The returned handle is mutable across its
|
|
718
726
|
* lifetime; consumers should not share it across requests.
|
|
727
|
+
*
|
|
728
|
+
* @stable
|
|
719
729
|
*/
|
|
720
730
|
declare function startRuntimeRun(options: RuntimeRunOptions): RuntimeRunHandle;
|
|
721
731
|
|
|
722
732
|
/**
|
|
723
|
-
* @experimental
|
|
724
733
|
*
|
|
725
734
|
* Driven-loop substrate — type surface.
|
|
726
735
|
*
|
|
@@ -730,6 +739,8 @@ declare function startRuntimeRun(options: RuntimeRunOptions): RuntimeRunHandle;
|
|
|
730
739
|
* accounting, concurrency, abort propagation, cost aggregation, and trace
|
|
731
740
|
* emission; the driver owns topology (plan + decide); the validator owns
|
|
732
741
|
* output scoring; the output adapter owns event-stream → typed-output decode.
|
|
742
|
+
*
|
|
743
|
+
* @experimental
|
|
733
744
|
*/
|
|
734
745
|
|
|
735
746
|
/** @experimental */
|
|
@@ -1243,7 +1254,11 @@ interface LoopTeardownFailedPayload {
|
|
|
1243
1254
|
/** `'timeout'` or the delete error message. */
|
|
1244
1255
|
reason: string;
|
|
1245
1256
|
}
|
|
1246
|
-
/**
|
|
1257
|
+
/**
|
|
1258
|
+
* Execution context for `runLoop`: the sandbox client the kernel creates boxes through, plus optional runtime hooks.
|
|
1259
|
+
*
|
|
1260
|
+
* @experimental
|
|
1261
|
+
*/
|
|
1247
1262
|
interface ExecCtx {
|
|
1248
1263
|
/** Sandbox SDK client — the kernel calls `.create()` per iteration. */
|
|
1249
1264
|
sandboxClient: SandboxClient;
|
|
@@ -1293,4 +1308,4 @@ interface ExecCtx {
|
|
|
1293
1308
|
parentSpanId?: string;
|
|
1294
1309
|
}
|
|
1295
1310
|
|
|
1296
|
-
export { type LoopDecisionPayload as $, type AgentRunSpec as A, type BackendErrorDetail as B, type RuntimeHookErrorContext as C, type RuntimeHookEvent as D, type ExecCtx as E, type RuntimeHookPhase as F, type RuntimeHookTarget as G, type RuntimeRunHandle as H, type Iteration as I, type RuntimeRunPersistenceAdapter as J, type KnowledgeReadinessDecision as K, type LoopTokenUsage as L, type RuntimeRunRow as M, composeRuntimeHooks as N, type OpenAIChatTool as O, defineRuntimeHooks as P, notifyRuntimeDecisionPoint as Q, type RuntimeHooks as R, type SandboxClient as S, notifyRuntimeHookEvent as T, startRuntimeRun as U, type Validator as V, type Driver as W, type LoopWinner as X, type LoopLineageOptions as Y, type LoopResult as Z, type MountRecorder as _, type RuntimeStreamEvent as a, type LoopEndedPayload as a0, type LoopIterationDispatchPayload as a1, type LoopIterationEndedPayload as a2, type LoopIterationStartedPayload as a3, type LoopPlanDescription as a4, type LoopPlanPayload as a5, type LoopStartedPayload as a6, type LoopTeardownFailedPayload as a7, type MountManifestEntry as a8, type RunProvenance as a9, type SelectionReceipt as aa, type ValidationCtx as ab, type OutputAdapter as b, type LoopTraceEvent as c, type LoopSandboxPlacement as d, type LoopTraceEmitter as e, type AgentBackendInput as f, type
|
|
1311
|
+
export { type LoopDecisionPayload as $, type AgentRunSpec as A, type BackendErrorDetail as B, type RuntimeHookErrorContext as C, type RuntimeHookEvent as D, type ExecCtx as E, type RuntimeHookPhase as F, type RuntimeHookTarget as G, type RuntimeRunHandle as H, type Iteration as I, type RuntimeRunPersistenceAdapter as J, type KnowledgeReadinessDecision as K, type LoopTokenUsage as L, type RuntimeRunRow as M, composeRuntimeHooks as N, type OpenAIChatTool as O, defineRuntimeHooks as P, notifyRuntimeDecisionPoint as Q, type RuntimeHooks as R, type SandboxClient as S, notifyRuntimeHookEvent as T, startRuntimeRun as U, type Validator as V, type Driver as W, type LoopWinner as X, type LoopLineageOptions as Y, type LoopResult as Z, type MountRecorder as _, type RuntimeStreamEvent as a, type LoopEndedPayload as a0, type LoopIterationDispatchPayload as a1, type LoopIterationEndedPayload as a2, type LoopIterationStartedPayload as a3, type LoopPlanDescription as a4, type LoopPlanPayload as a5, type LoopStartedPayload as a6, type LoopTeardownFailedPayload as a7, type MountManifestEntry as a8, type RunProvenance as a9, type SelectionReceipt as aa, type ValidationCtx as ab, type OutputAdapter as b, type LoopTraceEvent as c, type LoopSandboxPlacement as d, type LoopTraceEmitter as e, type AgentBackendInput as f, type OpenAIChatToolChoice as g, type OpenAIChatResponseFormat as h, type AgentExecutionBackend as i, type AgentBackendContext as j, type RunAgentTaskOptions as k, type AgentTaskRunResult as l, type RunAgentTaskStreamOptions as m, type AgentRuntimeEvent as n, type AgentTaskStatus as o, type RuntimeSessionStore as p, type RuntimeSession as q, type AgentAdapter as r, type AgentKnowledgeProvider as s, type AgentRuntimeEventSink as t, type AgentTaskContext as u, type AgentTaskSpec as v, type RuntimeDecisionEvidenceRef as w, type RuntimeDecisionKind as x, type RuntimeDecisionPoint as y, type RuntimeHookContext as z };
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { AgentProfile } from '@tangle-network/agent-interface';
|
|
2
2
|
import { AnalystFinding, DefaultVerdict } from '@tangle-network/agent-eval';
|
|
3
|
-
import { A as AgentSpec, b as ExecutorRegistry, B as Budget, c as Agent, S as SpawnJournal, d as ResultBlobStore, e as RootHandle, f as SupervisedResult, N as NodeId, g as Settled, h as Spend, i as Scope, a as Executor } from './types-
|
|
4
|
-
import { R as RuntimeHooks, I as Iteration } from './types-
|
|
3
|
+
import { A as AgentSpec, b as ExecutorRegistry, B as Budget, c as Agent, S as SpawnJournal, d as ResultBlobStore, e as RootHandle, f as SupervisedResult, N as NodeId, g as Settled, h as Spend, i as Scope, a as Executor } from './types-Driepl87.js';
|
|
4
|
+
import { R as RuntimeHooks, I as Iteration } from './types-ESeMOj94.js';
|
|
5
5
|
import { BackendType } from '@tangle-network/sandbox';
|
|
6
|
-
import { W as WorktreeHarnessResult, G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './worktree-harness-
|
|
7
|
-
import { L as LocalHarness, r as runLocalHarness } from './local-harness-
|
|
6
|
+
import { W as WorktreeHarnessResult, G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './worktree-harness-CX_McRLp.js';
|
|
7
|
+
import { L as LocalHarness, r as runLocalHarness } from './local-harness-sI0S_XNA.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* @experimental
|
|
11
10
|
*
|
|
12
11
|
* The personify layer — the "act like X" knob on top of the recursive keystone.
|
|
13
12
|
*
|
|
@@ -31,6 +30,8 @@ import { L as LocalHarness, r as runLocalHarness } from './local-harness-DU7yV6m
|
|
|
31
30
|
* substrate `AgentProfile`/`BackendType`. It typechecks standalone — no impl, no engine.
|
|
32
31
|
* Extensibility is structural: `Persona` carries an open `extensions` bag so a later
|
|
33
32
|
* world-model / memory field is additive (a new optional key), never a breaking change.
|
|
33
|
+
*
|
|
34
|
+
* @experimental
|
|
34
35
|
*/
|
|
35
36
|
|
|
36
37
|
/**
|
|
@@ -235,7 +236,6 @@ interface RunPersonifiedOptions<Task, D> {
|
|
|
235
236
|
type RunPersonified = <Task, D>(options: RunPersonifiedOptions<Task, D>) => Promise<SupervisedResult<Outcome<D>>>;
|
|
236
237
|
|
|
237
238
|
/**
|
|
238
|
-
* @experimental
|
|
239
239
|
*
|
|
240
240
|
* The RSI-wave type surface — the FROZEN contracts the wave's Core + Compose build to.
|
|
241
241
|
*
|
|
@@ -266,6 +266,8 @@ type RunPersonified = <Task, D>(options: RunPersonifiedOptions<Task, D>) => Prom
|
|
|
266
266
|
* Layering: imports ONLY keystone runtime types (`../supervise/types`), persona types
|
|
267
267
|
* (`./types`), the substrate `AnalystFinding`/`AgentProfile`, and the durable-store interfaces.
|
|
268
268
|
* Pure types/interfaces — this module typechecks standalone, owns no impl, invents no engine.
|
|
269
|
+
*
|
|
270
|
+
* @experimental
|
|
269
271
|
*/
|
|
270
272
|
|
|
271
273
|
/**
|
|
@@ -766,7 +768,6 @@ interface EqualKOnCostOptions {
|
|
|
766
768
|
type EqualKOnCost = (arms: ReadonlyArray<EqualKArm>, options?: EqualKOnCostOptions) => EqualKVerdict;
|
|
767
769
|
|
|
768
770
|
/**
|
|
769
|
-
* @experimental
|
|
770
771
|
*
|
|
771
772
|
* The mechanical patch gate — the SINGLE source of the no-op / always-on secret-path floor /
|
|
772
773
|
* forbidden-path / diff-size / test / typecheck checks over a captured diff. No I/O: it scores a
|
|
@@ -775,6 +776,8 @@ type EqualKOnCost = (arms: ReadonlyArray<EqualKArm>, options?: EqualKOnCostOptio
|
|
|
775
776
|
*
|
|
776
777
|
* The always-on safety floors (no-op rejection + secret-path) are also exported standalone
|
|
777
778
|
* (`isNonEmptyPatch` / `touchesSecretPath`) for reuse outside the full scorer.
|
|
779
|
+
*
|
|
780
|
+
* @experimental
|
|
778
781
|
*/
|
|
779
782
|
|
|
780
783
|
/** @experimental The per-task constraints the mechanical gate enforces. */
|
|
@@ -786,7 +789,6 @@ interface CoderCheckConstraints {
|
|
|
786
789
|
}
|
|
787
790
|
|
|
788
791
|
/**
|
|
789
|
-
* @experimental
|
|
790
792
|
*
|
|
791
793
|
* The worktree-CLI leaf executor — a supervisor-authored `AgentProfile` driving a local
|
|
792
794
|
* coding-harness CLI (claude / codex / opencode) on its OWN git worktree, surfaced as the open
|
|
@@ -806,6 +808,8 @@ interface CoderCheckConstraints {
|
|
|
806
808
|
* explicit, documented `budgetExempt` option rather than a buried hardcode: set it `false` ONLY for
|
|
807
809
|
* a harness that genuinely surfaces real token/usd usage to meter into the pool — otherwise the
|
|
808
810
|
* executor would meter a fabricated zero, which the no-silent-zeros rule forbids.
|
|
811
|
+
*
|
|
812
|
+
* @experimental
|
|
809
813
|
*/
|
|
810
814
|
|
|
811
815
|
/** Terminal artifact of one worktree-CLI run — the canonical worktree-harness result (the captured
|
|
@@ -865,7 +869,6 @@ interface WorktreeCliExecutorOptions {
|
|
|
865
869
|
declare function createWorktreeCliExecutor(options: WorktreeCliExecutorOptions): Executor<WorktreePatchArtifact>;
|
|
866
870
|
|
|
867
871
|
/**
|
|
868
|
-
* @experimental
|
|
869
872
|
*
|
|
870
873
|
* `patchDelivered` — the mechanical patch gate as a generic `DeliverableSpec` over the worktree-CLI
|
|
871
874
|
* artifact. It is one construction of a `DeliverableSpec` (a plain `check(artifact) => boolean`
|
|
@@ -883,6 +886,8 @@ declare function createWorktreeCliExecutor(options: WorktreeCliExecutorOptions):
|
|
|
883
886
|
* (the executor's `testCmd`/`typecheckCmd` were omitted) the corresponding signal is treated as
|
|
884
887
|
* passed UNLESS `require` lists it — so a gate that demands a tests-pass on an artifact that never
|
|
885
888
|
* ran tests fails closed (the honest outcome) rather than passing on a missing signal.
|
|
889
|
+
*
|
|
890
|
+
* @experimental
|
|
886
891
|
*/
|
|
887
892
|
|
|
888
893
|
/** @experimental */
|
|
@@ -905,7 +910,6 @@ interface PatchDeliverableOptions extends CoderCheckConstraints {
|
|
|
905
910
|
declare function patchDelivered(options?: PatchDeliverableOptions): DeliverableSpec<WorktreePatchArtifact>;
|
|
906
911
|
|
|
907
912
|
/**
|
|
908
|
-
* @experimental
|
|
909
913
|
*
|
|
910
914
|
* `worktreeFanout` — the GENERIC coding combinator: a `fanout` of N supervisor-authored harness
|
|
911
915
|
* profiles, each on its OWN worktree-CLI leaf, each `gateOnDeliverable(deliverable)`, winner via the
|
|
@@ -917,6 +921,8 @@ declare function patchDelivered(options?: PatchDeliverableOptions): DeliverableS
|
|
|
917
921
|
* worktree-CLI executor + the injected deliverable + the diff-size selector) into the generic
|
|
918
922
|
* combinator's `itemSpec`/`selectWinner` seams. Nothing here re-implements selection, gating, or
|
|
919
923
|
* fanout — it composes the existing primitives.
|
|
924
|
+
*
|
|
925
|
+
* @experimental
|
|
920
926
|
*/
|
|
921
927
|
|
|
922
928
|
/** @experimental One authored harness profile in a worktree fanout: the §1.5 profile + which local
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { a as Executor } from './types-
|
|
2
|
-
import { L as LocalHarness } from './local-harness-
|
|
1
|
+
import { a as Executor } from './types-Driepl87.js';
|
|
2
|
+
import { L as LocalHarness } from './local-harness-sI0S_XNA.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* @experimental
|
|
6
5
|
*
|
|
7
6
|
* The completion-oracle: **settled ⟺ DELIVERED.**
|
|
8
7
|
*
|
|
@@ -21,6 +20,8 @@ import { L as LocalHarness } from './local-harness-DU7yV6mG.js';
|
|
|
21
20
|
* The check is a DEPLOYABLE oracle — a test command, a state verifier, the commit0 judge —
|
|
22
21
|
* read off the child's output, never the model judging itself. A throwing check is
|
|
23
22
|
* fail-closed (not delivered), never a crash.
|
|
23
|
+
*
|
|
24
|
+
* @experimental
|
|
24
25
|
*/
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -44,7 +45,6 @@ interface DeliverableSpec<Out = unknown> {
|
|
|
44
45
|
declare function gateOnDeliverable<Out>(inner: Executor<Out>, deliverable: DeliverableSpec<Out>): Executor<Out>;
|
|
45
46
|
|
|
46
47
|
/**
|
|
47
|
-
* @experimental
|
|
48
48
|
*
|
|
49
49
|
* Git worktree helpers for the in-process delegation executor. Each
|
|
50
50
|
* delegation runs in its own worktree so multiple parallel harness
|
|
@@ -58,6 +58,8 @@ declare function gateOnDeliverable<Out>(inner: Executor<Out>, deliverable: Deliv
|
|
|
58
58
|
* (via a `runGit` helper). Stays narrow on purpose: no commits, no rebases.
|
|
59
59
|
* Diff capture stages all changes (`git add -A`) into the ephemeral worktree's
|
|
60
60
|
* index so created (untracked) files appear in the `--cached` diff.
|
|
61
|
+
*
|
|
62
|
+
* @experimental
|
|
61
63
|
*/
|
|
62
64
|
/** @experimental */
|
|
63
65
|
interface WorktreeHandle {
|
|
@@ -116,15 +118,14 @@ type GitRunner = (args: ReadonlyArray<string>, opts: {
|
|
|
116
118
|
stderr: string;
|
|
117
119
|
exitCode: number;
|
|
118
120
|
};
|
|
119
|
-
/** @experimental */
|
|
121
|
+
/** Checkout a fresh git worktree for a delegation run on a new branch under `variantsDir`. @experimental */
|
|
120
122
|
declare function createWorktree(options: CreateWorktreeOptions): Promise<WorktreeHandle>;
|
|
121
|
-
/** @experimental */
|
|
123
|
+
/** Stage all changes in a worktree and return the diff patch + shortstat against the base ref. @experimental */
|
|
122
124
|
declare function captureWorktreeDiff(options: DiffOptions): Promise<DiffResult>;
|
|
123
|
-
/** @experimental */
|
|
125
|
+
/** Remove a git worktree and delete its branch; tolerates already-removed paths. @experimental */
|
|
124
126
|
declare function removeWorktree(options: RemoveWorktreeOptions): Promise<void>;
|
|
125
127
|
|
|
126
128
|
/**
|
|
127
|
-
* @experimental
|
|
128
129
|
*
|
|
129
130
|
* The ONE worktree-harness execution core. The physical act — run a supervisor-authored
|
|
130
131
|
* `AgentProfile` on a local coding-harness CLI (claude / codex / opencode) against a fresh git
|
|
@@ -142,6 +143,8 @@ declare function removeWorktree(options: RemoveWorktreeOptions): Promise<void>;
|
|
|
142
143
|
* → the configured test/typecheck commands in the live worktree → return the result + a `cleanup`
|
|
143
144
|
* the caller invokes at its own teardown point. A throw cleans up before propagating, so a failed
|
|
144
145
|
* run never leaks a worktree.
|
|
146
|
+
*
|
|
147
|
+
* @experimental
|
|
145
148
|
*/
|
|
146
149
|
|
|
147
150
|
/** Outcome of one verification command run in the worktree (test or typecheck). */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.83.0",
|
|
4
4
|
"description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
|
|
5
5
|
"homepage": "https://github.com/tangle-network/agent-runtime#readme",
|
|
6
6
|
"repository": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/trace-propagation.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Trace context propagation for MCP subprocess.\n *\n * When the MCP server is launched as a child process by a sandbox harness,\n * the parent passes trace context via environment variables:\n *\n * TRACE_ID=<current-run-trace-id>\n * PARENT_SPAN_ID=<span-that-dispatched-the-delegation>\n *\n * The MCP server reads these at startup and uses them as the root of its\n * internal trace tree. All spans emitted by `runLoop` invocations inside\n * the MCP are children of the parent's delegation span.\n *\n * When these env vars are absent, the MCP generates a fresh trace root —\n * the server operates standalone without trace joining.\n */\n\nimport type { OtelExporter } from '../otel-export'\nimport { buildLoopOtelSpans, createOtelExporter } from '../otel-export'\nimport type { LoopTraceEmitter, LoopTraceEvent } from '../runtime/types'\n\nexport interface TraceContext {\n /** Trace id inherited from the parent process, or a fresh one. */\n traceId: string\n /** Parent span id from the delegation that launched this MCP server. */\n parentSpanId?: string\n}\n\n/**\n * Read trace context from the process environment.\n * Returns a context with inherited ids or a freshly generated root.\n */\nexport function readTraceContextFromEnv(): TraceContext {\n const traceId = process.env.TRACE_ID || generateTraceId()\n const parentSpanId = process.env.PARENT_SPAN_ID || undefined\n return { traceId, parentSpanId }\n}\n\n/**\n * Create a LoopTraceEmitter that:\n * 1. Parents all spans under the inherited PARENT_SPAN_ID.\n * 2. Exports spans to OTEL when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n *\n * Returns both the emitter and the optional exporter handle for shutdown.\n */\nexport function createPropagatingTraceEmitter(ctx: TraceContext): {\n emitter: LoopTraceEmitter\n exporter: OtelExporter | undefined\n context: TraceContext\n} {\n const exporter = createOtelExporter()\n\n // Buffer events per loop run, then emit the full nested span tree on\n // `loop.ended` so the topology hierarchy (loop → round → branch) reaches the\n // OTLP collector — not a flat list of zero-duration point spans. A run that\n // never reaches `loop.ended` (hard abort) drops its buffer; acceptable for\n // the short-lived MCP subprocess.\n const buffers = new Map<string, LoopTraceEvent[]>()\n\n const emitter: LoopTraceEmitter = {\n emit(event: LoopTraceEvent) {\n if (!exporter) return\n const buf = buffers.get(event.runId)\n if (buf) buf.push(event)\n else buffers.set(event.runId, [event])\n if (event.kind === 'loop.ended') {\n const events = buffers.get(event.runId) ?? [event]\n buffers.delete(event.runId)\n for (const span of buildLoopOtelSpans(events, ctx.traceId, ctx.parentSpanId)) {\n exporter.exportSpan(span)\n }\n }\n },\n }\n\n return { emitter, exporter, context: ctx }\n}\n\n/**\n * Build env vars to pass to a child MCP subprocess so it inherits the\n * current trace context.\n */\nexport function traceContextToEnv(ctx: TraceContext): Record<string, string> {\n const env: Record<string, string> = { TRACE_ID: ctx.traceId }\n if (ctx.parentSpanId) env.PARENT_SPAN_ID = ctx.parentSpanId\n return env\n}\n\nfunction generateTraceId(): string {\n const bytes = new Uint8Array(16)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n"],"mappings":";;;;;;AAkCO,SAAS,0BAAwC;AACtD,QAAM,UAAU,QAAQ,IAAI,YAAY,gBAAgB;AACxD,QAAM,eAAe,QAAQ,IAAI,kBAAkB;AACnD,SAAO,EAAE,SAAS,aAAa;AACjC;AASO,SAAS,8BAA8B,KAI5C;AACA,QAAM,WAAW,mBAAmB;AAOpC,QAAM,UAAU,oBAAI,IAA8B;AAElD,QAAM,UAA4B;AAAA,IAChC,KAAK,OAAuB;AAC1B,UAAI,CAAC,SAAU;AACf,YAAM,MAAM,QAAQ,IAAI,MAAM,KAAK;AACnC,UAAI,IAAK,KAAI,KAAK,KAAK;AAAA,UAClB,SAAQ,IAAI,MAAM,OAAO,CAAC,KAAK,CAAC;AACrC,UAAI,MAAM,SAAS,cAAc;AAC/B,cAAM,SAAS,QAAQ,IAAI,MAAM,KAAK,KAAK,CAAC,KAAK;AACjD,gBAAQ,OAAO,MAAM,KAAK;AAC1B,mBAAW,QAAQ,mBAAmB,QAAQ,IAAI,SAAS,IAAI,YAAY,GAAG;AAC5E,mBAAS,WAAW,IAAI;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,UAAU,SAAS,IAAI;AAC3C;AAMO,SAAS,kBAAkB,KAA2C;AAC3E,QAAM,MAA8B,EAAE,UAAU,IAAI,QAAQ;AAC5D,MAAI,IAAI,aAAc,KAAI,iBAAiB,IAAI;AAC/C,SAAO;AACT;AAEA,SAAS,kBAA0B;AACjC,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,MAAI,OAAO,WAAW,QAAQ,oBAAoB,YAAY;AAC5D,eAAW,OAAO,gBAAgB,KAAK;AAAA,EACzC,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,IAAI,IAAK,OAAM,CAAC,IAAI,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;AAAA,EACxE;AACA,SAAO,MAAM,KAAK,KAAK,EACpB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AACZ;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/local-harness.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Subprocess wrappers for the local coding-harness CLIs installed in the\n * sandbox image (claude-code, codex, opencode). Used by the in-process\n * delegation executor (`createInProcessExecutor`) so a delegated coding task\n * spawns a real harness on a real git worktree instead of provisioning a\n * sibling sandbox.\n *\n * All harness invocations:\n * - run with `cwd` set to the worktree\n * - inherit env from the parent (the MCP server inside the sandbox has\n * the harness's auth already)\n * - capture stdout/stderr\n * - support cancellation via AbortSignal\n * - enforce a wall-clock timeout\n */\n\nimport { type ChildProcess, spawn } from 'node:child_process'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\n\n/** Local coding harness available inside the sandbox. */\nexport type LocalHarness = 'claude' | 'codex' | 'opencode'\n\n/**\n * Default per-harness command + arg shape. `buildArgs` takes ONLY the task prompt and\n * emits the prompt-only invocation (no model, no system prompt) — the historical shape\n * the in-process executor's `streamPrompt` drives. `modelArgs` maps a resolved model to\n * the harness's selector flag (every supported harness takes `-m <model>`). The §1.5\n * profile-aware mapper `harnessInvocation` composes these to thread the full\n * supervisor-authored profile (systemPrompt + model) into argv.\n */\nconst HARNESS_INVOCATIONS: Record<\n LocalHarness,\n {\n command: string\n buildArgs: (taskPrompt: string) => string[]\n /** Map a resolved model to the harness's model-selector flag. */\n modelArgs: (model: string) => string[]\n }\n> = {\n claude: {\n command: 'claude',\n buildArgs: (taskPrompt) => ['--headless', '-p', taskPrompt],\n modelArgs: (model) => ['-m', model],\n },\n codex: {\n command: 'codex',\n buildArgs: (taskPrompt) => ['run', taskPrompt],\n modelArgs: (model) => ['-m', model],\n },\n opencode: {\n command: 'opencode',\n buildArgs: (taskPrompt) => ['run', taskPrompt],\n modelArgs: (model) => ['-m', model],\n },\n}\n\n/** Result of mapping an `AgentProfile` + task prompt onto a harness invocation. */\nexport interface HarnessInvocation {\n command: string\n args: string[]\n}\n\n/**\n * Map a supervisor-authored `AgentProfile` + the per-task prompt onto a concrete harness\n * `command` + `args` (the §1.5 fix). UNLIKE the prompt-only `HARNESS_INVOCATIONS.buildArgs`\n * — which drops both the authored model and the system prompt — this threads the FULL\n * profile payload into argv:\n *\n * - `profile.prompt.systemPrompt` → the PROMPT channel: a portable, harness-agnostic\n * default that prepends the system prompt above the task prompt (`<system>\\n\\n<task>`),\n * so the authored standing instructions reach EVERY harness (none of the three CLIs\n * expose a portable replace-system-prompt flag for a one-shot non-interactive run).\n * - `profile.model.default` → the harness's `-m <model>` selector.\n *\n * The task prompt alone is the floor; an empty/absent profile yields exactly the legacy\n * `buildArgs(taskPrompt)` shape so existing callers are byte-identical.\n */\nexport function harnessInvocation(\n harness: LocalHarness,\n profile: AgentProfile,\n taskPrompt: string,\n): HarnessInvocation {\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n throw new Error(`harnessInvocation: unknown harness ${String(harness)}`)\n }\n\n const systemPrompt = profile.prompt?.systemPrompt\n const composedPrompt =\n typeof systemPrompt === 'string' && systemPrompt.trim().length > 0\n ? `${systemPrompt}\\n\\n${taskPrompt}`\n : taskPrompt\n\n const args = invocation.buildArgs(composedPrompt)\n\n const model = profile.model?.default\n if (typeof model === 'string' && model.length > 0) {\n args.push(...invocation.modelArgs(model))\n }\n\n return { command: invocation.command, args }\n}\n\n/** @experimental */\nexport interface RunLocalHarnessOptions {\n harness: LocalHarness\n /** Working directory for the subprocess (typically a worktree path). */\n cwd: string\n /** Prompt forwarded as the harness CLI's task argument. */\n taskPrompt: string\n /**\n * Pre-built command + args (e.g. from `harnessInvocation` so the full authored\n * `AgentProfile` — systemPrompt + model — reaches the harness). When set it OVERRIDES the\n * default prompt-only `buildArgs(taskPrompt)` path; `command` defaults to the harness's\n * default binary when only `args` is supplied. When absent the legacy prompt-only shape\n * is used unchanged.\n */\n invocation?: { command?: string; args: ReadonlyArray<string> }\n /** Wall-clock kill deadline (ms). Default 5 min. Subprocess SIGTERMed on expiry. */\n timeoutMs?: number\n /** Caller cancellation. SIGTERM is sent on abort. */\n signal?: AbortSignal\n /** Override env (defaults to inheriting from the parent). */\n env?: NodeJS.ProcessEnv\n /**\n * Test seam — inject a custom spawner so unit tests can mock the\n * subprocess without touching the OS. Defaults to node's `child_process.spawn`.\n */\n spawn?: (\n command: string,\n args: ReadonlyArray<string>,\n opts: {\n cwd: string\n env: NodeJS.ProcessEnv\n stdio: 'pipe'\n },\n ) => ChildProcess\n}\n\n/** @experimental */\nexport interface LocalHarnessResult {\n /** OS exit code. `null` when killed before exit. */\n exitCode: number | null\n /** Concatenated stdout. */\n stdout: string\n /** Concatenated stderr. */\n stderr: string\n /** Set when the process exited via signal (timeout / abort). */\n killedBySignal: NodeJS.Signals | null\n /** Wall-clock duration ms (spawn → exit). */\n durationMs: number\n /** Set when timeoutMs elapsed before exit. */\n timedOut: boolean\n}\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000\n\n/**\n * Spawn a local coding harness CLI as a subprocess + collect its output.\n *\n * NOT responsible for parsing the harness's output or extracting a diff —\n * the in-process executor's `streamPrompt` orchestrates `git diff` against\n * the worktree after this resolves. This function is intentionally narrow:\n * spawn, wait, capture, return.\n *\n * Fails loud — throws when:\n * - `cwd` doesn't exist (subprocess emits ENOENT; surfaced as Error)\n * - the harness binary is not on PATH (ENOENT)\n *\n * Does NOT throw when:\n * - the subprocess exits non-zero (`result.exitCode` carries the code)\n * - the subprocess is aborted / timed out (`result.killedBySignal` /\n * `result.timedOut` carries the reason)\n *\n * @experimental\n */\nexport function runLocalHarness(options: RunLocalHarnessOptions): Promise<LocalHarnessResult> {\n const { harness, cwd, taskPrompt } = options\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const env = options.env ?? process.env\n const spawnImpl = options.spawn ?? spawn\n\n const invocation = HARNESS_INVOCATIONS[harness]\n if (!invocation) {\n return Promise.reject(new Error(`runLocalHarness: unknown harness ${String(harness)}`))\n }\n\n const startedAt = Date.now()\n const command = options.invocation?.command ?? invocation.command\n const args = options.invocation ? [...options.invocation.args] : invocation.buildArgs(taskPrompt)\n\n return new Promise<LocalHarnessResult>((resolve, reject) => {\n let child: ChildProcess\n try {\n child = spawnImpl(command, args, { cwd, env, stdio: 'pipe' })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n // The harness takes its task as an argv arg, not on stdin. Leaving stdin\n // OPEN makes a non-TTY `opencode run` (and likely the other harnesses)\n // BLOCK forever waiting on input — zero output, SIGTERM at the wall cap,\n // empty patch -> \"no candidate passed validation\". Close stdin so the\n // subprocess sees EOF and proceeds (the `cliExecutor` leaf does the same).\n child.stdin?.end()\n\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let settled = false\n\n const timer =\n timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n if (!child.killed) child.kill('SIGTERM')\n }, timeoutMs)\n : null\n if (timer && typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n\n const onAbort = () => {\n if (!child.killed) child.kill('SIGTERM')\n }\n if (options.signal) {\n if (options.signal.aborted) onAbort()\n else options.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n child.stdout?.on('data', (chunk) => {\n stdout += String(chunk)\n })\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n\n const finalize = (result: LocalHarnessResult) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n resolve(result)\n }\n\n child.on('error', (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n reject(err)\n })\n\n child.on('close', (code, signal) => {\n finalize({\n exitCode: code,\n stdout,\n stderr,\n killedBySignal: signal,\n durationMs: Date.now() - startedAt,\n timedOut,\n })\n })\n })\n}\n"],"mappings":";AAkBA,SAA4B,aAAa;AAczC,IAAM,sBAQF;AAAA,EACF,QAAQ;AAAA,IACN,SAAS;AAAA,IACT,WAAW,CAAC,eAAe,CAAC,cAAc,MAAM,UAAU;AAAA,IAC1D,WAAW,CAAC,UAAU,CAAC,MAAM,KAAK;AAAA,EACpC;AAAA,EACA,OAAO;AAAA,IACL,SAAS;AAAA,IACT,WAAW,CAAC,eAAe,CAAC,OAAO,UAAU;AAAA,IAC7C,WAAW,CAAC,UAAU,CAAC,MAAM,KAAK;AAAA,EACpC;AAAA,EACA,UAAU;AAAA,IACR,SAAS;AAAA,IACT,WAAW,CAAC,eAAe,CAAC,OAAO,UAAU;AAAA,IAC7C,WAAW,CAAC,UAAU,CAAC,MAAM,KAAK;AAAA,EACpC;AACF;AAuBO,SAAS,kBACd,SACA,SACA,YACmB;AACnB,QAAM,aAAa,oBAAoB,OAAO;AAC9C,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,sCAAsC,OAAO,OAAO,CAAC,EAAE;AAAA,EACzE;AAEA,QAAM,eAAe,QAAQ,QAAQ;AACrC,QAAM,iBACJ,OAAO,iBAAiB,YAAY,aAAa,KAAK,EAAE,SAAS,IAC7D,GAAG,YAAY;AAAA;AAAA,EAAO,UAAU,KAChC;AAEN,QAAM,OAAO,WAAW,UAAU,cAAc;AAEhD,QAAM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MAAgC,MAAM;AAAA,IAC1C;AAEA,UAAM,UAAU,MAAM;AACpB,UAAI,CAAC,MAAM,OAAQ,OAAM,KAAK,SAAS;AAAA,IACzC;AACA,QAAI,QAAQ,QAAQ;AAClB,UAAI,QAAQ,OAAO,QAAS,SAAQ;AAAA,UAC/B,SAAQ,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,IACvE;AAEA,UAAM,QAAQ,GAAG,QAAQ,CAAC,UAAU;AAClC,gBAAU,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,UAAM,QAAQ,GAAG,QAAQ,CAAC,UAAU;AAClC,gBAAU,OAAO,KAAK;AAAA,IACxB,CAAC;AAED,UAAM,WAAW,CAAC,WAA+B;AAC/C,UAAI,QAAS;AACb,gBAAU;AACV,UAAI,MAAO,cAAa,KAAK;AAC7B,cAAQ,QAAQ,oBAAoB,SAAS,OAAO;AACpD,cAAQ,MAAM;AAAA,IAChB;AAEA,UAAM,GAAG,SAAS,CAAC,QAAQ;AACzB,UAAI,QAAS;AACb,gBAAU;AACV,UAAI,MAAO,cAAa,KAAK;AAC7B,cAAQ,QAAQ,oBAAoB,SAAS,OAAO;AACpD,aAAO,GAAG;AAAA,IACZ,CAAC;AAED,UAAM,GAAG,SAAS,CAAC,MAAM,WAAW;AAClC,eAAS;AAAA,QACP,UAAU;AAAA,QACV;AAAA,QACA;AAAA,QACA,gBAAgB;AAAA,QAChB,YAAY,KAAK,IAAI,IAAI;AAAA,QACzB;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n * @experimental\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n let truncated = 0\n const spans = found.map((s) => {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n truncated += n\n return { ...s, attributes: capped }\n })\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n total_matches: hits.length,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const hits = span\n ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget).slice(0, max)\n : []\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n total_matches: hits.length,\n has_more: false,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge adapter → proposals (and\n * optionally apply them) → wiki edits\n * 6. Hand the findings to the improvement adapter → prompt / tool /\n * scaffolding edits (review-only by default)\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Adapters are optional: the loop works as a \"run + diff + report\"\n * primitive when no adapters are wired; it closes end-to-end when\n * both adapters are wired.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before any side-effecting adapter runs so\n // the ledger is the source of truth even if an adapter throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge adapter — proposals + optional auto-apply.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeAdapter) {\n knowledge = await runKnowledgeAdapter(opts, analystResult.findings, log, emit)\n }\n\n // 6. Improvement adapter — prompt / tool / scaffolding edits.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementAdapter) {\n improvement = await runImprovementAdapter(opts, analystResult.findings, log, emit)\n }\n\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs: Date.now() - startedAt,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, { priorFindings })\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeAdapter<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const adapter = opts.knowledgeAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.knowledge ?? false\n const threshold = opts.autoApply?.knowledgeConfidenceThreshold ?? 0.85\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: 0,\n withheldForReview: batch.proposals.length,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.proposals.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TProposal[] = []\n let withheld = 0\n for (const p of batch.proposals as Array<TProposal & { sourceFindingId?: string }>) {\n const src = p.sourceFindingId ? findingsById.get(p.sourceFindingId) : undefined\n if (!src) {\n withheld += 1\n continue\n }\n if (src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(p)\n }\n const result = await adapter.apply(safe)\n log('knowledge.apply', {\n applied: result.written.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: result.written.length,\n withheldForReview: withheld,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: result.written,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nasync function runImprovementAdapter<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const adapter = opts.improvementAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.improvement ?? false\n const threshold = opts.autoApply?.improvementConfidenceThreshold ?? 0.9\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: 0,\n withheldForReview: batch.edits.length,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.edits.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TEdit[] = []\n let withheld = 0\n for (const e of batch.edits as Array<TEdit & { sourceFindingId?: string }>) {\n const src = e.sourceFindingId ? findingsById.get(e.sourceFindingId) : undefined\n if (!src || src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(e)\n }\n const result = await adapter.apply(safe)\n log('improvement.apply', {\n applied: result.applied.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: result.applied.length,\n withheldForReview: withheld,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: result.applied,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string,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