@wildorder/nightshift 0.16.0 → 0.17.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 (50) hide show
  1. package/README.md +20 -0
  2. package/dist/agent-runner.d.ts +56 -4
  3. package/dist/agent-runner.d.ts.map +1 -1
  4. package/dist/agent-runner.js +253 -28
  5. package/dist/agent-runner.js.map +1 -1
  6. package/dist/author.d.ts +8 -0
  7. package/dist/author.d.ts.map +1 -1
  8. package/dist/author.js +84 -57
  9. package/dist/author.js.map +1 -1
  10. package/dist/causal-analysis.d.ts +212 -0
  11. package/dist/causal-analysis.d.ts.map +1 -0
  12. package/dist/causal-analysis.js +733 -0
  13. package/dist/causal-analysis.js.map +1 -0
  14. package/dist/decider-review.d.ts +6 -1
  15. package/dist/decider-review.d.ts.map +1 -1
  16. package/dist/decider-review.js +19 -7
  17. package/dist/decider-review.js.map +1 -1
  18. package/dist/index.d.ts +5 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +5 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/preflight.d.ts +3 -0
  23. package/dist/preflight.d.ts.map +1 -1
  24. package/dist/preflight.js +73 -57
  25. package/dist/preflight.js.map +1 -1
  26. package/dist/prompt-telemetry.d.ts +64 -0
  27. package/dist/prompt-telemetry.d.ts.map +1 -0
  28. package/dist/prompt-telemetry.js +112 -0
  29. package/dist/prompt-telemetry.js.map +1 -0
  30. package/dist/provider-telemetry.d.ts +106 -0
  31. package/dist/provider-telemetry.d.ts.map +1 -0
  32. package/dist/provider-telemetry.js +423 -0
  33. package/dist/provider-telemetry.js.map +1 -0
  34. package/dist/run-analytics-report.d.ts +173 -0
  35. package/dist/run-analytics-report.d.ts.map +1 -0
  36. package/dist/run-analytics-report.js +650 -0
  37. package/dist/run-analytics-report.js.map +1 -0
  38. package/dist/run-analytics.d.ts +738 -0
  39. package/dist/run-analytics.d.ts.map +1 -0
  40. package/dist/run-analytics.js +545 -0
  41. package/dist/run-analytics.js.map +1 -0
  42. package/dist/run-program.d.ts +69 -1
  43. package/dist/run-program.d.ts.map +1 -1
  44. package/dist/run-program.js +1254 -714
  45. package/dist/run-program.js.map +1 -1
  46. package/dist/whole-program-review.d.ts +3 -0
  47. package/dist/whole-program-review.d.ts.map +1 -1
  48. package/dist/whole-program-review.js +8 -1
  49. package/dist/whole-program-review.js.map +1 -1
  50. package/package.json +2 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-analytics.d.ts","sourceRoot":"","sources":["../src/run-analytics.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;GAQG;AAEH,iFAAiF;AACjF,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,iFAAiF;AACjF,eAAO,MAAM,OAAO,iMAWV,CAAC;AAEX,eAAO,MAAM,YAAY;;;;;;;;;;;EAAkB,CAAC;AAC5C,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAElD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCkB,CAAC;AAE5C,MAAM,MAAM,KAAK,GAAG,MAAM,OAAO,YAAY,CAAC;AAG9C,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAiB,CAAC;AAE1C,mHAAmH;AACnH,eAAO,MAAM,eAAe,iEAAkE,CAAC;AAC/F,eAAO,MAAM,cAAc;;;;;EAA0B,CAAC;AACtD,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAEtD;;;;;GAKG;AACH,eAAO,MAAM,cAAc,gFAOjB,CAAC;AAEX,8GAA8G;AAC9G,eAAO,MAAM,uBAAuB;;;;;;;;;;iBAKlC,CAAC;AACH,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,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0 +1,545 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { z } from "zod";
