@tangle-network/agent-runtime 0.82.0 → 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-A7LZR5DT.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-DJQFJEOD.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-JYURIKPF.js → chunk-QDVLTRCP.js} +4 -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-CO2KBPRE.js → chunk-SSA6OERV.js} +6 -6
- package/dist/chunk-SSA6OERV.js.map +1 -0
- package/dist/{chunk-SRGV56W4.js → chunk-UD4BHQMI.js} +2 -2
- package/dist/{chunk-SRGV56W4.js.map → chunk-UD4BHQMI.js.map} +1 -1
- package/dist/{chunk-KSGHI53L.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 +102 -45
- package/dist/loops.js +7 -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-5JAUQZQA.js.map +0 -1
- package/dist/chunk-A7LZR5DT.js.map +0 -1
- package/dist/chunk-C2FZ6GR6.js.map +0 -1
- package/dist/chunk-CO2KBPRE.js.map +0 -1
- package/dist/chunk-DJQFJEOD.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-JYURIKPF.js.map +0 -1
- package/dist/chunk-KSGHI53L.js.map +0 -1
- package/dist/chunk-LWGVVP2C.js.map +0 -1
- package/dist/chunk-NBV35BR6.js.map +0 -1
- package/dist/chunk-UZ5SODU7.js.map +0 -1
- package/dist/chunk-WIR4HOOJ.js.map +0 -1
package/README.md
CHANGED
|
@@ -96,5 +96,9 @@ All 28 live in [`examples/`](./examples).
|
|
|
96
96
|
|
|
97
97
|
- New here? [`docs/concepts.md`](./docs/concepts.md) — the mental model in plain terms.
|
|
98
98
|
- [`docs/canonical-api.md`](./docs/canonical-api.md) — find the primitive: "I want to ___ → use ___".
|
|
99
|
+
- [`docs/api/primitive-catalog.md`](./docs/api/primitive-catalog.md) — every export in one generated, never-stale list with its import path. Check it before building anything new.
|
|
100
|
+
- Import subpaths: the root export is the product surface (`handleChatTurn`, `improve`); deeper capabilities ship as subpaths — `/loops` (multi-agent + the loop kernel), `/mcp` (tool servers), `/intelligence` (observability drop-in), `/lifecycle`, `/agent`, `/profiles`, `/platform`, `/analyst-loop`, `/environment-provider`.
|
|
99
101
|
- [`docs/architecture.md`](./docs/architecture.md) — the design, end to end.
|
|
100
102
|
- [`bench/HARNESS.md`](./bench/HARNESS.md) — the experiment harness and how to run a benchmark.
|
|
103
|
+
|
|
104
|
+
**Contributing:** `pnpm i && pnpm test` gets you running; the full local gate is the [`package.json`](./package.json) scripts (`lint`, `typecheck`, `docs:check`).
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import * as _tangle_network_agent_eval from '@tangle-network/agent-eval';
|
|
2
2
|
import { TraceAnalystKindSpec, AnalystFinding } from '@tangle-network/agent-eval';
|
|
3
3
|
import { A as ArtifactKind, C as CandidateGenerator, P as PromotionGate } from './generator-YkAQrOoD.js';
|
|
4
|
-
import { a as RuntimeStreamEvent, S as SandboxClient, b as OutputAdapter, A as AgentRunSpec } from './types-
|
|
5
|
-
import { A as AgentSurfaces } from './improvement-adapter-
|
|
6
|
-
export { C as CreateSurfaceImprovementAdapterOpts, D as DraftPatchInput, a as DraftPatchOutput, R as ResolvedSurface, S as SurfaceImprovementEdit, b as SurfaceValidationIssue, c as createSurfaceImprovementAdapter, r as renderSurfaceIssues, d as resolveSubjectPath, v as validateSurfaces } from './improvement-adapter-
|
|
4
|
+
import { a as RuntimeStreamEvent, S as SandboxClient, b as OutputAdapter, A as AgentRunSpec } from './types-ESeMOj94.js';
|
|
5
|
+
import { A as AgentSurfaces } from './improvement-adapter-CDR8QNVM.js';
|
|
6
|
+
export { C as CreateSurfaceImprovementAdapterOpts, D as DraftPatchInput, a as DraftPatchOutput, R as ResolvedSurface, S as SurfaceImprovementEdit, b as SurfaceValidationIssue, c as createSurfaceImprovementAdapter, r as renderSurfaceIssues, d as resolveSubjectPath, v as validateSurfaces } from './improvement-adapter-CDR8QNVM.js';
|
|
7
7
|
import { K as KnowledgeAdapter, a as RunAnalystLoopResult } from './types-BC3bZpH0.js';
|
|
8
8
|
import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from '@tangle-network/agent-interface';
|
|
9
9
|
import { SandboxEvent } from '@tangle-network/sandbox';
|
|
@@ -262,6 +262,7 @@ interface AutoApplyPolicy {
|
|
|
262
262
|
mode?: 'write' | 'open-pr';
|
|
263
263
|
};
|
|
264
264
|
}
|
|
265
|
+
/** Thrown when `defineAgent` finds a required surface missing on disk. */
|
|
265
266
|
declare class AgentManifestError extends Error {
|
|
266
267
|
readonly agentId: string;
|
|
267
268
|
readonly issues: ReadonlyArray<unknown>;
|
|
@@ -338,6 +339,7 @@ interface KnowledgeAdapterDeps<TProposal> {
|
|
|
338
339
|
*/
|
|
339
340
|
lintAfterApply?: (root: string) => Promise<ReadonlyArray<string>>;
|
|
340
341
|
}
|
|
342
|
+
/** Wire a surface-based `KnowledgeAdapter` that writes analyst proposals to agent surface files. */
|
|
341
343
|
declare function createSurfaceKnowledgeAdapter<TProposal>(opts: CreateSurfaceKnowledgeAdapterOpts, deps: KnowledgeAdapterDeps<TProposal>): KnowledgeAdapter<TProposal>;
|
|
342
344
|
|
|
343
345
|
/**
|
package/dist/agent.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-QDVLTRCP.js";
|
|
2
2
|
import {
|
|
3
3
|
createSandboxForSpec
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
4
|
+
} from "./chunk-SSA6OERV.js";
|
|
5
|
+
import "./chunk-UD4BHQMI.js";
|
|
6
|
+
import "./chunk-BZF3KQ6G.js";
|
|
7
7
|
import {
|
|
8
8
|
mapSandboxEvent
|
|
9
9
|
} from "./chunk-4J6RBI3K.js";
|
|
10
|
-
import "./chunk-
|
|
11
|
-
import "./chunk-
|
|
12
|
-
import "./chunk-
|
|
10
|
+
import "./chunk-7LO5GMAO.js";
|
|
11
|
+
import "./chunk-YEJR7IXO.js";
|
|
12
|
+
import "./chunk-DPEUKJRO.js";
|
|
13
13
|
import {
|
|
14
14
|
__require
|
|
15
15
|
} from "./chunk-DGUM43GV.js";
|
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/surfaces.ts","../src/agent/define-agent.ts","../src/agent/improvement-adapter.ts","../src/agent/knowledge-adapter.ts","../src/agent/outcome.ts","../src/agent/sandbox-act.ts"],"sourcesContent":["/**\n * `AgentSurfaces` — declarative map of the mutable file/directory paths\n * the self-improvement loop can edit on behalf of an agent.\n *\n * The substrate uses this map to resolve every parsed `FindingSubject`\n * (from agent-eval) to a real on-disk path. No per-vertical glue;\n * no fabricated paths; no silent `existsSync(...)` skips that hide\n * misconfiguration from the operator.\n *\n * Surfaces are validated at `defineAgent` time — missing paths fail\n * loud with a list of every offender. A surface that's not needed\n * (e.g. an agent with no RAG corpora) is simply omitted; the loop\n * refuses to route those subjects rather than fabricating a target.\n */\n\nimport { existsSync } from 'node:fs'\nimport { isAbsolute, join } from 'node:path'\nimport type { FindingSubject } from '@tangle-network/agent-eval'\n\n/**\n * Surface declarations. Every path is repo-relative (or absolute) at\n * `defineAgent` time. At resolution time, paths are joined against the\n * agent's `repoRoot`.\n *\n * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends\n * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.\n * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in\n * place.\n *\n * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);\n * `applyKnowledgeWriteBlocks` writes pages relative to it.\n *\n * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)\n * can be omitted — the loop will reject findings targeting them with a\n * clear log message instead of fabricating a path.\n */\nexport interface AgentSurfaces {\n /** Directory containing one markdown file per system-prompt section. */\n systemPrompt: string\n /** Directory containing one subdir per tool (`<tool>/README.md`). */\n tools: string\n /** Single file (TypeScript module) defining the rubric weights + dimensions. */\n rubric: string\n /** Knowledge-base root; typically `.agent-knowledge`. */\n knowledge: string\n /** Directory containing one YAML/JSON file per persona. */\n personas: string\n /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */\n scaffolding?: string\n /** Optional: memory store path (JSONL / SQLite / DB). */\n memory?: string\n /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */\n rag?: string\n /** Optional: single file defining the output schema (Zod / JSON Schema). */\n outputSchema?: string\n}\n\nexport interface ResolvedSurface {\n /** Absolute filesystem path the operator can `cat` / `vim`. */\n absolutePath: string\n /** Repo-relative path for PR descriptions, diffs, audit logs. */\n repoRelativePath: string\n /** Whether the path currently exists on disk. */\n exists: boolean\n /** The substrate's intent: edit an existing file or create a new one. */\n intent: 'edit-existing' | 'create-new'\n}\n\n/**\n * Resolve a parsed `FindingSubject` to the file path the substrate\n * should edit (or create) on disk.\n *\n * Returns `null` when:\n * - the subject targets a surface the agent didn't declare\n * (e.g. `rag:*` when `surfaces.rag` is undefined), OR\n * - the subject is a `cluster` (failure-mode emits these as evidence,\n * not actionable mutations — they don't route to a file).\n *\n * Returns a `ResolvedSurface` with `intent: 'create-new'` when the\n * subject names a path that doesn't yet exist (e.g. a new wiki page).\n * The caller chooses whether to honour the create — for tightly-managed\n * surfaces like `systemPrompt` it's usually a contract violation\n * (the analyst named a section that doesn't exist); for `knowledge`\n * it's the whole point.\n */\nexport function resolveSubjectPath(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ResolvedSurface | null {\n const candidates = candidatePathsForSubject(subject, surfaces)\n if (candidates.length === 0) return null\n\n // Probe candidates in order, preferring the first one that exists on disk.\n // Lets the substrate accept both the flat `<section>.md` convention and\n // the skill-dir `<section>/SKILL.md` convention without forcing one layout.\n // When none exists, fall back to the first candidate (canonical create-new).\n for (const rel of candidates) {\n const abs = isAbsolute(rel) ? rel : join(repoRoot, rel)\n if (existsSync(abs)) {\n return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: 'edit-existing' }\n }\n }\n const fallback = candidates[0]!\n const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback)\n return {\n absolutePath: fallbackAbs,\n repoRelativePath: fallback,\n exists: false,\n intent: 'create-new',\n }\n}\n\nfunction candidatePathsForSubject(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n): ReadonlyArray<string> {\n switch (subject.kind) {\n case 'knowledge.wiki':\n case 'knowledge.stale':\n return [join(surfaces.knowledge, `${subject.slug}.md`)]\n case 'knowledge.claim':\n // Claims land in a per-topic claims directory under the knowledge root.\n return [join(surfaces.knowledge, 'claims', `${slugify(subject.topic)}.md`)]\n case 'knowledge.raw':\n return [join(surfaces.knowledge, 'raw', `${subject.sourceId}.md`)]\n case 'system-prompt': {\n const slug = slugify(subject.section)\n // Prefer flat layout for create-new (canonical); probe skill-dir layout\n // in case the existing repo (tax/legal/gtm/creative) uses\n // `<section>/SKILL.md` already.\n return [\n join(surfaces.systemPrompt, `${slug}.md`),\n join(surfaces.systemPrompt, slug, 'SKILL.md'),\n join(surfaces.systemPrompt, slug, 'index.md'),\n ]\n }\n case 'tool-doc':\n if (subject.aspect) {\n return [join(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`)]\n }\n // tool-doc default: `<tool>/README.md`; also probe `<tool>.md` for flat\n // tool-list repos.\n return [\n join(surfaces.tools, subject.tool, 'README.md'),\n join(surfaces.tools, `${subject.tool}.md`),\n ]\n case 'new-tool':\n return [join(surfaces.tools, subject.name, 'README.md')]\n case 'rag':\n if (!surfaces.rag) return []\n return [join(surfaces.rag, subject.corpus, `${subject.docId}.md`)]\n case 'memory':\n if (!surfaces.memory) return []\n return [join(surfaces.memory, `${slugify(subject.key)}.json`)]\n case 'scaffolding':\n if (!surfaces.scaffolding) return []\n return [join(surfaces.scaffolding, `${slugify(subject.concern)}.md`)]\n case 'output-schema':\n if (!surfaces.outputSchema) return []\n return [surfaces.outputSchema]\n case 'websearch.outdated':\n case 'prior-run-summary':\n // Stale signals don't map to a single file — handled by the knowledge\n // adapter as `agent-knowledge:stale:*` after operator review.\n return []\n case 'cluster':\n // failure-mode cluster labels are evidence, not mutations.\n return []\n }\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\n/**\n * Validate that every declared surface exists on disk under `repoRoot`.\n *\n * Returns an array of `SurfaceValidationIssue` — empty when all required\n * surfaces resolve. `defineAgent` throws with the issues rendered, so\n * a misconfigured manifest fails at startup (not at the first finding\n * the loop produces 20 minutes later).\n */\nexport interface SurfaceValidationIssue {\n surface: keyof AgentSurfaces\n path: string\n reason: 'missing' | 'not-directory' | 'not-file'\n}\n\nexport function validateSurfaces(\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ReadonlyArray<SurfaceValidationIssue> {\n const issues: SurfaceValidationIssue[] = []\n const dirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'systemPrompt',\n 'tools',\n 'personas',\n 'knowledge',\n ]\n const fileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['rubric']\n const optionalDirSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['scaffolding', 'memory', 'rag']\n const optionalFileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['outputSchema']\n\n for (const key of dirSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n }\n }\n for (const key of fileSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n }\n }\n for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {\n const p = surfaces[key] as string | undefined\n if (p === undefined) continue\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n }\n }\n return issues\n}\n\nexport function renderSurfaceIssues(\n issues: ReadonlyArray<SurfaceValidationIssue>,\n repoRoot: string,\n): string {\n if (issues.length === 0) return ''\n const lines = issues.map(\n (i) => ` - ${i.surface}: ${i.path ? `\"${i.path}\"` : '<not set>'} (${i.reason})`,\n )\n return [\n `Agent surface validation failed against repoRoot=${repoRoot}:`,\n ...lines,\n '',\n 'Fix the manifest: every required surface must point at an existing',\n 'directory (systemPrompt / tools / personas / knowledge) or file',\n '(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)',\n 'may be omitted; the loop will reject findings targeting omitted',\n 'surfaces rather than fabricating a path.',\n ].join('\\n')\n}\n","/**\n * `defineAgent` — typed, validated manifest API for declarative agent\n * configuration. The substrate consumes this manifest to wire the\n * canonical eval pattern + analyst self-improvement loop without any\n * per-vertical glue.\n *\n * Design goal: scale to 1000s of vertical agents. Every agent declares\n * its surfaces, rubric, runtime, and analyst configuration in ~50 lines.\n * No per-vertical `ImprovementAdapter`. No per-vertical CLI. No\n * fabricated paths.\n *\n * Validation: `defineAgent` runs `validateSurfaces` synchronously and\n * throws a structured error if any required surface is missing on\n * disk. The cost is one filesystem stat per surface (cheap); the\n * benefit is a manifest that can't ship broken.\n */\n\nimport type { TraceAnalystKindSpec } from '@tangle-network/agent-eval'\nimport type { PromotionGate } from '../lifecycle/gate'\nimport type { CandidateGenerator } from '../lifecycle/generator'\nimport type { ArtifactKind } from '../lifecycle/types'\nimport type { RuntimeStreamEvent } from '../types'\nimport { type AgentSurfaces, renderSurfaceIssues, validateSurfaces } from './surfaces'\n\n// ── manifest ─────────────────────────────────────────────────────────\n\n/**\n * The full agent manifest. Each agent ships ONE of these.\n *\n * Generics:\n * `TPersona` — the agent's persona shape (loaded from\n * `surfaces.personas`). Defaults to `unknown` so the substrate's\n * persona discovery (`loadPersonas`) can accept anything; per-agent\n * code re-narrows when it matters.\n * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric\n * scorers and emitted into the trace.\n */\nexport interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {\n /**\n * Stable identifier — used as `projectId` in traces, as the analyst\n * loop's `runId` prefix, and as the namespace under which findings\n * are persisted. MUST match the agent's repo name to keep\n * cross-repo telemetry joinable.\n */\n id: string\n\n /**\n * Filesystem root the substrate resolves surface paths against.\n * Typically `process.cwd()` or a fixed absolute path. Use an\n * absolute path when the agent's tests may run from subdirectories\n * (vitest sometimes shifts cwd).\n */\n repoRoot: string\n\n /**\n * Map of mutable surfaces the self-improvement loop can edit. See\n * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,\n * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,\n * `outputSchema`.\n *\n * Every required path is validated at `defineAgent` time. Missing\n * paths throw with the full list of offenders.\n */\n surfaces: AgentSurfaces\n\n /**\n * Rubric the substrate uses to score each run. Dimensions × weights\n * × judges. The substrate computes the weighted composite and\n * stamps it into the RunRecord.\n */\n rubric: AgentRubric<TRunOutput>\n\n /**\n * Runtime adapter — how the substrate INVOKES the agent against a\n * persona. The `act` function takes a persona + a context (with the\n * tracer the substrate threads through for span emission) and\n * returns the run output the rubric will score.\n *\n * The agent's existing production runtime goes in here; the\n * substrate is intentionally thin around it.\n */\n runtime: AgentRuntime<TPersona, TRunOutput>\n\n /**\n * Persona discovery — the substrate loads personas via this function\n * at eval start. Can read from `surfaces.personas`, an API, or be\n * hardcoded. The substrate calls it once per `runAgentEval` call;\n * persona ordering is preserved.\n */\n personas: () => Promise<ReadonlyArray<TPersona>>\n\n /**\n * Analyst kinds the substrate runs against each persona's trace.\n * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent\n * authors can prune (e.g. skip `knowledge-poisoning` when there's no\n * knowledge base) or extend (custom domain kinds).\n *\n * Empty array disables the loop — useful for `pnpm eval --no-analyst`.\n */\n analystKinds: ReadonlyArray<TraceAnalystKindSpec>\n\n /**\n * Analyst LLM configuration. The substrate uses these for all four\n * kinds (override per-kind via `analystKinds` if needed).\n */\n analyst: AnalystConfig\n\n /**\n * Auto-apply policy. Knowledge / improvement edits land only when\n * `enabled === true` AND the source finding's confidence meets the\n * threshold. `mode` controls how applies happen: `'write'` mutates\n * files in-place; `'open-pr'` writes to a branch and opens a PR.\n *\n * Default: knowledge auto-applies at confidence ≥0.85 in `'write'`\n * mode (wiki edits are git-reversible); improvement stays at\n * `enabled: false` until the agent author has measured precision.\n */\n autoApply?: AutoApplyPolicy\n\n /**\n * Declarative per-surface artifact-lifecycle config the closed loop reads.\n *\n * Each entry names a profile surface (`skill` / `tool` / `prompt` / `mcp` /\n * `hook` / `subagent`) and supplies the `CandidateGenerator` that grows it +\n * the `PromotionGate` (the held-back exam) that decides promotion. `runLifecycle`\n * consumes these: it pools the generators, measures each candidate's marginal\n * lift on the held-back split, gates it, and stores the winners in an\n * `ArtifactRegistry` — then `composeProfile` folds the top-`k` active artifacts\n * back into this agent's profile.\n *\n * Optional — agents that don't self-improve their profile omit it. An empty or\n * absent map means \"no lifecycle\"; the manifest is otherwise unchanged.\n */\n lifecycles?: ReadonlyArray<SurfaceLifecycle>\n}\n\n/**\n * One profile surface's artifact-lifecycle wiring — the declarative config a\n * `defineAgent` manifest carries and `runLifecycle` reads. It is config, not\n * execution: it names the generator + gate; the loop runs them.\n */\nexport interface SurfaceLifecycle {\n /** The profile surface this lifecycle grows. */\n surface: ArtifactKind\n /** Produces fresh candidate artifacts for `surface` from the agent's history. */\n generator: CandidateGenerator\n /** The held-back exam that decides promotion of a measured candidate. */\n gate: PromotionGate\n /** Top-`k` budget for `composeProfile` when folding this surface's promoted\n * artifacts back in. Omit to fold in every active artifact. */\n composeK?: number\n}\n\nexport interface AgentRubric<TRunOutput> {\n /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */\n dimensions: ReadonlyArray<RubricDimension<TRunOutput>>\n /**\n * Optional judges layered on top of deterministic dimensions. Each\n * judge returns a score per dimension; the substrate averages judges\n * (mean by default) for the LLM contribution.\n */\n judges?: ReadonlyArray<JudgeConfig<TRunOutput>>\n}\n\nexport interface RubricDimension<TRunOutput> {\n /** Unique identifier — appears in finding subjects (`rubric:<id>`). */\n id: string\n /** 0..1 — weight in the composite. */\n weight: number\n /**\n * Deterministic scorer: given the persona + run output, returns a\n * 0..1 score. The substrate sums weight × score across dimensions\n * for the deterministic composite; judges supplement subjective dims.\n */\n score: (input: { persona: unknown; output: TRunOutput }) => number\n /** Optional human-readable label for reports. */\n label?: string\n}\n\nexport interface JudgeConfig<TRunOutput> {\n /** Judge identifier — appears in trace spans + manifest. */\n id: string\n /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */\n model: string\n /** Dimensions this judge scores. */\n dimensions: ReadonlyArray<string>\n /**\n * Optional rubric anchors — text examples the judge sees as a\n * few-shot prompt to calibrate. STRONGLY recommended for subjective\n * dimensions; required by the calibration gate (Pearson ≥0.7).\n */\n anchors?: ReadonlyArray<{ input: string; output: TRunOutput; expected: Record<string, number> }>\n}\n\nexport interface AgentRuntime<TPersona, TRunOutput> {\n /**\n * Invoke the agent against one persona. Returns BOTH:\n * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric\n * product consumes verbatim (SSE / WebSocket / inline render).\n * **Streaming is mandatory — never collapse this to a single Promise.**\n * The agent's existing `runChatTurn` (or equivalent async generator)\n * plugs in here directly.\n * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream\n * drains. The eval substrate awaits this for rubric scoring; chat\n * products usually ignore it (they already rendered incrementally).\n *\n * Implementation contract:\n * 1. `act` MUST return immediately (synchronous construction of the\n * `events` iterator + the `output` promise).\n * 2. Iterating `events` drives the underlying LLM/tool calls — the\n * caller chooses when to consume.\n * 3. `output` resolves only after the iterator yields its terminal\n * event (typically `task_end`); see `collectAgentRun` helper.\n *\n * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes\n * SHOULD record LLM/tool spans through it for capture integrity.\n * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful\n * cancel. `ctx.signal` is the standard abort signal.\n */\n act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>\n}\n\nexport interface AgentRunInvocation<TRunOutput> {\n /** Live stream of typed runtime events. Consumed by chat UX directly. */\n events: AsyncIterable<RuntimeStreamEvent>\n /** Final structured output the rubric scores. Resolves after `events` drains. */\n output: Promise<TRunOutput>\n}\n\n/**\n * Stub for agents whose `runtime.act` is not yet wired to the substrate's\n * eval path. Preserves the streaming contract (empty event stream + a\n * rejected `output` promise that tells the caller exactly what to fix).\n *\n * Per-vertical manifests usually start with this stub and replace it with\n * the agent's real streaming runtime (`runChatTurn` or equivalent) once\n * the eval path consumes the manifest end-to-end.\n */\nexport function unimplementedAgentRun<TRunOutput = unknown>(\n reason = 'AgentRuntime.act is not yet wired for this manifest',\n): AgentRunInvocation<TRunOutput> {\n return {\n events: (async function* empty(): AsyncIterable<RuntimeStreamEvent> {})(),\n output: Promise.reject(new Error(reason)),\n }\n}\n\n/**\n * Drain `act`'s `events` into an array AND await its `output`. Useful for\n * eval / outcome-measurement code paths that don't care about live\n * rendering. The events array is preserved so the substrate can inspect\n * tool calls / readiness / questions retrospectively.\n *\n * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming\n * (no incremental render). Use `for await (const ev of invocation.events)`\n * directly in the chat surface.\n */\nexport async function collectAgentRun<TRunOutput>(\n invocation: AgentRunInvocation<TRunOutput>,\n): Promise<{ events: ReadonlyArray<RuntimeStreamEvent>; output: TRunOutput }> {\n const events: RuntimeStreamEvent[] = []\n for await (const ev of invocation.events) events.push(ev)\n const output = await invocation.output\n return { events, output }\n}\n\nexport interface AgentRunContext {\n /** Substrate-managed trace emitter. */\n emitter: import('@tangle-network/agent-eval').TraceEmitter\n /** Stable run id for this persona × variant cell. */\n runId: string\n /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */\n variantId?: string\n /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */\n deadlineMs?: number\n /** Optional abort signal. */\n signal?: AbortSignal\n}\n\nexport interface AnalystConfig {\n /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */\n model: string\n /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */\n budgetUsd?: number\n /** Backend hint for the AxAIService factory — same shape every kind uses. */\n backend?: {\n name?: 'openai' | 'router'\n apiKey?: string\n baseUrl?: string\n }\n}\n\nexport interface AutoApplyPolicy {\n knowledge?: {\n enabled: boolean\n confidenceThreshold?: number\n mode?: 'write' | 'open-pr'\n }\n improvement?: {\n enabled: boolean\n confidenceThreshold?: number\n mode?: 'write' | 'open-pr'\n }\n}\n\n// ── factory + validation ─────────────────────────────────────────────\n\nexport class AgentManifestError extends Error {\n constructor(\n message: string,\n public readonly agentId: string,\n public readonly issues: ReadonlyArray<unknown> = [],\n ) {\n super(message)\n this.name = 'AgentManifestError'\n }\n}\n\n/**\n * Construct a validated agent manifest. Throws `AgentManifestError`\n * if any required surface is missing on disk.\n *\n * Generics: pass your persona / output types if you want narrowed\n * `runtime.act` signatures:\n * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`\n *\n * Most callers don't need the generics — the substrate operates on\n * `unknown` payloads internally and the manifest's `score` /\n * `runtime.act` see the typed shapes via TypeScript inference at\n * the call site.\n */\nexport function defineAgent<TPersona = unknown, TRunOutput = unknown>(\n manifest: AgentManifest<TPersona, TRunOutput>,\n): AgentManifest<TPersona, TRunOutput> {\n if (!manifest.id || manifest.id.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `id` is required', manifest.id ?? '')\n }\n if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `repoRoot` is required', manifest.id)\n }\n const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot)\n if (issues.length > 0) {\n throw new AgentManifestError(\n renderSurfaceIssues(issues, manifest.repoRoot),\n manifest.id,\n issues,\n )\n }\n // Lightweight rubric sanity: weights sum to ~1.0 (no hard requirement —\n // the substrate normalizes — but flag wildly miscalibrated weights).\n const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0)\n if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {\n throw new AgentManifestError(\n `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} — should be ~1.0`,\n manifest.id,\n )\n }\n return manifest\n}\n","/**\n * Substrate-default `ImprovementAdapter` — surfaces-driven, LLM-drafted\n * patches, optional auto-apply or PR-open.\n *\n * This is the one ImprovementAdapter every vertical agent uses. The\n * substrate parses each finding's `subject` via\n * `parseFindingSubject` (agent-eval), resolves it to a real file path\n * via the agent's `AgentSurfaces`, reads the current content, and asks\n * an LLM to draft a unified-diff patch given the finding + current\n * content + per-kind editing-discipline rules.\n *\n * Auto-apply gates on the source-finding's confidence and the\n * autoApply.improvement policy. Two modes:\n * `write` — apply the patch in-place via `git apply -p0`. Operator\n * reviews via `git diff`.\n * `open-pr` — write to a branch, commit, push, open a PR via `gh`.\n * Operator reviews via the PR UI.\n *\n * Fail-loud rules:\n * - Findings whose subject doesn't parse → counted in `errors`.\n * - Findings whose subject targets an undeclared surface → counted in\n * `errors` with the offending kind in the message.\n * - Findings whose target path doesn't exist AND the kind isn't a\n * create-new variant (`new-tool`, `knowledge.wiki`) → counted in\n * `errors` with the resolved path in the message.\n * - LLM drafts that fail JSON-schema validation → counted in\n * `errors` with the schema issue.\n *\n * No silent skips. Every dropped finding has a recorded reason the\n * loop's report surfaces.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { readFileSync } from 'node:fs'\nimport type { AnalystFinding, FindingSubject } from '@tangle-network/agent-eval'\nimport { parseFindingSubject } from '@tangle-network/agent-eval/analyst'\nimport type { ImprovementAdapter } from '../analyst-loop/types'\nimport type { AgentSurfaces, ResolvedSurface } from './surfaces'\nimport { resolveSubjectPath } from './surfaces'\n\n// ── proposal shape ───────────────────────────────────────────────────\n\nexport interface SurfaceImprovementEdit {\n /** Stable id derived from the source finding so re-proposals are idempotent. */\n id: string\n /** The finding that produced this edit — for revert + audit trail. */\n sourceFindingId: string\n /** Parsed subject; included so the apply step doesn't re-parse. */\n subject: FindingSubject\n /** Resolved on-disk target. */\n target: ResolvedSurface\n /** SHA-256 of the current file content the patch was drafted against. */\n baseSha256: string\n /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */\n patch: string\n /** One-line summary the operator sees in the report / PR title. */\n summary: string\n /** Multi-line rationale for the PR body — finding context + LLM reasoning. */\n rationale: string\n /** Carry-forward from the finding so the apply gate can check the threshold. */\n confidence: number\n /** Carry-forward severity for prioritization. */\n severity: AnalystFinding['severity']\n}\n\nexport interface CreateSurfaceImprovementAdapterOpts {\n surfaces: AgentSurfaces\n repoRoot: string\n /**\n * LLM-draft callback. Given a finding + current file content + the\n * resolved target, returns a unified-diff patch + summary + rationale.\n *\n * Required — the substrate doesn't ship a hardcoded prompt; the agent\n * author picks the model (Haiku for cheap routine drafts, Sonnet for\n * substantive prompt rewrites, etc.) via this callback.\n */\n draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>\n /**\n * Apply mode:\n * `write` — `git apply` in-place; operator reviews via `git diff`\n * `open-pr` — branch + commit + push + `gh pr create`\n * `none` — never apply; collect proposals for the report only\n *\n * The `apply` method honours this even when the loop calls it; the\n * effective behaviour is also gated on the per-finding confidence\n * threshold via `runAnalystLoop`'s `autoApply` policy.\n */\n mode?: 'write' | 'open-pr' | 'none'\n /** When `mode === 'open-pr'`, the base branch new PRs target. Default: `main`. */\n baseBranch?: string\n /** Required for `mode === 'open-pr'` — the GH owner/repo (`tangle-network/tax-agent`). */\n ghRepo?: string\n /**\n * When the resolved target doesn't exist, allow the substrate to\n * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default\n * true for those kinds, false for `system-prompt` / `rubric` / etc.\n * (named sections that don't exist are a contract violation, not a\n * scaffolding opportunity).\n */\n allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>\n}\n\nexport interface DraftPatchInput {\n finding: AnalystFinding\n subject: FindingSubject\n target: ResolvedSurface\n /** Current file content (empty string when `intent === 'create-new'`). */\n currentContent: string\n}\n\nexport interface DraftPatchOutput {\n /** Unified diff against the current file content. Empty string skips this finding. */\n patch: string\n /** One-line summary for the operator. */\n summary: string\n /** Multi-line rationale for the PR body. */\n rationale: string\n}\n\n// ── factory ──────────────────────────────────────────────────────────\n\nconst DEFAULT_CREATE_KINDS: ReadonlyArray<FindingSubject['kind']> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'new-tool',\n]\n\nexport function createSurfaceImprovementAdapter(\n opts: CreateSurfaceImprovementAdapterOpts,\n): ImprovementAdapter<SurfaceImprovementEdit> {\n const mode = opts.mode ?? 'none'\n const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS\n\n return {\n async proposeFromFindings(findings) {\n const edits: SurfaceImprovementEdit[] = []\n const errors: Array<{ findingId: string; subject: string; message: string }> = []\n let skipped = 0\n\n for (const f of findings) {\n const subject = parseFindingSubject(f.subject)\n if (subject === null) {\n if (f.subject !== undefined) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject,\n message: 'subject does not parse against the finding-subject grammar',\n })\n } else {\n // Subject-less findings are descriptive, not actionable —\n // legitimate; count in `skipped` not `errors`.\n skipped += 1\n }\n continue\n }\n\n // `cluster` findings (failure-mode) are evidence, not mutations.\n if (subject.kind === 'cluster') {\n skipped += 1\n continue\n }\n\n // `agent-knowledge:*` findings flow to the KnowledgeAdapter;\n // the ImprovementAdapter skips them so subjects don't double-route.\n if (subject.kind.startsWith('knowledge.')) {\n skipped += 1\n continue\n }\n\n const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot)\n if (target === null) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `subject kind \"${subject.kind}\" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`,\n })\n continue\n }\n\n if (target.intent === 'create-new' && !allowCreate.includes(subject.kind)) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `target ${target.repoRelativePath} does not exist; the kind \"${subject.kind}\" requires an existing target (analyst named a section that isn't in the codebase)`,\n })\n continue\n }\n\n const currentContent = target.exists ? readFileSync(target.absolutePath, 'utf-8') : ''\n\n let draft: DraftPatchOutput\n try {\n draft = await opts.draftPatch({ finding: f, subject, target, currentContent })\n } catch (err) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`,\n })\n continue\n }\n\n if (draft.patch.trim().length === 0) {\n skipped += 1\n continue\n }\n\n edits.push({\n id: `imp-${f.finding_id}`,\n sourceFindingId: f.finding_id,\n subject,\n target,\n baseSha256: sha256(currentContent),\n patch: draft.patch,\n summary: draft.summary,\n rationale: draft.rationale,\n confidence: f.confidence,\n severity: f.severity,\n })\n }\n\n return { edits, skipped, errors }\n },\n\n async apply(edits) {\n const applied: string[] = []\n const warnings: string[] = []\n\n if (mode === 'none') {\n warnings.push(\n 'createSurfaceImprovementAdapter: mode=none; no edits applied — adjust manifest.autoApply.improvement.mode',\n )\n return { applied, warnings }\n }\n\n if (mode === 'open-pr' && !opts.ghRepo) {\n warnings.push(\n 'createSurfaceImprovementAdapter: mode=open-pr requires `ghRepo`; falling back to no-op',\n )\n return { applied, warnings }\n }\n\n for (const edit of edits) {\n // Race-detection: confirm the file content hasn't moved since the\n // patch was drafted. A diff applied against drifted content is a\n // recipe for silent corruption.\n const current = edit.target.exists ? readFileSync(edit.target.absolutePath, 'utf-8') : ''\n if (sha256(current) !== edit.baseSha256) {\n warnings.push(\n `${edit.target.repoRelativePath}: base SHA mismatch; file changed after draft. Skipping.`,\n )\n continue\n }\n\n const ok = applyPatchInPlace(edit, opts.repoRoot)\n if (!ok) {\n warnings.push(`${edit.target.repoRelativePath}: git apply failed`)\n continue\n }\n applied.push(edit.target.repoRelativePath)\n }\n\n if (mode === 'open-pr' && applied.length > 0 && opts.ghRepo) {\n const prUrl = openPullRequest(\n applied,\n edits.filter((e) => applied.includes(e.target.repoRelativePath)),\n opts.repoRoot,\n opts.ghRepo,\n opts.baseBranch ?? 'main',\n )\n if (prUrl) warnings.push(`opened PR: ${prUrl}`)\n else warnings.push('PR creation failed; edits are committed to a local branch only')\n }\n\n return { applied, warnings }\n },\n }\n}\n\n// ── apply helpers ────────────────────────────────────────────────────\n\nfunction applyPatchInPlace(edit: SurfaceImprovementEdit, repoRoot: string): boolean {\n const result = spawnSync('git', ['apply', '--whitespace=fix', '-p0', '-'], {\n cwd: repoRoot,\n input: edit.patch,\n encoding: 'utf-8',\n })\n return result.status === 0\n}\n\nfunction openPullRequest(\n paths: ReadonlyArray<string>,\n edits: ReadonlyArray<SurfaceImprovementEdit>,\n repoRoot: string,\n ghRepo: string,\n baseBranch: string,\n): string | null {\n const branch = `analyst-loop/${Date.now()}-${edits[0]?.sourceFindingId.slice(0, 12) ?? 'edits'}`\n // Create branch, stage, commit\n const checkout = spawnSync('git', ['checkout', '-b', branch], { cwd: repoRoot })\n if (checkout.status !== 0) return null\n const add = spawnSync('git', ['add', ...paths], { cwd: repoRoot })\n if (add.status !== 0) return null\n const title = `analyst-loop: ${edits[0]?.summary ?? `${edits.length} improvement edits`}`\n const body = [\n `Automated analyst-loop edits — review carefully before merge.`,\n '',\n `Source findings:`,\n ...edits.map(\n (e) =>\n ` - ${e.sourceFindingId} (confidence ${e.confidence.toFixed(2)}, severity ${e.severity})`,\n ),\n '',\n 'Rationales:',\n ...edits.map((e) => `\\n## ${e.target.repoRelativePath}\\n\\n${e.rationale}`),\n ].join('\\n')\n const commit = spawnSync('git', ['commit', '-m', title, '-m', body], { cwd: repoRoot })\n if (commit.status !== 0) return null\n const push = spawnSync('git', ['push', '-u', 'origin', branch], { cwd: repoRoot })\n if (push.status !== 0) return null\n const pr = spawnSync(\n 'gh',\n [\n 'pr',\n 'create',\n '--repo',\n ghRepo,\n '--title',\n title,\n '--body',\n body,\n '--base',\n baseBranch,\n '--head',\n branch,\n ],\n { cwd: repoRoot, encoding: 'utf-8' },\n )\n if (pr.status !== 0) return null\n return pr.stdout.trim()\n}\n\nfunction sha256(s: string): string {\n // node:crypto is dynamic-imported lazily so the adapter can be tested in\n // environments without crypto (browser tests, mocked envs).\n const crypto = require('node:crypto') as typeof import('node:crypto')\n return crypto.createHash('sha256').update(s, 'utf-8').digest('hex')\n}\n","/**\n * Substrate-default `KnowledgeAdapter` — wraps agent-knowledge's\n * `proposeFromFindings` + `applyKnowledgeWriteBlocks` with substrate\n * defaults (auto-lint after apply, source linkage via finding id).\n *\n * Every agent that ships a `.agent-knowledge/` tree uses this adapter\n * unmodified. Per-agent customization happens at the manifest level\n * (`autoApply.knowledge.confidenceThreshold`, etc.), not by writing a\n * new adapter.\n *\n * Lint discipline: after each apply we run agent-knowledge's\n * `lintKnowledgeIndex` to catch broken links / circular claims /\n * duplicate pages introduced by the new writes. Findings that fail the\n * post-apply lint are recorded in `warnings`; the apply itself is not\n * rolled back (lint failures are soft — humans review the wiki state).\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport type { KnowledgeAdapter } from '../analyst-loop/types'\n\nexport interface CreateSurfaceKnowledgeAdapterOpts {\n /** `.agent-knowledge/` root (absolute path the substrate writes blocks against). */\n knowledgeRoot: string\n}\n\n/**\n * Build the adapter. We accept the agent-knowledge functions as DI so\n * the substrate stays decoupled from a specific agent-knowledge\n * version — the agent author imports them in their manifest module\n * and hands them to the factory.\n *\n * `proposeFromFindings(findings)` returns\n * `{ proposals: KnowledgeProposal[]; skipped: number; errors: ... }`.\n *\n * `applyKnowledgeWriteBlocks(root, content)` returns\n * `{ written: string[]; warnings: string[] }`.\n *\n * `lintKnowledgeIndex(index)` (optional) returns `KnowledgeLintFinding[]`.\n */\nexport interface KnowledgeAdapterDeps<TProposal> {\n proposeFromFindings: (findings: ReadonlyArray<AnalystFinding>) => {\n proposals: TProposal[]\n skipped: number\n errors: Array<{ findingId: string; subject: string; message: string }>\n }\n applyKnowledgeWriteBlocks: (\n root: string,\n proposalText: string,\n ) => Promise<{ written: string[]; warnings: string[] }>\n /**\n * Optional post-apply lint hook. The substrate runs it after each\n * batch of writes; failures land in `warnings` (the apply is not\n * rolled back — lint signals drift to review, not block).\n */\n lintAfterApply?: (root: string) => Promise<ReadonlyArray<string>>\n}\n\nexport function createSurfaceKnowledgeAdapter<TProposal>(\n opts: CreateSurfaceKnowledgeAdapterOpts,\n deps: KnowledgeAdapterDeps<TProposal>,\n): KnowledgeAdapter<TProposal> {\n return {\n proposeFromFindings(findings) {\n const batch = deps.proposeFromFindings(findings)\n return {\n proposals: batch.proposals,\n skipped: batch.skipped,\n errors: batch.errors,\n }\n },\n async apply(proposals) {\n const written: string[] = []\n const warnings: string[] = []\n for (const p of proposals) {\n const proposalText = renderProposalAsWriteBlock(p)\n if (proposalText === null) {\n warnings.push(\n `proposal has no writeBlocks/content; skipping (sourceFindingId=${getSourceFindingId(p)})`,\n )\n continue\n }\n try {\n const r = await deps.applyKnowledgeWriteBlocks(opts.knowledgeRoot, proposalText)\n written.push(...r.written)\n warnings.push(...r.warnings)\n } catch (err) {\n warnings.push(\n `applyKnowledgeWriteBlocks failed: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n if (deps.lintAfterApply && written.length > 0) {\n try {\n const lintIssues = await deps.lintAfterApply(opts.knowledgeRoot)\n for (const issue of lintIssues) warnings.push(`lint: ${issue}`)\n } catch (err) {\n warnings.push(\n `lintAfterApply failed: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n return { written, warnings }\n },\n }\n}\n\n/**\n * Pluck the canonical write-block text from a proposal regardless of\n * which exact agent-knowledge version produced it. We accept either:\n * - `{ writeBlocks: Array<{ path, content }> }` — the typed shape\n * 1.3.0+ emits\n * - `{ proposalText: string }` — legacy single-block shape\n * - `{ content: string }` — minimal raw form\n *\n * Returns `null` when nothing parseable is present (warned upstream).\n */\nfunction renderProposalAsWriteBlock(p: unknown): string | null {\n if (!p || typeof p !== 'object') return null\n const obj = p as Record<string, unknown>\n if (Array.isArray(obj.writeBlocks)) {\n const blocks = obj.writeBlocks as Array<{ path?: string; content?: string }>\n if (blocks.length === 0) return null\n return blocks\n .map((b) => (typeof b.content === 'string' ? b.content : ''))\n .filter((s) => s.length > 0)\n .join('\\n\\n')\n }\n if (typeof obj.proposalText === 'string') return obj.proposalText\n if (typeof obj.content === 'string') return obj.content\n return null\n}\n\nfunction getSourceFindingId(p: unknown): string {\n if (!p || typeof p !== 'object') return '<unknown>'\n const obj = p as Record<string, unknown>\n if (typeof obj.sourceFindingId === 'string') return obj.sourceFindingId\n if (typeof obj.id === 'string') return obj.id\n return '<unknown>'\n}\n","/**\n * `OutcomeMeasurement` — the missing metric that turns the analyst\n * loop from \"observability\" into \"self-improvement\".\n *\n * Without this hook, the loop reports process counts (`findings: 42`,\n * `applied: 7`) and never proves the applied edits actually improved\n * anything. With this hook, the substrate re-runs the cohort against\n * the same personas after each apply pass and reports a composite\n * score delta. A negative delta is the substrate's strongest signal\n * to either roll back or surface for review.\n *\n * Wiring is intentionally simple: pass the manifest + the `runAgentEval`\n * function and a list of `personaIds` to re-run. The wrapper:\n * 1. Captures the baseline composite from the just-finished run.\n * 2. After `runAnalystLoop` returns, re-invokes `runAgentEval` against\n * the same persona slice.\n * 3. Computes the delta and appends to `loop-report.json`.\n * 4. If `rollbackOnRegression` and delta < 0, reverts applied edits.\n */\n\nimport type { RunAnalystLoopResult } from '../analyst-loop/types'\n\nexport interface OutcomeMeasurement {\n /** Baseline composite before applies — captured from the most-recent eval run. */\n baselineComposite: number\n /** Composite after re-running the cohort with applied edits. */\n afterComposite: number\n /** `afterComposite - baselineComposite`. Positive = the loop improved the agent. */\n delta: number\n /** Per-persona deltas for finer-grained review. */\n perPersona: ReadonlyArray<{ personaId: string; before: number; after: number; delta: number }>\n /** When the substrate rolled back applies due to regression, the paths reverted. */\n rolledBackPaths: ReadonlyArray<string>\n}\n\nexport interface OutcomeMeasurementOpts {\n /** Composite scores from the run that produced the findings. */\n baseline: ReadonlyArray<{ personaId: string; composite: number }>\n /**\n * Re-run callback — the substrate invokes this after applies. The\n * agent author provides their `runAgentEval`-equivalent so the\n * substrate can ask \"score this persona slice now.\"\n *\n * The callback SHOULD reuse the same cohort + judges + variant as\n * the baseline run; only the agent's mutable surfaces have changed.\n */\n reRunCohort: (\n personaIds: ReadonlyArray<string>,\n ) => Promise<ReadonlyArray<{ personaId: string; composite: number }>>\n /** When `true`, applied edits are reverted on negative delta. Default `false`. */\n rollbackOnRegression?: boolean\n /** Callback to revert a list of paths (typically `git checkout HEAD --`). */\n revert?: (paths: ReadonlyArray<string>) => Promise<void>\n}\n\n/**\n * Run `runAnalystLoop` and stamp an `OutcomeMeasurement` onto the\n * result. The substrate calls this after each canonical eval; the\n * delta lands in `loop-report.json` for cross-run trend analysis.\n *\n * The function returns the original `RunAnalystLoopResult` enriched\n * with `outcome` so callers stay backwards-compatible (the field is\n * optional on the type; missing means no measurement was wired).\n */\nexport async function measureOutcome<TProposal, TEdit>(\n result: RunAnalystLoopResult<TProposal, TEdit>,\n opts: OutcomeMeasurementOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit> & { outcome: OutcomeMeasurement }> {\n const applied = result.knowledge?.applied ?? []\n const improvementsApplied = result.improvement?.applied ?? []\n const allApplied = [...applied, ...improvementsApplied]\n\n // No applies → no outcome to measure. Return a zero-delta to keep the\n // shape stable for consumers; baseline / after equal.\n if (allApplied.length === 0) {\n return {\n ...result,\n outcome: {\n baselineComposite: meanComposite(opts.baseline),\n afterComposite: meanComposite(opts.baseline),\n delta: 0,\n perPersona: opts.baseline.map((b) => ({\n personaId: b.personaId,\n before: b.composite,\n after: b.composite,\n delta: 0,\n })),\n rolledBackPaths: [],\n },\n }\n }\n\n const personaIds = opts.baseline.map((b) => b.personaId)\n const after = await opts.reRunCohort(personaIds)\n const afterByPersona = new Map(after.map((r) => [r.personaId, r.composite]))\n\n const perPersona = opts.baseline.map((b) => {\n const a = afterByPersona.get(b.personaId) ?? b.composite\n return { personaId: b.personaId, before: b.composite, after: a, delta: a - b.composite }\n })\n const baselineComposite = meanComposite(opts.baseline)\n const afterComposite = meanComposite(after)\n const delta = afterComposite - baselineComposite\n\n let rolledBackPaths: string[] = []\n if (delta < 0 && opts.rollbackOnRegression && opts.revert) {\n await opts.revert(allApplied)\n rolledBackPaths = [...allApplied]\n }\n\n return {\n ...result,\n outcome: {\n baselineComposite,\n afterComposite,\n delta,\n perPersona,\n rolledBackPaths,\n },\n }\n}\n\nfunction meanComposite(rows: ReadonlyArray<{ composite: number }>): number {\n if (rows.length === 0) return 0\n return rows.reduce((acc, r) => acc + r.composite, 0) / rows.length\n}\n","/**\n * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.\n *\n * The point of this adapter is parity: the eval substrate must run the agent\n * through the SAME profile the production chat turn uses, or scorecard numbers\n * grade a profile that never ships. `createSandboxAct` boots a sandbox with the\n * agent's profile (the caller's `baseProfile`, with optional per-persona\n * overrides) through the loop kernel's own {@link createSandboxForSpec},\n * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`\n * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring\n * — satisfying the `act` streaming contract with one code path shared by chat\n * and eval.\n *\n * Agents with a bespoke streaming chat turn should wire THAT into `act`\n * directly (the contract is designed for it); this adapter is the default for\n * agents whose turn is a plain prod-profile sandbox dispatch — notably the\n * agents agent-builder generates.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n} from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { AgentRunSpec, OutputAdapter, SandboxClient } from '../runtime'\nimport { mapSandboxEvent } from '../runtime'\nimport { createSandboxForSpec } from '../runtime/run-loop'\nimport type { RuntimeStreamEvent } from '../types'\nimport type { AgentRunContext, AgentRunInvocation } from './define-agent'\n\n/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the\n * per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */\nexport interface SandboxActComposeOverrides {\n /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */\n systemPrompt?: string\n /** Extra file mounts layered after the base profile's `resources.files`. */\n extraFiles?: AgentProfileFileMount[]\n /** Override the profile `name`. Defaults to the base profile's name. */\n name?: string\n /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */\n tools?: Record<string, boolean>\n /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */\n mcpConnections?: Record<string, AgentProfileMcpServer>\n}\n\nexport interface CreateSandboxActOptions<TPersona, TRunOutput> {\n /** Canonical agent profile — the same one the prod chat turn uses. */\n baseProfile: AgentProfile\n /** Sandbox client used to boot the per-run sandbox. */\n sandboxClient: SandboxClient\n /** Persona → prompt. Pure; the eval cell's input. */\n buildPrompt: (persona: TPersona) => string\n /** Sandbox event stream → typed output the rubric scores. */\n output: OutputAdapter<TRunOutput>\n /**\n * Per-persona profile overrides (workspace-augmented system prompt, extra\n * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.\n */\n compose?: (persona: TPersona) => SandboxActComposeOverrides\n /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */\n sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides']\n /** Stable run name surfaced in mapped `llm_call` events. */\n name?: string\n /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */\n mapEvent?: (\n event: SandboxEvent,\n opts: { agentRunName?: string },\n ) => RuntimeStreamEvent | undefined\n}\n\n/**\n * Build an `AgentRuntime.act` implementation backed by a single prod-profile\n * sandbox run. The returned function honours the `act` contract: it returns\n * synchronously with a live `events` iterator and an `output` promise that\n * resolves only after the iterator drains.\n */\nexport function createSandboxAct<TPersona, TRunOutput>(\n options: CreateSandboxActOptions<TPersona, TRunOutput>,\n): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput> {\n const mapEvent = options.mapEvent ?? mapSandboxEvent\n\n return (persona: TPersona, ctx: AgentRunContext): AgentRunInvocation<TRunOutput> => {\n const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona))\n const agentRunName = options.name ?? profile.name ?? 'agent'\n const message = options.buildPrompt(persona)\n const signal = ctx.signal ?? new AbortController().signal\n\n const raw: SandboxEvent[] = []\n let settle!: (value: TRunOutput) => void\n let fail!: (err: unknown) => void\n const output = new Promise<TRunOutput>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n // The output promise rejects when the stream errors; if the caller ignores\n // `output` (chat UX) the rejection is still observed by the events iterator\n // throwing. Attach a no-op catch so an ignored rejection is never \"unhandled\".\n output.catch(() => {})\n\n const spec: AgentRunSpec<unknown> = {\n profile,\n taskToPrompt: () => message,\n name: agentRunName,\n ...(options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}),\n }\n\n async function* events(): AsyncIterable<RuntimeStreamEvent> {\n try {\n const box = await createSandboxForSpec(options.sandboxClient, spec, signal)\n for await (const event of box.streamPrompt(message, { signal })) {\n raw.push(event)\n const mapped = mapEvent(event, { agentRunName })\n if (mapped) yield mapped\n }\n settle(options.output.parse(raw))\n } catch (err) {\n fail(err)\n throw err\n }\n }\n\n return { events: events(), output }\n }\n}\n\n/** Overlay the per-persona overrides onto the base profile. Each slot merges over the base; an\n * absent override leaves the base profile untouched. */\nfunction applyComposeOverrides(\n base: AgentProfile,\n overrides: SandboxActComposeOverrides | undefined,\n): AgentProfile {\n if (!overrides) return base\n const prompt = overrides.systemPrompt\n ? { ...base.prompt, systemPrompt: overrides.systemPrompt }\n : base.prompt\n const mergedTools = overrides.tools ? { ...(base.tools ?? {}), ...overrides.tools } : base.tools\n const mergedMcp = overrides.mcpConnections\n ? { ...(base.mcp ?? {}), ...overrides.mcpConnections }\n : base.mcp\n const baseFiles = base.resources?.files ?? []\n const mergedFiles: AgentProfileFileMount[] = overrides.extraFiles?.length\n ? [...baseFiles, ...overrides.extraFiles]\n : [...baseFiles]\n return {\n ...base,\n name: overrides.name ?? base.name,\n prompt,\n ...(mergedTools ? { tools: mergedTools } : {}),\n ...(mergedMcp ? { mcp: mergedMcp } : {}),\n resources: { ...base.resources, files: mergedFiles },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,YAAY;AAqE1B,SAAS,mBACd,SACA,UACA,UACwB;AACxB,QAAM,aAAa,yBAAyB,SAAS,QAAQ;AAC7D,MAAI,WAAW,WAAW,EAAG,QAAO;AAMpC,aAAW,OAAO,YAAY;AAC5B,UAAM,MAAM,WAAW,GAAG,IAAI,MAAM,KAAK,UAAU,GAAG;AACtD,QAAI,WAAW,GAAG,GAAG;AACnB,aAAO,EAAE,cAAc,KAAK,kBAAkB,KAAK,QAAQ,MAAM,QAAQ,gBAAgB;AAAA,IAC3F;AAAA,EACF;AACA,QAAM,WAAW,WAAW,CAAC;AAC7B,QAAM,cAAc,WAAW,QAAQ,IAAI,WAAW,KAAK,UAAU,QAAQ;AAC7E,SAAO;AAAA,IACL,cAAc;AAAA,IACd,kBAAkB;AAAA,IAClB,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AACF;AAEA,SAAS,yBACP,SACA,UACuB;AACvB,UAAQ,QAAQ,MAAM;AAAA,IACpB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,CAAC,KAAK,SAAS,WAAW,GAAG,QAAQ,IAAI,KAAK,CAAC;AAAA,IACxD,KAAK;AAEH,aAAO,CAAC,KAAK,SAAS,WAAW,UAAU,GAAG,QAAQ,QAAQ,KAAK,CAAC,KAAK,CAAC;AAAA,IAC5E,KAAK;AACH,aAAO,CAAC,KAAK,SAAS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AU,eACrB,EAAE,GAAG,KAAK,QAAQ,cAAc,UAAU,aAAa,IACvD,KAAK;AACT,QAAM,cAAc,UAAU,QAAQ,EAAE,GAAI,KAAK,SAAS,CAAC,GAAI,GAAG,UAAU,MAAM,IAAI,KAAK;AAC3F,QAAM,YAAY,UAAU,iBACxB,EAAE,GAAI,KAAK,OAAO,CAAC,GAAI,GAAG,UAAU,eAAe,IACnD,KAAK;AACT,QAAM,YAAY,KAAK,WAAW,SAAS,CAAC;AAC5C,QAAM,cAAuC,UAAU,YAAY,SAC/D,CAAC,GAAG,WAAW,GAAG,UAAU,UAAU,IACtC,CAAC,GAAG,SAAS;AACjB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,UAAU,QAAQ,KAAK;AAAA,IAC7B;AAAA,IACA,GAAI,cAAc,EAAE,OAAO,YAAY,IAAI,CAAC;AAAA,IAC5C,GAAI,YAAY,EAAE,KAAK,UAAU,IAAI,CAAC;AAAA,IACtC,WAAW,EAAE,GAAG,KAAK,WAAW,OAAO,YAAY;AAAA,EACrD;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/agent/surfaces.ts","../src/agent/define-agent.ts","../src/agent/improvement-adapter.ts","../src/agent/knowledge-adapter.ts","../src/agent/outcome.ts","../src/agent/sandbox-act.ts"],"sourcesContent":["/**\n * `AgentSurfaces` — declarative map of the mutable file/directory paths\n * the self-improvement loop can edit on behalf of an agent.\n *\n * The substrate uses this map to resolve every parsed `FindingSubject`\n * (from agent-eval) to a real on-disk path. No per-vertical glue;\n * no fabricated paths; no silent `existsSync(...)` skips that hide\n * misconfiguration from the operator.\n *\n * Surfaces are validated at `defineAgent` time — missing paths fail\n * loud with a list of every offender. A surface that's not needed\n * (e.g. an agent with no RAG corpora) is simply omitted; the loop\n * refuses to route those subjects rather than fabricating a target.\n */\n\nimport { existsSync } from 'node:fs'\nimport { isAbsolute, join } from 'node:path'\nimport type { FindingSubject } from '@tangle-network/agent-eval'\n\n/**\n * Surface declarations. Every path is repo-relative (or absolute) at\n * `defineAgent` time. At resolution time, paths are joined against the\n * agent's `repoRoot`.\n *\n * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends\n * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.\n * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in\n * place.\n *\n * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);\n * `applyKnowledgeWriteBlocks` writes pages relative to it.\n *\n * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)\n * can be omitted — the loop will reject findings targeting them with a\n * clear log message instead of fabricating a path.\n */\nexport interface AgentSurfaces {\n /** Directory containing one markdown file per system-prompt section. */\n systemPrompt: string\n /** Directory containing one subdir per tool (`<tool>/README.md`). */\n tools: string\n /** Single file (TypeScript module) defining the rubric weights + dimensions. */\n rubric: string\n /** Knowledge-base root; typically `.agent-knowledge`. */\n knowledge: string\n /** Directory containing one YAML/JSON file per persona. */\n personas: string\n /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */\n scaffolding?: string\n /** Optional: memory store path (JSONL / SQLite / DB). */\n memory?: string\n /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */\n rag?: string\n /** Optional: single file defining the output schema (Zod / JSON Schema). */\n outputSchema?: string\n}\n\nexport interface ResolvedSurface {\n /** Absolute filesystem path the operator can `cat` / `vim`. */\n absolutePath: string\n /** Repo-relative path for PR descriptions, diffs, audit logs. */\n repoRelativePath: string\n /** Whether the path currently exists on disk. */\n exists: boolean\n /** The substrate's intent: edit an existing file or create a new one. */\n intent: 'edit-existing' | 'create-new'\n}\n\n/**\n * Resolve a parsed `FindingSubject` to the file path the substrate\n * should edit (or create) on disk.\n *\n * Returns `null` when:\n * - the subject targets a surface the agent didn't declare\n * (e.g. `rag:*` when `surfaces.rag` is undefined), OR\n * - the subject is a `cluster` (failure-mode emits these as evidence,\n * not actionable mutations — they don't route to a file).\n *\n * Returns a `ResolvedSurface` with `intent: 'create-new'` when the\n * subject names a path that doesn't yet exist (e.g. a new wiki page).\n * The caller chooses whether to honour the create — for tightly-managed\n * surfaces like `systemPrompt` it's usually a contract violation\n * (the analyst named a section that doesn't exist); for `knowledge`\n * it's the whole point.\n */\nexport function resolveSubjectPath(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ResolvedSurface | null {\n const candidates = candidatePathsForSubject(subject, surfaces)\n if (candidates.length === 0) return null\n\n // Probe candidates in order, preferring the first one that exists on disk.\n // Lets the substrate accept both the flat `<section>.md` convention and\n // the skill-dir `<section>/SKILL.md` convention without forcing one layout.\n // When none exists, fall back to the first candidate (canonical create-new).\n for (const rel of candidates) {\n const abs = isAbsolute(rel) ? rel : join(repoRoot, rel)\n if (existsSync(abs)) {\n return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: 'edit-existing' }\n }\n }\n const fallback = candidates[0]!\n const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback)\n return {\n absolutePath: fallbackAbs,\n repoRelativePath: fallback,\n exists: false,\n intent: 'create-new',\n }\n}\n\nfunction candidatePathsForSubject(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n): ReadonlyArray<string> {\n switch (subject.kind) {\n case 'knowledge.wiki':\n case 'knowledge.stale':\n return [join(surfaces.knowledge, `${subject.slug}.md`)]\n case 'knowledge.claim':\n // Claims land in a per-topic claims directory under the knowledge root.\n return [join(surfaces.knowledge, 'claims', `${slugify(subject.topic)}.md`)]\n case 'knowledge.raw':\n return [join(surfaces.knowledge, 'raw', `${subject.sourceId}.md`)]\n case 'system-prompt': {\n const slug = slugify(subject.section)\n // Prefer flat layout for create-new (canonical); probe skill-dir layout\n // in case the existing repo (tax/legal/gtm/creative) uses\n // `<section>/SKILL.md` already.\n return [\n join(surfaces.systemPrompt, `${slug}.md`),\n join(surfaces.systemPrompt, slug, 'SKILL.md'),\n join(surfaces.systemPrompt, slug, 'index.md'),\n ]\n }\n case 'tool-doc':\n if (subject.aspect) {\n return [join(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`)]\n }\n // tool-doc default: `<tool>/README.md`; also probe `<tool>.md` for flat\n // tool-list repos.\n return [\n join(surfaces.tools, subject.tool, 'README.md'),\n join(surfaces.tools, `${subject.tool}.md`),\n ]\n case 'new-tool':\n return [join(surfaces.tools, subject.name, 'README.md')]\n case 'rag':\n if (!surfaces.rag) return []\n return [join(surfaces.rag, subject.corpus, `${subject.docId}.md`)]\n case 'memory':\n if (!surfaces.memory) return []\n return [join(surfaces.memory, `${slugify(subject.key)}.json`)]\n case 'scaffolding':\n if (!surfaces.scaffolding) return []\n return [join(surfaces.scaffolding, `${slugify(subject.concern)}.md`)]\n case 'output-schema':\n if (!surfaces.outputSchema) return []\n return [surfaces.outputSchema]\n case 'websearch.outdated':\n case 'prior-run-summary':\n // Stale signals don't map to a single file — handled by the knowledge\n // adapter as `agent-knowledge:stale:*` after operator review.\n return []\n case 'cluster':\n // failure-mode cluster labels are evidence, not mutations.\n return []\n }\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\n/**\n * Validate that every declared surface exists on disk under `repoRoot`.\n *\n * Returns an array of `SurfaceValidationIssue` — empty when all required\n * surfaces resolve. `defineAgent` throws with the issues rendered, so\n * a misconfigured manifest fails at startup (not at the first finding\n * the loop produces 20 minutes later).\n */\nexport interface SurfaceValidationIssue {\n surface: keyof AgentSurfaces\n path: string\n reason: 'missing' | 'not-directory' | 'not-file'\n}\n\n/** Validate an `AgentSurfaces` map on disk — missing paths fail loud at `defineAgent` time instead of silently skipping self-improvement edits. */\nexport function validateSurfaces(\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ReadonlyArray<SurfaceValidationIssue> {\n const issues: SurfaceValidationIssue[] = []\n const dirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'systemPrompt',\n 'tools',\n 'personas',\n 'knowledge',\n ]\n const fileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['rubric']\n const optionalDirSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['scaffolding', 'memory', 'rag']\n const optionalFileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['outputSchema']\n\n for (const key of dirSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n }\n }\n for (const key of fileSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n }\n }\n for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {\n const p = surfaces[key] as string | undefined\n if (p === undefined) continue\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n }\n }\n return issues\n}\n\n/** Format a list of surface validation issues into a human-readable error string. */\nexport function renderSurfaceIssues(\n issues: ReadonlyArray<SurfaceValidationIssue>,\n repoRoot: string,\n): string {\n if (issues.length === 0) return ''\n const lines = issues.map(\n (i) => ` - ${i.surface}: ${i.path ? `\"${i.path}\"` : '<not set>'} (${i.reason})`,\n )\n return [\n `Agent surface validation failed against repoRoot=${repoRoot}:`,\n ...lines,\n '',\n 'Fix the manifest: every required surface must point at an existing',\n 'directory (systemPrompt / tools / personas / knowledge) or file',\n '(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)',\n 'may be omitted; the loop will reject findings targeting omitted',\n 'surfaces rather than fabricating a path.',\n ].join('\\n')\n}\n","/**\n * `defineAgent` — typed, validated manifest API for declarative agent\n * configuration. The substrate consumes this manifest to wire the\n * canonical eval pattern + analyst self-improvement loop without any\n * per-vertical glue.\n *\n * Design goal: scale to 1000s of vertical agents. Every agent declares\n * its surfaces, rubric, runtime, and analyst configuration in ~50 lines.\n * No per-vertical `ImprovementAdapter`. No per-vertical CLI. No\n * fabricated paths.\n *\n * Validation: `defineAgent` runs `validateSurfaces` synchronously and\n * throws a structured error if any required surface is missing on\n * disk. The cost is one filesystem stat per surface (cheap); the\n * benefit is a manifest that can't ship broken.\n */\n\nimport type { TraceAnalystKindSpec } from '@tangle-network/agent-eval'\nimport type { PromotionGate } from '../lifecycle/gate'\nimport type { CandidateGenerator } from '../lifecycle/generator'\nimport type { ArtifactKind } from '../lifecycle/types'\nimport type { RuntimeStreamEvent } from '../types'\nimport { type AgentSurfaces, renderSurfaceIssues, validateSurfaces } from './surfaces'\n\n// ── manifest ─────────────────────────────────────────────────────────\n\n/**\n * The full agent manifest. Each agent ships ONE of these.\n *\n * Generics:\n * `TPersona` — the agent's persona shape (loaded from\n * `surfaces.personas`). Defaults to `unknown` so the substrate's\n * persona discovery (`loadPersonas`) can accept anything; per-agent\n * code re-narrows when it matters.\n * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric\n * scorers and emitted into the trace.\n */\nexport interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {\n /**\n * Stable identifier — used as `projectId` in traces, as the analyst\n * loop's `runId` prefix, and as the namespace under which findings\n * are persisted. MUST match the agent's repo name to keep\n * cross-repo telemetry joinable.\n */\n id: string\n\n /**\n * Filesystem root the substrate resolves surface paths against.\n * Typically `process.cwd()` or a fixed absolute path. Use an\n * absolute path when the agent's tests may run from subdirectories\n * (vitest sometimes shifts cwd).\n */\n repoRoot: string\n\n /**\n * Map of mutable surfaces the self-improvement loop can edit. See\n * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,\n * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,\n * `outputSchema`.\n *\n * Every required path is validated at `defineAgent` time. Missing\n * paths throw with the full list of offenders.\n */\n surfaces: AgentSurfaces\n\n /**\n * Rubric the substrate uses to score each run. Dimensions × weights\n * × judges. The substrate computes the weighted composite and\n * stamps it into the RunRecord.\n */\n rubric: AgentRubric<TRunOutput>\n\n /**\n * Runtime adapter — how the substrate INVOKES the agent against a\n * persona. The `act` function takes a persona + a context (with the\n * tracer the substrate threads through for span emission) and\n * returns the run output the rubric will score.\n *\n * The agent's existing production runtime goes in here; the\n * substrate is intentionally thin around it.\n */\n runtime: AgentRuntime<TPersona, TRunOutput>\n\n /**\n * Persona discovery — the substrate loads personas via this function\n * at eval start. Can read from `surfaces.personas`, an API, or be\n * hardcoded. The substrate calls it once per `runAgentEval` call;\n * persona ordering is preserved.\n */\n personas: () => Promise<ReadonlyArray<TPersona>>\n\n /**\n * Analyst kinds the substrate runs against each persona's trace.\n * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent\n * authors can prune (e.g. skip `knowledge-poisoning` when there's no\n * knowledge base) or extend (custom domain kinds).\n *\n * Empty array disables the loop — useful for `pnpm eval --no-analyst`.\n */\n analystKinds: ReadonlyArray<TraceAnalystKindSpec>\n\n /**\n * Analyst LLM configuration. The substrate uses these for all four\n * kinds (override per-kind via `analystKinds` if needed).\n */\n analyst: AnalystConfig\n\n /**\n * Auto-apply policy. Knowledge / improvement edits land only when\n * `enabled === true` AND the source finding's confidence meets the\n * threshold. `mode` controls how applies happen: `'write'` mutates\n * files in-place; `'open-pr'` writes to a branch and opens a PR.\n *\n * Default: knowledge auto-applies at confidence ≥0.85 in `'write'`\n * mode (wiki edits are git-reversible); improvement stays at\n * `enabled: false` until the agent author has measured precision.\n */\n autoApply?: AutoApplyPolicy\n\n /**\n * Declarative per-surface artifact-lifecycle config the closed loop reads.\n *\n * Each entry names a profile surface (`skill` / `tool` / `prompt` / `mcp` /\n * `hook` / `subagent`) and supplies the `CandidateGenerator` that grows it +\n * the `PromotionGate` (the held-back exam) that decides promotion. `runLifecycle`\n * consumes these: it pools the generators, measures each candidate's marginal\n * lift on the held-back split, gates it, and stores the winners in an\n * `ArtifactRegistry` — then `composeProfile` folds the top-`k` active artifacts\n * back into this agent's profile.\n *\n * Optional — agents that don't self-improve their profile omit it. An empty or\n * absent map means \"no lifecycle\"; the manifest is otherwise unchanged.\n */\n lifecycles?: ReadonlyArray<SurfaceLifecycle>\n}\n\n/**\n * One profile surface's artifact-lifecycle wiring — the declarative config a\n * `defineAgent` manifest carries and `runLifecycle` reads. It is config, not\n * execution: it names the generator + gate; the loop runs them.\n */\nexport interface SurfaceLifecycle {\n /** The profile surface this lifecycle grows. */\n surface: ArtifactKind\n /** Produces fresh candidate artifacts for `surface` from the agent's history. */\n generator: CandidateGenerator\n /** The held-back exam that decides promotion of a measured candidate. */\n gate: PromotionGate\n /** Top-`k` budget for `composeProfile` when folding this surface's promoted\n * artifacts back in. Omit to fold in every active artifact. */\n composeK?: number\n}\n\nexport interface AgentRubric<TRunOutput> {\n /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */\n dimensions: ReadonlyArray<RubricDimension<TRunOutput>>\n /**\n * Optional judges layered on top of deterministic dimensions. Each\n * judge returns a score per dimension; the substrate averages judges\n * (mean by default) for the LLM contribution.\n */\n judges?: ReadonlyArray<JudgeConfig<TRunOutput>>\n}\n\nexport interface RubricDimension<TRunOutput> {\n /** Unique identifier — appears in finding subjects (`rubric:<id>`). */\n id: string\n /** 0..1 — weight in the composite. */\n weight: number\n /**\n * Deterministic scorer: given the persona + run output, returns a\n * 0..1 score. The substrate sums weight × score across dimensions\n * for the deterministic composite; judges supplement subjective dims.\n */\n score: (input: { persona: unknown; output: TRunOutput }) => number\n /** Optional human-readable label for reports. */\n label?: string\n}\n\nexport interface JudgeConfig<TRunOutput> {\n /** Judge identifier — appears in trace spans + manifest. */\n id: string\n /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */\n model: string\n /** Dimensions this judge scores. */\n dimensions: ReadonlyArray<string>\n /**\n * Optional rubric anchors — text examples the judge sees as a\n * few-shot prompt to calibrate. STRONGLY recommended for subjective\n * dimensions; required by the calibration gate (Pearson ≥0.7).\n */\n anchors?: ReadonlyArray<{ input: string; output: TRunOutput; expected: Record<string, number> }>\n}\n\nexport interface AgentRuntime<TPersona, TRunOutput> {\n /**\n * Invoke the agent against one persona. Returns BOTH:\n * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric\n * product consumes verbatim (SSE / WebSocket / inline render).\n * **Streaming is mandatory — never collapse this to a single Promise.**\n * The agent's existing `runChatTurn` (or equivalent async generator)\n * plugs in here directly.\n * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream\n * drains. The eval substrate awaits this for rubric scoring; chat\n * products usually ignore it (they already rendered incrementally).\n *\n * Implementation contract:\n * 1. `act` MUST return immediately (synchronous construction of the\n * `events` iterator + the `output` promise).\n * 2. Iterating `events` drives the underlying LLM/tool calls — the\n * caller chooses when to consume.\n * 3. `output` resolves only after the iterator yields its terminal\n * event (typically `task_end`); see `collectAgentRun` helper.\n *\n * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes\n * SHOULD record LLM/tool spans through it for capture integrity.\n * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful\n * cancel. `ctx.signal` is the standard abort signal.\n */\n act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>\n}\n\nexport interface AgentRunInvocation<TRunOutput> {\n /** Live stream of typed runtime events. Consumed by chat UX directly. */\n events: AsyncIterable<RuntimeStreamEvent>\n /** Final structured output the rubric scores. Resolves after `events` drains. */\n output: Promise<TRunOutput>\n}\n\n/**\n * Stub for agents whose `runtime.act` is not yet wired to the substrate's\n * eval path. Preserves the streaming contract (empty event stream + a\n * rejected `output` promise that tells the caller exactly what to fix).\n *\n * Per-vertical manifests usually start with this stub and replace it with\n * the agent's real streaming runtime (`runChatTurn` or equivalent) once\n * the eval path consumes the manifest end-to-end.\n */\nexport function unimplementedAgentRun<TRunOutput = unknown>(\n reason = 'AgentRuntime.act is not yet wired for this manifest',\n): AgentRunInvocation<TRunOutput> {\n return {\n events: (async function* empty(): AsyncIterable<RuntimeStreamEvent> {})(),\n output: Promise.reject(new Error(reason)),\n }\n}\n\n/**\n * Drain `act`'s `events` into an array AND await its `output`. Useful for\n * eval / outcome-measurement code paths that don't care about live\n * rendering. The events array is preserved so the substrate can inspect\n * tool calls / readiness / questions retrospectively.\n *\n * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming\n * (no incremental render). Use `for await (const ev of invocation.events)`\n * directly in the chat surface.\n */\nexport async function collectAgentRun<TRunOutput>(\n invocation: AgentRunInvocation<TRunOutput>,\n): Promise<{ events: ReadonlyArray<RuntimeStreamEvent>; output: TRunOutput }> {\n const events: RuntimeStreamEvent[] = []\n for await (const ev of invocation.events) events.push(ev)\n const output = await invocation.output\n return { events, output }\n}\n\nexport interface AgentRunContext {\n /** Substrate-managed trace emitter. */\n emitter: import('@tangle-network/agent-eval').TraceEmitter\n /** Stable run id for this persona × variant cell. */\n runId: string\n /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */\n variantId?: string\n /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */\n deadlineMs?: number\n /** Optional abort signal. */\n signal?: AbortSignal\n}\n\nexport interface AnalystConfig {\n /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */\n model: string\n /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */\n budgetUsd?: number\n /** Backend hint for the AxAIService factory — same shape every kind uses. */\n backend?: {\n name?: 'openai' | 'router'\n apiKey?: string\n baseUrl?: string\n }\n}\n\nexport interface AutoApplyPolicy {\n knowledge?: {\n enabled: boolean\n confidenceThreshold?: number\n mode?: 'write' | 'open-pr'\n }\n improvement?: {\n enabled: boolean\n confidenceThreshold?: number\n mode?: 'write' | 'open-pr'\n }\n}\n\n// ── factory + validation ─────────────────────────────────────────────\n\n/** Thrown when `defineAgent` finds a required surface missing on disk. */\nexport class AgentManifestError extends Error {\n constructor(\n message: string,\n public readonly agentId: string,\n public readonly issues: ReadonlyArray<unknown> = [],\n ) {\n super(message)\n this.name = 'AgentManifestError'\n }\n}\n\n/**\n * Construct a validated agent manifest. Throws `AgentManifestError`\n * if any required surface is missing on disk.\n *\n * Generics: pass your persona / output types if you want narrowed\n * `runtime.act` signatures:\n * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`\n *\n * Most callers don't need the generics — the substrate operates on\n * `unknown` payloads internally and the manifest's `score` /\n * `runtime.act` see the typed shapes via TypeScript inference at\n * the call site.\n */\nexport function defineAgent<TPersona = unknown, TRunOutput = unknown>(\n manifest: AgentManifest<TPersona, TRunOutput>,\n): AgentManifest<TPersona, TRunOutput> {\n if (!manifest.id || manifest.id.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `id` is required', manifest.id ?? '')\n }\n if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `repoRoot` is required', manifest.id)\n }\n const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot)\n if (issues.length > 0) {\n throw new AgentManifestError(\n renderSurfaceIssues(issues, manifest.repoRoot),\n manifest.id,\n issues,\n )\n }\n // Lightweight rubric sanity: weights sum to ~1.0 (no hard requirement —\n // the substrate normalizes — but flag wildly miscalibrated weights).\n const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0)\n if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {\n throw new AgentManifestError(\n `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} — should be ~1.0`,\n manifest.id,\n )\n }\n return manifest\n}\n","/**\n * Substrate-default `ImprovementAdapter` — surfaces-driven, LLM-drafted\n * patches, optional auto-apply or PR-open.\n *\n * This is the one ImprovementAdapter every vertical agent uses. The\n * substrate parses each finding's `subject` via\n * `parseFindingSubject` (agent-eval), resolves it to a real file path\n * via the agent's `AgentSurfaces`, reads the current content, and asks\n * an LLM to draft a unified-diff patch given the finding + current\n * content + per-kind editing-discipline rules.\n *\n * Auto-apply gates on the source-finding's confidence and the\n * autoApply.improvement policy. Two modes:\n * `write` — apply the patch in-place via `git apply -p0`. Operator\n * reviews via `git diff`.\n * `open-pr` — write to a branch, commit, push, open a PR via `gh`.\n * Operator reviews via the PR UI.\n *\n * Fail-loud rules:\n * - Findings whose subject doesn't parse → counted in `errors`.\n * - Findings whose subject targets an undeclared surface → counted in\n * `errors` with the offending kind in the message.\n * - Findings whose target path doesn't exist AND the kind isn't a\n * create-new variant (`new-tool`, `knowledge.wiki`) → counted in\n * `errors` with the resolved path in the message.\n * - LLM drafts that fail JSON-schema validation → counted in\n * `errors` with the schema issue.\n *\n * No silent skips. Every dropped finding has a recorded reason the\n * loop's report surfaces.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { readFileSync } from 'node:fs'\nimport type { AnalystFinding, FindingSubject } from '@tangle-network/agent-eval'\nimport { parseFindingSubject } from '@tangle-network/agent-eval/analyst'\nimport type { ImprovementAdapter } from '../analyst-loop/types'\nimport type { AgentSurfaces, ResolvedSurface } from './surfaces'\nimport { resolveSubjectPath } from './surfaces'\n\n// ── proposal shape ───────────────────────────────────────────────────\n\nexport interface SurfaceImprovementEdit {\n /** Stable id derived from the source finding so re-proposals are idempotent. */\n id: string\n /** The finding that produced this edit — for revert + audit trail. */\n sourceFindingId: string\n /** Parsed subject; included so the apply step doesn't re-parse. */\n subject: FindingSubject\n /** Resolved on-disk target. */\n target: ResolvedSurface\n /** SHA-256 of the current file content the patch was drafted against. */\n baseSha256: string\n /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */\n patch: string\n /** One-line summary the operator sees in the report / PR title. */\n summary: string\n /** Multi-line rationale for the PR body — finding context + LLM reasoning. */\n rationale: string\n /** Carry-forward from the finding so the apply gate can check the threshold. */\n confidence: number\n /** Carry-forward severity for prioritization. */\n severity: AnalystFinding['severity']\n}\n\nexport interface CreateSurfaceImprovementAdapterOpts {\n surfaces: AgentSurfaces\n repoRoot: string\n /**\n * LLM-draft callback. Given a finding + current file content + the\n * resolved target, returns a unified-diff patch + summary + rationale.\n *\n * Required — the substrate doesn't ship a hardcoded prompt; the agent\n * author picks the model (Haiku for cheap routine drafts, Sonnet for\n * substantive prompt rewrites, etc.) via this callback.\n */\n draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>\n /**\n * Apply mode:\n * `write` — `git apply` in-place; operator reviews via `git diff`\n * `open-pr` — branch + commit + push + `gh pr create`\n * `none` — never apply; collect proposals for the report only\n *\n * The `apply` method honours this even when the loop calls it; the\n * effective behaviour is also gated on the per-finding confidence\n * threshold via `runAnalystLoop`'s `autoApply` policy.\n */\n mode?: 'write' | 'open-pr' | 'none'\n /** When `mode === 'open-pr'`, the base branch new PRs target. Default: `main`. */\n baseBranch?: string\n /** Required for `mode === 'open-pr'` — the GH owner/repo (`tangle-network/tax-agent`). */\n ghRepo?: string\n /**\n * When the resolved target doesn't exist, allow the substrate to\n * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default\n * true for those kinds, false for `system-prompt` / `rubric` / etc.\n * (named sections that don't exist are a contract violation, not a\n * scaffolding opportunity).\n */\n allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>\n}\n\nexport interface DraftPatchInput {\n finding: AnalystFinding\n subject: FindingSubject\n target: ResolvedSurface\n /** Current file content (empty string when `intent === 'create-new'`). */\n currentContent: string\n}\n\nexport interface DraftPatchOutput {\n /** Unified diff against the current file content. Empty string skips this finding. */\n patch: string\n /** One-line summary for the operator. */\n summary: string\n /** Multi-line rationale for the PR body. */\n rationale: string\n}\n\n// ── factory ──────────────────────────────────────────────────────────\n\nconst DEFAULT_CREATE_KINDS: ReadonlyArray<FindingSubject['kind']> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'new-tool',\n]\n\n/** The substrate-default `ImprovementAdapter`: resolve each finding's subject to a real surface path, LLM-draft a unified-diff patch, then auto-apply or open a PR. */\nexport function createSurfaceImprovementAdapter(\n opts: CreateSurfaceImprovementAdapterOpts,\n): ImprovementAdapter<SurfaceImprovementEdit> {\n const mode = opts.mode ?? 'none'\n const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS\n\n return {\n async proposeFromFindings(findings) {\n const edits: SurfaceImprovementEdit[] = []\n const errors: Array<{ findingId: string; subject: string; message: string }> = []\n let skipped = 0\n\n for (const f of findings) {\n const subject = parseFindingSubject(f.subject)\n if (subject === null) {\n if (f.subject !== undefined) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject,\n message: 'subject does not parse against the finding-subject grammar',\n })\n } else {\n // Subject-less findings are descriptive, not actionable —\n // legitimate; count in `skipped` not `errors`.\n skipped += 1\n }\n continue\n }\n\n // `cluster` findings (failure-mode) are evidence, not mutations.\n if (subject.kind === 'cluster') {\n skipped += 1\n continue\n }\n\n // `agent-knowledge:*` findings flow to the KnowledgeAdapter;\n // the ImprovementAdapter skips them so subjects don't double-route.\n if (subject.kind.startsWith('knowledge.')) {\n skipped += 1\n continue\n }\n\n const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot)\n if (target === null) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `subject kind \"${subject.kind}\" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`,\n })\n continue\n }\n\n if (target.intent === 'create-new' && !allowCreate.includes(subject.kind)) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `target ${target.repoRelativePath} does not exist; the kind \"${subject.kind}\" requires an existing target (analyst named a section that isn't in the codebase)`,\n })\n continue\n }\n\n const currentContent = target.exists ? readFileSync(target.absolutePath, 'utf-8') : ''\n\n let draft: DraftPatchOutput\n try {\n draft = await opts.draftPatch({ finding: f, subject, target, currentContent })\n } catch (err) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`,\n })\n continue\n }\n\n if (draft.patch.trim().length === 0) {\n skipped += 1\n continue\n }\n\n edits.push({\n id: `imp-${f.finding_id}`,\n sourceFindingId: f.finding_id,\n subject,\n target,\n baseSha256: sha256(currentContent),\n patch: draft.patch,\n summary: draft.summary,\n rationale: draft.rationale,\n confidence: f.confidence,\n severity: f.severity,\n })\n }\n\n return { edits, skipped, errors }\n },\n\n async apply(edits) {\n const applied: string[] = []\n const warnings: string[] = []\n\n if (mode === 'none') {\n warnings.push(\n 'createSurfaceImprovementAdapter: mode=none; no edits applied — adjust manifest.autoApply.improvement.mode',\n )\n return { applied, warnings }\n }\n\n if (mode === 'open-pr' && !opts.ghRepo) {\n warnings.push(\n 'createSurfaceImprovementAdapter: mode=open-pr requires `ghRepo`; falling back to no-op',\n )\n return { applied, warnings }\n }\n\n for (const edit of edits) {\n // Race-detection: confirm the file content hasn't moved since the\n // patch was drafted. A diff applied against drifted content is a\n // recipe for silent corruption.\n const current = edit.target.exists ? readFileSync(edit.target.absolutePath, 'utf-8') : ''\n if (sha256(current) !== edit.baseSha256) {\n warnings.push(\n `${edit.target.repoRelativePath}: base SHA mismatch; file changed after draft. Skipping.`,\n )\n continue\n }\n\n const ok = applyPatchInPlace(edit, opts.repoRoot)\n if (!ok) {\n warnings.push(`${edit.target.repoRelativePath}: git apply failed`)\n continue\n }\n applied.push(edit.target.repoRelativePath)\n }\n\n if (mode === 'open-pr' && applied.length > 0 && opts.ghRepo) {\n const prUrl = openPullRequest(\n applied,\n edits.filter((e) => applied.includes(e.target.repoRelativePath)),\n opts.repoRoot,\n opts.ghRepo,\n opts.baseBranch ?? 'main',\n )\n if (prUrl) warnings.push(`opened PR: ${prUrl}`)\n else warnings.push('PR creation failed; edits are committed to a local branch only')\n }\n\n return { applied, warnings }\n },\n }\n}\n\n// ── apply helpers ────────────────────────────────────────────────────\n\nfunction applyPatchInPlace(edit: SurfaceImprovementEdit, repoRoot: string): boolean {\n const result = spawnSync('git', ['apply', '--whitespace=fix', '-p0', '-'], {\n cwd: repoRoot,\n input: edit.patch,\n encoding: 'utf-8',\n })\n return result.status === 0\n}\n\nfunction openPullRequest(\n paths: ReadonlyArray<string>,\n edits: ReadonlyArray<SurfaceImprovementEdit>,\n repoRoot: string,\n ghRepo: string,\n baseBranch: string,\n): string | null {\n const branch = `analyst-loop/${Date.now()}-${edits[0]?.sourceFindingId.slice(0, 12) ?? 'edits'}`\n // Create branch, stage, commit\n const checkout = spawnSync('git', ['checkout', '-b', branch], { cwd: repoRoot })\n if (checkout.status !== 0) return null\n const add = spawnSync('git', ['add', ...paths], { cwd: repoRoot })\n if (add.status !== 0) return null\n const title = `analyst-loop: ${edits[0]?.summary ?? `${edits.length} improvement edits`}`\n const body = [\n `Automated analyst-loop edits — review carefully before merge.`,\n '',\n `Source findings:`,\n ...edits.map(\n (e) =>\n ` - ${e.sourceFindingId} (confidence ${e.confidence.toFixed(2)}, severity ${e.severity})`,\n ),\n '',\n 'Rationales:',\n ...edits.map((e) => `\\n## ${e.target.repoRelativePath}\\n\\n${e.rationale}`),\n ].join('\\n')\n const commit = spawnSync('git', ['commit', '-m', title, '-m', body], { cwd: repoRoot })\n if (commit.status !== 0) return null\n const push = spawnSync('git', ['push', '-u', 'origin', branch], { cwd: repoRoot })\n if (push.status !== 0) return null\n const pr = spawnSync(\n 'gh',\n [\n 'pr',\n 'create',\n '--repo',\n ghRepo,\n '--title',\n title,\n '--body',\n body,\n '--base',\n baseBranch,\n '--head',\n branch,\n ],\n { cwd: repoRoot, encoding: 'utf-8' },\n )\n if (pr.status !== 0) return null\n return pr.stdout.trim()\n}\n\nfunction sha256(s: string): string {\n // node:crypto is dynamic-imported lazily so the adapter can be tested in\n // environments without crypto (browser tests, mocked envs).\n const crypto = require('node:crypto') as typeof import('node:crypto')\n return crypto.createHash('sha256').update(s, 'utf-8').digest('hex')\n}\n","/**\n * Substrate-default `KnowledgeAdapter` — wraps agent-knowledge's\n * `proposeFromFindings` + `applyKnowledgeWriteBlocks` with substrate\n * defaults (auto-lint after apply, source linkage via finding id).\n *\n * Every agent that ships a `.agent-knowledge/` tree uses this adapter\n * unmodified. Per-agent customization happens at the manifest level\n * (`autoApply.knowledge.confidenceThreshold`, etc.), not by writing a\n * new adapter.\n *\n * Lint discipline: after each apply we run agent-knowledge's\n * `lintKnowledgeIndex` to catch broken links / circular claims /\n * duplicate pages introduced by the new writes. Findings that fail the\n * post-apply lint are recorded in `warnings`; the apply itself is not\n * rolled back (lint failures are soft — humans review the wiki state).\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport type { KnowledgeAdapter } from '../analyst-loop/types'\n\nexport interface CreateSurfaceKnowledgeAdapterOpts {\n /** `.agent-knowledge/` root (absolute path the substrate writes blocks against). */\n knowledgeRoot: string\n}\n\n/**\n * Build the adapter. We accept the agent-knowledge functions as DI so\n * the substrate stays decoupled from a specific agent-knowledge\n * version — the agent author imports them in their manifest module\n * and hands them to the factory.\n *\n * `proposeFromFindings(findings)` returns\n * `{ proposals: KnowledgeProposal[]; skipped: number; errors: ... }`.\n *\n * `applyKnowledgeWriteBlocks(root, content)` returns\n * `{ written: string[]; warnings: string[] }`.\n *\n * `lintKnowledgeIndex(index)` (optional) returns `KnowledgeLintFinding[]`.\n */\nexport interface KnowledgeAdapterDeps<TProposal> {\n proposeFromFindings: (findings: ReadonlyArray<AnalystFinding>) => {\n proposals: TProposal[]\n skipped: number\n errors: Array<{ findingId: string; subject: string; message: string }>\n }\n applyKnowledgeWriteBlocks: (\n root: string,\n proposalText: string,\n ) => Promise<{ written: string[]; warnings: string[] }>\n /**\n * Optional post-apply lint hook. The substrate runs it after each\n * batch of writes; failures land in `warnings` (the apply is not\n * rolled back — lint signals drift to review, not block).\n */\n lintAfterApply?: (root: string) => Promise<ReadonlyArray<string>>\n}\n\n/** Wire a surface-based `KnowledgeAdapter` that writes analyst proposals to agent surface files. */\nexport function createSurfaceKnowledgeAdapter<TProposal>(\n opts: CreateSurfaceKnowledgeAdapterOpts,\n deps: KnowledgeAdapterDeps<TProposal>,\n): KnowledgeAdapter<TProposal> {\n return {\n proposeFromFindings(findings) {\n const batch = deps.proposeFromFindings(findings)\n return {\n proposals: batch.proposals,\n skipped: batch.skipped,\n errors: batch.errors,\n }\n },\n async apply(proposals) {\n const written: string[] = []\n const warnings: string[] = []\n for (const p of proposals) {\n const proposalText = renderProposalAsWriteBlock(p)\n if (proposalText === null) {\n warnings.push(\n `proposal has no writeBlocks/content; skipping (sourceFindingId=${getSourceFindingId(p)})`,\n )\n continue\n }\n try {\n const r = await deps.applyKnowledgeWriteBlocks(opts.knowledgeRoot, proposalText)\n written.push(...r.written)\n warnings.push(...r.warnings)\n } catch (err) {\n warnings.push(\n `applyKnowledgeWriteBlocks failed: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n if (deps.lintAfterApply && written.length > 0) {\n try {\n const lintIssues = await deps.lintAfterApply(opts.knowledgeRoot)\n for (const issue of lintIssues) warnings.push(`lint: ${issue}`)\n } catch (err) {\n warnings.push(\n `lintAfterApply failed: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n return { written, warnings }\n },\n }\n}\n\n/**\n * Pluck the canonical write-block text from a proposal regardless of\n * which exact agent-knowledge version produced it. We accept either:\n * - `{ writeBlocks: Array<{ path, content }> }` — the typed shape\n * 1.3.0+ emits\n * - `{ proposalText: string }` — legacy single-block shape\n * - `{ content: string }` — minimal raw form\n *\n * Returns `null` when nothing parseable is present (warned upstream).\n */\nfunction renderProposalAsWriteBlock(p: unknown): string | null {\n if (!p || typeof p !== 'object') return null\n const obj = p as Record<string, unknown>\n if (Array.isArray(obj.writeBlocks)) {\n const blocks = obj.writeBlocks as Array<{ path?: string; content?: string }>\n if (blocks.length === 0) return null\n return blocks\n .map((b) => (typeof b.content === 'string' ? b.content : ''))\n .filter((s) => s.length > 0)\n .join('\\n\\n')\n }\n if (typeof obj.proposalText === 'string') return obj.proposalText\n if (typeof obj.content === 'string') return obj.content\n return null\n}\n\nfunction getSourceFindingId(p: unknown): string {\n if (!p || typeof p !== 'object') return '<unknown>'\n const obj = p as Record<string, unknown>\n if (typeof obj.sourceFindingId === 'string') return obj.sourceFindingId\n if (typeof obj.id === 'string') return obj.id\n return '<unknown>'\n}\n","/**\n * `OutcomeMeasurement` — the missing metric that turns the analyst\n * loop from \"observability\" into \"self-improvement\".\n *\n * Without this hook, the loop reports process counts (`findings: 42`,\n * `applied: 7`) and never proves the applied edits actually improved\n * anything. With this hook, the substrate re-runs the cohort against\n * the same personas after each apply pass and reports a composite\n * score delta. A negative delta is the substrate's strongest signal\n * to either roll back or surface for review.\n *\n * Wiring is intentionally simple: pass the manifest + the `runAgentEval`\n * function and a list of `personaIds` to re-run. The wrapper:\n * 1. Captures the baseline composite from the just-finished run.\n * 2. After `runAnalystLoop` returns, re-invokes `runAgentEval` against\n * the same persona slice.\n * 3. Computes the delta and appends to `loop-report.json`.\n * 4. If `rollbackOnRegression` and delta < 0, reverts applied edits.\n */\n\nimport type { RunAnalystLoopResult } from '../analyst-loop/types'\n\nexport interface OutcomeMeasurement {\n /** Baseline composite before applies — captured from the most-recent eval run. */\n baselineComposite: number\n /** Composite after re-running the cohort with applied edits. */\n afterComposite: number\n /** `afterComposite - baselineComposite`. Positive = the loop improved the agent. */\n delta: number\n /** Per-persona deltas for finer-grained review. */\n perPersona: ReadonlyArray<{ personaId: string; before: number; after: number; delta: number }>\n /** When the substrate rolled back applies due to regression, the paths reverted. */\n rolledBackPaths: ReadonlyArray<string>\n}\n\nexport interface OutcomeMeasurementOpts {\n /** Composite scores from the run that produced the findings. */\n baseline: ReadonlyArray<{ personaId: string; composite: number }>\n /**\n * Re-run callback — the substrate invokes this after applies. The\n * agent author provides their `runAgentEval`-equivalent so the\n * substrate can ask \"score this persona slice now.\"\n *\n * The callback SHOULD reuse the same cohort + judges + variant as\n * the baseline run; only the agent's mutable surfaces have changed.\n */\n reRunCohort: (\n personaIds: ReadonlyArray<string>,\n ) => Promise<ReadonlyArray<{ personaId: string; composite: number }>>\n /** When `true`, applied edits are reverted on negative delta. Default `false`. */\n rollbackOnRegression?: boolean\n /** Callback to revert a list of paths (typically `git checkout HEAD --`). */\n revert?: (paths: ReadonlyArray<string>) => Promise<void>\n}\n\n/**\n * Run `runAnalystLoop` and stamp an `OutcomeMeasurement` onto the\n * result. The substrate calls this after each canonical eval; the\n * delta lands in `loop-report.json` for cross-run trend analysis.\n *\n * The function returns the original `RunAnalystLoopResult` enriched\n * with `outcome` so callers stay backwards-compatible (the field is\n * optional on the type; missing means no measurement was wired).\n */\nexport async function measureOutcome<TProposal, TEdit>(\n result: RunAnalystLoopResult<TProposal, TEdit>,\n opts: OutcomeMeasurementOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit> & { outcome: OutcomeMeasurement }> {\n const applied = result.knowledge?.applied ?? []\n const improvementsApplied = result.improvement?.applied ?? []\n const allApplied = [...applied, ...improvementsApplied]\n\n // No applies → no outcome to measure. Return a zero-delta to keep the\n // shape stable for consumers; baseline / after equal.\n if (allApplied.length === 0) {\n return {\n ...result,\n outcome: {\n baselineComposite: meanComposite(opts.baseline),\n afterComposite: meanComposite(opts.baseline),\n delta: 0,\n perPersona: opts.baseline.map((b) => ({\n personaId: b.personaId,\n before: b.composite,\n after: b.composite,\n delta: 0,\n })),\n rolledBackPaths: [],\n },\n }\n }\n\n const personaIds = opts.baseline.map((b) => b.personaId)\n const after = await opts.reRunCohort(personaIds)\n const afterByPersona = new Map(after.map((r) => [r.personaId, r.composite]))\n\n const perPersona = opts.baseline.map((b) => {\n const a = afterByPersona.get(b.personaId) ?? b.composite\n return { personaId: b.personaId, before: b.composite, after: a, delta: a - b.composite }\n })\n const baselineComposite = meanComposite(opts.baseline)\n const afterComposite = meanComposite(after)\n const delta = afterComposite - baselineComposite\n\n let rolledBackPaths: string[] = []\n if (delta < 0 && opts.rollbackOnRegression && opts.revert) {\n await opts.revert(allApplied)\n rolledBackPaths = [...allApplied]\n }\n\n return {\n ...result,\n outcome: {\n baselineComposite,\n afterComposite,\n delta,\n perPersona,\n rolledBackPaths,\n },\n }\n}\n\nfunction meanComposite(rows: ReadonlyArray<{ composite: number }>): number {\n if (rows.length === 0) return 0\n return rows.reduce((acc, r) => acc + r.composite, 0) / rows.length\n}\n","/**\n * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.\n *\n * The point of this adapter is parity: the eval substrate must run the agent\n * through the SAME profile the production chat turn uses, or scorecard numbers\n * grade a profile that never ships. `createSandboxAct` boots a sandbox with the\n * agent's profile (the caller's `baseProfile`, with optional per-persona\n * overrides) through the loop kernel's own {@link createSandboxForSpec},\n * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`\n * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring\n * — satisfying the `act` streaming contract with one code path shared by chat\n * and eval.\n *\n * Agents with a bespoke streaming chat turn should wire THAT into `act`\n * directly (the contract is designed for it); this adapter is the default for\n * agents whose turn is a plain prod-profile sandbox dispatch — notably the\n * agents agent-builder generates.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n} from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { AgentRunSpec, OutputAdapter, SandboxClient } from '../runtime'\nimport { mapSandboxEvent } from '../runtime'\nimport { createSandboxForSpec } from '../runtime/run-loop'\nimport type { RuntimeStreamEvent } from '../types'\nimport type { AgentRunContext, AgentRunInvocation } from './define-agent'\n\n/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the\n * per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */\nexport interface SandboxActComposeOverrides {\n /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */\n systemPrompt?: string\n /** Extra file mounts layered after the base profile's `resources.files`. */\n extraFiles?: AgentProfileFileMount[]\n /** Override the profile `name`. Defaults to the base profile's name. */\n name?: string\n /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */\n tools?: Record<string, boolean>\n /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */\n mcpConnections?: Record<string, AgentProfileMcpServer>\n}\n\nexport interface CreateSandboxActOptions<TPersona, TRunOutput> {\n /** Canonical agent profile — the same one the prod chat turn uses. */\n baseProfile: AgentProfile\n /** Sandbox client used to boot the per-run sandbox. */\n sandboxClient: SandboxClient\n /** Persona → prompt. Pure; the eval cell's input. */\n buildPrompt: (persona: TPersona) => string\n /** Sandbox event stream → typed output the rubric scores. */\n output: OutputAdapter<TRunOutput>\n /**\n * Per-persona profile overrides (workspace-augmented system prompt, extra\n * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.\n */\n compose?: (persona: TPersona) => SandboxActComposeOverrides\n /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */\n sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides']\n /** Stable run name surfaced in mapped `llm_call` events. */\n name?: string\n /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */\n mapEvent?: (\n event: SandboxEvent,\n opts: { agentRunName?: string },\n ) => RuntimeStreamEvent | undefined\n}\n\n/**\n * Build an `AgentRuntime.act` implementation backed by a single prod-profile\n * sandbox run. The returned function honours the `act` contract: it returns\n * synchronously with a live `events` iterator and an `output` promise that\n * resolves only after the iterator drains.\n */\nexport function createSandboxAct<TPersona, TRunOutput>(\n options: CreateSandboxActOptions<TPersona, TRunOutput>,\n): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput> {\n const mapEvent = options.mapEvent ?? mapSandboxEvent\n\n return (persona: TPersona, ctx: AgentRunContext): AgentRunInvocation<TRunOutput> => {\n const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona))\n const agentRunName = options.name ?? profile.name ?? 'agent'\n const message = options.buildPrompt(persona)\n const signal = ctx.signal ?? new AbortController().signal\n\n const raw: SandboxEvent[] = []\n let settle!: (value: TRunOutput) => void\n let fail!: (err: unknown) => void\n const output = new Promise<TRunOutput>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n // The output promise rejects when the stream errors; if the caller ignores\n // `output` (chat UX) the rejection is still observed by the events iterator\n // throwing. Attach a no-op catch so an ignored rejection is never \"unhandled\".\n output.catch(() => {})\n\n const spec: AgentRunSpec<unknown> = {\n profile,\n taskToPrompt: () => message,\n name: agentRunName,\n ...(options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}),\n }\n\n async function* events(): AsyncIterable<RuntimeStreamEvent> {\n try {\n const box = await createSandboxForSpec(options.sandboxClient, spec, signal)\n for await (const event of box.streamPrompt(message, { signal })) {\n raw.push(event)\n const mapped = mapEvent(event, { agentRunName })\n if (mapped) yield mapped\n }\n settle(options.output.parse(raw))\n } catch (err) {\n fail(err)\n throw err\n }\n }\n\n return { events: events(), output }\n }\n}\n\n/** Overlay the per-persona overrides onto the base profile. Each slot merges over the base; an\n * absent override leaves the base profile untouched. */\nfunction applyComposeOverrides(\n base: AgentProfile,\n overrides: SandboxActComposeOverrides | undefined,\n): AgentProfile {\n if (!overrides) return base\n const prompt = overrides.systemPrompt\n ? { ...base.prompt, systemPrompt: overrides.systemPrompt }\n : base.prompt\n const mergedTools = overrides.tools ? { ...(base.tools ?? {}), ...overrides.tools } : base.tools\n const mergedMcp = overrides.mcpConnections\n ? { ...(base.mcp ?? {}), ...overrides.mcpConnections }\n : base.mcp\n const baseFiles = base.resources?.files ?? []\n const mergedFiles: AgentProfileFileMount[] = overrides.extraFiles?.length\n ? [...baseFiles, ...overrides.extraFiles]\n : [...baseFiles]\n return {\n ...base,\n name: overrides.name ?? base.name,\n prompt,\n ...(mergedTools ? { tools: mergedTools } : {}),\n ...(mergedMcp ? { mcp: mergedMcp } : {}),\n resources: { ...base.resources, files: mergedFiles },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,YAAY;AAqE1B,SAAS,mBACd,SACA,UACA,UACwB;AACxB,QAAM,aAAa,yBAAyB,SAAS,QAAQ;AAC7D,MAAI,WAAW,WAAW,EAAG,QAAO;AAMpC,aAAW,OAAO,YAAY;AAC5B,UAAM,MAAM,WAAW,G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K,UAAU,IAAI,CAAC;AAAA,IACtC,WAAW,EAAE,GAAG,KAAK,WAAW,OAAO,YAAY;AAAA,EACrD;AACF;","names":[]}
|
package/dist/analyst-loop.d.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { TraceAnalystByteBudgets, TraceAnalysisStore } from '@tangle-network/agent-eval';
|
|
2
|
-
import { I as Iteration } from './types-
|
|
2
|
+
import { I as Iteration } from './types-ESeMOj94.js';
|
|
3
3
|
import { R as RunAnalystLoopOpts, a as RunAnalystLoopResult } from './types-BC3bZpH0.js';
|
|
4
4
|
export { A as AnalystLoopEvent, b as AnalystRegistryLike, c as AnalystRegistryStreamingLike, d as AutoApplyPolicy, F as FindingsStoreLike, I as ImprovementAdapter, e as ImprovementEditBatch, f as ImprovementReport, K as KnowledgeAdapter, g as KnowledgeProposalBatch, h as KnowledgeReport } from './types-BC3bZpH0.js';
|
|
5
5
|
import '@tangle-network/sandbox';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* @experimental
|
|
9
8
|
*
|
|
10
9
|
* The read seam that closes the autonomous loop: project a round's `Iteration[]`
|
|
11
10
|
* (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the
|
|
@@ -18,6 +17,8 @@ import '@tangle-network/sandbox';
|
|
|
18
17
|
* steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event
|
|
19
18
|
* lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration
|
|
20
19
|
* surfaces a real ERROR span carrying the real message.
|
|
20
|
+
*
|
|
21
|
+
* @experimental
|
|
21
22
|
*/
|
|
22
23
|
|
|
23
24
|
/**
|
package/dist/analyst-loop.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
iterationsToTraceStore,
|
|
3
3
|
runAnalystLoop
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-YPA5MLVE.js";
|
|
5
5
|
import "./chunk-4J6RBI3K.js";
|
|
6
|
-
import "./chunk-
|
|
6
|
+
import "./chunk-YEJR7IXO.js";
|
|
7
7
|
import "./chunk-DGUM43GV.js";
|
|
8
8
|
export {
|
|
9
9
|
iterationsToTraceStore,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildLoopOtelSpans,
|
|
3
3
|
createOtelExporter
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-UD4BHQMI.js";
|
|
5
5
|
|
|
6
6
|
// src/mcp/trace-propagation.ts
|
|
7
7
|
function readTraceContextFromEnv() {
|
|
@@ -49,4 +49,4 @@ export {
|
|
|
49
49
|
createPropagatingTraceEmitter,
|
|
50
50
|
traceContextToEnv
|
|
51
51
|
};
|
|
52
|
-
//# sourceMappingURL=chunk-
|
|
52
|
+
//# sourceMappingURL=chunk-4WXGK6GV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp/trace-propagation.ts"],"sourcesContent":["/**\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 * @experimental\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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SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AACZ;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/profiles/coder.ts"],"sourcesContent":["/**\n *\n * `CoderTask` + `coderTaskToPrompt` — the per-task DATA + pure formatter for code-modification tasks\n * (§1.5: the system authors profiles; there is no hardcoded coder profile constant). A domain\n * customizes the worker by authoring its own `AgentProfile` and handing it to a leaf executor\n * (`createWorktreeCliExecutor`) or a fanout (`worktreeFanout`); \"is it delivered\" is a\n * `DeliverableSpec` (`patchDelivered`), not a bundled validator. This formatter renders a `CoderTask`\n * into the per-task instruction that profile receives.\n *\n * @experimental\n */\n\nconst DEFAULT_MAX_DIFF_LINES = 400\n\n/** @experimental The per-task inputs `coderTaskToPrompt` renders + the worktree gate enforces. */\nexport interface CoderTask {\n /** What the agent must accomplish. Free-form prose. */\n goal: string\n /** Absolute path inside the sandbox where the repo lives. */\n repoRoot: string\n /** Default `main`. The branch the agent diffs against. */\n baseBranch?: string\n /** Default `pnpm test --run`. */\n testCmd?: string\n /** Default `pnpm typecheck`. */\n typecheckCmd?: string\n /** Files the agent may inspect for context. Surfaced verbatim in the prompt. */\n contextFiles?: string[]\n /**\n * Paths the agent must not touch. The mechanical gate hard-fails on any match.\n * Use glob-free literal path prefixes for unambiguous enforcement.\n */\n forbiddenPaths?: string[]\n /** Default 400. Hard cap; the gate hard-fails when exceeded. */\n maxDiffLines?: number\n}\n\n/** Render a `CoderTask` into the per-task instruction handed to the coder profile. @experimental */\nexport function coderTaskToPrompt(task: CoderTask): string {\n const base = task.baseBranch ?? 'main'\n const testCmd = task.testCmd ?? 'pnpm test --run'\n const typecheckCmd = task.typecheckCmd ?? 'pnpm typecheck'\n const maxDiff = task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = task.forbiddenPaths?.length ? task.forbiddenPaths.join(', ') : '(none)'\n const context = task.contextFiles?.length\n ? task.contextFiles.map((f) => ` - ${f}`).join('\\n')\n : ' (none)'\n return [\n `Goal: ${task.goal}`,\n `Repo: ${task.repoRoot}`,\n `Base branch: ${base}`,\n `Run tests with: ${testCmd}`,\n `Run typecheck with: ${typecheckCmd}`,\n `Forbidden paths: ${forbidden}`,\n `Max diff lines: ${maxDiff}`,\n 'Context files:',\n context,\n '',\n 'Produce a minimal patch on a fresh branch. Run tests and typecheck before',\n 'returning. Emit the final JSON result block exactly as instructed.',\n ].join('\\n')\n}\n"],"mappings":";AAYA,IAAM,yBAAyB;AA0BxB,SAAS,kBAAkB,MAAyB;AACzD,QAAM,OAAO,KAAK,cAAc;AAChC,QAAM,UAAU,KAAK,WAAW;AAChC,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,UAAU,KAAK,gBAAgB;AACrC,QAAM,YAAY,KAAK,gBAAgB,SAAS,KAAK,eAAe,KAAK,IAAI,IAAI;AACjF,QAAM,UAAU,KAAK,cAAc,SAC/B,KAAK,aAAa,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,EAAE,KAAK,IAAI,IAClD;AACJ,SAAO;AAAA,IACL,SAAS,KAAK,IAAI;AAAA,IAClB,SAAS,KAAK,QAAQ;AAAA,IACtB,gBAAgB,IAAI;AAAA,IACpB,mBAAmB,OAAO;AAAA,IAC1B,uBAAuB,YAAY;AAAA,IACnC,oBAAoB,SAAS;AAAA,IAC7B,mBAAmB,OAAO;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp/local-harness.ts"],"sourcesContent":["/**\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 * @experimental\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":";AAmBA,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,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