@cultured_computer/sight 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,37 @@
1
1
  # Sight
2
2
 
3
- A capture and measurement API for production conversational AI. Add the SDK to
4
- your serving process; Sight records every turn and session in a standard
5
- trajectory format and computes behavioural measurements on top: the situations
6
- a deployment handles, voice consistency across turns, uptake, breaks, and
7
- return behaviour. Capture is out of band, responses are never modified or
8
- delayed.
3
+ Know what your production AI is being, without writing evals. Add the SDK to
4
+ your serving process and Sight records every conversation as it happens: what
5
+ the situation was, what your agent said, how the user took it, and how it
6
+ ended. On top of that record it computes behavioural measurements: the
7
+ situations your deployment handles, voice consistency across turns, uptake,
8
+ breaks, and whether users come back. Capture is out of band; responses are
9
+ never modified or delayed.
10
+
11
+ What that buys you, concretely:
12
+
13
+ - **See every conversation as a story, worst moment first.** Sessions triage
14
+ by badness (flagged, broke at turn N, abandoned) and open on the
15
+ transcript, so "what went wrong last night" is one click, not a query.
16
+ - **Know what happened after the reply.** Outcomes (resolved, escalated,
17
+ converted, refunded) attach to the conversation that caused them, even when
18
+ they arrive days later from your CRM webhook, and return behaviour is
19
+ computed per user. Most observability ends at the trace; the record here
20
+ ends at what it led to.
21
+ - **Know how much to trust each number.** Interpreted measurements start as
22
+ "preliminary" and earn a reliability grade only after they agree with your
23
+ own judgement on your own traffic. No number is ever dressed up: a card
24
+ shows its evidence before it shows a headline.
25
+ - **Ask your own questions.** Author custom rubrics in the dashboard (a
26
+ question plus answer chips); they join the same blind labeling queue and
27
+ earn trust the same way: against a second rater, never against the
28
+ instrument.
29
+
30
+ If your job is grading tasks against expected outputs in CI, an eval platform
31
+ (Braintrust and its class) is built for that loop and does it well. Sight is
32
+ built for the other loop: zero eval authoring, capture as the product, and
33
+ answers to the questions evals cannot reach — what your deployment is being
34
+ in production, and what users do next.
9
35
 
10
36
  The SDK is in beta. Interfaces and rollout order may change without notice;
11
37
  the record format itself is versioned and stable.
@@ -96,6 +122,36 @@ time — the next turn's state corner, plus the causing turn's outcome corner
96
122
  when the event carries a `causeProvenance` turn reference — and never
97
123
  interprets them.
98
124
 
125
+ ## Capture spans
126
+
127
+ Deployments that keep their own sub-turn structure — tool calls, retrieval
128
+ steps, per-call model usage inside a single turn — can ship it as spans:
129
+
130
+ ```ts
131
+ await Sight.captureSpans(
132
+ [
133
+ {
134
+ deploymentSlug: 'my-agent',
135
+ sessionExternalId: sessionId,
136
+ turnIndex: 3,
137
+ spanType: 'tool_call',
138
+ name: 'lookup_order',
139
+ startedAt: '2026-07-22T00:00:01.200Z',
140
+ durationMs: 180,
141
+ attributes: { toolName: 'lookup_order', argKeys: ['orderId'] },
142
+ },
143
+ ],
144
+ { clock_source: 'my-agent-clock', skew_bound_ms: 25, rule_version: 'v1' },
145
+ )
146
+ ```
147
+
148
+ A span lands on the turn you name, or on the session's latest turn at/under
149
+ its `startedAt` when `turnIndex` is omitted. Parent structure rides the
150
+ batch: give a span a caller-local `spanId` and reference it from a sibling's
151
+ `parentSpanId`. `attributes` are metadata only — tool names and argument
152
+ shapes, never free-text conversation content. `Sight.captureSpan(span)` is
153
+ the single-span form.
154
+
99
155
  ## Scope
100
156
 
101
157
  Sight is a measurement system: it reports what a deployment did. It does not
