agentv 5.3.0-next.1 → 5.3.1-next.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.
Files changed (43) hide show
  1. package/README.md +22 -20
  2. package/dist/{artifact-writer-JFNIPMKW.js → artifact-writer-7NBCOAYC.js} +4 -4
  3. package/dist/{chunk-T32NL3E6.js → chunk-ASIGJIOJ.js} +50 -30
  4. package/dist/chunk-ASIGJIOJ.js.map +1 -0
  5. package/dist/{chunk-6ZZCDZPD.js → chunk-ELCJ23K4.js} +12766 -12478
  6. package/dist/chunk-ELCJ23K4.js.map +1 -0
  7. package/dist/{chunk-FVR4RQFK.js → chunk-LKGARI3W.js} +333 -24
  8. package/dist/chunk-LKGARI3W.js.map +1 -0
  9. package/dist/{chunk-V52ATPTT.js → chunk-LXBI3SPX.js} +142 -14
  10. package/dist/chunk-LXBI3SPX.js.map +1 -0
  11. package/dist/{chunk-BHKQHG26.js → chunk-RKE7SSET.js} +2 -2
  12. package/dist/cli.js +5 -5
  13. package/dist/dashboard/assets/{index-DNgf3qJ2.js → index-CbEMiJSb.js} +1 -1
  14. package/dist/dashboard/assets/{index-r_jSJmlw.js → index-DTA6-l7q.js} +3 -3
  15. package/dist/dashboard/index.html +1 -1
  16. package/dist/{dist-6Z7U473R.js → dist-NMXMI5SK.js} +17 -5
  17. package/dist/index.js +5 -5
  18. package/dist/{interactive-RUY3OCBI.js → interactive-BN527UV3.js} +5 -5
  19. package/dist/skills/agentv-bench/SKILL.md +14 -13
  20. package/dist/skills/agentv-bench/agents/analyzer.md +1 -1
  21. package/dist/skills/agentv-bench/agents/executor.md +1 -1
  22. package/dist/skills/agentv-bench/references/autoresearch.md +9 -9
  23. package/dist/skills/agentv-bench/references/environment-adaptation.md +4 -4
  24. package/dist/skills/agentv-bench/references/eval-yaml-spec.md +30 -47
  25. package/dist/skills/agentv-bench/references/schemas.md +44 -60
  26. package/dist/skills/agentv-bench/references/subagent-pipeline.md +20 -18
  27. package/dist/skills/agentv-eval-migrations/SKILL.md +13 -0
  28. package/dist/skills/agentv-eval-migrations/references/breaking-changes.md +39 -21
  29. package/dist/skills/agentv-eval-writer/SKILL.md +75 -46
  30. package/dist/skills/agentv-eval-writer/references/custom-evaluators.md +10 -5
  31. package/dist/skills/agentv-eval-writer/references/eval.schema.json +749 -2158
  32. package/dist/skills/agentv-eval-writer/references/rubric-evaluator.md +1 -1
  33. package/dist/{ts-eval-loader-DQDYRULE-V3377FOL.js → ts-eval-loader-2RFVZHCT-7CZ3DCDD.js} +8 -4
  34. package/package.json +1 -1
  35. package/dist/chunk-6ZZCDZPD.js.map +0 -1
  36. package/dist/chunk-FVR4RQFK.js.map +0 -1
  37. package/dist/chunk-T32NL3E6.js.map +0 -1
  38. package/dist/chunk-V52ATPTT.js.map +0 -1
  39. /package/dist/{artifact-writer-JFNIPMKW.js.map → artifact-writer-7NBCOAYC.js.map} +0 -0
  40. /package/dist/{chunk-BHKQHG26.js.map → chunk-RKE7SSET.js.map} +0 -0
  41. /package/dist/{dist-6Z7U473R.js.map → dist-NMXMI5SK.js.map} +0 -0
  42. /package/dist/{interactive-RUY3OCBI.js.map → interactive-BN527UV3.js.map} +0 -0
  43. /package/dist/{ts-eval-loader-DQDYRULE-V3377FOL.js.map → ts-eval-loader-2RFVZHCT-7CZ3DCDD.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../packages/core/src/evaluation/dashboard-trace-read-model.ts","../../../packages/core/src/evaluation/trace-normalization.ts","../../../packages/core/src/evaluation/loaders/eval-yaml-transpiler.ts","../../../packages/core/src/evaluation/prepared-workspace.ts","../../../packages/core/src/evaluation/config.ts","../../../packages/core/src/evaluation/generators/rubric-generator.ts","../../../packages/core/src/evaluation/results-repo.ts","../../../packages/core/src/project-sync.ts","../../../packages/core/src/evaluation/baseline.ts","../../../packages/core/src/evaluation/run-budget-tracker.ts","../../../packages/core/src/evaluation/hooks.ts","../../../packages/core/src/evaluation/env-injection.ts","../../../packages/core/src/import/claude-parser.ts","../../../packages/core/src/import/codex-parser.ts","../../../packages/core/src/import/codex-session-discovery.ts","../../../packages/core/src/import/session-discovery.ts","../../../packages/core/src/import/transcript-provider.ts","../../../packages/core/src/evaluation/providers/copilot-log-parser.ts","../../../packages/core/src/index.ts"],"sourcesContent":["/**\n * Dashboard trace/session wire read model.\n *\n * This module projects already-normalized `agentv.trace.v1` envelopes into the\n * stable snake_case payload consumed by the local Dashboard and served by the\n * CLI Dashboard API. It intentionally does not normalize raw OTLP/provider\n * traces; that stays in the trace normalization pipeline before artifacts reach\n * this projector.\n */\n\nimport type { ExternalTraceMetadataWire } from './external-trace.js';\n\nexport interface TraceSessionTokenUsage {\n input?: number;\n output?: number;\n reasoning?: number;\n cached?: number;\n total?: number;\n}\n\nexport interface TraceSessionSpanStatus {\n code?: string;\n message?: string;\n}\n\nexport type TraceSessionEventKind = 'annotation' | 'exception' | 'event' | 'score';\n\nexport interface TraceSessionEvent {\n event_id: string;\n span_id: string;\n name: string;\n kind: TraceSessionEventKind;\n time_unix_nano?: string;\n timestamp?: string;\n score?: number;\n text?: string;\n passed?: boolean;\n attributes?: Record<string, unknown>;\n}\n\nexport interface TraceSessionSpan {\n id: string;\n trace_id?: string;\n span_id: string;\n parent_span_id?: string | null;\n name: string;\n kind?: string;\n status?: TraceSessionSpanStatus;\n start_time_unix_nano?: string;\n end_time_unix_nano?: string;\n start_time?: string;\n end_time?: string;\n duration_ms?: number;\n token_usage?: TraceSessionTokenUsage;\n resource_attributes?: Record<string, unknown>;\n attributes?: Record<string, unknown>;\n events?: TraceSessionEvent[];\n}\n\nexport interface TraceSessionScore {\n name: string;\n type?: string;\n score: number;\n weight?: number;\n verdict?: string;\n source?: string;\n evaluated_at?: string;\n target_span_id?: string;\n evidence?: Record<string, unknown>;\n}\n\nexport interface TraceSessionSource {\n kind?: string;\n path?: string;\n provider?: string;\n format?: string;\n version?: string;\n artifact_path?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface TraceSessionArtifactLink {\n name: string;\n path: string;\n}\n\nexport interface TraceSessionSourceRef {\n event_id?: string;\n message_id?: string;\n span_id?: string;\n trace_id?: string;\n raw_kind?: string;\n path?: string;\n line?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface TraceSessionConversionWarning {\n code: string;\n severity?: 'info' | 'warning' | 'error' | string;\n span_id?: string;\n source_ref?: TraceSessionSourceRef;\n message: string;\n details?: Record<string, unknown>;\n}\n\nexport interface TraceSessionResponse {\n schema_version: 'agentv.dashboard.trace_session.v1';\n artifact_id?: string;\n created_at?: string;\n run_id?: string;\n test_id?: string;\n suite?: string;\n target?: string;\n trace_id?: string;\n root_span_id?: string;\n source?: TraceSessionSource;\n external_trace?: ExternalTraceMetadataWire;\n artifact_links?: TraceSessionArtifactLink[];\n resource_attributes?: Record<string, unknown>;\n conversion_warnings?: TraceSessionConversionWarning[];\n spans: TraceSessionSpan[];\n events: TraceSessionEvent[];\n scores?: TraceSessionScore[];\n}\n\nexport const TRACE_SESSION_SCHEMA_VERSION = 'agentv.dashboard.trace_session.v1' as const;\n\nexport interface TraceSessionProjectionOptions {\n runId?: string;\n artifactPath?: string;\n}\n\nexport interface TraceSpanNode {\n id: string;\n spanId: string;\n parentSpanId?: string | null;\n span: TraceSessionSpan;\n children: TraceSpanNode[];\n diagnostics?: TraceSpanTreeDiagnostic[];\n}\n\nexport type TraceSpanTreeDiagnosticCode =\n | 'cycle'\n | 'duplicate_span_id'\n | 'missing_parent'\n | 'missing_span_id'\n | 'self_parent';\n\nexport interface TraceSpanTreeDiagnostic {\n code: TraceSpanTreeDiagnosticCode;\n message: string;\n span_id?: string;\n node_id?: string;\n parent_span_id?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return isRecord(value) ? value : undefined;\n}\n\nfunction asArray(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction finiteInteger(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;\n}\n\nfunction boolValue(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction dropUndefined<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n\nfunction compactRecord(value: Record<string, unknown>): Record<string, unknown> | undefined {\n const compacted = dropUndefined(value);\n return Object.keys(compacted).length > 0 ? compacted : undefined;\n}\n\nfunction nonEmptyArray<T>(value: readonly T[] | undefined): readonly T[] | undefined {\n return value && value.length > 0 ? value : undefined;\n}\n\nfunction unixNanoToIso(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n try {\n return new Date(Number(BigInt(value) / 1_000_000n)).toISOString();\n } catch {\n return undefined;\n }\n}\n\nfunction durationMsFromNanos(\n start: string | undefined,\n end: string | undefined,\n): number | undefined {\n if (!start || !end) {\n return undefined;\n }\n try {\n const startNanos = BigInt(start);\n const endNanos = BigInt(end);\n if (endNanos < startNanos) {\n return undefined;\n }\n return Number(endNanos - startNanos) / 1_000_000;\n } catch {\n return undefined;\n }\n}\n\nfunction numberFromAttributes(\n attributes: Record<string, unknown>,\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n const value = finiteNumber(attributes[key]);\n if (value !== undefined) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction tokenUsageFromAttributes(\n attributes: Record<string, unknown> | undefined,\n): TraceSessionTokenUsage | undefined {\n if (!attributes) {\n return undefined;\n }\n\n const nested = asRecord(attributes.token_usage);\n const usage = compactRecord({\n input:\n finiteNumber(nested?.input) ??\n numberFromAttributes(attributes, [\n 'gen_ai.usage.input_tokens',\n 'llm.token_count.prompt',\n 'input_tokens',\n ]),\n output:\n finiteNumber(nested?.output) ??\n numberFromAttributes(attributes, [\n 'gen_ai.usage.output_tokens',\n 'llm.token_count.completion',\n 'output_tokens',\n ]),\n reasoning:\n finiteNumber(nested?.reasoning) ??\n numberFromAttributes(attributes, [\n 'gen_ai.usage.reasoning.output_tokens',\n 'reasoning_tokens',\n ]),\n cached:\n finiteNumber(nested?.cached) ??\n numberFromAttributes(attributes, ['gen_ai.usage.cache_read.input_tokens', 'cached_tokens']),\n total: finiteNumber(nested?.total) ?? numberFromAttributes(attributes, ['total_tokens']),\n });\n\n return usage as TraceSessionTokenUsage | undefined;\n}\n\nfunction isExternalTraceKey(key: string): boolean {\n return (\n key === 'external_trace' ||\n key.startsWith('external_trace_') ||\n key.startsWith('external_trace.')\n );\n}\n\nfunction isCredentialLikeKey(key: string): boolean {\n const normalized = key.toLowerCase();\n if (\n normalized === 'token_usage' ||\n normalized.endsWith('_tokens') ||\n normalized.endsWith('.tokens') ||\n normalized.includes('usage.')\n ) {\n return false;\n }\n return /(^|[._-])(api[._-]?key|authorization|bearer|password|secret|private[._-]?key|access[._-]?token|auth[._-]?token|client[._-]?secret|id[._-]?token|refresh[._-]?token|session[._-]?token|token)($|[._-])/.test(\n normalized,\n );\n}\n\nfunction sanitizeAttributeMap(\n value: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!value) {\n return undefined;\n }\n const entries = Object.entries(value).flatMap(([key, entry]) => {\n if (isExternalTraceKey(key) || isCredentialLikeKey(key)) {\n return [];\n }\n if (isRecord(entry)) {\n const nested = sanitizeAttributeMap(entry);\n return nested ? [[key, nested] as const] : [];\n }\n return [[key, entry] as const];\n });\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\nfunction spanStatusFromValue(value: unknown): TraceSessionSpan['status'] {\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n return compactRecord({\n code:\n stringValue(record.code) ??\n (typeof record.code === 'number' ? String(record.code) : undefined),\n message: stringValue(record.message),\n }) as TraceSessionSpan['status'];\n}\n\nfunction eventKind(\n name: string,\n attributes: Record<string, unknown> | undefined,\n): TraceSessionEventKind {\n const lowerName = name.toLowerCase();\n if (\n lowerName.includes('score') ||\n numberFromAttributes(attributes ?? {}, [\n 'score',\n 'agentv.score',\n 'agentv.grader.score',\n 'gen_ai.evaluation.score.value',\n 'openinference.evaluation.score',\n ]) !== undefined\n ) {\n return 'score';\n }\n if (\n lowerName.includes('annotation') ||\n stringValue(attributes?.text) !== undefined ||\n stringValue(attributes?.annotation) !== undefined ||\n stringValue(attributes?.['agentv.annotation.text']) !== undefined\n ) {\n return 'annotation';\n }\n if (lowerName === 'exception') {\n return 'exception';\n }\n return 'event';\n}\n\nfunction scoreFromEvent(attributes: Record<string, unknown> | undefined): number | undefined {\n if (!attributes) {\n return undefined;\n }\n return (\n finiteNumber(attributes.score) ??\n finiteNumber(attributes['agentv.score']) ??\n finiteNumber(attributes['agentv.grader.score']) ??\n finiteNumber(attributes['gen_ai.evaluation.score.value']) ??\n finiteNumber(attributes['openinference.evaluation.score'])\n );\n}\n\nfunction textFromEvent(attributes: Record<string, unknown> | undefined): string | undefined {\n if (!attributes) {\n return undefined;\n }\n return (\n stringValue(attributes.text) ??\n stringValue(attributes.annotation) ??\n stringValue(attributes['agentv.annotation.text']) ??\n stringValue(attributes['gen_ai.evaluation.explanation']) ??\n stringValue(attributes['gen_ai.evaluation.score.label']) ??\n stringValue(attributes['exception.message'])\n );\n}\n\nfunction passedFromEvent(attributes: Record<string, unknown> | undefined): boolean | undefined {\n if (!attributes) {\n return undefined;\n }\n return (\n boolValue(attributes.passed) ??\n boolValue(attributes['agentv.annotation.passed']) ??\n boolValue(attributes['agentv.grader.passed']) ??\n boolValue(attributes['gen_ai.evaluation.passed'])\n );\n}\n\nfunction eventId(\n spanId: string,\n index: number,\n attributes: Record<string, unknown> | undefined,\n): string {\n return (\n stringValue(attributes?.event_id) ??\n stringValue(attributes?.['agentv.event_id']) ??\n `${spanId}:event:${index}`\n );\n}\n\nfunction projectSpanEvent(\n spanId: string,\n event: unknown,\n index: number,\n): TraceSessionEvent | undefined {\n const record = asRecord(event);\n if (!record) {\n return undefined;\n }\n const name = stringValue(record.name);\n if (!name) {\n return undefined;\n }\n\n const attributes = asRecord(record.attributes);\n const safeAttributes = sanitizeAttributeMap(attributes);\n return dropUndefined({\n event_id: eventId(spanId, index, attributes),\n span_id: spanId,\n name,\n kind: eventKind(name, attributes),\n time_unix_nano: stringValue(record.time_unix_nano),\n timestamp: unixNanoToIso(stringValue(record.time_unix_nano)),\n score: scoreFromEvent(attributes),\n text: textFromEvent(attributes),\n passed: passedFromEvent(attributes),\n attributes: safeAttributes,\n });\n}\n\nfunction projectSpan(span: unknown, index: number): TraceSessionSpan | undefined {\n const record = asRecord(span);\n if (!record) {\n return undefined;\n }\n\n const spanId = stringValue(record.span_id) ?? `span-${index}`;\n const traceId = stringValue(record.trace_id);\n const parentSpanId = record.parent_span_id === null ? null : stringValue(record.parent_span_id);\n const attributes = asRecord(record.attributes);\n const safeAttributes = sanitizeAttributeMap(attributes);\n const startTimeUnixNano = stringValue(record.start_time_unix_nano);\n const endTimeUnixNano = stringValue(record.end_time_unix_nano);\n const events = asArray(record.events)\n .map((event, eventIndex) => projectSpanEvent(spanId, event, eventIndex))\n .filter((event): event is TraceSessionEvent => event !== undefined);\n\n return dropUndefined({\n id: spanId,\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n name: stringValue(record.name) ?? spanId,\n kind: stringValue(record.kind),\n status: spanStatusFromValue(record.status),\n start_time_unix_nano: startTimeUnixNano,\n end_time_unix_nano: endTimeUnixNano,\n start_time: unixNanoToIso(startTimeUnixNano),\n end_time: unixNanoToIso(endTimeUnixNano),\n duration_ms: durationMsFromNanos(startTimeUnixNano, endTimeUnixNano),\n token_usage: tokenUsageFromAttributes(attributes),\n resource_attributes: sanitizeAttributeMap(asRecord(record.resource_attributes)),\n attributes: safeAttributes,\n events: events.length > 0 ? events : undefined,\n });\n}\n\nfunction projectScores(scores: unknown): TraceSessionScore[] | undefined {\n const projected: TraceSessionScore[] = [];\n\n for (const score of asArray(scores)) {\n const record = asRecord(score);\n const name = stringValue(record?.name);\n const value = finiteNumber(record?.score);\n if (!record || !name || value === undefined) {\n continue;\n }\n projected.push(\n dropUndefined({\n name,\n type: stringValue(record.type),\n score: value,\n weight: finiteNumber(record.weight),\n verdict: stringValue(record.verdict),\n source: stringValue(record.source),\n evaluated_at: stringValue(record.evaluated_at),\n target_span_id: stringValue(record.target_span_id),\n evidence: asRecord(record.evidence),\n }) as TraceSessionScore,\n );\n }\n\n return projected.length > 0 ? projected : undefined;\n}\n\nconst EXTERNAL_TRACE_KEYS = [\n 'provider',\n 'source',\n 'endpoint',\n 'profile',\n 'project',\n 'project_id',\n 'session_id',\n 'session_node_id',\n 'trace_id',\n 'trace_node_id',\n 'span_id',\n 'span_node_id',\n 'traceparent',\n 'tracestate',\n 'ui_url',\n 'run_id',\n 'test_id',\n 'target',\n] as const;\n\nfunction sanitizeUrl(value: unknown): string | undefined {\n const raw = stringValue(value);\n if (!raw) {\n return undefined;\n }\n try {\n const url = new URL(raw);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {\n return undefined;\n }\n url.search = '';\n url.hash = '';\n return url.toString();\n } catch {\n return undefined;\n }\n}\n\nfunction sanitizeExternalTrace(value: unknown): ExternalTraceMetadataWire | undefined {\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n\n const sanitized = compactRecord({\n provider: stringValue(record.provider),\n source: stringValue(record.source),\n endpoint: sanitizeUrl(record.endpoint),\n profile: stringValue(record.profile),\n project: stringValue(record.project),\n project_id: stringValue(record.project_id) ?? stringValue(record.projectId),\n session_id: stringValue(record.session_id) ?? stringValue(record.session),\n session_node_id:\n stringValue(record.session_node_id) ??\n stringValue(record.session_node) ??\n stringValue(record.node_id),\n trace_id: stringValue(record.trace_id) ?? stringValue(record.trace),\n trace_node_id: stringValue(record.trace_node_id) ?? stringValue(record.trace_node),\n span_id: stringValue(record.span_id) ?? stringValue(record.span),\n span_node_id: stringValue(record.span_node_id) ?? stringValue(record.span_node),\n traceparent: stringValue(record.traceparent),\n tracestate: stringValue(record.tracestate),\n ui_url: sanitizeUrl(record.ui_url ?? record.url ?? record.href),\n run_id: stringValue(record.run_id),\n test_id: stringValue(record.test_id),\n target: stringValue(record.target),\n }) as ExternalTraceMetadataWire | undefined;\n\n return sanitized && EXTERNAL_TRACE_KEYS.some((key) => sanitized[key] !== undefined)\n ? sanitized\n : undefined;\n}\n\nfunction externalTraceFromFlatMetadata(\n metadata: Record<string, unknown> | undefined,\n): ExternalTraceMetadataWire | undefined {\n if (!metadata) {\n return undefined;\n }\n return sanitizeExternalTrace({\n provider: metadata.external_trace_provider ?? metadata['external_trace.provider'],\n source: metadata.external_trace_source ?? metadata['external_trace.source'],\n endpoint: metadata.external_trace_endpoint ?? metadata['external_trace.endpoint'],\n profile: metadata.external_trace_profile ?? metadata['external_trace.profile'],\n project: metadata.external_trace_project ?? metadata['external_trace.project'],\n project_id: metadata.external_trace_project_id ?? metadata['external_trace.project_id'],\n session_id:\n metadata.external_trace_session_id ??\n metadata.external_trace_session ??\n metadata['external_trace.session_id'] ??\n metadata['external_trace.session'],\n session_node_id:\n metadata.external_trace_session_node_id ??\n metadata.external_trace_node_id ??\n metadata['external_trace.session_node_id'] ??\n metadata['external_trace.node_id'],\n trace_id:\n metadata.external_trace_trace_id ??\n metadata.external_trace_trace ??\n metadata['external_trace.trace_id'] ??\n metadata['external_trace.trace'],\n trace_node_id:\n metadata.external_trace_trace_node_id ?? metadata['external_trace.trace_node_id'],\n span_id:\n metadata.external_trace_span_id ??\n metadata.external_trace_span ??\n metadata['external_trace.span_id'] ??\n metadata['external_trace.span'],\n span_node_id: metadata.external_trace_span_node_id ?? metadata['external_trace.span_node_id'],\n traceparent: metadata.external_trace_traceparent ?? metadata['external_trace.traceparent'],\n tracestate: metadata.external_trace_tracestate ?? metadata['external_trace.tracestate'],\n ui_url:\n metadata.external_trace_ui_url ??\n metadata.external_trace_url ??\n metadata['external_trace.ui_url'] ??\n metadata['external_trace.url'],\n run_id: metadata.external_trace_run_id ?? metadata['external_trace.run_id'],\n test_id: metadata.external_trace_test_id ?? metadata['external_trace.test_id'],\n target: metadata.external_trace_target ?? metadata['external_trace.target'],\n });\n}\n\nfunction sanitizeMetadataValue(value: unknown): unknown | undefined {\n if (Array.isArray(value)) {\n const sanitized = value\n .map(sanitizeMetadataValue)\n .filter((entry): entry is unknown => entry !== undefined);\n return sanitized.length > 0 ? sanitized : undefined;\n }\n if (isRecord(value)) {\n return sanitizeMetadata(value);\n }\n return value;\n}\n\nfunction sanitizeMetadata(\n value: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!value) {\n return undefined;\n }\n const entries = Object.entries(value).flatMap(([key, entry]) => {\n if (isExternalTraceKey(key) || isCredentialLikeKey(key)) {\n return [];\n }\n const sanitized = sanitizeMetadataValue(entry);\n return sanitized !== undefined ? [[key, sanitized] as const] : [];\n });\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\nfunction sourceFromEnvelope(\n source: Record<string, unknown> | undefined,\n artifactPath: string | undefined,\n): TraceSessionSource | undefined {\n if (!source && !artifactPath) {\n return undefined;\n }\n return compactRecord({\n kind: stringValue(source?.kind),\n path: stringValue(source?.path),\n provider: stringValue(source?.provider),\n format: stringValue(source?.format),\n version: stringValue(source?.version),\n artifact_path: artifactPath,\n metadata: sanitizeMetadata(asRecord(source?.metadata)),\n }) as TraceSessionSource | undefined;\n}\n\nfunction safeArtifactPath(value: unknown): string | undefined {\n const raw = stringValue(value);\n if (!raw || raw.includes('\\0')) {\n return undefined;\n }\n\n const normalized = raw.replace(/\\\\/g, '/');\n if (normalized.startsWith('/') || normalized.startsWith('//')) {\n return undefined;\n }\n if (/^[a-z][a-z0-9+.-]*:/i.test(normalized)) {\n return undefined;\n }\n if (normalized.split('/').includes('..')) {\n return undefined;\n }\n return normalized;\n}\n\nfunction projectArtifactLinks(artifacts: unknown): TraceSessionArtifactLink[] | undefined {\n const record = asRecord(artifacts);\n if (!record) {\n return undefined;\n }\n\n const links = Object.entries(record)\n .flatMap(([name, value]) => {\n if (!stringValue(name) || isCredentialLikeKey(name)) {\n return [];\n }\n const artifactPath = safeArtifactPath(value);\n return artifactPath ? [{ name, path: artifactPath }] : [];\n })\n .sort((first, second) => first.name.localeCompare(second.name));\n\n return links.length > 0 ? links : undefined;\n}\n\nfunction projectSourceRef(value: unknown): TraceSessionSourceRef | undefined {\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n return compactRecord({\n event_id: stringValue(record.event_id),\n message_id: stringValue(record.message_id),\n span_id: stringValue(record.span_id),\n trace_id: stringValue(record.trace_id),\n raw_kind: stringValue(record.raw_kind),\n path: safeArtifactPath(record.path),\n line: finiteInteger(record.line),\n metadata: sanitizeMetadata(asRecord(record.metadata)),\n }) as TraceSessionSourceRef | undefined;\n}\n\nfunction projectConversionWarnings(warnings: unknown): TraceSessionConversionWarning[] | undefined {\n const projected: TraceSessionConversionWarning[] = [];\n\n for (const warning of asArray(warnings)) {\n const record = asRecord(warning);\n const code = stringValue(record?.code);\n const message = stringValue(record?.message);\n if (!record || !code || !message) {\n continue;\n }\n projected.push(\n dropUndefined({\n code,\n severity: stringValue(record.severity),\n span_id: stringValue(record.span_id),\n source_ref: projectSourceRef(record.source_ref),\n message,\n details: sanitizeMetadata(asRecord(record.details)),\n }) as TraceSessionConversionWarning,\n );\n }\n\n return projected.length > 0 ? projected : undefined;\n}\n\nfunction externalTraceFromEnvelope(\n envelope: Record<string, unknown>,\n): ExternalTraceMetadataWire | undefined {\n const source = asRecord(envelope.source);\n const sourceMetadata = asRecord(source?.metadata);\n const trace = asRecord(envelope.trace);\n const rootSpanId = stringValue(trace?.root_span_id);\n const rootSpan = asArray(trace?.spans)\n .map(asRecord)\n .find((span) => stringValue(span?.span_id) === rootSpanId);\n const rootAttributes = asRecord(rootSpan?.attributes);\n\n return (\n sanitizeExternalTrace(envelope.external_trace) ??\n sanitizeExternalTrace(sourceMetadata?.external_trace) ??\n externalTraceFromFlatMetadata(sourceMetadata) ??\n externalTraceFromFlatMetadata(rootAttributes)\n );\n}\n\nexport function traceEnvelopeToTraceSessionResponse(\n input: unknown,\n options: TraceSessionProjectionOptions = {},\n): TraceSessionResponse {\n const envelope = asRecord(input) ?? {};\n const evaluation = asRecord(envelope.eval);\n const trace = asRecord(envelope.trace);\n const traceResource = asRecord(trace?.resource);\n const spans = asArray(trace?.spans)\n .map(projectSpan)\n .filter((span): span is TraceSessionSpan => span !== undefined);\n const events = spans.flatMap((span) => span.events ?? []);\n\n return dropUndefined({\n schema_version: TRACE_SESSION_SCHEMA_VERSION,\n artifact_id: stringValue(envelope.artifact_id),\n created_at: stringValue(envelope.created_at),\n run_id: options.runId ?? stringValue(evaluation?.run_id),\n test_id: stringValue(evaluation?.test_id),\n suite: stringValue(evaluation?.suite),\n target: stringValue(evaluation?.target),\n trace_id: stringValue(trace?.trace_id),\n root_span_id: stringValue(trace?.root_span_id),\n source: sourceFromEnvelope(asRecord(envelope.source), options.artifactPath),\n external_trace: externalTraceFromEnvelope(envelope),\n artifact_links: projectArtifactLinks(envelope.artifacts),\n resource_attributes: sanitizeAttributeMap(asRecord(traceResource?.attributes)),\n conversion_warnings: projectConversionWarnings(envelope.conversion_warnings),\n spans,\n events,\n scores: projectScores(envelope.scores),\n });\n}\n\nexport function buildTraceSpanTree(spans: readonly TraceSessionSpan[]): TraceSpanNode[] {\n const nodes: TraceSpanNode[] = [];\n const firstNodeBySpanId = new Map<string, TraceSpanNode>();\n const spanIdCounts = new Map<string, number>();\n\n spans.forEach((span, index) => {\n const rawSpanId = stringValue(span.span_id);\n const spanId = rawSpanId ?? `missing-span-${index}`;\n const occurrence = (spanIdCounts.get(spanId) ?? 0) + 1;\n spanIdCounts.set(spanId, occurrence);\n\n const node: TraceSpanNode = {\n id: occurrence === 1 ? spanId : `${spanId}#${occurrence}`,\n spanId,\n parentSpanId: span.parent_span_id,\n span,\n children: [],\n diagnostics: rawSpanId\n ? undefined\n : [\n {\n code: 'missing_span_id',\n message: 'Span was missing span_id and was assigned a stable node id.',\n node_id: spanId,\n },\n ],\n };\n\n if (occurrence > 1) {\n addNodeDiagnostic(node, {\n code: 'duplicate_span_id',\n message: 'Duplicate span_id was preserved with a collision-free node id.',\n span_id: spanId,\n node_id: node.id,\n });\n }\n if (!firstNodeBySpanId.has(spanId)) {\n firstNodeBySpanId.set(spanId, node);\n }\n nodes.push(node);\n });\n\n const parentByNodeId = new Map<string, TraceSpanNode>();\n for (const node of nodes) {\n const parentSpanId =\n typeof node.parentSpanId === 'string' && node.parentSpanId.length > 0\n ? node.parentSpanId\n : undefined;\n if (!parentSpanId) {\n continue;\n }\n if (parentSpanId === node.spanId) {\n addNodeDiagnostic(node, {\n code: 'self_parent',\n message: 'Span parent_span_id points to itself; span was promoted to a root.',\n span_id: node.spanId,\n node_id: node.id,\n parent_span_id: parentSpanId,\n });\n continue;\n }\n const parent = firstNodeBySpanId.get(parentSpanId);\n if (!parent) {\n addNodeDiagnostic(node, {\n code: 'missing_parent',\n message: 'Span parent_span_id was not present in this trace; span was promoted to a root.',\n span_id: node.spanId,\n node_id: node.id,\n parent_span_id: parentSpanId,\n });\n continue;\n }\n parentByNodeId.set(node.id, parent);\n }\n\n const cyclicNodes: TraceSpanNode[] = [];\n for (const node of nodes) {\n if (hasAncestorCycle(node, parentByNodeId)) {\n cyclicNodes.push(node);\n }\n }\n for (const node of cyclicNodes) {\n parentByNodeId.delete(node.id);\n addNodeDiagnostic(node, {\n code: 'cycle',\n message: 'Span parent chain contains a cycle; span was promoted to a root.',\n span_id: node.spanId,\n node_id: node.id,\n parent_span_id: typeof node.parentSpanId === 'string' ? node.parentSpanId : undefined,\n });\n }\n\n const roots: TraceSpanNode[] = [];\n for (const node of nodes) {\n const parent = parentByNodeId.get(node.id);\n if (parent) {\n parent.children.push(node);\n } else {\n roots.push(node);\n }\n }\n\n sortTraceSpanNodes(roots);\n return roots;\n}\n\nfunction addNodeDiagnostic(node: TraceSpanNode, diagnostic: TraceSpanTreeDiagnostic): void {\n node.diagnostics = [...(node.diagnostics ?? []), diagnostic];\n}\n\nfunction hasAncestorCycle(\n node: TraceSpanNode,\n parentByNodeId: ReadonlyMap<string, TraceSpanNode>,\n): boolean {\n const seen = new Set<string>();\n let cursor = parentByNodeId.get(node.id);\n while (cursor) {\n if (cursor.id === node.id || seen.has(cursor.id)) {\n return true;\n }\n seen.add(cursor.id);\n cursor = parentByNodeId.get(cursor.id);\n }\n return false;\n}\n\nfunction compareUnixNanoValue(first: string | undefined, second: string | undefined): number {\n if (first === second) {\n return 0;\n }\n if (!first) {\n return 1;\n }\n if (!second) {\n return -1;\n }\n try {\n const firstValue = BigInt(first);\n const secondValue = BigInt(second);\n return firstValue < secondValue ? -1 : firstValue > secondValue ? 1 : 0;\n } catch {\n return first.localeCompare(second);\n }\n}\n\nfunction compareTraceSpanNodes(first: TraceSpanNode, second: TraceSpanNode): number {\n const byStart = compareUnixNanoValue(\n first.span.start_time_unix_nano,\n second.span.start_time_unix_nano,\n );\n if (byStart !== 0) {\n return byStart;\n }\n if (first.spanId === second.parentSpanId) {\n return -1;\n }\n if (second.spanId === first.parentSpanId) {\n return 1;\n }\n const bySpanId = first.spanId.localeCompare(second.spanId);\n return bySpanId !== 0 ? bySpanId : first.id.localeCompare(second.id);\n}\n\nfunction sortTraceSpanNodes(nodes: TraceSpanNode[]): void {\n nodes.sort(compareTraceSpanNodes);\n for (const node of nodes) {\n node.children.sort(compareTraceSpanNodes);\n if (node.children.length > 0) {\n sortTraceSpanNodes(node.children);\n }\n node.diagnostics = nonEmptyArray(node.diagnostics) as TraceSpanTreeDiagnostic[] | undefined;\n }\n}\n","/**\n * Dashboard trace normalization.\n *\n * This module accepts raw trace artifacts that are already owned by AgentV\n * (`agentv.trace.v1`) or standards-shaped OTLP/OpenInference JSON, then projects\n * them into the shared Dashboard trace/session read model. It deliberately\n * avoids Phoenix-specific concepts; backend-specific mapping belongs in\n * adapters before or after this generic normalization boundary.\n */\n\nimport {\n type TraceSessionConversionWarning,\n type TraceSessionProjectionOptions,\n type TraceSessionResponse,\n traceEnvelopeToTraceSessionResponse,\n} from './dashboard-trace-read-model.js';\nimport { EXECUTION_TRACE_SCHEMA_VERSION } from './trace-envelope.js';\n\nconst TRACE_ENVELOPE_FORMAT = 'otlp_openinference_spans' as const;\n\nexport interface TraceArtifactNormalizationOptions extends TraceSessionProjectionOptions {\n runId?: string;\n testId?: string;\n suite?: string;\n target?: string;\n now?: () => Date;\n}\n\nexport type TraceArtifactNormalizationResult =\n | {\n status: 'ok';\n format: 'agentv_trace_v1' | 'otlp_json';\n traceSession: TraceSessionResponse;\n warnings?: readonly TraceSessionConversionWarning[];\n }\n | {\n status: 'unsupported';\n message: string;\n warnings?: readonly TraceSessionConversionWarning[];\n };\n\ntype WarningSink = TraceSessionConversionWarning[];\n\ninterface WarningContext {\n readonly rawKind?: string;\n readonly path?: string;\n readonly spanId?: string;\n readonly details?: Record<string, unknown>;\n}\n\ninterface NormalizedOtlpSpan {\n readonly trace_id?: string;\n readonly span_id: string;\n readonly parent_span_id?: string | null;\n readonly name: string;\n readonly kind?: string;\n readonly start_time_unix_nano?: string;\n readonly end_time_unix_nano?: string;\n readonly status?: {\n readonly code?: string;\n readonly message?: string;\n };\n readonly resource_attributes?: Record<string, unknown>;\n readonly attributes?: Record<string, unknown>;\n readonly events?: readonly {\n readonly name: string;\n readonly time_unix_nano?: string;\n readonly attributes?: Record<string, unknown>;\n }[];\n}\n\ninterface ParsedOtlpValue {\n readonly ok: boolean;\n readonly value?: unknown;\n}\n\nconst OTLP_ROOT_FIELDS = new Set(['resourceSpans']);\nconst OTLP_RESOURCE_SPAN_FIELDS = new Set(['resource', 'scopeSpans', 'schemaUrl']);\nconst OTLP_RESOURCE_FIELDS = new Set(['attributes', 'droppedAttributesCount']);\nconst OTLP_SCOPE_SPAN_FIELDS = new Set(['scope', 'spans', 'schemaUrl']);\nconst OTLP_SCOPE_FIELDS = new Set(['name', 'version', 'attributes', 'droppedAttributesCount']);\nconst OTLP_SPAN_FIELDS = new Set([\n 'traceId',\n 'spanId',\n 'parentSpanId',\n 'traceState',\n 'name',\n 'kind',\n 'startTimeUnixNano',\n 'endTimeUnixNano',\n 'attributes',\n 'droppedAttributesCount',\n 'events',\n 'droppedEventsCount',\n 'links',\n 'droppedLinksCount',\n 'status',\n]);\nconst OTLP_EVENT_FIELDS = new Set(['timeUnixNano', 'name', 'attributes', 'droppedAttributesCount']);\nconst OTLP_STATUS_FIELDS = new Set(['code', 'message']);\nconst OTLP_ATTRIBUTE_FIELDS = new Set(['key', 'value']);\nconst OTLP_ANY_VALUE_FIELDS = new Set([\n 'stringValue',\n 'boolValue',\n 'intValue',\n 'doubleValue',\n 'arrayValue',\n 'kvlistValue',\n 'bytesValue',\n]);\n\nexport function normalizeTraceArtifactToTraceSessionResponse(\n input: unknown,\n options: TraceArtifactNormalizationOptions = {},\n): TraceArtifactNormalizationResult {\n const artifact = asRecord(input);\n if (!artifact) {\n return {\n status: 'unsupported',\n message: 'Trace artifact is not a JSON object.',\n };\n }\n\n if (stringValue(artifact.schema_version) === EXECUTION_TRACE_SCHEMA_VERSION) {\n return normalizeAgentVTraceEnvelope(artifact, options);\n }\n\n if (Object.hasOwn(artifact, 'resourceSpans')) {\n return normalizeOtlpJson(artifact, options);\n }\n\n return {\n status: 'unsupported',\n message: 'Trace artifact is not an agentv.trace.v1 envelope or OTLP JSON resourceSpans body.',\n };\n}\n\nfunction normalizeAgentVTraceEnvelope(\n artifact: Record<string, unknown>,\n options: TraceArtifactNormalizationOptions,\n): TraceArtifactNormalizationResult {\n const trace = asRecord(artifact.trace);\n if (!Array.isArray(trace?.spans)) {\n return {\n status: 'unsupported',\n message: 'Trace artifact is not an agentv.trace.v1 envelope with trace.spans.',\n };\n }\n\n const traceSession = traceEnvelopeToTraceSessionResponse(artifact, options);\n return {\n status: 'ok',\n format: 'agentv_trace_v1',\n traceSession,\n warnings: traceSession.conversion_warnings,\n };\n}\n\nfunction normalizeOtlpJson(\n artifact: Record<string, unknown>,\n options: TraceArtifactNormalizationOptions,\n): TraceArtifactNormalizationResult {\n const warnings: WarningSink = [];\n warnUnknownFields(artifact, OTLP_ROOT_FIELDS, warnings, {\n rawKind: 'otlp_json',\n path: options.artifactPath,\n });\n\n const resourceSpans = Array.isArray(artifact.resourceSpans) ? artifact.resourceSpans : [];\n if (!Array.isArray(artifact.resourceSpans)) {\n addWarning(warnings, 'malformed_otlp_resource_spans', 'OTLP resourceSpans must be an array.', {\n rawKind: 'otlp_json',\n path: options.artifactPath,\n });\n }\n\n const spans: NormalizedOtlpSpan[] = [];\n const resourceAttributeSets: Record<string, unknown>[] = [];\n let scopeSpanCount = 0;\n let firstScope: { name?: string; version?: string } | undefined;\n\n resourceSpans.forEach((resourceSpan, resourceSpanIndex) => {\n const resourceRecord = asRecord(resourceSpan);\n if (!resourceRecord) {\n addWarning(\n warnings,\n 'malformed_otlp_resource_span',\n 'OTLP resourceSpans entry must be an object and was skipped.',\n {\n rawKind: 'otlp_resource_span',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex },\n },\n );\n return;\n }\n\n warnUnknownFields(resourceRecord, OTLP_RESOURCE_SPAN_FIELDS, warnings, {\n rawKind: 'otlp_resource_span',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex },\n });\n\n const resource = asRecord(resourceRecord.resource);\n if (resource) {\n warnUnknownFields(resource, OTLP_RESOURCE_FIELDS, warnings, {\n rawKind: 'otlp_resource',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex },\n });\n }\n const resourceAttributes = parseOtlpAttributes(resource?.attributes, warnings, {\n rawKind: 'otlp_resource_attributes',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex },\n });\n if (resourceAttributes && Object.keys(resourceAttributes).length > 0) {\n resourceAttributeSets.push(resourceAttributes);\n }\n\n const scopeSpans = Array.isArray(resourceRecord.scopeSpans) ? resourceRecord.scopeSpans : [];\n if (!Array.isArray(resourceRecord.scopeSpans)) {\n addWarning(\n warnings,\n 'malformed_otlp_scope_spans',\n 'OTLP resourceSpans.scopeSpans must be an array and was skipped.',\n {\n rawKind: 'otlp_resource_span',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex },\n },\n );\n }\n\n scopeSpans.forEach((scopeSpan, scopeSpanIndex) => {\n const scopeSpanRecord = asRecord(scopeSpan);\n if (!scopeSpanRecord) {\n addWarning(\n warnings,\n 'malformed_otlp_scope_span',\n 'OTLP scopeSpans entry must be an object and was skipped.',\n {\n rawKind: 'otlp_scope_span',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex, scope_span_index: scopeSpanIndex },\n },\n );\n return;\n }\n\n scopeSpanCount += 1;\n warnUnknownFields(scopeSpanRecord, OTLP_SCOPE_SPAN_FIELDS, warnings, {\n rawKind: 'otlp_scope_span',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex, scope_span_index: scopeSpanIndex },\n });\n\n const scope = normalizeOtlpScope(scopeSpanRecord.scope, warnings, {\n rawKind: 'otlp_scope',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex, scope_span_index: scopeSpanIndex },\n });\n firstScope ??= scope;\n\n const otlpSpans = Array.isArray(scopeSpanRecord.spans) ? scopeSpanRecord.spans : [];\n if (!Array.isArray(scopeSpanRecord.spans)) {\n addWarning(\n warnings,\n 'malformed_otlp_spans',\n 'OTLP scopeSpans.spans must be an array and was skipped.',\n {\n rawKind: 'otlp_scope_span',\n path: options.artifactPath,\n details: { resource_span_index: resourceSpanIndex, scope_span_index: scopeSpanIndex },\n },\n );\n }\n\n otlpSpans.forEach((span, spanIndex) => {\n const normalized = normalizeOtlpSpan(span, warnings, {\n resourceAttributes,\n path: options.artifactPath,\n resourceSpanIndex,\n scopeSpanIndex,\n spanIndex,\n });\n if (normalized) {\n spans.push(normalized);\n }\n });\n });\n });\n\n if (spans.length === 0) {\n addWarning(warnings, 'empty_otlp_trace', 'OTLP JSON did not contain any readable spans.', {\n rawKind: 'otlp_json',\n path: options.artifactPath,\n });\n }\n\n const traceId = firstString(spans.map((span) => span.trace_id));\n const rootSpanId = firstRootSpanId(spans);\n const resourceAttributes = singleDistinctRecord(resourceAttributeSets);\n const createdAt = (options.now?.() ?? new Date()).toISOString();\n const artifactPath = options.artifactPath;\n const envelope = dropUndefined({\n schema_version: EXECUTION_TRACE_SCHEMA_VERSION,\n artifact_id: `otlp-trace-${traceId ?? rootSpanId ?? 'unknown'}`,\n created_at: createdAt,\n eval: dropUndefined({\n run_id: options.runId,\n test_id: options.testId ?? traceId ?? 'otlp-trace',\n suite: options.suite,\n target: options.target ?? 'unknown',\n }),\n trace: dropUndefined({\n format: TRACE_ENVELOPE_FORMAT,\n trace_id: traceId,\n root_span_id: rootSpanId,\n resource: resourceAttributes ? { attributes: resourceAttributes } : undefined,\n scope: firstScope,\n spans,\n }),\n source: dropUndefined({\n kind: 'otlp',\n path: artifactPath,\n format: 'otlp_json',\n version: '1',\n metadata: dropUndefined({\n resource_spans_count: resourceSpans.length,\n scope_spans_count: scopeSpanCount,\n }),\n }),\n capture: {\n content: 'metadata',\n redaction_level: 'partial',\n },\n conversion_warnings: warnings.length > 0 ? warnings : undefined,\n artifacts: artifactPath ? { raw_trace_path: artifactPath } : undefined,\n });\n\n const traceSession = traceEnvelopeToTraceSessionResponse(envelope, options);\n return {\n status: 'ok',\n format: 'otlp_json',\n traceSession,\n warnings: traceSession.conversion_warnings,\n };\n}\n\nfunction normalizeOtlpScope(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): { name?: string; version?: string } | undefined {\n if (value === undefined) {\n return undefined;\n }\n const scope = asRecord(value);\n if (!scope) {\n addWarning(warnings, 'malformed_otlp_scope', 'OTLP scope must be an object and was ignored.', {\n ...context,\n rawKind: context.rawKind ?? 'otlp_scope',\n });\n return undefined;\n }\n warnUnknownFields(scope, OTLP_SCOPE_FIELDS, warnings, context);\n const normalized = dropUndefined({\n name: stringValue(scope.name),\n version: stringValue(scope.version),\n });\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeOtlpSpan(\n value: unknown,\n warnings: WarningSink,\n context: {\n readonly resourceAttributes?: Record<string, unknown>;\n readonly path?: string;\n readonly resourceSpanIndex: number;\n readonly scopeSpanIndex: number;\n readonly spanIndex: number;\n },\n): NormalizedOtlpSpan | undefined {\n const span = asRecord(value);\n const details = {\n resource_span_index: context.resourceSpanIndex,\n scope_span_index: context.scopeSpanIndex,\n span_index: context.spanIndex,\n };\n if (!span) {\n addWarning(warnings, 'malformed_otlp_span', 'OTLP span must be an object and was skipped.', {\n rawKind: 'otlp_span',\n path: context.path,\n details,\n });\n return undefined;\n }\n\n warnUnknownFields(span, OTLP_SPAN_FIELDS, warnings, {\n rawKind: 'otlp_span',\n path: context.path,\n details,\n });\n\n const spanId =\n stringValue(span.spanId) ??\n `missing-span-${context.resourceSpanIndex}-${context.scopeSpanIndex}-${context.spanIndex}`;\n if (!stringValue(span.spanId)) {\n addWarning(\n warnings,\n 'missing_span_id',\n 'OTLP span was missing spanId; a stable ID was assigned.',\n {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n },\n );\n }\n\n const traceId = stringValue(span.traceId);\n if (!traceId) {\n addWarning(warnings, 'missing_trace_id', 'OTLP span was missing traceId.', {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n });\n }\n\n const name = stringValue(span.name) ?? spanId;\n if (!stringValue(span.name)) {\n addWarning(warnings, 'missing_span_name', 'OTLP span was missing name; spanId was used.', {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n });\n }\n\n const parentSpanId =\n span.parentSpanId === undefined || span.parentSpanId === null || span.parentSpanId === ''\n ? null\n : stringValue(span.parentSpanId);\n if (\n span.parentSpanId !== undefined &&\n span.parentSpanId !== null &&\n span.parentSpanId !== '' &&\n !parentSpanId\n ) {\n addWarning(\n warnings,\n 'malformed_parent_span_id',\n 'OTLP span parentSpanId was not a string and was ignored.',\n {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n },\n );\n }\n\n const attributes = parseOtlpAttributes(span.attributes, warnings, {\n rawKind: 'otlp_span_attributes',\n path: context.path,\n spanId,\n details,\n });\n const events = normalizeOtlpEvents(span.events, warnings, {\n path: context.path,\n spanId,\n details,\n });\n\n return dropUndefined({\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n name,\n kind: normalizeOtlpSpanKind(span.kind, warnings, {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n }),\n start_time_unix_nano: normalizeUnixNano(span.startTimeUnixNano, 'startTimeUnixNano', warnings, {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n }),\n end_time_unix_nano: normalizeUnixNano(span.endTimeUnixNano, 'endTimeUnixNano', warnings, {\n rawKind: 'otlp_span',\n path: context.path,\n spanId,\n details,\n }),\n status: normalizeOtlpStatus(span.status, warnings, {\n rawKind: 'otlp_span_status',\n path: context.path,\n spanId,\n details,\n }),\n resource_attributes: context.resourceAttributes,\n attributes,\n events,\n });\n}\n\nfunction normalizeOtlpEvents(\n value: unknown,\n warnings: WarningSink,\n context: {\n readonly path?: string;\n readonly spanId: string;\n readonly details: Record<string, unknown>;\n },\n):\n | readonly {\n readonly name: string;\n readonly time_unix_nano?: string;\n readonly attributes?: Record<string, unknown>;\n }[]\n | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!Array.isArray(value)) {\n addWarning(warnings, 'malformed_otlp_events', 'OTLP span events must be an array.', {\n rawKind: 'otlp_span_events',\n path: context.path,\n spanId: context.spanId,\n details: context.details,\n });\n return undefined;\n }\n\n const events = value.flatMap((event, eventIndex) => {\n const eventRecord = asRecord(event);\n const details = { ...context.details, event_index: eventIndex };\n if (!eventRecord) {\n addWarning(\n warnings,\n 'malformed_otlp_event',\n 'OTLP span event must be an object and was skipped.',\n {\n rawKind: 'otlp_span_event',\n path: context.path,\n spanId: context.spanId,\n details,\n },\n );\n return [];\n }\n\n warnUnknownFields(eventRecord, OTLP_EVENT_FIELDS, warnings, {\n rawKind: 'otlp_span_event',\n path: context.path,\n spanId: context.spanId,\n details,\n });\n\n const name = stringValue(eventRecord.name) ?? `event-${eventIndex}`;\n if (!stringValue(eventRecord.name)) {\n addWarning(\n warnings,\n 'missing_event_name',\n 'OTLP span event was missing name; a stable name was assigned.',\n {\n rawKind: 'otlp_span_event',\n path: context.path,\n spanId: context.spanId,\n details,\n },\n );\n }\n\n return [\n dropUndefined({\n name,\n time_unix_nano: normalizeUnixNano(eventRecord.timeUnixNano, 'timeUnixNano', warnings, {\n rawKind: 'otlp_span_event',\n path: context.path,\n spanId: context.spanId,\n details,\n }),\n attributes: parseOtlpAttributes(eventRecord.attributes, warnings, {\n rawKind: 'otlp_event_attributes',\n path: context.path,\n spanId: context.spanId,\n details,\n }),\n }),\n ];\n });\n\n return events.length > 0 ? events : undefined;\n}\n\nfunction parseOtlpAttributes(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): Record<string, unknown> | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (asRecord(value)) {\n addWarning(\n warnings,\n 'nonstandard_otlp_attribute_map',\n 'OTLP attributes were an object map; values were preserved as-is.',\n context,\n );\n return value as Record<string, unknown>;\n }\n if (!Array.isArray(value)) {\n addWarning(warnings, 'malformed_otlp_attributes', 'OTLP attributes must be an array.', context);\n return undefined;\n }\n\n const attributes: Record<string, unknown> = {};\n value.forEach((attribute, attributeIndex) => {\n const attributeRecord = asRecord(attribute);\n const details = { ...(context.details ?? {}), attribute_index: attributeIndex };\n if (!attributeRecord) {\n addWarning(\n warnings,\n 'malformed_otlp_attribute',\n 'OTLP attribute must be an object and was skipped.',\n { ...context, details },\n );\n return;\n }\n\n warnUnknownFields(attributeRecord, OTLP_ATTRIBUTE_FIELDS, warnings, {\n ...context,\n rawKind: context.rawKind ?? 'otlp_attribute',\n details,\n });\n\n const key = stringValue(attributeRecord.key);\n if (!key) {\n addWarning(\n warnings,\n 'malformed_otlp_attribute',\n 'OTLP attribute was missing key and was skipped.',\n {\n ...context,\n details,\n },\n );\n return;\n }\n\n if (Object.hasOwn(attributes, key)) {\n addWarning(\n warnings,\n 'duplicate_otlp_attribute',\n `OTLP attribute \"${key}\" appeared more than once; the last value was used.`,\n {\n ...context,\n details: { ...details, key },\n },\n );\n }\n\n const parsed = parseOtlpAnyValue(attributeRecord.value, warnings, {\n ...context,\n rawKind: 'otlp_attribute_value',\n details: { ...details, key },\n });\n if (parsed.ok) {\n attributes[key] = parsed.value;\n }\n });\n\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n}\n\nfunction parseOtlpAnyValue(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): ParsedOtlpValue {\n if (isPrimitive(value)) {\n addWarning(\n warnings,\n 'nonstandard_otlp_value',\n 'OTLP attribute value was primitive; value was preserved as-is.',\n context,\n );\n return { ok: true, value };\n }\n\n const record = asRecord(value);\n if (!record) {\n addWarning(\n warnings,\n 'malformed_otlp_value',\n 'OTLP attribute value must be an object.',\n context,\n );\n return { ok: false };\n }\n\n const presentFields = Object.keys(record).filter((key) => OTLP_ANY_VALUE_FIELDS.has(key));\n const unknownFields = Object.keys(record).filter((key) => !OTLP_ANY_VALUE_FIELDS.has(key));\n if (unknownFields.length > 0) {\n addWarning(\n warnings,\n 'unknown_otlp_value_field',\n `Unknown OTLP attribute value field(s) ignored: ${unknownFields.join(', ')}.`,\n { ...context, details: { ...(context.details ?? {}), fields: unknownFields } },\n );\n }\n if (presentFields.length > 1) {\n addWarning(\n warnings,\n 'ambiguous_otlp_value',\n `OTLP attribute value had multiple value fields; ${presentFields[0]} was used.`,\n { ...context, details: { ...(context.details ?? {}), fields: presentFields } },\n );\n }\n\n const field = presentFields[0];\n if (!field) {\n addWarning(\n warnings,\n 'malformed_otlp_value',\n 'OTLP attribute value did not contain a recognized value field; raw value was preserved.',\n context,\n );\n return { ok: true, value };\n }\n\n switch (field) {\n case 'stringValue':\n case 'bytesValue':\n return { ok: true, value: stringValue(record[field]) ?? String(record[field] ?? '') };\n case 'boolValue':\n return { ok: true, value: Boolean(record.boolValue) };\n case 'intValue':\n return { ok: true, value: integerOrString(record.intValue) };\n case 'doubleValue':\n return { ok: true, value: numberOrString(record.doubleValue) };\n case 'arrayValue':\n return parseOtlpArrayValue(record.arrayValue, warnings, context);\n case 'kvlistValue':\n return parseOtlpKeyValueList(record.kvlistValue, warnings, context);\n default:\n return { ok: true, value };\n }\n}\n\nfunction parseOtlpArrayValue(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): ParsedOtlpValue {\n const arrayValue = asRecord(value);\n if (!arrayValue || !Array.isArray(arrayValue.values)) {\n addWarning(\n warnings,\n 'malformed_otlp_array_value',\n 'OTLP arrayValue.values must be an array.',\n context,\n );\n return { ok: false };\n }\n return {\n ok: true,\n value: arrayValue.values.map(\n (entry, index) =>\n parseOtlpAnyValue(entry, warnings, {\n ...context,\n details: { ...(context.details ?? {}), value_index: index },\n }).value,\n ),\n };\n}\n\nfunction parseOtlpKeyValueList(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): ParsedOtlpValue {\n const kvlistValue = asRecord(value);\n if (!kvlistValue || !Array.isArray(kvlistValue.values)) {\n addWarning(\n warnings,\n 'malformed_otlp_kvlist_value',\n 'OTLP kvlistValue.values must be an array.',\n context,\n );\n return { ok: false };\n }\n return {\n ok: true,\n value: parseOtlpAttributes(kvlistValue.values, warnings, context) ?? {},\n };\n}\n\nfunction normalizeOtlpSpanKind(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === 'string' && value.length > 0) {\n return value.replace(/^SPAN_KIND_/, '');\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n addWarning(\n warnings,\n 'malformed_span_kind',\n 'OTLP span kind was not a string or integer.',\n context,\n );\n return undefined;\n }\n if (value === 0) return 'INTERNAL';\n if (value === 1) return 'SERVER';\n if (value === 2) return 'CLIENT';\n if (value === 3) return 'PRODUCER';\n if (value === 4 || value === 5) return 'CONSUMER';\n addWarning(\n warnings,\n 'unknown_span_kind',\n `Unknown OTLP span kind ${value} was preserved as a string.`,\n context,\n );\n return String(value);\n}\n\nfunction normalizeOtlpStatus(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): { code?: string; message?: string } | undefined {\n if (value === undefined) {\n return undefined;\n }\n const status = asRecord(value);\n if (!status) {\n addWarning(warnings, 'malformed_otlp_status', 'OTLP span status must be an object.', context);\n return undefined;\n }\n warnUnknownFields(status, OTLP_STATUS_FIELDS, warnings, context);\n return dropUndefined({\n code: normalizeStatusCode(status.code, warnings, context),\n message: stringValue(status.message),\n });\n}\n\nfunction normalizeStatusCode(\n value: unknown,\n warnings: WarningSink,\n context: WarningContext,\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === 'string' && value.length > 0) {\n return value.replace(/^STATUS_CODE_/, '');\n }\n if (typeof value === 'number' && Number.isInteger(value)) {\n if (value === 0) return 'UNSET';\n if (value === 1) return 'OK';\n if (value === 2) return 'ERROR';\n addWarning(\n warnings,\n 'unknown_status_code',\n `Unknown OTLP status code ${value} was preserved as a string.`,\n context,\n );\n return String(value);\n }\n addWarning(\n warnings,\n 'malformed_status_code',\n 'OTLP status code was not a string or integer.',\n context,\n );\n return undefined;\n}\n\nfunction normalizeUnixNano(\n value: unknown,\n field: string,\n warnings: WarningSink,\n context: WarningContext,\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === 'string' && value.length > 0) {\n if (!/^\\d+$/.test(value)) {\n addWarning(\n warnings,\n 'malformed_unix_nano',\n `OTLP ${field} was not an unsigned integer string.`,\n context,\n );\n }\n return value;\n }\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {\n return String(Math.trunc(value));\n }\n addWarning(warnings, 'malformed_unix_nano', `OTLP ${field} was not a string or number.`, context);\n return undefined;\n}\n\nfunction firstRootSpanId(spans: readonly NormalizedOtlpSpan[]): string | undefined {\n const spanIds = new Set(spans.map((span) => span.span_id));\n return (\n spans.find(\n (span) =>\n !span.parent_span_id ||\n (typeof span.parent_span_id === 'string' && !spanIds.has(span.parent_span_id)),\n )?.span_id ?? spans[0]?.span_id\n );\n}\n\nfunction singleDistinctRecord(\n records: readonly Record<string, unknown>[],\n): Record<string, unknown> | undefined {\n if (records.length === 0) {\n return undefined;\n }\n const unique = new Map(records.map((record) => [stableRecordKey(record), record]));\n return unique.size === 1 ? [...unique.values()][0] : undefined;\n}\n\nfunction stableRecordKey(record: Record<string, unknown>): string {\n return JSON.stringify(\n Object.keys(record)\n .sort()\n .map((key) => [key, record[key]]),\n );\n}\n\nfunction firstString(values: readonly (string | undefined)[]): string | undefined {\n return values.find((value): value is string => typeof value === 'string' && value.length > 0);\n}\n\nfunction integerOrString(value: unknown): number | string {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string') {\n const numberValue = Number(value);\n return Number.isSafeInteger(numberValue) ? numberValue : value;\n }\n return String(value ?? '');\n}\n\nfunction numberOrString(value: unknown): number | string {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string') {\n const numberValue = Number(value);\n return Number.isFinite(numberValue) ? numberValue : value;\n }\n return String(value ?? '');\n}\n\nfunction warnUnknownFields(\n record: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n warnings: WarningSink,\n context: WarningContext,\n): void {\n const unknownFields = Object.keys(record).filter((key) => !allowed.has(key));\n for (const field of unknownFields) {\n addWarning(\n warnings,\n 'unknown_otlp_field',\n `Unknown OTLP ${context.rawKind ?? 'object'} field \"${field}\" was ignored.`,\n { ...context, details: { ...(context.details ?? {}), field } },\n );\n }\n}\n\nfunction addWarning(\n warnings: WarningSink,\n code: string,\n message: string,\n context: WarningContext = {},\n): void {\n warnings.push(\n dropUndefined({\n code,\n severity: 'warning',\n span_id: context.spanId,\n source_ref:\n context.path || context.rawKind\n ? dropUndefined({\n path: context.path,\n raw_kind: context.rawKind,\n span_id: context.spanId,\n })\n : undefined,\n message,\n details: context.details,\n }) as TraceSessionConversionWarning,\n );\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction isPrimitive(value: unknown): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n value === null\n );\n}\n\nfunction dropUndefined<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n","/**\n * EVAL.yaml → evals.json transpiler.\n *\n * Converts an AgentV EVAL.yaml file into Agent Skills evals.json format\n * for consumption by the skill-creator pipeline.\n *\n * Handles canonical `assert:` entries.\n */\n\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\n\nimport { parseYamlValue } from '../yaml-loader.js';\n\n// ---------------------------------------------------------------------------\n// evals.json output types\n// ---------------------------------------------------------------------------\n\nexport interface EvalsJsonCase {\n id: number;\n prompt: string;\n expected_output?: string;\n files?: string[];\n should_trigger?: boolean;\n assertions: string[];\n}\n\nexport interface EvalsJsonFile {\n skill_name: string;\n evals: EvalsJsonCase[];\n}\n\n// ---------------------------------------------------------------------------\n// Raw YAML input types (unvalidated)\n// ---------------------------------------------------------------------------\n\ntype RawContent =\n | string\n | Array<{ type?: string; value?: string; [key: string]: unknown }>\n | unknown;\n\ninterface RawMessage {\n role?: string;\n content?: RawContent;\n [key: string]: unknown;\n}\n\ninterface RawAssertEntry {\n type?: string;\n skill?: string;\n should_trigger?: boolean;\n criteria?: string;\n value?: unknown;\n metric?: string;\n description?: string;\n command?: unknown;\n prompt?: string;\n rubrics?: unknown[];\n expected?: unknown[];\n fields?: unknown[];\n threshold?: number;\n budget?: number;\n [key: string]: unknown;\n}\n\ninterface RawTestCase {\n id?: string | number;\n criteria?: string;\n input?: string | RawMessage[] | { [key: string]: unknown };\n input_files?: string[];\n expected_output?: string | RawMessage[] | unknown;\n assert?: RawAssertEntry[];\n [key: string]: unknown;\n}\n\ninterface RawSuite {\n tests?: RawTestCase[];\n assert?: RawAssertEntry[];\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Assertion → natural language conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Build an NL instruction string for a script grader that tells the grading agent\n * how to execute it via `agentv eval assert`.\n *\n * The `<agent_output>` and `<original_prompt>` placeholders are substituted\n * by the grading agent at evaluation time.\n */\nfunction scriptGraderInstruction(graderName: string, description?: string): string {\n const desc = description ? ` This grader: ${description}.` : '';\n return `Run \\`agentv eval assert ${graderName} --agent-output <agent_output> --agent-input <original_prompt>\\` and check the result.${desc} The command accepts --agent-output (the agent's full response text) and --agent-input (the original user prompt). It returns JSON on stdout: {\"score\": 0-1, \"reasoning\": \"...\"}. A score >= 0.5 means pass (exit 0); below 0.5 means fail (exit 1).`;\n}\n\n/**\n * Derive a grader name from a command array by finding the first argument\n * with a recognised script extension (e.g. `['bun', 'run', '.agentv/graders/format-checker.ts']` → `'format-checker'`).\n */\nfunction deriveGraderNameFromCommand(command: unknown): string | undefined {\n if (!Array.isArray(command) || command.length === 0) return undefined;\n for (const arg of command) {\n if (typeof arg !== 'string') continue;\n const match = arg.match(/([^/]+)\\.(ts|js|mts|mjs)$/);\n if (match) return match[1] || undefined;\n }\n return undefined;\n}\n\nfunction assertionToNaturalLanguage(entry: RawAssertEntry): string | null {\n const type = entry.type;\n\n switch (type) {\n case 'skill-trigger':\n // Handled separately — not an NL assertion\n return null;\n\n case 'llm-rubric':\n return typeof entry.value === 'string' ? entry.value : null;\n\n case 'contains':\n return `Output contains '${entry.value}'`;\n\n case 'contains-any': {\n const values = Array.isArray(entry.value)\n ? (entry.value as string[]).join(\"', '\")\n : entry.value;\n return `Output contains any of: '${values}'`;\n }\n\n case 'contains-all': {\n const values = Array.isArray(entry.value)\n ? (entry.value as string[]).join(\"', '\")\n : entry.value;\n return `Output contains all of: '${values}'`;\n }\n\n case 'icontains':\n return `Output contains (case-insensitive) '${entry.value}'`;\n\n case 'regex':\n return `Output matches regex: ${entry.value}`;\n\n case 'equals':\n return `Output exactly equals: ${entry.value}`;\n\n case 'is-json':\n return 'Output is valid JSON';\n\n case 'starts-with':\n return `Output starts with '${entry.value}'`;\n\n case 'ends-with':\n return `Output ends with '${entry.value}'`;\n\n case 'llm-grader':\n // Expand each rubric item to its own assertion string\n // Return the first one — callers handle arrays via assertionToNaturalLanguageList\n if (Array.isArray(entry.rubrics) && entry.rubrics.length > 0) {\n return null; // handled by list expansion below\n }\n return typeof entry.prompt === 'string' ? entry.prompt : null;\n\n case 'tool-trajectory': {\n const expectedArr = Array.isArray(entry.expected) ? entry.expected : [];\n const tools = (expectedArr as Array<{ tool?: string }>)\n .map((e) => e.tool)\n .filter(Boolean)\n .join(', ');\n return tools\n ? `Agent called tools in order: ${tools}`\n : 'Agent followed expected tool trajectory';\n }\n\n case 'script': {\n const graderName = entry.metric ?? deriveGraderNameFromCommand(entry.command) ?? 'script';\n const desc = typeof entry.description === 'string' ? entry.description : undefined;\n return scriptGraderInstruction(graderName, desc);\n }\n\n case 'field-accuracy': {\n const fieldPaths = Array.isArray(entry.fields)\n ? (entry.fields as Array<{ path?: string }>)\n .map((f) => f.path)\n .filter(Boolean)\n .join(', ')\n : '';\n return fieldPaths\n ? `Fields ${fieldPaths} match expected values`\n : 'Fields match expected values';\n }\n\n case 'latency':\n return typeof entry.threshold === 'number'\n ? `Response time under ${entry.threshold}ms`\n : 'Response time within threshold';\n\n case 'cost':\n return typeof entry.budget === 'number'\n ? `Cost under $${entry.budget}`\n : 'Cost within budget';\n\n case 'token-usage':\n return 'Token usage within limits';\n\n case 'execution-metrics':\n return 'Execution within metric bounds';\n\n default: {\n // Unknown type with a command -> treat as a script grader.\n if (entry.command !== undefined && type) {\n return scriptGraderInstruction(deriveGraderNameFromCommand(entry.command) ?? type);\n }\n // Fallback: try to produce something readable\n if (typeof entry.criteria === 'string') return entry.criteria;\n if (typeof entry.prompt === 'string') return entry.prompt;\n return type ? `${type} assertion` : null;\n }\n }\n}\n\n/**\n * Expand a single assertion entry into zero or more NL strings.\n * Most assertions produce exactly one string; llm-grader with rubrics expands to many.\n */\nfunction assertionToNaturalLanguageList(entry: RawAssertEntry): string[] {\n if (entry.type === 'llm-rubric') {\n if (Array.isArray(entry.value) && entry.value.length > 0) {\n return entry.value\n .map((rubric) => {\n if (typeof rubric === 'string') return rubric;\n if (!rubric || typeof rubric !== 'object') return undefined;\n const item = rubric as { outcome?: string; criteria?: string; id?: string };\n return item.outcome ?? item.criteria ?? item.id;\n })\n .filter((value): value is string => typeof value === 'string');\n }\n }\n if (entry.type === 'llm-grader') {\n if (Array.isArray(entry.rubrics) && entry.rubrics.length > 0) {\n return (entry.rubrics as Array<{ outcome?: string; criteria?: string; id?: string }>)\n .map((r) => r.outcome ?? r.criteria ?? r.id)\n .filter((s): s is string => typeof s === 'string');\n }\n }\n const nl = assertionToNaturalLanguage(entry);\n return nl !== null ? [nl] : [];\n}\n\n/**\n * Extract skill-trigger entries from an assertion list.\n * Returns entries with type === 'skill-trigger'.\n */\nfunction extractTriggerAssertions(assertions: RawAssertEntry[]): RawAssertEntry[] {\n return assertions.filter((a) => a.type === 'skill-trigger');\n}\n\n// ---------------------------------------------------------------------------\n// Input extraction\n// ---------------------------------------------------------------------------\n\ninterface ExtractedInput {\n prompt: string;\n files: string[];\n}\n\n/**\n * Extract prompt text and file paths from a test case input.\n *\n * Supports:\n * - String input → prompt, no files\n * - Message array with role: user and content blocks\n * - input_files shorthand (alongside string or message-array input)\n */\nfunction extractInput(rawCase: RawTestCase): ExtractedInput {\n const files: string[] = Array.isArray(rawCase.input_files)\n ? (rawCase.input_files as string[]).filter((f) => typeof f === 'string')\n : [];\n\n const input = rawCase.input;\n\n if (typeof input === 'string') {\n return { prompt: input, files };\n }\n\n if (Array.isArray(input)) {\n let prompt = '';\n for (const msg of input as RawMessage[]) {\n if (msg.role !== 'user') continue;\n if (typeof msg.content === 'string') {\n prompt = msg.content;\n } else if (Array.isArray(msg.content)) {\n for (const block of msg.content as Array<{ type?: string; value?: string }>) {\n if (block.type === 'text' && typeof block.value === 'string') prompt = block.value;\n else if (block.type === 'file' && typeof block.value === 'string')\n files.push(block.value);\n }\n }\n }\n return { prompt, files };\n }\n\n return { prompt: '', files };\n}\n\n/**\n * Flatten expected_output to a string.\n * Accepts string, message array (takes last assistant message content),\n * or any other value serialized to JSON.\n */\nfunction extractExpectedOutput(raw: unknown): string | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw === 'string') return raw;\n\n if (Array.isArray(raw)) {\n // Take the last assistant message content\n for (let i = raw.length - 1; i >= 0; i--) {\n const msg = raw[i] as RawMessage;\n if (typeof msg.content === 'string') return msg.content;\n }\n return undefined;\n }\n\n return JSON.stringify(raw);\n}\n\n// ---------------------------------------------------------------------------\n// Transpiler core\n// ---------------------------------------------------------------------------\n\n/**\n * Result of transpiling a single EVAL.yaml.\n * May produce multiple evals.json files (one per skill).\n */\nexport interface TranspileResult {\n /** Map from skill_name → EvalsJsonFile */\n files: Map<string, EvalsJsonFile>;\n /** Warning messages accumulated during transpilation */\n warnings: string[];\n}\n\n/**\n * Transpile a parsed EVAL.yaml object into one or more evals.json objects.\n *\n * @param suite Parsed YAML object (already loaded, no file I/O here)\n * @param source Source identifier for error messages (e.g. file path)\n */\nexport function transpileEvalYaml(suite: unknown, source = 'EVAL.yaml'): TranspileResult {\n const files = new Map<string, EvalsJsonFile>();\n\n if (typeof suite !== 'object' || suite === null) {\n throw new Error(`Invalid EVAL.yaml: expected an object in '${source}'`);\n }\n\n const rawSuite = suite as RawSuite;\n\n if (!Array.isArray(rawSuite.tests)) {\n throw new Error(`Invalid EVAL.yaml: missing 'tests' array in '${source}'`);\n }\n\n const suiteAssertions = rawSuite.assert ?? [];\n\n // Suite-level NL assertions (appended to every test)\n const suiteNlAssertions: string[] = suiteAssertions\n .filter((a) => a.type !== 'skill-trigger')\n .flatMap(assertionToNaturalLanguageList);\n\n /**\n * Helper: get or create the EvalsJsonFile for a skill.\n */\n function getSkillFile(skillName: string): EvalsJsonFile {\n const existing = files.get(skillName);\n if (existing) return existing;\n const created: EvalsJsonFile = { skill_name: skillName, evals: [] };\n files.set(skillName, created);\n return created;\n }\n\n const tests = rawSuite.tests as RawTestCase[];\n\n for (let idx = 0; idx < tests.length; idx++) {\n const rawCase = tests[idx];\n const caseAssertions = rawCase.assert ?? [];\n\n if (\n typeof rawCase.criteria === 'string' &&\n rawCase.criteria.trim() &&\n rawCase.assert !== undefined\n ) {\n throw new Error(\n `Invalid EVAL.yaml test '${rawCase.id ?? idx + 1}' in '${source}': do not combine test-level 'criteria' with 'assert'. Put human-readable case descriptions in 'description', or express grading text as an explicit assertion such as { type: 'llm-rubric', value: ... }.`,\n );\n }\n\n // Collect NL assertions (not skill-trigger)\n const nlAssertions: string[] = [];\n\n // Prepend test-level criteria as NL assertion\n if (typeof rawCase.criteria === 'string' && rawCase.criteria.trim()) {\n nlAssertions.push(rawCase.criteria.trim());\n }\n\n for (const entry of caseAssertions) {\n if (entry.type !== 'skill-trigger') {\n nlAssertions.push(...assertionToNaturalLanguageList(entry));\n }\n }\n\n // Append suite-level NL assertions\n nlAssertions.push(...suiteNlAssertions);\n\n const triggerJudges = extractTriggerAssertions(caseAssertions);\n const { prompt, files: inputFiles } = extractInput(rawCase);\n const expectedOutput = extractExpectedOutput(rawCase.expected_output);\n\n // Build the numeric id (1-based index)\n const numericId = idx + 1;\n\n // Build the base case (without should_trigger — added per-skill below)\n const baseCase: Omit<EvalsJsonCase, 'should_trigger'> & { should_trigger?: boolean } = {\n id: numericId,\n prompt,\n ...(expectedOutput !== undefined && { expected_output: expectedOutput }),\n ...(inputFiles.length > 0 && { files: inputFiles }),\n assertions: nlAssertions,\n };\n\n if (triggerJudges.length === 0) {\n // No skill-trigger: place in dominant skill (or _no-skill)\n // Determine dominant skill by scanning all tests (first occurrence wins)\n // We defer this: record with a sentinel and resolve after all tests are processed.\n // For now, push to _no-skill; we'll re-assign at the end.\n const noSkillFile = getSkillFile('_no-skill');\n noSkillFile.evals.push({ ...baseCase });\n } else {\n // Place in each skill with the correct should_trigger value\n for (const tj of triggerJudges) {\n const skillName = typeof tj.skill === 'string' ? tj.skill : '_no-skill';\n const shouldTrigger = tj.should_trigger !== false; // default true\n const skillFile = getSkillFile(skillName);\n skillFile.evals.push({ ...baseCase, should_trigger: shouldTrigger });\n }\n }\n }\n\n // Re-assign _no-skill tests to the dominant skill (if one exists)\n const noSkillFile = files.get('_no-skill');\n if (noSkillFile && noSkillFile.evals.length > 0) {\n // Find the skill with the most tests (among real skills)\n let dominantSkill: string | null = null;\n let maxCount = 0;\n for (const [name, f] of files) {\n if (name !== '_no-skill' && f.evals.length > maxCount) {\n maxCount = f.evals.length;\n dominantSkill = name;\n }\n }\n\n if (dominantSkill) {\n const targetFile = getSkillFile(dominantSkill);\n for (const evalCase of noSkillFile.evals) {\n targetFile.evals.push(evalCase);\n }\n files.delete('_no-skill');\n }\n // else: keep _no-skill if there are no other skills\n }\n\n return { files, warnings: [] };\n}\n\n// ---------------------------------------------------------------------------\n// File-level API\n// ---------------------------------------------------------------------------\n\n/**\n * Transpile an EVAL.yaml file into one or more evals.json objects.\n * Returns a map from output filename → JSON content.\n *\n * @param evalYamlPath Absolute path to the EVAL.yaml file\n */\nexport function transpileEvalYamlFile(evalYamlPath: string): TranspileResult {\n const content = readFileSync(evalYamlPath, 'utf8');\n const parsed = parseYamlValue(content);\n return transpileEvalYaml(parsed, path.basename(evalYamlPath));\n}\n\n/**\n * Determine the output filename(s) for a transpile result.\n * Single skill → \"evals.json\"\n * Multiple skills → \"<skill>.evals.json\"\n */\nexport function getOutputFilenames(result: TranspileResult): Map<string, string> {\n const names = new Map<string, string>();\n if (result.files.size === 1) {\n for (const [skill] of result.files) {\n names.set(skill, 'evals.json');\n }\n } else {\n for (const [skill] of result.files) {\n const safeName = skill.replace(/[^a-zA-Z0-9_-]/g, '_');\n names.set(skill, `${safeName}.evals.json`);\n }\n }\n return names;\n}\n","/**\n * Prepared workspace API for external attempts.\n *\n * `prepareEvalWorkspace` materializes exactly one eval case for one target and\n * stops immediately before provider execution. It is the core primitive behind\n * `agentv prepare` and future prepared-attempt grading: callers get a workspace\n * path, prompt inputs, setup-hook history, repo pins, and baseline metadata, but\n * no target provider or grader is invoked here.\n *\n * The returned object uses internal camelCase names. Any CLI manifest writer\n * should translate these fields to snake_case at the disk boundary.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport micromatch from 'micromatch';\n\nimport type { ResolvedTarget } from './providers/targets.js';\nimport type { ChatPrompt } from './providers/types.js';\nimport { AGENT_PROVIDER_KINDS } from './providers/types.js';\nimport type { EvalTest, JsonObject, RepoConfig, TargetHooksConfig } from './types.js';\nimport {\n type SharedWorkspaceSetup,\n type WorkspaceSetupHookExecution,\n type WorkspaceSetupMode,\n type WorkspaceSetupRetentionPolicy,\n prepareEvalCaseWorkspace,\n prepareSharedWorkspaceSetup,\n releaseSharedWorkspaceSetup,\n} from './workspace/setup.js';\nimport { type PromptInputs, buildPromptInputs, loadTests } from './yaml-parser.js';\n\nexport interface PrepareEvalWorkspaceOptions {\n readonly testFilePath: string;\n readonly repoRoot: URL | string;\n readonly target: ResolvedTarget;\n readonly targetHooks?: TargetHooksConfig;\n readonly evalCases?: readonly EvalTest[];\n /** Exact test id to prepare. */\n readonly testId?: string;\n /** Glob filter used when `testId` is not supplied. Must resolve to one case. */\n readonly filter?: string | readonly string[];\n readonly verbose?: boolean;\n readonly now?: () => Date;\n readonly maxConcurrency?: number;\n /** Legacy static workspace path override. */\n readonly workspace?: string;\n readonly workspacePath?: string;\n readonly keepWorkspaces?: boolean;\n readonly cleanupWorkspaces?: boolean;\n readonly retainOnSuccess?: WorkspaceSetupRetentionPolicy;\n readonly retainOnFailure?: WorkspaceSetupRetentionPolicy;\n}\n\nexport interface PreparedWorkspaceRepoPin {\n readonly path?: string;\n readonly repo?: string;\n readonly commit?: string;\n readonly ancestor?: number;\n readonly sparse?: readonly string[];\n}\n\nexport interface PreparedWorkspaceBaseline {\n readonly status: 'initialized' | 'unavailable';\n readonly commit?: string;\n}\n\nexport interface PreparedWorkspacePromptSource {\n readonly kind: 'eval_case';\n readonly formattingMode: 'agent' | 'lm';\n readonly question: string;\n readonly systemMessage?: string;\n readonly chatPrompt?: ChatPrompt;\n}\n\nexport interface PreparedWorkspaceCleanupPolicy {\n readonly mode: WorkspaceSetupMode;\n readonly retainOnSuccess: WorkspaceSetupRetentionPolicy;\n readonly retainOnFailure: WorkspaceSetupRetentionPolicy;\n readonly manualCleanup: boolean;\n}\n\nexport interface PreparedEvalWorkspace {\n readonly evalPath: string;\n readonly testId: string;\n readonly target: string;\n readonly evalRunId: string;\n readonly workspacePath: string;\n readonly workspaceFile?: string;\n readonly createdAt: string;\n readonly hookExecutions: readonly WorkspaceSetupHookExecution[];\n readonly providerContext?: JsonObject;\n readonly metadata?: Record<string, unknown>;\n readonly repoPins: readonly PreparedWorkspaceRepoPin[];\n readonly baseline: PreparedWorkspaceBaseline;\n readonly promptSource: PreparedWorkspacePromptSource;\n readonly cleanupPolicy: PreparedWorkspaceCleanupPolicy;\n readonly sharedWorkspace: boolean;\n}\n\nfunction matchesFilter(id: string, filter: string | readonly string[]): boolean {\n return typeof filter === 'string'\n ? micromatch.isMatch(id, filter)\n : filter.some((pattern) => micromatch.isMatch(id, pattern));\n}\n\nfunction selectSingleCase(options: {\n readonly evalCases: readonly EvalTest[];\n readonly testId?: string;\n readonly filter?: string | readonly string[];\n readonly evalPath: string;\n}): EvalTest {\n const selected = options.testId\n ? options.evalCases.filter((evalCase) => evalCase.id === options.testId)\n : options.filter\n ? options.evalCases.filter((evalCase) => matchesFilter(evalCase.id, options.filter ?? ''))\n : options.evalCases;\n\n if (selected.length !== 1) {\n const selector = options.testId\n ? `test_id \"${options.testId}\"`\n : options.filter\n ? `filter \"${Array.isArray(options.filter) ? options.filter.join(',') : options.filter}\"`\n : 'the eval file';\n throw new Error(\n `prepareEvalWorkspace requires exactly one test, but ${selector} matched ${selected.length} in ${options.evalPath}.`,\n );\n }\n\n return selected[0];\n}\n\nfunction promptModeForTarget(target: ResolvedTarget): 'agent' | 'lm' {\n return AGENT_PROVIDER_KINDS.includes(target.kind) || target.kind === 'cli' ? 'agent' : 'lm';\n}\n\nfunction toRepoPins(repos: readonly RepoConfig[] | undefined): readonly PreparedWorkspaceRepoPin[] {\n return (repos ?? []).map((repo) => ({\n ...(repo.path !== undefined && { path: repo.path }),\n ...(repo.repo !== undefined && { repo: repo.repo }),\n ...(repo.commit !== undefined && { commit: repo.commit }),\n ...(repo.ancestor !== undefined && { ancestor: repo.ancestor }),\n ...(repo.sparse !== undefined && { sparse: repo.sparse }),\n }));\n}\n\nexport async function prepareEvalWorkspace(\n options: PrepareEvalWorkspaceOptions,\n): Promise<PreparedEvalWorkspace> {\n const evalPath = path.resolve(options.testFilePath);\n const evalRunId = randomUUID();\n const evalCases =\n options.evalCases ??\n (await loadTests(evalPath, options.repoRoot, {\n verbose: options.verbose,\n filter: options.testId ?? options.filter,\n }));\n const evalCase = selectSingleCase({\n evalCases,\n testId: options.testId,\n filter: options.filter,\n evalPath,\n });\n const evalDir = path.dirname(evalPath);\n const workers = options.maxConcurrency ?? 1;\n const retainOnSuccess = options.retainOnSuccess ?? (options.keepWorkspaces ? 'keep' : 'cleanup');\n const retainOnFailure =\n options.retainOnFailure ?? (options.cleanupWorkspaces ? 'cleanup' : 'keep');\n const formattingMode = promptModeForTarget(options.target);\n const promptInputs: PromptInputs = await buildPromptInputs(evalCase, formattingMode);\n\n let sharedSetup: SharedWorkspaceSetup | undefined;\n try {\n sharedSetup = await prepareSharedWorkspaceSetup({\n evalRunId,\n evalCases: [evalCase],\n targetHooks: options.targetHooks,\n evalDir,\n verbose: options.verbose,\n workers,\n workspacePath: options.workspacePath,\n legacyWorkspacePath: options.workspace,\n });\n\n const selectedWorkspacePath = sharedSetup.sharedWorkspacePath;\n const selectedBaselineCommit = sharedSetup.sharedBaselineCommit;\n\n const caseSetup = await prepareEvalCaseWorkspace({\n evalCase,\n targetName: options.target.name,\n evalRunId,\n sharedWorkspacePath: selectedWorkspacePath,\n sharedBaselineCommit: selectedBaselineCommit,\n suiteWorkspaceFile: sharedSetup.suiteWorkspaceFile,\n repoManager: sharedSetup.repoManager,\n evalDir,\n cleanupWorkspaces: options.cleanupWorkspaces,\n targetHooks: options.targetHooks,\n sharedExtensionState: sharedSetup.extensionState,\n setupDebug: options.verbose,\n });\n\n if (!caseSetup.workspacePath) {\n throw new Error(\n `No workspace was materialized for test \"${evalCase.id}\". Add environment.workdir before preparing an external attempt, or use an internal workspace override for private runtime plumbing.`,\n );\n }\n\n return {\n evalPath,\n testId: evalCase.id,\n target: options.target.name,\n evalRunId,\n workspacePath: caseSetup.workspacePath,\n ...(caseSetup.caseWorkspaceFile !== undefined && {\n workspaceFile: caseSetup.caseWorkspaceFile,\n }),\n createdAt: (options.now ?? (() => new Date()))().toISOString(),\n hookExecutions: [...sharedSetup.hookExecutions, ...caseSetup.hookExecutions],\n ...(caseSetup.extensionState?.providerContext !== undefined && {\n providerContext: caseSetup.extensionState.providerContext,\n }),\n ...(caseSetup.extensionState?.metadata !== undefined && {\n metadata: caseSetup.extensionState.metadata,\n }),\n repoPins: toRepoPins(evalCase.workspace?.repos),\n baseline: caseSetup.baselineCommit\n ? { status: 'initialized', commit: caseSetup.baselineCommit }\n : { status: 'unavailable' },\n promptSource: {\n kind: 'eval_case',\n formattingMode,\n question: promptInputs.question,\n ...(promptInputs.systemMessage !== undefined && {\n systemMessage: promptInputs.systemMessage,\n }),\n ...(promptInputs.chatPrompt !== undefined && { chatPrompt: promptInputs.chatPrompt }),\n },\n cleanupPolicy: {\n mode: sharedSetup.configuredMode,\n retainOnSuccess,\n retainOnFailure,\n manualCleanup: true,\n },\n sharedWorkspace: caseSetup.isSharedWorkspace,\n };\n } catch (error) {\n if (sharedSetup) {\n await releaseSharedWorkspaceSetup(sharedSetup).catch(() => {});\n }\n throw error;\n }\n}\n","/**\n * Typed configuration file support for AgentV.\n *\n * Provides `defineConfig()` for use in `agentv.config.ts` files. Supports\n * auto-discovery, Zod validation, and IDE autocomplete.\n *\n * @example\n * ```typescript\n * // agentv.config.ts\n * import { defineConfig } from '@agentv/core';\n *\n * export default defineConfig({\n * execution: {\n * maxConcurrency: 5,\n * maxRetries: 2,\n * agentTimeoutMs: 120_000,\n * },\n * output: {\n * dir: './results',\n * },\n * });\n * ```\n *\n * @module\n */\n\nimport { z } from 'zod';\n\nconst ExecutionConfigSchema = z\n .object({\n /** General eval parallelism (default: 3) */\n maxConcurrency: z.number().int().min(1).max(50).optional(),\n /** Maximum retries on failure (default: 2) */\n maxRetries: z.number().int().min(0).optional(),\n /** Agent timeout in milliseconds. No timeout if not set. */\n agentTimeoutMs: z.number().int().min(0).optional(),\n /** Enable verbose logging */\n verbose: z.boolean().optional(),\n /** Always keep temp workspaces after eval */\n keepWorkspaces: z.boolean().optional(),\n })\n .passthrough()\n .superRefine((value, ctx) => {\n const supportedFields = new Set([\n 'maxConcurrency',\n 'maxRetries',\n 'agentTimeoutMs',\n 'verbose',\n 'keepWorkspaces',\n ]);\n\n if ('otelFile' in value) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['otelFile'],\n message:\n 'execution.otelFile has been removed. Emit OpenTelemetry/OpenInference traces from the system under test or provider and correlate AgentV run artifacts with external_trace metadata.',\n });\n }\n\n for (const key of Object.keys(value)) {\n if (!supportedFields.has(key) && key !== 'otelFile') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [key],\n message: `Unsupported execution field '${key}'`,\n });\n }\n }\n })\n .transform(({ maxConcurrency, maxRetries, agentTimeoutMs, verbose, keepWorkspaces }) => ({\n ...(maxConcurrency !== undefined && { maxConcurrency }),\n ...(maxRetries !== undefined && { maxRetries }),\n ...(agentTimeoutMs !== undefined && { agentTimeoutMs }),\n ...(verbose !== undefined && { verbose }),\n ...(keepWorkspaces !== undefined && { keepWorkspaces }),\n }));\n\n/**\n * Schema for AgentV project-level configuration.\n */\nconst AgentVConfigSchema = z.object({\n /** Default execution settings */\n execution: ExecutionConfigSchema.optional(),\n\n /** Output settings */\n output: z\n .object({\n /** Default eval run artifact directory */\n dir: z.string().optional(),\n })\n .strict()\n .optional(),\n\n /** Response caching */\n cache: z\n .object({\n /** Enable response caching */\n enabled: z.boolean().optional(),\n /** Response cache directory */\n path: z.string().optional(),\n })\n .optional(),\n\n /** Cost and duration limits */\n limits: z\n .object({\n /** Maximum cost per run in USD */\n maxCostUsd: z.number().min(0).optional(),\n /** Maximum duration per run in milliseconds */\n maxDurationMs: z.number().int().min(0).optional(),\n })\n .optional(),\n\n /** Lifecycle hooks */\n hooks: z\n .object({\n /**\n * Shell command to run once at agentv startup, before any command executes.\n * stdout is parsed for env var exports (`KEY=value` or `export KEY=\"value\"`)\n * and injected into process.env. Keys already set in the environment are\n * not overwritten — existing env always takes priority.\n * stderr is forwarded to the user. Non-zero exit aborts with an error.\n */\n beforeSession: z.string().optional(),\n })\n .optional(),\n\n /** Project-local reusable references for fields that support ref://name */\n refs: z.record(z.string().min(1)).optional(),\n});\n\n/**\n * AgentV project-level configuration type.\n * Inferred from the Zod schema for full type safety.\n */\nexport type AgentVConfig = z.infer<typeof AgentVConfigSchema>;\n\n/**\n * Define a typed AgentV configuration.\n *\n * Use this in `agentv.config.ts` at your project root. The configuration\n * is validated at load time and provides full IDE autocomplete.\n *\n * @param config - Configuration object\n * @returns Validated configuration\n *\n * @example\n * ```typescript\n * import { defineConfig } from '@agentv/core';\n *\n * export default defineConfig({\n * execution: { maxConcurrency: 5 },\n * output: { dir: './results' },\n * limits: { maxCostUsd: 10.0 },\n * });\n * ```\n */\nexport function defineConfig(config: AgentVConfig): AgentVConfig {\n return AgentVConfigSchema.parse(config);\n}\n\n/**\n * Config file discovery order.\n * The first file found wins.\n */\nconst CONFIG_FILE_NAMES = [\n 'agentv.config.ts',\n 'agentv.config.js',\n 'agentv.config.mts',\n 'agentv.config.mjs',\n '.agentv/config.ts',\n '.agentv/config.js',\n] as const;\n\n/**\n * Discover and load an AgentV config file from the project root.\n *\n * Searches for config files in discovery order. Returns null if\n * no config file is found.\n *\n * @param projectRoot - Project root directory to search from\n * @returns Loaded and validated config, or null if not found\n */\nexport async function loadTsConfig(projectRoot: string): Promise<AgentVConfig | null> {\n const { existsSync } = await import('node:fs');\n const { pathToFileURL } = await import('node:url');\n const { join } = await import('node:path');\n\n for (const fileName of CONFIG_FILE_NAMES) {\n const filePath = join(projectRoot, fileName);\n if (!existsSync(filePath)) {\n continue;\n }\n\n try {\n const fileUrl = pathToFileURL(filePath).href;\n const mod = await import(fileUrl);\n const config = mod.default ?? mod;\n\n return AgentVConfigSchema.parse(config);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load config from ${filePath}: ${msg}`);\n }\n }\n\n return null;\n}\n","import { z } from 'zod';\n\nimport type { Provider } from '../providers/types.js';\nimport { extractLastAssistantContent } from '../providers/types.js';\nimport type { RubricItem } from '../types.js';\n\nconst rubricItemSchema = z.object({\n id: z.string().describe('Short identifier for this rubric (e.g., clarity, completeness)'),\n outcome: z.string().describe('Concrete expected outcome for this rubric item'),\n weight: z.number().default(1.0).describe('Relative importance (default 1.0)'),\n required: z.boolean().default(true).describe('Whether this is a mandatory requirement'),\n});\n\nconst rubricGenerationSchema = z.object({\n rubrics: z.array(rubricItemSchema).describe('List of evaluation rubrics'),\n});\n\nexport interface GenerateRubricsOptions {\n readonly criteria: string;\n readonly question?: string;\n readonly referenceAnswer?: string;\n readonly provider: Provider;\n}\n\n/**\n * Generate rubrics from expected outcome using an LLM.\n *\n * Calls the provider through `Provider.invoke()` — the LLM call itself is\n * a single non-streaming, non-tool-using completion. JSON output is parsed\n * with up to 3 retries to absorb model formatting variance.\n */\nexport async function generateRubrics(\n options: GenerateRubricsOptions,\n): Promise<readonly RubricItem[]> {\n const { criteria, question, referenceAnswer, provider } = options;\n\n const prompt = buildPrompt(criteria, question, referenceAnswer);\n\n const system = `You are an expert at creating evaluation rubrics.\nYou must return a valid JSON object matching this schema:\n{\n \"rubrics\": [\n {\n \"id\": \"string (short identifier)\",\n \"outcome\": \"string (concrete expected outcome for this rubric item)\",\n \"weight\": number (default 1.0),\n \"required\": boolean (default true)\n }\n ]\n}`;\n\n let result: z.infer<typeof rubricGenerationSchema> | undefined;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n const response = await provider.invoke({\n question: prompt,\n systemPrompt: system,\n });\n\n const text = extractLastAssistantContent(response.output);\n const cleaned = text.replace(/```json\\n?|```/g, '').trim();\n result = rubricGenerationSchema.parse(JSON.parse(cleaned));\n break;\n } catch (e: unknown) {\n lastError = e instanceof Error ? e : new Error(String(e));\n // Continue to next attempt\n }\n }\n\n if (!result) {\n throw new Error(`Failed to parse generated rubrics after 3 attempts: ${lastError?.message}`);\n }\n\n return result.rubrics;\n}\n\nfunction buildPrompt(criteria: string, question?: string, referenceAnswer?: string): string {\n const parts: string[] = [\n 'You are an expert at creating evaluation rubrics.',\n 'Given the expected outcome (and optionally the question and reference answer),',\n 'generate a list of specific, measurable rubric items to evaluate whether an answer meets the expected outcome.',\n '',\n 'Each rubric should:',\n '- Be specific and testable',\n '- Have a short, descriptive ID',\n '- Include a clear expected outcome statement (what a good answer must demonstrate for this rubric)',\n '- Indicate if it is required (mandatory) or optional',\n '- Have an appropriate weight (default 1.0, use higher values for more important aspects)',\n '',\n 'Generate 3-7 rubric items that comprehensively cover the expected outcome.',\n '',\n '[[ ## criteria ## ]]',\n criteria,\n '',\n ];\n\n if (question && question.trim().length > 0) {\n parts.push('[[ ## question ## ]]', question, '');\n }\n\n if (referenceAnswer && referenceAnswer.trim().length > 0) {\n parts.push('[[ ## reference_answer ## ]]', referenceAnswer, '');\n }\n\n return parts.join('\\n');\n}\n","import { execFile, spawn } from 'node:child_process';\nimport { createHash, randomBytes } from 'node:crypto';\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { cp, lstat, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\n\nimport { getAgentvDataDir } from '../paths.js';\nimport type { ResultPushConflictPolicy, ResultsConfig } from './loaders/config-loader.js';\nimport {\n AGENTV_RESULTS_ARTIFACTS_REF,\n AGENTV_RESULTS_PRIMARY_REF,\n} from './result-artifact-contract.js';\n\nexport type { ResultPushConflictPolicy } from './loaders/config-loader.js';\n\nconst execFileAsync = promisify(execFile);\n// Local working-tree run workspace inside the eval repo. Local commands\n// (`agentv eval` default --output, inspect/trend/export/combine/serve) read and\n// write runs here. This is NOT the on-branch layout — see RESULTS_REPO_RUNS_DIR.\nconst RESULTS_REPO_RESULTS_DIR = '.agentv/results';\n// On-branch / results-repo-clone storage layout. The results branch (e.g.\n// agentv/results/v1) already namespaces results, so run bundles are stored at\n// the branch root as <run_id>/ with ADR-0017 internals preserved.\nconst RESULTS_REPO_RUNS_DIR = '.';\nconst RESULTS_REPO_INDEXES_DIR = '.indexes';\nconst RESULTS_REPO_CACHE_DIR = '.cache';\n// Top-level directories AgentV owns on the results branch. The auto-sync\n// dirty-commit path stages only these so it never touches unrelated repo files.\nconst RESULTS_REPO_TRACKED_DOT_DIRS = [RESULTS_REPO_INDEXES_DIR, RESULTS_REPO_CACHE_DIR] as const;\nconst GIT_RESULTS_INDEX_CACHE_SCHEMA_VERSION = 'agentv.git_results_index_cache.v1';\nconst GIT_RESULTS_INDEX_LAYOUT_VERSION = 'agentv.results_repo_branch_root.v1';\nconst FALLBACK_RESULTS_REPO_COMMIT_EMAIL = 'agentv@results-repo';\nconst FALLBACK_RESULTS_REPO_COMMIT_NAME = 'AgentV Results';\nconst GIT_COMMIT_IDENTITY_ENV_KEYS = [\n 'GIT_AUTHOR_NAME',\n 'GIT_AUTHOR_EMAIL',\n 'GIT_COMMITTER_NAME',\n 'GIT_COMMITTER_EMAIL',\n] as const;\nconst GIT_ENV_INHERIT_ALLOWLIST = new Set([\n 'GIT_ASKPASS',\n 'GIT_PASSWORD',\n 'GIT_SSH_COMMAND',\n 'GIT_TOKEN',\n 'GIT_USERNAME',\n]);\nexport const DEFAULT_RESULTS_BRANCH = AGENTV_RESULTS_PRIMARY_REF;\nconst GIT_EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';\n// The results branch is a self-rooted orphan whose first commit is a fixed,\n// byte-identical empty-tree genesis. Pinning the message, identity, and dates\n// through per-command env makes the root commit SHA deterministic across every\n// machine and clone, so all clients share\n// one genesis and fast-forward/append to a single ref instead of each minting a\n// divergent root. This identity is applied via per-command env only so AgentV\n// never overwrites the user's git config. See createOrphanResultsBranch.\nconst RESULTS_REPO_GENESIS_MESSAGE = 'chore(results): initialize AgentV results branch';\nconst RESULTS_REPO_GENESIS_DATE = '@0 +0000';\nconst RESULT_INDEX_FILENAME = 'index.jsonl';\nconst RUN_INTERNAL_DIRNAME = '.internal';\n\n// Artifact-aware merge config for the AgentV-owned results checkout. Concurrent\n// writers append to rebuildable cross-run JSONL catalogs and each run's\n// per-run JSONL index; git's stock `union` driver can reconcile those appends.\n// Run bundles under <run_id>/** are uniquely pathed, so a 3-way merge usually\n// never conflicts on them.\nconst RESULTS_REPO_GITATTRIBUTES_FILE = '.gitattributes';\nconst RESULTS_REPO_GITATTRIBUTES_CONTENT = `# Managed by AgentV. Artifact-aware merge so results sync never force-pushes.\n${RESULTS_REPO_INDEXES_DIR}/*.jsonl merge=union\n*/.internal/index.jsonl merge=union\n`;\n\nexport interface ResultsRepoLocalPaths {\n readonly rootDir: string;\n readonly repoDir: string;\n readonly statusFile: string;\n}\n\nexport type ResultsRepoSyncStatus =\n | 'clean'\n | 'unavailable'\n | 'behind'\n | 'ahead'\n | 'diverged'\n | 'dirty'\n | 'conflicted'\n | 'push_conflict'\n | 'needs_human_merge'\n | 'syncing';\n\n/**\n * Layer 2 of the no-force-push results sync: when a genuine conflict cannot be\n * auto-merged, the diverged local work is pushed to a fresh timestamped temp\n * branch (never the canonical branch) and surfaced here so the user can merge it\n * on GitHub and click OK to resume sync. Wire shape (snake_case).\n */\nexport interface ResultsPendingMerge {\n readonly temp_branch: string;\n readonly target_branch: string;\n readonly compare_url?: string;\n readonly contributed_run_count?: number;\n readonly created_at: string;\n}\n\nexport interface ResultsRepoStatus {\n readonly configured: boolean;\n readonly available: boolean;\n readonly repo?: string;\n readonly repo_path?: string;\n readonly path?: string;\n readonly auto_push?: boolean;\n readonly require_push?: boolean;\n readonly push_conflict_policy?: ResultPushConflictPolicy;\n readonly local_dir?: string;\n readonly last_synced_at?: string;\n readonly last_error?: string;\n readonly sync_status?: ResultsRepoSyncStatus;\n readonly branch?: string;\n readonly upstream?: string;\n readonly ahead?: number;\n readonly behind?: number;\n readonly dirty_paths?: readonly string[];\n readonly conflicted_paths?: readonly string[];\n readonly git_status?: string;\n readonly git_diff_summary?: string;\n readonly blocked?: boolean;\n readonly block_reason?: string;\n readonly pull_performed?: boolean;\n readonly push_performed?: boolean;\n readonly commit_created?: boolean;\n readonly auto_merged_remote?: boolean;\n readonly target_branch?: string;\n readonly remote_commit?: string;\n readonly local_commit?: string;\n readonly backup_ref?: string;\n readonly backup_commit?: string;\n readonly previous_remote_commit?: string;\n readonly force_pushed_commit?: string;\n readonly lease_commit?: string;\n readonly pending_merge?: ResultsPendingMerge;\n}\n\n/** Internal camelCase mirror of {@link ResultsPendingMerge}. */\nexport interface PendingMergeDetails {\n readonly tempBranch: string;\n readonly targetBranch: string;\n readonly compareUrl?: string;\n readonly contributedRunCount?: number;\n readonly createdAt: string;\n}\n\nexport interface NormalizedResultsConfig {\n readonly mode: 'github';\n readonly repo: string;\n readonly repo_url?: string;\n readonly repo_path?: string;\n readonly branch?: string;\n readonly remote: string;\n readonly path: string;\n readonly auto_push: boolean;\n readonly require_push: boolean;\n readonly push_conflict_policy: ResultPushConflictPolicy;\n /** @internal Runtime mode; not part of YAML wire format. */\n readonly storageBranchWorktree: boolean;\n}\n\n/**\n * Internal runtime shape accepted by {@link normalizeResultsConfig}. Extends the\n * flat wire {@link ResultsConfig} with internal/CLI-only fields that never appear\n * in persistent YAML: derived `repo_url`/`repo_path`, the local `remote` alias,\n * and the per-run `require_push` override (`--results-require-push`).\n */\nexport interface RuntimeResultsConfig {\n readonly mode?: 'github';\n readonly repo?: string;\n readonly repo_url?: string;\n readonly repo_path?: string;\n readonly branch?: string;\n readonly remote?: string;\n readonly path?: string;\n readonly auto_push?: boolean;\n readonly require_push?: boolean;\n}\n\ntype StorageBranchResultsConfig = NormalizedResultsConfig & { readonly branch: string };\n\nexport interface DirectPushResultsResult {\n readonly changed: boolean;\n readonly blocked?: boolean;\n readonly block_reason?: string;\n readonly sync_status?: ResultsRepoSyncStatus;\n readonly push_conflict_policy: ResultPushConflictPolicy;\n readonly auto_merged_remote?: boolean;\n readonly target_branch?: string;\n readonly remote_commit?: string;\n readonly local_commit?: string;\n readonly backup_ref?: string;\n readonly backup_commit?: string;\n readonly previous_remote_commit?: string;\n readonly force_pushed_commit?: string;\n readonly lease_commit?: string;\n readonly pending_merge?: ResultsPendingMerge;\n}\n\nexport interface CheckedOutResultsRepoBranch {\n readonly branchName: string;\n readonly baseBranch: string;\n readonly repoDir: string;\n}\n\nexport interface PreparedResultsRepoBranch extends CheckedOutResultsRepoBranch {\n readonly cleanup: () => Promise<void>;\n}\n\ntype PersistedStatus = {\n readonly last_synced_at?: string;\n readonly last_error?: string;\n};\n\ntype ResultsRepoGitInspection = {\n readonly syncStatus: ResultsRepoSyncStatus;\n readonly branch?: string;\n readonly upstream?: string;\n readonly ahead?: number;\n readonly behind?: number;\n readonly dirtyPaths: readonly string[];\n readonly conflictedPaths: readonly string[];\n readonly gitStatus?: string;\n readonly gitDiffSummary?: string;\n};\n\nconst activeResultsRepoSyncs = new Set<string>();\n\nfunction sanitizeRepoSlug(repo: string): string {\n return repo.trim().replace(/[^A-Za-z0-9._-]+/g, '-');\n}\n\nfunction withFriendlyGitHubAuthError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n const lower = message.toLowerCase();\n if (\n lower.includes('authentication failed') ||\n lower.includes('could not read username') ||\n lower.includes('permission denied') ||\n lower.includes('not logged into any github hosts')\n ) {\n return new Error(`${message}. Run 'gh auth login' to authenticate.`);\n }\n return new Error(message);\n}\n\nfunction expandHome(p: string): string {\n if (p === '~' || p.startsWith('~/') || p.startsWith('~\\\\')) {\n return path.join(os.homedir(), p.slice(1));\n }\n return p;\n}\n\nfunction resolveLocalPath(p: string, baseDir: string): string {\n const expanded = expandHome(p);\n return path.isAbsolute(expanded) ? expanded : path.resolve(baseDir, expanded);\n}\n\nfunction isNormalizedResultsConfig(\n config: RuntimeResultsConfig | NormalizedResultsConfig,\n): config is NormalizedResultsConfig {\n return typeof (config as NormalizedResultsConfig).storageBranchWorktree === 'boolean';\n}\n\nexport function normalizeResultsConfig(\n config: RuntimeResultsConfig | NormalizedResultsConfig,\n options?: { baseDir?: string },\n): NormalizedResultsConfig {\n if (isNormalizedResultsConfig(config)) {\n return config;\n }\n const baseDir = options?.baseDir ?? process.cwd();\n // `repo`/`repo_url` is a remote slug or URL. `repo_path` is an existing local\n // checkout that pushes to its own origin (storage-branch worktree). `path` is\n // an explicit clone destination for a remote-backed results repo.\n const repoUrl = (config.repo_url ?? config.repo)?.trim();\n const explicitPath = config.path?.trim();\n // `path` is a local checkout (storage-branch worktree) when no remote repo is\n // configured; with a remote repo it is the explicit clone destination.\n const repoPath = config.repo_path?.trim() ?? (repoUrl ? undefined : explicitPath);\n const explicitClonePath = repoUrl ? explicitPath : undefined;\n const repo = repoUrl ?? repoPath ?? '';\n const branch = config.branch?.trim() || (repoPath ? DEFAULT_RESULTS_BRANCH : undefined);\n const useStorageBranchWorktree = Boolean(repoPath || (repoUrl && explicitClonePath && branch));\n const remote = config.remote?.trim() || 'origin';\n const autoPush = config.auto_push === true;\n const requirePush = config.require_push === true;\n const resolvedRepoPath = repoPath ? resolveLocalPath(repoPath, baseDir) : undefined;\n const resolvedPath = explicitClonePath\n ? resolveLocalPath(explicitClonePath, baseDir)\n : repoUrl\n ? path.join(getAgentvDataDir(), 'results', sanitizeRepoSlug(repoUrl))\n : (resolvedRepoPath ?? path.join(getAgentvDataDir(), 'results', sanitizeRepoSlug(repo)));\n return {\n mode: 'github',\n repo,\n ...(repoUrl ? { repo_url: repoUrl } : {}),\n ...(resolvedRepoPath ? { repo_path: resolvedRepoPath } : {}),\n ...(branch ? { branch } : {}),\n remote,\n path: resolvedPath,\n auto_push: autoPush,\n require_push: requirePush,\n push_conflict_policy: 'block',\n storageBranchWorktree: useStorageBranchWorktree,\n };\n}\n\n// GitHub `owner/repo` shorthand: exactly two non-empty path segments and no\n// scheme, host, or extra slashes. A bare local path like `.` does not match\n// (no `/`), so it is never expanded into a clone URL.\nconst GITHUB_OWNER_REPO_SHORTHAND = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\n\nfunction isExplicitRemoteUrl(value: string): boolean {\n return value.includes('://') || value.startsWith('git@');\n}\n\nexport function resolveResultsRepoUrl(repo: string): string {\n const trimmed = repo.trim();\n if (isExplicitRemoteUrl(trimmed)) {\n return trimmed;\n }\n // Only genuine GitHub `owner/repo` shorthand is expanded to a clone URL.\n // Local paths (including `.`) and other non-URL values are returned unchanged\n // so we never synthesize a bogus URL such as `https://github.com/..git`.\n if (GITHUB_OWNER_REPO_SHORTHAND.test(trimmed)) {\n return `https://github.com/${trimmed}.git`;\n }\n return trimmed;\n}\n\nexport function getResultsRepoLocalPaths(repo: string): ResultsRepoLocalPaths {\n const rootDir = path.join(getAgentvDataDir(), 'cache', 'results-repo', sanitizeRepoSlug(repo));\n return {\n rootDir,\n repoDir: path.join(rootDir, 'repo'),\n statusFile: path.join(rootDir, 'status.json'),\n };\n}\n\nfunction usesStorageBranchWorktree(config: NormalizedResultsConfig): boolean {\n return config.storageBranchWorktree === true || Boolean(config.repo_path);\n}\n\nfunction readPersistedStatus(statusFile: string): PersistedStatus {\n if (!existsSync(statusFile)) {\n return {};\n }\n\n try {\n return JSON.parse(readFileSync(statusFile, 'utf8')) as PersistedStatus;\n } catch {\n return {};\n }\n}\n\nfunction writePersistedStatus(statusFile: string, status: PersistedStatus): void {\n mkdirSync(path.dirname(statusFile), { recursive: true });\n writeFileSync(statusFile, `${JSON.stringify(status, null, 2)}\\n`, 'utf8');\n}\n\nasync function runCommand(\n executable: string,\n args: readonly string[],\n options?: { cwd?: string; check?: boolean; env?: NodeJS.ProcessEnv },\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n try {\n const { stdout, stderr } = await execFileAsync(executable, [...args], {\n cwd: options?.cwd,\n env: options?.env ?? process.env,\n });\n return { stdout, stderr, exitCode: 0 };\n } catch (error) {\n if (options?.check === false && error && typeof error === 'object') {\n const execError = error as { code?: unknown; stdout?: string; stderr?: string };\n return {\n stdout: execError.stdout ?? '',\n stderr: execError.stderr ?? '',\n exitCode: typeof execError.code === 'number' ? execError.code : 1,\n };\n }\n throw withFriendlyGitHubAuthError(error);\n }\n}\n\nfunction getGitEnv(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined && (!key.startsWith('GIT_') || GIT_ENV_INHERIT_ALLOWLIST.has(key))) {\n env[key] = value;\n }\n }\n env.GIT_TERMINAL_PROMPT = '0';\n return env;\n}\n\nasync function runGit(\n args: readonly string[],\n options?: { cwd?: string; check?: boolean; env?: NodeJS.ProcessEnv },\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return runCommand('git', args, { ...options, env: { ...getGitEnv(), ...options?.env } });\n}\n\nasync function runGh(\n args: readonly string[],\n options?: { cwd?: string },\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return runCommand('gh', args, options);\n}\n\nfunction gitErrorText(error: unknown): string {\n const parts: string[] = [];\n if (error && typeof error === 'object') {\n const record = error as { stdout?: unknown; stderr?: unknown; message?: unknown };\n if (typeof record.stdout === 'string') parts.push(record.stdout);\n if (typeof record.stderr === 'string') parts.push(record.stderr);\n if (typeof record.message === 'string') parts.push(record.message);\n } else if (typeof error === 'string') {\n parts.push(error);\n }\n return parts.join('\\n').toLowerCase();\n}\n\nfunction isMissingGitIdentityError(error: unknown): boolean {\n const text = gitErrorText(error);\n return (\n text.includes('author identity unknown') ||\n text.includes('committer identity unknown') ||\n text.includes('please tell me who you are') ||\n text.includes('unable to auto-detect email address') ||\n text.includes('empty ident name')\n );\n}\n\nfunction fallbackResultsRepoCommitEnv(): NodeJS.ProcessEnv {\n return {\n GIT_AUTHOR_NAME: FALLBACK_RESULTS_REPO_COMMIT_NAME,\n GIT_AUTHOR_EMAIL: FALLBACK_RESULTS_REPO_COMMIT_EMAIL,\n GIT_COMMITTER_NAME: FALLBACK_RESULTS_REPO_COMMIT_NAME,\n GIT_COMMITTER_EMAIL: FALLBACK_RESULTS_REPO_COMMIT_EMAIL,\n };\n}\n\nfunction configuredGitCommitIdentityEnv(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {};\n for (const key of GIT_COMMIT_IDENTITY_ENV_KEYS) {\n const value = process.env[key];\n if (value !== undefined) {\n env[key] = value;\n }\n }\n return env;\n}\n\nasync function runGitWithFallbackCommitIdentity(\n args: readonly string[],\n options: { cwd: string; env?: NodeJS.ProcessEnv },\n): Promise<{ stdout: string; stderr: string }> {\n const env = {\n ...configuredGitCommitIdentityEnv(),\n ...options.env,\n };\n try {\n return await runGit(args, { ...options, env });\n } catch (error) {\n if (!isMissingGitIdentityError(error)) {\n throw error;\n }\n return runGit(args, {\n ...options,\n env: {\n ...env,\n ...fallbackResultsRepoCommitEnv(),\n },\n });\n }\n}\n\nasync function resolveDefaultBranch(repoDir: string): Promise<string> {\n try {\n const { stdout } = await runGit(['symbolic-ref', 'refs/remotes/origin/HEAD'], { cwd: repoDir });\n const ref = stdout.trim();\n const prefix = 'refs/remotes/origin/';\n if (ref.startsWith(prefix)) {\n return ref.slice(prefix.length);\n }\n } catch {\n // Fall through to main/master probing.\n }\n\n for (const candidate of ['main', 'master']) {\n try {\n await runGit(['rev-parse', '--verify', `origin/${candidate}`], { cwd: repoDir });\n return candidate;\n } catch {\n // Try next candidate.\n }\n }\n\n return 'main';\n}\n\nasync function fetchResultsRepo(\n repoDir: string,\n remote = 'origin',\n branch?: string,\n): Promise<void> {\n if (branch) {\n await fetchResultsBranchRef(repoDir, remote, branch);\n await runGit(['remote', 'prune', remote], { cwd: repoDir, check: false });\n return;\n }\n\n await runGit(['fetch', remote, '--prune'], { cwd: repoDir });\n}\n\nfunction isMissingRemoteBranchFetch(stderr: string): boolean {\n const lower = stderr.toLowerCase();\n return lower.includes(\"couldn't find remote ref\") || lower.includes('could not find remote ref');\n}\n\nasync function fetchResultsBranchRef(\n repoDir: string,\n remote: string,\n branch: string,\n): Promise<void> {\n const { exitCode, stderr } = await runGit(\n ['fetch', remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`],\n {\n cwd: repoDir,\n check: false,\n },\n );\n const fetchError = stderr.trim();\n if (exitCode !== 0 && !isMissingRemoteBranchFetch(fetchError)) {\n throw new Error(fetchError);\n }\n}\n\nasync function fetchResultsArtifactRef(\n repoDir: string,\n remote: string,\n branch: string,\n): Promise<void> {\n const refspec = `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`;\n await runGit(['fetch', '--filter=blob:none', remote, refspec], {\n cwd: repoDir,\n check: false,\n });\n if (!(await gitRefExists(repoDir, `refs/remotes/${remote}/${branch}`))) {\n await fetchResultsBranchRef(repoDir, remote, branch);\n }\n}\n\nfunction remoteBranchRef(branch: string, remote = 'origin'): string {\n return `${remote}/${branch}`;\n}\n\nasync function gitRefExists(repoDir: string, ref: string): Promise<boolean> {\n const { stdout } = await runGit(['rev-parse', '--verify', `${ref}^{commit}`], {\n cwd: repoDir,\n check: false,\n });\n return stdout.trim().length > 0;\n}\n\nasync function configuredResultsBranchRef(\n repoDir: string,\n config: NormalizedResultsConfig,\n): Promise<string | undefined> {\n if (!config.branch) {\n return undefined;\n }\n const remoteRef = remoteBranchRef(config.branch, config.remote);\n if (await gitRefExists(repoDir, remoteRef)) {\n return remoteRef;\n }\n if (await gitRefExists(repoDir, config.branch)) {\n return config.branch;\n }\n return undefined;\n}\n\nasync function assertConfiguredResultsBranchExists(\n repoDir: string,\n config: NormalizedResultsConfig,\n): Promise<string | undefined> {\n return configuredResultsBranchRef(repoDir, config);\n}\n\nasync function localBranchExists(repoDir: string, branch: string): Promise<boolean> {\n const { stdout } = await runGit(['rev-parse', '--verify', `refs/heads/${branch}`], {\n cwd: repoDir,\n check: false,\n });\n return stdout.trim().length > 0;\n}\n\nasync function checkoutConfiguredResultsBranch(\n repoDir: string,\n config: NormalizedResultsConfig,\n): Promise<string | undefined> {\n const branch = config.branch;\n if (!branch) {\n return undefined;\n }\n const remoteRef = await assertConfiguredResultsBranchExists(repoDir, config);\n if (!remoteRef) {\n await createOrphanResultsBranch(repoDir, branch);\n await runGit(['checkout', branch], { cwd: repoDir });\n return undefined;\n }\n\n const currentBranch = await getCurrentBranch(repoDir);\n if (currentBranch !== branch) {\n if (await localBranchExists(repoDir, branch)) {\n await runGit(['checkout', branch], { cwd: repoDir });\n } else {\n await runGit(['checkout', '--track', '-b', branch, remoteRef], { cwd: repoDir });\n }\n }\n if (remoteRef === remoteBranchRef(branch, config.remote)) {\n await runGit(['branch', '--set-upstream-to', remoteRef, branch], {\n cwd: repoDir,\n check: false,\n });\n }\n\n return remoteRef;\n}\n\nasync function createOrphanResultsBranch(repoDir: string, branch: string): Promise<void> {\n await runGit(['update-ref', `refs/heads/${branch}`, await createResultsGenesisCommit(repoDir)], {\n cwd: repoDir,\n });\n}\n\n// Mint the deterministic empty-tree genesis commit (no parents). Tree, message,\n// identity, and author/committer dates are all fixed, so two inits at different\n// wall-clock times — on different machines — produce the identical root SHA.\nasync function createResultsGenesisCommit(repoDir: string): Promise<string> {\n const { stdout } = await runGit(\n ['commit-tree', GIT_EMPTY_TREE, '-m', RESULTS_REPO_GENESIS_MESSAGE],\n {\n cwd: repoDir,\n env: {\n ...fallbackResultsRepoCommitEnv(),\n GIT_AUTHOR_DATE: RESULTS_REPO_GENESIS_DATE,\n GIT_COMMITTER_DATE: RESULTS_REPO_GENESIS_DATE,\n },\n },\n );\n return stdout.trim();\n}\n\nasync function isGitRepository(repoDir: string): Promise<boolean> {\n try {\n const { stdout } = await runGit(['rev-parse', '--is-inside-work-tree'], { cwd: repoDir });\n return stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\nasync function resolveGitTopLevel(repoDir: string): Promise<string> {\n const { stdout } = await runGit(['rev-parse', '--show-toplevel'], { cwd: repoDir });\n return stdout.trim() || repoDir;\n}\n\n// Install artifact-aware merge attributes in the AgentV-owned results checkout.\n// This is a one-time, idempotent local-config write (never global/user config).\n// The committed `.gitattributes` keeps the same JSONL union rules portable to\n// other clients.\nasync function ensureResultsMergeConfig(repoDir: string): Promise<void> {\n let gitDir: string;\n try {\n const { stdout } = await runGit(['rev-parse', '--git-common-dir'], { cwd: repoDir });\n const resolved = stdout.trim();\n gitDir = resolved\n ? path.isAbsolute(resolved)\n ? resolved\n : path.join(repoDir, resolved)\n : path.join(repoDir, '.git');\n } catch {\n return;\n }\n\n // Also mirror the merge attributes into the repo-local `info/attributes`. The\n // committed `.gitattributes` makes the rules portable to other clients, but\n // info/attributes guarantees they apply to *this* checkout's merges even on\n // branches committed before `.gitattributes` existed, and for both the\n // working-tree merge and the detached `merge-tree` paths.\n writeResultsInfoAttributes(gitDir);\n}\n\nconst RESULTS_INFO_ATTRIBUTES_BEGIN = '# >>> agentv results merge attributes >>>';\nconst RESULTS_INFO_ATTRIBUTES_END = '# <<< agentv results merge attributes <<<';\n\n// Idempotently install AgentV's merge attributes into `<git-dir>/info/attributes`\n// inside a managed marker block, preserving any unrelated lines already there.\nfunction writeResultsInfoAttributes(gitDir: string): void {\n const infoDir = path.join(gitDir, 'info');\n const attributesPath = path.join(infoDir, 'attributes');\n const managedBlock = `${RESULTS_INFO_ATTRIBUTES_BEGIN}\\n${RESULTS_REPO_GITATTRIBUTES_CONTENT.trimEnd()}\\n${RESULTS_INFO_ATTRIBUTES_END}\\n`;\n\n let existing = '';\n try {\n existing = readFileSync(attributesPath, 'utf8');\n } catch {\n existing = '';\n }\n\n const blockPattern = new RegExp(\n `${escapeRegExp(RESULTS_INFO_ATTRIBUTES_BEGIN)}[\\\\s\\\\S]*?${escapeRegExp(\n RESULTS_INFO_ATTRIBUTES_END,\n )}\\\\n?`,\n );\n const withoutManaged = existing.replace(blockPattern, '');\n const next =\n withoutManaged.length > 0 && !withoutManaged.endsWith('\\n')\n ? `${withoutManaged}\\n${managedBlock}`\n : `${withoutManaged}${managedBlock}`;\n if (next === existing) {\n return;\n }\n mkdirSync(infoDir, { recursive: true });\n writeFileSync(attributesPath, next);\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n// Inject the managed `.gitattributes` blob into a temporary git index so every\n// results commit carries it. Merge drivers read attributes from the trees being\n// merged, so the file must live on the branch, not just in repo config. Skips\n// the write when the base tree already has identical content, preserving the\n// \"tree unchanged\" no-op detection in the commit helpers.\nasync function addResultsGitattributesToIndex(\n repoDir: string,\n indexEnv: NodeJS.ProcessEnv,\n): Promise<void> {\n const { stdout: existing } = await runGit(\n ['cat-file', '-p', `:0:${RESULTS_REPO_GITATTRIBUTES_FILE}`],\n { cwd: repoDir, env: indexEnv, check: false },\n );\n if (existing === RESULTS_REPO_GITATTRIBUTES_CONTENT) {\n return;\n }\n const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'agentv-results-attrs-'));\n try {\n const scratchFile = path.join(scratchDir, RESULTS_REPO_GITATTRIBUTES_FILE);\n writeFileSync(scratchFile, RESULTS_REPO_GITATTRIBUTES_CONTENT);\n const { stdout: blob } = await runGit(['hash-object', '-w', '--no-filters', scratchFile], {\n cwd: repoDir,\n });\n await runGit(\n [\n 'update-index',\n '--add',\n '--cacheinfo',\n `100644,${blob.trim()},${RESULTS_REPO_GITATTRIBUTES_FILE}`,\n ],\n { cwd: repoDir, env: indexEnv },\n );\n } finally {\n rmSync(scratchDir, { recursive: true, force: true });\n }\n}\n\nfunction updateStatusFile(\n config: ResultsConfig | NormalizedResultsConfig,\n patch: PersistedStatus,\n): void {\n const repo = normalizeResultsConfig(config).repo;\n const cachePaths = getResultsRepoLocalPaths(repo);\n const current = readPersistedStatus(cachePaths.statusFile);\n writePersistedStatus(cachePaths.statusFile, {\n ...current,\n ...patch,\n });\n}\n\nexport async function ensureResultsRepoClone(config: ResultsConfig): Promise<string> {\n const normalized = normalizeResultsConfig(config);\n if (normalized.repo_path) {\n if (!(await isGitRepository(normalized.repo_path))) {\n throw new Error(`Results repo_path is not a git repository: ${normalized.repo_path}`);\n }\n const topLevel = await resolveGitTopLevel(normalized.repo_path);\n await ensureResultsMergeConfig(topLevel);\n return topLevel;\n }\n\n const cachePaths = getResultsRepoLocalPaths(normalized.repo);\n const cloneDir = normalized.path;\n mkdirSync(cachePaths.rootDir, { recursive: true });\n mkdirSync(path.dirname(cloneDir), { recursive: true });\n\n const cloneMissing = !existsSync(cloneDir);\n const gitDir = path.join(cloneDir, '.git');\n const cloneEmpty = !cloneMissing && !existsSync(gitDir) && (await readdir(cloneDir)).length === 0;\n\n if (cloneMissing || cloneEmpty) {\n try {\n await runGit([\n 'clone',\n '--filter=blob:none',\n ...(normalized.remote === 'origin' ? [] : ['--origin', normalized.remote]),\n resolveResultsRepoUrl(normalized.repo_url ?? normalized.repo),\n cloneDir,\n ]);\n await ensureResultsMergeConfig(cloneDir);\n return cloneDir;\n } catch (error) {\n updateStatusFile(normalized, { last_error: withFriendlyGitHubAuthError(error).message });\n throw withFriendlyGitHubAuthError(error);\n }\n }\n\n if (!existsSync(gitDir)) {\n throw new Error(`Results repo clone path is not a git repository: ${cloneDir}`);\n }\n\n await ensureResultsMergeConfig(cloneDir);\n return cloneDir;\n}\n\nexport function getResultsRepoStatus(config?: ResultsConfig): ResultsRepoStatus {\n if (!config) {\n return {\n configured: false,\n available: false,\n repo: '',\n local_dir: '',\n sync_status: 'unavailable',\n };\n }\n\n const normalized = normalizeResultsConfig(config);\n const localPaths = getResultsRepoLocalPaths(normalized.repo);\n const persisted = readPersistedStatus(localPaths.statusFile);\n\n return {\n configured: true,\n available: existsSync(normalized.path),\n repo: normalized.repo,\n ...(normalized.repo_path !== undefined && { repo_path: normalized.repo_path }),\n path: normalized.path,\n auto_push: normalized.auto_push,\n require_push: normalized.require_push,\n push_conflict_policy: normalized.push_conflict_policy,\n local_dir: normalized.path,\n last_synced_at: persisted.last_synced_at,\n last_error: persisted.last_error,\n sync_status: existsSync(normalized.path) ? 'clean' : 'unavailable',\n };\n}\n\nfunction parseGitPorcelainPaths(status: string): {\n dirtyPaths: string[];\n conflictedPaths: string[];\n} {\n const dirtyPaths = new Set<string>();\n const conflictedPaths = new Set<string>();\n const conflictCodes = new Set(['DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU']);\n\n for (const line of status.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const code = line.slice(0, 2);\n const rawPath = line.slice(3).trim();\n const paths = rawPath.includes(' -> ') ? rawPath.split(' -> ') : [rawPath];\n\n for (const p of paths.map((entry) => entry.trim()).filter(Boolean)) {\n dirtyPaths.add(p);\n if (conflictCodes.has(code)) {\n conflictedPaths.add(p);\n }\n }\n }\n\n return {\n dirtyPaths: [...dirtyPaths].sort(),\n conflictedPaths: [...conflictedPaths].sort(),\n };\n}\n\nasync function getCurrentBranch(repoDir: string): Promise<string | undefined> {\n const { stdout } = await runGit(['branch', '--show-current'], { cwd: repoDir, check: false });\n const branch = stdout.trim();\n if (branch) {\n return branch;\n }\n\n const { stdout: sha } = await runGit(['rev-parse', '--short', 'HEAD'], {\n cwd: repoDir,\n check: false,\n });\n return sha.trim() ? `HEAD@${sha.trim()}` : undefined;\n}\n\nasync function resolveComparisonRef(\n repoDir: string,\n config?: NormalizedResultsConfig,\n): Promise<string | undefined> {\n if (config?.branch) {\n return assertConfiguredResultsBranchExists(repoDir, config);\n }\n\n const { stdout: upstream } = await runGit(\n ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'],\n { cwd: repoDir, check: false },\n );\n const upstreamRef = upstream.trim();\n if (upstreamRef && !upstreamRef.includes('fatal:')) {\n return upstreamRef;\n }\n\n const baseBranch = await resolveDefaultBranch(repoDir);\n const fallback = `${config?.remote ?? 'origin'}/${baseBranch}`;\n const { stdout: fallbackSha } = await runGit(['rev-parse', '--verify', fallback], {\n cwd: repoDir,\n check: false,\n });\n return fallbackSha.trim() ? fallback : undefined;\n}\n\nasync function getAheadBehind(\n repoDir: string,\n upstream: string | undefined,\n): Promise<{ ahead?: number; behind?: number }> {\n if (!upstream) {\n return {};\n }\n\n const { stdout } = await runGit(['rev-list', '--left-right', '--count', `HEAD...${upstream}`], {\n cwd: repoDir,\n check: false,\n });\n const [aheadText, behindText] = stdout.trim().split(/\\s+/);\n const ahead = Number.parseInt(aheadText ?? '', 10);\n const behind = Number.parseInt(behindText ?? '', 10);\n\n return {\n ...(Number.isFinite(ahead) && { ahead }),\n ...(Number.isFinite(behind) && { behind }),\n };\n}\n\nasync function getAheadBehindForRefs(\n repoDir: string,\n leftRef: string,\n rightRef: string,\n): Promise<{ ahead?: number; behind?: number }> {\n const { stdout } = await runGit(\n ['rev-list', '--left-right', '--count', `${leftRef}...${rightRef}`],\n {\n cwd: repoDir,\n check: false,\n },\n );\n const [aheadText, behindText] = stdout.trim().split(/\\s+/);\n const ahead = Number.parseInt(aheadText ?? '', 10);\n const behind = Number.parseInt(behindText ?? '', 10);\n\n return {\n ...(Number.isFinite(ahead) && { ahead }),\n ...(Number.isFinite(behind) && { behind }),\n };\n}\n\nasync function readGitText(\n repoDir: string,\n ref: string | undefined,\n gitPath: string,\n): Promise<string | undefined> {\n if (!ref) {\n return undefined;\n }\n const { stdout } = await runGit(['show', `${ref}:${gitPath}`], {\n cwd: repoDir,\n check: false,\n });\n return stdout.length > 0 ? stdout : undefined;\n}\n\nasync function getStorageBranchWorktreeDirtyPaths(\n repoDir: string,\n config: NormalizedResultsConfig & { readonly branch: string },\n): Promise<{ dirtyPaths: string[]; conflictedPaths: string[] }> {\n const { stdout: porcelain } = await runGit(\n ['status', '--porcelain=v1', '--untracked-files=all'],\n {\n cwd: repoDir,\n check: false,\n },\n );\n const parsed = parseGitPorcelainPaths(porcelain);\n const safeDirtyPaths = parsed.dirtyPaths.filter(isSafeResultsRepoPath);\n const conflictedPaths = parsed.conflictedPaths.filter(isSafeResultsRepoPath);\n if (safeDirtyPaths.length === 0) {\n return { dirtyPaths: [], conflictedPaths };\n }\n\n const localRef = `refs/heads/${config.branch}`;\n const remoteRef = remoteBranchRef(config.branch, config.remote);\n const comparisonRef = (await gitRefExists(repoDir, localRef))\n ? localRef\n : (await gitRefExists(repoDir, remoteRef))\n ? remoteRef\n : undefined;\n const dirtyPaths: string[] = [];\n\n for (const gitPath of safeDirtyPaths) {\n const absolutePath = path.join(repoDir, ...gitPath.split('/'));\n if (!existsSync(absolutePath)) {\n if ((await readGitText(repoDir, comparisonRef, gitPath)) !== undefined) {\n dirtyPaths.push(gitPath);\n }\n continue;\n }\n\n const localContent = readFileSync(absolutePath, 'utf8');\n const branchContent = await readGitText(repoDir, comparisonRef, gitPath);\n if (branchContent === undefined || localContent !== branchContent) {\n dirtyPaths.push(gitPath);\n }\n }\n\n return { dirtyPaths: dirtyPaths.sort(), conflictedPaths };\n}\n\nasync function inspectResultsStorageBranchGit(\n repoDir: string,\n config: NormalizedResultsConfig,\n): Promise<ResultsRepoGitInspection> {\n if (!config.branch) {\n return {\n syncStatus: 'clean',\n dirtyPaths: [],\n conflictedPaths: [],\n };\n }\n const localRef = `refs/heads/${config.branch}`;\n const upstream = remoteBranchRef(config.branch, config.remote);\n const localExists = await gitRefExists(repoDir, localRef);\n const remoteExists = await gitRefExists(repoDir, upstream);\n const worktree = await getStorageBranchWorktreeDirtyPaths(repoDir, {\n ...config,\n branch: config.branch,\n });\n const { ahead = 0, behind = 0 } =\n localExists && remoteExists\n ? await getAheadBehindForRefs(repoDir, localRef, upstream)\n : {\n ahead: localExists && !remoteExists ? 1 : 0,\n behind: !localExists && remoteExists ? 1 : 0,\n };\n\n let syncStatus: ResultsRepoSyncStatus = 'clean';\n if (worktree.conflictedPaths.length > 0) {\n syncStatus = 'conflicted';\n } else if (worktree.dirtyPaths.length > 0) {\n syncStatus = 'dirty';\n } else if (ahead > 0 && behind > 0) {\n syncStatus = 'diverged';\n } else if (behind > 0) {\n syncStatus = 'behind';\n } else if (ahead > 0) {\n syncStatus = 'ahead';\n }\n\n return {\n syncStatus,\n branch: config.branch,\n ...(remoteExists && { upstream }),\n ahead,\n behind,\n dirtyPaths: worktree.dirtyPaths,\n conflictedPaths: worktree.conflictedPaths,\n };\n}\n\nasync function fastForwardStorageBranchRef(\n repoDir: string,\n normalized: StorageBranchResultsConfig,\n upstream: string,\n): Promise<void> {\n await assertValidResultsBranchName(repoDir, normalized.branch);\n await ensureResultsBranchNotCheckedOut(repoDir, normalized);\n\n const localRef = `refs/heads/${normalized.branch}`;\n const localExists = await gitRefExists(repoDir, localRef);\n const updateArgs = ['update-ref', localRef, upstream];\n if (localExists) {\n const { stdout: localSha } = await runGit(['rev-parse', localRef], { cwd: repoDir });\n updateArgs.push(localSha.trim());\n }\n await runGit(updateArgs, { cwd: repoDir });\n await runGit(['branch', '--set-upstream-to', upstream, normalized.branch], {\n cwd: repoDir,\n check: false,\n });\n}\n\nasync function getDirtyPathsChangedUpstream(\n repoDir: string,\n normalized: StorageBranchResultsConfig,\n dirtyPaths: readonly string[],\n upstream: string,\n): Promise<string[]> {\n const safeDirtyPaths = [...new Set(dirtyPaths.filter(isSafeResultsRepoPath))].sort();\n if (safeDirtyPaths.length === 0) {\n return [];\n }\n\n const localRef = `refs/heads/${normalized.branch}`;\n const localExists = await gitRefExists(repoDir, localRef);\n let changedPaths: string[];\n if (localExists) {\n const { stdout } = await runGit(['diff', '--name-only', `${localRef}..${upstream}`], {\n cwd: repoDir,\n check: false,\n });\n changedPaths = stdout\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .filter(isSafeResultsRepoPath)\n .sort();\n } else {\n changedPaths = [];\n for (const dirtyPath of safeDirtyPaths) {\n if ((await readGitText(repoDir, upstream, dirtyPath)) !== undefined) {\n changedPaths.push(dirtyPath);\n }\n }\n }\n\n const dirtySet = new Set(safeDirtyPaths);\n return [...new Set(changedPaths.filter((changedPath) => dirtySet.has(changedPath)))].sort();\n}\n\nasync function hasInProgressGitConflict(repoDir: string): Promise<boolean> {\n const markers = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'REBASE_HEAD'];\n for (const marker of markers) {\n const { stdout } = await runGit(['rev-parse', '--git-path', marker], {\n cwd: repoDir,\n check: false,\n });\n const markerPath = stdout.trim();\n const resolvedMarkerPath = path.isAbsolute(markerPath)\n ? markerPath\n : path.join(repoDir, markerPath);\n if (markerPath && existsSync(resolvedMarkerPath)) {\n return true;\n }\n }\n return false;\n}\n\nasync function buildGitDiffSummary(\n repoDir: string,\n upstream: string | undefined,\n): Promise<string | undefined> {\n const summaries: string[] = [];\n for (const args of [\n ['diff', '--stat'],\n ['diff', '--cached', '--stat'],\n ...(upstream ? ([['diff', '--stat', `${upstream}..HEAD`]] as string[][]) : []),\n ]) {\n const { stdout } = await runGit(args, { cwd: repoDir, check: false });\n const summary = stdout.trim();\n if (summary) {\n summaries.push(summary);\n }\n }\n\n return summaries.length > 0 ? summaries.join('\\n') : undefined;\n}\n\nasync function inspectResultsRepoGit(\n repoDir: string,\n config?: NormalizedResultsConfig,\n): Promise<ResultsRepoGitInspection> {\n const branch = await getCurrentBranch(repoDir);\n const upstream = await resolveComparisonRef(repoDir, config);\n const { stdout: porcelain } = await runGit(\n ['status', '--porcelain=v1', '--untracked-files=all'],\n {\n cwd: repoDir,\n check: false,\n },\n );\n const { stdout: shortStatus } = await runGit(['status', '--short', '--branch'], {\n cwd: repoDir,\n check: false,\n });\n const { dirtyPaths: allDirtyPaths, conflictedPaths } = parseGitPorcelainPaths(porcelain);\n const dirtyPaths = allDirtyPaths.filter(isSafeResultsRepoPath);\n const { ahead = 0, behind = 0 } = await getAheadBehind(repoDir, upstream);\n const inProgressConflict = await hasInProgressGitConflict(repoDir);\n\n let syncStatus: ResultsRepoSyncStatus = 'clean';\n if (conflictedPaths.length > 0 || inProgressConflict) {\n syncStatus = 'conflicted';\n } else if (dirtyPaths.length > 0) {\n syncStatus = 'dirty';\n } else if (ahead > 0 && behind > 0) {\n syncStatus = 'diverged';\n } else if (behind > 0) {\n syncStatus = 'behind';\n } else if (ahead > 0) {\n syncStatus = 'ahead';\n }\n\n return {\n syncStatus,\n branch,\n upstream,\n ahead,\n behind,\n dirtyPaths,\n conflictedPaths,\n gitStatus: shortStatus.trim() || undefined,\n gitDiffSummary: await buildGitDiffSummary(repoDir, upstream),\n };\n}\n\nfunction withGitInspection(\n status: ResultsRepoStatus,\n inspection: ResultsRepoGitInspection,\n): ResultsRepoStatus {\n return {\n ...status,\n sync_status: inspection.syncStatus,\n branch: inspection.branch,\n upstream: inspection.upstream,\n ahead: inspection.ahead,\n behind: inspection.behind,\n dirty_paths: inspection.dirtyPaths,\n conflicted_paths: inspection.conflictedPaths,\n git_status: inspection.gitStatus,\n git_diff_summary: inspection.gitDiffSummary,\n last_error: lastErrorForGitInspection(status, inspection),\n };\n}\n\nfunction lastErrorForGitInspection(\n status: ResultsRepoStatus,\n inspection: ResultsRepoGitInspection,\n): string | undefined {\n if (inspection.syncStatus === 'conflicted') {\n return 'Results repo has unresolved git conflicts';\n }\n\n if (inspection.syncStatus === 'diverged') {\n return 'Results repo local and remote histories have diverged';\n }\n\n if (inspection.syncStatus === 'dirty') {\n if (status.auto_push === false) {\n return 'Results repo has uncommitted changes and auto_push is disabled';\n }\n }\n\n return undefined;\n}\n\ntype ResultsBranchPushDetails = {\n readonly pushConflictPolicy: ResultPushConflictPolicy;\n readonly targetBranch: string;\n readonly remoteCommit?: string;\n readonly localCommit?: string;\n readonly backupRef?: string;\n readonly backupCommit?: string;\n readonly previousRemoteCommit?: string;\n readonly forcePushedCommit?: string;\n readonly leaseCommit?: string;\n readonly autoMergedRemote?: boolean;\n readonly pendingMerge?: PendingMergeDetails;\n};\n\ntype ResultsBranchPushOutcome =\n | {\n readonly blocked: false;\n readonly details?: ResultsBranchPushDetails;\n }\n | {\n readonly blocked: true;\n readonly blockReason: string;\n readonly details: ResultsBranchPushDetails;\n readonly syncStatus?: ResultsRepoSyncStatus;\n };\n\nclass ResultsBranchPushConflictError extends Error {\n constructor(readonly result: DirectPushResultsResult) {\n super(result.block_reason ?? 'Results branch push conflict');\n this.name = 'ResultsBranchPushConflictError';\n }\n}\n\nfunction pendingMergeToWire(details: PendingMergeDetails): ResultsPendingMerge {\n return {\n temp_branch: details.tempBranch,\n target_branch: details.targetBranch,\n ...(details.compareUrl !== undefined && { compare_url: details.compareUrl }),\n ...(details.contributedRunCount !== undefined && {\n contributed_run_count: details.contributedRunCount,\n }),\n created_at: details.createdAt,\n };\n}\n\nfunction pushDetailsToWire(\n details?: ResultsBranchPushDetails,\n): Pick<\n ResultsRepoStatus,\n | 'push_conflict_policy'\n | 'target_branch'\n | 'remote_commit'\n | 'local_commit'\n | 'backup_ref'\n | 'backup_commit'\n | 'previous_remote_commit'\n | 'force_pushed_commit'\n | 'lease_commit'\n | 'auto_merged_remote'\n | 'pending_merge'\n> {\n if (!details) {\n return {};\n }\n return {\n push_conflict_policy: details.pushConflictPolicy,\n target_branch: details.targetBranch,\n ...(details.remoteCommit !== undefined && { remote_commit: details.remoteCommit }),\n ...(details.localCommit !== undefined && { local_commit: details.localCommit }),\n ...(details.backupRef !== undefined && { backup_ref: details.backupRef }),\n ...(details.backupCommit !== undefined && { backup_commit: details.backupCommit }),\n ...(details.previousRemoteCommit !== undefined && {\n previous_remote_commit: details.previousRemoteCommit,\n }),\n ...(details.forcePushedCommit !== undefined && {\n force_pushed_commit: details.forcePushedCommit,\n }),\n ...(details.leaseCommit !== undefined && { lease_commit: details.leaseCommit }),\n ...(details.autoMergedRemote === true && { auto_merged_remote: true }),\n ...(details.pendingMerge !== undefined && {\n pending_merge: pendingMergeToWire(details.pendingMerge),\n }),\n };\n}\n\nfunction withBlockedStatus(\n status: ResultsRepoStatus,\n blockReason: string,\n flags?: {\n readonly pullPerformed?: boolean;\n readonly pushPerformed?: boolean;\n readonly commitCreated?: boolean;\n readonly pushDetails?: ResultsBranchPushDetails;\n },\n): ResultsRepoStatus {\n return {\n ...status,\n ...pushDetailsToWire(flags?.pushDetails),\n blocked: true,\n block_reason: blockReason,\n ...(flags?.pullPerformed !== undefined && { pull_performed: flags.pullPerformed }),\n ...(flags?.pushPerformed !== undefined && { push_performed: flags.pushPerformed }),\n ...(flags?.commitCreated !== undefined && { commit_created: flags.commitCreated }),\n };\n}\n\nfunction withPushConflictStatus(\n status: ResultsRepoStatus,\n blockReason: string,\n details: ResultsBranchPushDetails,\n flags: {\n readonly pullPerformed: boolean;\n readonly pushPerformed: boolean;\n readonly commitCreated: boolean;\n readonly syncStatus?: ResultsRepoSyncStatus;\n },\n): ResultsRepoStatus {\n return withBlockedStatus(\n {\n ...status,\n sync_status: flags.syncStatus ?? 'push_conflict',\n },\n blockReason,\n {\n pullPerformed: flags.pullPerformed,\n pushPerformed: flags.pushPerformed,\n commitCreated: flags.commitCreated,\n pushDetails: details,\n },\n );\n}\n\nfunction withActionFlags(\n status: ResultsRepoStatus,\n flags: {\n readonly pullPerformed: boolean;\n readonly pushPerformed: boolean;\n readonly commitCreated: boolean;\n readonly pushDetails?: ResultsBranchPushDetails;\n },\n): ResultsRepoStatus {\n return {\n ...status,\n ...pushDetailsToWire(flags.pushDetails),\n blocked: false,\n pull_performed: flags.pullPerformed,\n push_performed: flags.pushPerformed,\n commit_created: flags.commitCreated,\n };\n}\n\nfunction isSafeResultsRepoPath(p: string): boolean {\n const normalized = p.split(path.sep).join('/');\n const segments = normalized.split('/').filter(Boolean);\n const isRunBundlePath =\n segments.length >= 2 &&\n !segments[0]?.startsWith('.') &&\n segments[0] !== RESULTS_REPO_GITATTRIBUTES_FILE;\n return (\n normalized === RESULTS_REPO_GITATTRIBUTES_FILE ||\n RESULTS_REPO_TRACKED_DOT_DIRS.some(\n (dir) => normalized === dir || normalized.startsWith(`${dir}/`),\n ) ||\n isRunBundlePath\n );\n}\n\n// git errors on a pathspec that matches nothing, so when staging AgentV's result\n// trees we only pass the ones that currently exist on disk or in the index.\nasync function existingTrackedResultsPathspecs(repoDir: string): Promise<string[]> {\n const targets = new Set<string>();\n if (existsSync(path.join(repoDir, RESULTS_REPO_GITATTRIBUTES_FILE))) {\n targets.add(RESULTS_REPO_GITATTRIBUTES_FILE);\n }\n for (const dir of RESULTS_REPO_TRACKED_DOT_DIRS) {\n if (existsSync(path.join(repoDir, dir))) {\n targets.add(dir);\n continue;\n }\n const { stdout } = await runGit(['ls-files', '--', dir], { cwd: repoDir, check: false });\n if (stdout.trim().length > 0) {\n targets.add(dir);\n }\n }\n for (const entry of await readdir(repoDir, { withFileTypes: true }).catch(() => [])) {\n if (entry.name.startsWith('.') || !entry.isDirectory()) {\n continue;\n }\n if (existsSync(path.join(repoDir, entry.name, 'summary.json'))) {\n targets.add(entry.name);\n }\n }\n const { stdout } = await runGit(['ls-files'], { cwd: repoDir, check: false });\n for (const file of stdout.split(/\\r?\\n/)) {\n const normalized = file.trim();\n if (!normalized) {\n continue;\n }\n const segments = normalized.split('/');\n if (segments.length >= 2 && segments[0] && !segments[0].startsWith('.')) {\n targets.add(segments[0]);\n }\n }\n return [...targets].sort();\n}\n\nfunction areSafeResultsRepoPaths(paths: readonly string[]): boolean {\n return paths.length > 0 && paths.every(isSafeResultsRepoPath);\n}\n\nasync function getAheadPaths(\n repoDir: string,\n upstream: string | undefined,\n branch = 'HEAD',\n): Promise<readonly string[]> {\n if (!upstream) {\n return [];\n }\n const { stdout } = await runGit(['diff', '--name-only', `${upstream}..${branch}`], {\n cwd: repoDir,\n check: false,\n });\n return stdout\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .sort();\n}\n\nfunction getPushTargetBranch(\n upstream: string | undefined,\n baseBranch: string,\n remote = 'origin',\n): string {\n const prefix = `${remote}/`;\n return upstream?.startsWith(prefix) ? upstream.slice(prefix.length) : baseBranch;\n}\n\nfunction formatShortSha(sha: string | undefined): string {\n return sha ? sha.slice(0, 12) : 'unknown';\n}\n\nasync function getCommitSha(repoDir: string, ref: string | undefined): Promise<string | undefined> {\n if (!ref) {\n return undefined;\n }\n const { stdout } = await runGit(['rev-parse', '--verify', `${ref}^{commit}`], {\n cwd: repoDir,\n check: false,\n });\n const sha = stdout.trim();\n return sha.length > 0 ? sha : undefined;\n}\n\nfunction isNonFastForwardPushError(error: unknown): boolean {\n const text = gitErrorText(error);\n return (\n text.includes('non-fast-forward') ||\n text.includes('fetch first') ||\n text.includes('tip is behind its remote') ||\n text.includes('note about fast-forwards') ||\n text.includes('stale info')\n );\n}\n\n// Bounded optimistic retry for the fetch → merge → push loop. Covers the benign\n// race where another writer advances the remote between our fetch and push.\nconst RESULTS_PUSH_MERGE_MAX_ATTEMPTS = 5;\n\nasync function isAncestorCommit(\n repoDir: string,\n ancestor: string,\n descendant: string,\n): Promise<boolean> {\n const { exitCode } = await runGit(['merge-base', '--is-ancestor', ancestor, descendant], {\n cwd: repoDir,\n check: false,\n });\n return exitCode === 0;\n}\n\nasync function getMergeBaseCommit(\n repoDir: string,\n a: string,\n b: string,\n): Promise<string | undefined> {\n const { stdout, exitCode } = await runGit(['merge-base', a, b], { cwd: repoDir, check: false });\n const sha = stdout.trim();\n return exitCode === 0 && sha.length > 0 ? sha : undefined;\n}\n\nfunction buildNeedsHumanMergeReason(\n targetBranch: string,\n remoteCommit: string | undefined,\n localCommit: string | undefined,\n): string {\n return `Results branch ${targetBranch} diverged from the remote and could not be auto-merged: a genuine results content conflict remains (remote ${formatShortSha(\n remoteCommit,\n )}, local ${formatShortSha(\n localCommit,\n )}). The remote branch is unchanged and no history was rewritten; resolve it with a GitHub pull request.`;\n}\n\n// Stable, flat, slug-based naming for the Layer 2 temp branches. A flat name is\n// required: a nested `agentv/results/v1/sync-...` ref would D/F-conflict with the\n// canonical `agentv/results/v1` branch (git cannot store a ref as both a file and\n// a directory). Mirrors the old backup-ref scheme.\nfunction timestampForResultsRef(date = new Date()): string {\n const pad = (value: number) => String(value).padStart(2, '0');\n return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}T${pad(\n date.getUTCHours(),\n )}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`;\n}\n\nfunction slugifyResultsTargetBranch(branch: string): string {\n return (\n branch\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'results'\n );\n}\n\nfunction randomResultsRefToken(): string {\n return randomBytes(4).toString('hex').slice(0, 6);\n}\n\n// `agentv/results-sync/<utc_ts>-<branch_slug>-<rand6>` — a flat ref under a\n// dedicated namespace so it never collides with (or D/F-conflicts against) the\n// canonical results branch. `<rand6>` avoids same-second collisions between\n// concurrent writers.\nfunction buildResultsSyncBranchName(targetBranch: string, token = randomResultsRefToken()): string {\n return `agentv/results-sync/${timestampForResultsRef()}-${slugifyResultsTargetBranch(\n targetBranch,\n )}-${token}`;\n}\n\n// Build a GitHub compare URL for the temp branch, but only when the remote is a\n// GitHub remote. Returns undefined for non-GitHub remotes (zero-infra: URL\n// construction only, never a `gh` shell-out).\nexport function buildResultsCompareUrl(\n remoteUrl: string | undefined,\n targetBranch: string,\n syncBranch: string,\n): string | undefined {\n if (!remoteUrl) {\n return undefined;\n }\n const match = remoteUrl.trim().match(/github\\.com[:/]([^/\\s]+)\\/([^/\\s]+?)(?:\\.git)?\\/?$/i);\n if (!match) {\n return undefined;\n }\n const [, owner, repo] = match;\n return `https://github.com/${owner}/${repo}/compare/${encodeURIComponent(\n targetBranch,\n )}...${encodeURIComponent(syncBranch)}?expand=1`;\n}\n\nasync function resolveRemotePushUrl(repoDir: string, remote: string): Promise<string | undefined> {\n for (const args of [\n ['remote', 'get-url', '--push', remote],\n ['remote', 'get-url', remote],\n ]) {\n const { stdout, exitCode } = await runGit(args, { cwd: repoDir, check: false });\n const url = stdout.trim();\n if (exitCode === 0 && url.length > 0) {\n return url;\n }\n }\n return undefined;\n}\n\n// Count the unique top-level `<run_id>` run directories that the diverged\n// local commit adds on top of the remote target tip. Best-effort: returns\n// undefined when the diff cannot be computed.\nasync function countContributedRunDirs(\n repoDir: string,\n remoteTargetCommit: string | undefined,\n sourceCommit: string,\n): Promise<number | undefined> {\n if (!remoteTargetCommit) {\n return undefined;\n }\n const { stdout, exitCode } = await runGit(\n ['diff', '--name-only', `${remoteTargetCommit}...${sourceCommit}`, '--', RESULTS_REPO_RUNS_DIR],\n { cwd: repoDir, check: false },\n );\n if (exitCode !== 0) {\n return undefined;\n }\n const runDirs = new Set<string>();\n for (const line of stdout.split(/\\r?\\n/)) {\n const file = line.trim();\n if (!file) {\n continue;\n }\n const segments = file.split('/');\n // <run_id>/...\n if (segments.length >= 2 && segments[0] && !segments[0].startsWith('.')) {\n runDirs.add(segments[0]);\n }\n }\n return runDirs.size;\n}\n\n// Layer 2 push: create-only push of the diverged local commit to a fresh\n// timestamped temp branch. Never force, never the canonical branch. On the rare\n// same-second ref collision, regenerate the random token and retry once.\nasync function pushResultsSyncBranch(params: {\n readonly repoDir: string;\n readonly remote: string;\n readonly sourceCommit: string;\n readonly targetBranch: string;\n}): Promise<PendingMergeDetails> {\n const { repoDir, remote, sourceCommit, targetBranch } = params;\n const remoteTargetCommit = await getCommitSha(repoDir, remoteBranchRef(targetBranch, remote));\n\n let syncBranch = buildResultsSyncBranchName(targetBranch);\n await assertValidResultsBranchName(repoDir, syncBranch);\n try {\n await runGit(['push', '--porcelain', remote, `${sourceCommit}:refs/heads/${syncBranch}`], {\n cwd: repoDir,\n });\n } catch (error) {\n if (!isRefAlreadyExistsPushError(error)) {\n throw error;\n }\n syncBranch = buildResultsSyncBranchName(targetBranch);\n await assertValidResultsBranchName(repoDir, syncBranch);\n await runGit(['push', '--porcelain', remote, `${sourceCommit}:refs/heads/${syncBranch}`], {\n cwd: repoDir,\n });\n }\n\n const compareUrl = buildResultsCompareUrl(\n await resolveRemotePushUrl(repoDir, remote),\n targetBranch,\n syncBranch,\n );\n const contributedRunCount = await countContributedRunDirs(\n repoDir,\n remoteTargetCommit,\n sourceCommit,\n ).catch(() => undefined);\n\n return {\n tempBranch: syncBranch,\n targetBranch,\n ...(compareUrl !== undefined && { compareUrl }),\n ...(contributedRunCount !== undefined && { contributedRunCount }),\n createdAt: new Date().toISOString(),\n };\n}\n\nfunction isRefAlreadyExistsPushError(error: unknown): boolean {\n const text = gitErrorText(error);\n return (\n text.includes('already exists') ||\n text.includes('cannot lock ref') ||\n text.includes('reference already exists')\n );\n}\n\n// Merge `remoteCommit` into the currently checked-out branch via a real\n// `git merge`, so the working tree and index advance together (the ref-only\n// path uses merge-tree + update-ref instead). Returns the merge exit code; a\n// non-zero code means git left a conflict, which the caller aborts.\nasync function mergeRemoteIntoCheckedOutBranch(\n repoDir: string,\n remoteCommit: string,\n): Promise<number> {\n const args = ['merge', '--no-edit', '-m', 'chore(results): merge remote results', remoteCommit];\n let result = await runGit(args, {\n cwd: repoDir,\n check: false,\n env: configuredGitCommitIdentityEnv(),\n });\n if (result.exitCode !== 0 && isMissingGitIdentityError({ stderr: result.stderr })) {\n await runGit(['merge', '--abort'], { cwd: repoDir, check: false });\n result = await runGit(args, {\n cwd: repoDir,\n check: false,\n env: { ...configuredGitCommitIdentityEnv(), ...fallbackResultsRepoCommitEnv() },\n });\n }\n return result.exitCode;\n}\n\n// Layer 1 of the no-force-push results sync (see\n// docs/adr/0007-conflict-free-results-sync-without-force-push.md). A bounded\n// fetch → merge → push loop: fast-forward when possible, otherwise commit a real\n// 3-way merge using the artifact-aware JSONL union rules and fast-forward the\n// canonical branch onto it. A genuine results content\n// conflict returns a `needs_human_merge` blocked outcome — never a force push.\nasync function resolveResultBranchPushConflict(params: {\n readonly normalized: StorageBranchResultsConfig;\n readonly repoDir: string;\n readonly targetBranch: string;\n readonly sourceRef: string;\n}): Promise<ResultsBranchPushOutcome> {\n await ensureResultsMergeConfig(params.repoDir);\n\n const { repoDir, targetBranch } = params;\n const remote = params.normalized.remote;\n const localRef = params.sourceRef;\n const remoteRef = remoteBranchRef(targetBranch, remote);\n // When the caller hands us `HEAD`, the canonical branch is checked out, so we\n // must advance the working tree too (real `git merge`). The storage-branch\n // path hands us `refs/heads/<branch>` with a detached HEAD, where we update\n // the ref directly via merge-tree to avoid touching any working tree.\n const branchCheckedOut = params.sourceRef === 'HEAD';\n\n let lastDetails: ResultsBranchPushDetails = {\n pushConflictPolicy: params.normalized.push_conflict_policy,\n targetBranch,\n };\n\n // Layer 2: a genuine conflict could not be auto-merged. Push the diverged\n // local work to a fresh temp branch (never canonical, never force) and surface\n // a `pending_merge` block so the user can merge it on GitHub and click OK. If\n // the temp-branch push itself fails, still return the blocked outcome with the\n // error appended to the reason — never crash the sync.\n const buildHumanMergeOutcome = async (\n reason: string,\n details: ResultsBranchPushDetails,\n ): Promise<ResultsBranchPushOutcome> => {\n if (!details.localCommit) {\n return { blocked: true, blockReason: reason, details, syncStatus: 'needs_human_merge' };\n }\n try {\n const pendingMerge = await pushResultsSyncBranch({\n repoDir,\n remote,\n sourceCommit: details.localCommit,\n targetBranch: details.targetBranch,\n });\n return {\n blocked: true,\n blockReason: reason,\n details: { ...details, pendingMerge },\n syncStatus: 'needs_human_merge',\n };\n } catch (error) {\n return {\n blocked: true,\n blockReason: `${reason} (could not create the temp branch for the GitHub merge: ${getStatusMessage(\n error,\n )})`,\n details,\n syncStatus: 'needs_human_merge',\n };\n }\n };\n\n for (let attempt = 1; attempt <= RESULTS_PUSH_MERGE_MAX_ATTEMPTS; attempt += 1) {\n await fetchResultsRepo(repoDir, remote, targetBranch);\n const remoteCommit = await getCommitSha(repoDir, remoteRef);\n const localCommit = await getCommitSha(repoDir, localRef);\n const details: ResultsBranchPushDetails = {\n pushConflictPolicy: params.normalized.push_conflict_policy,\n targetBranch,\n ...(remoteCommit !== undefined && { remoteCommit, previousRemoteCommit: remoteCommit }),\n ...(localCommit !== undefined && { localCommit }),\n };\n lastDetails = details;\n\n if (!remoteCommit) {\n return {\n blocked: true,\n blockReason: `Results branch push conflict on ${targetBranch}: remote commit could not be resolved after fetch`,\n details,\n syncStatus: 'push_conflict',\n };\n }\n if (!localCommit) {\n return {\n blocked: true,\n blockReason: `Results branch push conflict on ${targetBranch}: local commit could not be resolved`,\n details,\n syncStatus: 'push_conflict',\n };\n }\n\n // Remote already contains our work: fast-forward to it and stop.\n if (await isAncestorCommit(repoDir, localCommit, remoteCommit)) {\n if (branchCheckedOut) {\n await runGit(['merge', '--ff-only', remoteCommit], { cwd: repoDir, check: false });\n } else {\n await runGit(['update-ref', localRef, remoteCommit, localCommit], {\n cwd: repoDir,\n check: false,\n });\n }\n return { blocked: false, details };\n }\n\n let pushSpec = branchCheckedOut ? 'HEAD' : localCommit;\n let autoMergedRemote = false;\n // Diverged (neither side is an ancestor): commit a real 3-way merge using\n // the artifact-aware drivers. If `git merge` reports a genuine conflict, no\n // history is rewritten and we route to a human GitHub merge.\n if (!(await isAncestorCommit(repoDir, remoteCommit, localCommit))) {\n if (branchCheckedOut) {\n const exitCode = await mergeRemoteIntoCheckedOutBranch(repoDir, remoteCommit);\n if (exitCode !== 0) {\n await runGit(['merge', '--abort'], { cwd: repoDir, check: false });\n return await buildHumanMergeOutcome(\n buildNeedsHumanMergeReason(targetBranch, remoteCommit, localCommit),\n details,\n );\n }\n pushSpec = 'HEAD';\n autoMergedRemote = true;\n } else {\n const base = await getMergeBaseCommit(repoDir, localCommit, remoteCommit);\n if (!base) {\n return await buildHumanMergeOutcome(\n buildNeedsHumanMergeReason(targetBranch, remoteCommit, localCommit),\n details,\n );\n }\n const merge = await runGit(\n ['merge-tree', '--write-tree', `--merge-base=${base}`, localCommit, remoteCommit],\n { cwd: repoDir, check: false },\n );\n const mergedTree = merge.stdout.trim().split(/\\r?\\n/)[0]?.trim();\n if (merge.exitCode !== 0 || !mergedTree) {\n return await buildHumanMergeOutcome(\n buildNeedsHumanMergeReason(targetBranch, remoteCommit, localCommit),\n details,\n );\n }\n const { stdout: mergeCommitOut } = await runGitWithFallbackCommitIdentity(\n [\n 'commit-tree',\n mergedTree,\n '-p',\n localCommit,\n '-p',\n remoteCommit,\n '-m',\n 'chore(results): merge remote results',\n ],\n { cwd: repoDir },\n );\n pushSpec = mergeCommitOut.trim();\n await runGit(['update-ref', localRef, pushSpec, localCommit], { cwd: repoDir });\n autoMergedRemote = true;\n }\n }\n\n try {\n await runGit(['push', '--porcelain', remote, `${pushSpec}:refs/heads/${targetBranch}`], {\n cwd: repoDir,\n });\n } catch (error) {\n if (isNonFastForwardPushError(error)) {\n // Remote advanced between fetch and push; retry the loop.\n continue;\n }\n throw error;\n }\n\n const pushedCommit = (await getCommitSha(repoDir, pushSpec)) ?? localCommit;\n return {\n blocked: false,\n details: {\n ...details,\n localCommit: pushedCommit,\n ...(autoMergedRemote && { autoMergedRemote }),\n },\n };\n }\n\n return await buildHumanMergeOutcome(\n `Results branch ${targetBranch} could not be reconciled after ${RESULTS_PUSH_MERGE_MAX_ATTEMPTS} attempts because the remote kept advancing; retry sync. The remote branch is unchanged.`,\n lastDetails,\n );\n}\n\nasync function statusFromInspection(\n normalized: NormalizedResultsConfig,\n repoDir: string,\n): Promise<ResultsRepoStatus> {\n return withGitInspection(\n getResultsRepoStatus(normalized),\n await inspectResultsRepoGit(repoDir, normalized),\n );\n}\n\nexport async function getResultsRepoSyncStatus(config?: ResultsConfig): Promise<ResultsRepoStatus> {\n const baseStatus = getResultsRepoStatus(config);\n if (!config) {\n return baseStatus;\n }\n\n const normalized = normalizeResultsConfig(config);\n if (activeResultsRepoSyncs.has(normalized.path)) {\n return {\n ...baseStatus,\n sync_status: 'syncing',\n };\n }\n\n if (!existsSync(normalized.path) || !(await isGitRepository(normalized.path))) {\n return {\n ...baseStatus,\n sync_status: 'unavailable',\n };\n }\n\n try {\n if (usesStorageBranchWorktree(normalized)) {\n // Dashboard status is read-only; explicit sync paths do the fetch.\n return withGitInspection(\n baseStatus,\n await inspectResultsStorageBranchGit(normalized.path, normalized),\n );\n }\n if (normalized.branch) {\n await fetchResultsRepo(normalized.path, normalized.remote, normalized.branch).catch(\n () => undefined,\n );\n await checkoutConfiguredResultsBranch(normalized.path, normalized);\n }\n return withGitInspection(baseStatus, await inspectResultsRepoGit(normalized.path, normalized));\n } catch (error) {\n return {\n ...baseStatus,\n ...(normalized.branch ? { available: false } : {}),\n sync_status: 'unavailable',\n last_error: getStatusMessage(error),\n };\n }\n}\n\nexport async function syncResultsRepo(config: ResultsConfig): Promise<ResultsRepoStatus> {\n const normalized = normalizeResultsConfig(config);\n\n try {\n const repoDir = await ensureResultsRepoClone(normalized);\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch);\n if (!usesStorageBranchWorktree(normalized)) {\n await checkoutConfiguredResultsBranch(repoDir, normalized);\n }\n updateStatusFile(normalized, {\n last_synced_at: new Date().toISOString(),\n last_error: undefined,\n });\n } catch (error) {\n updateStatusFile(normalized, {\n last_error: withFriendlyGitHubAuthError(error).message,\n });\n throw withFriendlyGitHubAuthError(error);\n }\n\n return getResultsRepoStatus(normalized);\n}\n\nfunction getStatusMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport async function syncResultsRepoForProject(config: ResultsConfig): Promise<ResultsRepoStatus> {\n const normalized = normalizeResultsConfig(config);\n const syncKey = normalized.path;\n if (activeResultsRepoSyncs.has(syncKey)) {\n return {\n ...(await getResultsRepoSyncStatus(normalized)),\n sync_status: 'syncing',\n blocked: true,\n block_reason: 'Results repo sync is already in progress',\n };\n }\n\n activeResultsRepoSyncs.add(syncKey);\n let pullPerformed = false;\n let pushPerformed = false;\n let commitCreated = false;\n let pushDetails: ResultsBranchPushDetails | undefined;\n\n try {\n const repoDir = await ensureResultsRepoClone(normalized);\n if (usesStorageBranchWorktree(normalized)) {\n try {\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch);\n } catch (error) {\n if (normalized.require_push) {\n throw error;\n }\n }\n let inspection = await inspectResultsStorageBranchGit(repoDir, normalized);\n const fastForwardBehindStorageBranch = async (): Promise<ResultsRepoStatus | undefined> => {\n if ((inspection.behind ?? 0) <= 0 || (inspection.ahead ?? 0) > 0) {\n return undefined;\n }\n\n if (!inspection.upstream) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has no upstream branch to pull from',\n });\n return withBlockedStatus(status, 'Results repo has no upstream branch to pull from', {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n if (!normalized.branch) {\n return undefined;\n }\n\n try {\n await fastForwardStorageBranchRef(\n repoDir,\n { ...normalized, branch: normalized.branch },\n inspection.upstream,\n );\n pullPerformed = true;\n inspection = await inspectResultsStorageBranchGit(repoDir, normalized);\n return undefined;\n } catch (error) {\n inspection = await inspectResultsStorageBranchGit(repoDir, normalized);\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n const reason = `Results repo could not be fast-forwarded: ${getStatusMessage(error)}`;\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n };\n\n if (inspection.syncStatus === 'conflicted') {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has unresolved git conflicts',\n });\n return withBlockedStatus(status, 'Results repo has unresolved git conflicts', {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n if ((inspection.ahead ?? 0) > 0 && (inspection.behind ?? 0) > 0) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n if (!normalized.branch) {\n updateStatusFile(normalized, {\n last_error: 'Results repo local and remote histories have diverged',\n });\n return withBlockedStatus(\n status,\n 'Results repo local and remote histories have diverged',\n {\n pullPerformed,\n pushPerformed,\n commitCreated,\n },\n );\n }\n const localRef = `refs/heads/${normalized.branch}`;\n const aheadPaths = await getAheadPaths(repoDir, inspection.upstream, localRef);\n if (!inspection.upstream || !areSafeResultsRepoPaths(aheadPaths)) {\n const reason = !inspection.upstream\n ? 'Results repo has no upstream branch to push to'\n : 'Results repo has non-results committed changes';\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n const outcome = await resolveResultBranchPushConflict({\n normalized: { ...normalized, branch: normalized.branch },\n repoDir,\n targetBranch: normalized.branch,\n sourceRef: localRef,\n });\n pushDetails = outcome.details;\n if (outcome.blocked) {\n updateStatusFile(normalized, { last_error: outcome.blockReason });\n return withPushConflictStatus(status, outcome.blockReason, outcome.details, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n syncStatus: outcome.syncStatus,\n });\n }\n pushPerformed = true;\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch(\n () => undefined,\n );\n inspection = await inspectResultsStorageBranchGit(repoDir, normalized);\n }\n\n if (inspection.syncStatus === 'dirty') {\n if (!normalized.auto_push && !normalized.require_push) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has uncommitted changes and auto_push is disabled',\n });\n return withBlockedStatus(\n status,\n 'Results repo has uncommitted changes and auto_push is disabled',\n {\n pullPerformed,\n pushPerformed,\n commitCreated,\n },\n );\n }\n\n if ((inspection.behind ?? 0) > 0) {\n if (inspection.upstream && normalized.branch) {\n const changedDirtyPaths = await getDirtyPathsChangedUpstream(\n repoDir,\n { ...normalized, branch: normalized.branch },\n inspection.dirtyPaths,\n inspection.upstream,\n );\n if (changedDirtyPaths.length > 0) {\n const conflictInspection: ResultsRepoGitInspection = {\n ...inspection,\n syncStatus: 'conflicted',\n conflictedPaths: [\n ...new Set([...inspection.conflictedPaths, ...changedDirtyPaths]),\n ].sort(),\n };\n const status = withGitInspection(\n getResultsRepoStatus(normalized),\n conflictInspection,\n );\n const reason = `Results repo local metadata changes conflict with upstream changes: ${changedDirtyPaths.join(', ')}`;\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n }\n const blockedStatus = await fastForwardBehindStorageBranch();\n if (blockedStatus) {\n return blockedStatus;\n }\n }\n\n if (normalized.branch) {\n commitCreated = await commitStorageBranchWorktreePaths({\n normalized: { ...normalized, branch: normalized.branch },\n repoDir,\n paths: inspection.dirtyPaths,\n commitMessage: 'chore(results): sync local result metadata',\n });\n inspection = await inspectResultsStorageBranchGit(repoDir, normalized);\n }\n }\n\n if ((inspection.behind ?? 0) > 0 && (inspection.ahead ?? 0) === 0) {\n const blockedStatus = await fastForwardBehindStorageBranch();\n if (blockedStatus) {\n return blockedStatus;\n }\n }\n\n if (normalized.auto_push || normalized.require_push) {\n if (normalized.branch) {\n const localRef = `refs/heads/${normalized.branch}`;\n if (await gitRefExists(repoDir, localRef)) {\n try {\n await runGit(\n [\n 'push',\n '--porcelain',\n normalized.remote,\n `${localRef}:refs/heads/${normalized.branch}`,\n ],\n { cwd: repoDir },\n );\n pushPerformed = true;\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch(\n () => undefined,\n );\n } catch (error) {\n if (isNonFastForwardPushError(error)) {\n const outcome = await resolveResultBranchPushConflict({\n normalized: { ...normalized, branch: normalized.branch },\n repoDir,\n targetBranch: normalized.branch,\n sourceRef: localRef,\n });\n pushDetails = outcome.details;\n if (!outcome.blocked) {\n pushPerformed = true;\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch(\n () => undefined,\n );\n inspection = await inspectResultsStorageBranchGit(repoDir, normalized);\n } else {\n updateStatusFile(normalized, { last_error: outcome.blockReason });\n const status = withGitInspection(\n getResultsRepoStatus(normalized),\n await inspectResultsStorageBranchGit(repoDir, normalized),\n );\n return withPushConflictStatus(status, outcome.blockReason, outcome.details, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n syncStatus: outcome.syncStatus,\n });\n }\n } else {\n updateStatusFile(normalized, { last_error: getStatusMessage(error) });\n if (normalized.require_push) {\n throw error;\n }\n const status = withGitInspection(\n getResultsRepoStatus(normalized),\n await inspectResultsStorageBranchGit(repoDir, normalized),\n );\n return withBlockedStatus(\n status,\n `Results repo push was rejected: ${getStatusMessage(error)}`,\n {\n pullPerformed,\n pushPerformed,\n commitCreated,\n },\n );\n }\n }\n }\n }\n }\n updateStatusFile(normalized, {\n last_synced_at: new Date().toISOString(),\n last_error: undefined,\n });\n const status = withGitInspection(\n getResultsRepoStatus(normalized),\n await inspectResultsStorageBranchGit(repoDir, normalized),\n );\n return withActionFlags(status, { pullPerformed, pushPerformed, commitCreated, pushDetails });\n }\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch);\n await checkoutConfiguredResultsBranch(repoDir, normalized);\n let inspection = await inspectResultsRepoGit(repoDir, normalized);\n\n if (inspection.syncStatus === 'conflicted') {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has unresolved git conflicts',\n });\n return withBlockedStatus(status, 'Results repo has unresolved git conflicts', {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n if (inspection.syncStatus === 'dirty') {\n if (!normalized.auto_push) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has uncommitted changes and auto_push is disabled',\n });\n return withBlockedStatus(\n status,\n 'Results repo has uncommitted changes and auto_push is disabled',\n {\n pullPerformed,\n pushPerformed,\n commitCreated,\n },\n );\n }\n\n if ((inspection.behind ?? 0) > 0) {\n if (!inspection.upstream) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has no upstream branch to pull from',\n });\n return withBlockedStatus(status, 'Results repo has no upstream branch to pull from', {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n try {\n await runGit(['merge', '--ff-only', inspection.upstream], { cwd: repoDir });\n pullPerformed = true;\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n } catch (error) {\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n const reason = `Results repo could not be fast-forwarded: ${getStatusMessage(error)}`;\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n }\n\n if (inspection.syncStatus === 'dirty') {\n const trackedPathspecs = await existingTrackedResultsPathspecs(repoDir);\n await runGit(['add', '--all', '--', ...trackedPathspecs], { cwd: repoDir });\n await runGitWithFallbackCommitIdentity(\n [\n 'commit',\n '-m',\n 'chore(results): sync local results branch changes',\n '--',\n ...trackedPathspecs,\n ],\n {\n cwd: repoDir,\n },\n );\n commitCreated = true;\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n }\n }\n\n if (inspection.syncStatus === 'diverged') {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n const aheadPaths = await getAheadPaths(repoDir, inspection.upstream);\n if (!inspection.upstream || !areSafeResultsRepoPaths(aheadPaths)) {\n const reason = !inspection.upstream\n ? 'Results repo has no upstream branch to push to'\n : 'Results repo has non-results committed changes';\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n const baseBranch = normalized.branch ?? (await resolveDefaultBranch(repoDir));\n const targetBranch = getPushTargetBranch(inspection.upstream, baseBranch, normalized.remote);\n const outcome = await resolveResultBranchPushConflict({\n normalized: { ...normalized, branch: targetBranch },\n repoDir,\n targetBranch,\n sourceRef: 'HEAD',\n });\n pushDetails = outcome.details;\n if (outcome.blocked) {\n updateStatusFile(normalized, { last_error: outcome.blockReason });\n return withPushConflictStatus(status, outcome.blockReason, outcome.details, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n syncStatus: outcome.syncStatus,\n });\n }\n pushPerformed = true;\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch);\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n }\n\n if ((inspection.behind ?? 0) > 0 && (inspection.ahead ?? 0) === 0) {\n if (!inspection.upstream) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, {\n last_error: 'Results repo has no upstream branch to pull from',\n });\n return withBlockedStatus(status, 'Results repo has no upstream branch to pull from', {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n try {\n await runGit(['merge', '--ff-only', inspection.upstream], { cwd: repoDir });\n pullPerformed = true;\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n } catch (error) {\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n const reason = `Results repo could not be fast-forwarded: ${getStatusMessage(error)}`;\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n }\n\n if ((inspection.ahead ?? 0) > 0) {\n if (!normalized.auto_push) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n return withActionFlags(status, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n const aheadPaths = await getAheadPaths(repoDir, inspection.upstream);\n if (!inspection.upstream || !areSafeResultsRepoPaths(aheadPaths)) {\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n const reason = !inspection.upstream\n ? 'Results repo has no upstream branch to push to'\n : 'Results repo has non-results committed changes';\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n\n const baseBranch = normalized.branch ?? (await resolveDefaultBranch(repoDir));\n const targetBranch = getPushTargetBranch(inspection.upstream, baseBranch, normalized.remote);\n try {\n await runGit(['push', normalized.remote, `HEAD:${targetBranch}`], { cwd: repoDir });\n pushPerformed = true;\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch);\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n } catch (error) {\n if (isNonFastForwardPushError(error)) {\n const outcome = await resolveResultBranchPushConflict({\n normalized: { ...normalized, branch: targetBranch },\n repoDir,\n targetBranch,\n sourceRef: 'HEAD',\n });\n pushDetails = outcome.details;\n if (!outcome.blocked) {\n pushPerformed = true;\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch);\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n } else {\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch(\n () => undefined,\n );\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n updateStatusFile(normalized, { last_error: outcome.blockReason });\n return withPushConflictStatus(status, outcome.blockReason, outcome.details, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n syncStatus: outcome.syncStatus,\n });\n }\n } else {\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch(\n () => undefined,\n );\n inspection = await inspectResultsRepoGit(repoDir, normalized);\n const status = withGitInspection(getResultsRepoStatus(normalized), inspection);\n const reason = `Results repo push was rejected: ${getStatusMessage(error)}`;\n updateStatusFile(normalized, { last_error: reason });\n return withBlockedStatus(status, reason, {\n pullPerformed,\n pushPerformed,\n commitCreated,\n });\n }\n }\n }\n\n updateStatusFile(normalized, {\n last_synced_at: new Date().toISOString(),\n last_error: undefined,\n });\n\n return withActionFlags(await statusFromInspection(normalized, repoDir), {\n pullPerformed,\n pushPerformed,\n commitCreated,\n pushDetails,\n });\n } catch (error) {\n updateStatusFile(normalized, {\n last_error: withFriendlyGitHubAuthError(error).message,\n });\n throw withFriendlyGitHubAuthError(error);\n } finally {\n activeResultsRepoSyncs.delete(syncKey);\n }\n}\n\n// Ancestor-guarded fast-forward of the local results checkout toward the merged\n// target branch. Only advances when the local commit is already an ancestor of\n// the remote target (i.e. the target genuinely contains the local work), so a\n// premature OK — where the user has not actually merged — is a no-op that leaves\n// the local work diverged and intact. Operates only on the results checkout,\n// never the user's source repo branch.\nasync function fastForwardResultsTowardTarget(\n repoDir: string,\n normalized: NormalizedResultsConfig,\n targetBranch: string,\n): Promise<void> {\n const upstreamRef = remoteBranchRef(targetBranch, normalized.remote);\n if (!(await gitRefExists(repoDir, upstreamRef))) {\n return;\n }\n const upstreamCommit = await getCommitSha(repoDir, upstreamRef);\n if (!upstreamCommit) {\n return;\n }\n\n if (usesStorageBranchWorktree(normalized) && normalized.branch) {\n const localRef = `refs/heads/${normalized.branch}`;\n if (!(await gitRefExists(repoDir, localRef))) {\n await runGit(['update-ref', localRef, upstreamCommit], { cwd: repoDir, check: false });\n await runGit(['branch', '--set-upstream-to', upstreamRef, normalized.branch], {\n cwd: repoDir,\n check: false,\n });\n return;\n }\n const localCommit = await getCommitSha(repoDir, localRef);\n if (localCommit && (await isAncestorCommit(repoDir, localCommit, upstreamCommit))) {\n await runGit(['update-ref', localRef, upstreamCommit, localCommit], {\n cwd: repoDir,\n check: false,\n });\n }\n return;\n }\n\n // Checkout mode: a plain fast-forward-only merge. It succeeds when the target\n // contains the local work and is a harmless no-op (non-zero, ignored) when the\n // local checkout is still diverged.\n await runGit(['merge', '--ff-only', upstreamRef], { cwd: repoDir, check: false });\n}\n\n/**\n * The explicit \"OK\" action of the Layer 2 human-merge flow. The user has merged\n * the temp branch into the target on GitHub; AgentV fetches the remote, pulls the\n * merged target into the local results checkout (ancestor-guarded fast-forward),\n * and resumes the normal sync path which clears the `pending_merge` state.\n *\n * A premature OK (target not actually merged) is safe: the fast-forward is a\n * no-op, the local work stays diverged and intact, and the resumed sync simply\n * re-creates a fresh temp branch — no data loss, no force push. Only the results\n * checkout is touched; the user's source repo branch is never modified.\n */\nexport async function confirmResultsMergeAndPull(\n config: ResultsConfig,\n): Promise<ResultsRepoStatus> {\n const normalized = normalizeResultsConfig(config);\n const repoDir = await ensureResultsRepoClone(normalized);\n const targetBranch = normalized.branch ?? (await resolveDefaultBranch(repoDir));\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch(() => undefined);\n await fastForwardResultsTowardTarget(repoDir, normalized, targetBranch);\n return syncResultsRepoForProject(config);\n}\n\nexport async function checkoutResultsRepoBranch(\n config: ResultsConfig,\n branchName: string,\n): Promise<CheckedOutResultsRepoBranch> {\n const normalized = normalizeResultsConfig(config);\n const repoDir = await ensureResultsRepoClone(normalized);\n const baseBranch = await resolveDefaultBranch(repoDir);\n await fetchResultsRepo(repoDir, normalized.remote);\n await runGit(['checkout', '-B', branchName, `${normalized.remote}/${baseBranch}`], {\n cwd: repoDir,\n });\n updateStatusFile(normalized, { last_error: undefined });\n return {\n branchName,\n baseBranch,\n repoDir,\n };\n}\n\nexport async function prepareResultsRepoBranch(\n config: ResultsConfig,\n branchName: string,\n): Promise<PreparedResultsRepoBranch> {\n const normalized = normalizeResultsConfig(config);\n const cloneDir = await ensureResultsRepoClone(normalized);\n const baseBranch = await resolveDefaultBranch(cloneDir);\n await fetchResultsRepo(cloneDir, normalized.remote);\n\n const worktreeRoot = await mkdtemp(path.join(os.tmpdir(), 'agentv-results-repo-'));\n const worktreeDir = path.join(worktreeRoot, 'repo');\n await runGit(\n ['worktree', 'add', '-B', branchName, worktreeDir, `${normalized.remote}/${baseBranch}`],\n {\n cwd: cloneDir,\n },\n );\n\n return {\n branchName,\n baseBranch,\n repoDir: worktreeDir,\n cleanup: async () => {\n try {\n await runGit(['worktree', 'remove', '--force', worktreeDir], { cwd: cloneDir });\n } finally {\n await rm(worktreeRoot, { recursive: true, force: true }).catch(() => undefined);\n }\n },\n };\n}\n\nexport async function stageResultsArtifacts(params: {\n readonly repoDir: string;\n readonly sourceDir: string;\n readonly destinationDir: string;\n}): Promise<void> {\n rmSync(params.destinationDir, { recursive: true, force: true });\n mkdirSync(path.dirname(params.destinationDir), { recursive: true });\n await cp(params.sourceDir, params.destinationDir, { recursive: true });\n}\n\nexport function resolveResultsRepoRunsDir(config: ResultsConfig): string {\n const normalized = normalizeResultsConfig(config);\n return path.join(normalized.path, RESULTS_REPO_RESULTS_DIR);\n}\n\nexport async function directorySizeBytes(targetPath: string): Promise<number> {\n const entry = await stat(targetPath);\n if (entry.isFile()) {\n return entry.size;\n }\n\n let total = 0;\n for (const child of await readdir(targetPath, { withFileTypes: true })) {\n total += await directorySizeBytes(path.join(targetPath, child.name));\n }\n return total;\n}\n\nexport async function commitAndPushResultsBranch(params: {\n readonly repoDir: string;\n readonly branchName: string;\n readonly commitMessage: string;\n}): Promise<boolean> {\n await runGit(['add', '--all'], { cwd: params.repoDir });\n\n const { stdout: diffStdout } = await runGit(['status', '--porcelain'], {\n cwd: params.repoDir,\n check: false,\n });\n if (diffStdout.trim().length === 0) {\n return false;\n }\n\n await runGitWithFallbackCommitIdentity(['commit', '-m', params.commitMessage], {\n cwd: params.repoDir,\n });\n await runGit(['push', '-u', 'origin', params.branchName], { cwd: params.repoDir });\n return true;\n}\n\nexport async function pushResultsRepoBranch(\n config: ResultsConfig,\n branchName: string,\n cwd?: string,\n): Promise<void> {\n const normalized = normalizeResultsConfig(config);\n await runGit(['push', '-u', normalized.remote, branchName], {\n cwd: cwd ?? normalized.path,\n });\n updateStatusFile(normalized, {\n last_synced_at: new Date().toISOString(),\n last_error: undefined,\n });\n}\n\nexport async function createDraftResultsPr(params: {\n readonly repo: string;\n readonly repoDir: string;\n readonly baseBranch: string;\n readonly branchName: string;\n readonly title: string;\n readonly body: string;\n}): Promise<string> {\n const { stdout } = await runGh(\n [\n 'pr',\n 'create',\n '--draft',\n '--repo',\n params.repo,\n '--base',\n params.baseBranch,\n '--head',\n params.branchName,\n '--title',\n params.title,\n '--body',\n params.body,\n ],\n { cwd: params.repoDir },\n );\n return stdout.trim();\n}\n\nasync function hasUnpushedCommits(\n repoDir: string,\n upstreamRef: string,\n branch: string,\n): Promise<boolean> {\n const { stdout } = await runGit(['rev-list', '--count', `${upstreamRef}..refs/heads/${branch}`], {\n cwd: repoDir,\n check: false,\n });\n return Number.parseInt(stdout.trim(), 10) > 0;\n}\n\nasync function assertValidResultsBranchName(repoDir: string, branch: string): Promise<void> {\n if (\n branch.length === 0 ||\n branch.includes('..') ||\n branch.startsWith('/') ||\n branch.endsWith('/') ||\n branch.endsWith('.lock') ||\n [...branch].some((char) => {\n const code = char.charCodeAt(0);\n return code <= 31 || code === 127;\n })\n ) {\n throw new Error(`Invalid results branch name: ${branch}`);\n }\n await runGit(['check-ref-format', '--branch', branch], { cwd: repoDir });\n}\n\nfunction normalizeDestinationPath(destinationPath: string): string {\n const normalized = destinationPath.split(path.sep).join('/');\n const segments = normalized.split('/').filter(Boolean);\n if (\n segments.length === 0 ||\n normalized.startsWith('/') ||\n segments.some((segment) => segment === '..') ||\n normalized.split('').some((char) => {\n const code = char.charCodeAt(0);\n return code <= 31 || code === 127;\n })\n ) {\n throw new Error(`Invalid results destination path: ${destinationPath}`);\n }\n return segments.join('/');\n}\n\nasync function listSourceFiles(sourceDir: string): Promise<string[]> {\n const entries: string[] = [];\n async function visit(dir: string): Promise<void> {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n const absolutePath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n await visit(absolutePath);\n } else if (entry.isFile() || entry.isSymbolicLink()) {\n entries.push(absolutePath);\n }\n }\n }\n await visit(sourceDir);\n entries.sort();\n return entries;\n}\n\ntype ArtifactSidecarPointer = {\n readonly path: string;\n readonly sha256?: string;\n readonly objectVersion?: string;\n};\n\ntype PreparedArtifactSidecar = {\n readonly sourceDir: string;\n readonly cleanup: () => Promise<void>;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction artifactSidecarPointers(record: unknown): ArtifactSidecarPointer[] {\n if (!isRecord(record) || !isRecord(record.artifact_pointers)) {\n return [];\n }\n\n const pointers: ArtifactSidecarPointer[] = [];\n const pointer = record.artifact_pointers.transcript;\n if (isRecord(pointer)) {\n if (pointer.ref !== AGENTV_RESULTS_ARTIFACTS_REF || typeof pointer.path !== 'string') {\n return pointers;\n }\n pointers.push({\n path: pointer.path,\n ...(typeof pointer.sha256 === 'string' ? { sha256: pointer.sha256 } : {}),\n ...(typeof pointer.object_version === 'string'\n ? { objectVersion: pointer.object_version }\n : {}),\n });\n }\n return pointers;\n}\n\nfunction artifactSidecarKey(destinationPath: string, pointerPath: string): string {\n return path.posix.join(\n RESULTS_REPO_RUNS_DIR,\n normalizeDestinationPath(destinationPath),\n normalizeDestinationPath(pointerPath),\n );\n}\n\nfunction isDeprecatedTraceArtifactPath(relativePath: string): boolean {\n return relativePath === 'trace.json' || relativePath.endsWith('/trace.json');\n}\n\nfunction isResultManifestFilename(filename: string): boolean {\n return filename === RESULT_INDEX_FILENAME;\n}\n\nfunction safeLocalSummaryManifestPath(\n sourceDir: string,\n manifestPath: unknown,\n): string | undefined {\n if (typeof manifestPath !== 'string' || manifestPath.trim().length === 0) {\n return undefined;\n }\n if (path.isAbsolute(manifestPath)) {\n return undefined;\n }\n const normalized = path.normalize(manifestPath);\n if (normalized.startsWith('..') || path.isAbsolute(normalized)) {\n return undefined;\n }\n return path.join(sourceDir, normalized);\n}\n\nfunction resolveLocalResultManifestPath(sourceDir: string): string | undefined {\n try {\n const summary = JSON.parse(readFileSync(path.join(sourceDir, 'summary.json'), 'utf8')) as {\n index_path?: unknown;\n manifest_path?: unknown;\n };\n const manifestPath = safeLocalSummaryManifestPath(\n sourceDir,\n summary.index_path ?? summary.manifest_path,\n );\n if (manifestPath && existsSync(manifestPath)) {\n return manifestPath;\n }\n } catch {}\n\n const manifestPath = path.join(sourceDir, RUN_INTERNAL_DIRNAME, RESULT_INDEX_FILENAME);\n if (existsSync(manifestPath)) {\n return manifestPath;\n }\n const legacyManifestPath = path.join(sourceDir, RESULT_INDEX_FILENAME);\n if (existsSync(legacyManifestPath)) {\n return legacyManifestPath;\n }\n return undefined;\n}\n\nfunction collectArtifactSidecarPointers(sourceDir: string): ArtifactSidecarPointer[] {\n const indexPath = resolveLocalResultManifestPath(sourceDir);\n if (!indexPath) {\n return [];\n }\n\n const pointers: ArtifactSidecarPointer[] = [];\n for (const line of readFileSync(indexPath, 'utf8').split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n try {\n pointers.push(...artifactSidecarPointers(JSON.parse(trimmed)));\n } catch {}\n }\n return pointers;\n}\n\nfunction resolveArtifactPointerSourcePath(sourceDir: string, pointerPath: string): string {\n const normalizedPointerPath = normalizeDestinationPath(pointerPath);\n const sourceRoot = path.resolve(sourceDir);\n const sourcePath = path.resolve(sourceRoot, ...normalizedPointerPath.split('/'));\n const relative = path.relative(sourceRoot, sourcePath);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error(`Artifact pointer path escapes run directory: ${pointerPath}`);\n }\n return sourcePath;\n}\n\nfunction verifyArtifactPointerChecksum(pointer: ArtifactSidecarPointer, content: Buffer): void {\n const sha256 = createHash('sha256').update(content).digest('hex');\n if (pointer.sha256 && pointer.sha256 !== sha256) {\n throw new Error(`Artifact pointer checksum mismatch for ${pointer.path}`);\n }\n if (pointer.objectVersion && pointer.objectVersion !== `sha256:${sha256}`) {\n throw new Error(`Artifact pointer object_version mismatch for ${pointer.path}`);\n }\n}\n\nasync function prepareArtifactSidecar(params: {\n readonly sourceDir: string;\n readonly pointers: readonly ArtifactSidecarPointer[];\n}): Promise<PreparedArtifactSidecar | undefined> {\n if (params.pointers.length === 0) {\n return undefined;\n }\n\n const sidecarRoot = await mkdtemp(path.join(os.tmpdir(), 'agentv-artifact-sidecar-'));\n const copied = new Set<string>();\n const contentByPath = new Map<string, Buffer>();\n\n try {\n for (const pointer of params.pointers) {\n const relativePointerPath = normalizeDestinationPath(pointer.path);\n let content = contentByPath.get(relativePointerPath);\n if (!content) {\n const sourcePath = resolveArtifactPointerSourcePath(params.sourceDir, relativePointerPath);\n content = readFileSync(sourcePath);\n contentByPath.set(relativePointerPath, content);\n }\n verifyArtifactPointerChecksum(pointer, content);\n if (copied.has(relativePointerPath)) {\n continue;\n }\n const destinationPath = path.join(sidecarRoot, ...relativePointerPath.split('/'));\n mkdirSync(path.dirname(destinationPath), { recursive: true });\n writeFileSync(destinationPath, content);\n copied.add(relativePointerPath);\n }\n } catch (error) {\n await rm(sidecarRoot, { recursive: true, force: true }).catch(() => undefined);\n throw error;\n }\n\n if (copied.size === 0) {\n await rm(sidecarRoot, { recursive: true, force: true }).catch(() => undefined);\n return undefined;\n }\n\n return {\n sourceDir: sidecarRoot,\n cleanup: () => rm(sidecarRoot, { recursive: true, force: true }),\n };\n}\n\nfunction rewritePublishedIndexLine(line: string, destinationPath: string): string {\n if (!line.trim()) {\n return line;\n }\n\n let record: unknown;\n try {\n record = JSON.parse(line);\n } catch {\n return line;\n }\n\n if (!isRecord(record) || !isRecord(record.artifact_pointers)) {\n return line;\n }\n\n let changed = false;\n const pointer = record.artifact_pointers.transcript;\n if (\n isRecord(pointer) &&\n pointer.ref === AGENTV_RESULTS_ARTIFACTS_REF &&\n typeof pointer.path === 'string'\n ) {\n const key = artifactSidecarKey(destinationPath, pointer.path);\n if (pointer.key !== key) {\n pointer.key = key;\n changed = true;\n }\n if (\n Object.keys(record.artifact_pointers).length !== 1 ||\n record.artifact_pointers.transcript !== pointer\n ) {\n changed = true;\n }\n record.artifact_pointers = { transcript: pointer };\n } else {\n record.artifact_pointers = undefined;\n changed = true;\n }\n\n return changed ? JSON.stringify(record) : line;\n}\n\nasync function preparePublishedResultsSource(params: {\n readonly sourceDir: string;\n readonly destinationPath: string;\n readonly pointers: readonly ArtifactSidecarPointer[];\n}): Promise<PreparedArtifactSidecar | undefined> {\n if (params.pointers.length === 0) {\n return undefined;\n }\n\n const publishedRoot = await mkdtemp(path.join(os.tmpdir(), 'agentv-results-published-'));\n const omittedPaths = new Set(\n params.pointers.map((pointer) => normalizeDestinationPath(pointer.path)),\n );\n\n try {\n const sourceFiles = await listSourceFiles(params.sourceDir);\n for (const sourceFile of sourceFiles) {\n const relativeFile = path.relative(params.sourceDir, sourceFile).split(path.sep).join('/');\n const destinationFile = path.join(publishedRoot, ...relativeFile.split('/'));\n if (isResultManifestFilename(path.posix.basename(relativeFile))) {\n const original = readFileSync(sourceFile, 'utf8');\n const rewritten = original\n .split(/\\r?\\n/)\n .map((line) => rewritePublishedIndexLine(line, params.destinationPath))\n .join('\\n');\n mkdirSync(path.dirname(destinationFile), { recursive: true });\n writeFileSync(destinationFile, rewritten);\n continue;\n }\n if (isDeprecatedTraceArtifactPath(relativeFile)) {\n continue;\n }\n if (omittedPaths.has(relativeFile)) {\n continue;\n }\n mkdirSync(path.dirname(destinationFile), { recursive: true });\n await cp(sourceFile, destinationFile, { dereference: false });\n }\n } catch (error) {\n await rm(publishedRoot, { recursive: true, force: true }).catch(() => undefined);\n throw error;\n }\n\n return {\n sourceDir: publishedRoot,\n cleanup: () => rm(publishedRoot, { recursive: true, force: true }),\n };\n}\n\nasync function getExistingRunTreePaths(\n repoDir: string,\n ref: string | undefined,\n destinationTreePath: string,\n): Promise<string[]> {\n if (!ref) {\n return [];\n }\n const { stdout } = await runGit(['ls-tree', '-r', '--name-only', ref, destinationTreePath], {\n cwd: repoDir,\n check: false,\n });\n return stdout\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n}\n\nasync function resolveStorageBranchBase(params: {\n readonly repoDir: string;\n readonly normalized: StorageBranchResultsConfig;\n readonly preferRemote?: boolean;\n}): Promise<{\n readonly baseRef?: string;\n readonly baseCommit?: string;\n readonly baseTree?: string;\n readonly localRef: string;\n readonly localExists: boolean;\n readonly remoteRef: string;\n readonly remoteExists: boolean;\n}> {\n const localRef = `refs/heads/${params.normalized.branch}`;\n const remoteRef = `refs/remotes/${params.normalized.remote}/${params.normalized.branch}`;\n const localExists = await gitRefExists(params.repoDir, localRef);\n const remoteExists = await gitRefExists(params.repoDir, remoteRef);\n const baseRef = params.preferRemote\n ? remoteExists\n ? remoteRef\n : localExists\n ? localRef\n : undefined\n : localExists\n ? localRef\n : remoteExists\n ? remoteRef\n : undefined;\n const baseCommit = baseRef\n ? (\n await runGit(['rev-parse', `${baseRef}^{commit}`], {\n cwd: params.repoDir,\n })\n ).stdout.trim()\n : undefined;\n const baseTree = baseRef\n ? (\n await runGit(['rev-parse', `${baseRef}^{tree}`], {\n cwd: params.repoDir,\n })\n ).stdout.trim()\n : undefined;\n return { baseRef, baseCommit, baseTree, localRef, localExists, remoteRef, remoteExists };\n}\n\nasync function ensureResultsBranchNotCheckedOut(\n repoDir: string,\n normalized: StorageBranchResultsConfig,\n): Promise<void> {\n const currentBranch = await getCurrentBranch(repoDir);\n if (currentBranch !== normalized.branch) {\n return;\n }\n if (usesStorageBranchWorktree(normalized)) {\n throw new Error(\n `Refusing to publish results while '${normalized.branch}' is checked out in ${repoDir}`,\n );\n }\n await runGit(['checkout', '--detach'], { cwd: repoDir });\n}\n\nasync function commitStorageBranchWorktreePaths(params: {\n readonly normalized: StorageBranchResultsConfig;\n readonly repoDir: string;\n readonly paths: readonly string[];\n readonly commitMessage: string;\n}): Promise<boolean> {\n const { normalized } = params;\n const paths = [...new Set(params.paths.filter(isSafeResultsRepoPath))].sort();\n if (paths.length === 0) {\n return false;\n }\n\n await assertValidResultsBranchName(params.repoDir, normalized.branch);\n await ensureResultsBranchNotCheckedOut(params.repoDir, normalized);\n\n let base = await resolveStorageBranchBase({\n repoDir: params.repoDir,\n normalized,\n });\n if (!base.baseRef) {\n await createOrphanResultsBranch(params.repoDir, normalized.branch);\n base = await resolveStorageBranchBase({\n repoDir: params.repoDir,\n normalized,\n });\n }\n\n const indexRoot = await mkdtemp(path.join(os.tmpdir(), 'agentv-results-index-'));\n const indexFile = path.join(indexRoot, 'index');\n const indexEnv = { GIT_INDEX_FILE: indexFile };\n\n try {\n if (base.baseRef) {\n await runGit(['read-tree', base.baseRef], { cwd: params.repoDir, env: indexEnv });\n } else {\n await runGit(['read-tree', '--empty'], { cwd: params.repoDir, env: indexEnv });\n }\n await addResultsGitattributesToIndex(params.repoDir, indexEnv);\n\n for (const gitPath of paths) {\n const sourcePath = path.join(params.repoDir, ...gitPath.split('/'));\n if (!existsSync(sourcePath)) {\n await runGit(['update-index', '--force-remove', '--', gitPath], {\n cwd: params.repoDir,\n env: indexEnv,\n check: false,\n });\n continue;\n }\n\n const fileStat = await lstat(sourcePath);\n let mode = fileStat.mode & 0o111 ? '100755' : '100644';\n if (fileStat.isSymbolicLink()) {\n mode = '120000';\n }\n const { stdout: blob } = await runGit(['hash-object', '-w', '--no-filters', sourcePath], {\n cwd: params.repoDir,\n });\n await runGit(['update-index', '--add', '--cacheinfo', `${mode},${blob.trim()},${gitPath}`], {\n cwd: params.repoDir,\n env: indexEnv,\n });\n }\n\n const { stdout: newTreeStdout } = await runGit(['write-tree'], {\n cwd: params.repoDir,\n env: indexEnv,\n });\n const newTree = newTreeStdout.trim();\n if (base.baseTree && newTree === base.baseTree) {\n return false;\n }\n\n const commitArgs = [\n 'commit-tree',\n newTree,\n ...(base.baseCommit ? ['-p', base.baseCommit] : []),\n '-m',\n params.commitMessage,\n ];\n const { stdout: commitStdout } = await runGitWithFallbackCommitIdentity(commitArgs, {\n cwd: params.repoDir,\n });\n const commitSha = commitStdout.trim();\n await runGit(\n [\n 'update-ref',\n `refs/heads/${normalized.branch}`,\n commitSha,\n ...(base.localExists ? [base.baseCommit ?? ''] : []),\n ].filter(Boolean),\n { cwd: params.repoDir },\n );\n\n if (base.remoteExists) {\n await runGit(['branch', '--set-upstream-to', base.remoteRef, normalized.branch], {\n cwd: params.repoDir,\n check: false,\n });\n }\n\n return true;\n } finally {\n await rm(indexRoot, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\nasync function commitResultsRunWithTemporaryIndex(params: {\n readonly normalized: StorageBranchResultsConfig;\n readonly repoDir: string;\n readonly sourceDir: string;\n readonly destinationPath: string;\n readonly commitMessage: string;\n readonly targetRunId: string;\n readonly preferRemoteBase?: boolean;\n}): Promise<{\n readonly commitCreated: boolean;\n readonly branchUpdated: boolean;\n readonly upstreamRef?: string;\n}> {\n const { normalized } = params;\n await assertValidResultsBranchName(params.repoDir, normalized.branch);\n await ensureResultsBranchNotCheckedOut(params.repoDir, normalized);\n\n const destinationRunPath = normalizeDestinationPath(params.destinationPath);\n const destinationTreePath = path.posix.join(RESULTS_REPO_RUNS_DIR, destinationRunPath);\n let base = await resolveStorageBranchBase({\n repoDir: params.repoDir,\n normalized,\n preferRemote: params.preferRemoteBase,\n });\n\n // No local or remote tip exists yet (after fetching the branch by name): this\n // is the branch's very first commit. Root it at the deterministic empty-tree\n // genesis and parent the run commit on it, rather than letting the run commit\n // itself be the parentless root. This keeps the root SHA byte-identical across\n // clients, so independent first-inits converge on one genesis and reconcile by\n // fast-forward instead of producing divergent orphans.\n if (!base.baseRef) {\n await createOrphanResultsBranch(params.repoDir, normalized.branch);\n base = await resolveStorageBranchBase({\n repoDir: params.repoDir,\n normalized,\n preferRemote: params.preferRemoteBase,\n });\n }\n\n const indexRoot = await mkdtemp(path.join(os.tmpdir(), 'agentv-results-index-'));\n const indexFile = path.join(indexRoot, 'index');\n const indexEnv = { GIT_INDEX_FILE: indexFile };\n\n try {\n if (base.baseRef) {\n await runGit(['read-tree', base.baseRef], { cwd: params.repoDir, env: indexEnv });\n } else {\n await runGit(['read-tree', '--empty'], { cwd: params.repoDir, env: indexEnv });\n }\n await addResultsGitattributesToIndex(params.repoDir, indexEnv);\n\n const existingPaths = await getExistingRunTreePaths(\n params.repoDir,\n base.baseRef,\n destinationTreePath,\n );\n for (const existingPath of existingPaths) {\n await runGit(['update-index', '--force-remove', '--', existingPath], {\n cwd: params.repoDir,\n env: indexEnv,\n check: false,\n });\n }\n\n const sourceFiles = await listSourceFiles(params.sourceDir);\n for (const sourceFile of sourceFiles) {\n const relativeFile = path.relative(params.sourceDir, sourceFile).split(path.sep).join('/');\n const destinationFile = path.posix.join(destinationTreePath, relativeFile);\n const fileStat = await lstat(sourceFile);\n let mode = fileStat.mode & 0o111 ? '100755' : '100644';\n let hashInputPath = sourceFile;\n if (fileStat.isSymbolicLink()) {\n mode = '120000';\n hashInputPath = sourceFile;\n }\n const { stdout: blob } = await runGit(['hash-object', '-w', '--no-filters', hashInputPath], {\n cwd: params.repoDir,\n });\n await runGit(\n ['update-index', '--add', '--cacheinfo', `${mode},${blob.trim()},${destinationFile}`],\n {\n cwd: params.repoDir,\n env: indexEnv,\n },\n );\n }\n\n const { stdout: newTreeStdout } = await runGit(['write-tree'], {\n cwd: params.repoDir,\n env: indexEnv,\n });\n const newTree = newTreeStdout.trim();\n if (base.baseTree && newTree === base.baseTree) {\n return {\n commitCreated: false,\n branchUpdated: false,\n upstreamRef: base.remoteExists ? base.remoteRef : undefined,\n };\n }\n\n const commitArgs = [\n 'commit-tree',\n newTree,\n ...(base.baseCommit ? ['-p', base.baseCommit] : []),\n '-m',\n params.commitMessage,\n '-m',\n `AgentV-Run: ${params.targetRunId}`,\n ];\n const { stdout: commitStdout } = await runGitWithFallbackCommitIdentity(commitArgs, {\n cwd: params.repoDir,\n });\n const commitSha = commitStdout.trim();\n await runGit(\n [\n 'update-ref',\n `refs/heads/${normalized.branch}`,\n commitSha,\n ...(base.localExists && !params.preferRemoteBase ? [base.baseCommit ?? ''] : []),\n ].filter(Boolean),\n { cwd: params.repoDir },\n );\n\n if (base.remoteExists) {\n await runGit(['branch', '--set-upstream-to', base.remoteRef, normalized.branch], {\n cwd: params.repoDir,\n check: false,\n });\n }\n\n return {\n commitCreated: true,\n branchUpdated: true,\n upstreamRef: base.remoteExists ? base.remoteRef : undefined,\n };\n } finally {\n await rm(indexRoot, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\nfunction buildDirectPushResult(\n normalized: NormalizedResultsConfig,\n changed: boolean,\n outcome?: ResultsBranchPushOutcome,\n): DirectPushResultsResult {\n const details = outcome?.details;\n return {\n changed,\n push_conflict_policy: normalized.push_conflict_policy,\n ...(outcome?.blocked === true && {\n blocked: true,\n block_reason: outcome.blockReason,\n sync_status: outcome.syncStatus ?? ('push_conflict' as const),\n }),\n ...pushDetailsToWire(details),\n };\n}\n\nfunction mergeDirectPushResults(\n normalized: NormalizedResultsConfig,\n results: readonly DirectPushResultsResult[],\n): DirectPushResultsResult {\n const blocked = results.find((result) => result.blocked);\n if (blocked) {\n return blocked;\n }\n const detailed = [...results]\n .reverse()\n .find((result) => result.backup_ref !== undefined || result.auto_merged_remote === true);\n return {\n changed: results.some((result) => result.changed),\n push_conflict_policy: normalized.push_conflict_policy,\n ...(detailed?.auto_merged_remote === true && { auto_merged_remote: true }),\n ...(detailed?.backup_ref !== undefined && {\n backup_ref: detailed.backup_ref,\n }),\n ...(detailed?.target_branch !== undefined && { target_branch: detailed.target_branch }),\n ...(detailed?.remote_commit !== undefined && { remote_commit: detailed.remote_commit }),\n ...(detailed?.local_commit !== undefined && { local_commit: detailed.local_commit }),\n ...(detailed?.backup_commit !== undefined && { backup_commit: detailed.backup_commit }),\n ...(detailed?.previous_remote_commit !== undefined && {\n previous_remote_commit: detailed.previous_remote_commit,\n }),\n ...(detailed?.force_pushed_commit !== undefined && {\n force_pushed_commit: detailed.force_pushed_commit,\n }),\n ...(detailed?.lease_commit !== undefined && { lease_commit: detailed.lease_commit }),\n };\n}\n\nasync function pushDirectResultsToStorageBranch(params: {\n readonly normalized: StorageBranchResultsConfig;\n readonly repoDir: string;\n readonly storageBranch: string;\n}): Promise<ResultsBranchPushOutcome | undefined> {\n try {\n await runGit(\n [\n 'push',\n '--porcelain',\n params.normalized.remote,\n `refs/heads/${params.storageBranch}:refs/heads/${params.storageBranch}`,\n ],\n { cwd: params.repoDir },\n );\n updateStatusFile(params.normalized, {\n last_synced_at: new Date().toISOString(),\n last_error: undefined,\n });\n await fetchResultsRepo(params.repoDir, params.normalized.remote, params.storageBranch).catch(\n () => undefined,\n );\n return undefined;\n } catch (error) {\n if (!isNonFastForwardPushError(error)) {\n throw error;\n }\n const outcome = await resolveResultBranchPushConflict({\n normalized: params.normalized,\n repoDir: params.repoDir,\n targetBranch: params.storageBranch,\n sourceRef: `refs/heads/${params.storageBranch}`,\n });\n if (outcome.blocked) {\n updateStatusFile(params.normalized, { last_error: outcome.blockReason });\n return outcome;\n }\n updateStatusFile(params.normalized, {\n last_synced_at: new Date().toISOString(),\n last_error: undefined,\n });\n await fetchResultsRepo(params.repoDir, params.normalized.remote, params.storageBranch).catch(\n () => undefined,\n );\n return outcome;\n }\n}\n\nasync function commitAndMaybePushRunTree(params: {\n readonly normalized: StorageBranchResultsConfig;\n readonly repoDir: string;\n readonly sourceDir: string;\n readonly destinationPath: string;\n readonly commitMessage: string;\n readonly targetRunId: string;\n readonly shouldPush: boolean;\n}): Promise<DirectPushResultsResult> {\n const result = await commitResultsRunWithTemporaryIndex({\n normalized: params.normalized,\n repoDir: params.repoDir,\n sourceDir: params.sourceDir,\n destinationPath: params.destinationPath,\n commitMessage: params.commitMessage,\n targetRunId: params.targetRunId,\n });\n\n if (!params.shouldPush) {\n updateStatusFile(params.normalized, { last_error: undefined });\n return buildDirectPushResult(params.normalized, result.commitCreated);\n }\n\n if (!result.commitCreated) {\n const localBranchExists = await gitRefExists(\n params.repoDir,\n `refs/heads/${params.normalized.branch}`,\n );\n const hasUnpushed = result.upstreamRef\n ? localBranchExists\n ? await hasUnpushedCommits(params.repoDir, result.upstreamRef, params.normalized.branch)\n : false\n : localBranchExists;\n if (!hasUnpushed) {\n return buildDirectPushResult(params.normalized, false);\n }\n\n const aheadPaths = result.upstreamRef\n ? await getAheadPaths(\n params.repoDir,\n result.upstreamRef,\n `refs/heads/${params.normalized.branch}`,\n )\n : [];\n if (result.upstreamRef && !areSafeResultsRepoPaths(aheadPaths)) {\n const error = new Error('Results repo has non-results committed changes');\n updateStatusFile(params.normalized, { last_error: error.message });\n throw error;\n }\n const outcome = await pushDirectResultsToStorageBranch({\n normalized: params.normalized,\n repoDir: params.repoDir,\n storageBranch: params.normalized.branch,\n });\n return buildDirectPushResult(params.normalized, !outcome?.blocked, outcome);\n }\n\n const outcome = await pushDirectResultsToStorageBranch({\n normalized: params.normalized,\n repoDir: params.repoDir,\n storageBranch: params.normalized.branch,\n });\n return buildDirectPushResult(params.normalized, !outcome?.blocked, outcome);\n}\n\n/**\n * Push results directly to the configured storage branch of the results repo.\n * Handles non-fast-forward conflicts with the configured push conflict policy.\n * Returns true if artifacts were pushed, false if no changes were detected.\n */\nexport async function directPushResults(params: {\n readonly config: ResultsConfig;\n readonly sourceDir: string;\n readonly destinationPath: string;\n readonly commitMessage: string;\n}): Promise<boolean> {\n const result = await directPushResultsWithDetails(params);\n if (result.blocked) {\n throw new ResultsBranchPushConflictError(result);\n }\n return result.changed;\n}\n\nexport async function directPushResultsWithDetails(params: {\n readonly config: ResultsConfig;\n readonly sourceDir: string;\n readonly destinationPath: string;\n readonly commitMessage: string;\n}): Promise<DirectPushResultsResult> {\n const normalized = normalizeResultsConfig(params.config);\n const repoDir = await ensureResultsRepoClone(normalized);\n await fetchResultsRepo(repoDir, normalized.remote, normalized.branch).catch((error) => {\n if (normalized.require_push) {\n throw error;\n }\n });\n const storageBranch = normalized.branch ?? (await resolveDefaultBranch(repoDir));\n const storageConfig: StorageBranchResultsConfig = {\n ...normalized,\n branch: storageBranch,\n };\n const targetRunId = buildGitRunId(params.destinationPath);\n const shouldPush = normalized.auto_push || normalized.require_push;\n const sidecarPointers = collectArtifactSidecarPointers(params.sourceDir);\n const sidecar = await prepareArtifactSidecar({\n sourceDir: params.sourceDir,\n pointers: sidecarPointers,\n });\n let publishedResultsSource: PreparedArtifactSidecar | undefined;\n\n try {\n publishedResultsSource = await preparePublishedResultsSource({\n sourceDir: params.sourceDir,\n destinationPath: params.destinationPath,\n pointers: sidecarPointers,\n });\n\n const pushResults: DirectPushResultsResult[] = [];\n if (sidecar) {\n await fetchResultsRepo(repoDir, normalized.remote, AGENTV_RESULTS_ARTIFACTS_REF).catch(\n (error) => {\n if (normalized.require_push) {\n throw error;\n }\n },\n );\n const sidecarResult = await commitAndMaybePushRunTree({\n normalized: {\n ...normalized,\n branch: AGENTV_RESULTS_ARTIFACTS_REF,\n },\n repoDir,\n sourceDir: sidecar.sourceDir,\n destinationPath: params.destinationPath,\n commitMessage: `chore(results): publish artifact sidecars for ${targetRunId}`,\n targetRunId,\n shouldPush,\n });\n pushResults.push(sidecarResult);\n if (sidecarResult.blocked) {\n return sidecarResult;\n }\n }\n\n pushResults.push(\n await commitAndMaybePushRunTree({\n normalized: storageConfig,\n repoDir,\n sourceDir: publishedResultsSource?.sourceDir ?? params.sourceDir,\n destinationPath: params.destinationPath,\n commitMessage: params.commitMessage,\n targetRunId,\n shouldPush,\n }),\n );\n return mergeDirectPushResults(normalized, pushResults);\n } finally {\n await publishedResultsSource?.cleanup().catch(() => undefined);\n await sidecar?.cleanup().catch(() => undefined);\n }\n}\n\nexport interface GitListedRun {\n run_id: string;\n experiment: string;\n timestamp: string;\n pass_rate?: number;\n target?: string;\n index_path: string;\n summary_path?: string;\n display_name: string;\n test_count: number;\n execution_error_count?: number;\n avg_score: number;\n size_bytes: number;\n}\n\ninterface GitResultsIndexCacheFile {\n readonly schema_version: typeof GIT_RESULTS_INDEX_CACHE_SCHEMA_VERSION;\n readonly result_layout_version: typeof GIT_RESULTS_INDEX_LAYOUT_VERSION;\n readonly repo_key: string;\n readonly repo_dir: string;\n readonly ref: string;\n readonly commit_sha: string;\n readonly generated_at: string;\n readonly runs: readonly GitListedRun[];\n}\n\ntype GitBatchBlob = {\n readonly size: number;\n readonly content: Buffer;\n};\n\ntype GitRunSummary = {\n readonly index_path?: string;\n readonly manifest_path?: string;\n readonly metadata?: {\n readonly display_name?: string;\n readonly timestamp?: string;\n readonly experiment?: string;\n readonly targets?: readonly string[];\n readonly tests_run?: readonly string[];\n };\n readonly run_summary?: Record<\n string,\n {\n readonly pass_rate?: { readonly mean?: number };\n }\n >;\n};\n\nfunction safeGitSummaryManifestPath(runDir: string, manifestPath: unknown): string | undefined {\n if (typeof manifestPath !== 'string' || manifestPath.trim().length === 0) {\n return undefined;\n }\n if (manifestPath.startsWith('/')) {\n return undefined;\n }\n const normalized = path.posix.normalize(manifestPath);\n if (normalized === '..' || normalized.startsWith('../')) {\n return undefined;\n }\n return path.posix.join(runDir, normalized);\n}\n\nfunction buildGitManifestPaths(\n treePaths: readonly string[],\n summaryByPath: ReadonlyMap<string, GitRunSummary>,\n): string[] {\n const treePathSet = new Set(treePaths);\n const manifestByRunDir = new Map<string, string>();\n\n for (const [summaryPath, summary] of summaryByPath) {\n const runDir = path.posix.dirname(summaryPath);\n const relativeRunPath = path.posix.relative(RESULTS_REPO_RUNS_DIR, runDir);\n if (!isV2ResultsRepoRunPath(relativeRunPath)) {\n continue;\n }\n const manifestPath =\n safeGitSummaryManifestPath(runDir, summary.index_path ?? summary.manifest_path) ??\n fallbackGitManifestPath(runDir, treePathSet);\n if (manifestPath && treePathSet.has(manifestPath)) {\n manifestByRunDir.set(runDir, manifestPath);\n }\n }\n\n for (const treePath of treePaths) {\n if (!treePath.endsWith(`/${RESULT_INDEX_FILENAME}`)) {\n continue;\n }\n const runDir = gitRunDirForManifestPath(treePath);\n const relativeRunPath = path.posix.relative(RESULTS_REPO_RUNS_DIR, runDir);\n if (!isV2ResultsRepoRunPath(relativeRunPath)) {\n continue;\n }\n if (!manifestByRunDir.has(runDir)) {\n manifestByRunDir.set(runDir, treePath);\n }\n }\n\n return [...manifestByRunDir.values()].sort();\n}\n\nfunction fallbackGitManifestPath(\n runDir: string,\n treePathSet: ReadonlySet<string>,\n): string | undefined {\n for (const candidate of [\n path.posix.join(runDir, '.internal', RESULT_INDEX_FILENAME),\n path.posix.join(runDir, RESULT_INDEX_FILENAME),\n ]) {\n if (treePathSet.has(candidate)) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction gitRunDirForManifestPath(manifestPath: string): string {\n const manifestDir = path.posix.dirname(manifestPath);\n return path.posix.basename(manifestDir) === '.internal'\n ? path.posix.dirname(manifestDir)\n : manifestDir;\n}\n\nfunction isV2ResultsRepoRunPath(relativeRunPath: string): boolean {\n const segments = relativeRunPath.split('/').filter(Boolean);\n return segments.length === 1 && !segments[0].startsWith('.');\n}\n\nfunction buildGitRunId(relativeRunPath: string): string {\n const normalized = relativeRunPath.split(path.sep).join('/');\n const segments = normalized.split('/').filter(Boolean);\n return segments[0] ?? relativeRunPath;\n}\n\nfunction getRunExperiment(runId: string, summary: GitRunSummary | undefined): string {\n const experiment = summary?.metadata?.experiment?.trim();\n if (experiment) {\n return experiment;\n }\n\n const separatorIndex = runId.lastIndexOf('::');\n return separatorIndex === -1 ? 'default' : runId.slice(0, separatorIndex);\n}\n\nfunction computeAveragePassRate(runSummary: GitRunSummary['run_summary']): number | undefined {\n if (!runSummary) {\n return undefined;\n }\n\n const passRates = Object.values(runSummary)\n .map((summary) => summary.pass_rate?.mean)\n .filter((value): value is number => typeof value === 'number' && Number.isFinite(value));\n\n if (passRates.length === 0) {\n return undefined;\n }\n\n return passRates.reduce((sum, value) => sum + value, 0) / passRates.length;\n}\n\nasync function runGitBatch(repoDir: string, input: string): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const child = spawn('git', ['cat-file', '--batch'], {\n cwd: repoDir,\n env: getGitEnv(),\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n\n child.stdout.on('data', (chunk: Buffer | string) => {\n stdoutChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n child.stderr.on('data', (chunk: Buffer | string) => {\n stderrChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n child.on('error', (error) => reject(withFriendlyGitHubAuthError(error)));\n child.on('close', (code) => {\n if (code === 0) {\n resolve(Buffer.concat(stdoutChunks));\n return;\n }\n\n const stderr = Buffer.concat(stderrChunks).toString('utf8').trim();\n reject(\n withFriendlyGitHubAuthError(\n stderr.length > 0 ? new Error(stderr) : new Error('git cat-file failed'),\n ),\n );\n });\n\n child.stdin.end(input);\n });\n}\n\nfunction parseGitBatchBlobs(output: Buffer): GitBatchBlob[] {\n const blobs: GitBatchBlob[] = [];\n let offset = 0;\n\n while (offset < output.length) {\n const headerEnd = output.indexOf(0x0a, offset);\n if (headerEnd === -1) {\n throw new Error('Malformed git cat-file output: missing header terminator');\n }\n\n const header = output.subarray(offset, headerEnd).toString('utf8');\n offset = headerEnd + 1;\n\n if (header.length === 0) {\n continue;\n }\n\n const missingMatch = /^(.*) missing$/.exec(header);\n if (missingMatch) {\n continue;\n }\n\n const headerMatch = /^(.*) (\\w+) (\\d+)$/.exec(header);\n if (!headerMatch) {\n throw new Error(`Malformed git cat-file header: ${header}`);\n }\n\n const [, objectRef, objectType, sizeText] = headerMatch;\n if (objectType !== 'blob') {\n throw new Error(`Unsupported git object type for ${objectRef}: ${objectType}`);\n }\n\n const size = Number.parseInt(sizeText, 10);\n const contentEnd = offset + size;\n if (contentEnd > output.length) {\n throw new Error(`Malformed git cat-file output for ${objectRef}: truncated blob content`);\n }\n\n blobs.push({\n size,\n content: output.subarray(offset, contentEnd),\n });\n offset = contentEnd;\n\n if (offset < output.length && output[offset] === 0x0a) {\n offset += 1;\n }\n }\n\n return blobs;\n}\n\nexport interface GitResultArtifactReadParams {\n readonly repoDir: string;\n readonly key: string;\n readonly ref?: string;\n readonly remote?: string;\n readonly sha256?: string;\n readonly objectVersion?: string;\n}\n\nexport async function readGitResultArtifact(\n params: GitResultArtifactReadParams,\n): Promise<Buffer | undefined> {\n const artifactRef = params.ref ?? AGENTV_RESULTS_ARTIFACTS_REF;\n const normalizedKey = normalizeDestinationPath(params.key);\n const remote = params.remote ?? 'origin';\n if (!artifactRef.startsWith('refs/')) {\n await fetchResultsArtifactRef(params.repoDir, remote, artifactRef).catch(() => undefined);\n }\n\n const candidateRefs = [\n `refs/remotes/${remote}/${artifactRef}`,\n `refs/heads/${artifactRef}`,\n artifactRef,\n ].filter((candidate, index, all) => all.indexOf(candidate) === index);\n\n for (const candidateRef of candidateRefs) {\n const blobs = parseGitBatchBlobs(\n await runGitBatch(params.repoDir, `${candidateRef}:${normalizedKey}\\n`),\n );\n const blob = blobs[0];\n if (!blob) {\n continue;\n }\n verifyArtifactPointerChecksum(\n {\n path: normalizedKey,\n ...(params.sha256 ? { sha256: params.sha256 } : {}),\n ...(params.objectVersion ? { objectVersion: params.objectVersion } : {}),\n },\n blob.content,\n );\n return Buffer.from(blob.content);\n }\n\n return undefined;\n}\n\n// ── WIP (work-in-progress) branch helpers ─────────────────────────────────\n//\n// Periodic best-effort checkpoints push the partial run output to a unique\n// non-default branch (`agentv/wip/<hostname>/<run-dir-basename>`) every ~30s.\n// The branch is force-pushed (single-writer) to avoid conflict handling and\n// noisy history. On successful run completion the branch is deleted.\n//\n// Manual recovery: if a pod is lost mid-run, an operator can clone the results\n// repo, checkout `agentv/wip/<hostname>/<run-dir>`, and resume with:\n// cp -r <run-dir> <local-workspace>\n// agentv eval <eval-file> --output <local-workspace>/<run-dir> --resume\n\nexport function buildWipBranchName(runDir: string): string {\n const hostname = os\n .hostname()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .slice(0, 40);\n const runBasename = path\n .basename(runDir)\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .slice(0, 60);\n return `agentv/wip/${hostname}/${runBasename}`;\n}\n\nexport interface WipWorktreeHandle {\n readonly wipBranch: string;\n readonly worktreeDir: string;\n readonly cloneDir: string;\n readonly remote: string;\n readonly cleanup: () => Promise<void>;\n}\n\nexport async function setupWipWorktree(params: {\n readonly config: ResultsConfig;\n readonly wipBranch: string;\n}): Promise<WipWorktreeHandle> {\n const normalized = normalizeResultsConfig(params.config);\n const cloneDir = await ensureResultsRepoClone(normalized);\n await fetchResultsRepo(cloneDir, normalized.remote, normalized.branch).catch((error) => {\n if (normalized.require_push) {\n throw error;\n }\n });\n let baseRef = normalized.branch\n ? await configuredResultsBranchRef(cloneDir, normalized)\n : remoteBranchRef(await resolveDefaultBranch(cloneDir), normalized.remote);\n if (!baseRef && normalized.branch) {\n await createOrphanResultsBranch(cloneDir, normalized.branch);\n baseRef = normalized.branch;\n }\n if (!baseRef) {\n throw new Error('Could not resolve a base ref for the WIP results branch');\n }\n const worktreeRoot = await mkdtemp(path.join(os.tmpdir(), 'agentv-wip-'));\n const worktreeDir = path.join(worktreeRoot, 'repo');\n await runGit(['worktree', 'add', '-B', params.wipBranch, worktreeDir, baseRef], {\n cwd: cloneDir,\n });\n return {\n wipBranch: params.wipBranch,\n worktreeDir,\n cloneDir,\n remote: normalized.remote,\n cleanup: async () => {\n try {\n await runGit(['worktree', 'remove', '--force', worktreeDir], { cwd: cloneDir });\n } finally {\n await rm(worktreeRoot, { recursive: true, force: true }).catch(() => undefined);\n }\n },\n };\n}\n\n/**\n * Snapshot the current run output into the WIP worktree and force-push to the\n * remote WIP branch. Returns true if a push was performed, false if nothing changed.\n *\n * Uses `--amend` on the base-branch tip so the remote WIP branch always holds\n * exactly one snapshot commit (no noisy history accumulation).\n */\nexport async function pushWipCheckpoint(params: {\n readonly handle: WipWorktreeHandle;\n readonly sourceDir: string;\n readonly destinationPath: string;\n}): Promise<boolean> {\n const destinationDir = path.join(\n params.handle.worktreeDir,\n RESULTS_REPO_RUNS_DIR,\n params.destinationPath,\n );\n await stageResultsArtifacts({\n repoDir: params.handle.worktreeDir,\n sourceDir: params.sourceDir,\n destinationDir,\n });\n writeFileSync(\n path.join(params.handle.worktreeDir, RESULTS_REPO_GITATTRIBUTES_FILE),\n RESULTS_REPO_GITATTRIBUTES_CONTENT,\n );\n await runGit(['add', '--all', '--', RESULTS_REPO_GITATTRIBUTES_FILE, params.destinationPath], {\n cwd: params.handle.worktreeDir,\n });\n const { stdout: status } = await runGit(['status', '--porcelain'], {\n cwd: params.handle.worktreeDir,\n check: false,\n });\n if (!status.trim()) {\n return false;\n }\n const timestamp = new Date().toISOString();\n await runGitWithFallbackCommitIdentity(\n ['commit', '--amend', '-m', `wip(results): checkpoint ${params.handle.wipBranch} ${timestamp}`],\n { cwd: params.handle.worktreeDir },\n );\n await runGit(['push', '--force', params.handle.remote, params.handle.wipBranch], {\n cwd: params.handle.worktreeDir,\n });\n return true;\n}\n\nexport async function deleteWipBranch(params: {\n readonly config: ResultsConfig;\n readonly wipBranch: string;\n}): Promise<void> {\n const normalized = normalizeResultsConfig(params.config);\n const cloneDir = await ensureResultsRepoClone(normalized);\n const result = await runGit(['push', normalized.remote, '--delete', params.wipBranch], {\n cwd: cloneDir,\n check: false,\n });\n if (result.exitCode === 0 || isMissingRemoteRefDelete(result)) {\n return;\n }\n throw new Error(result.stderr.trim() || result.stdout.trim() || 'Failed to delete WIP branch');\n}\n\nfunction isMissingRemoteRefDelete(result: { stdout: string; stderr: string }): boolean {\n const text = `${result.stderr}\\n${result.stdout}`.toLowerCase();\n return text.includes('remote ref does not exist');\n}\n\n// git exits non-zero with one of these messages when the requested ref/object\n// does not exist yet — e.g. a configured results branch that has never been\n// pushed. We treat that as \"no remote runs\" rather than a hard failure.\nfunction isMissingGitRefError(error: unknown): boolean {\n const parts: string[] = [];\n if (error && typeof error === 'object') {\n const e = error as { stderr?: unknown; message?: unknown };\n if (typeof e.stderr === 'string') parts.push(e.stderr);\n if (typeof e.message === 'string') parts.push(e.message);\n } else if (typeof error === 'string') {\n parts.push(error);\n }\n const haystack = parts.join('\\n').toLowerCase();\n return (\n haystack.includes('not a valid object name') ||\n haystack.includes('unknown revision or path') ||\n haystack.includes('bad revision') ||\n haystack.includes('does not exist') ||\n haystack.includes('needed a single revision')\n );\n}\n\nfunction gitResultsIndexHash(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction resolveGitResultsIndexRepoDir(repoDir: string): string {\n const resolved = path.resolve(repoDir);\n try {\n return realpathSync(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction gitResultsIndexRepoKey(repoDir: string): string {\n return `sha256-${gitResultsIndexHash(resolveGitResultsIndexRepoDir(repoDir)).slice(0, 32)}`;\n}\n\nfunction gitResultsIndexRefKey(ref: string): string {\n const slug = sanitizeRepoSlug(ref).slice(0, 80) || 'default';\n return `${slug}-${gitResultsIndexHash(ref).slice(0, 16)}`;\n}\n\nexport function resolveGitResultsIndexCacheFile(params: {\n readonly repoDir: string;\n readonly ref?: string;\n readonly commitSha: string;\n}): string {\n const ref = params.ref ?? 'origin/main';\n return path.join(\n getAgentvDataDir(),\n 'cache',\n 'results-index',\n gitResultsIndexRepoKey(params.repoDir),\n gitResultsIndexRefKey(ref),\n `${params.commitSha}.json`,\n );\n}\n\nfunction isGitListedRun(value: unknown): value is GitListedRun {\n if (!value || typeof value !== 'object') return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record.run_id === 'string' &&\n typeof record.experiment === 'string' &&\n typeof record.timestamp === 'string' &&\n (typeof record.index_path === 'string' || typeof record.manifest_path === 'string') &&\n typeof record.display_name === 'string' &&\n typeof record.test_count === 'number' &&\n typeof record.avg_score === 'number' &&\n typeof record.size_bytes === 'number' &&\n (record.execution_error_count === undefined ||\n typeof record.execution_error_count === 'number') &&\n (record.pass_rate === undefined || typeof record.pass_rate === 'number') &&\n (record.target === undefined || typeof record.target === 'string') &&\n (record.summary_path === undefined || typeof record.summary_path === 'string')\n );\n}\n\nfunction validateGitResultsIndexCacheFile(\n value: unknown,\n params: { repoDir: string; ref: string; commitSha: string },\n): GitResultsIndexCacheFile | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const record = value as Record<string, unknown>;\n const repoDir = resolveGitResultsIndexRepoDir(params.repoDir);\n const repoKey = gitResultsIndexRepoKey(params.repoDir);\n if (\n record.schema_version !== GIT_RESULTS_INDEX_CACHE_SCHEMA_VERSION ||\n record.result_layout_version !== GIT_RESULTS_INDEX_LAYOUT_VERSION ||\n record.repo_key !== repoKey ||\n record.repo_dir !== repoDir ||\n record.ref !== params.ref ||\n record.commit_sha !== params.commitSha ||\n !Array.isArray(record.runs) ||\n !record.runs.every(isGitListedRun)\n ) {\n return undefined;\n }\n return value as GitResultsIndexCacheFile;\n}\n\nasync function readGitResultsIndexCache(params: {\n readonly repoDir: string;\n readonly ref: string;\n readonly commitSha: string;\n}): Promise<readonly GitListedRun[] | undefined> {\n const cacheFile = resolveGitResultsIndexCacheFile(params);\n try {\n const parsed = JSON.parse(await readFile(cacheFile, 'utf8')) as unknown;\n return validateGitResultsIndexCacheFile(parsed, params)?.runs;\n } catch {\n return undefined;\n }\n}\n\nasync function writeGitResultsIndexCache(params: {\n readonly repoDir: string;\n readonly ref: string;\n readonly commitSha: string;\n readonly runs: readonly GitListedRun[];\n}): Promise<void> {\n const cacheFile = resolveGitResultsIndexCacheFile(params);\n const envelope: GitResultsIndexCacheFile = {\n schema_version: GIT_RESULTS_INDEX_CACHE_SCHEMA_VERSION,\n result_layout_version: GIT_RESULTS_INDEX_LAYOUT_VERSION,\n repo_key: gitResultsIndexRepoKey(params.repoDir),\n repo_dir: resolveGitResultsIndexRepoDir(params.repoDir),\n ref: params.ref,\n commit_sha: params.commitSha,\n generated_at: new Date().toISOString(),\n runs: params.runs,\n };\n try {\n mkdirSync(path.dirname(cacheFile), { recursive: true });\n const tempFile = `${cacheFile}.${process.pid}.${Date.now()}.tmp`;\n await writeFile(tempFile, `${JSON.stringify(envelope, null, 2)}\\n`, 'utf8');\n renameSync(tempFile, cacheFile);\n } catch {\n // Cache writes are best-effort; git-native listing remains the source of truth.\n }\n}\n\nexport async function resolveGitRunsRefCommit(\n repoDir: string,\n ref = 'origin/main',\n): Promise<string | undefined> {\n try {\n const { stdout } = await runGit(['rev-parse', '--verify', `${ref}^{commit}`], {\n cwd: repoDir,\n });\n return stdout.trim() || undefined;\n } catch (error) {\n if (isMissingGitRefError(error)) {\n return undefined;\n }\n throw error;\n }\n}\n\nexport async function listGitRunsCached(\n repoDir: string,\n ref = 'origin/main',\n): Promise<GitListedRun[]> {\n const commitSha = await resolveGitRunsRefCommit(repoDir, ref);\n if (!commitSha) {\n return [];\n }\n\n const cached = await readGitResultsIndexCache({ repoDir, ref, commitSha });\n if (cached) {\n return [...cached];\n }\n\n const runs = await listGitRuns(repoDir, ref);\n await writeGitResultsIndexCache({ repoDir, ref, commitSha, runs });\n return runs;\n}\n\nexport async function listGitRuns(repoDir: string, ref = 'origin/main'): Promise<GitListedRun[]> {\n let treeOut: string;\n try {\n ({ stdout: treeOut } = await runGit(\n ['ls-tree', '-r', '--name-only', ref, RESULTS_REPO_RUNS_DIR],\n {\n cwd: repoDir,\n },\n ));\n } catch (error) {\n // A not-yet-created results branch is an empty result, not an error. This\n // keeps the Dashboard's remote-results poll quiet before the first push.\n if (isMissingGitRefError(error)) {\n return [];\n }\n throw error;\n }\n\n const treePaths = treeOut\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n const summaryPaths = treePaths.filter((line) => line.endsWith('/summary.json'));\n const summaryByPath = new Map<string, GitRunSummary>();\n if (summaryPaths.length > 0) {\n const summaryBatchInput = `${summaryPaths.map((summaryPath) => `${ref}:${summaryPath}`).join('\\n')}\\n`;\n const summaryBlobs = parseGitBatchBlobs(await runGitBatch(repoDir, summaryBatchInput));\n for (let i = 0; i < summaryBlobs.length; i++) {\n const summaryPath = summaryPaths[i];\n const blob = summaryBlobs[i];\n if (!summaryPath || !blob) continue;\n summaryByPath.set(summaryPath, JSON.parse(blob.content.toString('utf8')) as GitRunSummary);\n }\n }\n\n const indexPaths = buildGitManifestPaths(treePaths, summaryByPath);\n if (indexPaths.length === 0) {\n return [];\n }\n\n const batchInput = `${indexPaths.map((indexPath) => `${ref}:${indexPath}`).join('\\n')}\\n`;\n const blobs = parseGitBatchBlobs(await runGitBatch(repoDir, batchInput));\n if (blobs.length !== indexPaths.length) {\n throw new Error(\n `Expected ${indexPaths.length} git blobs but received ${blobs.length} while listing results runs`,\n );\n }\n\n const runs = blobs.flatMap((blob, index): GitListedRun[] => {\n const manifestPath = indexPaths[index];\n const runDir = gitRunDirForManifestPath(manifestPath);\n const summaryPath = path.posix.join(runDir, 'summary.json');\n const summary = summaryByPath.get(summaryPath);\n const relativeRunPath = path.posix.relative(RESULTS_REPO_RUNS_DIR, runDir);\n const runId = buildGitRunId(relativeRunPath);\n const rows = blob.content\n .toString('utf8')\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .flatMap(\n (\n line,\n ): {\n timestamp?: string;\n target?: string;\n test_id?: string;\n score?: number;\n execution_status?: string;\n }[] => {\n try {\n return [\n JSON.parse(line) as {\n timestamp?: string;\n target?: string;\n test_id?: string;\n score?: number;\n execution_status?: string;\n },\n ];\n } catch {\n return [];\n }\n },\n );\n const rowTargets = [\n ...new Set(rows.map((row) => row.target).filter((target): target is string => !!target)),\n ];\n const rowTestIds = [\n ...new Set(rows.map((row) => row.test_id).filter((testId): testId is string => !!testId)),\n ];\n const rowScores = rows\n .map((row) => row.score)\n .filter((score): score is number => typeof score === 'number' && Number.isFinite(score));\n const avgScore =\n rowScores.length > 0\n ? rowScores.reduce((sum, score) => sum + score, 0) / rowScores.length\n : 0;\n const timestamp =\n summary?.metadata?.timestamp?.trim() || rows[0]?.timestamp || path.posix.basename(runDir);\n const displayName = summary?.metadata?.display_name?.trim() || path.posix.basename(runDir);\n const targets = summary?.metadata?.targets ?? rowTargets;\n const passRate = computeAveragePassRate(summary?.run_summary) ?? avgScore;\n const executionErrorCount = rows.filter(\n (row) => row.execution_status === 'execution_error',\n ).length;\n\n return [\n {\n run_id: runId,\n experiment: getRunExperiment(runId, summary),\n timestamp,\n ...(passRate !== undefined && { pass_rate: passRate }),\n ...(targets.length === 1 && targets[0] ? { target: targets[0] } : {}),\n index_path: manifestPath,\n ...(summaryByPath.has(summaryPath) && { summary_path: summaryPath }),\n display_name: displayName,\n test_count: summary?.metadata?.tests_run?.length ?? rowTestIds.length,\n ...(executionErrorCount > 0 && { execution_error_count: executionErrorCount }),\n avg_score: avgScore,\n size_bytes: blob.size,\n },\n ];\n });\n\n runs.sort((a, b) => b.timestamp.localeCompare(a.timestamp));\n return runs;\n}\n\nexport async function materializeGitRun(\n repoDir: string,\n relativeRunPath: string,\n ref = 'origin/main',\n): Promise<void> {\n const normalizedRunPath = relativeRunPath.split(path.sep).join('/');\n const runTreePath = path.posix.join(RESULTS_REPO_RUNS_DIR, normalizedRunPath);\n const targetRunDir = path.join(repoDir, ...runTreePath.split('/'));\n const { stdout: treeOut } = await runGit(['ls-tree', '-r', '--name-only', ref, runTreePath], {\n cwd: repoDir,\n });\n\n const filePaths = treeOut\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n if (filePaths.length === 0) {\n return;\n }\n\n const batchInput = `${filePaths.map((filePath) => `${ref}:${filePath}`).join('\\n')}\\n`;\n const blobs = parseGitBatchBlobs(await runGitBatch(repoDir, batchInput));\n if (blobs.length !== filePaths.length) {\n throw new Error(\n `Expected ${filePaths.length} git blobs but received ${blobs.length} while materializing results run`,\n );\n }\n\n const tempRoot = mkdtempSync(path.join(repoDir, '.agentv-run-'));\n const tempRunDir = path.join(tempRoot, 'run');\n\n try {\n for (const [index, filePath] of filePaths.entries()) {\n const relativeFilePath = path.posix.relative(runTreePath, filePath);\n const absolutePath = path.join(tempRunDir, ...relativeFilePath.split('/'));\n mkdirSync(path.dirname(absolutePath), { recursive: true });\n writeFileSync(absolutePath, blobs[index].content);\n }\n\n mkdirSync(path.dirname(targetRunDir), { recursive: true });\n try {\n renameSync(tempRunDir, targetRunDir);\n } catch (error) {\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined;\n if ((code === 'EEXIST' || code === 'ENOTEMPTY') && existsSync(targetRunDir)) {\n return;\n }\n throw error;\n }\n } finally {\n rmSync(tempRoot, { recursive: true, force: true });\n }\n}\n","/**\n * Project sync — pulls remote Git repos to the local path declared in the\n * project registry before Dashboard/eval startup.\n *\n * Sync is oneshot only, triggered by the Dashboard UI \"Sync\" button or the\n * `agentv project sync` CLI command. There is no daemon or continuous mode.\n *\n * First run — git clone --depth 1 --filter=blob:none --branch <ref> <repoUrl> <path>\n * Subsequent — git pull --ff-only (when <path>/.git already exists)\n *\n * Usage:\n * import { syncProjects } from './project-sync.js';\n * await syncProjects(registry.projects);\n */\n\nimport * as childProcess from 'node:child_process';\nimport { existsSync } from 'node:fs';\n\nimport type { ProjectEntry } from './projects.js';\n\n/**\n * Clone or pull a single project entry from its declared repo URL.\n * - No .git present: shallow clone into entry.path.\n * - .git present: git pull --ff-only to update in place.\n * Throws on git error or missing repoUrl/ref.\n */\nexport async function syncProject(entry: ProjectEntry): Promise<void> {\n if (!entry.repoUrl) {\n throw new Error(`Project '${entry.id}' has no repo.url defined`);\n }\n if (!entry.ref) {\n throw new Error(`Project '${entry.id}' has no repo.branch defined`);\n }\n const dest = entry.path;\n\n if (existsSync(`${dest}/.git`)) {\n childProcess.execFileSync('git', ['-C', dest, 'pull', '--ff-only'], { stdio: 'inherit' });\n } else {\n childProcess.execFileSync(\n 'git',\n ['clone', '--depth', '1', '--filter=blob:none', '--branch', entry.ref, entry.repoUrl, dest],\n { stdio: 'inherit' },\n );\n }\n}\n\n/**\n * Iterate project entries and sync any that have a repo URL declared.\n * Entries without repoUrl are skipped silently.\n */\nexport async function syncProjects(entries: ProjectEntry[]): Promise<void> {\n for (const entry of entries) {\n if (!entry.repoUrl) continue;\n console.log(`Syncing project '${entry.id}' from ${entry.repoUrl}...`);\n await syncProject(entry);\n console.log(`Project '${entry.id}' synced.`);\n }\n}\n","import type { EvaluationResult, GraderResult } from './types.js';\n\n/**\n * Top-level fields to strip from baseline results.\n * Uses a denylist approach: new fields are auto-preserved.\n */\nconst STRIPPED_TOP_LEVEL_FIELDS = new Set([\n 'requests',\n 'trace',\n 'workspacePath',\n 'output',\n 'beforeAllOutput',\n 'beforeEachOutput',\n 'afterAllOutput',\n 'afterEachOutput',\n 'fileChanges',\n // Promoted execution metrics (debug, not needed for regression comparison)\n 'tokenUsage',\n 'costUsd',\n 'durationMs',\n 'startTime',\n 'endTime',\n]);\n\n/**\n * Fields to strip from grader results.\n */\nconst STRIPPED_EVALUATOR_FIELDS = new Set(['rawRequest', 'input']);\n\n/**\n * Trims an evaluator result for baseline storage.\n * Strips debug/audit fields while preserving scoring data.\n * Recursively trims nested grader results (for composites).\n */\nfunction trimEvaluatorResult(result: GraderResult): GraderResult {\n const trimmed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(result)) {\n if (STRIPPED_EVALUATOR_FIELDS.has(key)) continue;\n if (key === 'scores' && Array.isArray(value)) {\n trimmed[key] = (value as GraderResult[]).map(trimEvaluatorResult);\n } else {\n trimmed[key] = value;\n }\n }\n return trimmed as unknown as GraderResult;\n}\n\n/**\n * Trims an EvaluationResult for baseline storage.\n * Strips large debug/audit fields (denylist approach) while preserving\n * all fields needed for regression comparison (scores, assertions, etc.).\n *\n * Returns a new object — the input is not mutated.\n */\nexport function trimBaselineResult(result: EvaluationResult): EvaluationResult {\n const trimmed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(result)) {\n if (STRIPPED_TOP_LEVEL_FIELDS.has(key)) continue;\n if (key === 'scores' && Array.isArray(value)) {\n trimmed[key] = (value as GraderResult[]).map(trimEvaluatorResult);\n } else {\n trimmed[key] = value;\n }\n }\n return trimmed as unknown as EvaluationResult;\n}\n","/**\n * Tracks cumulative cost across all eval files in a single CLI run.\n *\n * The per-suite budget (`evaluate_options.budget_usd` in YAML) is enforced by the\n * orchestrator and caps spend within one eval file. This tracker provides a **run-level**\n * cap that spans all files in a single `agentv run` invocation.\n *\n * Usage:\n * 1. Instantiate with the cap from `--budget-usd`.\n * 2. Share the tracker with each orchestrator running in the invocation.\n * 3. After each completed case, call `add()` with that case's total cost.\n * 4. Before dispatching the next case or file, check `isExceeded()`.\n *\n * Thread-safety note: AgentV mutates this tracker from async orchestration code, but all\n * updates occur on the JavaScript event loop. There is no shared-memory mutation across\n * threads, so simple cumulative accounting is sufficient here.\n */\nexport class RunBudgetTracker {\n private cumulative = 0;\n\n constructor(private readonly capUsd: number) {}\n\n /** Accumulate cost from a completed test or file. */\n add(costUsd: number): void {\n this.cumulative += costUsd;\n }\n\n /** True when cumulative cost meets or exceeds the cap. */\n isExceeded(): boolean {\n return this.cumulative >= this.capUsd;\n }\n\n /** Current accumulated cost. */\n get currentCostUsd(): number {\n return this.cumulative;\n }\n\n /** The configured cap. */\n get budgetCapUsd(): number {\n return this.capUsd;\n }\n}\n","/**\n * Session hook execution for AgentV.\n *\n * Runs a shell command once at agentv startup and injects exported environment\n * variables into the current process. This lets projects fetch secrets at\n * runtime (e.g. from a vault) without needing a wrapper script.\n *\n * ## How it works\n *\n * 1. The command is run via `sh -c` (or `cmd /c` on Windows).\n * 2. stdout is captured and parsed for env var exports.\n * 3. stderr is forwarded to the process stderr so the user sees output.\n * 4. Non-zero exit aborts with a clear error.\n * 5. Parsed keys are injected into `process.env` — only for keys not already\n * set, so existing env always wins.\n *\n * ## Supported output formats\n *\n * Both shell-export and dotenv formats are accepted:\n * export KEY=\"value\" (shell export — quotes optional)\n * KEY=value (dotenv — no export prefix)\n *\n * Lines that don't match either pattern are silently ignored.\n *\n * @module\n */\n\nimport { spawnSync } from 'node:child_process';\n\n/**\n * Parse env var lines from hook stdout.\n *\n * Accepts:\n * export KEY=\"value\" → { KEY: \"value\" }\n * export KEY=value → { KEY: \"value\" }\n * KEY=value → { KEY: \"value\" }\n *\n * Strips surrounding single or double quotes from values.\n * Skips lines with empty keys or values that look like shell syntax.\n */\nexport function parseEnvOutput(stdout: string): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const line of stdout.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n // Match: [export ]KEY=value\n const match = trimmed.match(/^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);\n if (!match) continue;\n\n const key = match[1];\n let value = match[2];\n\n // Strip surrounding quotes (single or double)\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n if (key) {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Run the before_session hook command and inject exported env vars into process.env.\n *\n * - Runs via shell (`sh -c` on POSIX, `cmd /c` on Windows)\n * - Captured stdout is parsed for env vars; stderr is forwarded to process.stderr\n * - Non-zero exit throws an Error with the command and exit code\n * - Keys already set in process.env are NOT overwritten\n *\n * @param command Shell command string to execute\n */\nexport function runBeforeSessionHook(command: string): void {\n const isWindows = process.platform === 'win32';\n const shell = isWindows ? 'cmd' : 'sh';\n const shellFlag = isWindows ? '/c' : '-c';\n\n console.log(`Running before_session hook: ${command}`);\n\n const result = spawnSync(shell, [shellFlag, command], {\n encoding: 'utf8',\n // Do not inherit stdio — capture stdout for parsing, forward stderr manually\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n // Forward stderr so the user can see hook output (warnings, progress, etc.)\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n if (result.error) {\n throw new Error(`before_session hook failed to start: ${result.error.message}`);\n }\n\n if (result.status !== 0) {\n throw new Error(\n `before_session hook exited with code ${result.status ?? 'unknown'}: ${command}`,\n );\n }\n\n const vars = parseEnvOutput(result.stdout ?? '');\n let injected = 0;\n\n for (const [key, value] of Object.entries(vars)) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n injected++;\n }\n }\n\n if (injected > 0) {\n console.log(`before_session hook injected ${injected} environment variable(s).`);\n }\n}\n","/**\n * v5-native environment injection for AgentV project config.\n *\n * `env_path` loads dotenv-style files and `env_from` runs argv commands and\n * parses their stdout, both injecting into `process.env` before validation\n * and eval so target `{{ env.* }}` interpolation can see the values. This is\n * the replacement path for the deprecated `hooks.before_session`.\n *\n * Existing `process.env` values always win — neither source overwrites a key\n * that is already set. Values are never printed; only file paths, commands,\n * and counts are logged.\n *\n * @module\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { EnvFromEntry, EnvFromFormat } from './loaders/config-loader.js';\n\nconst ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Parse `KEY=value` / `export KEY=value` lines, shared by `env_path` dotenv\n * files and `env_from` `shell_exports` output. Quotes are stripped; blank\n * lines, comments, and non-matching lines are skipped.\n */\nexport function parseShellExportsEnv(content: string): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const match = trimmed.match(/^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);\n if (!match) continue;\n\n const key = match[1];\n let value = match[2];\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Parse a flat JSON object of string values for `env_from` `format: json`.\n * Throws on invalid JSON, non-object shapes, invalid env var names, or\n * non-string values.\n */\nexport function parseJsonEnv(content: string): Record<string, string> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n // Do not include the parser's message: JS engines embed a snippet of the\n // offending content in JSON syntax errors, which could leak a secret\n // value from malformed env_from output.\n throw new Error('invalid JSON');\n }\n\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('expected a flat JSON object of string values');\n }\n\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (!ENV_NAME_PATTERN.test(key)) {\n throw new Error(`invalid environment variable name \"${key}\"`);\n }\n if (typeof value !== 'string') {\n throw new Error(`value for \"${key}\" must be a string`);\n }\n result[key] = value;\n }\n\n return result;\n}\n\n/** Injects vars into process.env; existing keys and invalid names are skipped. Returns injected count. */\nfunction injectEnv(vars: Record<string, string>): number {\n let injected = 0;\n for (const [key, value] of Object.entries(vars)) {\n if (!ENV_NAME_PATTERN.test(key)) continue;\n if (process.env[key] === undefined) {\n process.env[key] = value;\n injected++;\n }\n }\n return injected;\n}\n\nexport type EnvPathLoadResult = {\n readonly loaded: readonly string[];\n readonly missing: readonly string[];\n readonly injectedCount: number;\n};\n\n/**\n * Load one or more dotenv-style files and inject their variables into\n * `process.env`. Relative paths resolve against `baseDir`. A missing file\n * warns and is skipped rather than failing the command.\n */\nexport async function loadEnvPathFiles(\n envPaths: readonly string[],\n baseDir: string,\n): Promise<EnvPathLoadResult> {\n const loaded: string[] = [];\n const missing: string[] = [];\n let injectedCount = 0;\n\n for (const envPath of envPaths) {\n const resolvedPath = path.isAbsolute(envPath) ? envPath : path.join(baseDir, envPath);\n\n let content: string;\n try {\n content = await readFile(resolvedPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n missing.push(resolvedPath);\n logWarning(`env_path file not found: ${resolvedPath}`);\n continue;\n }\n throw new Error(`Could not read env_path file ${resolvedPath}: ${(error as Error).message}`);\n }\n\n injectedCount += injectEnv(parseShellExportsEnv(content));\n loaded.push(resolvedPath);\n }\n\n if (injectedCount > 0) {\n console.log(\n `env_path injected ${injectedCount} environment variable(s) from ${loaded.length} file(s).`,\n );\n }\n\n return { loaded, missing, injectedCount };\n}\n\nexport type EnvFromRunResult = {\n readonly injectedCount: number;\n};\n\nfunction parseEnvFromOutput(stdout: string, format: EnvFromFormat): Record<string, string> {\n return format === 'json' ? parseJsonEnv(stdout) : parseShellExportsEnv(stdout);\n}\n\n/**\n * Run one or more `env_from` argv commands and inject their parsed stdout\n * into `process.env`. A non-zero exit, spawn failure, or unparseable output\n * throws — command failures must fail the invoking command. stdout is never\n * logged or included in error messages since it may carry secret values.\n */\nexport async function runEnvFromEntries(\n entries: readonly EnvFromEntry[],\n options: { readonly cwd: string },\n): Promise<EnvFromRunResult> {\n let injectedCount = 0;\n\n for (const entry of entries) {\n const [command, ...args] = entry.command;\n const commandLabel = entry.command.join(' ');\n console.log(`Running env_from command: ${commandLabel}`);\n\n const result = spawnSync(command, args, {\n cwd: options.cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n if (result.error) {\n throw new Error(`env_from command failed to start: ${commandLabel}: ${result.error.message}`);\n }\n if (result.status !== 0) {\n throw new Error(\n `env_from command exited with code ${result.status ?? 'unknown'}: ${commandLabel}`,\n );\n }\n\n const format = entry.format ?? 'shell_exports';\n let vars: Record<string, string>;\n try {\n vars = parseEnvFromOutput(result.stdout ?? '', format);\n } catch (error) {\n throw new Error(\n `env_from command produced invalid ${format} output: ${commandLabel}: ${(error as Error).message}`,\n );\n }\n\n injectedCount += injectEnv(vars);\n }\n\n if (injectedCount > 0) {\n console.log(`env_from injected ${injectedCount} environment variable(s).`);\n }\n\n return { injectedCount };\n}\n\nfunction logWarning(message: string): void {\n console.warn(`Warning: ${message}`);\n}\n","/**\n * Claude Code session JSONL parser.\n *\n * Reads a Claude Code session transcript (~/.claude/projects/<encoded-path>/<uuid>.jsonl)\n * and converts it to AgentV's Message[] format.\n *\n * Each line is a JSON object with:\n * { type, message: { role, content }, sessionId, timestamp, uuid, requestId, ... }\n *\n * Supported event types:\n * user → Message { role: 'user' } (also contains tool_result blocks)\n * assistant → Message { role: 'assistant', toolCalls from tool_use content blocks }\n *\n * Skipped event types: progress, system, file-history-snapshot\n *\n * Key behaviors:\n * - tool_use blocks in assistant events → ToolCall (pending output)\n * - tool_result blocks in user events → matched to pending tool_use by tool_use_id\n * - Usage is cumulative per requestId; only the last value per requestId is used\n * - Streaming assistant events with the same requestId are deduplicated (keep latest)\n * - Subagent events (isSidechain: true) are filtered out in v1\n * - Duration is from first↔last event timestamp (including skipped types)\n * - cost_usd is null (Claude Code does not report per-session cost)\n */\n\nimport { normalizeToolCall } from '../evaluation/providers/normalize-tool-call.js';\nimport type { Message, ToolCall } from '../evaluation/providers/types.js';\nimport type { TranscriptEntry, TranscriptSource } from './types.js';\n\ninterface ClaudeEvent {\n readonly type: string;\n readonly requestId?: string;\n readonly isSidechain?: boolean;\n readonly message?: {\n readonly role?: string;\n readonly content?: string | readonly ClaudeContentBlock[];\n readonly usage?: ClaudeUsage;\n readonly model?: string;\n };\n readonly sessionId?: string;\n readonly timestamp?: string;\n readonly uuid?: string;\n readonly cwd?: string;\n}\n\ninterface ClaudeContentBlock {\n readonly type: string;\n readonly text?: string;\n readonly thinking?: string;\n readonly name?: string;\n readonly input?: unknown;\n readonly id?: string;\n readonly tool_use_id?: string;\n readonly content?: string | readonly { readonly type: string; readonly text?: string }[];\n}\n\ninterface ClaudeUsage {\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n readonly cache_read_input_tokens?: number;\n}\n\nconst SKIPPED_TYPES = new Set(['progress', 'system', 'file-history-snapshot']);\n\nexport function parseClaudeSession(jsonl: string): TranscriptEntry {\n const messages: Message[] = [];\n let sessionId = '';\n let projectPath: string | undefined;\n let model: string | undefined;\n let startTimestamp: string | undefined;\n let endTimestamp: string | undefined;\n\n // Track usage per requestId — values are cumulative, so we only keep the last\n const usageByRequestId = new Map<string, ClaudeUsage>();\n\n // Track the last assistant message per requestId to deduplicate streaming updates\n let lastAssistantRequestId: string | undefined;\n let lastAssistantIdx = -1;\n\n // Track pending tool_use IDs for pairing with tool_result in user events\n const pendingToolCalls = new Map<string, { msgIdx: number; toolIdx: number }>();\n\n const lines = jsonl.split('\\n').filter((l) => l.trim().length > 0);\n\n for (const line of lines) {\n let event: ClaudeEvent;\n try {\n event = JSON.parse(line) as ClaudeEvent;\n } catch {\n continue;\n }\n\n if (!event.type) continue;\n\n // Track timestamps from ALL events (including skipped types) for accurate duration\n if (event.timestamp) {\n if (!startTimestamp) startTimestamp = event.timestamp;\n endTimestamp = event.timestamp;\n }\n\n // Skip non-message event types\n if (SKIPPED_TYPES.has(event.type)) continue;\n\n // Skip subagent events (v1: only process main conversation)\n if (event.isSidechain) continue;\n\n // Capture session metadata from first event\n if (!sessionId && event.sessionId) {\n sessionId = event.sessionId;\n }\n if (!projectPath && event.cwd) {\n projectPath = event.cwd;\n }\n\n switch (event.type) {\n case 'user': {\n const msg = event.message;\n if (!msg) break;\n\n const contentArr = msg.content;\n\n // User events can contain both tool_result blocks (responses to tool_use)\n // and text blocks. Process tool_results first, then extract text.\n if (Array.isArray(contentArr)) {\n for (const block of contentArr as readonly ClaudeContentBlock[]) {\n if (block.type === 'tool_result' && block.tool_use_id) {\n const pending = pendingToolCalls.get(block.tool_use_id);\n if (pending) {\n const existingMsg = messages[pending.msgIdx];\n const existingCalls = [...(existingMsg.toolCalls ?? [])];\n existingCalls[pending.toolIdx] = {\n ...existingCalls[pending.toolIdx],\n output: extractToolResultContent(block.content),\n };\n messages[pending.msgIdx] = { ...existingMsg, toolCalls: existingCalls };\n pendingToolCalls.delete(block.tool_use_id);\n }\n }\n }\n }\n\n // Extract text content for the user message\n const text = extractTextContent(contentArr);\n if (text !== undefined) {\n messages.push({ role: 'user', content: text });\n }\n break;\n }\n\n case 'assistant': {\n const msg = event.message;\n if (!msg) break;\n\n // Capture model from first assistant message\n if (!model && msg.model) {\n model = msg.model;\n }\n\n // Track usage (cumulative per requestId — last value wins)\n if (msg.usage && event.requestId) {\n usageByRequestId.set(event.requestId, msg.usage);\n }\n\n // Parse content array for text and tool_use blocks\n const { text, toolCalls } = extractAssistantContent(msg.content);\n\n // Deduplicate streaming assistant events with the same requestId\n if (\n event.requestId &&\n event.requestId === lastAssistantRequestId &&\n lastAssistantIdx >= 0\n ) {\n // Replace the previous partial message\n messages[lastAssistantIdx] = {\n role: 'assistant',\n content: text || undefined,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n };\n // Re-register tool calls for pairing\n registerPendingToolCalls(toolCalls, lastAssistantIdx, pendingToolCalls);\n } else {\n // Only push if there's actual content or tool calls\n if (text || toolCalls.length > 0) {\n lastAssistantIdx = messages.length;\n messages.push({\n role: 'assistant',\n content: text || undefined,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n });\n registerPendingToolCalls(toolCalls, lastAssistantIdx, pendingToolCalls);\n }\n }\n lastAssistantRequestId = event.requestId;\n break;\n }\n }\n }\n\n // Compute final usage from last-seen value per requestId\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n for (const usage of usageByRequestId.values()) {\n totalInputTokens += Number(usage.input_tokens ?? 0);\n totalOutputTokens += Number(usage.output_tokens ?? 0);\n }\n const hasUsage = usageByRequestId.size > 0;\n\n let durationMs: number | undefined;\n if (startTimestamp && endTimestamp) {\n durationMs = new Date(endTimestamp).getTime() - new Date(startTimestamp).getTime();\n }\n\n const source: TranscriptSource = {\n provider: 'claude-sdk',\n sessionId,\n projectPath,\n startedAt: startTimestamp,\n model,\n };\n\n return {\n messages,\n source,\n tokenUsage: hasUsage ? { input: totalInputTokens, output: totalOutputTokens } : undefined,\n durationMs,\n costUsd: null,\n };\n}\n\n/**\n * Register tool_use IDs from an assistant message for later pairing with tool_result.\n */\nfunction registerPendingToolCalls(\n toolCalls: ToolCall[],\n msgIdx: number,\n pending: Map<string, { msgIdx: number; toolIdx: number }>,\n): void {\n for (let i = 0; i < toolCalls.length; i++) {\n const id = toolCalls[i].id;\n if (id) {\n pending.set(id, { msgIdx, toolIdx: i });\n }\n }\n}\n\n/**\n * Extract text content from a message's content field.\n */\nfunction extractTextContent(\n content: string | readonly ClaudeContentBlock[] | undefined,\n): string | undefined {\n if (content === undefined || content === null) return undefined;\n if (typeof content === 'string') return content;\n\n const textParts: string[] = [];\n for (const block of content) {\n if (block.type === 'text' && block.text) {\n textParts.push(block.text);\n }\n }\n return textParts.length > 0 ? textParts.join('') : undefined;\n}\n\n/**\n * Extract text and tool_use calls from an assistant message's content array.\n * Note: tool_result blocks appear in user events, not here.\n */\nfunction extractAssistantContent(content: string | readonly ClaudeContentBlock[] | undefined): {\n text: string | undefined;\n toolCalls: ToolCall[];\n} {\n if (content === undefined || content === null) {\n return { text: undefined, toolCalls: [] };\n }\n if (typeof content === 'string') {\n return { text: content, toolCalls: [] };\n }\n\n const textParts: string[] = [];\n const toolCalls: ToolCall[] = [];\n\n for (const block of content) {\n switch (block.type) {\n case 'text':\n if (block.text) textParts.push(block.text);\n break;\n\n case 'tool_use':\n if (block.name) {\n toolCalls.push(\n normalizeToolCall('claude-sdk', {\n tool: block.name,\n input: block.input,\n id: block.id,\n }),\n );\n }\n break;\n\n // Skip thinking blocks and other types\n }\n }\n\n return {\n text: textParts.length > 0 ? textParts.join('') : undefined,\n toolCalls,\n };\n}\n\n/**\n * Extract text from a tool_result content field.\n */\nfunction extractToolResultContent(\n content: string | readonly { readonly type: string; readonly text?: string }[] | undefined,\n): string | undefined {\n if (content === undefined || content === null) return undefined;\n if (typeof content === 'string') return content;\n\n const parts: string[] = [];\n for (const block of content) {\n if (block.type === 'text' && block.text) {\n parts.push(block.text);\n }\n }\n return parts.length > 0 ? parts.join('') : undefined;\n}\n","/**\n * Codex CLI session JSONL parser.\n *\n * Reads a Codex CLI rollout transcript\n * (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl) and converts it to AgentV's\n * Message[] format.\n *\n * Each line is a JSON object with one of these top-level types:\n * session_meta → session metadata (id, cwd, cli_version, model)\n * turn_context → per-turn context (model, cwd, turn_id)\n * event_msg → events: task_started, task_complete, user_message,\n * agent_message, token_count\n * response_item → conversation items: message, function_call,\n * function_call_output, reasoning, custom_tool_call,\n * custom_tool_call_output\n *\n * Key behaviors:\n * - response_item with type=message and role=user → user Message\n * - response_item with type=message and role=assistant → assistant Message\n * - response_item with type=function_call → ToolCall (pending output)\n * - response_item with type=function_call_output → matched to pending call by call_id\n * - response_item with type=reasoning → skipped (thinking tokens)\n * - response_item with role=developer → skipped (system prompt)\n * - session_meta → source metadata (session_id, cwd, version, model)\n * - turn_context → model name extraction\n * - Duration is from first↔last event timestamp\n * - cost_usd is null (Codex CLI does not report per-session cost)\n * - Token usage not available from rollout format (rate limit info only)\n *\n * To add a new response_item type: add a case to the switch in parseCodexSession().\n */\n\nimport { normalizeToolCall } from '../evaluation/providers/normalize-tool-call.js';\nimport type { Message, ToolCall } from '../evaluation/providers/types.js';\nimport type { TranscriptEntry, TranscriptSource } from './types.js';\n\ninterface CodexLine {\n readonly timestamp?: string;\n readonly type: string;\n readonly payload: Record<string, unknown>;\n}\n\nexport function parseCodexSession(jsonl: string): TranscriptEntry {\n const messages: Message[] = [];\n let sessionId = '';\n let cwd: string | undefined;\n let model: string | undefined;\n let version: string | undefined;\n let startTimestamp: string | undefined;\n let endTimestamp: string | undefined;\n\n // Track pending function calls by call_id\n const pendingCalls = new Map<string, { msgIdx: number; toolIdx: number }>();\n\n const lines = jsonl.split('\\n').filter((l) => l.trim().length > 0);\n\n for (const line of lines) {\n let entry: CodexLine;\n try {\n entry = JSON.parse(line) as CodexLine;\n } catch {\n continue;\n }\n\n if (!entry.type) continue;\n\n // Track timestamps for duration\n if (entry.timestamp) {\n if (!startTimestamp) startTimestamp = entry.timestamp;\n endTimestamp = entry.timestamp;\n }\n\n const payload = entry.payload ?? {};\n\n switch (entry.type) {\n case 'session_meta': {\n sessionId = String(payload.id ?? '');\n cwd = payload.cwd ? String(payload.cwd) : undefined;\n version = payload.cli_version ? String(payload.cli_version) : undefined;\n if (payload.model && !model) {\n model = String(payload.model);\n }\n break;\n }\n\n case 'turn_context': {\n if (payload.model && !model) {\n model = String(payload.model);\n }\n if (payload.cwd && !cwd) {\n cwd = String(payload.cwd);\n }\n break;\n }\n\n case 'response_item': {\n const itemType = String(payload.type ?? '');\n const role = String(payload.role ?? '');\n\n switch (itemType) {\n case 'message': {\n // Skip developer (system prompt) messages\n if (role === 'developer') break;\n\n const content = extractResponseItemContent(payload.content);\n if (role === 'user' && content) {\n messages.push({ role: 'user', content });\n } else if (role === 'assistant' && content) {\n messages.push({ role: 'assistant', content });\n }\n break;\n }\n\n case 'function_call': {\n const toolName = String(payload.name ?? '');\n const callId = String(payload.call_id ?? '');\n let input: unknown;\n if (typeof payload.arguments === 'string') {\n try {\n input = JSON.parse(payload.arguments);\n } catch {\n input = payload.arguments;\n }\n } else {\n input = payload.arguments;\n }\n\n const toolCall: ToolCall = normalizeToolCall('codex-cli', {\n tool: toolName,\n input,\n id: callId,\n });\n const msgIdx = messages.length;\n messages.push({\n role: 'assistant',\n toolCalls: [toolCall],\n });\n\n if (callId) {\n pendingCalls.set(callId, { msgIdx, toolIdx: 0 });\n }\n break;\n }\n\n case 'custom_tool_call': {\n const toolName = String(payload.name ?? '');\n const callId = String(payload.call_id ?? '');\n let input: unknown;\n if (typeof payload.arguments === 'string') {\n try {\n input = JSON.parse(payload.arguments);\n } catch {\n input = payload.arguments;\n }\n } else {\n input = payload.arguments;\n }\n\n const toolCall: ToolCall = normalizeToolCall('codex-cli', {\n tool: toolName,\n input,\n id: callId,\n });\n const msgIdx = messages.length;\n messages.push({\n role: 'assistant',\n toolCalls: [toolCall],\n });\n\n if (callId) {\n pendingCalls.set(callId, { msgIdx, toolIdx: 0 });\n }\n break;\n }\n\n case 'function_call_output':\n case 'custom_tool_call_output': {\n const callId = String(payload.call_id ?? '');\n const pending = pendingCalls.get(callId);\n if (pending) {\n const existingMsg = messages[pending.msgIdx];\n const existingCalls = [...(existingMsg.toolCalls ?? [])];\n existingCalls[pending.toolIdx] = {\n ...existingCalls[pending.toolIdx],\n output: payload.output,\n };\n messages[pending.msgIdx] = { ...existingMsg, toolCalls: existingCalls };\n pendingCalls.delete(callId);\n }\n break;\n }\n\n // Skip reasoning blocks (thinking tokens)\n case 'reasoning':\n break;\n }\n break;\n }\n\n // Skip event_msg types (task_started, task_complete, token_count, etc.)\n // They don't contain conversation content\n }\n }\n\n let durationMs: number | undefined;\n if (startTimestamp && endTimestamp) {\n durationMs = new Date(endTimestamp).getTime() - new Date(startTimestamp).getTime();\n }\n\n const source: TranscriptSource = {\n provider: 'codex',\n sessionId,\n cwd,\n startedAt: startTimestamp,\n model,\n version,\n };\n\n return {\n messages,\n source,\n // Codex rollout files don't include token counts (only rate limit info)\n tokenUsage: undefined,\n durationMs,\n costUsd: null,\n };\n}\n\n/**\n * Extract text content from a Codex response_item content array.\n * Content is typically: [{ type: \"input_text\"|\"output_text\", text: \"...\" }]\n */\nfunction extractResponseItemContent(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return undefined;\n\n const parts: string[] = [];\n for (const block of content) {\n if (typeof block === 'object' && block !== null) {\n const b = block as Record<string, unknown>;\n if (typeof b.text === 'string') {\n parts.push(b.text);\n }\n }\n }\n return parts.length > 0 ? parts.join('') : undefined;\n}\n","/**\n * Codex CLI session discovery.\n *\n * Scans ~/.codex/sessions/ for rollout JSONL files. Codex CLI stores sessions at:\n * ~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<uuid>.jsonl\n *\n * Sessions are returned sorted by modification time (most recent first).\n */\n\nimport { readdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport path from 'node:path';\n\nexport interface CodexSession {\n /** UUID from the filename */\n readonly sessionId: string;\n /** Full path to the JSONL file */\n readonly filePath: string;\n /** Filename (e.g., rollout-2026-03-29T14-22-01-<uuid>.jsonl) */\n readonly filename: string;\n /** Last modification time */\n readonly updatedAt: Date;\n}\n\nexport interface CodexDiscoverOptions {\n /** Filter by date string (YYYY-MM-DD). */\n readonly date?: string;\n /** Maximum number of sessions to return (default: 10). */\n readonly limit?: number;\n /** Override the default ~/.codex/sessions directory. */\n readonly sessionsDir?: string;\n /** Return only the most recent session. */\n readonly latest?: boolean;\n}\n\nconst DEFAULT_SESSIONS_DIR = () => path.join(homedir(), '.codex', 'sessions');\n\nexport async function discoverCodexSessions(opts?: CodexDiscoverOptions): Promise<CodexSession[]> {\n const sessionsDir = opts?.sessionsDir ?? DEFAULT_SESSIONS_DIR();\n const limit = opts?.latest ? 1 : (opts?.limit ?? 10);\n\n const sessions: CodexSession[] = [];\n\n // Walk YYYY/MM/DD directory structure\n let yearDirs: string[];\n try {\n yearDirs = await readdir(sessionsDir);\n } catch {\n return [];\n }\n\n for (const year of yearDirs) {\n const yearPath = path.join(sessionsDir, year);\n let monthDirs: string[];\n try {\n monthDirs = await readdir(yearPath);\n } catch {\n continue;\n }\n\n for (const month of monthDirs) {\n const monthPath = path.join(yearPath, month);\n let dayDirs: string[];\n try {\n dayDirs = await readdir(monthPath);\n } catch {\n continue;\n }\n\n for (const day of dayDirs) {\n // Filter by date if specified\n if (opts?.date) {\n const dirDate = `${year}-${month}-${day}`;\n if (dirDate !== opts.date) continue;\n }\n\n const dayPath = path.join(monthPath, day);\n let files: string[];\n try {\n files = await readdir(dayPath);\n } catch {\n continue;\n }\n\n for (const file of files) {\n if (!file.startsWith('rollout-') || !file.endsWith('.jsonl')) continue;\n\n const filePath = path.join(dayPath, file);\n\n // Extract UUID from filename: rollout-<timestamp>-<uuid>.jsonl\n // UUID is the last segment before .jsonl\n const nameWithoutExt = file.replace(/\\.jsonl$/, '');\n const parts = nameWithoutExt.split('-');\n // UUID is typically the last 5 hyphen-separated segments (standard UUID format)\n const sessionId = parts.length >= 6 ? parts.slice(-5).join('-') : nameWithoutExt;\n\n let updatedAt: Date;\n try {\n const fileStat = await stat(filePath);\n updatedAt = fileStat.mtime;\n } catch {\n updatedAt = new Date(0);\n }\n\n sessions.push({ sessionId, filePath, filename: file, updatedAt });\n }\n }\n }\n }\n\n sessions.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n return sessions.slice(0, limit);\n}\n","/**\n * Claude Code session discovery.\n *\n * Scans ~/.claude/projects/ for session JSONL files. Claude Code stores\n * sessions at:\n * ~/.claude/projects/<encoded-project-path>/<uuid>.jsonl\n *\n * Where <encoded-project-path> is the absolute project path with `/` replaced\n * by `-` and prefixed with `-` (e.g., `-home-user-myproject`).\n *\n * Sessions are returned sorted by modification time (most recent first).\n */\n\nimport { readdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport path from 'node:path';\n\nexport interface ClaudeSession {\n /** UUID of the session */\n readonly sessionId: string;\n /** Full path to the JSONL file */\n readonly filePath: string;\n /** Encoded project directory name */\n readonly projectDir: string;\n /** Last modification time */\n readonly updatedAt: Date;\n}\n\nexport interface ClaudeDiscoverOptions {\n /** Filter by session UUID (exact match). */\n readonly sessionId?: string;\n /** Filter by project path (substring match against encoded dir name). */\n readonly projectPath?: string;\n /** Maximum number of sessions to return (default: 10). */\n readonly limit?: number;\n /** Override the default ~/.claude/projects directory. */\n readonly projectsDir?: string;\n /** Return only the most recent session. */\n readonly latest?: boolean;\n}\n\nconst DEFAULT_PROJECTS_DIR = () => path.join(homedir(), '.claude', 'projects');\n\n/**\n * Encode a filesystem path to Claude Code's project directory format.\n * `/home/user/myproject` → `-home-user-myproject`\n */\nfunction encodeProjectPath(projectPath: string): string {\n return projectPath.replace(/\\//g, '-');\n}\n\nexport async function discoverClaudeSessions(\n opts?: ClaudeDiscoverOptions,\n): Promise<ClaudeSession[]> {\n const projectsDir = opts?.projectsDir ?? DEFAULT_PROJECTS_DIR();\n const limit = opts?.latest ? 1 : (opts?.limit ?? 10);\n\n let projectDirs: string[];\n try {\n projectDirs = await readdir(projectsDir);\n } catch {\n return [];\n }\n\n // Filter project directories if projectPath is specified\n if (opts?.projectPath) {\n const encoded = encodeProjectPath(opts.projectPath);\n projectDirs = projectDirs.filter((dir) => dir === encoded || dir.includes(encoded));\n }\n\n const sessions: ClaudeSession[] = [];\n\n for (const projectDir of projectDirs) {\n const dirPath = path.join(projectsDir, projectDir);\n\n let entries: string[];\n try {\n entries = await readdir(dirPath);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n if (!entry.endsWith('.jsonl')) continue;\n\n const sessionId = entry.replace(/\\.jsonl$/, '');\n\n // Filter by session ID if specified\n if (opts?.sessionId && sessionId !== opts.sessionId) continue;\n\n const filePath = path.join(dirPath, entry);\n\n let updatedAt: Date;\n try {\n const fileStat = await stat(filePath);\n updatedAt = fileStat.mtime;\n } catch {\n updatedAt = new Date(0);\n }\n\n sessions.push({\n sessionId,\n filePath,\n projectDir,\n updatedAt,\n });\n }\n }\n\n // Sort by modification time, most recent first\n sessions.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n\n return sessions.slice(0, limit);\n}\n","/**\n * Transcript provider — replays pre-recorded session transcripts through the\n * evaluation pipeline without invoking any live agent.\n *\n * Used by `agentv eval --transcript <file>` to grade imported sessions.\n *\n * How it works:\n * 1. Reads a transcript JSONL file (produced by `agentv import`)\n * 2. Each eval invocation resolves a transcript by matching `evalCaseId`\n * to transcript `test_id`\n * 3. Returns a ProviderResponse with pre-populated output, token usage, etc.\n * 4. Graders run identically to live eval — they see the same ProviderResponse\n *\n * The provider name in results is set to the source provider from the transcript\n * (e.g., \"claude\", \"codex\", \"copilot\").\n */\n\nimport type { Provider, ProviderRequest, ProviderResponse } from '../evaluation/providers/types.js';\nimport type { TranscriptReplayEntry } from './types.js';\nimport { groupTranscriptJsonLines, readTranscriptJsonl } from './types.js';\n\nexport class TranscriptProvider implements Provider {\n readonly id: string;\n readonly kind = 'transcript' as const;\n readonly targetName: string;\n\n private entries: TranscriptReplayEntry[];\n private entriesByTestId: Map<string, TranscriptReplayEntry>;\n private cursor = 0;\n\n constructor(targetName: string, entries: TranscriptReplayEntry[]) {\n this.targetName = targetName;\n this.id = `transcript:${targetName}`;\n this.entries = entries;\n this.entriesByTestId = new Map(entries.map((entry) => [entry.testId, entry]));\n }\n\n /**\n * Create a TranscriptProvider from a JSONL file path.\n */\n static async fromFile(filePath: string): Promise<TranscriptProvider> {\n const lines = await readTranscriptJsonl(filePath);\n if (lines.length === 0) {\n throw new Error(`Transcript file is empty: ${filePath}`);\n }\n const entries = groupTranscriptJsonLines(lines);\n const providerName = entries[0]?.source.provider ?? 'transcript';\n return new TranscriptProvider(providerName, entries);\n }\n\n get lineCount(): number {\n return this.entries.length;\n }\n\n get testIds(): readonly string[] {\n return this.entries.map((entry) => entry.testId);\n }\n\n async invoke(request: ProviderRequest): Promise<ProviderResponse> {\n const entry = request.evalCaseId\n ? this.entryForTestId(request.evalCaseId)\n : this.nextPositionalEntry();\n\n return {\n output: entry.messages,\n tokenUsage: entry.tokenUsage\n ? {\n input: entry.tokenUsage.input,\n output: entry.tokenUsage.output,\n cached: entry.tokenUsage.cached,\n reasoning: entry.tokenUsage.reasoning,\n }\n : undefined,\n durationMs: entry.durationMs,\n costUsd: entry.costUsd ?? undefined,\n startTime: entry.source.startedAt,\n };\n }\n\n private entryForTestId(testId: string): TranscriptReplayEntry {\n const entry = this.entriesByTestId.get(testId);\n if (entry) {\n return entry;\n }\n throw new Error(\n `Transcript replay found no entry for test_id=${testId}. Available test_id values: ${this.testIds.join(', ') || '<none>'}`,\n );\n }\n\n private nextPositionalEntry(): TranscriptReplayEntry {\n if (this.cursor >= this.entries.length) {\n throw new Error(\n `Transcript exhausted: ${this.entries.length} entr${this.entries.length === 1 ? 'y' : 'ies'} available but ` +\n `${this.cursor + 1} invocations attempted. Each transcript entry maps to one test case.`,\n );\n }\n\n return this.entries[this.cursor++];\n }\n}\n","/**\n * Copilot CLI events.jsonl parser.\n *\n * Reads a Copilot CLI session transcript (events.jsonl) and converts it to\n * AgentV's Message[] format. Each line is a JSON object with:\n * { type, data: { ...payload }, id, timestamp, parentId }\n *\n * All event-specific fields live under event.data.*, while type, id, timestamp,\n * and parentId are at the top level.\n *\n * Supported event types:\n * session.start → session metadata (data.sessionId, data.context.cwd)\n * user.message → Message { role: 'user' }\n * assistant.message → Message { role: 'assistant', toolCalls from data.toolRequests }\n * skill.invoked → ToolCall { tool: 'Skill', input: { skill: data.name } }\n * tool.execution_start + tool.execution_complete → ToolCall with output\n * session.shutdown → token usage from data.modelMetrics, end timestamp\n *\n * To add a new event type:\n * 1. Add a case to the switch in parseCopilotEvents()\n * 2. Map it to a Message or ToolCall\n * 3. Add a test in copilot-log-parser.test.ts\n */\n\nimport { normalizeToolCall } from './normalize-tool-call.js';\nimport type { Message, ProviderTokenUsage, ToolCall } from './types.js';\n\nexport interface CopilotSessionMeta {\n readonly sessionId: string;\n readonly model: string;\n readonly cwd: string;\n readonly repository?: string;\n readonly branch?: string;\n readonly startedAt?: string;\n}\n\nexport interface ParsedCopilotSession {\n readonly messages: Message[];\n readonly meta: CopilotSessionMeta;\n readonly tokenUsage?: ProviderTokenUsage;\n readonly durationMs?: number;\n}\n\ninterface ToolCallInProgress {\n readonly toolName: string;\n readonly input?: unknown;\n readonly toolCallId: string;\n}\n\nexport function parseCopilotEvents(eventsJsonl: string): ParsedCopilotSession {\n const messages: Message[] = [];\n const meta: {\n sessionId: string;\n model: string;\n cwd: string;\n repository?: string;\n branch?: string;\n startedAt?: string;\n } = { sessionId: '', model: '', cwd: '' };\n\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let hasUsage = false;\n let startTimestamp: string | undefined;\n let endTimestamp: string | undefined;\n\n const toolCallsInProgress = new Map<string, ToolCallInProgress>();\n\n const lines = eventsJsonl.split('\\n').filter((l) => l.trim().length > 0);\n\n for (const line of lines) {\n let event: Record<string, unknown>;\n try {\n event = JSON.parse(line);\n } catch {\n continue;\n }\n\n const eventType = event.type as string | undefined;\n if (!eventType) continue;\n\n // All event payloads are nested under event.data\n const data = (event.data ?? {}) as Record<string, unknown>;\n\n switch (eventType) {\n case 'session.start': {\n meta.sessionId = String(data.sessionId ?? '');\n const ctx = data.context as Record<string, unknown> | undefined;\n meta.cwd = String(ctx?.cwd ?? '');\n meta.repository = ctx?.repository ? String(ctx.repository) : undefined;\n meta.branch = ctx?.branch ? String(ctx.branch) : undefined;\n // timestamp is at event top level; startTime is in data\n const ts = event.timestamp ?? data.startTime;\n meta.startedAt = ts ? String(ts) : undefined;\n startTimestamp = ts ? String(ts) : undefined;\n break;\n }\n\n case 'user.message': {\n messages.push({\n role: 'user',\n content: data.content != null ? String(data.content) : '',\n });\n break;\n }\n\n case 'assistant.message': {\n const toolRequests = data.toolRequests as readonly Record<string, unknown>[] | undefined;\n\n const toolCalls: ToolCall[] = (toolRequests ?? []).map((req) =>\n normalizeToolCall('copilot-events', {\n tool: String(req.name ?? req.toolName ?? ''),\n input: req.arguments,\n id: req.toolCallId ? String(req.toolCallId) : undefined,\n }),\n );\n\n messages.push({\n role: 'assistant',\n content: data.content != null ? String(data.content) : undefined,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n });\n break;\n }\n\n case 'skill.invoked': {\n const skillName = String(data.name ?? '');\n messages.push({\n role: 'assistant',\n toolCalls: [\n {\n tool: 'Skill',\n input: { skill: skillName },\n },\n ],\n });\n break;\n }\n\n case 'tool.execution_start': {\n const toolCallId = String(data.toolCallId ?? '');\n if (toolCallId) {\n toolCallsInProgress.set(toolCallId, {\n toolName: String(data.toolName ?? ''),\n input: data.arguments,\n toolCallId,\n });\n }\n break;\n }\n\n case 'tool.execution_complete': {\n const toolCallId = String(data.toolCallId ?? '');\n const started = toolCallsInProgress.get(toolCallId);\n // Orphaned completes (no matching start) are silently dropped —\n // orphaned starts (session crashed mid-tool) are also discarded\n // since incomplete tool calls provide no useful evaluation signal.\n if (started) {\n toolCallsInProgress.delete(toolCallId);\n messages.push({\n role: 'assistant',\n toolCalls: [\n normalizeToolCall('copilot-events', {\n tool: started.toolName,\n input: started.input,\n output: data.result,\n id: toolCallId,\n }),\n ],\n });\n }\n break;\n }\n\n case 'session.shutdown': {\n endTimestamp = event.timestamp ? String(event.timestamp) : undefined;\n\n // Extract token usage from modelMetrics\n const modelMetrics = data.modelMetrics as\n | Record<string, { usage?: { inputTokens?: number; outputTokens?: number } }>\n | undefined;\n if (modelMetrics) {\n for (const metrics of Object.values(modelMetrics)) {\n if (metrics.usage) {\n hasUsage = true;\n totalInputTokens += Number(metrics.usage.inputTokens ?? 0);\n totalOutputTokens += Number(metrics.usage.outputTokens ?? 0);\n }\n }\n }\n\n // Extract model name from currentModel\n const currentModel = data.currentModel;\n if (currentModel && !meta.model) {\n meta.model = String(currentModel);\n }\n break;\n }\n }\n }\n\n let durationMs: number | undefined;\n if (startTimestamp && endTimestamp) {\n durationMs = new Date(endTimestamp).getTime() - new Date(startTimestamp).getTime();\n }\n\n return {\n messages,\n meta,\n tokenUsage: hasUsage ? { input: totalInputTokens, output: totalOutputTokens } : undefined,\n durationMs,\n };\n}\n","export * from './evaluation/content.js';\nexport * from './evaluation/types.js';\nexport * from './evaluation/trace.js';\nexport * from './evaluation/trace-envelope.js';\nexport * from './evaluation/metrics.js';\nexport * from './evaluation/transcript-summary.js';\nexport * from './evaluation/dashboard-trace-read-model.js';\nexport * from './evaluation/trace-normalization.js';\nexport * from './evaluation/external-trace.js';\nexport * from './evaluation/projection-identity.js';\nexport * from './evaluation/replay-fixtures.js';\nexport * from './evaluation/replay-trace-envelopes.js';\nexport * from './evaluation/replay-transcripts.js';\nexport {\n ResultRowSchemaError,\n normalizeResultRow,\n} from './evaluation/result-row-schema.js';\nexport * from './evaluation/result-artifact-contract.js';\nexport { parseYamlValue } from './evaluation/yaml-loader.js';\nexport * from './evaluation/experiment.js';\nexport * from './evaluation/yaml-parser.js';\nexport {\n loadConfig,\n resolveResultsConfigForProject,\n type AgentVConfig as AgentVYamlConfig,\n type ResultsConfig,\n type HooksConfig,\n type EnvFromEntry,\n type EnvFromFormat,\n} from './evaluation/loaders/config-loader.js';\nexport {\n isTypeScriptEvalConfigFileName,\n loadTsEvalFile,\n typeScriptEvalConfigGlob,\n type TsEvalResult,\n} from './evaluation/loaders/ts-eval-loader.js';\nexport type {\n DockerEnvironmentRecipe,\n EnvironmentRecipe,\n HostEnvironmentRecipe,\n} from './evaluation/loaders/environment-recipe.js';\nexport {\n transpileEvalYaml,\n transpileEvalYamlFile,\n getOutputFilenames,\n} from './evaluation/loaders/eval-yaml-transpiler.js';\nexport type {\n EvalsJsonCase,\n EvalsJsonFile,\n TranspileResult,\n} from './evaluation/loaders/eval-yaml-transpiler.js';\nexport * from './evaluation/file-utils.js';\nexport * from './evaluation/providers/index.js';\nexport * from './evaluation/graders.js';\nexport * from './evaluation/orchestrator.js';\nexport * from './evaluation/prepared-workspace.js';\nexport {\n evaluate,\n type AssertEntry,\n type ConversationTurnInput,\n type EvalConfig,\n type EvalRunArtifacts,\n type EvalTestInput,\n type EvalAssertionInput,\n type EvalRunResult,\n type EvalSummary,\n} from './evaluation/evaluate.js';\nexport {\n RESULT_INDEX_FILENAME,\n RUN_CONFIG_FILENAME,\n RUN_SUMMARY_FILENAME,\n aggregateRunDir,\n buildAggregateGradingArtifact,\n buildRunSummaryArtifact,\n buildEvalTestTargetKey,\n buildEvaluationResultTargetKey,\n buildGradingArtifact,\n buildIndexArtifactEntry,\n buildResultIndexArtifact,\n buildTestTargetKey,\n buildTimingArtifact,\n deduplicateByTestIdTarget,\n parseJsonlResults,\n readRunConfigArtifact,\n writeArtifacts,\n writeArtifactsFromResults,\n writeInitialRunSummaryArtifact,\n writePerTestArtifacts,\n type AdditionalResultArtifactsContext,\n type AdditionalResultArtifactsWriter,\n type AdditionalResultIndexFields,\n type AggregateGradingArtifact,\n type GradingArtifact,\n type IndexArtifactEntry,\n type EnvironmentSummaryWire,\n type ResultIndexArtifact,\n type RunRuntimeConfigSource,\n type RunRuntimeSourceMetadata,\n type RunConfigArtifact,\n type RunSummaryArtifact,\n type TimingArtifact,\n} from './evaluation/run-artifacts.js';\nexport type {\n AssertContext,\n AssertFn,\n AssertResult,\n} from './evaluation/assertions.js';\nexport {\n defineConfig,\n loadTsConfig,\n type AgentVConfig as AgentVTsConfig,\n} from './evaluation/config.js';\nexport * from './evaluation/generators/index.js';\nexport * from './evaluation/workspace/index.js';\nexport {\n ResponseCache,\n shouldEnableCache,\n shouldSkipCacheForTemperature,\n} from './evaluation/cache/response-cache.js';\nexport {\n EvaluationResultBoundarySchema,\n TraceBoundarySchema,\n TraceSummaryBoundarySchema,\n parseEvaluationResultBoundary,\n parseTraceBoundary,\n parseTraceSummaryBoundary,\n serializeEvaluationResultWire,\n serializeSnakeCaseBoundaryPayload,\n serializeTraceSummaryWire,\n serializeTraceWire,\n toCamelCaseDeep,\n toSnakeCaseDeep,\n type EvaluationResultWire,\n type TraceSummaryWire,\n type TraceWire,\n} from './evaluation/case-conversion.js';\nexport {\n ensureResultsRepoClone,\n syncResultsRepo,\n syncResultsRepoForProject,\n confirmResultsMergeAndPull,\n buildResultsCompareUrl,\n getResultsRepoLocalPaths,\n getResultsRepoStatus,\n getResultsRepoSyncStatus,\n normalizeResultsConfig,\n resolveResultsRepoRunsDir,\n resolveResultsRepoUrl,\n prepareResultsRepoBranch,\n checkoutResultsRepoBranch,\n stageResultsArtifacts,\n directorySizeBytes,\n commitAndPushResultsBranch,\n pushResultsRepoBranch,\n createDraftResultsPr,\n directPushResults,\n directPushResultsWithDetails,\n buildWipBranchName,\n setupWipWorktree,\n pushWipCheckpoint,\n deleteWipBranch,\n listGitRuns,\n listGitRunsCached,\n resolveGitResultsIndexCacheFile,\n resolveGitRunsRefCommit,\n materializeGitRun,\n readGitResultArtifact,\n type CheckedOutResultsRepoBranch,\n type DirectPushResultsResult,\n type GitResultArtifactReadParams,\n type GitListedRun,\n type NormalizedResultsConfig,\n type RuntimeResultsConfig,\n type PreparedResultsRepoBranch,\n type ResultPushConflictPolicy,\n type ResultsRepoLocalPaths,\n type ResultsRepoSyncStatus,\n type ResultsRepoStatus,\n type ResultsPendingMerge,\n type PendingMergeDetails,\n type WipWorktreeHandle,\n} from './evaluation/results-repo.js';\nexport {\n AGENTV_CONFIG_FILE_NAME,\n AGENTV_CONFIG_YML_FILE_NAME,\n AGENTV_LOCAL_CONFIG_FILE_NAME,\n AGENTV_LOCAL_CONFIG_YML_FILE_NAME,\n getLocalConfigPath,\n isAgentVConfigFileName,\n isPlainConfigObject,\n mergeConfigObjects,\n} from './config-overlays.js';\nexport {\n getAgentvConfigDir,\n getAgentvDataDir,\n getWorkspacesRoot,\n getSubagentsRoot,\n getTraceStateRoot,\n} from './paths.js';\nexport {\n type ProjectEntry,\n type ProjectRegistry,\n loadProjectRegistry,\n saveProjectRegistry,\n addProject,\n removeProject,\n getProject,\n getProjectForPath,\n touchProject,\n discoverProjects,\n deriveProjectId,\n getProjectsRegistryPath,\n} from './projects.js';\nexport { syncProject, syncProjects } from './project-sync.js';\nexport { trimBaselineResult } from './evaluation/baseline.js';\nexport { DEFAULT_CATEGORY, deriveCategory, normalizeCategoryPath } from './evaluation/category.js';\n\n// Registry exports\nexport {\n GraderRegistry,\n DeterministicAssertionGrader,\n} from './evaluation/registry/grader-registry.js';\nexport type {\n GraderDispatchContext,\n GraderFactoryFn,\n} from './evaluation/registry/grader-registry.js';\nexport { createBuiltinRegistry } from './evaluation/registry/builtin-graders.js';\nexport { discoverAssertions } from './evaluation/registry/assertion-discovery.js';\nexport {\n runContainsAssertion,\n runContainsAnyAssertion,\n runContainsAllAssertion,\n runIcontainsAssertion,\n runIcontainsAnyAssertion,\n runIcontainsAllAssertion,\n runStartsWithAssertion,\n runEndsWithAssertion,\n runRegexAssertion,\n runIsJsonAssertion,\n runEqualsAssertion,\n type AssertionResult,\n} from './evaluation/graders/assertions.js';\nexport { discoverGraders } from './evaluation/registry/grader-discovery.js';\nexport { RunBudgetTracker } from './evaluation/run-budget-tracker.js';\nexport { runBeforeSessionHook, parseEnvOutput } from './evaluation/hooks.js';\nexport {\n loadEnvPathFiles,\n runEnvFromEntries,\n parseShellExportsEnv,\n parseJsonEnv,\n type EnvPathLoadResult,\n type EnvFromRunResult,\n} from './evaluation/env-injection.js';\nexport {\n trackChild,\n killAllTrackedChildren,\n trackedChildCount,\n} from './runtime/child-tracker.js';\n\n// Import pipeline\nexport * from './import/index.js';\n\nexport type AgentKernel = {\n status: string;\n};\n\nexport function createAgentKernel(): AgentKernel {\n return { status: 'stub' };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AESA,SAAS,oBAAoB;AAC7B,OAAO,UAAU;ACGjB,SAAS,kBAAkB;AAC3B,OAAOA,WAAU;AACjB,OA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AoB,OAAO,UAAU;AACrC,mBAAS,KAAK;YACZ,MAAM;YACN,WAAW;cACT,kBAAkB,kBAAkB;gBAClC,MAAM,QAAQ;gBACd,OAAO,QAAQ;gBACf,QAAQ,KAAK;gBACb,IAAI;cACN,CAAC;YACH;UACF,CAAC;QACH;AACA;MACF;MAEA,KAAK,oBAAoB;AACvB,uBAAe,MAAM,YAAY,OAAO,MAAM,SAAS,IAAI;AAG3D,cAAM,eAAe,KAAK;AAG1B,YAAI,cAAc;AAChB,qBAAW,WAAW,OAAO,OAAO,YAAY,GAAG;AACjD,gBAAI,QAAQ,OAAO;AACjB,yBAAW;AACX,kCAAoB,OAAO,QAAQ,MAAM,eAAe,CAAC;AACzD,mCAAqB,OAAO,QAAQ,MAAM,gBAAgB,CAAC;YAC7D;UACF;QACF;AAGA,cAAM,eAAe,KAAK;AAC1B,YAAI,gBAAgB,CAAC,KAAK,OAAO;AAC/B,eAAK,QAAQ,OAAO,YAAY;QAClC;AACA;MACF;IACF;EACF;AAEA,MAAI;AACJ,MAAI,kBAAkB,cAAc;AAClC,iBAAa,IAAI,KAAK,YAAY,EAAE,QAAQ,IAAI,IAAI,KAAK,cAAc,EAAE,QAAQ;EACnF;AAEA,SAAO;IACL;IACA;IACA,YAAY,WAAW,EAAE,OAAO,kBAAkB,QAAQ,kBAAkB,IAAI;IAChF;EACF;AACF;ACsDO,SAAS,oBAAiC;AAC/C,SAAO,EAAE,QAAQ,OAAO;AAC1B;","names":["path","readFileSync","path","existsSync","spawnSync","readFile","readdir","stat","homedir","asRecord","stringValue","resourceAttributes","dropUndefined","noSkillFile","z","RESULT_INDEX_FILENAME","stdout","inspection","status","isRecord","manifestPath","localBranchExists","outcome"]}