@tangle-network/agent-runtime 0.194.0 → 0.195.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-BQFIiyUG.js → activation-B4adh0sA.js} +3 -3
- package/dist/{activation-BQFIiyUG.js.map → activation-B4adh0sA.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-B6CDW-fp.js → candidate-execution-nvqVIMyS.js} +5 -4
- package/dist/{candidate-execution-B6CDW-fp.js.map → candidate-execution-nvqVIMyS.js.map} +1 -1
- package/dist/{coordination-driver-iSN-m3VX.js → coordination-driver-CuShDjRV.js} +3 -3
- package/dist/{coordination-driver-iSN-m3VX.js.map → coordination-driver-CuShDjRV.js.map} +1 -1
- package/dist/{delegate-DCC2muUd.js → delegate-CSFC-Kh3.js} +2 -2
- package/dist/{delegate-DCC2muUd.js.map → delegate-CSFC-Kh3.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +2 -2
- package/dist/{environment-provider-Dr-wfnHg.js → environment-provider-Z1JazbJ1.js} +108 -10
- package/dist/environment-provider-Z1JazbJ1.js.map +1 -0
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-DghidDx5.js → graph-DqPUeri6.js} +3 -3
- package/dist/{graph-DghidDx5.js.map → graph-DqPUeri6.js.map} +1 -1
- package/dist/graph.d.ts +1 -1
- package/dist/graph.js +4 -4
- package/dist/{improve-COGzLCiY.d.ts → improve-7VTwse1c.d.ts} +4 -4
- package/dist/{improvement-cycle-DeS1ZC5B.js → improvement-cycle-DEbciBTL.js} +20 -6
- package/dist/{improvement-cycle-DeS1ZC5B.js.map → improvement-cycle-DEbciBTL.js.map} +1 -1
- package/dist/{index-CrBgLCIf.d.ts → index-CVD30soi.d.ts} +2 -2
- package/dist/{index-BEPjOPwH.d.ts → index-DNx0nWZH.d.ts} +9 -2
- package/dist/index.d.ts +6 -5
- package/dist/index.js +72 -26
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +1 -1
- package/dist/intelligence.js +7 -6
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +9 -9
- package/dist/{knowledge-B5okOzBQ.js → knowledge-B0Mrp-XB.js} +7 -17
- package/dist/knowledge-B0Mrp-XB.js.map +1 -0
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-U1J6x_UF.js → loop-runner-bin-C5K46H0Q.js} +3 -3
- package/dist/{loop-runner-bin-U1J6x_UF.js.map → loop-runner-bin-C5K46H0Q.js.map} +1 -1
- package/dist/{loop-runner-bin-Clc5IAwu.d.ts → loop-runner-bin-b4585v9Z.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/{prepare-C29kNAon.js → prepare-DDGp0-rW.js} +4 -54
- package/dist/prepare-DDGp0-rW.js.map +1 -0
- package/dist/profiles.js +454 -1
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-CKYND416.js → protected-model-port-DxFN8DLS.js} +3 -2
- package/dist/{protected-model-port-CKYND416.js.map → protected-model-port-DxFN8DLS.js.map} +1 -1
- package/dist/{protected-redaction--F3v1oo8.js → protected-redaction-wGo44k2K.js} +54 -3
- package/dist/protected-redaction-wGo44k2K.js.map +1 -0
- package/dist/{provision-supervisor-CRPbnJiB.js → provision-supervisor-chyz0_Aj.js} +4 -4
- package/dist/{provision-supervisor-CRPbnJiB.js.map → provision-supervisor-chyz0_Aj.js.map} +1 -1
- package/dist/{redact-BOU77QfQ.js → redact-Dv6PeuQz.js} +2 -2
- package/dist/{redact-BOU77QfQ.js.map → redact-Dv6PeuQz.js.map} +1 -1
- package/dist/{runtime-BVrqSu0-.js → runtime-BZryF6gD.js} +140 -65
- package/dist/runtime-BZryF6gD.js.map +1 -0
- package/dist/{server-D6XmE1Du.js → server-BorSFmn8.js} +3 -3
- package/dist/{server-D6XmE1Du.js.map → server-BorSFmn8.js.map} +1 -1
- package/dist/{structural-rollout-BcPXFzVb.js → structural-rollout-pOqANr8Y.js} +23 -10
- package/dist/structural-rollout-pOqANr8Y.js.map +1 -0
- package/dist/{supervise-C0V3pZXK.js → supervise-BReI5ATC.js} +4 -4
- package/dist/{supervise-C0V3pZXK.js.map → supervise-BReI5ATC.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +14 -13
- package/dist/testing.js.map +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{workspace-archive-BCezkeIk.js → workspace-archive-Ybomp7AN.js} +3 -2
- package/dist/{workspace-archive-BCezkeIk.js.map → workspace-archive-Ybomp7AN.js.map} +1 -1
- package/package.json +4 -4
- package/skills/agent-graphs/SKILL.md +28 -123
- package/skills/agent-graphs/references/authoring.md +34 -0
- package/skills/agent-graphs/references/measurement.md +18 -0
- package/skills/build-with-agent-runtime/SKILL.md +31 -117
- package/skills/build-with-agent-runtime/references/improvement.md +32 -0
- package/skills/codemode/SKILL.md +22 -34
- package/skills/codemode/references/runtime-execution.md +14 -0
- package/skills/generate-eval/SKILL.md +2 -1
- package/skills/loop-writer/SKILL.md +30 -84
- package/skills/supervise/SKILL.md +43 -95
- package/skills/supervise/references/profile-authoring.md +19 -0
- package/dist/environment-provider-Dr-wfnHg.js.map +0 -1
- package/dist/knowledge-B5okOzBQ.js.map +0 -1
- package/dist/prepare-C29kNAon.js.map +0 -1
- package/dist/protected-redaction--F3v1oo8.js.map +0 -1
- package/dist/researcher-Cp4JRbFp.js +0 -457
- package/dist/researcher-Cp4JRbFp.js.map +0 -1
- package/dist/runtime-BVrqSu0-.js.map +0 -1
- package/dist/structural-rollout-BcPXFzVb.js.map +0 -1
- package/skills/agent-graphs/IMPROVE.md +0 -58
package/dist/profiles.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profiles.js","names":["fs"],"sources":["../src/profiles/ui-auditor/slugify.ts","../src/audit/issue-writer.ts","../src/profiles/ui-auditor/lens-prompts.ts","../src/profiles/ui-auditor/output-adapter.ts","../src/profiles/ui-auditor/prompt.ts","../src/profiles/ui-auditor/validator.ts"],"sourcesContent":["/**\n *\n * Shared slug helper used by both the in-process auditor client (for\n * screenshot filenames) and the issue writer (for issue Markdown\n * filenames). Lowercases, normalizes, strips non-alphanumeric, trims\n * dashes, caps at 80 chars. Throws when the result is empty so callers\n * never silently write to a name-less filename.\n *\n * @experimental\n */\n\n/** @experimental */\nexport function slugify(value: string, fieldName: string): string {\n const slug = value\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 80)\n if (slug.length === 0) {\n throw new Error(\n `ui-auditor: ${fieldName} slugified to empty string. Provide a non-empty value (got ${JSON.stringify(value)}).`,\n )\n }\n return slug\n}\n","/**\n *\n * UI-audit issue writer — pure I/O. Takes a workspace dir + `UiFinding[]`\n * and emits:\n * - `<workspace>/issues/NNN--<lens>--<slug>.md` — one self-contained\n * GitHub-issue-ready Markdown per finding, with embedded screenshot\n * references.\n * - `<workspace>/registry.json` — finding index for dedup and audit\n * resume across iterations.\n * - `<workspace>/index.md` — human-readable rollup (severity / lens /\n * route counts plus a sorted finding list).\n *\n * The writer is deterministic, idempotent for `appendFindings()`, and\n * never invokes an LLM. It assigns the next monotonic id to a finding the\n * caller did not pre-id.\n *\n * @experimental\n */\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { slugify } from '../profiles/ui-auditor/slugify'\nimport {\n UI_FINDING_SEVERITIES,\n UI_LENSES,\n type UiFinding,\n type UiLens,\n} from '../profiles/ui-auditor/substrate'\n\n/** @experimental */\nexport interface AuditRegistry {\n schemaVersion: 1\n findings: UiFinding[]\n /** Route → URL + captures sidecar; preserved across runs. */\n routes: Record<string, { url?: string; captures: AuditRegistryCapture[] }>\n}\n\n/** @experimental */\nexport interface AuditRegistryCapture {\n file: string\n viewport?: string\n fullPage?: boolean\n elementSelector?: string\n capturedAt: string\n}\n\nconst SEVERITY_ORDER: Record<UiFinding['severity'], number> = {\n critical: 0,\n high: 1,\n med: 2,\n low: 3,\n}\n\n// Validate workspaceDir at every public entry point. The MCP tool checks\n// the same shape at the wire boundary, but the writer is independently\n// exported via `@tangle-network/agent-runtime/profiles`, so direct callers\n// would otherwise bypass that defense. Absolute + no `..` segments matches\n// the MCP tool's contract — any path that the writer joins for I/O must be\n// rooted at a deterministic location chosen by the caller.\nfunction assertValidWorkspaceDir(dir: string): void {\n if (typeof dir !== 'string' || dir.length === 0) {\n throw new Error(\n `audit-writer: workspaceDir must be a non-empty string (got ${JSON.stringify(dir)})`,\n )\n }\n if (!path.isAbsolute(dir)) {\n throw new Error(\n `audit-writer: workspaceDir must be an absolute path (got ${JSON.stringify(dir)})`,\n )\n }\n if (dir.split(path.sep).includes('..')) {\n throw new Error(\n `audit-writer: workspaceDir must not contain '..' segments (got ${JSON.stringify(dir)})`,\n )\n }\n}\n\n/** Create the `issues/`, `screenshots/`, and `registry.json` scaffold in a new audit workspace. @experimental */\nexport async function initAuditWorkspace(workspaceDir: string): Promise<void> {\n assertValidWorkspaceDir(workspaceDir)\n await fs.mkdir(path.join(workspaceDir, 'issues'), { recursive: true })\n await fs.mkdir(path.join(workspaceDir, 'screenshots'), { recursive: true })\n const regPath = path.join(workspaceDir, 'registry.json')\n try {\n await fs.access(regPath)\n } catch {\n const fresh: AuditRegistry = { schemaVersion: 1, findings: [], routes: {} }\n await fs.writeFile(regPath, JSON.stringify(fresh, null, 2))\n }\n}\n\n/** Read and validate the `registry.json` from an audit workspace. @experimental */\nexport async function readAuditRegistry(workspaceDir: string): Promise<AuditRegistry> {\n assertValidWorkspaceDir(workspaceDir)\n const regPath = path.join(workspaceDir, 'registry.json')\n const text = await fs.readFile(regPath, 'utf8')\n const parsed = JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`audit-writer: registry.json at ${regPath} is not a JSON object`)\n }\n const reg = parsed as Partial<AuditRegistry>\n if (reg.schemaVersion !== 1 || !Array.isArray(reg.findings) || typeof reg.routes !== 'object') {\n throw new Error(`audit-writer: registry.json at ${regPath} has an unrecognized shape`)\n }\n return reg as AuditRegistry\n}\n\nasync function writeAuditRegistry(workspaceDir: string, reg: AuditRegistry): Promise<void> {\n const regPath = path.join(workspaceDir, 'registry.json')\n // Write to a sibling temp file and rename. POSIX rename is atomic, so a\n // reader at any instant sees either the pre-write OR post-write registry,\n // never a half-written file. Prevents corruption on crash mid-write.\n const tmpPath = `${regPath}.tmp-${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n await fs.writeFile(tmpPath, JSON.stringify(reg, null, 2))\n await fs.rename(tmpPath, regPath)\n}\n\n// Per-workspace serialization. The writer reads registry.json, mutates it\n// in memory, then writes it back; concurrent calls would race on the\n// monotonic-id assignment and clobber each other's findings. Each\n// workspace key holds the Promise of the most-recently-enqueued operation;\n// new operations chain off it so they run strictly serially.\nconst workspaceLocks = new Map<string, Promise<unknown>>()\n\nasync function withWorkspaceLock<T>(workspaceDir: string, fn: () => Promise<T>): Promise<T> {\n const key = path.resolve(workspaceDir)\n const prev = workspaceLocks.get(key) ?? Promise.resolve()\n let signalDone!: () => void\n const done = new Promise<void>((resolve) => {\n signalDone = resolve\n })\n workspaceLocks.set(key, done)\n try {\n await prev\n return await fn()\n } finally {\n signalDone()\n // Only delete if no later caller has overwritten the slot — preserves\n // the chain for any concurrent callers still waiting.\n if (workspaceLocks.get(key) === done) workspaceLocks.delete(key)\n }\n}\n\nfunction assertFindingShape(f: UiFinding, index: number): void {\n const where = `audit-writer: findings[${index}]`\n if (!UI_LENSES.includes(f.lens)) {\n throw new Error(\n `${where}: invalid lens ${JSON.stringify(f.lens)}; one of ${UI_LENSES.join('|')}`,\n )\n }\n if (!UI_FINDING_SEVERITIES.includes(f.severity)) {\n throw new Error(\n `${where}: invalid severity ${JSON.stringify(f.severity)}; one of ${UI_FINDING_SEVERITIES.join('|')}`,\n )\n }\n for (const field of ['title', 'route', 'observation', 'impact', 'suggestedFix'] as const) {\n const v = f[field]\n if (typeof v !== 'string' || v.trim().length === 0) {\n throw new Error(`${where}: ${field} must be a non-empty string`)\n }\n }\n if (!Array.isArray(f.screenshots) || f.screenshots.length === 0) {\n throw new Error(`${where}: screenshots must be a non-empty array`)\n }\n for (let i = 0; i < f.screenshots.length; i += 1) {\n const s = f.screenshots[i]\n if (!s || typeof s.path !== 'string' || s.path.length === 0) {\n throw new Error(`${where}.screenshots[${i}].path must be a non-empty string`)\n }\n // Defense-in-depth: screenshot paths are written verbatim into Markdown\n // and the registry; a downstream consumer that joins workspaceDir with\n // them would otherwise be exposed to traversal-read. Reject `..`\n // segments at the validation boundary.\n if (s.path.split(/[/\\\\]/).includes('..')) {\n throw new Error(`${where}.screenshots[${i}].path must not contain '..' segments`)\n }\n }\n}\n\nfunction nextFindingId(reg: AuditRegistry): number {\n let max = 0\n for (const f of reg.findings) {\n if (typeof f.id === 'number' && f.id > max) max = f.id\n }\n return max + 1\n}\n\nfunction slugifyTitle(title: string): string {\n return slugify(title, 'title')\n}\n\nfunction renderFinding(finding: UiFinding): string {\n if (!finding.id) {\n throw new Error('audit-writer: cannot render a finding without an assigned id')\n }\n if (finding.screenshots.length === 0) {\n throw new Error(`audit-writer: finding #${finding.id} has no screenshots`)\n }\n const id = finding.id\n const numStr = String(id).padStart(3, '0')\n\n const metaLines: string[] = [\n `> **Issue #${numStr}** · **Severity:** ${finding.severity} · **Lens:** ${finding.lens}`,\n `> **Route:** \\`${finding.route}\\`${finding.url ? ` · **URL:** ${finding.url}` : ''}`,\n ]\n if (finding.viewport) metaLines.push(`> **Viewport:** ${finding.viewport}`)\n if (finding.selector) metaLines.push(`> **Selector:** \\`${finding.selector}\\``)\n if (finding.tags && finding.tags.length > 0) {\n metaLines.push(`> **Tags:** ${finding.tags.map((t) => `\\`${t}\\``).join(', ')}`)\n }\n if (finding.similarTo && finding.similarTo.length > 0) {\n metaLines.push(\n `> **Possible duplicates:** ${finding.similarTo.map((n) => `#${String(n).padStart(3, '0')}`).join(', ')}`,\n )\n }\n metaLines.push(`> _Generated: ${finding.createdAt ?? new Date().toISOString()}_`)\n\n const reproSteps =\n finding.reproSteps ??\n `1. Open \\`${finding.route}\\`${finding.url ? ` (${finding.url})` : ''}\\n2. Observe the area shown in the screenshot${finding.selector ? ` (selector: \\`${finding.selector}\\`)` : ''}.`\n\n // Screenshot paths are workspace-relative; the issue file sits in\n // `<workspace>/issues/`, so we render `../<path>`.\n const evidence = finding.screenshots\n .map((s) => ``)\n .join('\\n\\n')\n\n return [\n `# [UI] ${finding.title}`,\n '',\n metaLines.join('\\n'),\n '',\n '## Observation',\n finding.observation.trim(),\n '',\n '## Why it matters',\n finding.impact.trim(),\n '',\n '## Steps to reproduce',\n reproSteps,\n '',\n '## Suggested fix',\n finding.suggestedFix.trim(),\n '',\n '## Evidence',\n evidence,\n '',\n '---',\n `<sub>Generated by agent-runtime/ui-auditor · lens=\\`${finding.lens}\\` · severity=\\`${finding.severity}\\`</sub>`,\n '',\n ].join('\\n')\n}\n\n/** @experimental */\nexport interface AppendFindingsResult {\n /** Findings with id + createdAt assigned, in input order. */\n written: UiFinding[]\n /** Workspace-relative path to each issue Markdown file, in input order. */\n files: string[]\n}\n\n/**\n * Append findings to a workspace, writing one Markdown file per finding\n * and updating registry.json. Assigns monotonically increasing ids to\n * findings that arrived without one.\n *\n * Findings already carrying an id that collides with the registry are\n * rejected — callers must either freshly mint findings (id undefined) or\n * use a separate update path. This protects against accidental overwrite.\n *\n * @experimental\n */\nexport async function appendFindings(\n workspaceDir: string,\n findings: readonly UiFinding[],\n): Promise<AppendFindingsResult> {\n assertValidWorkspaceDir(workspaceDir)\n // Validate every finding BEFORE acquiring the lock so callers see a fast\n // input-shape error without blocking concurrent writers. Validation is\n // the only defense against path traversal via crafted `lens` values\n // (the filename interpolates lens directly) and against malformed\n // Markdown from missing required fields — TypeScript types are erased\n // at runtime, so this boundary cannot trust its callers.\n for (let i = 0; i < findings.length; i += 1) {\n const f = findings[i]\n if (!f) throw new Error(`audit-writer: findings[${i}] is undefined`)\n assertFindingShape(f, i)\n }\n\n return withWorkspaceLock(workspaceDir, async () => {\n await initAuditWorkspace(workspaceDir)\n const reg = await readAuditRegistry(workspaceDir)\n const usedIds = new Set<number>()\n for (const f of reg.findings) {\n if (typeof f.id === 'number') usedIds.add(f.id)\n }\n\n const written: UiFinding[] = []\n const files: string[] = []\n let nextId = nextFindingId(reg)\n\n for (const incoming of findings) {\n let id = incoming.id\n if (id !== undefined) {\n if (usedIds.has(id)) {\n throw new Error(\n `audit-writer: incoming finding id ${id} (title=${JSON.stringify(incoming.title)}) collides with an existing registry entry`,\n )\n }\n } else {\n id = nextId\n while (usedIds.has(id)) id += 1\n nextId = id + 1\n }\n usedIds.add(id)\n\n const createdAt = incoming.createdAt ?? new Date().toISOString()\n const persisted: UiFinding = { ...incoming, id, createdAt }\n\n const slug = slugifyTitle(persisted.title)\n const fileName = `${String(id).padStart(3, '0')}--${persisted.lens}--${slug}.md`\n const filePathAbs = path.join(workspaceDir, 'issues', fileName)\n const filePathRel = `issues/${fileName}`\n\n await fs.writeFile(filePathAbs, renderFinding(persisted))\n reg.findings.push(persisted)\n written.push(persisted)\n files.push(filePathRel)\n }\n\n await writeAuditRegistry(workspaceDir, reg)\n return { written, files }\n })\n}\n\n/** @experimental */\nexport interface RegisterCapturesOptions {\n route: string\n url?: string\n captures: readonly AuditRegistryCapture[]\n}\n\n/**\n * Record screenshots taken for a route in the registry, without filing a\n * finding. Useful when the auditor wants to remember which captures\n * exist for resume / dedup purposes.\n *\n * @experimental\n */\nexport async function registerCaptures(\n workspaceDir: string,\n options: RegisterCapturesOptions,\n): Promise<void> {\n assertValidWorkspaceDir(workspaceDir)\n if (typeof options.route !== 'string' || options.route.trim().length === 0) {\n throw new Error('audit-writer: registerCaptures: route must be a non-empty string')\n }\n return withWorkspaceLock(workspaceDir, async () => {\n await initAuditWorkspace(workspaceDir)\n const reg = await readAuditRegistry(workspaceDir)\n const slot = reg.routes[options.route] ?? { captures: [] }\n if (options.url) slot.url = options.url\n slot.captures = [...slot.captures, ...options.captures]\n reg.routes[options.route] = slot\n await writeAuditRegistry(workspaceDir, reg)\n })\n}\n\n/** @experimental */\nexport interface AuditIndex {\n /** Total findings in the workspace. */\n total: number\n bySeverity: Record<UiFinding['severity'], number>\n byLens: Partial<Record<UiLens, number>>\n byRoute: Record<string, number>\n}\n\n/** Compute finding counts by severity, lens, and route from an `AuditRegistry`. @experimental */\nexport function summarizeRegistry(reg: AuditRegistry): AuditIndex {\n const bySeverity: Record<UiFinding['severity'], number> = {\n critical: 0,\n high: 0,\n med: 0,\n low: 0,\n }\n const byLens: Partial<Record<UiLens, number>> = {}\n const byRoute: Record<string, number> = {}\n for (const f of reg.findings) {\n bySeverity[f.severity] += 1\n byLens[f.lens] = (byLens[f.lens] ?? 0) + 1\n byRoute[f.route] = (byRoute[f.route] ?? 0) + 1\n }\n return { total: reg.findings.length, bySeverity, byLens, byRoute }\n}\n\n/**\n * Regenerate `<workspace>/index.md` from registry.json.\n *\n * @experimental\n */\nexport async function writeAuditIndex(workspaceDir: string): Promise<string> {\n assertValidWorkspaceDir(workspaceDir)\n const reg = await readAuditRegistry(workspaceDir)\n const summary = summarizeRegistry(reg)\n\n const sorted = [...reg.findings].sort((a, b) => {\n const sa = SEVERITY_ORDER[a.severity]\n const sb = SEVERITY_ORDER[b.severity]\n if (sa !== sb) return sa - sb\n return (a.id ?? 0) - (b.id ?? 0)\n })\n\n const lines: string[] = []\n lines.push('# UI audit index', '')\n lines.push(`_Generated: ${new Date().toISOString()}_`, '')\n lines.push(`**Total findings:** ${summary.total}`, '')\n lines.push('## By severity')\n for (const s of ['critical', 'high', 'med', 'low'] as const) {\n const n = summary.bySeverity[s] ?? 0\n if (n > 0) lines.push(`- **${s}** — ${n}`)\n }\n lines.push('', '## By lens')\n const lensEntries: [string, number][] = Object.entries(summary.byLens).map(([k, v]) => [\n k,\n v ?? 0,\n ])\n for (const [lens, n] of lensEntries.sort((a, b) => b[1] - a[1])) {\n lines.push(`- **${lens}** — ${n}`)\n }\n lines.push('', '## By route')\n const routeEntries: [string, number][] = Object.entries(summary.byRoute).map(([k, v]) => [\n k,\n v ?? 0,\n ])\n for (const [route, n] of routeEntries.sort((a, b) => b[1] - a[1])) {\n lines.push(`- \\`${route}\\` — ${n}`)\n }\n lines.push('', '## Findings', '')\n for (const f of sorted) {\n if (typeof f.id !== 'number') continue\n const num = String(f.id).padStart(3, '0')\n const slug = slugifyTitle(f.title)\n const file = `issues/${num}--${f.lens}--${slug}.md`\n lines.push(`- [#${num} \\`${f.severity}\\` \\`${f.lens}\\` \\`${f.route}\\` — ${f.title}](${file})`)\n }\n lines.push('')\n\n const out = path.join(workspaceDir, 'index.md')\n const body = lines.join('\\n')\n await fs.writeFile(out, body)\n return out\n}\n","/**\n *\n * Per-lens guidance the auditor inlines into its system prompt for an\n * iteration. Each entry is a self-contained brief — the same content the\n * standalone ui-issue-finder skill ships, embedded as a string constant so\n * agent-runtime carries no runtime dep on that external workspace.\n *\n * Briefs are deliberately concrete: they enumerate the SIGNALS to look for\n * and the cross-lens distinctions to respect, so the judge files fewer\n * pile-on findings under generic labels.\n *\n * @experimental\n */\n\nimport type { UiLens } from './substrate'\n\n/** Cross-lens rules injected into every UI audit iteration: finding quality standards and scope limits. @experimental */\nexport const SHARED_AUDITOR_RULES = `\nYou are auditing a UI for a specific class of problems. Stay strictly in your assigned lens — do not file issues that belong to another lens (a separate iteration will catch those).\n\nA finding is only valid if a thoughtful product designer would agree the screenshot shows something that should change. Avoid:\n- Personal taste (\"I'd prefer brand blue\").\n- Hallucinated text or controls you cannot actually see in the screenshot.\n- Suggestions that depend on requirements you don't have access to.\n- Pile-on findings about the same root cause — file ONE finding and use \\`similarTo\\` to link the rest.\n\nRequired for every finding:\n- title: concrete, names the offending element AND what's wrong (NOT \"improve UX\").\n- severity: critical=blocks a core task or accessibility blocker; high=noticeable friction; med=visible polish issue; low=nitpick.\n- observation: 1–3 sentences describing exactly what you see that is wrong.\n- impact: who is affected and how (concrete).\n- suggestedFix: a specific change a developer could apply without asking you back.\n- screenshots: refer to the captures attached to this iteration by path.\n- selector: when you can pin the offending element with a CSS selector.\n\nMost findings are med or low. Reserve high/critical for genuine blockers.\n`.trim()\n\n/** Per-lens auditor briefs: concrete signals to look for and cross-lens distinctions to respect. @experimental */\nexport const LENS_BRIEFS: Record<UiLens, string> = {\n consistency: `\nLENS: consistency\nLook for inconsistencies in the design system — things that look like they came from different products glued together.\nSignals: multiple font families, inconsistent weights/sizes for the same role, two shades of \"primary\", arbitrary paddings/margins that don't snap to a scale (4/8/12/16/24), same control with different border-radius or shadow on different pages, mixed icon styles (filled vs outlined), inconsistent button heights/padding for the same variant, inconsistent capitalization (Title Case vs sentence case) for the same role.\nNOT this lens: layout misalignment (use \\`layout\\`), confusing user flow (use \\`ux-flow\\`), contrast/keyboard issues (use \\`accessibility\\`).\nTitle format: \\`Inconsistent <thing> between <A> and <B>\\`.\n`.trim(),\n hierarchy: `\nLENS: hierarchy\nLook for broken visual hierarchy — places where the eye does not land on what matters most.\nSignals: primary CTA same weight as secondary/tertiary controls, headings (H1/H2/H3) nearly the same size, important data buried (headline number smaller than its label), decoration outshining content, too many emphases competing, wrong scan order, missing or overly heavy section dividers.\nNOT this lens: same-role styled differently (\\`consistency\\`), grid/alignment (\\`layout\\`), contrast-failing text (\\`accessibility\\`).\nTitle format: \\`Weak hierarchy: <element> does not read as the <intended-role>\\`.\n`.trim(),\n layout: `\nLENS: layout\nLook for layout and organization problems — alignment, grouping, whitespace, structural choices that hurt scannability.\nSignals: misalignment within rows, inconsistent gutters in grids, orphan whitespace next to crammed regions, poor grouping (related fields separated, unrelated fields adjacent), no visual sections (long wall of content), container overflow (text/content punching out of card boundaries), cramped or oversized hit targets, sidebars/headers sized wrong relative to main content.\nNOT this lens: same-role styled differently (\\`consistency\\`), click-distance/friction (\\`ux-flow\\`), overflow specifically at small viewports (\\`responsive\\`).\nTitle format: \\`<Region> alignment/spacing problem\\` or \\`<Region> grouping unclear\\`.\n`.trim(),\n 'ux-flow': `\nLENS: ux-flow\nLook for interaction-flow friction — action sequences that are slower, more annoying, or more error-prone than necessary.\nSignals: sequential clicks far apart (e.g. Next top-right while user is bottom-left), destructive action adjacent to primary with same weight, confirmations that don't say what's being confirmed, primary CTA below the fold or hidden in a kebab menu, silent state changes (toggle gives no feedback), form ordering that fights real-world order, dead-end states after submit, lost inputs on back-navigation, hidden pre-selected options.\nNOT this lens: visual style only (\\`consistency\\`), component arrangement without a flow problem (\\`layout\\`), microcopy clarity (\\`content\\`).\nTitle format: \\`<Action A> → <Action B> friction: <root cause>\\`.\n`.trim(),\n duplication: `\nLENS: duplication\nLook for redundancy — the same control, link, or piece of content appearing more than once with no good reason.\nSignals: two ways to do the same action on the same screen with no difference, repeated nav (same links in sidebar AND top nav), drifted duplicates (two copies that have diverged), content repeated verbatim, icon + label saying the same thing twice in one row, per-row + bulk actions that overlap confusingly, multiple status indicators conveying the same status.\nNOT this lens: inconsistent styling of duplicates (\\`consistency\\`) — this lens is about the existence of duplicates.\nTitle format: \\`Duplicate <thing> in <location A> and <location B>\\`.\n`.trim(),\n accessibility: `\nLENS: accessibility\nLook for accessibility blockers and degradations. Be conservative — do not assume violations you cannot see.\nSignals: insufficient contrast on body text or controls, missing/invisible focus styles, tiny tap targets (<24px on mobile), color as sole signal (red border with no message), form labels missing or not associated (placeholders standing in for labels), broken heading order (H1 → H4), modals that don't trap focus, decorative elements that take focus, errors not announced, important text rendered inside images.\nNOT this lens: generic \"looks confusing\" (\\`hierarchy\\` or \\`content\\`), layout overflow at small viewports (\\`responsive\\`).\nTitle format: \\`Accessibility: <specific blocker> in <element>\\`.\n`.trim(),\n responsive: `\nLENS: responsive\nLook for layout breakage across viewport sizes — content that works at one width but degrades at another. This iteration's captures should include the same surface at >=2 viewports; compare across them.\nSignals: horizontal scroll where content should reflow, overlapping elements (header overlaps content, fixed footer covers inputs), desktop nav crammed into mobile without collapsing, table columns that don't truncate, tap targets too close at touch sizes, controls vanishing at certain widths, layout flips that break grouping order, modals exceeding viewport height (confirm button unreachable).\nNOT this lens: issues present at every viewport (\\`consistency\\` / \\`hierarchy\\` instead).\nTitle format: \\`<Element/Region> breaks at <viewport>\\`.\n`.trim(),\n states: `\nLENS: states\nLook for missing or broken UI states — the not-happy-paths that make a product feel finished or unfinished. The iteration's captures should depict at least one non-default state.\nSignals: empty lists with no guidance, skeletons that don't match final layout (CLS on settle), error states with no message or recovery action, disabled buttons with no explanation, toasts that disappear before being read, success states that don't confirm, missing hover/focus/active/disabled variants on primary controls, no long-content view, no-permission state broken.\nNOT this lens: generic polish on the happy path (other lenses), missing focus rings specifically (\\`accessibility\\`).\nTitle format: \\`Missing/broken <state> state on <surface>\\`.\n`.trim(),\n content: `\nLENS: content\nLook for microcopy and content problems — text that is unclear, inconsistent, condescending, jargon-heavy, or wrong.\nSignals: jargon/internal language leaking (\"Provisioning a Tenant\" instead of \"Setting up your account\"), inconsistent terminology (workspace vs team), verbose button labels, empty-state copy that's just \"No results\", error messages blaming the user, tone inconsistency, truncation without affordance, mixed date/number formats on one page, placeholder used as a label, \"Saved!\" toast appearing before save completes, typos and grammar errors.\nNOT this lens: visual treatment of text (\\`hierarchy\\` / \\`consistency\\`), missing labels for a11y (\\`accessibility\\`).\nTitle format: \\`Copy: \"<actual text>\" in <location>\\` or \\`Inconsistent term: \"<A>\" vs \"<B>\"\\`.\n`.trim(),\n interaction: `\nLENS: interaction\nLook for interaction quality problems — affordances, feedback, and micro-interactions.\nSignals: no affordance (clickable areas not looking clickable, non-clickable areas looking clickable), missing feedback (>100ms click with no progress), hover surprises (whole row highlights but only title clickable), cursor inconsistency, animations that block input, missing transitions where they're needed (accordion snaps open), drag-and-drop without indicators, scroll-jacking, click-through bugs (card click handler firing alongside button), hover-only revelations on touch.\nNOT this lens: position of controls (\\`layout\\` / \\`ux-flow\\`), missing focus styles (\\`accessibility\\`).\nTitle format: \\`<Action> on <element>: <missing/wrong> feedback\\`.\n`.trim(),\n 'performance-perceived': `\nLENS: performance-perceived\nLook for perceived-performance problems — visible jank a real user would notice, not benchmark numbers. This iteration's captures should include >=2 frames during load to show shift.\nSignals: layout shift (CLS) when late-arriving images/fonts/banners settle, FOUC (flash of unstyled content), font swap jumps, late-loading hero images that shift everything, skeletons that don't match final shape, spinners on instant local actions, loading state reappearing after content paints (refetch on focus), modal open animation longer than the operation it precedes.\nNOT this lens: slow API calls (file separately), stale data after navigation (\\`states\\`).\nTitle format: \\`Layout shift / late paint on <route>: <root cause>\\`.\n`.trim(),\n other: `\nLENS: other\nUse ONLY when a finding is clearly a UI quality issue but does not fit any other lens. Strongly prefer a specific lens — \\`other\\` should be rare. Title must still be concrete.\n`.trim(),\n}\n\n/**\n * Build a system prompt for a single auditor iteration.\n *\n * @experimental\n */\nexport function buildAuditorSystemPrompt(lens: UiLens): string {\n const brief = LENS_BRIEFS[lens]\n return `${SHARED_AUDITOR_RULES}\\n\\n${brief}`\n}\n","/**\n *\n * Sandbox-event stream → UiAuditOutput decoder. The custom auditor\n * `SandboxClient` emits events of the form:\n *\n * { type: 'audit.capture', data: UiAuditCapture }\n * { type: 'audit.finding', data: UiFinding }\n * { type: 'audit.notes', data: { notes: string } }\n * { type: 'audit.lens', data: { lens: UiLens } }\n * { type: 'done', data: { tokenUsage: { ... }, totalCostUsd?: number } }\n *\n * Other event types are tolerated and ignored. The adapter is pure: it\n * folds an already-collected event array into a UiAuditOutput.\n *\n * @experimental\n */\n\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { UI_LENSES, type UiFinding, type UiLens } from './substrate'\nimport type { UiAuditCapture, UiAuditOutput } from './task'\n\n// Build the lens-validation set from the canonical UI_LENSES tuple so adding\n// a lens to the substrate automatically extends the parser; otherwise a new\n// lens would silently fail isUiLens() and parseAuditorEvents would drop\n// every event using it.\nconst KNOWN_LENS_VALUES = new Set<UiLens>(UI_LENSES)\n\nfunction isUiLens(v: unknown): v is UiLens {\n return typeof v === 'string' && KNOWN_LENS_VALUES.has(v as UiLens)\n}\n\n/** Parse raw `SandboxEvent` emissions from an audit iteration into structured `UiAuditOutput`. @experimental */\nexport function parseAuditorEvents(events: SandboxEvent[]): UiAuditOutput {\n const findings: UiFinding[] = []\n const captures: UiAuditCapture[] = []\n let lens: UiLens | undefined\n let notes: string | undefined\n\n for (const evt of events) {\n if (!evt || typeof evt !== 'object') continue\n const type = String(evt.type ?? '')\n const data =\n evt.data && typeof evt.data === 'object' ? (evt.data as Record<string, unknown>) : undefined\n if (!data) continue\n\n switch (type) {\n case 'audit.lens': {\n const v = data.lens\n if (isUiLens(v)) lens = v\n break\n }\n case 'audit.capture': {\n const cap = data as unknown as Partial<UiAuditCapture>\n if (\n typeof cap.path === 'string' &&\n typeof cap.viewport === 'string' &&\n typeof cap.fullPage === 'boolean' &&\n typeof cap.route === 'string' &&\n typeof cap.url === 'string' &&\n typeof cap.capturedAt === 'string'\n ) {\n const out: UiAuditCapture = {\n path: cap.path,\n viewport: cap.viewport,\n fullPage: cap.fullPage,\n route: cap.route,\n url: cap.url,\n capturedAt: cap.capturedAt,\n }\n if (cap.elementSelector) out.elementSelector = cap.elementSelector\n if (cap.label) out.label = cap.label\n captures.push(out)\n }\n break\n }\n case 'audit.finding': {\n const f = data as unknown as Partial<UiFinding>\n // Hard requirement: all the actionable fields must be present and\n // non-empty for a finding to enter the output. The validator does the\n // softer scoring; the adapter only filters structural junk.\n if (\n typeof f.title === 'string' &&\n f.title.trim().length > 0 &&\n isUiLens(f.lens) &&\n typeof f.severity === 'string' &&\n ['low', 'med', 'high', 'critical'].includes(f.severity) &&\n typeof f.route === 'string' &&\n typeof f.observation === 'string' &&\n typeof f.impact === 'string' &&\n typeof f.suggestedFix === 'string' &&\n Array.isArray(f.screenshots)\n ) {\n findings.push(f as UiFinding)\n }\n break\n }\n case 'audit.notes': {\n const n = data.notes\n if (typeof n === 'string' && n.trim().length > 0) notes = n\n break\n }\n default:\n // Tolerate cost/usage events and other backend chatter — extractLlmCallEvent\n // in run-loop.ts handles cost accounting upstream from the adapter.\n break\n }\n }\n\n const out: UiAuditOutput = { lens: lens ?? 'other', findings, captures }\n if (notes) out.notes = notes\n return out\n}\n","/**\n *\n * Prompt formatter for the auditor profile. `formatAuditorPrompt` produces\n * the user message handed to the iteration — describes the captures to be\n * taken and the lens to apply. The system prompt comes from\n * `buildAuditorSystemPrompt(lens)` (lens-prompts.ts).\n *\n * The formatter prepends a machine-readable envelope (`<<UI_AUDIT_TASK>>`\n * … `<<UI_AUDIT_TASK_END>>`) carrying a JSON-serialised task. The\n * in-process auditor client recovers the task from this envelope so the\n * iteration is self-describing — robust to concurrent fanout, where any\n * per-client side state (e.g. a \"current task\" register) would race.\n *\n * The formatter is pure and deterministic — re-run on the same task\n * produces the same prompt. Tests and trace replays rely on this.\n *\n * @experimental\n */\n\nimport type { UiAuditTask } from './task'\n\nconst ENVELOPE_BEGIN = '<<UI_AUDIT_TASK>>'\nconst ENVELOPE_END = '<<UI_AUDIT_TASK_END>>'\n\n/** Wrap a `UiAuditTask` in a machine-readable envelope so iterations are self-describing. @experimental */\nexport function encodeAuditTaskEnvelope(task: UiAuditTask): string {\n return `${ENVELOPE_BEGIN}${JSON.stringify(task)}${ENVELOPE_END}`\n}\n\n/**\n * Parse a task envelope back out of a prompt string. Returns undefined if\n * the prompt does not contain a complete envelope OR if the payload is\n * not valid JSON.\n *\n * @experimental\n */\nexport function decodeAuditTaskEnvelope(prompt: string): UiAuditTask | undefined {\n const start = prompt.indexOf(ENVELOPE_BEGIN)\n if (start === -1) return undefined\n const payloadStart = start + ENVELOPE_BEGIN.length\n const end = prompt.indexOf(ENVELOPE_END, payloadStart)\n if (end === -1) return undefined\n const payload = prompt.slice(payloadStart, end)\n try {\n const parsed = JSON.parse(payload) as unknown\n if (!parsed || typeof parsed !== 'object') return undefined\n const t = parsed as Partial<UiAuditTask>\n if (typeof t.lens !== 'string' || !Array.isArray(t.captures)) return undefined\n return t as UiAuditTask\n } catch {\n return undefined\n }\n}\n\n/** Produce the user message for one audit iteration: lens, captures to take, and the task envelope. @experimental */\nexport function formatAuditorPrompt(task: UiAuditTask): string {\n const lines: string[] = []\n lines.push(`# UI audit iteration — lens: ${task.lens}`)\n lines.push('')\n if (task.productContext && task.productContext.trim().length > 0) {\n lines.push('## Product context')\n lines.push(task.productContext.trim())\n lines.push('')\n }\n lines.push('## Captures to take')\n task.captures.forEach((cap, i) => {\n const vp = cap.viewport ? `${cap.viewport.width}x${cap.viewport.height}` : '1280x800 (default)'\n const detail = [\n `viewport=${vp}`,\n cap.fullPage ? 'fullPage=true' : null,\n cap.elementSelector ? `selector=\\`${cap.elementSelector}\\`` : null,\n cap.waitFor ? `waitFor=\\`${cap.waitFor}\\`` : null,\n cap.waitMs !== undefined ? `waitMs=${cap.waitMs}` : null,\n cap.label ? `label=${cap.label}` : null,\n ]\n .filter((s): s is string => s !== null)\n .join(' · ')\n lines.push(`${i + 1}. route=\\`${cap.route}\\` url=${cap.url} ${detail ? `(${detail})` : ''}`)\n })\n lines.push('')\n if (task.knownFindingIds && task.knownFindingIds.length > 0) {\n lines.push('## Known findings (link via similarTo, do not refile)')\n lines.push(task.knownFindingIds.map((n) => `#${String(n).padStart(3, '0')}`).join(', '))\n lines.push('')\n }\n lines.push('## Output format')\n lines.push(\n 'Emit a single JSON object with the shape `{ findings: UiFinding[], notes?: string }` where every finding has the fields enumerated in your system prompt. The screenshots field on each finding must reference the captures above by path. Do not emit findings outside the lens.',\n )\n return lines.join('\\n')\n}\n","/**\n *\n * Auditor validator — scores a single iteration's findings for actionability\n * and gates the iteration result. The kernel uses `valid` + `score` for\n * winner selection across fanned-out iterations and to detect a degenerate\n * iteration (lens-violating findings, no screenshot evidence, no findings\n * at all on a route where we expected some).\n *\n * Hard fails (`valid = false`):\n * - A finding is filed under a lens that does not match the iteration's\n * lens. The whole iteration is bad — the judge isn't following the\n * lens discipline and the resulting Markdown would mislead reviewers.\n * - A finding has no screenshot reference.\n * - A finding's screenshot references a path that wasn't captured in\n * this iteration.\n *\n * Score (0..1, max two decimals stable):\n * - 0.4 * specificityRatio — proportion of findings with a selector\n * - 0.4 * evidenceRatio — proportion of findings whose screenshots resolve to captures\n * - 0.2 * (1 - genericTitleRatio) — proportion of findings whose titles\n * are concrete (not \"improve UX\", \"fix layout\", etc.)\n *\n * An iteration with zero findings scores 0.5 by convention — neither a\n * confident pass nor a hard failure (the judge might just have nothing to\n * say on this lens). The driver decides what to do with it.\n *\n * @experimental\n */\n\nimport type { DefaultVerdict } from '@tangle-network/agent-eval'\nimport type { Validator } from '../../runtime/types'\nimport type { UiAuditOutput, UiAuditTask } from './task'\n\nconst GENERIC_TITLE_PATTERNS = [\n /^improve\\s/i,\n /^fix\\s/i,\n /^update\\s/i,\n /^better\\s/i,\n /^bad\\s/i,\n /^make\\s.+\\sbetter/i,\n /\\bUX\\b\\s*$/i,\n /\\bUI\\b\\s*$/i,\n]\n\nfunction isGenericTitle(title: string): boolean {\n const t = title.trim()\n if (t.length < 16) return true\n return GENERIC_TITLE_PATTERNS.some((re) => re.test(t))\n}\n\n/** Build a `Validator` that rejects off-lens findings and findings missing screenshot evidence. @experimental */\nexport function createUiAuditorValidator(task: UiAuditTask): Validator<UiAuditOutput> {\n return {\n async validate(output) {\n const findings = output.findings\n const captures = output.captures\n const capturePaths = new Set(captures.map((c) => c.path))\n\n const offLens = findings.filter((f) => f.lens !== task.lens)\n if (offLens.length > 0) {\n const verdict: DefaultVerdict = {\n valid: false,\n score: 0,\n notes: `${offLens.length} finding(s) filed under wrong lens (expected ${task.lens}; got ${offLens.map((f) => f.lens).join(', ')})`,\n scores: { offLens: 0 },\n }\n return verdict\n }\n\n const missingEvidence = findings.filter(\n (f) => !Array.isArray(f.screenshots) || f.screenshots.length === 0,\n )\n if (missingEvidence.length > 0) {\n const verdict: DefaultVerdict = {\n valid: false,\n score: 0,\n notes: `${missingEvidence.length} finding(s) have no screenshot evidence`,\n scores: { evidence: 0 },\n }\n return verdict\n }\n\n const unresolvedShot = findings.filter((f) =>\n f.screenshots.some((s) => !capturePaths.has(s.path)),\n )\n if (unresolvedShot.length > 0) {\n const verdict: DefaultVerdict = {\n valid: false,\n score: 0,\n notes: `${unresolvedShot.length} finding(s) reference screenshot paths not captured this iteration`,\n scores: { evidence: 0 },\n }\n return verdict\n }\n\n if (findings.length === 0) {\n const verdict: DefaultVerdict = {\n valid: true,\n score: 0.5,\n notes: 'No findings reported. Neither a confident pass nor a failure.',\n scores: { specificity: 0, evidence: 1, titles: 1 },\n }\n return verdict\n }\n\n const withSelector = findings.filter((f) => typeof f.selector === 'string').length\n const specificity = withSelector / findings.length\n const generic = findings.filter((f) => isGenericTitle(f.title)).length\n const titles = 1 - generic / findings.length\n // Compute evidence honestly from the data: proportion of findings whose\n // screenshots are all resolvable against this iteration's captures. The\n // guards above hard-fail when this would be < 1, so today the result is\n // always 1; if a future change relaxes those guards into a soft-fail\n // mode, this still produces a truthful evidence ratio rather than a\n // stale constant inflating the score.\n const withFullEvidence = findings.filter(\n (f) =>\n Array.isArray(f.screenshots) &&\n f.screenshots.length > 0 &&\n f.screenshots.every((s) => capturePaths.has(s.path)),\n ).length\n const evidence = withFullEvidence / findings.length\n const score = Number((0.4 * specificity + 0.4 * evidence + 0.2 * titles).toFixed(4))\n\n const verdict: DefaultVerdict = {\n valid: true,\n score,\n notes: `${findings.length} finding(s) — specificity=${specificity.toFixed(2)} evidence=${evidence.toFixed(2)} titles=${titles.toFixed(2)}`,\n scores: { specificity, evidence, titles },\n }\n return verdict\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAYA,SAAgB,QAAQ,OAAe,WAA2B;CAChE,MAAM,OAAO,MACV,YAAY,C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vB,EAAE,YAAY,OAAO,MAAM,aAAa,IAAI,EAAE,IAAI,CAAC,CACvD,CAAC,CAAC,SACkC,SAAS;EAS7C,OAAO;GALL,OAAO;GACP,OAJY,QAAQ,KAAM,cAAc,KAAM,WAAW,KAAM,OAAA,CAAQ,QAAQ,CAAC,CAI5E;GACJ,OAAO,GAAG,SAAS,OAAO,4BAA4B,YAAY,QAAQ,CAAC,EAAE,YAAY,SAAS,QAAQ,CAAC,EAAE,UAAU,OAAO,QAAQ,CAAC;GACvI,QAAQ;IAAE;IAAa;IAAU;GAAO;EAE7B;CACf,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"profiles.js","names":["fs"],"sources":["../src/profiles/ui-auditor/slugify.ts","../src/audit/issue-writer.ts","../src/profiles/researcher.ts","../src/profiles/ui-auditor/lens-prompts.ts","../src/profiles/ui-auditor/output-adapter.ts","../src/profiles/ui-auditor/prompt.ts","../src/profiles/ui-auditor/validator.ts"],"sourcesContent":["/**\n *\n * Shared slug helper used by both the in-process auditor client (for\n * screenshot filenames) and the issue writer (for issue Markdown\n * filenames). Lowercases, normalizes, strips non-alphanumeric, trims\n * dashes, caps at 80 chars. Throws when the result is empty so callers\n * never silently write to a name-less filename.\n *\n * @experimental\n */\n\n/** @experimental */\nexport function slugify(value: string, fieldName: string): string {\n const slug = value\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 80)\n if (slug.length === 0) {\n throw new Error(\n `ui-auditor: ${fieldName} slugified to empty string. Provide a non-empty value (got ${JSON.stringify(value)}).`,\n )\n }\n return slug\n}\n","/**\n *\n * UI-audit issue writer — pure I/O. Takes a workspace dir + `UiFinding[]`\n * and emits:\n * - `<workspace>/issues/NNN--<lens>--<slug>.md` — one self-contained\n * GitHub-issue-ready Markdown per finding, with embedded screenshot\n * references.\n * - `<workspace>/registry.json` — finding index for dedup and audit\n * resume across iterations.\n * - `<workspace>/index.md` — human-readable rollup (severity / lens /\n * route counts plus a sorted finding list).\n *\n * The writer is deterministic, idempotent for `appendFindings()`, and\n * never invokes an LLM. It assigns the next monotonic id to a finding the\n * caller did not pre-id.\n *\n * @experimental\n */\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { slugify } from '../profiles/ui-auditor/slugify'\nimport {\n UI_FINDING_SEVERITIES,\n UI_LENSES,\n type UiFinding,\n type UiLens,\n} from '../profiles/ui-auditor/substrate'\n\n/** @experimental */\nexport interface AuditRegistry {\n schemaVersion: 1\n findings: UiFinding[]\n /** Route → URL + captures sidecar; preserved across runs. */\n routes: Record<string, { url?: string; captures: AuditRegistryCapture[] }>\n}\n\n/** @experimental */\nexport interface AuditRegistryCapture {\n file: string\n viewport?: string\n fullPage?: boolean\n elementSelector?: string\n capturedAt: string\n}\n\nconst SEVERITY_ORDER: Record<UiFinding['severity'], number> = {\n critical: 0,\n high: 1,\n med: 2,\n low: 3,\n}\n\n// Validate workspaceDir at every public entry point. The MCP tool checks\n// the same shape at the wire boundary, but the writer is independently\n// exported via `@tangle-network/agent-runtime/profiles`, so direct callers\n// would otherwise bypass that defense. Absolute + no `..` segments matches\n// the MCP tool's contract — any path that the writer joins for I/O must be\n// rooted at a deterministic location chosen by the caller.\nfunction assertValidWorkspaceDir(dir: string): void {\n if (typeof dir !== 'string' || dir.length === 0) {\n throw new Error(\n `audit-writer: workspaceDir must be a non-empty string (got ${JSON.stringify(dir)})`,\n )\n }\n if (!path.isAbsolute(dir)) {\n throw new Error(\n `audit-writer: workspaceDir must be an absolute path (got ${JSON.stringify(dir)})`,\n )\n }\n if (dir.split(path.sep).includes('..')) {\n throw new Error(\n `audit-writer: workspaceDir must not contain '..' segments (got ${JSON.stringify(dir)})`,\n )\n }\n}\n\n/** Create the `issues/`, `screenshots/`, and `registry.json` scaffold in a new audit workspace. @experimental */\nexport async function initAuditWorkspace(workspaceDir: string): Promise<void> {\n assertValidWorkspaceDir(workspaceDir)\n await fs.mkdir(path.join(workspaceDir, 'issues'), { recursive: true })\n await fs.mkdir(path.join(workspaceDir, 'screenshots'), { recursive: true })\n const regPath = path.join(workspaceDir, 'registry.json')\n try {\n await fs.access(regPath)\n } catch {\n const fresh: AuditRegistry = { schemaVersion: 1, findings: [], routes: {} }\n await fs.writeFile(regPath, JSON.stringify(fresh, null, 2))\n }\n}\n\n/** Read and validate the `registry.json` from an audit workspace. @experimental */\nexport async function readAuditRegistry(workspaceDir: string): Promise<AuditRegistry> {\n assertValidWorkspaceDir(workspaceDir)\n const regPath = path.join(workspaceDir, 'registry.json')\n const text = await fs.readFile(regPath, 'utf8')\n const parsed = JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`audit-writer: registry.json at ${regPath} is not a JSON object`)\n }\n const reg = parsed as Partial<AuditRegistry>\n if (reg.schemaVersion !== 1 || !Array.isArray(reg.findings) || typeof reg.routes !== 'object') {\n throw new Error(`audit-writer: registry.json at ${regPath} has an unrecognized shape`)\n }\n return reg as AuditRegistry\n}\n\nasync function writeAuditRegistry(workspaceDir: string, reg: AuditRegistry): Promise<void> {\n const regPath = path.join(workspaceDir, 'registry.json')\n // Write to a sibling temp file and rename. POSIX rename is atomic, so a\n // reader at any instant sees either the pre-write OR post-write registry,\n // never a half-written file. Prevents corruption on crash mid-write.\n const tmpPath = `${regPath}.tmp-${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n await fs.writeFile(tmpPath, JSON.stringify(reg, null, 2))\n await fs.rename(tmpPath, regPath)\n}\n\n// Per-workspace serialization. The writer reads registry.json, mutates it\n// in memory, then writes it back; concurrent calls would race on the\n// monotonic-id assignment and clobber each other's findings. Each\n// workspace key holds the Promise of the most-recently-enqueued operation;\n// new operations chain off it so they run strictly serially.\nconst workspaceLocks = new Map<string, Promise<unknown>>()\n\nasync function withWorkspaceLock<T>(workspaceDir: string, fn: () => Promise<T>): Promise<T> {\n const key = path.resolve(workspaceDir)\n const prev = workspaceLocks.get(key) ?? Promise.resolve()\n let signalDone!: () => void\n const done = new Promise<void>((resolve) => {\n signalDone = resolve\n })\n workspaceLocks.set(key, done)\n try {\n await prev\n return await fn()\n } finally {\n signalDone()\n // Only delete if no later caller has overwritten the slot — preserves\n // the chain for any concurrent callers still waiting.\n if (workspaceLocks.get(key) === done) workspaceLocks.delete(key)\n }\n}\n\nfunction assertFindingShape(f: UiFinding, index: number): void {\n const where = `audit-writer: findings[${index}]`\n if (!UI_LENSES.includes(f.lens)) {\n throw new Error(\n `${where}: invalid lens ${JSON.stringify(f.lens)}; one of ${UI_LENSES.join('|')}`,\n )\n }\n if (!UI_FINDING_SEVERITIES.includes(f.severity)) {\n throw new Error(\n `${where}: invalid severity ${JSON.stringify(f.severity)}; one of ${UI_FINDING_SEVERITIES.join('|')}`,\n )\n }\n for (const field of ['title', 'route', 'observation', 'impact', 'suggestedFix'] as const) {\n const v = f[field]\n if (typeof v !== 'string' || v.trim().length === 0) {\n throw new Error(`${where}: ${field} must be a non-empty string`)\n }\n }\n if (!Array.isArray(f.screenshots) || f.screenshots.length === 0) {\n throw new Error(`${where}: screenshots must be a non-empty array`)\n }\n for (let i = 0; i < f.screenshots.length; i += 1) {\n const s = f.screenshots[i]\n if (!s || typeof s.path !== 'string' || s.path.length === 0) {\n throw new Error(`${where}.screenshots[${i}].path must be a non-empty string`)\n }\n // Defense-in-depth: screenshot paths are written verbatim into Markdown\n // and the registry; a downstream consumer that joins workspaceDir with\n // them would otherwise be exposed to traversal-read. Reject `..`\n // segments at the validation boundary.\n if (s.path.split(/[/\\\\]/).includes('..')) {\n throw new Error(`${where}.screenshots[${i}].path must not contain '..' segments`)\n }\n }\n}\n\nfunction nextFindingId(reg: AuditRegistry): number {\n let max = 0\n for (const f of reg.findings) {\n if (typeof f.id === 'number' && f.id > max) max = f.id\n }\n return max + 1\n}\n\nfunction slugifyTitle(title: string): string {\n return slugify(title, 'title')\n}\n\nfunction renderFinding(finding: UiFinding): string {\n if (!finding.id) {\n throw new Error('audit-writer: cannot render a finding without an assigned id')\n }\n if (finding.screenshots.length === 0) {\n throw new Error(`audit-writer: finding #${finding.id} has no screenshots`)\n }\n const id = finding.id\n const numStr = String(id).padStart(3, '0')\n\n const metaLines: string[] = [\n `> **Issue #${numStr}** · **Severity:** ${finding.severity} · **Lens:** ${finding.lens}`,\n `> **Route:** \\`${finding.route}\\`${finding.url ? ` · **URL:** ${finding.url}` : ''}`,\n ]\n if (finding.viewport) metaLines.push(`> **Viewport:** ${finding.viewport}`)\n if (finding.selector) metaLines.push(`> **Selector:** \\`${finding.selector}\\``)\n if (finding.tags && finding.tags.length > 0) {\n metaLines.push(`> **Tags:** ${finding.tags.map((t) => `\\`${t}\\``).join(', ')}`)\n }\n if (finding.similarTo && finding.similarTo.length > 0) {\n metaLines.push(\n `> **Possible duplicates:** ${finding.similarTo.map((n) => `#${String(n).padStart(3, '0')}`).join(', ')}`,\n )\n }\n metaLines.push(`> _Generated: ${finding.createdAt ?? new Date().toISOString()}_`)\n\n const reproSteps =\n finding.reproSteps ??\n `1. Open \\`${finding.route}\\`${finding.url ? ` (${finding.url})` : ''}\\n2. Observe the area shown in the screenshot${finding.selector ? ` (selector: \\`${finding.selector}\\`)` : ''}.`\n\n // Screenshot paths are workspace-relative; the issue file sits in\n // `<workspace>/issues/`, so we render `../<path>`.\n const evidence = finding.screenshots\n .map((s) => ``)\n .join('\\n\\n')\n\n return [\n `# [UI] ${finding.title}`,\n '',\n metaLines.join('\\n'),\n '',\n '## Observation',\n finding.observation.trim(),\n '',\n '## Why it matters',\n finding.impact.trim(),\n '',\n '## Steps to reproduce',\n reproSteps,\n '',\n '## Suggested fix',\n finding.suggestedFix.trim(),\n '',\n '## Evidence',\n evidence,\n '',\n '---',\n `<sub>Generated by agent-runtime/ui-auditor · lens=\\`${finding.lens}\\` · severity=\\`${finding.severity}\\`</sub>`,\n '',\n ].join('\\n')\n}\n\n/** @experimental */\nexport interface AppendFindingsResult {\n /** Findings with id + createdAt assigned, in input order. */\n written: UiFinding[]\n /** Workspace-relative path to each issue Markdown file, in input order. */\n files: string[]\n}\n\n/**\n * Append findings to a workspace, writing one Markdown file per finding\n * and updating registry.json. Assigns monotonically increasing ids to\n * findings that arrived without one.\n *\n * Findings already carrying an id that collides with the registry are\n * rejected — callers must either freshly mint findings (id undefined) or\n * use a separate update path. This protects against accidental overwrite.\n *\n * @experimental\n */\nexport async function appendFindings(\n workspaceDir: string,\n findings: readonly UiFinding[],\n): Promise<AppendFindingsResult> {\n assertValidWorkspaceDir(workspaceDir)\n // Validate every finding BEFORE acquiring the lock so callers see a fast\n // input-shape error without blocking concurrent writers. Validation is\n // the only defense against path traversal via crafted `lens` values\n // (the filename interpolates lens directly) and against malformed\n // Markdown from missing required fields — TypeScript types are erased\n // at runtime, so this boundary cannot trust its callers.\n for (let i = 0; i < findings.length; i += 1) {\n const f = findings[i]\n if (!f) throw new Error(`audit-writer: findings[${i}] is undefined`)\n assertFindingShape(f, i)\n }\n\n return withWorkspaceLock(workspaceDir, async () => {\n await initAuditWorkspace(workspaceDir)\n const reg = await readAuditRegistry(workspaceDir)\n const usedIds = new Set<number>()\n for (const f of reg.findings) {\n if (typeof f.id === 'number') usedIds.add(f.id)\n }\n\n const written: UiFinding[] = []\n const files: string[] = []\n let nextId = nextFindingId(reg)\n\n for (const incoming of findings) {\n let id = incoming.id\n if (id !== undefined) {\n if (usedIds.has(id)) {\n throw new Error(\n `audit-writer: incoming finding id ${id} (title=${JSON.stringify(incoming.title)}) collides with an existing registry entry`,\n )\n }\n } else {\n id = nextId\n while (usedIds.has(id)) id += 1\n nextId = id + 1\n }\n usedIds.add(id)\n\n const createdAt = incoming.createdAt ?? new Date().toISOString()\n const persisted: UiFinding = { ...incoming, id, createdAt }\n\n const slug = slugifyTitle(persisted.title)\n const fileName = `${String(id).padStart(3, '0')}--${persisted.lens}--${slug}.md`\n const filePathAbs = path.join(workspaceDir, 'issues', fileName)\n const filePathRel = `issues/${fileName}`\n\n await fs.writeFile(filePathAbs, renderFinding(persisted))\n reg.findings.push(persisted)\n written.push(persisted)\n files.push(filePathRel)\n }\n\n await writeAuditRegistry(workspaceDir, reg)\n return { written, files }\n })\n}\n\n/** @experimental */\nexport interface RegisterCapturesOptions {\n route: string\n url?: string\n captures: readonly AuditRegistryCapture[]\n}\n\n/**\n * Record screenshots taken for a route in the registry, without filing a\n * finding. Useful when the auditor wants to remember which captures\n * exist for resume / dedup purposes.\n *\n * @experimental\n */\nexport async function registerCaptures(\n workspaceDir: string,\n options: RegisterCapturesOptions,\n): Promise<void> {\n assertValidWorkspaceDir(workspaceDir)\n if (typeof options.route !== 'string' || options.route.trim().length === 0) {\n throw new Error('audit-writer: registerCaptures: route must be a non-empty string')\n }\n return withWorkspaceLock(workspaceDir, async () => {\n await initAuditWorkspace(workspaceDir)\n const reg = await readAuditRegistry(workspaceDir)\n const slot = reg.routes[options.route] ?? { captures: [] }\n if (options.url) slot.url = options.url\n slot.captures = [...slot.captures, ...options.captures]\n reg.routes[options.route] = slot\n await writeAuditRegistry(workspaceDir, reg)\n })\n}\n\n/** @experimental */\nexport interface AuditIndex {\n /** Total findings in the workspace. */\n total: number\n bySeverity: Record<UiFinding['severity'], number>\n byLens: Partial<Record<UiLens, number>>\n byRoute: Record<string, number>\n}\n\n/** Compute finding counts by severity, lens, and route from an `AuditRegistry`. @experimental */\nexport function summarizeRegistry(reg: AuditRegistry): AuditIndex {\n const bySeverity: Record<UiFinding['severity'], number> = {\n critical: 0,\n high: 0,\n med: 0,\n low: 0,\n }\n const byLens: Partial<Record<UiLens, number>> = {}\n const byRoute: Record<string, number> = {}\n for (const f of reg.findings) {\n bySeverity[f.severity] += 1\n byLens[f.lens] = (byLens[f.lens] ?? 0) + 1\n byRoute[f.route] = (byRoute[f.route] ?? 0) + 1\n }\n return { total: reg.findings.length, bySeverity, byLens, byRoute }\n}\n\n/**\n * Regenerate `<workspace>/index.md` from registry.json.\n *\n * @experimental\n */\nexport async function writeAuditIndex(workspaceDir: string): Promise<string> {\n assertValidWorkspaceDir(workspaceDir)\n const reg = await readAuditRegistry(workspaceDir)\n const summary = summarizeRegistry(reg)\n\n const sorted = [...reg.findings].sort((a, b) => {\n const sa = SEVERITY_ORDER[a.severity]\n const sb = SEVERITY_ORDER[b.severity]\n if (sa !== sb) return sa - sb\n return (a.id ?? 0) - (b.id ?? 0)\n })\n\n const lines: string[] = []\n lines.push('# UI audit index', '')\n lines.push(`_Generated: ${new Date().toISOString()}_`, '')\n lines.push(`**Total findings:** ${summary.total}`, '')\n lines.push('## By severity')\n for (const s of ['critical', 'high', 'med', 'low'] as const) {\n const n = summary.bySeverity[s] ?? 0\n if (n > 0) lines.push(`- **${s}** — ${n}`)\n }\n lines.push('', '## By lens')\n const lensEntries: [string, number][] = Object.entries(summary.byLens).map(([k, v]) => [\n k,\n v ?? 0,\n ])\n for (const [lens, n] of lensEntries.sort((a, b) => b[1] - a[1])) {\n lines.push(`- **${lens}** — ${n}`)\n }\n lines.push('', '## By route')\n const routeEntries: [string, number][] = Object.entries(summary.byRoute).map(([k, v]) => [\n k,\n v ?? 0,\n ])\n for (const [route, n] of routeEntries.sort((a, b) => b[1] - a[1])) {\n lines.push(`- \\`${route}\\` — ${n}`)\n }\n lines.push('', '## Findings', '')\n for (const f of sorted) {\n if (typeof f.id !== 'number') continue\n const num = String(f.id).padStart(3, '0')\n const slug = slugifyTitle(f.title)\n const file = `issues/${num}--${f.lens}--${slug}.md`\n lines.push(`- [#${num} \\`${f.severity}\\` \\`${f.lens}\\` \\`${f.route}\\` — ${f.title}](${file})`)\n }\n lines.push('')\n\n const out = path.join(workspaceDir, 'index.md')\n const body = lines.join('\\n')\n await fs.writeFile(out, body)\n return out\n}\n","/**\n * Opinionated preset for source-grounded research\n * tasks. The agent is told to:\n * - bound its work to a single `knowledgeNamespace`\n * - emit `items[]` carrying provenance + confidence\n * - emit `citations[]` linking quotes back to source urls\n * - emit `proposedWrites[]` — never call materialize itself\n * - describe `gaps` it could not answer\n *\n * The profile is stateless and agent-agnostic. The caller supplies the exact execution profile;\n * this preset adds only the researcher prompt, tools, parser, and validator.\n *\n * Propose-don't-apply: the profile NEVER writes to the knowledge base.\n * It produces `proposedWrites: KnowledgeUpdate[]` in the output. The\n * caller (gtm-agent, journey-eval, user) decides whether to feed those\n * updates through `applyKnowledgeWriteBlocks` / a KbStore put.\n *\n * Namespace isolation: every `KnowledgeItem` + `KnowledgeUpdate` in the\n * output carries `namespace`. The validator hard-fails when any item\n * touches a namespace other than `task.knowledgeNamespace`.\n *\n * @experimental\n */\n\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ConfigError } from '../errors'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type {\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n OutputAdapter,\n Validator,\n} from '../runtime/types'\n\n/** Source families a researcher profile may prefer for a task. One owner: the delegation\n * vocabulary (`DelegateResearchArgs.sources`) re-exports this type rather than restating it.\n * @experimental */\nexport type ResearchSource = 'web' | 'corpus' | 'twitter' | 'github' | 'docs'\n\n/** Task contract for a source-grounded research agent. @experimental */\nexport interface ResearchTask {\n /** The research question to answer. */\n question: string\n /** Bound: e.g. \"audience for cpg-founder ICP\". */\n scope?: string\n /** Multi-tenant scope (customer-id, workspace-id). Validator enforces. */\n knowledgeNamespace: string\n sources?: ResearchSource[]\n recencyWindow?: { since?: Date; until?: Date }\n maxItems?: number\n /** Per-item minimum confidence in [0, 1]. Validator scores recall vs this. */\n minConfidence?: number\n}\n\n/**\n * Knowledge item emitted by the researcher.\n *\n * Profile-local type. When agent-knowledge promotes `KnowledgeClaim` →\n * top-level `KnowledgeItem` substrate-wide, these fields collapse 1:1.\n *\n * @experimental\n */\nexport interface KnowledgeItem {\n id: string\n /** Multi-tenant scope. MUST equal `task.knowledgeNamespace`. */\n namespace: string\n /** The factual claim, in the researcher's words. */\n claim: string\n /** Provenance — at least one entry required. */\n evidence: Array<{ source: string; quote?: string; url?: string; capturedAt: number }>\n /** Researcher's self-reported confidence in [0, 1]. */\n confidence: number\n /** Prior item ids this supersedes (chain). */\n supersedes?: string[]\n /** Set if the agent is retracting an earlier item. Unix ms. */\n retractedAt?: number\n authoredBy: { kind: 'human' | 'agent'; id: string }\n}\n\n/**\n * A proposed write to the knowledge base. The profile does NOT apply\n * these — the caller decides.\n *\n * @experimental\n */\nexport type KnowledgeUpdate =\n | { kind: 'insert'; namespace: string; item: KnowledgeItem }\n | { kind: 'supersede'; namespace: string; previousId: string; item: KnowledgeItem }\n | { kind: 'retract'; namespace: string; itemId: string; reason: string }\n\n/**\n * Researcher output. Required fields are typed; optional fields preserve\n * the agent's free-form intelligence (`notes`, `raw`). The validator\n * enforces the typed minimum.\n *\n * @experimental\n */\nexport interface ResearchOutput {\n items: KnowledgeItem[]\n citations: Array<{ url: string; quote: string; confidence: number }>\n proposedWrites: KnowledgeUpdate[]\n gaps?: string[]\n notes?: string\n /** Anything the agent emitted beyond the typed fields. */\n raw?: unknown\n}\n\n/** Options for the source-grounded researcher profile preset. @experimental */\nexport interface ResearcherProfileOptions {\n /** Caller-owned exact harness/provider/model identity. */\n profile: AgentProfile\n /** Custom system prompt replacement. Default = built-in researcher preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `profile.name`. */\n name?: string\n /**\n * Default 0.7. Minimum (citations with quote) / items ratio for `valid=true`.\n * Below this floor, citation_density scores < 1 and the item set is gated.\n */\n citationDensityMin?: number\n}\n\nconst DEFAULT_CITATION_DENSITY_MIN = 0.7\n\n/** Build a source-grounded researcher profile with output parsing and validation. @experimental */\nexport function researcherProfile(options: ResearcherProfileOptions & { task?: ResearchTask }): {\n profile: AgentProfile\n taskToPrompt: (task: ResearchTask) => string\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n agentRunSpec: AgentRunSpec<ResearchTask>\n} {\n const base = agentProfileSchema.parse(options.profile) as AgentProfile\n assertExecutableAgentProfile(base, 'researcherProfile')\n const name = options.name ?? base.name\n const systemPrompt = options.systemPrompt ?? RESEARCHER_SYSTEM_PROMPT\n const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const profile: AgentProfile = {\n ...base,\n name,\n description: base.description ?? \"Source-grounded research agent. Propose-don't-apply.\",\n prompt: { ...base.prompt, systemPrompt },\n tools: { web_search: true, fs: true, shell: true, ...base.tools },\n metadata: { ...base.metadata, specialty: 'researcher' },\n }\n const output: OutputAdapter<ResearchOutput> = { parse: parseResearcherEvents }\n const validator: Validator<ResearchOutput> = options.task\n ? createResearcherValidator(options.task, { citationDensityMin })\n : createResearcherValidator(\n { question: '', knowledgeNamespace: '' },\n { citationDensityMin, namespaceCheck: false },\n )\n const agentRunSpec: AgentRunSpec<ResearchTask> = {\n name,\n profile,\n taskToPrompt: formatResearcherPrompt,\n }\n return { profile, taskToPrompt: formatResearcherPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessResearcherFanoutOptions {\n /** Exact execution profiles, one per parallel researcher. */\n profiles: ReadonlyArray<AgentProfile>\n /** Default citation density floor for the shared validator. */\n citationDensityMin?: number\n /** Optional task — narrows the validator's namespace check. */\n task?: ResearchTask\n}\n\n/**\n * Build a fanout topology over multiple harnesses. The kernel round-robins\n * `agentRuns` across the N parallel iterations and the `FanoutVote` driver\n * picks the highest-scoring valid output.\n *\n * @experimental\n */\nexport function multiHarnessResearcherFanout(options: MultiHarnessResearcherFanoutOptions): {\n agentRuns: AgentRunSpec<ResearchTask>[]\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n driver: Driver<ResearchTask, ResearchOutput, 'done'>\n} {\n if (options.profiles.length === 0) {\n throw new ConfigError('multiHarnessResearcherFanout: at least one exact profile is required')\n }\n const agentRuns = options.profiles.map((profile) => {\n const { agentRunSpec } = researcherProfile({ profile })\n return agentRunSpec\n })\n const { output, validator } = researcherProfile({\n profile: options.profiles[0]!,\n citationDensityMin: options.citationDensityMin,\n task: options.task,\n })\n // Single fanout round across the N harnesses, then stop: the kernel\n // round-robins `agentRuns` over the N branches and selects the winner\n // (best valid score) across all iterations via `defaultSelectWinner`.\n const driver: Driver<ResearchTask, ResearchOutput, 'done'> = {\n name: 'researcher-fanout',\n async plan(task, history) {\n return history.length === 0 ? Array.from({ length: agentRuns.length }, () => task) : []\n },\n // 'done' is a terminal decision in the kernel; the loop finalizes after\n // the single fanout round and selects the winner via `defaultSelectWinner`.\n decide() {\n return 'done'\n },\n describePlan() {\n return { kind: 'fanout' }\n },\n }\n return { agentRuns, output, validator, driver }\n}\n\n/**\n * Build a validator that closes over a specific `ResearchTask`'s constraints.\n *\n * Checks in order:\n * 1. Items must be non-empty.\n * 2. Every item carries `evidence.length >= 1`.\n * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`\n * (hard-fail on any namespace mismatch — defence in depth for the\n * multi-tenant invariant).\n * 4. Citation density (citations with quote / items) >= floor.\n *\n * Aggregate score:\n * 0.4 · citation_density\n * + 0.2 · source_diversity (distinct sources / max(items, 1))\n * + 0.2 · recency_match (mean fraction within `recencyWindow`)\n * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)\n *\n * @experimental\n */\nexport function createResearcherValidator(\n task: ResearchTask,\n config: { citationDensityMin?: number; namespaceCheck?: boolean } = {},\n): Validator<ResearchOutput> {\n const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const namespaceCheck = config.namespaceCheck ?? true\n return {\n async validate(output) {\n const notes: string[] = []\n const scores: Record<string, number> = {}\n let pass = true\n\n if (!Array.isArray(output.items) || output.items.length === 0) {\n pass = false\n notes.push('no items')\n scores.items = 0\n } else {\n scores.items = 1\n }\n\n const missingEvidence = (output.items ?? []).filter(\n (item) => !Array.isArray(item.evidence) || item.evidence.length === 0,\n )\n if (missingEvidence.length > 0) {\n pass = false\n notes.push(`${missingEvidence.length} item(s) without evidence`)\n scores.provenance = 0\n } else {\n scores.provenance = 1\n }\n\n if (namespaceCheck) {\n const foreignItems = (output.items ?? []).filter(\n (item) => item.namespace !== task.knowledgeNamespace,\n )\n const foreignWrites = (output.proposedWrites ?? []).filter(\n (write) => write.namespace !== task.knowledgeNamespace,\n )\n if (foreignItems.length > 0 || foreignWrites.length > 0) {\n pass = false\n notes.push(\n `namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) ` +\n `outside ${task.knowledgeNamespace}`,\n )\n scores.namespace = 0\n } else {\n scores.namespace = 1\n }\n }\n\n const itemCount = Math.max(output.items?.length ?? 0, 1)\n const citationsWithQuote = (output.citations ?? []).filter(\n (citation) => typeof citation.quote === 'string' && citation.quote.length > 0,\n ).length\n const citationDensity = Math.min(1, citationsWithQuote / itemCount)\n if (citationDensity < citationDensityMin) {\n pass = false\n notes.push(\n `citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`,\n )\n }\n scores.citation_density = citationDensity\n\n const sourceSet = new Set<string>()\n for (const item of output.items ?? []) {\n for (const evidence of item.evidence ?? []) {\n if (evidence.source) sourceSet.add(evidence.source)\n }\n }\n scores.source_diversity = Math.min(1, sourceSet.size / itemCount)\n\n scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow)\n\n const maxGaps = itemCount\n const gapCount = output.gaps?.length ?? 0\n scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps)\n\n const score =\n 0.4 * scores.citation_density +\n 0.2 * scores.source_diversity +\n 0.2 * scores.recency_match +\n 0.2 * scores.gap_coverage\n\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n },\n }\n}\n\nfunction recencyMatchScore(items: KnowledgeItem[], window: ResearchTask['recencyWindow']): number {\n if (!window || (window.since === undefined && window.until === undefined)) return 1\n if (items.length === 0) return 0\n const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY\n const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY\n let hits = 0\n let total = 0\n for (const item of items) {\n for (const evidence of item.evidence ?? []) {\n if (typeof evidence.capturedAt !== 'number') continue\n total += 1\n if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1\n }\n }\n return total === 0 ? 0 : hits / total\n}\n\n/** Built-in source-grounded research contract added to a caller-owned exact profile. */\nexport const RESEARCHER_SYSTEM_PROMPT = [\n 'You are a research agent. Your job is to answer a research question with',\n 'source-grounded knowledge items that the caller will choose whether to',\n 'persist to a multi-tenant knowledge base.',\n '',\n 'Hard rules:',\n \" 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.\",\n ' Never write to a different namespace.',\n ' 2. Every item MUST carry at least one evidence entry with a source.',\n ' A quote + url is strongly preferred; capturedAt is unix ms.',\n ' 3. You propose writes — you do NOT apply them. The caller decides.',\n ' 4. Self-report confidence honestly in [0, 1]. Do not inflate.',\n ' 5. List what you could not answer in `gaps`. Better to admit a gap',\n ' than fabricate.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",',\n ' \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",',\n ' \"url\": \"...\", \"capturedAt\": 0 }],',\n ' \"confidence\": 0.0,',\n ' \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],',\n ' \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],',\n ' \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",',\n ' \"item\": { /* same shape as items[] */ } }],',\n ' \"gaps\": [\"...\"],',\n ' \"notes\": \"free-form commentary\" }',\n ' ```',\n].join('\\n')\n\nfunction formatResearcherPrompt(task: ResearchTask): string {\n const sources = task.sources?.length ? task.sources.join(', ') : '(no preference)'\n const window = formatRecencyWindow(task.recencyWindow)\n return [\n `Question: ${task.question}`,\n `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,\n `Scope: ${task.scope ?? '(unspecified)'}`,\n `Preferred sources: ${sources}`,\n `Recency window: ${window}`,\n `Max items: ${task.maxItems ?? '(no cap)'}`,\n `Per-item minimum confidence: ${task.minConfidence ?? '(no floor)'}`,\n '',\n 'Produce knowledge items with provenance + citations + proposed writes.',\n 'List gaps for anything you could not answer. Emit the final JSON',\n 'result block exactly as instructed.',\n ].join('\\n')\n}\n\nfunction formatRecencyWindow(window: ResearchTask['recencyWindow']): string {\n if (!window) return '(none)'\n const since = window.since ? window.since.toISOString() : '-∞'\n const until = window.until ? window.until.toISOString() : 'now'\n return `${since} .. ${until}`\n}\n\n/**\n * Walk the event stream and return the last structured `research.result`\n * payload. Falls back to scanning text deltas for a fenced JSON block.\n */\nfunction parseResearcherEvents(events: SandboxEvent[]): ResearchOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'research.result') {\n const direct = coerceResearchOutput(data.result ?? data.output ?? data)\n // opencode reports the agent's terminal answer in `finalText` (not result/output).\n // Parse it too, and prefer it when `direct` is an all-empty shape — otherwise an\n // event carrying both `{items:[],citations:[],proposedWrites:[]}` and a rich\n // finalText would silently drop the real answer.\n const finalText = pickString(data.finalText)\n const fenced = finalText ? extractFencedJson(finalText) : undefined\n const fromFinalText = fenced ? coerceResearchOutput(fenced) : undefined\n if (direct && !isEmptyOutput(direct)) return direct\n if (fromFinalText) return fromFinalText\n if (direct) return direct\n }\n }\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText)\n if (!text) continue\n const fenced = extractFencedJson(text)\n if (!fenced) continue\n const coerced = coerceResearchOutput(fenced)\n if (coerced) return coerced\n }\n return { items: [], citations: [], proposedWrites: [] }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** A coerced output that carries no items, citations, or proposed writes. */\nfunction isEmptyOutput(o: ResearchOutput): boolean {\n return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n if (!match) return undefined\n const body = (match[1] ?? '').trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction coerceResearchOutput(value: unknown): ResearchOutput | undefined {\n if (!isRecord(value)) return undefined\n const items = coerceItems(value.items)\n const citations = coerceCitations(value.citations)\n const proposedWrites = coerceProposedWrites(value.proposedWrites)\n // Reject completely empty payloads — those signal \"no result block\",\n // not \"a valid empty result\".\n if (items === undefined && citations === undefined && proposedWrites === undefined) {\n return undefined\n }\n const output: ResearchOutput = {\n items: items ?? [],\n citations: citations ?? [],\n proposedWrites: proposedWrites ?? [],\n }\n if (Array.isArray(value.gaps)) {\n output.gaps = value.gaps.filter((entry): entry is string => typeof entry === 'string')\n }\n const notes = pickString(value.notes)\n if (notes) output.notes = notes\n // Preserve any extra fields the agent emitted that don't fit the typed\n // surface — callers can inspect `raw` without forcing them through the\n // typed coercion. We only include `raw` when the agent emitted fields\n // beyond the known set.\n const known = new Set(['items', 'citations', 'proposedWrites', 'gaps', 'notes'])\n const extras: Record<string, unknown> = {}\n let extrasCount = 0\n for (const [key, val] of Object.entries(value)) {\n if (known.has(key)) continue\n extras[key] = val\n extrasCount += 1\n }\n if (extrasCount > 0) output.raw = extras\n return output\n}\n\nfunction coerceItems(value: unknown): KnowledgeItem[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeItem[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const id = pickString(entry.id)\n const namespace = pickString(entry.namespace)\n const claim = pickString(entry.claim)\n const evidence = coerceEvidence(entry.evidence)\n const confidence = toFiniteNumber(entry.confidence)\n const authoredBy = coerceAuthoredBy(entry.authoredBy)\n if (!id || !namespace || !claim || !authoredBy) continue\n const item: KnowledgeItem = {\n id,\n namespace,\n claim,\n evidence,\n confidence: clamp01(confidence),\n authoredBy,\n }\n if (Array.isArray(entry.supersedes)) {\n item.supersedes = entry.supersedes.filter((s): s is string => typeof s === 'string')\n }\n const retractedAt = toFiniteNumber(entry.retractedAt)\n if (retractedAt > 0) item.retractedAt = retractedAt\n out.push(item)\n }\n return out\n}\n\nfunction coerceEvidence(value: unknown): KnowledgeItem['evidence'] {\n if (!Array.isArray(value)) return []\n const out: KnowledgeItem['evidence'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const source = pickString(entry.source)\n if (!source) continue\n const item: KnowledgeItem['evidence'][number] = {\n source,\n capturedAt: toFiniteNumber(entry.capturedAt),\n }\n const quote = pickString(entry.quote)\n if (quote) item.quote = quote\n const url = pickString(entry.url)\n if (url) item.url = url\n out.push(item)\n }\n return out\n}\n\nfunction coerceAuthoredBy(value: unknown): KnowledgeItem['authoredBy'] | undefined {\n if (!isRecord(value)) return undefined\n const kind = value.kind === 'human' || value.kind === 'agent' ? value.kind : undefined\n const id = pickString(value.id)\n if (!kind || !id) return undefined\n return { kind, id }\n}\n\nfunction coerceCitations(value: unknown): ResearchOutput['citations'] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: ResearchOutput['citations'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const url = pickString(entry.url)\n const quote = pickString(entry.quote)\n if (!url || !quote) continue\n out.push({ url, quote, confidence: clamp01(toFiniteNumber(entry.confidence)) })\n }\n return out\n}\n\nfunction coerceProposedWrites(value: unknown): KnowledgeUpdate[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeUpdate[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const namespace = pickString(entry.namespace)\n if (!namespace) continue\n if (entry.kind === 'insert') {\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!item) continue\n out.push({ kind: 'insert', namespace, item })\n } else if (entry.kind === 'supersede') {\n const previousId = pickString(entry.previousId)\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!previousId || !item) continue\n out.push({ kind: 'supersede', namespace, previousId, item })\n } else if (entry.kind === 'retract') {\n const itemId = pickString(entry.itemId)\n const reason = pickString(entry.reason)\n if (!itemId || !reason) continue\n out.push({ kind: 'retract', namespace, itemId, reason })\n }\n }\n return out\n}\n\nfunction toFiniteNumber(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n if (value < 0) return 0\n if (value > 1) return 1\n return value\n}\n","/**\n *\n * Per-lens guidance the auditor inlines into its system prompt for an\n * iteration. Each entry is a self-contained brief — the same content the\n * standalone ui-issue-finder skill ships, embedded as a string constant so\n * agent-runtime carries no runtime dep on that external workspace.\n *\n * Briefs are deliberately concrete: they enumerate the SIGNALS to look for\n * and the cross-lens distinctions to respect, so the judge files fewer\n * pile-on findings under generic labels.\n *\n * @experimental\n */\n\nimport type { UiLens } from './substrate'\n\n/** Cross-lens rules injected into every UI audit iteration: finding quality standards and scope limits. @experimental */\nexport const SHARED_AUDITOR_RULES = `\nYou are auditing a UI for a specific class of problems. Stay strictly in your assigned lens — do not file issues that belong to another lens (a separate iteration will catch those).\n\nA finding is only valid if a thoughtful product designer would agree the screenshot shows something that should change. Avoid:\n- Personal taste (\"I'd prefer brand blue\").\n- Hallucinated text or controls you cannot actually see in the screenshot.\n- Suggestions that depend on requirements you don't have access to.\n- Pile-on findings about the same root cause — file ONE finding and use \\`similarTo\\` to link the rest.\n\nRequired for every finding:\n- title: concrete, names the offending element AND what's wrong (NOT \"improve UX\").\n- severity: critical=blocks a core task or accessibility blocker; high=noticeable friction; med=visible polish issue; low=nitpick.\n- observation: 1–3 sentences describing exactly what you see that is wrong.\n- impact: who is affected and how (concrete).\n- suggestedFix: a specific change a developer could apply without asking you back.\n- screenshots: refer to the captures attached to this iteration by path.\n- selector: when you can pin the offending element with a CSS selector.\n\nMost findings are med or low. Reserve high/critical for genuine blockers.\n`.trim()\n\n/** Per-lens auditor briefs: concrete signals to look for and cross-lens distinctions to respect. @experimental */\nexport const LENS_BRIEFS: Record<UiLens, string> = {\n consistency: `\nLENS: consistency\nLook for inconsistencies in the design system — things that look like they came from different products glued together.\nSignals: multiple font families, inconsistent weights/sizes for the same role, two shades of \"primary\", arbitrary paddings/margins that don't snap to a scale (4/8/12/16/24), same control with different border-radius or shadow on different pages, mixed icon styles (filled vs outlined), inconsistent button heights/padding for the same variant, inconsistent capitalization (Title Case vs sentence case) for the same role.\nNOT this lens: layout misalignment (use \\`layout\\`), confusing user flow (use \\`ux-flow\\`), contrast/keyboard issues (use \\`accessibility\\`).\nTitle format: \\`Inconsistent <thing> between <A> and <B>\\`.\n`.trim(),\n hierarchy: `\nLENS: hierarchy\nLook for broken visual hierarchy — places where the eye does not land on what matters most.\nSignals: primary CTA same weight as secondary/tertiary controls, headings (H1/H2/H3) nearly the same size, important data buried (headline number smaller than its label), decoration outshining content, too many emphases competing, wrong scan order, missing or overly heavy section dividers.\nNOT this lens: same-role styled differently (\\`consistency\\`), grid/alignment (\\`layout\\`), contrast-failing text (\\`accessibility\\`).\nTitle format: \\`Weak hierarchy: <element> does not read as the <intended-role>\\`.\n`.trim(),\n layout: `\nLENS: layout\nLook for layout and organization problems — alignment, grouping, whitespace, structural choices that hurt scannability.\nSignals: misalignment within rows, inconsistent gutters in grids, orphan whitespace next to crammed regions, poor grouping (related fields separated, unrelated fields adjacent), no visual sections (long wall of content), container overflow (text/content punching out of card boundaries), cramped or oversized hit targets, sidebars/headers sized wrong relative to main content.\nNOT this lens: same-role styled differently (\\`consistency\\`), click-distance/friction (\\`ux-flow\\`), overflow specifically at small viewports (\\`responsive\\`).\nTitle format: \\`<Region> alignment/spacing problem\\` or \\`<Region> grouping unclear\\`.\n`.trim(),\n 'ux-flow': `\nLENS: ux-flow\nLook for interaction-flow friction — action sequences that are slower, more annoying, or more error-prone than necessary.\nSignals: sequential clicks far apart (e.g. Next top-right while user is bottom-left), destructive action adjacent to primary with same weight, confirmations that don't say what's being confirmed, primary CTA below the fold or hidden in a kebab menu, silent state changes (toggle gives no feedback), form ordering that fights real-world order, dead-end states after submit, lost inputs on back-navigation, hidden pre-selected options.\nNOT this lens: visual style only (\\`consistency\\`), component arrangement without a flow problem (\\`layout\\`), microcopy clarity (\\`content\\`).\nTitle format: \\`<Action A> → <Action B> friction: <root cause>\\`.\n`.trim(),\n duplication: `\nLENS: duplication\nLook for redundancy — the same control, link, or piece of content appearing more than once with no good reason.\nSignals: two ways to do the same action on the same screen with no difference, repeated nav (same links in sidebar AND top nav), drifted duplicates (two copies that have diverged), content repeated verbatim, icon + label saying the same thing twice in one row, per-row + bulk actions that overlap confusingly, multiple status indicators conveying the same status.\nNOT this lens: inconsistent styling of duplicates (\\`consistency\\`) — this lens is about the existence of duplicates.\nTitle format: \\`Duplicate <thing> in <location A> and <location B>\\`.\n`.trim(),\n accessibility: `\nLENS: accessibility\nLook for accessibility blockers and degradations. Be conservative — do not assume violations you cannot see.\nSignals: insufficient contrast on body text or controls, missing/invisible focus styles, tiny tap targets (<24px on mobile), color as sole signal (red border with no message), form labels missing or not associated (placeholders standing in for labels), broken heading order (H1 → H4), modals that don't trap focus, decorative elements that take focus, errors not announced, important text rendered inside images.\nNOT this lens: generic \"looks confusing\" (\\`hierarchy\\` or \\`content\\`), layout overflow at small viewports (\\`responsive\\`).\nTitle format: \\`Accessibility: <specific blocker> in <element>\\`.\n`.trim(),\n responsive: `\nLENS: responsive\nLook for layout breakage across viewport sizes — content that works at one width but degrades at another. This iteration's captures should include the same surface at >=2 viewports; compare across them.\nSignals: horizontal scroll where content should reflow, overlapping elements (header overlaps content, fixed footer covers inputs), desktop nav crammed into mobile without collapsing, table columns that don't truncate, tap targets too close at touch sizes, controls vanishing at certain widths, layout flips that break grouping order, modals exceeding viewport height (confirm button unreachable).\nNOT this lens: issues present at every viewport (\\`consistency\\` / \\`hierarchy\\` instead).\nTitle format: \\`<Element/Region> breaks at <viewport>\\`.\n`.trim(),\n states: `\nLENS: states\nLook for missing or broken UI states — the not-happy-paths that make a product feel finished or unfinished. The iteration's captures should depict at least one non-default state.\nSignals: empty lists with no guidance, skeletons that don't match final layout (CLS on settle), error states with no message or recovery action, disabled buttons with no explanation, toasts that disappear before being read, success states that don't confirm, missing hover/focus/active/disabled variants on primary controls, no long-content view, no-permission state broken.\nNOT this lens: generic polish on the happy path (other lenses), missing focus rings specifically (\\`accessibility\\`).\nTitle format: \\`Missing/broken <state> state on <surface>\\`.\n`.trim(),\n content: `\nLENS: content\nLook for microcopy and content problems — text that is unclear, inconsistent, condescending, jargon-heavy, or wrong.\nSignals: jargon/internal language leaking (\"Provisioning a Tenant\" instead of \"Setting up your account\"), inconsistent terminology (workspace vs team), verbose button labels, empty-state copy that's just \"No results\", error messages blaming the user, tone inconsistency, truncation without affordance, mixed date/number formats on one page, placeholder used as a label, \"Saved!\" toast appearing before save completes, typos and grammar errors.\nNOT this lens: visual treatment of text (\\`hierarchy\\` / \\`consistency\\`), missing labels for a11y (\\`accessibility\\`).\nTitle format: \\`Copy: \"<actual text>\" in <location>\\` or \\`Inconsistent term: \"<A>\" vs \"<B>\"\\`.\n`.trim(),\n interaction: `\nLENS: interaction\nLook for interaction quality problems — affordances, feedback, and micro-interactions.\nSignals: no affordance (clickable areas not looking clickable, non-clickable areas looking clickable), missing feedback (>100ms click with no progress), hover surprises (whole row highlights but only title clickable), cursor inconsistency, animations that block input, missing transitions where they're needed (accordion snaps open), drag-and-drop without indicators, scroll-jacking, click-through bugs (card click handler firing alongside button), hover-only revelations on touch.\nNOT this lens: position of controls (\\`layout\\` / \\`ux-flow\\`), missing focus styles (\\`accessibility\\`).\nTitle format: \\`<Action> on <element>: <missing/wrong> feedback\\`.\n`.trim(),\n 'performance-perceived': `\nLENS: performance-perceived\nLook for perceived-performance problems — visible jank a real user would notice, not benchmark numbers. This iteration's captures should include >=2 frames during load to show shift.\nSignals: layout shift (CLS) when late-arriving images/fonts/banners settle, FOUC (flash of unstyled content), font swap jumps, late-loading hero images that shift everything, skeletons that don't match final shape, spinners on instant local actions, loading state reappearing after content paints (refetch on focus), modal open animation longer than the operation it precedes.\nNOT this lens: slow API calls (file separately), stale data after navigation (\\`states\\`).\nTitle format: \\`Layout shift / late paint on <route>: <root cause>\\`.\n`.trim(),\n other: `\nLENS: other\nUse ONLY when a finding is clearly a UI quality issue but does not fit any other lens. Strongly prefer a specific lens — \\`other\\` should be rare. Title must still be concrete.\n`.trim(),\n}\n\n/**\n * Build a system prompt for a single auditor iteration.\n *\n * @experimental\n */\nexport function buildAuditorSystemPrompt(lens: UiLens): string {\n const brief = LENS_BRIEFS[lens]\n return `${SHARED_AUDITOR_RULES}\\n\\n${brief}`\n}\n","/**\n *\n * Sandbox-event stream → UiAuditOutput decoder. The custom auditor\n * `SandboxClient` emits events of the form:\n *\n * { type: 'audit.capture', data: UiAuditCapture }\n * { type: 'audit.finding', data: UiFinding }\n * { type: 'audit.notes', data: { notes: string } }\n * { type: 'audit.lens', data: { lens: UiLens } }\n * { type: 'done', data: { tokenUsage: { ... }, totalCostUsd?: number } }\n *\n * Other event types are tolerated and ignored. The adapter is pure: it\n * folds an already-collected event array into a UiAuditOutput.\n *\n * @experimental\n */\n\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { UI_LENSES, type UiFinding, type UiLens } from './substrate'\nimport type { UiAuditCapture, UiAuditOutput } from './task'\n\n// Build the lens-validation set from the canonical UI_LENSES tuple so adding\n// a lens to the substrate automatically extends the parser; otherwise a new\n// lens would silently fail isUiLens() and parseAuditorEvents would drop\n// every event using it.\nconst KNOWN_LENS_VALUES = new Set<UiLens>(UI_LENSES)\n\nfunction isUiLens(v: unknown): v is UiLens {\n return typeof v === 'string' && KNOWN_LENS_VALUES.has(v as UiLens)\n}\n\n/** Parse raw `SandboxEvent` emissions from an audit iteration into structured `UiAuditOutput`. @experimental */\nexport function parseAuditorEvents(events: SandboxEvent[]): UiAuditOutput {\n const findings: UiFinding[] = []\n const captures: UiAuditCapture[] = []\n let lens: UiLens | undefined\n let notes: string | undefined\n\n for (const evt of events) {\n if (!evt || typeof evt !== 'object') continue\n const type = String(evt.type ?? '')\n const data =\n evt.data && typeof evt.data === 'object' ? (evt.data as Record<string, unknown>) : undefined\n if (!data) continue\n\n switch (type) {\n case 'audit.lens': {\n const v = data.lens\n if (isUiLens(v)) lens = v\n break\n }\n case 'audit.capture': {\n const cap = data as unknown as Partial<UiAuditCapture>\n if (\n typeof cap.path === 'string' &&\n typeof cap.viewport === 'string' &&\n typeof cap.fullPage === 'boolean' &&\n typeof cap.route === 'string' &&\n typeof cap.url === 'string' &&\n typeof cap.capturedAt === 'string'\n ) {\n const out: UiAuditCapture = {\n path: cap.path,\n viewport: cap.viewport,\n fullPage: cap.fullPage,\n route: cap.route,\n url: cap.url,\n capturedAt: cap.capturedAt,\n }\n if (cap.elementSelector) out.elementSelector = cap.elementSelector\n if (cap.label) out.label = cap.label\n captures.push(out)\n }\n break\n }\n case 'audit.finding': {\n const f = data as unknown as Partial<UiFinding>\n // Hard requirement: all the actionable fields must be present and\n // non-empty for a finding to enter the output. The validator does the\n // softer scoring; the adapter only filters structural junk.\n if (\n typeof f.title === 'string' &&\n f.title.trim().length > 0 &&\n isUiLens(f.lens) &&\n typeof f.severity === 'string' &&\n ['low', 'med', 'high', 'critical'].includes(f.severity) &&\n typeof f.route === 'string' &&\n typeof f.observation === 'string' &&\n typeof f.impact === 'string' &&\n typeof f.suggestedFix === 'string' &&\n Array.isArray(f.screenshots)\n ) {\n findings.push(f as UiFinding)\n }\n break\n }\n case 'audit.notes': {\n const n = data.notes\n if (typeof n === 'string' && n.trim().length > 0) notes = n\n break\n }\n default:\n // Tolerate cost/usage events and other backend chatter — extractLlmCallEvent\n // in run-loop.ts handles cost accounting upstream from the adapter.\n break\n }\n }\n\n const out: UiAuditOutput = { lens: lens ?? 'other', findings, captures }\n if (notes) out.notes = notes\n return out\n}\n","/**\n *\n * Prompt formatter for the auditor profile. `formatAuditorPrompt` produces\n * the user message handed to the iteration — describes the captures to be\n * taken and the lens to apply. The system prompt comes from\n * `buildAuditorSystemPrompt(lens)` (lens-prompts.ts).\n *\n * The formatter prepends a machine-readable envelope (`<<UI_AUDIT_TASK>>`\n * … `<<UI_AUDIT_TASK_END>>`) carrying a JSON-serialised task. The\n * in-process auditor client recovers the task from this envelope so the\n * iteration is self-describing — robust to concurrent fanout, where any\n * per-client side state (e.g. a \"current task\" register) would race.\n *\n * The formatter is pure and deterministic — re-run on the same task\n * produces the same prompt. Tests and trace replays rely on this.\n *\n * @experimental\n */\n\nimport type { UiAuditTask } from './task'\n\nconst ENVELOPE_BEGIN = '<<UI_AUDIT_TASK>>'\nconst ENVELOPE_END = '<<UI_AUDIT_TASK_END>>'\n\n/** Wrap a `UiAuditTask` in a machine-readable envelope so iterations are self-describing. @experimental */\nexport function encodeAuditTaskEnvelope(task: UiAuditTask): string {\n return `${ENVELOPE_BEGIN}${JSON.stringify(task)}${ENVELOPE_END}`\n}\n\n/**\n * Parse a task envelope back out of a prompt string. Returns undefined if\n * the prompt does not contain a complete envelope OR if the payload is\n * not valid JSON.\n *\n * @experimental\n */\nexport function decodeAuditTaskEnvelope(prompt: string): UiAuditTask | undefined {\n const start = prompt.indexOf(ENVELOPE_BEGIN)\n if (start === -1) return undefined\n const payloadStart = start + ENVELOPE_BEGIN.length\n const end = prompt.indexOf(ENVELOPE_END, payloadStart)\n if (end === -1) return undefined\n const payload = prompt.slice(payloadStart, end)\n try {\n const parsed = JSON.parse(payload) as unknown\n if (!parsed || typeof parsed !== 'object') return undefined\n const t = parsed as Partial<UiAuditTask>\n if (typeof t.lens !== 'string' || !Array.isArray(t.captures)) return undefined\n return t as UiAuditTask\n } catch {\n return undefined\n }\n}\n\n/** Produce the user message for one audit iteration: lens, captures to take, and the task envelope. @experimental */\nexport function formatAuditorPrompt(task: UiAuditTask): string {\n const lines: string[] = []\n lines.push(`# UI audit iteration — lens: ${task.lens}`)\n lines.push('')\n if (task.productContext && task.productContext.trim().length > 0) {\n lines.push('## Product context')\n lines.push(task.productContext.trim())\n lines.push('')\n }\n lines.push('## Captures to take')\n task.captures.forEach((cap, i) => {\n const vp = cap.viewport ? `${cap.viewport.width}x${cap.viewport.height}` : '1280x800 (default)'\n const detail = [\n `viewport=${vp}`,\n cap.fullPage ? 'fullPage=true' : null,\n cap.elementSelector ? `selector=\\`${cap.elementSelector}\\`` : null,\n cap.waitFor ? `waitFor=\\`${cap.waitFor}\\`` : null,\n cap.waitMs !== undefined ? `waitMs=${cap.waitMs}` : null,\n cap.label ? `label=${cap.label}` : null,\n ]\n .filter((s): s is string => s !== null)\n .join(' · ')\n lines.push(`${i + 1}. route=\\`${cap.route}\\` url=${cap.url} ${detail ? `(${detail})` : ''}`)\n })\n lines.push('')\n if (task.knownFindingIds && task.knownFindingIds.length > 0) {\n lines.push('## Known findings (link via similarTo, do not refile)')\n lines.push(task.knownFindingIds.map((n) => `#${String(n).padStart(3, '0')}`).join(', '))\n lines.push('')\n }\n lines.push('## Output format')\n lines.push(\n 'Emit a single JSON object with the shape `{ findings: UiFinding[], notes?: string }` where every finding has the fields enumerated in your system prompt. The screenshots field on each finding must reference the captures above by path. Do not emit findings outside the lens.',\n )\n return lines.join('\\n')\n}\n","/**\n *\n * Auditor validator — scores a single iteration's findings for actionability\n * and gates the iteration result. The kernel uses `valid` + `score` for\n * winner selection across fanned-out iterations and to detect a degenerate\n * iteration (lens-violating findings, no screenshot evidence, no findings\n * at all on a route where we expected some).\n *\n * Hard fails (`valid = false`):\n * - A finding is filed under a lens that does not match the iteration's\n * lens. The whole iteration is bad — the judge isn't following the\n * lens discipline and the resulting Markdown would mislead reviewers.\n * - A finding has no screenshot reference.\n * - A finding's screenshot references a path that wasn't captured in\n * this iteration.\n *\n * Score (0..1, max two decimals stable):\n * - 0.4 * specificityRatio — proportion of findings with a selector\n * - 0.4 * evidenceRatio — proportion of findings whose screenshots resolve to captures\n * - 0.2 * (1 - genericTitleRatio) — proportion of findings whose titles\n * are concrete (not \"improve UX\", \"fix layout\", etc.)\n *\n * An iteration with zero findings scores 0.5 by convention — neither a\n * confident pass nor a hard failure (the judge might just have nothing to\n * say on this lens). The driver decides what to do with it.\n *\n * @experimental\n */\n\nimport type { DefaultVerdict } from '@tangle-network/agent-eval'\nimport type { Validator } from '../../runtime/types'\nimport type { UiAuditOutput, UiAuditTask } from './task'\n\nconst GENERIC_TITLE_PATTERNS = [\n /^improve\\s/i,\n /^fix\\s/i,\n /^update\\s/i,\n /^better\\s/i,\n /^bad\\s/i,\n /^make\\s.+\\sbetter/i,\n /\\bUX\\b\\s*$/i,\n /\\bUI\\b\\s*$/i,\n]\n\nfunction isGenericTitle(title: string): boolean {\n const t = title.trim()\n if (t.length < 16) return true\n return GENERIC_TITLE_PATTERNS.some((re) => re.test(t))\n}\n\n/** Build a `Validator` that rejects off-lens findings and findings missing screenshot evidence. @experimental */\nexport function createUiAuditorValidator(task: UiAuditTask): Validator<UiAuditOutput> {\n return {\n async validate(output) {\n const findings = output.findings\n const captures = output.captures\n const capturePaths = new Set(captures.map((c) => c.path))\n\n const offLens = findings.filter((f) => f.lens !== task.lens)\n if (offLens.length > 0) {\n const verdict: DefaultVerdict = {\n valid: false,\n score: 0,\n notes: `${offLens.length} finding(s) filed under wrong lens (expected ${task.lens}; got ${offLens.map((f) => f.lens).join(', ')})`,\n scores: { offLens: 0 },\n }\n return verdict\n }\n\n const missingEvidence = findings.filter(\n (f) => !Array.isArray(f.screenshots) || f.screenshots.length === 0,\n )\n if (missingEvidence.length > 0) {\n const verdict: DefaultVerdict = {\n valid: false,\n score: 0,\n notes: `${missingEvidence.length} finding(s) have no screenshot evidence`,\n scores: { evidence: 0 },\n }\n return verdict\n }\n\n const unresolvedShot = findings.filter((f) =>\n f.screenshots.some((s) => !capturePaths.has(s.path)),\n )\n if (unresolvedShot.length > 0) {\n const verdict: DefaultVerdict = {\n valid: false,\n score: 0,\n notes: `${unresolvedShot.length} finding(s) reference screenshot paths not captured this iteration`,\n scores: { evidence: 0 },\n }\n return verdict\n }\n\n if (findings.length === 0) {\n const verdict: DefaultVerdict = {\n valid: true,\n score: 0.5,\n notes: 'No findings reported. Neither a confident pass nor a failure.',\n scores: { specificity: 0, evidence: 1, titles: 1 },\n }\n return verdict\n }\n\n const withSelector = findings.filter((f) => typeof f.selector === 'string').length\n const specificity = withSelector / findings.length\n const generic = findings.filter((f) => isGenericTitle(f.title)).length\n const titles = 1 - generic / findings.length\n // Compute evidence honestly from the data: proportion of findings whose\n // screenshots are all resolvable against this iteration's captures. The\n // guards above hard-fail when this would be < 1, so today the result is\n // always 1; if a future change relaxes those guards into a soft-fail\n // mode, this still produces a truthful evidence ratio rather than a\n // stale constant inflating the score.\n const withFullEvidence = findings.filter(\n (f) =>\n Array.isArray(f.screenshots) &&\n f.screenshots.length > 0 &&\n f.screenshots.every((s) => capturePaths.has(s.path)),\n ).length\n const evidence = withFullEvidence / findings.length\n const score = Number((0.4 * specificity + 0.4 * evidence + 0.2 * titles).toFixed(4))\n\n const verdict: DefaultVerdict = {\n valid: true,\n score,\n notes: `${findings.length} finding(s) — specificity=${specificity.toFixed(2)} evidence=${evidence.toFixed(2)} titles=${titles.toFixed(2)}`,\n scores: { specificity, evidence, titles },\n }\n return verdict\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAYA,SAAgB,QAAQ,OAAe,WAA2B;CAChE,MAAM,OAAO,MACV,YAAY,CAAC,CACb,UAAU,MAAM,CAAC,CACjB,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,YAAY,EAAE,CAAC,CACvB,MAAM,GAAG,EAAE;CACd,IAAI,KAAK,WAAW,GAClB,MAAM,IAAI,MACR,eAAe,UAAU,6DAA6D,KAAK,UAAU,KAAK,EAA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,QAAQ,MAAM,eAAe,EAAE,KAAK,CAAC,CAAC,CAAC,SACnC,SAAS;EAatC,MAAM,WANmB,SAAS,QAC/B,MACC,MAAM,QAAQ,EAAE,WAAW,KAC3B,EAAE,YAAY,SAAS,KACvB,EAAE,YAAY,OAAO,MAAM,aAAa,IAAI,EAAE,IAAI,CAAC,CACvD,CAAC,CAAC,SACkC,SAAS;EAS7C,OAAO;GALL,OAAO;GACP,OAJY,QAAQ,KAAM,cAAc,KAAM,WAAW,KAAM,OAAA,CAAQ,QAAQ,CAAC,CAI5E;GACJ,OAAO,GAAG,SAAS,OAAO,4BAA4B,YAAY,QAAQ,CAAC,EAAE,YAAY,SAAS,QAAQ,CAAC,EAAE,UAAU,OAAO,QAAQ,CAAC;GACvI,QAAQ;IAAE;IAAa;IAAU;GAAO;EAE7B;CACf,EACF;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as canonicalCandidateBytes, f as sha256Bytes, o as canonicalCandidateDigest, u as immutableCandidateValue } from "./protected-redaction-wGo44k2K.js";
|
|
2
|
+
import { B as assertExactObjectKeys, E as assertAgentCandidateExecutionRoots, l as candidateKnowledgeExecutionPaths, m as usdToNanos, p as sealAgentCandidateModelSettlement, q as candidateProfileAgentPaths } from "./prepare-DDGp0-rW.js";
|
|
2
3
|
import { posix } from "node:path";
|
|
3
4
|
import { isDeepStrictEqual } from "node:util";
|
|
4
5
|
//#region src/candidate-execution/exact-process-executor.ts
|
|
@@ -761,4 +762,4 @@ function record(value, label) {
|
|
|
761
762
|
//#endregion
|
|
762
763
|
export { exactProcessProviderAsCandidateExecutor as n, createProtectedAgentCandidateModelPort as t };
|
|
763
764
|
|
|
764
|
-
//# sourceMappingURL=protected-model-port-
|
|
765
|
+
//# sourceMappingURL=protected-model-port-DxFN8DLS.js.map
|