@intentius/chant 0.64.0 → 0.66.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 (66) hide show
  1. package/dist/behaviour-delta.d.ts +181 -0
  2. package/dist/behaviour-delta.d.ts.map +1 -0
  3. package/dist/behaviour-http.d.ts +106 -0
  4. package/dist/behaviour-http.d.ts.map +1 -0
  5. package/dist/behaviour-overlay.d.ts +61 -0
  6. package/dist/behaviour-overlay.d.ts.map +1 -0
  7. package/dist/behaviour.d.ts +1174 -0
  8. package/dist/behaviour.d.ts.map +1 -0
  9. package/dist/cli/handlers/scenario.d.ts.map +1 -1
  10. package/dist/identity.d.ts +28 -0
  11. package/dist/identity.d.ts.map +1 -1
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/lexicon.d.ts +45 -0
  15. package/dist/lexicon.d.ts.map +1 -1
  16. package/dist/lifecycle/scenario-eval.d.ts +23 -5
  17. package/dist/lifecycle/scenario-eval.d.ts.map +1 -1
  18. package/dist/lifecycle/scenario.d.ts +45 -3
  19. package/dist/lifecycle/scenario.d.ts.map +1 -1
  20. package/dist/lifecycle/types.d.ts +17 -0
  21. package/dist/lifecycle/types.d.ts.map +1 -1
  22. package/dist/op/activities/activity-contracts.d.ts +42 -0
  23. package/dist/op/activities/activity-contracts.d.ts.map +1 -1
  24. package/dist/op/activities/index.d.ts +2 -0
  25. package/dist/op/activities/index.d.ts.map +1 -1
  26. package/dist/op/activities/predict-behaviour.d.ts +207 -0
  27. package/dist/op/activities/predict-behaviour.d.ts.map +1 -0
  28. package/dist/op/activities/reconcile.d.ts +86 -16
  29. package/dist/op/activities/reconcile.d.ts.map +1 -1
  30. package/dist/op/composites/behaviour-op.d.ts +57 -0
  31. package/dist/op/composites/behaviour-op.d.ts.map +1 -0
  32. package/dist/op/composites/index.d.ts +2 -0
  33. package/dist/op/composites/index.d.ts.map +1 -1
  34. package/dist/op/index.d.ts +2 -2
  35. package/dist/op/index.d.ts.map +1 -1
  36. package/package.json +1 -1
  37. package/src/behaviour-delta.test.ts +331 -0
  38. package/src/behaviour-delta.ts +564 -0
  39. package/src/behaviour-http.test.ts +456 -0
  40. package/src/behaviour-http.ts +252 -0
  41. package/src/behaviour-overlay.test.ts +149 -0
  42. package/src/behaviour-overlay.ts +76 -0
  43. package/src/behaviour.test.ts +2011 -0
  44. package/src/behaviour.ts +2127 -0
  45. package/src/cli/handlers/scenario.test.ts +108 -0
  46. package/src/cli/handlers/scenario.ts +63 -16
  47. package/src/fold/subset-doc-parity.test.ts +60 -0
  48. package/src/identity.ts +31 -2
  49. package/src/index.ts +3 -0
  50. package/src/lexicon.ts +46 -0
  51. package/src/lifecycle/scenario-cost.test.ts +183 -0
  52. package/src/lifecycle/scenario-eval.ts +133 -6
  53. package/src/lifecycle/scenario.ts +72 -4
  54. package/src/lifecycle/types.ts +17 -0
  55. package/src/lint/rules/op/ops012-activity-contract.test.ts +31 -0
  56. package/src/op/activities/activity-contracts.ts +49 -0
  57. package/src/op/activities/index.ts +24 -0
  58. package/src/op/activities/predict-behaviour.test.ts +255 -0
  59. package/src/op/activities/predict-behaviour.ts +468 -0
  60. package/src/op/activities/reconcile.test.ts +84 -0
  61. package/src/op/activities/reconcile.ts +97 -24
  62. package/src/op/activity-contract-registry.test.ts +3 -0
  63. package/src/op/composites/behaviour-op.test.ts +56 -0
  64. package/src/op/composites/behaviour-op.ts +99 -0
  65. package/src/op/composites/index.ts +2 -0
  66. package/src/op/index.ts +2 -0
