session-orchestrator 5.10.0 → 5.11.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 (55) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.cursor-plugin/plugin.json +1 -1
  5. package/AGENTS.md +2 -0
  6. package/CHANGELOG.md +32 -0
  7. package/README.md +9 -8
  8. package/SECURITY.md +1 -1
  9. package/agents/code-implementer.md +7 -1
  10. package/docs/agent-authoring.md +2 -0
  11. package/docs/events-schema.md +2 -1
  12. package/docs/fleet-checkin-audit.md +172 -0
  13. package/docs/role-profile-contract.md +139 -0
  14. package/docs/scope-collision-guard.md +3 -0
  15. package/docs/session-config-reference.md +1 -1
  16. package/evals/instruction-ablation/run.mjs +11 -6
  17. package/hooks/_lib/hook-import-set.json +27 -2
  18. package/hooks/_lib/orchestrator-ignore.mjs +112 -0
  19. package/hooks/hooks-codex.json +1 -1
  20. package/hooks/hooks.json +1 -1
  21. package/hooks/on-session-end.mjs +8 -1
  22. package/hooks/on-session-start.mjs +7 -0
  23. package/hooks/post-bash-write-verify.mjs +16 -3
  24. package/hooks/pre-task-scope-disjoint.mjs +12 -0
  25. package/hooks/subagent-telemetry.mjs +8 -3
  26. package/hooks/wave-scope-commit-guard.mjs +4 -1
  27. package/package.json +1 -1
  28. package/rules/opt-in-stack/security-web.md +1 -1
  29. package/scripts/emit-session.mjs +13 -0
  30. package/scripts/fleet-checkin-audit.mjs +138 -0
  31. package/scripts/lib/common.mjs +2 -4
  32. package/scripts/lib/context-overhead-format.mjs +57 -0
  33. package/scripts/lib/fleet-checkin-audit.mjs +244 -0
  34. package/scripts/lib/memory-proposals/sink.mjs +79 -17
  35. package/scripts/lib/memory-proposals/store.mjs +245 -9
  36. package/scripts/lib/project-hygiene.mjs +37 -0
  37. package/scripts/lib/role-profile/schema.mjs +219 -0
  38. package/scripts/lib/session-lock.mjs +57 -10
  39. package/scripts/lib/session-record-repair.mjs +63 -30
  40. package/scripts/lib/session-schema/constants.mjs +8 -0
  41. package/scripts/lib/session-schema/validator.mjs +33 -0
  42. package/scripts/lib/subagents-schema.mjs +9 -0
  43. package/scripts/lib/telemetry/pricing.mjs +11 -0
  44. package/scripts/measure-context-overhead.sh +4 -21
  45. package/scripts/release.mjs +359 -11
  46. package/scripts/run-quality-gate.mjs +47 -0
  47. package/scripts/validate-wave-scope.mjs +59 -6
  48. package/skills/claude-md-drift-check/checker.mjs +8 -6
  49. package/skills/npm-publish/SKILL.md +3 -3
  50. package/skills/release/SKILL.md +2 -2
  51. package/skills/repo-audit/SKILL.md +1 -1
  52. package/skills/session-end/metrics-collection.md +2 -2
  53. package/skills/session-end/session-metrics-write.md +1 -1
  54. package/skills/session-start/references/phase-1-2-session-lock.md +1 -1
  55. package/skills/wave-executor/circuit-breaker.md +1 -0
