@useavalon/caelence-agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +201 -0
  2. package/bin/harness.ts +10 -0
  3. package/package.json +75 -0
  4. package/skills/copy-editor/SKILL.md +74 -0
  5. package/skills/copy-editor/references/anti-slop.md +62 -0
  6. package/skills/copy-editor/references/ui-states.md +46 -0
  7. package/skills/copy-editor/scripts/lint-copy.py +78 -0
  8. package/skills/copy-harry-dry/SKILL.md +120 -0
  9. package/skills/copy-rmbc/SKILL.md +97 -0
  10. package/skills/copywriting/SKILL.md +73 -0
  11. package/skills/impeccable/SKILL.md +133 -0
  12. package/skills/impeccable/references/visual-slop.md +36 -0
  13. package/src/cli/main.test.ts +36 -0
  14. package/src/cli/main.ts +384 -0
  15. package/src/cli/media-models.ts +82 -0
  16. package/src/cli/models.ts +43 -0
  17. package/src/cli/openrouter-live.test.ts +35 -0
  18. package/src/cli/openrouter-live.ts +72 -0
  19. package/src/cli/openrouter-modality.test.ts +25 -0
  20. package/src/cli/openrouter-modality.ts +83 -0
  21. package/src/cli/picker.test.ts +53 -0
  22. package/src/cli/picker.ts +48 -0
  23. package/src/cli/plain-text.ts +15 -0
  24. package/src/cli/slash-dispatch.test.ts +213 -0
  25. package/src/cli/slash-dispatch.ts +298 -0
  26. package/src/cli/slash.test.ts +113 -0
  27. package/src/cli/slash.ts +119 -0
  28. package/src/cli/theme.test.ts +10 -0
  29. package/src/cli/theme.ts +44 -0
  30. package/src/cli/tui-layout.test.ts +33 -0
  31. package/src/cli/tui-layout.ts +33 -0
  32. package/src/cli/tui-screen.test.ts +33 -0
  33. package/src/cli/tui-screen.ts +13 -0
  34. package/src/cli/tui.tsx +735 -0
  35. package/src/config.ts +86 -0
  36. package/src/core/approval.test.ts +60 -0
  37. package/src/core/approval.ts +83 -0
  38. package/src/core/auto-router.test.ts +31 -0
  39. package/src/core/auto-router.ts +66 -0
  40. package/src/core/errors.ts +67 -0
  41. package/src/core/events.ts +85 -0
  42. package/src/core/hooks.test.ts +66 -0
  43. package/src/core/hooks.ts +94 -0
  44. package/src/core/ids.ts +6 -0
  45. package/src/core/instructions.test.ts +49 -0
  46. package/src/core/instructions.ts +44 -0
  47. package/src/core/logger.ts +45 -0
  48. package/src/core/mcp.ts +191 -0
  49. package/src/core/mode.test.ts +63 -0
  50. package/src/core/mode.ts +60 -0
  51. package/src/core/run-turn.test.ts +339 -0
  52. package/src/core/run-turn.ts +487 -0
  53. package/src/core/session.test.ts +203 -0
  54. package/src/core/session.ts +349 -0
  55. package/src/core/stdio-mcp.ts +143 -0
  56. package/src/core/strands.ts +262 -0
  57. package/src/core/usage.test.ts +69 -0
  58. package/src/core/usage.ts +171 -0
  59. package/src/desktop/bridge.test.ts +331 -0
  60. package/src/desktop/bridge.ts +729 -0
  61. package/src/desktop/open-local.test.ts +40 -0
  62. package/src/desktop/open-local.ts +52 -0
  63. package/src/desktop/preview-cache.test.ts +36 -0
  64. package/src/desktop/preview-cache.ts +63 -0
  65. package/src/desktop/secrets.test.ts +44 -0
  66. package/src/desktop/secrets.ts +60 -0
  67. package/src/evals/runner.test.ts +43 -0
  68. package/src/evals/runner.ts +225 -0
  69. package/src/index.ts +132 -0
  70. package/src/init.test.ts +54 -0
  71. package/src/init.ts +117 -0
  72. package/src/integrations/catalog-data.json +424 -0
  73. package/src/integrations/catalog.ts +81 -0
  74. package/src/integrations/connect.ts +231 -0
  75. package/src/integrations/integrations.test.ts +329 -0
  76. package/src/integrations/marks/airtable.svg +1 -0
  77. package/src/integrations/marks/algolia-mcp.svg +1 -0
  78. package/src/integrations/marks/canva.jpg +0 -0
  79. package/src/integrations/marks/cloudflare-mcp.svg +1 -0
  80. package/src/integrations/marks/contentful-mcp.svg +1 -0
  81. package/src/integrations/marks/craft.png +0 -0
  82. package/src/integrations/marks/dinero.png +0 -0
  83. package/src/integrations/marks/figma.svg +1 -0
  84. package/src/integrations/marks/gitlab.svg +1 -0
  85. package/src/integrations/marks/google-calendar.svg +1 -0
  86. package/src/integrations/marks/google-docs.svg +1 -0
  87. package/src/integrations/marks/google-drive.svg +1 -0
  88. package/src/integrations/marks/google-gmail.svg +1 -0
  89. package/src/integrations/marks/google-sheets.svg +1 -0
  90. package/src/integrations/marks/google-slides.svg +1 -0
  91. package/src/integrations/marks/granola.png +0 -0
  92. package/src/integrations/marks/jira.svg +1 -0
  93. package/src/integrations/marks/linear.svg +1 -0
  94. package/src/integrations/marks/microsoft-365.svg +7 -0
  95. package/src/integrations/marks/miro.svg +1 -0
  96. package/src/integrations/marks/mixpanel-mcp.svg +1 -0
  97. package/src/integrations/marks/monday.png +0 -0
  98. package/src/integrations/marks/mux-mcp.png +0 -0
  99. package/src/integrations/marks/neon-mcp.svg +1 -0
  100. package/src/integrations/marks/notion.svg +1 -0
  101. package/src/integrations/marks/paddle-mcp.svg +1 -0
  102. package/src/integrations/marks/posthog-mcp.svg +1 -0
  103. package/src/integrations/marks/prismic-mcp.svg +1 -0
  104. package/src/integrations/marks/replicate-mcp.svg +1 -0
  105. package/src/integrations/marks/resend-mcp.svg +1 -0
  106. package/src/integrations/marks/sanity-mcp.svg +1 -0
  107. package/src/integrations/marks/sceneplane.png +0 -0
  108. package/src/integrations/marks/sentry-mcp.svg +1 -0
  109. package/src/integrations/marks/stripe-mcp.svg +1 -0
  110. package/src/integrations/marks/supabase-mcp.svg +1 -0
  111. package/src/integrations/marks/upstash-mcp.svg +1 -0
  112. package/src/integrations/marks/vercel.svg +1 -0
  113. package/src/integrations/marks/webflow.svg +1 -0
  114. package/src/integrations/mcp-oauth.test.ts +39 -0
  115. package/src/integrations/mcp-oauth.ts +330 -0
  116. package/src/integrations/oauth-clients.test.ts +77 -0
  117. package/src/integrations/oauth-clients.ts +127 -0
  118. package/src/integrations/oauth.ts +145 -0
  119. package/src/integrations/remote-mcp.ts +307 -0
  120. package/src/integrations/store.ts +149 -0
  121. package/src/media/openrouter-generate.test.ts +80 -0
  122. package/src/media/openrouter-generate.ts +178 -0
  123. package/src/media/prefs.ts +54 -0
  124. package/src/observability/categories.ts +41 -0
  125. package/src/observability/create.test.ts +56 -0
  126. package/src/observability/create.ts +45 -0
  127. package/src/observability/experiments.ts +113 -0
  128. package/src/observability/fake.ts +191 -0
  129. package/src/observability/index.ts +57 -0
  130. package/src/observability/judges.ts +91 -0
  131. package/src/observability/langfuse.ts +275 -0
  132. package/src/observability/noop.ts +33 -0
  133. package/src/observability/observability.test.ts +113 -0
  134. package/src/observability/prompts.ts +98 -0
  135. package/src/observability/regression-items.ts +158 -0
  136. package/src/observability/sanitize.test.ts +26 -0
  137. package/src/observability/sanitize.ts +57 -0
  138. package/src/observability/types.ts +122 -0
  139. package/src/observability/version.ts +41 -0
  140. package/src/product.ts +2 -0
  141. package/src/runtime.test.ts +98 -0
  142. package/src/runtime.ts +438 -0
  143. package/src/skills/author-skill.ts +49 -0
  144. package/src/skills/create-skill.test.ts +108 -0
  145. package/src/skills/create-skill.ts +70 -0
  146. package/src/skills/loader.test.ts +122 -0
  147. package/src/skills/loader.ts +162 -0
  148. package/src/skills/registry.test.ts +190 -0
  149. package/src/skills/registry.ts +402 -0
  150. package/src/skills/skill-command.ts +53 -0
  151. package/src/skills/user-dir.ts +8 -0
  152. package/src/tools/git.test.ts +71 -0
  153. package/src/tools/git.ts +126 -0
  154. package/src/tools/local.ts +258 -0
  155. package/src/tools/paths.test.ts +24 -0
  156. package/src/tools/paths.ts +39 -0
  157. package/src/tools/read-skill.ts +43 -0
  158. package/src/tools/subagent.test.ts +77 -0
  159. package/src/tools/subagent.ts +74 -0
  160. package/src/tools/todo.test.ts +25 -0
  161. package/src/tools/todo.ts +70 -0