@@ -0,0 +1,2127 @@
1
+ /**
2
+ * The behaviour prediction contract (#2356) — what a lexicon's
3
+ * `predictBehaviour()` is allowed to mean.
4
+ *
5
+ * `describeResources()` (./observation.ts) answers whether a declared entity
6
+ * exists. `observeResourcesDeep()` (./deep-observation.ts) answers what its
7
+ * properties currently are. Both report facts a substrate was asked for. This
8
+ * third axis reports something no substrate holds: what the declared estate
9
+ * would *do* at a stated traffic level — cost per hour, how far each entity is
10
+ * from saturation, the error rate to expect, whether it survives a named
11
+ * failure, and a smaller size that would still carry the load.
12
+ *
13
+ * None of that is a measurement, and the type is built so it cannot be read as
14
+ * one.
15
+ *
16
+ * ## A prediction is not a bill
17
+ *
18
+ * The one failure mode that matters here is somebody quoting a modeled figure
19
+ * as money owed. Four things in this module work against that, and it is worth
20
+ * being exact about how much they buy, because an overstated guarantee is how
21
+ * a consumer ends up trusting one:
22
+ *
23
+ * 1. Money appears in exactly one shape, {@link PredictedRate}, and that
24
+ * shape carries a literal `rate: "per-hour"` discriminant. There is no
25
+ * field anywhere for an amount, a period, an account, an invoice or a
26
+ * due date, so an elapsed charge is not expressible *in this module's
27
+ * types*.
28
+ * 2. A figure cannot exist without {@link PredictedBehaviour.at}, the traffic
29
+ * level it was predicted for. A bill is for an hour that happened; this is
30
+ * for an hour the engine was asked to imagine.
31
+ * 3. {@link BehaviourProvenance} is required on every entity, and its
32
+ * {@link BehaviourProvenance.basis} is a closed two-value enum: `modeled`
33
+ * off list prices, or `validated` against a real bill. A figure that will
34
+ * not say which of the two it is cannot be constructed.
35
+ * 4. A refusal is a separate member of the {@link BehaviourResult} union with
36
+ * no figures on it at all, so "the engine is gone" and "the engine says
37
+ * zero" are different objects rather than the same object with zeroes in
38
+ * it. This one is airtight: there is no `entities` key on the refusal arm
39
+ * to be empty and no total to be zero.
40
+ *
41
+ * **What this does not do is make a bill a type error.** A consumer holding a
42
+ * {@link PredictedBehaviour} can write
43
+ * `const { rate, ...rest } = cost; return { amount: rest.perHour * hours }`
44
+ * and TypeScript will not object; the discriminant is a field on an object, and
45
+ * a field can be dropped. behold's own validator rebuilds `cost` as
46
+ * `{ perHour, currency }` and its estate sum carries no discriminant at all, so
47
+ * the marker is stripped by the first consumer *by design*. What the shape
48
+ * genuinely buys is that a bill cannot be constructed **accidentally** — every
49
+ * route from a prediction to something that reads as money owed has a
50
+ * deliberate destructure or cast in it, and shows up in review as one. Treat
51
+ * rules 1 to 3 as a speed bump with a name, and rule 4 as the enforced one.
52
+ *
53
+ * ## The engine sees no credential and writes nothing
54
+ *
55
+ * {@link PredictBehaviourOptions} mirrors `observeResourcesDeep`'s options
56
+ * field for field, plus `traffic`, `edges` and `edgeCoverage`, and then works
57
+ * against credentials on two levels. The type declares every obvious name
58
+ * `?: never`, which catches the deliberate attempt; and
59
+ * {@link screenBehaviourRequest} walks the whole request at runtime, matching
60
+ * credential-shaped **values** as well as credential-shaped keys, which is what
61
+ * catches the accident.
62
+ *
63
+ * `screenBehaviourRequest` is the one entry point — its own doc comment carries
64
+ * the call sequence, and nothing else here restates it. The runtime walk is the
65
+ * load-bearing half, because the type cannot see the two channels that actually
66
+ * carry a secret in practice: `entities[*].props` is `Record<string, unknown>`
67
+ * straight out of the build, and a lexicon surfacing a connection string puts
68
+ * one there without deciding to. See {@link assertNoCredentialInOptions} for
69
+ * exactly what the walk detects and, more importantly, what it does not.
70
+ *
71
+ * `edges` is the one place the options mirror breaks, and the field's own doc
72
+ * says why: the epic's input is a resource graph, a deep read has no use for
73
+ * neighbours, and a prediction is nothing but statements about paths through
74
+ * the estate. It carries `IREdge` (./graph-ir.ts) rather than an edge type of
75
+ * this contract's own, because that is already the shape both the declared
76
+ * path and the live path produce.
77
+ *
78
+ * Nothing in the options is a handle. There is no client, no transport, no
79
+ * apply callback, no writer — only strings, a name list and the entity map the
80
+ * build already produced. An engine handed this cannot reach the account even
81
+ * if it wanted to, which is the structural half of "it never writes".
82
+ *
83
+ * ## The tri-state, and why it is not `UnobservedReason`
84
+ *
85
+ * Behaviour keeps the same three-verdict discipline `./observation.ts`
86
+ * established — PREDICTED, NOT-PREDICTABLE-FOR-THIS-KIND, and NOT-PREDICTED
87
+ * with a named reason — but on a stricter total: every entity the caller asked
88
+ * about lands in `entities` or in `unpredicted`, never in neither. The thin
89
+ * read needs a third position because "the provider says it is not there" is a
90
+ * real answer with no row to sit on. A prediction has no such answer. An entity
91
+ * either got a figure or it did not, and when it did not there is a reason,
92
+ * so an entity in neither map means the lexicon lost track of it.
93
+ *
94
+ * {@link BehaviourUnpredictedReason} derives from `UnobservedReason` rather
95
+ * than restating it, so the four shared verdicts provably keep their spelling
96
+ * and their meaning. It differs in two ways, both deliberate:
97
+ *
98
+ * - `no-credentials` is **excluded**. A behaviour read has no credential to
99
+ * be missing — see the section above — so an enum that could say it would
100
+ * be inviting a lexicon to send an operator hunting for a variable this
101
+ * contract forbids.
102
+ * - Four reasons about the predictor itself are **added** — `no-engine`,
103
+ * `engine-unreachable`, `engine-out-of-credit` and `engine-over-quota` —
104
+ * because the epic wants a missing engine named and `no-binding` is about
105
+ * the environment resolving to no target, a different axis. They are four
106
+ * rather than one because each has a different remedy, and a refusal that
107
+ * names the wrong remedy is worse than a slow one: set a variable, check an
108
+ * address, pay for the account, or wait for a window. The last two arrive
109
+ * from an engine that answered perfectly well (#2359), so folding them into
110
+ * `engine-unreachable` would send somebody to debug a network that is fine.
111
+ *
112
+ * ## Deltas: the invariant is here, the presentation is not
113
+ *
114
+ * The epic wants a declared prediction and a live prediction shown as a delta,
115
+ * and #2358 posts one on a merge request. This module deliberately ships no
116
+ * delta type and no differencing function. What it ships is the one thing a
117
+ * hand-rolled diff silently loses, which is that a figure's context does not
118
+ * survive subtraction: {@link compareFigures} classifies a pair `comparable`,
119
+ * `mixed-basis`, `mixed-level` or `mixed-engine`, and the rule this contract
120
+ * binds its consumers to is that anything but `comparable` must be marked
121
+ * wherever it is shown. A `modeled` figure minus a `validated` one is not a
122
+ * change in the estate; part of that difference is the gap between a price list
123
+ * and an invoice. Nor is a 100 rps figure minus a 1000 rps one, which is why
124
+ * {@link compareProvenance} — which cannot see `at` and never could — is not
125
+ * the function to reach for. How the mark looks is #2358's to define. Whether
126
+ * there is one is not.
127
+ *
128
+ * ## Shape compatibility with the overlay
129
+ *
130
+ * {@link PredictedBehaviour} is the object `chant graph --live --overlay` puts
131
+ * on a node as `attrs._behaviour`.
132
+ *
133
+ * On the graph, `meta._behaviour` takes {@link BehaviourReportMeta} **or the
134
+ * whole {@link BehaviourRefusalReport}** — not a bare {@link BehaviourRefusal}.
135
+ * behold reads that key as `{ engine?, version?, at?, total?, refusal? }` and
136
+ * branches on the presence of `refusal`, so a bare `BehaviourRefusal` has no
137
+ * `refusal` key, falls through to the engine check, and is dropped as
138
+ * "meta.engine missing" — a refusal that renders as nothing at all, which is
139
+ * the one outcome this contract exists to prevent. #2360 implements this
140
+ * sentence, so it says what behold does.
141
+ *
142
+ * behold reads those keys and does arithmetic on the engine's figures; it never
143
+ * produces one of its own. Fields beyond what it reads (`cause` and `source` on
144
+ * a refusal, `edgeCoverage` on the meta) are additive and ignorable.
145
+ *
146
+ * ## The transport is part of the contract (#2373, decided in #2359)
147
+ *
148
+ * The first version of this module named the address chain, said the address
149
+ * may be a URL, a socket path or a command on `PATH`, and stopped. augur
150
+ * (#2357) then declared a private `BehaviourEngine` and its own mapping from
151
+ * what the wire said to which of the three engine-answered refusals to build.
152
+ * With a second implementation to generalise from, the seam is here:
153
+ * {@link BehaviourTransport} is one method, `send(body)`, taking the request
154
+ * as the lexicon rendered it and returning either the engine's answer as text
155
+ * or a {@link BehaviourRefusalReport} ready to return.
156
+ *
157
+ * Two things about that shape are decisions rather than defaults.
158
+ *
159
+ * - **The transport returns text, not a report.** #2373 proposed
160
+ * `send(request) → Promise<BehaviourResult>`. A report cannot be built
161
+ * without the request's `entityNames`, `traffic` and `edgeCoverage`, and
162
+ * what an answer's fields *mean* is the lexicon's wire version, not the
163
+ * contract's. A transport that built reports would have to know both, and
164
+ * every lexicon would need its own. One that carries bytes is one HTTP
165
+ * client and one subprocess spawner for every lexicon there will ever be.
166
+ * - **The failure arm is a finished refusal, not a `{cause, detail}` pair.**
167
+ * The transport is the one party that saw the wire condition and holds the
168
+ * lexicon name and the endpoint, so it is the one party that can name the
169
+ * condition, the address and the variable together. Handing back a cause
170
+ * for the lexicon to translate would put the same three-way switch in
171
+ * every lexicon, and one of them would fold `engine-over-quota` into
172
+ * `engine-unreachable` on a bad afternoon. {@link behaviourWireRefusal}
173
+ * is that switch, written once.
174
+ *
175
+ * What the wire says maps to the causes above as follows, and
176
+ * `./behaviour-http.ts` (the first adapter) and augur's command transport both
177
+ * hold to it: an HTTP 402 is `engine-out-of-credit`; a 429 is
178
+ * `engine-over-quota`; a connection refused, a timeout, a 5xx, a redirect, or
179
+ * an answer that is not JSON is `engine-unreachable`; an unset address is
180
+ * `no-engine` before any transport is built; and an unset or rejected bearer
181
+ * token is `no-engine` too, because its remedy is the same kind — set a
182
+ * variable — and the reason says which. A transport that spawns a child hands
183
+ * it {@link behaviourEngineChildEnvironment} and nothing more, for the reason
184
+ * given on that function.
185
+ *
186
+ * A bearer token on the wire is the transport's, and is not the credential
187
+ * rule 3 is about. "The engine is never handed a credential" is a statement
188
+ * about the *request body* — the graph — which {@link screenBehaviourRequest}
189
+ * still walks first. {@link behaviourTokenFrom} resolves the token an engine
190
+ * authenticates chant with, on a chain parallel to the address chain, and the
191
+ * token goes in a header the engine reads and nowhere else: never in the body,
192
+ * never in a refusal, never in a `detail`.
193
+ */
194
+
195
+ import type { UnobservedReason } from "./observation";
196
+ import type { IREdge } from "./graph-ir";
197
+ import type { DanglingRef } from "./graph-refs";
198
+ import {
199
+ CREDENTIAL_ENV_NAME,
200
+ CREDENTIAL_SHAPES,
201
+ CREDENTIAL_TOKEN_SHAPES,
202
+ REDACTED,
203
+ redactCredentialMaterial,
204
+ } from "./identity";
205
+
206
+ /**
207
+ * Whether a figure came off a price list or off a bill. Closed, and required on
208
+ * every prediction — this is the distinction that keeps rule 1 enforceable.
209
+ *
210
+ * - `modeled` — computed from published list prices and the engine's own model.
211
+ * The honest default, and the word a badge shows unless told otherwise.
212
+ * - `validated` — reconciled against a real invoice for a comparable estate.
213
+ */
214
+ export type BehaviourBasis = "modeled" | "validated";
215
+
216
+ /**
217
+ * Every legal {@link BehaviourBasis}, for validation and conformance checks.
218
+ *
219
+ * Derived from a total witness rather than typed as `readonly BehaviourBasis[]`
220
+ * and written out by hand. A hand-written array is only checked for having
221
+ * legal members, never for having ALL of them, so a value added to the union
222
+ * leaves the array silently short and every runtime guard built on it starts
223
+ * rejecting a value the type accepts. Keying a `Record` off the union makes the
224
+ * omission a compile error at the point of the omission. Same construction for
225
+ * {@link RESILIENCE_VERDICTS} and {@link BEHAVIOUR_UNPREDICTED_REASONS}, and
226
+ * the last of those is the one that needed it: it derives from
227
+ * `UnobservedReason`, so a reason added *upstream* would otherwise widen this
228
+ * type with nothing here failing.
229
+ */
230
+ const BEHAVIOUR_BASIS_WITNESS: Record<BehaviourBasis, true> = {
231
+ modeled: true,
232
+ validated: true,
233
+ };
234
+
235
+ export const BEHAVIOUR_BASES: readonly BehaviourBasis[] = Object.keys(
236
+ BEHAVIOUR_BASIS_WITNESS,
237
+ ) as BehaviourBasis[];
238
+
239
+ /** True when `value` is a legal {@link BehaviourBasis}. */
240
+ export function isBehaviourBasis(value: unknown): value is BehaviourBasis {
241
+ return typeof value === "string" && (BEHAVIOUR_BASES as readonly string[]).includes(value);
242
+ }
243
+
244
+ /**
245
+ * Where one entity's numbers came from and how far they can be trusted.
246
+ * Required on every {@link PredictedBehaviour}, and per entity rather than per
247
+ * report, because one estate can be priced by two engines.
248
+ */
249
+ export interface BehaviourProvenance {
250
+ /** The engine that produced the figures, as it names itself (`acme-sim`). */
251
+ engine: string;
252
+ /** That engine's own version string (`1.4.2`). Never inferred. */
253
+ version: string;
254
+ /**
255
+ * The engine's stated tolerance, echoed verbatim (`±15%`). chant does not
256
+ * parse it and does not invent one for an engine that states none — an engine
257
+ * with nothing to say here has no business publishing a figure.
258
+ */
259
+ tolerance: string;
260
+ /** List prices, or a real bill. See {@link BehaviourBasis}. */
261
+ basis: BehaviourBasis;
262
+ }
263
+
264
+ /**
265
+ * The traffic level a prediction is for. A string the engine names and chant
266
+ * echoes, never a number chant does arithmetic on: `100 rps, p50`, `peak hour,
267
+ * black friday`, `steady state`. Required, because a figure without the
268
+ * question it answers is the figure most likely to be quoted as a bill.
269
+ */
270
+ export interface BehaviourTrafficLevel {
271
+ traffic: string;
272
+ }
273
+
274
+ /**
275
+ * Money, in the only shape this module has for it: a rate for one hypothetical
276
+ * hour at a stated traffic level.
277
+ *
278
+ * The literal `rate: "per-hour"` is load-bearing. It makes the type structurally
279
+ * distinct from any billing record — nothing that models an amount charged
280
+ * carries that field — so a `PredictedRate` cannot be passed where a charge is
281
+ * wanted, and a charge cannot be passed here.
282
+ */
283
+ export interface PredictedRate {
284
+ /** Discriminant. A rate for an imagined hour, never an amount charged for a real one. */
285
+ readonly rate: "per-hour";
286
+ /** The rate itself, in `currency` per hour. */
287
+ perHour: number;
288
+ /** ISO 4217 code, as the engine states it. chant converts nothing. */
289
+ currency: string;
290
+ }
291
+
292
+ /** Build a {@link PredictedRate}. Lexicons use this rather than writing the discriminant by hand. */
293
+ export function predictedRate(perHour: number, currency: string): PredictedRate {
294
+ return { rate: "per-hour", perHour, currency };
295
+ }
296
+
297
+ /**
298
+ * How much of each axis is still free at the stated traffic level, as a
299
+ * fraction in `0..1`. Both axes are optional and an axis the engine does not
300
+ * model is **absent**, never `0` — zero headroom means saturated, which is the
301
+ * opposite claim.
302
+ */
303
+ export type BehaviourHeadroom =
304
+ | { cpu: number; latency?: number }
305
+ | { cpu?: number; latency: number };
306
+
307
+ /** What an entity does when the named failure happens. Closed. */
308
+ export type ResilienceVerdict = "survives" | "degrades" | "fails";
309
+
310
+ const RESILIENCE_VERDICT_WITNESS: Record<ResilienceVerdict, true> = {
311
+ survives: true,
312
+ degrades: true,
313
+ fails: true,
314
+ };
315
+
316
+ /** Every legal {@link ResilienceVerdict}, for validation and conformance checks. */
317
+ export const RESILIENCE_VERDICTS: readonly ResilienceVerdict[] = Object.keys(
318
+ RESILIENCE_VERDICT_WITNESS,
319
+ ) as ResilienceVerdict[];
320
+
321
+ /** True when `value` is a legal {@link ResilienceVerdict}. */
322
+ export function isResilienceVerdict(value: unknown): value is ResilienceVerdict {
323
+ return typeof value === "string" && (RESILIENCE_VERDICTS as readonly string[]).includes(value);
324
+ }
325
+
326
+ /** The verdict under one named failure, and which failure it was tested against. */
327
+ export interface BehaviourResilience {
328
+ /**
329
+ * The failure, named by the engine and echoed verbatim: `one zone lost`,
330
+ * `primary database failover`. A verdict without its failure says nothing.
331
+ */
332
+ failure: string;
333
+ verdict: ResilienceVerdict;
334
+ /** Free text from the engine, when it has more to say than the verdict. */
335
+ note?: string;
336
+ }
337
+
338
+ /** A smaller size the engine believes would still carry the stated traffic. */
339
+ export interface BehaviourRightSize {
340
+ /** The size, in the provider's own vocabulary (`t3.small`, `db-f1-micro`). */
341
+ suggestion: string;
342
+ /** Why. A suggestion nobody can evaluate is noise. */
343
+ reason?: string;
344
+ }
345
+
346
+ /**
347
+ * One entity's prediction — the object that rides as `attrs._behaviour` on an
348
+ * overlay node.
349
+ *
350
+ * Everything here except `rightSize`, `resilience.note` and either
351
+ * {@link BehaviourHeadroom} axis is required. An entity the engine could not
352
+ * price does not get a thinned-out version of this block; it goes in
353
+ * {@link BehaviourReport.unpredicted} with a reason.
354
+ */
355
+ export interface PredictedBehaviour {
356
+ /** The traffic level every figure below is for. */
357
+ at: BehaviourTrafficLevel;
358
+ /** Cost per hour at `at`. */
359
+ cost: PredictedRate;
360
+ /** Distance from saturation at `at`. A modeled axis is present; an unmodeled one is absent. */
361
+ headroom: BehaviourHeadroom;
362
+ /** Expected fraction of requests failing at `at`, in `0..1`. */
363
+ errorRate: number;
364
+ /** The verdict under a named failure. */
365
+ resilience: BehaviourResilience;
366
+ /** Optional: a smaller size that would still do. */
367
+ rightSize?: BehaviourRightSize;
368
+ /** Which engine said all of this, and on what basis. Required. */
369
+ provenance: BehaviourProvenance;
370
+ }
371
+
372
+ /**
373
+ * Why one declared entity got no prediction. Total: a lexicon that cannot
374
+ * predict an entity must pick one of these, and consumers may switch
375
+ * exhaustively.
376
+ *
377
+ * Derived from {@link UnobservedReason} so the four shared verdicts keep their
378
+ * exact spelling and meaning:
379
+ *
380
+ * - `read-failed` — the engine was reached and the prediction errored.
381
+ * - `no-binding` — the environment resolves to no concrete target to predict.
382
+ * - `unsupported-kind` — the engine has no model for this entity type. The
383
+ * entity is perfectly real and may well cost money; this engine cannot say
384
+ * how much, and says so instead of returning zero.
385
+ * - `filtered` — reached but withheld by a caller-requested filter (`owned`).
386
+ *
387
+ * `no-credentials` is excluded on purpose: the engine is never handed one, so
388
+ * it can never be missing one. Two reasons are added for the predictor itself:
389
+ *
390
+ * - `no-engine` — no variable in the chain named an engine, or — for a
391
+ * transport that authenticates — no variable in the token chain named a
392
+ * token the engine accepts. Nothing usable is configured; this is a setup
393
+ * state, not a failure, and the reason says which variable.
394
+ * - `engine-unreachable` — a variable named an engine and it did not answer.
395
+ * - `engine-out-of-credit` — the engine answered, and refused because the
396
+ * account behind it has no balance left (#2359).
397
+ * - `engine-over-quota` — the engine answered, and refused because a rate or
398
+ * volume limit is spent (#2359).
399
+ * - `credential-in-request` — the request itself carried something that must
400
+ * not leave the process, so nothing was sent. The one refusal chant raises
401
+ * about itself rather than about the engine; see
402
+ * {@link screenBehaviourRequest}.
403
+ *
404
+ * The last four are one axis split four ways, because each has a different
405
+ * remedy and a refusal exists to be acted on. `no-engine` wants a variable
406
+ * set. `engine-unreachable` wants the address checked. `engine-out-of-credit`
407
+ * wants somebody to pay, and no amount of waiting fixes it.
408
+ * `engine-over-quota` usually wants nothing but the window to roll over, and
409
+ * telling somebody to top up an account that is not empty sends them to the
410
+ * wrong place — as does folding either into `engine-unreachable`, which points
411
+ * at an address that is answering perfectly well.
412
+ */
413
+ export type BehaviourUnpredictedReason =
414
+ | Exclude<UnobservedReason, "no-credentials">
415
+ | "no-engine"
416
+ | "engine-unreachable"
417
+ | "engine-out-of-credit"
418
+ | "engine-over-quota"
419
+ | "credential-in-request";
420
+
421
+ /**
422
+ * The total witness. This is the one that earns the construction: the type
423
+ * above derives from `UnobservedReason`, so adding a reason to THAT union —
424
+ * in ./observation.ts, for reasons that have nothing to do with prediction —
425
+ * silently widens this one. With a hand-written array, the widening compiled
426
+ * clean, every existing test stayed green, and the new reason was assignable to
427
+ * `BehaviourUnpredictedReason` while {@link isBehaviourUnpredictedReason}
428
+ * returned `false` for it and the conformance suite rejected it. Keyed off the
429
+ * union, the same change fails to compile here and somebody has to decide
430
+ * whether the new reason belongs to behaviour at all.
431
+ */
432
+ const BEHAVIOUR_UNPREDICTED_REASON_WITNESS: Record<BehaviourUnpredictedReason, true> = {
433
+ "read-failed": true,
434
+ "no-binding": true,
435
+ "unsupported-kind": true,
436
+ filtered: true,
437
+ "no-engine": true,
438
+ "engine-unreachable": true,
439
+ "engine-out-of-credit": true,
440
+ "engine-over-quota": true,
441
+ "credential-in-request": true,
442
+ };
443
+
444
+ /** Every legal {@link BehaviourUnpredictedReason}, for validation and conformance checks. */
445
+ export const BEHAVIOUR_UNPREDICTED_REASONS: readonly BehaviourUnpredictedReason[] = Object.keys(
446
+ BEHAVIOUR_UNPREDICTED_REASON_WITNESS,
447
+ ) as BehaviourUnpredictedReason[];
448
+
449
+ /** True when `value` is a legal {@link BehaviourUnpredictedReason}. */
450
+ export function isBehaviourUnpredictedReason(
451
+ value: unknown,
452
+ ): value is BehaviourUnpredictedReason {
453
+ return (
454
+ typeof value === "string" &&
455
+ (BEHAVIOUR_UNPREDICTED_REASONS as readonly string[]).includes(value)
456
+ );
457
+ }
458
+
459
+ /** One declared entity that got no prediction, and why. */
460
+ export interface UnpredictedEntity {
461
+ /** Declared entity type, when the lexicon knows it (it usually does — the entity is declared). */
462
+ type?: string;
463
+ /** Total verdict. */
464
+ reason: BehaviourUnpredictedReason;
465
+ /** Human-readable detail: the kind with no model, the call that failed. */
466
+ detail?: string;
467
+ }
468
+
469
+ /**
470
+ * Report-level facts about a run that produced figures. Rides as
471
+ * `meta._behaviour` on the overlay graph.
472
+ */
473
+ export interface BehaviourReportMeta {
474
+ /** The engine that answered for the run as a whole. */
475
+ engine: string;
476
+ /** Its version. */
477
+ version: string;
478
+ /** The traffic level the run was asked for, echoed from the request. */
479
+ at: BehaviourTrafficLevel;
480
+ /**
481
+ * An estate total, when the engine states one of its own. Optional, and
482
+ * emphatically not a field for chant or a consumer to fill in by summing —
483
+ * a consumer that sums does its own arithmetic and labels it as such.
484
+ */
485
+ total?: PredictedRate;
486
+ /**
487
+ * The edge coverage the run was given, echoed from the request (#2360).
488
+ *
489
+ * Required, and it is the whole reason `edgeCoverage` is worth stating. Held
490
+ * only on {@link PredictBehaviourOptions} it never reached a reader, so a
491
+ * consumer holding a report could not tell whether a "survives one zone lost"
492
+ * verdict was computed over a complete graph or over one whose builder had no
493
+ * idea what it had missed. Under this contract's own second constraint that
494
+ * makes the verdict a faked number the shape renders invisible — the failure
495
+ * the refusal arm exists to prevent, reappearing one level down.
496
+ *
497
+ * `behaviourReport` copies it from the request, so a lexicon does not restate
498
+ * it and cannot restate it differently.
499
+ */
500
+ edgeCoverage: BehaviourEdgeCoverage;
501
+ }
502
+
503
+ /**
504
+ * A run that produced figures. The `behaviour: "v1"` discriminant is a wire
505
+ * version for the same reason `observation: "v1"` is: consumers branch on it.
506
+ */
507
+ export interface BehaviourReport {
508
+ /** Discriminant + wire version. */
509
+ readonly behaviour: "v1";
510
+ /** Which engine ran, at what traffic level. */
511
+ meta: BehaviourReportMeta;
512
+ /** PREDICTED, keyed by chant entity name. */
513
+ entities: Record<string, PredictedBehaviour>;
514
+ /**
515
+ * NOT-PREDICTED, keyed by chant entity name, with a total reason. Together
516
+ * with `entities` this must cover every name the caller asked about.
517
+ */
518
+ unpredicted?: Record<string, UnpredictedEntity>;
519
+ }
520
+
521
+ /**
522
+ * Why there is no report at all, and what to do about it.
523
+ *
524
+ * `reason` and `remedy` are the two strings a consumer prints where the legend
525
+ * would go; `cause` and `source` are additive and switchable. The refusal is
526
+ * the lexicon's own text in the house style, naming the variable it wanted —
527
+ * see {@link noBehaviourEngineMessage}.
528
+ */
529
+ export interface BehaviourRefusal {
530
+ /** Total, switchable verdict. */
531
+ cause: BehaviourUnpredictedReason;
532
+ /** The sentence a consumer prints. Names what was missing. */
533
+ reason: string;
534
+ /** How to fix it. Names the variable and how to set it. */
535
+ remedy: string;
536
+ /**
537
+ * Which variable answered, when one did: the address variable for a refusal
538
+ * about the engine, the token variable for a refusal about a rejected
539
+ * token. Absent when no variable answered at all.
540
+ */
541
+ source?: string;
542
+ }
543
+
544
+ /**
545
+ * A run that produced nothing, and says why.
546
+ *
547
+ * A separate member of the union rather than a flag on {@link BehaviourReport},
548
+ * so a refusal has no `entities` map to be empty and no `meta.total` to be
549
+ * zero. "The engine is unreachable" and "the engine priced this estate at
550
+ * nothing" are different objects, and no amount of downstream carelessness can
551
+ * turn the first into the second.
552
+ */
553
+ export interface BehaviourRefusalReport {
554
+ /** Discriminant + wire version, shared with {@link BehaviourReport}. */
555
+ readonly behaviour: "v1";
556
+ /** The refusal. Present *instead of* every figure, never alongside one. */
557
+ refusal: BehaviourRefusal;
558
+ }
559
+
560
+ /** What `predictBehaviour()` returns: figures, or a named refusal. Never both, never neither. */
561
+ export type BehaviourResult = BehaviourReport | BehaviourRefusalReport;
562
+
563
+ /** True when the lexicon refused rather than predicting. */
564
+ export function isBehaviourRefusalReport(
565
+ value: BehaviourResult,
566
+ ): value is BehaviourRefusalReport {
567
+ return typeof value === "object" && value !== null && "refusal" in value;
568
+ }
569
+
570
+ /**
571
+ * True when `value` is either arm of the versioned {@link BehaviourResult}
572
+ * envelope.
573
+ *
574
+ * Both the discriminant AND an arm, because the discriminant alone is not the
575
+ * type. `{ behaviour: "v1" }` carries the version and is neither arm: it fails
576
+ * {@link isBehaviourRefusalReport}, so a consumer's `if (refusal) … else …`
577
+ * narrows it to {@link BehaviourReport}, and `result.entities` is `undefined`
578
+ * at a site TypeScript has been told cannot be.
579
+ */
580
+ export function isBehaviourResult(value: unknown): value is BehaviourResult {
581
+ if (typeof value !== "object" || value === null) return false;
582
+ const v = value as { behaviour?: unknown; refusal?: unknown; entities?: unknown; meta?: unknown };
583
+ if (v.behaviour !== "v1") return false;
584
+ if (typeof v.refusal === "object" && v.refusal !== null) return true;
585
+ return (
586
+ typeof v.entities === "object" && v.entities !== null && typeof v.meta === "object" && v.meta !== null
587
+ );
588
+ }
589
+
590
+ /**
591
+ * Words that state nothing. Rejected wherever this contract asks an engine to
592
+ * *state* something — its tolerance, and the failure a verdict is about.
593
+ *
594
+ * `"none"` as a `resilience.failure` was the hole: the module's own doc says a
595
+ * verdict with no named failure says nothing, and `"none"` names no failure
596
+ * while sailing through a non-empty-string check.
597
+ */
598
+ const STATES_NOTHING: readonly string[] = ["n/a", "na", "none", "unknown", "-", "?", "tbd", "null"];
599
+
600
+ /** True when a stated value is one of the words that state nothing. */
601
+ function statesNothing(value: string): boolean {
602
+ return STATES_NOTHING.includes(value.trim().toLowerCase().replace(/\.$/, ""));
603
+ }
604
+
605
+ const isFraction = (v: unknown): boolean => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
606
+ const isFilled = (v: unknown): boolean => typeof v === "string" && v.trim() !== "";
607
+
608
+ /**
609
+ * Every rule behold's `validateBehaviourBlock` applies, applied here instead —
610
+ * before the block is built rather than after it has travelled.
611
+ *
612
+ * The rule set is deliberately, literally the same set. behold
613
+ * (`behold/src/behaviour.ts:209`) validates each block on arrival and **drops
614
+ * the whole block** with a diagnostic when one fails, so a block chant's types
615
+ * accept and behold's validator rejects renders nothing at all, having looked
616
+ * perfectly legal every step of the way here. Types cannot carry most of these:
617
+ * `tolerance: string` accepts `""`, `errorRate: number` accepts `1.2`, and
618
+ * `cost.perHour: number` accepts `-4`.
619
+ *
620
+ * The mapping, by behold's own numbering, so a future change there has a named
621
+ * place to land here:
622
+ *
623
+ * 2 `at.traffic` non-empty · 3 `cost.perHour` finite · 4 not negative ·
624
+ * 5 `cost.currency` non-empty · 6 `headroom` present · 7/8 each axis a
625
+ * fraction · 9 at least one axis · 10 `errorRate` a fraction ·
626
+ * 11 `resilience.failure` non-empty · 12 verdict in the closed set ·
627
+ * 13 `rightSize` implies a `suggestion` · 14 `provenance.engine` non-empty ·
628
+ * 15 `version` non-empty · 16 `tolerance` non-empty · 17 `basis` in the closed
629
+ * set.
630
+ *
631
+ * Rules 9 and 16 are the two chant is stricter on. Rule 9 is also a type here
632
+ * ({@link BehaviourHeadroom} is a union requiring one axis), so this is the
633
+ * backstop for a JavaScript caller. And on 16, behold accepts any non-empty
634
+ * string while this rejects `n/a`, `none`, `unknown` and friends: the epic asks
635
+ * for the engine's *stated* tolerance, and a word meaning "I have none to
636
+ * state" passes behold's check while defeating its purpose.
637
+ */
638
+ export function validateBehaviourBlock(name: string, block: PredictedBehaviour): void {
639
+ const bad = (why: string): never => {
640
+ throw new Error(
641
+ `predictBehaviour produced an invalid block for "${name}": ${why}. behold's own validator ` +
642
+ "(behold/src/behaviour.ts) drops a block failing this, so it would render nothing rather than " +
643
+ "render wrong — which is worse to debug, because everything here looked legal.",
644
+ );
645
+ };
646
+
647
+ if (!isFilled(block.at?.traffic)) bad("at.traffic is missing — name the traffic level you priced");
648
+
649
+ const perHour = block.cost?.perHour;
650
+ if (typeof perHour !== "number" || !Number.isFinite(perHour)) bad("cost.perHour is not a finite number");
651
+ if ((perHour as number) < 0) bad("cost.perHour is negative");
652
+ if (!isFilled(block.cost?.currency)) bad("cost.currency is missing");
653
+
654
+ const headroom = block.headroom as { cpu?: unknown; latency?: unknown } | undefined;
655
+ if (!headroom || typeof headroom !== "object") bad("headroom is missing");
656
+ const h = headroom as { cpu?: unknown; latency?: unknown };
657
+ if (h.cpu !== undefined && !isFraction(h.cpu)) bad("headroom.cpu is not a fraction 0..1");
658
+ if (h.latency !== undefined && !isFraction(h.latency)) bad("headroom.latency is not a fraction 0..1");
659
+ if (h.cpu === undefined && h.latency === undefined) {
660
+ bad("headroom carries neither cpu nor latency — an axis you did not model is absent, and a block with no axis at all says nothing");
661
+ }
662
+
663
+ if (!isFraction(block.errorRate)) bad("errorRate is not a fraction 0..1");
664
+
665
+ if (!isFilled(block.resilience?.failure)) {
666
+ bad("resilience.failure is missing — a verdict with no named failure says nothing");
667
+ }
668
+ if (statesNothing(block.resilience.failure)) {
669
+ bad(
670
+ `resilience.failure ${JSON.stringify(block.resilience.failure)} names no failure. behold takes ` +
671
+ "any non-empty string here, so this passes its validator and renders a confident verdict about " +
672
+ 'nothing. Name the event: "one zone lost", "primary database failover"',
673
+ );
674
+ }
675
+ if (!isResilienceVerdict(block.resilience?.verdict)) {
676
+ bad(`resilience.verdict ${JSON.stringify(block.resilience?.verdict)} is not survives/degrades/fails`);
677
+ }
678
+
679
+ if (block.rightSize !== undefined && !isFilled(block.rightSize.suggestion)) {
680
+ bad("rightSize is present without a suggestion");
681
+ }
682
+
683
+ const p = block.provenance;
684
+ if (!p || typeof p !== "object") bad("provenance is missing");
685
+ if (!isFilled(p?.engine)) bad("provenance.engine is missing");
686
+ if (!isFilled(p?.version)) bad("provenance.version is missing");
687
+ if (!isFilled(p?.tolerance)) {
688
+ bad("provenance.tolerance is missing — a figure without a stated tolerance is not a prediction");
689
+ }
690
+ if (statesNothing(p.tolerance)) {
691
+ bad(
692
+ `provenance.tolerance ${JSON.stringify(p.tolerance)} states no tolerance. An engine with nothing ` +
693
+ "to say about its own error bars has no business publishing a figure; say the number, however wide",
694
+ );
695
+ }
696
+ if (!isBehaviourBasis(p?.basis)) {
697
+ bad(`provenance.basis ${JSON.stringify(p?.basis)} is not modeled/validated`);
698
+ }
699
+ }
700
+
701
+ /** What a lexicon states about the run itself. Everything else in the meta is copied from the request. */
702
+ export interface BehaviourEngineStamp {
703
+ engine: string;
704
+ version: string;
705
+ /** An estate total, when the engine states one of its own. Never chant's sum. */
706
+ total?: PredictedRate;
707
+ }
708
+
709
+ /**
710
+ * Build a {@link BehaviourReport}, and refuse to build an invalid one.
711
+ *
712
+ * Takes the request rather than a hand-assembled meta, and derives `at`,
713
+ * `edgeCoverage` and the asked-for names from it. A lexicon states only what is
714
+ * genuinely its own — which engine answered, at what version, and a total if
715
+ * the engine has one — so the three fields that must agree with the request
716
+ * cannot be restated differently.
717
+ *
718
+ * That is a check and not a proof, and the distinction matters enough to say
719
+ * plainly: {@link BehaviourReport} is a plain interface, {@link isBehaviourResult}
720
+ * accepts a hand-built one, and a lexicon calling this with
721
+ * `entityNames: Object.keys(entities)` self-certifies. What passing the request
722
+ * buys is that the ordinary route is checked and the check names what is wrong;
723
+ * a consumer that needs the guarantee runs its own
724
+ * `validateBehaviourResult(result, askedFor)` on arrival, which is #2358's and
725
+ * #2360's to write.
726
+ *
727
+ * Refusals, all naming what went wrong:
728
+ *
729
+ * - an entity in neither map — the tri-state's whole point, and the one a
730
+ * `continue` in a lexicon's loop produces silently;
731
+ * - an entity in both maps — priced and unpriced at once;
732
+ * - a figure for something nobody asked about;
733
+ * - a block priced at a level the run did not ask for;
734
+ * - an edge-coverage claim that names no gap ({@link validateEdgeCoverage});
735
+ * - any block failing {@link validateBehaviourBlock}.
736
+ */
737
+ export function behaviourReport(
738
+ request: Pick<PredictBehaviourOptions, "entityNames" | "traffic" | "edgeCoverage">,
739
+ stamp: BehaviourEngineStamp,
740
+ entities: Record<string, PredictedBehaviour>,
741
+ unpredicted?: Record<string, UnpredictedEntity>,
742
+ ): BehaviourReport {
743
+ if (!isFilled(stamp?.engine)) throw new Error("predictBehaviour: meta.engine is missing");
744
+ if (!isFilled(stamp?.version)) throw new Error("predictBehaviour: meta.version is missing");
745
+ if (!isFilled(request?.traffic)) throw new Error("predictBehaviour: meta.at.traffic is missing");
746
+ if (stamp.total && (!Number.isFinite(stamp.total.perHour) || stamp.total.perHour < 0)) {
747
+ throw new Error("predictBehaviour: meta.total.perHour is not a non-negative finite number");
748
+ }
749
+ validateEdgeCoverage(request.edgeCoverage);
750
+
751
+ const meta: BehaviourReportMeta = {
752
+ engine: stamp.engine,
753
+ version: stamp.version,
754
+ at: { traffic: request.traffic },
755
+ ...(stamp.total ? { total: stamp.total } : {}),
756
+ // Copied, not aliased. `readonly` is erased at runtime, so assigning the
757
+ // request's object by reference let a caller mutate
758
+ // `request.edgeCoverage.unresolvedKinds` after construction and change what
759
+ // the report claims it was computed over — the one field whose whole job is
760
+ // to be the report's honest account of its own inputs.
761
+ edgeCoverage: copyEdgeCoverage(request.edgeCoverage),
762
+ };
763
+ const entityNames = request.entityNames;
764
+ const asked = new Set(entityNames);
765
+ const holes = new Set(Object.keys(unpredicted ?? {}));
766
+
767
+ for (const name of Object.keys(entities)) {
768
+ if (holes.has(name)) {
769
+ throw new Error(
770
+ `predictBehaviour reported "${name}" as both priced and unpriced. An entity has one verdict.`,
771
+ );
772
+ }
773
+ if (!asked.has(name)) {
774
+ throw new Error(
775
+ `predictBehaviour returned a figure for "${name}", which was not in entityNames. An engine ` +
776
+ "answering about entities nobody asked about is answering about the wrong estate.",
777
+ );
778
+ }
779
+ validateBehaviourBlock(name, entities[name]);
780
+ if (entities[name].at.traffic !== meta.at.traffic) {
781
+ throw new Error(
782
+ `predictBehaviour priced "${name}" at ${JSON.stringify(entities[name].at.traffic)} in a run ` +
783
+ `whose meta.at.traffic is ${JSON.stringify(meta.at.traffic)}. One run, one level.`,
784
+ );
785
+ }
786
+ }
787
+
788
+ for (const name of holes) {
789
+ if (!asked.has(name)) {
790
+ throw new Error(`predictBehaviour reported "${name}" unpredicted, and it was not in entityNames.`);
791
+ }
792
+ if (!isBehaviourUnpredictedReason(unpredicted![name]?.reason)) {
793
+ throw new Error(
794
+ `predictBehaviour gave "${name}" the reason ` +
795
+ `${JSON.stringify(unpredicted![name]?.reason)}, which is not one of ` +
796
+ `${BEHAVIOUR_UNPREDICTED_REASONS.join(", ")}.`,
797
+ );
798
+ }
799
+ }
800
+
801
+ const missing = entityNames.filter(
802
+ (name) => !Object.prototype.hasOwnProperty.call(entities, name) && !holes.has(name),
803
+ );
804
+ if (missing.length > 0) {
805
+ throw new Error(
806
+ `predictBehaviour gave no verdict at all for ${missing.map((n) => `"${n}"`).join(", ")}. Every ` +
807
+ "entity asked about lands in `entities` or in `unpredicted` — there is no third position, " +
808
+ "because a prediction has no equivalent of \"the provider says it is not there\". An entity " +
809
+ "you could not price is `unsupported-kind`, not an omission.",
810
+ );
811
+ }
812
+
813
+ return {
814
+ behaviour: "v1",
815
+ meta,
816
+ entities,
817
+ ...(unpredicted && Object.keys(unpredicted).length > 0 ? { unpredicted } : {}),
818
+ };
819
+ }
820
+
821
+ /** Build a {@link BehaviourRefusalReport}. */
822
+ export function behaviourRefusal(refusal: BehaviourRefusal): BehaviourRefusalReport {
823
+ return { behaviour: "v1", refusal };
824
+ }
825
+
826
+ /* -------------------------------------------------------------------------- */
827
+ /* Comparing two results */
828
+ /* -------------------------------------------------------------------------- */
829
+
830
+ /**
831
+ * Whether two figures are a delta of like things.
832
+ *
833
+ * - `comparable` — same engine, same version, same tolerance, same basis. The
834
+ * difference between the two numbers is a difference in the estate.
835
+ * - `mixed-basis` — same engine and version, one figure `modeled` off list
836
+ * prices and the other `validated` against a bill. Subtracting these does
837
+ * not measure a change in the estate; part of the difference is the
838
+ * difference between a price list and an invoice.
839
+ * - `mixed-engine` — the engine, its version or its stated tolerance differs.
840
+ * Two models are not one scale, and a delta across them is arithmetic on
841
+ * numbers that were never on the same axis.
842
+ */
843
+ export type ProvenanceComparability = "comparable" | "mixed-basis" | "mixed-engine";
844
+
845
+ /**
846
+ * Classify a pair of *provenances*. Almost always the wrong function to call —
847
+ * see {@link compareFigures}, which is the one consumers want.
848
+ *
849
+ * The limit is structural rather than an oversight: `at` lives on
850
+ * {@link PredictedBehaviour} and not on {@link BehaviourProvenance}, so this
851
+ * function cannot see the traffic level and will happily answer `comparable`
852
+ * for a figure at 100 rps and a figure at 1000 rps. Two predictions of the same
853
+ * estate by the same engine at different levels are not a delta of like things;
854
+ * they are answers to different questions. Use this only where the two figures
855
+ * are already known to share a level.
856
+ */
857
+ export function compareProvenance(
858
+ a: BehaviourProvenance,
859
+ b: BehaviourProvenance,
860
+ ): ProvenanceComparability {
861
+ if (a.engine !== b.engine || a.version !== b.version || a.tolerance !== b.tolerance) {
862
+ return "mixed-engine";
863
+ }
864
+ return a.basis === b.basis ? "comparable" : "mixed-basis";
865
+ }
866
+
867
+ /** One axis on which two figures fail to be a delta of like things. */
868
+ export type FigureMismatch =
869
+ | "mixed-engine"
870
+ | "mixed-level"
871
+ | "mixed-basis"
872
+ | "mixed-currency"
873
+ | "mixed-failure";
874
+
875
+ /**
876
+ * The total witness, keyed by the union — the same construction the other four
877
+ * closed sets use, and this one needs it as much as any.
878
+ *
879
+ * {@link figureMismatches} filters {@link compareFigures}'s output through the
880
+ * array below. An axis added to the union and to `compareFigures` but not to
881
+ * the array would be reported by one and silently dropped by the other, which
882
+ * is exactly the "a mismatch went unsaid" failure the set return was added to
883
+ * prevent, reappearing in the display path.
884
+ *
885
+ * The value is the display rank rather than `true`, so the order is derived
886
+ * from the witness too and there is one place to state it.
887
+ */
888
+ const FIGURE_MISMATCH_WITNESS: Record<FigureMismatch, number> = {
889
+ "mixed-engine": 0,
890
+ "mixed-level": 1,
891
+ "mixed-currency": 2,
892
+ "mixed-basis": 3,
893
+ "mixed-failure": 4,
894
+ };
895
+
896
+ /**
897
+ * Every mismatch, in the order a consumer should show them — most fundamental
898
+ * first. Order is presentation; membership is the contract.
899
+ */
900
+ export const FIGURE_MISMATCHES: readonly FigureMismatch[] = (
901
+ Object.keys(FIGURE_MISMATCH_WITNESS) as FigureMismatch[]
902
+ ).sort((a, b) => FIGURE_MISMATCH_WITNESS[a] - FIGURE_MISMATCH_WITNESS[b]);
903
+
904
+ /**
905
+ * Classify a pair of figures for delta purposes. **This is the one to call.**
906
+ *
907
+ * Returns **every** axis on which the two disagree, not the first. An earlier
908
+ * version returned one label and stopped at the first mismatch, which meant a
909
+ * pair differing in level AND basis reported `mixed-level` and dropped the
910
+ * basis crossing on the floor — a consumer told "different traffic level" would
911
+ * caption it as such and show a modeled-minus-validated difference underneath
912
+ * with nothing said. Precedence is a fine way to decide what to show first and
913
+ * a bad way to decide what to know.
914
+ *
915
+ * The axes:
916
+ *
917
+ * - `mixed-engine` — engine, version or tolerance differs. Two models are not
918
+ * one scale.
919
+ * - `mixed-level` — different `at`. The same question asked of two different
920
+ * worlds.
921
+ * - `mixed-currency` — different `cost.currency`. chant converts nothing, so
922
+ * USD minus EUR is not a number. behold already refuses to *sum* these
923
+ * (`behold/src/behaviour.ts`); permitting them to be *differenced* left this
924
+ * contract laxer than its own consumer.
925
+ * - `mixed-basis` — one figure off a price list, the other off an invoice.
926
+ * - `mixed-failure` — different `resilience.failure`. "Survives one zone lost"
927
+ * against "survives a region lost" are two verdicts about two events, and
928
+ * differencing the costs beside them implies they answer the same question.
929
+ *
930
+ * The rule this contract binds its consumers to, in one sentence: **a delta
931
+ * between two figures whose mismatch set is not empty must be marked as such
932
+ * wherever it is shown, and must never be presented as a plain difference.**
933
+ * How it is marked is #2358's to choose. Whether it must be marked is not.
934
+ */
935
+ export function compareFigures(
936
+ a: PredictedBehaviour,
937
+ b: PredictedBehaviour,
938
+ ): ReadonlySet<FigureMismatch> {
939
+ const out = new Set<FigureMismatch>();
940
+ if (compareProvenance(a.provenance, b.provenance) === "mixed-engine") out.add("mixed-engine");
941
+ if (a.at.traffic !== b.at.traffic) out.add("mixed-level");
942
+ if (a.cost.currency !== b.cost.currency) out.add("mixed-currency");
943
+ if (a.provenance.basis !== b.provenance.basis) out.add("mixed-basis");
944
+ if (a.resilience.failure !== b.resilience.failure) out.add("mixed-failure");
945
+ return out;
946
+ }
947
+
948
+ /** The mismatches, ordered for display. A convenience over {@link compareFigures}. */
949
+ export function figureMismatches(a: PredictedBehaviour, b: PredictedBehaviour): FigureMismatch[] {
950
+ const found = compareFigures(a, b);
951
+ return FIGURE_MISMATCHES.filter((m) => found.has(m));
952
+ }
953
+
954
+ /** True when two whole figures may be shown as a plain difference, with no mark. */
955
+ export function isComparableFigure(a: PredictedBehaviour, b: PredictedBehaviour): boolean {
956
+ return compareFigures(a, b).size === 0;
957
+ }
958
+
959
+ /** True when two provenances may be shown as a plain difference. Level-blind — see {@link compareProvenance}. */
960
+ export function isComparableProvenance(a: BehaviourProvenance, b: BehaviourProvenance): boolean {
961
+ return compareProvenance(a, b) === "comparable";
962
+ }
963
+
964
+ /* -------------------------------------------------------------------------- */
965
+ /* Resolving an engine, and refusing when there is none */
966
+ /* -------------------------------------------------------------------------- */
967
+
968
+ /**
969
+ * The engine a lexicon predicts against, and the variable that named it.
970
+ *
971
+ * `value` is an address — a URL, a socket path, a command on `PATH`. It is
972
+ * **not** a credential and this contract has no channel for one; see
973
+ * {@link PredictBehaviourOptions}. An engine that demands authentication is out
974
+ * of scope for the plugin surface, and a lexicon that needs one must reach it
975
+ * on its own transport without routing it through here.
976
+ */
977
+ export interface BehaviourEngineEndpoint {
978
+ /** The address the lexicon will predict against. */
979
+ value: string;
980
+ /** The variable it came from, so a refusal or a log line can name it. */
981
+ source: string;
982
+ }
983
+
984
+ /**
985
+ * The variables that can name a behaviour engine, most specific first. Exported
986
+ * so a refusal message and a test can agree on the chain without restating it.
987
+ *
988
+ * `lexicon` scopes the first entry, which is what lets an estate priced by two
989
+ * engines point each lexicon at its own without a per-call flag.
990
+ */
991
+ export function behaviourEngineVariables(lexicon: string): string[] {
992
+ const scope = lexicon.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
993
+ return [`CHANT_BEHAVIOUR_ENGINE_${scope}`, "CHANT_BEHAVIOUR_ENGINE", "BEHAVIOUR_ENGINE"];
994
+ }
995
+
996
+ /**
997
+ * Resolve the engine one lexicon predicts against, most specific first. Pure —
998
+ * exported for testing.
999
+ *
1000
+ * The chain is lexicon-scoped, then chant-scoped, then bare, for the same
1001
+ * reason `gitlabNoteTokenFrom` reads `CHANT_GITLAB_TOKEN` before `GITLAB_TOKEN`
1002
+ * (`./op/activities/reconcile.ts`): the narrower name exists so a project that
1003
+ * has to differ can differ, and the wider one exists so a project that does not
1004
+ * need to sets one variable.
1005
+ *
1006
+ * Returns `undefined` when nothing in the chain answered. That is `no-engine`,
1007
+ * and the caller turns it into {@link noBehaviourEngineMessage} — never into an
1008
+ * empty report.
1009
+ */
1010
+ export function behaviourEngineFrom(
1011
+ lexicon: string,
1012
+ env: Record<string, string | undefined>,
1013
+ ): BehaviourEngineEndpoint | undefined {
1014
+ for (const source of behaviourEngineVariables(lexicon)) {
1015
+ const value = env[source]?.trim();
1016
+ if (value) return { value, source };
1017
+ }
1018
+ return undefined;
1019
+ }
1020
+
1021
+ /** What a lexicon says when no variable in the chain names an engine. */
1022
+ export function noBehaviourEngineMessage(lexicon: string): string {
1023
+ const [scoped, chantWide, bare] = behaviourEngineVariables(lexicon);
1024
+ return (
1025
+ `predictBehaviour has the ${lexicon} estate to predict and no engine to predict it with. Set a ` +
1026
+ `${chantWide} environment variable to the engine's address — a URL, a socket path, or a command on ` +
1027
+ `PATH — or ${bare} where nothing else in the environment is chant's. ${scoped} is read first, for an ` +
1028
+ "estate whose lexicons are priced by different engines. The address is not a credential: the engine " +
1029
+ "is never handed one and never writes."
1030
+ );
1031
+ }
1032
+
1033
+ /**
1034
+ * The bearer token a transport authenticates chant to an engine with, and the
1035
+ * variable that named it. The counterpart of {@link BehaviourEngineEndpoint}
1036
+ * for the second thing a metered engine needs to know: whose account this is.
1037
+ *
1038
+ * This is **not** the credential rule 3 forbids. That rule is about the
1039
+ * request body, and {@link screenBehaviourRequest} enforces it on every
1040
+ * request before any transport is reached. The token here never enters the
1041
+ * body; it goes in a header the engine reads, and the transport that sends it
1042
+ * is the only code that ever holds it.
1043
+ */
1044
+ export interface BehaviourEngineToken {
1045
+ value: string;
1046
+ /** The variable it came from, so a refusal or a log line can name it — never the value. */
1047
+ source: string;
1048
+ }
1049
+
1050
+ /**
1051
+ * The variables that can hold a behaviour engine's token, most specific first.
1052
+ * Parallel to {@link behaviourEngineVariables} and deliberately not the same
1053
+ * chain: `CHANT_BEHAVIOUR_ENGINE` is an address, and an address is printed in
1054
+ * refusals, while a token is never printed anywhere. Reusing one chain for
1055
+ * both would put the token in every message that names the address.
1056
+ */
1057
+ export function behaviourTokenVariables(lexicon: string): string[] {
1058
+ const scope = lexicon.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
1059
+ return [`CHANT_BEHAVIOUR_TOKEN_${scope}`, "CHANT_BEHAVIOUR_TOKEN", "BEHAVIOUR_TOKEN"];
1060
+ }
1061
+
1062
+ /**
1063
+ * Resolve the token one lexicon's transport authenticates with, most specific
1064
+ * first. Pure — exported for testing. The same shape as `gitlabNoteTokenFrom`
1065
+ * (`./op/activities/reconcile.ts`): a chain, the first non-empty value wins,
1066
+ * and the result names the variable so a refusal can say which one it read.
1067
+ *
1068
+ * Returns `undefined` when nothing in the chain answered. A transport whose
1069
+ * engine bills an account turns that into {@link noBehaviourTokenRefusal}
1070
+ * before sending anything: a request sent without the token is a request the
1071
+ * engine will reject, and the refusal should name the variable rather than
1072
+ * quote the engine's 401.
1073
+ */
1074
+ export function behaviourTokenFrom(
1075
+ lexicon: string,
1076
+ env: Record<string, string | undefined>,
1077
+ ): BehaviourEngineToken | undefined {
1078
+ for (const source of behaviourTokenVariables(lexicon)) {
1079
+ const value = env[source]?.trim();
1080
+ if (value) return { value, source };
1081
+ }
1082
+ return undefined;
1083
+ }
1084
+
1085
+ /** What a transport says when the engine bills an account and no variable named a token. */
1086
+ export function noBehaviourTokenMessage(lexicon: string, endpoint: BehaviourEngineEndpoint): string {
1087
+ const [scoped, chantWide, bare] = behaviourTokenVariables(lexicon);
1088
+ return (
1089
+ `predictBehaviour has the ${lexicon} behaviour engine at ${redactEngineAddress(endpoint.value)}, ` +
1090
+ `named by ${endpoint.source}, and no token to authenticate to it with, so nothing was sent. Set a ` +
1091
+ `${chantWide} environment variable to the bearer token the engine issued — or ${bare} where nothing ` +
1092
+ `else in the environment is chant's. ${scoped} is read first, for an estate whose lexicons are ` +
1093
+ "priced by different engines on different accounts. The token goes in a header the engine reads " +
1094
+ "and nowhere else; it is never in the request body and never in a message."
1095
+ );
1096
+ }
1097
+
1098
+ /**
1099
+ * The refusal for a metered engine with no token configured. `no-engine`,
1100
+ * because that is the cause whose remedy is "set a variable" — the engine is
1101
+ * named, reachable for all anyone knows, and unusable until one more variable
1102
+ * is set. No `source`: the token chain is the chain this refusal is about, and
1103
+ * nothing in it answered.
1104
+ */
1105
+ export function noBehaviourTokenRefusal(
1106
+ lexicon: string,
1107
+ endpoint: BehaviourEngineEndpoint,
1108
+ ): BehaviourRefusalReport {
1109
+ const [, chantWide] = behaviourTokenVariables(lexicon);
1110
+ return behaviourRefusal({
1111
+ cause: "no-engine",
1112
+ reason: noBehaviourTokenMessage(lexicon, endpoint),
1113
+ remedy: `Set ${chantWide} to the bearer token the engine at ${redactEngineAddress(endpoint.value)} issued.`,
1114
+ });
1115
+ }
1116
+
1117
+ /**
1118
+ * The refusal for an engine that answered and rejected the token it was sent.
1119
+ * Also `no-engine`: the address is fine, the account is not the problem, and
1120
+ * the one action is to set the named variable to a token the engine accepts.
1121
+ * `source` is the token variable, not the address variable, because that is
1122
+ * the one a consumer would tell somebody to change.
1123
+ *
1124
+ * `detail` is whatever the engine said, and it goes through
1125
+ * {@link scrubEngineDetail}. The token's own value is never in a message: a
1126
+ * transport passes the variable's name here and keeps the value to itself.
1127
+ */
1128
+ export function rejectedBehaviourTokenRefusal(
1129
+ lexicon: string,
1130
+ endpoint: BehaviourEngineEndpoint,
1131
+ token: BehaviourEngineToken,
1132
+ detail: string,
1133
+ ): BehaviourRefusalReport {
1134
+ return behaviourRefusal({
1135
+ cause: "no-engine",
1136
+ reason:
1137
+ `The ${lexicon} behaviour engine at ${redactEngineAddress(endpoint.value)}, named by ` +
1138
+ `${endpoint.source}, answered and rejected the token ${token.source} holds ` +
1139
+ `(${scrubEngineDetail(detail)}). The address is reachable and the account is not the problem; ` +
1140
+ "the token is not one this engine accepts. No overlay is drawn and no figure is guessed locally.",
1141
+ remedy: `Set ${token.source} to a bearer token the engine at ${redactEngineAddress(endpoint.value)} accepts.`,
1142
+ source: token.source,
1143
+ });
1144
+ }
1145
+
1146
+ /** What a lexicon says when a variable named an engine and the engine did not answer. */
1147
+ export function unreachableBehaviourEngineMessage(
1148
+ lexicon: string,
1149
+ endpoint: BehaviourEngineEndpoint,
1150
+ detail: string,
1151
+ ): string {
1152
+ return (
1153
+ `predictBehaviour reached for the ${lexicon} behaviour engine at ${redactEngineAddress(endpoint.value)}, ` +
1154
+ `named by ${endpoint.source}, and it did not answer: ${scrubEngineDetail(detail)}. No overlay is drawn and no figure is ` +
1155
+ `guessed locally. Check the engine is up and that ${endpoint.source} names the address this ` +
1156
+ "environment can reach."
1157
+ );
1158
+ }
1159
+
1160
+ /**
1161
+ * The refusal for an estate with no engine configured. The whole of the
1162
+ * `no-engine` path, so no lexicon has to assemble one by hand.
1163
+ */
1164
+ export function noBehaviourEngineRefusal(lexicon: string): BehaviourRefusalReport {
1165
+ const [, chantWide] = behaviourEngineVariables(lexicon);
1166
+ return behaviourRefusal({
1167
+ cause: "no-engine",
1168
+ reason: noBehaviourEngineMessage(lexicon),
1169
+ remedy: `Set ${chantWide} to the engine's address.`,
1170
+ });
1171
+ }
1172
+
1173
+ /** The refusal for a configured engine that did not answer. */
1174
+ export function unreachableBehaviourEngineRefusal(
1175
+ lexicon: string,
1176
+ endpoint: BehaviourEngineEndpoint,
1177
+ detail: string,
1178
+ ): BehaviourRefusalReport {
1179
+ return behaviourRefusal({
1180
+ cause: "engine-unreachable",
1181
+ reason: unreachableBehaviourEngineMessage(lexicon, endpoint, detail),
1182
+ remedy: `Check the engine at ${redactEngineAddress(endpoint.value)} is reachable, or repoint ${endpoint.source}.`,
1183
+ source: endpoint.source,
1184
+ });
1185
+ }
1186
+
1187
+ /**
1188
+ * What a lexicon says when the engine answered and refused for want of money
1189
+ * (#2359). Distinct from unreachable on purpose: the address is fine, the
1190
+ * request arrived, and telling somebody to check their networking wastes the
1191
+ * one thing a refusal is for.
1192
+ */
1193
+ export function outOfCreditBehaviourEngineMessage(
1194
+ lexicon: string,
1195
+ endpoint: BehaviourEngineEndpoint,
1196
+ detail: string,
1197
+ ): string {
1198
+ return (
1199
+ `The ${lexicon} behaviour engine at ${redactEngineAddress(endpoint.value)}, named by ${endpoint.source}, ` +
1200
+ `answered and refused: the account behind it is out of credit (${scrubEngineDetail(detail)}). The address is reachable and nothing ` +
1201
+ "here is a networking problem. Add credit to the account this engine bills, or point " +
1202
+ `${endpoint.source} at an engine on an account that has some. No overlay is drawn and no figure is ` +
1203
+ "guessed locally."
1204
+ );
1205
+ }
1206
+
1207
+ /** What a lexicon says when the engine answered and refused for a spent limit (#2359). */
1208
+ export function overQuotaBehaviourEngineMessage(
1209
+ lexicon: string,
1210
+ endpoint: BehaviourEngineEndpoint,
1211
+ detail: string,
1212
+ ): string {
1213
+ return (
1214
+ `The ${lexicon} behaviour engine at ${redactEngineAddress(endpoint.value)}, named by ${endpoint.source}, ` +
1215
+ `answered and refused: a rate or volume limit is spent (${scrubEngineDetail(detail)}). The account has credit and the address is ` +
1216
+ "reachable, so this usually clears when the engine's window rolls over. Wait for it, raise the limit " +
1217
+ `on the account, or point ${endpoint.source} at an engine with its own budget. No overlay is drawn ` +
1218
+ "and no figure is guessed locally."
1219
+ );
1220
+ }
1221
+
1222
+ /** The refusal for an engine that answered and said the account has no balance (#2359). */
1223
+ export function outOfCreditBehaviourEngineRefusal(
1224
+ lexicon: string,
1225
+ endpoint: BehaviourEngineEndpoint,
1226
+ detail: string,
1227
+ ): BehaviourRefusalReport {
1228
+ return behaviourRefusal({
1229
+ cause: "engine-out-of-credit",
1230
+ reason: outOfCreditBehaviourEngineMessage(lexicon, endpoint, detail),
1231
+ remedy: `Add credit to the account behind ${endpoint.source}, or repoint it at a funded engine.`,
1232
+ source: endpoint.source,
1233
+ });
1234
+ }
1235
+
1236
+ /** The refusal for an engine that answered and said a limit is spent (#2359). */
1237
+ export function overQuotaBehaviourEngineRefusal(
1238
+ lexicon: string,
1239
+ endpoint: BehaviourEngineEndpoint,
1240
+ detail: string,
1241
+ ): BehaviourRefusalReport {
1242
+ return behaviourRefusal({
1243
+ cause: "engine-over-quota",
1244
+ reason: overQuotaBehaviourEngineMessage(lexicon, endpoint, detail),
1245
+ remedy: `Wait for the engine's window to roll over, or raise the limit on the account behind ${endpoint.source}.`,
1246
+ source: endpoint.source,
1247
+ });
1248
+ }
1249
+
1250
+ /* -------------------------------------------------------------------------- */
1251
+ /* The transport */
1252
+ /* -------------------------------------------------------------------------- */
1253
+
1254
+ /**
1255
+ * What a transport brings back: the engine's answer as the text it wrote, or a
1256
+ * refusal ready to be returned from `predictBehaviour` as it stands.
1257
+ *
1258
+ * The answer is text rather than a parsed object because what the text means
1259
+ * is the lexicon's wire version (`augur/v1`), and the lexicon is the one that
1260
+ * validates it — an answer that fails that validation is
1261
+ * {@link unreachableBehaviourEngineRefusal} with a detail naming the field,
1262
+ * built by the lexicon, since the transport has nothing to say about it.
1263
+ */
1264
+ export type BehaviourTransportOutcome =
1265
+ | { ok: true; body: string }
1266
+ | { ok: false; refusal: BehaviourRefusalReport };
1267
+
1268
+ /**
1269
+ * The seam between a lexicon and whatever answers its request (#2373).
1270
+ *
1271
+ * One method. `body` is the request as the lexicon rendered it — augur's
1272
+ * canonical JSON, say — and the transport carries it to the address it was
1273
+ * built for and brings back what came out, or a refusal naming why nothing
1274
+ * did. A transport is built knowing the lexicon and the endpoint, which is
1275
+ * what lets it build the refusal itself; see the module doc for why that is
1276
+ * better than returning a cause.
1277
+ *
1278
+ * Two ship today: `./behaviour-http.ts` dials a URL with a bearer token, and
1279
+ * augur's `commandTransport` spawns a command on `PATH` with
1280
+ * {@link behaviourEngineChildEnvironment}. A lexicon picks one by the shape of
1281
+ * the address and does not otherwise know which it got.
1282
+ */
1283
+ export interface BehaviourTransport {
1284
+ send(body: string): Promise<BehaviourTransportOutcome>;
1285
+ }
1286
+
1287
+ /**
1288
+ * The three things a wire can say that are the engine's to answer for, and
1289
+ * that each want a different refusal. `no-engine` is not here: it is decided
1290
+ * before a transport exists (an unset address) or by the transport's own
1291
+ * constructor (an unset token), never by the wire.
1292
+ */
1293
+ export type BehaviourWireCause = "engine-unreachable" | "engine-out-of-credit" | "engine-over-quota";
1294
+
1295
+ /**
1296
+ * One wire cause onto the refusal builder that names it. The whole of the
1297
+ * mapping every transport applies, so it is written once: a transport that
1298
+ * classified the wire correctly and then reached for the wrong builder would
1299
+ * send an operator to check a network that is answering.
1300
+ */
1301
+ export function behaviourWireRefusal(
1302
+ lexicon: string,
1303
+ endpoint: BehaviourEngineEndpoint,
1304
+ cause: BehaviourWireCause,
1305
+ detail: string,
1306
+ ): BehaviourRefusalReport {
1307
+ switch (cause) {
1308
+ case "engine-out-of-credit":
1309
+ return outOfCreditBehaviourEngineRefusal(lexicon, endpoint, detail);
1310
+ case "engine-over-quota":
1311
+ return overQuotaBehaviourEngineRefusal(lexicon, endpoint, detail);
1312
+ case "engine-unreachable":
1313
+ return unreachableBehaviourEngineRefusal(lexicon, endpoint, detail);
1314
+ }
1315
+ }
1316
+
1317
+ /**
1318
+ * The environment a transport hands a child process: `PATH`, and nothing else.
1319
+ *
1320
+ * Rule 3 says the engine never sees a credential, and
1321
+ * {@link screenBehaviourRequest} enforces it on the request. A child that
1322
+ * inherits `process.env` walks straight around that: the request is spotless
1323
+ * and the child holds `AWS_SECRET_ACCESS_KEY` anyway. So a transport that
1324
+ * spawns builds the environment from this and nothing more — `PATH` because
1325
+ * the address is resolved against it, and no allowlist beyond that, because
1326
+ * every name added is a name a credential could be sitting under. augur's
1327
+ * command transport pins this by test (#2372); this is the rule it pins.
1328
+ */
1329
+ export function behaviourEngineChildEnvironment(
1330
+ env: Record<string, string | undefined> = process.env,
1331
+ ): Record<string, string> {
1332
+ return { PATH: env.PATH ?? "" };
1333
+ }
1334
+
1335
+ /* -------------------------------------------------------------------------- */
1336
+ /* Rendering */
1337
+ /* -------------------------------------------------------------------------- */
1338
+
1339
+ const RED = "\x1b[31m";
1340
+ const RESET = "\x1b[0m";
1341
+
1342
+ /**
1343
+ * Render a refusal for a terminal, in red.
1344
+ *
1345
+ * Red rather than the amber a degradation gets, because a missing engine is not
1346
+ * a partial answer: every behaviour-derived figure and colour is gone, and the
1347
+ * one thing the reader must not do is assume the numbers are merely late.
1348
+ *
1349
+ * `color` defaults to the same rule the rest of the CLI uses (`NO_COLOR`, and a
1350
+ * TTY on stdout); pass it explicitly where the output is asserted on.
1351
+ */
1352
+ export function renderBehaviourRefusal(
1353
+ refusal: BehaviourRefusal,
1354
+ options: { color?: boolean } = {},
1355
+ ): string {
1356
+ const color = options.color ?? (!process.env.NO_COLOR && process.stdout.isTTY !== false);
1357
+ const body = `behaviour: refused (${refusal.cause}) — ${refusal.reason}\n ${refusal.remedy}`;
1358
+ return color ? `${RED}${body}${RESET}` : body;
1359
+ }
1360
+
1361
+ /* -------------------------------------------------------------------------- */
1362
+ /* The request */
1363
+ /* -------------------------------------------------------------------------- */
1364
+
1365
+ /**
1366
+ * Names this contract refuses to carry, each declared `?: never` on
1367
+ * {@link PredictBehaviourOptions} so the deliberate attempt is a compile error.
1368
+ *
1369
+ * This list is the *narrow* half of the guard and never the whole of it. A
1370
+ * denylist of names cannot enforce "the engine never sees a credential" — the
1371
+ * same argument that made `?: never` better than omission applies to every name
1372
+ * the list omits, and `xApiKey`, `pat` and `Authorization` with a capital A all
1373
+ * sailed past an earlier version of this file. What actually enforces the rule
1374
+ * is {@link assertNoCredentialInOptions}, which walks values.
1375
+ */
1376
+ export const CREDENTIAL_OPTION_KEYS: readonly string[] = [
1377
+ "token",
1378
+ "credential",
1379
+ "credentials",
1380
+ "secret",
1381
+ "secrets",
1382
+ "password",
1383
+ "apiKey",
1384
+ "accessKey",
1385
+ "secretKey",
1386
+ "sessionToken",
1387
+ "auth",
1388
+ "authorization",
1389
+ "bearer",
1390
+ "privateKey",
1391
+ ];
1392
+
1393
+ /**
1394
+ * Key names that are credential-shaped on their own but not as a substring —
1395
+ * the two `CREDENTIAL_ENV_NAME` (./identity.ts) does not cover.
1396
+ */
1397
+ const EXTRA_CREDENTIAL_KEYS: readonly string[] = ["pat", "cookie"];
1398
+
1399
+ /**
1400
+ * Shortest string worth suspecting. Borrowed from `identity.ts`'s
1401
+ * `MIN_CREDENTIAL_LENGTH`, and for the same reason: below it, a "secret" is a
1402
+ * false positive.
1403
+ */
1404
+ const MIN_CREDENTIAL_LENGTH = 8;
1405
+
1406
+ /**
1407
+ * Key suffixes that name a **reference to** a credential rather than a
1408
+ * credential, and the handful of whole names that do the same.
1409
+ *
1410
+ * This is the correction that made the guard usable. Run over every distinct
1411
+ * property key in this repo's own generated schemas, a bare substring match on
1412
+ * `SECRET|TOKEN|PASSWORD|AUTH` refused 406 aws keys, 173 azure, 89 gcp and 7
1413
+ * k8s — `imagePullSecrets`, `secretName`, `secretKeyRef` (all three are
1414
+ * references to a Secret *by name*), `ClientToken` (an idempotency nonce on
1415
+ * dozens of AWS resources), `CertificateAuthorityArn`, `authorizedNetworks`,
1416
+ * `passwordPolicy`, `authMode`, `oauthScopes`. A `tags: { author: "…" }` was
1417
+ * refused because `author` contains `auth`.
1418
+ *
1419
+ * None of those hold secret material, and every one of them is ordinary in real
1420
+ * infrastructure, which #2357, #2359 and #2360 all assemble their requests from.
1421
+ */
1422
+ const REFERENCE_KEY_SUFFIXES: readonly string[] = [
1423
+ "ref",
1424
+ "refs",
1425
+ "name",
1426
+ "names",
1427
+ "id",
1428
+ "ids",
1429
+ "arn",
1430
+ "arns",
1431
+ "count",
1432
+ "validity",
1433
+ "mode",
1434
+ "modes",
1435
+ "policy",
1436
+ "policies",
1437
+ "scope",
1438
+ "scopes",
1439
+ "network",
1440
+ "networks",
1441
+ "type",
1442
+ "types",
1443
+ "enabled",
1444
+ "required",
1445
+ "version",
1446
+ "uri",
1447
+ "url",
1448
+ "urls",
1449
+ "config",
1450
+ "configs",
1451
+ "settings",
1452
+ "options",
1453
+ ];
1454
+
1455
+ /** Whole key names that are never credential material, whatever they contain. */
1456
+ const REFERENCE_KEY_NAMES: readonly string[] = [
1457
+ "imagepullsecrets",
1458
+ "clienttoken",
1459
+ // A Kubernetes boolean: "mount the service account's token into this pod".
1460
+ // It holds no token and never did.
1461
+ "automountserviceaccounttoken",
1462
+ "author",
1463
+ "authors",
1464
+ "authority",
1465
+ "secretsmanager",
1466
+ ];
1467
+
1468
+ /**
1469
+ * `CREDENTIAL_ENV_NAME` with its underscores removed, derived from the same
1470
+ * source so the two cannot drift.
1471
+ *
1472
+ * That pattern was written for environment variables, where the convention is
1473
+ * `AWS_SECRET_ACCESS_KEY`, so several of its alternatives carry an underscore:
1474
+ * `PRIVATE_KEY`, `ACCESS_KEY`, `SESSION_KEY`. Object keys are written
1475
+ * `privateKey` and `accessKey`, which match none of them. Squashing both sides
1476
+ * makes one rule cover `PRIVATE_KEY`, `privateKey`, `private-key` and
1477
+ * `privatekey`.
1478
+ */
1479
+ const CREDENTIAL_ENV_NAME_SQUASHED = new RegExp(CREDENTIAL_ENV_NAME.source.replace(/_/g, ""), "i");
1480
+
1481
+ /**
1482
+ * True when a string carries a password in userinfo — with or without a scheme.
1483
+ *
1484
+ * The scheme-less half matters: a DSN is routinely written
1485
+ * `app:hunter2@db.internal:5432/prod`, with the driver supplying the scheme, and
1486
+ * `new URL()` will not parse that at all.
1487
+ */
1488
+ function hasUrlPassword(value: string): boolean {
1489
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
1490
+ try {
1491
+ if (new URL(value).password !== "") return true;
1492
+ } catch {
1493
+ /* fall through to the scheme-less test */
1494
+ }
1495
+ }
1496
+ // `user:pass@host` with no scheme. Both halves non-empty, no whitespace, and
1497
+ // a host that looks like a host, so `mailto`-ish text and prose do not match.
1498
+ return /^[^\s:@/]+:[^\s:@/]+@[A-Za-z0-9._-]+(?::\d+)?(?:[/?#]|$)/.test(value.trim());
1499
+ }
1500
+
1501
+ /**
1502
+ * True when a key name is credential-shaped, whatever its casing or separators.
1503
+ *
1504
+ * Reuses `CREDENTIAL_ENV_NAME`, which is a case-insensitive substring match over
1505
+ * `SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIAL|PRIVATE_KEY|APIKEY|API_KEY|ACCESS_KEY|SESSION_KEY|AUTH`.
1506
+ * That one expression covers `Authorization`, `xApiKey`, `clientSecret`,
1507
+ * `refreshToken`, `awsSecretAccessKey` and `x-api-key` — every name an earlier
1508
+ * fixed 14-entry list here missed — because it is chant's existing answer to
1509
+ * the same question and had already been widened by everyone who hit a gap.
1510
+ */
1511
+ function isCredentialKey(key: string): boolean {
1512
+ const squashed = key.toLowerCase().replace(/[^a-z0-9]/g, "");
1513
+ if (REFERENCE_KEY_NAMES.includes(squashed)) return false;
1514
+ if (REFERENCE_KEY_SUFFIXES.some((s) => squashed.endsWith(s))) return false;
1515
+ if (EXTRA_CREDENTIAL_KEYS.includes(squashed)) return true;
1516
+ return CREDENTIAL_ENV_NAME.test(key) || CREDENTIAL_ENV_NAME_SQUASHED.test(squashed);
1517
+ }
1518
+
1519
+ /**
1520
+ * True when a string is evidently a *pointer to* a secret rather than one.
1521
+ *
1522
+ * `AdminPassword` on `AWS::DirectoryService::MicrosoftAD` is a genuine
1523
+ * credential field, and chant source almost always fills it with a
1524
+ * `{{resolve:secretsmanager:…}}` string or an interpolation rather than a
1525
+ * literal. Refusing those would refuse the correct way to write it.
1526
+ */
1527
+ function looksLikeSecretReference(value: string): boolean {
1528
+ return (
1529
+ /^\{\{[^}]+\}\}$/.test(value.trim()) ||
1530
+ /^\$\{[^}]+\}$/.test(value.trim()) ||
1531
+ /^!(?:Ref|GetAtt|Sub|ImportValue)\b/.test(value.trim()) ||
1532
+ /^arn:[a-z0-9-]*:secretsmanager:/i.test(value.trim()) ||
1533
+ /^projects\/[^/]+\/secrets\/[^/]+/.test(value.trim())
1534
+ );
1535
+ }
1536
+
1537
+ /**
1538
+ * What a credential-shaped value is, or `undefined`. Named so a refusal can say
1539
+ * which rule fired rather than "something looked wrong".
1540
+ */
1541
+ function credentialValueShape(value: string): string | undefined {
1542
+ for (const re of CREDENTIAL_SHAPES) {
1543
+ re.lastIndex = 0;
1544
+ if (re.test(value)) return "a literal credential shape (PEM key, JWT or Authorization value)";
1545
+ }
1546
+ for (const { name, re } of CREDENTIAL_TOKEN_SHAPES) {
1547
+ re.lastIndex = 0;
1548
+ if (re.test(value)) return name;
1549
+ }
1550
+ if (hasUrlPassword(value)) return "a password in a URL's userinfo";
1551
+ return undefined;
1552
+ }
1553
+
1554
+ /** A URL-ish string with its userinfo blanked and its query dropped. */
1555
+ function stripUrlSecrets(value: string): string {
1556
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return value;
1557
+ try {
1558
+ const url = new URL(value);
1559
+ const hadUserinfo = url.username !== "" || url.password !== "";
1560
+ const hadQuery = url.search !== "";
1561
+ // The fragment too. OAuth's implicit flow puts the access token there
1562
+ // (`#access_token=…`), it never reaches a server, and it was untouched.
1563
+ const hadFragment = url.hash !== "";
1564
+ url.username = "";
1565
+ url.password = "";
1566
+ url.search = "";
1567
+ url.hash = "";
1568
+ // Markers are appended AFTER `toString()` and in wire order — query then
1569
+ // fragment. Appending the query marker to a string that still carried a
1570
+ // fragment used to land it inside the fragment.
1571
+ let out = url.toString();
1572
+ if (hadUserinfo) out = out.replace("://", `://${REDACTED}@`);
1573
+ if (hadQuery) out += `?${REDACTED}`;
1574
+ if (hadFragment) out += `#${REDACTED}`;
1575
+ return out;
1576
+ } catch {
1577
+ return value;
1578
+ }
1579
+ }
1580
+
1581
+ /**
1582
+ * Blank the value of an inline command-line flag: `--token=x`, `-p x`,
1583
+ * `--api-key x`. A behaviour engine may be a command on `PATH`, and a command
1584
+ * carries its credential as an argument rather than in a URL, so the URL parse
1585
+ * has nothing to bite on and `redactCredentialMaterial` — which knows env
1586
+ * values and ten token prefixes — sees an inline flag value as neither.
1587
+ */
1588
+ function stripFlagSecrets(value: string): string {
1589
+ return value
1590
+ .replace(
1591
+ /(--?[A-Za-z0-9-]*(?:secret|token|password|passwd|key|credential|auth|pat)[A-Za-z0-9-]*)([=\s])(\S+)/gi,
1592
+ (_m, flag: string, sep: string) => `${flag}${sep}${REDACTED}`,
1593
+ )
1594
+ .replace(/(^|\s)(-[pPkK])(\s+)(\S+)/g, (_m, lead: string, flag: string, sp: string) => `${lead}${flag}${sp}${REDACTED}`);
1595
+ }
1596
+
1597
+ /**
1598
+ * An engine address, safe to interpolate into a refusal that a merge-request
1599
+ * comment will carry (#2358).
1600
+ *
1601
+ * `CHANT_BEHAVIOUR_ENGINE=https://svc:s3cr3t@engine.internal/predict?key=abc` is
1602
+ * an ordinary way to point at an authenticated endpoint, and it is the shape
1603
+ * this contract's own "resolve auth on your own transport" guidance produces.
1604
+ * Printing it verbatim in a refusal publishes it.
1605
+ *
1606
+ * Three passes, in order:
1607
+ *
1608
+ * 1. The URL parse blanks `username`/`password`, and drops the query string and
1609
+ * the fragment **whole** rather than by known parameter name — `?key=`,
1610
+ * `?token=`, `?sig=` and `#access_token=` are all common and the set is not
1611
+ * enumerable. The fragment matters on its own account: OAuth's implicit
1612
+ * flow puts the access token there.
1613
+ * 2. Inline command-line flag values (`--token=…`, `-p …`), for an engine that
1614
+ * is a command on `PATH` rather than a URL.
1615
+ * 3. {@link redactCredentialMaterial}, for env-held values and the token
1616
+ * shapes chant knows.
1617
+ *
1618
+ * **What survives:** a credential written as a bare path segment
1619
+ * (`https://host/predict/<token>/go`) unless it matches a known token shape.
1620
+ * Nothing here can tell that segment from a resource id, and an earlier version
1621
+ * of this doc claimed pass 3 caught it, which was wrong. If an engine
1622
+ * authenticates by path, do not put its address in a variable whose refusal
1623
+ * text is published.
1624
+ */
1625
+ export function redactEngineAddress(
1626
+ value: string,
1627
+ env: Record<string, string | undefined> = process.env,
1628
+ ): string {
1629
+ return redactCredentialMaterial(stripFlagSecrets(stripUrlSecrets(value)), env);
1630
+ }
1631
+
1632
+ /**
1633
+ * Engine-supplied detail, bounded and scrubbed before it reaches a refusal.
1634
+ *
1635
+ * `detail` on a credit or quota refusal is whatever the engine said, echoed.
1636
+ * An engine is a third party: it can be verbose, and it can quote the request
1637
+ * back at you, which is how a URL or an id ends up in a public comment. So the
1638
+ * text is truncated, anything URL-shaped is reduced to its host, and the result
1639
+ * goes through {@link redactCredentialMaterial}.
1640
+ */
1641
+ export function scrubEngineDetail(
1642
+ detail: string,
1643
+ env: Record<string, string | undefined> = process.env,
1644
+ ): string {
1645
+ const withoutUrls = detail.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi, (match) => {
1646
+ try {
1647
+ return new URL(match).host || REDACTED;
1648
+ } catch {
1649
+ return REDACTED;
1650
+ }
1651
+ });
1652
+ const scrubbed = redactCredentialMaterial(withoutUrls, env).replace(/\s+/g, " ").trim();
1653
+ return scrubbed.length > MAX_ENGINE_DETAIL ? `${scrubbed.slice(0, MAX_ENGINE_DETAIL)}…` : scrubbed;
1654
+ }
1655
+
1656
+ /** How much engine-supplied text a refusal will repeat. */
1657
+ const MAX_ENGINE_DETAIL = 200;
1658
+
1659
+ /**
1660
+ * How complete a request's edge list is (#2360).
1661
+ *
1662
+ * - `complete` — every reference between the named entities is in `edges`.
1663
+ * Only claim this when the builder knows it: a declared-path build walking
1664
+ * resolved `AttrRef`s does, a live rebuild over a partial catalog does not.
1665
+ * - `partial` — some references are known to be missing, and `dangling` or
1666
+ * `unresolvedKinds` says which. An engine may still answer, and should
1667
+ * discount its own confidence.
1668
+ * - `unknown` — the builder cannot say. Treat like `partial` and trust nothing
1669
+ * that depends on reachability.
1670
+ */
1671
+ export type EdgeCoverageVerdict = "complete" | "partial" | "unknown";
1672
+
1673
+ const EDGE_COVERAGE_WITNESS: Record<EdgeCoverageVerdict, true> = {
1674
+ complete: true,
1675
+ partial: true,
1676
+ unknown: true,
1677
+ };
1678
+
1679
+ /** Every legal {@link EdgeCoverageVerdict}. */
1680
+ export const EDGE_COVERAGE_VERDICTS: readonly EdgeCoverageVerdict[] = Object.keys(
1681
+ EDGE_COVERAGE_WITNESS,
1682
+ ) as EdgeCoverageVerdict[];
1683
+
1684
+ /** True when `value` is a legal {@link EdgeCoverageVerdict}. */
1685
+ export function isEdgeCoverageVerdict(value: unknown): value is EdgeCoverageVerdict {
1686
+ return typeof value === "string" && (EDGE_COVERAGE_VERDICTS as readonly string[]).includes(value);
1687
+ }
1688
+
1689
+ /**
1690
+ * What a caller knows about the completeness of the graph it is handing over.
1691
+ *
1692
+ * Note on `complete` with a non-empty {@link dangling}: that is **not** a
1693
+ * contradiction and must not be "fixed". A dangling reference points at
1694
+ * something outside the named entity set by definition — a cross-account VPC, a
1695
+ * resource another team owns — so a builder can have found every edge among the
1696
+ * entities it was asked about and still have references leaving the estate.
1697
+ * `complete` is a claim about the edges *between the named entities*.
1698
+ */
1699
+ export interface BehaviourEdgeCoverage {
1700
+ verdict: EdgeCoverageVerdict;
1701
+ /**
1702
+ * References that resolved to no entity in this request — the `dangling` list
1703
+ * `reconstructEdges` (./graph-refs.ts) already returns and used to discard.
1704
+ *
1705
+ * `DanglingRef`, not a flattened string. The record carries `from`, and `from`
1706
+ * is the field that says *which* entity's path leaves the estate; flattening
1707
+ * to the target value alone leaves an engine knowing that something dangles
1708
+ * and not what.
1709
+ */
1710
+ dangling?: readonly DanglingRef[];
1711
+ /**
1712
+ * Entity types the builder has no reference rules for, so nothing was looked
1713
+ * for. This is the quiet one: a kind with no `RefRule` produces no edges and
1714
+ * no complaint.
1715
+ */
1716
+ unresolvedKinds?: readonly string[];
1717
+ /**
1718
+ * Containment as traversable edges — populate from
1719
+ * `reconstructEdges().containmentEdges` (./graph-refs.ts), **not** from the
1720
+ * `containment: ContainmentPair[]` field beside it. The two are the same
1721
+ * relationships in two shapes, and only the edge shape belongs here; the
1722
+ * field was called `containment` and pointed #2360 straight at the wrong one.
1723
+ *
1724
+ * Carried separately from {@link PredictBehaviourOptions.edges} because
1725
+ * `chant graph` draws containment as a boundary rather than a line, and
1726
+ * putting it in `edges` would draw a line from every resource to its VPC. An
1727
+ * engine asked whether an estate survives one zone lost needs the membership
1728
+ * and `edges` will never have it.
1729
+ */
1730
+ containmentEdges?: readonly IREdge[];
1731
+ }
1732
+
1733
+ /**
1734
+ * Refuse an edge-coverage claim that does not say anything.
1735
+ *
1736
+ * `partial` means "some references are known to be missing", and a `partial`
1737
+ * with neither `dangling` nor `unresolvedKinds` names none of them — which is
1738
+ * `unknown` wearing a more confident word. Use `unknown` for "I cannot say";
1739
+ * `partial` is for "I can say, and here it is".
1740
+ */
1741
+ /**
1742
+ * A detached copy, frozen. The report's account of its own inputs must not
1743
+ * change after the report exists, and `readonly` buys nothing at runtime.
1744
+ */
1745
+ export function copyEdgeCoverage(coverage: BehaviourEdgeCoverage): BehaviourEdgeCoverage {
1746
+ const copy: BehaviourEdgeCoverage = {
1747
+ verdict: coverage.verdict,
1748
+ ...(coverage.dangling ? { dangling: Object.freeze(coverage.dangling.map((d) => Object.freeze({ ...d }))) } : {}),
1749
+ ...(coverage.unresolvedKinds ? { unresolvedKinds: Object.freeze([...coverage.unresolvedKinds]) } : {}),
1750
+ ...(coverage.containmentEdges
1751
+ ? { containmentEdges: Object.freeze(coverage.containmentEdges.map((e) => Object.freeze({ ...e }))) }
1752
+ : {}),
1753
+ };
1754
+ return Object.freeze(copy);
1755
+ }
1756
+
1757
+ export function validateEdgeCoverage(coverage: BehaviourEdgeCoverage): void {
1758
+ if (!isEdgeCoverageVerdict(coverage?.verdict)) {
1759
+ throw new Error(
1760
+ `predictBehaviour: edgeCoverage.verdict ${JSON.stringify(coverage?.verdict)} is not ` +
1761
+ `${EDGE_COVERAGE_VERDICTS.join("/")}.`,
1762
+ );
1763
+ }
1764
+ if (
1765
+ coverage.verdict === "partial" &&
1766
+ (coverage.dangling?.length ?? 0) === 0 &&
1767
+ (coverage.unresolvedKinds?.length ?? 0) === 0
1768
+ ) {
1769
+ throw new Error(
1770
+ 'predictBehaviour: edgeCoverage is "partial" and names nothing missing. Populate `dangling` ' +
1771
+ 'or `unresolvedKinds`, or say "unknown" — a partial that lists no gap is an unknown with a ' +
1772
+ "more confident word on it.",
1773
+ );
1774
+ }
1775
+ }
1776
+
1777
+ /**
1778
+ * What core hands a lexicon's `predictBehaviour`.
1779
+ *
1780
+ * The first seven fields are `observeResourcesDeep`'s options, field for field
1781
+ * and doc for doc, so a caller that already drives the deep read drives this
1782
+ * with the same object plus `traffic`. That is the point of the mirror: the two
1783
+ * reads answer different questions about the same request.
1784
+ *
1785
+ * The `?: never` block is the enforcement half of "the engine never sees
1786
+ * credentials". Declaring the keys rather than omitting them buys a real check:
1787
+ * an omitted key is only caught by the excess-property check on an object
1788
+ * literal, and slips through a spread or a widened variable, while `never`
1789
+ * rejects a `string` from any position and names the field in the error.
1790
+ */
1791
+ export interface PredictBehaviourOptions {
1792
+ environment: string;
1793
+ buildOutput: string;
1794
+ entityNames: string[];
1795
+ entities: Map<string, { entityType: string; props: Record<string, unknown> }>;
1796
+ /** Deployed stack to predict for, in a multi-stack project (see `stacks` in `ChantConfig`). */
1797
+ stack?: string;
1798
+ /** Region the stack is deployed in, mirroring the deep read (#1267). Omitted keeps the ambient default. */
1799
+ region?: string;
1800
+ /** Restrict to chant-owned resources (#119). An entity withheld here is `filtered`, not absent. */
1801
+ owned?: boolean;
1802
+ /**
1803
+ * The traffic level to predict at, verbatim: `100 rps, p50`. The one field
1804
+ * the deep read has no counterpart for, and the reason a prediction can never
1805
+ * be mistaken for an observation — an observation is not *at* anything.
1806
+ *
1807
+ * chant does not parse it, does not default it, and does not convert it. An
1808
+ * engine that cannot understand the level it was handed refuses; it does not
1809
+ * substitute one it likes better.
1810
+ */
1811
+ traffic: string;
1812
+ /**
1813
+ * The edges between the entities above (#2355) — the half of "a resource
1814
+ * graph" that a bag of nodes is not.
1815
+ *
1816
+ * This is the one field where the mirror of `observeResourcesDeep`'s options
1817
+ * deliberately breaks, and it breaks because the two reads want different
1818
+ * things. A deep read answers per entity and needs no neighbours: an S3
1819
+ * bucket's live property tree is the same tree whether or not a Lambda reads
1820
+ * from it. A prediction is the opposite. Headroom, an error rate and a
1821
+ * resilience verdict under "one zone lost" are all statements about a path
1822
+ * through the estate, and an engine handed nodes alone can only price each
1823
+ * box in isolation, which is the arithmetic a consumer could already do for
1824
+ * itself.
1825
+ *
1826
+ * `IREdge` (./graph-ir.ts) rather than an edge type of this contract's own,
1827
+ * for one reason that outranks the tidiness of a purpose-built shape: it is
1828
+ * already the engine-neutral edge that BOTH paths produce. `collectEdges`
1829
+ * builds them from declared `AttrRef`s and lexicon-resolved entity
1830
+ * references on the declared path, and `reconstructEdges` (./graph-refs.ts)
1831
+ * rebuilds them from observed physical identifiers on the live path, which
1832
+ * is the path #2360 assembles this request on. A second edge type here would
1833
+ * put a lossy translation hop on each side, and the epic wants the declared
1834
+ * prediction and the live prediction shown as a delta — two shapes that have
1835
+ * each been through a different translation are the worst possible input to
1836
+ * a delta. `DependencyObservation.edges` (./lexicon.ts) already carries
1837
+ * `IREdge` for the same reason.
1838
+ *
1839
+ * `from` and `to` are chant entity names, the keys {@link entityNames} and
1840
+ * {@link entities} use. An edge naming an entity outside `entityNames`
1841
+ * points outside the estate the caller asked about, and an engine may ignore
1842
+ * it.
1843
+ *
1844
+ * Required, and an empty array is a claim rather than a shrug: it says this
1845
+ * estate's entities reference nothing of each other. A caller that has not
1846
+ * computed edges must not pass `[]` and call it a graph, for the same reason
1847
+ * absence and unreadness are separate verdicts everywhere else here — which
1848
+ * is what {@link edgeCoverage} exists to let it say instead.
1849
+ */
1850
+ edges: readonly IREdge[];
1851
+ /**
1852
+ * How complete {@link edges} is, and what is known to be missing from it.
1853
+ *
1854
+ * `edges: []` cannot distinguish "nothing references anything" from "I could
1855
+ * not work out what references what", and both are ordinary outcomes on the
1856
+ * live path. `reconstructEdges` (./graph-refs.ts) returns `dangling` — the
1857
+ * references it resolved to no observed node — and drops them; a kind with no
1858
+ * `RefRule` in the lexicon's catalog contributes no edges at all and says
1859
+ * nothing about it; and containment (a subnet inside a VPC) is deliberately
1860
+ * not an edge, which means zone membership is absent from `edges` by design.
1861
+ * An engine asked "does this survive one zone lost" over a graph with no zone
1862
+ * membership answers confidently and wrongly.
1863
+ *
1864
+ * So the completeness is stated rather than assumed, and stated *now*, before
1865
+ * five consumers are written against a field that silently means "complete".
1866
+ */
1867
+ edgeCoverage: BehaviourEdgeCoverage;
1868
+
1869
+ /** Not a channel. See {@link CREDENTIAL_OPTION_KEYS}. */
1870
+ token?: never;
1871
+ /** Not a channel. */
1872
+ credential?: never;
1873
+ /** Not a channel. */
1874
+ credentials?: never;
1875
+ /** Not a channel. */
1876
+ secret?: never;
1877
+ /** Not a channel. */
1878
+ secrets?: never;
1879
+ /** Not a channel. */
1880
+ password?: never;
1881
+ /** Not a channel. */
1882
+ apiKey?: never;
1883
+ /** Not a channel. */
1884
+ accessKey?: never;
1885
+ /** Not a channel. */
1886
+ secretKey?: never;
1887
+ /** Not a channel. */
1888
+ sessionToken?: never;
1889
+ /** Not a channel. */
1890
+ auth?: never;
1891
+ /** Not a channel. */
1892
+ authorization?: never;
1893
+ /** Not a channel. */
1894
+ bearer?: never;
1895
+ /** Not a channel. */
1896
+ privateKey?: never;
1897
+ }
1898
+
1899
+ /** How deep the credential walk goes before it stops descending. */
1900
+ /**
1901
+ * How deep the credential walk goes before it stops descending and says so.
1902
+ *
1903
+ * Budget the levels honestly: `options → entities → .get(name) → props` spends
1904
+ * three before a single declared property is reached, so the number here is not
1905
+ * the depth a lexicon author is thinking about. A Kubernetes workload tree
1906
+ * (`spec.template.spec.containers[].env[].valueFrom.secretKeyRef.key`) or a
1907
+ * nested CloudFormation `Properties` block runs to a dozen on its own, and
1908
+ * exceeding this is now a *refusal* rather than silence — so a budget set too
1909
+ * low refuses real estates instead of protecting them.
1910
+ */
1911
+ const CREDENTIAL_WALK_DEPTH = 32;
1912
+
1913
+ /**
1914
+ * Refuse a request carrying anything credential-shaped, anywhere in it.
1915
+ *
1916
+ * The `?: never` fields on {@link PredictBehaviourOptions} stop the deliberate
1917
+ * attempt at compile time. This stops the accident, which is the one that
1918
+ * happens: it walks **the whole request** — including `entities[*].props`,
1919
+ * which is `Record<string, unknown>` straight out of the build and which no
1920
+ * type on this contract can see into, and every field of every
1921
+ * {@link import("./graph-ir").IREdge}.
1922
+ *
1923
+ * ## What it detects
1924
+ *
1925
+ * 1. **A credential-shaped value**, whatever the key is called: the PEM / JWT /
1926
+ * `Bearer` shapes in `CREDENTIAL_SHAPES`, plus the provider-prefixed tokens
1927
+ * in `CREDENTIAL_TOKEN_SHAPES` (GitHub, GitLab, OpenAI, Stripe, Slack, AWS,
1928
+ * Google, npm).
1929
+ * 2. **A password in userinfo**, with or without a scheme — `new URL()` for the
1930
+ * former and a pattern for `app:hunter2@db.internal:5432/prod`, which is how
1931
+ * a DSN is usually written and which `URL` will not parse at all.
1932
+ * 3. **A credential-shaped key**, but only when its value is a string of at
1933
+ * least {@link MIN_CREDENTIAL_LENGTH} characters that is not an evident
1934
+ * reference, and only when the key is not in the reference family
1935
+ * ({@link REFERENCE_KEY_SUFFIXES}).
1936
+ *
1937
+ * Rules 1 and 2 throw. Rule 3, and a structure deeper than the walk reads,
1938
+ * produce a refusal instead — see {@link screenBehaviourRequest} for why the
1939
+ * blast radii differ.
1940
+ *
1941
+ * **The name layer is a fast path, not a safety net.** After the gating above
1942
+ * it fires on very little, and a credential under a benign name — `dsn`,
1943
+ * `config`, `note` — is caught by rules 1 and 2 or not at all. That is the
1944
+ * intended division of labour and the reason those two exist; do not read
1945
+ * rule 3 as the guarantee.
1946
+ *
1947
+ * ## What it deliberately does not detect
1948
+ *
1949
+ * Rule 1 is **a denylist of known formats, not a proof**. A token from a
1950
+ * provider nobody has added, an internal issuer's format, a bare random string
1951
+ * or a base64 blob passes every rule here, as does a secret split across two
1952
+ * fields or encoded. There is no entropy scoring, on purpose: this walks build
1953
+ * output full of ids, ARNs, hashes and digests, and a heuristic that refuses
1954
+ * those would refuse real projects rather than protect them. So the honest
1955
+ * statement of the guarantee is that a credential a human would recognize on
1956
+ * sight will not reach the engine by accident, and that a novel or opaque
1957
+ * secret still can. A lexicon author putting secret material in `props` is
1958
+ * outside what this contract can catch, and the remedy there is not to.
1959
+ */
1960
+ export type CredentialRule = "value-shape" | "key-name" | "walk-depth";
1961
+
1962
+ /** One thing the walk objected to, and which rule objected. */
1963
+ export interface CredentialFinding {
1964
+ /** Where in the request, as a readable path (`options.entities.get(db).props.dsn`). */
1965
+ path: string;
1966
+ rule: CredentialRule;
1967
+ /** What was found, in words, for the message. Never the value itself. */
1968
+ what: string;
1969
+ }
1970
+
1971
+ /**
1972
+ * Every objection the walk has to a request. Pure, and exported so a caller can
1973
+ * decide what to do rather than take this module's word for it.
1974
+ */
1975
+ export function findCredentialsInOptions(options: object): CredentialFinding[] {
1976
+ const findings: CredentialFinding[] = [];
1977
+ const seen = new WeakSet<object>();
1978
+
1979
+ const walk = (value: unknown, path: string, depth: number): void => {
1980
+ if (depth > CREDENTIAL_WALK_DEPTH) {
1981
+ // Not silence. A request deeper than the walk goes is a request this
1982
+ // guard has not actually checked, and saying nothing about it is the
1983
+ // shape of failure this whole contract exists to refuse.
1984
+ findings.push({
1985
+ path,
1986
+ rule: "walk-depth",
1987
+ what: `a structure deeper than ${CREDENTIAL_WALK_DEPTH} levels, which the credential walk did not read`,
1988
+ });
1989
+ return;
1990
+ }
1991
+ if (typeof value === "string") {
1992
+ const shape = credentialValueShape(value);
1993
+ if (shape) findings.push({ path, rule: "value-shape", what: shape });
1994
+ return;
1995
+ }
1996
+ if (value === null || typeof value !== "object") return;
1997
+ if (seen.has(value)) return;
1998
+ seen.add(value);
1999
+
2000
+ if (Array.isArray(value)) {
2001
+ value.forEach((item, i) => walk(item, `${path}[${i}]`, depth + 1));
2002
+ return;
2003
+ }
2004
+ if (value instanceof Map) {
2005
+ for (const [key, item] of value) {
2006
+ const label = typeof key === "string" ? key : String(key);
2007
+ const child = `${path}.get(${label})`;
2008
+ // Both halves. A Map's KEY is as likely to be `DB_PASSWORD` as an
2009
+ // object's is — an env block is the obvious case — and walking only
2010
+ // values missed it entirely.
2011
+ if (typeof key === "string") checkKey(key, child, item);
2012
+ walk(item, child, depth + 1);
2013
+ }
2014
+ return;
2015
+ }
2016
+ if (value instanceof Set) {
2017
+ let i = 0;
2018
+ for (const item of value) walk(item, `${path}.item[${i++}]`, depth + 1);
2019
+ return;
2020
+ }
2021
+ for (const [key, item] of Object.entries(value)) {
2022
+ const child = `${path}.${key}`;
2023
+ checkKey(key, child, item);
2024
+ walk(item, child, depth + 1);
2025
+ }
2026
+ };
2027
+
2028
+ /**
2029
+ * The name arm. Gated on the value being a string long enough to be a secret,
2030
+ * and not an evident reference to one — see {@link REFERENCE_KEY_SUFFIXES}
2031
+ * for why the ungated version was unusable.
2032
+ */
2033
+ function checkKey(key: string, path: string, item: unknown): void {
2034
+ if (typeof item !== "string") return;
2035
+ if (item.length < MIN_CREDENTIAL_LENGTH) return;
2036
+ if (looksLikeSecretReference(item)) return;
2037
+ if (!isCredentialKey(key)) return;
2038
+ findings.push({ path, rule: "key-name", what: `a credential-shaped field name ("${key}")` });
2039
+ }
2040
+
2041
+ walk(options, "options", 0);
2042
+ return findings;
2043
+ }
2044
+
2045
+ /**
2046
+ * Throw when the request carries something that **is** a credential.
2047
+ *
2048
+ * **Not the entry point.** This applies one of the three rules and discards the
2049
+ * other two, so a `key-name` hit and a `walk-depth` hit both pass it silently.
2050
+ * Call {@link screenBehaviourRequest}, which runs this and then acts on what is
2051
+ * left. This stays exported because "did the request contain an actual token"
2052
+ * is a question worth asking on its own, and because the split is what keeps
2053
+ * the blast radii different.
2054
+ *
2055
+ * Only the value-shape rule throws, and throwing is deliberate: a live token in
2056
+ * a request bound for a third party is not a degradation to report, it is a
2057
+ * stop. Throwing is the whole-lexicon failure per `lexicon.ts`, which is the
2058
+ * right blast radius for this and the wrong one for a suspicious field name.
2059
+ */
2060
+ export function assertNoCredentialInOptions(options: object): void {
2061
+ const found = findCredentialsInOptions(options).filter((f) => f.rule === "value-shape");
2062
+ if (found.length === 0) return;
2063
+ const [first] = found;
2064
+ throw new Error(
2065
+ `predictBehaviour was passed ${first.what} at ${first.path}. The behaviour engine is never handed ` +
2066
+ "a credential: it is given the resource graph and a traffic level, and nothing it receives can " +
2067
+ "reach the account. Remove it — a lexicon that needs authenticated access to its own engine " +
2068
+ "resolves that on its own transport, not through this contract.",
2069
+ );
2070
+ }
2071
+
2072
+ /**
2073
+ * Screen a whole request. **This is the entry point, and the only one.**
2074
+ *
2075
+ * This doc comment is the source of truth for the sequence; the module header
2076
+ * and the authoring page both point here rather than restating it. A lexicon's
2077
+ * `predictBehaviour` opens with exactly this and nothing else:
2078
+ *
2079
+ * ```ts
2080
+ * const refusal = screenBehaviourRequest("acme", options);
2081
+ * if (refusal) return refusal;
2082
+ * ```
2083
+ *
2084
+ * Calling {@link assertNoCredentialInOptions} instead applies one rule of three
2085
+ * and drops the rest, which is how a `ghp_…` token nested past the walk's depth
2086
+ * budget, and an `awsSecretAccessKey` in `props`, both sailed through into a
2087
+ * request that was then sent.
2088
+ *
2089
+ * Two outcomes, because two things are being caught and they deserve different
2090
+ * blast radii:
2091
+ *
2092
+ * - a value that IS a credential throws, via
2093
+ * {@link assertNoCredentialInOptions};
2094
+ * - a merely suspicious field name, or a structure too deep to have been read,
2095
+ * returns a {@link BehaviourRefusalReport} with cause
2096
+ * `credential-in-request`. No overlay is drawn and the reason names the
2097
+ * path, which is the contract's own answer to "no faked numbers" applied to
2098
+ * its own guard.
2099
+ *
2100
+ * The split exists because the name arm is a heuristic and the old version
2101
+ * threw on it. One `tags: { author: "…" }` anywhere in an estate killed the
2102
+ * entire overlay with a stack trace, which is the exact failure mode constraint
2103
+ * 2 was written against.
2104
+ *
2105
+ * Returns `undefined` when the request is clean, so a lexicon reads
2106
+ * `const refusal = screenBehaviourRequest(name, options); if (refusal) return refusal;`
2107
+ */
2108
+ export function screenBehaviourRequest(
2109
+ lexicon: string,
2110
+ options: object,
2111
+ ): BehaviourRefusalReport | undefined {
2112
+ assertNoCredentialInOptions(options);
2113
+ const findings = findCredentialsInOptions(options);
2114
+ if (findings.length === 0) return undefined;
2115
+ const [first] = findings;
2116
+ const more = findings.length > 1 ? ` (and ${findings.length - 1} more)` : "";
2117
+ return behaviourRefusal({
2118
+ cause: "credential-in-request",
2119
+ reason:
2120
+ `The ${lexicon} behaviour request carries ${first.what} at ${first.path}${more}, so it was not ` +
2121
+ "sent. The engine is a third party and this contract hands it the resource graph and a traffic " +
2122
+ "level only. No overlay is drawn and no figure is guessed locally.",
2123
+ remedy:
2124
+ "Remove the value from the declaration, or hold it in a secret reference the build does not " +
2125
+ "expand. If the field is a false positive, it still leaves the process in this request.",
2126
+ });
2127
+ }