@@ -527,8 +527,10 @@ export function readLockDetailed(opts = {}) {
527
527
  * result — this keeps acquire() synchronous.
528
528
  *
529
529
  * Returns one of:
530
- * { ok: true, lock, exclusivityClass? }
531
- * — lock created
530
+ * { ok: true, lock, exclusivityClass?, ownerProof }
531
+ * — lock created. `ownerProof` reports the owner-proof rewrite that
532
+ * follows every successful lock write (#1541, see withOwnerProof()):
533
+ * `{ ok: true }` or `{ ok: false, reason }` — never thrown.
532
534
  * { ok: false, reason: 'active', existingLock, ageHours, exclusivityClass? }
533
535
  * — local lock held: its last_heartbeat is within ttl_hours. `ageHours`
534
536
  * is the age from `started_at` (null when unparseable). `existingLock`
@@ -777,7 +779,7 @@ export function acquire({ sessionId, mode, ttlHours = DEFAULT_TTL_HOURS, repoRoo
777
779
  const createResult = createSessionLockExclusive(lockFile, lock);
778
780
 
779
781
  if (createResult.ok) {
780
- return { ok: true, lock, exclusivityClass: callerClass };
782
+ return withOwnerProof({ ok: true, lock, exclusivityClass: callerClass }, repoRoot);
781
783
  }
782
784
  if (createResult.reason === 'fs-error') {
783
785
  return { ok: false, reason: 'fs-error', error: createResult.error, exclusivityClass: callerClass };
@@ -804,7 +806,8 @@ export function acquire({ sessionId, mode, ttlHours = DEFAULT_TTL_HOURS, repoRoo
804
806
  * Call only after the user has explicitly authorised stale-lock takeover.
805
807
  *
806
808
  * Returns:
807
- * { ok: true, lock, replacedLock? } — lock written (replacedLock present if one was overwritten)
809
+ * { ok: true, lock, replacedLock?, ownerProof } — lock written (replacedLock present if one was overwritten;
810
+ * ownerProof as on acquire(), #1541)
808
811
  * { ok: false, reason: 'missing-session-id' } — no usable `sessionId` given; NOTHING was written
809
812
  * { ok: false, reason: 'fs-error', ... } — filesystem failure
810
813
  *
@@ -833,6 +836,48 @@ export function acquire({ sessionId, mode, ttlHours = DEFAULT_TTL_HOURS, repoRoo
833
836
  *
834
837
  * @param {{ sessionId: string, mode: string, ttlHours?: number, repoRoot?: string, semanticSessionId?: string, onlyIfNotLive?: boolean }} args
835
838
  */
839
+ /**
840
+ * Rewrite `.orchestrator/runtime/lock-owner-proof.json` for a lock this module
841
+ * has JUST written, and report the outcome on the result (#1541).
842
+ *
843
+ * Invariant: proof = current lock. Before #1541 only the SessionStart bootstrap
844
+ * wrote the proof, so a lock taken on the prose path (Phase 1.2 `acquire()`
845
+ * after a `/close` in the same conversation, or a force-take / reclaim) left
846
+ * the PREVIOUS lock's proof on disk — and `release()` answered
847
+ * `proof-mismatch` for the session's own lock at its next `/close`.
848
+ *
849
+ * Called only on the `ok: true` paths, directly after the lock write, with the
850
+ * same `repoRoot` the lock path was resolved from (both fall back to
851
+ * `process.cwd()`), so the proof lands beside the lock it describes. The
852
+ * bootstrap's own later writeOwnerProof() on the enriched lock yields the same
853
+ * triple (enrichment never touches pid/host/started_at) — idempotent.
854
+ *
855
+ * Never throws and never turns `ok: true` into a failure: the lock IS held, and
856
+ * a missing proof only degrades `/close` to the session_id-only release.
857
+ *
858
+ * Ceiling (BV-004): two plain forceAcquire() calls racing on one path are
859
+ * last-writer-wins for the lock AND the proof, and the two writes can
860
+ * interleave (A lock, B lock, B proof, A proof). The proof then names A while B
861
+ * holds the lock — the same state as before #1541, and safe: release() still
862
+ * gates on the raw session_id first, so the mismatched proof can only refuse a
863
+ * release, never grant one. Revisit if `release-proof-mismatch` shows up after
864
+ * a force-take.
865
+ *
866
+ * Known limit: the proof is one file per repo and identifies the process that
867
+ * last wrote the lock, never the conversation. Twins sharing one raw
868
+ * session_id (two terminals resuming the same conversation) are therefore
869
+ * indistinguishable to it — either can release after the other force-took.
870
+ *
871
+ * @param {{ ok: true, lock: object }} result
872
+ * @param {string|undefined} repoRoot
873
+ * @returns {object} the same result object, with `ownerProof` set
874
+ */
875
+ function withOwnerProof(result, repoRoot) {
876
+ const w = writeOwnerProof({ repoRoot, lock: result.lock });
877
+ result.ownerProof = w.ok ? { ok: true } : { ok: false, reason: w.reason };
878
+ return result;
879
+ }
880
+
836
881
  /**
837
882
  * A `sessionId` is usable only when it is a non-blank string. ONE predicate,
838
883
  * shared by acquire() and forceAcquire(), so the two entry points cannot drift
@@ -863,7 +908,7 @@ export function forceAcquire({ sessionId, mode, ttlHours = DEFAULT_TTL_HOURS, re
863
908
 
864
909
  const result = { ok: true, lock };
865
910
  if (replacedLock !== null) result.replacedLock = replacedLock;
866
- return result;
911
+ return withOwnerProof(result, repoRoot);
867
912
  } catch (err) {
868
913
  return { ok: false, reason: 'fs-error', error: err.message };
869
914
  }
@@ -948,7 +993,7 @@ function reclaimIfNotLive({ sessionId, mode, ttlHours, repoRoot, semanticSession
948
993
  if (created.ok) {
949
994
  const result = { ok: true, lock };
950
995
  if (moved !== null) result.replacedLock = moved;
951
- return result;
996
+ return withOwnerProof(result, repoRoot);
952
997
  }
953
998
  if (created.reason === 'exists') return reacquire();
954
999
  return created;
@@ -1108,10 +1153,12 @@ export function isLockOwnedByProof(lock, proof) {
1108
1153
  * persistence at lock genesis; Part 2, the on-session-end consumption side,
1109
1154
  * is a separate change).
1110
1155
  *
1111
- * Intended caller: `bootstrapLock()` (hooks/_lib/lock-bootstrap.mjs)
1112
- * immediately after its enriched-lock write — the `lock` argument there is
1113
- * byte-identical to the on-disk lock, so the proof it yields will verify via
1114
- * `isLockOwnedByProof()` against any later re-read of that same lock.
1156
+ * Callers: `acquire()` / `forceAcquire()` on every `ok: true` lock write
1157
+ * (#1541, via withOwnerProof()), and `bootstrapLock()`
1158
+ * (hooks/_lib/lock-bootstrap.mjs) again immediately after its enriched-lock
1159
+ * write. In every case the `lock` argument is byte-identical to the on-disk
1160
+ * lock, so the proof it yields will verify via `isLockOwnedByProof()` against
1161
+ * any later re-read of that same lock.
1115
1162
  *
1116
1163
  * Envelope shape (schema_version 1):
1117
1164
  * {
@@ -108,13 +108,15 @@ const INCOMPLETE_FIELD_ORDER = Object.freeze([
108
108
  'total_agents',
109
109
  'total_files_changed',
110
110
  ]);
111
- // `timestamp_precision` (#1442) deliberately adds NOTHING to the list above: a
112
- // truncated timestamp is still a measurement (exact to the millisecond), not a
113
- // default. Listing it would make consumers discard a real value —
114
- // `sessions-staleness-banner.mjs` returns null for any timestamp named in
115
- // `_backfill_incomplete_fields`, `session-close-backfill.mjs` keys on
116
- // `includes('started_at')`. The sub-millisecond original survives in the
117
- // `_<field>_raw` sidecar instead.
111
+ // `timestamp_precision` (#1442) and `timestamp_offset` (#1525) deliberately add
112
+ // NOTHING to the list above: a truncated or UTC-converted timestamp is still a
113
+ // measurement (exact to the millisecond), not a default. Listing it would make
114
+ // consumers discard a real value — `sessions-staleness-banner.mjs` returns null
115
+ // for any timestamp named in `_backfill_incomplete_fields`,
116
+ // `session-close-backfill.mjs` keys on `includes('started_at')`. The original
117
+ // spelling survives in the `_<field>_raw` sidecar instead. Two classes because
118
+ // the losses differ: `precision` drops sub-ms digits, `offset` drops nothing
119
+ // but the zone spelling (the instant is kept exactly).
118
120
 
119
121
  /**
120
122
  * Timestamp fields `validateSession` holds to `ISO_8601_UTC_MS_RE`
@@ -124,11 +126,15 @@ const INCOMPLETE_FIELD_ORDER = Object.freeze([
124
126
  const MS_PRECISION_FIELDS = Object.freeze(['started_at', 'completed_at', 'lease_acquired_at']);
125
127
 
126
128
  /**
127
- * ISO-8601 UTC with MORE than three fractional digits and exactly `Z` or
128
- * `+00:00` (#1525). Group 1 is the value cut at the millisecond. Nonzero
129
- * offsets, other timezone spellings and shorter fractions stay unrepaired.
129
+ * Strict ISO-8601 timestamp the repair may normalize (#1525): seconds required,
130
+ * fraction optional and of any length, zone exactly `Z` or `±HH:MM`. Anything
131
+ * looser (`+0000`, `+00`, lowercase `z`, no zone) stays unrepaired, so the
132
+ * lenient `Date.parse` never gets to decide what a value meant.
133
+ * Groups: 1 wall-clock date-time to the second, 2 fraction digits, 3 zone,
134
+ * 4 offset sign, 5 offset hours, 6 offset minutes.
130
135
  */
131
- const ISO_UTC_SUB_MS_RE = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3})\d+(?:Z|\+00:00)$/;
136
+ const ISO_REPAIRABLE_RE =
137
+ /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
132
138
 
133
139
  // ---------------------------------------------------------------------------
134
140
  // Helpers
@@ -144,23 +150,45 @@ function isCount(v) {
144
150
  }
145
151
 
146
152
  /**
147
- * Cut a sub-millisecond ISO-8601 UTC timestamp to milliseconds. TRUNCATES,
148
- * never rounds: `.9999Z` must not roll into the next second, and truncation is
149
- * monotone, so `completed_at >= started_at` survives on every pair it held on.
153
+ * Normalize a timestamp to the validator's UTC-millisecond shape (#1442, #1525).
154
+ *
155
+ * - `precision`: a fraction of other than 0 or 3 digits. Sub-millisecond
156
+ * digits are TRUNCATED, never rounded: `.9999Z` must not roll into the next
157
+ * second, and truncation is monotone, so `completed_at >= started_at`
158
+ * survives on every pair it held on. Shorter fractions are zero-padded.
159
+ * - `offset`: any zone spelled other than `Z`. Converting `±HH:MM` to UTC keeps
160
+ * the instant exactly (offsets are whole minutes), so it is lossless and
161
+ * commutes with the truncation above.
150
162
  *
151
163
  * @param {unknown} value
152
- * @returns {string|null} the truncated value, or null when there is nothing to cut
164
+ * @returns {null | {invalid: true} | {value: string, precision: boolean, offset: boolean}}
165
+ * null when there is nothing to normalize (not a string, not the strict
166
+ * shape, or already canonical); `{invalid: true}` when the shape matches but
167
+ * the calendar/clock components or the offset are out of range.
153
168
  */
154
- function truncateToMs(value) {
169
+ function normalizeTimestamp(value) {
155
170
  if (typeof value !== 'string') return null;
156
- const m = ISO_UTC_SUB_MS_RE.exec(value);
171
+ const m = ISO_REPAIRABLE_RE.exec(value);
157
172
  if (!m) return null;
158
- const canonical = `${m[1]}Z`;
159
- const ms = Date.parse(canonical);
173
+ const [, wall, fraction = '', zone, sign, offH, offM] = m;
174
+ const precision = fraction.length !== 0 && fraction.length !== 3;
175
+ const offset = zone !== 'Z';
176
+ if (!precision && !offset) return null; // already what the validator accepts
177
+ const wallCanonical = `${wall}.${fraction.slice(0, 3).padEnd(3, '0')}Z`;
178
+ const wallMs = Date.parse(wallCanonical);
160
179
  // Date.parse rolls over e.g. April 31, non-leap February 29 and 24:00.
161
180
  // Equality with the original calendar components refuses those repairs.
162
- if (!Number.isFinite(ms) || new Date(ms).toISOString() !== canonical) return null;
163
- return canonical;
181
+ if (!Number.isFinite(wallMs) || new Date(wallMs).toISOString() !== wallCanonical) {
182
+ return { invalid: true };
183
+ }
184
+ let offsetMin = 0;
185
+ if (offset) {
186
+ if (Number(offH) > 23 || Number(offM) > 59) return { invalid: true };
187
+ offsetMin = (sign === '-' ? -1 : 1) * (Number(offH) * 60 + Number(offM));
188
+ }
189
+ const utc = new Date(wallMs - offsetMin * 60_000);
190
+ if (!Number.isFinite(utc.getTime())) return { invalid: true };
191
+ return { value: utc.toISOString(), precision, offset };
164
192
  }
165
193
 
166
194
  function orderIncompleteFields(fields) {
@@ -377,12 +405,14 @@ export function repairRecord(record) {
377
405
  // `started_at` — a microsecond `started_at` would otherwise be copied into
378
406
  // `completed_at` and spread the defect instead of fixing it.
379
407
  let precisionCut = false;
408
+ let offsetNormalized = false;
380
409
  for (const key of MS_PRECISION_FIELDS) {
381
- const truncated = truncateToMs(out[key]);
382
- if (truncated === null) continue;
410
+ const norm = normalizeTimestamp(out[key]);
411
+ if (norm === null || 'invalid' in norm) continue;
383
412
  preserveRaw(out, key, record[key], rescued);
384
- out[key] = truncated;
385
- precisionCut = true;
413
+ out[key] = norm.value;
414
+ precisionCut ||= norm.precision;
415
+ offsetNormalized ||= norm.offset;
386
416
  }
387
417
 
388
418
  // -- completed_at ---------------------------------------------------------
@@ -396,18 +426,20 @@ export function repairRecord(record) {
396
426
  preserveRaw(out, 'completed_at', record.completed_at, rescued);
397
427
  const endedMs = typeof out.ended_at === 'string' ? Date.parse(out.ended_at) : NaN;
398
428
  const startedMs = Date.parse(out.started_at);
399
- const endedTruncated = truncateToMs(out.ended_at);
429
+ const endedNorm = normalizeTimestamp(out.ended_at);
400
430
  if (typeof out.ended_at === 'string' &&
401
- (!Number.isFinite(endedMs) ||
402
- (ISO_UTC_SUB_MS_RE.test(out.ended_at) && endedTruncated === null))) {
431
+ (!Number.isFinite(endedMs) || (endedNorm !== null && 'invalid' in endedNorm))) {
403
432
  // Preserve an invalid legacy measurement for the final schema gate to
404
433
  // reject; do not turn it into a valid default or a rolled-over date.
405
434
  out.completed_at = out.ended_at;
406
435
  } else if (Number.isFinite(endedMs) && Number.isFinite(startedMs) && endedMs >= startedMs) {
407
436
  // The COPY is cut to milliseconds; `ended_at` itself is not a validated
408
437
  // field and keeps its original bytes, so nothing needs a sidecar here.
409
- if (endedTruncated !== null) precisionCut = true;
410
- out.completed_at = endedTruncated ?? out.ended_at;
438
+ if (endedNorm !== null) {
439
+ precisionCut ||= endedNorm.precision;
440
+ offsetNormalized ||= endedNorm.offset;
441
+ }
442
+ out.completed_at = endedNorm?.value ?? out.ended_at;
411
443
  } else {
412
444
  out.completed_at = out.started_at;
413
445
  }
@@ -415,6 +447,7 @@ export function repairRecord(record) {
415
447
  incomplete.add('completed_at');
416
448
  }
417
449
  if (precisionCut) defects.push('timestamp_precision');
450
+ if (offsetNormalized) defects.push('timestamp_offset');
418
451
 
419
452
  if (defects.length === 0) {
420
453
  return { record, defects: [], incompleteFields: [], changed: false };
@@ -252,6 +252,14 @@ export const OPTIONAL_FIELDS = Object.freeze([
252
252
  // 2026-10-01), so the counters say which of the two it is.
253
253
  'cost_records_priced',
254
254
  'cost_records_total',
255
+ // #1470 Pkt 4/6 — what `total_cost_usd` is and which price table produced
256
+ // the cost fields. Merged by scripts/emit-session.mjs from
257
+ // scripts/lib/telemetry/pricing.mjs (`COST_BASIS`, `PRICING_TABLE_DATE`):
258
+ // `cost_basis` only beside a written `total_cost_usd`, `pricing_table_date`
259
+ // beside the cost counters. Absent on every record before #1470 — such a
260
+ // cost is not thereby a verified payment either.
261
+ 'cost_basis',
262
+ 'pricing_table_date',
255
263
  // #986 — shape-checked by `_validateOptionalFields` since before this list
256
264
  // existed, never declared until the census test made the gap visible.
257
265
  'discovery_stats',
@@ -26,6 +26,17 @@ import {
26
26
  /** Valid values for the optional `expected_cost_tier` field (ADR-364). */
27
27
  const EXPECTED_COST_TIERS = Object.freeze(['quick', 'standard', 'deep']);
28
28
 
29
+ /**
30
+ * Valid values for the optional `cost_basis` field (#1470 Pkt 4). Must contain
31
+ * `COST_BASIS` from scripts/lib/telemetry/pricing.mjs — the value emit-session
32
+ * writes beside `total_cost_usd`. There is deliberately no payment value: no
33
+ * writer can see what was actually billed.
34
+ */
35
+ const COST_BASES = Object.freeze(['api-list-equivalent']);
36
+
37
+ /** `pricing_table_date` (#1470 Pkt 6): a calendar date, `YYYY-MM-DD`. */
38
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
39
+
29
40
  /**
30
41
  * Valid values for the optional `status` field (Epic #724 C1).
31
42
  * `completed` — record written by a normal /close flow.
@@ -456,6 +467,28 @@ function _validateOptionalFields(entry) {
456
467
  );
457
468
  }
458
469
 
470
+ // #1470 Pkt 4/6 — what the cost figure is and which price table produced it.
471
+ if (entry.cost_basis !== undefined && entry.cost_basis !== null) {
472
+ if (!COST_BASES.includes(entry.cost_basis)) {
473
+ throw new ValidationError(
474
+ `cost_basis must be one of ${COST_BASES.join('|')} or null, got: ${entry.cost_basis}`
475
+ );
476
+ }
477
+ }
478
+ if (entry.pricing_table_date !== undefined && entry.pricing_table_date !== null) {
479
+ if (
480
+ typeof entry.pricing_table_date !== 'string' ||
481
+ !ISO_DATE_RE.test(entry.pricing_table_date) ||
482
+ // Round-trip, not Date.parse alone: V8 rolls 2026-02-30 over to March.
483
+ Number.isNaN(Date.parse(`${entry.pricing_table_date}T00:00:00Z`)) ||
484
+ new Date(`${entry.pricing_table_date}T00:00:00Z`).toISOString().slice(0, 10) !== entry.pricing_table_date
485
+ ) {
486
+ throw new ValidationError(
487
+ `pricing_table_date must be an ISO date (YYYY-MM-DD) or null, got: ${entry.pricing_table_date}`
488
+ );
489
+ }
490
+ }
491
+
459
492
  // Epic #724 C1 — SessionEnd close-through backfill provenance fields.
460
493
  // All additive-optional; null/absent passes without further checks so that
461
494
  // pre-#724 records (and every normally-closed record) validate cleanly.
@@ -55,6 +55,8 @@
55
55
  * total_cost_usd number | null — native total cost in USD (#624, fractional,
56
56
  * best-effort: null when the harness does not
57
57
  * expose it; no rate table is applied)
58
+ * cost_basis 'api-list-equivalent' | null — explicitly supplied cost
59
+ * provenance; null means unknown (#1543)
58
60
  *
59
61
  * OTel aliases (optional, stop-only, additive — #411, schema_version=1 backwards-compat):
60
62
  * gen_ai.usage.input_tokens integer | null — RAW UNCACHED prompt tokens (OTel
@@ -69,6 +71,7 @@
69
71
  import { readFile, appendFile, mkdir } from 'node:fs/promises';
70
72
  import { existsSync } from 'node:fs';
71
73
  import path from 'node:path';
74
+ import { COST_BASIS } from './telemetry/pricing.mjs';
72
75
 
73
76
  // ---------------------------------------------------------------------------
74
77
  // Constants
@@ -267,6 +270,11 @@ export function validateSubagent(entry, options = {}) {
267
270
  }
268
271
  }
269
272
 
273
+ // #1543 additive: never infer provenance from a native dollar value.
274
+ if (entry.cost_basis !== undefined && entry.cost_basis !== null && entry.cost_basis !== COST_BASIS) {
275
+ throw new ValidationError(`cost_basis must be ${COST_BASIS} or null`, 'cost_basis');
276
+ }
277
+
270
278
  // OTel alias — #411 additive, schema_version=1 backwards-compat
271
279
  const otelInputTokens = entry['gen_ai.usage.input_tokens'];
272
280
  if (otelInputTokens !== undefined && otelInputTokens !== null) {
@@ -334,6 +342,7 @@ export function normalizeSubagent(entry) {
334
342
  model: entry.model ?? null,
335
343
  // total_cost_usd — #624 additive, best-effort native cost (null when absent)
336
344
  total_cost_usd: entry.total_cost_usd ?? null,
345
+ cost_basis: entry.cost_basis ?? null,
337
346
  // OTel alias — #411 additive, schema_version=1 backwards-compat
338
347
  'gen_ai.usage.input_tokens': entry['gen_ai.usage.input_tokens'] ?? null,
339
348
  'gen_ai.usage.cache_read_input_tokens': entry['gen_ai.usage.cache_read_input_tokens'] ?? null,
@@ -62,6 +62,17 @@
62
62
  */
63
63
  export const PRICING_TABLE_DATE = '2026-09-29';
64
64
 
65
+ /**
66
+ * What a dollar figure computed from this table IS (#1470 Pkt 4): the API
67
+ * list-price equivalent of the metered tokens — never a payment. Subscription
68
+ * quota, purchased credits and what was actually billed are not visible to
69
+ * this module, so a consumer must not present the figure as any of them.
70
+ * Written beside every persisted cost as `cost_basis`; the session validator's
71
+ * `COST_BASES` must contain it (pinned by tests/scripts/emit-session.test.mjs).
72
+ * @type {'api-list-equivalent'}
73
+ */
74
+ export const COST_BASIS = 'api-list-equivalent';
75
+
65
76
  /**
66
77
  * @typedef {Object} PricingRow
67
78
  * @property {number} input - USD per 1M uncached prompt tokens.
@@ -44,6 +44,8 @@
44
44
  set -uo pipefail
45
45
 
46
46
  PROMPT='Antworte nur mit dem Wort: OK'
47
+ SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
48
+ FORMATTER="$SCRIPT_DIR/lib/context-overhead-format.mjs"
47
49
 
48
50
  measure_one() {
49
51
  local dir="$1" label="$2"
@@ -51,29 +53,10 @@ measure_one() {
51
53
  printf '%s\tNO-SUCH-DIR\n' "$label"
52
54
  return
53
55
  fi
54
- ( cd "$dir" && claude -p "$PROMPT" --output-format json 2>/dev/null ) | node -e "
55
- let s = '';
56
- process.stdin.on('data', (d) => (s += d)).on('end', () => {
57
- const label = process.argv[1];
58
- try {
59
- const j = JSON.parse(s);
60
- const u = j.usage || {};
61
- const ctx =
62
- (u.input_tokens || 0) +
63
- (u.cache_creation_input_tokens || 0) +
64
- (u.cache_read_input_tokens || 0);
65
- process.stdout.write(
66
- [label, ctx, u.cache_creation_input_tokens || 0, u.cache_read_input_tokens || 0,
67
- u.output_tokens || 0, (j.total_cost_usd || 0).toFixed(4)].join('\t') + '\n',
68
- );
69
- } catch {
70
- process.stdout.write(label + '\tPARSE-ERROR\n');
71
- }
72
- });
73
- " "$label"
56
+ ( cd "$dir" && claude -p "$PROMPT" --output-format json 2>/dev/null ) | node "$FORMATTER" -- "$label"
74
57
  }
75
58
 
76
- header() { printf 'LABEL\tCONTEXT_TOK\tcache_create\tcache_read\toutput\tUSD\n'; }
59
+ header() { node "$FORMATTER" --header; }
77
60
 
78
61
  # ── --ablate mode ───────────────────────────────────────────────────
79
62
  if [ "${1:-}" = "--ablate" ]; then