@@ -0,0 +1,57 @@
1
+ export { categorizeFailure, type FailureSignals } from "./categories.ts";
2
+ export {
3
+ createObservability,
4
+ getObservability,
5
+ resetObservabilityForTests,
6
+ startObservability,
7
+ } from "./create.ts";
8
+ export {
9
+ DEFAULT_GATES,
10
+ type ExperimentEvaluator,
11
+ type ExperimentItem,
12
+ type ExperimentResult,
13
+ runLocalExperiment,
14
+ } from "./experiments.ts";
15
+ export { createRecordingObservability, type RecordedScore, type RecordedSpan } from "./fake.ts";
16
+ export {
17
+ parseQualityScores,
18
+ postDeterministicScores,
19
+ QUALITY_DIMENSIONS,
20
+ type QualityDimension,
21
+ type QualityScores,
22
+ qualityEvalEnabled,
23
+ scoreQualityDimensions,
24
+ } from "./judges.ts";
25
+ export { isNoopObservability, noopObservability } from "./noop.ts";
26
+ export {
27
+ harnessPromptRecords,
28
+ type PromptRecord,
29
+ promptVersionHash,
30
+ promptVersionMap,
31
+ recordPromptVersions,
32
+ syncPrompts,
33
+ WEBSITE_PROMPT_FILES,
34
+ } from "./prompts.ts";
35
+ export { WEBSITE_GENERATION_REGRESSION } from "./regression-items.ts";
36
+ export { sanitize } from "./sanitize.ts";
37
+ export type {
38
+ CreateObservabilityOptions,
39
+ EventInput,
40
+ FailureCategory,
41
+ FeedbackCategory,
42
+ GenerationFields,
43
+ GenerationHandle,
44
+ GenerationOptions,
45
+ Observability,
46
+ ScoreInput,
47
+ SpanFields,
48
+ SpanHandle,
49
+ SpanOptions,
50
+ TurnOptions,
51
+ } from "./types.ts";
52
+ export { FAILURE_CATEGORIES, FEEDBACK_CATEGORIES } from "./types.ts";
53
+ export {
54
+ langfuseKeysPresent,
55
+ resolveAgentVersion,
56
+ resolveEnvironment,
57
+ } from "./version.ts";
@@ -0,0 +1,91 @@
1
+ import type { Observability } from "./types.ts";
2
+
3
+ export const QUALITY_DIMENSIONS = [
4
+ "instruction_following",
5
+ "visual_quality",
6
+ "content_quality",
7
+ "design_consistency",
8
+ "ux_quality",
9
+ "code_quality",
10
+ ] as const;
11
+
12
+ export type QualityDimension = (typeof QUALITY_DIMENSIONS)[number];
13
+
14
+ export interface QualityScores {
15
+ [name: string]: number;
16
+ }
17
+
18
+ const JUDGE_SYSTEM = `You score a generated website against the user's request.
19
+ Reply with JSON only: an object whose keys are exactly
20
+ instruction_following, visual_quality, content_quality, design_consistency, ux_quality, code_quality
21
+ and whose values are numbers from 0 to 1.
22
+ Do not invent metrics about the business. Score only what you can see in the provided artifacts.`;
23
+
24
+ export function parseQualityScores(text: string): QualityScores | undefined {
25
+ const start = text.indexOf("{");
26
+ const end = text.lastIndexOf("}");
27
+ if (start < 0 || end <= start) return undefined;
28
+ try {
29
+ const parsed = JSON.parse(text.slice(start, end + 1)) as Record<string, unknown>;
30
+ const out: QualityScores = {};
31
+ for (const key of QUALITY_DIMENSIONS) {
32
+ const raw = parsed[key];
33
+ const n = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : NaN;
34
+ if (!Number.isFinite(n)) continue;
35
+ out[key] = Math.min(1, Math.max(0, n));
36
+ }
37
+ return Object.keys(out).length > 0 ? out : undefined;
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ }
42
+
43
+ export async function scoreQualityDimensions(input: {
44
+ obs: Observability;
45
+ chat: (args: { system: string; user: string; model: string }) => Promise<string>;
46
+ model: string;
47
+ userRequest: string;
48
+ artifact: string;
49
+ traceId?: string;
50
+ }): Promise<QualityScores | undefined> {
51
+ if (!input.obs.enabled) return undefined;
52
+ try {
53
+ const text = await input.chat({
54
+ system: JUDGE_SYSTEM,
55
+ user: `Request:\n${input.userRequest.slice(0, 4000)}\n\nArtifact:\n${input.artifact.slice(0, 12_000)}`,
56
+ model: input.model,
57
+ });
58
+ const scores = parseQualityScores(text);
59
+ if (!scores) return undefined;
60
+ for (const [name, value] of Object.entries(scores)) {
61
+ input.obs.score({
62
+ name,
63
+ value,
64
+ traceId: input.traceId,
65
+ dataType: "NUMERIC",
66
+ });
67
+ }
68
+ return scores;
69
+ } catch {
70
+ return undefined;
71
+ }
72
+ }
73
+
74
+ /** Opt-in LLM-as-judge. Off unless `LANGFUSE_QUALITY_EVAL` is 1/true/yes. */
75
+ export function qualityEvalEnabled(env: Record<string, string | undefined> = process.env): boolean {
76
+ const value = (env.LANGFUSE_QUALITY_EVAL ?? "").trim().toLowerCase();
77
+ return value === "1" || value === "true" || value === "yes";
78
+ }
79
+
80
+ /** Deterministic scores from scans (site-design eval, health checks). Never invent. */
81
+ export function postDeterministicScores(
82
+ obs: Observability,
83
+ scores: Record<string, number>,
84
+ traceId?: string,
85
+ ): void {
86
+ if (!obs.enabled) return;
87
+ for (const [name, value] of Object.entries(scores)) {
88
+ if (!Number.isFinite(value)) continue;
89
+ obs.score({ name, value, traceId, dataType: "NUMERIC" });
90
+ }
91
+ }
@@ -0,0 +1,275 @@
1
+ import { sanitize } from "./sanitize.ts";
2
+ import type {
3
+ CreateObservabilityOptions,
4
+ EventInput,
5
+ GenerationHandle,
6
+ Observability,
7
+ ScoreInput,
8
+ SpanHandle,
9
+ TurnOptions,
10
+ } from "./types.ts";
11
+ import { resolveAgentVersion, resolveEnvironment } from "./version.ts";
12
+
13
+ type StartActive = (
14
+ name: string,
15
+ fn: (obs: LangfuseObservation) => Promise<unknown>,
16
+ options?: { asType?: string },
17
+ ) => Promise<unknown>;
18
+
19
+ interface LangfuseObservation {
20
+ update(fields: Record<string, unknown>): unknown;
21
+ end?(): void;
22
+ }
23
+
24
+ interface LangfuseTracing {
25
+ startActiveObservation: StartActive;
26
+ propagateAttributes: (
27
+ attrs: Record<string, unknown>,
28
+ fn: () => Promise<unknown>,
29
+ ) => Promise<unknown>;
30
+ getActiveTraceId?: () => string | undefined;
31
+ }
32
+
33
+ interface LangfuseClientLike {
34
+ score: {
35
+ create(input: Record<string, unknown>): Promise<unknown>;
36
+ };
37
+ flush?: () => Promise<unknown>;
38
+ shutdown?: () => Promise<unknown>;
39
+ }
40
+
41
+ interface OtelHandle {
42
+ shutdown(): Promise<void>;
43
+ }
44
+
45
+ function safe(fn: () => void): void {
46
+ try {
47
+ fn();
48
+ } catch {
49
+ // never throw into the agent loop
50
+ }
51
+ }
52
+
53
+ function observationHandle(
54
+ obs: LangfuseObservation,
55
+ getTraceId: () => string | undefined,
56
+ ): GenerationHandle {
57
+ return {
58
+ get traceId() {
59
+ return getTraceId();
60
+ },
61
+ update(fields) {
62
+ safe(() => {
63
+ const payload: Record<string, unknown> = {};
64
+ if ("input" in fields) payload.input = sanitize(fields.input);
65
+ if ("output" in fields) payload.output = sanitize(fields.output);
66
+ if (fields.metadata) payload.metadata = sanitize(fields.metadata);
67
+ if (fields.level) payload.level = fields.level;
68
+ if (fields.statusMessage) payload.statusMessage = fields.statusMessage;
69
+ if ("model" in fields && fields.model) payload.model = fields.model;
70
+ if ("usage" in fields && fields.usage) {
71
+ payload.usageDetails = {
72
+ promptTokens: fields.usage.promptTokens,
73
+ completionTokens: fields.usage.completionTokens,
74
+ totalTokens: fields.usage.totalTokens,
75
+ };
76
+ }
77
+ obs.update(payload);
78
+ });
79
+ },
80
+ end() {
81
+ safe(() => {
82
+ obs.end?.();
83
+ });
84
+ },
85
+ };
86
+ }
87
+
88
+ export async function tryCreateLangfuseObservability(
89
+ options: CreateObservabilityOptions = {},
90
+ ): Promise<Observability | undefined> {
91
+ const env = options.env ?? process.env;
92
+ const secret = env.LANGFUSE_SECRET_KEY?.trim();
93
+ const publicKey = env.LANGFUSE_PUBLIC_KEY?.trim();
94
+ if (!secret || !publicKey) return undefined;
95
+
96
+ let tracing: LangfuseTracing;
97
+ let LangfuseSpanProcessor: new (opts?: Record<string, unknown>) => unknown;
98
+ let NodeSDK: new (opts: {
99
+ spanProcessors: unknown[];
100
+ }) => { start(): void; shutdown(): Promise<void> };
101
+ let LangfuseClient: new (opts?: Record<string, unknown>) => LangfuseClientLike;
102
+ try {
103
+ const tracingMod = (await import("@langfuse/tracing")) as unknown as LangfuseTracing;
104
+ const otelMod = (await import("@langfuse/otel")) as {
105
+ LangfuseSpanProcessor: typeof LangfuseSpanProcessor;
106
+ };
107
+ const sdkMod = (await import("@opentelemetry/sdk-node")) as { NodeSDK: typeof NodeSDK };
108
+ const clientMod = (await import("@langfuse/client")) as unknown as {
109
+ LangfuseClient: typeof LangfuseClient;
110
+ };
111
+ tracing = tracingMod;
112
+ LangfuseSpanProcessor = otelMod.LangfuseSpanProcessor;
113
+ NodeSDK = sdkMod.NodeSDK;
114
+ LangfuseClient = clientMod.LangfuseClient;
115
+ } catch {
116
+ return undefined;
117
+ }
118
+
119
+ const baseUrl = env.LANGFUSE_BASE_URL?.trim() || undefined;
120
+ const agentVersion = resolveAgentVersion(options.agentVersion, env);
121
+ const environment = options.environment ?? resolveEnvironment(env);
122
+
123
+ let otel: OtelHandle | undefined;
124
+ try {
125
+ const processor = new LangfuseSpanProcessor({
126
+ publicKey,
127
+ secretKey: secret,
128
+ ...(baseUrl ? { baseUrl } : {}),
129
+ environment,
130
+ });
131
+ const sdk = new NodeSDK({ spanProcessors: [processor] });
132
+ sdk.start();
133
+ otel = sdk;
134
+ } catch {
135
+ return undefined;
136
+ }
137
+
138
+ const client = new LangfuseClient({
139
+ publicKey,
140
+ secretKey: secret,
141
+ ...(baseUrl ? { baseUrl } : {}),
142
+ });
143
+
144
+ const getTraceId = (): string | undefined => {
145
+ try {
146
+ return tracing.getActiveTraceId?.();
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ };
151
+
152
+ const runObservation = async <T>(
153
+ name: string,
154
+ asType: string,
155
+ fn: (span: SpanHandle) => Promise<T>,
156
+ seed?: Record<string, unknown>,
157
+ ): Promise<T> => {
158
+ try {
159
+ return (await tracing.startActiveObservation(
160
+ name,
161
+ async (obs) => {
162
+ if (seed && Object.keys(seed).length > 0) {
163
+ safe(() => obs.update(seed));
164
+ }
165
+ return fn(observationHandle(obs, getTraceId));
166
+ },
167
+ { asType },
168
+ )) as T;
169
+ } catch (err) {
170
+ // If Langfuse itself fails, still run the work.
171
+ if (err instanceof Error && /langfuse/i.test(err.message)) {
172
+ return fn(observationHandle({ update() {}, end() {} }, getTraceId));
173
+ }
174
+ throw err;
175
+ }
176
+ };
177
+
178
+ const obs: Observability = {
179
+ enabled: true,
180
+ async startTurn(turn: TurnOptions, fn) {
181
+ const metadata = sanitize({
182
+ ...turn.metadata,
183
+ agentVersion,
184
+ environment,
185
+ ...(turn.sessionId ? { sessionId: turn.sessionId } : {}),
186
+ });
187
+ const attrs: Record<string, unknown> = {
188
+ traceName: turn.name,
189
+ metadata,
190
+ version: agentVersion,
191
+ };
192
+ if (turn.userId) attrs.userId = turn.userId;
193
+ if (turn.sessionId) attrs.sessionId = turn.sessionId;
194
+ if (turn.tags) attrs.tags = turn.tags;
195
+ try {
196
+ return (await tracing.propagateAttributes(attrs, () =>
197
+ runObservation(
198
+ turn.name,
199
+ "span",
200
+ fn,
201
+ turn.input !== undefined ? { input: sanitize(turn.input) } : undefined,
202
+ ),
203
+ )) as Awaited<ReturnType<typeof fn>>;
204
+ } catch {
205
+ return fn(observationHandle({ update() {}, end() {} }, getTraceId));
206
+ }
207
+ },
208
+ startSpan(name, fn, options) {
209
+ return runObservation(name, "span", fn, {
210
+ ...(options?.input !== undefined ? { input: sanitize(options.input) } : {}),
211
+ ...(options?.metadata ? { metadata: sanitize(options.metadata) } : {}),
212
+ });
213
+ },
214
+ generation(name, fn, options) {
215
+ return runObservation(name, "generation", fn, {
216
+ ...(options?.model ? { model: options.model } : {}),
217
+ ...(options?.input !== undefined ? { input: sanitize(options.input) } : {}),
218
+ ...(options?.metadata ? { metadata: sanitize(options.metadata) } : {}),
219
+ });
220
+ },
221
+ tool(name, fn, options) {
222
+ return runObservation(`tool:${name}`, "span", fn, {
223
+ ...(options?.input !== undefined ? { input: sanitize(options.input) } : {}),
224
+ ...(options?.metadata
225
+ ? { metadata: sanitize({ ...options.metadata, toolName: name }) }
226
+ : { metadata: { toolName: name } }),
227
+ });
228
+ },
229
+ score(input: ScoreInput) {
230
+ const traceId = input.traceId ?? getTraceId();
231
+ if (!traceId) return;
232
+ void client.score
233
+ .create({
234
+ traceId,
235
+ name: input.name,
236
+ value: input.value,
237
+ ...(input.comment ? { comment: input.comment } : {}),
238
+ ...(input.dataType ? { dataType: input.dataType } : {}),
239
+ ...(input.stringValue ? { stringValue: input.stringValue } : {}),
240
+ ...(input.metadata ? { metadata: sanitize(input.metadata) } : {}),
241
+ })
242
+ .catch(() => undefined);
243
+ },
244
+ event(name: string, input?: EventInput) {
245
+ void runObservation(name, "event", async (span) => {
246
+ span.update({
247
+ input: input?.input,
248
+ metadata: input?.metadata,
249
+ });
250
+ }).catch(() => undefined);
251
+ },
252
+ currentTraceId: getTraceId,
253
+ async flush() {
254
+ try {
255
+ await client.flush?.();
256
+ } catch {
257
+ /* ignore */
258
+ }
259
+ },
260
+ async shutdown() {
261
+ try {
262
+ await client.flush?.();
263
+ await client.shutdown?.();
264
+ } catch {
265
+ /* ignore */
266
+ }
267
+ try {
268
+ await otel?.shutdown();
269
+ } catch {
270
+ /* ignore */
271
+ }
272
+ },
273
+ };
274
+ return obs;
275
+ }
@@ -0,0 +1,33 @@
1
+ import type { GenerationHandle, Observability, ScoreInput } from "./types.ts";
2
+
3
+ const silentSpan: GenerationHandle = {
4
+ update() {},
5
+ end() {},
6
+ };
7
+
8
+ export const noopObservability: Observability = {
9
+ enabled: false,
10
+ startTurn(_options, fn) {
11
+ return fn(silentSpan);
12
+ },
13
+ startSpan(_name, fn) {
14
+ return fn(silentSpan);
15
+ },
16
+ generation(_name, fn) {
17
+ return fn(silentSpan);
18
+ },
19
+ tool(_name, fn) {
20
+ return fn(silentSpan);
21
+ },
22
+ score(_input: ScoreInput) {},
23
+ event() {},
24
+ currentTraceId() {
25
+ return undefined;
26
+ },
27
+ async flush() {},
28
+ async shutdown() {},
29
+ };
30
+
31
+ export function isNoopObservability(obs: Observability): boolean {
32
+ return obs === noopObservability || obs.enabled === false;
33
+ }
@@ -0,0 +1,113 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { categorizeFailure } from "./categories.ts";
3
+ import { runLocalExperiment } from "./experiments.ts";
4
+ import { createRecordingObservability } from "./fake.ts";
5
+ import { parseQualityScores, qualityEvalEnabled, scoreQualityDimensions } from "./judges.ts";
6
+ import { harnessPromptRecords, promptVersionHash } from "./prompts.ts";
7
+ import { WEBSITE_GENERATION_REGRESSION } from "./regression-items.ts";
8
+
9
+ describe("categorizeFailure", () => {
10
+ test("maps gates and error types", () => {
11
+ expect(categorizeFailure({ typecheckPass: false })).toBe("BUILD_ERROR");
12
+ expect(categorizeFailure({ uiPass: false })).toBe("RUNTIME_ERROR");
13
+ expect(categorizeFailure({ errorType: "tdd_failed" })).toBe("CODE_GENERATION_ERROR");
14
+ expect(categorizeFailure({ timedOut: true })).toBe("TIMEOUT");
15
+ expect(categorizeFailure({ phase: "mcp" })).toBe("TOOL_ERROR");
16
+ });
17
+ });
18
+
19
+ describe("parseQualityScores", () => {
20
+ test("extracts 0-1 dimensions from JSON", () => {
21
+ const scores = parseQualityScores(
22
+ 'noise {"instruction_following": 0.9, "visual_quality": 1.4, "nope": 3} trailing',
23
+ );
24
+ expect(scores?.instruction_following).toBe(0.9);
25
+ expect(scores?.visual_quality).toBe(1);
26
+ expect(scores?.nope).toBeUndefined();
27
+ });
28
+ });
29
+
30
+ describe("scoreQualityDimensions", () => {
31
+ test("posts parsed dimensions onto the observer", async () => {
32
+ const obs = createRecordingObservability();
33
+ const scores = await scoreQualityDimensions({
34
+ obs,
35
+ model: "fake",
36
+ userRequest: "A bakery site",
37
+ artifact: "<html></html>",
38
+ chat: async () =>
39
+ JSON.stringify({
40
+ instruction_following: 0.8,
41
+ visual_quality: 0.5,
42
+ content_quality: 0.7,
43
+ design_consistency: 0.6,
44
+ ux_quality: 0.4,
45
+ code_quality: 0.9,
46
+ }),
47
+ });
48
+ expect(scores?.instruction_following).toBe(0.8);
49
+ expect(obs.scores).toHaveLength(6);
50
+ });
51
+ });
52
+
53
+ describe("qualityEvalEnabled", () => {
54
+ test("is off unless explicitly opted in", () => {
55
+ expect(qualityEvalEnabled({})).toBe(false);
56
+ expect(qualityEvalEnabled({ LANGFUSE_QUALITY_EVAL: "1" })).toBe(true);
57
+ expect(qualityEvalEnabled({ LANGFUSE_QUALITY_EVAL: "true" })).toBe(true);
58
+ expect(qualityEvalEnabled({ LANGFUSE_QUALITY_EVAL: "no" })).toBe(false);
59
+ });
60
+ });
61
+
62
+ describe("promptVersionHash", () => {
63
+ test("is stable for the same body", () => {
64
+ expect(promptVersionHash("hello")).toBe(promptVersionHash("hello"));
65
+ expect(promptVersionHash("hello")).not.toBe(promptVersionHash("hello "));
66
+ });
67
+ });
68
+
69
+ describe("harnessPromptRecords", () => {
70
+ test("loads bundled copywriting and impeccable skills", () => {
71
+ const names = harnessPromptRecords().map((p) => p.name);
72
+ expect(names).toContain("copywriting");
73
+ expect(names).toContain("impeccable");
74
+ });
75
+ });
76
+
77
+ describe("regression seed", () => {
78
+ test("has twenty briefs with no invented metrics", () => {
79
+ expect(WEBSITE_GENERATION_REGRESSION).toHaveLength(20);
80
+ for (const item of WEBSITE_GENERATION_REGRESSION) {
81
+ const brief =
82
+ item.input && typeof item.input === "object" && "brief" in item.input
83
+ ? String((item.input as { brief?: unknown }).brief ?? "")
84
+ : "";
85
+ expect(brief.length).toBeGreaterThan(10);
86
+ }
87
+ });
88
+ });
89
+
90
+ describe("runLocalExperiment", () => {
91
+ test("aggregates evaluator scores and honors a gate", async () => {
92
+ const obs = createRecordingObservability();
93
+ const result = await runLocalExperiment({
94
+ name: "website-generation-regression",
95
+ observability: obs,
96
+ items: [
97
+ { id: "a", input: "one" },
98
+ { id: "b", input: "two" },
99
+ ],
100
+ task: async (item) => String(item.input),
101
+ evaluators: [
102
+ {
103
+ name: "build_success",
104
+ run: ({ output }) => ({ value: output === "one" ? 1 : 0 }),
105
+ },
106
+ ],
107
+ gate: { score: "build_success", min: 0.9 },
108
+ });
109
+ expect(result.aggregates.build_success).toBe(0.5);
110
+ expect(result.ok).toBe(false);
111
+ expect(obs.turns[0]?.name).toBe("website-generation-regression");
112
+ });
113
+ });
@@ -0,0 +1,98 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import type { Observability } from "./types.ts";
5
+
6
+ export interface PromptRecord {
7
+ name: string;
8
+ body: string;
9
+ label?: string;
10
+ }
11
+
12
+ export function promptVersionHash(body: string): string {
13
+ return createHash("sha256").update(body).digest("hex").slice(0, 12);
14
+ }
15
+
16
+ export const WEBSITE_PROMPT_FILES: Record<string, string> = {
17
+ website_planner: "to-spec",
18
+ design_system_generator: "to-design",
19
+ page_generator: "to-sitemap",
20
+ code_generator: "implement",
21
+ code_reviewer: "code-review",
22
+ browser_debugger: "tdd",
23
+ content_generator: "to-design-brief",
24
+ };
25
+
26
+ export function promptVersionMap(bodies: Record<string, string>): Record<string, string> {
27
+ const out: Record<string, string> = {};
28
+ for (const [name, body] of Object.entries(bodies)) {
29
+ out[name] = promptVersionHash(body);
30
+ }
31
+ return out;
32
+ }
33
+
34
+ /** Git-backed copy / visual-QA skills shipped with the harness. */
35
+ export function harnessPromptRecords(): PromptRecord[] {
36
+ const dir = join(import.meta.dir, "..", "..", "skills");
37
+ const out: PromptRecord[] = [];
38
+ for (const name of ["copywriting", "impeccable"] as const) {
39
+ try {
40
+ out.push({ name, body: readFileSync(join(dir, name, "SKILL.md"), "utf8") });
41
+ } catch {}
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /**
47
+ * Upsert named prompts in Langfuse. Fail-soft: git remains the source of truth
48
+ * and production never waits on this network call.
49
+ */
50
+ export async function syncPrompts(input: {
51
+ prompts: PromptRecord[];
52
+ env?: Record<string, string | undefined>;
53
+ }): Promise<{ synced: string[]; skipped: boolean }> {
54
+ const env = input.env ?? process.env;
55
+ if (!env.LANGFUSE_SECRET_KEY?.trim() || !env.LANGFUSE_PUBLIC_KEY?.trim()) {
56
+ return { synced: [], skipped: true };
57
+ }
58
+ try {
59
+ const mod = (await import("@langfuse/client")) as {
60
+ LangfuseClient: new (
61
+ opts?: Record<string, unknown>,
62
+ ) => {
63
+ prompt: {
64
+ create(body: Record<string, unknown>): Promise<unknown>;
65
+ };
66
+ };
67
+ };
68
+ const client = new mod.LangfuseClient({
69
+ publicKey: env.LANGFUSE_PUBLIC_KEY,
70
+ secretKey: env.LANGFUSE_SECRET_KEY,
71
+ ...(env.LANGFUSE_BASE_URL?.trim() ? { baseUrl: env.LANGFUSE_BASE_URL.trim() } : {}),
72
+ });
73
+ const synced: string[] = [];
74
+ for (const prompt of input.prompts) {
75
+ const version = promptVersionHash(prompt.body);
76
+ await client.prompt.create({
77
+ name: prompt.name,
78
+ prompt: prompt.body,
79
+ labels: prompt.label ? [prompt.label] : ["production"],
80
+ commitMessage: version,
81
+ });
82
+ synced.push(`${prompt.name}:${version}`);
83
+ }
84
+ return { synced, skipped: false };
85
+ } catch {
86
+ return { synced: [], skipped: true };
87
+ }
88
+ }
89
+
90
+ export function recordPromptVersions(
91
+ obs: Observability,
92
+ versions: Record<string, string>,
93
+ traceId?: string,
94
+ ): void {
95
+ obs.event("prompt_versions", {
96
+ metadata: { ...versions, ...(traceId ? { traceId } : {}) },
97
+ });
98
+ }