package/dist/index.cjs CHANGED
@@ -12,7 +12,7 @@ var IngestClient = class {
12
12
  debug;
13
13
  dashboardUrl;
14
14
  /**
15
- * First-trace permalink ritual (PLAN-2026-07-14-adoptions A1): the first
15
+ * First-trace permalink: the first
16
16
  * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
17
17
  * then never again for the life of this client (one IngestClient per
18
18
  * process — one `init` per process; a restart prints once more, accepted).
@@ -53,7 +53,7 @@ var IngestClient = class {
53
53
  const response = await this.retryIfRateLimited(await send(), send);
54
54
  if (response === null) return;
55
55
  if (!response.ok) {
56
- this.log(`[probe] ingest failed status=${response.status}`);
56
+ this.log(`[sight] ingest failed status=${response.status}`);
57
57
  return;
58
58
  }
59
59
  if (!this.firstCaptureAnnounced) {
@@ -64,16 +64,16 @@ var IngestClient = class {
64
64
  }
65
65
  if (this.debug) {
66
66
  const body = await response.json();
67
- this.log(`[probe] ingest ok id=${body.pendingId ?? "?"}`);
67
+ this.log(`[sight] ingest ok id=${body.pendingId ?? "?"}`);
68
68
  }
69
69
  } catch (err) {
70
70
  const msg = err instanceof Error ? err.message : String(err);
71
- this.log(`[probe] ingest error: ${msg}`);
71
+ this.log(`[sight] ingest error: ${msg}`);
72
72
  }
73
73
  }
74
74
  /**
75
75
  * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
76
- * Populates the `user_flagged_break` outcome column in Chapter 9c.
76
+ * Populates the `user_flagged_break` outcome column on the dashboard.
77
77
  */
78
78
  async sendFlag(deploymentSlug, flag) {
79
79
  try {
@@ -94,15 +94,15 @@ var IngestClient = class {
94
94
  const response = await this.retryIfRateLimited(await send(), send);
95
95
  if (response === null) return;
96
96
  if (!response.ok) {
97
- this.log(`[probe] flag ingest failed status=${response.status}`);
97
+ this.log(`[sight] flag ingest failed status=${response.status}`);
98
98
  return;
99
99
  }
100
100
  if (this.debug) {
101
- this.log(`[probe] flag ingest ok session=${flag.sessionExternalId}`);
101
+ this.log(`[sight] flag ingest ok session=${flag.sessionExternalId}`);
102
102
  }
103
103
  } catch (err) {
104
104
  const msg = err instanceof Error ? err.message : String(err);
105
- this.log(`[probe] flag ingest error: ${msg}`);
105
+ this.log(`[sight] flag ingest error: ${msg}`);
106
106
  }
107
107
  }
108
108
  /**
@@ -126,20 +126,20 @@ var IngestClient = class {
126
126
  const response = await this.retryIfRateLimited(await send(), send);
127
127
  if (response === null) return;
128
128
  if (!response.ok) {
129
- this.log(`[probe] session-end ingest failed status=${response.status}`);
129
+ this.log(`[sight] session-end ingest failed status=${response.status}`);
130
130
  return;
131
131
  }
132
132
  if (this.debug) {
133
- this.log(`[probe] session-end ingest ok session=${end.externalId}`);
133
+ this.log(`[sight] session-end ingest ok session=${end.externalId}`);
134
134
  }
135
135
  } catch (err) {
136
136
  const msg = err instanceof Error ? err.message : String(err);
137
- this.log(`[probe] session-end ingest error: ${msg}`);
137
+ this.log(`[sight] session-end ingest error: ${msg}`);
138
138
  }
139
139
  }
140
140
  /**
141
141
  * Send an outcome event to the ingest API. Fire-and-log. Populates
142
- * probe_outcome_events per Amendment I Method D.
142
+ * the outcome-events store.
143
143
  */
144
144
  async sendOutcomeEvent(deploymentSlug, event) {
145
145
  try {
@@ -161,17 +161,17 @@ var IngestClient = class {
161
161
  const response = await this.retryIfRateLimited(await send(), send);
162
162
  if (response === null) return;
163
163
  if (!response.ok) {
164
- this.log(`[probe] outcome-event ingest failed status=${response.status}`);
164
+ this.log(`[sight] outcome-event ingest failed status=${response.status}`);
165
165
  return;
166
166
  }
167
167
  if (this.debug) {
168
168
  this.log(
169
- `[probe] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`
169
+ `[sight] outcome-event ingest ok session=${event.sessionExternalId} kind=${event.kind}`
170
170
  );
171
171
  }
172
172
  } catch (err) {
173
173
  const msg = err instanceof Error ? err.message : String(err);
174
- this.log(`[probe] outcome-event ingest error: ${msg}`);
174
+ this.log(`[sight] outcome-event ingest error: ${msg}`);
175
175
  }
176
176
  }
177
177
  /**
@@ -192,15 +192,45 @@ var IngestClient = class {
192
192
  const response = await this.retryIfRateLimited(await send(), send);
193
193
  if (response === null) return;
194
194
  if (!response.ok) {
195
- this.log(`[probe] environment-events ingest failed status=${response.status}`);
195
+ this.log(`[sight] environment-events ingest failed status=${response.status}`);
196
196
  return;
197
197
  }
198
198
  if (this.debug) {
199
- this.log(`[probe] environment-events ingest ok events=${batch.events.length}`);
199
+ this.log(`[sight] environment-events ingest ok events=${batch.events.length}`);
200
200
  }
201
201
  } catch (err) {
202
202
  const msg = err instanceof Error ? err.message : String(err);
203
- this.log(`[probe] environment-events ingest error: ${msg}`);
203
+ this.log(`[sight] environment-events ingest error: ${msg}`);
204
+ }
205
+ }
206
+ /**
207
+ * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.
208
+ * Spans carry sub-turn structure (llm_call / tool_call / framework_step /
209
+ * custom); the worker resolves each span's session/turn and wires in-batch
210
+ * parent references.
211
+ */
212
+ async sendSpans(batch) {
213
+ try {
214
+ const send = () => fetch(`${this.endpoint}/v1/spans`, {
215
+ method: "POST",
216
+ headers: {
217
+ Authorization: `Bearer ${this.apiKey}`,
218
+ "content-type": "application/json"
219
+ },
220
+ body: JSON.stringify(batch)
221
+ });
222
+ const response = await this.retryIfRateLimited(await send(), send);
223
+ if (response === null) return;
224
+ if (!response.ok) {
225
+ this.log(`[sight] spans ingest failed status=${response.status}`);
226
+ return;
227
+ }
228
+ if (this.debug) {
229
+ this.log(`[sight] spans ingest ok spans=${batch.spans.length}`);
230
+ }
231
+ } catch (err) {
232
+ const msg = err instanceof Error ? err.message : String(err);
233
+ this.log(`[sight] spans ingest error: ${msg}`);
204
234
  }
205
235
  }
206
236
  /**
@@ -221,10 +251,10 @@ var IngestClient = class {
221
251
  "Sight: ingest rate limit (429) \u2014 retrying once per Retry-After; sustained limiting drops captures. See https://field.cultured.computer/sight/sdk-reference#rate-limits"
222
252
  );
223
253
  } else {
224
- this.log("[probe] ingest rate limited (429), retrying once");
254
+ this.log("[sight] ingest rate limited (429), retrying once");
225
255
  }
226
256
  if (this.pendingRetries >= MAX_PENDING_RETRIES) {
227
- this.log("[probe] retry buffer full, dropped");
257
+ this.log("[sight] retry buffer full, dropped");
228
258
  return null;
229
259
  }
230
260
  const raw = response.headers.get("retry-after");
@@ -292,8 +322,8 @@ var ProbeConfigSchema = zod.z.object({
292
322
  apiKey: zod.z.string().min(1),
293
323
  /** Deployment slug registered in the Probe backend. Required. */
294
324
  deployment: zod.z.string().min(1),
295
- /** Ingest endpoint. Defaults to https://ingest.probe.io. */
296
- endpoint: zod.z.string().url().default("https://ingest.probe.io"),
325
+ /** Ingest endpoint. Defaults to the production ingest service. */
326
+ endpoint: zod.z.string().url().default("https://fieldwork-ingest.fly.dev"),
297
327
  /**
298
328
  * Dashboard base URL used by the one-time first-capture announcement
299
329
  * (the stderr permalink printed after the first successful send).
@@ -335,7 +365,7 @@ var SessionStartSchema = zod.z.object({
335
365
  */
336
366
  persona: zod.z.string().min(1).optional(),
337
367
  /**
338
- * How the user got into this session (P2 per PLAN-2026-07-11).
368
+ * How the user got into this session.
339
369
  * Retention semantics differ radically between a resume and a fresh
340
370
  * notification landing.
341
371
  */
@@ -352,8 +382,8 @@ var SessionStartSchema = zod.z.object({
352
382
  */
353
383
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
354
384
  /**
355
- * RLDS episode-level provenance (Amendment R populater 2026-07-11).
356
- * Powers Chapter 8e′ Card 3 version behavioral diff. All optional.
385
+ * RLDS episode-level provenance. Powers the version behavioral diff
386
+ * on the dashboard. All optional.
357
387
  * agentId — model/policy version
358
388
  * experimentId — A/B arm or feature flag
359
389
  * environmentConfigHash — SHA of prompt/config file(s)
@@ -366,7 +396,9 @@ var SessionStartSchema = zod.z.object({
366
396
  });
367
397
  zod.z.object({
368
398
  externalId: zod.z.string().min(1),
369
- endedReason: zod.z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional()
399
+ endedReason: zod.z.enum(["natural", "user_closed", "timeout", "agent_error", "user_flagged", "crashed"]).optional(),
400
+ outcome: zod.z.string().min(1).max(64).optional(),
401
+ outcomeDetail: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
370
402
  });
371
403
  var FlagPersonaBreakSchema = zod.z.object({
372
404
  sessionExternalId: zod.z.string().min(1),
@@ -903,7 +935,7 @@ function registerAllInstrumentations(state2, captureFn) {
903
935
  if (!state2.config.debug) return;
904
936
  for (const result of results) {
905
937
  if (result.status === "rejected") {
906
- console.error(`[probe] adapter register rejected: ${result.reason}`);
938
+ console.error(`[sight] adapter register rejected: ${result.reason}`);
907
939
  }
908
940
  }
909
941
  });
@@ -943,6 +975,13 @@ function matchSignaturePhrases(text, compiled) {
943
975
  }
944
976
  return matches;
945
977
  }
978
+
979
+ // ../shared/src/effectiveness-gap.ts
980
+ new Set(
981
+ "the a an to of and or is are was were do does did how what where when who why which can could should would may might i you your my me it its this that these those in on for with at by from as be been being am not no yes okay ok um uh hi hello please thanks thank".split(" ")
982
+ );
983
+
984
+ // ../shared/src/index.ts
946
985
  var REACTION_REGISTERS = ["heavy", "comic", "edge"];
947
986
  var InterpretiveRecordSchema = zod.z.object({
948
987
  // Open vocabulary: any string tag. Seeds live in GENERAL_SITUATION_TAGS /
@@ -1072,6 +1111,15 @@ zod.z.object({
1072
1111
  */
1073
1112
  externalUserId: zod.z.string().min(1).optional(),
1074
1113
  turnIndex: zod.z.number().int().nonnegative(),
1114
+ /**
1115
+ * Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
1116
+ * worker: when present it becomes turns.started_at; when absent the
1117
+ * insert defaults to processing time. This is PROVENANCE, not
1118
+ * verification — intended for historical imports (ZVA telemetry, log
1119
+ * backfills, the datadump importer); live SDK traffic leaves it unset
1120
+ * (arrival time is the honest clock there).
1121
+ */
1122
+ startedAt: zod.z.string().datetime().optional(),
1075
1123
  /**
1076
1124
  * Persona slug active for this turn. Customer-supplied (from SDK persona
1077
1125
  * resolution: turn override / session / init default). Optional; deployments
@@ -1216,6 +1264,100 @@ var EnvironmentEventsBatchSchema = zod.z.object({
1216
1264
  events: zod.z.array(EnvironmentEventInputSchema).min(1).max(100),
1217
1265
  alignment: AlignmentProvenanceSchema
1218
1266
  });
1267
+ var SPAN_TYPES = ["llm_call", "tool_call", "framework_step", "custom"];
1268
+ var SpanInputSchema = zod.z.object({
1269
+ deploymentSlug: zod.z.string().min(1),
1270
+ sessionExternalId: zod.z.string().min(1),
1271
+ /**
1272
+ * Turn the span belongs to. Optional: when omitted the worker resolves the
1273
+ * session's latest turn at/under the span's startedAt (falling back to the
1274
+ * session's most recent turn when startedAt is also absent — the outcome
1275
+ * events' rule). A span whose turn cannot be resolved is SKIPPED by the
1276
+ * worker (logged, batch still processed): spans never land unattributed.
1277
+ */
1278
+ turnIndex: zod.z.number().int().nonnegative().optional(),
1279
+ spanType: zod.z.enum(SPAN_TYPES),
1280
+ /** Human/otel-style span name (tool name, model call label). */
1281
+ name: zod.z.string().optional(),
1282
+ /**
1283
+ * Caller-asserted span start (ISO). OPTIONAL and honored like
1284
+ * TurnInput.startedAt: provenance, not verification — when absent the
1285
+ * worker stamps processing time.
1286
+ */
1287
+ startedAt: zod.z.string().datetime().optional(),
1288
+ endedAt: zod.z.string().datetime().optional(),
1289
+ durationMs: zod.z.number().int().nonnegative().optional(),
1290
+ model: zod.z.string().optional(),
1291
+ provider: zod.z.string().optional(),
1292
+ tokensInput: zod.z.number().int().nonnegative().optional(),
1293
+ tokensOutput: zod.z.number().int().nonnegative().optional(),
1294
+ costUsd: zod.z.number().nonnegative().optional(),
1295
+ error: zod.z.string().optional(),
1296
+ /**
1297
+ * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values
1298
+ * are Presidio-scrubbed by the worker before storage (see the PII rule
1299
+ * above). Capped at 16k JSON chars per span.
1300
+ */
1301
+ attributes: zod.z.record(zod.z.string(), zod.z.unknown()).optional().refine((v) => v === void 0 || JSON.stringify(v).length <= 16e3, {
1302
+ message: "attributes exceed 16k JSON chars \u2014 spans are telemetry, not blob storage"
1303
+ }),
1304
+ /**
1305
+ * Caller-local span id, unique within the batch. Exists only so sibling
1306
+ * spans can name this span as their parentSpanId; never stored (the DB
1307
+ * assigns the real uuid).
1308
+ */
1309
+ spanId: zod.z.string().min(1).optional(),
1310
+ /**
1311
+ * Caller-local reference to another span's `spanId` IN THE SAME BATCH (NOT
1312
+ * a database uuid). The worker wires spans.parent_span_id when the parent
1313
+ * resolves within the batch, stores null otherwise.
1314
+ */
1315
+ parentSpanId: zod.z.string().min(1).optional()
1316
+ });
1317
+ var SpansBatchSchema = zod.z.object({
1318
+ /** Spans are self-addressed: a batch may span sessions/deployments. */
1319
+ spans: zod.z.array(SpanInputSchema).min(1).max(50),
1320
+ alignment: AlignmentProvenanceSchema
1321
+ });
1322
+ var DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
1323
+ var DEFINITION_VALUE = zod.z.string().trim().min(1).max(64);
1324
+ zod.z.object({
1325
+ /** Measurement family the definition belongs to (e.g. 'voice-conformance'). */
1326
+ family: zod.z.string().regex(DEFINITION_SLUG, "family must be a lowercase slug (a-z, 0-9, _-)."),
1327
+ /** Slug within the family. family+name identifies the definition across versions. */
1328
+ name: zod.z.string().regex(DEFINITION_SLUG, "name must be a lowercase slug (a-z, 0-9, _-)."),
1329
+ /** The elicitation prompt — the queue row's plain-language question. */
1330
+ question: zod.z.string().trim().min(1).max(280),
1331
+ /** Difference metric for α (Krippendorff). Elicit v1: nominal | ordinal. */
1332
+ metric: zod.z.enum(["nominal", "ordinal"]),
1333
+ /** The chips (closed vocabulary the rater chooses from). */
1334
+ values: zod.z.array(DEFINITION_VALUE).min(2, "A rubric needs at least two chips.").max(9, "The queue is keyboard-first \u2014 at most 9 chips."),
1335
+ /** Rank order (lowest first) — required iff metric is 'ordinal'. */
1336
+ ordinalScale: zod.z.array(DEFINITION_VALUE).min(2).max(9).optional()
1337
+ }).refine((input) => new Set(input.values).size === input.values.length, {
1338
+ message: "Chips must be unique.",
1339
+ path: ["values"]
1340
+ }).superRefine((input, ctx) => {
1341
+ if (input.metric === "ordinal") {
1342
+ const scale = input.ordinalScale;
1343
+ if (!scale) {
1344
+ ctx.addIssue({
1345
+ code: zod.z.ZodIssueCode.custom,
1346
+ message: "ordinalScale is required when metric is ordinal.",
1347
+ path: ["ordinalScale"]
1348
+ });
1349
+ return;
1350
+ }
1351
+ const same = scale.length === input.values.length && [...scale].sort().join("") === [...input.values].sort().join("");
1352
+ if (!same) {
1353
+ ctx.addIssue({
1354
+ code: zod.z.ZodIssueCode.custom,
1355
+ message: "ordinalScale must be exactly the chips in rank order (lowest first).",
1356
+ path: ["ordinalScale"]
1357
+ });
1358
+ }
1359
+ }
1360
+ });
1219
1361
  zod.z.object({
1220
1362
  deploymentSlug: zod.z.string().min(1),
1221
1363
  sessionExternalId: zod.z.string().min(1),
@@ -1237,6 +1379,10 @@ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
1237
1379
  clock_source: "sdk",
1238
1380
  rule_version: "v1"
1239
1381
  };
1382
+ var DEFAULT_SPAN_ALIGNMENT = {
1383
+ clock_source: "sdk",
1384
+ rule_version: "v1"
1385
+ };
1240
1386
  var state = null;
1241
1387
  var Probe = class {
1242
1388
  /**
@@ -1245,7 +1391,7 @@ var Probe = class {
1245
1391
  */
1246
1392
  static init(config) {
1247
1393
  if (state !== null) {
1248
- console.warn("[probe] already initialized; call shutdown() first");
1394
+ console.warn("[sight] already initialized; call shutdown() first");
1249
1395
  return;
1250
1396
  }
1251
1397
  const validated = ProbeConfigSchema.parse(config);
@@ -1283,7 +1429,7 @@ var Probe = class {
1283
1429
  */
1284
1430
  static async withSession(sessionId, fn) {
1285
1431
  if (state === null) {
1286
- console.warn("[probe] withSession called before init");
1432
+ console.warn("[sight] withSession called before init");
1287
1433
  return fn();
1288
1434
  }
1289
1435
  return withSession(sessionId, fn);
@@ -1295,7 +1441,7 @@ var Probe = class {
1295
1441
  */
1296
1442
  static identifyPersona(persona) {
1297
1443
  if (state === null) {
1298
- console.warn("[probe] identifyPersona called before init");
1444
+ console.warn("[sight] identifyPersona called before init");
1299
1445
  return;
1300
1446
  }
1301
1447
  state.persona = persona;
@@ -1318,7 +1464,7 @@ var Probe = class {
1318
1464
  */
1319
1465
  static startSession(input) {
1320
1466
  if (state === null) {
1321
- console.warn("[probe] startSession called before init");
1467
+ console.warn("[sight] startSession called before init");
1322
1468
  return;
1323
1469
  }
1324
1470
  const validated = SessionStartSchema.parse(input);
@@ -1389,7 +1535,7 @@ var Probe = class {
1389
1535
  * for the diff table axis (a card keyed by a3f9c2… is unreadable).
1390
1536
  *
1391
1537
  * Ships as a helper because inconsistent hashing across restarts breaks
1392
- * Chapter 8e′ Card 3 (version behavioral diff) — every customer would
1538
+ * The version behavioral diff — every customer would
1393
1539
  * hash their own way and version-diff would become noise.
1394
1540
  *
1395
1541
  * The same hashing (src/hash.ts) backs the OTel processor's automatic
@@ -1421,7 +1567,18 @@ var Probe = class {
1421
1567
  if (state === null) return;
1422
1568
  const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
1423
1569
  const endedReason = typeof externalId === "string" ? void 0 : externalId.endedReason;
1424
- if (state.outcomeHook) {
1570
+ const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
1571
+ if (declared) {
1572
+ await this.emitOutcomeEvent({
1573
+ sessionExternalId: externalIdStr,
1574
+ kind: declared,
1575
+ detail: {
1576
+ declaredAt: "endSession",
1577
+ ...typeof externalId === "object" && externalId.outcomeDetail ? externalId.outcomeDetail : {}
1578
+ }
1579
+ });
1580
+ }
1581
+ if (!declared && state.outcomeHook) {
1425
1582
  try {
1426
1583
  const result = await state.outcomeHook.resolve(externalIdStr);
1427
1584
  if (result && state !== null) {
@@ -1437,7 +1594,7 @@ var Probe = class {
1437
1594
  }
1438
1595
  } catch (err) {
1439
1596
  console.warn(
1440
- "[probe] outcome hook resolve failed:",
1597
+ "[sight] outcome hook resolve failed:",
1441
1598
  err instanceof Error ? err.message : err
1442
1599
  );
1443
1600
  }
@@ -1445,12 +1602,12 @@ var Probe = class {
1445
1602
  if (state === null) return;
1446
1603
  if (endedReason) {
1447
1604
  await state.client.sendSessionEnd(state.config.deployment, { externalId: externalIdStr, endedReason }).catch((err) => {
1448
- console.warn("[probe] sendSessionEnd failed:", err instanceof Error ? err.message : err);
1605
+ console.warn("[sight] sendSessionEnd failed:", err instanceof Error ? err.message : err);
1449
1606
  });
1450
1607
  }
1451
1608
  state.sessions.delete(externalIdStr);
1452
1609
  }
1453
- // ── User-side helpers (P1 per PLAN-2026-07-11) ─────────────────────────
1610
+ // ── User-side helpers ──────────────────────────────────────────────────
1454
1611
  // These accumulate user-side signals during a turn; captureTurn folds the
1455
1612
  // accumulated state into TurnInput.userInput / userOutcome before send.
1456
1613
  // Signals that arrive before any session entry exists (typing starts
@@ -1543,7 +1700,7 @@ var Probe = class {
1543
1700
  */
1544
1701
  static wireOutcomeHook(hook) {
1545
1702
  if (state === null) {
1546
- console.warn("[probe] wireOutcomeHook called before init");
1703
+ console.warn("[sight] wireOutcomeHook called before init");
1547
1704
  return;
1548
1705
  }
1549
1706
  state.outcomeHook = hook;
@@ -1574,7 +1731,7 @@ var Probe = class {
1574
1731
  const contract = validatePropensityContract(propensity);
1575
1732
  if (!contract.ok) {
1576
1733
  console.warn(
1577
- `[probe] Amendment S contract violation (${contract.class}): ${contract.reason}`
1734
+ `[sight] propensity contract violation (${contract.class}): ${contract.reason}`
1578
1735
  );
1579
1736
  turn.payload.propensity = void 0;
1580
1737
  validPropensity = void 0;
@@ -1673,7 +1830,7 @@ var Probe = class {
1673
1830
  propensity: validPropensity,
1674
1831
  // Forward RLDS provenance from the local session entry (populated
1675
1832
  // by Probe.startSession). Worker persists at first-turn session
1676
- // create; nulls stay null. Amendment R populater 2026-07-11.
1833
+ // create; nulls stay null.
1677
1834
  agentId: session.agentId ?? void 0,
1678
1835
  experimentId: session.experimentId ?? void 0,
1679
1836
  environmentConfigHash: session.environmentConfigHash ?? void 0,
@@ -1682,7 +1839,7 @@ var Probe = class {
1682
1839
  }
1683
1840
  /**
1684
1841
  * Emit a custom outcome event on a session. Populates probe_outcome_events
1685
- * with the customer-supplied `kind` string (Amendment I Method D). Use for
1842
+ * with the customer-supplied `kind` string. Use for
1686
1843
  * customer-defined kinds like "purchase_complete", "handoff_to_human",
1687
1844
  * "character_break_severe". Universal seed kinds (break, escalation,
1688
1845
  * resolution, thumbs_*, rating_*) are also emitted by worker-side
@@ -1691,14 +1848,14 @@ var Probe = class {
1691
1848
  */
1692
1849
  static async emitOutcomeEvent(input) {
1693
1850
  if (state === null) {
1694
- console.warn("[probe] emitOutcomeEvent called before init");
1851
+ console.warn("[sight] emitOutcomeEvent called before init");
1695
1852
  return;
1696
1853
  }
1697
1854
  const validated = OutcomeEventEmitSchema.parse(input);
1698
1855
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
1699
1856
  }
1700
1857
  /**
1701
- * Capture one environment event against a session (Arc D-rail). The
1858
+ * Capture one environment event against a session. The
1702
1859
  * envelope is generalized: `source_type` and `event` are free strings whose
1703
1860
  * meaning is defined per deployment — the instrument stores the event and
1704
1861
  * attaches it to the session's record by time (the next turn's state
@@ -1712,7 +1869,7 @@ var Probe = class {
1712
1869
  */
1713
1870
  static async captureEnvironmentEvent(event, alignment) {
1714
1871
  if (state === null) {
1715
- console.warn("[probe] captureEnvironmentEvent called before init");
1872
+ console.warn("[sight] captureEnvironmentEvent called before init");
1716
1873
  return;
1717
1874
  }
1718
1875
  const validated = EnvironmentEventInputSchema.parse(event);
@@ -1728,23 +1885,63 @@ var Probe = class {
1728
1885
  */
1729
1886
  static async captureEnvironmentEvents(events, alignment) {
1730
1887
  if (state === null) {
1731
- console.warn("[probe] captureEnvironmentEvents called before init");
1888
+ console.warn("[sight] captureEnvironmentEvents called before init");
1732
1889
  return;
1733
1890
  }
1734
1891
  const batch = EnvironmentEventsBatchSchema.parse({ events, alignment });
1735
1892
  await state.client.sendEnvironmentEvents(batch);
1736
1893
  }
1894
+ /**
1895
+ * Capture one sub-turn span against a session: one LLM call, one tool
1896
+ * call, one framework step, or a custom unit inside a turn. The span lands
1897
+ * on the turn named by `turnIndex`, or — when omitted — on the session's
1898
+ * latest turn at/under the span's `startedAt` (most recent turn when
1899
+ * `startedAt` is also absent). A span whose turn cannot be resolved is
1900
+ * dropped server-side; spans never land unattributed. Fire-and-log, like
1901
+ * captureTurn: errors are debug-logged, never thrown.
1902
+ *
1903
+ * `attributes` are metadata only (tool names, argument shapes) — never
1904
+ * free-text conversation content. Alignment defaults to the SDK's own
1905
+ * clock claim; deployments with a stricter clock contract (or batches, or
1906
+ * parent references between spans) should call captureSpans.
1907
+ */
1908
+ static async captureSpan(span, alignment) {
1909
+ if (state === null) {
1910
+ console.warn("[sight] captureSpan called before init");
1911
+ return;
1912
+ }
1913
+ const validated = SpanInputSchema.parse(span);
1914
+ const align = alignment ? AlignmentProvenanceSchema.parse(alignment) : DEFAULT_SPAN_ALIGNMENT;
1915
+ await state.client.sendSpans({ spans: [validated], alignment: align });
1916
+ }
1917
+ /**
1918
+ * Capture a batch of spans with explicit alignment provenance
1919
+ * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50
1920
+ * spans and may span sessions — every span is self-addressed. Parent
1921
+ * structure rides the batch: a span's `parentSpanId` names another span's
1922
+ * caller-local `spanId` within the same batch and is wired server-side
1923
+ * (unresolvable references land null). Same fire-and-log discipline as the
1924
+ * single-span capture above.
1925
+ */
1926
+ static async captureSpans(spans, alignment) {
1927
+ if (state === null) {
1928
+ console.warn("[sight] captureSpans called before init");
1929
+ return;
1930
+ }
1931
+ const batch = SpansBatchSchema.parse({ spans, alignment });
1932
+ await state.client.sendSpans(batch);
1933
+ }
1737
1934
  /**
1738
1935
  * Flag a persona break for a session. Wire this to the customer's in-product
1739
1936
  * "that didn't sound like you" UX. Populates the `user_flagged_break`
1740
- * outcome column in Chapter 9c.
1937
+ * outcome column on the dashboard.
1741
1938
  *
1742
1939
  * If `turnIndex` is omitted, the flag attaches to the session's most
1743
1940
  * recent turn.
1744
1941
  */
1745
1942
  static async flagPersonaBreak(input) {
1746
1943
  if (state === null) {
1747
- console.warn("[probe] flagPersonaBreak called before init");
1944
+ console.warn("[sight] flagPersonaBreak called before init");
1748
1945
  return;
1749
1946
  }
1750
1947
  const validated = FlagPersonaBreakSchema.parse(input);