5
+ /**
6
+ * The versioned, provider-neutral run-observation contract (WS-01). This
7
+ * module defines the schema, the stage-to-bucket mapping, the injectable
8
+ * clock, the recorder, and the atomic persistence boundary — it emits no
9
+ * per-stage spans of its own beyond a handful of reference spans proving the
10
+ * API end-to-end (see the WS-01/WS-02 emission-boundary decision). WS-02
11
+ * instruments the full run lifecycle against this contract; WS-03 attaches
12
+ * provider/prompt facts; WS-04 aggregates; WS-05 interprets.
13
+ */
14
+ /** Bumped only when the shape of the finalized artifact changes incompatibly. */
15
+ export const RUN_ANALYTICS_SCHEMA_VERSION = 1;
16
+ /** The closed top-level attribution taxonomy — a new bucket is a plan change. */
17
+ export const BUCKETS = [
18
+ "preflight",
19
+ "authoring",
20
+ "implementation",
21
+ "verification",
22
+ "review-and-decisions",
23
+ "recovery-and-fixes",
24
+ "git-and-persistence",
25
+ "whole-program-review",
26
+ "reporting",
27
+ "unattributed",
28
+ ];
29
+ export const bucketSchema = z.enum(BUCKETS);
30
+ /**
31
+ * The closed set of concrete operations, each mapping to exactly one bucket.
32
+ * WS-02 emits stages; WS-04 reads buckets; both import this exact table so
33
+ * they cannot drift ("same stage, different bucket" is closed by
34
+ * construction). Bar one exception, there is no `unattributed` stage:
35
+ * `unattributed` is normally a residual WS-04 computes as elapsed time minus
36
+ * the union of known top-level spans, never emitted by an instrumentation
37
+ * site. The exception is `"run"` itself (below) — a single, WS-01-owned span
38
+ * opened once per run, never an ad hoc WS-02 filler, whose entire purpose is
39
+ * to prove full temporal coverage from run start onward by parenting every
40
+ * other span; once WS-04 subtracts the union of its children, what remains
41
+ * of its own duration is, by construction, exactly the residual its bucket
42
+ * already names.
43
+ */
44
+ export const STAGE_BUCKET = {
45
+ run: "unattributed",
46
+ "prerequisite-check": "preflight",
47
+ "baseline-verification": "preflight",
48
+ author: "authoring",
49
+ "re-author": "authoring",
50
+ "spec-critique": "authoring",
51
+ implementer: "implementation",
52
+ recovery: "implementation",
53
+ "informed-retry": "implementation",
54
+ "verification-command": "verification",
55
+ "test-critique": "review-and-decisions",
56
+ "decision-review": "review-and-decisions",
57
+ "finding-triage": "review-and-decisions",
58
+ "causal-analysis": "review-and-decisions",
59
+ "failure-diagnosis": "recovery-and-fixes",
60
+ "fix-now": "recovery-and-fixes",
61
+ "test-critique-fix": "recovery-and-fixes",
62
+ "manifest-persist": "git-and-persistence",
63
+ "ledger-persist": "git-and-persistence",
64
+ "analytics-persist": "git-and-persistence",
65
+ "git-diff": "git-and-persistence",
66
+ "git-commit": "git-and-persistence",
67
+ "whole-program-review": "whole-program-review",
68
+ "as-built-snapshot": "whole-program-review",
69
+ "report-assembly": "reporting",
70
+ "report-commit": "reporting",
71
+ };
72
+ const STAGES = Object.keys(STAGE_BUCKET);
73
+ export const stageSchema = z.enum(STAGES);
74
+ /** The observability label every measurement carries; absent telemetry is `unavailable`, never a measured zero. */
75
+ export const COVERAGE_VALUES = ["observed", "estimated", "unavailable", "incomplete"];
76
+ export const coverageSchema = z.enum(COVERAGE_VALUES);
77
+ /**
78
+ * Documented, non-exhaustive outcome vocabulary (SC-04): `outcome` is an open
79
+ * `z.string()` so a future outcome (e.g. a timeout) can be added without a
80
+ * schema version bump. This is documentation and a lint target, never a gate
81
+ * — an unknown outcome string still validates and round-trips.
82
+ */
83
+ export const KNOWN_OUTCOMES = [
84
+ "success",
85
+ "failed",
86
+ "discarded",
87
+ "no-op",
88
+ "skipped",
89
+ "interrupted",
90
+ ];
91
+ /** The only evidence locality WS-01 defines: a build-logs reference resolves only on the machine that ran. */
92
+ export const evidenceReferenceSchema = z.object({
93
+ kind: z.enum(["transcript", "ledger-event", "commit", "diagnosis"]),
94
+ locality: z.literal("local"),
95
+ ref: z.string(),
96
+ note: z.string().optional(),
97
+ });
98
+ const agentRoleSchema = z.enum([
99
+ "agent",
100
+ "recoveryAgent",
101
+ "authorAgent",
102
+ "deciderAgent",
103
+ "reviewerAgent",
104
+ ]);
105
+ /** The stable facts attached to an interval or point. Provider/model identity is deliberately absent — WS-03's sole home. */
106
+ export const dimensionsSchema = z.object({
107
+ stage: stageSchema,
108
+ workstream: z.string().optional(),
109
+ role: agentRoleSchema.optional(),
110
+ attemptSeat: z.string().optional(),
111
+ attemptIndex: z.number().optional(),
112
+ attemptReason: z.string().optional(),
113
+ verifyCommand: z.string().optional(),
114
+ outcome: z.string().optional(),
115
+ evidence: z.array(evidenceReferenceSchema).optional(),
116
+ });
117
+ const partialDimensionsSchema = dimensionsSchema.partial();
118
+ /**
119
+ * An interval observation — the unit that carries wall-clock time. The
120
+ * schema permits overlapping spans (a parent and its children overlap by
121
+ * construction); WS-01 validates only the local invariants (bucket matches
122
+ * stage, end >= start when present, parentId resolves within the artifact).
123
+ * WS-04 owns interval-union conservation and rejecting double-counted
124
+ * overlaps at the top level.
125
+ */
126
+ export const spanSchema = z
127
+ .object({
128
+ id: z.string(),
129
+ parentId: z.string().optional(),
130
+ stage: stageSchema,
131
+ bucket: bucketSchema,
132
+ startOffsetMs: z.number(),
133
+ /**
134
+ * Absent means this span's true end was not observed by finalize time.
135
+ * Usually that is a crashed/interrupted span, but the runner's own
136
+ * top-level `run` span and its `report-commit` child are open by design
137
+ * on every run, crashed or not: both close only after `finalize()` has
138
+ * already persisted this very artifact, so their real end can never be
139
+ * captured inside the file they are committed in.
140
+ */
141
+ endOffsetMs: z.number().optional(),
142
+ dimensions: dimensionsSchema,
143
+ })
144
+ .refine((span) => STAGE_BUCKET[span.stage] === span.bucket, {
145
+ message: "bucket must equal STAGE_BUCKET[stage]",
146
+ path: ["bucket"],
147
+ })
148
+ .refine((span) => span.endOffsetMs === undefined || span.endOffsetMs >= span.startOffsetMs, { message: "endOffsetMs must be >= startOffsetMs", path: ["endOffsetMs"] });
149
+ /**
150
+ * A fact measured at an instant, not an interval. `kind` is an open string
151
+ * for the same forward-compatibility reason as `outcome`.
152
+ *
153
+ * `label` and `detail` are WS-03's sole, additive amendment to this schema
154
+ * (see the `scalar-points-plus-additive-fields` decision): `label` names the
155
+ * specific metric or prompt component a point measures (e.g.
156
+ * `"input-tokens"`, `"model"`, `"roster"`), and `detail` carries a
157
+ * string-valued fact — an exact model identity, a provider label, a
158
+ * comma-joined demoted-dependency id list — when the measurement is not
159
+ * numeric. Both are optional and unconstrained by an enum, so every existing
160
+ * point (and every WS-01 fixture) round-trips unchanged.
161
+ */
162
+ export const pointObservationSchema = z.object({
163
+ id: z.string(),
164
+ atOffsetMs: z.number(),
165
+ kind: z.string(),
166
+ coverage: coverageSchema,
167
+ value: z.number().optional(),
168
+ unit: z.string().optional(),
169
+ label: z.string().optional(),
170
+ detail: z.string().optional(),
171
+ dimensions: partialDimensionsSchema.optional(),
172
+ evidence: z.array(evidenceReferenceSchema).optional(),
173
+ });
174
+ /**
175
+ * States the window the reconciled numbers cover: run start through the
176
+ * pre-render analytics snapshot taken just before `finalize()` persists this
177
+ * artifact and the report is written and committed (SC-03, SC-14). The
178
+ * report-write/commit tail is unobservable from inside the artifact — the
179
+ * `run` and `report-commit` spans stay open and the tail lands as a sidecar
180
+ * point — and publish runs after the CLI's run call returns. Adopted by
181
+ * human ruling (decisions 062f9cc308fe22fa, 987817d69c457259).
182
+ */
183
+ export const AGGREGATION_BOUNDARY = "run-start-to-pre-render-snapshot";
184
+ export const runAnalyticsSchema = z
185
+ .object({
186
+ // A literal, not z.number(): SC-01 promises one validated versioned
187
+ // contract, so an artifact stamped with any other schemaVersion — an
188
+ // unsupported future format, a corrupted file, a stale format after a
189
+ // real bump — fails validation outright rather than silently parsing as
190
+ // if it were this version. readPriorRunId relies on exactly this to
191
+ // never adopt lineage from a schema it does not understand.
192
+ schemaVersion: z.literal(RUN_ANALYTICS_SCHEMA_VERSION),
193
+ identity: z.object({
194
+ runId: z.string(),
195
+ parentRunId: z.string().optional(),
196
+ programId: z.string(),
197
+ }),
198
+ anchors: z.object({
199
+ startedAt: z.string(),
200
+ monotonicAnchorMs: z.number(),
201
+ finalizedAt: z.string().optional(),
202
+ finalizedOffsetMs: z.number().optional(),
203
+ }),
204
+ aggregationBoundary: z.literal(AGGREGATION_BOUNDARY),
205
+ spans: z.array(spanSchema),
206
+ points: z.array(pointObservationSchema),
207
+ })
208
+ .superRefine((artifact, ctx) => {
209
+ const ids = new Set(artifact.spans.map((span) => span.id));
210
+ artifact.spans.forEach((span, index) => {
211
+ if (span.parentId !== undefined && !ids.has(span.parentId)) {
212
+ ctx.addIssue({
213
+ code: z.ZodIssueCode.custom,
214
+ message: `parentId "${span.parentId}" does not resolve to another span in this artifact`,
215
+ path: ["spans", index, "parentId"],
216
+ });
217
+ }
218
+ });
219
+ });
220
+ /** Mirrors `runReportPath` — the one canonical location for a program's analytics artifact. */
221
+ export function runAnalyticsPath(root, programId) {
222
+ return join(resolve(root), "docs", "programs", `${programId}-run-analytics.json`);
223
+ }
224
+ /** The gitignored crash-durability sidecar (see the incremental-durability decision); never read back by this module. */
225
+ function runAnalyticsSidecarPath(root, programId) {
226
+ return join(resolve(root), "build-logs", programId, "run-analytics.jsonl");
227
+ }
228
+ function randomId() {
229
+ return randomBytes(8).toString("hex");
230
+ }
231
+ /**
232
+ * Write-temp-then-rename in the same directory as the target. Same-directory
233
+ * rename is atomic on POSIX and, via libuv's `MOVEFILE_REPLACE_EXISTING`,
234
+ * replaces atomically on Windows too — a crash mid-write can never leave a
235
+ * half-written artifact; a reader sees either the old file or the new one.
236
+ */
237
+ async function atomicWriteFile(path, contents) {
238
+ await mkdir(dirname(path), { recursive: true });
239
+ const tmp = join(dirname(path), `.${randomId()}.tmp-${randomId()}`);
240
+ await writeFile(tmp, contents, "utf8");
241
+ try {
242
+ await rename(tmp, path);
243
+ }
244
+ catch (error) {
245
+ // A failed rename must never leave an orphaned temp file behind for a
246
+ // later `docs/programs` commit to sweep up as an untracked artifact.
247
+ await rm(tmp, { force: true }).catch(() => undefined);
248
+ throw error;
249
+ }
250
+ }
251
+ /**
252
+ * Reads any prior finalized artifact for `programId` purely to source
253
+ * `parentRunId` — a plain read with no durable effect, safe before the
254
+ * could-not-start gate. Absent, unreadable, or invalid prior artifacts all
255
+ * resolve to `undefined` (fail open): a missing lineage is not a reason to
256
+ * fail a run.
257
+ */
258
+ export async function readPriorRunId(root, programId) {
259
+ try {
260
+ const raw = await readFile(runAnalyticsPath(root, programId), "utf8");
261
+ const parsed = runAnalyticsSchema.safeParse(JSON.parse(raw));
262
+ return parsed.success ? parsed.data.identity.runId : undefined;
263
+ }
264
+ catch {
265
+ return undefined;
266
+ }
267
+ }
268
+ /**
269
+ * Records a run's spans and point observations and persists them
270
+ * fail-open. Created at run start so pre-gate stages (preflight, baseline
271
+ * verification) can be buffered in memory; stays disarmed — writing nothing
272
+ * durable — until `arm()` is called immediately after the could-not-start
273
+ * gate. Every method is non-throwing: a malformed observation is diagnosed
274
+ * and dropped, a persistence failure is diagnosed and swallowed, and nothing
275
+ * here can change a run's outcome, exit code, status, or report.
276
+ */
277
+ export class RunRecorder {
278
+ runId;
279
+ clock;
280
+ root;
281
+ programId;
282
+ parentRunIdValue;
283
+ log;
284
+ monotonicAnchorMs;
285
+ startedAt;
286
+ permanentlyDisarmed;
287
+ armed = false;
288
+ finalized = false;
289
+ spans = [];
290
+ points = [];
291
+ openStack = [];
292
+ sidecarQueue = Promise.resolve();
293
+ constructor(opts) {
294
+ this.clock = opts.clock;
295
+ this.root = opts.root;
296
+ this.programId = opts.programId;
297
+ this.parentRunIdValue = opts.parentRunId;
298
+ this.log = opts.log;
299
+ this.permanentlyDisarmed = opts.permanentlyDisarmed ?? false;
300
+ this.startedAt = opts.clock.now().toISOString();
301
+ this.runId = this.startedAt;
302
+ this.monotonicAnchorMs = opts.clock.monotonic();
303
+ }
304
+ static create(opts) {
305
+ return new RunRecorder(opts);
306
+ }
307
+ /**
308
+ * Enables durable writes. Idempotent; intended to be called once,
309
+ * immediately after the could-not-start gate. A no-op on a
310
+ * permanently-disarmed instance ({@link NOOP_RUN_RECORDER}) — WS-02's
311
+ * `RunProgramOptions.recorder` test seam lets a caller inject that shared
312
+ * singleton straight into a real run, and `runProgramWith` calls `arm()`
313
+ * unconditionally on whatever recorder it holds, so this guard is what
314
+ * keeps that injection from durably arming — and thereby writing through
315
+ * — the one instance every other no-recorder caller also depends on
316
+ * staying inert.
317
+ */
318
+ arm() {
319
+ if (this.permanentlyDisarmed)
320
+ return;
321
+ this.armed = true;
322
+ }
323
+ /** Opens a span; the currently open span (if any) becomes its parent automatically. */
324
+ span(dims) {
325
+ return this.openSpan(dims, this.openStack[this.openStack.length - 1]?.id);
326
+ }
327
+ point(obs) {
328
+ try {
329
+ const point = {
330
+ id: randomId(),
331
+ atOffsetMs: this.elapsedMs(),
332
+ kind: obs.kind,
333
+ coverage: obs.coverage,
334
+ ...(obs.value === undefined ? {} : { value: obs.value }),
335
+ ...(obs.unit === undefined ? {} : { unit: obs.unit }),
336
+ ...(obs.label === undefined ? {} : { label: obs.label }),
337
+ ...(obs.detail === undefined ? {} : { detail: obs.detail }),
338
+ ...(obs.dimensions === undefined ? {} : { dimensions: obs.dimensions }),
339
+ ...(obs.evidence === undefined ? {} : { evidence: obs.evidence }),
340
+ };
341
+ const parsed = pointObservationSchema.safeParse(point);
342
+ if (!parsed.success) {
343
+ this.diagnose(`dropped malformed point observation: ${parsed.error.message}`);
344
+ return;
345
+ }
346
+ this.points.push(parsed.data);
347
+ this.appendSidecar({ kind: "point", point: parsed.data });
348
+ }
349
+ catch (error) {
350
+ this.diagnose(`point record failed: ${error.message}`);
351
+ }
352
+ }
353
+ /**
354
+ * Builds the in-memory buffer (including any span still open — a
355
+ * crashed/interrupted span composes with no `endOffsetMs`) into a
356
+ * `RunAnalytics` shape at the given wall/monotonic instant. Shared by
357
+ * `finalize()` (which persists the result) and `snapshot()` (which does
358
+ * not), so the two can never independently drift on what "the observed
359
+ * artifact so far" means.
360
+ */
361
+ compose(finalizedAt, finalizedOffsetMs) {
362
+ return {
363
+ schemaVersion: RUN_ANALYTICS_SCHEMA_VERSION,
364
+ identity: {
365
+ runId: this.runId,
366
+ ...(this.parentRunIdValue === undefined ? {} : { parentRunId: this.parentRunIdValue }),
367
+ programId: this.programId,
368
+ },
369
+ anchors: {
370
+ startedAt: this.startedAt,
371
+ monotonicAnchorMs: this.monotonicAnchorMs,
372
+ finalizedAt,
373
+ finalizedOffsetMs,
374
+ },
375
+ aggregationBoundary: AGGREGATION_BOUNDARY,
376
+ spans: [...this.spans, ...this.openSpanSnapshots()],
377
+ points: this.points,
378
+ };
379
+ }
380
+ /**
381
+ * Composes the in-memory buffer into a `RunAnalytics` object, validates
382
+ * it, and atomically persists it. Fail-open: never throws. A no-op when
383
+ * not armed, or when already finalized once.
384
+ */
385
+ async finalize() {
386
+ if (!this.armed || this.finalized)
387
+ return;
388
+ this.finalized = true;
389
+ try {
390
+ await this.sidecarQueue.catch(() => undefined);
391
+ const artifact = this.compose(this.clock.now().toISOString(), this.elapsedMs());
392
+ const parsed = runAnalyticsSchema.safeParse(artifact);
393
+ if (!parsed.success) {
394
+ this.diagnose(`analytics artifact failed validation and was not written: ${parsed.error.message}`);
395
+ return;
396
+ }
397
+ await atomicWriteFile(runAnalyticsPath(this.root, this.programId), `${JSON.stringify(parsed.data, null, 2)}\n`);
398
+ }
399
+ catch (error) {
400
+ this.diagnose(`analytics finalize failed: ${error.message}`);
401
+ }
402
+ }
403
+ /**
404
+ * A validated in-memory view of everything observed so far, for the run
405
+ * report's "Where the time went" section (WS-04) — which renders before
406
+ * `finalize()` runs, so it cannot read the file `finalize()` writes.
407
+ * Read-only: composes and validates exactly as `finalize()` does but
408
+ * writes nothing, to the canonical artifact or the sidecar, and is safe to
409
+ * call before `arm()`, after `finalize()`, or any number of times.
410
+ * Non-throwing; returns `undefined` on any failure (fail open).
411
+ */
412
+ snapshot() {
413
+ try {
414
+ const artifact = this.compose(this.clock.now().toISOString(), this.elapsedMs());
415
+ const parsed = runAnalyticsSchema.safeParse(artifact);
416
+ return parsed.success ? parsed.data : undefined;
417
+ }
418
+ catch {
419
+ return undefined;
420
+ }
421
+ }
422
+ elapsedMs() {
423
+ return this.clock.monotonic() - this.monotonicAnchorMs;
424
+ }
425
+ openSpan(dims, parentId) {
426
+ try {
427
+ const open = {
428
+ id: randomId(),
429
+ ...(parentId === undefined ? {} : { parentId }),
430
+ stage: dims.stage,
431
+ bucket: STAGE_BUCKET[dims.stage],
432
+ startOffsetMs: this.elapsedMs(),
433
+ dimensions: dims,
434
+ };
435
+ this.openStack.push(open);
436
+ let closed = false;
437
+ return {
438
+ close: (result) => {
439
+ if (closed)
440
+ return;
441
+ closed = true;
442
+ this.closeSpan(open, result);
443
+ },
444
+ child: (childDims) => this.openSpan(childDims, open.id),
445
+ };
446
+ }
447
+ catch (error) {
448
+ this.diagnose(`span open failed: ${error.message}`);
449
+ return this.inertHandle();
450
+ }
451
+ }
452
+ inertHandle() {
453
+ return { close: () => undefined, child: () => this.inertHandle() };
454
+ }
455
+ closeSpan(open, result) {
456
+ try {
457
+ const dimensions = {
458
+ ...open.dimensions,
459
+ ...(result?.outcome === undefined ? {} : { outcome: result.outcome }),
460
+ ...(result?.evidence === undefined ? {} : { evidence: result.evidence }),
461
+ };
462
+ const span = {
463
+ id: open.id,
464
+ ...(open.parentId === undefined ? {} : { parentId: open.parentId }),
465
+ stage: open.stage,
466
+ bucket: open.bucket,
467
+ startOffsetMs: open.startOffsetMs,
468
+ endOffsetMs: this.elapsedMs(),
469
+ dimensions,
470
+ };
471
+ const parsed = spanSchema.safeParse(span);
472
+ if (!parsed.success) {
473
+ this.diagnose(`dropped malformed span: ${parsed.error.message}`);
474
+ }
475
+ else {
476
+ this.spans.push(parsed.data);
477
+ this.appendSidecar({ kind: "span", span: parsed.data });
478
+ }
479
+ }
480
+ catch (error) {
481
+ this.diagnose(`span close failed: ${error.message}`);
482
+ }
483
+ finally {
484
+ const index = this.openStack.indexOf(open);
485
+ if (index >= 0)
486
+ this.openStack.splice(index, 1);
487
+ }
488
+ }
489
+ openSpanSnapshots() {
490
+ return this.openStack.map((open) => ({
491
+ id: open.id,
492
+ ...(open.parentId === undefined ? {} : { parentId: open.parentId }),
493
+ stage: open.stage,
494
+ bucket: open.bucket,
495
+ startOffsetMs: open.startOffsetMs,
496
+ dimensions: open.dimensions,
497
+ }));
498
+ }
499
+ /**
500
+ * Appends one JSON line to the gitignored `build-logs/` sidecar — the
501
+ * crash-durability layer for a hard kill that never reaches the flush
502
+ * seam. Queued so concurrent closes/points never interleave partial
503
+ * writes; a failing append is diagnosed and never breaks the queue for
504
+ * subsequent appends.
505
+ */
506
+ appendSidecar(entry) {
507
+ if (!this.armed)
508
+ return;
509
+ const path = runAnalyticsSidecarPath(this.root, this.programId);
510
+ const line = `${JSON.stringify(entry)}\n`;
511
+ this.sidecarQueue = this.sidecarQueue.then(async () => {
512
+ await mkdir(dirname(path), { recursive: true });
513
+ await appendFile(path, line, "utf8");
514
+ });
515
+ this.sidecarQueue = this.sidecarQueue.catch((error) => {
516
+ this.diagnose(`sidecar append failed: ${error.message}`);
517
+ });
518
+ }
519
+ diagnose(message) {
520
+ try {
521
+ this.log(`run-analytics: ${message}`);
522
+ }
523
+ catch {
524
+ // Logging must never be the reason an analytics failure escapes fail-open.
525
+ }
526
+ }
527
+ }
528
+ /**
529
+ * A shared, permanently disarmed recorder — the default for callers that
530
+ * have no run-scoped recorder to hand (a standalone test, the doctor probe,
531
+ * a fix/critique path WS-02 has not yet wired), and a valid injection
532
+ * straight into `RunProgramOptions.recorder` (WS-02, SC-13) for a test that
533
+ * wants to prove fail-open by equivalence. Buffers harmlessly in memory and
534
+ * never performs I/O: `permanentlyDisarmed` makes `arm()` a no-op even when
535
+ * a real run calls it unconditionally, so this one shared instance can never
536
+ * be armed by any caller, ever.
537
+ */
538
+ export const NOOP_RUN_RECORDER = RunRecorder.create({
539
+ clock: { now: () => new Date(0), monotonic: () => 0 },
540
+ root: "",
541
+ programId: "",
542
+ log: () => undefined,
543
+ permanentlyDisarmed: true,
544
+ });
545
+ //# sourceMappingURL=run-analytics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-analytics.js","sourceRoot":"","sources":["../src/run-analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACtF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;GAQG;AAEH,iFAAiF;AACjF,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAE9C,iFAAiF;AACjF,MAAM,CAAC,MAAM,OAAO,GAAG;IACrB,WAAW;IACX,WAAW;IACX,gBAAgB;IAChB,cAAc;IACd,sBAAsB;IACtB,oBAAoB;IACpB,qBAAqB;IACrB,sBAAsB;IACtB,WAAW;IACX,cAAc;CACN,CAAC;AAEX,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAG5C;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,GAAG,EAAE,cAAc;IAEnB,oBAAoB,EAAE,WAAW;IACjC,uBAAuB,EAAE,WAAW;IAEpC,MAAM,EAAE,WAAW;IACnB,WAAW,EAAE,WAAW;IACxB,eAAe,EAAE,WAAW;IAE5B,WAAW,EAAE,gBAAgB;IAC7B,QAAQ,EAAE,gBAAgB;IAC1B,gBAAgB,EAAE,gBAAgB;IAElC,sBAAsB,EAAE,cAAc;IAEtC,eAAe,EAAE,sBAAsB;IACvC,iBAAiB,EAAE,sBAAsB;IACzC,gBAAgB,EAAE,sBAAsB;IACxC,iBAAiB,EAAE,sBAAsB;IAEzC,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