@mark1russell7/alerts 0.0.0-bootstrap.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -1
- package/build/index.d.ts +6401 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +11078 -0
- package/build/index.js.map +1 -0
- package/package.json +64 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["highest","HOUR","DAY","nonNegative","byTime","HOUR","rankOf"],"sources":["../src/contracts.ts","../src/ids.ts","../src/audience.ts","../src/merge.ts","../src/retention.ts","../src/kind-prefix.ts","../src/why.ts","../src/relevance.ts","../src/shapes.ts","../src/assess.ts","../src/score.ts","../src/escalation.ts","../src/chain.ts","../src/channel-down.ts","../src/clock-step.ts","../src/taxonomy.ts","../src/delivery.ts","../src/digest.ts","../src/coverage.ts","../src/drill.ts","../src/system-reports.ts","../src/send-limit.ts","../src/observe.ts","../src/throttle.ts","../src/interest-defaults.ts","../src/opt-in.ts","../src/config.ts","../src/health.ts","../src/lateness.ts","../src/copy-measure.ts","../src/link.ts","../src/map.ts","../src/basemap.ts","../src/health-payload.ts","../src/history.ts","../src/indicators.ts","../src/baseline.ts","../src/breadth.ts","../src/history-reader.ts","../src/problems.ts","../src/interests-payload.ts","../src/schemas.ts","../src/lifelines.ts"],"sourcesContent":["/**\n * The contracts of the alert system: the event, the indicator, the source and the channel.\n *\n * The text of `docs/CONTRACTS.md` explains each part. All values are JSON values, so each type\n * crosses a procedure call, a log row and a copy of the system without a change.\n */\n\n// =============================================================================\n// Time, ids and references\n// =============================================================================\n\n/** This type is a time in milliseconds since the Unix epoch, in UTC. */\nexport type Instant = number;\n\n/** This type is a length of time in milliseconds. */\nexport type Duration = number;\n\ndeclare const brand: unique symbol;\n/** This type gives a string a name, so that two kinds of id do not mix. */\nexport type Id<Name extends string> = string & { readonly [brand]: Name };\n\n/** The id of a source adapter, for example `nws-api`. */\nexport type SourceId = Id<\"SourceId\">;\n/** The source of each report of the core. No adapter has this id. Each copy makes its own system reports. */\nexport const SYSTEM_SOURCE = \"system\" as SourceId;\n/** The id of a delivery channel, for example `pushover`. */\nexport type ChannelId = Id<\"ChannelId\">;\n/** The id of one raw message from a source: the SHA-256 of its content, in hex. `observationId` makes it. */\nexport type ObservationId = Id<\"ObservationId\">;\n/** The id of one report: the SHA-256 of the source id, the source key and the sent time, in hex. `reportId` makes it. */\nexport type ReportId = Id<\"ReportId\">;\n/** The id of a person that the system watches over. The private configuration resolves it. */\nexport type PersonId = Id<\"PersonId\">;\n/** The id of a place that the system watches. The private configuration resolves it. */\nexport type PlaceId = Id<\"PlaceId\">;\n\n// =============================================================================\n// The event: CAP 1.2 values, in lower case\n// =============================================================================\n\n/** The CAP status. Only `actual` can alert a person. */\nexport type Status = \"actual\" | \"exercise\" | \"system\" | \"test\" | \"draft\";\n\n/** The CAP message type, without `ack` and `error`. */\nexport type Operation = \"alert\" | \"update\" | \"cancel\";\n\n/** The CAP severity. */\nexport type Severity = \"extreme\" | \"severe\" | \"moderate\" | \"minor\" | \"unknown\";\n\n/** The CAP urgency. */\nexport type Urgency = \"immediate\" | \"expected\" | \"future\" | \"past\" | \"unknown\";\n\n/** The CAP certainty. */\nexport type Certainty = \"observed\" | \"likely\" | \"possible\" | \"unlikely\" | \"unknown\";\n\n/** The CAP response type. */\nexport type ResponseType =\n | \"shelter\"\n | \"evacuate\"\n | \"prepare\"\n | \"execute\"\n | \"avoid\"\n | \"monitor\"\n | \"assess\"\n | \"allclear\"\n | \"none\";\n\n/** The CAP categories, and five more: cyber, market, civic, personal and system. */\nexport type Category =\n | \"geo\"\n | \"met\"\n | \"safety\"\n | \"security\"\n | \"rescue\"\n | \"fire\"\n | \"health\"\n | \"env\"\n | \"transport\"\n | \"infra\"\n | \"cbrne\"\n | \"other\"\n | \"cyber\"\n | \"market\"\n | \"civic\"\n | \"personal\"\n | \"system\";\n\n/** The stage of a hazard message. NWS VTEC gives it the name significance. */\nexport type Significance = \"warning\" | \"watch\" | \"advisory\" | \"statement\" | \"outlook\" | \"observation\";\n\n/** The kind of an event in the taxonomy of the system. */\nexport interface Kind {\n /** A dotted code of the taxonomy, for example `met.tornado` or `infra.power.outage`. */\n readonly code: string;\n /** The stage, when the source gives one. */\n readonly significance?: Significance;\n /** The name that the source gives, for example `Tornado Warning`. */\n readonly label: string;\n}\n\n/** A position as in GeoJSON (RFC 7946): longitude, then latitude, in degrees (WGS 84). */\nexport type Position = readonly [lon: number, lat: number];\n\n/**\n * The code of a region in one system of codes: `state`, `same`, `ugc`, `fips`, `iso3166` and others. The\n * system `ugc` holds the NWS forecast zones and counties (`KSZ083`, `KSC173`). The system `ugc-fire` holds the NWS fire\n * weather zones (`KSZ083` too). A fire zone and a forecast zone can have one code and different outlines. The system `same`\n * holds the SAME county codes (`020173`).\n */\nexport interface RegionCode {\n readonly system: string;\n readonly code: string;\n}\n\n/**\n * The key of the area block of a message, for example the path `info[0].area[1]` of a CAP `area` element. The\n * areas of one block tell one area together: the shapes of a block decide for that block. In a report,\n * the adapter writes a key that is unique in the report. In an incident, the merge puts the report id\n * before the key, so the blocks of two reports stay apart. An area with no key is in no block.\n */\nexport interface AreaBlock {\n readonly block?: string;\n}\n\n/** One area of an event. */\nexport type Area =\n /** A polygon. The first ring is the outside. Each ring closes on its first position. */\n | ({ readonly type: \"polygon\"; readonly rings: readonly (readonly Position[])[] } & AreaBlock)\n /** A circle on the ground. */\n | ({ readonly type: \"circle\"; readonly center: Position; readonly radiusKm: number } & AreaBlock)\n /** A region by its code. */\n | ({ readonly type: \"code\" } & RegionCode & AreaBlock)\n /**\n * A watched place of the configuration. Only the reports of the core use it, for example a gap of\n * the coverage at that place. An adapter does not know the places.\n */\n | { readonly type: \"place\"; readonly place: PlaceId };\n\n/** A thing that an event is about, other than a place: a service, a cloud region, a market. */\nexport interface Subject {\n /** The system of the id, for example `cloud`, `service` or `market`. */\n readonly system: string;\n /** The id in that system, for example `aws/us-east-1`. */\n readonly id: string;\n readonly label?: string;\n}\n\n/**\n * A key that two sources share for one real event: an NWS VTEC event (office, phenomenon,\n * significance, event number and year), a USGS event id, and others. A shared key links two\n * reports into one incident with no doubt.\n */\nexport interface CorrelationKey {\n readonly system: string;\n readonly id: string;\n}\n\n/** One raw message as a source gave it. The log keeps each observation. */\nexport interface Observation {\n readonly id: ObservationId;\n readonly source: SourceId;\n /** The time at which the adapter got the message. */\n readonly fetched: Instant;\n readonly contentType: string;\n /** The body as text. A binary body is in base64, and `contentType` tells it. */\n readonly body: string;\n /** The facts of the transport. */\n readonly transport: {\n readonly url?: string;\n readonly status?: number;\n readonly latency: Duration;\n readonly etag?: string;\n readonly lastModified?: string;\n };\n}\n\n/**\n * One report: one message of one source, in the one format of the system. A report does not\n * change. An update or a cancel of the source is a new report.\n */\nexport interface Report {\n readonly id: ReportId;\n readonly source: SourceId;\n /**\n * The authority that issued the message: one of the `origins` of the source descriptor, for\n * example `nws` or `usgs`. The corroboration of an incident counts the different origins.\n */\n readonly origin: string;\n /** The id that the source gives to the message (the CAP identifier). */\n readonly key: string;\n /** The keys of the same source that this report updates or cancels (the CAP references). */\n readonly references: readonly string[];\n /** The keys that other sources also give for the same real event. */\n readonly correlation: readonly CorrelationKey[];\n readonly status: Status;\n readonly op: Operation;\n readonly kind: Kind;\n readonly categories: readonly Category[];\n readonly severity: Severity;\n readonly urgency: Urgency;\n readonly certainty: Certainty;\n readonly response: readonly ResponseType[];\n /** The time at which the source sent the message. */\n readonly sent: Instant;\n /** The time at which the adapter got the message. */\n readonly received: Instant;\n readonly effective?: Instant;\n readonly onset?: Instant;\n readonly expires?: Instant;\n /** The time at which the event ends, when the source tells it apart from `expires`. */\n readonly ends?: Instant;\n /** The areas of the event. An empty list: the event has no place. */\n readonly areas: readonly Area[];\n readonly areaText?: string;\n readonly about: readonly Subject[];\n /**\n * The persons of a private report: the CAP scope `Private` with its `addresses`. Each id is a person of the configuration.\n * A private report reaches only these persons. Absent means the CAP scope `Public`.\n */\n readonly addresses?: readonly PersonId[];\n /** The authority that sent the message, for example `NWS Topeka KS`. */\n readonly sender: string;\n readonly headline: string;\n readonly description?: string;\n readonly instruction?: string;\n readonly web?: string;\n /** The observation that the map function made this report from. */\n readonly observation: ObservationId;\n /** The name and value pairs of the source that the core does not know (the CAP parameters). */\n readonly parameters: Readonly<Record<string, readonly string[]>>;\n}\n\n// =============================================================================\n// The indicator contract\n// =============================================================================\n\n/**\n * The dimensions of the indicators. A dimension is one kind of measure, for example rail delays or grid frequency. The\n * list is closed, as the taxonomy is. A new dimension is a change of the contract.\n */\nexport const DIMENSIONS = [\n { id: \"road-traffic\", title: \"Road traffic flow\" },\n { id: \"road-events\", title: \"Road closures, incidents and work zones\" },\n { id: \"rail\", title: \"Rail punctuality and cancellations\" },\n { id: \"public-transit\", title: \"Bus, tram and metro service\" },\n { id: \"micromobility\", title: \"Bike and scooter share\" },\n { id: \"aviation-delays\", title: \"Airport delays and ground stops\" },\n { id: \"air-traffic\", title: \"Aircraft in the air\" },\n { id: \"air-passengers\", title: \"Air passengers and flights\" },\n { id: \"gnss-interference\", title: \"GNSS interference\" },\n { id: \"maritime-traffic\", title: \"Vessel traffic\" },\n { id: \"port-activity\", title: \"Port calls and chokepoint transits\" },\n { id: \"internet-connectivity\", title: \"Internet connectivity\" },\n { id: \"internet-routing\", title: \"Internet routing and latency\" },\n { id: \"internet-censorship\", title: \"Internet censorship\" },\n { id: \"online-service-status\", title: \"Online service status\" },\n { id: \"power-demand\", title: \"Electric load\" },\n { id: \"grid-frequency\", title: \"Grid frequency\" },\n { id: \"power-supply\", title: \"Power generation and prices\" },\n { id: \"fuel-prices\", title: \"Fuel prices and stock\" },\n { id: \"gas-storage\", title: \"Natural gas storage\" },\n { id: \"radiation\", title: \"Ambient radiation\" },\n { id: \"river-levels\", title: \"River levels and flow\" },\n { id: \"reservoir-storage\", title: \"Reservoir storage\" },\n { id: \"snowpack\", title: \"Snowpack\" },\n { id: \"sea-level\", title: \"Sea level\" },\n { id: \"public-health\", title: \"Public health signals\" },\n { id: \"hospital-occupancy\", title: \"Hospital bed occupancy\" },\n { id: \"outbreak-reports\", title: \"Official outbreak reports\" },\n { id: \"drug-shortages\", title: \"Medicine shortages\" },\n { id: \"online-attention\", title: \"Online attention\" },\n { id: \"news-volume\", title: \"News volume\" },\n { id: \"social-volume\", title: \"Social media volume\" },\n { id: \"active-fires\", title: \"Active fires\" },\n { id: \"lightning-activity\", title: \"Lightning strokes\" },\n { id: \"night-lights\", title: \"Night lights\" },\n { id: \"air-quality\", title: \"Air quality\" },\n { id: \"felt-reports\", title: \"Felt reports\" },\n { id: \"food-prices\", title: \"Food prices\" },\n { id: \"ev-charging\", title: \"Electric vehicle charging\" },\n { id: \"emergency-calls\", title: \"Emergency and service calls\" },\n { id: \"border-crossings\", title: \"Border crossings\" },\n { id: \"financial-markets\", title: \"Financial markets\" },\n { id: \"jobless-claims\", title: \"Jobless claims\" },\n { id: \"disaster-mapping\", title: \"Satellite disaster mapping\" },\n] as const;\n\n/** The id of a dimension of `DIMENSIONS`. */\nexport type DimensionId = (typeof DIMENSIONS)[number][\"id\"];\n\n/** The ids of the dimensions, in the order of `DIMENSIONS`. */\nexport const DIMENSION_IDS: readonly DimensionId[] = DIMENSIONS.map((dimension) => dimension.id);\n\n/**\n * The kind of the area of the readings of a measure. A country and a subdivision are region codes, for example\n * `iso3166-1` and `iso3166-2`. A grid cell and a box that the caller chose are polygons.\n */\nexport type IndicatorAreaKind = \"code\" | \"point\" | \"line\" | \"polygon\" | \"zone\" | \"world\";\n\n/** The kinds of the area of a reading, in their order in a report. */\nexport const INDICATOR_AREA_KINDS: readonly IndicatorAreaKind[] = [\"code\", \"point\", \"line\", \"polygon\", \"zone\", \"world\"];\n\n/** The area of one reading. Its `type` is the area kind of the measure. */\nexport type IndicatorArea =\n /** A region by its code, for example a country, a state or an NWS zone. */\n | ({ readonly type: \"code\" } & RegionCode)\n /** A station, a gauge, a sensor or a vehicle. */\n | { readonly type: \"point\"; readonly at: Position }\n /** A road link or a rail line: two positions or more. */\n | { readonly type: \"line\"; readonly path: readonly Position[] }\n /** A grid cell, or a box that the caller chose. The first ring is the outside, and each ring closes on its first position. */\n | { readonly type: \"polygon\"; readonly rings: readonly (readonly Position[])[] }\n /**\n * A zone of the domain of the source, for example an electricity bidding zone or a balancing authority. The\n * system names the codes, for example `eic`. A table of the atlas gives the regions of each zone.\n */\n | { readonly type: \"zone\"; readonly system: string; readonly code: string }\n /** No place: a market series, a subreddit or a service of the world. */\n | { readonly type: \"world\" };\n\n/** The direction of a change that is a signal: `rise`, `drop` or `both`. */\nexport type Move = \"rise\" | \"drop\" | \"both\";\n\n/** The directions of a change, in their order in a report. */\nexport const MOVES: readonly Move[] = [\"rise\", \"drop\", \"both\"];\n\n/**\n * The baseline that a source gives with its values. With `none`, the core computes the normal level of each\n * series from its history. With `expected`, each reading holds the expected value of the source, for example a\n * load forecast or a timetable. With `flag`, each reading tells if the source marks it as an anomaly.\n */\nexport type OwnBaseline = \"none\" | \"expected\" | \"flag\";\n\n/** The baselines that a source can give, in their order in a report. */\nexport const OWN_BASELINES: readonly OwnBaseline[] = [\"none\", \"expected\", \"flag\"];\n\n/**\n * One measure that a source gives. A source can give measures of two dimensions or more. Each measure has one\n * dimension, one unit and one area kind.\n */\nexport interface MeasureDeclaration {\n /** The id of the measure in its source: small letters, digits and hyphens, with a letter first. */\n readonly id: string;\n readonly dimension: DimensionId;\n readonly title: string;\n /** The unit of each value, in the grammar of `@mark1russell7/quantity`, for example `{vehicle}/h`, `km/h` or `Hz`. */\n readonly unit: string;\n readonly area: IndicatorAreaKind;\n /** The direction of a change that is a signal. A cancelled train is a rise, and a station that goes offline is a drop. */\n readonly moves: Move;\n readonly baseline: OwnBaseline;\n /** The time between two values of one series. Absent: the cadence is not known. */\n readonly cadence?: Duration;\n /** The time from the time of a value to its publication. Absent: the delay is not known. */\n readonly delay?: Duration;\n /** The history that the source gives at once. Absent: the source gives only live values, so a baseline starts empty. */\n readonly backfill?: Duration;\n}\n\n/**\n * One value of one series of a measure at one time. A series is a station, a link or a zone of the source. A\n * reading does not change.\n */\nexport interface Reading {\n readonly source: SourceId;\n /** The id of the measure in the declaration of the source. The measure gives the dimension and the unit. */\n readonly measure: string;\n /** The id of the series in the measure, for example the id of a station. */\n readonly series: string;\n /**\n * The version of the method of the series. The source changes it when its method changes, for example a new\n * instrument. A baseline does not cross a version. Absent: the first version.\n */\n readonly version?: string;\n /** The time of the value, not the time of the fetch. */\n readonly at: Instant;\n readonly value: number;\n readonly area: IndicatorArea;\n /**\n * The cadence of the series, as the source states it, for example the ttl of a GBFS file. When it is present, it\n * replaces the cadence of the measure for this series. A general reader of many feeds gives it.\n */\n readonly cadence?: Duration;\n /** The expected value of the source. It is present only for a measure with the baseline `expected`. */\n readonly expected?: number;\n /** True when the source marks the value as an anomaly. It is present only for a measure with the baseline `flag`. */\n readonly flagged?: boolean;\n /** The raw message that gave the reading. */\n readonly observation: ObservationId;\n}\n\n// =============================================================================\n// The source contract\n// =============================================================================\n\n/** How a source gives its data. */\nexport type Transport = \"poll\" | \"stream\" | \"push\" | \"radio\";\n\n/**\n * A resource of the cell. The cell is the copy of the system on one machine. Each source of the\n * cell uses the same internet link, the same DNS resolver, the same power and the same receivers. So the fault of a\n * resource is a common fault of the cell, not the fault of one source.\n */\nexport type CellResource = \"internet\" | \"dns\" | \"power\" | \"receiver\";\n\n/** The resources of the cell, in their order in a report. */\nexport const CELL_RESOURCES: readonly CellResource[] = [\"internet\", \"dns\", \"power\", \"receiver\"];\n\n/** The facts of a source. The core uses them for the schedule, the health and the coverage. */\nexport interface SourceDescriptor {\n readonly id: SourceId;\n readonly title: string;\n /** The authorities whose messages the source carries, for example `nws` or `usgs`. */\n readonly origins: readonly string[];\n /**\n * The failure domains outside the cell that the source needs: providers, CDNs, carriers, transmitters\n * and regions. Examples: `provider:nws-api`, `cdn:akamai`, `carrier:noaaport`, `rf:nwr`. The kind of a\n * domain comes before the colon. The paths of the atlas use the same ids. Two sources with a shared\n * domain are not independent for coverage. Do not put the resources of the cell here.\n */\n readonly dependsOn: readonly string[];\n /**\n * The resources of the cell that the source uses. An internet source uses `internet`, `dns` and\n * `power`. A radio source uses `receiver` and `power`.\n */\n readonly uses: readonly CellResource[];\n /** The prefixes of the taxonomy codes that the source covers, for example `met` and `geo.earthquake`. */\n readonly kinds: readonly string[];\n /** The areas that the source covers, or `global`. */\n readonly coverage: readonly Area[] | \"global\";\n readonly transport: Transport;\n /** The time between two fetches in normal work. */\n readonly interval: Duration;\n /** The longest time that a fetch takes before the health is `slow`. */\n readonly slowAfter: Duration;\n /**\n * The longest normal time with no new message. Absent: a quiet source is normal, as an alert\n * feed with no alert.\n */\n readonly maxQuiet?: Duration;\n readonly auth: \"none\" | \"key\" | \"oauth\";\n /**\n * `snapshot`: each complete fetch gives all the messages that are in effect, and a message that ends\n * leaves the list with no cancel. Then the runtime ends a report that is absent from complete fetches.\n * Absent: a stream. A message stays until its cancel or its expiry.\n */\n readonly listing?: \"snapshot\";\n /** A plain sentence of the canary check, when the source has one. */\n readonly canary?: string;\n /** The measures of an indicator source. Absent: the source gives only events. */\n readonly measures?: readonly MeasureDeclaration[];\n}\n\n/**\n * A place that the system watches, as the adapters see it. It holds no name and no address. A source\n * fetches by the region codes, and the core matches the places on the machine of the instance.\n */\nexport interface WatchedPlace {\n readonly id: PlaceId;\n /** The position of the place. Absent unless the owner lets this source get positions. */\n readonly at?: Position;\n /**\n * The codes of the regions that contain the place: the NWS zones and county, SAME, the state\n * (`state`) and the country (`iso3166`). The coverage of a source can name a region at each level.\n */\n readonly codes: readonly RegionCode[];\n /** The distance around the place that the system also watches. */\n readonly bufferKm: number;\n}\n\n/** What a fetch asks for. */\nexport interface Watch {\n readonly places: readonly WatchedPlace[];\n /** The prefixes of the taxonomy codes. Absent: all kinds of the source. */\n readonly kinds?: readonly string[];\n}\n\n/** The state that a source keeps between two fetches: an ETag, a time, a sequence number. */\nexport type Cursor = Readonly<Record<string, string>>;\n\n/** Why a fetch failed. */\nexport type FetchFailure =\n | { readonly kind: \"network\" | \"timeout\" | \"server\"; readonly message: string; readonly retryAfter?: Duration }\n | { readonly kind: \"rate-limited\"; readonly message: string; readonly retryAfter?: Duration }\n | { readonly kind: \"auth\" | \"refused\"; readonly message: string };\n\n/** The result of one fetch. */\nexport type FetchOutcome =\n | {\n readonly ok: true;\n readonly observations: readonly Observation[];\n readonly cursor?: Cursor;\n /**\n * True: the source answered in full. An empty list with `complete` true means \"no message\",\n * not \"no answer\".\n */\n readonly complete: boolean;\n /**\n * The time of the data of a complete list of a snapshot source: the time of its newest product. A cache can give an\n * old list, and this time tells its age. The runtime reads a list with no time as current.\n */\n readonly asOf?: Instant;\n }\n | { readonly ok: false; readonly failure: FetchFailure };\n\n/**\n * A part of a message that the map function did not understand. Problems tell of a format change. A\n * problem has one of three effects. A fatal problem gives no report. A lossy problem gives a report that\n * lacks a value of the message, or holds a fallback in its place. A note gives a whole report.\n */\nexport interface MapProblem {\n /** The path in the message, for example `features[3].properties.onset`. */\n readonly path: string;\n readonly message: string;\n /** True: the map function could not make a report from the message. */\n readonly fatal: boolean;\n /**\n * True: the report lacks a value of the message, or holds a fallback in its place. The field is\n * absent for a note and for a fatal problem.\n */\n readonly lossy?: true;\n}\n\n/** The result of the map function. */\nexport interface MapResult {\n readonly reports: readonly Report[];\n readonly problems: readonly MapProblem[];\n /**\n * The readings of the indicator measures in the message. The runtime checks each reading against the declaration of\n * its measure, and keeps it in the store of the readings, not in the event log. A source with no measures gives no field.\n */\n readonly readings?: readonly Reading[];\n}\n\n/** The result of the canary check of a source. */\nexport interface CanaryResult {\n readonly pass: boolean;\n readonly reason: string;\n}\n\n/**\n * The record of one fetch of a source. The runtime writes one record when each fetch ends, and the\n * core calculates the health of the source from the records.\n */\nexport interface FetchRecord {\n readonly source: SourceId;\n /** The time at which the fetch started. */\n readonly at: Instant;\n /** The time that the fetch took. */\n readonly took: Duration;\n /** The failure of the fetch. It is absent when the fetch passed. */\n readonly failure?: FetchFailure;\n /** The count of observations of the fetch that the log did not have before. */\n readonly fresh: number;\n /** The count of fatal problems that the map gave for the observations of the fetch. */\n readonly fatal: number;\n /** The count of lossy problems that the map gave for the observations of the fetch. An absent count is 0. */\n readonly lossy?: number;\n /** The result of the canary check of the observations of the fetch, when the source has a canary and the check decides. */\n readonly canary?: CanaryResult;\n}\n\n/**\n * The part of an `AbortSignal` that a fetch reads. The core has no platform, thus it does not name the\n * `AbortSignal` type of a platform. An `AbortSignal` of Node.js or of a browser has each member.\n */\nexport interface FetchSignal {\n /** This value is true after the abort. */\n readonly aborted: boolean;\n /** This value is the reason of the abort, after the abort. */\n readonly reason?: unknown;\n /** This function adds a listener of the abort. */\n addEventListener(type: \"abort\", listener: () => void, options?: { readonly once?: boolean }): void;\n /** This function removes a listener of the abort. */\n removeEventListener(type: \"abort\", listener: () => void): void;\n}\n\n/**\n * The procedures of one source. Each source package registers them under the path\n * `alerts.source.<id>.<name>`.\n *\n * - `describe`: no effects.\n * - `fetch`: it reads `network`, through polite-crawler. It is idempotent. For a failure of the\n * source, it gives `{ ok: false }` and does not throw.\n * - The optional `signal` of `fetch` stops the fetch. The runtime aborts it at the time limit of\n * the fetch and at the stop of the runtime. After the abort, the fetch sends no more requests.\n * It can then throw the reason of the signal.\n * - `map`: a pure, total function. It does not throw, and the same observation gives the same\n * reports with the same ids.\n * - `check`: it examines the observations of a fetch against the canary, and sends no request. It gives `undefined`\n * when it cannot decide yet: no read. The health then gets no canary event. A stream gives no read until its session\n * had one full period of its test message.\n * - `locate`: optional. It reads `network` and is idempotent. It gives the region codes of a\n * position, for a source that has a lookup: the `/points` query of the NWS API.\n * - `close`: optional. It ends the resources of the source, for example the session of a stream. The runtime starts\n * it one time, at the stop, after the last fetch. It does not throw.\n */\nexport interface SourceProcedures {\n describe(): SourceDescriptor;\n fetch(input: { readonly watch: Watch; readonly cursor?: Cursor }, signal?: FetchSignal): Promise<FetchOutcome>;\n map(input: { readonly observation: Observation }): MapResult;\n check?(input: { readonly observations: readonly Observation[] }): CanaryResult | undefined;\n locate?(input: { readonly at: Position }): Promise<LocateOutcome>;\n close?(): Promise<void>;\n}\n\n/** The result of a lookup of the region codes of a position. */\nexport type LocateOutcome =\n | { readonly ok: true; readonly codes: readonly RegionCode[] }\n | { readonly ok: false; readonly failure: FetchFailure };\n\n// =============================================================================\n// Health and coverage (the core calculates them, not the adapter)\n// =============================================================================\n\n/** The health of a source. */\nexport type HealthState = \"unknown\" | \"healthy\" | \"slow\" | \"failing\" | \"silent\" | \"changed\";\n\n/** The health of one source at one time. */\nexport interface SourceHealth {\n readonly source: SourceId;\n readonly state: HealthState;\n readonly since: Instant;\n readonly lastSuccess?: Instant;\n readonly lastFailure?: { readonly at: Instant; readonly failure: FetchFailure };\n readonly reason: string;\n}\n\n/** The sources that cover one kind at one place at this time. */\nexport interface Coverage {\n readonly place: PlaceId;\n readonly kind: string;\n /** The sources that are up and cover the kind at the place. */\n readonly sources: readonly SourceId[];\n /**\n * The smallest count of outside failure domains whose faults stop each of these sources. At 2\n * or more, no single outside fault stops the coverage.\n */\n readonly independent: number;\n /**\n * The search of the smallest count ended. When it is false, the search passed its budget. Then\n * `independent` is the count of a set that the search found, and the true count can be smaller.\n */\n readonly proven: boolean;\n /** The outside failure domains of the smallest set: one fault of each stops each of these sources. */\n readonly faults: readonly string[];\n /**\n * The resources of the cell that each of these sources uses. One fault of one of them stops all\n * of these sources in this cell.\n */\n readonly commonResources: readonly CellResource[];\n /** The count that the policy needs. A smaller count is a coverage alert. */\n readonly required: number;\n}\n\n// =============================================================================\n// Incidents (the core makes them from the reports)\n// =============================================================================\n\n/**\n * One real event, made from one or more reports. The core calculates each incident from the\n * merge state and a time, so each copy of the system gets the same incidents.\n */\nexport interface Incident {\n /** The smallest report id of the incident. It changes when two incidents merge. */\n readonly anchor: ReportId;\n /** The report ids of the incident, from the smallest. */\n readonly reports: readonly ReportId[];\n /** The status of each report of the incident. Reports of two statuses are not in one incident. */\n readonly status: Status;\n readonly kind: Kind;\n readonly severity: Severity;\n readonly urgency: Urgency;\n readonly certainty: Certainty;\n readonly onset?: Instant;\n readonly expires?: Instant;\n readonly areas: readonly Area[];\n readonly about: readonly Subject[];\n /** The persons of a private incident: the `addresses` of its reports. Each report of an incident has the same audience. */\n readonly addresses?: readonly PersonId[];\n /** False when each line of reports is cancelled, expired or ended at the time of the calculation. */\n readonly live: boolean;\n /** The count of different origins that report the event. */\n readonly corroboration: number;\n /**\n * The lines of the incident: one for each report that gives its values, with the values and the areas of that\n * report. The merge gives them only when the values of two lines differ. The assessment gives each place the\n * level of the lines whose areas hold that place. Without lines, each place gets the level of the incident.\n */\n readonly lines?: readonly IncidentLine[];\n}\n\n/**\n * One line of an incident: a report that gives the values of the incident, with its own values and areas. For\n * example, each band of the shaking of an earthquake is one line, with its severity and its circle.\n */\nexport interface IncidentLine {\n readonly report: ReportId;\n readonly kind: Kind;\n readonly severity: Severity;\n readonly urgency: Urgency;\n readonly certainty: Certainty;\n readonly onset?: Instant;\n /** The live areas of the report, with the keys of the blocks of the incident. */\n readonly areas: readonly Area[];\n}\n\n// =============================================================================\n// Delivery: the level, the message and the channel contract\n// =============================================================================\n\n/**\n * The level of an alert.\n * - `life-safety`: it wakes the person, sounds through silent mode and escalates until acknowledged.\n * - `urgent`: a push at once, without the break through Do Not Disturb.\n * - `notice`: a push in the day. In the quiet window of the person, a quiet push that the next digest tells again.\n * - `digest`: the next digest: one message each day for each person (`planDigests`).\n */\nexport type Level = \"life-safety\" | \"urgent\" | \"notice\" | \"digest\";\n\n/** The order of the levels, from the lowest. */\nexport const LEVELS: readonly Level[] = [\"digest\", \"notice\", \"urgent\", \"life-safety\"];\n\n/**\n * One field of the address of a person on a channel, for example the user key of Pushover. The load of the\n * configuration checks each address with the fields of its channel.\n */\nexport interface AddressField {\n /** The name of the field in the address, for example `user` or `to`. */\n readonly name: string;\n /** True: each address on the channel has the field. */\n readonly required: boolean;\n /**\n * The form of the whole value: the source of a regular expression with the flag `u`. The check adds the anchors\n * `^` and `$`. Write a pattern with no nested repeats, because the check runs it on each address.\n */\n readonly pattern: string;\n /** The form in words, for the text of a problem, for example `a phone number in E.164 form`. It tells no value. */\n readonly form: string;\n /**\n * True: each value of the field needs a record of the opt-in list of the configuration (`optIn`). A send to a value\n * with no opt-in fails with the kind `consent`. The default is false.\n */\n readonly optIn?: boolean;\n}\n\n/** The facts of a channel. The core uses them for the escalation and the coverage of delivery. */\nexport interface ChannelDescriptor {\n readonly id: ChannelId;\n readonly title: string;\n /**\n * The failure domains outside the cell that the channel needs, for example `provider:pushover` and\n * `provider:apns`. Do not put the resources of the cell here.\n */\n readonly dependsOn: readonly string[];\n /**\n * The online services that the channel needs, as the keys of entities, for example `domain:api.twilio.com`. Each person\n * with a contact on the channel gets each service in the layer `delivery` of the interest graph. Thus an outage of\n * the path of the alerts of a person reaches that person.\n */\n readonly services?: readonly NodeKey[];\n /**\n * The endpoints that the procedures of the channel call, as the keys of entities, for example `domain:api.twilio.com`.\n * Each one is also in `services`. A report of a down channel names them (AL-65). Thus the layer `delivery` of the\n * interest graph takes the report to each person with a contact on the channel. A service that the calls do not reach,\n * as the push service of a phone platform, is only in `services`.\n */\n readonly api?: readonly NodeKey[];\n /**\n * The resources of the cell that the channel uses. A push or a text through an API uses\n * `internet`, `dns` and `power`. Thus a fault of the internet link stops each source and each such\n * channel together.\n */\n readonly uses: readonly CellResource[];\n /** True: the channel can sound through silent mode and Do Not Disturb. */\n readonly breaksThrough: boolean;\n /** True: the channel repeats a message by itself until the person acknowledges it. */\n readonly repeats: boolean;\n /** How the channel tells of an acknowledgment: not at all, by a receipt to poll, or by a callback. */\n readonly ack: \"none\" | \"poll\" | \"callback\";\n readonly maxTitle: number;\n readonly maxBody: number;\n /** The cost of one message, when the channel costs money. */\n readonly costUsd?: number;\n /**\n * The most calls of the channel in progress at the same time, from the rules of its provider. The delivery\n * holds each other call for a later step. Without it, the delivery has no limit.\n */\n readonly maxInFlight?: number;\n /**\n * True: a person takes one message of the channel at a time, as with a phone call. A second phone call during the\n * first gets a busy line. Thus a copy with a rank above 0 waits at least the rank floor before a step of the channel.\n */\n readonly exclusive?: boolean;\n /**\n * The limit of the why line of the channel. `WHY_LIMITS` in `why.ts` holds the limit of each kind of channel.\n * When it is absent, the messages of the channel have no why line.\n */\n readonly why?: WhyLimit;\n /**\n * The fields of the address of a person on the channel. The load of the configuration refuses an address that\n * does not agree with this list. With no list, each address passes. The function `addressProblems` tells the rules.\n */\n readonly address?: readonly AddressField[];\n /**\n * The levels at which a message of the channel asks the person for an acknowledgment. With no list, a channel with an\n * `ack` other than `none` asks at each level. An exhausted escalation tells the watchers only after such a step (AL-21).\n */\n readonly ackLevels?: readonly Level[];\n}\n\n/** The limit of a why line: the most characters, the most words, or both. */\nexport interface WhyLimit {\n /** The most characters (code points). */\n readonly chars?: number;\n /** The most words. */\n readonly words?: number;\n}\n\n/** One message to one person on one channel. */\nexport interface Message {\n /**\n * The delivery key: the SHA-256 of the incident anchor, the level, the person and the step. `messageKey` makes it.\n * A channel that can drop a repeated key does so.\n */\n readonly key: string;\n readonly person: PersonId;\n readonly level: Level;\n readonly title: string;\n readonly body: string;\n readonly url?: string;\n /** A report of the incident: its anchor at the time of the send. */\n readonly incident: ReportId;\n /** The time after which the message has no use. */\n readonly expires?: Instant;\n /**\n * True: the channel sends the message in its silent mode, for example Pushover priority `-1`, or a\n * text and no call. The escalation sets it in the quiet window of the person. A `life-safety`\n * message is not quiet in the window. A mute with the effect `silent` makes each message quiet,\n * also at `life-safety`. The channel keeps no rule of its own about the time of day.\n */\n readonly quiet: boolean;\n /**\n * True: the message tells of the entry of a channel into the reserve of its quota. The channel can send\n * it from the reserve, one time in each window. `messageOf` sets it.\n */\n readonly useReserve?: boolean;\n /**\n * The why line: why the message reaches the person, in the limit of the channel. The runtime makes it from the\n * `WhyRecord` of the route and the private labels. It holds no address, point or region code.\n */\n readonly why?: string;\n}\n\n/** The address of a person on a channel, from the private configuration. The repo does not hold an address. */\nexport type Address = Readonly<Record<string, string>>;\n\n/** The receipt of a sent message, as the channel gives it. */\nexport type Receipt = Readonly<Record<string, string>>;\n\n/**\n * The stages of the quota of a channel. Each stage is a line of system reports:\n *\n * - `low`: the window has 2 reserves of units or fewer left.\n * - `reserve`: the window has the reserve or fewer left. The channel sends only `life-safety`.\n * - `spent`: the provider refuses each message, also a `life-safety` message.\n */\nexport type QuotaStage = \"low\" | \"reserve\" | \"spent\";\n\n/** The state of the quota of a channel in its window, as the gate of the channel counts it. */\nexport interface ChannelQuota {\n readonly channel: ChannelId;\n /** The units of one window. */\n readonly limit: number;\n /** The last units of the window. The channel uses them only for `life-safety`. */\n readonly reserve: number;\n /** The units used in the window. */\n readonly used: number;\n /** The end of the window. */\n readonly resetAt?: Instant;\n /** The provider refuses each message until this time. */\n readonly blockedUntil?: Instant;\n /** The name of the units in a text, in the plural: for example `cents` for a cap of the spend. The default is `units`. */\n readonly unit?: string;\n}\n\n/**\n * The stages of the balance of a provider account. Each stage is a line of system reports:\n *\n * - `low`: the balance is below a floor. Each floor that the balance is below gives its own line `low`.\n * - `empty`: the balance is 0 or less. The provider then refuses each paid message.\n * - `unread`: no read passed for the maximum age or longer. Then the watch cannot see a low balance.\n */\nexport type BalanceStage = \"low\" | \"empty\" | \"unread\";\n\n/** One read of the balance of a provider account that passed. */\nexport interface BalanceRead {\n /** The balance in the currency of the account. It is below 0 when the account owes money. */\n readonly balance: number;\n /** The currency of the account, as a code of ISO 4217: for example `USD`. */\n readonly currency: string;\n readonly at: Instant;\n}\n\n/**\n * The stages of another copy of the system (AL-16), as this copy sees it. Each stage is a line of system reports:\n *\n * - `skew`: the clock of the other copy differs from the clock of this copy by more than the limit.\n * - `config`: the other copy has a different hash of the configuration. Then the copies can route an alert in two ways.\n * - `unread`: no read of the log of the other copy passed for the maximum age. Then the two copies can both send.\n * - `unsteady`: the other copy did not get steady for `COPY_STEADY_LIMIT` (AL-108). It starts again and again, and it sends nothing.\n */\nexport type CopyStage = \"skew\" | \"config\" | \"unread\" | \"unsteady\";\n\n/** One read of the log of another copy that passed. */\nexport interface CopyRead {\n /** The middle of the call, on the clock of this copy. */\n readonly at: Instant;\n /** The time of the other copy minus `at`. It is below 0 when the clock of the other copy is behind. */\n readonly skew: Duration;\n /** This value tells if the other copy has the hash of the configuration of this copy. */\n readonly sameConfig: boolean;\n}\n\n/** The watch of another copy of the system, at one time. */\nexport interface CopyWatch {\n /** The id of the other copy. */\n readonly copy: string;\n /** The largest difference of the two clocks with no stage `skew`. */\n readonly skewLimit: Duration;\n /** The longest time with no read that passed. After it, the stage is `unread`. */\n readonly maxAge: Duration;\n /** The start of the watch. With no read, the time of `unread` counts from it. */\n readonly since: Instant;\n /** The last read that passed. */\n readonly read?: CopyRead;\n /**\n * The last start of each drill of the other copy, by the id of the drill, on the clock of that copy (AL-43). The last\n * read that passed gives them. A copy of an older build gives none.\n */\n readonly drills?: Readonly<Record<string, Instant>>;\n /**\n * The first read that passed and told that the other copy is not steady, after its last steady read (AL-108). A steady\n * read ends it. A failed read keeps it. A copy of an older build tells nothing, thus its watch has none.\n */\n readonly unsteadySince?: Instant;\n}\n\n/** The watch of the balance of one provider account, at one time. */\nexport interface ProviderBalance {\n /** The provider, as an id in the `dependsOn` of its channels: for example `provider:twilio`. */\n readonly provider: string;\n /** The name of the provider in a text: for example `Twilio`. */\n readonly title: string;\n /** The channels that the account pays for. The reports have their subjects. */\n readonly channels: readonly ChannelId[];\n /**\n * The floors of the balance in the currency of the account. The list has one floor or more. Below a floor, the stage is\n * `low`. Each floor that the balance is below gives its own line `low`.\n */\n readonly floors: readonly number[];\n /** The longest time with no read that passed. After it, the stage is `unread`. */\n readonly maxAge: Duration;\n /** The start of the watch. With no read, the time of `unread` counts from it. */\n readonly since: Instant;\n /** The last read that passed. */\n readonly read?: BalanceRead;\n}\n\n/**\n * The result of a send. A failed send has one of these kinds:\n *\n * - `network`, `timeout` and `server`: the channel can have the message.\n * - `rate-limited`: the provider refuses each message until the retry.\n * - `reserved`: the channel keeps the last units of its quota for a higher level. It still sends a message of that level.\n * - `auth` and `refused`: the provider refused the key or the message.\n * - `consent`: the address has no opt-in, or its person took the opt-in back with a STOP reply. The channel sent nothing.\n * - `quiet`: the message is quiet, and the channel has no silent mode, as a call. The step goes after the quiet window.\n * - `expired`: the message expired before the send. The channel sent nothing.\n */\nexport type SendOutcome =\n | { readonly ok: true; readonly receipt: Receipt; readonly accepted: Instant }\n | {\n readonly ok: false;\n readonly kind: \"network\" | \"timeout\" | \"server\" | \"rate-limited\" | \"reserved\" | \"auth\" | \"refused\" | \"consent\" | \"quiet\" | \"expired\";\n readonly message: string;\n readonly retryAfter?: Duration;\n };\n\n/** The kind of a failed send. `SendOutcome` tells each kind. */\nexport type ChannelFailureKind = Extract<SendOutcome, { readonly ok: false }>[\"kind\"];\n\n/**\n * The outcome of a probe of a channel: a call to its provider that sends nothing and costs nothing. A success tells that\n * the provider takes the calls of the channel. A failure has a kind of `ChannelFailureKind`.\n */\nexport type ProbeOutcome =\n | { readonly ok: true; readonly at: Instant }\n | { readonly ok: false; readonly kind: ChannelFailureKind; readonly message: string };\n\n/** The state of a sent message. */\nexport type DeliveryState = \"accepted\" | \"delivered\" | \"acknowledged\" | \"expired\" | \"failed\";\n\n/** The state of a sent message, as the channel tells it. */\nexport interface DeliveryStatus {\n readonly state: DeliveryState;\n readonly at: Instant;\n /** The device or the person that acknowledged, when the channel tells it. */\n readonly by?: string;\n readonly reason?: string;\n}\n\n/**\n * The procedures of one channel. Each channel package registers them under the path\n * `alerts.channel.<id>.<name>`. The core does the escalation and the acknowledgment, not the channel.\n *\n * - `describe`: no effects.\n * - `send`: it writes `network`. It is not idempotent, unless the channel drops a repeated key.\n * - `status`: it reads `network`.\n * - `cancel`: it writes `network`. It stops the repeats of a message. It is idempotent.\n * - `probe`: it reads `network`. It is an authenticated read that sends nothing and costs nothing. The runtime calls it\n * 15 minutes after the last good call, and sooner after a failed probe (AL-65). A failed probe counts in the run of the\n * channel, and a success ends the run and the line. A channel with no probe keeps its line until an accepted send.\n * - `services`: no effects. It reads only the address. The procedure is optional.\n */\nexport interface ChannelProcedures {\n describe(): ChannelDescriptor;\n send(input: SendInput): Promise<SendOutcome>;\n status(input: { readonly receipt: Receipt }): Promise<DeliveryStatus>;\n cancel(input: CancelTarget): Promise<void>;\n probe?(): Promise<ProbeOutcome>;\n /**\n * The services that carry the messages of the channel to one address, as node keys of entities. An example is the\n * region of the carrier network of a phone number. The procedure gives an empty list for an address that it cannot\n * read. It does not throw.\n */\n services?(input: { readonly address: Address }): readonly NodeKey[];\n}\n\n/**\n * The services of the contact of a person on one channel, as node keys of entities (`ChannelProcedures.services`).\n * The load adds them to the services of the channel for that person only. A result can tell a private fact of the\n * address, for example the region of a phone number. Thus no problem and no log holds it.\n */\nexport type ContactServices = (channel: ChannelId, address: Address) => readonly NodeKey[];\n\n/** The input of a send. */\nexport interface SendInput {\n readonly message: Message;\n readonly address: Address;\n /**\n * The id of this send of the key. Its characters match `COPY_ID`. Each send of a key has a new id.\n * A channel that repeats a message keeps the id with the message. Then `cancel({ copy })` stops this copy only.\n */\n readonly copy?: string;\n}\n\n/**\n * The target of a cancel. A receipt stops each copy of its delivery key. A copy id stops one copy\n * whose send did not end, thus the cancel has no receipt of it. The new copy of the key continues.\n */\nexport type CancelTarget = { readonly receipt: Receipt } | { readonly copy: string };\n\n/** One step of an escalation: a channel, and the wait after the step before it. */\nexport interface EscalationStep {\n readonly channel: ChannelId;\n /** The time from the start of the escalation to this step. */\n readonly at: Duration;\n}\n\n/**\n * The escalation of one level: the steps, until a person acknowledges. A policy with a subject (`about`) applies only\n * to the incidents about that subject with the status `system`, `test` or `exercise`. For them, it replaces the policy\n * of the level with no subject. Thus no policy with a subject changes the plan of a real warning.\n */\nexport interface EscalationPolicy {\n readonly level: Level;\n /**\n * The daily time of the digest. Only a policy of the level `digest` has it. Without it, the digest goes at the\n * end of the quiet window of the person.\n */\n readonly daily?: DailyTime;\n /** The subject of the policy, as a subject watch. A subject watch with no id matches each subject of its system. */\n readonly about?: SubjectWatch;\n readonly steps: readonly EscalationStep[];\n /** The time after the last step at which the escalation is exhausted. Exhausted is a system alert. */\n readonly exhaustedAfter: Duration;\n}\n\n/** A local time of each day in a time zone. The digest goes at this time. */\nexport interface DailyTime {\n /** The IANA name of the time zone, for example `Europe/Berlin`. */\n readonly zone: string;\n /** The local time `HH:MM`, from `00:00` to `23:59`. */\n readonly time: string;\n}\n\n/**\n * One accepted send of one step of an escalation. The merge state keeps each send, so each copy of\n * the system knows the level that a person already got. A send that failed makes no record, so its\n * step stays due.\n */\nexport interface Delivery {\n /** The key of the message, from `messageKey`. */\n readonly key: string;\n /** A report of the incident: its anchor at the time of the send. */\n readonly incident: ReportId;\n readonly level: Level;\n readonly person: PersonId;\n readonly channel: ChannelId;\n /** The index of the step in the escalation, from 0. */\n readonly step: number;\n /** The time at which the channel accepted the message. */\n readonly at: Instant;\n /** The receipt of the channel, when it gives one. The escalation uses it to cancel or to poll. */\n readonly receipt?: Receipt;\n}\n\n/** An acknowledgment from a person, by any channel or the UI. It stops the escalation of the level. */\nexport interface Acknowledgment {\n /** A report of the incident. The ack applies to the incident that holds this report, also after a merge. */\n readonly incident: ReportId;\n readonly level: Level;\n readonly person: PersonId;\n readonly at: Instant;\n readonly via: ChannelId | \"ui\";\n}\n\n// =============================================================================\n// The merge state\n// =============================================================================\n\n/**\n * A mark of the runtime on a report of a snapshot source. The latest mark of a report at a time tells\n * if the report ended. At one time, a mark with `ended` false wins, so a tie keeps the report live.\n */\nexport interface EndMark {\n readonly report: ReportId;\n readonly at: Instant;\n /** True: the report left the list of its source. False: the report is in the list again. */\n readonly ended: boolean;\n /** The time of the data of the list that ended the report (`asOf` of the fetch), if the list has a time. */\n readonly asOf?: Instant;\n}\n\n/**\n * The mark of a report that left the merge state after the horizon of its incident (`retirements`). A copy\n * of the report that arrives later stays out until the time `until`. Then `pruneTombstones` drops the mark.\n */\nexport interface Tombstone {\n readonly report: ReportId;\n readonly until: Instant;\n}\n\n/**\n * The merge state: five grow-only sets. The join of two states is their union, so each copy of\n * the system that gets the same parts gets the same state. `normalize` gives the one form of a\n * state. It has one report for each id, in the order of the ids. It has each delivery, each\n * acknowledgment and each end mark one time, in the order of their canonical JSON.\n *\n * The tombstones remove parts: a state has no report with a tombstone, and no delivery,\n * acknowledgment or end mark of such a report. The removal reads only the union, so the join keeps its laws.\n */\nexport interface MergeState {\n readonly reports: readonly Report[];\n readonly deliveries: readonly Delivery[];\n readonly acks: readonly Acknowledgment[];\n /** The end marks of the reports of the snapshot sources. */\n readonly ends: readonly EndMark[];\n /** The tombstones of the retired reports: one for each report, with the latest `until`, in the order of the report ids. */\n readonly retired: readonly Tombstone[];\n}\n\n// =============================================================================\n// The assessment\n// =============================================================================\n\n/** The level of an incident for a person, or `none`: no message. */\nexport type AssessedLevel = Level | \"none\";\n\n/** The order of the assessed levels, from the lowest. */\nexport const ASSESSED_LEVELS: readonly AssessedLevel[] = [\"none\", ...LEVELS];\n\n/**\n * The highest levels for the severity and for the urgency of an incident. The level of the table is the\n * lower of the two values.\n */\nexport interface LevelTable {\n readonly severity: Readonly<Record<Severity, AssessedLevel>>;\n readonly urgency: Readonly<Record<Urgency, AssessedLevel>>;\n /**\n * The time after the onset in which the urgency `past` counts as `immediate`. A report of an event that\n * occurred, for example an earthquake, has the urgency `past`. With no time of the assessment or no onset,\n * the age is unknown, and `past` counts as `immediate`. When it is absent, `past` keeps its lookup.\n */\n readonly pastWithin?: Duration;\n}\n\n/** A class of kinds with its own table, for example the kinds that can reach `life-safety`. */\nexport interface KindClass extends LevelTable {\n readonly id: string;\n /** The prefixes of the taxonomy codes of the class, for example `met.tornado`. */\n readonly kinds: readonly string[];\n /** The statuses that can make a message of this class. Absent: the statuses of the policy. */\n readonly statuses?: readonly Status[];\n}\n\n/** The data of the first assessment. A change of the policy is a change of data, not of code. */\nexport interface AssessPolicy {\n /** The statuses that can make a message, for each class with no statuses of its own. Another status gets `none`. */\n readonly statuses: readonly Status[];\n /** The classes, in order. The first class with a prefix of the kind applies. */\n readonly classes: readonly KindClass[];\n /** The table of each kind that no class has. */\n readonly otherwise: LevelTable;\n /** The policy of the relevance for a person with an interest graph. When it is absent, the assessment uses `DEFAULT_RELEVANCE_POLICY`. */\n readonly relevance?: RelevancePolicy;\n}\n\n/**\n * A rule of a person: the highest level of the incidents of some kinds at some places. At each\n * place, the first rule that matches the place and the kind applies. With no matching rule, the\n * table level stays.\n */\nexport interface LevelRule {\n /** The places of the rule. When it is absent, the rule applies at each place of the person. */\n readonly places?: readonly PlaceId[];\n /** The prefixes of the taxonomy codes of the rule. When it is absent, the rule applies to each kind. */\n readonly kinds?: readonly string[];\n /**\n * The kinds of the entries of the rule. The rule matches an incident only through an entry of one of these kinds. A\n * watched place is an entry of the kind `place`. A watched subject has the kind of its system, or `entity`. When it\n * is absent, the rule matches through each entry.\n *\n * An example is a rule with `through: [\"topic\"]` for the outages of online services. It lowers an outage that\n * reaches the person only through a topic of the work. An outage of a service that the person names keeps its level.\n */\n readonly through?: readonly SubjectKind[];\n readonly max: AssessedLevel;\n}\n\n/**\n * The quiet window of a person: a part of each day, in local times of a time zone. In the window,\n * each message below `life-safety` is quiet. A `life-safety` message ignores the window. The shape\n * is that of `TimeWindow` of `@mark1russell7/algebra/clock`, without the days of the week.\n */\nexport interface QuietWindow {\n /** The IANA name of the time zone, for example `Europe/Berlin`. */\n readonly zone: string;\n /** The start of the window, a local time `HH:MM` from `00:00` to `23:59`. The start is in the window. */\n readonly start: string;\n /** The end of the window, a local time `HH:MM`. The end is not in the window. An end before the start crosses midnight. An end equal to the start gives the full day. */\n readonly end: string;\n}\n\n/**\n * A subject that a person watches, other than a place: a source of the system, a service, a cloud\n * region. A watch with no id matches each subject of its system.\n */\nexport interface SubjectWatch {\n readonly system: string;\n readonly id?: string;\n}\n\n/** The places and the rules of one person. The private configuration gives them. */\nexport interface PersonWatch {\n readonly person: PersonId;\n /** The places that the person watches. */\n readonly places: readonly PlaceId[];\n /**\n * The subjects that the person watches. The health reports of the sources have the subjects of\n * the system `alerts.source`. The quota and balance reports have the subjects of the system `alerts.channel`. So the\n * person who operates the system watches `{ system: \"alerts.source\" }` and `{ system: \"alerts.channel\" }`.\n */\n readonly subjects?: readonly SubjectWatch[];\n /** The rules of the person, in order. */\n readonly rules: readonly LevelRule[];\n /** The quiet window of the person. When it is absent, no message is quiet. */\n readonly quiet?: QuietWindow;\n /**\n * The interest graph of the person (`docs/RELEVANCE.md`). With a graph, a place or another entry of an incident\n * counts only when the entry reaches the person. With no graph, each place in the areas counts.\n */\n readonly interests?: InterestGraph;\n /**\n * The rules of the life-safety warnings at the places of the person, one rule for each place at most. A place\n * with no rule has the rule on, and its range is the buffer of the place.\n */\n readonly mandatory?: readonly MandatoryRule[];\n}\n\n/**\n * The rule of the life-safety warnings at one place of a person. When the rule is on, a warning of the level\n * `life-safety` at the place in the range always counts. An edge that is off does not stop it, and a mute makes it\n * silent under the policy `silent` of the relevance.\n */\nexport interface MandatoryRule {\n readonly place: PlaceId;\n /** False when the person turned the rule off at this place. */\n readonly on: boolean;\n /**\n * The range in kilometers. A match by a shape at this distance from the place or nearer is in the range. A match by\n * the codes or by the id of the place is always in the range.\n */\n readonly rangeKm: number;\n}\n\n/** A measured value with its interval. The interval holds the value: `low <= value <= high`. */\nexport interface Estimate {\n readonly value: number;\n readonly low: number;\n readonly high: number;\n}\n\n/**\n * The priors of one kind of event, from public measures. A field that the measures do not give is\n * absent. Then the shadow score of the kind has no read.\n */\nexport interface KindPrior {\n /** The share of the warnings of the kind that an event verified, from 0 to 1. It applies to the significance `warning` only. */\n readonly verified?: Estimate;\n /** The deaths in one event of the kind. */\n readonly deaths?: Estimate;\n /** The injuries in one event of the kind. */\n readonly injuries?: Estimate;\n /** The harm in one area under one active alert of the kind, for each significance with a measure. */\n readonly under?: Readonly<Partial<Record<Significance, UnderPrior>>>;\n}\n\n/** The kinds of area of an alert: a county, or a forecast zone. */\nexport type AlertArea = \"county\" | \"zone\";\n\n/**\n * The harm in one area under one active alert of a kind and a significance. An area is one alert in one county or one\n * zone. The measure counts each event under an active alert. Thus it holds the probability of the event.\n */\nexport interface UnderPrior {\n /** The deaths in one area under one alert. */\n readonly deaths: Estimate;\n /** The injuries in one area under one alert. */\n readonly injuries: Estimate;\n /** The kind of area of the measure. The measure takes the kind of area that has most of the events of the kind. */\n readonly area: AlertArea;\n}\n\n/**\n * The priors of the shadow score. Each factor comes from a public measure, not from a guess. The\n * format of the file is `alerts-priors/2`. Format 2 adds the harm under an active alert (`KindPrior.under`).\n */\nexport interface ScorePriors {\n readonly format: \"alerts-priors/2\";\n /** The priors of the kinds, by prefixes of the taxonomy codes. For each field, the longest prefix of a kind with that field decides. */\n readonly kinds: Readonly<Record<string, KindPrior>>;\n /** The probability of each CAP certainty value, from 0 to 1. */\n readonly certainty: Readonly<Partial<Record<Certainty, Estimate>>>;\n}\n\n/**\n * The source of a factor of a shadow score in the priors.\n *\n * - The table `kinds` has a prefix of the kind as its key. The table `certainty` has a CAP certainty value.\n * - The table `under` has a prefix of the kind, the significance and the kind of area of the measure.\n */\nexport type ScoreSource =\n | { readonly table: \"kinds\" | \"certainty\"; readonly key: string }\n | { readonly table: \"under\"; readonly key: string; readonly significance: Significance; readonly area: AlertArea };\n\n/** One factor of a shadow score, with the key of the priors that gave it. */\nexport interface ScoreFactor {\n readonly estimate: Estimate;\n /** The table of the priors and its key. */\n readonly from: ScoreSource;\n}\n\n/**\n * The expected harm of an incident in one area. The basis `event` gives the probability of the event times the\n * deaths and the injuries of one event. Then each interval holds each product of a point of the two intervals.\n */\nexport interface ExpectedHarm {\n readonly deaths: Estimate;\n readonly injuries: Estimate;\n}\n\n/** A factor of the shadow score that the priors do not give. */\nexport type ScoreGap = \"probability\" | \"deaths\" | \"injuries\";\n\n/**\n * The shadow score of an incident. The score does not decide a level at this time. The table decides, and the\n * assessment shows the score next to it.\n *\n * - The basis `event` is the probability of the event times the harm of one event.\n * - The basis `alert` is the harm in one area under one active alert of the kind and the significance.\n * - A score with a gap has no read, and it shows each factor that the priors do not give.\n */\nexport type ShadowScore =\n | {\n readonly read: true;\n /**\n * The basis of the score. A score of a log line from before the basis `alert` has no field `basis`. Its basis is\n * `event`.\n */\n readonly basis?: \"event\";\n /** The probability that the event occurs. */\n readonly probability: ScoreFactor;\n /** The deaths in one event of the kind. */\n readonly deaths: ScoreFactor;\n /** The injuries in one event of the kind. */\n readonly injuries: ScoreFactor;\n /** The probability times the deaths and the injuries of one event. */\n readonly expected: ExpectedHarm;\n }\n | {\n readonly read: true;\n readonly basis: \"alert\";\n /** The deaths in one area under one alert, from the table `under`. */\n readonly deaths: ScoreFactor;\n /** The injuries in one area under one alert, from the table `under`. */\n readonly injuries: ScoreFactor;\n /** The expected harm. It is the estimate of each factor, because the measure holds the probability of the event. */\n readonly expected: ExpectedHarm;\n }\n | { readonly read: false; readonly missing: readonly ScoreGap[] };\n\n/** An incident with its level from the table and its shadow score, as the map gives it. */\nexport interface ScoredIncident {\n readonly anchor: ReportId;\n readonly level: AssessedLevel;\n /** The shadow score of the incident. An incident with no score is in no difference. */\n readonly shadow?: ShadowScore;\n}\n\n/**\n * A difference between the table and the shadow score. The table gives `above` a higher level than `below`.\n * The score gives `below` more expected deaths and more expected injuries, and the intervals do not overlap.\n */\nexport interface ShadowDifference {\n /** The incident with the higher level of the table. */\n readonly above: ReportId;\n /** The incident with the higher shadow score. */\n readonly below: ReportId;\n}\n\n/** A reason of an assessment. The UI shows the reasons, so each level tells why. */\nexport type AssessReason =\n /** Each line of the incident is cancelled or expired. */\n | { readonly kind: \"ended\" }\n /** The policy does not send incidents of this status. */\n | { readonly kind: \"status\"; readonly status: Status }\n /** No place of the person is in the areas of the incident. */\n | { readonly kind: \"no-place\" }\n /** The incident has no area, and the person watches no subject of the incident. */\n | { readonly kind: \"no-subject\" }\n /** The incident is private (AL-92), and the person is not in its addresses. */\n | { readonly kind: \"not-addressed\" }\n /** The incident is private, and the person is in its addresses. The places and the subjects do not count. */\n | { readonly kind: \"addressed\" }\n /**\n * The areas of the incident have no code and no place, and no shape can match. Either the areas have\n * no shape, or no place of the person has a position.\n */\n | { readonly kind: \"no-codes\" }\n /** The configuration has no watched place for this id of the person. */\n | { readonly kind: \"unknown-place\"; readonly place: PlaceId }\n /**\n * An area of the incident covers this place. The codes are the codes of the place that decided the match.\n * `distanceKm` is the distance from the place to the nearest shape that decided, and it is 0 in a shape.\n * It is present when that distance is in the buffer of the place. For a match by a shape only, the codes\n * are empty. `shapeRefused` is true when the codes of a block decided because `@mark1russell7/geo`\n * refuses each shape of that block. `zoneFallback` is true when a fire zone code of an area decided through the\n * forecast zone code of the place with the same code. Then the place has no fire zone code of that state.\n */\n | {\n readonly kind: \"place\";\n readonly place: PlaceId;\n readonly codes: readonly RegionCode[];\n readonly distanceKm?: number;\n readonly shapeRefused?: true;\n readonly zoneFallback?: true;\n }\n /** The person watches a subject of the incident. */\n | { readonly kind: \"subject\"; readonly subject: SubjectWatch }\n /**\n * The level of the table at this place is not the level of the incident. The lines of these reports hold the\n * place, and the highest table of those lines gives the level.\n */\n | { readonly kind: \"place-table\"; readonly place: PlaceId; readonly reports: readonly ReportId[]; readonly level: AssessedLevel }\n /** The table gave this level. The class is absent for the table `otherwise`. */\n | {\n readonly kind: \"table\";\n readonly class?: string;\n readonly bySeverity: AssessedLevel;\n readonly byUrgency: AssessedLevel;\n readonly level: AssessedLevel;\n /** This value is true when the urgency `past` counted as `immediate` in the window `pastWithin` of the table. */\n readonly recentPast?: true;\n /**\n * This value is true when the table is the quiet table of the sources of other copies (AL-76). The kind has no\n * class, and this copy runs no source of the incident.\n */\n readonly foreign?: true;\n }\n /**\n * A rule of the person lowered the level at this place. The index is the position of the rule.\n * The place is absent for a subject.\n */\n | { readonly kind: \"rule\"; readonly place?: PlaceId; readonly index: number; readonly max: AssessedLevel }\n /** The shadow score of the incident. It does not change the level. */\n | { readonly kind: \"shadow\"; readonly score: ShadowScore }\n /**\n * The relevance of the incident over the interest graph of the person. `reached` holds the entries that reach the\n * person alone: the places, the areas, the subjects and the topic, in this order. `mandatory` holds the places\n * where the rule of the life-safety warnings keeps the level. `entryLevel` is present when an entry that is not a\n * watched place reaches the person. It is the level of the table, up to `entryMax` of the policy, before the rules. The why comes from the strongest path.\n */\n | {\n readonly kind: \"reach\";\n readonly reach: Estimate;\n readonly reached: readonly NodeKey[];\n readonly mandatory: readonly PlaceId[];\n readonly entryLevel?: AssessedLevel;\n readonly why?: WhyRecord;\n }\n /** The relevance failed, so the places in the areas decided, as for a person with no graph. The message tells the fault. */\n | { readonly kind: \"relevance-fault\"; readonly message: string };\n\n/** The level of one incident for one person, with its reasons. */\nexport interface Assessment {\n /** The anchor of the incident at the time of the assessment. */\n readonly incident: ReportId;\n readonly person: PersonId;\n readonly level: AssessedLevel;\n /** The places of the person that the areas of the incident contain. */\n readonly places: readonly PlaceId[];\n readonly reasons: readonly AssessReason[];\n /**\n * The mute of the person that matches the incident, and its effect: the field `muted` of the relevance. With the\n * effect `absent`, the incident does not reach the person. With `silent`, the level stays, and `route` sends one quiet\n * message at most.\n */\n readonly muted?: { readonly mute: string; readonly effect: MuteEffect };\n}\n\n// =============================================================================\n// Relevance: how much an incident touches one person (AL-35, `docs/RELEVANCE.md`)\n// =============================================================================\n\n/** The three kinds of the subjects of an incident. */\nexport type SubjectKind = \"place\" | \"topic\" | \"entity\";\n\n/**\n * A system of the ids of subjects. The system `place` holds the watched places of a person. The system\n * `topic` holds the codes of the taxonomy and their prefixes.\n */\nexport type SubjectSystem =\n | \"place\"\n | \"point\"\n | \"polygon\"\n | \"ugc\"\n | \"ugc-fire\"\n | \"same\"\n | \"fips\"\n | \"state\"\n | \"iso3166\"\n | \"geonames\"\n | \"icao\"\n | \"topic\"\n | \"iptc\"\n | \"cap-category\"\n | \"cve\"\n | \"wikidata\"\n | \"asn\"\n | \"domain\"\n | \"provider-region\"\n | \"ticker\"\n | \"lei\"\n | \"purl\";\n\n/**\n * The kind of the subjects of each system. The list is closed. A new system comes with the first source or\n * default that gives its ids.\n */\nexport const SUBJECT_SYSTEMS: Readonly<Record<SubjectSystem, SubjectKind>> = {\n place: \"place\",\n point: \"place\",\n polygon: \"place\",\n ugc: \"place\",\n \"ugc-fire\": \"place\",\n same: \"place\",\n fips: \"place\",\n state: \"place\",\n iso3166: \"place\",\n geonames: \"place\",\n icao: \"place\",\n topic: \"topic\",\n iptc: \"topic\",\n \"cap-category\": \"topic\",\n cve: \"entity\",\n wikidata: \"entity\",\n asn: \"entity\",\n domain: \"entity\",\n \"provider-region\": \"entity\",\n ticker: \"entity\",\n lei: \"entity\",\n purl: \"entity\",\n};\n\n/**\n * The key of a node of an interest graph: `person`, or `<system>:<id>` with a system of `SUBJECT_SYSTEMS`.\n * Examples are `place:home`, `ugc:KSC173`, `topic:infra.power.outage` and `domain:example.com`. The id is the\n * text after the first colon, thus an id can hold a colon, as in `purl:pkg:npm/example`.\n */\nexport type NodeKey = string;\n\n/**\n * The kind of an edge. The first four are the kinds of dependency of Rinaldi, Peerenboom and Kelly (2001). An\n * edge of the kind `interest` goes into the person.\n */\nexport type EdgeKind = \"physical\" | \"cyber\" | \"geographic\" | \"logical\" | \"interest\";\n\n/**\n * The origin of the weight of an edge. Each origin except `person` is one layer of the defaults.\n * - `base`: the human base, the same for each person.\n * - `places`: the watched places of the person.\n * - `services`: the services that the person names.\n * - `delivery`: the services of the channels of the person (`ChannelDescriptor.services`).\n * - `work`: the tools and the services of a kind of work.\n * - `data`: public data, for example the service area of a power utility.\n * - `measured`: a measure of the system, for example the DNS providers of a domain.\n * - `person`: the person set the value. No default replaces it.\n */\nexport type EdgeOrigin = \"base\" | \"places\" | \"services\" | \"delivery\" | \"work\" | \"data\" | \"measured\" | \"person\";\n\n/** One edge of an interest graph: the cause at `from` can impair the node at `to`, with a chance. */\nexport interface InterestEdge {\n /** The id of the edge. The exact sum expands the edges in the order of their ids, thus the order of a file has no effect. */\n readonly id: string;\n /** The cause. It is not `person`. */\n readonly from: NodeKey;\n /** The node that the cause can impair, or `person`. */\n readonly to: NodeKey;\n readonly kind: EdgeKind;\n /**\n * The chance that an effect passes along the edge, from 0 to 1. The interval is the doubt of a default. An\n * unknown edge gets a wide interval, not 0. For a supply with a backup, the weight is the need times the\n * chance that an outage lasts longer than the backup.\n */\n readonly weight: Estimate;\n readonly origin: EdgeOrigin;\n /** The data or the measure that gave the weight, for example `eia-861/2025`. */\n readonly source?: string;\n /** The day of the source or of the choice of the person, `YYYY-MM-DD`. */\n readonly date?: string;\n /** False when the person turned the route off. The edge stays in the graph as a row, and the reach does not use it. */\n readonly on: boolean;\n}\n\n/**\n * A mute of a person. An incident matches when its kind has a prefix in `kinds`, and an entry of the incident\n * is in `subjects`. An absent list matches each incident. A mute has one list or both. A matched incident does\n * not reach the person on any path, except an incident of the mandatory class (`RelevancePolicy`).\n */\nexport interface Mute {\n readonly id: string;\n /** The prefixes of the taxonomy codes, as in `LevelRule`. */\n readonly kinds?: readonly string[];\n /** The subjects of the incidents that the mute matches. */\n readonly subjects?: readonly NodeKey[];\n /** The mute has effect until this time. With no end, it has effect until the person removes it. */\n readonly until?: Instant;\n /** The day that the person set the mute, `YYYY-MM-DD`. */\n readonly date: string;\n}\n\n/**\n * The interest graph of one person, the format `alerts-interest/1`. The file is private configuration. The\n * repository holds the model, the taxonomy and the defaults from public data, and no graph of a real person.\n */\nexport interface InterestGraph {\n readonly format: \"alerts-interest/1\";\n readonly person: PersonId;\n readonly edges: readonly InterestEdge[];\n readonly mutes: readonly Mute[];\n /** The private labels of the nodes, for the text of an alert. The why record holds only the keys. */\n readonly labels?: Readonly<Record<NodeKey, string>>;\n}\n\n/** A subject of an incident that is a node of the graph of a person. */\nexport interface SubjectEntry {\n readonly node: NodeKey;\n readonly kind: SubjectKind;\n /**\n * The chance that the incident hits the subject when the event is real. It is the share of the area near a\n * place for a place, and 1 for a topic or a named entity.\n */\n readonly hit: Estimate;\n}\n\n/** One path from a subject of an incident to the person. */\nexport interface RelevancePath {\n readonly subject: NodeKey;\n /** The ids of the edges of the path, in order from the subject. */\n readonly edges: readonly string[];\n /** The chance that each part of the path is on: the hit chance times the weight of each edge. */\n readonly chance: number;\n}\n\n/**\n * The record of why an incident reaches a person. The delivery puts it in the text of each channel. It holds\n * keys and no labels, and the runtime gives the private labels.\n */\nexport interface WhyRecord {\n /** A stable id of the reason, `reach.<subject kind>.<origin>`, for example `reach.place.base`. */\n readonly rule: string;\n readonly subject: NodeKey;\n readonly kind: SubjectKind;\n /** The first node after the subject, when the path has two nodes or more between the subject and the person. */\n readonly via?: NodeKey;\n /** The last node before the person: the place, the service or the topic of the interest. */\n readonly anchor: NodeKey;\n /** The origin of the last edge of the path, the interest edge. */\n readonly origin: EdgeOrigin;\n /** The reach of the shown paths alone, divided by the full reach, from 0 to 1. */\n readonly coverage: number;\n}\n\n/** The effect of a mute on an incident: it does not reach the person, or it reaches the person with no sound. */\nexport type MuteEffect = \"absent\" | \"silent\";\n\n/** The policy of the relevance. */\nexport interface RelevancePolicy {\n /** The most edges of a path. A longer path does not count. */\n readonly hopCap: number;\n /** The most paths in a relevance, from the strongest. */\n readonly topPaths: number;\n /** The effect of a mute on an incident of the mandatory class. A mute removes each other incident that it matches. */\n readonly mandatory: MuteEffect;\n /**\n * The highest level of an incident that reaches the person only through entries that are not watched places. The\n * level `life-safety` needs a place of the person. When it is absent, the assessment uses `DEFAULT_ENTRY_MAX`.\n */\n readonly entryMax?: AssessedLevel;\n}\n\n/** The relevance of an incident for one person. */\nexport interface Relevance {\n /**\n * The reach: the chance that at least one path from a subject of the incident to the person is fully on.\n * The value comes from the point weights. The interval comes from the ends of the intervals of the weights.\n */\n readonly reach: Estimate;\n /** The lower bound at the point weights: the chance of the best path. */\n readonly best: number;\n /** The upper bound at the point weights: noisy-OR over the paths. */\n readonly noisyOr: number;\n /** The strongest paths, from the strongest. */\n readonly paths: readonly RelevancePath[];\n /** The why, from the strongest path. It is absent when no path reaches the person. */\n readonly why?: WhyRecord;\n /** The edge with the largest Birnbaum importance: the reach with the edge on, minus the reach with the edge off. */\n readonly weakest?: { readonly edge: string; readonly importance: number };\n /** The edge to ask the person about: the largest importance times the width of the weight interval, of the edges with a default weight. */\n readonly next?: { readonly edge: string; readonly gain: number };\n /** The mute that matched, and its effect. When the effect is `absent`, the reach is 0 and the relevance has no path. */\n readonly muted?: { readonly mute: string; readonly effect: MuteEffect };\n /**\n * The kind of the result when the budget of steps ended the exact sum. With `bounds`, the reach is noisy-OR, a\n * ceiling. With `partial`, the path search did not end, and the ceiling is 1. An exact result has no field.\n */\n readonly bound?: \"bounds\" | \"partial\";\n}\n","/**\n * The id functions of the alert system. Each id is the SHA-256 of a content, in lowercase hex.\n * So each adapter and each copy of the system gives the same id to the same content, and a\n * duplicate changes nothing.\n *\n * The hash input is the canonical JSON of an array: the scheme, the kind of id, then the fields.\n * JSON escapes each string, so two different lists of fields do not give the same input. The kind\n * keeps the ids of two kinds apart. The hash comes from `@mark1russell7/rigor-generators`, the home\n * of content hashes. It is pure JavaScript, so the ids are synchronous in Node and in browsers.\n */\nimport { canonicalHash } from \"@mark1russell7/rigor-generators\";\nimport type { CorrelationKey, Instant, Level, ObservationId, PersonId, ReportId, SourceId } from \"./contracts.ts\";\n\n/** The version of the id scheme. A change of the input of an id function raises it. */\nexport const ID_SCHEME = \"alerts-id/1\";\n\n/** The input of `observationId`: the parts of an observation that tell its content. */\nexport interface ObservationIdInput {\n readonly source: SourceId;\n readonly contentType: string;\n readonly body: string;\n /**\n * The part of the URL of the request that the `map` function of the adapter reads. The `map` function\n * can read the URL, so it is part of the content. A part that `map` does not read, for example the time\n * of a poll, is not in it. Then a poll with no change gives the same id.\n */\n readonly url?: string;\n}\n\n/** The fields of each input of `reportId`: the source, the key that the source gives and the part. */\ninterface ReportIdFields {\n readonly source: SourceId;\n readonly key: string;\n /**\n * The part of a message that gives two or more reports, for example `info[1]`, the second info block of a CAP\n * message. The reports of one message keep its key, so a reference to the message ends each of them. A report\n * with no part keeps the id of a report of one part.\n */\n readonly part?: string | undefined;\n}\n\n/**\n * The input of `reportId`. A report gives its sent time, or a version when its source gives no time of its own.\n * The version is the id of the observation that holds the text of the report. Thus each copy and each start of the\n * runtime give one id to one text. A new text gets a new id with the same key.\n */\nexport type ReportIdInput = ReportIdFields & ({ readonly sent: Instant; readonly version?: undefined } | { readonly version: string; readonly sent?: undefined });\n\n/** The input of `messageKey`: one step of the escalation of one level of one incident to one person. */\nexport interface MessageKeyInput {\n readonly incident: ReportId;\n readonly level: Level;\n readonly person: PersonId;\n /** The index of the step in the escalation of the person, from 0. */\n readonly step: number;\n /**\n * The count of the ends of the escalations of the person in the incident before this escalation (`EscalationEnd`).\n * When the threat comes back to the person after an end, the new escalation gets new keys.\n */\n readonly episode?: number | undefined;\n}\n\n/**\n * This function gives the id of an observation. A poll that gets the same body from the same\n * request gives the same id, so the log keeps the observation one time. The fetch time and the\n * other facts of the transport are not part of the id.\n */\nexport function observationId(input: ObservationIdInput): ObservationId {\n return digest([\"observation\", input.source, input.contentType, input.url ?? null, input.body]) as ObservationId;\n}\n\n/**\n * This function gives the id of a report. An update of the source has a new key, a new sent\n * time or a new version, so it gets a new id. The merge uses the smallest report id of an incident\n * as its anchor. A version is a text in the hash input, and a sent time is a number. Thus a version\n * and a sent time do not give the same id.\n */\nexport function reportId(input: ReportIdInput): ReportId {\n const fields = [\"report\", input.source, input.key, input.version ?? input.sent];\n return digest(input.part === undefined ? fields : [...fields, input.part]) as ReportId;\n}\n\n/** The system of the correlation key of one CAP message (`capMessageKey`). */\nexport const CAP_MESSAGE_SYSTEM = \"cap\";\n\n/** The input of `capMessageKey`: the values that name one CAP message, as in the field `references` of CAP 1.2. */\nexport interface CapMessageKeyInput {\n readonly sender: string;\n readonly identifier: string;\n readonly sent: Instant;\n /**\n * The part of a message that gives two or more reports, for example `info[1]`. Each part gets its own key, because\n * two info blocks of one message can tell of two events.\n */\n readonly part?: string | undefined;\n}\n\n/**\n * This function gives the correlation key of one CAP message. Two sources that carry one message give it the same\n * sender, identifier and sent time. Thus the key joins the copies of a message in one incident, also with no VTEC\n * key. A special weather statement of the NWS is an example (AL-8).\n *\n * - The id is a hash, because the sender of a local authority can be the address of a person.\n * - The sent time is a number in the hash input. Thus two forms of one time give one key.\n * - An empty sender or identifier gives no key, because the two values do not name a message then.\n */\nexport function capMessageKey(input: CapMessageKeyInput): CorrelationKey | undefined {\n const sender = input.sender.trim();\n const identifier = input.identifier.trim();\n if (sender === \"\" || identifier === \"\") return undefined;\n const fields = [\"cap-message\", sender, identifier, input.sent];\n return { system: CAP_MESSAGE_SYSTEM, id: digest(input.part === undefined ? fields : [...fields, input.part]) };\n}\n\n/**\n * The characters of a copy id: letters, digits, `_` and `-`. A channel can put a copy id in the path\n * of a URL, thus a `.` or a `/` is not in it.\n */\nexport const COPY_ID: RegExp = /^[A-Za-z0-9_-]+$/;\n\n/** The input of `digestKey`: one digest of one person at one time, on one step of the digest policy. */\nexport interface DigestKeyInput {\n readonly person: PersonId;\n /** The time of the digest: the instant of the daily time. */\n readonly at: Instant;\n /** The index of the step in the digest policy, from 0. */\n readonly step: number;\n}\n\n/** This function gives the key of a digest message. The same digest after a restart gets the same key. */\nexport function digestKey(input: DigestKeyInput): string {\n return digest([\"digest\", input.person, input.at, input.step]);\n}\n\n/**\n * This function gives the key of the delivery of one incident in a digest message. Each incident of a digest has its\n * own delivery, thus each copy of the system knows which incidents a digest told.\n */\nexport function digestEntryKey(key: string, incident: ReportId): string {\n return digest([\"digest-entry\", key, incident]);\n}\n\n/**\n * This function gives the key of a message. A channel that can drop a repeated key does so. A\n * repeat of the same step gets the same key, and the next step gets a new key.\n *\n * - An episode after the first one is in the key. Thus a new escalation after an end gets new keys.\n * - The key of the first episode has no episode field. Thus the keys of a log from before the episodes do not change.\n */\nexport function messageKey(input: MessageKeyInput): string {\n const episode = input.episode ?? 0;\n const fields = [\"message\", input.incident, input.level, input.person, input.step];\n return digest(episode === 0 ? fields : [...fields, episode]);\n}\n\n// The form \"json\" writes NaN and an infinite number as null, and escapes a lone surrogate. So the\n// id functions do not throw, and `map` stays total.\nfunction digest(fields: readonly (string | number | null)[]): string {\n return canonicalHash([ID_SCHEME, ...fields], { form: \"json\" });\n}\n","/**\n * The audience of a report or an incident (AL-92). A report with no `addresses` is public: the CAP scope `Public`.\n * A report with `addresses` is private: the CAP scope `Private`. It reaches only the persons of its addresses.\n *\n * The merge puts reports in one incident only when their audiences are the same. Thus the text of a private report\n * does not reach a person outside its addresses through an incident. Also, a public report does not lose its persons.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { PersonId } from \"./contracts.ts\";\n\n/** The part of a report or an incident that gives its audience. */\nexport interface Audience {\n /** The persons of a private item. A public item has no such field. */\n readonly addresses?: readonly PersonId[] | undefined;\n}\n\n/** This function tells if a report or an incident is private. */\nexport function isPrivate(item: Audience): boolean {\n return item.addresses !== undefined;\n}\n\n/** This function gives the addresses of a private item in one order, with no repeat. */\nexport function audienceOf(addresses: readonly PersonId[]): readonly PersonId[] {\n return [...new Set(addresses)].sort(compareCodeUnits);\n}\n\n/** This function gives the key of the audience of an item: `public`, or the addresses of a private item in one order. */\nexport function audienceKey(item: Audience): string {\n return item.addresses === undefined ? \"public\" : JSON.stringify(audienceOf(item.addresses));\n}\n\n/** This function tells if a person is in the audience of an item. A public item has each person. */\nexport function inAudience(item: Audience, person: PersonId): boolean {\n return item.addresses === undefined || item.addresses.includes(person);\n}\n","/**\n * The merge of the alert system: the join of two merge states, and the incidents of a state.\n *\n * The join is the union of five grow-only sets, so it is idempotent, commutative and\n * associative. The incidents are a function of the state and a time. So each copy of the system\n * that gets the same reports gets the same incidents, in any order of arrival.\n */\nimport { stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { canonicalJson } from \"@mark1russell7/rigor-generators\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { audienceKey, audienceOf } from \"./audience.ts\";\nimport type {\n Acknowledgment,\n Area,\n Certainty,\n Delivery,\n EndMark,\n Incident,\n IncidentLine,\n Instant,\n Level,\n MergeState,\n PersonId,\n Report,\n ReportId,\n Severity,\n Tombstone,\n Urgency,\n} from \"./contracts.ts\";\nimport { LEVELS } from \"./contracts.ts\";\n\n/** The merge state with no part. */\nexport const EMPTY_STATE: MergeState = { reports: [], deliveries: [], acks: [], ends: [], retired: [] };\n\n/** The parts of a merge state, in any order and with duplicates. */\nexport interface MergeParts {\n readonly reports?: readonly Report[];\n readonly deliveries?: readonly Delivery[];\n readonly acks?: readonly Acknowledgment[];\n readonly ends?: readonly EndMark[];\n readonly retired?: readonly Tombstone[];\n}\n\n/**\n * This function gives the one form of a merge state. It keeps one report for each id: for two\n * contents of one id, the content with the smaller canonical JSON. It keeps each delivery, each\n * acknowledgment and each end mark one time. It keeps one tombstone for each report, with the\n * latest `until`. Then it removes each report with a tombstone, and each delivery, acknowledgment\n * and end mark of such a report.\n */\nexport function normalize(parts: MergeParts): MergeState {\n const tombstones = new Map<ReportId, Tombstone>();\n for (const tombstone of parts.retired ?? []) {\n const held = tombstones.get(tombstone.report);\n if (held === undefined || tombstone.until > held.until) tombstones.set(tombstone.report, { report: tombstone.report, until: tombstone.until });\n }\n const kept = (report: ReportId): boolean => !tombstones.has(report);\n // The text of a report is made only when two contents of one id meet. Most ids have one content, thus no text.\n const reports = new Map<ReportId, { readonly report: Report; readonly text?: string }>();\n for (const report of parts.reports ?? []) {\n if (!kept(report.id)) continue;\n const held = reports.get(report.id);\n if (held === undefined) reports.set(report.id, { report });\n else if (held.report !== report) {\n const heldText = held.text ?? reportText(held.report);\n const text = reportText(report);\n reports.set(report.id, text < heldText ? { report, text } : { report: held.report, text: heldText });\n }\n }\n return normal({\n reports: [...reports.entries()].sort(([a], [b]) => compareCodeUnits(a, b)).map(([, held]) => held.report),\n deliveries: uniqueByText((parts.deliveries ?? []).filter((delivery) => kept(delivery.incident))),\n acks: uniqueByText((parts.acks ?? []).filter((ack) => kept(ack.incident))),\n ends: uniqueByText((parts.ends ?? []).filter((mark) => kept(mark.report))),\n retired: [...tombstones.entries()].sort(([a], [b]) => compareCodeUnits(a, b)).map(([, tombstone]) => tombstone),\n });\n}\n\n// The merge states in the one form: each list is in its order and has no duplicate. Only `normalize` and `add` put a\n// state in this set, so `add` can insert into the lists of such a state. A state from another place gets a full\n// `normalize`. A merge state does not change its lists.\nconst normalStates = new WeakSet<MergeState>();\nfunction normal(state: MergeState): MergeState {\n normalStates.add(state);\n return state;\n}\nnormal(EMPTY_STATE);\n\n/** This function gives the join of two merge states: the union of their parts. */\nexport function join(a: MergeState, b: MergeState): MergeState {\n // The join is commutative, so the parts of the other state go into the state in the one form.\n if (normalStates.has(a)) return add(a, b);\n if (normalStates.has(b)) return add(b, a);\n return normalize({\n reports: [...a.reports, ...b.reports],\n deliveries: [...a.deliveries, ...b.deliveries],\n acks: [...a.acks, ...b.acks],\n ends: [...a.ends, ...b.ends],\n retired: [...a.retired, ...b.retired],\n });\n}\n\n/**\n * This function adds parts to a merge state. A part that the state has already changes nothing.\n *\n * The result is equal to the `normalize` of all the parts. For a state in the one form, the function inserts each\n * new part into the sorted lists. Each new part costs a search in the list, and each list that changes costs one copy.\n * When no part changes the state, the function gives the same state. A state that is not in the one form gets a full\n * `normalize`. A new tombstone also gets a full `normalize`, because it removes parts.\n */\nexport function add(state: MergeState, parts: MergeParts): MergeState {\n if (!normalStates.has(state) || retiresMore(state.retired, parts.retired ?? [])) {\n return normalize({\n reports: [...state.reports, ...(parts.reports ?? [])],\n deliveries: [...state.deliveries, ...(parts.deliveries ?? [])],\n acks: [...state.acks, ...(parts.acks ?? [])],\n ends: [...state.ends, ...(parts.ends ?? [])],\n retired: [...state.retired, ...(parts.retired ?? [])],\n });\n }\n const kept = (report: ReportId): boolean => indexIn(state.retired, report, tombstoneKey) < 0;\n // For two contents of one id, the content with the smaller canonical JSON. A tie keeps the content that the state has.\n const smaller = (held: Report, report: Report): Report => (held === report || reportText(report) >= reportText(held) ? held : report);\n const first = <T>(held: T): T => held;\n const reports = insertSorted(state.reports, (parts.reports ?? []).filter((report) => kept(report.id)), reportKey, smaller);\n const deliveries = insertSorted(state.deliveries, (parts.deliveries ?? []).filter((delivery) => kept(delivery.incident)), canonical, first);\n const acks = insertSorted(state.acks, (parts.acks ?? []).filter((ack) => kept(ack.incident)), canonical, first);\n const ends = insertSorted(state.ends, (parts.ends ?? []).filter((mark) => kept(mark.report)), canonical, first);\n if (reports === state.reports && deliveries === state.deliveries && acks === state.acks && ends === state.ends) return state;\n return normal({ reports, deliveries, acks, ends, retired: state.retired });\n}\n\nconst reportKey = (report: Report): string => report.id;\nconst tombstoneKey = (tombstone: Tombstone): string => tombstone.report;\n\n/** True when a tombstone of the parts is new, or has a later `until` than the tombstone of the state. */\nfunction retiresMore(held: readonly Tombstone[], tombstones: readonly Tombstone[]): boolean {\n return tombstones.some((tombstone) => {\n const index = indexIn(held, tombstone.report, tombstoneKey);\n return index < 0 || tombstone.until > held[index]!.until;\n });\n}\n\n/**\n * This function gives the index of a key in a list in the order of its keys. For a key that the list does not have, it\n * gives `-(p + 1)`, where `p` is the index where the key goes.\n */\nfunction indexIn<T>(list: readonly T[], key: string, keyOf: (item: T) => string): number {\n let low = 0;\n let high = list.length - 1;\n while (low <= high) {\n const middle = (low + high) >>> 1;\n const order = compareCodeUnits(keyOf(list[middle]!), key);\n if (order === 0) return middle;\n if (order < 0) low = middle + 1;\n else high = middle - 1;\n }\n return -(low + 1);\n}\n\n/**\n * This function inserts items into a list in the order of its keys, with one item for each key. For a key that is\n * there already, `pick` gives the item that stays. When no item changes the list, it gives the same list.\n */\nfunction insertSorted<T>(list: readonly T[], items: readonly T[], keyOf: (item: T) => string, pick: (held: T, item: T) => T): readonly T[] {\n if (items.length === 0) return list;\n let replaced: Map<number, T> | undefined;\n let added: Map<string, T> | undefined;\n for (const item of items) {\n const key = keyOf(item);\n const index = indexIn(list, key, keyOf);\n if (index >= 0) {\n const held = replaced?.get(index) ?? list[index]!;\n const chosen = pick(held, item);\n if (chosen !== held) (replaced ??= new Map()).set(index, chosen);\n } else {\n const held = added?.get(key);\n (added ??= new Map()).set(key, held === undefined ? item : pick(held, item));\n }\n }\n if (replaced === undefined && added === undefined) return list;\n const swaps = replaced;\n const base = swaps === undefined ? list : list.map((item, index) => swaps.get(index) ?? item);\n if (added === undefined) return base;\n const out: T[] = [];\n let from = 0;\n for (const [key, item] of [...added.entries()].sort(([a], [b]) => compareCodeUnits(a, b))) {\n const to = -(indexIn(base, key, keyOf) + 1);\n for (let index = from; index < to; index += 1) out.push(base[index]!);\n out.push(item);\n from = to;\n }\n for (let index = from; index < base.length; index += 1) out.push(base[index]!);\n return out;\n}\n\n/**\n * The link rule of merge rule 3. The function `linkRule` makes the rule of a policy (`link.ts`,\n * `docs/CONTRACTS.md`). The merge tests only the pairs of reports that share a block. So the\n * cost grows with the size of the blocks, not with the square of the count of reports.\n */\nexport interface LinkRule {\n /** The blocks of a report, for example its family of kind and its day. A report with no block links to no report. */\n blocks(report: Report): readonly string[];\n /** True when two reports tell of one real event. It is symmetric, and it reads only the two reports. */\n matches(a: Report, b: Report): boolean;\n}\n\n/** The options of `incidents`. */\nexport interface IncidentOptions {\n /** The link rule of merge rule 3. When it is absent, the merge uses rules 1 and 2 only. */\n readonly link?: LinkRule;\n}\n\n/**\n * This function gives the incidents of a merge state at a time, in the order of their anchors.\n * The groups of reports do not use the time. Only the field `live` reads it.\n *\n * Two reports of one status are in one incident when one of these rules matches:\n *\n * 1. One report references the key of the other in the same source.\n * 2. The two reports share a correlation key.\n * 3. The link rule matches.\n *\n * A head of an incident is a report that no reference ends as a whole, and that no later report of\n * its origin replaces (the rule of the copies, `docs/CONTRACTS.md`). The areas of the incident are\n * the areas of its heads with no code that has a later statement.\n */\nexport function incidents(state: MergeState, at: Instant, options: IncidentOptions = {}): Incident[] {\n const ended = endedReports(state, at);\n return groupsOf(state.reports, options.link).map((group) => cachedIncident(group, at, ended));\n}\n\n// The key of the groups of a list of reports with no link rule.\nconst NO_LINK: object = {};\n// The groups of each list of reports and each link rule, in the order of their anchors. The groups do not read the\n// time, so each pass over the same list reads them again. Each entry lives while its list and its link rule live.\nconst groupCache = new WeakMap<readonly Report[], WeakMap<object, readonly (readonly Report[])[]>>();\n\n/** This function gives the groups of reports of the incidents, in the order of their anchors. */\nfunction groupsOf(reports: readonly Report[], link: LinkRule | undefined): readonly (readonly Report[])[] {\n let byLink = groupCache.get(reports);\n if (byLink === undefined) groupCache.set(reports, (byLink = new WeakMap()));\n const held = byLink.get(link ?? NO_LINK);\n if (held !== undefined) return held;\n const edges: number[][] = reports.map(() => []);\n const connect = (a: number, b: number): void => {\n edges[a]!.push(b);\n edges[b]!.push(a);\n };\n // Each report connects to the first report with the same key, so the reports of one key are connected.\n const firstOf = new Map<string, number>();\n const share = (key: string, index: number): void => {\n const first = firstOf.get(key);\n if (first === undefined) firstOf.set(key, index);\n else connect(first, index);\n };\n // Each key holds the audience of the report. Thus reports with two audiences never connect (AL-92, `audience.ts`).\n reports.forEach((report, index) => {\n const audience = audienceKey(report);\n share(JSON.stringify([\"key\", audience, report.status, report.source, report.key]), index);\n for (const reference of report.references) share(JSON.stringify([\"key\", audience, report.status, report.source, reference]), index);\n for (const key of report.correlation) share(JSON.stringify([\"correlation\", audience, report.status, key.system, key.id]), index);\n });\n if (link !== undefined) {\n const blocks = new Map<string, number[]>();\n reports.forEach((report, index) => {\n for (const block of new Set(link.blocks(report))) {\n const key = JSON.stringify([audienceKey(report), report.status, block]);\n const members = blocks.get(key);\n if (members === undefined) blocks.set(key, [index]);\n else members.push(index);\n }\n });\n for (const members of blocks.values()) {\n for (let i = 0; i < members.length; i += 1) {\n for (let j = i + 1; j < members.length; j += 1) {\n if (link.matches(reports[members[i]!]!, reports[members[j]!]!)) connect(members[i]!, members[j]!);\n }\n }\n }\n }\n // The edges go in the two directions, so the strong components are the connected components.\n // The nodes of a component keep the order of the reports: the order of their ids.\n const components = stronglyConnectedComponents(reports.keys(), (index) => edges[index]!);\n // The anchor of an incident is the id of the first report of its group.\n const groups = components.map((component) => component.map((index) => reports[index]!)).sort((a, b) => compareCodeUnits(a[0]!.id, b[0]!.id));\n byLink.set(link ?? NO_LINK, groups);\n return groups;\n}\n\n// The incident of each group, by its first report, with the reports and the live mask that it read.\nconst incidentCache = new WeakMap<Report, { readonly group: readonly Report[]; readonly mask: string; readonly incident: Incident }>();\n\n/** True when a report is live at a time: it is not a cancel, it did not expire and it did not end. */\nconst liveAt = (report: Report, at: Instant, ended: ReadonlySet<ReportId>): boolean =>\n report.op !== \"cancel\" && !(report.expires !== undefined && report.expires <= at) && !ended.has(report.id);\n\n/**\n * This function gives the incident of a group at a time. The incident reads the time only through the live reports.\n * Thus the same reports with the same live mask give the same incident, and the function gives it again.\n */\nfunction cachedIncident(group: readonly Report[], at: Instant, ended: ReadonlySet<ReportId>): Incident {\n let mask = \"\";\n for (const report of group) mask += liveAt(report, at, ended) ? \"1\" : \"0\";\n const held = incidentCache.get(group[0]!);\n if (held !== undefined && held.mask === mask && held.group.length === group.length && held.group.every((report, index) => report === group[index])) return held.incident;\n const incident = incidentOf(group, at, ended);\n incidentCache.set(group[0]!, { group, mask, incident });\n return incident;\n}\n\n/**\n * This function gives the reports that ended at a time: each report whose latest end mark at or before\n * the time has `ended` true. A mark after the time changes nothing, so a replay of a past time gives\n * the past value.\n */\nexport function endedReports(state: MergeState, at: Instant): ReadonlySet<ReportId> {\n const latest = new Map<ReportId, EndMark>();\n for (const mark of state.ends) {\n if (mark.at > at) continue;\n const held = latest.get(mark.report);\n // At one time, the mark with `ended` false wins. Thus the order of the marks changes nothing.\n if (held === undefined || mark.at > held.at || (mark.at === held.at && !mark.ended)) latest.set(mark.report, mark);\n }\n return new Set([...latest.values()].filter((mark) => mark.ended).map((mark) => mark.report));\n}\n\n/**\n * This function gives the highest level that a person got for an incident. It reads each\n * delivery to the person that points to a report of the incident. The value only grows, so a\n * merge of two incidents does not send a level again.\n */\nexport function sentLevel(state: MergeState, incident: Incident, person: PersonId): Level | undefined {\n const reports = new Set<string>(incident.reports);\n return highest(state.deliveries.filter((d) => d.person === person && reports.has(d.incident)));\n}\n\n/**\n * This function gives the highest level that a person acknowledged for an incident. An\n * acknowledgment of a level also covers each lower level.\n */\nexport function acknowledgedLevel(state: MergeState, incident: Incident, person: PersonId): Level | undefined {\n const reports = new Set<string>(incident.reports);\n return highest(state.acks.filter((a) => a.person === person && reports.has(a.incident)));\n}\n\n// The orders of the CAP values, from the lowest. `unknown` is the lowest, so it does not hide a known value.\nconst SEVERITY: readonly Severity[] = [\"unknown\", \"minor\", \"moderate\", \"severe\", \"extreme\"];\nconst URGENCY: readonly Urgency[] = [\"unknown\", \"past\", \"future\", \"expected\", \"immediate\"];\nconst CERTAINTY: readonly Certainty[] = [\"unknown\", \"unlikely\", \"possible\", \"likely\", \"observed\"];\n\n// The first item with the highest value. The reports come in the order of their ids, so a tie goes to the smallest id.\nfunction top<T>(items: readonly T[], rank: (item: T) => number): T {\n return items.reduce((best, item) => (rank(item) > rank(best) ? item : best));\n}\n\nfunction incidentOf(group: readonly Report[], at: Instant, ended: ReadonlySet<ReportId>): Incident {\n const events = eventsOf(group);\n const { superseded, later, replaced } = statementsOf(group, events);\n let heads = group.filter((report) => !superseded.has(report.id) && !replaced.has(report.id));\n // A cycle of references leaves no head. Then each report counts as a head.\n if (heads.length === 0) heads = [...group];\n const liveHeads = heads.filter((report) => liveAt(report, at, ended));\n const basis = liveHeads.length > 0 ? liveHeads : heads;\n const stated = basis.map((report) => ({ report, ...knownValues(report, events) }));\n const lines = stated.map(\n ({ report, severity, urgency, certainty }): IncidentLine => ({\n report: report.id,\n kind: report.kind,\n severity,\n urgency,\n certainty,\n ...(report.onset === undefined ? {} : { onset: report.onset }),\n areas: liveAreas(report, later.get(report.id)),\n }),\n );\n const first = group[0]!;\n const worst = top(stated, (values) => SEVERITY.indexOf(values.severity));\n const onsets = basis.flatMap((report) => (report.onset === undefined ? [] : [report.onset]));\n const expiries = basis.flatMap((report) => (report.expires === undefined ? [] : [report.expires]));\n const incident: Incident = {\n anchor: first.id,\n reports: group.map((report) => report.id),\n status: first.status,\n kind: worst.report.kind,\n severity: worst.severity,\n urgency: top(stated, (values) => URGENCY.indexOf(values.urgency)).urgency,\n certainty: top(stated, (values) => CERTAINTY.indexOf(values.certainty)).certainty,\n areas: uniqueByText(lines.flatMap((line) => line.areas)),\n about: uniqueByText(basis.flatMap((report) => report.about)),\n // Each report of a group has the same audience, so the first report gives it.\n ...(first.addresses === undefined ? {} : { addresses: audienceOf(first.addresses) }),\n live: liveHeads.length > 0,\n corroboration: new Set(group.map((report) => report.origin)).size,\n // The lines are present only when their values differ. Else each place gets the values of the incident.\n ...(lines.length > 1 && new Set(lines.map(lineValues)).size > 1 ? { lines } : {}),\n };\n return {\n ...incident,\n ...(onsets.length > 0 ? { onset: onsets.reduce((a, b) => Math.min(a, b)) } : {}),\n // A head with no end makes the incident open.\n ...(expiries.length === basis.length && expiries.length > 0 ? { expires: expiries.reduce((a, b) => Math.max(a, b)) } : {}),\n };\n}\n\n// The values of a line with no areas, as one key for a set.\nconst lineValues = (line: IncidentLine): string => canonical([line.kind, line.severity, line.urgency, line.certainty, line.onset ?? null]);\n\n// The text of a region code, as one key for a set.\nconst codeText = (area: Extract<Area, { type: \"code\" }>): string => JSON.stringify([area.system, area.code]);\n\nfunction codesOf(report: Report): ReadonlySet<string> {\n return new Set(report.areas.flatMap((area) => (area.type === \"code\" ? [codeText(area)] : [])));\n}\n\n/** The later statements of the codes of the reports of a group. */\ninterface Statements {\n /** The reports that a reference ends as a whole. */\n readonly superseded: ReadonlySet<ReportId>;\n /** For each report, the codes of it that a later statement names. */\n readonly later: ReadonlyMap<ReportId, ReadonlySet<string>>;\n /** The reports with one or more codes, each of which has a later statement (the rule of the copies). */\n readonly replaced: ReadonlySet<ReportId>;\n}\n\n/**\n * This function gives the later statements of the codes of each report of a group. Two rules give a statement.\n *\n * - The rule of the copies. Two reports of one origin with a shared correlation key tell of one event. A report\n * of the event with a later sent time states each code that it names. A tie of the sent time states nothing.\n * - The rule of a part. A cancel that names a proper subset of the codes of a report that it references states\n * only those codes. The NWS ends a part of a warning so: one cancel for the part, one update for the rest.\n *\n * Each other reference ends the whole report, as CAP tells. A report is replaced when each of its codes has a\n * later statement. Thus a cancel of the NWS also ends the copy of that alert from IPAWS. The rows of IEM, one\n * for each county, end the NWS message of two counties.\n *\n * For each code, the latest reports that name it stay, so no later statement of a code is lost. A code with no\n * later statement keeps its report live, and a report with no code is not replaced. When the update of the rest\n * is lost, the rest stays live until it expires. Each error is on the safe side. The rule reads only the group,\n * so it keeps the laws of the merge.\n */\nfunction statementsOf(group: readonly Report[], byEvent: Events): Statements {\n const codes = new Map(group.map((report) => [report.id, codesOf(report)]));\n const later = new Map<ReportId, Set<string>>();\n const state = (report: Report, named: Iterable<string>): void => {\n let set = later.get(report.id);\n if (set === undefined) later.set(report.id, (set = new Set()));\n for (const code of named) set.add(code);\n };\n for (const reports of byEvent.values()) {\n // From the latest sent time to the earliest. `seen` holds the codes of the reports after the current time.\n const ordered = [...reports].sort((a, b) => b.sent - a.sent);\n const seen = new Set<string>();\n for (let start = 0, end = 0; start < ordered.length; start = end) {\n while (end < ordered.length && ordered[end]!.sent === ordered[start]!.sent) end += 1;\n const tied = ordered.slice(start, end);\n if (seen.size > 0) for (const report of tied) state(report, seen);\n for (const report of tied) for (const code of codes.get(report.id)!) seen.add(code);\n }\n }\n const byKey = new Map<string, Report[]>();\n for (const report of group) {\n const key = JSON.stringify([report.source, report.key]);\n const reports = byKey.get(key);\n if (reports === undefined) byKey.set(key, [report]);\n else reports.push(report);\n }\n const superseded = new Set<ReportId>();\n for (const report of group) {\n const named = codes.get(report.id)!;\n for (const reference of report.references) {\n for (const target of byKey.get(JSON.stringify([report.source, reference])) ?? []) {\n const own = codes.get(target.id)!;\n const part = report.op === \"cancel\" && named.size > 0 && named.size < own.size && [...named].every((code) => own.has(code));\n if (part) state(target, named);\n else superseded.add(target.id);\n }\n }\n }\n const replaced = new Set<ReportId>();\n for (const report of group) {\n const own = codes.get(report.id)!;\n const stated = later.get(report.id);\n if (own.size > 0 && stated !== undefined && [...own].every((code) => stated.has(code))) replaced.add(report.id);\n }\n return { superseded, later, replaced };\n}\n\n/**\n * This function gives the areas of a report with no code that has a later statement. A block with such a code also\n * loses its shapes, because a code cannot cut a shape. The block then decides by its other codes. A block with no\n * shape covers each place in its codes, so the error is on the safe side.\n */\nfunction liveAreas(report: Report, later: ReadonlySet<string> | undefined): Area[] {\n const areas = blockAreas(report);\n if (later === undefined) return areas;\n const stated = (area: Area): boolean => area.type === \"code\" && later.has(codeText(area));\n const cut = new Set(areas.flatMap((area) => (area.type !== \"place\" && area.block !== undefined && stated(area) ? [area.block] : [])));\n const inCut = (area: Area): boolean => area.type !== \"place\" && area.type !== \"code\" && area.block !== undefined && cut.has(area.block);\n return areas.filter((area) => !stated(area) && !inCut(area));\n}\n\n// The reports of each event of a group: one origin and one correlation key.\ntype Events = ReadonlyMap<string, readonly Report[]>;\n\nconst eventKey = (report: Report, key: Report[\"correlation\"][number]): string => JSON.stringify([report.origin, key.system, key.id]);\n\nfunction eventsOf(group: readonly Report[]): Events {\n const byEvent = new Map<string, Report[]>();\n for (const report of group) {\n for (const key of report.correlation) {\n const event = eventKey(report, key);\n const reports = byEvent.get(event);\n if (reports === undefined) byEvent.set(event, [report]);\n else reports.push(report);\n }\n }\n return byEvent;\n}\n\ntype Stated = Pick<Report, \"severity\" | \"urgency\" | \"certainty\">;\n\n/**\n * The severity, the urgency and the certainty of a report, with each `unknown` value filled from its\n * events. A copy with no value, as a row of IEM, then keeps the values of the message of the authority.\n */\nfunction knownValues(report: Report, events: Events): Stated {\n return {\n severity: knownValue(report, \"severity\", SEVERITY, events),\n urgency: knownValue(report, \"urgency\", URGENCY, events),\n certainty: knownValue(report, \"certainty\", CERTAINTY, events),\n };\n}\n\n/**\n * The value of one field. An `unknown` value takes the value of the latest report of an event of the\n * report with a known value. That report is not later than the report and is not a cancel, because\n * a cancel of the NWS gives the values of an end. A tie of time takes the highest value.\n */\nfunction knownValue<F extends keyof Stated>(report: Report, field: F, order: readonly Report[F][], events: Events): Report[F] {\n let value = report[field];\n if (value !== \"unknown\") return value;\n let sent = -Infinity;\n for (const key of report.correlation) {\n for (const other of events.get(eventKey(report, key)) ?? []) {\n const found = other[field];\n if (other.op === \"cancel\" || found === \"unknown\" || other.sent > report.sent) continue;\n if (other.sent > sent || (other.sent === sent && order.indexOf(found) > order.indexOf(value))) {\n value = found;\n sent = other.sent;\n }\n }\n }\n return value;\n}\n\nfunction highest(parts: readonly { readonly level: Level }[]): Level | undefined {\n const index = parts.reduce((best, part) => Math.max(best, LEVELS.indexOf(part.level)), -1);\n return index < 0 ? undefined : LEVELS[index];\n}\n\n/**\n * The canonical JSON of a report, made at each call. The merge compares two contents of one id with it. The text of\n * a report is as large as the report, thus no cache keeps it. A cache kept a second copy of each live report (AL-102).\n */\nfunction reportText(report: Report): string {\n return canonicalJson(report, { form: \"json\" });\n}\n\n// The canonical JSON of each small object (a delivery, an acknowledgment, an end mark, a line), kept for the life of the object.\nconst texts = new WeakMap<object, string>();\nfunction canonical(value: object): string {\n let text = texts.get(value);\n if (text === undefined) {\n text = canonicalJson(value, { form: \"json\" });\n texts.set(value, text);\n }\n return text;\n}\n\nfunction uniqueByText<T extends object>(items: readonly T[]): T[] {\n const byText = new Map<string, T>();\n for (const item of items) {\n const text = canonical(item);\n if (!byText.has(text)) byText.set(text, item);\n }\n return [...byText.entries()].sort(([a], [b]) => compareCodeUnits(a, b)).map(([, item]) => item);\n}\n\n/**\n * The areas of a report, with the report id before each block key. Thus the blocks of two reports stay\n * apart, also when the NWS and IPAWS copies of one warning give the same keys.\n */\nfunction blockAreas(report: Report): Area[] {\n return report.areas.map((area) => (area.type === \"place\" || area.block === undefined ? area : { ...area, block: `${report.id}/${area.block}` }));\n}\n","/**\n * The retention of the merge state (AL-47). An incident that ended long ago leaves the merge state as a whole. The\n * event log keeps each of its reports. Thus the cost of a pass follows the recent incidents, not the age of the instance.\n *\n * - `retirements` gives the reports of each whole incident that is not live and has no change in the horizon.\n * With a quiet rule, an incident that sent nothing to a person retires after the shorter quiet horizon (AL-109).\n * - `retire` gives them tombstones. A tombstone keeps a late copy of a report out of the state.\n * An example is a copy from the log of another copy of the system.\n * - `pruneTombstones` drops each tombstone after its time `until`, thus the tombstones also have a bound.\n *\n * A retirement removes whole incidents. The groups of reports are the connected components of the links, thus the\n * removal of a whole group changes no other group. The test of this module holds it.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { Duration, Incident, Instant, MergeState, ReportId } from \"./contracts.ts\";\nimport { add } from \"./merge.ts\";\n\nconst HOUR = 3_600_000;\nconst DAY = 24 * HOUR;\n\n/** The default horizon: an incident leaves the merge state 7 days after its last change. */\nexport const RETENTION_HORIZON: Duration = 7 * DAY;\n\n/**\n * The default horizon of a quiet incident (AL-109): 6 hours. Most incidents send nothing to a person, for example an\n * alert of a far area. They are most of the merge state, thus this horizon sets the memory of the state.\n */\nexport const QUIET_HORIZON: Duration = 6 * HOUR;\n\n/**\n * The early retirement of a quiet incident (AL-109). A quiet incident has no delivery and no acknowledgment of a\n * report. Thus no person knows it, and no escalation, end message or repeat applies to it.\n */\nexport interface QuietRule {\n /** The time after the last change of a quiet incident before it retires. A value above the horizon gives the horizon. */\n readonly horizon: Duration;\n /**\n * This function tells if a reader keeps a quiet incident for the full horizon. An example is a check that counts the\n * incidents of a source over a longer window. The default keeps no incident.\n */\n readonly keeps?: ((incident: Incident) => boolean) | undefined;\n}\n\n/**\n * The default life of a tombstone: 30 days. A feed lists a report for approximately 30 days at most, for example the\n * feed of the earthquakes of the last 30 days. A new copy of the system that fetches the report gives it while the\n * tombstone is there, thus the report stays out.\n */\nexport const TOMBSTONE_LIFE: Duration = 30 * DAY;\n\n/**\n * This function gives the reports to retire at a time, in the order of their ids. `found` is the incidents of `state`\n * at `at`. An incident retires as a whole when it is not live and its last change is at or before `at - horizon`.\n * With the rule `quiet`, a quiet incident that the rule does not keep retires at `at - quiet.horizon`.\n *\n * The last change of an incident is the latest time of its parts. These are the sent, received and expiry times of its\n * reports, and the times of their end marks, deliveries and acknowledgments. Thus an expiry in the future keeps a\n * cancelled report. Each error is on the safe side: an incident stays longer, not shorter.\n */\nexport function retirements(state: MergeState, found: readonly Incident[], at: Instant, horizon: Duration = RETENTION_HORIZON, quiet?: QuietRule): ReportId[] {\n const changed = new Map<ReportId, Instant>();\n const touch = (report: ReportId, time: Instant): void => {\n const held = changed.get(report);\n if (held === undefined || time > held) changed.set(report, time);\n };\n for (const report of state.reports) touch(report.id, Math.max(report.sent, report.received, report.expires ?? -Infinity));\n for (const mark of state.ends) touch(mark.report, mark.at);\n for (const delivery of state.deliveries) touch(delivery.incident, delivery.at);\n for (const ack of state.acks) touch(ack.incident, ack.at);\n const long = Math.max(0, horizon);\n const limit = at - long;\n // The reports that a person knows: each delivery and each acknowledgment names a report of its incident.\n const told = new Set<ReportId>();\n for (const delivery of state.deliveries) told.add(delivery.incident);\n for (const ack of state.acks) told.add(ack.incident);\n const quietLimit = quiet === undefined ? limit : at - Math.min(long, Math.max(0, quiet.horizon));\n const limitOf = (incident: Incident): Instant =>\n quiet === undefined || incident.reports.some((report) => told.has(report)) || (quiet.keeps?.(incident) ?? false) ? limit : quietLimit;\n return found\n .filter((incident) => {\n if (incident.live) return false;\n const until = limitOf(incident);\n return incident.reports.every((report) => (changed.get(report) ?? Infinity) <= until);\n })\n .flatMap((incident) => incident.reports)\n .sort(compareCodeUnits);\n}\n\n/** This function gives the state with a tombstone for each report, until the time `until`. It removes the parts of the reports. */\nexport function retire(state: MergeState, reports: readonly ReportId[], until: Instant): MergeState {\n return add(state, { retired: reports.map((report) => ({ report, until })) });\n}\n\n/** This function drops each tombstone with its time `until` at or before `at`. It brings back no part. */\nexport function pruneTombstones(state: MergeState, at: Instant): MergeState {\n const retired = state.retired.filter((tombstone) => tombstone.until > at);\n return retired.length === state.retired.length ? state : { ...state, retired };\n}\n\n","// The one rule of the prefixes of the kinds. It is a leaf module, so the assessment and the relevance both import it with no cycle.\n\n/**\n * This function tells if a kind has one of the prefixes. A prefix ends at a dot: `met.flood` has\n * `met.flood.flash`, but `met.fl` does not have `met.flood`. The adapters and the core use this one rule.\n */\nexport function hasKind(prefixes: readonly string[], kind: string): boolean {\n return prefixes.some((prefix) => kind === prefix || kind.startsWith(`${prefix}.`));\n}\n","// The why line: why a message reaches a person, in the limit of each channel (AL-35, `docs/RELEVANCE.md`).\n\nimport { SUBJECT_SYSTEMS, type Assessment, type InterestGraph, type NodeKey, type PlaceId, type Subject, type SubjectKind, type WhyLimit, type WhyRecord } from \"./contracts.ts\";\n\n/**\n * The limit of the why line on each kind of channel. A channel descriptor gives the limit of its kind in its\n * field `why`. `docs/RELEVANCE.md` tells the reasons of the values.\n */\nexport const WHY_LIMITS: Readonly<Record<\"push\" | \"text\" | \"call\", WhyLimit>> = {\n /** A push message: 80 characters. */\n push: { chars: 80 },\n /** A text message: 40 characters, each of the GSM-7 base set. */\n text: { chars: 40 },\n /** A voice call: 12 words. */\n call: { words: 12 },\n};\n\n/**\n * The label of a node of the interest graph for the person, or `undefined`. The runtime gives the labels from the\n * private configuration. A label is not in a `WhyRecord` at any time.\n */\nexport type WhyLabels = (node: NodeKey) => string | undefined;\n\n/** A function of labels that gives no label. Each why line then uses plain nouns. */\nexport const NO_LABELS: WhyLabels = () => undefined;\n\n/**\n * This function adds the labels of an interest graph to the labels of the instance. A label of the instance comes\n * first, so the label of a place in the configuration stays. With no graph or no graph labels, the labels stay the same.\n */\nexport function graphLabels(labels: WhyLabels, graph: Pick<InterestGraph, \"labels\"> | undefined): WhyLabels {\n const own = graph?.labels;\n if (own === undefined) return labels;\n // `Object.hasOwn`, thus a key such as `constructor` is a plain key.\n return (node) => labels(node) ?? (Object.hasOwn(own, node) ? own[node] : undefined);\n}\n\n/** A why with a coverage below this value tells that it is a part of the reason. */\nexport const WHY_FULL_COVERAGE = 0.99;\n\n// A label goes into a text only when it is plain words: letters, spaces and the characters ' & . , -, with a\n// lowercase letter and no two capitals in a row. Thus a why line has no digit (no address number, no point and no\n// region code) and no code in capitals, and each of its characters is in the GSM-7 base set.\nconst PLAIN_LABEL = /^[A-Za-z][A-Za-z '&.,-]*$/;\n\n/**\n * This function gives the label of a node when it is safe for a channel text, or `undefined`. A safe label has\n * only letters, spaces and the characters ' & . , -, a lowercase letter, and no two capitals in a row.\n */\nexport function plainLabel(labels: WhyLabels, node: NodeKey): string | undefined {\n const label = labels(node)?.trim().replace(/\\s+/g, \" \");\n if (label === undefined || !PLAIN_LABEL.test(label) || !/[a-z]/.test(label) || /[A-Z]{2}/.test(label)) return undefined;\n return label;\n}\n\n/** The system and the id of a subject, with no label. */\nexport type SubjectKey = Pick<Subject, \"system\" | \"id\">;\n\n/**\n * This function gives the node of a subject in an interest graph: the system, a colon and the id, for example\n * `domain:github.com`. Each node key of a subject comes from this function.\n */\nexport function subjectNode(subject: SubjectKey): NodeKey {\n return `${subject.system}:${subject.id}`;\n}\n\n/** This function gives the kind of a node key from its system, or `undefined` for a key with no known system. */\nexport function kindOfNode(node: NodeKey): SubjectKind | undefined {\n const colon = node.indexOf(\":\");\n if (colon <= 0) return undefined;\n const system = node.slice(0, colon);\n return Object.hasOwn(SUBJECT_SYSTEMS, system) ? SUBJECT_SYSTEMS[system as keyof typeof SUBJECT_SYSTEMS] : undefined;\n}\n\n/**\n * The systems of the node keys with path ids. In these systems, an id is a path of parts with `/` between them. A\n * node covers each node below it. For example, `provider-region:twilio/europe` covers `provider-region:twilio/europe/sms`.\n */\nexport const PATH_SYSTEMS: readonly string[] = [\"provider-region\"];\n\n/**\n * This function tells if the node `a` covers the node `b`. A node covers itself. In a system of `PATH_SYSTEMS`, a node\n * also covers each node whose id starts with its id and a `/`. A mute covers the nodes below its subjects.\n */\nexport function nodeCovers(a: NodeKey, b: NodeKey): boolean {\n if (a === b) return true;\n const colon = a.indexOf(\":\");\n return colon > 0 && colon < a.length - 1 && PATH_SYSTEMS.includes(a.slice(0, colon)) && b.startsWith(`${a}/`);\n}\n\n/**\n * This function tells if two nodes overlap: one of the two nodes covers the other (`nodeCovers`). An incident about a\n * node reaches each node that it overlaps. Thus an outage of a region reaches a product of the region, and the reverse.\n */\nexport function nodesOverlap(a: NodeKey, b: NodeKey): boolean {\n return nodeCovers(a, b) || nodeCovers(b, a);\n}\n\nconst PLACE_SYSTEM = \"place:\";\n\n/** This function gives the node key of a watched place: `place:<id>`. */\nexport function placeNode(place: PlaceId): NodeKey {\n return `${PLACE_SYSTEM}${place}`;\n}\n\n/** This function gives the id of the watched place of a node key `place:<id>`, or `undefined` for another node. */\nexport function placeOfNode(node: NodeKey): PlaceId | undefined {\n return node.startsWith(PLACE_SYSTEM) ? (node.slice(PLACE_SYSTEM.length) as PlaceId) : undefined;\n}\n\n/** This function tells if a text keeps a limit of a why line. It counts code points and words. */\nexport function fitsWhy(text: string, limit: WhyLimit): boolean {\n if (limit.chars !== undefined && [...text].length > limit.chars) return false;\n if (limit.words !== undefined && text.split(/\\s+/).filter((word) => word !== \"\").length > limit.words) return false;\n return true;\n}\n\n// The names of the nodes of one candidate line. An absent name gives a plain noun.\ninterface Names {\n readonly subject?: string;\n readonly via?: string;\n readonly anchor?: string;\n}\n\n// The plain noun of an anchor of each kind, for a path from another subject. The shortest plain line, with the\n// prefix of a part, has 40 characters: \"Why, in part: it can affect your service\". Thus a why fits each limit of WHY_LIMITS.\nconst ANCHOR_NOUNS: Readonly<Record<SubjectKind, string>> = { place: \"your place\", topic: \"your topic\", entity: \"your service\" };\n\nfunction sentence(record: WhyRecord, names: Names): string {\n const kind = kindOfNode(record.anchor) ?? record.kind;\n if (record.subject === record.anchor) {\n if (kind === \"place\") return `${names.anchor ?? \"your place\"} is in the area`;\n if (kind === \"topic\") return `you follow ${names.anchor ?? \"this topic\"}`;\n return `you use ${names.anchor ?? \"this service\"}`;\n }\n const via = names.via === undefined ? \"\" : ` via ${names.via}`;\n return `${names.subject ?? \"this event\"} can affect ${names.anchor ?? ANCHOR_NOUNS[kind]}${via}`;\n}\n\n/**\n * This function gives the why line of a record in a limit, or `undefined` when no line fits.\n *\n * - The line starts with `Why: `, or with `Why, in part: ` when the coverage is below `WHY_FULL_COVERAGE`.\n * - The function tries the lines from the fullest to the shortest. The fullest line has the labels of the subject,\n * the `via` node and the anchor. The next lines have fewer labels, and the last lines have only plain nouns.\n * - The function gives the first line that fits. With the limits of `WHY_LIMITS`, a line always fits.\n * - A label goes in only when `plainLabel` keeps it. Thus the line holds no address, point or region code.\n */\nexport function whyLine(record: WhyRecord, labels: WhyLabels, limit: WhyLimit): string | undefined {\n const prefix = record.coverage < WHY_FULL_COVERAGE ? \"Why, in part: \" : \"Why: \";\n const subject = record.subject === record.anchor ? undefined : plainLabel(labels, record.subject);\n const via = record.via === undefined ? undefined : plainLabel(labels, record.via);\n const anchor = plainLabel(labels, record.anchor);\n const named = anchor === undefined ? {} : { anchor };\n const candidates: readonly Names[] = [\n { ...(subject === undefined ? {} : { subject }), ...(via === undefined ? {} : { via }), ...named },\n { ...(subject === undefined ? {} : { subject }), ...named },\n named,\n { subject: \"it\", ...named },\n {},\n { subject: \"it\" },\n ];\n for (const names of candidates) {\n const line = `${prefix}${sentence(record, names)}`;\n if (fitsWhy(line, limit)) return line;\n }\n return undefined;\n}\n\n/**\n * This function gives the why of a match by places: the watched place with the first id in code-point order. Thus\n * the order of the configuration does not change it. It gives `undefined` when no place matches.\n */\nexport function placeWhy(places: readonly PlaceId[]): WhyRecord | undefined {\n if (places.length === 0) return undefined;\n const first = places.reduce((least, id) => (id < least ? id : least));\n const key = placeNode(first);\n return { rule: \"reach.place.places\", subject: key, kind: \"place\", anchor: key, origin: \"places\", coverage: 1 };\n}\n\n/**\n * This function gives the why of an assessment. The why of the reason `reach` comes first, when the interest graph\n * gives one. Else the why is the watched place with the first id (`placeWhy`). A place of the rule of the life-safety\n * warnings with an edge that is off has no path, thus its why is its place.\n */\nexport function assessmentWhy(assessment: Pick<Assessment, \"reasons\" | \"places\">): WhyRecord | undefined {\n for (const reason of assessment.reasons) if (reason.kind === \"reach\" && reason.why !== undefined) return reason.why;\n return placeWhy(assessment.places);\n}\n","// The relevance of an incident for one person: a calculation over the interest graph (AL-35, `docs/RELEVANCE.md`).\n\nimport {\n NUMBER_RING,\n pathSetReliability,\n twoTerminalReliability,\n type OrderedRing,\n type TwoTerminalReliability,\n} from \"@mark1russell7/collections/graph\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { hasKind } from \"./kind-prefix.ts\";\nimport { nodeCovers } from \"./why.ts\";\nimport type {\n AssessedLevel,\n Estimate,\n Instant,\n InterestEdge,\n InterestGraph,\n Mute,\n MuteEffect,\n NodeKey,\n Relevance,\n RelevancePath,\n RelevancePolicy,\n SubjectEntry,\n WhyRecord,\n} from \"./contracts.ts\";\n\n/** The incident, as the relevance reads it. */\nexport interface RelevanceInput {\n /** The taxonomy code of the kind of the incident. A mute matches it by prefix. */\n readonly kind: string;\n /** The subjects of the incident that are nodes of the graph. Two entries of one node count as one, with the larger hit. */\n readonly entries: readonly SubjectEntry[];\n /** The time of the calculation. A mute with an end at this time or before it has no effect. */\n readonly at: Instant;\n /** True when the incident is of the mandatory class. Then a mute has the effect `policy.mandatory`. */\n readonly mandatory: boolean;\n}\n\n/** The options of the relevance. */\nexport interface RelevanceOptions {\n /** The largest count of steps of each exact sum, as in `twoTerminalReliability`. The default is 1000000. */\n readonly maxSteps?: number;\n}\n\n/** The arithmetic of the exact sum: a ring, and the function that puts a chance into the ring. */\nexport interface ReachArithmetic<N> {\n readonly ring: OrderedRing<N>;\n readonly of: (chance: number) => N;\n}\n\n/** The arithmetic of production: floats. */\nexport const FLOAT_REACH: ReachArithmetic<number> = { ring: NUMBER_RING, of: (chance) => chance };\n\n/** The highest level of an incident that reaches a person only through entries that are not watched places, when the policy gives none. */\nexport const DEFAULT_ENTRY_MAX: AssessedLevel = \"urgent\";\n\n/**\n * The first policy of the relevance. A path has 4 edges or fewer, and a relevance shows the 3 strongest paths. A mute\n * makes a life-safety warning at a watched place silent, not absent. The top class of WEA and of EU-Alert works the same way.\n */\nexport const DEFAULT_RELEVANCE_POLICY: RelevancePolicy = { hopCap: 4, topPaths: 3, mandatory: \"silent\", entryMax: DEFAULT_ENTRY_MAX };\n\n/** One end of the intervals of the weights and of the hits. */\nexport type ReachEnd = \"low\" | \"value\" | \"high\";\n\n// The virtual source node of the event. The empty text is not a node key, so it is not a node of a graph.\nconst EVENT = \"\";\nconst PERSON: NodeKey = \"person\";\n\n// One edge of the reliability problem: a hit edge from the event to an entry, or an edge of the graph that is on.\ninterface Part {\n readonly from: NodeKey;\n readonly to: NodeKey;\n readonly weight: Estimate;\n readonly entry?: SubjectEntry;\n readonly edge?: InterestEdge;\n}\n\n// The mutes that have effect at the time of the input, and whose kinds match its kind or that have no kinds.\nfunction activeMutes(input: RelevanceInput, graph: InterestGraph): readonly Mute[] {\n return graph.mutes\n .filter((mute) => mute.until === undefined || mute.until > input.at)\n .filter((mute) => mute.kinds === undefined || hasKind(mute.kinds, input.kind));\n}\n\n// The test of the nodes that the active mutes cut from the graph: each node that a subject of a mute covers\n// (`nodeCovers`). An incident of the mandatory class under the policy `silent` has no cut, because a mute changes\n// only its sound.\nfunction cutOf(input: RelevanceInput, graph: InterestGraph, policy: RelevancePolicy): (node: NodeKey) => boolean {\n if (input.mandatory && policy.mandatory === \"silent\") return () => false;\n const subjects = activeMutes(input, graph).flatMap((mute) => mute.subjects ?? []);\n return (node) => subjects.some((subject) => nodeCovers(subject, node));\n}\n\n// The hit edges in the order of their nodes, then the edges of the graph that are on, in the order of their ids. Each\n// edge into or out of a node of the cut is off. Thus the order of the entries, of the edges and of a file has no effect\n// on the result.\nfunction partsOf(input: RelevanceInput, graph: InterestGraph, policy: RelevancePolicy): readonly Part[] {\n const cut = cutOf(input, graph, policy);\n const entries = new Map<NodeKey, SubjectEntry>();\n for (const entry of input.entries) {\n if (entry.node === PERSON) throw new RangeError(\"An entry of an incident is a subject, not the person.\");\n const known = entries.get(entry.node);\n entries.set(entry.node, known === undefined ? entry : larger(known, entry));\n }\n const ids = new Set<string>();\n const edges: InterestEdge[] = [];\n for (const edge of graph.edges) {\n if (ids.has(edge.id)) throw new RangeError(`The id ${edge.id} is on two edges of the graph.`);\n ids.add(edge.id);\n if (edge.from === PERSON) throw new RangeError(`The edge ${edge.id} starts at the person.`);\n if (edge.on && !cut(edge.from) && !cut(edge.to)) edges.push(edge);\n }\n edges.sort((a, b) => compareCodeUnits(a.id, b.id));\n const hits = [...entries.values()].filter((entry) => !cut(entry.node)).sort((a, b) => compareCodeUnits(a.node, b.node));\n return [\n ...hits.map((entry): Part => ({ from: EVENT, to: entry.node, weight: entry.hit, entry })),\n ...edges.map((edge): Part => ({ from: edge.from, to: edge.to, weight: edge.weight, edge })),\n ];\n}\n\n// Of two entries of one node, the entry with the larger hit at each end. The kind comes from the first in the order of\n// the kinds, so the result does not depend on the order of the entries.\nfunction larger(a: SubjectEntry, b: SubjectEntry): SubjectEntry {\n const hit = { value: Math.max(a.hit.value, b.hit.value), low: Math.max(a.hit.low, b.hit.low), high: Math.max(a.hit.high, b.hit.high) };\n return { node: a.node, kind: compareCodeUnits(a.kind, b.kind) <= 0 ? a.kind : b.kind, hit };\n}\n\nfunction solve<N>(parts: readonly Part[], end: ReachEnd, arithmetic: ReachArithmetic<N>, policy: RelevancePolicy, maxSteps: number | undefined): TwoTerminalReliability<N> {\n const edges = parts.map((part) => ({ from: part.from, to: part.to, chance: arithmetic.of(part.weight[end]) }));\n // The hit edge is not an edge of the graph, so the cap of the sum is one edge more than the cap of the policy.\n return twoTerminalReliability(edges, EVENT, PERSON, arithmetic.ring, { hopCap: policy.hopCap + 1, maxSteps });\n}\n\n/**\n * This function gives the reach of an incident at one end of the intervals, in the arithmetic of `arithmetic`. It\n * applies the cut of the mutes, and not the match of `muteOf`. The result is the result of `twoTerminalReliability`\n * over the hit edges and the edges that are on. No edge goes into or out of a muted subject. The gates use it with\n * exact rationals.\n */\nexport function reachOf<N>(\n input: RelevanceInput,\n graph: InterestGraph,\n policy: RelevancePolicy,\n arithmetic: ReachArithmetic<N>,\n end: ReachEnd = \"value\",\n options: RelevanceOptions = {},\n): TwoTerminalReliability<N> {\n return solve(partsOf(input, graph, policy), end, arithmetic, policy, options.maxSteps);\n}\n\n/**\n * This function gives the mute of the graph that matches the incident, and its effect, or `undefined`. A mute has\n * effect when it has no end or its end is after `input.at`. A mute with subjects matches when one of its subjects\n * covers an entry (`nodeCovers`). Of two matched mutes, the mute with the first id wins. A mute with subjects that\n * does not match cuts the nodes that its subjects cover from the graph (`reachOf`).\n */\nexport function muteOf(input: RelevanceInput, graph: InterestGraph, policy: RelevancePolicy): { readonly mute: string; readonly effect: MuteEffect } | undefined {\n const nodes = input.entries.map((entry) => entry.node);\n const matched = activeMutes(input, graph)\n .filter((mute) => mute.subjects === undefined || mute.subjects.some((subject) => nodes.some((node) => nodeCovers(subject, node))))\n .sort((a, b) => compareCodeUnits(a.id, b.id));\n const first = matched[0];\n if (first === undefined) return undefined;\n return { mute: first.id, effect: input.mandatory ? policy.mandatory : \"absent\" };\n}\n\n/**\n * This function gives the entry of the topic of a kind, or `undefined`. The node is `topic:<prefix>` for the longest\n * prefix of the kind that starts an edge of the graph. An edge that is off counts too, so it turns off its level only.\n */\nexport function topicEntry(kind: string, graph: InterestGraph): SubjectEntry | undefined {\n let found: string | undefined;\n for (const edge of graph.edges) {\n if (!edge.from.startsWith(\"topic:\")) continue;\n const prefix = edge.from.slice(\"topic:\".length);\n if (hasKind([prefix], kind) && (found === undefined || prefix.length > found.length)) found = prefix;\n }\n return found === undefined ? undefined : { node: `topic:${found}`, kind: \"topic\", hit: { value: 1, low: 1, high: 1 } };\n}\n\nconst NONE: Estimate = { value: 0, low: 0, high: 0 };\n\n// The low and the high reach of one result. A result of the budget gives its bounds: the best path is a floor. Noisy-OR\n// is a ceiling of the result `bounds`, and the result `partial` has no ceiling but 1.\nfunction lowOf(result: TwoTerminalReliability<number>): number {\n return result.kind === \"exact\" ? result.value : result.best;\n}\n\nfunction highOf(result: TwoTerminalReliability<number>): number {\n return result.kind === \"exact\" ? result.value : result.kind === \"bounds\" ? result.noisyOr : 1;\n}\n\n/**\n * This function tells if the entries of an input can reach the person. Then the reach at the high ends of the weights\n * and the hits is more than 0. It applies the cut of the mutes, as `reachOf`. When the budget ends the sum, the ceiling\n * decides, so an alert is not lost.\n */\nexport function canReach(input: RelevanceInput, graph: InterestGraph, policy: RelevancePolicy, options: RelevanceOptions = {}): boolean {\n return highOf(reachOf(input, graph, policy, FLOAT_REACH, \"high\", options)) > 0;\n}\n\n/**\n * This function gives the relevance of an incident for one person.\n *\n * - A mute with the effect `absent` gives a reach of 0 and no path.\n * - A mute with subjects cuts each subject from the graph: each edge into or out of a muted subject is off. Thus no\n * path goes through a muted subject. An incident of the mandatory class under the policy `silent` has no cut.\n * - The reach is the exact two-terminal reliability from the event to the person, over paths of `policy.hopCap` edges\n * of the graph or fewer. The interval comes from the low and the high ends of the weights and the hits.\n * - When the budget of steps ends a sum, the field `bound` tells it. The reach is then the ceiling, so an alert is not lost.\n * - The why comes from the strongest path. Its coverage is the reach of the shown paths alone, divided by the reach.\n */\nexport function relevance(input: RelevanceInput, graph: InterestGraph, policy: RelevancePolicy, options: RelevanceOptions = {}): Relevance {\n const muted = muteOf(input, graph, policy);\n if (muted?.effect === \"absent\") return { reach: NONE, best: 0, noisyOr: 0, paths: [], muted };\n const parts = partsOf(input, graph, policy);\n const point = solve(parts, \"value\", FLOAT_REACH, policy, options.maxSteps);\n // A float sum can pass 1 by a unit in the last place, so each end stays in the unit interval.\n const low = Math.min(1, lowOf(solve(parts, \"low\", FLOAT_REACH, policy, options.maxSteps)));\n const high = Math.min(1, highOf(solve(parts, \"high\", FLOAT_REACH, policy, options.maxSteps)));\n const value = Math.min(Math.max(highOf(point), low), high);\n const shown = point.paths.filter((path) => path.chance > 0).slice(0, policy.topPaths);\n const paths = shown.map((path): RelevancePath => {\n const [hit, ...rest] = path.edges;\n return { subject: parts[hit!]!.to, edges: rest.map((index) => parts[index]!.edge!.id), chance: path.chance };\n });\n const base: Relevance = {\n reach: { value, low: Math.min(low, value), high },\n best: point.best,\n noisyOr: point.kind === \"partial\" ? 1 : point.noisyOr,\n paths,\n ...(point.kind === \"exact\" ? {} : { bound: point.kind }),\n ...(muted === undefined ? {} : { muted }),\n };\n const top = shown[0];\n if (top === undefined) return base;\n const chances = parts.map((part) => part.weight.value);\n const alone = pathSetReliability(\n shown.map((path) => path.edges),\n chances,\n NUMBER_RING,\n options.maxSteps === undefined ? {} : { maxSteps: options.maxSteps },\n );\n // Within the budget, the coverage is exact. Out of it, the strongest path alone is a floor of the coverage.\n const covered = alone.kind === \"exact\" ? alone.value : top.chance;\n const why = whyOf(parts, top.edges, value === 0 ? 0 : Math.min(1, covered / value));\n return { ...base, why, ...(point.kind === \"exact\" ? weakOf(parts, point.importance) : {}) };\n}\n\n// The why of one path: its subject, the first node after the subject when two nodes or more are between the subject\n// and the person, the last node before the person, and the origin of the interest edge.\nfunction whyOf(parts: readonly Part[], indices: readonly number[], coverage: number): WhyRecord {\n const [hit, ...rest] = indices;\n const entry = parts[hit!]!.entry!;\n const edges = rest.map((index) => parts[index]!.edge!);\n const last = edges[edges.length - 1]!;\n return {\n rule: `reach.${entry.kind}.${last.origin}`,\n subject: entry.node,\n kind: entry.kind,\n ...(edges.length >= 3 ? { via: edges[0]!.to } : {}),\n anchor: last.from,\n origin: last.origin,\n coverage,\n };\n}\n\n// The weakest edge and the next question. Each is the first edge in the order of the ids with the largest value, and\n// it is absent when the largest value is 0.\nfunction weakOf(parts: readonly Part[], importance: readonly number[]): Pick<Relevance, \"weakest\" | \"next\"> {\n let weakest: { readonly edge: string; readonly importance: number } | undefined;\n let next: { readonly edge: string; readonly gain: number } | undefined;\n for (const [index, part] of parts.entries()) {\n const edge = part.edge;\n if (edge === undefined) continue;\n const value = Math.min(1, importance[index]!);\n if (value > 0 && (weakest === undefined || value > weakest.importance)) weakest = { edge: edge.id, importance: value };\n const gain = value * (edge.weight.high - edge.weight.low);\n if (edge.origin !== \"person\" && gain > 0 && (next === undefined || gain > next.gain)) next = { edge: edge.id, gain };\n }\n return { ...(weakest === undefined ? {} : { weakest }), ...(next === undefined ? {} : { next }) };\n}\n","/**\n * The tests of the shapes of an area against a position: the polygons and the circles of the core. The\n * home of geography, `@mark1russell7/geo`, gives the great-circle distances. An edge of a polygon is a\n * straight line in longitude and latitude, as in GeoJSON (RFC 7946).\n */\nimport { distanceKm, distanceToGeometryKm, GeoError } from \"@mark1russell7/geo\";\nimport { canonicalJson } from \"@mark1russell7/rigor-generators\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { Area, Position } from \"./contracts.ts\";\nimport type { MapRegion, MapShape } from \"./map.ts\";\n\n/** This function tells if an area is a shape: a polygon or a circle. */\nexport function isShape(area: Area): area is MapShape {\n return area.type === \"polygon\" || area.type === \"circle\";\n}\n\n/**\n * This function gives each area one time, with no block key, in the order of the areas. The NWS and IPAWS\n * copies of one warning give equal areas in two blocks. The map and the views draw each area one time.\n */\nexport function areasWithoutBlocks(areas: readonly Area[]): Area[] {\n const byText = new Map<string, Area>();\n for (const area of areas) {\n const plain = withoutBlock(area);\n const text = canonicalJson(plain, { form: \"json\" });\n if (!byText.has(text)) byText.set(text, plain);\n }\n return [...byText.values()];\n}\n\n/**\n * This function gives each shape one time, in the order of the first. Two shapes are equal by reference or by value, with no\n * block key. A zone and a county of one message can give the same outline from the store. The map draws it one time.\n */\nexport function distinctShapes(shapes: readonly MapShape[]): MapShape[] {\n const seen = new Set<MapShape>();\n const texts = new Set<string>();\n const out: MapShape[] = [];\n for (const shape of shapes) {\n if (seen.has(shape)) continue;\n seen.add(shape);\n const text = canonicalJson(withoutBlock(shape), { form: \"json\" });\n if (texts.has(text)) continue;\n texts.add(text);\n out.push(shape);\n }\n return out;\n}\n\nfunction withoutBlock(area: Area): Area {\n if (area.type === \"place\" || area.block === undefined) return area;\n if (area.type === \"polygon\") return { type: \"polygon\", rings: area.rings };\n if (area.type === \"circle\") return { type: \"circle\", center: area.center, radiusKm: area.radiusKm };\n return { type: \"code\", system: area.system, code: area.code };\n}\n\n/**\n * This function gives the great-circle distance in kilometers from a position to the nearest point of a\n * shape. The distance is 0 only when the shape contains the position. The function gives `undefined`\n * when `@mark1russell7/geo` refuses the shape, for example a ring with fewer than 4 positions.\n */\nexport function shapeDistanceKm(shape: MapShape, at: Position): number | undefined {\n const point = { lat: at[1], lon: at[0] };\n try {\n if (shape.type === \"circle\") {\n const center = { lat: shape.center[1], lon: shape.center[0] };\n return Math.max(0, distanceKm(point, center) - shape.radiusKm);\n }\n return distanceToGeometryKm(point, { type: \"Polygon\", coordinates: shape.rings });\n } catch (error) {\n if (error instanceof GeoError) return undefined;\n throw error;\n }\n}\n\n/**\n * This function gives the great-circle distance in kilometers from a position to the nearest shape of a region. The distance\n * is 0 only when a shape contains the position. A region with no shape that `@mark1russell7/geo` reads gives `undefined`.\n */\nexport function regionDistanceKm(region: MapRegion, at: Position): number | undefined {\n let nearest: number | undefined;\n for (const shape of region.shapes) {\n const distance = shapeDistanceKm(shape, at);\n if (distance !== undefined && (nearest === undefined || distance < nearest)) nearest = distance;\n }\n return nearest;\n}\n\n/** A region near a position, with the great-circle distance from the position to the nearest shape of the region. */\nexport interface NearRegion {\n readonly region: MapRegion;\n /** The distance in kilometers. It is 0 when a shape of the region contains the position. */\n readonly distanceKm: number;\n}\n\n/**\n * This function gives the regions with a shape at `bufferKm` or less from a position. The nearest region is first. Regions at\n * one distance are in the order of the system and the code. A region with no shape that geo reads is not near. A negative\n * buffer, or a buffer that is not finite, throws a `RangeError`.\n */\nexport function regionsNear(regions: readonly MapRegion[], at: Position, bufferKm: number): NearRegion[] {\n if (!Number.isFinite(bufferKm) || bufferKm < 0) throw new RangeError(`The buffer is ${String(bufferKm)}, not a number of 0 or more kilometers.`);\n const near: NearRegion[] = [];\n for (const region of regions) {\n const distanceKm = regionDistanceKm(region, at);\n if (distanceKm !== undefined && distanceKm <= bufferKm) near.push({ region, distanceKm });\n }\n return near.sort((a, b) => a.distanceKm - b.distanceKm || compareCodeUnits(a.region.code.system, b.region.code.system) || compareCodeUnits(a.region.code.code, b.region.code.code));\n}\n","/**\n * The first assessment of the alert system: the level of an incident for a person.\n *\n * The level is a calculation on data. The policy gives a table for each class of kinds. The table\n * gives the highest level for the severity and the highest level for the urgency, and the lower of\n * the two applies. The level for a person is the highest level at the places of the person, after the rules\n * of the person. The assessment reads no clock: the field `live` of the incident holds the time.\n */\nimport { inAudience, isPrivate } from \"./audience.ts\";\nimport type {\n AssessedLevel,\n AssessPolicy,\n AssessReason,\n Assessment,\n Incident,\n IncidentLine,\n Instant,\n InterestGraph,\n KindClass,\n LevelTable,\n NodeKey,\n PersonWatch,\n PlaceId,\n Position,\n RegionCode,\n Relevance,\n RelevancePolicy,\n ReportId,\n SubjectEntry,\n SubjectKind,\n SubjectSystem,\n SubjectWatch,\n WatchedPlace,\n} from \"./contracts.ts\";\nimport { ASSESSED_LEVELS, SUBJECT_SYSTEMS, SYSTEM_SOURCE } from \"./contracts.ts\";\nimport { hasKind } from \"./kind-prefix.ts\";\nimport type { MapShape } from \"./map.ts\";\nimport { DEFAULT_ENTRY_MAX, DEFAULT_RELEVANCE_POLICY, canReach, relevance, topicEntry } from \"./relevance.ts\";\nimport { isShape, shapeDistanceKm } from \"./shapes.ts\";\nimport { kindOfNode, nodesOverlap, placeNode, subjectNode } from \"./why.ts\";\n\nexport { hasKind } from \"./kind-prefix.ts\";\n\n/**\n * The kinds that can reach `life-safety` in the first policy: the list of `docs/CONTRACTS.md`, as\n * prefixes of the taxonomy codes. A kind is in the list when its warning tells the people at a place\n * to act at once to save their lives. They take shelter, leave, or go to high ground.\n */\nexport const LIFE_SAFETY_KINDS: readonly string[] = [\n \"met.tornado\",\n \"met.flood.flash\",\n \"met.wind.extreme\",\n \"met.tropical.hurricane\",\n \"met.tropical.typhoon\",\n \"met.surge\",\n \"fire.wildfire\",\n \"geo.tsunami\",\n \"geo.earthquake\",\n \"geo.debris-flow\",\n \"geo.volcano.eruption\",\n \"safety.national-emergency\",\n \"safety.evacuation\",\n \"safety.shelter-in-place\",\n \"safety.civil-danger\",\n \"safety.civil-emergency\",\n \"cbrne\",\n];\n\n/**\n * The table of the kinds that can reach `life-safety`. An `unknown` severity or urgency counts as\n * high, because a miss costs more than a false alarm for these kinds.\n */\nconst LIFE_SAFETY_TABLE: LevelTable = {\n severity: { extreme: \"life-safety\", severe: \"life-safety\", moderate: \"urgent\", minor: \"notice\", unknown: \"life-safety\" },\n urgency: { immediate: \"life-safety\", expected: \"life-safety\", future: \"urgent\", past: \"digest\", unknown: \"life-safety\" },\n};\n\n/** The kinds of the earthquake class: the reports of the shaking after a rupture. An early warning is in the life-safety class. */\nexport const EARTHQUAKE_KINDS: readonly string[] = [\"geo.earthquake\"];\n\n/** The time after the onset of an earthquake in which its report counts as `immediate`: one hour. */\nexport const EARTHQUAKE_PAST_WITHIN = 3_600_000;\n\n/**\n * The table of an earthquake. A report of the shaking has the urgency `past`, so it counts as `immediate` in\n * `EARTHQUAKE_PAST_WITHIN` after the onset. Then the severity of the band at the place decides. The severity\n * `extreme` (MMI VIII and more) wakes the person, and `severe` (MMI VII) is `urgent`. An unknown value counts as high.\n */\nconst EARTHQUAKE_TABLE: LevelTable = {\n severity: { extreme: \"life-safety\", severe: \"urgent\", moderate: \"notice\", minor: \"digest\", unknown: \"life-safety\" },\n urgency: { immediate: \"life-safety\", expected: \"life-safety\", future: \"urgent\", past: \"digest\", unknown: \"life-safety\" },\n pastWithin: EARTHQUAKE_PAST_WITHIN,\n};\n\n/**\n * The kinds of context. With the default policy, a report of such a kind reaches the digest at most. It starts no\n * escalation. A feed of the service alerts of public transit holds many alerts each day. Thus only a moderate or\n * higher severity reaches the digest, and a minor alert stays in the map and the log.\n *\n * The count of its alerts is an indicator reading. A policy of the configuration can give the kinds a different level.\n */\nexport const CONTEXT_KINDS: readonly string[] = [\"transport.transit\"];\n\n/**\n * The table of the kinds of context. It gives `digest` at most. A minor or unknown severity, or the urgency\n * `past`, gives `none`.\n */\nconst CONTEXT_TABLE: LevelTable = {\n severity: { extreme: \"digest\", severe: \"digest\", moderate: \"digest\", minor: \"none\", unknown: \"none\" },\n urgency: { immediate: \"digest\", expected: \"digest\", future: \"digest\", past: \"none\", unknown: \"digest\" },\n};\n\n/**\n * The table of a kind with no class in an incident whose sources this copy does not run (AL-76). Such an incident came\n * from another copy, and that copy can run a newer build with a class for the kind. Thus the incident reaches the\n * digest at most. A minor severity or the urgency `past` gives `none`.\n */\nexport const FOREIGN_TABLE: LevelTable = {\n severity: { extreme: \"digest\", severe: \"digest\", moderate: \"digest\", minor: \"none\", unknown: \"digest\" },\n urgency: { immediate: \"digest\", expected: \"digest\", future: \"digest\", past: \"none\", unknown: \"digest\" },\n};\n\n/** The table of the other kinds. These kinds reach `urgent` at most. */\nconst OTHER_TABLE: LevelTable = {\n severity: { extreme: \"urgent\", severe: \"urgent\", moderate: \"notice\", minor: \"digest\", unknown: \"digest\" },\n urgency: { immediate: \"urgent\", expected: \"urgent\", future: \"notice\", past: \"digest\", unknown: \"notice\" },\n};\n\n/**\n * The prefix of the kinds of the health reports of the core. The state follows it:\n * `system.health.failing`. An adapter does not map a message to this prefix.\n */\nexport const HEALTH_KIND = \"system.health\";\n\n/**\n * The prefix of the kinds of the coverage reports of the core. The covered kind follows it:\n * `system.coverage.met.tornado`. An adapter does not map a message to this prefix.\n */\nexport const COVERAGE_KIND = \"system.coverage\";\n\n/**\n * The prefix of the kinds of the quota reports of the core. The stage follows it:\n * `system.quota.reserve`. An adapter does not map a message to this prefix.\n */\nexport const QUOTA_KIND = \"system.quota\";\n\n/**\n * The prefix of the kinds of the balance reports of the core. The stage follows it:\n * `system.balance.low`. An adapter does not map a message to this prefix.\n */\nexport const BALANCE_KIND = \"system.balance\";\n\n/**\n * The prefix of the kinds of the clock reports of the core: `system.clock.step`, a step of the wall clock\n * against the monotonic clock. An adapter does not map a message to this prefix.\n */\nexport const CLOCK_KIND = \"system.clock\";\n\n/**\n * The prefix of the kinds of the log reports of the core: `system.log.recovered`, a broken log file that went into\n * quarantine. An adapter does not map a message to this prefix.\n */\nexport const LOG_KIND = \"system.log\";\n\n/**\n * The prefix of the kinds of the copy reports of the core. The stage follows it: `system.copy.unread`. An adapter does\n * not map a message to this prefix.\n */\nexport const COPY_KIND = \"system.copy\";\n\n/**\n * The prefix of the kinds of the drill reports of the core. `system.drill.run` is a run that waits for its\n * acknowledgment, and `system.drill.failed` is a failed run. An adapter does not map a message to this prefix.\n */\nexport const DRILL_KIND = \"system.drill\";\n\n/**\n * The prefix of the kinds of the escalation reports of the core (AL-21). `system.escalation.exhausted` tells that a\n * person did not acknowledge a real warning in the time of the policy. An adapter does not map a message to this prefix.\n */\nexport const ESCALATION_KIND = \"system.escalation\";\n\n/**\n * The prefix of the kinds of the channel reports of the core (AL-65). `system.channel.down` tells that the calls of a\n * channel of this copy fail. An adapter does not map a message to this prefix.\n */\nexport const CHANNEL_KIND = \"system.channel\";\n\n/**\n * The prefix of the kinds of the store reports of the core (AL-86). `system.store.empty` tells that a family of a store of\n * the runtime has no entry in the time after a start. An adapter does not map a message to this prefix.\n */\nexport const STORE_KIND = \"system.store\";\n\n/**\n * The prefix of the kinds of the send-limit reports of the core (AL-81). `system.limit.held` tells a person that the send\n * limit holds new alerts for the person, and that the digest tells them. Such a report is private. An adapter does not map a message to this prefix.\n */\nexport const LIMIT_KIND = \"system.limit\";\n\n/**\n * The prefix of the kinds of the messages of the operator (AL-92). The intake of the runtime maps each message to\n * `system.tell.<class>` with the status `system`. Each such message is private: its addresses name its persons.\n */\nexport const TELL_KIND = \"system.tell\";\n\n/**\n * The classes of a message of the operator (AL-92). `needs-you`: the person must decide or act. `done-you-asked`: a\n * request of the person is done. `live`: a change is live.\n */\nexport const TELL_CLASSES = [\"needs-you\", \"done-you-asked\", \"live\"] as const;\n\n/** The class of a message of the operator. */\nexport type TellClass = (typeof TELL_CLASSES)[number];\n\n/**\n * The subject system of a person. The id of a subject is the id of a person. A person who watches the subject of another\n * person gets the escalation reports of that person. A subject of the person itself does not match the person.\n */\nexport const PERSON_SUBJECT = \"alerts.person\";\n\n/**\n * The table of the system reports that can reach `life-safety`: the coverage of a life-safety kind, a drill run and an\n * exhausted escalation. The severity and the urgency of an exhausted escalation give back its level.\n */\nconst LOUD_SYSTEM_TABLE: LevelTable = {\n severity: { extreme: \"life-safety\", severe: \"urgent\", moderate: \"notice\", minor: \"digest\", unknown: \"urgent\" },\n urgency: { immediate: \"life-safety\", expected: \"urgent\", future: \"notice\", past: \"digest\", unknown: \"urgent\" },\n};\n\n/** The table of the other reports of the system. These reports reach `notice` at most. */\nconst SYSTEM_TABLE: LevelTable = {\n severity: { extreme: \"notice\", severe: \"notice\", moderate: \"notice\", minor: \"digest\", unknown: \"notice\" },\n urgency: { immediate: \"notice\", expected: \"notice\", future: \"digest\", past: \"digest\", unknown: \"notice\" },\n};\n\n/**\n * The table of the messages of the operator (AL-92). These messages reach `urgent` at most. The intake gives the\n * severity `severe` and the urgency `immediate` only to an urgent `needs-you`. Each other message gets `notice`.\n */\nconst TELL_TABLE: LevelTable = {\n severity: { extreme: \"urgent\", severe: \"urgent\", moderate: \"notice\", minor: \"digest\", unknown: \"notice\" },\n urgency: { immediate: \"urgent\", expected: \"notice\", future: \"notice\", past: \"digest\", unknown: \"notice\" },\n};\n\n/**\n * The first policy. An incident is `life-safety` when its status is `actual` and its kind is in\n * `LIFE_SAFETY_KINDS`. Its severity must be `severe`, `extreme` or `unknown`, and its urgency must\n * be `immediate`, `expected` or `unknown`. A place of the person must be in its areas.\n *\n * The three system classes hold the reports of the core, and they admit only the status `system`. The\n * coverage of a life-safety kind, a drill run and an exhausted escalation can reach `life-safety`. Each other report of the core reaches\n * `notice` at most. The NWS kinds `system.test` and `system.admin` are not in these classes.\n *\n * The class `system-tell` holds the messages of the operator (`TELL_KIND`). It admits only the status `system`, and it\n * reaches `urgent` at most.\n *\n * The earthquake class has its own table. In one hour after the onset, its urgency `past` counts as\n * `immediate`. Then `extreme` is `life-safety`, and `severe` is `urgent`.\n *\n * The kinds of context (`CONTEXT_KINDS`) reach the digest at most. Thus a report of such a kind starts no escalation,\n * and the rule of the life-safety warnings does not apply to it.\n */\nexport const DEFAULT_ASSESS_POLICY: AssessPolicy = {\n statuses: [\"actual\"],\n classes: [\n // The first class with a prefix of the kind applies. Thus an early warning stays in the life-safety class.\n { id: \"life-safety\", kinds: [...LIFE_SAFETY_KINDS.filter((kind) => !EARTHQUAKE_KINDS.includes(kind)), \"geo.earthquake.early-warning\"], ...LIFE_SAFETY_TABLE },\n { id: \"earthquake\", kinds: EARTHQUAKE_KINDS, ...EARTHQUAKE_TABLE },\n { id: \"system-coverage\", kinds: LIFE_SAFETY_KINDS.map((kind) => `${COVERAGE_KIND}.${kind}`), statuses: [\"system\"], ...LOUD_SYSTEM_TABLE },\n // A drill run tests the path of the life-safety warnings, thus it reaches `life-safety`. A failed drill gets `notice` at most.\n { id: \"system-drill\", kinds: [`${DRILL_KIND}.run`], statuses: [\"system\"], ...LOUD_SYSTEM_TABLE },\n // An exhausted escalation of a person keeps its level for the people who watch that person (AL-21).\n { id: \"system-escalation\", kinds: [ESCALATION_KIND], statuses: [\"system\"], ...LOUD_SYSTEM_TABLE },\n // A message of the operator reaches only the persons of its addresses (AL-92). An urgent `needs-you` reaches `urgent`.\n { id: \"system-tell\", kinds: [TELL_KIND], statuses: [\"system\"], ...TELL_TABLE },\n { id: \"system\", kinds: [HEALTH_KIND, COVERAGE_KIND, QUOTA_KIND, BALANCE_KIND, CLOCK_KIND, LOG_KIND, COPY_KIND, DRILL_KIND, CHANNEL_KIND, STORE_KIND, LIMIT_KIND], statuses: [\"system\"], ...SYSTEM_TABLE },\n // The service alerts of public transit are context. Their counts are indicator readings.\n { id: \"context\", kinds: CONTEXT_KINDS, ...CONTEXT_TABLE },\n ],\n otherwise: OTHER_TABLE,\n};\n\n/** This function gives the lower of two levels. */\nexport function lowerLevel(a: AssessedLevel, b: AssessedLevel): AssessedLevel {\n return rank(a) <= rank(b) ? a : b;\n}\n\n/** This function gives the higher of two levels. */\nexport function higherLevel(a: AssessedLevel, b: AssessedLevel): AssessedLevel {\n return rank(a) >= rank(b) ? a : b;\n}\n\n/** The result of the table for one incident. */\nexport interface TableResult {\n /** The id of the class of the kind. It is absent for the table `otherwise`. */\n readonly class?: string;\n readonly bySeverity: AssessedLevel;\n readonly byUrgency: AssessedLevel;\n /** The lower of the two levels. */\n readonly level: AssessedLevel;\n /** This value is true when the urgency `past` counted as `immediate` in the window `pastWithin` of the table. */\n readonly recentPast?: true;\n /** This value is true when the table is `FOREIGN_TABLE`: the kind has no class, and only other copies run the sources of the incident. */\n readonly foreign?: true;\n}\n\n/** This function gives the first class of the policy with a prefix of a kind, or `undefined`. */\nexport function classOf(policy: AssessPolicy, kind: string): KindClass | undefined {\n return policy.classes.find((candidate) => hasKind(candidate.kinds, kind));\n}\n\n/**\n * This function tells if the policy sends an incident of this status and kind. The class of the kind\n * gives the statuses, else the policy gives them.\n */\nexport function admits(policy: AssessPolicy, incident: Pick<Incident, \"status\" | \"kind\">): boolean {\n return (classOf(policy, incident.kind.code)?.statuses ?? policy.statuses).includes(incident.status);\n}\n\n/**\n * This function gives the level of the table for an incident or a line: the lower of its two lookups. In the\n * window `pastWithin` of the table after the onset, the urgency `past` counts as `immediate`. The time `at`\n * gives the age. With no time or no onset, the age is unknown, and `past` counts as `immediate`. With `foreign`, a kind\n * with no class gets `FOREIGN_TABLE`.\n */\nexport function tableLevel(\n policy: AssessPolicy,\n incident: Pick<Incident | IncidentLine, \"kind\" | \"severity\" | \"urgency\" | \"onset\">,\n at?: Instant,\n foreign = false,\n): TableResult {\n const found = classOf(policy, incident.kind.code);\n // A kind with no class in an incident of the sources of other copies gets the quiet table (AL-76).\n const other = found === undefined && foreign;\n const table = found ?? (other ? FOREIGN_TABLE : policy.otherwise);\n const span = table.pastWithin;\n const recent = incident.urgency === \"past\" && span !== undefined && (at === undefined || incident.onset === undefined || at - incident.onset <= span);\n const bySeverity = table.severity[incident.severity];\n const byUrgency = table.urgency[recent ? \"immediate\" : incident.urgency];\n const level = lowerLevel(bySeverity, byUrgency);\n return {\n ...(found === undefined ? {} : { class: found.id }),\n bySeverity,\n byUrgency,\n level,\n ...(recent ? { recentPast: true as const } : {}),\n ...(other ? { foreign: true as const } : {}),\n };\n}\n\n/**\n * This function gives the test of an incident of the sources of other copies (AL-76). The test is true when each report\n * of the incident comes from a source that is not in `sources`. Such an incident came from another copy only. A report\n * with no known source counts as a report of this copy. A report of `SYSTEM_SOURCE` also counts as a report of this\n * copy, because each copy makes its own system reports. Without `sources`, the test is always false.\n */\nexport function foreignIncidents(\n reports: readonly { readonly id: string; readonly source: string }[],\n sources: ReadonlySet<string> | undefined,\n): (incident: Pick<Incident, \"anchor\" | \"reports\">) => boolean {\n if (sources === undefined) return () => false;\n const sourceOf = new Map<string, string>(reports.map((report) => [report.id, report.source]));\n return (incident) =>\n [incident.anchor, ...incident.reports].every((report) => {\n const source = sourceOf.get(report);\n return source !== undefined && source !== SYSTEM_SOURCE && !sources.has(source);\n });\n}\n\n/**\n * This function tells if a code of an area and a code of a place name regions that meet. The codes\n * must be of one system and equal, with one more rule for SAME (`sameScope`). Thus a SAME code of a\n * state meets each county of that state, and a part of a county meets the full county. The match of\n * the places uses this rule. It is on the safe side: an alert for a part of a region goes to the places\n * of that region.\n */\nexport function regionCovers(area: RegionCode, place: RegionCode): boolean {\n if (area.system !== place.system) return false;\n if (area.code === place.code) return true;\n return area.system === \"same\" && sameRelation(area.code, place.code, \"meets\");\n}\n\n/**\n * This function tells if the region of a code of an area holds all of the region of a code of a place.\n * The codes must be of one system and equal, with one more rule for SAME (`sameScope`). The coverage of\n * the sources uses this rule. It is on the safe side: a source of a part of a county does not hide a gap\n * of the full county.\n */\nexport function regionContains(area: RegionCode, place: RegionCode): boolean {\n if (area.system !== place.system) return false;\n if (area.code === place.code) return true;\n return area.system === \"same\" && sameRelation(area.code, place.code, \"contains\");\n}\n\n/** A place in the areas of an incident, with the codes or the distance that decided the match. */\nexport interface PlaceMatch {\n readonly place: PlaceId;\n /** The codes of the place that decided the match. The list is empty for a match by a shape only. */\n readonly codes: readonly RegionCode[];\n /**\n * The great-circle distance in kilometers from the place to the nearest shape that decided. It is 0 in\n * a shape. It is present only when that distance is in the buffer of the place.\n */\n readonly distanceKm?: number;\n /**\n * True when the codes of a block decided the match because `@mark1russell7/geo` refuses each shape of\n * that block. The view shows it, because the shape of that block did not decide.\n */\n readonly shapeRefused?: true;\n /**\n * True when a fire zone code of an area decided through the forecast zone code of the place with the same code\n * (AL-33). The place has no fire zone code of that state. The view shows it, because the two outlines can differ.\n */\n readonly zoneFallback?: true;\n}\n\n/**\n * This function gives the places that the areas of an incident cover, in the order of the places. One\n * block that matches is enough.\n *\n * - An area of a watched place covers that place.\n * - A block with a shape decides by its shapes for a place with a position. The place matches when the\n * great-circle distance to the nearest polygon or circle of the block is not more than its buffer. The\n * codes of that block do not decide for that place.\n * - A block with no shape decides by its codes. So does each block for a place with no position.\n * - When `@mark1russell7/geo` refuses each shape of a block, the codes of the block decide. This is on the\n * safe side, and the match tells it with `shapeRefused`.\n * - The areas with no block key keep the union rule. Their codes are the floor of the match, and a shape\n * adds a place in its buffer. A shape that geo refuses adds no place.\n * - A fire zone code (`ugc-fire`) covers only a fire zone code of a place. A place with no fire zone code of\n * a state uses the forecast zone code (`ugc`) with the same code. This is on the safe side, and the match\n * tells it with `zoneFallback`.\n */\nexport function matchPlaces(incident: Pick<Incident, \"areas\">, places: readonly WatchedPlace[]): PlaceMatch[] {\n const ids = new Set(incident.areas.flatMap((area) => (area.type === \"place\" ? [area.place] : [])));\n const groups = new Map<string | undefined, (MapShape | (RegionCode & { readonly type: \"code\" }))[]>();\n for (const area of incident.areas) {\n if (area.type === \"place\") continue;\n const group = groups.get(area.block) ?? [];\n group.push(area);\n groups.set(area.block, group);\n }\n return places.flatMap((place): PlaceMatch[] => {\n const covered = new Set<RegionCode>();\n let nearest = Number.POSITIVE_INFINITY;\n let shapeRefused = false;\n // The codes that an area code covers, and the codes that only the fallback of the fire zones covers.\n const direct = new Set<RegionCode>();\n const fallback = new Set<RegionCode>();\n const fireStates = new Set(place.codes.flatMap((code) => (code.system === \"ugc-fire\" ? [code.code.slice(0, 2)] : [])));\n for (const [block, areas] of groups) {\n const shapes = areas.filter(isShape);\n const distance = place.at === undefined || shapes.length === 0 ? undefined : nearestShape(shapes, place.at);\n if (distance !== undefined) nearest = Math.min(nearest, distance);\n // A block decides by its shapes when geo reads one of them. The areas with no block always give their codes.\n if (block !== undefined && distance !== undefined) continue;\n const codeAreas = areas.filter((area) => area.type === \"code\");\n const byBlock: RegionCode[] = [];\n for (const code of place.codes) {\n if (codeAreas.some((area) => regionCovers(area, code))) {\n direct.add(code);\n byBlock.push(code);\n } else if (!fireStates.has(code.code.slice(0, 2)) && codeAreas.some((area) => zoneFallbackCovers(area, code))) {\n fallback.add(code);\n byBlock.push(code);\n }\n }\n for (const code of byBlock) covered.add(code);\n if (byBlock.length > 0 && block !== undefined && place.at !== undefined && shapes.length > 0) shapeRefused = true;\n }\n const codes = place.codes.filter((code) => covered.has(code));\n const near = nearest <= place.bufferKm;\n if (codes.length === 0 && !near && !ids.has(place.id)) return [];\n const zoneFallback = codes.some((code) => fallback.has(code) && !direct.has(code));\n return [\n {\n place: place.id,\n codes,\n ...(near ? { distanceKm: nearest } : {}),\n ...(shapeRefused ? { shapeRefused: true as const } : {}),\n ...(zoneFallback ? { zoneFallback: true as const } : {}),\n },\n ];\n });\n}\n\n// The fallback of the fire zones: a fire zone code of an area covers the forecast zone code of a place with the same code.\n// The caller uses it only for a place with no fire zone code of the state of that code.\nfunction zoneFallbackCovers(area: RegionCode, place: RegionCode): boolean {\n return area.system === \"ugc-fire\" && place.system === \"ugc\" && area.code === place.code;\n}\n\n// The distance to the nearest shape that geo reads, or `undefined` when geo refuses each shape.\nfunction nearestShape(shapes: readonly MapShape[], at: Position): number | undefined {\n let nearest: number | undefined;\n for (const shape of shapes) {\n const distance = shapeDistanceKm(shape, at);\n if (distance !== undefined) nearest = Math.min(nearest ?? distance, distance);\n }\n return nearest;\n}\n\n/**\n * This function gives the watches of a person that a subject of an incident matches, in the order\n * of the watches. A watch with no id matches each subject of its system. A watch with an id matches each subject\n * whose node overlaps its node (`nodesOverlap`). Outside the systems of paths, that is the subject with the same id.\n */\nexport function matchSubjects(incident: Pick<Incident, \"about\">, watches: readonly SubjectWatch[]): SubjectWatch[] {\n return watches.filter((watch) =>\n incident.about.some(\n (subject) => subject.system === watch.system && (watch.id === undefined || nodesOverlap(subjectNode({ system: watch.system, id: watch.id }), subjectNode(subject))),\n ),\n );\n}\n\n/**\n * This function gives the assessment as it reaches the person. A mute with the effect `absent` keeps the incident from the\n * person, thus the level is `none`. A mute with the effect `silent` keeps the level. Each other assessment stays the same.\n */\nexport function reachedAssessment(assessment: Assessment): Assessment {\n return assessment.muted?.effect === \"absent\" ? { ...assessment, level: \"none\" } : assessment;\n}\n\n/**\n * This function gives the level of an incident for a person, with its reasons. The level is `none`\n * when the incident ended, or when the policy does not send its status for its kind. It is also\n * `none` when the incident has no place and no subject that the person watches.\n *\n * Else the level is the highest level at the matches of the person: each place in the areas, and\n * each watched subject. At each match, the first rule of the person that matches can lower the\n * level of the table. A rule with places does not match a subject.\n *\n * An incident with lines has a table level at each place: the highest level of the lines whose areas\n * hold that place. Thus a far place of an earthquake gets the level of its band of shaking, not the\n * level of the center. A subject gets the level of the incident.\n *\n * A person with an interest graph gets the routing by the relevance (`docs/RELEVANCE.md`). A place or another\n * entry counts only when it reaches the person alone. A place under the rule of the life-safety warnings always\n * counts. An entry that is not a watched place gives the level of the table, up to `entryMax` of the policy.\n * When the relevance fails, the places decide as with no graph, and the reason `relevance-fault` tells the fault.\n *\n * The value `foreign` tells that this copy runs no source of the incident (`foreignIncidents`). A kind with no class\n * then gets `FOREIGN_TABLE`, not the table `otherwise` (AL-76).\n */\nexport function assess(\n incident: Incident,\n person: PersonWatch,\n places: readonly WatchedPlace[],\n policy: AssessPolicy = DEFAULT_ASSESS_POLICY,\n at?: Instant,\n foreign = false,\n): Assessment {\n // A private incident reaches only the persons of its addresses (AL-92, `audience.ts`).\n if (!inAudience(incident, person.person)) {\n return { incident: incident.anchor, person: person.person, level: \"none\", places: [], reasons: [{ kind: \"not-addressed\" }] };\n }\n const byId = new Map(places.map((place) => [place.id, place]));\n const reasons: AssessReason[] = [];\n const watched: WatchedPlace[] = [];\n for (const id of person.places) {\n const place = byId.get(id);\n if (place === undefined) reasons.push({ kind: \"unknown-place\", place: id });\n else watched.push(place);\n }\n const matches = matchPlaces(incident, watched);\n // The escalation reports of a person go to the people who watch that person, and not to the person. Thus the subject\n // of the person itself matches no watch of the person, also a watch with no id.\n const others = incident.about.filter((subject) => !(subject.system === PERSON_SUBJECT && subject.id === person.person));\n const subjects = matchSubjects({ about: others }, person.subjects ?? []);\n let muted: Assessment[\"muted\"];\n const result = (level: AssessedLevel): Assessment => ({\n incident: incident.anchor,\n person: person.person,\n level,\n places: matches.map((match) => match.place),\n reasons,\n ...(muted === undefined ? {} : { muted }),\n });\n if (!incident.live) {\n reasons.push({ kind: \"ended\" });\n return result(\"none\");\n }\n if (!admits(policy, incident)) {\n reasons.push({ kind: \"status\", status: incident.status });\n return result(\"none\");\n }\n const table = tableLevel(policy, incident, at, foreign);\n const tables = new Map<PlaceId, PlaceTable>();\n // The level of the table at one place: the highest table of the lines that hold the place.\n const placeTable = (id: PlaceId): PlaceTable => {\n const known = tables.get(id);\n if (known !== undefined) return known;\n const place = byId.get(id);\n const holding = place === undefined ? [] : linesAt(incident, place);\n const found: PlaceTable =\n holding.length === 0\n ? { level: table.level, reports: [] }\n : { level: holding.map((line) => tableLevel(policy, line, at, foreign).level).reduce(higherLevel), reports: holding.map((line) => line.report) };\n tables.set(id, found);\n return found;\n };\n const relevancePolicy = policy.relevance ?? DEFAULT_RELEVANCE_POLICY;\n let plan: RelevancePlan | undefined;\n // The sender of a private incident named the person, so the interest graph does not decide.\n if (person.interests !== undefined && !isPrivate(incident)) {\n try {\n plan = planOf(incident, person, person.interests, matches, byId, (id) => placeTable(id).level, relevancePolicy, at);\n } catch (error) {\n // The alert is not lost: the places decide, as for a person with no graph.\n reasons.push({ kind: \"relevance-fault\", message: error instanceof Error && error.message !== \"\" ? error.message : RELEVANCE_FAULT });\n }\n }\n // The result keeps the mute also when nothing reaches the person, because a mute that removes each entry is the cause.\n muted = plan?.relevance.muted;\n if (!isPrivate(incident) && matches.length === 0 && subjects.length === 0 && (plan === undefined || plan.reached.length === 0)) {\n reasons.push({ kind: noMatch(incident, watched) });\n return result(\"none\");\n }\n reasons.push({ kind: \"table\", ...table });\n const entryLevel = lowerLevel(table.level, relevancePolicy.entryMax ?? DEFAULT_ENTRY_MAX);\n if (plan !== undefined) {\n const { reach, why } = plan.relevance;\n reasons.push({\n kind: \"reach\",\n reach,\n reached: plan.reached,\n mandatory: plan.mandatory,\n ...(plan.others.length > 0 ? { entryLevel } : {}),\n ...(why === undefined ? {} : { why }),\n });\n }\n let level: AssessedLevel = \"none\";\n // The level at one match through an entry of the kind `through`: the first rule that matches can lower the level of the table.\n const atMatch = (place: PlaceId | undefined, base: AssessedLevel, through: SubjectKind): AssessedLevel => {\n const index = person.rules.findIndex(\n (rule) =>\n (rule.places === undefined || (place !== undefined && rule.places.includes(place))) &&\n (rule.kinds === undefined || hasKind(rule.kinds, incident.kind.code)) &&\n (rule.through === undefined || rule.through.includes(through)),\n );\n const rule = person.rules[index];\n if (rule === undefined || rank(rule.max) >= rank(base)) return base;\n reasons.push(place === undefined ? { kind: \"rule\", index, max: rule.max } : { kind: \"rule\", place, index, max: rule.max });\n return rule.max;\n };\n if (isPrivate(incident)) {\n reasons.push({ kind: \"addressed\" });\n return result(atMatch(undefined, table.level, \"entity\"));\n }\n for (const match of matches) {\n reasons.push({ kind: \"place\", ...match });\n if (plan !== undefined && !plan.places.has(match.place)) continue;\n const found = placeTable(match.place);\n if (found.reports.length > 0 && found.level !== table.level) reasons.push({ kind: \"place-table\", place: match.place, reports: found.reports, level: found.level });\n level = higherLevel(level, atMatch(match.place, found.level, \"place\"));\n }\n // Each kind of the other entries that count gets its own rule. Thus a rule through topics does not lower an entity.\n for (const through of plan?.others ?? []) level = higherLevel(level, atMatch(undefined, entryLevel, through));\n for (const subject of subjects) {\n reasons.push({ kind: \"subject\", subject });\n level = higherLevel(level, atMatch(undefined, table.level, kindOfNode(subjectNode({ system: subject.system, id: subject.id ?? \"*\" })) ?? \"entity\"));\n }\n return result(level);\n}\n\n// The level of the table at one place, and the reports of the lines that hold the place.\ninterface PlaceTable {\n readonly level: AssessedLevel;\n readonly reports: readonly ReportId[];\n}\n\n// The routing by the relevance for one person.\ninterface RelevancePlan {\n // The matched places that count: each place of the rule of the life-safety warnings, and each place that reaches the person alone.\n readonly places: ReadonlySet<PlaceId>;\n // The kinds of the entries that are not matched places and that reach the person alone, in the order of SUBJECT_KINDS.\n readonly others: readonly SubjectKind[];\n // The entries that count, in the order of the entries.\n readonly reached: readonly NodeKey[];\n // The matched places of the rule of the life-safety warnings, in the order of the matches.\n readonly mandatory: readonly PlaceId[];\n readonly relevance: Relevance;\n}\n\n// The kinds of the entries, in the order of the reasons and the rules.\nconst SUBJECT_KINDS: readonly SubjectKind[] = [\"place\", \"topic\", \"entity\"];\n\n// The message of a fault with no text of its own.\nconst RELEVANCE_FAULT = \"The relevance failed with no message.\";\n\n// The hit of an entry that the incident names: a place in its areas, a code, a subject or the topic of its kind.\nconst FULL_HIT = { value: 1, low: 1, high: 1 } as const;\n\n// The plan of the routing by the relevance. A matched place is under the rule of the life-safety warnings when the\n// rule of the person is on there, the match is in its range and the table gives `life-safety` at the place. Each other\n// entry counts when it reaches the person alone, with the cut of the mutes. The function throws when the relevance\n// throws, and the caller records the fault.\nfunction planOf(\n incident: Incident,\n person: PersonWatch,\n graph: InterestGraph,\n matches: readonly PlaceMatch[],\n byId: ReadonlyMap<PlaceId, WatchedPlace>,\n levelAt: (place: PlaceId) => AssessedLevel,\n policy: RelevancePolicy,\n at: Instant | undefined,\n): RelevancePlan {\n if (graph.person !== person.person) throw new RangeError(\"The interest graph is of another person.\");\n const mandatory = matches\n .filter((match) => {\n const rule = person.mandatory?.find((candidate) => candidate.place === match.place);\n const rangeKm = rule?.rangeKm ?? byId.get(match.place)?.bufferKm ?? 0;\n const inRange = match.codes.length > 0 || match.distanceKm === undefined || match.distanceKm <= rangeKm;\n return (rule?.on ?? true) && inRange && levelAt(match.place) === \"life-safety\";\n })\n .map((match) => match.place);\n const entries = entriesOf(incident, matches, graph);\n const kind = incident.kind.code;\n // With no time, a mute with an end has no effect, so the alert is not lost.\n const time = at ?? Number.POSITIVE_INFINITY;\n const found = relevance({ kind, entries, at: time, mandatory: mandatory.length > 0 }, graph, policy);\n const kept = new Set(mandatory.map(placeNode));\n // Only a node that starts an edge can reach the person. Each entry counts alone, with the cut of the mutes.\n const starts = new Set(graph.edges.map((edge) => edge.from));\n const reached = entries\n .filter((entry) => kept.has(entry.node) || (starts.has(entry.node) && canReach({ kind, entries: [entry], at: time, mandatory: false }, graph, policy)))\n .map((entry) => entry.node);\n const counted = new Set(reached);\n const places = new Set(matches.filter((match) => counted.has(placeNode(match.place))).map((match) => match.place));\n const matched = new Set(matches.map((match) => placeNode(match.place)));\n const otherKinds = new Set(entries.filter((entry) => counted.has(entry.node) && !matched.has(entry.node)).map((entry) => entry.kind));\n return { places, others: SUBJECT_KINDS.filter((kind) => otherKinds.has(kind)), reached, mandatory, relevance: found };\n}\n\n// The entries of an incident for a graph, one for each node: the matched places, the areas, the subjects and the topic,\n// in this order. A code or a subject gives an entry when its system is in `SUBJECT_SYSTEMS`.\nfunction entriesOf(incident: Incident, matches: readonly PlaceMatch[], graph: InterestGraph): SubjectEntry[] {\n const found = new Map<NodeKey, SubjectEntry>();\n const add = (system: string, id: string): void => {\n if (!Object.hasOwn(SUBJECT_SYSTEMS, system)) return;\n const node = subjectNode({ system, id });\n if (!found.has(node)) found.set(node, { node, kind: SUBJECT_SYSTEMS[system as SubjectSystem], hit: FULL_HIT });\n };\n for (const match of matches) add(\"place\", match.place);\n for (const area of incident.areas) {\n if (area.type === \"code\") add(area.system, area.code);\n else if (area.type === \"place\") add(\"place\", area.place);\n }\n for (const subject of incident.about) add(subject.system, subject.id);\n // A node of the graph that overlaps a subject in a system of paths is also an entry (`nodesOverlap`).\n const subjects = [...found.keys()];\n for (const node of new Set(graph.edges.flatMap((edge) => [edge.from, edge.to]))) {\n const kind = kindOfNode(node);\n if (kind !== undefined && !found.has(node) && subjects.some((subject) => nodesOverlap(subject, node))) found.set(node, { node, kind, hit: FULL_HIT });\n }\n const topic = topicEntry(incident.kind.code, graph);\n if (topic !== undefined && !found.has(topic.node)) found.set(topic.node, topic);\n return [...found.values()];\n}\n\n/**\n * This function gives the lines of an incident whose areas hold a place, in the order of the lines. Each line\n * decides by the rules of `matchPlaces`. An incident with no lines gives an empty list.\n */\nexport function linesAt(incident: Pick<Incident, \"lines\">, place: WatchedPlace): IncidentLine[] {\n return (incident.lines ?? []).filter((line) => matchPlaces(line, [place]).length > 0);\n}\n\n// The reason when the incident has no place and no subject of the person. A shape can match only a\n// place with a position.\nfunction noMatch(incident: Pick<Incident, \"areas\" | \"about\">, places: readonly WatchedPlace[]): \"no-place\" | \"no-subject\" | \"no-codes\" {\n if (incident.areas.some((area) => area.type === \"code\" || area.type === \"place\")) return \"no-place\";\n if (incident.areas.some(isShape) && places.some((place) => place.at !== undefined)) return \"no-place\";\n if (incident.areas.length === 0 && incident.about.length > 0) return \"no-subject\";\n return \"no-codes\";\n}\n\n// A SAME code: a part digit, two digits of the state and three digits of the county.\nconst SAME = /^\\d{6}$/;\n\n/**\n * This function gives the levels of a SAME code `PSSCCC`: the state `SS`, the county `CCC` and the part\n * `P`. `undefined` is all of a level. The part `0` is the full county, the county `000` is the full\n * state, and `000000` is the full country (47 CFR 11.31). A code that is not 6 digits gives `undefined`.\n */\nfunction sameScope(code: string): readonly (string | undefined)[] | undefined {\n if (!SAME.test(code)) return undefined;\n const [part, state, county] = [code.slice(0, 1), code.slice(1, 3), code.slice(3)];\n if (county === \"000\") return state === \"00\" ? [undefined, undefined, undefined] : [state, undefined, undefined];\n return [state, county, part === \"0\" ? undefined : part];\n}\n\n/**\n * This function compares the levels of two SAME codes. The first contains the second when each of its\n * levels is all of the level or equal. The two meet when each level is all of the level in one of them,\n * or equal.\n */\nfunction sameRelation(first: string, second: string, relation: \"meets\" | \"contains\"): boolean {\n const [outer, inner] = [sameScope(first), sameScope(second)];\n if (outer === undefined || inner === undefined) return false;\n return outer.every((level, at) => level === undefined || level === inner[at] || (relation === \"meets\" && inner[at] === undefined));\n}\n\nfunction rank(level: AssessedLevel): number {\n return ASSESSED_LEVELS.indexOf(level);\n}\n","/**\n * The shadow score of an incident: the probability of the event and the harm of one event, from public\n * measures. The score operates next to the table, and it does not decide a level at this time. The table\n * decides each send, and the gate test of `score.test.ts` holds this.\n */\n\nimport { interval } from \"@mark1russell7/interval\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { assess, DEFAULT_ASSESS_POLICY, hasKind } from \"./assess.ts\";\nimport {\n LEVELS,\n type AssessPolicy,\n type Assessment,\n type Certainty,\n type Estimate,\n type ExpectedHarm,\n type Incident,\n type Instant,\n type KindPrior,\n type PersonWatch,\n type ScoredIncident,\n type ScoreFactor,\n type ScoreGap,\n type ScorePriors,\n type ShadowDifference,\n type ShadowScore,\n type Significance,\n type UnderPrior,\n type WatchedPlace,\n} from \"./contracts.ts\";\n\n/** The format of a file of priors. */\nexport const PRIORS_FORMAT: ScorePriors[\"format\"] = \"alerts-priors/2\";\n\n// The value of the longest prefix of the kind that gives a value. A prefix ends at a dot, as in `hasKind`.\nfunction longestPrefix<T>(priors: ScorePriors, kind: string, pick: (prior: KindPrior) => T | undefined): { readonly value: T; readonly key: string } | undefined {\n let found: { readonly value: T; readonly key: string } | undefined;\n for (const [key, prior] of Object.entries(priors.kinds)) {\n const value = pick(prior);\n if (value === undefined || !hasKind([key], kind)) continue;\n if (found === undefined || key.length > found.key.length) found = { value, key };\n }\n return found;\n}\n\n// The field of the longest prefix of the kind that has the field.\nfunction kindFactor(priors: ScorePriors, kind: string, field: \"verified\" | \"deaths\" | \"injuries\"): ScoreFactor | undefined {\n const found = longestPrefix(priors, kind, (prior) => prior[field]);\n return found === undefined ? undefined : { estimate: found.value, from: { table: \"kinds\", key: found.key } };\n}\n\n// The harm under one alert of the significance, from the longest prefix of the kind with that measure.\nfunction underOf(priors: ScorePriors, kind: string, significance: Significance): { readonly prior: UnderPrior; readonly key: string } | undefined {\n const found = longestPrefix(priors, kind, (prior) => prior.under?.[significance]);\n return found === undefined ? undefined : { prior: found.value, key: found.key };\n}\n\n// The probability of a CAP certainty value.\nfunction certaintyFactor(priors: ScorePriors, certainty: Certainty): ScoreFactor | undefined {\n const estimate = priors.certainty[certainty];\n return estimate === undefined ? undefined : { estimate, from: { table: \"certainty\", key: certainty } };\n}\n\n/**\n * This function gives the product of a probability and a count. `mul` of `@mark1russell7/interval` rounds the interval\n * outward. The two factors are 0 or more, thus the exact product is 0 or more. A low bound below 0 becomes 0, and the\n * interval still holds each product. An underflow to 0 gives such a bound.\n */\nexport function expectedOf(probability: Estimate, count: Estimate): Estimate {\n const bounds = interval.mul([probability.low, probability.high], [count.low, count.high]);\n if (bounds === null) throw new Error(\"The product of two intervals that are not empty is not empty.\");\n return { value: probability.value * count.value, low: Math.max(0, bounds[0]), high: bounds[1] };\n}\n\n/**\n * This function calculates the shadow score of an incident from the priors.\n *\n * - An observed event has the basis `event`. The harm under an alert counts each alert, also the alerts with no event.\n * Thus it is too low for an event that occurs.\n * - Else an incident with a significance has the basis `alert` when the priors give the harm under its alerts. The\n * longest prefix of the kind with a measure of that significance decides.\n * - Else the basis is `event`. The probability of a warning is the verified share of the warnings of its kind. The\n * measure of the warnings is data, so it decides over the certainty word of the sender.\n * - Else the probability is that of the certainty of the incident.\n * - The deaths and the injuries of one event come from the longest prefix of the kind with each field.\n * - The expected harm is the probability times the deaths and times the injuries (`expectedOf`).\n *\n * A factor that the priors do not give makes a score with no read. The score names each missing factor.\n */\nexport function shadowScore(incident: Pick<Incident, \"kind\" | \"certainty\">, priors: ScorePriors): ShadowScore {\n const code = incident.kind.code;\n const significance = incident.kind.significance;\n const under = incident.certainty === \"observed\" || significance === undefined ? undefined : underOf(priors, code, significance);\n if (under !== undefined && significance !== undefined) {\n const from = { table: \"under\", key: under.key, significance, area: under.prior.area } as const;\n const { deaths, injuries } = under.prior;\n return { read: true, basis: \"alert\", deaths: { estimate: deaths, from }, injuries: { estimate: injuries, from }, expected: { deaths, injuries } };\n }\n const verified = incident.certainty !== \"observed\" && incident.kind.significance === \"warning\" ? kindFactor(priors, code, \"verified\") : undefined;\n const probability = verified ?? certaintyFactor(priors, incident.certainty);\n const deaths = kindFactor(priors, code, \"deaths\");\n const injuries = kindFactor(priors, code, \"injuries\");\n if (probability !== undefined && deaths !== undefined && injuries !== undefined) {\n const expected = { deaths: expectedOf(probability.estimate, deaths.estimate), injuries: expectedOf(probability.estimate, injuries.estimate) };\n return { read: true, basis: \"event\", probability, deaths, injuries, expected };\n }\n const missing: ScoreGap[] = [];\n if (probability === undefined) missing.push(\"probability\");\n if (deaths === undefined) missing.push(\"deaths\");\n if (injuries === undefined) missing.push(\"injuries\");\n return { read: false, missing };\n}\n\n/**\n * This function gives the assessment of `assess`, with the shadow score as its last reason. The score\n * does not change the level or the other reasons. An assessment with no reason of the table gets no\n * score. Examples are an ended incident, a status that the policy does not send and an incident with no match.\n */\nexport function assessWithShadow(\n incident: Incident,\n person: PersonWatch,\n places: readonly WatchedPlace[],\n priors: ScorePriors,\n policy: AssessPolicy = DEFAULT_ASSESS_POLICY,\n at?: Instant,\n): Assessment {\n const assessment = assess(incident, person, places, policy, at);\n if (!assessment.reasons.some((reason) => reason.kind === \"table\")) return assessment;\n return { ...assessment, reasons: [...assessment.reasons, { kind: \"shadow\", score: shadowScore(incident, priors) }] };\n}\n\n// True when each expected measure of `a` is above that of `b`, and the intervals do not overlap.\nfunction harmAbove(a: ExpectedHarm, b: ExpectedHarm): boolean {\n return a.deaths.low > b.deaths.high && a.injuries.low > b.injuries.high;\n}\n\n/**\n * This function gives each difference between the table and the shadow score. In a difference, the table gives\n * `above` the higher level, and the score of `below` is higher on each measure with no overlap. Thus the function\n * needs no weight between a death and an injury.\n *\n * - An incident with the level `none` or with a score with no read is in no difference.\n * - The differences are in the code-point order of `above`, then of `below`. Thus the order of the input does not change them.\n */\nexport function shadowDifferences(incidents: readonly ScoredIncident[]): ShadowDifference[] {\n const scored = incidents.flatMap((incident) =>\n incident.level === \"none\" || incident.shadow?.read !== true ? [] : [{ anchor: incident.anchor, rank: LEVELS.indexOf(incident.level), expected: incident.shadow.expected }],\n );\n const differences: ShadowDifference[] = [];\n for (const high of scored) {\n for (const low of scored) if (high.rank > low.rank && harmAbove(low.expected, high.expected)) differences.push({ above: high.anchor, below: low.anchor });\n }\n return differences.sort((a, b) => compareCodeUnits(a.above, b.above) || compareCodeUnits(a.below, b.below));\n}\n","/**\n * The escalation of one level of one incident to one person. It is a pure calculation. Its input\n * is the policy, the deliveries and the acknowledgments of the merge state, and the time. Its\n * output is the state, the sends that are due, the cancels and the time of the next decision. It\n * reads no channel and no clock: the runtime gives `now`, and starts it again at `wakeAt` or when the\n * merge state changes.\n *\n * `ESCALATION_MACHINE` is the machine document of the escalation, in the format of\n * `@mark1russell7/algebra`. Each plan gives its transitions, and a replay against the document\n * finds a transition that the document does not permit.\n */\n\nimport type { Machine, Transition } from \"@mark1russell7/algebra\";\nimport { firstInstantOf, inWindow, localTime, windowProblems } from \"@mark1russell7/algebra/clock\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { LEVELS } from \"./contracts.ts\";\nimport type {\n Acknowledgment,\n ChannelDescriptor,\n DailyTime,\n ChannelId,\n Delivery,\n Duration,\n EscalationPolicy,\n Incident,\n Instant,\n Level,\n PersonId,\n QuietWindow,\n ReportId,\n} from \"./contracts.ts\";\nimport type { MessageKeyInput } from \"./ids.ts\";\n\n/**\n * The state of an escalation.\n * - `idle`: no step is due.\n * - `sent`: one or more steps are due, and one or more steps are not due.\n * - `last`: each step is due. The time to the exhaustion runs.\n * - `exhausted`: no acknowledgment came in the time of the policy. This is a system alert.\n * - `acknowledged`: the person acknowledged, by a channel or by the UI.\n * - `ended`: the incident is over, by its expiry or by its cancel.\n */\nexport type EscalationState = \"idle\" | \"sent\" | \"last\" | \"exhausted\" | \"acknowledged\" | \"ended\";\n\n/** The events of the escalation machine. */\nexport const ESCALATION_EVENTS: {\n readonly step: \"timer.step\";\n readonly exhaust: \"timer.exhaust\";\n readonly ack: \"app.ack\";\n readonly end: \"app.end\";\n} = { step: \"timer.step\", exhaust: \"timer.exhaust\", ack: \"app.ack\", end: \"app.end\" };\n\n/** The machine document of the escalation. `escalate` makes only the transitions of this document. */\nexport const ESCALATION_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"alerts.escalation\",\n title: \"The escalation of one level of one incident to one person, until an acknowledgment\",\n layer: \"self\",\n version: \"1\",\n sources: [{ ref: \"docs/CONTRACTS.md of the alerts repository: the channel contract and the delivery promise\", rung: \"derived\" }],\n states: {\n idle: { initial: true, note: \"no step is due\" },\n sent: { note: \"one or more steps are due, and one or more steps are not due\" },\n last: { note: \"each step is due, and the exhaust timer runs\" },\n exhausted: { note: \"no acknowledgment came in the time of the policy. An acknowledgment or the end still stops the repeats\" },\n acknowledged: { final: true },\n ended: { final: true, note: \"the incident is over, by its expiry or by its cancel\" },\n },\n events: {\n \"timer.step\": { kind: \"timer\", note: \"the time of the next step of the policy\" },\n \"timer.exhaust\": { kind: \"timer\", note: \"the end of the time after the last step\" },\n \"app.ack\": { kind: \"app\", note: \"an acknowledgment in the merge state, from a channel or from the UI\" },\n \"app.end\": { kind: \"app\", note: \"the expiry or the cancel of the incident\" },\n },\n knobs: {\n step_at: { key: \"EscalationStep.at\", scope: \"policy\", unit: \"ms\", default: null, note: \"the time from the start to the first step\" },\n step_wait: { key: \"the time from one step of the policy to the next\", scope: \"policy\", unit: \"ms\", default: null, note: \"the policy gives one for each step. At a rank above 0, the rank floor of a channel changes it\" },\n rank_wait: {\n key: \"rank × max(the rank delay of the level, the rank floor of the channel of the step)\",\n scope: \"cell\",\n unit: \"ms\",\n default: null,\n note: \"a copy waits for its rank before each send. The rank delay of a level can be 0, then each copy sends a step of a channel with no floor at once\",\n },\n exhausted_after: { key: \"EscalationPolicy.exhaustedAfter\", scope: \"policy\", unit: \"ms\", default: null },\n },\n timers: {\n first: {\n duration: { expr: \"step_at + rank_wait\", unit: \"ms\" },\n arms: [\"enter:idle\"],\n cancels: [\"app.ack\", \"app.end\"],\n fires: \"timer.step\",\n note: \"the time from the start to the first step\",\n },\n next: {\n duration: { knob: \"step_wait\", unit: \"ms\" },\n arms: [\"timer.step\"],\n cancels: [\"app.ack\", \"app.end\", \"enter:last\"],\n fires: \"timer.step\",\n note: \"the time from one step to the next\",\n },\n exhaust: {\n duration: { knob: \"exhausted_after\", unit: \"ms\" },\n arms: [\"enter:last\"],\n cancels: [\"app.ack\", \"app.end\"],\n fires: \"timer.exhaust\",\n note: \"it does not arm in the silent mode of a mute: a quiet message asks for no acknowledgment\",\n },\n },\n transitions: [\n { id: \"es.first\", from: \"idle\", to: \"sent\", on: \"timer.step\", note: \"the first step of a policy with two or more steps\" },\n { id: \"es.only\", from: \"idle\", to: \"last\", on: \"timer.step\", note: \"the step of a policy with one step\" },\n { id: \"es.next\", from: \"sent\", to: \"sent\", on: \"timer.step\" },\n { id: \"es.last\", from: \"sent\", to: \"last\", on: \"timer.step\" },\n { id: \"es.exhaust\", from: \"last\", to: \"exhausted\", on: \"timer.exhaust\" },\n { id: \"es.none\", from: \"idle\", to: \"exhausted\", on: \"timer.exhaust\", note: \"a policy with no step: nothing reaches the person\" },\n { id: \"es.ack\", from: \"*\", to: \"acknowledged\", on: \"app.ack\" },\n { id: \"es.end\", from: \"*\", to: \"ended\", on: \"app.end\" },\n ],\n};\n\n/** The input of `escalate`. */\nexport interface EscalationInput {\n readonly policy: EscalationPolicy;\n readonly person: PersonId;\n /** The incident. A delivery or an acknowledgment that points to one of its reports belongs to it. */\n readonly incident: Pick<Incident, \"anchor\" | \"reports\">;\n /** The time at which the level of the incident first called for this escalation. */\n readonly since: Instant;\n /** The time at which the incident is over: its expiry, or the time of its cancel. Without it, the incident is live. */\n readonly endsAt?: Instant | undefined;\n /** The deliveries of the merge state. The function keeps the deliveries of this incident, level and person. */\n readonly deliveries: readonly Delivery[];\n /**\n * The acknowledgments of the merge state. The function keeps the acknowledgments of the person for\n * this incident, at this level or above. An acknowledgment of a level also covers each lower level.\n */\n readonly acknowledgments: readonly Acknowledgment[];\n /** The delivery keys that this copy cancelled. A cancel is idempotent, so this set only prevents a second call. */\n readonly cancelled?: ReadonlySet<string> | undefined;\n /** The rank of this copy of the system, from 0. A copy waits `rank × rankDelay` before each send. */\n readonly rank?: number | undefined;\n /** The wait of one rank at the level of the policy. `rankDelayOf` gives it from the table of the levels. */\n readonly rankDelay?: Duration | undefined;\n /**\n * The least wait of one rank before a step of each channel: the rank floor. A channel with no entry has the floor 0.\n * `rankFloors` gives the floor of each exclusive channel.\n */\n readonly floors?: ReadonlyMap<ChannelId, Duration> | undefined;\n /** The quiet window of the person, from `PersonWatch.quiet`. A send below `life-safety` in the window is quiet. */\n readonly quiet?: QuietWindow | undefined;\n /**\n * The episode of the escalation: the count of the earlier ends of the escalations of the person in the incident.\n * The default is 0. Each send has it, thus `messageKey` gives new keys after an end.\n */\n readonly episode?: number | undefined;\n /**\n * True: the escalation is in the silent mode of a mute. Each send is quiet, also at `life-safety`, and the exhaust\n * timer does not arm. The caller gives the steps of the mode: `route` gives step 0 at most.\n */\n readonly silent?: boolean | undefined;\n readonly now: Instant;\n}\n\n/**\n * The wait of one rank of a copy, for each level. A level with no entry takes the default of the caller. With 0 at a\n * level, each copy sends each step of the level at once, thus a person gets one message from each copy.\n */\nexport type RankDelays = Readonly<Partial<Record<Level, Duration>>>;\n\n/** The longest rank delay of a level in a configuration: one hour. The longest rank floor is the same. */\nexport const RANK_DELAY_LIMIT: Duration = 60 * 60_000;\n\n/**\n * This function gives the rank floor of each exclusive channel: `floor`. A person takes one message of such a channel at a\n * time. Thus a copy with a rank above 0 waits for the delivery of rank 0 before its step of the channel.\n */\nexport function rankFloors(channels: readonly ChannelDescriptor[], floor: Duration | undefined): ReadonlyMap<ChannelId, Duration> {\n return new Map(floor === undefined ? [] : channels.filter((channel) => channel.exclusive === true).map((channel) => [channel.id, floor] as const));\n}\n\n/** This function gives the problems of a rank floor: it is a whole number of milliseconds up to `RANK_DELAY_LIMIT`. */\nexport function rankFloorProblems(floor: Duration | undefined): string[] {\n return floor === undefined || (Number.isInteger(floor) && floor >= 0 && floor <= RANK_DELAY_LIMIT)\n ? []\n : [`The rank floor is not a whole number of milliseconds from 0 to ${RANK_DELAY_LIMIT}.`];\n}\n\n/** This function gives the rank delay of a level: its entry in the table, or else the default. */\nexport function rankDelayOf(level: Level, delays: RankDelays | undefined, fallback: Duration | undefined): Duration | undefined {\n return delays?.[level] ?? fallback;\n}\n\n/** This function gives the problems of a table of rank delays. Each problem names a level, and each value is a whole number of milliseconds up to `RANK_DELAY_LIMIT`. */\nexport function rankDelayProblems(delays: RankDelays): string[] {\n return Object.entries(delays).flatMap(([level, delay]) =>\n delay !== undefined && Number.isInteger(delay) && delay >= 0 && delay <= RANK_DELAY_LIMIT ? [] : [`The rank delay of the level ${level} is not a whole number of milliseconds from 0 to ${RANK_DELAY_LIMIT}.`],\n );\n}\n\n/** A send that is due. The runtime makes the delivery key with `messageKey` of this value. */\nexport interface EscalationSend extends MessageKeyInput {\n readonly channel: ChannelId;\n /** The time at which the step became due. It holds `wait`. */\n readonly due: Instant;\n /** The wait of the rank of this copy before the send: `rank × max(rankDelay, floor)` for the channel. At 0, each copy sends the step at once. */\n readonly wait: Duration;\n /** True: the channel sends in its silent mode. The value is for a send at `now`. `Message.quiet` takes it. */\n readonly quiet: boolean;\n}\n\n/** The output of `escalate`. */\nexport interface EscalationPlan {\n readonly state: EscalationState;\n /** The start of the escalation: the earliest of `since` and the start that each delivery of the ledger shows. */\n readonly start: Instant;\n /** The indexes of the steps that are due, in the order of their times. */\n readonly due: readonly number[];\n /** The steps that are due and have no delivery in the ledger. Only `sent`, `last` and `exhausted` have sends. */\n readonly sends: readonly EscalationSend[];\n /** The deliveries to cancel, after an acknowledgment or the end. Each one has a different key. */\n readonly cancels: readonly Delivery[];\n /** The time of the next decision. It is absent when only an acknowledgment or the end can change the state. */\n readonly wakeAt?: Instant;\n /** The first acknowledgment of the person. */\n readonly acknowledgment?: Acknowledgment;\n /** The time of the exhaustion, when it occurred. */\n readonly exhaustedAt?: Instant;\n /** Each transition from the start to `now`. The instance is the anchor, the level and the person. */\n readonly transitions: readonly Transition[];\n}\n\ninterface Event {\n readonly at: Instant;\n readonly on: (typeof ESCALATION_EVENTS)[keyof typeof ESCALATION_EVENTS];\n /** At one time, an acknowledgment comes first, then the end, then the steps, then the exhaustion. */\n readonly order: number;\n readonly step: number;\n}\n\nconst FINAL: ReadonlySet<EscalationState> = new Set([\"acknowledged\", \"ended\"]);\nconst ACTIVE: ReadonlySet<EscalationState> = new Set([\"sent\", \"last\", \"exhausted\"]);\n\n/**\n * This function calculates the escalation at `now`. It is pure and total: the same input gives\n * the same plan, and it does not throw. Two copies of the system with the same merge state give the\n * same plan, apart from the wait of their rank.\n *\n * - A step is due at `start + step.at + wait`. The wait of a step is `rank × max(rankDelay, floor)`, with the floor of\n * the channel of the step. Each due step without a delivery in the ledger is a send, also a late one. The system\n * prefers a duplicate to a miss.\n * - An acknowledgment stops the sends, and each delivery becomes a cancel. The end does the same.\n * - The exhaustion comes `exhaustedAfter` after the latest due time of a step. The repeats continue after it.\n * - A failed send makes no delivery, so its step stays due and the next plan sends it again.\n * - The delivery is at least once, not exactly once. A crash after a send and before its record\n * gives a second send with the same `messageKey`. A channel that drops a repeated key drops it.\n * - A send below `life-safety` at `now` in the quiet window of the person is quiet. A send of\n * `life-safety` is not quiet in the window.\n * - In the silent mode of a mute, each send is quiet, also at `life-safety`, and the exhaustion does not come.\n */\nexport function escalate(input: EscalationInput): EscalationPlan {\n const { policy, person, incident, now } = input;\n const level = policy.level;\n const reports = new Set<string>([incident.anchor, ...incident.reports]);\n const ours = (item: { readonly incident: ReportId; readonly level: Level; readonly person: PersonId }): boolean =>\n reports.has(item.incident) && item.level === level && item.person === person;\n const deliveries = input.deliveries.filter(ours);\n const least = LEVELS.indexOf(level);\n const covers = (ack: Acknowledgment): boolean => reports.has(ack.incident) && ack.person === person && LEVELS.indexOf(ack.level) >= least;\n const acknowledgment = input.acknowledgments.filter(covers).sort(byTimeThenVia)[0];\n const steps = policy.steps;\n const rank = nonNegative(input.rank);\n const delay = nonNegative(input.rankDelay);\n // Each step has its wait: a step of an exclusive channel waits at least the floor of the channel for each rank.\n const waits = steps.map((step) => rank * Math.max(delay, nonNegative(input.floors?.get(step.channel))));\n const silent = input.silent === true;\n const quiet = silent || (level !== \"life-safety\" && inQuietWindow(input.quiet, now));\n\n // A step time that is not a number of 0 or more counts as 0: escalationProblems reports it, and a send comes early, not late.\n const offsets = steps.map((step) => nonNegative(step.at));\n\n // Another copy can have started first. Its deliveries show its start.\n let start = Number.isFinite(input.since) ? input.since : now;\n for (const delivery of deliveries) {\n const offset = offsets[delivery.step];\n if (offset !== undefined && Number.isFinite(delivery.at)) start = Math.min(start, delivery.at - offset);\n }\n\n const dueAt = offsets.map((offset, index) => offset + (waits[index] ?? 0));\n const events: Event[] = dueAt.map((at, index) => ({ at: start + at, on: ESCALATION_EVENTS.step, order: 2, step: index }));\n // The latest due time of a step. A policy with no step has the wait of the rank delay.\n const lastAt = Math.max(rank * delay, ...dueAt);\n // A quiet message asks for no acknowledgment, thus the silent mode has no exhaustion.\n if (!silent) events.push({ at: start + lastAt + nonNegative(policy.exhaustedAfter), on: ESCALATION_EVENTS.exhaust, order: 3, step: -1 });\n // An acknowledgment in the merge state occurred, also when the clock of its copy is ahead or broken.\n if (acknowledgment !== undefined) {\n events.push({ at: Number.isFinite(acknowledgment.at) ? Math.min(acknowledgment.at, now) : now, on: ESCALATION_EVENTS.ack, order: 0, step: -1 });\n }\n if (input.endsAt !== undefined && Number.isFinite(input.endsAt)) events.push({ at: input.endsAt, on: ESCALATION_EVENTS.end, order: 1, step: -1 });\n events.sort((a, b) => a.at - b.at || a.order - b.order || a.step - b.step);\n\n // An episode that is not a whole number above 0 counts as 0.\n const episode = input.episode !== undefined && Number.isSafeInteger(input.episode) && input.episode > 0 ? input.episode : 0;\n const instance = `${incident.anchor} ${level} ${person}${episode === 0 ? \"\" : ` ${episode}`}`;\n const transitions: Transition[] = [];\n const due: number[] = [];\n let state: EscalationState = \"idle\";\n let wakeAt: Instant | undefined;\n let exhaustedAt: Instant | undefined;\n const move = (event: Event, to: EscalationState): void => {\n transitions.push({ machine: ESCALATION_MACHINE.id, instance, from: state, on: event.on, to, at: event.at });\n state = to;\n };\n\n for (const event of events) {\n if (FINAL.has(state)) break;\n if (event.at > now) {\n wakeAt = event.at;\n break;\n }\n if (event.on === ESCALATION_EVENTS.step) {\n due.push(event.step);\n move(event, due.length === steps.length ? \"last\" : \"sent\");\n } else if (event.on === ESCALATION_EVENTS.exhaust) {\n exhaustedAt = event.at;\n move(event, \"exhausted\");\n } else {\n move(event, event.on === ESCALATION_EVENTS.ack ? \"acknowledged\" : \"ended\");\n }\n }\n\n const delivered = new Set(deliveries.map((delivery) => delivery.step));\n const sends: EscalationSend[] = ACTIVE.has(state)\n ? due.flatMap((index) => {\n const step = steps[index];\n const wait = waits[index] ?? 0;\n return step === undefined || delivered.has(index)\n ? []\n : [{ incident: incident.anchor, level, person, step: index, ...(episode === 0 ? {} : { episode }), channel: step.channel, due: start + (dueAt[index] ?? 0), wait, quiet }];\n })\n : [];\n\n const cancels: Delivery[] = [];\n if (FINAL.has(state)) {\n const seen = new Set<string>(input.cancelled ?? []);\n for (const delivery of [...deliveries].sort((a, b) => byTime(a.at, b.at) || compareCodeUnits(a.key, b.key))) {\n if (seen.has(delivery.key)) continue;\n seen.add(delivery.key);\n cancels.push(delivery);\n }\n }\n\n return {\n state,\n start,\n due,\n sends,\n cancels,\n ...(wakeAt === undefined ? {} : { wakeAt }),\n ...(acknowledgment === undefined ? {} : { acknowledgment }),\n ...(exhaustedAt === undefined ? {} : { exhaustedAt }),\n transitions,\n };\n}\n\n/**\n * This function gives the problems of a policy. `escalate` accepts each policy, but a policy with a\n * problem does not do what its author meant.\n */\nexport function escalationProblems(policy: EscalationPolicy): string[] {\n const problems: string[] = [];\n if (policy.steps.length === 0) problems.push(`The policy of ${policy.level} has no step, so nothing reaches the person.`);\n policy.steps.forEach((step, index) => {\n if (!Number.isFinite(step.at) || step.at < 0) problems.push(`Step ${index} has the time ${step.at}. A time is 0 or more.`);\n const before = policy.steps[index - 1];\n if (before !== undefined && step.at < before.at) problems.push(`Step ${index} comes before step ${index - 1}.`);\n });\n if (!Number.isFinite(policy.exhaustedAfter) || policy.exhaustedAfter < 0) problems.push(`exhaustedAfter is ${policy.exhaustedAfter}. It is 0 or more.`);\n return problems;\n}\n\n/**\n * This function tells if the time `at` is in the quiet window. It is `inWindow` of\n * `@mark1russell7/algebra/clock`. Thus the window follows the clock of the person when daylight\n * saving time starts or ends. The start is in the window, and the end is not. An end before the\n * start crosses midnight, and an end equal to the start gives the full day.\n *\n * The function does not throw. An absent window, a bad time zone, a bad local time or a bad `at`\n * gives `false`. A message that is not quiet is louder than the person wants, but it is not a miss.\n * `quietWindowProblems` finds a bad window.\n */\nexport function inQuietWindow(window: QuietWindow | undefined, at: Instant): boolean {\n return window !== undefined && inWindow(at, window);\n}\n\n/** This function gives the problems of a quiet window: a bad time zone or a bad local time. With a problem, `inQuietWindow` gives `false`. */\nexport function quietWindowProblems(window: QuietWindow): string[] {\n return windowProblems(window);\n}\n\n/** The form of a local time of each day: `HH:MM`, from `00:00` to `23:59`. */\nconst DAILY_FORM = /^([01][0-9]|2[0-3]):([0-5][0-9])$/u;\n\n/** One day of 24 hours on the wall clock, in milliseconds. */\nconst WALL_DAY = 86_400_000;\n\n/** This function gives the problems of a daily time: a bad time zone or a bad local time. */\nexport function dailyTimeProblems(daily: DailyTime): string[] {\n const problems: string[] = [];\n if (localTime(0, daily.zone) === undefined) problems.push(`The time zone ${daily.zone} is not an IANA time zone.`);\n if (!DAILY_FORM.test(daily.time)) problems.push(`The time ${daily.time} is not a local time HH:MM from 00:00 to 23:59.`);\n return problems;\n}\n\n/**\n * This function gives the instant of a daily time near `at`. It is the last one at or before `at`. With `next`, it is\n * the first one after `at`. A bad daily time or a bad `at` gives `undefined`, and `dailyTimeProblems` finds the bad time.\n *\n * - A local time in the gap of a change forward gives the end of the gap. Thus each day has its instant.\n * - A local time in the hour of a change back occurs two times. Only the first instant counts.\n */\nexport function dailyInstant(daily: DailyTime, at: Instant, next = false): Instant | undefined {\n const form = DAILY_FORM.exec(daily.time);\n const local = form === null || !Number.isFinite(at) ? undefined : localTime(at, daily.zone);\n if (form === null || local === undefined) return undefined;\n const wall = Date.UTC(local.year, local.month - 1, local.day, Number(form[1]), Number(form[2]));\n // The wall clock of today, then of the day before or after. A day of 23 or 25 hours moves the instant by one hour at most.\n for (let days = 0; days <= 2; days += 1) {\n const instant = firstInstantOf(wall + (next ? days : -days) * WALL_DAY, daily.zone);\n if (instant !== undefined && (next ? instant > at : instant <= at)) return instant;\n }\n return undefined;\n}\n\n/**\n * This function gives the daily time of the digest of a person. It is the time of the digest policy, or else the end\n * of the quiet window of the person. With neither, it gives `undefined`, and the person gets no digest.\n */\nexport function digestTimeOf(policy: EscalationPolicy, quiet: QuietWindow | undefined): DailyTime | undefined {\n return policy.daily ?? (quiet === undefined ? undefined : { zone: quiet.zone, time: quiet.end });\n}\n\nconst nonNegative = (value: number | undefined): number => (value !== undefined && Number.isFinite(value) && value > 0 ? value : 0);\n\n/** This order puts a time that is not a number last, so the order of the input has no effect. */\nconst byTime = (a: number, b: number): number => {\n const x = Number.isFinite(a) ? a : Number.POSITIVE_INFINITY;\n const y = Number.isFinite(b) ? b : Number.POSITIVE_INFINITY;\n return x < y ? -1 : x > y ? 1 : 0;\n};\n\nfunction byTimeThenVia(a: Acknowledgment, b: Acknowledgment): number {\n return byTime(a.at, b.at) || compareCodeUnits(a.via, b.via);\n}\n","/**\n * The chain of tries: the escalation of one person when no timer runs. The end of each try starts\n * the next try, so a function with no state can make each step. The outage call of the outside\n * heartbeat uses it. The instance is down then, so a function on the server of the call provider\n * operates the chain.\n *\n * `CHAIN_MACHINE` is the machine document of the chain, in the format of `@mark1russell7/algebra`.\n * `chainRun` makes only its transitions. `outageAudit` compares each outage with the records of\n * the tries, and finds each person with no confirmed try.\n */\n\nimport type { Machine, Transition } from \"@mark1russell7/algebra\";\nimport type { ChannelId, Duration, Instant, PersonId } from \"./contracts.ts\";\n\n/**\n * The end of one try.\n * - `acked`: the person confirmed the message, for example with a key press.\n * - `unconfirmed`: the try reached the address, and no person confirmed it. Busy, no answer, a voicemail and a hang-up with no key press are unconfirmed.\n * - `failed`: the try did not reach the address, for example a failed call or a refused number.\n * - `sent`: a channel with no confirmation accepted the message, for example a text message.\n */\nexport type TryEnd = \"acked\" | \"unconfirmed\" | \"failed\" | \"sent\";\n\n/** The ends of a try, in a fixed order. */\nexport const TRY_ENDS: readonly TryEnd[] = [\"acked\", \"unconfirmed\", \"failed\", \"sent\"];\n\n/** The chain of one person: the channel of each try, in order. Each try starts at the end of the try before it. */\nexport interface TryChain {\n readonly steps: readonly ChannelId[];\n}\n\n/**\n * The state of a chain.\n * - `trying`: the try `step` on `channel` runs.\n * - `acked`: the person confirmed the try `step`. No try follows.\n * - `exhausted`: each try ended with no confirmation. No try follows, and the audit reports it.\n */\nexport type ChainState =\n | { readonly kind: \"trying\"; readonly step: number; readonly channel: ChannelId }\n | { readonly kind: \"acked\"; readonly step: number }\n | { readonly kind: \"exhausted\" };\n\n/** The machine document of the chain. `chainRun` makes only the transitions of this document. */\nexport const CHAIN_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"alerts.chain\",\n title: \"The tries of one person when no timer runs, until a confirmation\",\n layer: \"self\",\n version: \"1\",\n sources: [{ ref: \"docs/CONTRACTS.md of the alerts repository: the chain of tries\", rung: \"derived\" }],\n states: {\n start: { initial: true, note: \"no try started\" },\n trying: { note: \"one try runs\" },\n acked: { final: true, note: \"the person confirmed a try\" },\n exhausted: { final: true, note: \"each try ended with no confirmation\" },\n },\n events: {\n \"app.start\": { kind: \"app\", note: \"the start of the chain, for example the webhook of the outside check\" },\n \"app.acked\": { kind: \"app\", note: \"the person confirmed the try\" },\n \"app.unconfirmed\": { kind: \"app\", note: \"the try reached the address, and no person confirmed it\" },\n \"app.failed\": { kind: \"app\", note: \"the try did not reach the address\" },\n \"app.sent\": { kind: \"app\", note: \"a channel with no confirmation accepted the message\" },\n },\n knobs: {},\n timers: {},\n transitions: [\n { id: \"ch.start\", from: \"start\", to: \"trying\", on: \"app.start\" },\n { id: \"ch.none\", from: \"start\", to: \"exhausted\", on: \"app.start\", note: \"a chain with no step: nothing reaches the person\" },\n { id: \"ch.ack\", from: \"trying\", to: \"acked\", on: \"app.acked\" },\n { id: \"ch.next.unconfirmed\", from: \"trying\", to: \"trying\", on: \"app.unconfirmed\" },\n { id: \"ch.next.failed\", from: \"trying\", to: \"trying\", on: \"app.failed\" },\n { id: \"ch.next.sent\", from: \"trying\", to: \"trying\", on: \"app.sent\" },\n { id: \"ch.last.unconfirmed\", from: \"trying\", to: \"exhausted\", on: \"app.unconfirmed\" },\n { id: \"ch.last.failed\", from: \"trying\", to: \"exhausted\", on: \"app.failed\" },\n { id: \"ch.last.sent\", from: \"trying\", to: \"exhausted\", on: \"app.sent\" },\n ],\n};\n\n/**\n * This function gives the next state of a chain. Without `end`, it gives the start. With `end`, it\n * gives the state after the try `step`. A step that the chain does not have gives `exhausted`, so an\n * old or false step starts no try.\n */\nexport function chainNext(chain: TryChain, step?: number, end?: TryEnd): ChainState {\n if (step === undefined || end === undefined) return tryAt(chain, 0);\n if (!Number.isSafeInteger(step) || step < 0 || step >= chain.steps.length) return { kind: \"exhausted\" };\n if (end === \"acked\") return { kind: \"acked\", step };\n return tryAt(chain, step + 1);\n}\n\nfunction tryAt(chain: TryChain, step: number): ChainState {\n const channel = chain.steps[step];\n return channel === undefined ? { kind: \"exhausted\" } : { kind: \"trying\", step, channel };\n}\n\n/** The end of one try at a time. */\nexport interface TimedEnd {\n readonly end: TryEnd;\n readonly at: Instant;\n}\n\n/** The result of `chainRun`. */\nexport interface ChainRun {\n readonly state: ChainState;\n /** The count of the tries that started. It is at most the count of the steps of the chain. */\n readonly tries: number;\n /** The transitions, in the format of `@mark1russell7/algebra`, for a replay against `CHAIN_MACHINE`. */\n readonly transitions: readonly Transition[];\n /** The count of the ends after a final state. Each one is a fault of the records, because no try was open. */\n readonly extra: number;\n}\n\n/** This function gives the state of a chain that started at `start`, after the ends of its tries in order. It is a fold of `chainNext`. */\nexport function chainRun(chain: TryChain, start: Instant, ends: readonly TimedEnd[], instance: string): ChainRun {\n const transitions: Transition[] = [];\n let state = chainNext(chain);\n transitions.push({ machine: CHAIN_MACHINE.id, instance, from: \"start\", on: \"app.start\", to: state.kind, at: start });\n let tries = state.kind === \"trying\" ? 1 : 0;\n let extra = 0;\n for (const { end, at } of ends) {\n if (state.kind !== \"trying\") {\n extra += 1;\n continue;\n }\n const next = chainNext(chain, state.step, end);\n transitions.push({ machine: CHAIN_MACHINE.id, instance, from: \"trying\", on: `app.${end}`, to: next.kind, at });\n if (next.kind === \"trying\") tries += 1;\n state = next;\n }\n return { state, tries, transitions, extra };\n}\n\n/** One outage of the instance: the time at which the outside check went down, and the time at which it came up. */\nexport interface Outage {\n readonly down: Instant;\n readonly up?: Instant;\n}\n\n/** The record of one try of one person, from the records of the provider. */\nexport interface TryRecord {\n readonly person: PersonId;\n readonly started: Instant;\n readonly end: TryEnd;\n /** The time of the end of the try. */\n readonly at: Instant;\n}\n\n/**\n * The reach of one outage to one person.\n * - `acked`: the person confirmed a try.\n * - `exhausted`: each try ended with no confirmation.\n * - `open`: the records end before the chain does.\n * - `untried`: no try started. The webhook of the check or the start of the chain failed.\n */\nexport interface OutageReach {\n readonly down: Instant;\n readonly person: PersonId;\n readonly state: \"acked\" | \"exhausted\" | \"open\" | \"untried\";\n /** The count of the records of tries. A count above the count of the steps of the chain is a fault: the provider made more tries than the chain permits. */\n readonly tries: number;\n /** The time of the confirmation, when the state is `acked`. */\n readonly ackedAt?: Instant;\n}\n\n/**\n * This function gives the reach of each outage to each person. The tries of an outage are the records\n * that start in the time `within` after its down time, and before the next down time. Each reach that\n * is not `acked` is a fault of the outage call.\n */\nexport function outageAudit(outages: readonly Outage[], chains: ReadonlyMap<PersonId, TryChain>, records: readonly TryRecord[], within: Duration): OutageReach[] {\n const downs = [...outages].sort((a, b) => a.down - b.down);\n return downs.flatMap((outage, index) => {\n const until = Math.min(outage.down + within, downs[index + 1]?.down ?? Number.POSITIVE_INFINITY);\n return [...chains].map(([person, chain]): OutageReach => {\n const own = records.filter((record) => record.person === person && record.started >= outage.down && record.started < until).sort((a, b) => a.started - b.started);\n if (own.length === 0) return { down: outage.down, person, state: \"untried\", tries: 0 };\n const run = chainRun(chain, outage.down, own, `${outage.down} ${person}`);\n const tries = own.length;\n if (run.state.kind === \"acked\") return { down: outage.down, person, state: \"acked\", tries, ackedAt: own[run.state.step]!.at };\n return { down: outage.down, person, state: run.state.kind === \"exhausted\" ? \"exhausted\" : \"open\", tries };\n });\n });\n}\n","// The runs of failed calls of the channels and the policy of a down channel (AL-65, `docs/CONTRACTS.md`).\n\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { ChannelFailureKind, ChannelId, Duration, Instant, NodeKey } from \"./contracts.ts\";\n\n/**\n * The kinds of a failed call that count in the run of a channel. The other kinds are facts of a person, a message or a\n * quota: `consent`, `quiet`, `expired`, `refused`, `reserved` and `rate-limited`. The quota lines tell of a limit.\n */\nexport const COUNTED_FAILURES: readonly ChannelFailureKind[] = [\"network\", \"timeout\", \"server\", \"auth\"];\n\n/**\n * The calls of a channel whose failures count in its run. A failed probe counts too. Thus the probe of a quiet channel\n * finds an outage before the next message.\n */\nexport const COUNTED_CALLS: readonly string[] = [\"send\", \"status\", \"probe\"];\n\n// The kinds of a failed call that got an answer from the provider. Such a call tells that the network of the copy works.\nconst ANSWERED: readonly ChannelFailureKind[] = [\"server\", \"auth\"];\n\n/** The policy of a down channel: the run of failed calls that opens a line. */\nexport interface ChannelDownPolicy {\n /** The fewest failed calls in a run that open a line. */\n readonly failures: number;\n /** The shortest time from the first to the last failed call of a run that opens a line. Thus one burst opens no line. */\n readonly span: Duration;\n}\n\n/** The policy of a down channel when the configuration gives no value: 3 failed calls in at least 60 s. */\nexport const DEFAULT_CHANNEL_DOWN: ChannelDownPolicy = { failures: 3, span: 60_000 };\n\n/** The policy of a down channel in the configuration. Each absent field has its value of `DEFAULT_CHANNEL_DOWN`. */\nexport interface ChannelDownConfig {\n readonly failures?: number;\n readonly span?: Duration;\n}\n\n/** This function gives the policy of a down channel from the configuration, with the defaults for the absent fields. */\nexport function channelDownPolicy(config?: ChannelDownConfig): ChannelDownPolicy {\n return { failures: config?.failures ?? DEFAULT_CHANNEL_DOWN.failures, span: config?.span ?? DEFAULT_CHANNEL_DOWN.span };\n}\n\n/** The run of failed calls of one channel of a copy since its last good call. The runtime keeps it in memory. */\nexport interface ChannelRun {\n readonly channel: ChannelId;\n /** The count of the failed calls of the run. */\n readonly failures: number;\n /** The time of the first failed call. A line of the run has this onset. */\n readonly first: Instant;\n /** The time of the last failed call. */\n readonly last: Instant;\n /** The kind of the last failed call. */\n readonly kind: ChannelFailureKind;\n /**\n * True when the network of the copy worked during the run. Then a call of the run got an answer from the provider. Or a\n * source fetched with success after the first failed call, and a later call failed. A run with no such fact opens no\n * line, because the copy can be offline. The outside check of the copy tells of that.\n */\n readonly reached: boolean;\n}\n\n/** One failed call of a channel in a step of the delivery. */\nexport interface ChannelCallFailure {\n readonly channel: ChannelId;\n /** The call: `send`, `status`, `probe`, `cancel` or another call. Only the calls of `COUNTED_CALLS` count. */\n readonly call: string;\n readonly kind: string;\n}\n\n/** The calls of the channels in one step of the delivery of a copy. */\nexport interface ChannelRunStep {\n /** The time of the step. Each failed call of the step has this time. */\n readonly at: Instant;\n readonly failures: readonly ChannelCallFailure[];\n /** The channels with a good call in the step: an accepted send or a probe success. */\n readonly good: readonly ChannelId[];\n /** The time of the last fetch of a source with success, at the time of the step. */\n readonly lastSuccess?: Instant;\n}\n\n/**\n * This function adds one step of the delivery to the runs of the channels. It is pure, and it gives the runs in the order\n * of their channels.\n *\n * - A good call of a channel in the step ends its run. The failed calls of the same step then start no run, because the\n * provider took a call.\n * - Each failed call of a counted call and a counted kind adds to the run of its channel, or starts a run.\n * - The other failed calls change nothing.\n */\nexport function channelRuns(runs: readonly ChannelRun[], step: ChannelRunStep): ChannelRun[] {\n const { at, lastSuccess } = step;\n const good = new Set<string>(step.good);\n const next = new Map<string, ChannelRun>(runs.filter((run) => !good.has(run.channel)).map((run) => [run.channel, run]));\n for (const failure of step.failures) {\n if (good.has(failure.channel) || !COUNTED_CALLS.includes(failure.call)) continue;\n const kind = failure.kind as ChannelFailureKind;\n if (!COUNTED_FAILURES.includes(kind)) continue;\n const run = next.get(failure.channel);\n const first = run?.first ?? at;\n const online = ANSWERED.includes(kind) || (run !== undefined && lastSuccess !== undefined && lastSuccess >= run.first && lastSuccess <= at);\n next.set(failure.channel, { channel: failure.channel, failures: (run?.failures ?? 0) + 1, first, last: at, kind, reached: (run?.reached ?? false) || online });\n }\n return [...next.values()].sort((a, b) => compareCodeUnits(a.channel, b.channel));\n}\n\n/** This function tells if a run opens a line under a policy. */\nexport function runOpens(run: ChannelRun, policy: ChannelDownPolicy): boolean {\n return run.reached && run.failures >= policy.failures && run.last - run.first >= policy.span;\n}\n\n/** One channel of a copy in a snapshot of the system. */\nexport interface ChannelSnapshot {\n /** The id of the copy whose calls the run holds. Each copy has its own lines, because each copy has its own network path. */\n readonly copy: string;\n readonly channel: ChannelId;\n /** The title of the channel. The headline names it. */\n readonly title: string;\n /** The endpoints of the channel (`ChannelDescriptor.api`). The report names them, so the layer `delivery` routes it. */\n readonly api?: readonly NodeKey[];\n /** The run of failed calls since the last good call. A restart empties it, and an empty run ends no open line. */\n readonly run?: ChannelRun;\n /** The time of the last good call of the channel in the copy: an accepted send or a probe success. */\n readonly good?: Instant;\n}\n","/**\n * This module holds the steps of the wall clock. A step changes the wall clock and not the monotonic clock, for\n * example a correction of the system time. The runtime then moves each of its own instants by the size of the step.\n * Thus each own instant keeps its distance on the monotonic clock, and each timer comes at its time.\n *\n * The instants of others do not move, because they come from the clocks of the sources and the channels. They are\n * the times of a report of a source, `asOf` of an end mark and the time of an acknowledgment. The times of a report\n * of a source are `sent`, `effective`, `onset`, `expires` and `ends`. The system reports are own reports, thus each\n * of their instants moves.\n */\nimport type { Acknowledgment, Delivery, Duration, EndMark, Instant, MergeState, Report } from \"./contracts.ts\";\nimport type { EscalationEnd, EscalationStart } from \"./delivery.ts\";\nimport type { HealthTrack } from \"./health.ts\";\nimport { normalize } from \"./merge.ts\";\nimport { SYSTEM_SOURCE } from \"./contracts.ts\";\n\n/** A change of the wall clock against the monotonic clock larger than this size is a step. A smaller change is a drift. */\nexport const CLOCK_STEP_ABOVE: Duration = 2000;\n\nconst by = (instant: Instant, size: Duration): Instant => instant + size;\n\n/** This function moves the own instants of a report. A system report moves each instant. A report of a source moves only `received`. */\nexport function shiftReport(report: Report, size: Duration): Report {\n if (report.source !== SYSTEM_SOURCE) return { ...report, received: by(report.received, size) };\n return {\n ...report,\n sent: by(report.sent, size),\n received: by(report.received, size),\n ...(report.effective === undefined ? {} : { effective: by(report.effective, size) }),\n ...(report.onset === undefined ? {} : { onset: by(report.onset, size) }),\n ...(report.expires === undefined ? {} : { expires: by(report.expires, size) }),\n ...(report.ends === undefined ? {} : { ends: by(report.ends, size) }),\n };\n}\n\n/** This function moves the time of a delivery: the time at which the channel accepted the message. */\nexport function shiftDelivery(delivery: Delivery, size: Duration): Delivery {\n return { ...delivery, at: by(delivery.at, size) };\n}\n\n/** This function moves the time of an end mark. Its `asOf` is the time of the data of the source, thus it does not move. */\nexport function shiftEndMark(mark: EndMark, size: Duration): EndMark {\n return { ...mark, at: by(mark.at, size) };\n}\n\n/** This function moves the own instants of the parts of a merge state, and gives its normal form. An acknowledgment does not move. */\nexport function shiftMerge(state: MergeState, size: Duration): MergeState {\n const acks: readonly Acknowledgment[] = state.acks;\n return normalize({\n reports: state.reports.map((report) => shiftReport(report, size)),\n deliveries: state.deliveries.map((delivery) => shiftDelivery(delivery, size)),\n acks,\n ends: state.ends.map((mark) => shiftEndMark(mark, size)),\n // The runtime sets the end of a tombstone from its own clock, thus the end moves.\n retired: state.retired.map((tombstone) => ({ ...tombstone, until: by(tombstone.until, size) })),\n });\n}\n\n/** This function moves each instant of a health track. Each time of the track comes from the fetches of the runtime. */\nexport function shiftHealth(track: HealthTrack, size: Duration): HealthTrack {\n return {\n ...track,\n since: by(track.since, size),\n time: by(track.time, size),\n staleFrom: by(track.staleFrom, size),\n ...(track.quietFrom === undefined ? {} : { quietFrom: by(track.quietFrom, size) }),\n ...(track.passed === undefined ? {} : { passed: { ...track.passed, at: by(track.passed.at, size) } }),\n ...(track.lastFailure === undefined ? {} : { lastFailure: { ...track.lastFailure, at: by(track.lastFailure.at, size) } }),\n };\n}\n\n/** This function moves the time of the start of an escalation. */\nexport function shiftEscalationStart(start: EscalationStart, size: Duration): EscalationStart {\n return { ...start, at: by(start.at, size) };\n}\n\n/** This function moves the time of the end of an escalation. */\nexport function shiftEscalationEnd(end: EscalationEnd, size: Duration): EscalationEnd {\n return { ...end, at: by(end.at, size) };\n}\n","/**\n * The taxonomy of the kinds. A kind code is dotted, for example `met.flood.flash`. Its first part is a\n * category of the system. The taxonomy is a tree: the parent of each code is also a code, so\n * `met.flood` is the parent of `met.flood.flash`. Each category is a root. `parentKind` gives the parent.\n *\n * The taxonomy is closed. Each code that a map function gives must be in it, and a gate test of each\n * adapter holds this rule. A code with a typo does not match the life-safety class, so it can stop a\n * wake. The schemas of the private configuration hold the same rule for each kind that a person names.\n *\n * The source atlas (`@mark1russell7/alerts-atlas`) uses these codes as its signal classes. Each code has\n * its plain name and its summary here, and in no other place. A new code comes here first, in its pull request.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { BALANCE_KIND, CHANNEL_KIND, CLOCK_KIND, COPY_KIND, COVERAGE_KIND, DRILL_KIND, ESCALATION_KIND, HEALTH_KIND, LIMIT_KIND, LOG_KIND, QUOTA_KIND, STORE_KIND, TELL_KIND } from \"./assess.ts\";\nimport type { BalanceStage, Category, CopyStage, HealthState, QuotaStage } from \"./contracts.ts\";\n\n/** One code of the taxonomy: its plain name and one plain sentence about it. */\nexport interface KindEntry {\n /** The plain name, for example `Flash flood`. */\n readonly label: string;\n /** One plain sentence that tells what a signal of the code is. */\n readonly summary: string;\n}\n\nconst entry = (label: string, summary: string): KindEntry => ({ label, summary });\n\n// The categories of the system: the 12 categories of CAP 1.2 first, then the categories that CAP does not have.\nconst CATEGORY_ENTRIES: Readonly<Record<Category, KindEntry>> = {\n geo: entry(\"Geophysical\", \"A hazard from the solid Earth or from space: earthquakes, volcanoes, tsunamis, landslides and space weather.\"),\n met: entry(\"Weather\", \"A hazard from the weather, the water or the sea, with the products of a weather service.\"),\n safety: entry(\"Public safety\", \"A general emergency or a danger to the public, from an evacuation to a product recall.\"),\n security: entry(\"Security\", \"A threat from people: law enforcement, armed conflict, terrorism and crime.\"),\n rescue: entry(\"Rescue\", \"Rescue and recovery: search and rescue, shelters and aid after a disaster.\"),\n fire: entry(\"Fire\", \"A fire or a fire danger: wildfires, fire weather, burn bans and structure fires.\"),\n health: entry(\"Health\", \"A danger to health: outbreaks, the drug supply and the capacity of hospitals.\"),\n env: entry(\"Environment\", \"A danger from pollution or from nature: air quality, smoke, water quality, pollen and UV.\"),\n transport: entry(\"Transport\", \"A disruption or an accident of air, rail, road, sea, space or public transport.\"),\n infra: entry(\"Infrastructure\", \"A failure of a utility or a service that people depend on: power, water, telecom, internet and supply.\"),\n cbrne: entry(\"Chemical, biological, radiological and nuclear\", \"A release of a chemical, biological, radiological or nuclear agent, or an explosion.\"),\n other: entry(\"Other\", \"A signal that no other category holds, for example an event that the kind tables do not know.\"),\n cyber: entry(\"Cyber\", \"A cyber threat: an exploited flaw, an attack, a breach or a malicious package.\"),\n market: entry(\"Markets\", \"A move or a failure in finance: banks, exchanges, prices, crypto and prediction markets.\"),\n civic: entry(\"Civic\", \"An action of a government or a public body: declarations, rules, elections, closures and holidays.\"),\n personal: entry(\"Personal\", \"A change in the life of one person or one household, for example a loss of income or a death.\"),\n system: entry(\"The alert system\", \"A message of the alert system about itself: the health of a source, coverage, quota and tests.\"),\n};\n\n/** The plain name of each category of the system. Each category is also the root code of a tree. */\nexport const CATEGORY_LABELS: Readonly<Record<Category, string>> = Object.fromEntries(\n Object.entries(CATEGORY_ENTRIES).map(([category, value]) => [category, value.label]),\n) as Record<Category, string>;\n\n/** The categories of the system: the 12 categories of CAP 1.2 first, then the categories that CAP does not have. */\nexport const CATEGORIES: readonly Category[] = Object.keys(CATEGORY_ENTRIES) as Category[];\n\n/** This function gives the category of a kind code: its first part. A first part that is not a category gives `other`. */\nexport function categoryOf(kindCode: string): Category {\n const first = kindCode.split(\".\", 1)[0] ?? \"\";\n return Object.hasOwn(CATEGORY_ENTRIES, first) ? (first as Category) : \"other\";\n}\n\n/** The code of a kind that the tables of an adapter do not know. */\nexport const UNKNOWN_KIND = \"other.unknown\";\n\n// The quota kinds of the core: one for each stage of the quota of a channel.\nconst QUOTA_ENTRIES: Readonly<Record<QuotaStage, KindEntry>> = {\n low: entry(\"Low quota of a channel\", \"The window of a channel has 2 reserves of units or fewer left.\"),\n reserve: entry(\"Quota of a channel in its reserve\", \"The window of a channel has its reserve or fewer units left, so the channel sends only life-safety messages.\"),\n spent: entry(\"Spent quota of a channel\", \"The provider of a channel refuses each message, also a life-safety message.\"),\n};\n\n// The balance kinds of the core: one for each stage of the balance of a provider account.\nconst BALANCE_ENTRIES: Readonly<Record<BalanceStage, KindEntry>> = {\n low: entry(\"Low balance of a provider\", \"The balance of a paid provider account is below its floor.\"),\n empty: entry(\"Empty balance of a provider\", \"The balance of a paid provider account is 0 or less, so the provider refuses each paid message.\"),\n unread: entry(\"Balance of a provider not read\", \"No read of the balance of a paid provider account passed for the maximum age, so a low balance is not seen.\"),\n};\n\n// The copy kinds of the core: one for each stage of the watch of another copy of the system.\nconst COPY_ENTRIES: Readonly<Record<CopyStage, KindEntry>> = {\n skew: entry(\"Clock difference of a copy\", \"The clock of another copy of the alert system differs from the clock of this copy by more than the limit.\"),\n config: entry(\"Configuration difference of a copy\", \"Another copy of the alert system has a different configuration, so the copies can route an alert in two ways.\"),\n unread: entry(\"Copy not read\", \"No read of the log of another copy of the alert system passed for the maximum age, so the two copies can both send.\"),\n unsteady: entry(\"Copy not steady\", \"Another copy of the alert system starts again and again and does not get steady, so it sends no alert.\"),\n};\n\n// The health kinds of the core: one for each health state, and `late` for the lateness against another source.\nconst HEALTH_ENTRIES: Readonly<Record<HealthState | \"late\", KindEntry>> = {\n unknown: entry(\"Health of a source not known\", \"The system has no fetch of the source yet, so it does not know its health.\"),\n healthy: entry(\"Healthy source\", \"The source answers on time with valid signals.\"),\n slow: entry(\"Slow source\", \"The source answers, but slower than its usual time.\"),\n failing: entry(\"Failing source\", \"The fetches or the canary of the source fail.\"),\n silent: entry(\"Silent source\", \"The source gives no fresh observation for longer than its quiet limit, and quiet is not normal for it.\"),\n changed: entry(\"Changed format of a source\", \"A fetch passed, but the map found fatal or lossy problems: the format of the source changed.\"),\n late: entry(\"Late source\", \"The source gives a signal later than another source of the same event.\"),\n};\n\n/**\n * The codes of the taxonomy, each with its plain name and its summary. The categories come first, then\n * the codes of each category. The kinds of the core come last. The coverage codes `system.coverage.<code>`\n * are a family: `knownKind` finds them.\n */\nexport const TAXONOMY: Readonly<Record<string, KindEntry>> = {\n ...CATEGORY_ENTRIES,\n\n \"geo.avalanche\": entry(\"Avalanche\", \"Snow avalanche danger for backcountry zones, and avalanche warnings for roads and towns.\"),\n \"geo.debris-flow\": entry(\"Debris flow\", \"A fast flow of mud, rock and debris down a slope, often from heavy rain on a burn scar.\"),\n \"geo.earthquake\": entry(\"Earthquake\", \"Ground shaking from a fault rupture, reported with a location, depth and magnitude soon after the event.\"),\n \"geo.earthquake.early-warning\": entry(\"Earthquake early warning\", \"A warning sent seconds before strong shaking arrives, issued from the first seismic waves of a rupture.\"),\n \"geo.fireball\": entry(\"Fireball or airburst\", \"A bright meteor or airburst over a region, sometimes with a sonic boom or fallen meteorites.\"),\n \"geo.landslide\": entry(\"Landslide\", \"Movement of rock or earth down a slope, after heavy rain, an earthquake or a thaw.\"),\n \"geo.near-earth-object\": entry(\"Asteroid impact risk\", \"A near-Earth object with a computed non-zero impact probability, rated on the Torino and Palermo scales.\"),\n \"geo.space-debris\": entry(\"Space debris\", \"Objects in orbit that fall back to the Earth.\"),\n \"geo.space-debris.reentry\": entry(\"Space debris re-entry\", \"An uncontrolled re-entry of a satellite or rocket body, with a predicted time window and ground track.\"),\n \"geo.space-weather\": entry(\"Space weather\", \"Solar activity that disturbs the magnetosphere and ionosphere, with effects on power grids, radio, GPS and satellites.\"),\n \"geo.space-weather.geomagnetic-storm\": entry(\"Geomagnetic storm\", \"A disturbance of the Earth's magnetic field on the NOAA G scale that can stress grids and degrade GPS.\"),\n \"geo.space-weather.radio-blackout\": entry(\"Radio blackout from a solar flare\", \"An X-ray flare on the NOAA R scale that blacks out HF radio on the sunlit side of the Earth.\"),\n \"geo.space-weather.solar-radiation-storm\": entry(\"Solar radiation storm\", \"High proton flux on the NOAA S scale that affects high-latitude flights, satellites and polar radio.\"),\n \"geo.subsidence\": entry(\"Sinkhole and ground subsidence\", \"A sudden collapse or slow sinking of the ground that damages roads, pipes and buildings.\"),\n \"geo.tsunami\": entry(\"Tsunami\", \"A series of sea waves from an earthquake, landslide or eruption, with watches, advisories and warnings for coasts.\"),\n \"geo.volcano\": entry(\"Volcano\", \"Unrest or eruption of a volcano, with alert-level and aviation colour-code changes from a volcano observatory.\"),\n \"geo.volcano.ashfall\": entry(\"Ashfall\", \"Ash plumes that close airspace and ash fall that harms lungs, roofs, water and engines downwind of a volcano.\"),\n \"geo.volcano.ashfall-marine\": entry(\"Ashfall at sea\", \"Ash that falls on boats and coastal waters downwind of a volcano.\"),\n \"geo.volcano.eruption\": entry(\"Volcanic eruption\", \"A volcano erupts, with ash, lava, gas or flows that are a danger to people near it.\"),\n\n \"met.beach-hazards\": entry(\"Beach hazards\", \"Dangers at a beach, for example rip currents and high waves, as a statement of a weather service.\"),\n \"met.blowing-dust\": entry(\"Blowing dust\", \"Wind that lifts dust and cuts the visibility, less severe than a dust storm.\"),\n \"met.cold\": entry(\"Cold\", \"Dangerous cold or wind chill that harms people, animals and pipes.\"),\n \"met.cold.extreme\": entry(\"Extreme cold\", \"Cold that is a danger to life with no shelter, as an extreme cold warning.\"),\n \"met.cold.wind-chill\": entry(\"Wind chill\", \"Wind and cold that freeze skin fast.\"),\n \"met.drought\": entry(\"Drought\", \"A long dry period, rated weekly by drought category, that leads to water limits, crop loss and fire risk.\"),\n \"met.dust-storm\": entry(\"Dust storm\", \"A wall of dust or sand that drops the visibility to near zero on roads.\"),\n \"met.flood\": entry(\"Flood\", \"Water over normally dry land from rain, rivers, snowmelt, ice jams or dam releases.\"),\n \"met.flood.areal\": entry(\"Areal flood\", \"Water over an area from heavy rain, slower than a flash flood.\"),\n \"met.flood.coastal\": entry(\"Coastal flood\", \"Sea water over coastal land from high tides, waves or a storm.\"),\n \"met.flood.flash\": entry(\"Flash flood\", \"A flood that rises within hours of heavy rain, a dam failure or a debris jam.\"),\n \"met.flood.hydrologic\": entry(\"Hydrologic conditions\", \"A statement of a weather service about river levels, snowmelt or the water supply.\"),\n \"met.flood.lakeshore\": entry(\"Lakeshore flood\", \"Lake water over the shore from wind and waves.\"),\n \"met.flood.river\": entry(\"River flood\", \"A river above flood stage at a gauge, with observed and forecast stages.\"),\n \"met.fog\": entry(\"Dense fog\", \"Fog that cuts visibility enough to cause road crashes and flight delays.\"),\n \"met.fog.freezing\": entry(\"Freezing fog\", \"Fog that freezes on roads and other surfaces.\"),\n \"met.freeze\": entry(\"Freeze\", \"Temperatures at or below freezing that kill crops and plants.\"),\n \"met.freeze.hard\": entry(\"Hard freeze\", \"Temperatures well below freezing for hours, which kill most crops and can burst pipes.\"),\n \"met.frost\": entry(\"Frost\", \"Frost on plants on a clear, calm night near freezing.\"),\n \"met.heat\": entry(\"Heat\", \"Dangerous heat that harms health, with heat warnings and heat risk levels.\"),\n \"met.heat.extreme\": entry(\"Extreme heat\", \"Heat that is a danger to life, as an extreme heat warning.\"),\n \"met.lightning\": entry(\"Lightning\", \"Cloud-to-ground lightning near a place, a direct risk to people outdoors and a common cause of fires and outages.\"),\n \"met.marine\": entry(\"Marine weather\", \"Gales, hazardous seas, freezing spray and special marine warnings for boats and coastal waters.\"),\n \"met.marine.brisk-wind\": entry(\"Brisk wind at sea\", \"Strong wind at sea that is a danger to small boats.\"),\n \"met.marine.fog\": entry(\"Dense fog at sea\", \"Fog that cuts the visibility for boats on coastal waters.\"),\n \"met.marine.freezing-spray\": entry(\"Freezing spray\", \"Spray that freezes on ships and adds weight to them.\"),\n \"met.marine.freezing-spray.heavy\": entry(\"Heavy freezing spray\", \"A fast build-up of ice from spray that can capsize a ship.\"),\n \"met.marine.gale\": entry(\"Gale\", \"Wind of 34 to 47 knots at sea.\"),\n \"met.marine.hazardous-seas\": entry(\"Hazardous seas\", \"Waves that are a danger to most boats.\"),\n \"met.marine.hurricane-force-wind\": entry(\"Hurricane-force wind at sea\", \"Wind of 64 knots or more at sea, not from a tropical cyclone.\"),\n \"met.marine.low-water\": entry(\"Low water\", \"Water levels that are low enough to put boats aground.\"),\n \"met.marine.small-craft\": entry(\"Small craft\", \"Wind or waves that are a danger to small boats.\"),\n \"met.marine.small-craft.rough-bar\": entry(\"Small craft at a rough bar\", \"Breaking waves at the entrance of a harbor (a bar) that are a danger to small boats.\"),\n \"met.marine.small-craft.seas\": entry(\"Small craft in hazardous seas\", \"Waves that are a danger to small boats.\"),\n \"met.marine.small-craft.wind\": entry(\"Small craft in wind\", \"Wind that is a danger to small boats.\"),\n \"met.marine.special\": entry(\"Special marine weather\", \"A short warning for boats of strong wind, hail or waterspouts from a storm.\"),\n \"met.marine.storm\": entry(\"Storm at sea\", \"Wind of 48 to 63 knots at sea.\"),\n \"met.outlook\": entry(\"Hazardous weather outlook\", \"A daily forecast of the hazardous weather of the next days, before any watch.\"),\n \"met.rain\": entry(\"Heavy rain\", \"Rain heavy enough to flood streets, cellars and low ground, below the level of a flood warning.\"),\n \"met.rip-current\": entry(\"Rip current\", \"A strong current that pulls swimmers away from the beach.\"),\n \"met.severe-weather\": entry(\"Severe weather\", \"An official weather watch, warning or advisory from a national meteorological service for an area.\"),\n \"met.special\": entry(\"Special weather\", \"A short statement of a weather service about weather below the level of a warning, for example a strong storm.\"),\n \"met.surf\": entry(\"High surf\", \"Large breaking waves that are a danger to people on the beach and the shore.\"),\n \"met.surge\": entry(\"Storm surge\", \"A rise of the sea above the tide from a storm, with a flood of the coast that is a danger to life.\"),\n \"met.thunderstorm\": entry(\"Thunderstorm\", \"A storm with damaging wind, large hail or a long-lived wind event, with watches and warnings.\"),\n \"met.thunderstorm.severe\": entry(\"Severe thunderstorm\", \"A thunderstorm with wind of 58 mph or more, or hail of 1 inch or more, as a watch or a warning.\"),\n \"met.tornado\": entry(\"Tornado\", \"A rotating column of air in contact with the ground, with watches and radar-indicated or observed warnings.\"),\n \"met.tropical\": entry(\"Tropical cyclone\", \"A hurricane, typhoon or tropical storm, with forecasts, watches and warnings for coasts in its path.\"),\n \"met.tropical.hurricane\": entry(\"Hurricane\", \"A tropical cyclone with wind of 74 mph or more.\"),\n \"met.tropical.storm\": entry(\"Tropical storm\", \"A tropical cyclone with wind of 39 to 73 mph.\"),\n \"met.tropical.typhoon\": entry(\"Typhoon\", \"A tropical cyclone of the western Pacific with wind of 74 mph or more.\"),\n \"met.wind\": entry(\"Wind\", \"Strong wind that is not from a thunderstorm, from a lake wind to the extreme wind of a hurricane.\"),\n \"met.wind.extreme\": entry(\"Extreme wind\", \"Wind of 115 mph or more, near the eyewall of a strong hurricane.\"),\n \"met.wind.high\": entry(\"High wind\", \"Wind or gusts that damage trees, power lines and buildings.\"),\n \"met.wind.lake\": entry(\"Lake wind\", \"Wind on lakes that is a danger to small boats.\"),\n \"met.winter\": entry(\"Winter\", \"Heavy snow, blowing snow, freezing rain or snow squalls that close roads and break power lines.\"),\n \"met.winter.blizzard\": entry(\"Blizzard\", \"Snow and strong wind that cut the visibility to near zero for hours.\"),\n \"met.winter.freezing-rain\": entry(\"Freezing rain\", \"Rain that freezes on roads, trees and power lines.\"),\n \"met.winter.ice-storm\": entry(\"Ice storm\", \"A heavy build-up of ice that breaks trees and power lines.\"),\n \"met.winter.lake-effect-snow\": entry(\"Lake-effect snow\", \"Heavy bands of snow downwind of a large lake.\"),\n \"met.winter.snow-squall\": entry(\"Snow squall\", \"A short burst of heavy snow and wind that drops the visibility fast on roads.\"),\n \"met.winter.storm\": entry(\"Winter storm\", \"Heavy snow, sleet or ice from a winter storm, as a watch or a warning.\"),\n \"met.winter.weather\": entry(\"Winter weather\", \"Snow, sleet or ice that makes travel difficult, below the level of a winter storm.\"),\n\n \"safety.civil-danger\": entry(\"Civil danger\", \"An authority warns a large population of an event that is a danger to life, for example a contaminated water supply.\"),\n \"safety.civil-emergency\": entry(\"Civil emergency\", \"An authority warns of a large threat to public safety or property that is not weather.\"),\n \"safety.crowd-crush\": entry(\"Crowd crush or stampede\", \"Dangerous crowd density at an event or transit point that can cause a crush.\"),\n \"safety.evacuation\": entry(\"Evacuation\", \"Authorities order or advise people to leave an area now, with zones and routes.\"),\n \"safety.local-emergency\": entry(\"Local emergency\", \"An authority warns of an event in a local area that is a threat to safety, with less priority than a civil emergency.\"),\n \"safety.national-emergency\": entry(\"National emergency\", \"A national authority sends an emergency message to the whole country, for example an Emergency Action Notification.\"),\n \"safety.public-lands-closure\": entry(\"Park or public land closure\", \"A park, trail or recreation area closes or posts a danger notice.\"),\n \"safety.recall\": entry(\"Product recall\", \"A maker or regulator withdraws a product that can hurt people, with the product, the hazard and the remedy.\"),\n \"safety.recall.consumer-product\": entry(\"Consumer product recall\", \"A household product, toy or appliance is recalled for fire, injury, choking or other hazards.\"),\n \"safety.recall.drug\": entry(\"Drug recall or falsified medicine alert\", \"A medicine is recalled for contamination, wrong strength or bad labels, or a falsified version is found.\"),\n \"safety.recall.food\": entry(\"Food recall or public health alert\", \"A food is recalled or flagged for contamination, undeclared allergens or foreign objects.\"),\n \"safety.recall.medical-device\": entry(\"Medical device recall\", \"A medical device is removed or corrected because it can fail or harm the patient.\"),\n \"safety.recall.vehicle\": entry(\"Vehicle recall\", \"A vehicle or part is recalled for a safety defect, sometimes with a do-not-drive or park-outside notice.\"),\n \"safety.scam\": entry(\"Scam or fraud wave\", \"A scam that targets many people at this time, for example fake government calls, text tolls or disaster charities.\"),\n \"safety.shelter-in-place\": entry(\"Shelter in place\", \"People in an area are told to go indoors, close windows and stay, from a release, a fire or a threat.\"),\n \"safety.wildlife\": entry(\"Dangerous wildlife activity\", \"A bear, cougar, shark or other dangerous animal is active near people, or an area closes for it.\"),\n\n \"security.active-threat\": entry(\"Active shooter or attack in progress\", \"An attack is under way at a place, and the people near it must run, hide or avoid the area.\"),\n \"security.air-raid\": entry(\"Air raid or missile alert\", \"A siren-level alert for missiles, drones or aircraft over a region, telling people to take cover now.\"),\n \"security.armed-conflict\": entry(\"Armed conflict event\", \"Battles, strikes, shelling or violence against civilians in an area of armed conflict.\"),\n \"security.blue-alert\": entry(\"Threat to the police\", \"Police ask the public for help after an officer is killed or badly injured and the suspect is at large.\"),\n \"security.child-abduction\": entry(\"Child abduction\", \"Police ask the public to look for an abducted child, with a description of the child, the suspect and the vehicle.\"),\n \"security.civil-unrest\": entry(\"Protest, riot or civil unrest\", \"Demonstrations, riots or strikes that close roads, cause violence or bring curfews.\"),\n \"security.crime\": entry(\"Crime near a place\", \"Reported crimes or police incidents near a place, for awareness rather than immediate danger.\"),\n \"security.curfew\": entry(\"Curfew or movement restriction\", \"An authority orders people to stay home or limits movement in an area for a period.\"),\n \"security.explosive-ordnance\": entry(\"Unexploded ordnance or mine hazard\", \"Unexploded bombs, mines or shells found or present in an area, with closures and danger to people.\"),\n \"security.kidnap\": entry(\"Kidnap risk\", \"Kidnaps of residents or travelers in an area, often for ransom.\"),\n \"security.law-enforcement\": entry(\"Law enforcement warning\", \"Police warn an area of a danger, for example an armed person, a manhunt or a bomb threat.\"),\n \"security.maritime-threat\": entry(\"Attack or threat to shipping\", \"Piracy, armed robbery, missile or drone attacks and boarding of ships in a sea area.\"),\n \"security.missing-person\": entry(\"Missing and endangered person\", \"Police ask the public to look for a missing person who is in danger, for example an older person with dementia.\"),\n \"security.terrorism\": entry(\"Terrorism threat or attack\", \"A government warning of a terrorist threat, or a terrorist attack that has happened.\"),\n \"security.travel-advisory\": entry(\"Government travel advisory\", \"A government changes its advice on travel to a country or region for safety, health or security reasons.\"),\n\n \"rescue.disaster-assistance\": entry(\"Disaster recovery center or aid open\", \"Aid becomes available after a disaster: recovery centers, assistance programs, food and water points.\"),\n \"rescue.search-and-rescue\": entry(\"Search and rescue operation\", \"A search for missing people at sea, in the mountains or after a collapse, with a request to watch.\"),\n \"rescue.shelter-open\": entry(\"Emergency shelter open\", \"Shelters open for people who leave their homes in a disaster, with location and capacity.\"),\n\n \"fire.burn-ban\": entry(\"Burn ban and fire restriction\", \"A ban on open burning, fireworks or campfires from a county, state or land agency.\"),\n \"fire.structure\": entry(\"Structure fire and local fire incident\", \"A building, vehicle or local fire that fire services dispatch to, near a place of interest.\"),\n \"fire.weather\": entry(\"Fire weather\", \"Wind, heat and low humidity that let fires start and spread fast, as red flag warnings.\"),\n \"fire.wildfire\": entry(\"Wildfire\", \"An uncontrolled fire in vegetation, with incident location, size, containment and perimeter.\"),\n \"fire.wildfire.hotspot\": entry(\"Satellite fire detection\", \"A satellite hotspot that can show a new fire before any report, with no official confirmation.\"),\n\n \"health.animal-disease\": entry(\"Animal disease event\", \"An outbreak in animals, for example avian influenza in poultry or dairy herds, with a risk to the food supply and to people.\"),\n \"health.drug-shortage\": entry(\"Drug or medical supply shortage\", \"A shortage of a medicine or medical product that affects patients.\"),\n \"health.drug-supply-threat\": entry(\"Dangerous drug supply or overdose cluster\", \"A new adulterant or potent drug in the illicit supply, or a spike in overdoses in an area.\"),\n \"health.hospital-capacity\": entry(\"Hospital or emergency care strain\", \"Hospitals in an area are full, on diversion or closed, so emergency care takes longer.\"),\n \"health.medical-emergency\": entry(\"Medical emergency\", \"A person needs emergency medical care now, for example after a fall, an injury, a stroke or a heart attack at home.\"),\n \"health.outbreak\": entry(\"Disease outbreak\", \"An unusual cluster or spread of an infectious disease, reported by a public health agency.\"),\n \"health.outbreak.foodborne\": entry(\"Foodborne illness outbreak\", \"Illnesses linked to a food product, under investigation, often before or with a recall.\"),\n \"health.travel-notice\": entry(\"Travel health notice\", \"A health notice for travellers to a country, from usual precautions to avoid all travel.\"),\n \"health.wastewater-signal\": entry(\"Wastewater pathogen signal\", \"A rise in a virus or bacterium measured in sewage, an early sign of community spread.\"),\n\n \"env.air-quality\": entry(\"Air quality\", \"Ozone, particles or other pollutants at an unhealthy AQI level, observed or forecast.\"),\n \"env.air-quality.smoke\": entry(\"Wildfire smoke\", \"Smoke from near or distant fires that raises fine particles to unhealthy levels.\"),\n \"env.air-stagnation\": entry(\"Air stagnation\", \"Light wind and a stable air mass that hold pollutants near the ground for days.\"),\n \"env.pest-quarantine\": entry(\"Plant pest or animal disease quarantine\", \"A quarantine area for an invasive pest or plant disease that limits moving plants, wood or produce.\"),\n \"env.pollen\": entry(\"High pollen\", \"A high pollen index that affects people with allergy or asthma.\"),\n \"env.smoke\": entry(\"Dense smoke\", \"Smoke that cuts the visibility on roads, as a dense smoke advisory of a weather service.\"),\n \"env.smoke.marine\": entry(\"Dense smoke at sea\", \"Smoke that cuts the visibility for boats on coastal waters.\"),\n \"env.spill\": entry(\"Oil or chemical spill to the environment\", \"A release of oil or a hazardous substance into water or land, reported to the authorities.\"),\n \"env.uv\": entry(\"High UV index\", \"A forecast UV index high enough to burn skin in minutes.\"),\n \"env.water\": entry(\"Water quality\", \"Bacteria, toxins or sewage in drinking water, lakes, rivers or the sea.\"),\n \"env.water.beach-advisory\": entry(\"Beach advisory or closure\", \"A beach closed or under advisory because of bacteria, sewage or toxins in the water.\"),\n \"env.water.drinking-advisory\": entry(\"Drinking water advisory (boil water, do not drink)\", \"A notice that tap water is unsafe to drink without boiling, or not at all.\"),\n \"env.water.harmful-algal-bloom\": entry(\"Harmful algal bloom\", \"Toxic algae or cyanobacteria in a lake or coastal water that make swimming, drinking water or shellfish unsafe.\"),\n \"env.water.sewage-overflow\": entry(\"Sewage overflow\", \"Untreated sewage released to rivers or the sea from a storm overflow or a failed plant.\"),\n\n \"transport.air\": entry(\"Air transport\", \"Aircraft, airports and airspace.\"),\n \"transport.air.accident\": entry(\"Aircraft accident\", \"A crash or serious incident of an aircraft, with the operator, place and casualties.\"),\n \"transport.air.conflict-zone\": entry(\"Conflict zone airspace warning\", \"A regulator warns airlines of a risk to aircraft over a conflict zone.\"),\n \"transport.air.disruption\": entry(\"Airport delay, ground stop or closure\", \"Flights at an airport are held, delayed by a program or stopped, or the airport closes.\"),\n \"transport.air.hazard-weather\": entry(\"Aviation weather hazard\", \"SIGMETs and advisories for turbulence, icing, convection, volcanic ash or low ceilings along air routes.\"),\n \"transport.air.notam\": entry(\"Airspace restriction (NOTAM or TFR)\", \"A notice that closes or restricts airspace, a runway or a navigation aid, including temporary flight restrictions.\"),\n \"transport.rail\": entry(\"Rail transport\", \"Trains and railways.\"),\n \"transport.rail.accident\": entry(\"Train accident or derailment\", \"A derailment, collision or grade crossing crash, sometimes with a hazardous materials release.\"),\n \"transport.road\": entry(\"Road transport\", \"Roads, highways and border crossings.\"),\n \"transport.road.border-wait\": entry(\"Border crossing delay\", \"Long waits or closure at a land border crossing.\"),\n \"transport.road.incident\": entry(\"Road closure, crash or work zone\", \"A road is closed or slowed by a crash, works, weather or an event.\"),\n \"transport.sea\": entry(\"Sea transport\", \"Ships, ports and sea routes.\"),\n \"transport.sea.navigational-warning\": entry(\"Navigational warning\", \"A warning to ships of hazards, for example drifting objects, firing exercises or failed lights.\"),\n \"transport.space\": entry(\"Space transport\", \"Rocket launches and the returns of objects from space.\"),\n \"transport.space.launch\": entry(\"Rocket launch or reentry hazard area\", \"A launch with closures of airspace, sea and roads, and possible debris or sonic booms.\"),\n \"transport.transit\": entry(\"Public transit\", \"The buses, trains and ferries of public transit.\"),\n \"transport.transit.service-alert\": entry(\"Public transit disruption\", \"A bus, train or ferry line is suspended, rerouted or delayed.\"),\n\n \"infra.cloud\": entry(\"Cloud services\", \"The public cloud regions and services that apps and sites run on.\"),\n \"infra.cloud.outage\": entry(\"Cloud provider outage\", \"A failure of a public cloud region or service that takes down the apps and sites built on it.\"),\n \"infra.dam\": entry(\"Dams and levees\", \"The dams and levees that hold back water above people.\"),\n \"infra.dam.failure\": entry(\"Dam or levee failure\", \"A dam or levee fails or is likely to fail, with fast flooding below it.\"),\n \"infra.fuel\": entry(\"Fuel supply\", \"The supply of gasoline, diesel and other fuels to stations and homes.\"),\n \"infra.fuel.shortage\": entry(\"Fuel shortage\", \"Stations run out of fuel after a refinery, pipeline or supply problem.\"),\n \"infra.gas\": entry(\"Gas and liquid pipelines\", \"The pipelines of natural gas and hazardous liquids.\"),\n \"infra.gas.pipeline-incident\": entry(\"Gas or liquid pipeline incident\", \"A leak, rupture or explosion of a gas or hazardous liquid pipeline.\"),\n \"infra.gnss\": entry(\"Satellite navigation\", \"GPS and the other satellite navigation systems.\"),\n \"infra.gnss.interference\": entry(\"GPS or satellite navigation interference\", \"GPS signals are jammed, spoofed or tested in an area, which affects aircraft, ships and phones.\"),\n \"infra.internet\": entry(\"Internet\", \"The networks, routes and shared providers of the internet.\"),\n \"infra.internet.bgp\": entry(\"Route hijack or route leak\", \"Wrong routing announcements that send traffic of a network to another network or drop it.\"),\n \"infra.internet.dns-cdn\": entry(\"DNS, CDN or certificate provider failure\", \"A failure of a shared internet provider (DNS, content delivery or certificates) that breaks many sites at once.\"),\n \"infra.internet.outage\": entry(\"Internet outage in a region or network\", \"A large drop in internet reachability in a country, region or provider network, from cuts, power or faults.\"),\n \"infra.internet.shutdown\": entry(\"Government internet shutdown\", \"An intentional cut or throttle of internet or platforms by an authority, often during protests or exams.\"),\n \"infra.payments\": entry(\"Payment systems\", \"Card networks, bank transfers and the other payment services.\"),\n \"infra.payments.outage\": entry(\"Payment or banking system outage\", \"A failure of card, bank transfer or payment services, so people cannot pay or get paid.\"),\n \"infra.postal\": entry(\"Postal service\", \"The mail and parcel services.\"),\n \"infra.postal.disruption\": entry(\"Postal service disruption\", \"Mail and parcel delays or suspensions from weather, facility closures or strikes.\"),\n \"infra.power\": entry(\"Electric power\", \"The supply of electric power from the grid to its customers.\"),\n \"infra.power.grid-emergency\": entry(\"Grid emergency or conservation appeal\", \"A grid operator warns that supply is short, asks people to save power, or orders rotating outages.\"),\n \"infra.power.load-shedding\": entry(\"Scheduled load shedding\", \"Rotating power cuts by a published schedule and stage when a national grid lacks supply.\"),\n \"infra.power.outage\": entry(\"Power outage\", \"Loss of electric power to customers in an area, with counts of customers out and restoration estimates.\"),\n \"infra.power.psps\": entry(\"Planned power shutoff for wildfire safety\", \"A utility turns off power in an area ahead of high wind to prevent its lines from starting fires.\"),\n \"infra.saas\": entry(\"Online services\", \"The web services, apps and platforms that people use.\"),\n \"infra.saas.outage\": entry(\"Online service outage\", \"An outage of a web service, app or platform that a person uses, from its own status page or user reports.\"),\n \"infra.structure\": entry(\"Structures\", \"Buildings, bridges, tunnels and the other built structures.\"),\n \"infra.structure.collapse\": entry(\"Building or bridge collapse\", \"A building, bridge, tunnel or other structure fails, often with casualties and closures around it.\"),\n \"infra.supply-chain\": entry(\"Supply chains\", \"The ports, routes and suppliers that move goods.\"),\n \"infra.supply-chain.disruption\": entry(\"Supply chain or shipping chokepoint disruption\", \"A block at a port, canal or strait, or a supplier failure, that delays goods and raises prices.\"),\n \"infra.telecom\": entry(\"Telephone and network\", \"The phone, mobile and emergency call networks.\"),\n \"infra.telecom.911-outage\": entry(\"911 outage\", \"Emergency calls to 911 do not connect in an area, with an alternate number to call.\"),\n \"infra.telecom.outage\": entry(\"Phone or mobile network outage\", \"Loss of mobile, landline or cable service in an area, from storms, cuts or carrier faults.\"),\n \"infra.timekeeping\": entry(\"Time zone or clock rule change\", \"A change to a time zone rule or daylight saving date that breaks schedules and software clocks.\"),\n \"infra.water\": entry(\"Water service\", \"The supply of tap water to an area.\"),\n \"infra.water.outage\": entry(\"Water service outage\", \"Loss of water pressure or supply to an area after a main break, pump failure or plant fault.\"),\n\n \"cbrne.biological\": entry(\"Biological agent incident\", \"A deliberate or accidental release of a dangerous pathogen or toxin.\"),\n \"cbrne.explosion\": entry(\"Industrial explosion\", \"An explosion at a plant, depot or storage site, with fire, blast damage and smoke.\"),\n \"cbrne.hazardous-materials\": entry(\"Hazardous materials\", \"A release of toxic gas or liquid from a plant, a vehicle or an attack that endangers people nearby.\"),\n \"cbrne.nuclear-plant\": entry(\"Nuclear power plant\", \"An event at a nuclear plant reported to the regulator, from a minor fault up to an emergency classification.\"),\n \"cbrne.radiological\": entry(\"Radiological hazard\", \"Raised radiation levels or loss of a radioactive source, with protective actions.\"),\n\n \"cyber.advisory\": entry(\"Security advisory\", \"A government or vendor advisory about a flaw or a threat.\"),\n \"cyber.advisory.ics\": entry(\"Industrial control system or medical device advisory\", \"A government advisory on a flaw in control systems or medical devices that run plants, utilities or hospitals.\"),\n \"cyber.campaign\": entry(\"Active threat campaign advisory\", \"A joint government advisory on an active attacker group, its methods and the steps defenders take now.\"),\n \"cyber.data-breach\": entry(\"Data breach\", \"Personal data stolen from an organization, which can expose the accounts and identity of the people in it.\"),\n \"cyber.ddos\": entry(\"Large denial-of-service attack\", \"A flood of traffic that takes a service, a network or a country offline for a period.\"),\n \"cyber.ransomware\": entry(\"Ransomware\", \"Ransomware attacks and the groups that do them.\"),\n \"cyber.ransomware.victim\": entry(\"Ransomware attack on an organization\", \"A ransomware group claims an organization as a victim, which can stop services that people depend on.\"),\n \"cyber.software\": entry(\"Software lifecycle\", \"The facts of the lifecycle of a software product that change its risk.\"),\n \"cyber.software.end-of-life\": entry(\"Software end of support\", \"A product or version that stops getting security fixes on a known date, so its users must upgrade.\"),\n \"cyber.supply-chain\": entry(\"Software supply chain\", \"A threat to the packages and the build tools that software depends on.\"),\n \"cyber.supply-chain.malicious-package\": entry(\"Malicious software package\", \"A package in a public registry that contains malware, often a typo-squat or a hijacked maintainer account.\"),\n \"cyber.vulnerability\": entry(\"Software vulnerability\", \"A flaw in software that an attacker can use.\"),\n \"cyber.vulnerability.exploited\": entry(\"Vulnerability exploited in the wild\", \"A software flaw that attackers use now, so systems that run the product need a patch or a work-around fast.\"),\n \"cyber.vulnerability.published\": entry(\"New vulnerability in software that a person uses\", \"A newly published CVE or advisory for a product, library or package, with severity and fixed versions.\"),\n\n \"market.bank\": entry(\"Banks\", \"A bank fails or its service stops, which can block a person's money.\"),\n \"market.bank.failure\": entry(\"Bank failure\", \"A regulator closes a bank and the FDIC names the acquiring bank or pays depositors.\"),\n \"market.bank.outage\": entry(\"Bank service outage\", \"A bank or neobank reports that its app, cards or transfers do not work.\"),\n \"market.broker\": entry(\"Brokers\", \"The brokers that hold the investments of people.\"),\n \"market.broker.outage\": entry(\"Broker outage\", \"A broker reports that trading, deposits or withdrawals do not work.\"),\n \"market.credit\": entry(\"Credit\", \"The credit of countries, banks and companies.\"),\n \"market.credit.rating\": entry(\"Credit rating change\", \"A rating agency changes the rating of a country, bank or company.\"),\n \"market.credit.sovereign-debt\": entry(\"Sovereign debt event\", \"A government default, downgrade, or debt ceiling event.\"),\n \"market.crypto\": entry(\"Crypto market events\", \"A stablecoin, exchange or chain has a failure that can lock or lose a person's funds.\"),\n \"market.crypto.chain-halt\": entry(\"Blockchain halt\", \"A blockchain stops making blocks or confirming transactions.\"),\n \"market.crypto.depeg\": entry(\"Stablecoin depeg\", \"A stablecoin trades away from its peg by more than a set amount.\"),\n \"market.crypto.exchange-outage\": entry(\"Crypto exchange outage\", \"A crypto exchange or custodian reports degraded trading, deposits or withdrawals.\"),\n \"market.crypto.hack\": entry(\"Crypto hack or exploit\", \"A protocol, bridge or exchange loses funds to an attack.\"),\n \"market.exchange\": entry(\"Exchange operations\", \"An exchange has a system problem or a closure that changes when a person can trade.\"),\n \"market.exchange.closure\": entry(\"Market closure or early close\", \"An exchange closes for a holiday, an early close or an unscheduled event.\"),\n \"market.exchange.outage\": entry(\"Exchange system issue\", \"An exchange reports that its systems are affected or down.\"),\n \"market.halt\": entry(\"Trading halts\", \"Trading stops in a whole market or in one security.\"),\n \"market.halt.marketwide\": entry(\"Market-wide circuit breaker\", \"US equity trading stops across all markets after a large index fall (codes MWC1, MWC2, MWC3).\"),\n \"market.halt.security\": entry(\"Single-security halt\", \"Trading stops in one security for news, volatility (LULD) or a regulatory reason.\"),\n \"market.halt.suspension\": entry(\"Regulatory trading suspension\", \"The SEC suspends trading in a security, mostly for doubts about its information.\"),\n \"market.indicator\": entry(\"Economic indicators\", \"The indicators that tell the state of the economy.\"),\n \"market.indicator.recession\": entry(\"Recession indicator\", \"A recession indicator crosses its trigger level.\"),\n \"market.investor\": entry(\"Investor protection\", \"The warnings and actions of regulators that protect investors.\"),\n \"market.investor.alert\": entry(\"Investor fraud or enforcement alert\", \"A regulator warns of a fraud or acts against a firm that a person can use.\"),\n \"market.prediction\": entry(\"Prediction market signals\", \"A forecast market or crowd forecast changes in a way that tells of a coming event.\"),\n \"market.prediction.move\": entry(\"Sudden probability move\", \"The probability of an outcome changes by a large amount in a short window.\"),\n \"market.prediction.new\": entry(\"New market with activity\", \"A new market opens on a topic the person follows and gets real volume.\"),\n \"market.prediction.resolution\": entry(\"Market resolution\", \"A market closes and resolves to an outcome, which confirms an event.\"),\n \"market.prediction.threshold\": entry(\"Probability crosses a set level\", \"The probability of an outcome passes a level that the person chose.\"),\n \"market.prediction.volume\": entry(\"Volume surge\", \"Trading volume in a market rises far above its normal rate, which can tell of private information.\"),\n \"market.price\": entry(\"Price and rate moves\", \"A price that touches a person's costs or savings moves sharply.\"),\n \"market.price.commodity\": entry(\"Commodity price shock\", \"The price of crude oil, natural gas or another commodity moves sharply.\"),\n \"market.price.fuel\": entry(\"Fuel price change\", \"Retail gasoline or diesel prices in a region rise past a level or by a set amount.\"),\n \"market.price.fx\": entry(\"Sharp currency move\", \"An exchange rate moves more than a set percent, which changes the cost of travel or transfers.\"),\n \"market.price.move\": entry(\"Sharp asset or index move\", \"A stock index, stock or crypto asset moves more than a set percent in a set window.\"),\n \"market.price.volatility\": entry(\"Volatility spike\", \"A volatility index, for example the VIX, rises sharply, which marks market stress.\"),\n \"market.rates\": entry(\"Interest rates\", \"The interest rates that touch the loans and savings of people.\"),\n \"market.rates.mortgage\": entry(\"Mortgage rate change\", \"Average mortgage rates pass a level or move by a set amount in a week.\"),\n \"market.release\": entry(\"Scheduled economic releases\", \"A scheduled economic release or central bank decision is due or is out.\"),\n \"market.release.fomc\": entry(\"FOMC decision or minutes\", \"The Federal Open Market Committee publishes a rate decision, statement or minutes.\"),\n \"market.release.macro\": entry(\"Macro data release\", \"A government agency publishes a scheduled economic number, for example CPI, jobs or GDP.\"),\n\n \"civic.court-ruling\": entry(\"Court ruling or docket change\", \"A court rules or a docket changes in a case that matters to the person.\"),\n \"civic.economy\": entry(\"Government economic actions\", \"A government takes an economic action, for example sanctions or a fiscal step, that touches a person.\"),\n \"civic.economy.enforcement\": entry(\"Financial enforcement action\", \"A financial regulator takes an enforcement action against a firm.\"),\n \"civic.economy.fiscal\": entry(\"Federal fiscal stress\", \"Federal cash or debt data shows a debt-limit squeeze or another fiscal stress.\"),\n \"civic.election\": entry(\"Election date or voting change\", \"Election dates, registration deadlines, polling place changes and results that affect a voter.\"),\n \"civic.emergency-declaration\": entry(\"Emergency or disaster declaration\", \"A government declares an emergency or a major disaster, which opens aid and changes rules.\"),\n \"civic.government-operating-status\": entry(\"Government office closure or delay\", \"Government offices close, open late or change to telework, from weather or other events.\"),\n \"civic.government-shutdown\": entry(\"Government shutdown\", \"A lapse in funding stops or slows government services, payments and parks.\"),\n \"civic.labor-action\": entry(\"Strike or labor action\", \"A strike or walkout that stops a service: transit, ports, postal, schools or hospitals.\"),\n \"civic.planned-event\": entry(\"Large planned event\", \"A concert, game, march or festival that brings crowds, closures and traffic to an area.\"),\n \"civic.public-holiday\": entry(\"Public holiday\", \"A public holiday that closes offices, banks and markets and changes transit schedules.\"),\n \"civic.regulation\": entry(\"New rule or law\", \"A new regulation, rule or law that changes what a person or a business must do.\"),\n \"civic.sanctions\": entry(\"Sanctions action\", \"OFAC adds, removes or licenses sanctions on a country, bank, company or person.\"),\n \"civic.school-closure\": entry(\"School closure or delay\", \"Schools close, start late or go remote for weather, threats or other events.\"),\n \"civic.tax-relief\": entry(\"Disaster tax relief\", \"A tax authority postpones deadlines for people in a disaster area.\"),\n \"personal.death\": entry(\"Death in the household\", \"A person of the household dies, and the others must act on the care, the money and the papers.\"),\n \"personal.income-loss\": entry(\"Loss of income\", \"A person loses a job or another main source of money, for example after a layoff, a closure or an injury.\"),\n\n [UNKNOWN_KIND]: entry(\"Unknown event\", \"An event that the kind tables of an adapter do not know.\"),\n\n \"system.admin\": entry(\"Administrative message\", \"A message about the alert systems, not about a hazard.\"),\n \"system.test\": entry(\"Test message\", \"A test of an alert system. It shows that the path works, and it does not wake a person.\"),\n [HEALTH_KIND]: entry(\"Health of a source\", \"The health of a source of signals, from its fetches and its timing.\"),\n ...Object.fromEntries(Object.entries(HEALTH_ENTRIES).map(([state, value]) => [`${HEALTH_KIND}.${state}`, value])),\n [COVERAGE_KIND]: entry(\"Coverage of a kind\", \"A report that too few healthy sources cover a kind at a place. The covered code follows the prefix.\"),\n [QUOTA_KIND]: entry(\"Quota of a channel\", \"The quota of a channel: the units that it can send in one window of its provider.\"),\n ...Object.fromEntries(Object.entries(QUOTA_ENTRIES).map(([stage, value]) => [`${QUOTA_KIND}.${stage}`, value])),\n [BALANCE_KIND]: entry(\"Balance of a provider\", \"The balance of a paid provider account: the money that its channels can spend.\"),\n ...Object.fromEntries(Object.entries(BALANCE_ENTRIES).map(([stage, value]) => [`${BALANCE_KIND}.${stage}`, value])),\n [CLOCK_KIND]: entry(\"Clock of the computer\", \"The wall clock of the computer that runs the alert system.\"),\n [`${CLOCK_KIND}.step`]: entry(\"Step of the clock\", \"The wall clock of the computer stepped back or forward against its monotonic clock.\"),\n [LOG_KIND]: entry(\"Log of the runtime\", \"The log file of the runtime of the alert system. The state of the runtime comes from it.\"),\n [COPY_KIND]: entry(\"Copy of the system\", \"Another copy of the alert system on another computer. The copies share their reports and their sends.\"),\n ...Object.fromEntries(Object.entries(COPY_ENTRIES).map(([stage, value]) => [`${COPY_KIND}.${stage}`, value])),\n [`${LOG_KIND}.recovered`]: entry(\"Recovery of the log\", \"The log file was broken. The runtime moved it into quarantine and started a new file with the events that it read.\"),\n [DRILL_KIND]: entry(\"Drill of a path\", \"A drill of the path of the life-safety warnings: the provider, the phone and the person.\"),\n [`${DRILL_KIND}.run`]: entry(\"Drill\", \"A drill message. It wakes the person, and an acknowledgment in its time passes the drill. It is not a warning.\"),\n [`${DRILL_KIND}.failed`]: entry(\"Failed drill\", \"No acknowledgment of a drill came in its time. A real warning on this path can also go without an answer.\"),\n [ESCALATION_KIND]: entry(\"Escalation of a warning\", \"The steps that send a warning to a person again on more channels, until the person acknowledges it.\"),\n [CHANNEL_KIND]: entry(\"Channel of the system\", \"A channel that takes the alerts to the people, as a push service, a text service or a call service.\"),\n [`${CHANNEL_KIND}.down`]: entry(\"Down channel\", \"The calls of a channel to its provider fail. The other channels of each person carry the alerts until a call passes again.\"),\n [STORE_KIND]: entry(\"Store of the system\", \"A store of the alert system that fills from its sources after each start, as the store of the outlines of the zones.\"),\n [TELL_KIND]: entry(\"Message of the operator\", \"A short private message from the operator of the alert system to one person. It is not a warning.\"),\n [`${TELL_KIND}.needs-you`]: entry(\"Needs you\", \"A message of the operator: the person must decide or act.\"),\n [`${TELL_KIND}.done-you-asked`]: entry(\"Done\", \"A message of the operator: a request of the person is done.\"),\n [`${TELL_KIND}.live`]: entry(\"Live\", \"A message of the operator: a change is live.\"),\n [`${STORE_KIND}.empty`]: entry(\"Empty store\", \"A family of a store has no entry in the time after a start. Each feature that reads the family works without it.\"),\n [LIMIT_KIND]: entry(\"Send limit of the system\", \"The most new alerts that one person gets in one window. The digest tells each alert that the limit holds.\"),\n [`${LIMIT_KIND}.held`]: entry(\"Alerts held\", \"The send limit holds new alerts for the person. The next digest tells each one. The limit does not hold a life-safety warning.\"),\n [`${ESCALATION_KIND}.exhausted`]: entry(\"Exhausted escalation\", \"A person did not acknowledge a real warning in the time of the policy. The people who watch the person get this report.\"),\n};\n\n/**\n * The old codes of the taxonomy, each with its new code. A code leaves `TAXONOMY` only with an entry\n * here, so a stored kind with an old code still parses. The file `taxonomy.lock.json` holds each code\n * of `TAXONOMY` and each old code, and a test holds the lock. Thus the removal of a code is a deliberate step.\n */\nexport const KIND_ALIASES: Readonly<Record<string, string>> = {};\n\n/**\n * This function gives the new code of an old code, and each other code with no change. It also maps\n * the covered code of `system.coverage.<code>`. The schemas apply it before the check of `knownKind`.\n */\nexport function canonicalKind(code: string, aliases: Readonly<Record<string, string>> = KIND_ALIASES): string {\n if (Object.hasOwn(aliases, code)) return aliases[code] ?? code;\n if (!code.startsWith(`${COVERAGE_KIND}.`)) return code;\n const covered = code.slice(COVERAGE_KIND.length + 1);\n return Object.hasOwn(aliases, covered) ? `${COVERAGE_KIND}.${aliases[covered] ?? covered}` : code;\n}\n\n/**\n * This function tells if a code is in the taxonomy. The code must be a code of `TAXONOMY`, or\n * `system.coverage.<code>` for a code of `TAXONOMY` that is not a code of the system. It is the one\n * rule for each code: the adapters, the schemas of the configuration and the source atlas use it.\n */\nexport function knownKind(code: string): boolean {\n if (Object.hasOwn(TAXONOMY, code)) return true;\n if (!code.startsWith(`${COVERAGE_KIND}.`)) return false;\n const covered = code.slice(COVERAGE_KIND.length + 1);\n return categoryOf(covered) !== \"system\" && Object.hasOwn(TAXONOMY, covered);\n}\n\n/** This function gives the codes that are not in the taxonomy, sorted and each one time. The gate tests of the adapters use it. */\nexport function unknownKinds(codes: Iterable<string>): string[] {\n return [...new Set([...codes].filter((code) => !knownKind(code)))].sort(compareCodeUnits);\n}\n\n/** This function gives the parent of a code: the code without its last part, or `null` for a category. */\nexport function parentKind(code: string): string | null {\n const end = code.lastIndexOf(\".\");\n return end < 0 ? null : code.slice(0, end);\n}\n\n/** This function gives the plain name of a code. A code that `TAXONOMY` does not have gives the code itself. */\nexport function kindLabel(code: string): string {\n return Object.hasOwn(TAXONOMY, code) ? (TAXONOMY[code]?.label ?? code) : code;\n}\n","/**\n * This module routes each incident to the escalations of each person. It also makes the message of a\n * send and the acknowledgment of a status. It is pure. The runtime gives the time, and\n * the runtime does each call of a channel.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { assess, COVERAGE_KIND, DEFAULT_ASSESS_POLICY, foreignIncidents, hasKind, LIFE_SAFETY_KINDS, matchSubjects, PERSON_SUBJECT, QUOTA_KIND, reachedAssessment } from \"./assess.ts\";\nimport { isPrivate } from \"./audience.ts\";\nimport {\n ASSESSED_LEVELS,\n LEVELS,\n type Acknowledgment,\n type Address,\n type AssessedLevel,\n type AssessPolicy,\n type ChannelDescriptor,\n type ChannelId,\n type Delivery,\n type DeliveryStatus,\n type Duration,\n type EscalationPolicy,\n type Incident,\n type Instant,\n type Level,\n type MergeState,\n type Message,\n type PersonId,\n type PersonWatch,\n type Report,\n type ReportId,\n type Status,\n type SubjectWatch,\n type WatchedPlace,\n type WhyRecord,\n} from \"./contracts.ts\";\nimport { dailyTimeProblems, digestTimeOf, escalate, escalationProblems, quietWindowProblems, rankDelayOf, rankFloors, type EscalationPlan, type EscalationSend, type RankDelays } from \"./escalation.ts\";\nimport { messageKey } from \"./ids.ts\";\nimport type { Suppression } from \"./throttle.ts\";\nimport { unknownKinds } from \"./taxonomy.ts\";\nimport { assessmentWhy } from \"./why.ts\";\n\n/** A person of the delivery. The private configuration gives each one. */\nexport interface Recipient {\n /** The places, the subjects, the rules and the quiet window of the person. */\n readonly watch: PersonWatch;\n /**\n * The escalation policies of the person (`policyFor`). A level with no policy starts no escalation for this person.\n */\n readonly policies: readonly EscalationPolicy[];\n /** The address of the person on each channel, by the channel id. */\n readonly addresses: Readonly<Record<string, Address>>;\n /** The channel rules of the person. `loadConfig` makes two rules for each drill of the person. */\n readonly channelRules?: readonly ChannelRule[];\n}\n\n/** The statuses of the incidents that a channel rule can change. A rule does not change the steps of a real warning. */\nexport const RULED_STATUSES: readonly Status[] = [\"system\", \"test\", \"exercise\"];\n\n/**\n * A channel rule of a person: the channels of the steps for the incidents of some kinds. A rule applies only to an\n * incident with a status of `RULED_STATUSES`. A rule has no status field, thus no rule changes an incident `actual`.\n */\nexport interface ChannelRule {\n /** The kinds of the rule: prefixes of the taxonomy. */\n readonly kinds: readonly string[];\n /** The subject of the rule. Without it, the rule applies to each incident of its kinds. */\n readonly about?: SubjectWatch;\n /** With `only`, only the steps on the channels stay. With `except`, the steps on the channels go. */\n readonly keep: \"only\" | \"except\";\n readonly channels: readonly ChannelId[];\n}\n\n/** The policy of an incident after the channel rules of a person. */\nexport interface RuledPolicy {\n /** The policy with only the steps that stay. */\n readonly policy: EscalationPolicy;\n /** The indexes of the rules that apply to the incident. */\n readonly rules: readonly number[];\n /** The indexes of the steps of the policy that the rules remove. */\n readonly dropped: readonly number[];\n}\n\n/**\n * This function applies the channel rules of a person to the policy of an incident. Each rule that matches the kind and\n * the subject of the incident applies. A step stays only when each of these rules keeps it. An incident with a status\n * out of `RULED_STATUSES` keeps each step.\n */\nexport function ruleSteps(policy: EscalationPolicy, rules: readonly ChannelRule[] | undefined, incident: Pick<Incident, \"status\" | \"kind\" | \"about\">): RuledPolicy {\n if (rules === undefined || rules.length === 0 || !RULED_STATUSES.includes(incident.status)) return { policy, rules: [], dropped: [] };\n const matched = rules.flatMap((rule, index) => (hasKind(rule.kinds, incident.kind.code) && (rule.about === undefined || matchSubjects(incident, [rule.about]).length > 0) ? [index] : []));\n if (matched.length === 0) return { policy, rules: [], dropped: [] };\n const keeps = (channel: ChannelId): boolean => matched.every((index) => rules[index]!.channels.includes(channel) === (rules[index]!.keep === \"only\"));\n const dropped = policy.steps.flatMap((step, index) => (keeps(step.channel) ? [] : [index]));\n return { policy: dropped.length === 0 ? policy : { ...policy, steps: policy.steps.filter((step) => keeps(step.channel)) }, rules: matched, dropped };\n}\n\n/**\n * This function gives the policy of a level for an incident. An incident with a status of `RULED_STATUSES` gets the\n * first policy of the level whose subject matches a subject of the incident (`matchSubjects`). Each other incident,\n * and an incident with no such policy, gets the first policy of the level with no subject.\n */\nexport function policyFor(policies: readonly EscalationPolicy[], level: Level, incident: Pick<Incident, \"status\" | \"about\">): EscalationPolicy | undefined {\n const ofLevel = policies.filter((policy) => policy.level === level);\n const ruled = RULED_STATUSES.includes(incident.status);\n const about = ruled ? ofLevel.find((policy) => policy.about !== undefined && matchSubjects(incident, [policy.about]).length > 0) : undefined;\n return about ?? ofLevel.find((policy) => policy.about === undefined);\n}\n\n/**\n * This function gives the name of a policy in a problem: its level, and its subject when it has one.\n */\nexport function policyName(policy: EscalationPolicy): string {\n const about = policy.about;\n return about === undefined ? policy.level : `${policy.level} about ${about.system}${about.id === undefined ? \"\" : ` ${about.id}`}`;\n}\n\n/**\n * The start of an escalation: the time at which the level of an incident first called for it. The\n * runtime keeps each start in its log, thus the start does not move after a restart.\n */\nexport interface EscalationStart {\n /** A report of the incident: its anchor at the start. */\n readonly incident: ReportId;\n readonly level: Level;\n readonly person: PersonId;\n readonly at: Instant;\n /**\n * True: the escalation is in the silent mode of a mute with the effect `silent`. Its episode sends one quiet message\n * at most: its step 0, when the person has no delivery of the incident.\n */\n readonly silent?: true;\n}\n\n/**\n * The reason of an end of a person.\n * - `ended`: the threat left the person, for example after a cancel of the area of the person.\n * - `muted`: a mute of the person changed. A mute with the effect `absent` started, or the mode of the escalation\n * changed between loud and silent.\n *\n * The runtime sends no message for an end. An acknowledgment before an end `muted` still covers the next episode.\n */\nexport type EndReason = \"ended\" | \"muted\";\n\n/**\n * The end of the escalations of a person in a live incident. The incident no longer reaches the person, for example\n * after a cancel of the area of the person, or a mute changed. The runtime keeps each end in its log. A later match of\n * the person starts a new episode, and the sends of the new episode get new message keys.\n */\nexport interface EscalationEnd {\n /** A report of the incident: its anchor at the end. */\n readonly incident: ReportId;\n readonly person: PersonId;\n readonly at: Instant;\n /** The reason of the end. An end with no reason is an end `ended`. */\n readonly reason?: EndReason;\n}\n\n/**\n * A hold of an escalation by the send limit of the person (`limitRoutes`, AL-72). The escalation sends nothing in its\n * episode, and the next digest tells its incident. The runtime keeps each hold in its own log.\n */\nexport interface EscalationHold {\n /** The report of the start of the escalation. */\n readonly incident: ReportId;\n readonly level: Level;\n readonly person: PersonId;\n /** The episode of the escalation. A later episode of the incident is a new escalation, and it needs a new place. */\n readonly episode: number;\n readonly at: Instant;\n}\n\n/** The input of `route`. */\nexport interface RouteInput {\n /** The merge state. Its deliveries and its acknowledgments go to each escalation. */\n readonly state: MergeState;\n /** The incidents of the merge state at `now`. */\n readonly incidents: readonly Incident[];\n readonly recipients: readonly Recipient[];\n readonly places: readonly WatchedPlace[];\n /** The policy of the assessment. The default is `DEFAULT_ASSESS_POLICY`. */\n readonly assess?: AssessPolicy | undefined;\n /**\n * The ids of the sources that this copy runs by its config, also a source whose fetch fails at this time (AL-76). A kind with\n * no class in an incident of only other sources gets `FOREIGN_TABLE`. Without the set, each source is a source of this copy.\n */\n readonly sources?: ReadonlySet<string> | undefined;\n /** The starts that the log has. They are the starts of this copy: the copies do not share their starts. */\n readonly starts: readonly EscalationStart[];\n /** The ends that the log has. The default is none. */\n readonly ends?: readonly EscalationEnd[] | undefined;\n /** The delivery keys with no more repeats. */\n readonly cancelled: ReadonlySet<string>;\n /** The descriptor of each channel. A delivery of a channel with the acknowledgment `poll` gets a poll. */\n readonly channels: readonly ChannelDescriptor[];\n /** The rank of this copy of the system, and the wait of each rank. `escalate` tells how they apply. */\n readonly rank?: number | undefined;\n /** The default wait of one rank: the wait of each level with no entry in `rankDelays`. */\n readonly rankDelay?: Duration | undefined;\n /** The wait of one rank for each level. With 0 for `life-safety`, each copy sends a life-safety step at once. */\n readonly rankDelays?: RankDelays | undefined;\n /**\n * The least wait of one rank before a step of an exclusive channel, as a call. A step of the channel waits\n * `rank × max(rankDelay, rankFloor)`. Without it, the channels have no floor.\n */\n readonly rankFloor?: Duration | undefined;\n readonly now: Instant;\n}\n\n/** One escalation: one incident, one level and one person. */\nexport interface Route {\n readonly incident: Incident;\n readonly person: PersonId;\n /** The policy of the plan: the policy of the person for the level, with only the steps that the channel rules keep. */\n readonly policy: EscalationPolicy;\n /**\n * The channel rules of the person that apply to the incident (`ruleSteps`), and the steps of the policy of the person\n * that they remove. Thus the explain and the map can tell why a step is absent.\n */\n readonly ruled?: { readonly rules: readonly number[]; readonly dropped: readonly number[] };\n /** The start of the escalation. When `fresh` is true, the log does not have it, and the runtime writes it. */\n readonly start: EscalationStart;\n readonly fresh: boolean;\n /** The deliveries of this escalation in the ledger. */\n readonly deliveries: readonly Delivery[];\n /** The deliveries that need a poll for an acknowledgment: each one with a receipt, no cancel and a channel that polls. */\n readonly polls: readonly Delivery[];\n readonly plan: EscalationPlan;\n /** The episode of the escalation: the count of the earlier ends of the person in the incident. Its sends have it. */\n readonly episode: number;\n /**\n * The end of the episode: the end in the log, or the end at `now` when the live incident no longer reaches the\n * person. When `freshEnd` is true, the log does not have the end, and the runtime writes it.\n */\n readonly end?: EscalationEnd;\n readonly freshEnd: boolean;\n /**\n * Why the incident reaches the person (`assessmentWhy`): the why of the interest graph, or else the watched place of\n * the match with the first id. A route of an incident that is not live has no why. A match by the subjects of\n * `PersonWatch.subjects` has no why.\n */\n readonly why?: WhyRecord;\n /** The hold of the send limit (`limitRoutes`). A held route has no send in its plan. Its cancels stay. */\n readonly held?: EscalationHold;\n /**\n * This value is true when only the deliveries of another copy give the level, and the own assessment of the live\n * incident is lower (AL-76). This copy has no start at the level. The route sends nothing, writes no start and gives\n * no exhaustion. Its polls, its cancels and its end stay.\n */\n readonly imported?: true;\n /**\n * The first suppression of the throttle (`throttleRoutes`), when the escalation has no delivery. The person did not get\n * its message, thus such a route gives no exhaustion.\n */\n readonly suppressed?: Suppression;\n}\n\n/**\n * This function gives a reader of the items of a set of report ids. The reader gives the items in the order of the\n * list, so it gives the value of a filter of the list.\n */\nfunction byReport<T extends { readonly incident: ReportId }>(items: readonly T[]): (reports: ReadonlySet<string>) => T[] {\n const index = new Map<string, number[]>();\n items.forEach((item, at) => {\n const held = index.get(item.incident);\n if (held === undefined) index.set(item.incident, [at]);\n else held.push(at);\n });\n return (reports) => {\n const found: number[] = [];\n for (const report of reports) for (const at of index.get(report) ?? []) found.push(at);\n return found.sort((a, b) => a - b).map((at) => items[at]!);\n };\n}\n\n/**\n * This function gives the escalations at `now`, in the order of the anchor, the person, the episode and the level.\n *\n * - The levels of an incident and a person are each level of a start or a delivery, and the assessed level.\n * The assessed level counts only when it is higher than those levels and the person has a policy for it.\n * An incident that is not live has no assessed level.\n * - Only the highest level continues. A lower level ends at the start of a higher level, thus its repeats stop.\n * An acknowledgment of the higher level also covers each lower level.\n * - Thus the level does not go down. An escalation continues until an acknowledgment, the end of the incident or the end of the person.\n * - The end of the person: when a live incident no longer reaches a person (the assessed level is `none`), each\n * escalation of the person ends at `now`. The route gives that end (`freshEnd`), and the runtime writes it to the log.\n * - Each end of the log closes an episode of the person. A later match starts a new episode with new message keys. Its starts,\n * its deliveries and its acknowledgments come after the end. An acknowledgment between the end and the new start covers nothing.\n * - A mute of the assessment (`Assessment.muted`) with the effect `absent` gives the level `none`. Its end has the reason `muted`.\n * - A mute with the effect `silent` keeps the level and sets the silent mode. A change between loud and silent ends the\n * episode at `now` with the reason `muted`. The next episode starts in the new mode at once.\n * - A silent episode sends one quiet step 0 at most, only when the person has no delivery of the incident. Thus a mute\n * after a loud alert sends no copy, and a mute before the incident still gives one quiet message.\n * - An end `muted` keeps the acknowledgments of the episode before it. Thus a change of a mute does not alert again.\n * - An earlier episode gets an escalation only when one of its deliveries has no cancel. Its end is its end in the log.\n * - An incident that is not live gets an escalation only when one of its deliveries has no cancel. Its end is its expiry, or `now`.\n * - The start of an escalation is the start in the log. A new escalation starts at `now`, or earlier when the ledger shows an earlier start.\n * - The channel rules of the person (`ruleSteps`) remove steps of a system, test or exercise incident before the plan.\n * - The level `digest` has no escalation. The digest (`planDigests`) tells it, thus a route has no delivery and no start of it.\n * - Copies of two builds (AL-76). A level with no start of this copy, above the own assessment of the live incident,\n * comes only from the deliveries of another copy. Its route sends nothing and writes no start (`Route.imported`).\n * The level still holds the top, thus a lower own level starts nothing. A later own assessment at that level sends.\n * - A kind with no class in an incident of only the sources of other copies (`RouteInput.sources`) gets `FOREIGN_TABLE`.\n */\nexport function route(input: RouteInput): Route[] {\n const { state, now } = input;\n const policy = input.assess ?? DEFAULT_ASSESS_POLICY;\n const polling = new Set(input.channels.filter((channel) => channel.ack === \"poll\").map((channel) => channel.id as string));\n const floors = rankFloors(input.channels, input.rankFloor);\n const routes: Route[] = [];\n // The parts of each report id. Thus each incident reads only its own parts, not each part of the state.\n const deliveriesOf = byReport(state.deliveries.filter((delivery) => delivery.level !== \"digest\"));\n const startsOf = byReport(input.starts);\n const acksOf = byReport(state.acks);\n const endsOf = byReport(input.ends ?? []);\n const isForeign = foreignIncidents(state.reports, input.sources);\n for (const incident of input.incidents) {\n const reports = new Set<string>([incident.anchor, ...incident.reports]);\n const foreign = isForeign(incident);\n // A delivery of a digest is not a step of an escalation. The digest plan reads it.\n const deliveries = deliveriesOf(reports);\n const open = deliveries.some((delivery) => !input.cancelled.has(delivery.key));\n if (!incident.live && !open) continue;\n const starts = startsOf(reports);\n const acks = acksOf(reports);\n const ends = endsOf(reports);\n const end = endOf(incident, now);\n for (const recipient of input.recipients) {\n const person = recipient.watch.person;\n const policyOf = (level: Level): EscalationPolicy | undefined => policyFor(recipient.policies, level, incident);\n const mine = <T extends { readonly person: PersonId }>(items: readonly T[]): T[] => items.filter((item) => item.person === person);\n // The ends of the person in time order. Each one closes an episode. A change of the mode adds its end at `now`.\n const closes: EscalationEnd[] = mine(ends)\n .filter((item) => Number.isFinite(item.at))\n .sort((a, b) => a.at - b.at || compareCodeUnits(a.incident, b.incident));\n // The episode of a time: the count of the ends before it. A time that is not a number is in the first episode.\n const episodeOf = (at: Instant): number => closes.filter((close) => close.at < at).length;\n // The first time of an episode: its earliest start or delivery, or `now`.\n const firstOf = (episode: number): Instant =>\n Math.min(now, ...[...mine(starts), ...mine(deliveries)].filter((item) => episodeOf(item.at) === episode).map((item) => item.at).filter(Number.isFinite));\n const assessment = incident.live ? assess(incident, recipient.watch, input.places, policy, now, foreign) : undefined;\n // A mute with the effect `absent` keeps the incident from the person. With `silent`, the level stays and the mode changes.\n const muted = assessment?.muted;\n const assessed: AssessedLevel | undefined = assessment === undefined ? undefined : reachedAssessment(assessment).level;\n const silentNow = muted?.effect === \"silent\";\n for (let episode = 0; episode <= closes.length; episode += 1) {\n const closed = closes[episode];\n const current = closed === undefined;\n const ownStarts = mine(starts).filter((item) => episodeOf(item.at) === episode);\n const ownDeliveries = mine(deliveries).filter((item) => episodeOf(item.at) === episode);\n // An earlier episode continues only to cancel its deliveries with no cancel.\n if (!current && ownDeliveries.every((delivery) => input.cancelled.has(delivery.key))) continue;\n const levels = new Set<Level>();\n for (const item of [...ownStarts, ...ownDeliveries]) levels.add(item.level);\n // The starts are the starts of this copy. A level with no start of this copy and above the own assessment of the\n // live incident comes only from the deliveries of another copy. This copy sends nothing at it (AL-76).\n const startedHere = new Set(ownStarts.map((item) => item.level));\n const lower = assessed === undefined ? undefined : ASSESSED_LEVELS.indexOf(assessed);\n const imported = (level: Level): boolean => current && lower !== undefined && !startedHere.has(level) && ASSESSED_LEVELS.indexOf(level) > lower;\n // The level does not go down: an assessed level below a level of the episode starts nothing.\n const top = Math.max(-1, ...[...levels].map((level) => LEVELS.indexOf(level)));\n // The mode of the episode: silent when each of its starts is silent. With no start, a delivery tells a loud\n // episode, and an episode with neither has the mode of now.\n const known = ownStarts.length > 0 ? ownStarts.every((item) => item.silent === true) : ownDeliveries.length > 0 ? false : undefined;\n const silent = known ?? (current && silentNow);\n // A change of the mode between loud and silent ends the episode now. The next episode starts in the new mode.\n const changed = current && assessed !== undefined && assessed !== \"none\" && known !== undefined && known !== silentNow;\n if (current && assessed !== undefined && !changed) {\n if (assessed !== \"none\" && assessed !== \"digest\" && LEVELS.indexOf(assessed) > top && policyOf(assessed) !== undefined) levels.add(assessed);\n }\n // The live incident no longer reaches the person, or the mode changed: the episode ends now, and the log keeps the end.\n const freshEnd = current && ((assessed === \"none\" && levels.size > 0) || changed);\n const reason: EndReason = changed || muted?.effect === \"absent\" ? \"muted\" : \"ended\";\n const closing = closed ?? (freshEnd ? { incident: incident.anchor, person, at: now, ...(reason === \"ended\" ? {} : { reason }) } : undefined);\n if (changed && closing !== undefined) closes.push(closing);\n const why = current && assessment !== undefined ? assessmentWhy(assessment) : undefined;\n // A later episode keeps only the acknowledgments from its first time. An end `muted` joins two episodes: the\n // acknowledgments of the episode before it still count, thus a change of a mute does not alert again.\n let from = episode;\n while (from > 0 && closes[from - 1]?.reason === \"muted\") from -= 1;\n const since = from === 0 ? undefined : firstOf(from);\n const ownAcks = mine(acks).filter((ack) => {\n const at = episodeOf(ack.at);\n return at >= from && at <= episode && (since === undefined || ack.at >= since);\n });\n const ordered = LEVELS.filter((level) => levels.has(level));\n // The start in the log of each level, or `undefined`.\n const logged = ordered.map((level) => earliestStart(ownStarts, person, level));\n // A higher level that has no start starts at `now`. A start of a later episode comes after the end before it, also\n // when the clock has not moved past that end. Thus the start is in its own episode.\n const after = closes[episode - 1]?.at;\n const startAt = ordered.map((_, index) => logged[index]?.at ?? (after === undefined ? now : Math.max(now, after + 1)));\n ordered.forEach((level, index) => {\n const endsAt = earliest([end, closing?.at, ...startAt.slice(index + 1)]);\n // A level of the log with no policy now gets a policy with no step: it sends nothing, and its end still stops its repeats.\n // The channel rules of the person remove some steps of a system, test or exercise incident.\n const ruled = ruleSteps(policyOf(level) ?? { level, steps: [], exhaustedAfter: 0 }, recipient.channelRules, incident);\n const chosen = ruled.policy;\n // The silent mode sends step 0 only, and only when the person has no other delivery of the incident.\n const others = silent && mine(deliveries).some((item) => item.level !== level || episodeOf(item.at) !== episode);\n const planned = escalate({\n policy: silent ? { ...chosen, steps: others ? [] : chosen.steps.slice(0, 1) } : chosen,\n person,\n incident,\n since: startAt[index]!,\n ...(endsAt === undefined ? {} : { endsAt }),\n deliveries: ownDeliveries,\n acknowledgments: ownAcks,\n cancelled: input.cancelled,\n rank: input.rank,\n rankDelay: rankDelayOf(level, input.rankDelays, input.rankDelay),\n floors,\n quiet: recipient.watch.quiet,\n episode,\n silent,\n now,\n });\n // A level of another copy only keeps its timers, polls and cancels. Its sends and its start are the other copy's.\n const shared = imported(level);\n const plan = shared ? { ...planned, sends: [] } : planned;\n const ours = ownDeliveries.filter((delivery) => delivery.level === level);\n const active = plan.state === \"sent\" || plan.state === \"last\" || plan.state === \"exhausted\";\n const polls = active ? ours.filter((delivery) => delivery.receipt !== undefined && !input.cancelled.has(delivery.key) && polling.has(delivery.channel)) : [];\n const found = logged[index];\n const fresh = found === undefined && !shared;\n const start: EscalationStart = { incident: found?.incident ?? incident.anchor, level, person, at: plan.start, ...(silent ? { silent: true } : {}) };\n routes.push({\n incident,\n person,\n policy: chosen,\n start,\n fresh,\n deliveries: ours,\n polls,\n plan,\n episode,\n ...(ruled.rules.length === 0 ? {} : { ruled: { rules: ruled.rules, dropped: ruled.dropped } }),\n ...(closing === undefined ? {} : { end: closing }),\n freshEnd,\n ...(why === undefined ? {} : { why }),\n ...(shared ? { imported: true as const } : {}),\n });\n });\n }\n }\n }\n return routes.sort(\n (a, b) => compareCodeUnits(a.incident.anchor, b.incident.anchor) || compareCodeUnits(a.person, b.person) || a.episode - b.episode || LEVELS.indexOf(a.policy.level) - LEVELS.indexOf(b.policy.level),\n );\n}\n\n/**\n * An exhausted escalation of a real warning (AL-21). The person did not acknowledge the warning in the time of the\n * policy. The function `systemReports` makes a report of it for the people who watch the person.\n */\nexport interface Exhaustion {\n /** The report of the start of the escalation. It stays the same after a merge of the incident. */\n readonly incident: ReportId;\n readonly person: PersonId;\n readonly level: Level;\n readonly episode: number;\n /** The time of the exhaustion. */\n readonly at: Instant;\n /** The kind of the warning. */\n readonly kind: Incident[\"kind\"];\n /** The title of the warning (`incidentTitle`). Thus the people who watch the person know what the person missed. */\n readonly title: string;\n}\n\n/**\n * This function tells if a step of the policy asks the person for an acknowledgment. Such a step is on a channel with\n * an `ack` other than `none`, at a level of its `ackLevels`. A channel with no `ackLevels` asks at each level.\n */\nexport function asksForAck(policy: EscalationPolicy, channels: readonly ChannelDescriptor[]): boolean {\n const known = new Map(channels.map((channel) => [channel.id, channel]));\n return policy.steps.some((step) => {\n const channel = known.get(step.channel);\n return channel !== undefined && channel.ack !== \"none\" && (channel.ackLevels === undefined || channel.ackLevels.includes(policy.level));\n });\n}\n\n/**\n * This function gives the exhausted escalations of the routes (AL-21). A route gives an exhaustion when all of these\n * are true:\n *\n * - The status of its incident is `actual`. Thus a drill, a test and a report of the system give none, and an\n * exhaustion does not give another exhaustion.\n * - The state of its plan is `exhausted`. An acknowledgment or the end of the incident ends the exhaustion.\n * - Its policy has a step after the channel rules. A plan that a channel rule empties sent nothing to the person.\n * - A step of its policy asks for an acknowledgment (`asksForAck`). Without such a step, no acknowledgment can come.\n * - The send limit did not hold it (`Route.held`). A held escalation sent nothing, and the digest tells it.\n * - The throttle did not stop it with no delivery (`Route.suppressed`). Such an escalation sent nothing, and the digest tells it.\n * - Its level is not a level of another copy only (`Route.imported`). That copy gives the exhaustion of its own escalation.\n *\n * The reports give the title of each warning (`incidentTitle`).\n */\nexport function exhaustions(routes: readonly Route[], channels: readonly ChannelDescriptor[], reports: readonly Report[]): Exhaustion[] {\n const found: Exhaustion[] = [];\n for (const entry of routes) {\n const { incident, plan, policy } = entry;\n if (entry.held !== undefined || entry.suppressed !== undefined || entry.imported === true || incident.status !== \"actual\" || plan.state !== \"exhausted\" || plan.exhaustedAt === undefined) continue;\n if (policy.steps.length === 0 || !asksForAck(policy, channels)) continue;\n // The people who watch the person are not in the addresses of a private incident: its title stays out (AL-92).\n found.push({ incident: entry.start.incident, person: entry.person, level: policy.level, episode: entry.episode, at: plan.exhaustedAt, kind: incident.kind, title: isPrivate(incident) ? incident.kind.label : incidentTitle(incident, reports) });\n }\n return found;\n}\n\n/** The codes that can reach `life-safety`: the life-safety kinds, and the coverage of each of them. */\nconst LIFE_SAFETY_CODES: readonly string[] = [...LIFE_SAFETY_KINDS, ...LIFE_SAFETY_KINDS.map((kind) => `${COVERAGE_KIND}.${kind}`)];\n\n/** This function tells if two prefixes of the taxonomy share a kind: one of them has the other. */\nconst overlap = (a: string, b: string): boolean => hasKind([a], b) || hasKind([b], a);\n\n/** This function gives the regular expression of the whole value of a pattern, or `undefined` for a bad pattern. */\nfunction patternOf(source: string): RegExp | undefined {\n try {\n return new RegExp(`^(?:${source})$`, \"u\");\n } catch {\n return undefined;\n }\n}\n\n/**\n * This function gives the problems of an address on a channel, from the fields of its descriptor. A problem\n * names the field and its form, and not its value, because a value can be a secret.\n *\n * - A channel with no list of fields accepts each address.\n * - The address has each necessary field, and each value has the form of its field.\n * - The address has no field that the channel does not read. Thus a typo of a field name is a problem, not a silent default.\n * - A pattern that is not a regular expression is a problem of the channel. The function does not throw.\n */\nexport function addressProblems(address: Address, channel: ChannelDescriptor): string[] {\n if (channel.address === undefined) return [];\n const problems: string[] = [];\n // Own fields only: a field such as `constructor` is not a field of a plain object.\n const valueOf = (name: string): string | undefined => (Object.hasOwn(address, name) ? address[name] : undefined);\n for (const field of channel.address) {\n const value = valueOf(field.name);\n if (value === undefined) {\n if (field.required) problems.push(`The address on ${channel.id} has no field ${field.name}. The channel needs ${field.form}.`);\n continue;\n }\n const form = patternOf(field.pattern);\n if (form === undefined) problems.push(`The channel ${channel.id} gives the field ${field.name} a pattern that is not a regular expression.`);\n else if (!form.test(value)) problems.push(`The field ${field.name} of the address on ${channel.id} is not ${field.form}.`);\n }\n const names = new Set(channel.address.map((field) => field.name));\n for (const name of Object.keys(address)) if (!names.has(name)) problems.push(`The address on ${channel.id} has the field ${name}, and the channel reads no such field.`);\n return problems;\n}\n\n/**\n * This function gives the problems of a recipient. `route` accepts each recipient, but a recipient with\n * a problem does not get what its author meant. A kind with a typo matches no alert, so it can stop a wake.\n *\n * A life-safety alert always gets its escalation. Thus a person who watches a place or a subject has a\n * `life-safety` policy, and no rule keeps a life-safety kind below `life-safety`.\n *\n * Each address on a known channel has the fields of its channel (`addressProblems`). An address on a channel that the\n * system does not know is not a problem: no step can use it.\n */\nexport function recipientProblems(recipient: Recipient, channels: readonly ChannelDescriptor[]): string[] {\n const problems: string[] = [];\n const known = new Map(channels.map((channel) => [channel.id as string, channel]));\n for (const [id, address] of Object.entries(recipient.addresses)) {\n const channel = known.get(id);\n if (channel !== undefined) problems.push(...addressProblems(address, channel));\n }\n // The level and the subject of each policy. Two policies with the same name: only the first one applies.\n const seen = new Set<string>();\n for (const policy of recipient.policies) {\n const name = policyName(policy);\n if (seen.has(name)) problems.push(`Two policies have the level ${name}. Only the first one applies.`);\n seen.add(name);\n for (const problem of escalationProblems(policy)) problems.push(`The policy of ${name}: ${problem}`);\n policy.steps.forEach((step, index) => {\n if (!known.has(step.channel)) problems.push(`Step ${index} of ${name} uses the channel ${step.channel}, and the system has no such channel.`);\n if (recipient.addresses[step.channel] === undefined) problems.push(`Step ${index} of ${name} uses the channel ${step.channel}, and the person has no address on it.`);\n });\n }\n // A policy with a subject does not apply to a real warning. Thus only a policy with no subject covers life-safety.\n const watches = recipient.watch.places.length > 0 || (recipient.watch.subjects ?? []).length > 0;\n if (watches && !seen.has(\"life-safety\")) problems.push(\"The person watches a place or a subject, and has no policy of the level life-safety. A life-safety alert sends nothing to the person.\");\n // The exhausted escalations of a person go to the other people who watch the person (AL-21), never to the person.\n if ((recipient.watch.subjects ?? []).some((subject) => subject.system === PERSON_SUBJECT && subject.id === recipient.watch.person)) {\n problems.push(`The person watches the subject ${PERSON_SUBJECT} of the person itself. The exhausted escalations of a person never reach that person.`);\n }\n recipient.watch.rules.forEach((rule, index) => {\n for (const code of unknownKinds(rule.kinds ?? [])) problems.push(`Rule ${index} names the kind ${code}, and the taxonomy has no such code. The rule matches no alert of it.`);\n // A rule only at places that the person does not watch matches no alert. A rule with an empty list of kinds also matches none.\n if (rule.max === \"life-safety\" || (rule.places !== undefined && !rule.places.some((place) => recipient.watch.places.includes(place)))) return;\n const capped = rule.kinds === undefined ? [\"each kind\"] : rule.kinds.filter((kind) => LIFE_SAFETY_CODES.some((code) => overlap(kind, code)));\n if (capped.length > 0) problems.push(`Rule ${index} keeps ${capped.join(\", \")} at ${rule.max} or lower. A life-safety kind is in it, and a rule does not keep a life-safety kind below life-safety.`);\n });\n (recipient.channelRules ?? []).forEach((rule, index) => {\n for (const code of unknownKinds(rule.kinds)) problems.push(`Channel rule ${index} names the kind ${code}, and the taxonomy has no such code.`);\n if (rule.kinds.length === 0) problems.push(`Channel rule ${index} has no kind. It applies to no incident.`);\n for (const channel of rule.channels) if (!known.has(channel)) problems.push(`Channel rule ${index} names the channel ${channel}, and the system has no such channel.`);\n });\n if (recipient.watch.quiet !== undefined) for (const problem of quietWindowProblems(recipient.watch.quiet)) problems.push(`The quiet window: ${problem}`);\n // The time of the digest: the daily time of the policy, or the end of the quiet window. Neither is a problem, not a silent default.\n for (const policy of recipient.policies) {\n const name = policyName(policy);\n if (policy.daily !== undefined && policy.level !== \"digest\") problems.push(`The policy of ${name} has a daily time. Only a policy of the level digest uses it.`);\n if (policy.daily !== undefined) for (const problem of dailyTimeProblems(policy.daily)) problems.push(`The daily time of the policy of ${name}: ${problem}`);\n if (policy.level === \"digest\" && digestTimeOf(policy, recipient.watch.quiet) === undefined) {\n problems.push(`The policy of ${name} has no daily time, and the person has no quiet window. The person gets no digest.`);\n }\n }\n return problems;\n}\n\n/**\n * This function makes the message of a send. The text comes from one report of the incident. That\n * report has the severity and the urgency of the incident, and it is the latest one by its time of\n * sending. The channel cuts the text to its limits.\n *\n * A message of the line `system.quota.reserve` can use the reserve of the quota. Else the reserve\n * stops the message that tells of it.\n *\n * The `why` is the why line of the channel, from `whyLine`. An empty line gives no field.\n */\nexport function messageOf(incident: Incident, reports: readonly Report[], send: EscalationSend, why?: string): Message {\n const report = textReport(incident, reports);\n const title = titleOf(incident, report);\n const body = [report?.instruction, report?.areaText, report?.description].flatMap((part) => (part === undefined || part.trim() === \"\" ? [] : [part.trim()])).join(\"\\n\\n\");\n return {\n key: messageKey(send),\n person: send.person,\n level: send.level,\n title,\n body,\n ...(report?.web === undefined ? {} : { url: report.web }),\n incident: send.incident,\n ...(incident.expires === undefined ? {} : { expires: incident.expires }),\n quiet: send.quiet,\n ...(incident.kind.code === `${QUOTA_KIND}.reserve` ? { useReserve: true } : {}),\n ...(why === undefined || why === \"\" ? {} : { why }),\n };\n}\n\n/**\n * This function gives the title of an incident in a message. The title is the headline of the report of the text\n * (`messageOf`). With no headline, it is the label of the kind of the incident.\n */\nexport function incidentTitle(incident: Incident, reports: readonly Report[]): string {\n return titleOf(incident, textReport(incident, reports));\n}\n\nconst titleOf = (incident: Incident, report: Report | undefined): string => report?.headline.trim() || incident.kind.label;\n\n/** This function gives the acknowledgment that a status of a delivery tells, or `undefined`. */\nexport function acknowledgmentOf(delivery: Delivery, status: DeliveryStatus): Acknowledgment | undefined {\n if (status.state !== \"acknowledged\") return undefined;\n return { incident: delivery.incident, level: delivery.level, person: delivery.person, at: status.at, via: delivery.channel };\n}\n\n// The end of an incident: its expiry, or `now` when it is not live and its expiry is not earlier.\nfunction endOf(incident: Incident, now: Instant): Instant | undefined {\n const expires = incident.expires !== undefined && Number.isFinite(incident.expires) ? incident.expires : undefined;\n if (incident.live) return expires;\n return expires !== undefined && expires <= now ? expires : now;\n}\n\nfunction earliest(times: readonly (Instant | undefined)[]): Instant | undefined {\n let found: Instant | undefined;\n for (const time of times) if (time !== undefined && Number.isFinite(time) && (found === undefined || time < found)) found = time;\n return found;\n}\n\n// The earliest start in the log of a person and a level. A tie goes to the smallest report id.\nfunction earliestStart(starts: readonly EscalationStart[], person: PersonId, level: Level): EscalationStart | undefined {\n let found: EscalationStart | undefined;\n for (const start of starts) {\n if (start.person !== person || start.level !== level || !Number.isFinite(start.at)) continue;\n if (found === undefined || start.at < found.at || (start.at === found.at && compareCodeUnits(start.incident, found.incident) < 0)) found = start;\n }\n return found;\n}\n\n// The report of the text of a message. The reports come from the merge state, in the order of their ids.\nfunction textReport(incident: Incident, reports: readonly Report[]): Report | undefined {\n const members = new Set<string>(incident.reports);\n let found: Report | undefined;\n for (const report of reports) {\n if (!members.has(report.id)) continue;\n const matches = report.severity === incident.severity && report.urgency === incident.urgency;\n const foundMatches = found !== undefined && found.severity === incident.severity && found.urgency === incident.urgency;\n if (found === undefined || (matches && !foundMatches) || (matches === foundMatches && report.sent > found.sent)) found = report;\n }\n return found;\n}\n","/**\n * This module plans the digest: one message each day for each person with a policy of the level `digest`. It is\n * pure. The runtime gives the time, and the runtime does each call of a channel.\n *\n * The digest tells two kinds of incidents:\n *\n * - Each live incident of the level `digest` for the person that no earlier digest told, and that no louder message told.\n * - Each incident that a quiet message of the level `notice` or `urgent` told in the quiet window since the digest time before.\n * Thus the morning digest tells again what came in the night.\n * - Each incident that the send limit held or the throttle stopped since the digest time before, with no message to the person (AL-72).\n *\n * The record of a digest is one delivery for each incident in it (`digestDeliveries`). The merge state keeps each delivery, thus\n * a restart and each other copy of the system know which incidents a digest told. A send that failed makes no record, thus\n * the digest stays due.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { assess, DEFAULT_ASSESS_POLICY, foreignIncidents, reachedAssessment } from \"./assess.ts\";\nimport {\n LEVELS,\n type AssessPolicy,\n type ChannelDescriptor,\n type ChannelId,\n type Delivery,\n type Duration,\n type Incident,\n type Instant,\n type Level,\n type MergeState,\n type Message,\n type PersonId,\n type Receipt,\n type Report,\n type WatchedPlace,\n} from \"./contracts.ts\";\nimport { incidentTitle, policyFor, type EscalationHold, type Recipient } from \"./delivery.ts\";\nimport { dailyInstant, digestTimeOf, inQuietWindow, rankDelayOf, rankFloors, type RankDelays } from \"./escalation.ts\";\nimport { digestEntryKey, digestKey } from \"./ids.ts\";\n\n/** The input of `planDigests`. */\nexport interface DigestInput {\n readonly state: MergeState;\n /** The incidents of the merge state at `now`. */\n readonly incidents: readonly Incident[];\n readonly recipients: readonly Recipient[];\n readonly places: readonly WatchedPlace[];\n /** The policy of the assessment. The default is `DEFAULT_ASSESS_POLICY`. */\n readonly assess?: AssessPolicy | undefined;\n /** The ids of the sources of this copy, as `RouteInput.sources` tells (AL-76). Without the set, each source is a source of this copy. */\n readonly sources?: ReadonlySet<string> | undefined;\n /** The channels of the system. The rank floor applies to the exclusive channels. */\n readonly channels: readonly ChannelDescriptor[];\n /** The rank of this copy of the system, from 0. A copy waits `rank × max(rank delay, floor)` before each send. */\n readonly rank?: number | undefined;\n /** The default wait of one rank. */\n readonly rankDelay?: Duration | undefined;\n /** The wait of one rank for each level. The entry `digest` applies. */\n readonly rankDelays?: RankDelays | undefined;\n /** The least wait of one rank before a send on an exclusive channel. */\n readonly rankFloor?: Duration | undefined;\n /** The holds of the send limit (`limitRoutes`) and the suppressions of the throttle (`throttleRoutes`). The default is no hold. */\n readonly holds?: readonly EscalationHold[] | undefined;\n readonly now: Instant;\n}\n\n/** One incident in a digest. */\nexport interface DigestEntry {\n readonly incident: Incident;\n /** `digest`, or the highest level of a quiet message or a hold of the incident for the person since the digest before. */\n readonly level: Level;\n}\n\n/** One digest message of one person on one step of the digest policy. */\nexport interface DigestSend {\n readonly person: PersonId;\n readonly channel: ChannelId;\n /** The index of the step in the digest policy, from 0. */\n readonly step: number;\n /** The digest time: the last instant of the daily time at or before `now`. */\n readonly at: Instant;\n /** The time at which the send is due: the digest time, then the time of the step, then the wait of the rank. */\n readonly due: Instant;\n /** The key of the message, from `digestKey`. */\n readonly key: string;\n /** True when `now` is in the quiet window of the person. */\n readonly quiet: boolean;\n /** The incidents of the digest, from the highest level, then from the earliest receipt. */\n readonly entries: readonly DigestEntry[];\n}\n\n/** The digests at `now`. */\nexport interface DigestPlan {\n /** The digest messages that are due at `now`. */\n readonly sends: readonly DigestSend[];\n /** The earliest time after `now` at which a digest can come due. */\n readonly wakeAt?: Instant;\n}\n\n/**\n * This function gives the digests at `now`. A person gets a digest when the person has a policy of the level `digest`\n * with no subject, and a daily time (`digestTimeOf`). Each step of the policy sends one message on its channel.\n *\n * - The digest time is the last instant of the daily time at or before `now`. A digest tells only the incidents that\n * the system got at or before the digest time. Thus a later incident waits for the next digest, also when the digest\n * of today had nothing to tell.\n * - An incident of the level `digest` goes in one digest of each step. A delivery of a louder level to the person\n * keeps it out, because the person already has its message.\n * - A quiet message of `notice` or `urgent` in the quiet window puts its incident in the digest again. The message is after\n * the digest time before, and at or before the digest time. The entry has the highest such level. A digest of this\n * digest time that told the incident keeps it out.\n * - A hold of the send limit or a suppression of the throttle puts its incident in the digest. This applies only when\n * the person has no message of the incident. The hold is after the digest time before, and at or before the digest\n * time. The entry has the highest level of such holds. A digest of this digest time that told the incident keeps it\n * out.\n * - A digest with no incident sends nothing.\n * - Each step of a person sends one digest for each digest time, across the copies. A digest delivery of the step at or\n * after the digest time keeps the step quiet. Thus the entries that only this copy knows wait for the next digest.\n * - A runtime that was down at the digest time sends the digest when it comes back, until the next digest time.\n */\nexport function planDigests(input: DigestInput): DigestPlan {\n const { state, now } = input;\n const policy = input.assess ?? DEFAULT_ASSESS_POLICY;\n const floors = rankFloors(input.channels, input.rankFloor);\n const rank = nonNegative(input.rank);\n const delay = nonNegative(rankDelayOf(\"digest\", input.rankDelays, input.rankDelay));\n const isForeign = foreignIncidents(state.reports, input.sources);\n const received = new Map<string, Instant>();\n for (const report of state.reports) {\n const known = received.get(report.id);\n if (Number.isFinite(report.received) && (known === undefined || report.received < known)) received.set(report.id, report.received);\n }\n // The earliest receipt of a report of the incident. An incident with no time of receipt is not in a digest.\n const receiptOf = (incident: Incident): Instant => Math.min(...[incident.anchor, ...incident.reports].map((id) => received.get(id) ?? Number.POSITIVE_INFINITY));\n const sends: DigestSend[] = [];\n const wakes: Instant[] = [];\n for (const recipient of input.recipients) {\n const { watch } = recipient;\n const person = watch.person;\n const digest = policyFor(recipient.policies, \"digest\", { status: \"actual\", about: [] });\n const daily = digest === undefined ? undefined : digestTimeOf(digest, watch.quiet);\n if (digest === undefined || daily === undefined) continue;\n const waitOf = (channel: ChannelId): Duration => rank * Math.max(delay, floors.get(channel) ?? 0);\n const upcoming = dailyInstant(daily, now, true);\n if (upcoming !== undefined) for (const step of digest.steps) wakes.push(upcoming + nonNegative(step.at) + waitOf(step.channel));\n const at = dailyInstant(daily, now);\n if (at === undefined) continue;\n const before = dailyInstant(daily, at - 1);\n const mine = state.deliveries.filter((delivery) => delivery.person === person);\n const holds = (input.holds ?? []).filter((hold) => hold.person === person && hold.at <= at && (before === undefined || hold.at > before));\n digest.steps.forEach((step, index) => {\n // Another copy, or this copy before a restart, sent the digest of this time and step. Its record is in the shared ledger.\n if (mine.some((delivery) => delivery.level === \"digest\" && delivery.step === index && delivery.at >= at)) return;\n const entries: DigestEntry[] = [];\n for (const incident of input.incidents) {\n const reports = new Set<string>([incident.anchor, ...incident.reports]);\n const own = mine.filter((delivery) => reports.has(delivery.incident));\n const told = own.filter((delivery) => delivery.level === \"digest\" && delivery.step === index);\n const louder = own.filter((delivery) => delivery.level !== \"digest\");\n const night = louder.filter(\n (delivery) => delivery.level !== \"life-safety\" && delivery.at <= at && (before === undefined || delivery.at > before) && inQuietWindow(watch.quiet, delivery.at),\n );\n if (night.length > 0) {\n if (!told.some((delivery) => delivery.at >= at)) entries.push({ incident, level: highest(night.map((delivery) => delivery.level)) });\n continue;\n }\n const held = louder.length === 0 ? holds.filter((hold) => reports.has(hold.incident)) : [];\n if (held.length > 0) {\n if (!told.some((delivery) => delivery.at >= at)) entries.push({ incident, level: highest(held.map((hold) => hold.level)) });\n continue;\n }\n if (louder.length > 0 || told.length > 0 || !incident.live || !(receiptOf(incident) <= at)) continue;\n if (reachedAssessment(assess(incident, watch, input.places, policy, now, isForeign(incident))).level === \"digest\") entries.push({ incident, level: \"digest\" });\n }\n if (entries.length === 0) return;\n const due = at + nonNegative(step.at) + waitOf(step.channel);\n if (now < due) {\n wakes.push(due);\n return;\n }\n entries.sort(\n (a, b) => LEVELS.indexOf(b.level) - LEVELS.indexOf(a.level) || receiptOf(a.incident) - receiptOf(b.incident) || compareCodeUnits(a.incident.anchor, b.incident.anchor),\n );\n sends.push({ person, channel: step.channel, step: index, at, due, key: digestKey({ person, at, step: index }), quiet: inQuietWindow(watch.quiet, now), entries });\n });\n }\n const later = wakes.filter((time) => Number.isFinite(time) && time > now);\n return later.length === 0 ? { sends } : { sends, wakeAt: Math.min(...later) };\n}\n\n/**\n * This function makes the message of a digest. The title has the count of the incidents. The body has one line for\n * each incident: its title (`incidentTitle`), after its level when the level is not `digest`. The channel cuts the text\n * to its limits. The incident of the message is the first incident of the digest.\n */\nexport function digestMessageOf(send: DigestSend, reports: readonly Report[]): Message {\n const count = send.entries.length;\n const lines = send.entries.map((entry) => `- ${entry.level === \"digest\" ? \"\" : `${entry.level}: `}${incidentTitle(entry.incident, reports)}`);\n return {\n key: send.key,\n person: send.person,\n level: \"digest\",\n title: count === 1 ? \"The digest: 1 alert\" : `The digest: ${String(count)} alerts`,\n body: lines.join(\"\\n\"),\n // A send of `planDigests` has one incident or more.\n incident: send.entries[0]!.incident.anchor,\n quiet: send.quiet,\n };\n}\n\n/**\n * This function gives the record of a digest that a channel accepted. The record is one delivery of the level `digest`\n * for each incident of the digest. Each delivery has the time of the accept and the receipt of the channel.\n */\nexport function digestDeliveries(send: DigestSend, accepted: Instant, receipt?: Receipt): Delivery[] {\n return send.entries.map((entry) => ({\n key: digestEntryKey(send.key, entry.incident.anchor),\n incident: entry.incident.anchor,\n level: \"digest\",\n person: send.person,\n channel: send.channel,\n step: send.step,\n at: accepted,\n ...(receipt === undefined ? {} : { receipt }),\n }));\n}\n\nconst nonNegative = (value: number | undefined): number => (value !== undefined && Number.isFinite(value) && value > 0 ? value : 0);\n\n// The highest of some levels. An empty list gives `digest`.\nconst highest = (levels: readonly Level[]): Level => LEVELS[Math.max(0, ...levels.map((level) => LEVELS.indexOf(level)))]!;\n","/**\n * The coverage of each kind at each place. It gives the sources that are up, the count of their\n * independent outside failure domains, and the resources of the cell that they share. It is a pure\n * calculation on the descriptors, the health and the places. It reads no clock.\n *\n * `independent` is the size of the smallest set of outside domains whose faults stop each of the\n * sources. That is a minimum hitting set, and `@mark1russell7/collections/graph` calculates it.\n */\nimport { minimumHittingSet, type HittingSetChoice } from \"@mark1russell7/collections/graph\";\nimport { CONTEXT_KINDS, hasKind, LIFE_SAFETY_KINDS, regionContains } from \"./assess.ts\";\nimport type { Coverage, HealthState, RegionCode, SourceDescriptor, SourceHealth, SourceId, WatchedPlace } from \"./contracts.ts\";\nimport { CELL_RESOURCES } from \"./contracts.ts\";\nimport { isShape, shapeDistanceKm } from \"./shapes.ts\";\n\n/** The count of independent outside domains that a class of kinds needs. */\nexport interface CoverageNeed {\n /** The prefixes of the taxonomy codes of the class. */\n readonly kinds: readonly string[];\n readonly required: number;\n}\n\n/** The policy of the coverage. */\nexport interface CoveragePolicy {\n /** The health states in which a source counts for the coverage. */\n readonly up: readonly HealthState[];\n /** The needs of the classes of kinds. The first need whose prefixes have the kind applies. */\n readonly needs: readonly CoverageNeed[];\n /** The count for a kind that no need has. */\n readonly otherwise: number;\n /** The largest count of steps of the search of the hitting set. Absent: the default of the search. */\n readonly maxSteps?: number;\n}\n\n/**\n * The first policy. A source counts when it is `healthy` or `slow`. Each life-safety kind needs 2\n * independent domains, so no single outside fault stops it. A kind of context (`CONTEXT_KINDS`) needs none,\n * because its reports reach the digest at most. Each other kind needs 1.\n */\nexport const DEFAULT_COVERAGE_POLICY: CoveragePolicy = {\n up: [\"healthy\", \"slow\"],\n needs: [\n { kinds: LIFE_SAFETY_KINDS, required: 2 },\n { kinds: CONTEXT_KINDS, required: 0 },\n ],\n otherwise: 1,\n};\n\n/** What the coverage needs: the sources, their health, the places and the kinds to examine. */\nexport interface CoverageInput {\n readonly sources: readonly SourceDescriptor[];\n /** The health of the sources. A source with no health is `unknown`. */\n readonly health: readonly SourceHealth[];\n /**\n * The sources that are late against another source, from `lateSources`. A late source does not\n * count, also when its health state is up: its fetches pass, but it does not carry the reports.\n */\n readonly late?: readonly SourceId[];\n readonly places: readonly WatchedPlace[];\n /** The taxonomy codes or prefixes to examine at each place. */\n readonly kinds: readonly string[];\n /**\n * The codes of the regions that hold all of the region of a code, for example the state of a zone. The coverage adds them\n * to the codes of each place, and then the codes of those codes. Without it, a place has only its own codes. The core knows\n * no system of codes, so the package of a format gives this function.\n */\n readonly containing?: (code: RegionCode) => readonly RegionCode[];\n}\n\n/** The largest count of codes of one place, with the codes that `containing` adds. */\nexport const MAX_PLACE_CODES = 1000;\n\n/**\n * This function gives the codes of a place and each code that `containing` gives for them, again and again, with no\n * code two times. The codes of the place stay first, in their order.\n *\n * @throws RangeError when the place gets more than `MAX_PLACE_CODES` codes, because the function gives codes with no end.\n */\nexport function placeCodesWithContaining(codes: readonly RegionCode[], containing: (code: RegionCode) => readonly RegionCode[]): RegionCode[] {\n const all: RegionCode[] = [];\n const seen = new Set<string>();\n const add = (code: RegionCode): void => {\n const key = JSON.stringify([code.system, code.code]);\n if (seen.has(key)) return;\n if (all.length >= MAX_PLACE_CODES) throw new RangeError(`A place has more than ${MAX_PLACE_CODES} codes with the codes that contain them.`);\n seen.add(key);\n all.push({ system: code.system, code: code.code });\n };\n codes.forEach(add);\n for (let at = 0; at < all.length; at += 1) {\n const code = all[at];\n if (code !== undefined) containing(code).forEach(add);\n }\n return all;\n}\n\n/**\n * This function tells if a source covers a kind at a place, when the source is up.\n *\n * - One prefix of the source must have the kind. A source of a part of the kind does not count: the\n * prefix `met.tornado.warning` does not cover the kind `met.tornado`.\n * - The coverage of the source must be `global`, or an area of the coverage must hold the place. A\n * code of the coverage must hold a code of the place (`regionContains`), or a shape must contain the\n * position of the place.\n * - A shape covers no place with no position. A shape that `@mark1russell7/geo` refuses covers no\n * place, so the coverage shows a gap.\n */\nexport function sourceCovers(source: SourceDescriptor, place: WatchedPlace, kind: string): boolean {\n if (!hasKind(source.kinds, kind)) return false;\n if (source.coverage === \"global\") return true;\n const at = place.at;\n return source.coverage.some((area) =>\n area.type === \"code\"\n ? place.codes.some((code) => regionContains(area, code))\n : isShape(area) && at !== undefined && shapeDistanceKm(area, at) === 0,\n );\n}\n\n/**\n * This function gives the outside failure domains of a source for the coverage. A source with no\n * domain gets its own domain `source:<id>`, so it is independent of each other source.\n */\nexport function failureDomains(source: SourceDescriptor): readonly string[] {\n return source.dependsOn.length > 0 ? source.dependsOn : [`source:${source.id}`];\n}\n\n/** This function gives the count of independent domains that the policy needs for a kind. */\nexport function requiredFor(policy: CoveragePolicy, kind: string): number {\n return policy.needs.find((need) => hasKind(need.kinds, kind))?.required ?? policy.otherwise;\n}\n\n/**\n * This function gives the coverage of each kind at each place, in the order of the places and then\n * of the kinds. The sources of each coverage are in the order of the input. With `containing`, a\n * source of a region that holds a code of a place covers that place.\n *\n * @throws RangeError when `containing` gives more than `MAX_PLACE_CODES` codes for one place.\n */\nexport function coverage(input: CoverageInput, policy: CoveragePolicy = DEFAULT_COVERAGE_POLICY): Coverage[] {\n const states = new Map<SourceId, HealthState>(input.health.map((entry) => [entry.source, entry.state]));\n const late = new Set(input.late ?? []);\n const up = input.sources.filter((source) => policy.up.includes(states.get(source.id) ?? \"unknown\") && !late.has(source.id));\n const { containing } = input;\n const places = containing === undefined ? input.places : input.places.map((place) => ({ ...place, codes: placeCodesWithContaining(place.codes, containing) }));\n return places.flatMap((place) =>\n input.kinds.map((kind) => coverageOf(place.id, kind, up.filter((source) => sourceCovers(source, place, kind)), requiredFor(policy, kind), policy)),\n );\n}\n\n/**\n * This function tells if a coverage is below its policy. A coverage that the search did not prove\n * is also below, because its true count can be smaller. A policy that needs no source has no gap, also\n * when the search of many sources stops at its budget.\n */\nexport function coverageShort(entry: Coverage): boolean {\n return entry.required > 0 && (!entry.proven || entry.independent < entry.required);\n}\n\nfunction coverageOf(place: Coverage[\"place\"], kind: string, sources: readonly SourceDescriptor[], required: number, policy: CoveragePolicy): Coverage {\n const search = minimumHittingSet<string>(sources.map(failureDomains), policy.maxSteps === undefined ? {} : { maxSteps: policy.maxSteps });\n // Each set of domains has one or more domains, so the result is never none.\n const found: HittingSetChoice<string> = search.kind === \"budget\" ? search.best : search.kind === \"exact\" ? search : { elements: [], weight: 0 };\n const commonResources = CELL_RESOURCES.filter((resource) => sources.length > 0 && sources.every((source) => source.uses.includes(resource)));\n return {\n place,\n kind,\n sources: sources.map((source) => source.id),\n independent: found.elements.length,\n proven: search.kind === \"exact\",\n faults: found.elements,\n commonResources,\n required,\n };\n}\n","/**\n * The drills of the live paths (AL-43). The fakes and the fault cases of CI test the code. Only a drill tests the live\n * path: the provider, the phone and the person. A drill is data: a path, the least time between two starts, a window of\n * the starts and the time of the acknowledgment. A drill with no acknowledgment in its time fails.\n *\n * The functions are pure. They read no clock. The runs of each copy come in as data, and two runs of one start join\n * into one run. Thus the order of the runs has no effect.\n */\nimport { inWindow, nextBoundary, windowProblems, type TimeWindow } from \"@mark1russell7/algebra/clock\";\nimport type { ChannelDescriptor, ChannelId, CopyWatch, Duration, Instant, PersonId, QuietWindow } from \"./contracts.ts\";\nimport { inQuietWindow } from \"./escalation.ts\";\n\n/**\n * The path of a drill: one channel of the escalation of the person. A drill goes as a system report of the level\n * `life-safety`, with the subject `DRILL_SUBJECT`. Thus it goes through the route and the escalation policy of a\n * life-safety warning. Only an acknowledgment of a delivery on this channel counts for the drill.\n */\nexport interface DrillPath {\n readonly kind: \"channel\";\n readonly channel: ChannelId;\n}\n\n/** One drill of the configuration. */\nexport interface DrillConfig {\n /** The id of the drill: 1 to 32 lowercase letters, digits and hyphens. */\n readonly id: string;\n /** The person who acknowledges the drill. */\n readonly person: PersonId;\n readonly path: DrillPath;\n /**\n * The least time from the start of one drill to the start of the next. For a drill on one day of each week, give\n * 6 days and a window on that day.\n */\n readonly every: Duration;\n /** The window of the starts. A drill starts only in this window, and not in the quiet window of the person. */\n readonly window: TimeWindow;\n /** The time from the start to the acknowledgment. With no acknowledgment in this time, the drill fails. */\n readonly ackWithin: Duration;\n /**\n * The ids of the copies that start the drill. Each of them starts its own runs. Without the list, only the copy of\n * rank 0 starts the drill. Thus two copies do not send one drill at once.\n */\n readonly copies?: readonly string[];\n}\n\n/** One run of a drill: its start, and the first acknowledgment of a delivery on the channel of the path. */\nexport interface DrillRun {\n /** The id of the drill. */\n readonly drill: string;\n /** The start of the run. */\n readonly at: Instant;\n /** The time of the acknowledgment. */\n readonly acked?: Instant;\n}\n\n/**\n * The verdict of a run at a time.\n *\n * - `pending`: the run has no acknowledgment, and its time continues until `until`.\n * - `passed`: the acknowledgment came in its time, `after` the start.\n * - `failed`: no acknowledgment came in the time (`no-ack`), or it came late (`late-ack`).\n */\nexport type DrillVerdict =\n | { readonly state: \"pending\"; readonly until: Instant }\n | { readonly state: \"passed\"; readonly after: Duration }\n | { readonly state: \"failed\"; readonly why: \"no-ack\" | \"late-ack\" };\n\n// The most changes of the windows that the search of the next start reads. Each change is one boundary of the window of\n// the drill or of the quiet window. Thus a drill with a window in the quiet window gives no start, and the search stops.\nconst SEARCH_LIMIT = 64;\n\n/**\n * This function joins two runs of one start into one run: the earlier acknowledgment counts. The join is idempotent,\n * commutative and associative.\n */\nexport function joinRuns(a: DrillRun, b: DrillRun): DrillRun {\n const acked = a.acked === undefined ? b.acked : b.acked === undefined ? a.acked : Math.min(a.acked, b.acked);\n return acked === undefined ? { drill: a.drill, at: a.at } : { drill: a.drill, at: a.at, acked };\n}\n\n/** This function gives the last run of the drill `id`: the run with the latest start, joined with each run of that start. */\nexport function lastRun(runs: readonly DrillRun[], id: string): DrillRun | undefined {\n let last: DrillRun | undefined;\n for (const run of runs) {\n if (run.drill !== id || !Number.isFinite(run.at)) continue;\n if (last === undefined || run.at > last.at) last = run;\n else if (run.at === last.at) last = joinRuns(last, run);\n }\n return last;\n}\n\n/** This function gives the verdict of the run of a drill at the time `at`. */\nexport function drillVerdict(drill: DrillConfig, run: DrillRun, at: Instant): DrillVerdict {\n const until = run.at + drill.ackWithin;\n if (run.acked !== undefined) return run.acked <= until ? { state: \"passed\", after: Math.max(0, run.acked - run.at) } : { state: \"failed\", why: \"late-ack\" };\n return at < until ? { state: \"pending\", until } : { state: \"failed\", why: \"no-ack\" };\n}\n\n/**\n * This function gives the next start of a drill at the time `at` or later. A timer can wait for it. The start is in the\n * window of the drill, and it is `every` or more after the last start. The time of the acknowledgment from the start\n * ends before the next quiet window of the person. Thus a drill does not wake the person in the quiet window.\n *\n * The function gives `undefined` for a bad window and for a bad quiet window. It also gives `undefined` with no start in\n * the next 64 changes of the two windows. Thus a drill with a window in the quiet window has no start.\n */\nexport function nextDrillAt(drill: DrillConfig, runs: readonly DrillRun[], at: Instant, quiet?: QuietWindow): Instant | undefined {\n const last = lastRun(runs, drill.id);\n let time = last === undefined ? at : Math.max(at, last.at + drill.every);\n for (let step = 0; step < SEARCH_LIMIT; step += 1) {\n const window = !inWindow(time, drill.window) ? drill.window : quiet !== undefined && inQuietWindow(quiet, time) ? quiet : undefined;\n if (window === undefined) {\n if (!Number.isFinite(time)) return undefined;\n // The next quiet window opens in the time of the acknowledgment: the search goes on from that opening.\n const opening = quiet === undefined ? undefined : nextBoundary(time, quiet);\n if (opening === undefined || opening.at >= time + drill.ackWithin) return time;\n time = opening.at;\n continue;\n }\n const boundary = nextBoundary(time, window);\n if (boundary === undefined) return undefined;\n time = boundary.at;\n }\n return undefined;\n}\n\n/** This function tells if the copy `copy` of the rank `rank` starts the drill. */\nexport function drillInCopy(drill: DrillConfig, copy: string, rank: number): boolean {\n return drill.copies === undefined ? rank === 0 : drill.copies.includes(copy);\n}\n\n/** This function tells if a drill starts at the time `at`: the next start of the drill is `at`. */\nexport function drillDue(drill: DrillConfig, runs: readonly DrillRun[], at: Instant, quiet?: QuietWindow): boolean {\n return nextDrillAt(drill, runs, at, quiet) === at;\n}\n\n/**\n * This function gives the start that a drill missed, or `undefined`. The missed start is the next start after the last\n * run. It is before `at`, and the drill is not due at `at`. Thus the window of that start ended with no run.\n *\n * - A copy that stops for the full window misses the start. At its next pass, the missed start is a fact.\n * - A late start in the same window is not a miss: the drill is due, and it tests the path.\n * - Before the first run, no start is missed: the configuration gives no time from which to count.\n * - A reload that makes a drill due earlier also gives a missed start, until the next run.\n */\nexport function missedDrillAt(drill: DrillConfig, runs: readonly DrillRun[], at: Instant, quiet?: QuietWindow): Instant | undefined {\n const last = lastRun(runs, drill.id);\n if (last === undefined) return undefined;\n const expected = nextDrillAt(drill, [last], last.at, quiet);\n return expected !== undefined && expected < at && !drillDue(drill, runs, at, quiet) ? expected : undefined;\n}\n\n/**\n * One drill that another copy starts, in the watch of this copy. A copy that stops for the full window of a start reports\n * nothing in that time. Thus each other copy watches the starts of that copy, and it tells of a start that did not come.\n */\nexport interface DrillWatch {\n readonly drill: DrillConfig;\n /** The quiet window of the person of the drill. */\n readonly quiet?: QuietWindow;\n /**\n * The copy that starts the drill: an id of the list `copies` of the drill. Without it, the copy of rank 0 starts the\n * drill, and each other copy can be that copy.\n */\n readonly copy?: string;\n}\n\n/**\n * The time after the end of the window of a start before the watch tells of a miss: 15 minutes. In this time, the\n * exchange brings a late start of the other copy. A read of the exchange comes each few seconds.\n */\nexport const DRILL_WATCH_GRACE: Duration = 15 * 60_000;\n\n/** A start of a drill that the watch did not see (`watchedDrillMiss`). */\nexport interface DrillWatchMiss {\n /** The start that the watch did not see. */\n readonly due: Instant;\n /** The end of the window of that start. */\n readonly end: Instant;\n /**\n * The reason of the miss.\n *\n * - `unseen`: no read gives a start at `due` or later. The copy did not answer after the end of the window, or it did not start the drill.\n * - `no-read`: the copy answers after the end of the window, but its answers give no starts of drills. A copy of an older build gives none.\n */\n readonly why: \"unseen\" | \"no-read\";\n /** The last start of the drill in the reads. */\n readonly last?: Instant;\n /** The time of the last read that passed. */\n readonly read?: Instant;\n}\n\n// The state of one watch: the start that it waits for, the end of the window of that start, and the reads of the copies.\ninterface WatchState {\n readonly due: Instant;\n readonly end: Instant;\n readonly last?: Instant;\n readonly scope: readonly CopyWatch[];\n}\n\n// The due start of a watch is the next start after the last start in the reads. With no start in the reads, the count\n// starts at the start of the watch. An open line keeps its start until a read gives a start at that time or later.\nfunction watchState(watch: DrillWatch, copies: readonly CopyWatch[], held: Instant | undefined): WatchState | undefined {\n const { drill, quiet } = watch;\n const scope = copies.filter((entry) => watch.copy === undefined || entry.copy === watch.copy);\n if (scope.length === 0) return undefined;\n let last: Instant | undefined;\n for (const entry of scope) {\n const start = entry.drills?.[drill.id];\n if (start !== undefined && Number.isFinite(start) && (last === undefined || start > last)) last = start;\n }\n const since = Math.min(...scope.map((entry) => entry.since));\n const due =\n held !== undefined && (last === undefined || last < held)\n ? held\n : last === undefined\n ? nextDrillAt(drill, [], since, quiet)\n : nextDrillAt(drill, [{ drill: drill.id, at: last }], last, quiet);\n if (due === undefined || (last !== undefined && last >= due)) return undefined;\n // A late start in the window of the due start is not a miss. A window with no end gives the due start as its end.\n const end = nextBoundary(due, drill.window)?.at ?? due;\n return { due, end, ...(last === undefined ? {} : { last }), scope };\n}\n\n/**\n * This function gives the time when the watch tells of a miss: the end of the window of the due start, plus `grace`. It\n * gives `undefined` when the watch waits for no start. A timer can wait for the time.\n */\nexport function watchedDrillReportAt(watch: DrillWatch, copies: readonly CopyWatch[], held?: Instant, grace: Duration = DRILL_WATCH_GRACE): Instant | undefined {\n const state = watchState(watch, copies, held);\n return state === undefined ? undefined : state.end + grace;\n}\n\n/**\n * This function gives the start of a drill of another copy that this copy did not see at the time `at`, or `undefined`.\n * The function reads no clock.\n *\n * - The watch reads the copies of `copies` that can start the drill. Each read that passed gives the last start of each\n * drill of its copy.\n * - The due start is the next start after the last start in the reads (`nextDrillAt`). With no start in the reads, the\n * count starts at the start of the watch.\n * - The start `held` of an open line stays the due start until a read gives a start at that time or later. Thus a\n * restart of this copy does not end the line.\n * - The miss is a fact at the end of the window of the due start, plus `grace`. A start at the due time or later ends it.\n * - A copy that answers with no starts of drills gives the reason `no-read`, not a pass. Thus a watch that cannot read tells it.\n */\nexport function watchedDrillMiss(watch: DrillWatch, copies: readonly CopyWatch[], at: Instant, held?: Instant, grace: Duration = DRILL_WATCH_GRACE): DrillWatchMiss | undefined {\n const state = watchState(watch, copies, held);\n if (state === undefined || at < state.end + grace) return undefined;\n const { due, end, last, scope } = state;\n const answered = scope.filter((entry) => entry.read !== undefined && entry.read.at >= end);\n const why = answered.length > 0 && answered.every((entry) => entry.drills === undefined) ? \"no-read\" : \"unseen\";\n const reads = scope.flatMap((entry) => (entry.read === undefined ? [] : [entry.read.at]));\n const read = reads.length === 0 ? undefined : Math.max(...reads);\n return { due, end, why, ...(last === undefined ? {} : { last }), ...(read === undefined ? {} : { read }) };\n}\n\n/**\n * The starts of the searches for a start of a drill: Monday 5 January and Monday 6 July 2026, 00:00 UTC. The windows\n * repeat each week in local time. Two windows in two zones move by an hour at a change of an offset. Thus each season\n * has its own search of 8 days, with no change of an offset in it.\n */\nexport const DRILL_PROBES: readonly Instant[] = [Date.UTC(2026, 0, 5), Date.UTC(2026, 6, 6)];\n\n// A weekly window has each of its starts in 7 days. One more day keeps a start at the edge of the week.\nconst PROBE_SPAN: Duration = 8 * 24 * 3_600_000;\n\n/**\n * This function gives the problems of one drill that a schema cannot find. `loadConfig` also checks the person, the\n * subject that the person watches, the policy of the person and the contact on the channel.\n *\n * - The time of the acknowledgment is above 0, and the least time between two starts is above it.\n * - The window has a good time zone and good local times.\n * - The drill has a start out of the quiet window of the person in each season (`DRILL_PROBES`). The time of the\n * acknowledgment ends before the quiet window.\n * - The list of the copies is not empty, and it names each copy one time.\n * - The instance has the channel of the path, and the channel tells of an acknowledgment.\n */\nexport function drillProblems(drill: DrillConfig, channels: readonly ChannelDescriptor[], quiet?: QuietWindow): string[] {\n const problems: string[] = [];\n const name = `The drill ${drill.id}`;\n if (!Number.isFinite(drill.ackWithin) || drill.ackWithin <= 0) problems.push(`${name} has the time of the acknowledgment ${String(drill.ackWithin)}. It is a finite number above 0.`);\n // A new start in the time of the last run makes two runs that wait together. The second hides the verdict of the first.\n if (!Number.isFinite(drill.every) || !(drill.every > drill.ackWithin)) problems.push(`${name} has the least time between two starts ${String(drill.every)}. It is above the time of the acknowledgment.`);\n const windowed = windowProblems(drill.window);\n for (const problem of windowed) problems.push(`${name}: the window: ${problem}`);\n const timed = Number.isFinite(drill.ackWithin) && drill.ackWithin > 0;\n const missing = windowed.length === 0 && timed ? DRILL_PROBES.filter((from) => !((nextDrillAt(drill, [], from, quiet) ?? Infinity) < from + PROBE_SPAN)) : [];\n if (missing.length > 0) {\n const weeks = missing.map((from) => new Date(from).toISOString().slice(0, 10)).join(\" and \");\n problems.push(`${name} has no start in the weeks from ${weeks}: each time of its window is in the quiet window of the person, or too near to it.`);\n }\n // An empty list of copies starts the drill in no copy, and nothing tells of it.\n if (drill.copies !== undefined && drill.copies.length === 0) problems.push(`${name} has an empty list of copies. No copy starts it.`);\n for (const copy of new Set((drill.copies ?? []).filter((copy, index, all) => all.indexOf(copy) !== index))) problems.push(`${name} names the copy ${copy} two times.`);\n const channel = channels.find((known) => known.id === drill.path.channel);\n if (channel === undefined) problems.push(`${name} uses the channel ${drill.path.channel}, and the instance has no such channel.`);\n else if (channel.ack === \"none\") problems.push(`${name} uses the channel ${drill.path.channel}, and the channel does not tell of an acknowledgment. The drill cannot pass.`);\n return problems;\n}\n","/**\n * The reports of the system itself. Each source that is down or late becomes a line of reports with the\n * status `system`. Each gap of the coverage and each stage of the quota of a channel also becomes such a line.\n * Each recent step of the wall clock is also a line. So the merge, the assessment and the escalation carry them as they carry the reports of a source.\n *\n * The function is a fold over snapshots of the health and the coverage. A condition that starts\n * gives an alert. A change of its facts gives an update that references the last key of the line.\n * The end of the condition gives a cancel. The fold reads no clock.\n */\nimport { canonicalJson } from \"@mark1russell7/rigor-generators\";\nimport { countOf } from \"@mark1russell7/text/english\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { BALANCE_KIND, CHANNEL_KIND, CLOCK_KIND, CONTEXT_KINDS, COPY_KIND, COVERAGE_KIND, DRILL_KIND, ESCALATION_KIND, hasKind, HEALTH_KIND, LIMIT_KIND, LOG_KIND, matchPlaces, PERSON_SUBJECT, QUOTA_KIND, STORE_KIND } from \"./assess.ts\";\nimport { isPrivate } from \"./audience.ts\";\nimport type {\n Area,\n BalanceStage,\n ChannelId,\n ChannelQuota,\n CopyStage,\n CopyWatch,\n Coverage,\n Duration,\n HealthState,\n Incident,\n Instant,\n Kind,\n Observation,\n Operation,\n PersonId,\n PlaceId,\n ProviderBalance,\n QuotaStage,\n Report,\n ResponseType,\n Severity,\n Significance,\n SourceDescriptor,\n SourceHealth,\n SourceId,\n Subject,\n Urgency,\n WatchedPlace,\n} from \"./contracts.ts\";\nimport { SYSTEM_SOURCE } from \"./contracts.ts\";\nimport { channelDownPolicy, runOpens, type ChannelDownConfig, type ChannelDownPolicy, type ChannelRun, type ChannelSnapshot } from \"./channel-down.ts\";\nimport { coverageShort } from \"./coverage.ts\";\nimport type { Exhaustion } from \"./delivery.ts\";\nimport { drillVerdict, watchedDrillMiss, watchedDrillReportAt, type DrillConfig, type DrillRun, type DrillWatch, type DrillWatchMiss } from \"./drill.ts\";\nimport { observationId, reportId } from \"./ids.ts\";\nimport type { Lateness } from \"./lateness.ts\";\nimport type { ObserveCondition } from \"./observe.ts\";\nimport type { HeldPerson } from \"./send-limit.ts\";\nimport { kindLabel } from \"./taxonomy.ts\";\n\n/** The system of the subjects of the health reports. The id of a subject is the id of a source. */\nexport const SOURCE_SUBJECT = \"alerts.source\";\n\n/** The system of the subjects of the quota reports. The id of a subject is the id of a channel. */\nexport const CHANNEL_SUBJECT = \"alerts.channel\";\n\n/** The system of the subject of the clock reports. The id of the subject is `wall`: the wall clock of the computer. */\nexport const CLOCK_SUBJECT = \"alerts.clock\";\n\n/** The system of the subject of the log reports. The id of the subject is `runtime`: the log file of the runtime. */\nexport const LOG_SUBJECT = \"alerts.log\";\n\n/** The subject system of another copy of the system. The id of a subject is the id of the copy. */\nexport const COPY_SUBJECT = \"alerts.copy\";\n\n/** The system of the subjects of the drill reports. The id of a subject is the id of a drill. */\nexport const DRILL_SUBJECT = \"alerts.drill\";\n\n/** The system of the subjects of the store reports (AL-86). The id of a subject is the store and the family, as `shapes/fire`. */\nexport const STORE_SUBJECT = \"alerts.store\";\n\n/** The subject system of an incident. The id of a subject is a report of the incident: an exhausted escalation links its warning. */\nexport const INCIDENT_SUBJECT = \"alerts.incident\";\n\n/** The stages of a quota, from the first to the last. */\nexport const QUOTA_STAGES: readonly QuotaStage[] = [\"low\", \"reserve\", \"spent\"];\n\n/** The stages of a balance. `empty` holds `low`. `unread` comes from the time of the last read. */\nexport const BALANCE_STAGES: readonly BalanceStage[] = [\"low\", \"empty\", \"unread\"];\n\n/**\n * The stages of another copy. `skew` and `config` come from the last read that passed. `unread` comes from its time.\n * `unsteady` comes from the time of the first read that told that the copy is not steady.\n */\nexport const COPY_STAGES: readonly CopyStage[] = [\"skew\", \"config\", \"unread\", \"unsteady\"];\n\n/**\n * The longest time that another copy is not steady with no stage `unsteady` (AL-108). The limit is longer than a normal\n * start. The longest ready window is 10 minutes, and a copy is steady 5 minutes after its first pass. The limit adds 5\n * minutes to the sum of the two.\n */\nexport const COPY_STEADY_LIMIT: Duration = 20 * 60_000;\n\n/** The health states that start a line of health reports. */\nexport const DOWN_STATES: readonly HealthState[] = [\"failing\", \"silent\", \"changed\"];\n\n/**\n * The policy of the end of the line of a down source (AL-75). The line ends only after the source is up for its clear\n * time: the larger of `floor` and `fetches` intervals of the source. A source that is down again in that time keeps its\n * line. Thus a source that flaps gives one incident, not one incident for each failure.\n */\nexport interface SourceClearPolicy {\n /** The shortest clear time. At 0 with `fetches` at 0, the line ends at the first state that is not down. */\n readonly floor: Duration;\n /** The count of intervals of the source in the clear time. */\n readonly fetches: number;\n}\n\n/** The default policy of the end of the line of a down source: 15 minutes, or 3 intervals of the source when that is longer. */\nexport const DEFAULT_SOURCE_CLEAR: SourceClearPolicy = { floor: 15 * 60_000, fetches: 3 };\n\n/** The policy of the end of the line of a down source in the configuration. Each absent field has its value of `DEFAULT_SOURCE_CLEAR`. */\nexport interface SourceClearConfig {\n readonly floor?: Duration;\n readonly fetches?: number;\n}\n\n/** This function gives the policy of the end of the line of a down source, with the defaults for the absent fields. */\nexport function sourceClearPolicy(config?: SourceClearConfig): SourceClearPolicy {\n return { floor: config?.floor ?? DEFAULT_SOURCE_CLEAR.floor, fetches: config?.fetches ?? DEFAULT_SOURCE_CLEAR.fetches };\n}\n\n/** This function gives the clear time of a source under a policy: the larger of the floor and the intervals of the source. */\nexport function sourceClearTime(policy: SourceClearPolicy, source: SourceDescriptor | undefined): Duration {\n return Math.max(policy.floor, policy.fetches * (source?.interval ?? 0));\n}\n\n/**\n * This function gives the end times after `at` of the open lines of the sources that are up. Each end time is the start\n * of the state of the source plus its clear time. The runtime wakes at these times. Thus a line ends on time, also when\n * no fetch is due.\n */\nexport function sourceClearAt(lines: SystemLines, snapshot: Pick<SystemSnapshot, \"sources\" | \"health\" | \"sourceClear\">, at: Instant): Instant[] {\n const policy = sourceClearPolicy(snapshot.sourceClear);\n const descriptors = new Map(snapshot.sources.map((source) => [source.id, source]));\n return snapshot.health.flatMap((health) => {\n if (DOWN_STATES.includes(health.state) || lines.open[healthName(health.source)] === undefined) return [];\n const end = health.since + sourceClearTime(policy, descriptors.get(health.source));\n return end > at ? [end] : [];\n });\n}\n\n/** The stages of an incident that make a gap of the coverage more dangerous. An incident with no stage also counts. */\nexport const THREAT_STAGES: readonly Significance[] = [\"warning\", \"watch\"];\n\n/** One step of the wall clock. */\nexport interface ClockStep {\n /** The time of the step on the wall clock after the step. A later step moves it. */\n readonly at: Instant;\n /** The size of the step in milliseconds: negative for a step back. */\n readonly size: Duration;\n}\n\n/**\n * One recovery of the log of the runtime from a broken file. The runtime moved the file into quarantine, and it wrote\n * each event that the salvage read into a new file.\n */\nexport interface LogRecovery {\n /** The time of the recovery. A later step of the wall clock moves it. */\n readonly at: Instant;\n /** The name of the quarantine folder, in the folder of the log. */\n readonly quarantine: string;\n /** The count of the events that the new file got. */\n readonly kept: number;\n /** The count of the positions of the broken file that the salvage could not read. */\n readonly lost: number;\n /** This value tells if the salvage read each part of the broken file with no problem. Then no event is lost. */\n readonly whole: boolean;\n}\n\n/** The time after a recovery of the log during which its system report stays open. Thus the digest of the day shows it. */\nexport const LOG_RECOVERY_WINDOW: Duration = 24 * 60 * 60 * 1000;\n\n/** The time after a step during which its system report stays open. Thus the digest of the day shows the step. */\nexport const CLOCK_STEP_WINDOW: Duration = 24 * 60 * 60 * 1000;\n\n/**\n * The fill of one family of a store of the runtime (AL-86), as the fire zones of the store of shapes. A store fills after each\n * start. A family with no entry at the end of its window is a condition.\n */\nexport interface StoreFill {\n /** The id of the store, as `shapes`. */\n readonly store: string;\n /** The family of the entries, as `fire`. */\n readonly family: string;\n /** The count of the entries of the family at the time of the snapshot. */\n readonly entries: number;\n /** The start of the instance that fills the store. */\n readonly since: Instant;\n /** The time after the start in which the family gets its first entry. */\n readonly within: Duration;\n /** The sources that feed the store. A person who watches one of them gets the report. */\n readonly sources: readonly SourceId[];\n}\n\n/** The time after a start in which each family of a store gets its first entry (AL-86). */\nexport const STORE_FILL_WINDOW: Duration = 60 * 60 * 1000;\n\n/** This function gives the time when a family with no entry becomes a condition: the end of its window after the start. */\nexport function storeEmptyAt(fill: StoreFill): Instant {\n return fill.since + fill.within;\n}\n\n/**\n * This function gives the size of a step in a text: whole hours, whole minutes, or else whole seconds. A step of\n * 3600000 ms is `1 h`, a step of 600000 ms is `10 min`, and a step of 90000 ms is `90 s`.\n */\nexport function stepSizeText(size: Duration): string {\n const ms = Math.abs(size);\n if (ms >= 3_600_000 && ms % 3_600_000 === 0) return `${String(ms / 3_600_000)} h`;\n if (ms >= 60_000 && ms % 60_000 === 0) return `${String(ms / 60_000)} min`;\n return `${String(Math.round(ms / 1000))} s`;\n}\n\n/** An open line of reports. The fold keeps it until the condition ends. */\nexport interface SystemLine {\n /** The key of the last report of the line. The next report references it. */\n readonly key: string;\n /** The canonical JSON of the facts of the last report. Only a change of the facts gives an update. */\n readonly facts: string;\n readonly kind: Kind;\n readonly areas: readonly Area[];\n readonly about: readonly Subject[];\n /** The persons of a private line (AL-81). Its cancel goes to the same persons. */\n readonly addresses?: readonly PersonId[];\n}\n\n/** The state of the fold. It is data, so the runtime can keep it in its log. */\nexport interface SystemLines {\n /** The count of the reports of the fold. Each key has it, so each key is new. */\n readonly count: number;\n /** The open lines, by the name of the condition. */\n readonly open: Readonly<Record<string, SystemLine>>;\n}\n\n/** The state of the fold before the first snapshot. */\nexport const NO_SYSTEM_LINES: SystemLines = { count: 0, open: {} };\n\n/** A place and a kind with a live watch or warning. */\nexport interface Threat {\n readonly place: PlaceId;\n /** The taxonomy code of the incident. */\n readonly kind: string;\n}\n\n/** One drill of one copy in a snapshot. */\nexport interface DrillSnapshot {\n /** The id of the copy that starts the drill. */\n readonly copy: string;\n readonly drill: DrillConfig;\n /** The last run of the drill in the copy. A drill that is due has a run that starts at the time of the snapshot. */\n readonly run?: DrillRun;\n /**\n * This value tells that the drill has no next start: `nextDrillAt` gives `undefined`. Such a drill is a condition, a\n * failure with the reason `no-start`. Thus the path of the life-safety warnings does not lose its test with no report.\n */\n readonly noStart?: boolean;\n /**\n * The start that the drill missed (`missedDrillAt`). Such a drill is a condition, a failure with the reason `missed`.\n * The next run ends it.\n */\n readonly missed?: Instant;\n}\n\n/** One snapshot of the system. */\nexport interface SystemSnapshot {\n /** The descriptors of the sources. The reports take their titles. */\n readonly sources: readonly SourceDescriptor[];\n readonly health: readonly SourceHealth[];\n readonly coverage: readonly Coverage[];\n /** The places and the kinds with a live watch or warning. The function `threats` gives them. */\n readonly threats: readonly Threat[];\n /** The lateness of the sources that carry the reports of other sources. Each `late` entry is a condition. */\n readonly lateness?: readonly Lateness[];\n /**\n * The quotas of the channels. Each stage that `quotaStages` gives is a condition. With no quotas, each\n * open line of a quota stays open: a failed read of a count ends no line.\n */\n readonly quotas?: readonly ChannelQuota[];\n /**\n * The balances of the provider accounts. Each stage that `balanceStages` gives is a condition. With no\n * balances, each open line of a balance stays open. Only one copy reports the stages `low` and `empty` (`reportsShared`).\n */\n readonly balances?: readonly ProviderBalance[];\n /** The id of this copy. With the watches of the other copies, it chooses the copy that reports the facts of a shared account. */\n readonly copy?: string;\n /**\n * The watches of the other copies of the system. Each stage that `copyStages` gives is a condition. With no copies,\n * each open line of a copy stays open.\n */\n readonly copies?: readonly CopyWatch[];\n /** The steps of the wall clock. The latest step in `CLOCK_STEP_WINDOW` before the time of the snapshot is a condition. */\n readonly steps?: readonly ClockStep[];\n /** The recoveries of the log. The latest recovery in `LOG_RECOVERY_WINDOW` before the time of the snapshot is a condition. */\n readonly recoveries?: readonly LogRecovery[];\n /**\n * The fills of the families of the stores (AL-86). A family with no entry at `storeEmptyAt` is a condition. An open line\n * stays a condition while its family has no entry, also after a restart. With no list, each open line of a store stays open.\n */\n readonly stores?: readonly StoreFill[];\n /**\n * The drills of the copy. A run that waits for its acknowledgment is a condition, and a failed last run is a condition.\n * With no drills, each open line of a drill stays open.\n */\n readonly drills?: readonly DrillSnapshot[];\n /**\n * The drills that other copies start, in the watch of this copy (AL-43). The watch reads `copies`. A start that the\n * watch did not see is a condition (`watchedDrillMiss`). With no watches, each open line of a watch stays open.\n */\n readonly drillWatches?: readonly DrillWatch[];\n /**\n * The exhausted escalations of the real warnings (`exhaustions`, AL-21). Each one is a condition, for the people who\n * watch the person. Only one copy reports them (`reportsShared`). With no list, each open line of an exhaustion stays open.\n */\n readonly exhausted?: readonly Exhaustion[];\n /**\n * The persons with a hold of the send limit in its window (`heldPersons`, AL-81). Each one is a private condition for\n * that person. Only one copy reports them (`reportsShared`). With no list, each open line of a hold stays open.\n */\n readonly held?: readonly HeldPerson[];\n /**\n * The channels of this copy, with their runs of failed calls (AL-65). A run that `runOpens` under the policy is a\n * condition. An open line stays a condition until a good call at or after its onset, also with no run. With no list,\n * each open line of a channel stays open.\n */\n readonly channels?: readonly ChannelSnapshot[];\n /** The policy of a down channel. Each absent field has its value of `DEFAULT_CHANNEL_DOWN`. */\n readonly channelDown?: ChannelDownConfig;\n /**\n * The conditions of the observe mode of the new sources (`observeConditions`, AL-73). With no list, each open line\n * of the observe mode stays open.\n */\n readonly observing?: readonly ObserveCondition[];\n /** The policy of the end of the line of a down source (AL-75). Each absent field has its value of `DEFAULT_SOURCE_CLEAR`. */\n readonly sourceClear?: SourceClearConfig;\n}\n\n/** The result of one step of the fold. */\nexport interface SystemStep {\n readonly lines: SystemLines;\n /** The new reports, in the order of the names of their conditions. */\n readonly reports: readonly Report[];\n /** The observation of each new report. The log keeps them, as it keeps the observations of the sources. */\n readonly observations: readonly Observation[];\n}\n\n/**\n * This function gives the places and the kinds with a live threat. A threat is an incident with the\n * status `actual`, a stage in `THREAT_STAGES` or no stage, and an area that covers a watched place.\n */\nexport function threats(incidents: readonly Incident[], places: readonly WatchedPlace[]): Threat[] {\n return incidents.flatMap((incident) => {\n const stage = incident.kind.significance;\n if (isPrivate(incident) || !incident.live || incident.status !== \"actual\" || (stage !== undefined && !THREAT_STAGES.includes(stage))) return [];\n return matchPlaces(incident, places).map((match) => ({ place: match.place, kind: incident.kind.code }));\n });\n}\n\n/**\n * This function gives the stages that a quota reached, in the order of `QUOTA_STAGES`. Each later stage\n * holds the earlier stages. Thus each stage is one line, and the line of the entry into the reserve is\n * one alert in a window.\n */\nexport function quotaStages(quota: ChannelQuota): QuotaStage[] {\n const left = quota.limit - quota.used;\n const spent = quota.blockedUntil !== undefined || left <= 0;\n const reached: Readonly<Record<QuotaStage, boolean>> = { low: spent || left <= 2 * quota.reserve, reserve: spent || left <= quota.reserve, spent };\n return QUOTA_STAGES.filter((stage) => reached[stage]);\n}\n\n/**\n * This function gives the stages of a balance at the time `at`, in the order of `BALANCE_STAGES`.\n *\n * - `low` and `empty` come from the last read that passed, also when the read is old.\n * - `unread` starts at `balanceUnreadAt`. A read that passes ends it.\n */\nexport function balanceStages(balance: ProviderBalance, at: Instant): BalanceStage[] {\n const read = balance.read;\n const empty = read !== undefined && read.balance <= 0;\n const reached: Readonly<Record<BalanceStage, boolean>> = {\n low: balanceFloorsBelow(balance).length > 0,\n empty,\n unread: at >= balanceUnreadAt(balance),\n };\n return BALANCE_STAGES.filter((stage) => reached[stage]);\n}\n\n/** This function gives the time when a balance reaches `unread`: the maximum age after the last read, or after the start with no read. */\nexport function balanceUnreadAt(balance: ProviderBalance): Instant {\n return (balance.read?.at ?? balance.since) + balance.maxAge;\n}\n\n/**\n * This function gives the floors that the last read of a balance is below, from the highest to the lowest, each one time.\n * At 0 or less, the balance is below each floor. With no read, the list is empty.\n */\nexport function balanceFloorsBelow(balance: ProviderBalance): number[] {\n const read = balance.read;\n if (read === undefined) return [];\n return [...new Set(balance.floors)].filter((floor) => read.balance <= 0 || read.balance < floor).sort((a, b) => b - a);\n}\n\n/**\n * This function gives the stages of another copy at the time `at`, in the order of `COPY_STAGES`.\n *\n * - `skew` and `config` come from the last read that passed, also when the read is old.\n * - `unread` starts at `copyUnreadAt`. A read that passes ends it.\n * - `unsteady` starts at `copyUnsteadyAt`. A steady read ends it.\n */\nexport function copyStages(watch: CopyWatch, at: Instant): CopyStage[] {\n const read = watch.read;\n const reached: Readonly<Record<CopyStage, boolean>> = {\n skew: read !== undefined && Math.abs(read.skew) > watch.skewLimit,\n config: read !== undefined && !read.sameConfig,\n unread: at >= copyUnreadAt(watch),\n unsteady: watch.unsteadySince !== undefined && at >= watch.unsteadySince + COPY_STEADY_LIMIT,\n };\n return COPY_STAGES.filter((stage) => reached[stage]);\n}\n\n/** This function gives the time when a copy reaches `unread`: the maximum age after the last read, or after the start with no read. */\nexport function copyUnreadAt(watch: CopyWatch): Instant {\n return (watch.read?.at ?? watch.since) + watch.maxAge;\n}\n\n/** This function gives the time when a copy reaches `unsteady`, or `undefined` when the copy is steady or tells nothing. */\nexport function copyUnsteadyAt(watch: CopyWatch): Instant | undefined {\n return watch.unsteadySince === undefined ? undefined : watch.unsteadySince + COPY_STEADY_LIMIT;\n}\n\n/** The time with no read of another copy after which this copy also reports the facts of a shared account (AL-62). It is longer than a restart. */\nexport const SHARED_HANDOVER: Duration = 15 * 60_000;\n\n/**\n * This function tells if this copy reports the facts of a shared account at the time `at` (AL-62). Each copy reads the\n * same account, thus each copy sees the same stages `low` and `empty` of a balance.\n *\n * - The copy with the smallest id of the copies that answer reports them. Thus the copies send one alert, not one alert each.\n * - Another copy answers until `SHARED_HANDOVER` after its last read that passed, or after the start of its watch.\n * - With no id of this copy, or with no watches of other copies, this copy reports them.\n */\nexport function reportsShared(copy: string | undefined, copies: readonly CopyWatch[] | undefined, at: Instant): boolean {\n const from = sharedHandoverAt(copy, copies);\n return from === undefined || from <= at;\n}\n\n/**\n * This function gives the time from which this copy reports the facts of a shared account. A copy with a smaller id\n * that answers before that time moves it. With no copy with a smaller id, it gives `undefined`.\n */\nexport function sharedHandoverAt(copy: string | undefined, copies: readonly CopyWatch[] | undefined): Instant | undefined {\n if (copy === undefined || copies === undefined) return undefined;\n const smaller = copies.filter((watch) => compareCodeUnits(watch.copy, copy) < 0);\n if (smaller.length === 0) return undefined;\n return Math.max(...smaller.map((watch) => (watch.read?.at ?? watch.since) + SHARED_HANDOVER));\n}\n\n/**\n * This function gives the latest item at `at` or before it, in `window` before `at`, or `undefined`. Of two items at\n * the same time, it gives the last in the list.\n */\nexport function latestIn<T extends { readonly at: Instant }>(items: readonly T[], at: Instant, window: Duration): T | undefined {\n let found: T | undefined;\n for (const item of items) if (item.at <= at && at - item.at < window && (found === undefined || item.at >= found.at)) found = item;\n return found;\n}\n\n/** This function gives the latest step at `at` or before it, in `CLOCK_STEP_WINDOW` before `at`, or `undefined`. */\nexport function recentStep(steps: readonly ClockStep[], at: Instant): ClockStep | undefined {\n return latestIn(steps, at, CLOCK_STEP_WINDOW);\n}\n\n/** This function gives the latest recovery of the log at `at` or before it, in `LOG_RECOVERY_WINDOW` before `at`, or `undefined`. */\nexport function recentRecovery(recoveries: readonly LogRecovery[], at: Instant): LogRecovery | undefined {\n return latestIn(recoveries, at, LOG_RECOVERY_WINDOW);\n}\n\n/**\n * This function gives the CAP severity and urgency of a gap of the coverage. The assessment policy\n * gives the level from them:\n *\n * - No independent source during a threat of the kind: `extreme` and `immediate`.\n * - Fewer independent sources than the policy needs: `severe` and `expected`.\n * - A count that the search did not prove: `moderate` and `expected`.\n */\nexport function gapGrade(entry: Coverage, threatened: boolean): { readonly severity: Severity; readonly urgency: Urgency } {\n if (entry.independent === 0 && threatened) return { severity: \"extreme\", urgency: \"immediate\" };\n if (entry.independent < entry.required) return { severity: \"severe\", urgency: \"expected\" };\n return { severity: \"moderate\", urgency: \"expected\" };\n}\n\n/**\n * This function adds one snapshot to the fold at the time `at`. Each of these is a condition:\n *\n * - Each source in `DOWN_STATES`, each late expectation and each coverage that is short. The open line of a source that is\n * up stays a condition for the clear time of the source (`sourceClearTime`).\n * - Each stage of a quota, each stage of a balance and each stage of another copy. Only one copy reports the stages\n * `low` and `empty` of a balance (`reportsShared`). The stage `unread` is a fact of each copy.\n * - The latest step of the wall clock in `CLOCK_STEP_WINDOW` before `at`.\n * - The latest recovery of the log in `LOG_RECOVERY_WINDOW` before `at`.\n * - Each run of a drill that waits for its acknowledgment, and each drill whose last run failed.\n * - Each start of a drill of another copy that the watch of this copy did not see (`watchedDrillMiss`).\n * - Each exhausted escalation of a real warning. Only one copy reports it (`reportsShared`).\n * - Each person with a hold of the send limit in its window. The report is private. Only one copy reports it (`reportsShared`).\n * - Each down channel of the copy: a run that opens a line, or an open line with no good call since its onset.\n * - Each family of a store with no entry at the end of its window after the start, or with an open line and no entry.\n *\n * An open line with no condition in the snapshot ends with a cancel. Equal snapshots give no new report.\n */\nexport function systemReports(lines: SystemLines, snapshot: SystemSnapshot, at: Instant): SystemStep {\n const conditions = new Map<string, Condition>();\n const titles = new Map(snapshot.sources.map((source) => [source.id, source.title]));\n const context = new Set(snapshot.sources.filter(contextSource).map((source) => source.id));\n const descriptors = new Map(snapshot.sources.map((source) => [source.id, source]));\n const clear = sourceClearPolicy(snapshot.sourceClear);\n for (const health of snapshot.health) {\n const name = healthName(health.source);\n // A source that is up keeps its open line for its clear time, with the facts of the line. Thus a source that flaps\n // gives no cancel and no new alert (AL-75). On 2026-11-18, a source that failed 2 fetches of 4 gave one incident for each flap.\n const state = DOWN_STATES.includes(health.state) ? health.state : heldState(lines.open[name], health, at, sourceClearTime(clear, descriptors.get(health.source)));\n if (state !== undefined) conditions.set(name, healthCondition({ ...health, state }, titles.get(health.source) ?? health.source, context.has(health.source)));\n }\n for (const entry of snapshot.lateness ?? []) {\n if (entry.state === \"late\") conditions.set(lateName(entry.expectation), lateCondition(entry, titles));\n }\n for (const entry of snapshot.coverage) {\n if (!coverageShort(entry)) continue;\n const threatened = snapshot.threats.some((threat) => threat.place === entry.place && hasKind([entry.kind], threat.kind));\n conditions.set(coverageName(entry.place, entry.kind), coverageCondition(entry, threatened));\n }\n for (const quota of snapshot.quotas ?? []) {\n for (const stage of quotaStages(quota)) conditions.set(quotaName(quota.channel, stage), quotaCondition(quota, stage));\n }\n // The stages low and empty are facts of the account, and one copy reports them. The stage unread is a fact of this copy.\n const shared = reportsShared(snapshot.copy, snapshot.copies, at);\n for (const balance of snapshot.balances ?? []) {\n for (const stage of balanceStages(balance, at)) {\n if (stage !== \"unread\" && !shared) continue;\n if (stage !== \"low\") conditions.set(balanceName(balance.provider, stage), balanceCondition(balance, stage, at));\n // Each floor that the balance is below is its own line. Thus each floor gives its own alert.\n else for (const floor of balanceFloorsBelow(balance)) conditions.set(balanceName(balance.provider, stage, floor), balanceCondition(balance, stage, at, floor));\n }\n }\n for (const watch of snapshot.copies ?? []) {\n for (const stage of copyStages(watch, at)) conditions.set(copyName(watch.copy, stage), copyCondition(watch, stage, at));\n // A copy that starts again and again answers in each try, and it stops after each try. Thus an open line of the copy\n // ends only at a steady read (AL-108). On 2026-11-21, a copy made 125 starts, and its line unread opened at each stop.\n // An open line unsteady also stays open over a restart of this copy, until the first steady read.\n const steadyRead = watch.read !== undefined && watch.unsteadySince === undefined;\n for (const stage of [\"unread\", \"unsteady\"] as const) {\n const name = copyName(watch.copy, stage);\n const held = stage === \"unread\" ? watch.unsteadySince !== undefined : !steadyRead;\n if (held && !conditions.has(name) && lines.open[name] !== undefined) conditions.set(name, copyCondition(watch, stage, at));\n }\n }\n const step = recentStep(snapshot.steps ?? [], at);\n if (step !== undefined) conditions.set(CLOCK_LINE, clockCondition(step));\n const recovery = recentRecovery(snapshot.recoveries ?? [], at);\n if (recovery !== undefined) conditions.set(LOG_LINE, logCondition(recovery));\n for (const entry of snapshot.drills ?? []) {\n const { copy, drill, run } = entry;\n if (entry.noStart === true) conditions.set(`${drillName(copy, drill.id)}/no-start`, drillNoStartCondition(copy, drill));\n if (run === undefined || run.drill !== drill.id) continue;\n if (entry.missed !== undefined) conditions.set(`${drillName(copy, drill.id)}/missed`, drillMissedCondition(copy, drill, run, entry.missed));\n const verdict = drillVerdict(drill, run, at);\n if (verdict.state === \"pending\") conditions.set(drillName(copy, drill.id), drillRunCondition(copy, drill, run));\n else if (verdict.state === \"failed\") conditions.set(`${drillName(copy, drill.id)}/failed`, drillFailedCondition(copy, drill, run, verdict.why));\n }\n // A copy that stops for the full window of a start tells nothing in that time. Thus each other copy tells of it.\n for (const watch of snapshot.drillWatches ?? []) {\n const name = drillWatchName(watch);\n const miss = watchedDrillMiss(watch, snapshot.copies ?? [], at, heldDue(lines.open[name]));\n if (miss !== undefined) conditions.set(name, drillWatchCondition(watch, miss));\n }\n // The two copies see the same exhaustion in the shared log. Thus one copy reports it, as with a shared balance.\n if (shared) for (const entry of snapshot.exhausted ?? []) conditions.set(exhaustionName(entry), exhaustionCondition(entry));\n // Each copy counts the deliveries of all the copies, thus each copy holds the same burst. One copy tells each person (AL-81).\n if (shared) for (const entry of snapshot.held ?? []) conditions.set(heldName(entry), heldCondition(entry));\n // Each copy reports its own down channels, because each copy has its own network path to the provider.\n const policy = channelDownPolicy(snapshot.channelDown);\n for (const entry of snapshot.channels ?? []) {\n const name = channelName(entry.copy, entry.channel);\n const condition = channelCondition(entry, lines.open[name], policy);\n if (condition !== undefined) conditions.set(name, condition);\n }\n for (const entry of snapshot.observing ?? []) conditions.set(observeName(entry), observeCondition(entry, titles.get(entry.source) ?? entry.source, context.has(entry.source)));\n // A restart gives a new start. Thus an open line of a family with no entry stays open, and it gives no new alert.\n for (const fill of snapshot.stores ?? []) {\n const name = storeName(fill);\n if (fill.entries === 0 && (at >= storeEmptyAt(fill) || lines.open[name] !== undefined)) conditions.set(name, storeCondition(fill, titles));\n }\n const names = [...new Set([...Object.keys(lines.open), ...conditions.keys()])].sort(compareCodeUnits);\n let count = lines.count;\n const open = new Map(Object.entries(lines.open));\n const reports: Report[] = [];\n const observations: Observation[] = [];\n for (const name of names) {\n const line = lines.open[name];\n const condition = conditions.get(name);\n if (condition === undefined && snapshot.quotas === undefined && name.startsWith(QUOTA_LINE)) continue;\n if (condition === undefined && snapshot.balances === undefined && name.startsWith(BALANCE_LINE)) continue;\n if (condition === undefined && snapshot.copies === undefined && name.startsWith(COPY_LINE)) continue;\n if (condition === undefined && snapshot.drills === undefined && name.startsWith(DRILL_LINE)) continue;\n if (condition === undefined && snapshot.drillWatches === undefined && name.startsWith(DRILL_WATCH_LINE)) continue;\n if (condition === undefined && snapshot.exhausted === undefined && name.startsWith(EXHAUSTION_LINE)) continue;\n if (condition === undefined && snapshot.held === undefined && name.startsWith(HELD_LINE)) continue;\n if (condition === undefined && snapshot.channels === undefined && name.startsWith(CHANNEL_LINE)) continue;\n if (condition === undefined && snapshot.observing === undefined && name.startsWith(OBSERVE_LINE)) continue;\n if (condition === undefined && snapshot.stores === undefined && name.startsWith(STORE_LINE)) continue;\n const draft = condition === undefined ? (line === undefined ? undefined : cancelOf(line)) : condition;\n if (draft === undefined) continue;\n const facts = canonicalJson(draft.facts, { form: \"json\" });\n if (line !== undefined && condition !== undefined && line.facts === facts) continue;\n const op: Operation = condition === undefined ? \"cancel\" : line === undefined ? \"alert\" : \"update\";\n count += 1;\n const key = `${name}#${count}`;\n const observation = observationOf(name, op, draft.facts, at);\n observations.push(observation);\n reports.push(reportOf(draft, { key, op, references: line === undefined ? [] : [line.key], at, observation: observation.id }));\n if (op === \"cancel\") open.delete(name);\n else open.set(name, { key, facts, kind: draft.kind, areas: draft.areas, about: draft.about, ...(draft.addresses === undefined ? {} : { addresses: draft.addresses }) });\n }\n const sorted = [...open.entries()].sort(([a], [b]) => compareCodeUnits(a, b));\n return { lines: { count, open: Object.fromEntries(sorted) }, reports, observations };\n}\n\n/**\n * This function adds the reports of the fold to the lines, in their order. It gives the lines that\n * `systemReports` gave with these reports. Thus the runtime rebuilds the lines from its log, and the\n * log holds no copy of the state. A report of another source changes nothing.\n *\n * The observation of each report gives the facts of its line. The function throws when an observation\n * is not in `observations`, because then the log is not complete.\n */\nexport function addSystemReports(lines: SystemLines, reports: readonly Report[], observations: readonly Observation[]): SystemLines {\n const bodies = new Map(observations.map((observation) => [observation.id, observation.body]));\n let count = lines.count;\n const open = new Map(Object.entries(lines.open));\n for (const report of reports) {\n if (report.source !== SYSTEM_SOURCE) continue;\n const mark = report.key.lastIndexOf(\"#\");\n const name = report.key.slice(0, mark);\n const body = bodies.get(report.observation);\n if (mark < 0 || body === undefined) throw new Error(`The system report ${report.key} has no observation ${report.observation}.`);\n const { facts } = JSON.parse(body) as { readonly facts: Condition[\"facts\"] };\n count = Math.max(count, Number(report.key.slice(mark + 1)));\n if (report.op === \"cancel\") open.delete(name);\n else open.set(name, { key: report.key, facts: canonicalJson(facts, { form: \"json\" }), kind: report.kind, areas: report.areas, about: report.about, ...(report.addresses === undefined ? {} : { addresses: report.addresses }) });\n }\n const sorted = [...open.entries()].sort(([a], [b]) => compareCodeUnits(a, b));\n return { count, open: Object.fromEntries(sorted) };\n}\n\n// The parts of a report that a condition gives. The fold adds the key, the references, the times and the observation.\ninterface Condition {\n readonly facts: Readonly<Record<string, unknown>>;\n readonly kind: Kind;\n readonly severity: Severity;\n readonly urgency: Urgency;\n readonly response: readonly ResponseType[];\n readonly onset?: Instant;\n readonly areas: readonly Area[];\n readonly about: readonly Subject[];\n /** The persons of a private condition (AL-81). Only they get its report. */\n readonly addresses?: readonly PersonId[];\n readonly headline: string;\n readonly description?: string;\n readonly instruction?: string;\n readonly parameters: Readonly<Record<string, readonly string[]>>;\n}\n\nconst HEADLINES: Readonly<Record<string, string>> = {\n failing: \"the fetches fail\",\n silent: \"the source gives no new data\",\n changed: \"the format of the source changed\",\n};\n\nfunction healthName(source: SourceId): string {\n return `health/${encodeURIComponent(source)}`;\n}\n\nfunction lateName(expectation: string): string {\n return `late/${encodeURIComponent(expectation)}`;\n}\n\n// The start of the name of each line of a quota.\nconst QUOTA_LINE = \"quota/\";\n\nfunction quotaName(channel: string, stage: QuotaStage): string {\n return `${QUOTA_LINE}${encodeURIComponent(channel)}/${stage}`;\n}\n\n// The start of the name of each line of a balance.\nconst BALANCE_LINE = \"balance/\";\n\nfunction balanceName(provider: string, stage: BalanceStage, floor?: number): string {\n const name = `${BALANCE_LINE}${encodeURIComponent(provider)}/${stage}`;\n return floor === undefined ? name : `${name}/${String(floor)}`;\n}\n\n// The start of the name of each line of another copy.\nconst COPY_LINE = \"copy/\";\n\nfunction copyName(copy: string, stage: CopyStage): string {\n return `${COPY_LINE}${encodeURIComponent(copy)}/${stage}`;\n}\n\n// The start of the name of each line of a drill. The id of the copy is in the name, because each copy starts its own runs.\nconst DRILL_LINE = \"drill/\";\n\nfunction drillName(copy: string, drill: string): string {\n return `${DRILL_LINE}${encodeURIComponent(copy)}/${encodeURIComponent(drill)}`;\n}\n\n// The start of the name of each line of the watch of a drill of another copy. A watch with no copy has an empty part.\nconst DRILL_WATCH_LINE = \"drill-watch/\";\n\nfunction drillWatchName(watch: DrillWatch): string {\n return `${DRILL_WATCH_LINE}${encodeURIComponent(watch.copy ?? \"\")}/${encodeURIComponent(watch.drill.id)}`;\n}\n\n// The due start of an open line of a watch. The line keeps it over a restart of this copy, because the log rebuilds the lines.\nfunction heldDue(line: SystemLine | undefined): Instant | undefined {\n if (line === undefined) return undefined;\n const { due } = JSON.parse(line.facts) as { readonly due?: unknown };\n return typeof due === \"number\" && Number.isFinite(due) ? due : undefined;\n}\n\n/**\n * This function gives the time when the watch of a drill of another copy tells of a miss. The open line of the watch in\n * `lines` keeps its due start. The function gives `undefined` when the watch waits for no start. A timer can wait for the time.\n */\nexport function drillWatchAt(lines: SystemLines, watch: DrillWatch, copies: readonly CopyWatch[]): Instant | undefined {\n return watchedDrillReportAt(watch, copies, heldDue(lines.open[drillWatchName(watch)]));\n}\n\n// The name of the line of the steps of the wall clock. A step in the window of an open line gives an update.\nconst CLOCK_LINE = \"clock\";\n\n// The name of the line of the recoveries of the log. A second recovery in the window of an open line gives an update.\nconst LOG_LINE = \"log\";\n\n// The start of the name of each line of a store. The store and the family follow it.\nconst STORE_LINE = \"store/\";\n\nfunction storeName(fill: StoreFill): string {\n return `${STORE_LINE}${encodeURIComponent(fill.store)}/${encodeURIComponent(fill.family)}`;\n}\n\nfunction coverageName(place: PlaceId, kind: string): string {\n return `coverage/${encodeURIComponent(place)}/${encodeURIComponent(kind)}`;\n}\n\n// The start of the name of each line of an exhausted escalation. The copy is not in the name: one copy reports it.\nconst CHANNEL_LINE = \"channel/\";\n\nfunction channelName(copy: string, channel: string): string {\n return `${CHANNEL_LINE}${copy}/${channel}`;\n}\n\n/** This function gives the channels of a copy with an open line of a down channel, in the order of their ids. The runtime probes them. */\nexport function downChannels(lines: SystemLines, copy: string): ChannelId[] {\n const prefix = channelName(copy, \"\");\n return Object.keys(lines.open)\n .filter((name) => name.startsWith(prefix))\n .map((name) => name.slice(prefix.length) as ChannelId)\n .sort(compareCodeUnits);\n}\n\n// The facts of the line of a down channel. A new count is not a fact, so the line gives one alert. A new cause gives an update.\ninterface ChannelDownFacts {\n readonly copy: string;\n readonly channel: string;\n readonly onset: Instant;\n /** `key`: the provider refuses the key of the channel. `outage`: the calls get no answer, or a fault of the provider. */\n readonly cause: \"key\" | \"outage\";\n}\n\nfunction causeOf(run: ChannelRun): ChannelDownFacts[\"cause\"] {\n return run.kind === \"auth\" ? \"key\" : \"outage\";\n}\n\n// The time of a run in a text: whole seconds under 2 min, else whole minutes.\nfunction spanText(span: number): string {\n return stepSizeText(span < 120_000 ? Math.round(span / 1000) * 1000 : Math.round(span / 60_000) * 60_000);\n}\n\nconst FAILURE_TEXT: Readonly<Record<string, string>> = {\n network: \"the network to the provider failed\",\n timeout: \"the provider gave no answer in time\",\n server: \"the provider gave a server error\",\n auth: \"the provider refused the key\",\n};\n\n// The condition of one channel of a copy. An open line stays until a good call at or after its onset. A restart\n// empties the run, and an empty run does not end the line. A closed line opens only for a run that `runOpens`.\nfunction channelCondition(entry: ChannelSnapshot, line: SystemLine | undefined, policy: ChannelDownPolicy): Condition | undefined {\n const { copy, channel, title, run, good } = entry;\n const open = line === undefined ? undefined : (JSON.parse(line.facts) as ChannelDownFacts);\n let facts: ChannelDownFacts;\n if (open !== undefined) {\n if (good !== undefined && good >= open.onset) return undefined;\n facts = run === undefined ? open : { ...open, cause: causeOf(run) };\n } else {\n if (run === undefined || !runOpens(run, policy) || (good !== undefined && good >= run.first)) return undefined;\n facts = { copy, channel, onset: run.first, cause: causeOf(run) };\n }\n const code = `${CHANNEL_KIND}.down`;\n const count = run === undefined ? \"\" : ` ${String(run.failures)} calls failed in ${spanText(run.last - run.first)}, and ${FAILURE_TEXT[run.kind] ?? run.kind} at the last call.`;\n const text =\n facts.cause === \"key\"\n ? {\n headline: `The provider of ${title} refuses the key of the channel. This is not an outage.`,\n description: `The copy ${copy} cannot send on ${title}.${count} The fault does not end by itself.`,\n instruction: \"Replace the key of the channel in the secrets of the copy. Until then, the other channels carry the alerts.\",\n }\n : {\n headline: `${title} is down for the copy ${copy}.`,\n description: `The calls of the copy ${copy} to the provider of ${title} fail.${count}`,\n instruction: \"The other channels carry the alerts. The line ends at the next call that passes.\",\n };\n return {\n facts: { ...facts },\n kind: { code, label: kindLabel(code) },\n severity: \"severe\",\n urgency: \"expected\",\n response: [\"assess\"],\n onset: facts.onset,\n areas: [],\n about: [{ system: CHANNEL_SUBJECT, id: channel, label: title }, ...(entry.api ?? []).flatMap(entitySubject)],\n ...text,\n parameters: { copy: [copy], channel: [channel], cause: [facts.cause], ...(run === undefined ? {} : { failures: [String(run.failures)], last: [run.kind] }) },\n };\n}\n\n// The subject of the key of an entity, as `domain:api.twilio.com`. The id is the text after the first colon.\n// The schema refuses an endpoint key with no system or no id. A descriptor in code has no parse, thus such a key gives no subject.\nfunction entitySubject(key: string): Subject[] {\n const colon = key.indexOf(\":\");\n if (colon <= 0 || colon === key.length - 1) return [];\n return [{ system: key.slice(0, colon), id: key.slice(colon + 1) }];\n}\n\n// The start of the name of each line of the observe mode.\nconst OBSERVE_LINE = \"observe/\";\n\nfunction observeName(entry: ObserveCondition): string {\n return `${OBSERVE_LINE}${encodeURIComponent(entry.source)}/${entry.state}`;\n}\n\nfunction observeCondition(entry: ObserveCondition, title: string, context: boolean): Condition {\n // As with the health, a condition of a source of context reaches the digest at most.\n const terms = context ? ({ severity: \"minor\", urgency: \"future\" } as const) : ({ severity: \"moderate\", urgency: \"expected\" } as const);\n const about = [{ system: SOURCE_SUBJECT, id: entry.source, label: title }];\n if (entry.state === \"held\") {\n return {\n // The reason has counts, so it is not a fact: a new count gives no update.\n facts: { source: entry.source, state: entry.state },\n kind: { code: `${HEALTH_KIND}.observe`, label: \"Source held in observe mode\" },\n ...terms,\n response: [\"assess\"],\n onset: entry.since,\n areas: [],\n about,\n headline: `${title}: the source stays in the observe mode.`,\n ...(entry.reason === \"\" ? {} : { description: entry.reason }),\n instruction: \"Examine the areas of the source. The source goes live after one day with no cap passed.\",\n parameters: { state: [entry.state] },\n };\n }\n // Each new incident is a new fact, so it gives an update.\n const count = entry.incidents.length;\n return {\n facts: { source: entry.source, state: entry.state, incidents: entry.incidents },\n kind: { code: `${HEALTH_KIND}.observe-life-safety`, label: \"Life-safety alert from a source in observe mode\" },\n ...terms,\n response: [\"assess\"],\n ...(Number.isFinite(entry.since) ? { onset: entry.since } : {}),\n areas: [],\n about,\n headline: `${title}: a source in the observe mode gave ${String(count)} life-safety ${count === 1 ? \"alert\" : \"alerts\"}.`,\n description: \"The observe mode sent each life-safety alert, because a missed real warning is worse than a wrong one.\",\n instruction: \"Examine the areas of the source and each alert. A wrong area makes alerts for a person away from the event.\",\n parameters: { state: [entry.state], incident: entry.incidents },\n };\n}\n\nconst EXHAUSTION_LINE = \"exhausted/\";\n\nfunction exhaustionName(entry: Exhaustion): string {\n return `${EXHAUSTION_LINE}${encodeURIComponent(entry.person)}/${encodeURIComponent(entry.incident)}/${String(entry.episode)}/${entry.level}`;\n}\n\n// The severity and the urgency of an exhaustion at each level. The table of the class `system-escalation` gives back the level.\nconst EXHAUSTION_TERMS: Readonly<Record<Exhaustion[\"level\"], { readonly severity: Severity; readonly urgency: Urgency }>> = {\n \"life-safety\": { severity: \"extreme\", urgency: \"immediate\" },\n urgent: { severity: \"severe\", urgency: \"expected\" },\n notice: { severity: \"moderate\", urgency: \"future\" },\n digest: { severity: \"minor\", urgency: \"past\" },\n};\n\nfunction exhaustionCondition(entry: Exhaustion): Condition {\n const code = `${ESCALATION_KIND}.exhausted`;\n return {\n // The facts do not change while the escalation stays exhausted. Thus it gives one alert, and an acknowledgment or the end gives its cancel.\n // The title is not a fact: a new text of the warning gives no new alert.\n facts: { person: entry.person, incident: entry.incident, episode: entry.episode, level: entry.level, at: entry.at },\n kind: { code, label: kindLabel(code) },\n ...EXHAUSTION_TERMS[entry.level],\n response: [\"assess\"],\n onset: entry.at,\n // The report has no area. Thus it reaches only the people who watch the person, and not the people at the place.\n areas: [],\n about: [\n { system: PERSON_SUBJECT, id: entry.person, label: `Person ${entry.person}` },\n { system: INCIDENT_SUBJECT, id: entry.incident, label: entry.title },\n ],\n // The headline tells what the person missed: the kind, the title and the level of the warning.\n headline: `${entry.person} did not acknowledge ${entry.kind.label} (${entry.level})${entry.title === entry.kind.label ? \"\" : `: ${entry.title}`}`,\n description: `The warning reached ${entry.person} at the level ${entry.level}. No acknowledgment came before ${new Date(entry.at).toISOString()}, the end of the escalation.`,\n instruction: `Speak to ${entry.person}. An acknowledgment of the warning by ${entry.person} ends this alert.`,\n parameters: { person: [entry.person], level: [entry.level], kind: [entry.kind.code], incident: [entry.incident] },\n };\n}\n\nconst HELD_LINE = \"held/\";\n\n/** The count of the held alerts that a notice of the send limit names (AL-98). The next digest tells each one. */\nexport const HELD_SHOWN = 3;\n\n/**\n * This function gives the text of a notice of the send limit (AL-98). It names the held alerts from the highest level,\n * with their levels, and the count of the rest. The text is the text of the first report of the line. Thus a later hold\n * in the window does not change it.\n */\nexport function heldText(entry: Pick<HeldPerson, \"alerts\">): string {\n const end = \"The limit does not hold a life-safety warning.\";\n if (entry.alerts.length === 0) return `More new alerts came than your send limit lets through in one window. ${end}`;\n const shown = entry.alerts.slice(0, HELD_SHOWN).map((alert) => `- ${alert.headline} (${alert.level})`);\n const rest = entry.alerts.length - shown.length;\n return [`The send limit holds ${countOf(entry.alerts.length, \"new alert\")} for you:`, ...shown, ...(rest > 0 ? [`- ${countOf(rest, \"other alert\")}`] : []), end].join(\"\\n\");\n}\n\nfunction heldName(entry: HeldPerson): string {\n return `${HELD_LINE}${encodeURIComponent(entry.person)}`;\n}\n\nfunction heldCondition(entry: HeldPerson): Condition {\n const code = `${LIMIT_KIND}.held`;\n return {\n // The person is the only fact. Thus the first hold of a window gives one alert, and a later hold in the window gives no report.\n // The line ends one window after the last hold. A hold after that end opens a new line, thus a new message.\n facts: { person: entry.person },\n kind: { code, label: kindLabel(code) },\n // The table of the system reports gives the level `notice`.\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"none\"],\n onset: entry.first,\n // The report is private. Thus only the person with the holds gets it, and the people who watch the person do not.\n areas: [],\n about: [{ system: PERSON_SUBJECT, id: entry.person, label: `Person ${entry.person}` }],\n addresses: [entry.person],\n headline: \"The send limit holds new alerts for you\",\n description: heldText(entry),\n instruction: \"Read the next digest. It tells each held alert.\",\n parameters: { person: [entry.person] },\n };\n}\n\nfunction drillRunCondition(copy: string, drill: DrillConfig, run: DrillRun): Condition {\n const code = `${DRILL_KIND}.run`;\n return {\n // The start is the only fact. Thus a run gives one alert, and the end of the wait gives its cancel.\n facts: { copy, drill: drill.id, at: run.at },\n kind: { code, label: kindLabel(code) },\n severity: \"extreme\",\n urgency: \"immediate\",\n response: [\"none\"],\n onset: run.at,\n areas: [],\n about: [{ system: DRILL_SUBJECT, id: drill.id, label: `Drill ${drill.id}` }],\n headline: `Drill ${drill.id}: acknowledge this message. This is not a warning.`,\n description: `This message tests the path of the life-safety warnings from the copy ${copy}. An acknowledgment in ${String(Math.round(drill.ackWithin / 60_000))} minutes passes the drill.`,\n instruction: \"Acknowledge the message.\",\n parameters: { drill: [drill.id], copy: [copy] },\n };\n}\n\nfunction drillFailedCondition(copy: string, drill: DrillConfig, run: DrillRun, why: \"no-ack\" | \"late-ack\"): Condition {\n const code = `${DRILL_KIND}.failed`;\n const late = why === \"late-ack\";\n return {\n // Each run and each reason is a new fact. Thus a late acknowledgment after a failure gives an update.\n facts: { copy, drill: drill.id, at: run.at, why },\n kind: { code, label: kindLabel(code) },\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n onset: run.at + drill.ackWithin,\n areas: [],\n about: [{ system: DRILL_SUBJECT, id: drill.id, label: `Drill ${drill.id}` }],\n headline: `The drill ${drill.id} failed: ${late ? \"the acknowledgment came late\" : \"no acknowledgment came\"}.`,\n description: `The drill started at ${new Date(run.at).toISOString()} on the channel ${drill.path.channel}, from the copy ${copy}. A real warning on this path can also go without an answer.`,\n instruction: \"Examine the channel, the app and the settings of the phone. The next run of the drill tests the path again.\",\n parameters: { drill: [drill.id], copy: [copy], why: [why] },\n };\n}\n\nfunction drillMissedCondition(copy: string, drill: DrillConfig, run: DrillRun, due: Instant): Condition {\n const code = `${DRILL_KIND}.failed`;\n return {\n // The missed start comes from the last run, thus it stays the same until the next run ends the line.\n facts: { copy, drill: drill.id, due, why: \"missed\" },\n kind: { code, label: kindLabel(code) },\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n onset: due,\n areas: [],\n about: [{ system: DRILL_SUBJECT, id: drill.id, label: `Drill ${drill.id}` }],\n headline: `The drill ${drill.id} did not start at its time.`,\n description: `The drill was due at ${new Date(due).toISOString()} on the channel ${drill.path.channel}, from the copy ${copy}. No run started in its window. The last run started at ${new Date(run.at).toISOString()}.`,\n instruction: \"Examine why the copy did not operate in the window of the drill. The next run of the drill tests the path again.\",\n parameters: { drill: [drill.id], copy: [copy], why: [\"missed\"] },\n };\n}\n\nfunction drillNoStartCondition(copy: string, drill: DrillConfig): Condition {\n const code = `${DRILL_KIND}.failed`;\n return {\n // The drill and the reason are the only facts. Thus the line gives one alert, and a next start gives its cancel.\n facts: { copy, drill: drill.id, why: \"no-start\" },\n kind: { code, label: kindLabel(code) },\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n areas: [],\n about: [{ system: DRILL_SUBJECT, id: drill.id, label: `Drill ${drill.id}` }],\n headline: `The drill ${drill.id} has no next start.`,\n description: `Each time of the window of the drill is in the quiet window of the person, or too near to it. The copy ${copy} does not test the path on the channel ${drill.path.channel}.`,\n instruction: \"Change the window of the drill or the quiet window of the person in the configuration.\",\n parameters: { drill: [drill.id], copy: [copy], why: [\"no-start\"] },\n };\n}\n\nfunction drillWatchCondition(watch: DrillWatch, miss: DrillWatchMiss): Condition {\n const code = `${DRILL_KIND}.failed`;\n const { drill } = watch;\n const copy = watch.copy === undefined ? \"the copy of rank 0\" : `the copy ${watch.copy}`;\n const Copy = `T${copy.slice(1)}`;\n const noRead = miss.why === \"no-read\";\n const due = `The drill was due at ${new Date(miss.due).toISOString()}, and its window ended at ${new Date(miss.end).toISOString()}.`;\n const read = miss.read === undefined ? `No read of ${copy} passed after the start of the watch.` : `The last read of ${copy} that passed was at ${new Date(miss.read).toISOString()}.`;\n const last = miss.last === undefined ? \"No read gave a start of the drill.\" : `The last start of the drill in the reads was at ${new Date(miss.last).toISOString()}.`;\n return {\n // The due start and the reason are the only facts. Thus a new read and a restart of this copy give no update.\n facts: { watched: watch.copy ?? \"\", drill: drill.id, due: miss.due, why: miss.why },\n kind: { code, label: kindLabel(code) },\n severity: noRead ? \"minor\" : \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n onset: miss.end,\n areas: [],\n about: [{ system: DRILL_SUBJECT, id: drill.id, label: `Drill ${drill.id}` }],\n headline: noRead ? `This copy cannot tell if the drill ${drill.id} started.` : `No start of the drill ${drill.id} came from ${copy}.`,\n description: noRead\n ? `${due} ${Copy} answers, but its answers give no starts of drills. A copy of an older build gives none.`\n : `${due} ${read} ${last} The path of the life-safety warnings on the channel ${drill.path.channel} has no test from that copy.`,\n instruction: noRead\n ? `Update ${copy} to the build of this copy. The next start of the drill ends this message.`\n : `Examine ${copy}: its state, its log and the configuration of the drill. The next start of the drill ends this message.`,\n parameters: { drill: [drill.id], ...(watch.copy === undefined ? {} : { copy: [watch.copy] }), why: [miss.why] },\n };\n}\n\n/**\n * This function tells if each kind of a source is a kind of context (`CONTEXT_KINDS`). The reports of such a source reach the\n * digest at most, so its health also reaches the digest at most. A source with no kind is not a source of context.\n */\nexport function contextSource(source: SourceDescriptor): boolean {\n return source.kinds.length > 0 && source.kinds.every((kind) => hasKind(CONTEXT_KINDS, kind));\n}\n\n// The down state of the open line of a source that is up, while the source is up for less than its clear time. The state\n// of the line comes from its facts. A source that is slow after it was up has a later start of its state, so its line\n// stays open for longer: this error keeps a line, and it never ends a line early.\nfunction heldState(line: SystemLine | undefined, health: SourceHealth, at: Instant, clear: Duration): HealthState | undefined {\n if (line === undefined || at - health.since >= clear) return undefined;\n const { state } = JSON.parse(line.facts) as { readonly state?: unknown };\n return DOWN_STATES.find((down) => down === state);\n}\n\nfunction healthCondition(health: SourceHealth, title: string, context: boolean): Condition {\n return {\n // The reason of the health has counts and times, so it is not a fact: a new count gives no update.\n facts: { source: health.source, state: health.state },\n kind: { code: `${HEALTH_KIND}.${health.state}`, label: `Source ${health.state}` },\n // With the default policy, the health of a source of context reaches the digest at most.\n severity: context ? \"minor\" : \"moderate\",\n urgency: context ? \"future\" : \"expected\",\n response: [\"assess\"],\n onset: health.since,\n areas: [],\n about: [{ system: SOURCE_SUBJECT, id: health.source, label: title }],\n headline: `${title}: ${HEADLINES[health.state] ?? health.state}.`,\n ...(health.reason === \"\" ? {} : { description: health.reason }),\n parameters: { state: [health.state] },\n };\n}\n\nfunction lateCondition(entry: Lateness, titles: ReadonlyMap<SourceId, string>): Condition {\n const to = titles.get(entry.to) ?? entry.to;\n const from = titles.get(entry.from) ?? entry.from;\n const delay = entry.limit?.delay ?? 0;\n const misses = entry.limit?.misses ?? 1;\n return {\n // Each new miss is a new fact, so it gives an update.\n facts: { expectation: entry.expectation, from: entry.from, to: entry.to, missed: entry.missed },\n kind: { code: `${HEALTH_KIND}.late`, label: \"Source late\" },\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n ...(entry.since === undefined ? {} : { onset: entry.since }),\n areas: [],\n about: [{ system: SOURCE_SUBJECT, id: entry.to, label: to }],\n headline: `${to} is late: it did not carry the reports of ${from} in time.`,\n description: `Reports with no copy: ${entry.missed.length}. The limit of the delay is ${Math.round(delay / 1000)} seconds, and the limit of the misses is ${misses}, from the measured delays and misses.`,\n parameters: { expectation: [entry.expectation], missed: entry.missed, delay: [String(delay)], misses: [String(misses)] },\n };\n}\n\nfunction coverageCondition(entry: Coverage, threatened: boolean): Condition {\n const grade = gapGrade(entry, threatened);\n const lines = [\n entry.independent === 0\n ? `No source that is up covers ${entry.kind} at this place.`\n : `A fault of ${entry.faults.join(\", \")} stops each source that covers ${entry.kind} at this place.`,\n ...(entry.proven ? [] : [\"The search did not prove the count, so the true count can be smaller.\"]),\n ...(entry.commonResources.length === 0 ? [] : [`Each of these sources uses the ${entry.commonResources.join(\", \")} of this place.`]),\n ];\n return {\n facts: { place: entry.place, kind: entry.kind, ...grade, independent: entry.independent, required: entry.required, proven: entry.proven, faults: entry.faults },\n kind: { code: `${COVERAGE_KIND}.${entry.kind}`, label: `Coverage of ${entry.kind}` },\n ...grade,\n response: entry.independent === 0 ? [\"monitor\"] : [\"assess\"],\n areas: [{ type: \"place\", place: entry.place }],\n about: [],\n headline: `Coverage of ${entry.kind}: ${entry.independent} of ${entry.required} independent sources.`,\n description: lines.join(\" \"),\n ...(entry.independent === 0 ? { instruction: \"Use another source of warnings, for example a weather radio.\" } : {}),\n parameters: {\n independent: [String(entry.independent)],\n required: [String(entry.required)],\n proven: [String(entry.proven)],\n faults: entry.faults,\n sources: entry.sources,\n },\n };\n}\n\nfunction quotaCondition(quota: ChannelQuota, stage: QuotaStage): Condition {\n const { channel, limit, reserve, used } = quota;\n const unit = quota.unit ?? \"units\";\n const until = stage === \"spent\" ? (quota.blockedUntil ?? quota.resetAt) : quota.resetAt;\n const end = until === undefined ? \"\" : ` until ${new Date(until).toISOString()}`;\n const text: Readonly<Record<QuotaStage, { readonly headline: string; readonly description: string }>> = {\n low: {\n headline: `${channel}: ${Math.max(0, limit - used)} of ${limit} ${unit} of the window are left.`,\n description: `At ${reserve} ${unit} left, the channel sends only life-safety messages${end}. The other messages then wait for the reset.`,\n },\n reserve: {\n headline: `${channel} sends only life-safety messages${end}.`,\n description: `The channel keeps its last ${reserve} of ${limit} ${unit} for life-safety. The other messages wait for the reset.`,\n },\n spent: {\n headline: `${channel} sends no message${end}.`,\n description: \"The provider refuses each message, also a life-safety message. Only the other channels carry the alerts.\",\n },\n };\n const code = `${QUOTA_KIND}.${stage}`;\n return {\n // A new count is not a fact. Thus each stage gives one alert in a window, and no update.\n facts: { channel, stage, ...(until === undefined ? {} : { until }) },\n kind: { code, label: kindLabel(code) },\n severity: stage === \"low\" ? \"moderate\" : \"severe\",\n urgency: stage === \"spent\" ? \"immediate\" : \"expected\",\n response: [\"assess\"],\n areas: [],\n about: [{ system: CHANNEL_SUBJECT, id: channel, label: channel }],\n ...text[stage],\n parameters: { stage: [stage], used: [String(used)], limit: [String(limit)], reserve: [String(reserve)] },\n };\n}\n\n// The condition of one stage of a balance. A line `low` has its floor. The other stages have no floor.\nfunction balanceCondition(balance: ProviderBalance, stage: BalanceStage, at: Instant, floor?: number): Condition {\n const { provider, title, floors, read } = balance;\n const amount = read === undefined ? \"\" : `${read.balance.toFixed(2)} ${read.currency}`;\n const last = read === undefined ? `the start of the watch at ${new Date(balance.since).toISOString()}` : new Date(read.at).toISOString();\n const text: Readonly<Record<BalanceStage, { readonly headline: string; readonly description: string }>> = {\n low: {\n headline: `${title}: the balance is ${amount}, below the floor of ${(floor ?? Math.max(...floors)).toFixed(2)}.`,\n description: \"Add money to the account. At 0, the provider refuses each paid message, also a life-safety message.\",\n },\n empty: {\n headline: `${title} refuses each paid message: the balance is ${amount}.`,\n description: \"Add money to the account. Until then, only the other channels carry the alerts.\",\n },\n unread: {\n headline: `The balance of ${title} has no read since ${last}.`,\n description: \"The watch cannot see a low balance. Examine the key of the account and the network.\",\n },\n };\n const code = `${BALANCE_KIND}.${stage}`;\n return {\n // A new balance is not a fact. Thus each stage, and each floor of `low`, gives one alert, and no update.\n facts: { provider, stage, ...(floor === undefined ? {} : { floor }) },\n kind: { code, label: kindLabel(code) },\n severity: stage === \"empty\" ? \"severe\" : \"moderate\",\n urgency: stage === \"empty\" ? \"immediate\" : \"expected\",\n response: [\"assess\"],\n areas: [],\n about: balance.channels.map((channel) => ({ system: CHANNEL_SUBJECT, id: channel, label: channel })),\n ...text[stage],\n parameters: {\n stage: [stage],\n floor: floor === undefined ? floors.map(String) : [String(floor)],\n ...(read === undefined ? {} : { balance: [String(read.balance)], currency: [read.currency] }),\n age: [String(at - (read?.at ?? balance.since))],\n },\n };\n}\n\nfunction copyCondition(watch: CopyWatch, stage: CopyStage, at: Instant): Condition {\n const { copy, read } = watch;\n const last = read === undefined ? `the start of the watch at ${new Date(watch.since).toISOString()}` : new Date(read.at).toISOString();\n const skew = read === undefined ? \"\" : `${(Math.abs(read.skew) / 1000).toFixed(1)} s`;\n const text: Readonly<Record<CopyStage, { readonly headline: string; readonly description: string; readonly instruction: string }>> = {\n skew: {\n headline: `The clock of the copy ${copy} differs from the clock of this copy by ${skew}.`,\n description: `The rank wait holds a difference of ${(watch.skewLimit / 1000).toFixed(1)} s or less. A larger difference can let two copies send the same alert.`,\n instruction: \"Examine the time settings and the time server of each computer.\",\n },\n config: {\n headline: `The copy ${copy} has a different configuration.`,\n description: \"The copies can route one alert in two ways. Then a person can get an alert from each copy, or on a different channel.\",\n instruction: \"Give each copy the same file config.json. Then restart each copy.\",\n },\n unread: {\n headline: `No read of the copy ${copy} passed since ${last}.`,\n description: \"This copy cannot see the sends of the other copy. Thus the two copies can both send each alert.\",\n instruction: \"Examine the other computer and the network between the copies.\",\n },\n unsteady: {\n headline: `The copy ${copy} is not steady since ${new Date(watch.unsteadySince ?? watch.since).toISOString()}.`,\n description: \"The other copy starts again and again, and it stops before it is steady. It sends no alert. Thus this copy is the only copy that sends.\",\n instruction: \"Examine the memory and the start log of the other computer.\",\n },\n };\n const code = `${COPY_KIND}.${stage}`;\n return {\n // A new difference or a new age is not a fact. Thus each stage gives one alert, and no update.\n facts: { copy, stage },\n kind: { code, label: kindLabel(code) },\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n areas: [],\n about: [{ system: COPY_SUBJECT, id: copy, label: `Copy ${copy}` }],\n ...text[stage],\n parameters: {\n stage: [stage],\n ...(read === undefined ? {} : { skew: [String(read.skew)], sameConfig: [String(read.sameConfig)] }),\n age: [String(at - (read?.at ?? watch.since))],\n },\n };\n}\n\nfunction clockCondition(step: ClockStep): Condition {\n const code = `${CLOCK_KIND}.step`;\n return {\n // Each step is a new fact, thus a second step in the window gives an update.\n facts: { at: step.at, size: step.size },\n kind: { code, label: kindLabel(code) },\n severity: \"minor\",\n urgency: \"past\",\n response: [\"assess\"],\n onset: step.at,\n areas: [],\n about: [{ system: CLOCK_SUBJECT, id: \"wall\", label: \"Wall clock\" }],\n headline: `The wall clock stepped ${step.size < 0 ? \"back\" : \"forward\"} by ${stepSizeText(step.size)}.`,\n description: \"The alert system moved its own times by the step, thus each timer keeps its time. The times of the sources and the channels did not move.\",\n instruction: \"Examine the time settings and the time server of the computer.\",\n parameters: { size: [String(step.size)] },\n };\n}\n\n// A loss of events can repeat a send or lose an acknowledgment, thus it gets `notice`. A recovery with no loss gets `digest`.\nfunction logCondition(recovery: LogRecovery): Condition {\n const code = `${LOG_KIND}.recovered`;\n const lossy = !recovery.whole || recovery.lost > 0;\n const positions = recovery.lost > 0 ? ` (${String(recovery.lost)} positions)` : \"\";\n const kept = lossy\n ? `It kept ${String(recovery.kept)} events, and it could not read each part of the file${positions}. A lost event can repeat a send or lose an acknowledgment.`\n : `It kept each of the ${String(recovery.kept)} events.`;\n return {\n facts: { at: recovery.at, quarantine: recovery.quarantine, kept: recovery.kept, lost: recovery.lost, whole: recovery.whole },\n kind: { code, label: kindLabel(code) },\n severity: lossy ? \"moderate\" : \"minor\",\n urgency: lossy ? \"expected\" : \"past\",\n response: [\"assess\"],\n onset: recovery.at,\n areas: [],\n about: [{ system: LOG_SUBJECT, id: \"runtime\", label: \"Log of the runtime\" }],\n headline: \"The log file of the alert system was broken.\",\n description: `The alert system moved the broken file into the quarantine folder ${recovery.quarantine}, and it started a new log. ${kept}`,\n instruction: \"Examine the disk of the computer. Keep the quarantine folder until you know the cause.\",\n parameters: { quarantine: [recovery.quarantine], kept: [String(recovery.kept)], lost: [String(recovery.lost)], whole: [String(recovery.whole)] },\n };\n}\n\n// A family with no entry stops a feature, not a send. Thus it gets `notice` at most.\nfunction storeCondition(fill: StoreFill, titles: ReadonlyMap<SourceId, string>): Condition {\n const code = `${STORE_KIND}.empty`;\n const minutes = Math.round(fill.within / 60_000);\n return {\n // A new count or a new start is not a fact. Thus a restart gives no update and no new alert.\n facts: { store: fill.store, family: fill.family },\n kind: { code, label: kindLabel(code) },\n severity: \"moderate\",\n urgency: \"expected\",\n response: [\"assess\"],\n areas: [],\n about: [\n { system: STORE_SUBJECT, id: `${fill.store}/${fill.family}`, label: `Store ${fill.store}, family ${fill.family}` },\n ...fill.sources.map((source) => ({ system: SOURCE_SUBJECT, id: source, label: titles.get(source) ?? source })),\n ],\n headline: `The store ${fill.store} has no entry of the family ${fill.family} ${String(minutes)} minutes after the start.`,\n description: \"The store did not fill in the time. Its sources can be down, or the store gets no turn to fetch. Each feature that reads the family works without it.\",\n instruction: \"Examine the health of the sources of the store and the log of its refreshes.\",\n parameters: { entries: [String(fill.entries)], within: [String(fill.within)] },\n };\n}\n\n// The cancel of a line: an all clear of the same kind, areas and subjects.\nfunction cancelOf(line: SystemLine): Condition {\n return {\n facts: { cancel: line.key },\n kind: line.kind,\n severity: \"minor\",\n urgency: \"past\",\n response: [\"allclear\"],\n areas: line.areas,\n about: line.about,\n ...(line.addresses === undefined ? {} : { addresses: line.addresses }),\n headline: `${line.kind.label}: the condition ended.`,\n parameters: {},\n };\n}\n\nfunction observationOf(name: string, op: Operation, facts: Condition[\"facts\"], at: Instant): Observation {\n const contentType = \"application/json\";\n const body = canonicalJson({ name, op, facts }, { form: \"json\" });\n return { id: observationId({ source: SYSTEM_SOURCE, contentType, body }), source: SYSTEM_SOURCE, fetched: at, contentType, body, transport: { latency: 0 } };\n}\n\ninterface Envelope {\n readonly key: string;\n readonly op: Operation;\n readonly references: readonly string[];\n readonly at: Instant;\n readonly observation: Observation[\"id\"];\n}\n\nfunction reportOf(draft: Condition, envelope: Envelope): Report {\n const { key, op, references, at, observation } = envelope;\n return {\n id: reportId({ source: SYSTEM_SOURCE, key, sent: at }),\n source: SYSTEM_SOURCE,\n origin: SYSTEM_SOURCE,\n key,\n references,\n correlation: [],\n status: \"system\",\n op,\n kind: draft.kind,\n categories: [\"system\"],\n severity: draft.severity,\n urgency: draft.urgency,\n certainty: \"observed\",\n response: draft.response,\n sent: at,\n received: at,\n ...(draft.onset === undefined ? {} : { onset: draft.onset }),\n areas: draft.areas,\n about: draft.about,\n ...(draft.addresses === undefined ? {} : { addresses: draft.addresses }),\n sender: \"alerts\",\n headline: draft.headline,\n ...(draft.description === undefined ? {} : { description: draft.description }),\n ...(draft.instruction === undefined ? {} : { instruction: draft.instruction }),\n observation,\n parameters: draft.parameters,\n };\n}\n","/**\n * This module holds the send limit of each person (AL-72). It is pure. The limit keeps a burst of new incidents away\n * from the phone of a person. Each level below `life-safety` admits a count of new escalations in each window, over all\n * the copies of the system. The digest tells each incident that the limit held. The private incidents (AL-92) have their own\n * places, thus the messages of the operator and the alerts do not take places from each other. A person with a hold gets\n * one notice in each window (`heldPersons`, AL-81).\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { isPrivate } from \"./audience.ts\";\nimport { LEVELS } from \"./contracts.ts\";\nimport type { CopyWatch, Delivery, Duration, Instant, Level, PersonId, Report, ReportId } from \"./contracts.ts\";\nimport type { EscalationHold, Route } from \"./delivery.ts\";\nimport { messageKey } from \"./ids.ts\";\nimport { copyStages } from \"./system-reports.ts\";\n\n/** The levels with a send limit. A `life-safety` escalation has no limit, and the level `digest` has no escalation. */\nexport type LimitedLevel = \"notice\" | \"urgent\";\n\n/** The levels with a send limit, from the lowest level up. */\nexport const LIMITED_LEVELS: readonly LimitedLevel[] = [\"notice\", \"urgent\"];\n\n/** The send limit of each person: the most new escalations of each level in one window, over all the copies. */\nexport interface SendLimits {\n /** The length of the window. */\n readonly window: Duration;\n /** The most new escalations of the level `notice` of one person in one window. */\n readonly notice: number;\n /** The most new escalations of the level `urgent` of one person in one window. */\n readonly urgent: number;\n}\n\n/** The part of the configuration that changes the send limit. Each field that is absent keeps its default. */\nexport type SendLimitConfig = Partial<SendLimits>;\n\n/**\n * The default send limit: 6 notices and 12 urgent escalations in one hour. From 2026-11-16 to 2026-11-18, before the\n * burst of AL-72, the busiest hour of one person had 4 notices and 8 urgent messages. The limit adds 50 percent.\n */\nexport const DEFAULT_SEND_LIMITS: SendLimits = { window: 3_600_000, notice: 6, urgent: 12 };\n\n/** The shortest window of a send limit: one minute. */\nexport const SEND_LIMIT_MIN_WINDOW: Duration = 60_000;\n\n/** The longest window of a send limit: one day. */\nexport const SEND_LIMIT_MAX_WINDOW: Duration = 86_400_000;\n\n/** This function gives the send limit of a configuration. Each field that is absent has its default. */\nexport function sendLimitsOf(config: SendLimitConfig | undefined): SendLimits {\n return { ...DEFAULT_SEND_LIMITS, ...config };\n}\n\n/**\n * This function gives the problems of the send limit of a configuration. The window is one minute to one day. Each\n * count is an integer of 1 or more.\n */\nexport function sendLimitProblems(config: SendLimitConfig): string[] {\n const problems: string[] = [];\n const { window } = config;\n if (window !== undefined && !(Number.isInteger(window) && window >= SEND_LIMIT_MIN_WINDOW && window <= SEND_LIMIT_MAX_WINDOW)) {\n problems.push(`The window of the send limit is ${String(window)} ms. It must be an integer from ${SEND_LIMIT_MIN_WINDOW} to ${SEND_LIMIT_MAX_WINDOW} ms.`);\n }\n for (const level of LIMITED_LEVELS) {\n const count = config[level];\n if (count !== undefined && !(Number.isInteger(count) && count >= 1)) problems.push(`The send limit of the level ${level} is ${String(count)}. It must be an integer of 1 or more.`);\n }\n return problems;\n}\n\n/** This function tells if a level has a send limit. */\nexport function isLimitedLevel(level: Level): level is LimitedLevel {\n return (LIMITED_LEVELS as readonly Level[]).includes(level);\n}\n\n/**\n * This function gives the share of the send limit for this copy at `at`. This copy does not see the sends of a copy\n * that it cannot read. That copy does not see the sends of this copy. Thus each of them takes one share: 1 divided by\n * 1 plus the count of these copies. With each other copy read, the share is 1.\n *\n * - A copy in the stage `unread` counts.\n * - A copy with no read from the start of its watch also counts. Thus two copies that start in a split send one limit together.\n */\nexport function limitShare(watches: readonly CopyWatch[], at: Instant): number {\n return 1 / (1 + watches.filter((watch) => watch.read === undefined || copyStages(watch, at).includes(\"unread\")).length);\n}\n\n/** The holds of one person in the window of the send limit (AL-81). */\nexport interface HeldPerson {\n readonly person: PersonId;\n /** The time of the first hold in the window. */\n readonly first: Instant;\n /** The time of the last hold in the window. */\n readonly last: Instant;\n /** The time when the last hold leaves the window: one window after it. Then the person has no hold. */\n readonly until: Instant;\n /** The count of the holds in the window. */\n readonly count: number;\n /**\n * The held alerts, one for each incident with its highest held level (AL-98). They come from the highest level, then\n * from the earliest hold. A hold of a report that the state does not have gives no alert.\n */\n readonly alerts: readonly HeldAlert[];\n}\n\n/** One held alert of a person: the incident, its highest held level and its headline (AL-98). */\nexport interface HeldAlert {\n readonly incident: ReportId;\n readonly level: Level;\n readonly headline: string;\n}\n\n/**\n * This function gives each person with a hold in the window before `at`, in the order of the person ids (AL-81).\n *\n * - A hold counts from its time until one window after it. A hold after `at` does not count.\n * - A hold of a private report (`reports`, AL-92) does not count. Thus a held message of the operator, or a held notice\n * of the send limit, opens no notice of the send limit.\n * - The headline of each held alert comes from the report of the hold (AL-98). Thus the notice tells which alerts wait.\n */\nexport function heldPersons(holds: readonly EscalationHold[], reports: readonly Pick<Report, \"id\" | \"addresses\" | \"headline\">[], window: Duration, at: Instant): HeldPerson[] {\n // A hold names the report of the start of its escalation, thus the ids of the private reports find each private hold.\n const secret = new Set(reports.filter(isPrivate).map((report) => report.id));\n const headlines = new Map(reports.map((report) => [report.id, report.headline]));\n const persons = new Map<PersonId, EscalationHold[]>();\n for (const hold of holds) {\n if (hold.at > at || hold.at + window <= at || secret.has(hold.incident)) continue;\n const list = persons.get(hold.person);\n if (list === undefined) persons.set(hold.person, [hold]);\n else list.push(hold);\n }\n return [...persons.entries()].sort(([a], [b]) => compareCodeUnits(a, b)).map(([person, list]) => {\n const first = Math.min(...list.map((hold) => hold.at));\n const last = Math.max(...list.map((hold) => hold.at));\n return { person, first, last, until: last + window, count: list.length, alerts: heldAlerts(list, headlines) };\n });\n}\n\n/** This function gives the held alerts of the holds of one person: one for each incident with a known report (AL-98). */\nfunction heldAlerts(list: readonly EscalationHold[], headlines: ReadonlyMap<ReportId, string>): HeldAlert[] {\n const rank = (level: Level): number => LEVELS.indexOf(level);\n const top = new Map<ReportId, EscalationHold>();\n for (const hold of list) {\n const known = top.get(hold.incident);\n if (known === undefined || rank(hold.level) > rank(known.level) || (hold.level === known.level && hold.at < known.at)) top.set(hold.incident, hold);\n }\n return [...top.values()]\n .flatMap((hold) => {\n const headline = headlines.get(hold.incident);\n return headline === undefined ? [] : [{ hold, headline }];\n })\n .sort((a, b) => rank(b.hold.level) - rank(a.hold.level) || a.hold.at - b.hold.at || compareCodeUnits(a.hold.incident, b.hold.incident))\n .map(({ hold, headline }) => ({ incident: hold.incident, level: hold.level, headline }));\n}\n\n/** This function gives the key of a hold: one hold for each escalation and episode. */\nexport function holdKey(hold: Pick<EscalationHold, \"incident\" | \"level\" | \"person\" | \"episode\">): string {\n return `${hold.incident}:${hold.level}:${hold.person}:${String(hold.episode)}`;\n}\n\n/** The input of `limitRoutes`. */\nexport interface LimitInput {\n /** The routes at `now` (`route`). */\n readonly routes: readonly Route[];\n /** The deliveries of the ledger: the deliveries of this copy and the deliveries of the other copies. */\n readonly deliveries: readonly Delivery[];\n /** The holds of the log. */\n readonly holds: readonly EscalationHold[];\n /** The send limit. The default is `DEFAULT_SEND_LIMITS`. */\n readonly limits?: SendLimits | undefined;\n /** The share of the limit for this copy (`limitShare`), above 0 and at most 1. The default is 1. */\n readonly share?: number | undefined;\n /**\n * The delivery keys of the sends that this copy started and that have no end yet: a send in flight, or an open copy.\n * A route with one of these sends keeps its place. The default is no key.\n */\n readonly started?: ReadonlySet<string> | undefined;\n /**\n * The reports of the merge state (`MergeState.reports`). A delivery of a private report counts only in the private\n * places of its person and level. The default is no report: then only the routes tell the private incidents.\n */\n readonly reports?: readonly Pick<Report, \"id\" | \"addresses\">[] | undefined;\n readonly now: Instant;\n}\n\n/** The result of `limitRoutes`. */\nexport interface LimitResult {\n /** The routes in the same order. A held route has no send in its plan, and it has the hold (`Route.held`). */\n readonly routes: readonly Route[];\n /** The new holds at `now`, in the order of the routes. The runtime writes them to its log. */\n readonly holds: readonly EscalationHold[];\n}\n\n/**\n * This function applies the send limit of each person to the routes.\n *\n * - A route of `life-safety` has no limit. It does not change.\n * - A route with a hold in the log is held. The hold does not end in its episode.\n * - A route with a delivery in its episode is admitted. Its later steps go with no limit, thus the repeats of an\n * alert are not cut.\n * - A route with a send and no delivery is new. Each person and each level has a count of places. The count is the\n * limit times the share, less the incidents with a delivery of the level in the window. The deliveries of the\n * other copies count, thus the limit applies over all the copies. The places of the share are at least 1, thus each\n * copy that runs alone still sends.\n * - Each delivery in the window counts, not only the first delivery of the incident. Thus a new episode of an old\n * incident counts after its send, and the window cannot hold more than the limit.\n * - The new routes get places in the order of their first due time, then of the anchor, then of the episode. A new\n * route with no place gets a hold at `now`.\n * - A send in flight or a refused send has no delivery yet. Its route stays new, and it keeps its place, because its\n * first due time is early. Thus the count of the admitted escalations does not pass the limit over many passes.\n * - A route with a started send (`started`) gets a place before each other new route, and it does not get a hold. The\n * phone can already have its message. Thus a new route with an earlier due time cannot take its place.\n * - A held route has no send in its plan. Its cancels stay.\n * - A private incident (`addresses`, AL-92) has its own places for each person and level, with the same counts. Only the\n * deliveries of the private reports count in them. Thus a burst of messages of the operator does not hold an alert.\n * Also, a busy hour of alerts does not hold a message of the operator.\n */\nexport function limitRoutes(input: LimitInput): LimitResult {\n const limits = input.limits ?? DEFAULT_SEND_LIMITS;\n const share = input.share !== undefined && input.share > 0 && input.share <= 1 ? input.share : 1;\n const logged = new Map(input.holds.map((hold) => [holdKey(hold), hold]));\n // The ids of the private reports: of the reports of the merge state, and of the incidents of the routes. A delivery holds\n // the anchor of its incident at the time of its send. The anchor is one of the reports, thus the set finds it also after\n // a change of the anchor.\n const secret = new Set<string>();\n for (const report of input.reports ?? []) if (isPrivate(report)) secret.add(report.id);\n for (const entry of input.routes) if (isPrivate(entry.incident)) for (const id of [entry.incident.anchor, ...entry.incident.reports]) secret.add(id);\n const groupOf = (person: PersonId, level: Level, only: boolean): string => `${level} ${person}${only ? \" private\" : \"\"}`;\n // The incidents of each person at each level with a limit that have a delivery in the window. An incident counts one\n // time, also with many steps or episodes. A time that is not a number is in no window. Two reports of one merged\n // incident can count two times, thus the limit can hold an escalation early, never late.\n const counted = new Set<string>();\n const used = new Map<string, number>();\n for (const delivery of input.deliveries) {\n if (!isLimitedLevel(delivery.level) || !(delivery.at > input.now - limits.window && delivery.at <= input.now)) continue;\n const group = groupOf(delivery.person, delivery.level, secret.has(delivery.incident));\n const key = `${group} ${delivery.incident}`;\n if (counted.has(key)) continue;\n counted.add(key);\n used.set(group, (used.get(group) ?? 0) + 1);\n }\n\n // The new routes of each person and level.\n const fresh = new Map<string, { readonly index: number; readonly due: Instant; readonly started: boolean }[]>();\n const held = new Map<number, EscalationHold>();\n input.routes.forEach((entry, index) => {\n const level = entry.policy.level;\n if (!isLimitedLevel(level)) return;\n const hold = logged.get(holdKey({ incident: entry.start.incident, level, person: entry.person, episode: entry.episode }));\n if (hold !== undefined) {\n held.set(index, hold);\n return;\n }\n if (entry.deliveries.length > 0 || entry.plan.sends.length === 0) return;\n const group = groupOf(entry.person, level, isPrivate(entry.incident));\n const due = Math.min(...entry.plan.sends.map((send) => send.due));\n const started = input.started !== undefined && entry.plan.sends.some((send) => input.started?.has(messageKey(send)) === true);\n fresh.set(group, [...(fresh.get(group) ?? []), { index, due, started }]);\n });\n const added: { readonly index: number; readonly hold: EscalationHold }[] = [];\n for (const [group, entries] of fresh) {\n const level = group.slice(0, group.indexOf(\" \")) as LimitedLevel;\n const places = Math.max(0, Math.max(1, Math.floor(limits[level] * share)) - (used.get(group) ?? 0));\n // The routes with a started send take their places first. They do not get a hold, also past the limit.\n const begun = entries.filter((item) => item.started).length;\n const ordered = entries\n .filter((item) => !item.started)\n .sort((a, b) => {\n const left = input.routes[a.index]!;\n const right = input.routes[b.index]!;\n return a.due - b.due || compareCodeUnits(left.start.incident, right.start.incident) || left.episode - right.episode;\n });\n for (const { index } of ordered.slice(Math.max(0, places - begun))) {\n const entry = input.routes[index]!;\n const hold: EscalationHold = { incident: entry.start.incident, level, person: entry.person, episode: entry.episode, at: input.now };\n held.set(index, hold);\n added.push({ index, hold });\n }\n }\n if (held.size === 0) return { routes: input.routes, holds: [] };\n return {\n routes: input.routes.map((entry, index) => {\n const hold = held.get(index);\n return hold === undefined ? entry : { ...entry, plan: { ...entry.plan, sends: [] }, held: hold };\n }),\n holds: added.sort((a, b) => a.index - b.index).map(({ hold }) => hold),\n };\n}\n","/**\n * The observe mode of a new source (AL-73). A new source can make a burst of alerts at its start, for example from an\n * area that is too large. Thus a new source starts in the observe mode. Its incidents stay in the merge, the map and the\n * log, but they start no escalation and no digest entry below `life-safety` (`observeCut`).\n *\n * The verdict (`observeVerdict`) replays the last day of a source. For each person, it counts the incidents of the\n * source that reach the person at each level. The source goes live when the observed time is long enough, and no person\n * passes a cap in that day. Thus a source with a burst goes live one day after the burst, when no new burst comes. The caps are the send limit of each person (`send-limit.ts`) times the share of this copy.\n * Thus a split of the copies does not let a new source pass on a double count.\n *\n * The functions are pure folds over the merge state and the time. They read no clock.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { assess, reachedAssessment } from \"./assess.ts\";\nimport type { AssessedLevel, AssessPolicy, Duration, Incident, Instant, MergeState, PersonId, PersonWatch, ReportId, SourceId, WatchedPlace } from \"./contracts.ts\";\nimport { DEFAULT_SEND_LIMITS, LIMITED_LEVELS, type LimitedLevel, type SendLimits } from \"./send-limit.ts\";\n\nconst HOUR = 3_600_000;\n\n/**\n * The shortest observed time of a new source: one day. A day holds the daily cycle of most feeds, for example the peaks\n * of a transit network and the daily products of a forecast office.\n */\nexport const OBSERVE_WINDOW: Duration = 24 * HOUR;\n\n/**\n * The most digest entries of one new source for one person in one day: 20. The digest tells each entry in one message.\n * More entries from one new source fill the digest, and they tell of a wrong map more often than of a real event.\n */\nexport const OBSERVE_DIGEST_PER_DAY = 20;\n\n/** The input of `observeCut`. */\nexport interface ObserveCutInput {\n /** The incidents of the merge state at `at`. */\n readonly incidents: readonly Incident[];\n readonly state: MergeState;\n /** The sources in the observe mode. A source that this copy does not operate is not in the set, thus it counts as live. */\n readonly observing: ReadonlySet<SourceId>;\n /**\n * The reports of the incidents with an escalation start or a hold of the send limit. A send in flight has a start and no\n * delivery. The cut does not hold these incidents, because the phone can have the message.\n */\n readonly started?: ReadonlySet<ReportId>;\n readonly people: readonly PersonWatch[];\n readonly places: readonly WatchedPlace[];\n readonly assess?: AssessPolicy;\n readonly at: Instant;\n}\n\n/** The result of `observeCut`. */\nexport interface ObserveCut {\n /** The incidents that go to the route and to the digest, in their order. */\n readonly sent: readonly Incident[];\n /** The incidents that the observe mode holds. */\n readonly held: readonly Incident[];\n /**\n * The incidents of observing sources only that go on, because they reach a person at `life-safety`. Each one needs a note to\n * the operator. An incident stays in the list after its send, while it reaches a person at `life-safety`.\n */\n readonly lifeSafety: readonly Incident[];\n}\n\n/** This function gives the reports of an incident: its anchor and each other report. */\nconst reportsOf = (incident: Incident): readonly ReportId[] => [incident.anchor, ...incident.reports];\n\n/**\n * This function divides the incidents for the route and the digest. The observe mode holds an incident when each of its\n * reports comes from a source in the observe mode. These incidents go on:\n *\n * - An incident with a report of a live source, of a source that this copy does not operate, or that the state does not have.\n * - An incident that reaches a person at `life-safety`. A missed real warning is worse than a wrong one. The incident goes to\n * the route for each person, and the send limit holds the lower levels. The operator gets a note of it (`lifeSafety`).\n * - An incident with a delivery, an escalation start or a hold, for example a `life-safety` incident that went to a lower\n * level. The route continues or ends its escalation.\n */\nexport function observeCut(input: ObserveCutInput): ObserveCut {\n if (input.observing.size === 0) return { sent: input.incidents, held: [], lifeSafety: [] };\n const sourceOf = new Map(input.state.reports.map((report) => [report.id as string, report.source]));\n const delivered = new Set<string>(input.state.deliveries.map((delivery) => delivery.incident));\n const sent: Incident[] = [];\n const held: Incident[] = [];\n const lifeSafety: Incident[] = [];\n for (const incident of input.incidents) {\n const ids = reportsOf(incident);\n const observed = ids.every((id) => {\n const source = sourceOf.get(id);\n return source !== undefined && input.observing.has(source);\n });\n if (!observed) {\n sent.push(incident);\n continue;\n }\n const levels = incident.live ? input.people.map((person) => levelOf(incident, person, input.places, input.assess, input.at)) : [];\n if (levels.includes(\"life-safety\")) {\n sent.push(incident);\n lifeSafety.push(incident);\n } else if (ids.some((id) => delivered.has(id) || input.started?.has(id) === true)) {\n sent.push(incident);\n } else {\n held.push(incident);\n }\n }\n return { sent, held, lifeSafety };\n}\n\n/** This function gives the level of an incident that reaches a person at a time. */\nfunction levelOf(incident: Incident, person: PersonWatch, places: readonly WatchedPlace[], policy: AssessPolicy | undefined, at: Instant): AssessedLevel {\n return reachedAssessment(assess(incident, person, places, policy, at)).level;\n}\n\n/** One condition of the observe mode, for the system reports. */\nexport interface ObserveCondition {\n readonly source: SourceId;\n /**\n * The state of the condition:\n *\n * - `held`: the source has its full observed time, and its verdict fails. The source stays in the observe mode.\n * - `life-safety`: incidents of observing sources only reached a person at `life-safety`, and they went on.\n */\n readonly state: \"held\" | \"life-safety\";\n /** The start of the observe mode of the source. */\n readonly since: Instant;\n /** The reason of the verdict, or the empty text. */\n readonly reason: string;\n /** The anchors of the incidents at `life-safety`, sorted. A `held` condition has none. */\n readonly incidents: readonly ReportId[];\n}\n\n/**\n * This function gives the conditions of the observe mode, in the order of the sources and then of the states.\n *\n * - Each verdict that does not pass with its full observed time gives a `held` condition.\n * - Each source of an incident in `lifeSafety` (`observeCut`) gives a `life-safety` condition. Thus the operator sees\n * a wrong map in its first hour, and not after one day.\n *\n * @param since - The start of the observe mode of each source.\n */\nexport function observeConditions(verdicts: readonly ObserveVerdict[], lifeSafety: readonly Incident[], state: MergeState, since: ReadonlyMap<SourceId, Instant>): ObserveCondition[] {\n const conditions: ObserveCondition[] = [];\n for (const verdict of verdicts) {\n if (!verdict.pass && verdict.at - verdict.since >= verdict.window) conditions.push({ source: verdict.source, state: \"held\", since: verdict.since, reason: verdict.reason, incidents: [] });\n }\n const sourceOf = new Map(state.reports.map((report) => [report.id as string, report.source]));\n const anchors = new Map<SourceId, Set<ReportId>>();\n for (const incident of lifeSafety) {\n for (const id of reportsOf(incident)) {\n const source = sourceOf.get(id);\n if (source === undefined) continue;\n const set = anchors.get(source) ?? new Set<ReportId>();\n set.add(incident.anchor);\n anchors.set(source, set);\n }\n }\n for (const [source, set] of anchors) {\n conditions.push({ source, state: \"life-safety\", since: since.get(source) ?? Number.NEGATIVE_INFINITY, reason: \"\", incidents: [...set].sort(compareCodeUnits) });\n }\n return conditions.sort((a, b) => compareCodeUnits(a.source, b.source) || compareCodeUnits(a.state, b.state));\n}\n\n/** The input of `observeVerdict`. */\nexport interface ObserveVerdictInput {\n readonly source: SourceId;\n /** The start of the observe mode of the source. */\n readonly since: Instant;\n readonly at: Instant;\n readonly state: MergeState;\n /** The incidents of the merge state at `at`, for example the incidents of the view. */\n readonly incidents: readonly Incident[];\n readonly people: readonly PersonWatch[];\n readonly places: readonly WatchedPlace[];\n readonly assess?: AssessPolicy;\n /** The send limit of each person (`sendLimitsOf` of the configuration). The default is `DEFAULT_SEND_LIMITS`. */\n readonly limits?: SendLimits;\n /** The share of the send limit for this copy (`limitShare`), above 0 and at most 1. The default is 1. */\n readonly share?: number;\n /** The shortest observed time, and the time that the verdict counts. The default is `OBSERVE_WINDOW`. */\n readonly window?: Duration;\n}\n\n/** The counts of one person in the verdict of a source. */\nexport interface ObservedPerson {\n readonly person: PersonId;\n /** The incidents of the source that reach the person at a level. */\n readonly matched: number;\n /** The matched incidents over each incident of the source, from 0 to 1. It is 0 when the source has no incident. */\n readonly share: number;\n /** The most new incidents of each limited level in one window of the send limit. */\n readonly worst: Readonly<Record<LimitedLevel, number>>;\n /** The incidents at `life-safety`. They have no cap. */\n readonly lifeSafety: number;\n /** The most digest entries in one day. */\n readonly digestDay: number;\n /** One text for each cap that the person passes, in plain words with the numbers: \"9 notices in 1 hour, limit 6\". */\n readonly over: readonly string[];\n}\n\n/** The verdict of the observe mode of one source. */\nexport interface ObserveVerdict {\n readonly source: SourceId;\n readonly since: Instant;\n readonly at: Instant;\n /** The observed time in hours, from `since`. */\n readonly hours: number;\n /** The start of the counted time: the start of the last window, or `since` when it is later. */\n readonly from: Instant;\n /** The incidents with a report of the source in the counted time. */\n readonly incidents: number;\n /** The incidents in each hour of the counted time, over one hour at least. */\n readonly perHour: number;\n /** The cap of each limited level in one window: the send limit times the share, and 1 at least. */\n readonly caps: Readonly<Record<LimitedLevel, number>>;\n /** The window of the caps: the window of the send limit. */\n readonly capWindow: Duration;\n /** The shortest observed time of the verdict. */\n readonly window: Duration;\n readonly people: readonly ObservedPerson[];\n /** True when the observed time is long enough and no person passes a cap. */\n readonly pass: boolean;\n /**\n * The reason of the verdict in plain words with the numbers. A person has the number of its place in `people`, and no\n * id: \"person 1: 9 notices in 1 hour, limit 6\".\n */\n readonly reason: string;\n}\n\n/** This function gives a duration in plain words: \"1 hour\", \"2 hours\" or \"30 minutes\". */\nexport function durationText(length: Duration): string {\n const hours = length / HOUR;\n if (Number.isInteger(hours)) return `${String(hours)} ${hours === 1 ? \"hour\" : \"hours\"}`;\n const minutes = Math.round(length / 60_000);\n return `${String(minutes)} ${minutes === 1 ? \"minute\" : \"minutes\"}`;\n}\n\n/** The plain word of the incidents of each limited level. */\nconst LEVEL_WORDS: Readonly<Record<LimitedLevel, readonly [string, string]>> = { notice: [\"notice\", \"notices\"], urgent: [\"urgent alert\", \"urgent alerts\"] };\n\n/** This function gives the most times in one window of a length. The window holds its start and not its end. */\nexport function mostInWindow(times: readonly Instant[], length: Duration): number {\n const sorted = [...times].sort((a, b) => a - b);\n let most = 0;\n let first = 0;\n for (let last = 0; last < sorted.length; last += 1) {\n while (sorted[last]! - sorted[first]! >= length) first += 1;\n most = Math.max(most, last - first + 1);\n }\n return most;\n}\n\n/**\n * This function gives the verdict of the observe mode of a source at `at`. It replays each incident with a report of the\n * source from the counted time. The counted time is the last window before `at`, and it starts at `since` or later.\n *\n * - The time of an incident is the earliest receipt of a report of the source in it. The level of a person is the\n * assessment of the incident at that time.\n * - For each limited level, the most incidents of a person in one window of the send limit is at most the cap of the level.\n * - The most digest entries of a person in one day is at most `OBSERVE_DIGEST_PER_DAY`.\n * - The source passes when the observed time is `window` or more, and no person passes a cap.\n */\nexport function observeVerdict(input: ObserveVerdictInput): ObserveVerdict {\n const limits = input.limits ?? DEFAULT_SEND_LIMITS;\n const share = input.share ?? 1;\n const window = input.window ?? OBSERVE_WINDOW;\n const caps = { notice: Math.max(1, Math.floor(limits.notice * share)), urgent: Math.max(1, Math.floor(limits.urgent * share)) };\n const from = Math.max(input.since, input.at - window);\n const received = new Map<string, Instant>();\n for (const report of input.state.reports) {\n if (report.source === input.source && report.received >= from && report.received <= input.at) received.set(report.id, report.received);\n }\n const timed: { readonly incident: Incident; readonly at: Instant }[] = [];\n for (const incident of input.incidents) {\n const times = reportsOf(incident).flatMap((id) => {\n const at = received.get(id);\n return at === undefined ? [] : [at];\n });\n if (times.length > 0) timed.push({ incident, at: Math.min(...times) });\n }\n const people = input.people.map((person): ObservedPerson => {\n const at: Record<AssessedLevel, Instant[]> = { none: [], digest: [], notice: [], urgent: [], \"life-safety\": [] };\n for (const item of timed) at[levelOf(item.incident, person, input.places, input.assess, item.at)].push(item.at);\n const worst = { notice: mostInWindow(at.notice, limits.window), urgent: mostInWindow(at.urgent, limits.window) };\n const digestDay = mostInWindow(at.digest, 24 * HOUR);\n const over = [\n ...LIMITED_LEVELS.filter((level) => worst[level] > caps[level]).map(\n (level) => `${String(worst[level])} ${LEVEL_WORDS[level][worst[level] === 1 ? 0 : 1]} in ${durationText(limits.window)}, limit ${String(caps[level])}`,\n ),\n ...(digestDay > OBSERVE_DIGEST_PER_DAY ? [`${String(digestDay)} digest entries in 1 day, limit ${String(OBSERVE_DIGEST_PER_DAY)}`] : []),\n ];\n const matched = timed.length - at.none.length;\n return { person: person.person, matched, share: timed.length === 0 ? 0 : matched / timed.length, worst, lifeSafety: at[\"life-safety\"].length, digestDay, over };\n });\n const hours = (input.at - input.since) / HOUR;\n const long = input.at - input.since >= window;\n const counted = (input.at - from) / HOUR;\n const over = people.flatMap((person, index) => person.over.map((text) => `person ${String(index + 1)}: ${text}`));\n const observed = `${hours.toFixed(1)} of ${durationText(window)} observed`;\n const reason = over.length > 0 ? [...over, ...(long ? [] : [observed])].join(\"; \") : long ? `${hours.toFixed(1)} hours observed, no person over a limit` : observed;\n return {\n source: input.source,\n since: input.since,\n at: input.at,\n hours,\n from,\n incidents: timed.length,\n perHour: timed.length / Math.max(counted, 1),\n caps,\n capWindow: limits.window,\n window,\n people,\n pass: long && over.length === 0,\n reason,\n };\n}\n","/**\n * This module holds the rise-only throttle of each person and channel (AL-72 part 4). It is pure. In one window, a\n * channel sends a second message to a person only when the level rises. The new level must be above each level that\n * the channel sent to the person in the window. A send of the same level or of a lower level does not go. The log keeps\n * it as a suppression with its reason, and the digest tells its incident. Each stream has its own window. By default,\n * the system lines (the kinds of the family `system`) are one stream, and the alerts are the other stream. Thus a health\n * notice does not stop a weather notice, and a weather notice does not stop a health notice. Each private incident is\n * its own stream (AL-92). Thus the throttle stops only the repeats of a message of the operator.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { isPrivate, type Audience } from \"./audience.ts\";\nimport { LEVELS, type ChannelId, type Delivery, type Duration, type Instant, type Kind, type Level, type PersonId, type Report, type ReportId } from \"./contracts.ts\";\nimport type { Route } from \"./delivery.ts\";\nimport type { EscalationSend } from \"./escalation.ts\";\nimport { messageKey } from \"./ids.ts\";\nimport { hasKind } from \"./kind-prefix.ts\";\n\n/** The family of the kinds of the system lines: `system.health`, `system.quota` and the other kinds `system.*` of `assess.ts`. */\nconst SYSTEM_KINDS: readonly string[] = [\"system\"];\n\n/** The stream of the system lines. */\nconst SYSTEM_STREAM = \"system\";\n\n/** The first part of the stream of a private incident. Each private incident is its own stream (AL-92). */\nconst PRIVATE_STREAM = \"private\";\n\n/**\n * The key of the window of the throttle.\n *\n * - `channel`: one window for each person and channel. A new incident of the same level does not go.\n * - `incident`: one window for each person, channel and incident. Only the repeats of one incident do not go.\n */\nexport type ThrottleKey = \"channel\" | \"incident\";\n\n/** The keys of the window of the throttle. */\nexport const THROTTLE_KEYS: readonly ThrottleKey[] = [\"channel\", \"incident\"];\n\n/**\n * The streams of the throttle. Each stream has its own window, for each person and channel.\n *\n * - `system`: two streams. The system lines are one stream, and the alerts are the other stream.\n * - `family`: the stream of the system lines, and one stream for each family of the alerts. The family is the first part\n * of the kind, for example `met` of `met.flood`.\n */\nexport type ThrottleStreams = \"system\" | \"family\";\n\n/** The streams of the throttle. */\nexport const THROTTLE_STREAMS: readonly ThrottleStreams[] = [\"system\", \"family\"];\n\n/** The rise-only throttle of each person and channel. */\nexport interface Throttle {\n /** The length of the window. */\n readonly window: Duration;\n /** The key of the window. */\n readonly key: ThrottleKey;\n /** The streams. Each stream has its own window. */\n readonly streams: ThrottleStreams;\n /** The levels that the throttle does not stop. Their sends always go, and they count in the window of the other levels. */\n readonly exempt: readonly Level[];\n}\n\n/** The part of the configuration that changes the throttle. Each field that is absent keeps its default. */\nexport type ThrottleConfig = Partial<Throttle>;\n\n/**\n * The default throttle: a window of 30 minutes for each person, channel and stream. The streams are the system lines and\n * the alerts. A `life-safety` send always goes.\n *\n * The window comes from a replay of the burst of 2026-11-18 (`fixtures/burst-2026-11-18.json`, with made-up ids). The\n * burst gave 171 messages to one person on one channel in 22 minutes, in two waves 9 minutes apart. With a window of 15\n * minutes or more, the replay gives 2 messages: the first notice, and the first urgent message. On 2026-11-16 and\n * 2026-11-17, the shortest time between two messages that did not come at the same time was 32 minutes. A window of 32\n * minutes or less stops none of them. The default is 30 minutes, in this range.\n */\nexport const DEFAULT_THROTTLE: Throttle = { window: 1_800_000, key: \"channel\", streams: \"system\", exempt: [\"life-safety\"] };\n\n/** The shortest window of the throttle: one minute. */\nexport const THROTTLE_MIN_WINDOW: Duration = 60_000;\n\n/** The longest window of the throttle: one day. */\nexport const THROTTLE_MAX_WINDOW: Duration = 86_400_000;\n\n/** The part of a report or an incident that gives its stream of the throttle. */\nexport interface ThrottleItem extends Audience {\n readonly kind: Pick<Kind, \"code\">;\n}\n\n/**\n * This function gives the stream of the throttle for a report or an incident (D16). A private item (AL-92) is its own\n * stream, by its id: the id of a report, or the anchor of an incident. The system lines are one stream. The alerts are\n * the other stream. With the streams `family`, each family of the alerts is a stream.\n */\nexport function throttleStreamOf(item: ThrottleItem, id: string, streams: ThrottleStreams): string {\n if (isPrivate(item)) return `${PRIVATE_STREAM} ${id}`;\n const kind = item.kind.code;\n return hasKind(SYSTEM_KINDS, kind) ? SYSTEM_STREAM : streams === \"family\" ? `alerts ${kind.split(\".\")[0]!}` : \"alerts\";\n}\n\n/** This function gives the throttle of a configuration. Each field that is absent has its default. */\nexport function throttleOf(config: ThrottleConfig | undefined): Throttle {\n return { ...DEFAULT_THROTTLE, ...config };\n}\n\n/** This function gives the problems of the throttle of a configuration. The window is one minute to one day. */\nexport function throttleProblems(config: ThrottleConfig): string[] {\n const problems: string[] = [];\n const { window } = config;\n if (window !== undefined && !(Number.isInteger(window) && window >= THROTTLE_MIN_WINDOW && window <= THROTTLE_MAX_WINDOW)) {\n problems.push(`The window of the throttle is ${String(window)} ms. It must be an integer from ${THROTTLE_MIN_WINDOW} to ${THROTTLE_MAX_WINDOW} ms.`);\n }\n if (config.key !== undefined && !THROTTLE_KEYS.includes(config.key)) problems.push(`The key of the throttle is ${String(config.key)}. It must be one of: ${THROTTLE_KEYS.join(\", \")}.`);\n if (config.streams !== undefined && !THROTTLE_STREAMS.includes(config.streams)) problems.push(`The streams of the throttle are ${String(config.streams)}. They must be one of: ${THROTTLE_STREAMS.join(\", \")}.`);\n for (const level of config.exempt ?? []) {\n if (!LEVELS.includes(level) || level === \"digest\") problems.push(`The throttle cannot exempt the level ${String(level)}. A level with an exemption is notice, urgent or life-safety.`);\n }\n return problems;\n}\n\n/**\n * The reason of a suppression.\n *\n * - `same-level`: the channel already sent a message of the same level and stream to the person in the window.\n * - `lower-level`: the channel already sent a message of a higher level and of the same stream to the person in the window.\n */\nexport type SuppressionReason = \"same-level\" | \"lower-level\";\n\n/** A send that the throttle stopped. The send does not go, and the next digest tells its incident. */\nexport interface Suppression {\n /** The delivery key of the send (`messageKey`). */\n readonly key: string;\n readonly incident: ReportId;\n readonly level: Level;\n readonly person: PersonId;\n readonly channel: ChannelId;\n readonly step: number;\n /** The episode of the escalation. */\n readonly episode: number;\n readonly at: Instant;\n readonly reason: SuppressionReason;\n /** The highest level of the stream that the channel sent to the person in the window, or that it sends in the same pass. */\n readonly over: Level;\n}\n\n/** The input of `throttleRoutes`. */\nexport interface ThrottleInput {\n /** The routes at `now`, after the send limit (`limitRoutes`). */\n readonly routes: readonly Route[];\n /** The deliveries of the ledger: the deliveries of this copy and the deliveries of the other copies. */\n readonly deliveries: readonly Delivery[];\n /** The suppressions of the log. A send with a suppression does not go, also after its window. */\n readonly suppressions: readonly Suppression[];\n /**\n * The reports of the merge state (`MergeState.reports`). They give the stream of a delivery after the end of its route. A\n * retirement removes a report and its deliveries together, thus a delivery in the window always has its report here.\n */\n readonly reports?: readonly Pick<Report, \"id\" | \"kind\" | \"addresses\">[] | undefined;\n /** The throttle. The default is `DEFAULT_THROTTLE`. */\n readonly throttle?: Throttle | undefined;\n /**\n * The delivery keys of the sends that this copy started and that have no end yet: a send in flight, or an open copy.\n * Such a send goes, and its level counts in the window. The default is no key.\n */\n readonly started?: ReadonlySet<string> | undefined;\n readonly now: Instant;\n}\n\n/** The result of `throttleRoutes`. */\nexport interface ThrottleResult {\n /**\n * The routes in the same order. A route has no send that the throttle stopped. A route with a suppression and no\n * delivery has its first suppression (`Route.suppressed`).\n */\n readonly routes: readonly Route[];\n /** The new suppressions at `now`, in the order of their sends. The runtime writes them to its log. */\n readonly suppressions: readonly Suppression[];\n}\n\nconst rankOf = (level: Level): number => LEVELS.indexOf(level);\n\n/**\n * This function applies the throttle to the sends of the routes.\n *\n * - Each send and each delivery has a stream: the system lines, or the alerts (`streams`). A system line has a kind of\n * the family `system`. The routes and the reports give the kind of the incident of a delivery.\n * - A private incident (`addresses`) is its own stream, by its anchor. Thus only its own deliveries count in its bar.\n * - A delivery of an incident with no route and no report is in the stream of the system lines. The copies share the\n * reports of the alerts (the `fetch` events), but not the system lines. Thus such a delivery is a system line of the\n * other copy. An alert delivery of the other copy can come before its report. Then the worst result is one more push.\n * The other choice can stop a weather notice under a system line of the other copy, and only the digest then tells it.\n * - A send of a level with an exemption goes. Thus a `life-safety` alert of a new incident goes, and each step of an\n * escalation of `life-safety` goes until the acknowledgment.\n * - A send with a suppression in the log does not go. The suppression does not end, thus the send does not go late.\n * - A started send (`started`) goes. The phone can already have its message.\n * - Each other send goes only when its level is above the bar of its window. The bar is the highest level of two\n * groups. The first group is the deliveries of the ledger of its stream to the person on the channel in the window. The\n * second group is the sends of its stream that go before it in this pass.\n * With the key `incident`, only the deliveries and the sends of the same incident count. The deliveries of the other\n * copies count, thus the throttle applies over all the copies.\n * - A send at or below the bar gets a suppression at `now`, with its reason.\n * - The sends go in the order of their due times, then of the anchor, the episode, the step and the channel. The\n * started sends come first. The sends of a level with an exemption count in the bar too.\n * - A digest has no throttle, and it does not count in the bar.\n * - A route with a suppression and no delivery gets `suppressed`. Thus such an escalation gives no exhaustion: the\n * person did not get its message.\n */\nexport function throttleRoutes(input: ThrottleInput): ThrottleResult {\n const throttle = input.throttle ?? DEFAULT_THROTTLE;\n const exempt = new Set(throttle.exempt);\n const logged = new Set(input.suppressions.map((suppression) => suppression.key));\n const started = input.started ?? new Set<string>();\n const from = input.now - throttle.window;\n\n interface Item {\n readonly route: number;\n readonly send: EscalationSend;\n readonly key: string;\n readonly started: boolean;\n }\n // The reports of the incident of each route. With the key `incident`, a delivery counts for each route that holds its report.\n const reportsOf = input.routes.map((entry) => new Set<string>([entry.incident.anchor, ...entry.incident.reports]));\n // The stream of each route (D16). A private incident is a message to its persons (AL-92). It is its own stream, by its\n // anchor. Thus the throttle stops only its repeats, and a system line does not stop it. Its intake has its own gates: a\n // check of repeats and a daily cap.\n const routeStreams = input.routes.map((entry) => throttleStreamOf(entry.incident, entry.incident.anchor, throttle.streams));\n // The stream of each known report. A delivery of an unknown report is a system line of the other copy. A delivery holds\n // the anchor of its incident at its send, thus after the end of the route a private report by its own id gives the\n // stream. A later report with a smaller id changes the anchor, and then a new route has another stream. Two private\n // reports in one incident are rare, thus the worst result is one more push.\n const reportStreams = new Map<string, string>();\n for (const report of input.reports ?? []) reportStreams.set(report.id, throttleStreamOf(report, report.id, throttle.streams));\n reportsOf.forEach((reports, route) => {\n for (const report of reports) reportStreams.set(report, routeStreams[route]!);\n });\n\n const items: Item[] = [];\n const dropped = new Set<string>();\n input.routes.forEach((entry, route) => {\n for (const send of entry.plan.sends) {\n if (send.level === \"digest\") continue;\n const key = messageKey(send);\n if (logged.has(key) && !started.has(key)) {\n dropped.add(key);\n continue;\n }\n items.push({ route, send, key, started: started.has(key) });\n }\n });\n items.sort((a, b) => {\n const left = input.routes[a.route]!;\n const right = input.routes[b.route]!;\n return (\n Number(b.started) - Number(a.started) ||\n a.send.due - b.send.due ||\n compareCodeUnits(left.incident.anchor, right.incident.anchor) ||\n left.episode - right.episode ||\n a.send.step - b.send.step ||\n compareCodeUnits(a.send.channel, b.send.channel)\n );\n });\n\n // The window of a send: its person, channel and stream, and with the key `incident` the anchor of the incident of its route.\n const groupOf = (person: PersonId, channel: ChannelId, route: number): string =>\n throttle.key === \"incident\" ? `${person} ${channel} ${routeStreams[route]!} ${input.routes[route]!.incident.anchor}` : `${person} ${channel} ${routeStreams[route]!}`;\n // The bar of each window: the highest level of the deliveries in the window, then of the sends of this pass.\n const bars = new Map<string, number>();\n const raise = (group: string, level: Level): void => {\n bars.set(group, Math.max(bars.get(group) ?? -1, rankOf(level)));\n };\n for (const delivery of input.deliveries) {\n if (delivery.level === \"digest\" || !(delivery.at > from && delivery.at <= input.now)) continue;\n if (throttle.key === \"channel\") raise(`${delivery.person} ${delivery.channel} ${reportStreams.get(delivery.incident) ?? SYSTEM_STREAM}`, delivery.level);\n else reportsOf.forEach((reports, route) => {\n if (reports.has(delivery.incident)) raise(groupOf(delivery.person, delivery.channel, route), delivery.level);\n });\n }\n\n const added: Suppression[] = [];\n for (const item of items) {\n const { send } = item;\n const group = groupOf(send.person, send.channel, item.route);\n const bar = bars.get(group) ?? -1;\n if (item.started || exempt.has(send.level) || rankOf(send.level) > bar) {\n raise(group, send.level);\n continue;\n }\n dropped.add(item.key);\n const over = LEVELS[bar]!;\n added.push({\n key: item.key,\n incident: send.incident,\n level: send.level,\n person: send.person,\n channel: send.channel,\n step: send.step,\n episode: send.episode ?? 0,\n at: input.now,\n reason: over === send.level ? \"same-level\" : \"lower-level\",\n over,\n });\n }\n // The suppressions of each report. A route with no delivery gets the first suppression of its person, episode and level.\n const byReport = new Map<string, Suppression[]>();\n for (const suppression of [...input.suppressions, ...added]) {\n const list = byReport.get(suppression.incident);\n if (list === undefined) byReport.set(suppression.incident, [suppression]);\n else list.push(suppression);\n }\n const suppressedOf = (entry: Route, route: number): Suppression | undefined => {\n if (entry.deliveries.length > 0 || byReport.size === 0) return undefined;\n for (const report of reportsOf[route]!) {\n const found = byReport.get(report)?.find((suppression) => suppression.person === entry.person && suppression.episode === entry.episode && suppression.level === entry.policy.level);\n if (found !== undefined) return found;\n }\n return undefined;\n };\n if (dropped.size === 0 && byReport.size === 0) return { routes: input.routes, suppressions: [] };\n return {\n routes: input.routes.map((entry, route) => {\n const sends = entry.plan.sends.filter((send) => !dropped.has(messageKey(send)));\n const suppressed = suppressedOf(entry, route);\n if (sends.length === entry.plan.sends.length && suppressed === undefined) return entry;\n return { ...entry, ...(suppressed === undefined ? {} : { suppressed }), plan: { ...entry.plan, sends } };\n }),\n suppressions: added,\n };\n}\n","// The defaults of an interest graph: a layer for each origin, joined with the rows of the person (AL-35,\n// `docs/RELEVANCE.md`, the section \"The defaults\").\n\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { ChannelDescriptor, EdgeOrigin, Estimate, InterestEdge, InterestGraph, NodeKey, PersonId, PlaceId } from \"./contracts.ts\";\nimport { TAXONOMY } from \"./taxonomy.ts\";\nimport { kindOfNode, placeNode } from \"./why.ts\";\n\n/**\n * The rank of each origin, the strongest first. At one pair of nodes, the graph holds the edges of the strongest\n * origin. Each other edge at that pair stays as a row.\n *\n * The choice of the person comes first. A measure of the system comes before public data. A service that the person names comes before a service of a channel of the person. Both\n * come before a default of a kind of work. The watched places come before the human base.\n */\nexport const ORIGIN_RANK: readonly EdgeOrigin[] = [\"person\", \"measured\", \"data\", \"services\", \"delivery\", \"work\", \"places\", \"base\"];\n\n/**\n * The weight of an edge with an unknown chance: the full interval, with the mean of a uniform chance as its value. An\n * unknown part is exposure, not nothing. A calibration from the event log can give a narrower interval later.\n */\nexport const UNKNOWN_WEIGHT: Estimate = { value: 0.5, low: 0, high: 1 };\n\nconst CERTAIN: Estimate = { value: 1, low: 1, high: 1 };\n\n/** The topics of one kind of work. Each topic is a code of `TAXONOMY`. */\nexport interface WorkDefaults {\n readonly label: string;\n readonly topics: readonly string[];\n}\n\n/** The day of the table `WORK_DEFAULTS`. Each row of the layer `work` shows it. */\nexport const WORK_DEFAULTS_DATE = \"2026-11-17\";\n\n/**\n * The topics of each kind of work. A topic edge reaches the person from each place on the Earth. Thus the table names\n * only the topics that touch the work wherever they occur. The places of the person cover the local events.\n */\nexport const WORK_DEFAULTS: Readonly<Record<string, WorkDefaults>> = {\n software: {\n label: \"Software\",\n topics: [\"infra.cloud\", \"infra.saas\", \"infra.internet.dns-cdn\", \"infra.internet.bgp\", \"cyber.vulnerability.exploited\"],\n },\n finance: {\n label: \"Finance\",\n topics: [\"market.exchange\", \"market.halt.marketwide\", \"market.bank.failure\", \"market.broker.outage\", \"infra.payments\"],\n },\n};\n\n/** One row of the graph of a person: an edge and, for a replaced default, the edge that replaced it. */\nexport interface InterestRow {\n readonly edge: InterestEdge;\n /** The id of the edge that replaced this edge: an edge of a stronger origin at the same pair. It is absent when the graph holds this edge. */\n readonly replacedBy?: string;\n}\n\n/** The graph of a person from the layers, and a row for each edge of the layers and of the person. */\nexport interface ComposedInterests {\n readonly graph: InterestGraph;\n readonly rows: readonly InterestRow[];\n}\n\n/** This function gives the id of a default edge from its origin and its pair. Thus a default has the same id at each build. */\nexport function defaultEdgeId(origin: EdgeOrigin, from: NodeKey, to: NodeKey): string {\n return `${origin}/${from}>${to}`;\n}\n\nfunction interestEdge(origin: EdgeOrigin, from: NodeKey, weight: Estimate, extra: { readonly source?: string; readonly date?: string } = {}): InterestEdge {\n return { id: defaultEdgeId(origin, from, \"person\"), from, to: \"person\", kind: \"interest\", weight, origin, ...extra, on: true };\n}\n\n/**\n * This function gives the layer `places`: one edge from each watched place to the person, with the weight 1. A graph\n * with only this layer gives the routing of the first releases. This is the compatibility gate of `docs/RELEVANCE.md`.\n */\nexport function placesLayer(places: readonly PlaceId[]): readonly InterestEdge[] {\n return [...new Set(places)].sort(compareCodeUnits).map((place) => interestEdge(\"places\", placeNode(place), CERTAIN));\n}\n\n/**\n * This function gives the layer `work`: one edge from each topic of each kind of work to the person. The table gives\n * the topics, not the chances, so each edge has `UNKNOWN_WEIGHT`. The source of an edge names each work that gives\n * the topic. The function throws a `RangeError` for a work that the table does not have, and for a topic that is not\n * a code of `TAXONOMY`.\n */\nexport function workLayer(works: readonly string[], table: Readonly<Record<string, WorkDefaults>> = WORK_DEFAULTS, date: string = WORK_DEFAULTS_DATE): readonly InterestEdge[] {\n const byTopic = new Map<string, string[]>();\n for (const work of [...new Set(works)].sort(compareCodeUnits)) {\n if (!Object.hasOwn(table, work)) throw new RangeError(`The table of the kinds of work does not have the work \"${work}\".`);\n for (const topic of table[work]!.topics) {\n if (!Object.hasOwn(TAXONOMY, topic)) throw new RangeError(`The topic \"${topic}\" of the work \"${work}\" is not a code of the taxonomy.`);\n byTopic.set(topic, [...(byTopic.get(topic) ?? []), work]);\n }\n }\n return [...byTopic]\n .sort(([a], [b]) => compareCodeUnits(a, b))\n .map(([topic, from]) => interestEdge(\"work\", `topic:${topic}`, UNKNOWN_WEIGHT, { source: `work:${from.join(\",\")}`, date }));\n}\n\n/**\n * This function gives the layer `services`: one edge from each service that the person names to the person. The\n * chance is unknown, so each edge has `UNKNOWN_WEIGHT`. The function throws a `RangeError` for a key that is not an\n * entity, for example a place or a topic.\n */\nexport function servicesLayer(services: readonly NodeKey[]): readonly InterestEdge[] {\n return [...new Set(services)].sort(compareCodeUnits).map((service) => {\n if (kindOfNode(service) !== \"entity\") throw new RangeError(`The service \"${service}\" is not the key of an entity, for example domain:example.com.`);\n return interestEdge(\"services\", service, UNKNOWN_WEIGHT);\n });\n}\n\n/**\n * This function gives the layer `delivery`: one edge from each service of the given channels to the person. Give the\n * channels where the person has a contact (`contactChannels`). Then the alerts of the person go through each such\n * service, so each edge has the weight 1, as a watched place has. The source of an edge names its channels, for\n * example `channel:twilio-call,twilio-text`. The function throws a `RangeError` for a service that is not the key of\n * an entity.\n */\nexport function deliveryLayer(channels: readonly ChannelDescriptor[]): readonly InterestEdge[] {\n const byService = new Map<NodeKey, string[]>();\n for (const channel of channels) {\n for (const service of new Set(channel.services ?? [])) {\n if (kindOfNode(service) !== \"entity\") throw new RangeError(`The service \"${service}\" of the channel ${channel.id} is not the key of an entity, for example domain:example.com.`);\n byService.set(service, [...(byService.get(service) ?? []), channel.id]);\n }\n }\n return [...byService]\n .sort(([a], [b]) => compareCodeUnits(a, b))\n .map(([service, ids]) => interestEdge(\"delivery\", service, CERTAIN, { source: `channel:${[...new Set(ids)].sort(compareCodeUnits).join(\",\")}` }));\n}\n\nconst rankOf = (edge: InterestEdge): number => ORIGIN_RANK.indexOf(edge.origin);\n\nfunction sameEdge(a: InterestEdge, b: InterestEdge): boolean {\n return (\n a.id === b.id &&\n a.from === b.from &&\n a.to === b.to &&\n a.kind === b.kind &&\n a.origin === b.origin &&\n a.on === b.on &&\n a.source === b.source &&\n a.date === b.date &&\n a.weight.value === b.weight.value &&\n a.weight.low === b.weight.low &&\n a.weight.high === b.weight.high\n );\n}\n\n/**\n * This function joins the default layers and the graph of the person into one graph, and gives a row for each edge.\n *\n * At each pair of nodes, the graph holds the edges of the strongest origin of `ORIGIN_RANK`. Each weaker edge at\n * that pair stays as a row, with the id of the edge that replaced it. Thus a person turns a default off with an edge\n * of the origin `person` that is off, and the row of the default stays visible. Two edges of one origin at one pair\n * are two routes. The mutes and the labels come from the graph of the person.\n *\n * An edge that is in a layer and in the graph of the person counts once. Thus a second join of a joined graph gives\n * the same result. The order of the layers and of their edges has no effect.\n *\n * The function throws a `RangeError` for a layer edge of the origin `person`. It also throws a `RangeError` for two\n * different edges with one id, and for a graph of another person.\n */\nexport function composeInterests(person: PersonId, layers: readonly (readonly InterestEdge[])[], own?: InterestGraph): ComposedInterests {\n if (own !== undefined && own.person !== person) throw new RangeError(`The graph of the person \"${own.person}\" is not the graph of \"${person}\".`);\n const byId = new Map<string, InterestEdge>();\n const add = (edge: InterestEdge): void => {\n const known = byId.get(edge.id);\n if (known === undefined) byId.set(edge.id, edge);\n else if (!sameEdge(known, edge)) throw new RangeError(`Two different edges have the id \"${edge.id}\".`);\n };\n for (const layer of layers) {\n for (const edge of layer) {\n if (edge.origin === \"person\") throw new RangeError(`The default edge \"${edge.id}\" has the origin person. Only the graph of the person holds such an edge.`);\n add(edge);\n }\n }\n for (const edge of own?.edges ?? []) add(edge);\n\n const pairs = new Map<string, InterestEdge[]>();\n for (const edge of byId.values()) {\n const key = `${edge.from}\\n${edge.to}`;\n pairs.set(key, [...(pairs.get(key) ?? []), edge]);\n }\n const used: InterestEdge[] = [];\n const rows: InterestRow[] = [];\n for (const [, edges] of [...pairs].sort(([a], [b]) => compareCodeUnits(a, b))) {\n const ordered = [...edges].sort((a, b) => rankOf(a) - rankOf(b) || compareCodeUnits(a.id, b.id));\n const winner = ordered[0]!;\n for (const edge of ordered) {\n if (rankOf(edge) === rankOf(winner)) {\n used.push(edge);\n rows.push({ edge });\n } else rows.push({ edge, replacedBy: winner.id });\n }\n }\n const graph: InterestGraph = {\n format: \"alerts-interest/1\",\n person,\n edges: used.sort((a, b) => compareCodeUnits(a.id, b.id)),\n mutes: own?.mutes ?? [],\n ...(own?.labels === undefined ? {} : { labels: own.labels }),\n };\n return { graph, rows };\n}\n","/**\n * The opt-in list of the alert texts (AL-56). A channel of texts sends only to a number with a record of the list. A STOP\n * reply removes the number, and a START reply puts it back.\n *\n * - The list holds phone numbers. Thus it is in the private configuration, and not in the repository.\n * - The number of a record is a phone number or the name of a secret, as the address of a contact.\n * - The opt-in page of the site gives the consent words of each version, and the form of a record.\n * - A problem of the list names the index of a record, and no number.\n */\n\nimport type { AddressValue, SecretLookup } from \"./config.ts\";\nimport type { AddressField, ChannelDescriptor, Instant } from \"./contracts.ts\";\n\n/** The versions of the consent words. The opt-in page of the site gives the words of each version. */\nexport const OPT_IN_WORDS: readonly string[] = [\"texts-consent/1\"];\n\n/** The ways of a yes: in writing, or in speech. */\nexport const OPT_IN_WAYS = [\"written\", \"spoken\"] as const;\n\n/** The way of a yes. */\nexport type OptInWay = (typeof OPT_IN_WAYS)[number];\n\n/** One yes of a person to the alert texts at one phone number: one record of the private opt-in list. */\nexport interface OptInRecord {\n /** The mobile phone number, in E.164 form. */\n readonly number: string;\n /** The date and the time of the yes in UTC, as an ISO 8601 text with seconds: for example `2026-11-17T21:30:00Z`. */\n readonly at: string;\n /** `written` for a yes in writing, or `spoken` for a yes in speech. */\n readonly way: OptInWay;\n /** The version of the consent words that the person agreed to: one of `OPT_IN_WORDS`. */\n readonly words: string;\n}\n\n/** One record of the opt-in list in the configuration. The number is a phone number, or the name of a secret that holds it. */\nexport interface OptInConfig {\n /** The mobile phone number in E.164 form, or a reference to the secret that holds it. */\n readonly number: AddressValue;\n /** The date and the time of the yes in UTC, as an ISO 8601 text with seconds: for example `2026-11-17T21:30:00Z`. */\n readonly at: string;\n /** `written` for a yes in writing, or `spoken` for a yes in speech. */\n readonly way: OptInWay;\n /** The version of the consent words that the person agreed to: one of `OPT_IN_WORDS`. */\n readonly words: string;\n}\n\n/** The opt-in list with the value of each secret, and the problems of the list. */\nexport interface ResolvedOptIn {\n /** The records with a value for each number, in the order of the list. A record whose secret has no value is not in it. */\n readonly records: readonly OptInRecord[];\n /** The problems of the list. Each problem names the index of a record and the names of secrets, and no number. */\n readonly problems: readonly string[];\n}\n\n/**\n * This function gives the value of the number of each record of the opt-in list, from the secret store. Then it\n * checks the list with `optInProblems`.\n */\nexport function resolveOptIn(list: readonly OptInConfig[], secret: SecretLookup): ResolvedOptIn {\n const problems: string[] = [];\n const resolved = list.map((entry, index): OptInRecord | undefined => {\n if (typeof entry.number === \"string\") return { ...entry, number: entry.number };\n const found = secret(entry.number.secret);\n if (found !== undefined && found !== \"\") return { ...entry, number: found };\n problems.push(`Record ${String(index + 1)} of the opt-in list names the secret ${entry.number.secret}, and the secret store has no value for it.`);\n return undefined;\n });\n problems.push(...optInProblems(resolved));\n return { records: resolved.filter((record) => record !== undefined), problems };\n}\n\n/** One reply that changes the opt-in of a number. `stop` removes the number, and `start` puts it back. */\nexport interface OptInChange {\n readonly number: string;\n readonly kind: \"stop\" | \"start\";\n readonly at: Instant;\n}\n\n/** The E.164 form of a phone number: a plus sign and 8 to 15 digits. The first digit is not 0. */\nconst E164 = /^\\+[1-9]\\d{7,14}$/u;\n\n/** The form of a time of a record: a date, a time with seconds, and `Z`. */\nconst UTC_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$/u;\n\n/**\n * This function gives the time of a record in milliseconds since the epoch. It gives `undefined` when the text is not a\n * UTC time with seconds, or when it names a day that does not exist, as `2026-02-30`.\n */\nexport function optInTime(record: Pick<OptInRecord, \"at\">): Instant | undefined {\n if (!UTC_TIME.test(record.at)) return undefined;\n const time = Date.parse(record.at);\n if (!Number.isFinite(time)) return undefined;\n // `Date.parse` moves a day that does not exist to the next month. The text of the time then differs.\n return new Date(time).toISOString() === record.at.replace(\"Z\", \".000Z\") ? time : undefined;\n}\n\n/**\n * This function gives the problems of an opt-in list. A problem is a number that is not in E.164 form, or a time that\n * is not in UTC. It is also consent words of an unknown version, or two records of one number. A problem names the index\n * of a record, and no number.\n * The function does not examine an `undefined` entry: the record of a secret with no value.\n */\nexport function optInProblems(records: readonly (OptInRecord | undefined)[]): string[] {\n const problems: string[] = [];\n const first = new Map<string, number>();\n records.forEach((record, index) => {\n if (record === undefined) return;\n const position = index + 1;\n if (!E164.test(record.number)) problems.push(`Record ${position} of the opt-in list has no phone number in E.164 form.`);\n if (optInTime(record) === undefined) problems.push(`Record ${position} of the opt-in list has no time in UTC with seconds, as 2026-11-17T21:30:00Z.`);\n if (!OPT_IN_WORDS.includes(record.words)) problems.push(`Record ${position} of the opt-in list names consent words of an unknown version.`);\n const before = first.get(record.number);\n if (before === undefined) first.set(record.number, position);\n else problems.push(`Records ${before} and ${position} of the opt-in list have the same number.`);\n });\n return problems;\n}\n\n/**\n * This function tells if a number has the opt-in at the time `at`. It is a fold of the record of the number and the changes.\n *\n * - A number with no record, or with a record after `at`, has no opt-in. A START reply does not add a number.\n * - Each change of the number from the time of its record to `at` counts. The last change decides.\n * - A STOP and a START at the same time give STOP. The order of the changes in the list does not matter.\n * - A new yes after a STOP is a record with a later time. Then the STOP before it does not count.\n */\nexport function optedIn(records: readonly OptInRecord[], changes: readonly OptInChange[], number: string, at: Instant): boolean {\n const record = records.find((entry) => entry.number === number);\n const since = record === undefined ? undefined : optInTime(record);\n if (since === undefined || since > at) return false;\n let last: OptInChange | undefined;\n for (const change of changes) {\n if (change.number !== number || change.at < since || change.at > at) continue;\n if (last === undefined || change.at > last.at || (change.at === last.at && change.kind === \"stop\")) last = change;\n }\n return last?.kind !== \"stop\";\n}\n\n/** This function gives the fields of the address of a channel whose values need a record of the opt-in list. */\nexport function optInFields(channel: Pick<ChannelDescriptor, \"address\">): readonly AddressField[] {\n return (channel.address ?? []).filter((field) => field.optIn === true);\n}\n","/**\n * This module holds the private configuration of the people and the places. It has the format of\n * the owner, and the load that checks it and makes the recipients. The repository holds no\n * configuration. The functions are pure, and the caller gives the secrets.\n */\nimport { localTime } from \"@mark1russell7/algebra/clock\";\nimport { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { canonicalHash } from \"@mark1russell7/rigor-generators\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { Address, AssessPolicy, ChannelDescriptor, ChannelId, ContactServices, Duration, EscalationPolicy, Instant, InterestGraph, NodeKey, PersonId, PersonWatch, PlaceId, Position, RegionCode, SourceId, WatchedPlace } from \"./contracts.ts\";\nimport { assess, CHANNEL_KIND, DEFAULT_ASSESS_POLICY, DRILL_KIND, matchSubjects, reachedAssessment } from \"./assess.ts\";\nimport type { ChannelDownConfig } from \"./channel-down.ts\";\nimport { policyFor, recipientProblems, ruleSteps, type ChannelRule, type Recipient } from \"./delivery.ts\";\nimport { DRILL_PROBES, drillProblems, nextDrillAt, type DrillConfig } from \"./drill.ts\";\nimport { composeInterests, deliveryLayer, placesLayer, servicesLayer, workLayer, type InterestRow } from \"./interest-defaults.ts\";\nimport { incidents, normalize } from \"./merge.ts\";\nimport { optInFields, resolveOptIn, type OptInConfig, type OptInRecord } from \"./opt-in.ts\";\nimport { CHANNEL_SUBJECT, DRILL_SUBJECT, NO_SYSTEM_LINES, systemReports, type SourceClearConfig } from \"./system-reports.ts\";\nimport type { TryChain } from \"./chain.ts\";\nimport type { Expectation } from \"./lateness.ts\";\nimport { rankDelayProblems, rankFloorProblems, type RankDelays } from \"./escalation.ts\";\nimport { sendLimitProblems, type SendLimitConfig } from \"./send-limit.ts\";\nimport { throttleProblems, type ThrottleConfig } from \"./throttle.ts\";\nimport type { LinkPolicy } from \"./link.ts\";\nimport { kindOfNode, placeNode, placeOfNode, type WhyLabels } from \"./why.ts\";\n\n/** The name of the format of a configuration. A change that breaks a configuration gets a new name. */\nexport const CONFIG_FORMAT = \"alerts-config/1\";\n\n/** A reference to a secret: the name of a key in the secret store of the instance. */\nexport interface SecretRef {\n /** The name of the key, for example `PUSHOVER_USER_KEY`. */\n readonly secret: string;\n}\n\n/** A value of an address: the value itself, or a reference to a secret. */\nexport type AddressValue = string | SecretRef;\n\n/** A place of the configuration. The label and the position stay on the machine of the instance. */\nexport interface PlaceConfig {\n readonly id: PlaceId;\n /** The name of the place for its people, for example `Home`. No source gets it. */\n readonly label: string;\n /** The position of the place. Only the sources of `sharePosition` get it. */\n readonly at?: Position;\n /** The codes of the regions that contain the place. The core matches an incident to a place by these codes. */\n readonly codes: readonly RegionCode[];\n /** The distance around the place that the system also watches. */\n readonly bufferKm: number;\n /** The sources that get the position of the place. When it is absent, no source gets it. */\n readonly sharePosition?: readonly SourceId[];\n}\n\n/**\n * The inputs of the default layers of the interest graph of a person (`interest-defaults.ts`). The load joins the\n * layers with the graph of the person in `PersonWatch.interests`.\n */\nexport interface InterestDefaultsConfig {\n /** The kinds of work of the person. Each one is a key of `WORK_DEFAULTS`, for example `software`. */\n readonly works?: readonly string[];\n /** The services that the person uses. Each one is the node key of an entity, for example `domain:example.com`. */\n readonly services?: readonly NodeKey[];\n /**\n * The switch of the layer `delivery`: the services of the channels of the contacts of the person\n * (`ChannelDescriptor.services`). The layer is on when the field is absent. The value `false` turns it off.\n */\n readonly delivery?: boolean;\n}\n\n/** A person of the configuration. */\nexport interface PersonConfig {\n /** The places, the subjects, the rules and the quiet window of the person. */\n readonly watch: PersonWatch;\n /**\n * The inputs of the default layers of the interest graph. When it is present, the recipient gets the join of the\n * layer `places`, the other layers and the graph of the person. When it is absent, the watch stays as it is.\n */\n readonly defaults?: InterestDefaultsConfig;\n /** The name of the person for the UI. */\n readonly label?: string;\n /**\n * The escalation policies of the person. When it is absent, the policies of the configuration apply. A person with\n * policies of their own gets no policy of the configuration, also no policy with a subject.\n */\n readonly policies?: readonly EscalationPolicy[];\n}\n\n/** The address of one person on one channel. */\nexport interface ContactConfig {\n readonly person: PersonId;\n readonly channel: ChannelId;\n /** The fields of the address that the channel reads, for example `user` for Pushover. */\n readonly address: Readonly<Record<string, AddressValue>>;\n}\n\n/**\n * The money rules of one paid provider account: the cap of the spend of its channels, and the floor of its balance.\n * The values are private. Only the configuration holds them.\n */\nexport interface SpendConfig {\n /** The provider, as an id in the `dependsOn` of its channels: for example `provider:twilio`. */\n readonly provider: string;\n /** The most that the channels of the account spend in one calendar month, in US dollars. */\n readonly monthlyUsd: number;\n /**\n * The fixed costs of the account in each month, for example the rent of each phone number. The sends of a month get\n * the monthly cap less these costs (`sendCapUsd`). The default is no fixed cost. Then the whole cap is for the sends,\n * and the rent is outside the cap. Give fixed costs only for a cap of the whole bill.\n */\n readonly fixed?: readonly FixedCost[];\n /** The last part of the cap of the sends that only `life-safety` messages use, in US dollars. The default is 0. */\n readonly reserveUsd?: number;\n /**\n * The floor of the balance of the account, in the currency of the account: one floor or a list of floors. Below each\n * floor, the system reports one line `low`. Thus the list `[10, 3]` gives one alert at 10 and one more alert at 3.\n */\n readonly floor: number | readonly number[];\n /** The time zone of the start of the month, as an IANA name: for example `America/New_York`. */\n readonly timeZone: string;\n}\n\n/** One fixed cost of a provider account in each month, for example the rent of one phone number. */\nexport interface FixedCost {\n /** The name of the cost, for example `toll-free number`. */\n readonly what: string;\n /** The cost in each month, in US dollars. */\n readonly usd: number;\n}\n\n/**\n * This function gives the part of the monthly cap of a spend entry that the sends get, in US dollars. That part is the\n * cap less the fixed costs. The value is 0 or less when the fixed costs use all of the cap.\n */\nexport function sendCapUsd(spend: Pick<SpendConfig, \"monthlyUsd\" | \"fixed\">): number {\n return spend.monthlyUsd - (spend.fixed ?? []).reduce((sum, cost) => sum + cost.usd, 0);\n}\n\n/**\n * This function gives the floors of the balance of a spend entry, from the highest to the lowest, each one time. One\n * floor gives a list of one floor.\n */\nexport function balanceFloors(floor: SpendConfig[\"floor\"]): number[] {\n return [...new Set(typeof floor === \"number\" ? [floor] : floor)].sort((a, b) => b - a);\n}\n\n/** One person of the outage call, with the chain of the tries of the person. */\nexport interface OutagePersonConfig {\n readonly person: PersonId;\n /** The channel of each try, in order. The address of a try is the contact of the person on its channel. */\n readonly chain: TryChain;\n}\n\n/**\n * The outage call: the calls to people when the outside check finds the instance down. The provider of\n * the calls makes them, so they work while the instance is down. A deploy copies the list to the provider.\n */\nexport interface OutageConfig {\n /** The people of the outage call, in the order of the first calls. */\n readonly people: readonly OutagePersonConfig[];\n}\n\n/**\n * The two forms of the links of a local site (AL-92). A link on the loopback address does not open on a phone. Thus the\n * intake changes the origin `local` of a link to the origin `phone`, and it keeps the path, the query and the fragment.\n */\nexport interface TellSite {\n /** The origin of the site on the loopback address: `http` or `https`, the host `127.0.0.1`, `localhost` or `[::1]`, and a port. */\n readonly local: string;\n /** The origin of the same site that a phone opens: `https` and a host of two labels or more, with no path. */\n readonly phone: string;\n}\n\n/**\n * The intake of the messages of the operator (AL-92). The runtime takes each message on a port of the loopback address,\n * with the token of the file `tell.token` in its home. Without this entry, the runtime has no intake.\n */\nexport interface TellConfig {\n /** The port of the intake on the loopback address. */\n readonly port: number;\n /** The most messages that the intake takes in one day. Without it, the cap is `DEFAULT_TELL_DAILY_CAP`. */\n readonly dailyCap?: number;\n /**\n * The local site of the links. The intake changes a link of this site, or a path that starts with `/`, to its phone form.\n * It refuses each other link on the loopback address. Without this entry, it refuses each such link and each path.\n */\n readonly site?: TellSite;\n}\n\n/** The daily cap of the intake of the messages of the operator when the configuration gives none. */\nexport const DEFAULT_TELL_DAILY_CAP = 20;\n\n/** The private configuration of the people and the places. Each copy of the system loads the same configuration. */\nexport interface AlertConfig {\n readonly format: typeof CONFIG_FORMAT;\n readonly places: readonly PlaceConfig[];\n readonly people: readonly PersonConfig[];\n readonly contacts: readonly ContactConfig[];\n /** The escalation policies of each person with no policies of their own. */\n readonly policies: readonly EscalationPolicy[];\n /**\n * The contact of the operator of the instance: an `https` URL or a `mailto` URL. Each request to the\n * server of another party gives it in the User-Agent. Without it, the User-Agent has no contact.\n */\n readonly contact?: string;\n /** The settings of the expectations of the instance. Each entry names an expectation by its id. */\n readonly expectations?: readonly ExpectationConfig[];\n /** The money rules of each paid provider account. A provider with no entry has no cap and no watch of its balance. */\n readonly spend?: readonly SpendConfig[];\n /** The policy of the link rule of the merge. Without it, the instance uses `DEFAULT_LINK_POLICY`. */\n readonly link?: LinkPolicy;\n /** The outage call. Without it, an outage of the instance calls no person. */\n readonly outage?: OutageConfig;\n /**\n * The wait of one rank of a copy, for each level. A level with no entry takes the default of the runtime. Each copy\n * loads the same table. With 0 for `life-safety`, each copy sends each life-safety step at once.\n * Two copies with different tables are safe. The copy of rank 0 sends at once in each case. A copy with no\n * entry for a level waits the default.\n */\n readonly rankDelay?: RankDelays;\n /**\n * The least wait of one rank before a step of an exclusive channel, as a call. Without it, the runtime gives its\n * default. A phone takes one call at a time. Thus a copy with rank 1 waits for the call of rank 0 in its ledger.\n */\n readonly rankFloor?: Duration;\n /**\n * The policy of the assessment: the statuses, the tables of the levels and the relevance policy. When it is absent,\n * the default policy of the core applies. A policy here replaces the full default policy.\n */\n readonly assess?: AssessPolicy;\n /** The drills of the live paths. Without them, the instance starts no drill. */\n readonly drills?: readonly DrillConfig[];\n /**\n * The private opt-in list of the texts. A channel with an address field of `optIn` sends only to a phone on this\n * list, and a STOP reply removes the number. The list holds phone numbers: keep it out of each public text.\n */\n readonly optIn?: readonly OptInConfig[];\n /**\n * The policy of a down channel (AL-65): the run of failed calls that opens its line. Without it, 3 failed calls in at\n * least 60 s open a line (`DEFAULT_CHANNEL_DOWN`).\n */\n readonly channelDown?: ChannelDownConfig;\n /**\n * The policy of the end of the line of a down source (AL-75): the time that a source stays up before its line ends.\n * Without it, the time is 15 minutes or 3 intervals of the source, the longer (`DEFAULT_SOURCE_CLEAR`).\n */\n readonly sourceClear?: SourceClearConfig;\n /**\n * The send limit of each person (AL-72): the most new escalations of each level below `life-safety` in one window,\n * over all the copies. Each field that is absent keeps its default (`DEFAULT_SEND_LIMITS`).\n */\n readonly sendLimit?: SendLimitConfig;\n /**\n * The rise-only throttle of each person, channel and stream (AL-72 part 4). In one window, a channel sends again to a\n * person only for a higher level of the stream. Each field that is absent keeps its default (`DEFAULT_THROTTLE`).\n */\n readonly throttle?: ThrottleConfig;\n /** The intake of the messages of the operator (AL-92). Without it, the runtime takes no message of the operator. */\n readonly tell?: TellConfig;\n}\n\n/** The name of the format of a part of the configuration. A change that breaks a part gets a new name. */\nexport const CONFIG_PART_FORMAT = \"alerts-config-part/1\";\n\n/**\n * A part of the configuration from one writer: places, people and contacts. Each writer keeps its own file, so\n * two writers do not overwrite each other. The root configuration keeps the other fields: policies, drills and spend.\n */\nexport interface ConfigPart {\n readonly format: typeof CONFIG_PART_FORMAT;\n readonly places?: readonly PlaceConfig[];\n readonly people?: readonly PersonConfig[];\n readonly contacts?: readonly ContactConfig[];\n}\n\n/** A part with its name. The name of a part in a file is the name of the file with no `.json`. */\nexport interface NamedPart {\n readonly name: string;\n readonly part: ConfigPart;\n}\n\n/** The name of a part has small letters, digits and hyphens. It starts with a letter and has 40 characters or fewer. */\nexport const PART_NAME: RegExp = /^[a-z][a-z0-9-]{0,39}$/u;\n\n/** This function gives the name of a part at the start of a problem. A bad name can hold any text, thus the label gives the index of the part. */\nexport function partLabel(name: string, index: number): string {\n return PART_NAME.test(name) ? `The part ${name}` : `Part ${String(index)}`;\n}\n\n/**\n * This function merges the parts into the root configuration. The entries of the root come first. The entries of\n * the parts come after them, in the order of the names. Thus the order of the reads does not change the merge or its hash.\n *\n * The merge finds a bad name and two parts with one name. It also finds an entry in two files: a place, a person, or\n * a contact of one person on one channel. Two entries with one id in one file are a problem of `loadConfig`. A problem\n * names ids and parts, and holds no other value.\n */\nexport function mergeParts(root: AlertConfig, parts: readonly NamedPart[]): Result<AlertConfig, readonly string[]> {\n const problems: string[] = [];\n const names = new Set<string>();\n const good: NamedPart[] = [];\n parts.forEach((named, index) => {\n if (!PART_NAME.test(named.name)) problems.push(`The name of part ${index} is not small letters, digits and hyphens with a letter first, up to 40 characters.`);\n else if (names.has(named.name)) problems.push(`Two parts have the name ${named.name}.`);\n else good.push(named);\n names.add(named.name);\n });\n good.sort((a, b) => compareCodeUnits(a.name, b.name));\n\n // The file of each key, the first time the merge sees it. A key twice in one file is a problem of the load.\n const fileOf = new Map<string, string>();\n const claim = (key: string, file: string, what: string): void => {\n const first = fileOf.get(key);\n if (first === undefined) fileOf.set(key, file);\n else if (first !== file) problems.push(`${what} is in ${first} and in ${file}.`);\n };\n const files: readonly { readonly file: string; readonly part: Omit<ConfigPart, \"format\"> }[] = [\n { file: \"the root configuration\", part: root },\n ...good.map(({ name, part }) => ({ file: `the part ${name}`, part })),\n ];\n for (const { file, part } of files) {\n for (const place of part.places ?? []) claim(`place\\u0000${place.id}`, file, `The place ${place.id}`);\n for (const { watch } of part.people ?? []) claim(`person\\u0000${watch.person}`, file, `The person ${watch.person}`);\n for (const { person, channel } of part.contacts ?? []) claim(`contact\\u0000${person}\\u0000${channel}`, file, `The contact of the person ${person} on the channel ${channel}`);\n }\n if (problems.length > 0) return err(problems);\n return ok({\n ...root,\n places: files.flatMap(({ part }) => part.places ?? []),\n people: files.flatMap(({ part }) => part.people ?? []),\n contacts: files.flatMap(({ part }) => part.contacts ?? []),\n });\n}\n\n/** The name of the format of the settings of one copy of the system. A change that breaks a file gets a new name. */\nexport const COPY_FORMAT = \"alerts-copy/1\";\n\n/** The address and the port of the exchange of a copy. */\nexport interface CopyListen {\n /** The address of the computer on the tailnet. An address of all interfaces is a problem. */\n readonly host: string;\n readonly port: number;\n}\n\n/** Another copy of the system, as one copy sees it. */\nexport interface CopyPeer {\n /** The id of the other copy. */\n readonly id: string;\n /** The URL of the exchange of the other copy, with `http` or `https`. */\n readonly url: string;\n}\n\n/**\n * The settings of one copy of the system: the file `copy.json`. Each copy has its own file. The configuration and the\n * secrets are the same in each copy. A runtime with no file is the only copy, `ONLY_COPY`.\n */\nexport interface CopySettings {\n readonly format: typeof COPY_FORMAT;\n /** The name of the copy, for example `home` or `cloud`. Two copies do not have the same id. */\n readonly id: string;\n /** The order of the copy, from 0. A copy waits its rank times the rank delay before each send. */\n readonly rank: number;\n /** The address of the exchange of this copy. A copy with other copies needs it. */\n readonly listen?: CopyListen;\n /** The other copies. */\n readonly peers?: readonly CopyPeer[];\n /** The key of the secrets with the ping URL of the first check of this copy. The runtime gives a default key. */\n readonly pingKey?: string;\n /**\n * The number of the account of each source with an account, by the id of the source. The keys of account 2 end in\n * `_2`. The default is account 1. Two copies do not share an account, because an account has one session.\n */\n readonly accounts?: Readonly<Record<string, number>>;\n /**\n * The id of the copy that gives the configuration of this copy: `config.json` and the parts. Without it, this copy\n * keeps its own files. The id is the id of a copy of `peers`. Each copy keeps its own `secrets.env` and `copy.json`.\n */\n readonly configFrom?: string;\n}\n\n/** The settings of a runtime with no file `copy.json`: the only copy, with rank 0 and no exchange. */\nexport const ONLY_COPY: CopySettings = { format: COPY_FORMAT, id: \"only\", rank: 0 };\n\n// The addresses of all the interfaces. The exchange does not listen on them: only the tailnet reaches it.\nconst ALL_INTERFACES: ReadonlySet<string> = new Set([\"0.0.0.0\", \"::\", \"[::]\", \"*\"]);\n\n/**\n * This function gives the problems of the settings of a copy that a schema cannot find. Each problem names a field,\n * and it holds no address and no URL.\n *\n * - A rank is lower than the count of the copies, because the ranks of the copies are 0, 1, 2 and up.\n * - The other copies have different ids and URLs, and no other copy has the id of this copy.\n * - A copy with other copies has the address `listen`, and the address is not an address of all interfaces.\n * - The field `configFrom` names a copy of `peers`.\n */\nexport function copyProblems(settings: CopySettings): string[] {\n const problems: string[] = [];\n const peers = settings.peers ?? [];\n if (settings.rank > peers.length) problems.push(`The rank is ${String(settings.rank)}, but the copies are ${String(peers.length + 1)}. A rank is lower than the count of the copies.`);\n const ids = new Set<string>([settings.id]);\n const urls = new Set<string>();\n peers.forEach((peer, at) => {\n if (ids.has(peer.id)) problems.push(`peers[${String(at)}]: the id ${peer.id} is the id of this copy or of an earlier copy.`);\n if (urls.has(peer.url)) problems.push(`peers[${String(at)}]: the URL is the URL of an earlier copy.`);\n ids.add(peer.id);\n urls.add(peer.url);\n });\n if (settings.configFrom !== undefined && !peers.some((peer) => peer.id === settings.configFrom)) problems.push(\"configFrom: the id is not the id of a copy in peers.\");\n if (peers.length > 0 && settings.listen === undefined) problems.push(\"A copy with other copies needs the address listen of its exchange.\");\n if (settings.listen !== undefined && ALL_INTERFACES.has(settings.listen.host)) problems.push(\"listen.host: the exchange does not listen on all the interfaces. Give the tailnet address of the computer.\");\n return problems;\n}\n\n/** The settings of one expectation of the instance, for example the WEA check of a copy source. */\nexport interface ExpectationConfig {\n /** The id of the expectation. */\n readonly id: string;\n /** The start of a new record of the checks of the expectation. The value goes into `Expectation.since`. */\n readonly since: Instant;\n}\n\n/**\n * This function gives the expectations with the settings of the configuration. The `since` of each\n * entry goes into the expectation with its id. An expectation with no entry stays the same.\n */\nexport function configuredExpectations(expectations: readonly Expectation[], settings: readonly ExpectationConfig[] = []): Expectation[] {\n const byId = new Map(settings.map((entry) => [entry.id, entry]));\n return expectations.map((expectation) => {\n const entry = byId.get(expectation.id);\n return entry === undefined ? expectation : { ...expectation, since: entry.since };\n });\n}\n\n/**\n * This function checks the settings of expectations against the expectations of an instance. It finds\n * an entry with an unknown id, and a `since` after the time `at`. A `since` in the future stops the\n * record until that time, so the source cannot be late.\n */\nexport function expectationProblems(settings: readonly ExpectationConfig[] | undefined, expectations: readonly Expectation[], at: Instant): string[] {\n const known = new Set(expectations.map((expectation) => expectation.id));\n return (settings ?? []).flatMap((entry) => [\n ...(known.has(entry.id) ? [] : [`The configuration sets the expectation ${entry.id}, and the instance has no such expectation.`]),\n ...(entry.since > at ? [`The since of the expectation ${entry.id} is in the future. The check of the source then has no record until that time.`] : []),\n ]);\n}\n\n/** The secret store of the instance. It gives the value of a key, or `undefined` when it has no such key. */\nexport type SecretLookup = (name: string) => string | undefined;\n\n/** The result of a load. */\nexport interface LoadedConfig {\n /** The recipient of each person, in the order of the configuration. */\n readonly recipients: readonly Recipient[];\n /**\n * The problems of the configuration. Each problem names ids, fields and the names of secrets, but\n * no value of a secret, no label and no position. The runtime does not start with a problem.\n */\n readonly problems: readonly string[];\n /** The opt-in list of the texts, with the value of each number. */\n readonly optIn: readonly OptInRecord[];\n}\n\n/**\n * This function checks a configuration and makes the recipient of each person. It finds:\n *\n * - two places or two people with one id, and a place with no region code\n * - a place of a person or of a rule that the configuration or the person does not have\n * - a contact of an unknown person, two contacts of a person on one channel, and a secret that the store does not have\n * - two settings of one expectation\n * - two spend entries of one provider, and a provider that no channel depends on\n * - a reserve of a spend entry that is not below its cap, and a time zone that is not an IANA name\n * - an unknown person of the outage call, a person two times in it, and a chain with no step\n * - a step of the outage call on a channel with no contact of the person\n * - a rank delay that is not a whole number of milliseconds up to `RANK_DELAY_LIMIT`\n * - a window of the send limit that is not one minute to one day, and a count of the send limit below 1\n * - two drills with one id, a drill of an unknown person, and a drill on a channel with no contact of the person\n * - a drill of a person who does not watch `DRILL_SUBJECT`\n * - a run or a failure of a drill that sends nothing to its person: no policy of its level, or no step after the rules\n * - each problem of `drillProblems` for each drill\n * - each problem of `recipientProblems` for each person.\n *\n * With `services`, the layer `delivery` of each person also takes the services of each contact of the person\n * (`contactChannels`). No problem holds them.\n */\nexport function loadConfig(config: AlertConfig, channels: readonly ChannelDescriptor[], secret: SecretLookup, services?: ContactServices): LoadedConfig {\n const problems: string[] = [];\n const places = new Set<string>();\n for (const place of config.places) {\n if (places.has(place.id)) problems.push(`Two places have the id ${place.id}.`);\n places.add(place.id);\n // The core matches by the region codes only, until the home of geography has the tests of shapes.\n if (place.codes.length === 0) problems.push(`The place ${place.id} has no region code, so no incident matches it.`);\n }\n\n const people = new Set<string>();\n // The watch of each recipient, in the order of the people: the join of the default layers, or the watch as it is.\n const watches: PersonWatch[] = [];\n for (const entry of config.people) {\n const { watch } = entry;\n const person = watch.person;\n if (people.has(person)) problems.push(`Two people have the id ${person}.`);\n people.add(person);\n const own = new Set<string>(watch.places);\n for (const place of watch.places) if (!places.has(place)) problems.push(`The person ${person} watches the place ${place}, and the configuration has no such place.`);\n watch.rules.forEach((rule, index) => {\n for (const place of rule.places ?? []) {\n if (!own.has(place)) problems.push(`Rule ${index} of the person ${person} names the place ${place}, and the person does not watch it. The rule matches no incident there.`);\n }\n });\n const joined = personInterests(entry, contactChannels(config, person, channels, services === undefined ? undefined : { secret, services }));\n if (joined.problem !== undefined) problems.push(`The defaults of the person ${person}: ${joined.problem}`);\n watches.push(joined.watch);\n problems.push(...relevanceProblems(joined.watch, own));\n }\n\n const expectations = new Set<string>();\n for (const { id } of config.expectations ?? []) {\n if (expectations.has(id)) problems.push(`Two settings of expectations have the id ${id}.`);\n expectations.add(id);\n }\n\n // Maps, not objects: an id or a field such as `constructor` is then a plain key.\n const addresses = new Map<string, Map<string, Address>>();\n for (const contact of config.contacts) {\n const { person, channel } = contact;\n if (!people.has(person)) {\n problems.push(`A contact on the channel ${channel} is for the person ${person}, and the configuration has no such person.`);\n continue;\n }\n const ofPerson = addresses.get(person) ?? new Map<string, Address>();\n addresses.set(person, ofPerson);\n if (ofPerson.has(channel)) {\n problems.push(`The person ${person} has two contacts on the channel ${channel}.`);\n continue;\n }\n const { address, missing } = resolveAddress(contact, secret);\n for (const { field, name } of missing) problems.push(`The field ${field} of the contact of ${person} on ${channel} names the secret ${name}, and the secret store has no value for it.`);\n ofPerson.set(channel, address);\n }\n\n // Each value of an opt-in field needs a record. A channel of texts then sends only to a person who agreed.\n const { records: optIn, problems: optInFound } = resolveOptIn(config.optIn ?? [], secret);\n problems.push(...optInFound);\n const listed = new Set(optIn.map((record) => record.number));\n for (const channel of channels) {\n for (const field of optInFields(channel)) {\n for (const [person, ofPerson] of addresses) {\n const value = ofPerson.get(channel.id)?.[field.name];\n if (value !== undefined && !listed.has(value)) problems.push(`The field ${field.name} of the contact of ${person} on ${channel.id} is not on the opt-in list. The channel sends nothing to it.`);\n }\n }\n }\n\n const providers = new Set<string>();\n for (const spend of config.spend ?? []) {\n const { provider } = spend;\n if (providers.has(provider)) problems.push(`Two spend entries are for the provider ${provider}.`);\n providers.add(provider);\n // A typo of a provider gives a cap that no send takes from.\n if (!channels.some((channel) => channel.dependsOn.includes(provider))) problems.push(`The spend entry of ${provider} names a provider that no channel depends on.`);\n // The fixed costs come first. Thus the reserve is a part of the cap of the sends, and the sends get more than 0.\n const sends = sendCapUsd(spend);\n if (!(sends > 0)) problems.push(`The fixed costs of the spend of ${provider} use all of its monthly cap. No send can go.`);\n else if (!((spend.reserveUsd ?? 0) < sends)) problems.push(`The reserve of the spend of ${provider} is not below its monthly cap less its fixed costs.`);\n if (localTime(0, spend.timeZone) === undefined) problems.push(`The time zone of the spend of ${provider} is not an IANA name.`);\n }\n\n problems.push(...rankDelayProblems(config.rankDelay ?? {}));\n problems.push(...rankFloorProblems(config.rankFloor));\n problems.push(...sendLimitProblems(config.sendLimit ?? {}));\n problems.push(...throttleProblems(config.throttle ?? {}));\n\n const called = new Set<string>();\n for (const { person, chain } of config.outage?.people ?? []) {\n if (called.has(person)) problems.push(`The outage call has the person ${person} two times.`);\n called.add(person);\n if (!people.has(person)) {\n problems.push(`The outage call names the person ${person}, and the configuration has no such person.`);\n continue;\n }\n if (chain.steps.length === 0) problems.push(`The outage chain of the person ${person} has no step, so no outage call reaches the person.`);\n for (const channel of new Set(chain.steps)) {\n if (!channels.some((known) => known.id === channel)) problems.push(`The outage chain of the person ${person} uses the channel ${channel}, and the instance has no such channel.`);\n else if (addresses.get(person)?.has(channel) !== true) problems.push(`The outage chain of the person ${person} uses the channel ${channel}, and the person has no contact on it.`);\n }\n }\n\n const recipients = config.people.map((entry, index): Recipient => {\n const recipient: Recipient = {\n watch: watches[index] ?? entry.watch,\n policies: entry.policies ?? config.policies,\n addresses: Object.fromEntries(addresses.get(entry.watch.person) ?? []),\n };\n for (const problem of recipientProblems(recipient, channels)) problems.push(`The person ${entry.watch.person}: ${problem}`);\n return recipient;\n });\n\n const drills = new Set<string>();\n const recipientOf = new Map(recipients.map((recipient) => [recipient.watch.person as string, recipient]));\n const rulesOf = new Map<string, ChannelRule[]>();\n for (const drill of config.drills ?? []) {\n const { id, person, path } = drill;\n if (drills.has(id)) problems.push(`Two drills have the id ${id}.`);\n drills.add(id);\n const recipient = recipientOf.get(person);\n if (recipient === undefined) problems.push(`The drill ${id} is for the person ${person}, and the configuration has no such person.`);\n else {\n if (addresses.get(person)?.has(path.channel) !== true) problems.push(`The drill ${id} uses the channel ${path.channel}, and the person ${person} has no contact on it.`);\n // The route sends the drill report only to a person who watches its subject.\n const watched = (recipient.watch.subjects ?? []).some((watch) => watch.system === DRILL_SUBJECT && (watch.id === undefined || watch.id === id));\n if (!watched) problems.push(`The drill ${id} is for the person ${person}, and the person does not watch the subject ${DRILL_SUBJECT}. The drill does not reach the person.`);\n const rules = drillRules(drill);\n rulesOf.set(person, [...(rulesOf.get(person) ?? []), ...rules]);\n // A run goes only to the person of the drill. Another person who watches the drill gets no step of a run, and\n // still gets the failure.\n for (const other of recipients) {\n if (other.watch.person === person || matchSubjects({ about: [{ system: DRILL_SUBJECT, id }] }, other.watch.subjects ?? []).length === 0) continue;\n rulesOf.set(other.watch.person, [...(rulesOf.get(other.watch.person) ?? []), { kinds: [`${DRILL_KIND}.run`], about: { system: DRILL_SUBJECT, id }, keep: \"only\", channels: [] }]);\n }\n if (watched) problems.push(...drillPlanProblems(drill, { ...recipient, channelRules: [...(recipient.channelRules ?? []), ...rules] }, config.assess ?? DEFAULT_ASSESS_POLICY));\n }\n problems.push(...drillProblems(drill, channels, recipient?.watch.quiet));\n }\n // The report of a down channel goes on each other channel of the person, because the down channel does not carry it.\n const ruled = recipients.map((recipient) => {\n const own = [...(addresses.get(recipient.watch.person)?.keys() ?? [])].sort(compareCodeUnits) as ChannelId[];\n const rules = [...(rulesOf.get(recipient.watch.person) ?? []), ...channelDownRules(own)];\n return rules.length === 0 ? recipient : { ...recipient, channelRules: [...(recipient.channelRules ?? []), ...rules] };\n });\n return { recipients: ruled, problems, optIn };\n}\n\n/**\n * This function gives the channel rules of the reports of down channels (AL-65), one for each channel. The report of a\n * down channel goes on each channel of the person except that channel. `loadConfig` adds them to each person.\n */\nexport function channelDownRules(channels: readonly ChannelId[]): ChannelRule[] {\n return channels.map((channel) => ({ kinds: [`${CHANNEL_KIND}.down`], about: { system: CHANNEL_SUBJECT, id: channel }, keep: \"except\", channels: [channel] }));\n}\n\n/**\n * This function gives the two channel rules of a drill. A run goes only on the channel of the path. A failure goes on\n * each other channel of the person, because the path can be the broken part. `loadConfig` adds them to the person.\n */\nexport function drillRules(drill: DrillConfig): ChannelRule[] {\n const about = { system: DRILL_SUBJECT, id: drill.id };\n return [\n { kinds: [`${DRILL_KIND}.run`], about, keep: \"only\", channels: [drill.path.channel] },\n { kinds: [`${DRILL_KIND}.failed`], about, keep: \"except\", channels: [drill.path.channel] },\n ];\n}\n\n// The plans of a drill for its person: the system fold makes the reports of a run and of its failure, the assessment\n// gives their levels, and the channel rules keep the steps. Thus the check reads the same code as the runtime.\nfunction drillPlanProblems(drill: DrillConfig, recipient: Recipient, policy: AssessPolicy): string[] {\n const at = DRILL_PROBES.map((from) => nextDrillAt(drill, [], from, recipient.watch.quiet)).find((start) => start !== undefined);\n // A drill with no start has a problem of `drillProblems`.\n if (at === undefined) return [];\n const snapshot = { sources: [], health: [], coverage: [], threats: [], drills: [{ copy: \"probe\", drill, run: { drill: drill.id, at } }] };\n const run = systemReports(NO_SYSTEM_LINES, snapshot, at);\n const end = at + drill.ackWithin;\n const failed = systemReports(run.lines, snapshot, end);\n const { id, person, path } = drill;\n const plans = [\n { name: \"run\", reports: run.reports, at },\n { name: \"failure\", reports: failed.reports.filter((report) => report.kind.code === `${DRILL_KIND}.failed`), at: end },\n ];\n const problems: string[] = [];\n for (const plan of plans) {\n for (const incident of incidents(normalize({ reports: plan.reports }), plan.at)) {\n const level = reachedAssessment(assess(incident, recipient.watch, [], policy, plan.at)).level;\n const found = level === \"none\" ? undefined : policyFor(recipient.policies, level, incident);\n if (found === undefined) {\n problems.push(`The ${plan.name} of the drill ${id} reaches the person ${person} at the level ${level}, and the person has no policy of it. It sends nothing.`);\n continue;\n }\n const kept = ruleSteps(found, recipient.channelRules, incident).policy;\n if (kept.steps.length > 0) continue;\n const which = plan.name === \"run\" ? `no step on the channel ${path.channel}` : `no step on a channel other than ${path.channel}`;\n problems.push(`The ${plan.name} of the drill ${id} reaches the person ${person} at the level ${level}, and its policy has ${which}. It sends nothing.`);\n }\n }\n return problems;\n}\n\n// The place ids of the place nodes of a graph, in the order of the edges and then of the mutes.\nfunction graphPlaces(graph: InterestGraph): PlaceId[] {\n const nodes = [...graph.edges.flatMap((edge) => [edge.from, edge.to]), ...graph.mutes.flatMap((mute) => mute.subjects ?? [])];\n return [...new Set(nodes.flatMap((node) => placeOfNode(node) ?? []))];\n}\n\n/** The interests of one person after the load: the watch of the recipient, a row for each edge, and the problem of the join. */\nexport interface PersonInterests {\n readonly watch: PersonWatch;\n /** The rows of the graph of the watch. A person with no graph has no row. */\n readonly rows: readonly InterestRow[];\n /** The text of the refusal of the join. Then the person keeps the watch of the configuration. */\n readonly problem?: string;\n}\n\n/**\n * This function gives the watch of a recipient: the join of the default layers and the graph of the person\n * (`composeInterests`). A person with no defaults keeps the watch, and each edge of the graph is a row.\n *\n * The array `channels` holds the channels of the contacts of the person (`contactChannels`). The layer `delivery` takes\n * their services, unless the field `delivery` of the defaults is `false`.\n *\n * The layer `places` is always in the join. Without it, a graph of work topics alone stops the routing at the places.\n * A graph of another person also stays as it is: `relevanceProblems` reports it, and the places decide.\n */\nexport function personInterests(entry: PersonConfig, channels: readonly ChannelDescriptor[] = []): PersonInterests {\n const { watch, defaults } = entry;\n const own = watch.interests;\n const kept = (problem?: string): PersonInterests => ({ watch, rows: own?.edges.map((edge) => ({ edge })) ?? [], ...(problem === undefined ? {} : { problem }) });\n if (defaults === undefined || (own !== undefined && own.person !== watch.person)) return kept();\n try {\n const delivery = defaults.delivery === false ? [] : deliveryLayer(channels);\n const layers = [placesLayer(watch.places), workLayer(defaults.works ?? []), servicesLayer(defaults.services ?? []), delivery];\n const { graph, rows } = composeInterests(watch.person, layers, own);\n return { watch: { ...watch, interests: graph }, rows };\n } catch (error) {\n if (error instanceof RangeError) return kept(error.message);\n throw error;\n }\n}\n\n/** The lookup of the services of each contact: the store of the secrets, and the services of an address. */\nexport interface ContactLookup {\n readonly secret: SecretLookup;\n readonly services: ContactServices;\n}\n\n/**\n * This function gives the channels of the contacts of a person, in the order of `channels`. Each such descriptor has a\n * contact of the person in the configuration. The layer `delivery` takes the services of these channels.\n *\n * With a `lookup`, the descriptor of each channel also gets the services of the first contact of the person on it.\n * Only the keys of entities count. A missing secret, a lookup that throws and a key of another kind give no service.\n * The check of the contacts reports a missing secret. Thus no problem holds a value of an address or its services.\n */\nexport function contactChannels(\n config: Pick<AlertConfig, \"contacts\">,\n person: PersonId,\n channels: readonly ChannelDescriptor[],\n lookup?: ContactLookup,\n): readonly ChannelDescriptor[] {\n const contacts = config.contacts.filter((contact) => contact.person === person);\n const ids = new Set<string>(contacts.map((contact) => contact.channel));\n const found = channels.filter((channel) => ids.has(channel.id));\n if (lookup === undefined) return found;\n return found.map((channel) => {\n const contact = contacts.find((one) => one.channel === channel.id);\n const resolved = contact === undefined ? undefined : resolveAddress(contact, lookup.secret);\n const added = resolved === undefined || resolved.missing.length > 0 ? [] : contactNodes(lookup.services, channel.id, resolved.address);\n return added.length === 0 ? channel : { ...channel, services: [...new Set([...(channel.services ?? []), ...added])] };\n });\n}\n\n// The address of a contact with the value of each secret, and each field whose secret the store does not have.\nfunction resolveAddress(contact: ContactConfig, secret: SecretLookup): { readonly address: Address; readonly missing: readonly { readonly field: string; readonly name: string }[] } {\n const fields: [string, string][] = [];\n const missing: { field: string; name: string }[] = [];\n for (const [field, value] of Object.entries(contact.address)) {\n if (typeof value === \"string\") {\n fields.push([field, value]);\n continue;\n }\n const found = secret(value.secret);\n if (found === undefined || found === \"\") missing.push({ field, name: value.secret });\n else fields.push([field, found]);\n }\n return { address: Object.fromEntries(fields), missing };\n}\n\n// The services of an address that are entities. A lookup that throws gives none. By its contract it does not throw, and\n// a problem with its error could hold a private fact of the address.\nfunction contactNodes(services: ContactServices, channel: ChannelId, address: Address): readonly NodeKey[] {\n try {\n return services(channel, address).filter((node) => kindOfNode(node) === \"entity\");\n } catch {\n return [];\n }\n}\n\n/**\n * This function gives the problems of the interest graph and of the rule of the life-safety warnings of a person. The\n * set `own` holds the places of the person. A graph of another person makes the relevance fail at each incident. A\n * place node or a rule at a place that the person does not watch matches no incident.\n */\nfunction relevanceProblems(watch: PersonWatch, own: ReadonlySet<string>): string[] {\n const person = watch.person;\n const problems: string[] = [];\n const graph = watch.interests;\n if (graph !== undefined) {\n if (graph.person !== person) problems.push(`The interest graph of the person ${person} is of the person ${graph.person}. The relevance fails, and the places decide.`);\n for (const place of graphPlaces(graph)) {\n if (!own.has(place)) problems.push(`The interest graph of the person ${person} names the place ${place}, and the person does not watch it.`);\n }\n }\n for (const rule of watch.mandatory ?? []) {\n if (!own.has(rule.place)) problems.push(`The rule of the life-safety warnings of the person ${person} names the place ${rule.place}, and the person does not watch it.`);\n }\n if (graph === undefined && (watch.mandatory?.length ?? 0) > 0) {\n problems.push(`The person ${person} has rules of the life-safety warnings and no interest graph. The rules have no effect without a graph.`);\n }\n return problems;\n}\n\n/**\n * This function gives the places of the configuration for the matching on the machine of the\n * instance, with each position. Do not give these places to a source: use `sourcePlaces`.\n */\nexport function localPlaces(config: AlertConfig): WatchedPlace[] {\n return config.places.map((place) => watchedPlace(place, true));\n}\n\n/** This function gives the places of the configuration for one source. A place has a position only when it shares it with that source. */\nexport function sourcePlaces(config: AlertConfig, source: SourceId): WatchedPlace[] {\n return config.places.map((place) => watchedPlace(place, place.sharePosition?.includes(source) === true));\n}\n\n/**\n * This function gives the labels of the places of the configuration, by their node keys `place:<id>`. The labels\n * stay on the machine of the instance: the runtime puts them only in the why line of a message.\n */\nexport function placeLabels(config: AlertConfig): WhyLabels {\n const labels = new Map<NodeKey, string>(config.places.map((place) => [placeNode(place.id), place.label]));\n return (node) => labels.get(node);\n}\n\n/** The scheme of the hash of a configuration. A new scheme gives a new hash to each configuration. */\nexport const CONFIG_HASH_SCHEME = \"alerts-config-hash/1\";\n\n/**\n * This function gives the hash of a configuration: the SHA-256 of its canonical JSON (RFC 8785), as 64 hex characters.\n * The order of the keys does not change the hash. The copies of the system compare their hashes in the exchange.\n * A different hash tells that two copies can route an alert in two ways. The hash holds no value of the configuration.\n */\nexport function configHash(config: AlertConfig): string {\n return canonicalHash([CONFIG_HASH_SCHEME, config], { form: \"json\" });\n}\n\n// A watched place has no label. It has the position only when `withPosition` is true.\nfunction watchedPlace(place: PlaceConfig, withPosition: boolean): WatchedPlace {\n return { id: place.id, codes: place.codes, bufferKm: place.bufferKm, ...(withPosition && place.at !== undefined ? { at: place.at } : {}) };\n}\n","/**\n * The health of one source. It is a pure fold over the fetch records of the source and the time.\n * It reads no clock and no network: the runtime gives each record when its fetch ends, and gives the\n * time again at `wakeAt`.\n *\n * `HEALTH_MACHINE` is the machine document of the health, in the format of `@mark1russell7/algebra`.\n * Each step gives its transitions, and a replay against the document finds a transition that the\n * document does not permit. Each transition is also a system report.\n */\nimport type { Machine, Transition } from \"@mark1russell7/algebra\";\nimport type { CanaryResult, Duration, FetchFailure, FetchRecord, HealthState, Instant, SourceDescriptor, SourceHealth, SourceId } from \"./contracts.ts\";\n\n/** The events of the health machine. */\nexport const HEALTH_EVENTS: {\n readonly passed: \"app.fetch-passed\";\n readonly slow: \"app.fetch-slow\";\n readonly changed: \"app.fetch-changed\";\n readonly failed: \"app.fetch-failed\";\n readonly canaryPassed: \"app.canary-passed\";\n readonly canaryFailed: \"app.canary-failed\";\n readonly quiet: \"timer.quiet\";\n readonly stale: \"timer.stale\";\n} = {\n passed: \"app.fetch-passed\",\n slow: \"app.fetch-slow\",\n changed: \"app.fetch-changed\",\n failed: \"app.fetch-failed\",\n canaryPassed: \"app.canary-passed\",\n canaryFailed: \"app.canary-failed\",\n quiet: \"timer.quiet\",\n stale: \"timer.stale\",\n};\n\ntype HealthEvent = (typeof HEALTH_EVENTS)[keyof typeof HEALTH_EVENTS];\n\n/** The count of fetches in a row that fail before the state is `failing`, when the options do not give it. */\nexport const DEFAULT_FAIL_AFTER = 2;\n\n/** The count of fetch intervals with no passed fetch before the state is `failing`, when the options do not give a time. */\nexport const DEFAULT_STALE_INTERVALS = 3;\n\n/** The machine document of the health. The health steps make only the transitions of this document. */\nexport const HEALTH_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"alerts.health\",\n title: \"The health of one source, from the records of its fetches\",\n layer: \"self\",\n version: \"1\",\n sources: [{ ref: \"docs/CONTRACTS.md of the alerts repository: health and coverage\", rung: \"derived\" }],\n states: {\n unknown: { initial: true, note: \"no fetch passed yet\" },\n healthy: { note: \"the last fetch passed in less than slowAfter\" },\n slow: { note: \"the last fetch passed in slowAfter or more\" },\n failing: { note: \"fail_after fetches in a row failed, no fetch passed for stale_after, or the canary failed\" },\n silent: { note: \"no fresh observation for max_quiet, for a source where quiet is not normal\" },\n changed: { note: \"the map gave fatal or lossy problems for the last passed fetch\" },\n },\n events: {\n \"app.fetch-passed\": { kind: \"app\", note: \"a fetch passed in less than slowAfter, with no fatal or lossy problem of the map\" },\n \"app.fetch-slow\": { kind: \"app\", note: \"a fetch passed in slowAfter or more, with no fatal or lossy problem of the map\" },\n \"app.fetch-changed\": { kind: \"app\", note: \"a fetch passed, and the map gave fatal or lossy problems\" },\n \"app.fetch-failed\": { kind: \"app\", note: \"a fetch failed\" },\n \"app.canary-passed\": { kind: \"app\", note: \"the canary check of a fetch passed\" },\n \"app.canary-failed\": { kind: \"app\", note: \"the canary check of a fetch failed\" },\n \"timer.quiet\": { kind: \"timer\", note: \"max_quiet passed with no fresh observation\" },\n \"timer.stale\": { kind: \"timer\", note: \"stale_after passed with no passed fetch\" },\n },\n knobs: {\n interval: { key: \"SourceDescriptor.interval\", scope: \"source\", unit: \"ms\", default: null },\n slow_after: { key: \"SourceDescriptor.slowAfter\", scope: \"source\", unit: \"ms\", default: null },\n max_quiet: { key: \"SourceDescriptor.maxQuiet\", scope: \"source\", unit: \"ms\", default: null, note: \"absent: a quiet source is normal, and the quiet timer is off\" },\n fail_after: { key: \"HealthOptions.failAfter\", scope: \"cell\", unit: \"count\", default: DEFAULT_FAIL_AFTER },\n stale_after: { key: \"HealthOptions.staleAfter\", scope: \"cell\", unit: \"ms\", default: null, note: \"absent: 3 times the interval\" },\n },\n timers: {\n stale: {\n duration: { knob: \"stale_after\", unit: \"ms\" },\n arms: [\"enter:unknown\", \"app.fetch-passed\", \"app.fetch-slow\", \"app.fetch-changed\"],\n fires: \"timer.stale\",\n note: \"the end of each passed fetch starts it again\",\n },\n quiet: {\n duration: { knob: \"max_quiet\", unit: \"ms\" },\n arms: [\"app.fetch-passed\", \"app.fetch-slow\", \"app.fetch-changed\"],\n fires: \"timer.quiet\",\n note: \"the first passed fetch and each passed fetch with a fresh observation start it again\",\n },\n },\n transitions: [\n { id: \"he.stale\", from: [\"unknown\", \"healthy\", \"slow\", \"silent\", \"changed\"], to: \"failing\", on: \"timer.stale\", timer: \"stale\" },\n { id: \"he.quiet\", from: [\"healthy\", \"slow\"], to: \"silent\", on: \"timer.quiet\", timer: \"quiet\" },\n { id: \"he.failed\", from: [\"unknown\", \"healthy\", \"slow\", \"silent\", \"changed\"], to: \"failing\", on: \"app.fetch-failed\", guard: \"fail_after fetches in a row failed\" },\n { id: \"he.passed\", from: [\"unknown\", \"failing\", \"slow\", \"silent\", \"changed\"], to: \"healthy\", on: \"app.fetch-passed\", guard: \"the last canary did not fail\" },\n { id: \"he.slow\", from: [\"unknown\", \"failing\", \"healthy\", \"silent\", \"changed\"], to: \"slow\", on: \"app.fetch-slow\", guard: \"the last canary did not fail\" },\n { id: \"he.changed\", from: [\"unknown\", \"failing\", \"healthy\", \"slow\", \"silent\"], to: \"changed\", on: \"app.fetch-changed\", guard: \"the last canary did not fail\" },\n {\n id: \"he.passed-quiet\",\n from: [\"failing\", \"changed\"],\n to: \"silent\",\n on: [\"app.fetch-passed\", \"app.fetch-slow\"],\n guard: \"no fresh observation for max_quiet\",\n note: \"the quiet timer fired in the state failing or changed, which hold it\",\n },\n { id: \"he.canary-failed\", from: [\"healthy\", \"slow\", \"silent\", \"changed\"], to: \"failing\", on: \"app.canary-failed\" },\n { id: \"he.canary-healthy\", from: \"failing\", to: \"healthy\", on: \"app.canary-passed\" },\n { id: \"he.canary-slow\", from: \"failing\", to: \"slow\", on: \"app.canary-passed\" },\n { id: \"he.canary-silent\", from: \"failing\", to: \"silent\", on: \"app.canary-passed\" },\n { id: \"he.canary-changed\", from: \"failing\", to: \"changed\", on: \"app.canary-passed\" },\n ],\n};\n\n/** The options of the health. */\nexport interface HealthOptions {\n /** The count of fetches in a row that fail before the state is `failing`. */\n readonly failAfter?: number;\n /** The longest time with no passed fetch before the state is `failing`. */\n readonly staleAfter?: Duration;\n}\n\n/** The last passed fetch of a source. */\nexport interface PassedFetch {\n readonly at: Instant;\n readonly took: Duration;\n readonly fatal: number;\n /** The count of lossy problems. An absent count is 0. */\n readonly lossy?: number;\n}\n\n/** The state of the fold of the health. It is data, so the runtime can keep it in its log. */\nexport interface HealthTrack {\n readonly source: SourceId;\n readonly state: HealthState;\n /** The time of the last change of state. */\n readonly since: Instant;\n /** The time of the last step. Time does not go back. */\n readonly time: Instant;\n /** The count of the last fetches in a row that failed. */\n readonly failures: number;\n /** The end of the last passed fetch, or the start of the track. The stale timer starts at it. */\n readonly staleFrom: Instant;\n /** The end of the last passed fetch with a fresh observation, or of the first passed fetch. */\n readonly quietFrom?: Instant;\n readonly passed?: PassedFetch;\n readonly lastFailure?: { readonly at: Instant; readonly failure: FetchFailure };\n /** The result of the last canary check. */\n readonly canary?: CanaryResult;\n}\n\n/** The result of one step of the health. */\nexport interface HealthStep {\n readonly track: HealthTrack;\n readonly health: SourceHealth;\n /** The changes of state of the step, in order. The instance is the source id. */\n readonly transitions: readonly Transition[];\n /** The time of the next timer. The runtime gives the time again then. Absent: only a record can change the state. */\n readonly wakeAt?: Instant;\n}\n\n/** This function starts the health of a source at a time, in the state `unknown`. */\nexport function startHealth(source: SourceId, at: Instant): HealthTrack {\n return { source, state: \"unknown\", since: at, time: at, failures: 0, staleFrom: at };\n}\n\n/**\n * This function adds the record of one fetch. The record is an event at the end of the fetch. The\n * timers that end before that time fire first.\n */\nexport function observeFetch(track: HealthTrack, record: FetchRecord, descriptor: SourceDescriptor, options: HealthOptions = {}): HealthStep {\n const end = Math.max(track.time, record.at + record.took);\n const transitions: Transition[] = [];\n let next = fire(track, end, descriptor, options, transitions);\n if (record.failure !== undefined) {\n next = { ...next, failures: next.failures + 1, lastFailure: { at: record.at, failure: record.failure } };\n next = change(next, HEALTH_EVENTS.failed, end, descriptor, options, transitions);\n } else {\n const lossy = record.lossy ?? 0;\n const passed: PassedFetch = { at: record.at, took: record.took, fatal: record.fatal, ...(lossy > 0 ? { lossy } : {}) };\n const quietFrom = record.fresh > 0 || next.quietFrom === undefined ? end : next.quietFrom;\n next = { ...next, failures: 0, staleFrom: end, quietFrom, passed };\n const event = record.fatal + lossy > 0 ? HEALTH_EVENTS.changed : record.took >= descriptor.slowAfter ? HEALTH_EVENTS.slow : HEALTH_EVENTS.passed;\n next = change(next, event, end, descriptor, options, transitions);\n if (record.canary !== undefined) {\n next = { ...next, canary: record.canary };\n const canaryEvent = record.canary.pass ? HEALTH_EVENTS.canaryPassed : HEALTH_EVENTS.canaryFailed;\n next = change(next, canaryEvent, end, descriptor, options, transitions);\n }\n }\n return stepOf(next, descriptor, options, transitions);\n}\n\n/** This function moves the health to a time. The timers that end by that time fire. */\nexport function advanceHealth(track: HealthTrack, now: Instant, descriptor: SourceDescriptor, options: HealthOptions = {}): HealthStep {\n const transitions: Transition[] = [];\n return stepOf(fire(track, now, descriptor, options, transitions), descriptor, options, transitions);\n}\n\n/**\n * This function gives the health of a source at the time `now`. It starts a track at `start`, and\n * adds the records in the order of their ends.\n */\nexport function health(\n descriptor: SourceDescriptor,\n start: Instant,\n records: readonly FetchRecord[],\n now: Instant,\n options: HealthOptions = {},\n): HealthStep {\n const transitions: Transition[] = [];\n let track = startHealth(descriptor.id, start);\n for (const record of records) {\n const step = observeFetch(track, record, descriptor, options);\n transitions.push(...step.transitions);\n track = step.track;\n }\n const last = advanceHealth(track, now, descriptor, options);\n return { ...last, transitions: [...transitions, ...last.transitions] };\n}\n\n// The timers that end after the last step and by `to` fire in the order of their ends.\nfunction fire(track: HealthTrack, to: Instant, descriptor: SourceDescriptor, options: HealthOptions, transitions: Transition[]): HealthTrack {\n let next = track;\n for (const timer of deadlines(track, descriptor, options).filter((t) => t.at > track.time && t.at <= to).sort((a, b) => a.at - b.at)) {\n next = change(next, timer.on, timer.at, descriptor, options, transitions);\n }\n return next.time >= to ? next : { ...next, time: to };\n}\n\nfunction deadlines(track: HealthTrack, descriptor: SourceDescriptor, options: HealthOptions): { readonly at: Instant; readonly on: HealthEvent }[] {\n const found: { at: Instant; on: HealthEvent }[] = [{ at: track.staleFrom + staleAfter(descriptor, options), on: HEALTH_EVENTS.stale }];\n const quiet = maxQuiet(descriptor);\n if (quiet !== undefined && track.quietFrom !== undefined) {\n found.push({ at: track.quietFrom + quiet, on: HEALTH_EVENTS.quiet });\n }\n return found;\n}\n\n// One event at one time: the state becomes the state of the conditions.\nfunction change(track: HealthTrack, on: HealthEvent, at: Instant, descriptor: SourceDescriptor, options: HealthOptions, transitions: Transition[]): HealthTrack {\n const time = Math.max(track.time, at);\n const to = classify({ ...track, time }, descriptor, options).state;\n if (to === track.state) return { ...track, time };\n transitions.push({ machine: HEALTH_MACHINE.id, instance: track.source, from: track.state, on, to, at: time });\n return { ...track, state: to, since: time, time };\n}\n\n// The reason of the state changed. A fetch with no lossy problem keeps the text of the fatal problems only.\nfunction changedReason(passed: PassedFetch): string {\n const lossy = passed.lossy ?? 0;\n const counts =\n lossy === 0\n ? `${passed.fatal} fatal problems`\n : passed.fatal === 0\n ? `${lossy} lossy problems`\n : `${passed.fatal} fatal problems and ${lossy} lossy problems`;\n return `The map gave ${counts} for the last passed fetch.`;\n}\n\n/**\n * The conditions in the order of their weight. The first condition that holds gives the state:\n * failing, then unknown, then changed, then silent, then slow, then healthy.\n */\nfunction classify(track: HealthTrack, descriptor: SourceDescriptor, options: HealthOptions): { readonly state: HealthState; readonly reason: string } {\n const failAfter = Math.max(1, options.failAfter ?? DEFAULT_FAIL_AFTER);\n if (track.failures >= failAfter) {\n return { state: \"failing\", reason: `The last ${track.failures} fetches failed: ${track.lastFailure?.failure.kind ?? \"unknown\"}.` };\n }\n const stale = staleAfter(descriptor, options);\n if (track.time - track.staleFrom >= stale) {\n return { state: \"failing\", reason: `No fetch passed in ${seconds(track.time - track.staleFrom)}, and the limit is ${seconds(stale)}.` };\n }\n if (track.canary !== undefined && !track.canary.pass) {\n return { state: \"failing\", reason: `The canary failed: ${track.canary.reason}` };\n }\n if (track.passed === undefined) return { state: \"unknown\", reason: \"No fetch passed yet.\" };\n if (track.passed.fatal + (track.passed.lossy ?? 0) > 0) return { state: \"changed\", reason: changedReason(track.passed) };\n const quiet = maxQuiet(descriptor);\n if (quiet !== undefined && track.quietFrom !== undefined && track.time - track.quietFrom >= quiet) {\n return { state: \"silent\", reason: `No fresh observation in ${seconds(track.time - track.quietFrom)}, and the limit is ${seconds(quiet)}.` };\n }\n if (track.passed.took >= descriptor.slowAfter) {\n return { state: \"slow\", reason: `The last fetch took ${seconds(track.passed.took)}, and the limit is ${seconds(descriptor.slowAfter)}.` };\n }\n return { state: \"healthy\", reason: \"The last fetch passed.\" };\n}\n\nfunction stepOf(track: HealthTrack, descriptor: SourceDescriptor, options: HealthOptions, transitions: readonly Transition[]): HealthStep {\n const { reason } = classify(track, descriptor, options);\n const health: SourceHealth = {\n source: track.source,\n state: track.state,\n since: track.since,\n ...(track.passed === undefined ? {} : { lastSuccess: track.passed.at }),\n ...(track.lastFailure === undefined ? {} : { lastFailure: track.lastFailure }),\n reason,\n };\n const wake = deadlines(track, descriptor, options).filter((t) => t.at > track.time).map((t) => t.at);\n return { track, health, transitions, ...(wake.length > 0 ? { wakeAt: Math.min(...wake) } : {}) };\n}\n\n// Each limit is 1 or more, so an event never meets a limit at the time that it sets the limit.\nfunction staleAfter(descriptor: SourceDescriptor, options: HealthOptions): Duration {\n return Math.max(1, options.staleAfter ?? DEFAULT_STALE_INTERVALS * descriptor.interval);\n}\n\nfunction maxQuiet(descriptor: SourceDescriptor): Duration | undefined {\n return descriptor.maxQuiet === undefined ? undefined : Math.max(1, descriptor.maxQuiet);\n}\n\nfunction seconds(ms: Duration): string {\n return `${Math.round(ms / 1000)} s`;\n}\n","/**\n * The lateness of a source that carries the messages of another source. FEMA IPAWS carries each NWS\n * warning for Wireless Emergency Alerts. Its feed can be quiet for hours in normal work, so the quiet\n * timer of the health cannot show that it stopped. An expectation tells which reports of one source\n * the other source carries. When the copy of such a report does not come in time, the second source\n * is late.\n *\n * The functions are pure folds over the merge state and the time. They read no clock. The limit of\n * the delay comes from the measured delays as the upper bound of a quantile (`delayLimit`). The count\n * of misses that makes a source late comes from the measured rate of the misses (`missLimit`). No\n * person sets a time or a count.\n *\n * One record of decisions (`decide`) gives each check its deadline at its start. A copy that missed\n * its deadline enters the sample at its limit. So a lag does not teach the limit.\n */\nimport { clopperPearson, quantileInterval } from \"@mark1russell7/rigor-statistics\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { hasKind } from \"./assess.ts\";\nimport type { Duration, Incident, Instant, MergeState, Operation, Report, ReportId, SourceId, Status } from \"./contracts.ts\";\n\n/** The reports of a source that start an expectation. Each field that is present must hold. */\nexport interface ReportFilter {\n readonly statuses?: readonly Status[];\n readonly ops?: readonly Operation[];\n /** The prefixes of the taxonomy codes. */\n readonly kinds?: readonly string[];\n /** The names of the parameters that the report must have, each with one value or more. */\n readonly parameters?: readonly string[];\n /**\n * The systems of the correlation keys that the report must have, each with one key or more. An expectation that\n * joins its copies by a key thus does not check a report of an older map with no such key.\n */\n readonly correlation?: readonly string[];\n}\n\n/**\n * A source that carries a copy of some reports of another source. The two copies must be in one\n * incident, so the second source must give a correlation key of the first, for example the VTEC key.\n */\nexport interface Expectation {\n readonly id: string;\n /** The source of the first copy. */\n readonly from: SourceId;\n /** The source that carries the second copy. */\n readonly to: SourceId;\n readonly when: ReportFilter;\n /**\n * The start of the record of the expectation. `lateness` reads only the checks that start at this\n * time or later. An operator sets it after a change of a source, so the old record does not teach the limit.\n */\n readonly since?: Instant;\n}\n\n/**\n * One check of an expectation for one message of the source `from`. A message is the reports of `from`\n * in one incident with one sent time that pass the filter.\n */\nexport interface Carriage {\n readonly expectation: string;\n /** The first report of the message. Its id is the key of the check. */\n readonly report: ReportId;\n /** The time when that report came. */\n readonly started: Instant;\n /**\n * The time when the copy came: the first report of the source `to` in the incident with the same sent\n * time. It is absent when no copy came.\n */\n readonly arrived?: Instant;\n}\n\n/** The quantile and the level of the limits of an expectation. The policy of the runtime gives them. */\nexport interface DelayLimitOptions {\n /** The quantile of the delays, for example `0.99`. In normal work, a smaller part than `1 - quantile` of the copies comes after the limit. */\n readonly quantile: number;\n /**\n * The level of confidence of the upper bounds, for example `0.95`. In normal work, a run of misses\n * that makes the source late comes with a chance of `1 - level` or less.\n */\n readonly level: number;\n}\n\n/** The limits of one expectation at one time. */\nexport interface LatenessLimit {\n /** The limit of the delay of a copy, in milliseconds. A check passes its limit at `started + delay`. */\n readonly delay: Duration;\n /** The count of misses after the last check that came that makes the source late. It is 1 or more. */\n readonly misses: number;\n}\n\n/**\n * The misses of the past of one expectation. A trial is a check that passed its limit, after a check\n * that met its limit. The first check is also a trial. A miss is a trial with no copy by its limit.\n */\nexport interface MissRecord {\n readonly trials: number;\n readonly misses: number;\n}\n\n/**\n * The state of an expectation at one time.\n *\n * - `no-limit`: the expectation has no limits yet. The check only measures.\n * - `no-data`: no check came, and the misses are fewer than the limit.\n * - `met`: a check came, and the misses after the last check that came are fewer than the limit.\n * - `late`: the count of misses after the last check that came is at the limit or more.\n */\nexport type LatenessState = \"no-limit\" | \"no-data\" | \"met\" | \"late\";\n\n/** The lateness of the source `to` against the source `from` for one expectation. */\nexport interface Lateness {\n readonly expectation: string;\n readonly from: SourceId;\n readonly to: SourceId;\n readonly state: LatenessState;\n readonly limit?: LatenessLimit;\n /** The checks that passed their limit with no copy, after the last check that came, from the earliest. */\n readonly missed: readonly ReportId[];\n /** The time when the miss that made the source late passed its limit. */\n readonly since?: Instant;\n /** The next time when a check passes its limit. The runtime starts `lateness` again at that time. */\n readonly wakeAt?: Instant;\n}\n\n/** This function tells if a report passes a filter. */\nexport function reportPasses(filter: ReportFilter, report: Report): boolean {\n return (\n (filter.statuses === undefined || filter.statuses.includes(report.status)) &&\n (filter.ops === undefined || filter.ops.includes(report.op)) &&\n (filter.kinds === undefined || hasKind(filter.kinds, report.kind.code)) &&\n (filter.parameters ?? []).every((name) => (report.parameters[name]?.length ?? 0) > 0) &&\n (filter.correlation ?? []).every((system) => report.correlation.some((key) => key.system === system))\n );\n}\n\n/**\n * This function gives one check for each expectation and each message of `from`. The copy of a message\n * is the first report of `to` in the incident with the same sent time. Thus each message of an event,\n * for example an extension, has its own check, and a copy of a different message is not its copy.\n *\n * Two reports of `from` with one sent time in one incident are one message, and they give one check.\n * The result is a function of the set of reports, so the order of the reports does not change it. A\n * copy that came first gives a check with `arrived` before `started`.\n */\nexport function carriages(state: MergeState, found: readonly Incident[], expectations: readonly Expectation[]): Carriage[] {\n const byId = new Map(state.reports.map((report) => [report.id, report]));\n const checks: Carriage[] = [];\n for (const incident of found) {\n const reports = incident.reports.flatMap((id) => byId.get(id) ?? []);\n for (const expectation of expectations) {\n const copies = bySent(reports.filter((report) => report.source === expectation.to));\n for (const [sent, message] of bySent(reports.filter((report) => report.source === expectation.from && reportPasses(expectation.when, report)))) {\n const first = firstOf(message);\n if (first === undefined) continue;\n const copy = firstOf(copies.get(sent) ?? []);\n checks.push({ expectation: expectation.id, report: first.id, started: first.received, ...(copy === undefined ? {} : { arrived: copy.received }) });\n }\n }\n }\n return checks.sort((a, b) => compareCodeUnits(a.expectation, b.expectation) || a.started - b.started || compareCodeUnits(a.report, b.report));\n}\n\n/**\n * This function gives the limit of the delay: the distribution-free upper bound of the quantile of\n * the delays in a sample, from `quantileInterval` of `@mark1russell7/rigor-statistics`. A sample that is\n * too small has no upper bound, and the function gives `undefined`. Then the check only measures.\n *\n * The sample comes from `decide`. A copy that missed its deadline enters at the limit of its check, so\n * a lag of the copies does not raise the limit. The limit is not less than 0.\n */\nexport function delayLimit(delays: readonly Duration[], options: DelayLimitOptions): Duration | undefined {\n if (delays.length === 0) return undefined;\n const { high } = quantileInterval(delays, options.quantile, options.level);\n return Number.isFinite(high) ? Math.max(0, high) : undefined;\n}\n\n/**\n * The outcome of one check in the record of an expectation.\n *\n * - `met`: the copy came by the deadline of the check.\n * - `missed`: the deadline passed with no copy, or the copy came after the deadline.\n * - `open`: the deadline is after the time, and no copy came yet.\n * - `measured`: no limit was in force at the start of the check, and its copy came. The check has no deadline.\n * - `waiting`: no limit was in force at the start of the check, and no copy came yet.\n */\nexport type CheckOutcome = \"met\" | \"missed\" | \"open\" | \"measured\" | \"waiting\";\n\n/** One check in the record of an expectation. */\nexport interface Decision {\n readonly check: Carriage;\n /** The limit of the delay in force at the start of the check. The deadline is `started + limit`. It is absent when no limit was in force. */\n readonly limit?: Duration;\n readonly outcome: CheckOutcome;\n /** The time of the decision: the copy, or the deadline. It is absent for an open or a waiting check. */\n readonly decided?: Instant;\n /** The value that the check gives to the sample of the delays. It is absent for an open or a waiting check. */\n readonly sample?: Duration;\n}\n\n/** The rule of the two limits: the limit of the delay from a sample, and the count of misses from a record of misses. */\nexport interface LimitRule {\n readonly delay: (sample: readonly Duration[]) => Duration | undefined;\n readonly misses: (record: MissRecord) => number | undefined;\n}\n\n/** This function gives the measured rule of the limits: `delayLimit` and `missLimit` with the quantile and the level of the policy. */\nexport function limitRule(options: DelayLimitOptions): LimitRule {\n return { delay: (sample) => delayLimit(sample, options), misses: (record) => missLimit(record, options.level) };\n}\n\n/** A decision that has its time, before its value goes into the sample. */\ninterface Queued {\n readonly index: number;\n readonly time: Instant;\n readonly decision: Omit<Decision, \"sample\">;\n readonly value: Duration;\n}\n\n/**\n * This function gives the record of one expectation at the time `at`. The record has one decision for\n * each check that started by `at`, in the order of the start. It is a fold over the time. After each decision,\n * `limitOf` gives the limit in force from the sample.\n *\n * - The deadline of a check is fixed at its start: `started + limit`, with the limit in force at that time.\n * A later change of the limit does not move it, so no step of the fold goes back in time.\n * - A met check gives its delay to the sample. A missed check gives its limit, because its delay is\n * known only to be more than the limit (right-censored). Thus a lag or a backlog does not raise the limit.\n * - A check with no limit at its start gives its delay. When a limit is in force at the time of its copy,\n * the value is clipped at that limit.\n * - A decision at the time of a start goes into the sample after that start.\n *\n * With the measured rule, each limit after the first limit is at most the first limit. Thus a lasting\n * rise of the normal delay shows as a lasting late state. A copy that came after `at` does not count.\n * The result is a function of the set of checks. Each decision calculates the limit again with `limitOf`.\n * `decideStep` continues an earlier fold at a lower cost.\n */\nexport function decide(checks: readonly Carriage[], expectation: string, at: Instant, limitOf: (sample: readonly Duration[]) => Duration | undefined): Decision[] {\n return [...decideStep(undefined, checks, expectation, at, limitOf).record];\n}\n\n/**\n * The state of the fold of one expectation at one time: the record, the sample and the limit after\n * each decision by that time. `decideStep` continues it at a later time.\n */\nexport interface DecideState {\n readonly expectation: string;\n readonly at: Instant;\n readonly limitOf: (sample: readonly Duration[]) => Duration | undefined;\n /** The record at `at`: one decision for each check that started by `at`, in the order of the start. */\n readonly record: readonly Decision[];\n /** The values of the sample, in the order of their decisions. */\n readonly sample: readonly Duration[];\n /** The limit in force after the last decision. */\n readonly limit: Duration | undefined;\n}\n\n/** The record of one expectation at one time, and the state of its fold. */\nexport interface DecideStep {\n readonly record: readonly Decision[];\n readonly state: DecideState;\n}\n\n/**\n * This function gives the record of `decide`, and continues the state `before` of an earlier fold when\n * the state agrees with the checks. The record is the same with or without the state. Only the cost changes.\n *\n * The state agrees with the checks on three conditions. Its expectation and its `limitOf` are the same.\n * Its time is not after `at`. The checks that started by its time are the same: each has the same report,\n * start and copy by that time. A check that starts after the time of the state is new.\n *\n * A decision by the time of the state does not change, because each of its inputs is the same. Thus\n * the fold decides again only the open and the waiting checks of the state, and then it folds the new\n * checks. Each new decision comes after the time of the state, thus after each decision of the state.\n * The cost is one call of `limitOf` for each new decision. When the state does not agree, the fold starts again.\n */\nexport function decideStep(\n before: DecideState | undefined,\n checks: readonly Carriage[],\n expectation: string,\n at: Instant,\n limitOf: (sample: readonly Duration[]) => Duration | undefined,\n): DecideStep {\n const own = checks\n .filter((check) => check.expectation === expectation && check.started <= at)\n .sort((a, b) => a.started - b.started || compareCodeUnits(a.report, b.report));\n const kept = before !== undefined && agrees(before, own, expectation, at, limitOf) ? before : undefined;\n // Each decision of the state takes the check of this fold, thus the record is the record of the fold from the start.\n const record: Decision[] = kept === undefined ? [] : kept.record.map((entry, index) => ({ ...entry, check: own[index]! }));\n const sample: Duration[] = kept === undefined ? [] : [...kept.sample];\n let limit = kept === undefined ? limitOf(sample) : kept.limit;\n const queue: Queued[] = [];\n const apply = ({ index, decision, value }: Queued): void => {\n const entry = decision.outcome === \"measured\" && limit !== undefined ? Math.min(value, limit) : value;\n record[index] = { ...decision, sample: entry };\n sample.push(entry);\n limit = limitOf(sample);\n };\n // The decision of one check with the limit in force at its start.\n const judge = (check: Carriage, index: number, start: Duration | undefined): void => {\n const came = check.arrived !== undefined && check.arrived <= at ? check.arrived : undefined;\n const base = { check, ...(start === undefined ? {} : { limit: start }) };\n if (start === undefined) {\n if (came === undefined) record[index] = { ...base, outcome: \"waiting\" };\n else {\n const time = Math.max(came, check.started);\n enqueue(queue, { index, time, decision: { ...base, outcome: \"measured\", decided: time }, value: came - check.started });\n }\n return;\n }\n const deadline = check.started + start;\n if (came !== undefined && came <= deadline) {\n const time = Math.max(came, check.started);\n enqueue(queue, { index, time, decision: { ...base, outcome: \"met\", decided: time }, value: came - check.started });\n } else if (deadline <= at) {\n enqueue(queue, { index, time: deadline, decision: { ...base, outcome: \"missed\", decided: deadline }, value: start });\n } else {\n record[index] = { ...base, outcome: \"open\" };\n }\n };\n // An open or a waiting check of the state keeps its limit. Its copy or its deadline can come after the time of the state.\n kept?.record.forEach((entry, index) => {\n if (entry.outcome === \"open\" || entry.outcome === \"waiting\") judge(own[index]!, index, entry.limit);\n });\n const first = record.length;\n for (let index = first; index < own.length; index += 1) {\n const check = own[index]!;\n while (queue[0] !== undefined && queue[0].time < check.started) apply(queue.shift()!);\n judge(check, index, limit);\n }\n while (queue[0] !== undefined) apply(queue.shift()!);\n return { record, state: { expectation, at, limitOf, record, sample, limit } };\n}\n\n/** This function tells if the state of a fold agrees with `own`, the sorted checks of the expectation at the time `at`. */\nfunction agrees(state: DecideState, own: readonly Carriage[], expectation: string, at: Instant, limitOf: (sample: readonly Duration[]) => Duration | undefined): boolean {\n if (state.expectation !== expectation || state.limitOf !== limitOf || state.at > at || state.record.length > own.length) return false;\n const next = own[state.record.length];\n if (next !== undefined && next.started <= state.at) return false;\n // The copy of a check by the time of the state. A copy after that time is new.\n const came = (check: Carriage): Instant | undefined => (check.arrived !== undefined && check.arrived <= state.at ? check.arrived : undefined);\n return state.record.every(({ check }, index) => {\n const now = own[index]!;\n return now.report === check.report && now.started === check.started && came(now) === came(check);\n });\n}\n\n/** This function puts a decision in the queue, sorted by its time and then by the order of the start. */\nfunction enqueue(queue: Queued[], item: Queued): void {\n let at = queue.length;\n while (at > 0 && (queue[at - 1]!.time > item.time || (queue[at - 1]!.time === item.time && queue[at - 1]!.index > item.index))) at -= 1;\n queue.splice(at, 0, item);\n}\n\n/**\n * This function gives the misses of the past from the record of an expectation. A trial is a decided\n * check after a check whose copy came. The first decided check is also a trial. A miss is a missed\n * check. Thus a long stop of the source counts as one miss, and does not raise the normal rate of the\n * misses. A copy after its deadline is a miss.\n */\nexport function missRecord(record: readonly Decision[]): MissRecord {\n let trials = 0;\n let misses = 0;\n let afterMet = true;\n for (const { outcome } of record) {\n if (outcome === \"open\" || outcome === \"waiting\") continue;\n const met = outcome !== \"missed\";\n if (afterMet) {\n trials += 1;\n if (!met) misses += 1;\n }\n afterMet = met;\n }\n return { trials, misses };\n}\n\n/**\n * This function gives the count of misses in a row that makes the source late. The count is the\n * smallest k with `high ** k <= 1 - level`. `high` is the upper bound of the rate of the misses, from\n * `clopperPearson` of `@mark1russell7/rigor-statistics`.\n *\n * Thus in normal work, k misses in a row come with a chance of `1 - level` or less. A source that\n * stops misses each check, so it is late after k checks. The function gives `undefined` when the\n * bound is 1, for example with no trials. Then `lateness` only measures.\n */\nexport function missLimit(record: MissRecord, level: number): number | undefined {\n const { high } = clopperPearson(record.misses, record.trials, level);\n if (!(high < 1)) return undefined;\n const alpha = 1 - level;\n if (high <= alpha) return 1;\n // The logarithms give the count, and the loop corrects an error of rounding at a whole number.\n let k = Math.max(1, Math.ceil(Math.log(alpha) / Math.log(high)));\n while (k > 1 && high ** (k - 1) <= alpha) k -= 1;\n while (high ** k > alpha) k += 1;\n return k;\n}\n\n/**\n * This function gives the state of each expectation at the time `at`. The record of each expectation\n * (`decide`) and the rule give its limits: the delay from the whole sample, and the count of misses\n * from `missRecord`. Each check is judged by its own deadline.\n *\n * A copy after its deadline is a miss, so a lag of the copies keeps the source late. The first met\n * check after the misses ends them, because it shows that the source carries the reports in time again.\n * A check that starts before the `since` of its expectation is not in the record.\n */\nexport function lateness(checks: readonly Carriage[], expectations: readonly Expectation[], at: Instant, rule: LimitRule): Lateness[] {\n return latenessStep(checks, expectations, at, rule).lateness;\n}\n\n/** The states of the folds of `lateness` at one time, by the id of the expectation. */\nexport type LatenessFolds = ReadonlyMap<string, DecideState>;\n\n/** The state of each expectation at one time, and the folds that the next step continues. */\nexport interface LatenessStep {\n readonly lateness: Lateness[];\n readonly folds: LatenessFolds;\n}\n\n/**\n * This function gives the states of `lateness`, and the fold of each expectation continues its fold in\n * `before` (`decideStep`). The states are the same with or without `before`. Only the cost changes.\n * Thus a runtime keeps the folds of each pass for the next pass, and a pass folds only the new checks.\n * The `delay` function of the rule must be the same in each step, or each fold starts again.\n */\nexport function latenessStep(checks: readonly Carriage[], expectations: readonly Expectation[], at: Instant, rule: LimitRule, before?: LatenessFolds): LatenessStep {\n const folds = new Map<string, DecideState>();\n const states = expectations.map((expectation): Lateness => {\n const base = { expectation: expectation.id, from: expectation.from, to: expectation.to };\n const start = expectation.since;\n const { record, state: fold } = decideStep(before?.get(expectation.id), start === undefined ? checks : checks.filter((check) => check.started >= start), expectation.id, at, rule.delay);\n folds.set(expectation.id, fold);\n const deadlines = record.flatMap((entry) => (entry.outcome === \"open\" && entry.limit !== undefined ? [entry.check.started + entry.limit] : []));\n const wake = deadlines.length === 0 ? {} : { wakeAt: deadlines.reduce((a, b) => Math.min(a, b)) };\n const delay = rule.delay(record.flatMap((entry) => (entry.sample === undefined ? [] : [entry.sample])));\n const misses = delay === undefined ? undefined : rule.misses(missRecord(record));\n if (delay === undefined || misses === undefined) return { ...base, state: \"no-limit\", missed: [], ...wake };\n const lastMet = record.reduce((last, entry) => (entry.outcome === \"met\" || entry.outcome === \"measured\" ? Math.max(last, entry.check.started) : last), Number.NEGATIVE_INFINITY);\n const missed = record.filter((entry) => entry.outcome === \"missed\" && entry.check.started > lastMet);\n // A count below 1 is not valid, and 1 is the safe side: the first miss makes the source late.\n const needed = Math.max(1, Math.ceil(misses));\n const late = missed.length >= needed;\n const state: LatenessState = late ? \"late\" : lastMet > Number.NEGATIVE_INFINITY ? \"met\" : \"no-data\";\n const since = late ? missed.map((entry) => entry.decided!).sort((a, b) => a - b)[needed - 1] : undefined;\n return {\n ...base,\n state,\n limit: { delay, misses },\n missed: missed.map((entry) => entry.check.report),\n ...(since === undefined ? {} : { since }),\n ...wake,\n };\n });\n return { lateness: states, folds };\n}\n\n/** This function gives the sources that are late, sorted. The coverage does not count them. */\nexport function lateSources(states: readonly Lateness[]): SourceId[] {\n return [...new Set(states.filter((entry) => entry.state === \"late\").map((entry) => entry.to))].sort(compareCodeUnits);\n}\n\n// The reports by their sent time.\nfunction bySent(reports: readonly Report[]): Map<Instant, Report[]> {\n const groups = new Map<Instant, Report[]>();\n for (const report of reports) groups.set(report.sent, [...(groups.get(report.sent) ?? []), report]);\n return groups;\n}\n\n// The first report: the earlier time first, then the smaller id.\nfunction firstOf(reports: readonly Report[]): Report | undefined {\n let first: Report | undefined;\n for (const report of reports) {\n if (first === undefined || report.received < first.received || (report.received === first.received && compareCodeUnits(report.id, first.id) < 0)) first = report;\n }\n return first;\n}\n","/**\n * The measure of the copies of an expectation (AL-8). The core finds the copy of a message by its incident and by\n * its sent time, to the millisecond (`carriages`). A copy with a different sent time is not a copy for the core, so\n * its check is a miss. The functions of this module give a class to each check, and the delay of each copy. Thus a\n * measure over real reports shows if a source carries the messages of another source, before the runtime uses the\n * expectation.\n *\n * The functions are pure. They read no clock and no network. A script gives them the reports of the two sources,\n * from the history of the sources or from the log of a runtime.\n */\n\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { Duration, Instant, Report, ReportId } from \"./contracts.ts\";\nimport { carriages, type Expectation } from \"./lateness.ts\";\nimport { incidents, normalize, type LinkRule } from \"./merge.ts\";\n\n/**\n * The class of one message of the source `from` in the measure.\n *\n * - `same`: the incident of the message has a copy with the same sent time. The check of the core finds it.\n * - `shifted`: the incident has the copy with the key of the copy, but at a different sent time. The check of the core is a miss.\n * - `lost`: the incident has copies, but no copy with the key of the copy and no copy at its sent time. The check of the core is a miss.\n * - `apart`: the incident has no copy, but a copy with the key of the copy is in a different incident.\n * - `none`: the reports have no copy of the message.\n * - `censored`: the message comes after the censor time, and no copy has its sent time. Its copy can come later.\n *\n * The class `lost` is a different fault from `shifted`, for example the lost copy of an extension.\n */\nexport type SentClass = \"same\" | \"shifted\" | \"lost\" | \"apart\" | \"none\" | \"censored\";\n\n/** One report of the source `to`: its key and its sent time. */\nexport interface CopyTime {\n /** The key of the report, for example the CAP identifier of the copy. */\n readonly key: string;\n readonly sent: Instant;\n}\n\n/** One message of the source `from` that the expectation checks, and its class. */\nexport interface SentCheck {\n /** The id of the first report of the message. It is the key of the check of the core. */\n readonly report: ReportId;\n /** The key of that report, for example the CAP identifier of the message. */\n readonly key: string;\n /** The event of the message, from the option `eventOf`. */\n readonly event: string;\n readonly sent: Instant;\n readonly class: SentClass;\n /** The reports of the source `to` in the incident of the message, from the earliest sent time. */\n readonly copies: readonly CopyTime[];\n /**\n * The time of the copy minus the time of the first report of the message, in milliseconds, for the class `same`.\n * A copy that came first gives a value below 0.\n */\n readonly delay?: Duration;\n}\n\n/** A message with a copy, but with no copy at its sent time: the pair of the message and its copy. */\nexport interface SentGap {\n readonly report: ReportId;\n readonly key: string;\n readonly event: string;\n readonly sent: Instant;\n readonly class: \"shifted\" | \"lost\" | \"apart\";\n /** The copy: the copy with the key of the copy, or for the class `lost` the copy of the incident with the nearest sent time. */\n readonly copy: CopyTime;\n /** The rule that found the copy: the key of the copy (`shifted` and `apart`), or the nearest sent time (`lost`). */\n readonly match: \"id\" | \"nearest\";\n /** The sent time of the copy minus the sent time of the message, in milliseconds. */\n readonly difference: Duration;\n}\n\n/** The count of the messages of each class. The sum of `shifted` and `lost` must be 0 (`sentFails`). */\nexport interface SentCounts {\n readonly messages: number;\n readonly same: number;\n /** The messages with the copy with the key of the copy in the incident, at a different sent time. The sum of `shifted` and `lost` must be 0. */\n readonly shifted: number;\n /** The messages with copies in the incident, but no copy with the key of the copy and no copy at their sent time. The sum of `shifted` and `lost` must be 0. */\n readonly lost: number;\n readonly apart: number;\n readonly none: number;\n readonly censored: number;\n}\n\n/** The result of the measure. */\nexport interface SentMeasure {\n readonly counts: SentCounts;\n /** The checks, in the order of their sent times. */\n readonly checks: readonly SentCheck[];\n /** The messages of the classes `shifted`, `lost` and `apart`, each with its copy, in the order of their sent times. */\n readonly gaps: readonly SentGap[];\n}\n\n/** The options of `copyMeasure`. */\nexport interface CopyMeasureOptions {\n /**\n * The censor time. A message with a later sent time and no copy at its sent time is censored,\n * because its copy can come after the data. With no censor time, no message is censored.\n */\n readonly censorAfter?: Instant;\n /** This function gives the key of the copy of a message from the key of the message. The default gives the same key. */\n readonly copyKey?: (key: string) => string;\n /** This function gives the event of a message for the checks. The default is the code of the kind of the report. */\n readonly eventOf?: (report: Report) => string;\n /** The link rule of the incidents, as in the runtime. With no rule, the incidents use the merge rules 1 and 2 only. */\n readonly link?: LinkRule;\n}\n\n/**\n * This function measures the copies of an expectation over the reports of the two sources. It uses the path of the\n * core: `normalize`, `incidents` and `carriages` with the expectation. Then it gives a class to each check with no\n * copy, from the reports of the source `to` in the same incident.\n *\n * - A check that starts before the `since` of the expectation is not in the result, as in `lateness`.\n * - The result is a function of the set of reports, so the order of the reports does not change it.\n */\nexport function copyMeasure(reports: readonly Report[], expectation: Expectation, options: CopyMeasureOptions = {}): SentMeasure {\n const copyKey = options.copyKey ?? ((key: string): string => key);\n const eventOf = options.eventOf ?? ((report: Report): string => report.kind.code);\n const state = normalize({ reports });\n // The groups of the incidents do not use the time. The time is the latest receipt, so the result reads no clock.\n const at = state.reports.reduce((latest, report) => Math.max(latest, report.received), 0);\n const found = incidents(state, at, options.link === undefined ? {} : { link: options.link });\n const byId = new Map(state.reports.map((report) => [report.id, report]));\n const copiesOf = new Map<ReportId, CopyTime[]>();\n for (const incident of found) {\n const copies = incident.reports\n .flatMap((id) => byId.get(id) ?? [])\n .filter((report) => report.source === expectation.to)\n .map((report) => ({ key: report.key, sent: report.sent }))\n .sort(byTime);\n for (const id of incident.reports) copiesOf.set(id, copies);\n }\n const byKey = new Map<string, CopyTime>();\n for (const report of state.reports) {\n if (report.source !== expectation.to) continue;\n const held = byKey.get(report.key);\n if (held === undefined || byTime({ key: report.key, sent: report.sent }, held) < 0) byKey.set(report.key, { key: report.key, sent: report.sent });\n }\n\n const checks: SentCheck[] = [];\n const gaps: SentGap[] = [];\n for (const check of carriages(state, found, [expectation])) {\n if (expectation.since !== undefined && check.started < expectation.since) continue;\n const report = byId.get(check.report);\n if (report === undefined) continue;\n const copies = copiesOf.get(report.id) ?? [];\n const own = byKey.get(copyKey(report.key));\n const base = { report: report.id, key: report.key, event: eventOf(report), sent: report.sent };\n if (check.arrived !== undefined) {\n checks.push({ ...base, class: \"same\", copies, delay: check.arrived - check.started });\n continue;\n }\n let kind: SentClass;\n if (options.censorAfter !== undefined && report.sent > options.censorAfter) kind = \"censored\";\n else if (copies.length > 0) {\n const byIdInIncident = copies.find((copy) => copy.key === own?.key);\n if (byIdInIncident !== undefined) {\n kind = \"shifted\";\n gaps.push({ ...base, class: kind, copy: byIdInIncident, match: \"id\", difference: byIdInIncident.sent - report.sent });\n } else {\n kind = \"lost\";\n const copy = nearest(copies, report.sent);\n gaps.push({ ...base, class: kind, copy, match: \"nearest\", difference: copy.sent - report.sent });\n }\n } else if (own !== undefined) {\n kind = \"apart\";\n gaps.push({ ...base, class: kind, copy: own, match: \"id\", difference: own.sent - report.sent });\n } else kind = \"none\";\n checks.push({ ...base, class: kind, copies });\n }\n const order = (a: { sent: Instant; key: string }, b: { sent: Instant; key: string }): number => a.sent - b.sent || compareCodeUnits(a.key, b.key);\n checks.sort(order);\n gaps.sort(order);\n const count = (kind: SentClass): number => checks.filter((check) => check.class === kind).length;\n return {\n counts: {\n messages: checks.length,\n same: count(\"same\"),\n shifted: count(\"shifted\"),\n lost: count(\"lost\"),\n apart: count(\"apart\"),\n none: count(\"none\"),\n censored: count(\"censored\"),\n },\n checks,\n gaps,\n };\n}\n\n/**\n * This function tells if the counts of a measure show a fault: the sum of `shifted` and `lost` is above 0.\n * The classes `same`, `apart`, `none` and `censored` do not change the result.\n */\nexport function sentFails(counts: SentCounts): boolean {\n return counts.shifted + counts.lost > 0;\n}\n\n// The copy with the nearest sent time. A tie goes to the earlier copy. The list is not empty.\nfunction nearest(copies: readonly CopyTime[], sent: Instant): CopyTime {\n return copies.reduce((best, copy) => (Math.abs(copy.sent - sent) < Math.abs(best.sent - sent) ? copy : best));\n}\n\n// The order of the copies: the earlier sent time first, then the smaller key.\nfunction byTime(a: CopyTime, b: CopyTime): number {\n return a.sent - b.sent || compareCodeUnits(a.key, b.key);\n}\n","/**\n * The link rule of the merge (rule 3) for the kinds of events with a point and a time, for example the\n * earthquakes. Two sources can report one real event with different ids. Then no reference and no\n * correlation key joins their reports, and the person gets two alerts for one event. This rule joins them\n * by their onsets, their points and their magnitudes.\n *\n * The rule is on the safe side. A false join can hide a second event after an acknowledgment, but a\n * false split gives only a second alert. Thus a report with no onset, no circle area or no magnitude\n * (when the family has a limit of the magnitude) links to no report. Two reports of one source do not\n * link: a source that gives two ids tells of two events.\n *\n * The rule compares two reports at a time, and the incidents are the connected components. So a chain\n * can join two real events: an event of one source between two events of another source joins the\n * three. This is a known limit (`docs/CONTRACTS.md`). A pairwise rule only joins incidents when a report\n * comes. It does not split an incident, so a sent alert stays with its incident.\n */\n\nimport { distanceKm, GeoError } from \"@mark1russell7/geo\";\nimport { hasKind } from \"./assess.ts\";\nimport type { Instant, Report } from \"./contracts.ts\";\nimport type { LinkRule } from \"./merge.ts\";\n\n/** The link of one family of kinds: the largest differences of two reports of one real event. */\nexport interface LinkFamily {\n /** A taxonomy code or a prefix of codes. A report is in the family when the code of its kind has this prefix by parts. */\n readonly family: string;\n /** The largest time between the onsets of two reports, in milliseconds. It is more than 0. */\n readonly windowMs: number;\n /** The largest great-circle distance between the centers of the circle areas of two reports, in kilometers. */\n readonly distanceKm: number;\n /** The largest difference of the parameter `magnitude` of two reports. When it is absent, the rule does not read the magnitude. */\n readonly magnitude?: number;\n}\n\n/** The policy of the link rule: each family of kinds that links, with its limits. */\nexport interface LinkPolicy {\n readonly families: readonly LinkFamily[];\n}\n\n/**\n * The first policy, with two families.\n *\n * Two earthquake reports link when their onsets are 30 s apart or less, their epicenters 100 km apart or less, and\n * their magnitudes 1.0 apart or less. One capture of EMSC and USGS (2026-11-16) matched each of its 30 shared events\n * at 20 s and 100 km. The largest time difference was 6.3 s.\n *\n * Two reports of a geomagnetic storm link when their onsets are 6 hours apart or less. Each source of the family\n * gives the polar caps of one model of the poles. Thus the centers are 0 km apart. The limit of 100 km keeps a\n * different model.\n *\n * A replay of the years 2015 to 2025 measured the window (`scripts/measure-link.ts` of the GFZ source). At 6 hours,\n * 457 of the 460 runs of GFZ join the SWPC, and 447 join at 3 hours. Each of the 3 other runs has one interval, 6.3\n * to 9 hours from a storm report of the SWPC. A larger window puts more runs of GFZ in one incident, through the\n * chains of keys of the SWPC. There are 55 such pairs at 6 hours, and 24 at 5 hours. The gate `link.test.ts` of the\n * GFZ source holds two of these storms.\n */\nexport const DEFAULT_LINK_POLICY: LinkPolicy = {\n families: [\n { family: \"geo.earthquake\", windowMs: 30_000, distanceKm: 100, magnitude: 1 },\n { family: \"geo.space-weather.geomagnetic-storm\", windowMs: 6 * 3_600_000, distanceKm: 100 },\n ],\n};\n\n/** The name of the parameter of a report that holds its magnitude. */\nexport const MAGNITUDE_PARAMETER = \"magnitude\";\n\n// The magnitudes have one or two decimals, so 3.1 - 2.1 is 1.0000000000000002. This margin keeps a difference of 1.0 in the limit.\nconst MAGNITUDE_MARGIN = 1e-9;\n\n/** The facts of a report that the link of one family reads. */\ninterface Facts {\n readonly onset: Instant;\n readonly centers: readonly { readonly lat: number; readonly lon: number }[];\n readonly magnitude?: number;\n}\n\n/** This function gives the number of a decimal text, for example `4.5` or `-0.3`. Each other text gives `undefined`. */\nfunction decimal(text: string | undefined): number | undefined {\n return text !== undefined && /^-?\\d+(\\.\\d+)?$/.test(text) ? Number(text) : undefined;\n}\n\n/** This function gives the facts of a report for one family. A report that is not in the family, or that has a missing fact, gives `undefined`. */\nfunction factsOf(report: Report, family: LinkFamily): Facts | undefined {\n if (!hasKind([family.family], report.kind.code) || report.onset === undefined) return undefined;\n const centers = report.areas.flatMap((area) => (area.type === \"circle\" ? [{ lat: area.center[1], lon: area.center[0] }] : []));\n if (centers.length === 0) return undefined;\n if (family.magnitude === undefined) return { onset: report.onset, centers };\n const values = report.parameters[MAGNITUDE_PARAMETER];\n const magnitude = values?.length === 1 ? decimal(values[0]) : undefined;\n return magnitude === undefined ? undefined : { onset: report.onset, centers, magnitude };\n}\n\n/** This function tells if a center of one list and a center of the other are no farther apart than the limit. A point that is not valid is not near. */\nfunction near(a: Facts[\"centers\"], b: Facts[\"centers\"], limitKm: number): boolean {\n return a.some((x) =>\n b.some((y) => {\n try {\n return distanceKm(x, y) <= limitKm;\n } catch (error) {\n if (error instanceof GeoError) return false;\n throw error;\n }\n }),\n );\n}\n\n/** This function tells if two reports of one family tell of one real event. */\nfunction linked(a: Report, b: Report, family: LinkFamily): boolean {\n const x = factsOf(a, family);\n const y = factsOf(b, family);\n if (x === undefined || y === undefined) return false;\n if (Math.abs(x.onset - y.onset) > family.windowMs) return false;\n if (family.magnitude !== undefined && Math.abs(x.magnitude! - y.magnitude!) > family.magnitude + MAGNITUDE_MARGIN) return false;\n return near(x.centers, y.centers, family.distanceKm);\n}\n\n// The rule of each policy object. A policy does not change.\nconst rules = new WeakMap<LinkPolicy, LinkRule>();\n\n/**\n * This function gives the link rule of a policy, for `incidents`.\n *\n * The blocks of a report are, for each family that has its facts, the slot of its onset and the slot\n * before it. A slot is as long as the window of the family. So two onsets in one window are in one slot\n * or in two slots next to each other, and their reports share a block.\n *\n * One policy object gives one rule object. Thus `incidents` keeps the groups of a list of reports for each pass.\n *\n * @throws RangeError when the window of a family is not more than 0\n */\nexport function linkRule(policy: LinkPolicy): LinkRule {\n const held = rules.get(policy);\n if (held !== undefined) return held;\n for (const family of policy.families) {\n if (!(family.windowMs > 0)) throw new RangeError(`The window of the family ${family.family} is not more than 0: ${family.windowMs}.`);\n }\n const rule: LinkRule = {\n blocks: (report) =>\n policy.families.flatMap((family, index) => {\n const facts = factsOf(report, family);\n if (facts === undefined) return [];\n const slot = Math.floor(facts.onset / family.windowMs);\n return [JSON.stringify([\"link\", index, slot]), JSON.stringify([\"link\", index, slot - 1])];\n }),\n matches: (a, b) => a.source !== b.source && policy.families.some((family) => linked(a, b, family)),\n };\n rules.set(policy, rule);\n return rule;\n}\n","/**\n * This module gives the view of the map: the live incidents in the order of their level, with their\n * shapes. The view also gives each watched place with its highest level and its gaps of coverage. The view is a pure\n * calculation. A renderer draws it, and a store of shapes gives the outline of each region code.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { assess, higherLevel, matchPlaces, reachedAssessment } from \"./assess.ts\";\nimport { isPrivate } from \"./audience.ts\";\nimport type { IndicatorBreadth } from \"./breadth.ts\";\nimport {\n ASSESSED_LEVELS,\n type Area,\n type AssessedLevel,\n type Assessment,\n type AssessPolicy,\n type Coverage,\n type Incident,\n type Kind,\n type PersonWatch,\n type PlaceId,\n type Position,\n type RegionCode,\n type ReportId,\n type ScorePriors,\n type Severity,\n type ShadowScore,\n type Instant,\n type Status,\n} from \"./contracts.ts\";\nimport { coverageShort } from \"./coverage.ts\";\nimport { shadowScore } from \"./score.ts\";\nimport { areasWithoutBlocks, distinctShapes } from \"./shapes.ts\";\n\n/** A shape of the map in WGS 84: a polygon or a circle. A region code gets its shapes from the store. */\nexport type MapShape = Extract<Area, { readonly type: \"polygon\" } | { readonly type: \"circle\" }>;\n\n/**\n * This function gives the shapes of a region code, or `undefined` when the store has no shape for it.\n * A region with many parts, for example a county with islands, has many shapes.\n */\nexport type ShapeLookup = (code: RegionCode) => readonly MapShape[] | undefined;\n\n/** A place of the map. The label and the position stay on the machine of the instance. */\nexport interface MapPlaceInput {\n readonly id: PlaceId;\n readonly label: string;\n readonly at?: Position;\n readonly codes: readonly RegionCode[];\n readonly bufferKm: number;\n}\n\n/** These are the inputs of the view of the map. */\nexport interface MapInput {\n /** The incidents of the merge. The view keeps only the live incidents. */\n readonly incidents: readonly Incident[];\n /** The assessments of each person for these incidents. */\n readonly assessments: readonly Assessment[];\n readonly places: readonly MapPlaceInput[];\n /** The coverage of each place and kind. A short entry is a gap at its place. */\n readonly coverage: readonly Coverage[];\n readonly shape: ShapeLookup;\n}\n\n/** An incident on the map. */\nexport interface MapIncident {\n readonly anchor: ReportId;\n /**\n * The status of the incident. A renderer shows each status other than `actual` with a look and a legend entry of its own.\n * Thus a test or an exercise does not look like a real alert.\n */\n readonly status: Status;\n readonly kind: Kind;\n /** The highest level of the incident over each person, or `none` when no person gets it. */\n readonly level: AssessedLevel;\n readonly severity: Severity;\n readonly onset?: Instant;\n readonly expires?: Instant;\n /** The shapes of the areas: each polygon, each circle and the shapes of each region code. Each shape comes one time. */\n readonly shapes: readonly MapShape[];\n /** The region codes of the areas with no shape in the store. The renderer lists them as text. */\n readonly unshaped: readonly RegionCode[];\n /** The watched places in the areas, for each person. */\n readonly places: readonly PlaceId[];\n /**\n * The shadow score of the incident, when the payload has the priors and the incident reaches a person. The score\n * does not change the level.\n */\n readonly shadow?: ShadowScore;\n}\n\n/** A watched place on the map. */\nexport interface MapPlace {\n readonly id: PlaceId;\n readonly label: string;\n readonly at?: Position;\n /**\n * The shapes of the smallest region of the place with a shape: a zone before a county, a county\n * before a state. The list is empty when no code of the place has a shape.\n */\n readonly shapes: readonly MapShape[];\n /**\n * The highest level of the live incidents at the place. An assessment keeps only the highest level\n * of its places. Thus this level is an upper bound when a rule lowers the level at one place.\n */\n readonly level: AssessedLevel;\n /** The anchors of the live incidents at the place, in the order of the view. */\n readonly incidents: readonly ReportId[];\n /** The kinds whose coverage at the place is short. */\n readonly gaps: readonly string[];\n}\n\n/** The view of the map. */\nexport interface MapView {\n /** The live incidents, from the highest level. In one level, the order is the severity, then the anchor. */\n readonly incidents: readonly MapIncident[];\n /** The places, in the order of the input. */\n readonly places: readonly MapPlace[];\n /** Each region code of a live incident with no shape, once, in the order of the system and the code. */\n readonly unshaped: readonly RegionCode[];\n}\n\n/** One region of the basemap: its code, its name and its shapes, from the store of shapes. */\nexport interface MapRegion {\n readonly code: RegionCode;\n readonly name: string;\n readonly shapes: readonly MapShape[];\n}\n\n/**\n * The answer of the map route of the runtime: the view, and the regions of the basemap. The route is on the loopback\n * address only, because the view holds the labels and the positions of the places. The local page draws this answer.\n */\nexport interface MapPayload {\n /** The format of the payload. A page of another format tells the reader to start the runtime of its own version. */\n readonly format: typeof MAP_FORMAT;\n /** The time of the view: the time of the last pass, or `null` before the first pass. */\n readonly at: Instant | null;\n readonly view: MapView;\n /** The regions under the view: the zones and the counties of each watched state, from the store of shapes. */\n readonly basemap: readonly MapRegion[];\n /**\n * The breadth of the indicator signals at the time of the view, in the world and at each place. A runtime with no store\n * of the readings has no field. The breadth is of the last pass, thus a past map of the history has no breadth.\n */\n readonly breadth?: IndicatorBreadth;\n}\n\n/** The name of the format of the map payload. A change that breaks a reader gets a new name. */\nexport const MAP_FORMAT = \"alerts-map/1\";\n\n/** These are the inputs of the payload of the map route. */\nexport interface MapPayloadInput extends Omit<MapInput, \"assessments\"> {\n /** The time of the view: the time of the last pass, or `null` before the first pass. */\n readonly at: Instant | null;\n /** The watches of the people. The payload assesses each live incident for each person at `at`. */\n readonly people: readonly PersonWatch[];\n /** The policy of the assessment: the policy of the delivery. The default is the policy of the core. */\n readonly policy?: AssessPolicy;\n /** The regions under the view, from the store of shapes. */\n readonly basemap: readonly MapRegion[];\n /** The priors of the shadow score. Without them, no incident of the payload has a score. */\n readonly priors?: ScorePriors;\n /**\n * The test of an incident of only the sources of other copies (`foreignIncidents`, AL-76). Thus the level on the map\n * is the level of the route. Without the test, each incident is an incident of this copy.\n */\n readonly foreign?: ((incident: Pick<Incident, \"anchor\" | \"reports\">) => boolean) | undefined;\n /** The breadth of the indicator signals of the last pass. Without it, the payload has no field `breadth`. */\n readonly breadth?: IndicatorBreadth;\n}\n\n// The view with the shadow score of each incident that reaches a person. The score does not change the level.\nfunction withShadow(view: MapView, live: readonly Incident[], priors: ScorePriors): MapView {\n const byAnchor = new Map(live.map((incident) => [incident.anchor, incident]));\n const incidents = view.incidents.map((shown) => {\n const incident = byAnchor.get(shown.anchor);\n return shown.level === \"none\" || incident === undefined ? shown : { ...shown, shadow: shadowScore(incident, priors) };\n });\n return { ...view, incidents };\n}\n\n/**\n * This function gives the payload of the map route. It assesses each live incident for each person with the policy of the\n * delivery. Thus the level on the map is the level that reaches the person. A mute with the effect `absent` gives `none`.\n * With the priors, each incident that reaches a person gets its shadow score.\n */\nexport function mapPayload(input: MapPayloadInput): MapPayload {\n const { at, people, policy, basemap, priors, breadth, foreign, ...given } = input;\n // Each viewer of the page sees the map, so it shows no private incident (AL-92, `audience.ts`).\n const view = { ...given, incidents: given.incidents.filter((incident) => !isPrivate(incident)) };\n const live = view.incidents.filter((incident) => incident.live);\n const assessments = live.flatMap((incident) => people.map((person) => reachedAssessment(assess(incident, person, view.places, policy, at ?? undefined, foreign?.(incident) ?? false))));\n const drawn = mapView({ ...view, assessments });\n return { format: MAP_FORMAT, at, view: priors === undefined ? drawn : withShadow(drawn, live, priors), basemap, ...(breadth === undefined ? {} : { breadth }) };\n}\n\n/** The severities, from the highest. The map and the history sort by this order. */\nexport const SEVERITY_ORDER: readonly Severity[] = [\"extreme\", \"severe\", \"moderate\", \"minor\", \"unknown\"];\n\n/**\n * This function gives the rank of the size of a region code, from the smallest. An NWS forecast zone or fire zone\n * (`KSZ083`) is before an NWS county (`KSC173`), a county before a state, and a state before a country.\n */\nexport function regionRank(code: RegionCode): number {\n switch (code.system) {\n case \"ugc\":\n return code.code[2] === \"Z\" ? 0 : 1;\n case \"ugc-fire\":\n return 0;\n case \"same\":\n case \"fips\":\n return 1;\n case \"state\":\n return 2;\n case \"iso3166\":\n return 3;\n default:\n return 4;\n }\n}\n\n/** This function gives the view of the map. The output does not depend on the order of the incidents or the assessments. */\nexport function mapView(input: MapInput): MapView {\n const levels = new Map<string, AssessedLevel>();\n const placeLevels = new Map<string, AssessedLevel>();\n for (const assessment of input.assessments) {\n levels.set(assessment.incident, higherLevel(levels.get(assessment.incident) ?? \"none\", assessment.level));\n for (const place of assessment.places) placeLevels.set(place, higherLevel(placeLevels.get(place) ?? \"none\", assessment.level));\n }\n\n const unshaped = new Map<string, RegionCode>();\n const incidents = input.incidents\n .filter((incident) => incident.live)\n .map((incident): MapIncident => {\n const shapes: MapShape[] = [];\n const missing: RegionCode[] = [];\n for (const area of areasWithoutBlocks(incident.areas)) {\n if (area.type === \"polygon\" || area.type === \"circle\") shapes.push(area);\n else if (area.type === \"code\") {\n const code = { system: area.system, code: area.code };\n const found = input.shape(code);\n if (found === undefined) {\n missing.push(code);\n unshaped.set(regionCodeKey(code), code);\n } else shapes.push(...found);\n }\n }\n return {\n anchor: incident.anchor,\n status: incident.status,\n kind: incident.kind,\n level: levels.get(incident.anchor) ?? \"none\",\n severity: incident.severity,\n ...(incident.onset === undefined ? {} : { onset: incident.onset }),\n ...(incident.expires === undefined ? {} : { expires: incident.expires }),\n // A zone and its county can give one outline from the store. The renderer draws each shape one time.\n shapes: distinctShapes(shapes),\n unshaped: missing,\n places: matchPlaces(incident, input.places).map((match) => match.place),\n };\n })\n .sort(compareMapIncidents);\n\n const places = input.places.map((place): MapPlace => {\n const gaps = input.coverage.filter((entry) => entry.place === place.id && coverageShort(entry)).map((entry) => entry.kind);\n return {\n id: place.id,\n label: place.label,\n ...(place.at === undefined ? {} : { at: place.at }),\n shapes: smallestShapes(place.codes, input.shape),\n level: placeLevels.get(place.id) ?? \"none\",\n incidents: incidents.filter((incident) => incident.places.includes(place.id)).map((incident) => incident.anchor),\n gaps: [...new Set(gaps)].sort(compareCodeUnits),\n };\n });\n\n return {\n incidents,\n places,\n unshaped: [...unshaped.values()].sort(compareRegionCodes),\n };\n}\n\n/** The shapes of the smallest region of the codes with a shape. In one rank, the first code of the place wins. */\nfunction smallestShapes(codes: readonly RegionCode[], shape: ShapeLookup): readonly MapShape[] {\n const ranked = codes.map((code, index) => ({ code, index, rank: regionRank(code) })).sort((a, b) => a.rank - b.rank || a.index - b.index);\n for (const { code } of ranked) {\n const found = shape(code);\n if (found !== undefined && found.length > 0) return found;\n }\n return [];\n}\n\n/** This function compares two incidents of the map: the higher level first. In one level, the order is the severity, then the anchor. */\nexport function compareMapIncidents(a: MapIncident, b: MapIncident): number {\n return ASSESSED_LEVELS.indexOf(b.level) - ASSESSED_LEVELS.indexOf(a.level) || SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || compareCodeUnits(a.anchor, b.anchor);\n}\n\n/** This function gives the key of a region code: one text for each system and code. Two equal codes give one key. */\nexport function regionCodeKey(code: RegionCode): string {\n return `${code.system}\\u0000${code.code}`;\n}\n\n/** This function compares two region codes by the system, then by the code. */\nexport function compareRegionCodes(a: RegionCode, b: RegionCode): number {\n return compareCodeUnits(a.system, b.system) || compareCodeUnits(a.code, b.code);\n}\n","/**\n * This module makes the basemap small for the map. The outlines of the counties and zones of one state are many megabytes. The\n * page draws them in a view box of 1000 units. A position near the line of its neighbors, at less than half a unit, changes\n * no pixel. The module removes those positions with `simplifyRegions` of `@mark1russell7/geo`. The match of the places\n * does not use this module: it reads the outlines of the store.\n */\nimport { EARTH_MEAN_RADIUS_KM, simplifyRegions, type Region } from \"@mark1russell7/geo\";\nimport type { Position } from \"./contracts.ts\";\nimport { regionRank, type MapRegion, type MapShape } from \"./map.ts\";\n\n/**\n * The view box of the map, in units. The page fits the shapes into the box with the Mercator projection, with `pad` units at\n * each edge.\n */\nexport const MAP_VIEW = { width: 1000, height: 640, pad: 24 } as const;\n\n/** A polygon of the map. */\ntype PolygonShape = Extract<MapShape, { readonly type: \"polygon\" }>;\n\n/** This function gives the Mercator y of a latitude in degrees, in radians. */\nconst mercatorY = (lat: number): number => Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360));\n\n/**\n * This function gives the tolerance of the simplification of a basemap, in kilometres. The tolerance is half of one unit of\n * `MAP_VIEW` at the Mercator fit of the polygons of the regions.\n *\n * - The fit of the page also holds the incidents and the places. A larger fit has larger units, thus this tolerance is on the\n * safe side.\n * - In the Mercator projection, one unit covers the least ground at the latitude farthest from the equator. The function\n * measures the unit at that latitude. Thus a removed position moves the line by half a unit or less at each latitude.\n * - The function gives `undefined` for regions with no polygon, and for longitudes with a span of more than 180 degrees. Such\n * regions cross the antimeridian, and their longitudes are not in one range.\n */\nexport function basemapToleranceKm(regions: readonly MapRegion[]): number | undefined {\n let west = Infinity;\n let east = -Infinity;\n let south = Infinity;\n let north = -Infinity;\n for (const region of regions) {\n for (const shape of region.shapes) {\n if (shape.type !== \"polygon\") continue;\n for (const [lon, lat] of shape.rings.flat()) {\n west = Math.min(west, lon);\n east = Math.max(east, lon);\n south = Math.min(south, lat);\n north = Math.max(north, lat);\n }\n }\n }\n if (west > east || east - west > 180) return undefined;\n const width = ((east - west) * Math.PI) / 180;\n const height = mercatorY(north) - mercatorY(south);\n const scales = [width > 0 ? (MAP_VIEW.width - 2 * MAP_VIEW.pad) / width : Infinity, height > 0 ? (MAP_VIEW.height - 2 * MAP_VIEW.pad) / height : Infinity];\n // The units for each radian of longitude at the fit. A region with no width and no height has no fit.\n const scale = Math.min(...scales);\n if (!Number.isFinite(scale)) return undefined;\n const farthest = Math.max(Math.abs(south), Math.abs(north));\n return (EARTH_MEAN_RADIUS_KM * Math.cos((farthest * Math.PI) / 180)) / scale / 2;\n}\n\n/** This function gives the GeoJSON region of the polygons of a region of the map, or `undefined` for a region with no polygon. */\nfunction geoRegion(polygons: readonly PolygonShape[]): Region | undefined {\n const coordinates = polygons.map((polygon) => polygon.rings);\n if (coordinates.length === 0) return undefined;\n return coordinates.length === 1 ? { type: \"Polygon\", coordinates: coordinates[0]! } : { type: \"MultiPolygon\", coordinates };\n}\n\n/** This function gives the polygons of a simplified GeoJSON region as shapes of the map. */\nfunction shapesOf(region: Region): PolygonShape[] {\n const polygons = region.type === \"Polygon\" ? [region.coordinates] : region.coordinates;\n return polygons.map((rings) => ({ type: \"polygon\", rings: rings.map((ring) => ring.map(([lon, lat]): Position => [lon!, lat!])) }));\n}\n\n/**\n * This function simplifies the regions of a basemap with `simplifyRegions` of `@mark1russell7/geo`.\n *\n * - The regions of one rank (`regionRank`) tile the ground, for example the counties of a state. Thus each rank is one set, and\n * a border that two regions of a rank share stays one border. Regions of two ranks overlap, and they do not join.\n * - Each region keeps its code, its name, its place in the list and the order of its shapes. A circle stays as it is.\n * - Each removed position is at most `toleranceKm` from the result. `basemapToleranceKm` gives a tolerance for the view box.\n *\n * @throws GeoError - The errors of `simplifyRegions`, for example for a tolerance less than 0.\n */\nexport function simplifyBasemap(regions: readonly MapRegion[], toleranceKm: number): MapRegion[] {\n const ranks = new Map<number, { readonly at: number[]; readonly regions: (Region)[] }>();\n for (const [at, region] of regions.entries()) {\n const geo = geoRegion(region.shapes.filter((shape): shape is PolygonShape => shape.type === \"polygon\"));\n if (geo === undefined) continue;\n const rank = regionRank(region.code);\n const set = ranks.get(rank) ?? { at: [], regions: [] };\n set.at.push(at);\n set.regions.push(geo);\n ranks.set(rank, set);\n }\n const simplified = new Map<number, PolygonShape[]>();\n for (const set of ranks.values()) {\n const results = simplifyRegions(set.regions, toleranceKm);\n for (const [index, at] of set.at.entries()) simplified.set(at, shapesOf(results[index]!));\n }\n return regions.map((region, at) => {\n const polygons = simplified.get(at);\n if (polygons === undefined) return region;\n // The simplified polygons take the places of the polygons, in order. Each circle keeps its place.\n let next = 0;\n return { ...region, shapes: region.shapes.map((shape) => (shape.type === \"polygon\" ? polygons[next++]! : shape)) };\n });\n}\n","/**\n * The payload of the health route of the runtime. It tells the state of each part of the system. The parts are the\n * sources, the lateness, the coverage, the other copies, the quotas, the balances, the reads on a schedule and the channels.\n */\n\nimport type {\n BalanceStage,\n ChannelQuota,\n CopyRead,\n CopyStage,\n CopyWatch,\n Coverage,\n FetchFailure,\n Instant,\n ProviderBalance,\n QuotaStage,\n SourceHealth,\n} from \"./contracts.ts\";\nimport { DEFAULT_CHANNEL_DOWN, runOpens, type ChannelDownPolicy, type ChannelSnapshot } from \"./channel-down.ts\";\nimport type { Lateness } from \"./lateness.ts\";\nimport { balanceStages, copyStages, quotaStages } from \"./system-reports.ts\";\n\n/** The name of the format of the health payload. A change that breaks a reader gets a new name. */\nexport const HEALTH_FORMAT = \"alerts-health/4\";\n\n/**\n * The health of one source in the payload. It keeps the kind of the last failure, and not its message. A message can hold\n * the address of a fetch, and an address can hold a key.\n */\nexport interface SourceHealthView extends Omit<SourceHealth, \"lastFailure\"> {\n readonly lastFailure?: { readonly at: Instant; readonly kind: FetchFailure[\"kind\"] };\n}\n\n/** The health of another copy of the system: its stages at the time of the read, and its last read that passed. */\nexport interface CopyHealth {\n readonly copy: string;\n readonly stages: readonly CopyStage[];\n readonly read?: CopyRead;\n}\n\n/** The health of the quota of one channel: the quota, and the stages that it reached. */\nexport interface QuotaHealth {\n readonly quota: ChannelQuota;\n readonly stages: readonly QuotaStage[];\n}\n\n/**\n * The health of one read on a schedule of the runtime, for example the read of the replies of the texts. It holds no\n * message of a failure and no value of the read.\n */\nexport interface ReadHealth {\n /** The read, as words: for example `replies of the texts` or `spend of provider:twilio`. */\n readonly what: string;\n /** The end of the last read that passed, or `null` before it. */\n readonly at: Instant | null;\n /** This value is true when the last read failed. */\n readonly failed: boolean;\n /** The time of the next read, or `null` before the first read. */\n readonly next: Instant | null;\n}\n\n/**\n * The health of one channel of this copy (AL-65): its endpoints, its last good call and its run of failed calls. The run\n * holds the kind of each failure, and not its message. Thus a passed probe shows as a new time in `good`.\n */\nexport interface ChannelHealth extends ChannelSnapshot {\n /** This value is true when the run opens a line under the policy of the down channels (`runOpens`). */\n readonly down: boolean;\n}\n\n/** The health of the balance of one provider account: the balance, and its stages at the time of the read. */\nexport interface BalanceHealth {\n readonly balance: ProviderBalance;\n readonly stages: readonly BalanceStage[];\n}\n\n/**\n * The answer of the health route of the runtime. The route is on the loopback address only, because the coverage holds\n * the ids of the places. The payload holds no secret and no message of a failure.\n */\nexport interface HealthPayload {\n /** The format of the payload. A page of another format tells the reader to start the runtime of its own version. */\n readonly format: typeof HEALTH_FORMAT;\n /** The time of the last pass, or `null` before the first pass. The sources, the lateness and the coverage are from it. */\n readonly at: Instant | null;\n /** The time of the read. The stages of the copies and of the balances are at this time. */\n readonly now: Instant;\n readonly sources: readonly SourceHealthView[];\n readonly lateness: readonly Lateness[];\n readonly coverage: readonly Coverage[];\n readonly copies: readonly CopyHealth[];\n readonly quotas: readonly QuotaHealth[];\n readonly balances: readonly BalanceHealth[];\n readonly reads: readonly ReadHealth[];\n readonly channels: readonly ChannelHealth[];\n}\n\n/** These are the inputs of the payload of the health route. */\nexport interface HealthPayloadInput {\n /** The time of the last pass, or `null` before the first pass. */\n readonly at: Instant | null;\n /** The time of the read. */\n readonly now: Instant;\n /** The health of each source at the last pass. */\n readonly sources: readonly SourceHealth[];\n /** The lateness of each expectation at the last pass. */\n readonly lateness: readonly Lateness[];\n /** The coverage of each kind at each place at the last pass. */\n readonly coverage: readonly Coverage[];\n /** The watch of each other copy at the time of the read. */\n readonly copies: readonly CopyWatch[];\n /** The quota of each channel at the time of the read. */\n readonly quotas: readonly ChannelQuota[];\n /** The balance of each provider account that has a read. */\n readonly balances: readonly ProviderBalance[];\n /** The health of each read on a schedule, other than the balances, at the time of the read. */\n readonly reads: readonly ReadHealth[];\n /** The channels of this copy at the time of the read (AL-65). The default is no channel. */\n readonly channels?: readonly ChannelSnapshot[];\n /** The policy of the down channels. The default is `DEFAULT_CHANNEL_DOWN`. */\n readonly channelDown?: ChannelDownPolicy;\n}\n\n/** This function gives the health of a source without the message of its last failure. */\nexport function sourceHealthView(health: SourceHealth): SourceHealthView {\n const { lastFailure, ...rest } = health;\n return lastFailure === undefined ? rest : { ...rest, lastFailure: { at: lastFailure.at, kind: lastFailure.failure.kind } };\n}\n\n/**\n * This function gives the payload of the health route. It keeps the order of each list of its input. The core gives the\n * stages, thus the page and the system reports agree on each stage.\n */\nexport function healthPayload(input: HealthPayloadInput): HealthPayload {\n const { at, now } = input;\n const policy = input.channelDown ?? DEFAULT_CHANNEL_DOWN;\n return {\n format: HEALTH_FORMAT,\n at,\n now,\n sources: input.sources.map(sourceHealthView),\n lateness: input.lateness,\n coverage: input.coverage,\n copies: input.copies.map((watch) => ({ copy: watch.copy, stages: copyStages(watch, now), ...(watch.read === undefined ? {} : { read: watch.read }) })),\n quotas: input.quotas.map((quota) => ({ quota, stages: quotaStages(quota) })),\n balances: input.balances.map((balance) => ({ balance, stages: balanceStages(balance, now) })),\n reads: input.reads,\n channels: (input.channels ?? []).map((snapshot) => ({ ...snapshot, down: snapshot.run !== undefined && runOpens(snapshot.run, policy) })),\n };\n}\n","/**\n * This module gives the history of the incidents for a time scrubber. The history of an incident has the parts of the\n * incident that this copy knew after each time of entry of its reports. The history is a pure calculation over the merge\n * state. The runtime gives it on its route `GET /history`, and a page replays how each incident grew.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { assess, classOf, DEFAULT_ASSESS_POLICY, foreignIncidents, higherLevel, matchPlaces, reachedAssessment } from \"./assess.ts\";\nimport { isPrivate } from \"./audience.ts\";\nimport type { AssessedLevel, AssessPolicy, EndMark, Incident, Instant, Kind, MergeState, PersonWatch, PlaceId, RegionCode, Report, ReportId, Severity, Status } from \"./contracts.ts\";\nimport { compareRegionCodes, regionCodeKey, SEVERITY_ORDER, type MapPlaceInput, type MapShape, type ShapeLookup } from \"./map.ts\";\nimport { incidents, type IncidentOptions, type LinkRule } from \"./merge.ts\";\nimport { areasWithoutBlocks, distinctShapes } from \"./shapes.ts\";\n\n/** The name of the format of the history payload. A change that breaks a reader gets a new name. */\nexport const HISTORY_FORMAT = \"alerts-history/1\";\n\n/** One watched place in the areas of a change. */\nexport interface HistoryPlace {\n readonly id: PlaceId;\n /**\n * The highest level of the assessments with this place, over each part and each person. A matched place with no\n * assessment has the level `none`. The map uses the same rule.\n */\n readonly level: AssessedLevel;\n}\n\n/**\n * One change of an incident: the parts of the incident that this copy knew at one time. A change comes at each time of\n * entry of a report of the incident. An end mark of a known report of the incident also gives a change. A time edge\n * gives a change when the view of the incident changes at that time with no new fact. The time edges are the expiry of a\n * report, the end of the window `pastWithin` of a table and the end of a mute. Thus the view at a time is the last change\n * at or before it.\n *\n * A change has the live parts of the incident. With no live part, it has each part.\n */\nexport interface HistoryChange {\n /** The time of the change on this copy. */\n readonly at: Instant;\n /** The reports of the incident that came in at this time, from the smallest. A change of an end mark or of a time edge has no report. */\n readonly reports: readonly ReportId[];\n /** The highest level over each person at the time of the change, after the policy and the mutes. */\n readonly level: AssessedLevel;\n /** The highest severity of the parts at the time of the change. */\n readonly severity: Severity;\n /** False when each part ended at the time of the change. */\n readonly live: boolean;\n /** The earliest onset of the parts. */\n readonly onset?: Instant;\n /** The latest expiry of the parts. A part with no expiry gives no expiry. */\n readonly expires?: Instant;\n /** The region codes of the areas with a shape, in the order of the system and the code. The field `regions` of the payload has their shapes. */\n readonly codes: readonly RegionCode[];\n /** The polygons and the circles of the areas. Each shape comes one time. */\n readonly shapes: readonly MapShape[];\n /** The region codes of the areas with no shape in the store, in the order of the system and the code. */\n readonly unshaped: readonly RegionCode[];\n /** The watched places in the areas, in the order of the input places, each with its level. */\n readonly places: readonly HistoryPlace[];\n}\n\n/** The history of one incident of the merge state. */\nexport interface HistoryIncident {\n /** The anchor of the incident at the time of the payload. */\n readonly anchor: ReportId;\n /** The report ids of the incident at the time of the payload, from the smallest. */\n readonly reports: readonly ReportId[];\n readonly status: Status;\n readonly kind: Kind;\n /** The changes, from the oldest. */\n readonly changes: readonly HistoryChange[];\n}\n\n/** The shapes of one region code of the history, from the store of shapes. */\nexport interface HistoryRegion {\n readonly code: RegionCode;\n readonly shapes: readonly MapShape[];\n}\n\n/**\n * The answer of the history route of the runtime. The route is on the loopback address only, because the levels come\n * from the choices of the people. A reader replaces the history of each incident of the payload. It also drops each\n * history whose anchor is a report of an incident of the payload, because these incidents merged.\n */\nexport interface HistoryPayload {\n /** The format of the payload. A page of another format tells the reader to start the runtime of its own version. */\n readonly format: typeof HISTORY_FORMAT;\n /** The time of the history: the time of the last pass, or `null` before the first pass. */\n readonly at: Instant | null;\n /** The payload has each incident with a change at this time or later. The value `null` gives each incident. */\n readonly since: Instant | null;\n /**\n * The newest time of a change or of a time edge of the merge state, or `null` with no change. A reader gives it as\n * `since` of its next read. A value below the `since` of the read tells that a step of the clock moved the times back.\n * Then the reader reads each incident again with no `since`.\n */\n readonly next: Instant | null;\n /** The incidents with a change at `since` or later, in the order of their anchors. Each incident has each of its changes. */\n readonly incidents: readonly HistoryIncident[];\n /** The shapes of each code of the changes of the payload, one time each, in the order of the system and the code. */\n readonly regions: readonly HistoryRegion[];\n}\n\n/**\n * The times of entry on this copy. A report or an end mark of another copy comes later than its own time. Also, the\n * clock of the other copy is not the clock of this copy. Thus the history replays what this copy knew at each time.\n */\nexport interface EntryTimes {\n /** This function gives the time of entry of a report on this copy. */\n report(report: Report): Instant;\n /** This function gives the time of entry of an end mark on this copy. */\n mark(mark: EndMark): Instant;\n}\n\n/** The times of entry with no import: the time of receipt of each report, and the time of each end mark. */\nexport const OWN_ENTRY_TIMES: EntryTimes = { report: (report) => report.received, mark: (mark) => mark.at };\n\n/** These are the inputs of the history payload. */\nexport interface HistoryInput {\n /** The time of the history: the time of the last pass, or `null` before the first pass. */\n readonly at: Instant | null;\n /** The payload gives only the incidents with a change at this time or later. The default `null` gives each incident. */\n readonly since?: Instant | null;\n /** The merge state of the copy. The history has the incidents of this state. */\n readonly merge: MergeState;\n /** The times of entry on this copy. The default `OWN_ENTRY_TIMES` reads the times of the copy that wrote each part. */\n readonly entered?: EntryTimes;\n /** The watches of the people. The level of each change is the highest level over these people. */\n readonly people: readonly PersonWatch[];\n readonly places: readonly MapPlaceInput[];\n /** The policy of the assessment: the policy of the delivery. The default is the policy of the core. */\n readonly policy?: AssessPolicy;\n /** The ids of the sources of this copy, as `RouteInput.sources` tells (AL-76). Thus the level of each change is the level of the route. */\n readonly sources?: ReadonlySet<string> | undefined;\n readonly shape: ShapeLookup;\n /** The link rule of the delivery step and the view. */\n readonly link?: LinkRule;\n}\n\n/**\n * This function gives the payload of the history route. At each time of a change, it makes the incidents of the known\n * reports of each incident, at that time. Two parts of an incident before their merge give one change: the highest\n * level and severity, and each area of the live parts. The work for an incident with no change and no time edge at\n * `since` or later is only the read of its times.\n */\nexport function historyPayload(input: HistoryInput): HistoryPayload {\n const since = input.since ?? null;\n const policy = input.policy ?? DEFAULT_ASSESS_POLICY;\n const mutes = input.people.flatMap((person) => (person.interests?.mutes ?? []).flatMap((mute) => (mute.until === undefined ? [] : [mute.until])));\n const entered = input.entered ?? OWN_ENTRY_TIMES;\n const options: IncidentOptions = input.link === undefined ? {} : { link: input.link };\n // Each viewer of the page sees the history, so it reads no private report and no end mark of one (AL-92, `audience.ts`).\n // A private report never joins a public one, thus the other incidents do not change.\n const reports = input.merge.reports.filter((report) => !isPrivate(report));\n const publicIds = new Set(reports.map((report) => report.id));\n const state: MergeState = { ...input.merge, reports, ends: input.merge.ends.filter((mark) => publicIds.has(mark.report)) };\n const byId = new Map(state.reports.map((report) => [report.id, report]));\n const foreign = foreignIncidents(state.reports, input.sources);\n const entries = new Map(state.reports.map((report) => [report.id, entered.report(report)]));\n // Each end mark has its time of entry. Thus the parts at a time have only the marks that this copy knew at that time.\n const marks = new Map<ReportId, EndMark[]>();\n for (const mark of state.ends) marks.set(mark.report, [...(marks.get(mark.report) ?? []), { ...mark, at: entered.mark(mark) }]);\n // The time edges count up to the horizon: the time of the payload, or the newest time of entry when it is later. A take\n // of the exchange after the last pass gives a later time of entry. Thus a later read finds each new edge after its since.\n let horizon = input.at ?? Number.NEGATIVE_INFINITY;\n for (const time of entries.values()) if (time > horizon) horizon = time;\n for (const list of marks.values()) for (const mark of list) if (mark.at > horizon) horizon = mark.at;\n const lookups = new Map<string, readonly MapShape[] | undefined>();\n const lookup = (code: RegionCode): readonly MapShape[] | undefined => {\n const key = regionCodeKey(code);\n if (!lookups.has(key)) lookups.set(key, input.shape(code));\n return lookups.get(key);\n };\n\n let next: Instant | null = null;\n const shown: HistoryIncident[] = [];\n // The groups of the reports do not read the time. Thus the time of the current incidents changes nothing.\n for (const incident of incidents(state, input.at ?? 0, options)) {\n const own = incident.reports.flatMap((id) => byId.get(id) ?? []);\n const ownMarks = incident.reports.flatMap((id) => marks.get(id) ?? []);\n const entryTimes = [...own.map((report) => entries.get(report.id)!), ...ownMarks.map((mark) => mark.at)];\n if (entryTimes.length === 0) continue;\n const first = Math.min(...entryTimes);\n // The time edges count after the first entry, up to the horizon. A later edge comes in a later read.\n const edges = new Set(timeEdges(own, policy, mutes).filter((time) => time > first && time <= horizon));\n const times = [...new Set([...entryTimes, ...edges])].sort((a, b) => a - b);\n const last = times.at(-1)!;\n if (next === null || last > next) next = last;\n if (since !== null && last < since) continue;\n const changes: HistoryChange[] = [];\n for (const at of times) {\n const known = own.filter((report) => entries.get(report.id)! <= at);\n if (known.length === 0) continue;\n const came = known.filter((report) => entries.get(report.id) === at).map((report) => report.id);\n const marked = new Set(ownMarks.filter((mark) => mark.at === at).map((mark) => mark.report));\n const fact = came.length > 0 || known.some((report) => marked.has(report.id));\n if (!fact && !edges.has(at)) continue;\n const parts = incidents({ ...state, reports: known, ends: ownMarks }, at, options);\n const change = changeOf(at, parts, came.sort(compareCodeUnits), input, lookup, foreign);\n const previous = changes.at(-1);\n // A time edge with no new fact gives a change only when the view changes.\n if (!fact && previous !== undefined && sameView(previous, change)) continue;\n changes.push(change);\n }\n shown.push({ anchor: incident.anchor, reports: incident.reports, status: incident.status, kind: incident.kind, changes });\n }\n\n const regions = new Map<string, HistoryRegion>();\n for (const change of shown.flatMap((incident) => incident.changes)) {\n for (const code of change.codes) {\n const key = regionCodeKey(code);\n if (!regions.has(key)) regions.set(key, { code, shapes: distinctShapes(lookup(code) ?? []) });\n }\n }\n return { format: HISTORY_FORMAT, at: input.at, since, next, incidents: shown, regions: [...regions.values()].sort((a, b) => compareRegionCodes(a.code, b.code)) };\n}\n\n/**\n * The time edges of the reports: the times at which the view can change with no new fact. They are the expiry of each\n * report, the end of the window `pastWithin` of its table and the end of each mute. When each report has an expiry, no\n * part is live after the last expiry. Thus no later edge counts.\n */\nfunction timeEdges(reports: readonly Report[], policy: AssessPolicy, mutes: readonly Instant[]): Instant[] {\n const expiries = reports.flatMap((report) => (report.expires === undefined ? [] : [report.expires]));\n const end = expiries.length === reports.length && expiries.length > 0 ? Math.max(...expiries) : Number.POSITIVE_INFINITY;\n const pasts = reports.flatMap((report) => {\n const span = (classOf(policy, report.kind.code) ?? policy.otherwise).pastWithin;\n // The window holds while the age is `span` or less. Thus the level changes one millisecond after its end.\n return report.urgency === \"past\" && span !== undefined && report.onset !== undefined ? [report.onset + span + 1] : [];\n });\n return [...expiries, ...pasts, ...mutes].filter((time) => time <= end);\n}\n\n// Two changes give the same view when each field other than the time and the reports is the same.\nfunction sameView(a: HistoryChange, b: HistoryChange): boolean {\n return JSON.stringify({ ...a, at: 0, reports: [] }) === JSON.stringify({ ...b, at: 0, reports: [] });\n}\n\n// The change of the parts of one incident at a time. The map shows only live incidents, thus the change has only the live\n// parts. With no live part, the change has each part, and the reader does not show it.\nfunction changeOf(\n at: Instant,\n all: readonly Incident[],\n reports: readonly ReportId[],\n input: HistoryInput,\n lookup: ShapeLookup,\n foreign: (part: Incident) => boolean,\n): HistoryChange {\n const live = all.filter((part) => part.live);\n const parts = live.length > 0 ? live : all;\n let level: AssessedLevel = \"none\";\n const placeLevels = new Map<PlaceId, AssessedLevel>();\n for (const part of parts) {\n for (const match of matchPlaces(part, input.places)) if (!placeLevels.has(match.place)) placeLevels.set(match.place, \"none\");\n for (const person of input.people) {\n const assessment = reachedAssessment(assess(part, person, input.places, input.policy, at, foreign(part)));\n level = higherLevel(level, assessment.level);\n for (const id of assessment.places) placeLevels.set(id, higherLevel(placeLevels.get(id) ?? \"none\", assessment.level));\n }\n }\n const severity = parts.map((part) => part.severity).reduce((a, b) => (SEVERITY_ORDER.indexOf(b) < SEVERITY_ORDER.indexOf(a) ? b : a));\n const onsets = parts.flatMap((part) => (part.onset === undefined ? [] : [part.onset]));\n const expiries = parts.map((part) => part.expires);\n const codes = new Map<string, RegionCode>();\n const unshaped = new Map<string, RegionCode>();\n const shapes: MapShape[] = [];\n for (const area of areasWithoutBlocks(parts.flatMap((part) => part.areas))) {\n if (area.type === \"polygon\" || area.type === \"circle\") shapes.push(area);\n else if (area.type === \"code\") {\n const code = { system: area.system, code: area.code };\n const found = lookup(code);\n (found === undefined || found.length === 0 ? unshaped : codes).set(regionCodeKey(code), code);\n }\n }\n return {\n at,\n reports,\n level,\n severity,\n live: live.length > 0,\n ...(onsets.length === 0 ? {} : { onset: Math.min(...onsets) }),\n ...(expiries.some((expires) => expires === undefined) ? {} : { expires: Math.max(...expiries.map((expires) => expires!)) }),\n codes: [...codes.values()].sort(compareRegionCodes),\n shapes: distinctShapes(shapes),\n unshaped: [...unshaped.values()].sort(compareRegionCodes),\n places: input.places.flatMap((place) => {\n const found = placeLevels.get(place.id);\n return found === undefined ? [] : [{ id: place.id, level: found }];\n }),\n };\n}\n","/**\n * The checks of the indicator contract. An indicator is a measure that is not an event, for example road traffic,\n * rail delays or grid frequency. A measure becomes a signal when it leaves its normal level.\n *\n * - A source declares each measure in the field `measures` of its descriptor. The schema of the descriptor checks them.\n * - A reading is one value of one series of a measure. The schema checks its form, and `readingProblems` checks it against its measure.\n * - `seriesKey` gives the key of the history of a series. The key holds the version, so a baseline does not cross a change of method.\n *\n * The types are in `contracts.ts`. `docs/CONTRACTS.md` explains them.\n */\nimport { kindOf } from \"@mark1russell7/quantity\";\nimport { DIMENSION_IDS, type DimensionId, type MeasureDeclaration, type Reading, type SourceDescriptor } from \"./contracts.ts\";\n\n/** The form of the id of a measure: small letters, digits and hyphens, with a letter first, 40 characters or fewer. */\nexport const MEASURE_ID: RegExp = /^[a-z][a-z0-9-]{0,39}$/u;\n\n/** The form of the version of a series: letters, digits, dots and hyphens, with a letter or a digit first, 40 characters or fewer. */\nexport const SERIES_VERSION: RegExp = /^[A-Za-z0-9][A-Za-z0-9.-]{0,39}$/u;\n\n// The kinds of quantity whose values are 0 or more: a count, and a count in each unit of time.\nconst NOT_NEGATIVE = new Set([\"count\", \"frequency\"]);\n\n/** This function tells if a text is the id of a dimension of `DIMENSIONS`. */\nexport function isDimensionId(text: string): text is DimensionId {\n return DIMENSION_IDS.some((id) => id === text);\n}\n\n/** This function gives the declaration of the measure of a reading, or undefined when the source does not declare it. */\nexport function measureOf(reading: Reading, source: SourceDescriptor): MeasureDeclaration | undefined {\n return reading.source === source.id ? source.measures?.find((measure) => measure.id === reading.measure) : undefined;\n}\n\n/**\n * This function checks a reading against the declaration of its measure. The schema checks the form of the reading\n * first. This check finds the rules that need the declaration: the area kind, the baseline and the sign of a count.\n */\nexport function readingProblems(reading: Reading, source: SourceDescriptor): string[] {\n const measure = measureOf(reading, source);\n if (measure === undefined) return [`The source ${source.id} declares no measure ${reading.measure}.`];\n const name = `A reading of the measure ${measure.id} of ${source.id}`;\n const problems: string[] = [];\n if (reading.area.type !== measure.area) problems.push(`${name} has an area of the kind ${reading.area.type}, and the measure declares ${measure.area}.`);\n if ((measure.baseline === \"expected\") !== (reading.expected !== undefined)) {\n problems.push(measure.baseline === \"expected\" ? `${name} has no expected value, and its measure has the baseline expected.` : `${name} has an expected value, and its measure has the baseline ${measure.baseline}.`);\n }\n if ((measure.baseline === \"flag\") !== (reading.flagged !== undefined)) {\n problems.push(measure.baseline === \"flag\" ? `${name} has no flag, and its measure has the baseline flag.` : `${name} has a flag, and its measure has the baseline ${measure.baseline}.`);\n }\n if (reading.value < 0 && NOT_NEGATIVE.has(kindOf(measure.unit))) problems.push(`${name} has a value below 0, and its unit ${measure.unit} counts.`);\n return problems;\n}\n\n/**\n * This function gives the key of the history of the series of a reading: the source, the measure, the series and the\n * version. Two readings have one key only when they are values of one series with one method.\n */\nexport function seriesKey(reading: Reading): string {\n return JSON.stringify([reading.source, reading.measure, reading.series, reading.version ?? \"\"]);\n}\n","/**\n * The baseline and the read of an indicator series. The read tells how far the latest value of a series is from the\n * normal level of the series.\n *\n * - With the baseline `none`, the normal level comes from the history of the series. The history holds the values at the same time of the week or of the day.\n * - With the baseline `expected`, the read compares the residual of the latest value with the residuals of the history. A residual is the value minus its expected value.\n * - With the baseline `flag`, the flag of the source is the signal.\n * - The score is the robust z-score of Iglewicz and Hoaglin, from `modifiedZ` of `@mark1russell7/rigor-statistics`.\n *\n * A series with too few values, or with no recent value, has no read. A missing value is not a normal value at any time.\n */\nimport { median, modifiedZ, MODIFIED_Z_CUT } from \"@mark1russell7/rigor-statistics\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport type { Duration, Instant, MeasureDeclaration, Move, Reading } from \"./contracts.ts\";\nimport { seriesKey } from \"./indicators.ts\";\n\nconst HOUR = 3_600_000;\nconst DAY = 24 * HOUR;\nconst WEEK = 7 * DAY;\n\n/** The season of the normal level: the same time of the week, the same time of the day, or each time. */\nexport type Season = \"week\" | \"day\" | \"none\";\n\n/** The settings of the baseline of a series. `DEFAULT_BASELINE` gives a value for each one. */\nexport interface BaselinePolicy {\n /** The history that the baseline reads, before the time of the latest value. */\n readonly window: Duration;\n readonly season: Season;\n /**\n * The half width of the slot of the season. With 1 h and the season `day`, the slot of 08:00 holds the values from\n * 07:00 to 09:00 of each earlier day. A slot holds no value of the period of the latest value.\n */\n readonly slack: Duration;\n /** The fewest values of the history in the slot that give a read. */\n readonly samples: number;\n /** The cut of the absolute score that is a signal. */\n readonly cut: number;\n /** The count of cadences with no new value that makes a series stale. The delay of the measure adds to this time. */\n readonly staleCadences: number;\n /** The time with no new value that makes a series stale when its cadence is not known. */\n readonly staleAfter: Duration;\n}\n\n/**\n * The default baseline: the same time of the week, within 1 h, in the 28 days before the latest value. The cut is the\n * cut of Iglewicz and Hoaglin, 3.5.\n */\nexport const DEFAULT_BASELINE: BaselinePolicy = {\n window: 28 * DAY,\n season: \"week\",\n slack: HOUR,\n samples: 8,\n cut: MODIFIED_Z_CUT,\n staleCadences: 3,\n staleAfter: 6 * HOUR,\n};\n\n/** The cause of a series with no read. */\nexport type NoReadCause =\n /** The series has no reading at the time of the read. */\n | \"no-reading\"\n /** The latest reading is older than the stale time of the series. */\n | \"stale\"\n /** The history has fewer values in the slot than the policy needs. */\n | \"few-samples\";\n\n/** The read of one series at one time. */\nexport type SeriesRead =\n /** The robust score of the latest value. `center` is the normal level of the value, in the unit of the measure. */\n | { readonly kind: \"score\"; readonly at: Instant; readonly score: number; readonly signal: boolean; readonly center: number; readonly samples: number }\n /** The flag of the source on the latest value. */\n | { readonly kind: \"flag\"; readonly at: Instant; readonly signal: boolean }\n | { readonly kind: \"no-read\"; readonly cause: NoReadCause };\n\n/** This function tells if a score is a signal for the direction of a measure. */\nexport function isSignal(score: number, moves: Move, cut: number): boolean {\n if (moves === \"rise\") return score >= cut;\n if (moves === \"drop\") return score <= -cut;\n return Math.abs(score) >= cut;\n}\n\n/** This function gives the time with no new value that makes a series stale. The cadence of the reading comes first. */\nexport function staleTime(latest: Reading, measure: MeasureDeclaration, policy: BaselinePolicy = DEFAULT_BASELINE): Duration {\n const cadence = latest.cadence ?? measure.cadence;\n return cadence === undefined ? policy.staleAfter : policy.staleCadences * cadence + (measure.delay ?? 0);\n}\n\n// This function tells if the gap from a value of the history to the latest value is in the slot of the season: within\n// the slack of one or more whole periods.\nfunction inSlot(gap: Duration, policy: BaselinePolicy): boolean {\n if (policy.season === \"none\") return true;\n const period = policy.season === \"week\" ? WEEK : DAY;\n const periods = Math.max(1, Math.round(gap / period));\n return Math.abs(gap - periods * period) <= policy.slack;\n}\n\n// The order of two readings of one time: the smaller observation id first. The order of the input does not change it.\nfunction earlier(a: Reading, b: Reading): number {\n return a.at - b.at || compareCodeUnits(a.observation, b.observation);\n}\n\n/**\n * This function reads one series at the time `now`. The readings are of one source, one measure and one series id.\n * They can hold two versions, duplicates and any order.\n *\n * - The latest reading at `now` or before gives the version. The history holds only the readings with its key, so a\n * baseline does not cross a version.\n * - The history holds one reading for each time: the reading with the smallest observation id.\n * - The score of the latest value is its robust z-score among the values of the history and itself.\n */\nexport function readSeries(readings: readonly Reading[], measure: MeasureDeclaration, now: Instant, policy: BaselinePolicy = DEFAULT_BASELINE): SeriesRead {\n const live = readings.filter((reading) => reading.at <= now && (measure.baseline !== \"expected\" || reading.expected !== undefined)).sort(earlier);\n const newest = live.at(-1);\n if (newest === undefined) return { kind: \"no-read\", cause: \"no-reading\" };\n const latest = live.find((reading) => reading.at === newest.at) ?? newest;\n if (now - latest.at > staleTime(latest, measure, policy)) return { kind: \"no-read\", cause: \"stale\" };\n if (measure.baseline === \"flag\") return { kind: \"flag\", at: latest.at, signal: latest.flagged === true };\n const key = seriesKey(latest);\n const valueOf = (reading: Reading): number => reading.value - (measure.baseline === \"expected\" ? (reading.expected ?? 0) : 0);\n const history: number[] = [];\n let last: Instant | undefined;\n for (const reading of live) {\n if (reading.at === last || reading.at >= latest.at || latest.at - reading.at > policy.window) continue;\n if (seriesKey(reading) !== key || !inSlot(latest.at - reading.at, policy)) continue;\n last = reading.at;\n history.push(valueOf(reading));\n }\n if (history.length < policy.samples) return { kind: \"no-read\", cause: \"few-samples\" };\n const scores = modifiedZ([...history, valueOf(latest)]).scores;\n const score = scores[scores.length - 1] ?? 0;\n const center = median(history) + (measure.baseline === \"expected\" ? (latest.expected ?? 0) : 0);\n return { kind: \"score\", at: latest.at, score, signal: isSignal(score, measure.moves, policy.cut), center, samples: history.length };\n}\n","/**\n * The breadth of the indicator signals. One measure out of its normal level is a weak sign. Many dimensions out of their\n * normal levels at one time in one area is a strong sign.\n *\n * - The breadth of a place is the count of the dimensions with a signal in a series near the place.\n * - The breadth of the world holds each series, near a place or not. A dimension with signals in many series tells a\n * change in many areas at one time.\n * - Each count also tells the series with a read and the series with no read. A breadth of 2 dimensions of 2 with a read\n * is not a breadth of 2 dimensions of 30.\n *\n * The breadth gives counts and no decision. The threat level reads the counts.\n */\nimport { distanceKm, distanceToGeometryKm, GeoError } from \"@mark1russell7/geo\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { regionCovers } from \"./assess.ts\";\nimport type { SeriesRead } from \"./baseline.ts\";\nimport { DIMENSIONS, type DimensionId, type IndicatorArea, type PlaceId, type Position, type RegionCode, type WatchedPlace } from \"./contracts.ts\";\nimport { shapeDistanceKm } from \"./shapes.ts\";\n\n/** The read of one series at one time, with the dimension of its measure and the area of its latest reading. */\nexport interface SeriesSignal {\n /** The key of the series, for example from `seriesKey`. One key counts one time in each dimension. */\n readonly series: string;\n readonly dimension: DimensionId;\n readonly area: IndicatorArea;\n readonly read: SeriesRead;\n}\n\n/** The regions of one zone of the domain of a source, from a table of the atlas. */\nexport interface ZoneRegions {\n readonly system: string;\n readonly code: string;\n readonly regions: readonly RegionCode[];\n}\n\n/** The counts of the series of one dimension. Each key counts one time. */\nexport interface DimensionCount {\n readonly dimension: DimensionId;\n /** The count of the series with a score or a flag. */\n readonly read: number;\n /** The count of the series with a signal. It is not more than `read`. */\n readonly signals: number;\n /** The count of the series with no read. */\n readonly noRead: number;\n}\n\n/** The breadth of a group of series. */\nexport interface Breadth {\n /** The dimensions with a signal in one series or more, in the order of `DIMENSIONS`. The length of the list is the breadth. */\n readonly signals: readonly DimensionId[];\n /** The dimensions with a read of one series or more, in the order of `DIMENSIONS`. */\n readonly read: readonly DimensionId[];\n /** The counts of each dimension with one series or more, in the order of `DIMENSIONS`. */\n readonly dimensions: readonly DimensionCount[];\n}\n\n/** The breadth of the series near one watched place. */\nexport interface PlaceBreadth extends Breadth {\n readonly place: PlaceId;\n}\n\n/** The breadth of the world and of each watched place. */\nexport interface IndicatorBreadth {\n /** The breadth of each series, near a place or not. */\n readonly world: Breadth;\n /** The breadth of each place, in the order of the places. A place with no series near it has empty lists. */\n readonly places: readonly PlaceBreadth[];\n /**\n * The keys of the series with an area that the match cannot read, in the order of the code units. The area is a zone\n * with no regions in the table, or a shape that `@mark1russell7/geo` refuses for a place with a position.\n */\n readonly unplaced: readonly string[];\n}\n\n// The state of one series: no read, a read with no signal, or a signal. A key with two states keeps the higher state.\ntype State = 0 | 1 | 2;\n\nfunction stateOf(read: SeriesRead): State {\n if (read.kind === \"no-read\") return 0;\n return read.signal ? 2 : 1;\n}\n\n/**\n * This function gives the breadth of a group of series. The result is a function of the set of the series: the order\n * does not change it, and a duplicate does not change it.\n *\n * - A key counts one time in each dimension.\n * - When a key has two reads in one dimension, the higher read counts: a signal, then a read, then no read.\n */\nexport function breadthOf(series: readonly SeriesSignal[]): Breadth {\n const states = new Map<DimensionId, Map<string, State>>();\n for (const one of series) {\n const keys = states.get(one.dimension) ?? new Map<string, State>();\n keys.set(one.series, Math.max(keys.get(one.series) ?? 0, stateOf(one.read)) as State);\n states.set(one.dimension, keys);\n }\n const dimensions: DimensionCount[] = [];\n for (const { id } of DIMENSIONS) {\n const keys = states.get(id);\n if (keys === undefined) continue;\n let read = 0;\n let signals = 0;\n for (const state of keys.values()) {\n if (state > 0) read++;\n if (state === 2) signals++;\n }\n dimensions.push({ dimension: id, read, signals, noRead: keys.size - read });\n }\n return {\n signals: dimensions.filter((count) => count.signals > 0).map((count) => count.dimension),\n read: dimensions.filter((count) => count.read > 0).map((count) => count.dimension),\n dimensions,\n };\n}\n\n// The key of a zone in the table.\nfunction zoneKey(system: string, code: string): string {\n return JSON.stringify([system, code]);\n}\n\n// The regions of each zone. Two rows of one zone give the union of their regions.\nfunction zoneTable(zones: readonly ZoneRegions[]): Map<string, RegionCode[]> {\n const table = new Map<string, RegionCode[]>();\n for (const zone of zones) {\n const key = zoneKey(zone.system, zone.code);\n table.set(key, [...(table.get(key) ?? []), ...zone.regions]);\n }\n return table;\n}\n\n// The great-circle distance in kilometers from a position to the area of a point, a line or a polygon, or `undefined`\n// when `@mark1russell7/geo` refuses the area.\nfunction distanceTo(area: Extract<IndicatorArea, { readonly type: \"point\" | \"line\" | \"polygon\" }>, at: Position): number | undefined {\n if (area.type === \"polygon\") return shapeDistanceKm({ type: \"polygon\", rings: area.rings }, at);\n const point = { lat: at[1], lon: at[0] };\n try {\n if (area.type === \"point\") return distanceKm(point, { lat: area.at[1], lon: area.at[0] });\n return distanceToGeometryKm(point, { type: \"LineString\", coordinates: area.path });\n } catch (error) {\n if (error instanceof GeoError) return undefined;\n throw error;\n }\n}\n\n/**\n * This function tells if the area of a series meets a watched place. It gives `undefined` when the match cannot read\n * the area: a zone with no regions in the table, or a shape that `@mark1russell7/geo` refuses.\n *\n * - A `code` area meets a place when it covers a code of the place, by the rule of `regionCovers`.\n * - A `point`, a `line` or a `polygon` meets a place with a position at the buffer of the place or nearer. It meets no\n * place with no position.\n * - A `zone` meets a place when a region of the zone in the table covers a code of the place.\n * - A `world` area meets no place. Only the breadth of the world holds it.\n */\nexport function areaMeetsPlace(area: IndicatorArea, place: WatchedPlace, zones: readonly ZoneRegions[] = []): boolean | undefined {\n return meets(area, place, zoneTable(zones));\n}\n\nfunction meets(area: IndicatorArea, place: WatchedPlace, table: ReadonlyMap<string, readonly RegionCode[]>): boolean | undefined {\n switch (area.type) {\n case \"world\":\n return false;\n case \"code\":\n return place.codes.some((code) => regionCovers(area, code));\n case \"zone\": {\n const regions = table.get(zoneKey(area.system, area.code));\n if (regions === undefined) return undefined;\n return place.codes.some((code) => regions.some((region) => regionCovers(region, code)));\n }\n default: {\n if (place.at === undefined) return false;\n const distance = distanceTo(area, place.at);\n return distance === undefined ? undefined : distance <= place.bufferKm;\n }\n }\n}\n\n/**\n * This function gives the breadth of the world and of each watched place. The result is a function of the set of the\n * series and of the set of the zones. The order and a duplicate do not change it.\n *\n * - The breadth of the world holds each series.\n * - The breadth of a place holds each series with an area that meets the place, by the rules of `areaMeetsPlace`.\n * - A series with an area that the match cannot read is in `unplaced`, and it is in no breadth of a place.\n */\nexport function indicatorBreadth(series: readonly SeriesSignal[], places: readonly WatchedPlace[], zones: readonly ZoneRegions[] = []): IndicatorBreadth {\n const table = zoneTable(zones);\n const near = places.map((): SeriesSignal[] => []);\n const unplaced = new Set<string>();\n for (const one of series) {\n if (one.area.type === \"zone\" && !table.has(zoneKey(one.area.system, one.area.code))) unplaced.add(one.series);\n places.forEach((place, index) => {\n const found = meets(one.area, place, table);\n if (found === undefined) unplaced.add(one.series);\n else if (found) near[index]?.push(one);\n });\n }\n return {\n world: breadthOf(series),\n places: places.map((place, index) => ({ place: place.id, ...breadthOf(near[index] ?? []) })),\n unplaced: [...unplaced].sort(compareCodeUnits),\n };\n}\n","/**\n * This module is the reader of the history route. A reader keeps the history of each incident by its anchor, and it\n * adds each answer of the route to them. A time scrubber of a page reads the times of the changes from them. The\n * module is a pure calculation with no clock and no request.\n */\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { higherLevel } from \"./assess.ts\";\nimport type { AssessedLevel, Instant, PlaceId, RegionCode, ReportId } from \"./contracts.ts\";\nimport type { HistoryChange, HistoryIncident, HistoryPayload, HistoryRegion } from \"./history.ts\";\nimport { compareMapIncidents, compareRegionCodes, regionCodeKey, type MapIncident, type MapPlace, type MapView } from \"./map.ts\";\nimport { distinctShapes } from \"./shapes.ts\";\n\n/** The histories that a reader of the history route keeps. */\nexport interface Histories {\n /** The time of the newest answer: the time of the last pass of the runtime, or `null` before the first pass. */\n readonly at: Instant | null;\n /** The query `since` of the next read. The value `null` asks for each incident. */\n readonly since: Instant | null;\n /** The history of each incident, in the order of the anchors. */\n readonly incidents: readonly HistoryIncident[];\n /** The shapes of each region code of the changes, one time each, in the order of the system and the code. */\n readonly regions: readonly HistoryRegion[];\n}\n\n/** The histories of a reader before its first read. */\nexport const NO_HISTORIES: Histories = { at: null, since: null, incidents: [], regions: [] };\n\n/**\n * This function adds one answer of the history route to the histories of a reader. An answer to a read with no `since`\n * has each incident, so it replaces each history. An answer to a read with `since` replaces the history of each of its\n * incidents. It also drops each history whose anchor is a report of an incident of the answer, because these incidents\n * merged. The result keeps only the regions of its changes.\n *\n * The field `since` of the result is the query of the next read. It is `null` when the answer has no newest change, or\n * when that time is below the `since` of the answer. Then a step of the clock moved the times, and the next read asks\n * for each incident again.\n */\nexport function addHistory(kept: Histories, payload: HistoryPayload): Histories {\n const replaced = new Set<ReportId>(payload.incidents.flatMap((incident) => [incident.anchor, ...incident.reports]));\n const older = payload.since === null ? [] : kept.incidents.filter((incident) => !replaced.has(incident.anchor));\n const incidents = [...older, ...payload.incidents].sort((a, b) => compareCodeUnits(a.anchor, b.anchor));\n\n // The shapes of a code come from the newest answer that has the code. A code of no change leaves the histories.\n const known = new Map<string, HistoryRegion>();\n for (const region of [...kept.regions, ...payload.regions]) known.set(regionCodeKey(region.code), region);\n const regions = new Map<string, HistoryRegion>();\n for (const code of incidents.flatMap((incident) => incident.changes.flatMap((change) => change.codes))) {\n const key = regionCodeKey(code);\n const region = known.get(key);\n if (region !== undefined) regions.set(key, region);\n }\n\n const next = payload.next;\n const since = next !== null && (payload.since === null || next >= payload.since) ? next : null;\n return { at: payload.at, since, incidents, regions: [...regions.values()].sort((a, b) => compareRegionCodes(a.code, b.code)) };\n}\n\n/**\n * This function gives the times at which the map of the histories can change, one time each, from the oldest. These\n * are the times of the changes. The runtime gives a change at each time edge, thus an expiry has no time of its own.\n * A scrubber shows a tick at each time.\n */\nexport function historyTimes(kept: Histories): readonly Instant[] {\n const times = new Set<Instant>(kept.incidents.flatMap((incident) => incident.changes.map((change) => change.at)));\n return [...times].sort((a, b) => a - b);\n}\n\n/**\n * This function gives the change of an incident that is on the map at a time: the last change at or before the time.\n * It gives `undefined` when the incident is not on the map: before its first change, and while that change is not live.\n * The reader has no rule of its own for an expiry, because the runtime gives a change at each time edge.\n */\nexport function historyChangeAt(incident: HistoryIncident, at: Instant): HistoryChange | undefined {\n const change = incident.changes.findLast((each) => each.at <= at);\n return change?.live === true ? change : undefined;\n}\n\n/**\n * This function gives the view of the map at a time of the histories. The view has each incident that is on the map at\n * that time. Each incident has the level, the severity, the areas and the places of its change. A page draws this view\n * with the renderer of the live map. The order of the incidents is the order of the live view.\n *\n * Each place of the result keeps its label, its position and its shapes from `places`. Its level is the highest level\n * of the place in the changes of the view, as on the live map. The history has no coverage, thus a place of the result\n * has no gap. The places of the live view give `places`.\n */\nexport function historyView(kept: Histories, at: Instant, places: readonly MapPlace[]): MapView {\n const shapes = new Map(kept.regions.map((region) => [regionCodeKey(region.code), region.shapes]));\n const unshaped = new Map<string, RegionCode>();\n const levels = new Map<PlaceId, AssessedLevel>();\n const incidents = kept.incidents\n .flatMap((incident): MapIncident[] => {\n const change = historyChangeAt(incident, at);\n if (change === undefined) return [];\n for (const code of change.unshaped) unshaped.set(regionCodeKey(code), code);\n for (const place of change.places) levels.set(place.id, higherLevel(levels.get(place.id) ?? \"none\", place.level));\n return [\n {\n anchor: incident.anchor,\n status: incident.status,\n kind: incident.kind,\n level: change.level,\n severity: change.severity,\n ...(change.onset === undefined ? {} : { onset: change.onset }),\n ...(change.expires === undefined ? {} : { expires: change.expires }),\n shapes: distinctShapes([...change.shapes, ...change.codes.flatMap((code) => shapes.get(regionCodeKey(code)) ?? [])]),\n unshaped: change.unshaped,\n places: change.places.map((place) => place.id),\n },\n ];\n })\n .sort(compareMapIncidents);\n return {\n incidents,\n places: places.map(\n ({ id, label, at: position, shapes: own }): MapPlace => ({\n id,\n label,\n ...(position === undefined ? {} : { at: position }),\n shapes: own,\n level: levels.get(id) ?? \"none\",\n incidents: incidents.filter((incident) => incident.places.includes(id)).map((incident) => incident.anchor),\n gaps: [],\n }),\n ),\n unshaped: [...unshaped.values()].sort(compareRegionCodes),\n };\n}\n","/**\n * The collector of the problems of a map function. Each adapter makes lists of `MapProblem`, so the\n * core is the home of the collector. A reader of a format takes a `ProblemSink`.\n */\n\nimport type { MapProblem } from \"./contracts.ts\";\n\n/**\n * The effect of a problem on the report. `fatal`: no report. `lossy`: the report lacks a value of the\n * message, or holds a fallback in its place. `note`: the report is whole, and the message has more.\n */\nexport type ProblemEffect = \"note\" | \"lossy\" | \"fatal\";\n\n/**\n * The place where a map function or a reader puts the problems of a message. The default effect is\n * `lossy`, because a loss that the health does not see changes the level of an alert silently.\n */\nexport interface ProblemSink {\n add(path: string, message: string, effect?: ProblemEffect): void;\n}\n\n/**\n * The problems of one message, in order. The collector puts its prefix before each path: the prefix\n * `features[3]` and the path `properties.onset` give `features[3].properties.onset`.\n */\nexport class Problems implements ProblemSink {\n readonly list: MapProblem[] = [];\n private readonly prefix: string;\n\n /** The prefix is the path of the message. The default is no prefix. */\n constructor(prefix = \"\") {\n this.prefix = prefix;\n }\n\n /** This method adds one problem. A problem is lossy if the caller does not give another effect. */\n add(path: string, message: string, effect: ProblemEffect = \"lossy\"): void {\n const full = this.prefix === \"\" ? path : path === \"\" ? this.prefix : `${this.prefix}.${path}`;\n this.list.push(effect === \"lossy\" ? { path: full, message, fatal: false, lossy: true } : { path: full, message, fatal: effect === \"fatal\" });\n }\n\n /** The count of the fatal problems. A `FetchRecord` holds this count for the observations of a fetch. */\n get fatal(): number {\n return this.list.filter((problem) => problem.fatal).length;\n }\n\n /** The count of the lossy problems. A `FetchRecord` holds this count for the observations of a fetch. */\n get lossy(): number {\n return this.list.filter((problem) => problem.lossy === true).length;\n }\n}\n","// The payload of the route `GET /interests` of the runtime: the rows of the interest graph of each person (AL-35,\n// `docs/RELEVANCE.md`, the section \"The join of the layers\").\n\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport { contactChannels, personInterests, placeLabels, type AlertConfig, type ContactLookup } from \"./config.ts\";\nimport type { ChannelDescriptor, Mute, NodeKey, PersonId } from \"./contracts.ts\";\nimport type { InterestRow } from \"./interest-defaults.ts\";\nimport { kindLabel } from \"./taxonomy.ts\";\nimport { graphLabels } from \"./why.ts\";\n\n/** The format of the payload of the route `GET /interests`. */\nexport const INTERESTS_FORMAT = \"alerts-interests/1\";\n\n/** The interests of one person: the routing of the alerts, and a row for each edge. */\nexport interface InterestsPerson {\n readonly person: PersonId;\n /** The name of the person for the UI. */\n readonly label?: string;\n /** The routing of the alerts: `graph` when the relevance decides, `places` when the watched places decide. */\n readonly routing: \"graph\" | \"places\";\n /** The rows of the graph: each edge of the layers and of the person. A replaced default has the id of its replacement. */\n readonly rows: readonly InterestRow[];\n /** The mutes of the person. */\n readonly mutes: readonly Mute[];\n /** The label of each node of the rows and the mutes that has one: a place, a label of the graph or a topic. */\n readonly labels: Readonly<Record<string, string>>;\n /** The problem of the join or of the graph. Then the person keeps the watch of the configuration. */\n readonly problem?: string;\n}\n\n/** The payload of the route `GET /interests`: the interests of each person, in the order of the configuration. */\nexport interface InterestsPayload {\n readonly format: typeof INTERESTS_FORMAT;\n readonly people: readonly InterestsPerson[];\n}\n\nconst TOPIC = \"topic:\";\n\n/**\n * This function gives the payload of the route `GET /interests` from the configuration. The rows come from the same\n * join as the load (`personInterests`), with the same channels and the same `lookup` of the services of the contacts.\n * The payload holds the labels of the places. Thus only the loopback address serves the route.\n */\nexport function interestsPayload(config: AlertConfig, channels: readonly ChannelDescriptor[] = [], lookup?: ContactLookup): InterestsPayload {\n const places = placeLabels(config);\n const people = config.people.map((entry): InterestsPerson => {\n const person = entry.watch.person;\n const own = entry.watch.interests;\n const joined = personInterests(entry, contactChannels(config, person, channels, lookup));\n const graph = joined.watch.interests;\n const other = own !== undefined && own.person !== person ? own.person : undefined;\n const labelOf = graphLabels(places, graph);\n const nodes = new Set<NodeKey>([...joined.rows.flatMap(({ edge }) => [edge.from, edge.to]), ...(graph?.mutes ?? []).flatMap((mute) => mute.subjects ?? [])]);\n const labels = Object.fromEntries(\n [...nodes].sort(compareCodeUnits).flatMap((node) => {\n const label = labelOf(node) ?? (node.startsWith(TOPIC) ? kindLabel(node.slice(TOPIC.length)) : undefined);\n return label === undefined ? [] : [[node, label] as const];\n }),\n );\n const problem = joined.problem ?? (other === undefined ? undefined : `The interest graph is of the person ${other}. The relevance fails, and the places decide.`);\n return {\n person,\n ...(entry.label === undefined ? {} : { label: entry.label }),\n routing: graph !== undefined && other === undefined ? \"graph\" : \"places\",\n rows: joined.rows,\n mutes: graph?.mutes ?? [],\n labels,\n ...(problem === undefined ? {} : { problem }),\n };\n });\n return { format: INTERESTS_FORMAT, people };\n}\n","/**\n * The runtime schemas of the contracts, in zod 4. Each schema checks one data type of `contracts.ts`\n * or `lateness.ts` at a trust boundary. The boundaries are the output of a map function, the event\n * log, the private configuration and the procedure tools.\n *\n * - The TypeScript types stay the source of truth. `schemaOf` holds each schema to its type, so a\n * drift fails the type check.\n * - Each object is strict, so an unknown key fails. The contract is closed, as the taxonomy is.\n * - Each schema has no transform, so `z.toJSONSchema` converts it. The MCP tools use the JSON Schema.\n * - The rules of the values that a type cannot hold are refinements. Each rule tells the line of the\n * contract that states it.\n */\nimport { tryParseUnit } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\nimport {\n ASSESSED_LEVELS,\n CELL_RESOURCES,\n DIMENSION_IDS,\n INDICATOR_AREA_KINDS,\n LEVELS,\n MOVES,\n OWN_BASELINES,\n type Acknowledgment,\n type Address,\n type AddressField,\n type Area,\n type AssessedLevel,\n type AssessPolicy,\n type AssessReason,\n type Assessment,\n type BalanceRead,\n type BalanceStage,\n type CanaryResult,\n type Category,\n type CellResource,\n type Certainty,\n type ChannelDescriptor,\n type ChannelFailureKind,\n type ChannelId,\n type ChannelQuota,\n type CopyRead,\n type CopyStage,\n type CorrelationKey,\n type Coverage,\n type Cursor,\n type Delivery,\n type DimensionId,\n type DeliveryState,\n type DeliveryStatus,\n type EndMark,\n type Estimate,\n type ExpectedHarm,\n type Duration,\n type EscalationPolicy,\n type EscalationStep,\n type FetchFailure,\n type FetchOutcome,\n type FetchRecord,\n type HealthState,\n type Id,\n type Incident,\n type IndicatorArea,\n type IndicatorAreaKind,\n type IncidentLine,\n type Instant,\n type Kind,\n type KindClass,\n type AlertArea,\n type KindPrior,\n type Level,\n type MeasureDeclaration,\n type Move,\n type LevelRule,\n type LevelTable,\n type LocateOutcome,\n type MandatoryRule,\n type MapProblem,\n type MapResult,\n type Message,\n type Observation,\n type ObservationId,\n type Operation,\n type PersonId,\n type PersonWatch,\n type PlaceId,\n type OwnBaseline,\n type Position,\n type Reading,\n type ProviderBalance,\n type QuietWindow,\n type QuotaStage,\n type Receipt,\n type RegionCode,\n type Report,\n type ReportId,\n type ResponseType,\n type ScoreFactor,\n type ScorePriors,\n type SendOutcome,\n type Severity,\n type ShadowScore,\n type Significance,\n type UnderPrior,\n type SourceDescriptor,\n type SourceHealth,\n type SourceId,\n type Status,\n type Subject,\n type SubjectWatch,\n type Transport,\n type Urgency,\n type Watch,\n SUBJECT_SYSTEMS,\n type EdgeKind,\n type EdgeOrigin,\n type InterestEdge,\n type InterestGraph,\n type Mute,\n type MuteEffect,\n type NodeKey,\n type Relevance,\n type RelevancePath,\n type RelevancePolicy,\n type SubjectEntry,\n type SubjectKind,\n type WhyLimit,\n type WhyRecord,\n type WatchedPlace,\n type ContactServices,\n} from \"./contracts.ts\";\nimport { MEASURE_ID, SERIES_VERSION } from \"./indicators.ts\";\nimport { err, ok, tryCatch, type Result } from \"@mark1russell7/optional\";\nimport { compareCodeUnits } from \"@mark1russell7/text/order\";\nimport {\n CONFIG_FORMAT,\n CONFIG_PART_FORMAT,\n COPY_FORMAT,\n copyProblems,\n loadConfig,\n mergeParts,\n partLabel,\n type AddressValue,\n type AlertConfig,\n type ConfigPart,\n type ContactConfig,\n type NamedPart,\n type CopyListen,\n type CopyPeer,\n type CopySettings,\n type ExpectationConfig,\n type OutageConfig,\n type OutagePersonConfig,\n type PersonConfig,\n type InterestDefaultsConfig,\n type PlaceConfig,\n type SecretLookup,\n type SpendConfig,\n type SecretRef,\n type TellConfig,\n type TellSite,\n} from \"./config.ts\";\nimport type { TryChain } from \"./chain.ts\";\nimport type { ChannelDownConfig, ChannelRun } from \"./channel-down.ts\";\nimport type { SourceClearConfig } from \"./system-reports.ts\";\nimport type { SendLimitConfig } from \"./send-limit.ts\";\nimport type { ThrottleConfig } from \"./throttle.ts\";\nimport type { EscalationEnd, Recipient } from \"./delivery.ts\";\nimport type { DrillConfig, DrillPath } from \"./drill.ts\";\nimport { OPT_IN_WAYS, type OptInConfig, type OptInRecord } from \"./opt-in.ts\";\nimport type { RankDelays } from \"./escalation.ts\";\nimport { HEALTH_FORMAT, type BalanceHealth, type ChannelHealth, type CopyHealth, type HealthPayload, type QuotaHealth, type ReadHealth, type SourceHealthView } from \"./health-payload.ts\";\nimport type { InterestRow } from \"./interest-defaults.ts\";\nimport { INTERESTS_FORMAT, type InterestsPayload, type InterestsPerson } from \"./interests-payload.ts\";\nimport { HISTORY_FORMAT, type HistoryChange, type HistoryIncident, type HistoryPayload, type HistoryPlace, type HistoryRegion } from \"./history.ts\";\nimport type { MapShape } from \"./map.ts\";\nimport type { Lateness, LatenessLimit, LatenessState } from \"./lateness.ts\";\nimport type { LinkFamily, LinkPolicy } from \"./link.ts\";\nimport { COVERAGE_KIND } from \"./assess.ts\";\nimport { canonicalKind, CATEGORIES, KIND_ALIASES, knownKind, TAXONOMY } from \"./taxonomy.ts\";\n\n// =============================================================================\n// The gate between a schema and its type\n// =============================================================================\n\n// This type removes the intersections and the names of the interfaces. It keeps the readonly keys and the optional keys.\ntype Plain<T> = T extends string | number | boolean | null | undefined ? T : { [K in keyof T]: Plain<T[K]> };\n\n// This type is true when the two types are the same after `Plain`. The comparison of two generic functions finds each difference of a readonly key or an optional key.\ntype Same<A, B> = (<G>() => G extends Plain<A> ? 1 : 2) extends <G>() => G extends Plain<B> ? 1 : 2 ? true : false;\n\n/** This type is the error of `schemaOf`. The type check shows its key when a schema does not match its type. */\nexport interface SchemaDrift<T> {\n readonly \"The output or the input of this schema is not exactly its type.\": T;\n}\n\n// This type is `unknown` when the output and the input of the schema are exactly the type. Else it is the error.\ntype Exact<S extends z.ZodType, T> = Same<z.output<S>, T> extends true ? (Same<z.input<S>, T> extends true ? unknown : SchemaDrift<T>) : SchemaDrift<T>;\n\n/**\n * This function gives a schema the type of its contract. The type check fails when the output or the\n * input of the schema is not exactly the type `T`. The readonly keys and the optional keys must also\n * be the same. The function changes nothing at run time.\n *\n * The package checks its declarations in isolation. Thus each exported schema has the short type\n * `z.ZodType<T, T>`. This function compares the full type of the schema to `T` first.\n */\nexport function schemaOf<T>(): <S extends z.ZodType<T, T>>(schema: S & Exact<S, T>) => z.ZodType<T, T> {\n return (schema) => schema;\n}\n\n// The brand of `contracts.ts` is a `unique symbol` of the types only, and `.brand()` of zod has a different symbol.\n// So this cast gives the non-empty string schema the branded type of the id. It is the one cast of this file.\nfunction idSchema<T extends Id<string>>(): z.ZodType<T, T> {\n const nonEmpty: z.ZodType<string, string> = z.string().min(1, \"An id is a non-empty string.\");\n return nonEmpty as z.ZodType<T, T>;\n}\n\n// =============================================================================\n// Time, ids and counts\n// =============================================================================\n\n/** This schema checks a time in milliseconds since the epoch. A zod number is finite, so it refuses `Infinity` and `NaN`. */\nexport const instantSchema: z.ZodType<Instant, Instant> = schemaOf<Instant>()(z.number());\n\n/** This schema checks a length of time in milliseconds. A duration is finite, and it is 0 or more. */\nexport const durationSchema: z.ZodType<Duration, Duration> = schemaOf<Duration>()(z.number().nonnegative(\"A duration is 0 or more.\"));\n\n/** This schema checks the id of a source adapter. */\nexport const sourceIdSchema: z.ZodType<SourceId, SourceId> = idSchema<SourceId>();\n/** This schema checks the id of a delivery channel. */\nexport const channelIdSchema: z.ZodType<ChannelId, ChannelId> = idSchema<ChannelId>();\n/** This schema checks the id of an observation. */\nexport const observationIdSchema: z.ZodType<ObservationId, ObservationId> = idSchema<ObservationId>();\n/** This schema checks the id of a report. */\nexport const reportIdSchema: z.ZodType<ReportId, ReportId> = idSchema<ReportId>();\n/** This schema checks the id of a person. */\nexport const personIdSchema: z.ZodType<PersonId, PersonId> = idSchema<PersonId>();\n/** This schema checks the id of a place. */\nexport const placeIdSchema: z.ZodType<PlaceId, PlaceId> = idSchema<PlaceId>();\n\n// A count and an index are integers, 0 or more. The fields that use it state a count or a position in words.\nconst count = (): z.ZodInt => z.int().nonnegative(\"A count is an integer, 0 or more.\");\n\n// =============================================================================\n// The event\n// =============================================================================\n\n/** This schema checks a CAP status. */\nexport const statusSchema: z.ZodType<Status, Status> = schemaOf<Status>()(z.enum([\"actual\", \"exercise\", \"system\", \"test\", \"draft\"]));\n\n/** This schema checks a CAP message type, without `ack` and `error`. */\nexport const operationSchema: z.ZodType<Operation, Operation> = schemaOf<Operation>()(z.enum([\"alert\", \"update\", \"cancel\"]));\n\n/** This schema checks a CAP severity. */\nexport const severitySchema: z.ZodType<Severity, Severity> = schemaOf<Severity>()(z.enum([\"extreme\", \"severe\", \"moderate\", \"minor\", \"unknown\"]));\n\n/** This schema checks a CAP urgency. */\nexport const urgencySchema: z.ZodType<Urgency, Urgency> = schemaOf<Urgency>()(z.enum([\"immediate\", \"expected\", \"future\", \"past\", \"unknown\"]));\n\n/** This schema checks a CAP certainty. */\nexport const certaintySchema: z.ZodType<Certainty, Certainty> = schemaOf<Certainty>()(z.enum([\"observed\", \"likely\", \"possible\", \"unlikely\", \"unknown\"]));\n\n/** This schema checks a CAP response type. */\nexport const responseTypeSchema: z.ZodType<ResponseType, ResponseType> = schemaOf<ResponseType>()(\n z.enum([\"shelter\", \"evacuate\", \"prepare\", \"execute\", \"avoid\", \"monitor\", \"assess\", \"allclear\", \"none\"]),\n);\n\n/** This schema checks a category. The values come from `CATEGORIES` of the taxonomy. */\nexport const categorySchema: z.ZodType<Category, Category> = schemaOf<Category>()(z.enum(CATEGORIES));\n\n/** This schema checks the stage of a hazard message. */\nexport const significanceSchema: z.ZodType<Significance, Significance> = schemaOf<Significance>()(\n z.enum([\"warning\", \"watch\", \"advisory\", \"statement\", \"outlook\", \"observation\"]),\n);\n\n// Each code that `kindCodeSchema` takes, sorted: each code of `TAXONOMY`, each old code, and the coverage form of\n// each, when the rule of the schema takes it. The rule is the one test, so the list and the parse agree. A test\n// gives its own old codes with a mock of the taxonomy, so the list reads `KIND_ALIASES` here.\nconst kindCodes = (): string[] => {\n const codes = [...Object.keys(TAXONOMY), ...Object.keys(KIND_ALIASES)];\n const takes = (code: string): boolean => knownKind(canonicalKind(code));\n const all = new Set([...codes, ...codes.map((code) => `${COVERAGE_KIND}.${code}`)].filter(takes));\n return [...all].sort(compareCodeUnits);\n};\n\n/**\n * This schema checks a code of the taxonomy, or a prefix of a code by its parts. `knownKind` is the one rule:\n * a prefix by parts is also a code, so `met` and `met.flood` pass and `met.fl` does not. A kind with a typo\n * matches no alert, so this rule holds for each kind that a person or an adapter names. The parse first\n * changes an old code to its new code (`canonicalKind`). This change is not a transform, so the JSON Schema stays.\n *\n * The JSON Schema is an enum of each code that the rule takes. zod puts it one time in `$defs`, with the id `KindCode`.\n * The schema stays a string schema and not `z.enum`, because zod makes a record with enum keys need each key.\n */\nexport const kindCodeSchema: z.ZodType<string, string> = z\n .string()\n .overwrite((code) => canonicalKind(code))\n .refine(knownKind, \"The kind code is not in the taxonomy.\")\n .meta({ id: \"KindCode\", description: \"A code of the taxonomy, an old code, or the coverage form of one of them.\", enum: kindCodes() });\n\n// The prefix of a topic key, and the problem of a topic id that is not a code of the taxonomy.\nconst TOPIC_PREFIX = \"topic:\";\nconst TOPIC_PROBLEM = \"The id of a topic is a code of the taxonomy, or a prefix of one by its parts.\";\n// A topic key with an old code changes to the key of its new code. Each other key stays.\nconst canonicalKey = (key: string): string => (key.startsWith(TOPIC_PREFIX) ? `${TOPIC_PREFIX}${canonicalKind(key.slice(TOPIC_PREFIX.length))}` : key);\n\n/** This schema checks a kind. Its code must be in the taxonomy: `knownKind` gives true. This rule is the runtime gate of the closed taxonomy. */\nexport const kindSchema: z.ZodType<Kind, Kind> = schemaOf<Kind>()(\n z\n .strictObject({\n code: kindCodeSchema,\n significance: significanceSchema.exactOptional(),\n label: z.string(),\n })\n .readonly(),\n);\n\n/** This schema checks a position: the longitude in [-180, 180], then the latitude in [-90, 90]. */\nexport const positionSchema: z.ZodType<Position, Position> = schemaOf<Position>()(\n z.tuple([z.number().min(-180).max(180), z.number().min(-90).max(90)]).readonly(),\n);\n\n/** This schema checks the code of a region in one system of codes. */\nexport const regionCodeSchema: z.ZodType<RegionCode, RegionCode> = schemaOf<RegionCode>()(\n z.strictObject({ system: z.string(), code: z.string() }).readonly(),\n);\n\n// The polygon and the circle of an area. An area and a shape of the map share them.\nconst polygonObject = z.strictObject({\n type: z.literal(\"polygon\"),\n rings: z.array(z.array(positionSchema).readonly()).readonly(),\n block: z.string().exactOptional(),\n});\nconst circleObject = z.strictObject({ type: z.literal(\"circle\"), center: positionSchema, radiusKm: z.number(), block: z.string().exactOptional() });\n\n/** This schema checks one area of an event: a polygon, a circle, a region code or a watched place. */\nexport const areaSchema: z.ZodType<Area, Area> = schemaOf<Area>()(\n z\n .discriminatedUnion(\"type\", [\n polygonObject,\n circleObject,\n z.strictObject({ type: z.literal(\"code\"), system: z.string(), code: z.string(), block: z.string().exactOptional() }),\n z.strictObject({ type: z.literal(\"place\"), place: placeIdSchema }),\n ])\n .readonly(),\n);\n\n/** This schema checks a thing that an event is about, other than a place. */\nexport const subjectSchema: z.ZodType<Subject, Subject> = schemaOf<Subject>()(\n z.strictObject({ system: z.string(), id: z.string(), label: z.string().exactOptional() }).readonly(),\n);\n\n/** This schema checks a key that two sources share for one real event. */\nexport const correlationKeySchema: z.ZodType<CorrelationKey, CorrelationKey> = schemaOf<CorrelationKey>()(\n z.strictObject({ system: z.string(), id: z.string() }).readonly(),\n);\n\n/** This schema checks one raw message as a source gave it. */\nexport const observationSchema: z.ZodType<Observation, Observation> = schemaOf<Observation>()(\n z\n .strictObject({\n id: observationIdSchema,\n source: sourceIdSchema,\n fetched: instantSchema,\n contentType: z.string(),\n body: z.string(),\n transport: z\n .strictObject({\n url: z.string().exactOptional(),\n status: z.number().exactOptional(),\n latency: durationSchema,\n etag: z.string().exactOptional(),\n lastModified: z.string().exactOptional(),\n })\n .readonly(),\n })\n .readonly(),\n);\n\n/**\n * This schema checks one report. A report has one area or more, or one subject or more. The merge\n * takes the areas of an incident from its heads. So a report with no area and no subject can empty\n * the places of a life-safety incident.\n */\nexport const reportSchema: z.ZodType<Report, Report> = schemaOf<Report>()(\n z\n .strictObject({\n id: reportIdSchema,\n source: sourceIdSchema,\n origin: z.string(),\n key: z.string(),\n references: z.array(z.string()).readonly(),\n correlation: z.array(correlationKeySchema).readonly(),\n status: statusSchema,\n op: operationSchema,\n kind: kindSchema,\n categories: z.array(categorySchema).readonly(),\n severity: severitySchema,\n urgency: urgencySchema,\n certainty: certaintySchema,\n response: z.array(responseTypeSchema).readonly(),\n sent: instantSchema,\n received: instantSchema,\n effective: instantSchema.exactOptional(),\n onset: instantSchema.exactOptional(),\n expires: instantSchema.exactOptional(),\n ends: instantSchema.exactOptional(),\n areas: z.array(areaSchema).readonly(),\n areaText: z.string().exactOptional(),\n about: z.array(subjectSchema).readonly(),\n addresses: z.array(personIdSchema).min(1, \"A private report has one address or more.\").readonly().exactOptional(),\n sender: z.string(),\n headline: z.string(),\n description: z.string().exactOptional(),\n instruction: z.string().exactOptional(),\n web: z.string().exactOptional(),\n observation: observationIdSchema,\n parameters: z.record(z.string(), z.array(z.string()).readonly()).readonly(),\n })\n .readonly()\n .refine((report) => report.areas.length > 0 || report.about.length > 0 || (report.addresses?.length ?? 0) > 0, {\n error: \"A report has one area or more, one subject or more, or one address or more.\",\n path: [\"areas\"],\n }),\n);\n\n// =============================================================================\n// The indicator contract\n// =============================================================================\n\n/** This schema checks the id of a dimension. The values come from `DIMENSION_IDS`. */\nexport const dimensionIdSchema: z.ZodType<DimensionId, DimensionId> = schemaOf<DimensionId>()(z.enum(DIMENSION_IDS));\n\n/** This schema checks the kind of the area of a measure. The values come from `INDICATOR_AREA_KINDS`. */\nexport const indicatorAreaKindSchema: z.ZodType<IndicatorAreaKind, IndicatorAreaKind> = schemaOf<IndicatorAreaKind>()(z.enum(INDICATOR_AREA_KINDS));\n\n/** This schema checks the direction of a change that is a signal. The values come from `MOVES`. */\nexport const moveSchema: z.ZodType<Move, Move> = schemaOf<Move>()(z.enum(MOVES));\n\n/** This schema checks the baseline that a source gives. The values come from `OWN_BASELINES`. */\nexport const ownBaselineSchema: z.ZodType<OwnBaseline, OwnBaseline> = schemaOf<OwnBaseline>()(z.enum(OWN_BASELINES));\n\n/** This schema checks the area of one reading. A line has two positions or more. */\nexport const indicatorAreaSchema: z.ZodType<IndicatorArea, IndicatorArea> = schemaOf<IndicatorArea>()(\n z\n .discriminatedUnion(\"type\", [\n z.strictObject({ type: z.literal(\"code\"), system: z.string(), code: z.string() }),\n z.strictObject({ type: z.literal(\"point\"), at: positionSchema }),\n z.strictObject({ type: z.literal(\"line\"), path: z.array(positionSchema).min(2, \"A line has two positions or more.\").readonly() }),\n z.strictObject({ type: z.literal(\"polygon\"), rings: z.array(z.array(positionSchema).readonly()).readonly() }),\n z.strictObject({ type: z.literal(\"zone\"), system: z.string(), code: z.string() }),\n z.strictObject({ type: z.literal(\"world\") }),\n ])\n .readonly(),\n);\n\n// A time that is more than 0. A cadence of 0 is not a cadence, and a backfill of 0 is no backfill.\nconst positiveDuration = z.number().positive(\"The time is more than 0.\");\n\n/** This schema checks one measure of a source. Its unit is in the grammar of `@mark1russell7/quantity`. */\nexport const measureDeclarationSchema: z.ZodType<MeasureDeclaration, MeasureDeclaration> = schemaOf<MeasureDeclaration>()(\n z\n .strictObject({\n id: z.string().regex(MEASURE_ID, \"The id of a measure is small letters, digits and hyphens, with a letter first, up to 40 characters.\"),\n dimension: dimensionIdSchema,\n title: z.string(),\n unit: z.string().refine((unit) => tryParseUnit(unit) !== undefined, \"The unit is not in the grammar of @mark1russell7/quantity.\"),\n area: indicatorAreaKindSchema,\n moves: moveSchema,\n baseline: ownBaselineSchema,\n cadence: positiveDuration.exactOptional(),\n delay: durationSchema.exactOptional(),\n backfill: positiveDuration.exactOptional(),\n })\n .readonly(),\n);\n\n// The measures of a source. Two measures of one source do not have one id, because a reading names its measure by the id.\nconst sourceMeasures = z\n .array(measureDeclarationSchema)\n .readonly()\n .refine((measures) => new Set(measures.map((measure) => measure.id)).size === measures.length, \"Two measures of the source have one id.\");\n\n/** This schema checks one value of one series of a measure. The values are finite numbers. */\nexport const readingSchema: z.ZodType<Reading, Reading> = schemaOf<Reading>()(\n z\n .strictObject({\n source: sourceIdSchema,\n measure: z.string(),\n series: z.string().min(1, \"The id of a series is not empty.\"),\n version: z.string().regex(SERIES_VERSION, \"The version of a series is letters, digits, dots and hyphens, up to 40 characters.\").exactOptional(),\n at: instantSchema,\n value: z.number(),\n area: indicatorAreaSchema,\n cadence: positiveDuration.exactOptional(),\n expected: z.number().exactOptional(),\n flagged: z.boolean().exactOptional(),\n observation: observationIdSchema,\n })\n .readonly(),\n);\n\n// =============================================================================\n// The source contract\n// =============================================================================\n\n/** This schema checks how a source gives its data. */\nexport const transportSchema: z.ZodType<Transport, Transport> = schemaOf<Transport>()(z.enum([\"poll\", \"stream\", \"push\", \"radio\"]));\n\n/** This schema checks a resource of the cell. The values come from `CELL_RESOURCES`. */\nexport const cellResourceSchema: z.ZodType<CellResource, CellResource> = schemaOf<CellResource>()(z.enum(CELL_RESOURCES));\n\n// The failure domains outside the cell. contracts.ts, lines 240 and 476: \"Do not put the resources of the cell here.\"\nconst outsideDomains = z\n .array(z.string().refine((domain) => !CELL_RESOURCES.some((resource) => resource === domain), \"A resource of the cell is not a failure domain outside the cell.\"))\n .readonly();\n\n// The internet link of the cell finds each host through the DNS resolver of the cell, so a use of `internet` needs `dns`.\nconst cellUses = z\n .array(cellResourceSchema)\n .readonly()\n .refine((uses) => !uses.includes(\"internet\") || uses.includes(\"dns\"), \"A use of the internet needs the DNS resolver of the cell: add dns to uses.\");\n\n/** This schema checks the facts of a source. Its `dependsOn` holds no resource of the cell. */\nexport const sourceDescriptorSchema: z.ZodType<SourceDescriptor, SourceDescriptor> = schemaOf<SourceDescriptor>()(\n z\n .strictObject({\n id: sourceIdSchema,\n title: z.string(),\n origins: z.array(z.string()).readonly(),\n dependsOn: outsideDomains,\n uses: cellUses,\n kinds: z.array(kindCodeSchema).readonly(),\n coverage: z.union([z.array(areaSchema).readonly(), z.literal(\"global\")]),\n transport: transportSchema,\n interval: durationSchema,\n slowAfter: durationSchema,\n maxQuiet: durationSchema.exactOptional(),\n auth: z.enum([\"none\", \"key\", \"oauth\"]),\n listing: z.literal(\"snapshot\").exactOptional(),\n canary: z.string().exactOptional(),\n measures: sourceMeasures.exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks a place that the system watches, as the adapters see it. */\nexport const watchedPlaceSchema: z.ZodType<WatchedPlace, WatchedPlace> = schemaOf<WatchedPlace>()(\n z\n .strictObject({\n id: placeIdSchema,\n at: positionSchema.exactOptional(),\n codes: z.array(regionCodeSchema).readonly(),\n bufferKm: z.number(),\n })\n .readonly(),\n);\n\n/** This schema checks what a fetch asks for. */\nexport const watchSchema: z.ZodType<Watch, Watch> = schemaOf<Watch>()(\n z.strictObject({ places: z.array(watchedPlaceSchema).readonly(), kinds: z.array(kindCodeSchema).readonly().exactOptional() }).readonly(),\n);\n\n/** This schema checks the state that a source keeps between two fetches. */\nexport const cursorSchema: z.ZodType<Cursor, Cursor> = schemaOf<Cursor>()(z.record(z.string(), z.string()).readonly());\n\n/** This schema checks why a fetch failed. */\nexport const fetchFailureSchema: z.ZodType<FetchFailure, FetchFailure> = schemaOf<FetchFailure>()(\n z\n .discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.enum([\"network\", \"timeout\", \"server\"]), message: z.string(), retryAfter: durationSchema.exactOptional() }),\n z.strictObject({ kind: z.literal(\"rate-limited\"), message: z.string(), retryAfter: durationSchema.exactOptional() }),\n z.strictObject({ kind: z.enum([\"auth\", \"refused\"]), message: z.string() }),\n ])\n .readonly(),\n);\n\n/** This schema checks the result of one fetch. */\nexport const fetchOutcomeSchema: z.ZodType<FetchOutcome, FetchOutcome> = schemaOf<FetchOutcome>()(\n z\n .discriminatedUnion(\"ok\", [\n z.strictObject({\n ok: z.literal(true),\n observations: z.array(observationSchema).readonly(),\n cursor: cursorSchema.exactOptional(),\n complete: z.boolean(),\n asOf: instantSchema.exactOptional(),\n }),\n z.strictObject({ ok: z.literal(false), failure: fetchFailureSchema }),\n ])\n .readonly(),\n);\n\n/** This schema checks a part of a message that the map function did not understand. The field `lossy` is absent or true. */\nexport const mapProblemSchema: z.ZodType<MapProblem, MapProblem> = schemaOf<MapProblem>()(\n z.strictObject({ path: z.string(), message: z.string(), fatal: z.boolean(), lossy: z.literal(true).exactOptional() }).readonly(),\n);\n\n/** This schema checks the result of the map function. */\nexport const mapResultSchema: z.ZodType<MapResult, MapResult> = schemaOf<MapResult>()(\n z\n .strictObject({\n reports: z.array(reportSchema).readonly(),\n problems: z.array(mapProblemSchema).readonly(),\n readings: z.array(readingSchema).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the result of the canary check of a source. */\nexport const canaryResultSchema: z.ZodType<CanaryResult, CanaryResult> = schemaOf<CanaryResult>()(\n z.strictObject({ pass: z.boolean(), reason: z.string() }).readonly(),\n);\n\n/** This schema checks the record of one fetch. The three counts are integers, 0 or more (`contracts.ts`, lines 356, 358 and 360). */\nexport const fetchRecordSchema: z.ZodType<FetchRecord, FetchRecord> = schemaOf<FetchRecord>()(\n z\n .strictObject({\n source: sourceIdSchema,\n at: instantSchema,\n took: durationSchema,\n failure: fetchFailureSchema.exactOptional(),\n fresh: count(),\n fatal: count(),\n lossy: count().exactOptional(),\n canary: canaryResultSchema.exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the result of a lookup of the region codes of a position. */\nexport const locateOutcomeSchema: z.ZodType<LocateOutcome, LocateOutcome> = schemaOf<LocateOutcome>()(\n z\n .discriminatedUnion(\"ok\", [\n z.strictObject({ ok: z.literal(true), codes: z.array(regionCodeSchema).readonly() }),\n z.strictObject({ ok: z.literal(false), failure: fetchFailureSchema }),\n ])\n .readonly(),\n);\n\n// =============================================================================\n// Health and coverage\n// =============================================================================\n\n/** This schema checks the health of a source. */\nexport const healthStateSchema: z.ZodType<HealthState, HealthState> = schemaOf<HealthState>()(\n z.enum([\"unknown\", \"healthy\", \"slow\", \"failing\", \"silent\", \"changed\"]),\n);\n\n/** This schema checks the health of one source at one time. */\nexport const sourceHealthSchema: z.ZodType<SourceHealth, SourceHealth> = schemaOf<SourceHealth>()(\n z\n .strictObject({\n source: sourceIdSchema,\n state: healthStateSchema,\n since: instantSchema,\n lastSuccess: instantSchema.exactOptional(),\n lastFailure: z.strictObject({ at: instantSchema, failure: fetchFailureSchema }).readonly().exactOptional(),\n reason: z.string(),\n })\n .readonly(),\n);\n\n/** This schema checks the coverage of one kind at one place. The two counts are integers, 0 or more (`contracts.ts`, lines 416 and 432). */\nexport const coverageSchema: z.ZodType<Coverage, Coverage> = schemaOf<Coverage>()(\n z\n .strictObject({\n place: placeIdSchema,\n kind: z.string(),\n sources: z.array(sourceIdSchema).readonly(),\n independent: count(),\n proven: z.boolean(),\n faults: z.array(z.string()).readonly(),\n commonResources: z.array(cellResourceSchema).readonly(),\n required: count(),\n })\n .readonly(),\n);\n\n// =============================================================================\n// Incidents\n// =============================================================================\n\n/**\n * This schema checks one incident. It has one report or more (`contracts.ts`, line 430). Its report ids\n * go from the smallest, each one time, and its anchor is the smallest (lines 434 and 436). The order\n * is the order of the code units, as in the merge. The corroboration is a count (line 450).\n */\n/** This schema checks one line of an incident: a report that gives the values of the incident, with its areas. */\nexport const incidentLineSchema: z.ZodType<IncidentLine, IncidentLine> = schemaOf<IncidentLine>()(\n z\n .strictObject({\n report: reportIdSchema,\n kind: kindSchema,\n severity: severitySchema,\n urgency: urgencySchema,\n certainty: certaintySchema,\n onset: instantSchema.exactOptional(),\n areas: z.array(areaSchema).readonly(),\n })\n .readonly(),\n);\n\nexport const incidentSchema: z.ZodType<Incident, Incident> = schemaOf<Incident>()(\n z\n .strictObject({\n anchor: reportIdSchema,\n reports: z.array(reportIdSchema).min(1, \"An incident has one report or more.\").readonly(),\n status: statusSchema,\n kind: kindSchema,\n severity: severitySchema,\n urgency: urgencySchema,\n certainty: certaintySchema,\n onset: instantSchema.exactOptional(),\n expires: instantSchema.exactOptional(),\n areas: z.array(areaSchema).readonly(),\n about: z.array(subjectSchema).readonly(),\n addresses: z.array(personIdSchema).min(1, \"A private incident has one address or more.\").readonly().exactOptional(),\n live: z.boolean(),\n corroboration: count(),\n lines: z.array(incidentLineSchema).min(2, \"An incident with lines has two lines or more.\").readonly().exactOptional(),\n })\n .readonly()\n .refine((incident) => (incident.lines ?? []).every((line) => incident.reports.includes(line.report)), {\n error: \"The report of each line is a report of the incident.\",\n path: [\"lines\"],\n })\n .refine((incident) => incident.reports[0] === incident.anchor, { error: \"The anchor of an incident is its smallest report id.\", path: [\"anchor\"] })\n .refine(\n (incident) =>\n incident.reports.every((id, index) => {\n const before = incident.reports[index - 1];\n return before === undefined || before < id;\n }),\n { error: \"The report ids of an incident go from the smallest, each one time.\", path: [\"reports\"] },\n ),\n);\n\n// =============================================================================\n// Delivery\n// =============================================================================\n\n/** This schema checks the level of an alert. The values come from `LEVELS`. */\nexport const levelSchema: z.ZodType<Level, Level> = schemaOf<Level>()(z.enum(LEVELS));\n\n/** This schema checks the limit of a why line: each limit is an integer of 1 or more. */\nexport const whyLimitSchema: z.ZodType<WhyLimit, WhyLimit> = schemaOf<WhyLimit>()(\n z\n .strictObject({\n chars: z.number().int().min(1).exactOptional(),\n words: z.number().int().min(1).exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the facts of a channel. Its `dependsOn` holds no resource of the cell. */\n/** This function tells if a text is the source of a regular expression with the flag `u`. */\nconst isPattern = (source: string): boolean => {\n try {\n new RegExp(source, \"u\");\n return true;\n } catch {\n return false;\n }\n};\n\n/** This schema checks one field of the address of a channel. Its pattern is a regular expression with the flag `u`. */\nexport const addressFieldSchema: z.ZodType<AddressField, AddressField> = schemaOf<AddressField>()(\n z\n .strictObject({\n name: z.string().min(1, \"The name of an address field is a non-empty string.\"),\n required: z.boolean(),\n pattern: z.string().refine(isPattern, \"The pattern of an address field is a regular expression with the flag u.\"),\n form: z.string().min(1, \"The form of an address field is a non-empty text.\"),\n optIn: z.boolean().exactOptional(),\n })\n .readonly(),\n);\n\nexport const channelDescriptorSchema: z.ZodType<ChannelDescriptor, ChannelDescriptor> = schemaOf<ChannelDescriptor>()(\n z\n .strictObject({\n id: channelIdSchema,\n title: z.string(),\n dependsOn: outsideDomains,\n // A lazy schema: the schema of a node key comes later in this file.\n services: z.array(z.lazy(() => nodeKeySchema)).readonly().exactOptional(),\n api: z.array(z.lazy(() => nodeKeySchema)).min(1, \"A list of endpoints is not empty.\").readonly().exactOptional(),\n uses: cellUses,\n breaksThrough: z.boolean(),\n repeats: z.boolean(),\n ack: z.enum([\"none\", \"poll\", \"callback\"]),\n maxTitle: z.number(),\n maxBody: z.number(),\n costUsd: z.number().exactOptional(),\n maxInFlight: z.number().int().min(1).exactOptional(),\n exclusive: z.boolean().exactOptional(),\n why: whyLimitSchema.exactOptional(),\n address: z.array(addressFieldSchema).readonly().exactOptional(),\n ackLevels: z.array(levelSchema).readonly().exactOptional(),\n })\n .readonly()\n .refine((channel) => channel.ack !== \"none\" || (channel.ackLevels ?? []).length === 0, {\n error: \"A channel with the ack none asks for no acknowledgment, thus it has no ackLevels.\",\n path: [\"ackLevels\"],\n })\n // An endpoint is a service that the calls reach. Thus the delivery layer has an edge from it (AL-65).\n .refine((channel) => (channel.api ?? []).every((key) => (channel.services ?? []).includes(key)), {\n error: \"Each endpoint in api is also in services.\",\n path: [\"api\"],\n }),\n);\n\n/** This schema checks one message to one person on one channel. A `life-safety` message is not quiet (`contracts.ts`, line 516). */\nexport const messageSchema: z.ZodType<Message, Message> = schemaOf<Message>()(\n z\n .strictObject({\n key: z.string(),\n person: personIdSchema,\n level: levelSchema,\n title: z.string(),\n body: z.string(),\n url: z.string().exactOptional(),\n incident: reportIdSchema,\n expires: instantSchema.exactOptional(),\n quiet: z.boolean(),\n useReserve: z.boolean().exactOptional(),\n why: z.string().min(1).exactOptional(),\n })\n .readonly()\n .refine((message) => !(message.level === \"life-safety\" && message.quiet), {\n error: \"A life-safety message is not quiet at any time.\",\n path: [\"quiet\"],\n }),\n);\n\n/** This schema checks the address of a person on a channel. */\nexport const addressSchema: z.ZodType<Address, Address> = schemaOf<Address>()(z.record(z.string(), z.string()).readonly());\n\n/** This schema checks the receipt of a sent message. */\nexport const receiptSchema: z.ZodType<Receipt, Receipt> = schemaOf<Receipt>()(z.record(z.string(), z.string()).readonly());\n\n/** This schema checks the kind of a failed send (`ChannelFailureKind`). */\nexport const channelFailureKindSchema: z.ZodType<ChannelFailureKind, ChannelFailureKind> = schemaOf<ChannelFailureKind>()(\n z.enum([\"network\", \"timeout\", \"server\", \"rate-limited\", \"reserved\", \"auth\", \"refused\", \"consent\", \"quiet\", \"expired\"]),\n);\n\n/** This schema checks the result of a send. */\nexport const sendOutcomeSchema: z.ZodType<SendOutcome, SendOutcome> = schemaOf<SendOutcome>()(\n z\n .discriminatedUnion(\"ok\", [\n z.strictObject({ ok: z.literal(true), receipt: receiptSchema, accepted: instantSchema }),\n z.strictObject({\n ok: z.literal(false),\n kind: channelFailureKindSchema,\n message: z.string(),\n retryAfter: durationSchema.exactOptional(),\n }),\n ])\n .readonly(),\n);\n\n/** This schema checks the state of a sent message. */\nexport const deliveryStateSchema: z.ZodType<DeliveryState, DeliveryState> = schemaOf<DeliveryState>()(\n z.enum([\"accepted\", \"delivered\", \"acknowledged\", \"expired\", \"failed\"]),\n);\n\n/** This schema checks the state of a sent message, as the channel tells it. */\nexport const deliveryStatusSchema: z.ZodType<DeliveryStatus, DeliveryStatus> = schemaOf<DeliveryStatus>()(\n z\n .strictObject({\n state: deliveryStateSchema,\n at: instantSchema,\n by: z.string().exactOptional(),\n reason: z.string().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks one step of an escalation. */\nexport const escalationStepSchema: z.ZodType<EscalationStep, EscalationStep> = schemaOf<EscalationStep>()(\n z.strictObject({ channel: channelIdSchema, at: durationSchema }).readonly(),\n);\n\n/** This schema checks one accepted send. The step is an index from 0 (`contracts.ts`, line 593). */\nexport const deliverySchema: z.ZodType<Delivery, Delivery> = schemaOf<Delivery>()(\n z\n .strictObject({\n key: z.string(),\n incident: reportIdSchema,\n level: levelSchema,\n person: personIdSchema,\n channel: channelIdSchema,\n step: count(),\n at: instantSchema,\n receipt: receiptSchema.exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks an acknowledgment from a person, by a channel or the UI. */\nexport const acknowledgmentSchema: z.ZodType<Acknowledgment, Acknowledgment> = schemaOf<Acknowledgment>()(\n z\n .strictObject({\n incident: reportIdSchema,\n level: levelSchema,\n person: personIdSchema,\n at: instantSchema,\n via: z.union([channelIdSchema, z.literal(\"ui\")]),\n })\n .readonly(),\n);\n\n/** This schema checks the end of the escalations of a person in an incident. An end with no reason is an end `ended`. */\nexport const escalationEndSchema: z.ZodType<EscalationEnd, EscalationEnd> = schemaOf<EscalationEnd>()(\n z\n .strictObject({\n incident: reportIdSchema,\n person: personIdSchema,\n at: instantSchema,\n reason: z.enum([\"ended\", \"muted\"]).exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks an end mark of a report of a snapshot source. */\nexport const endMarkSchema: z.ZodType<EndMark, EndMark> = schemaOf<EndMark>()(\n z\n .strictObject({\n report: reportIdSchema,\n at: instantSchema,\n ended: z.boolean(),\n asOf: instantSchema.exactOptional(),\n })\n .readonly(),\n);\n\n// =============================================================================\n// The assessment\n// =============================================================================\n\n/** This schema checks the level of an incident for a person, or `none`. The values come from `ASSESSED_LEVELS`. */\nexport const assessedLevelSchema: z.ZodType<AssessedLevel, AssessedLevel> = schemaOf<AssessedLevel>()(z.enum(ASSESSED_LEVELS));\n\n// The two lookups of a table. Each lookup has a level for each value.\nconst severityLookup = z.record(severitySchema, assessedLevelSchema).readonly();\nconst urgencyLookup = z.record(urgencySchema, assessedLevelSchema).readonly();\n\n/** This schema checks the highest levels for the severity and the urgency. Each lookup has a level for each value. */\nexport const levelTableSchema: z.ZodType<LevelTable, LevelTable> = schemaOf<LevelTable>()(\n z.strictObject({ severity: severityLookup, urgency: urgencyLookup, pastWithin: z.number().min(0).exactOptional() }).readonly(),\n);\n\n/**\n * This schema checks a class of kinds with its own table. Each prefix of the class must be a code of\n * the taxonomy, because each policy names only known codes (`docs/CONTRACTS.md`, line 219).\n */\nexport const kindClassSchema: z.ZodType<KindClass, KindClass> = schemaOf<KindClass>()(\n z\n .strictObject({\n id: z.string(),\n kinds: z.array(kindCodeSchema).readonly(),\n statuses: z.array(statusSchema).readonly().exactOptional(),\n severity: severityLookup,\n urgency: urgencyLookup,\n pastWithin: z.number().min(0).exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the data of the first assessment. */\nexport const assessPolicySchema: z.ZodType<AssessPolicy, AssessPolicy> = schemaOf<AssessPolicy>()(\n z\n .strictObject({\n statuses: z.array(statusSchema).readonly(),\n classes: z.array(kindClassSchema).readonly(),\n otherwise: levelTableSchema,\n // The schema of the relevance policy comes later in this file.\n relevance: z.lazy(() => relevancePolicySchema).exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the kind of a subject. */\nexport const subjectKindSchema: z.ZodType<SubjectKind, SubjectKind> = schemaOf<SubjectKind>()(z.enum([\"place\", \"topic\", \"entity\"]));\n\n/** This schema checks a rule of a person. */\nexport const levelRuleSchema: z.ZodType<LevelRule, LevelRule> = schemaOf<LevelRule>()(\n z\n .strictObject({\n places: z.array(placeIdSchema).readonly().exactOptional(),\n kinds: z.array(kindCodeSchema).readonly().exactOptional(),\n through: z.array(subjectKindSchema).readonly().exactOptional(),\n max: assessedLevelSchema,\n })\n .readonly(),\n);\n\n/**\n * This schema checks the quiet window of a person. It does not check the time zone or the local\n * times. The contract gives a bad window a meaning: it makes no quiet send (`docs/CONTRACTS.md`,\n * line 278). `quietWindowProblems` finds a bad window.\n */\nexport const quietWindowSchema: z.ZodType<QuietWindow, QuietWindow> = schemaOf<QuietWindow>()(\n z.strictObject({ zone: z.string(), start: z.string(), end: z.string() }).readonly(),\n);\n\n/**\n * This schema checks a subject that a person watches. The id of a subject of the system `topic` is a code of\n * the taxonomy. The parse changes an old code to its new code first.\n */\nexport const subjectWatchSchema: z.ZodType<SubjectWatch, SubjectWatch> = schemaOf<SubjectWatch>()(\n z\n .strictObject({ system: z.string(), id: z.string().exactOptional() })\n .overwrite((subject) => (subject.system === \"topic\" && subject.id !== undefined ? { ...subject, id: canonicalKind(subject.id) } : subject))\n .refine((subject) => subject.system !== \"topic\" || subject.id === undefined || knownKind(subject.id), TOPIC_PROBLEM)\n .readonly(),\n);\n\n/** This schema checks the escalation of one level, with its optional subject. */\nexport const escalationPolicySchema: z.ZodType<EscalationPolicy, EscalationPolicy> = schemaOf<EscalationPolicy>()(\n z\n .strictObject({\n level: levelSchema,\n daily: z.strictObject({ zone: z.string(), time: z.string() }).readonly().exactOptional(),\n about: subjectWatchSchema.exactOptional(),\n steps: z.array(escalationStepSchema).readonly(),\n exhaustedAfter: durationSchema,\n })\n .readonly(),\n);\n\n// The rule of the life-safety warnings at one place of a person. The range is 0 or more.\nconst mandatoryRuleSchema: z.ZodType<MandatoryRule, MandatoryRule> = schemaOf<MandatoryRule>()(\n z.strictObject({ place: placeIdSchema, on: z.boolean(), rangeKm: z.number().min(0, \"The range of a rule is 0 km or more.\") }).readonly(),\n);\n\n/**\n * This schema checks the places and the rules of one person. A place has one rule of the life-safety warnings at\n * most. The schema of the interest graph comes later in this file.\n */\nexport const personWatchSchema: z.ZodType<PersonWatch, PersonWatch> = schemaOf<PersonWatch>()(\n z\n .strictObject({\n person: personIdSchema,\n places: z.array(placeIdSchema).readonly(),\n subjects: z.array(subjectWatchSchema).readonly().exactOptional(),\n rules: z.array(levelRuleSchema).readonly(),\n quiet: quietWindowSchema.exactOptional(),\n interests: z.lazy(() => interestGraphSchema).exactOptional(),\n mandatory: z\n .array(mandatoryRuleSchema)\n .refine((rules) => new Set(rules.map((rule) => rule.place)).size === rules.length, \"A place has one rule of the life-safety warnings at most.\")\n .readonly()\n .exactOptional(),\n })\n .readonly(),\n);\n\n// An estimate with each number from `min` to `max`, and an interval that holds the value.\nfunction estimateIn(min: number, max: number): z.ZodType<Estimate, Estimate> {\n const part = z.number().min(min).max(max);\n return schemaOf<Estimate>()(\n z\n .strictObject({ value: part, low: part, high: part })\n .refine((estimate) => estimate.low <= estimate.value && estimate.value <= estimate.high, \"The interval of an estimate holds its value: low <= value <= high.\")\n .readonly(),\n );\n}\n\n/** This schema checks a probability with its interval: each number is from 0 to 1. */\nexport const probabilitySchema: z.ZodType<Estimate, Estimate> = estimateIn(0, 1);\n\n/**\n * This schema checks a measured value with its interval. Each number is from 0 to `Number.MAX_SAFE_INTEGER`. Thus the\n * product of a probability and a count has a finite interval.\n */\nexport const estimateSchema: z.ZodType<Estimate, Estimate> = estimateIn(0, Number.MAX_SAFE_INTEGER);\n\n/** This schema checks a kind of area of an alert. */\nexport const alertAreaSchema: z.ZodType<AlertArea, AlertArea> = schemaOf<AlertArea>()(z.enum([\"county\", \"zone\"]));\n\n/** This schema checks the harm in one area under one active alert. */\nexport const underPriorSchema: z.ZodType<UnderPrior, UnderPrior> = schemaOf<UnderPrior>()(\n z.strictObject({ deaths: estimateSchema, injuries: estimateSchema, area: alertAreaSchema }).readonly(),\n);\n\n/** This schema checks the priors of one kind. */\nexport const kindPriorSchema: z.ZodType<KindPrior, KindPrior> = schemaOf<KindPrior>()(\n z\n .strictObject({\n verified: probabilitySchema.exactOptional(),\n deaths: estimateSchema.exactOptional(),\n injuries: estimateSchema.exactOptional(),\n under: z.partialRecord(significanceSchema, underPriorSchema).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks a file of priors, `alerts-priors/2`. */\nexport const scorePriorsSchema: z.ZodType<ScorePriors, ScorePriors> = schemaOf<ScorePriors>()(\n z\n .strictObject({\n format: z.literal(\"alerts-priors/2\"),\n kinds: z.record(kindCodeSchema, kindPriorSchema).readonly(),\n certainty: z\n .strictObject({\n observed: probabilitySchema.exactOptional(),\n likely: probabilitySchema.exactOptional(),\n possible: probabilitySchema.exactOptional(),\n unlikely: probabilitySchema.exactOptional(),\n unknown: probabilitySchema.exactOptional(),\n })\n .readonly(),\n })\n .readonly(),\n);\n\nconst priorKey = z.string().min(1, \"A key of the priors is a non-empty string.\");\n\n/** This schema checks one factor of a shadow score. */\nexport const scoreFactorSchema: z.ZodType<ScoreFactor, ScoreFactor> = schemaOf<ScoreFactor>()(\n z\n .strictObject({\n estimate: estimateSchema,\n from: z.union([\n z.strictObject({ table: z.enum([\"kinds\", \"certainty\"]), key: priorKey }).readonly(),\n z.strictObject({ table: z.literal(\"under\"), key: priorKey, significance: significanceSchema, area: alertAreaSchema }).readonly(),\n ]),\n })\n .readonly(),\n);\n\n// A factor of the table `under`.\nconst underFactorSchema = scoreFactorSchema.refine((factor) => factor.from.table === \"under\", \"A factor of the basis alert comes from the table under.\");\n\n/** This schema checks the expected harm of a shadow score. */\nexport const expectedHarmSchema: z.ZodType<ExpectedHarm, ExpectedHarm> = schemaOf<ExpectedHarm>()(\n z.strictObject({ deaths: estimateSchema, injuries: estimateSchema }).readonly(),\n);\n\n/**\n * This schema checks a shadow score. A score with no read names one or more factors that the priors do not give. A score\n * of the basis `alert` has its factors from the table `under`.\n */\nexport const shadowScoreSchema: z.ZodType<ShadowScore, ShadowScore> = schemaOf<ShadowScore>()(\n z\n .union([\n z.strictObject({\n read: z.literal(true),\n basis: z.literal(\"event\").exactOptional(),\n probability: scoreFactorSchema,\n deaths: scoreFactorSchema,\n injuries: scoreFactorSchema,\n expected: expectedHarmSchema,\n }),\n z.strictObject({\n read: z.literal(true),\n basis: z.literal(\"alert\"),\n deaths: underFactorSchema,\n injuries: underFactorSchema,\n expected: expectedHarmSchema,\n }),\n z.strictObject({\n read: z.literal(false),\n missing: z\n .array(z.enum([\"probability\", \"deaths\", \"injuries\"]))\n .min(1, \"A score with no read names each factor that the priors do not give.\")\n .readonly(),\n }),\n ])\n .readonly(),\n);\n\n// =============================================================================\n// Relevance (AL-35, `docs/RELEVANCE.md`)\n// =============================================================================\n\n// The key `person`, or `<system>:<id>` with a system of SUBJECT_SYSTEMS and an id that is not empty.\nconst NODE_KEY = new RegExp(`^(?:person|(?:${Object.keys(SUBJECT_SYSTEMS).join(\"|\")}):.+)$`);\nconst nodeKeyText = z\n .string()\n .regex(NODE_KEY, \"A node key is `person`, or `<system>:<id>` with a system of SUBJECT_SYSTEMS and an id that is not empty.\")\n .overwrite(canonicalKey)\n .refine((key) => !key.startsWith(TOPIC_PREFIX) || knownKind(key.slice(TOPIC_PREFIX.length)), TOPIC_PROBLEM);\n\n/** This schema checks the key of a node of an interest graph (`contracts.ts`, `NodeKey`). */\nexport const nodeKeySchema: z.ZodType<NodeKey, NodeKey> = schemaOf<NodeKey>()(nodeKeyText);\n\n// A day, `YYYY-MM-DD`.\nconst dayText = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/, \"A day is `YYYY-MM-DD`.\");\n\n// A number from 0 to 1.\nconst unit = z.number().min(0).max(1);\n\n/** This schema checks the kind of an edge. */\nexport const edgeKindSchema: z.ZodType<EdgeKind, EdgeKind> = schemaOf<EdgeKind>()(z.enum([\"physical\", \"cyber\", \"geographic\", \"logical\", \"interest\"]));\n\n/** This schema checks the origin of the weight of an edge. */\nexport const edgeOriginSchema: z.ZodType<EdgeOrigin, EdgeOrigin> = schemaOf<EdgeOrigin>()(\n z.enum([\"base\", \"places\", \"services\", \"delivery\", \"work\", \"data\", \"measured\", \"person\"]),\n);\n\n/**\n * This schema checks one edge of an interest graph. An edge does not start at the person, and it joins two\n * different nodes. An edge goes into the person when its kind is `interest`, and only then.\n */\nexport const interestEdgeSchema: z.ZodType<InterestEdge, InterestEdge> = schemaOf<InterestEdge>()(\n z\n .strictObject({\n id: z.string().min(1, \"The id of an edge is a non-empty string.\"),\n from: nodeKeySchema,\n to: nodeKeySchema,\n kind: edgeKindSchema,\n weight: probabilitySchema,\n origin: edgeOriginSchema,\n source: z.string().min(1, \"The source of a weight is a non-empty string.\").exactOptional(),\n date: dayText.exactOptional(),\n on: z.boolean(),\n })\n .refine((edge) => edge.from !== \"person\", \"An edge does not start at the person.\")\n .refine((edge) => edge.from !== edge.to, \"An edge joins two different nodes.\")\n .refine((edge) => (edge.kind === \"interest\") === (edge.to === \"person\"), \"An edge goes into the person when its kind is interest, and only then.\")\n .readonly(),\n);\n\n/** This schema checks a mute. A mute has a list of kinds, a list of subjects or both, and each list has one item or more. */\nexport const muteSchema: z.ZodType<Mute, Mute> = schemaOf<Mute>()(\n z\n .strictObject({\n id: z.string().min(1, \"The id of a mute is a non-empty string.\"),\n kinds: z\n .array(kindCodeSchema)\n .min(1, \"A list of a mute has one item or more.\")\n .readonly()\n .exactOptional(),\n subjects: z.array(nodeKeySchema).min(1, \"A list of a mute has one item or more.\").readonly().exactOptional(),\n until: instantSchema.exactOptional(),\n date: dayText,\n })\n .refine((mute) => mute.kinds !== undefined || mute.subjects !== undefined, \"A mute has a list of kinds, a list of subjects or both.\")\n .readonly(),\n);\n\n/** This schema checks the interest graph of a person, `alerts-interest/1`. The ids of the edges are unique, and so are the ids of the mutes. */\nexport const interestGraphSchema: z.ZodType<InterestGraph, InterestGraph> = schemaOf<InterestGraph>()(\n z\n .strictObject({\n format: z.literal(\"alerts-interest/1\"),\n person: personIdSchema,\n edges: z.array(interestEdgeSchema).readonly(),\n mutes: z.array(muteSchema).readonly(),\n labels: z.record(nodeKeyText, z.string().min(1, \"A label is a non-empty string.\")).readonly().exactOptional(),\n })\n .refine((graph) => new Set(graph.edges.map((edge) => edge.id)).size === graph.edges.length, \"The ids of the edges of a graph are unique.\")\n .refine((graph) => new Set(graph.mutes.map((mute) => mute.id)).size === graph.mutes.length, \"The ids of the mutes of a graph are unique.\")\n .readonly(),\n);\n\n/** This schema checks a subject of an incident that is a node of the graph of a person. */\nexport const subjectEntrySchema: z.ZodType<SubjectEntry, SubjectEntry> = schemaOf<SubjectEntry>()(\n z.strictObject({ node: nodeKeySchema, kind: subjectKindSchema, hit: probabilitySchema }).readonly(),\n);\n\n/** This schema checks one path of a relevance. A path has one edge or more. */\nexport const relevancePathSchema: z.ZodType<RelevancePath, RelevancePath> = schemaOf<RelevancePath>()(\n z\n .strictObject({\n subject: nodeKeySchema,\n edges: z.array(z.string().min(1, \"The id of an edge is a non-empty string.\")).min(1, \"A path has one edge or more.\").readonly(),\n chance: unit,\n })\n .readonly(),\n);\n\n/** This schema checks the why record of a relevance. */\nexport const whyRecordSchema: z.ZodType<WhyRecord, WhyRecord> = schemaOf<WhyRecord>()(\n z\n .strictObject({\n rule: z.string().min(1, \"The rule of a why record is a non-empty string.\"),\n subject: nodeKeySchema,\n kind: subjectKindSchema,\n via: nodeKeySchema.exactOptional(),\n anchor: nodeKeySchema,\n origin: edgeOriginSchema,\n coverage: unit,\n })\n .readonly(),\n);\n\n/** This schema checks the effect of a mute. */\nexport const muteEffectSchema: z.ZodType<MuteEffect, MuteEffect> = schemaOf<MuteEffect>()(z.enum([\"absent\", \"silent\"]));\n\n/** This schema checks the policy of the relevance. The hop cap and the count of paths are whole numbers, 1 or more. */\nexport const relevancePolicySchema: z.ZodType<RelevancePolicy, RelevancePolicy> = schemaOf<RelevancePolicy>()(\n z\n .strictObject({\n hopCap: z.number().int().min(1, \"The hop cap is 1 or more.\"),\n topPaths: z.number().int().min(1, \"The count of paths is 1 or more.\"),\n mandatory: muteEffectSchema,\n entryMax: assessedLevelSchema.exactOptional(),\n })\n .readonly(),\n);\n\n/**\n * This schema checks a relevance. A relevance has a why when it has a path, and only then. A mute with the\n * effect `absent` gives a reach of 0 and no path.\n */\nexport const relevanceSchema: z.ZodType<Relevance, Relevance> = schemaOf<Relevance>()(\n z\n .strictObject({\n reach: probabilitySchema,\n best: unit,\n noisyOr: unit,\n paths: z.array(relevancePathSchema).readonly(),\n why: whyRecordSchema.exactOptional(),\n weakest: z.strictObject({ edge: z.string().min(1, \"The id of an edge is a non-empty string.\"), importance: unit }).readonly().exactOptional(),\n next: z.strictObject({ edge: z.string().min(1, \"The id of an edge is a non-empty string.\"), gain: unit }).readonly().exactOptional(),\n muted: z.strictObject({ mute: z.string().min(1, \"The id of a mute is a non-empty string.\"), effect: muteEffectSchema }).readonly().exactOptional(),\n bound: z.enum([\"bounds\", \"partial\"]).exactOptional(),\n })\n .refine((relevance) => (relevance.why === undefined) === (relevance.paths.length === 0), \"A relevance has a why when it has a path, and only then.\")\n .refine(\n (relevance) => relevance.muted?.effect !== \"absent\" || (relevance.reach.high === 0 && relevance.paths.length === 0),\n \"A mute with the effect absent gives a reach of 0 and no path.\",\n )\n .readonly(),\n);\n\n/** This schema checks a reason of an assessment. The index of a rule is its position, from 0 (`contracts.ts`, line 747). */\nexport const assessReasonSchema: z.ZodType<AssessReason, AssessReason> = schemaOf<AssessReason>()(\n z\n .discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"ended\") }),\n z.strictObject({ kind: z.literal(\"status\"), status: statusSchema }),\n z.strictObject({ kind: z.literal(\"no-place\") }),\n z.strictObject({ kind: z.literal(\"no-subject\") }),\n z.strictObject({ kind: z.literal(\"not-addressed\") }),\n z.strictObject({ kind: z.literal(\"addressed\") }),\n z.strictObject({ kind: z.literal(\"no-codes\") }),\n z.strictObject({ kind: z.literal(\"unknown-place\"), place: placeIdSchema }),\n z.strictObject({\n kind: z.literal(\"place\"),\n place: placeIdSchema,\n codes: z.array(regionCodeSchema).readonly(),\n distanceKm: z.number().min(0).exactOptional(),\n shapeRefused: z.literal(true).exactOptional(),\n zoneFallback: z.literal(true).exactOptional(),\n }),\n z.strictObject({ kind: z.literal(\"subject\"), subject: subjectWatchSchema }),\n z.strictObject({ kind: z.literal(\"place-table\"), place: placeIdSchema, reports: z.array(reportIdSchema).min(1).readonly(), level: assessedLevelSchema }),\n z.strictObject({\n kind: z.literal(\"table\"),\n class: z.string().exactOptional(),\n bySeverity: assessedLevelSchema,\n byUrgency: assessedLevelSchema,\n level: assessedLevelSchema,\n recentPast: z.literal(true).exactOptional(),\n foreign: z.literal(true).exactOptional(),\n }),\n z.strictObject({ kind: z.literal(\"rule\"), place: placeIdSchema.exactOptional(), index: count(), max: assessedLevelSchema }),\n z.strictObject({ kind: z.literal(\"shadow\"), score: shadowScoreSchema }),\n z.strictObject({\n kind: z.literal(\"reach\"),\n reach: probabilitySchema,\n reached: z.array(nodeKeySchema).readonly(),\n mandatory: z.array(placeIdSchema).readonly(),\n entryLevel: assessedLevelSchema.exactOptional(),\n why: whyRecordSchema.exactOptional(),\n }),\n z.strictObject({ kind: z.literal(\"relevance-fault\"), message: z.string().min(1, \"The message of a fault is a non-empty string.\") }),\n ])\n .readonly(),\n);\n\n/** This schema checks the level of one incident for one person, with its reasons. */\nexport const assessmentSchema: z.ZodType<Assessment, Assessment> = schemaOf<Assessment>()(\n z\n .strictObject({\n incident: reportIdSchema,\n person: personIdSchema,\n level: assessedLevelSchema,\n places: z.array(placeIdSchema).readonly(),\n reasons: z.array(assessReasonSchema).readonly(),\n muted: z.strictObject({ mute: z.string().min(1, \"The id of a mute is a non-empty string.\"), effect: muteEffectSchema }).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n// =============================================================================\n// The lateness across sources\n// =============================================================================\n\n/** This schema checks the state of an expectation. */\nexport const latenessStateSchema: z.ZodType<LatenessState, LatenessState> = schemaOf<LatenessState>()(z.enum([\"no-limit\", \"no-data\", \"met\", \"late\"]));\n\n/** This schema checks the limits of one expectation. The count of misses is an integer, 1 or more (`lateness.ts`, line 66). */\nexport const latenessLimitSchema: z.ZodType<LatenessLimit, LatenessLimit> = schemaOf<LatenessLimit>()(\n z.strictObject({ delay: durationSchema, misses: z.int().min(1, \"The count of misses is an integer, 1 or more.\") }).readonly(),\n);\n\n/** This schema checks the lateness of one source against another source for one expectation. */\nexport const latenessSchema: z.ZodType<Lateness, Lateness> = schemaOf<Lateness>()(\n z\n .strictObject({\n expectation: z.string(),\n from: sourceIdSchema,\n to: sourceIdSchema,\n state: latenessStateSchema,\n limit: latenessLimitSchema.exactOptional(),\n missed: z.array(reportIdSchema).readonly(),\n since: instantSchema.exactOptional(),\n wakeAt: instantSchema.exactOptional(),\n })\n .readonly(),\n);\n\n// =============================================================================\n// The private configuration\n// =============================================================================\n\n/** This schema checks a reference to a secret. The name is not empty. The value stays in the secret store. */\nexport const secretRefSchema: z.ZodType<SecretRef, SecretRef> = schemaOf<SecretRef>()(\n z.strictObject({ secret: z.string().min(1, \"The name of a secret is a non-empty string.\") }).readonly(),\n);\n\n/** This schema checks one field of an address: a text, or a reference to a secret. */\nexport const addressValueSchema: z.ZodType<AddressValue, AddressValue> = schemaOf<AddressValue>()(z.union([z.string(), secretRefSchema]));\n\n/** This schema checks a place of the configuration. */\nexport const placeConfigSchema: z.ZodType<PlaceConfig, PlaceConfig> = schemaOf<PlaceConfig>()(\n z\n .strictObject({\n id: placeIdSchema,\n label: z.string(),\n at: positionSchema.exactOptional(),\n codes: z.array(regionCodeSchema).readonly(),\n bufferKm: z.number(),\n sharePosition: z.array(sourceIdSchema).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n// The printable ASCII characters, with no space, no parenthesis and no backslash.\nconst CONTACT_CHARACTERS = /^[\\x21-\\x27\\x2a-\\x5b\\x5d-\\x7e]+$/;\n// An `https` URL with a host of two labels or more, or a `mailto` URL with one address.\nconst CONTACT_FORMS = [\n /^https:\\/\\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+(?::[0-9]{1,5})?(?:[/?#].*)?$/i,\n /^mailto:[^@/?#]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+(?:\\?.*)?$/i,\n];\n\n/**\n * This function tells if a text is a contact of an operator: an `https` URL with a host, or a `mailto` URL\n * with an address. The contact goes into the comment of the User-Agent. Thus it has only\n * printable ASCII characters, with no space, no parenthesis and no backslash. A header with other\n * characters stops the fetch. A parenthesis ends the comment, and a backslash escapes the next character.\n */\nexport function isContactUrl(text: string): boolean {\n return CONTACT_CHARACTERS.test(text) && CONTACT_FORMS.some((form) => form.test(text));\n}\n\n/**\n * This schema checks the inputs of the default layers of a person. The load checks each work against the table, and\n * checks that each service is an entity.\n */\nexport const interestDefaultsConfigSchema: z.ZodType<InterestDefaultsConfig, InterestDefaultsConfig> = schemaOf<InterestDefaultsConfig>()(\n z\n .strictObject({\n works: z.array(z.string().min(1)).readonly().exactOptional(),\n services: z.array(nodeKeySchema).readonly().exactOptional(),\n delivery: z.boolean().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks a person of the configuration: the watch, and the policies of the person when they are not the default. */\nexport const personConfigSchema: z.ZodType<PersonConfig, PersonConfig> = schemaOf<PersonConfig>()(\n z\n .strictObject({\n watch: personWatchSchema,\n defaults: interestDefaultsConfigSchema.exactOptional(),\n label: z.string().exactOptional(),\n policies: z.array(escalationPolicySchema).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the settings of one expectation of the instance. */\nexport const expectationConfigSchema: z.ZodType<ExpectationConfig, ExpectationConfig> = schemaOf<ExpectationConfig>()(\n z.strictObject({ id: z.string(), since: instantSchema }).readonly(),\n);\n\n/** This schema checks one address of one person on one channel. */\nexport const contactConfigSchema: z.ZodType<ContactConfig, ContactConfig> = schemaOf<ContactConfig>()(\n z.strictObject({ person: personIdSchema, channel: channelIdSchema, address: z.record(z.string(), addressValueSchema).readonly() }).readonly(),\n);\n\n/** This schema checks the form of one record of the opt-in list. `loadConfig` checks the number, the time and the words. */\nexport const optInConfigSchema: z.ZodType<OptInConfig, OptInConfig> = schemaOf<OptInConfig>()(\n z.strictObject({ number: addressValueSchema, at: z.string().min(1), way: z.enum(OPT_IN_WAYS), words: z.string().min(1) }).readonly(),\n);\n\n/**\n * This schema checks the money rules of one paid provider account, with its fixed costs. `loadConfig` checks the\n * provider, the fixed costs against the cap, the reserve and the time zone.\n */\nexport const spendConfigSchema: z.ZodType<SpendConfig, SpendConfig> = schemaOf<SpendConfig>()(\n z\n .strictObject({\n provider: z.string().min(1),\n monthlyUsd: z.number().positive(),\n fixed: z\n .array(z.strictObject({ what: z.string().min(1), usd: z.number().nonnegative() }).readonly())\n .readonly()\n .exactOptional(),\n reserveUsd: z.number().nonnegative().exactOptional(),\n floor: z.union([z.number(), z.array(z.number()).min(1, \"The list of floors has one floor or more.\").readonly()]),\n timeZone: z.string().min(1),\n })\n .readonly(),\n);\n\n/** This schema checks the link of one family of kinds: its code, its window, its distance and its limit of the magnitude. */\nexport const linkFamilySchema: z.ZodType<LinkFamily, LinkFamily> = schemaOf<LinkFamily>()(\n z\n .strictObject({\n family: kindCodeSchema,\n windowMs: z.int().positive(\"The window is an integer count of milliseconds, 1 or more.\"),\n distanceKm: z.number().nonnegative(\"The distance is 0 km or more.\"),\n magnitude: z.number().nonnegative(\"The limit of the magnitude is 0 or more.\").exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the policy of the link rule. The configuration can give it in place of `DEFAULT_LINK_POLICY`. */\nexport const linkPolicySchema: z.ZodType<LinkPolicy, LinkPolicy> = schemaOf<LinkPolicy>()(\n z.strictObject({ families: z.array(linkFamilySchema).readonly() }).readonly(),\n);\n\n/** This schema checks a chain of tries: the channel of each try, in order. */\nexport const tryChainSchema: z.ZodType<TryChain, TryChain> = schemaOf<TryChain>()(\n z.strictObject({ steps: z.array(channelIdSchema).readonly() }).readonly(),\n);\n\n/** This schema checks one person of the outage call. `loadConfig` checks the person and the channel of each step. */\nexport const outagePersonConfigSchema: z.ZodType<OutagePersonConfig, OutagePersonConfig> = schemaOf<OutagePersonConfig>()(\n z.strictObject({ person: personIdSchema, chain: tryChainSchema }).readonly(),\n);\n\n/** This schema checks the outage call: the people and their chains. */\nexport const outageConfigSchema: z.ZodType<OutageConfig, OutageConfig> = schemaOf<OutageConfig>()(\n z.strictObject({ people: z.array(outagePersonConfigSchema).readonly() }).readonly(),\n);\n\n// The id of a copy: a short name of lowercase letters, digits and hyphens, thus a log line and a file name can hold it.\n/** This schema checks the id of a copy of the system: 1 to 32 lowercase letters, digits and hyphens. */\nexport const copyIdSchema: z.ZodType<string, string> = z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/u, \"The id of a copy is 1 to 32 lowercase letters, digits and hyphens.\");\n\n/**\n * This schema checks the window of the starts of a drill: the shape of `TimeWindow` of `@mark1russell7/algebra/clock`.\n * It does not check the time zone or the local times. `drillProblems` finds a bad window.\n */\nexport const drillWindowSchema: z.ZodType<DrillConfig[\"window\"], DrillConfig[\"window\"]> = schemaOf<DrillConfig[\"window\"]>()(\n z\n .strictObject({\n zone: z.string(),\n start: z.string(),\n end: z.string(),\n days: z.array(z.int().min(0).max(6, \"A day of the week is from 0 (Sunday) to 6 (Saturday).\")).readonly().optional(),\n })\n .readonly(),\n);\n\n/** This schema checks the path of a drill: one channel. `loadConfig` checks the channel and the contact of the person on it. */\nexport const drillPathSchema: z.ZodType<DrillPath, DrillPath> = schemaOf<DrillPath>()(z.strictObject({ kind: z.literal(\"channel\"), channel: channelIdSchema }).readonly());\n\n/** This schema checks one drill of the configuration. `loadConfig` checks the person, the channel and the times. */\nexport const drillConfigSchema: z.ZodType<DrillConfig, DrillConfig> = schemaOf<DrillConfig>()(\n z\n .strictObject({\n id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/u, \"The id of a drill is 1 to 32 lowercase letters, digits and hyphens.\"),\n person: personIdSchema,\n path: drillPathSchema,\n every: durationSchema,\n window: drillWindowSchema,\n ackWithin: durationSchema,\n copies: z.array(copyIdSchema).min(1).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks a table of rank delays: a duration for some levels. `loadConfig` checks the bounds of each value. */\nexport const rankDelaysSchema: z.ZodType<RankDelays, RankDelays> = schemaOf<RankDelays>()(\n z.strictObject({ digest: durationSchema.exactOptional(), notice: durationSchema.exactOptional(), urgent: durationSchema.exactOptional(), \"life-safety\": durationSchema.exactOptional() }).readonly(),\n);\n\n/** This schema checks the send limit of each person (AL-72). `loadConfig` checks the bounds of each value. */\nexport const sendLimitConfigSchema: z.ZodType<SendLimitConfig, SendLimitConfig> = schemaOf<SendLimitConfig>()(\n z.strictObject({ window: durationSchema.exactOptional(), notice: z.number().int().exactOptional(), urgent: z.number().int().exactOptional() }).readonly(),\n);\n\n/** This schema checks the throttle of each person and channel (AL-72 part 4). `loadConfig` checks the bounds of the window. */\nexport const throttleConfigSchema: z.ZodType<ThrottleConfig, ThrottleConfig> = schemaOf<ThrottleConfig>()(\n z.strictObject({ window: durationSchema.exactOptional(), key: z.enum([\"channel\", \"incident\"]).exactOptional(), streams: z.enum([\"system\", \"family\"]).exactOptional(), exempt: z.array(levelSchema).readonly().exactOptional() }).readonly(),\n);\n\n// The origin of a site on the loopback address, with a port and no path.\nconst LOOPBACK_ORIGIN = /^https?:\\/\\/(?:127\\.0\\.0\\.1|localhost|\\[::1\\]):[0-9]{1,5}$/iu;\n// The origin of a site that a phone opens: `https`, a host of two labels or more and an optional port, with no path.\nconst PHONE_ORIGIN = /^https:\\/\\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+(?::[0-9]{1,5})?$/iu;\n// An IPv4 address. A phone does not open the loopback form of the site, thus the phone origin has no such host.\nconst IPV4_HOST = /^https:\\/\\/[0-9.]+(?::[0-9]{1,5})?$/u;\n\n/** This schema checks the two forms of the links of a local site (AL-92): a loopback origin and a phone origin. */\nexport const tellSiteSchema: z.ZodType<TellSite, TellSite> = schemaOf<TellSite>()(\n z\n .strictObject({\n local: z.string().regex(LOOPBACK_ORIGIN, \"The local origin is http or https, a loopback host and a port, with no path.\"),\n phone: z\n .string()\n .regex(PHONE_ORIGIN, \"The phone origin is https and a host of two labels or more, with no path.\")\n .refine((text) => !IPV4_HOST.test(text), \"The phone origin has a name, not an IPv4 address.\"),\n })\n .readonly(),\n);\n\n/** This schema checks the intake of the messages of the operator (AL-92): a port, a daily cap of 1 or more, and the local site. */\nexport const tellConfigSchema: z.ZodType<TellConfig, TellConfig> = schemaOf<TellConfig>()(\n z\n .strictObject({\n port: z.int().min(1).max(65535, \"The port is 1 to 65535.\"),\n dailyCap: z.int().min(1).exactOptional(),\n site: tellSiteSchema.exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the policy of a down channel (AL-65). A run opens a line at 1 failed call or more. */\nexport const channelDownConfigSchema: z.ZodType<ChannelDownConfig, ChannelDownConfig> = schemaOf<ChannelDownConfig>()(\n z.strictObject({ failures: z.number().int().min(1).exactOptional(), span: durationSchema.exactOptional() }).readonly(),\n);\n\n/** This schema checks the policy of the end of the line of a down source (AL-75). At 0 and 0, a line ends at the first state that is up. */\nexport const sourceClearConfigSchema: z.ZodType<SourceClearConfig, SourceClearConfig> = schemaOf<SourceClearConfig>()(\n z.strictObject({ floor: durationSchema.exactOptional(), fetches: z.number().int().min(0).exactOptional() }).readonly(),\n);\n\n/**\n * This schema checks the JSON of the private configuration at the load. It checks the form of each\n * value. Then `loadConfig` checks the references: the ids, the places of each person, the contacts,\n * the secrets, the outage call and the drills.\n */\nexport const alertConfigSchema: z.ZodType<AlertConfig, AlertConfig> = schemaOf<AlertConfig>()(\n z\n .strictObject({\n format: z.literal(CONFIG_FORMAT),\n places: z.array(placeConfigSchema).readonly(),\n people: z.array(personConfigSchema).readonly(),\n contacts: z.array(contactConfigSchema).readonly(),\n policies: z.array(escalationPolicySchema).readonly(),\n contact: z.string().refine(isContactUrl, \"The contact is not an https URL or a mailto URL.\").exactOptional(),\n expectations: z.array(expectationConfigSchema).readonly().exactOptional(),\n spend: z.array(spendConfigSchema).readonly().exactOptional(),\n link: linkPolicySchema.exactOptional(),\n outage: outageConfigSchema.exactOptional(),\n rankDelay: rankDelaysSchema.exactOptional(),\n rankFloor: durationSchema.exactOptional(),\n assess: assessPolicySchema.exactOptional(),\n drills: z.array(drillConfigSchema).readonly().exactOptional(),\n optIn: z.array(optInConfigSchema).readonly().exactOptional(),\n channelDown: channelDownConfigSchema.exactOptional(),\n sourceClear: sourceClearConfigSchema.exactOptional(),\n sendLimit: sendLimitConfigSchema.exactOptional(),\n throttle: throttleConfigSchema.exactOptional(),\n tell: tellConfigSchema.exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the JSON of one part of the private configuration. Then the merge and `loadConfig` check the references. */\nexport const configPartSchema: z.ZodType<ConfigPart, ConfigPart> = schemaOf<ConfigPart>()(\n z\n .strictObject({\n format: z.literal(CONFIG_PART_FORMAT),\n places: z.array(placeConfigSchema).readonly().exactOptional(),\n people: z.array(personConfigSchema).readonly().exactOptional(),\n contacts: z.array(contactConfigSchema).readonly().exactOptional(),\n })\n .readonly(),\n);\n\n// The URL of the exchange of another copy. The tailnet carries it, thus `http` is also a valid protocol. The host is a\n// name with one label or more, an IPv4 address or an IPv6 address in brackets. The URL has no user, no query and no fragment.\nconst EXCHANGE_URL = /^https?:\\/\\/(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*|\\[[0-9a-f:.]+\\])(?::[0-9]{1,5})?(?:\\/[^\\s?#]*)?$/iu;\nconst isExchangeUrl = (text: string): boolean => EXCHANGE_URL.test(text);\n\n/** This schema checks the address of the exchange of a copy. */\nexport const copyListenSchema: z.ZodType<CopyListen, CopyListen> = schemaOf<CopyListen>()(\n z.strictObject({ host: z.string().min(1, \"The address is a non-empty text.\"), port: z.int().min(1).max(65535, \"The port is 1 to 65535.\") }).readonly(),\n);\n\n/** This schema checks another copy of the system: its id and the URL of its exchange. */\nexport const copyPeerSchema: z.ZodType<CopyPeer, CopyPeer> = schemaOf<CopyPeer>()(\n z.strictObject({ id: copyIdSchema, url: z.string().refine(isExchangeUrl, \"The URL of a copy is an http or https URL with no user, no query and no fragment.\") }).readonly(),\n);\n\n/** This schema checks the JSON of the settings of one copy, the file `copy.json`. Then `copyProblems` checks the ranks and the ids. */\nexport const copySettingsSchema: z.ZodType<CopySettings, CopySettings> = schemaOf<CopySettings>()(\n z\n .strictObject({\n format: z.literal(COPY_FORMAT),\n id: copyIdSchema,\n rank: z.int().nonnegative(\"The rank is an integer, 0 or more.\"),\n listen: copyListenSchema.exactOptional(),\n peers: z.array(copyPeerSchema).readonly().exactOptional(),\n pingKey: z\n .string()\n .regex(/^[A-Z][A-Z0-9_]*$/u, \"The key is a name of the secrets: capital letters, digits and underscores.\")\n .exactOptional(),\n accounts: z\n .record(z.string().min(1, \"The id of a source is a non-empty text.\"), z.int().min(1, \"The number of an account is an integer, 1 or more.\"))\n .readonly()\n .exactOptional(),\n configFrom: copyIdSchema.exactOptional(),\n })\n .readonly(),\n);\n\n// =============================================================================\n// The health payload\n// =============================================================================\n\n/** This schema checks the health of one source in the health payload: the kind of its last failure, with no message. */\nexport const sourceHealthViewSchema: z.ZodType<SourceHealthView, SourceHealthView> = schemaOf<SourceHealthView>()(\n z\n .strictObject({\n source: sourceIdSchema,\n state: healthStateSchema,\n since: instantSchema,\n lastSuccess: instantSchema.exactOptional(),\n lastFailure: z.strictObject({ at: instantSchema, kind: z.enum([\"network\", \"timeout\", \"server\", \"rate-limited\", \"auth\", \"refused\"]) }).readonly().exactOptional(),\n reason: z.string(),\n })\n .readonly(),\n);\n\n/** This schema checks a stage of another copy. */\nexport const copyStageSchema: z.ZodType<CopyStage, CopyStage> = schemaOf<CopyStage>()(z.enum([\"skew\", \"config\", \"unread\", \"unsteady\"]));\n\n/** This schema checks one read of the log of another copy that passed. */\nexport const copyReadSchema: z.ZodType<CopyRead, CopyRead> = schemaOf<CopyRead>()(\n z.strictObject({ at: instantSchema, skew: z.number(), sameConfig: z.boolean() }).readonly(),\n);\n\n/** This schema checks the health of another copy: its stages and its last read that passed. */\nexport const copyHealthSchema: z.ZodType<CopyHealth, CopyHealth> = schemaOf<CopyHealth>()(\n z.strictObject({ copy: copyIdSchema, stages: z.array(copyStageSchema).readonly(), read: copyReadSchema.exactOptional() }).readonly(),\n);\n\n/** This schema checks a stage of the quota of a channel. */\nexport const quotaStageSchema: z.ZodType<QuotaStage, QuotaStage> = schemaOf<QuotaStage>()(z.enum([\"low\", \"reserve\", \"spent\"]));\n\n/** This schema checks the state of the quota of a channel in its window. Each count is an integer, 0 or more. */\nexport const channelQuotaSchema: z.ZodType<ChannelQuota, ChannelQuota> = schemaOf<ChannelQuota>()(\n z\n .strictObject({\n channel: channelIdSchema,\n limit: z.int().min(0, \"The limit of a quota is an integer, 0 or more.\"),\n reserve: z.int().min(0, \"The reserve of a quota is an integer, 0 or more.\"),\n used: z.int().min(0, \"The used units of a quota are an integer, 0 or more.\"),\n resetAt: instantSchema.exactOptional(),\n blockedUntil: instantSchema.exactOptional(),\n unit: z.string().min(1, \"The name of the units is a non-empty string.\").exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the health of the quota of one channel: the quota and its stages. */\nexport const quotaHealthSchema: z.ZodType<QuotaHealth, QuotaHealth> = schemaOf<QuotaHealth>()(\n z.strictObject({ quota: channelQuotaSchema, stages: z.array(quotaStageSchema).readonly() }).readonly(),\n);\n\n/** This schema checks a stage of the balance of a provider account. */\nexport const balanceStageSchema: z.ZodType<BalanceStage, BalanceStage> = schemaOf<BalanceStage>()(z.enum([\"low\", \"empty\", \"unread\"]));\n\n/** This schema checks one read of a balance that passed. The currency is a code of ISO 4217: three capital letters. */\nexport const balanceReadSchema: z.ZodType<BalanceRead, BalanceRead> = schemaOf<BalanceRead>()(\n z.strictObject({ balance: z.number(), currency: z.string().regex(/^[A-Z]{3}$/u, \"A currency is a code of ISO 4217.\"), at: instantSchema }).readonly(),\n);\n\n/** This schema checks the watch of the balance of one provider account. */\nexport const providerBalanceSchema: z.ZodType<ProviderBalance, ProviderBalance> = schemaOf<ProviderBalance>()(\n z\n .strictObject({\n provider: z.string().min(1, \"The provider is a non-empty string.\"),\n title: z.string(),\n channels: z.array(channelIdSchema).readonly(),\n floors: z.array(z.number()).min(1, \"The list of floors has one floor or more.\").readonly(),\n maxAge: durationSchema,\n since: instantSchema,\n read: balanceReadSchema.exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the health of the balance of one provider account: the balance and its stages. */\nexport const balanceHealthSchema: z.ZodType<BalanceHealth, BalanceHealth> = schemaOf<BalanceHealth>()(\n z.strictObject({ balance: providerBalanceSchema, stages: z.array(balanceStageSchema).readonly() }).readonly(),\n);\n\n/** This schema checks the health of one read on a schedule of the runtime. */\nexport const readHealthSchema: z.ZodType<ReadHealth, ReadHealth> = schemaOf<ReadHealth>()(\n z\n .strictObject({\n what: z.string().min(1, \"The words of a read are a non-empty string.\"),\n at: instantSchema.nullable(),\n failed: z.boolean(),\n next: instantSchema.nullable(),\n })\n .readonly(),\n);\n\n/** This schema checks the run of failed calls of one channel of a copy (AL-65). */\nexport const channelRunSchema: z.ZodType<ChannelRun, ChannelRun> = schemaOf<ChannelRun>()(\n z\n .strictObject({\n channel: channelIdSchema,\n failures: z.number().int().min(1, \"A run has one failed call or more.\"),\n first: instantSchema,\n last: instantSchema,\n kind: channelFailureKindSchema,\n reached: z.boolean(),\n })\n .readonly(),\n);\n\n/** This schema checks the health of one channel of this copy: its endpoints, its last good call, its run and the down flag. */\nexport const channelHealthSchema: z.ZodType<ChannelHealth, ChannelHealth> = schemaOf<ChannelHealth>()(\n z\n .strictObject({\n copy: z.string().min(1, \"The id of a copy is a non-empty string.\"),\n channel: channelIdSchema,\n title: z.string(),\n api: z.array(z.lazy(() => nodeKeySchema)).readonly().exactOptional(),\n run: channelRunSchema.exactOptional(),\n good: instantSchema.exactOptional(),\n down: z.boolean(),\n })\n .readonly(),\n);\n\n/** This schema checks the answer of the health route of the runtime. */\nexport const healthPayloadSchema: z.ZodType<HealthPayload, HealthPayload> = schemaOf<HealthPayload>()(\n z\n .strictObject({\n format: z.literal(HEALTH_FORMAT),\n at: instantSchema.nullable(),\n now: instantSchema,\n sources: z.array(sourceHealthViewSchema).readonly(),\n lateness: z.array(latenessSchema).readonly(),\n coverage: z.array(coverageSchema).readonly(),\n copies: z.array(copyHealthSchema).readonly(),\n quotas: z.array(quotaHealthSchema).readonly(),\n balances: z.array(balanceHealthSchema).readonly(),\n reads: z.array(readHealthSchema).readonly(),\n channels: z.array(channelHealthSchema).readonly(),\n })\n .readonly(),\n);\n\n/** This schema checks a shape of the map: a polygon or a circle. */\nexport const mapShapeSchema: z.ZodType<MapShape, MapShape> = schemaOf<MapShape>()(z.discriminatedUnion(\"type\", [polygonObject, circleObject]).readonly());\n\n/** This schema checks one watched place of a change of the history. */\nexport const historyPlaceSchema: z.ZodType<HistoryPlace, HistoryPlace> = schemaOf<HistoryPlace>()(\n z.strictObject({ id: placeIdSchema, level: assessedLevelSchema }).readonly(),\n);\n\n/** This schema checks one change of the history of an incident. */\nexport const historyChangeSchema: z.ZodType<HistoryChange, HistoryChange> = schemaOf<HistoryChange>()(\n z\n .strictObject({\n at: instantSchema,\n reports: z.array(reportIdSchema).readonly(),\n level: assessedLevelSchema,\n severity: severitySchema,\n live: z.boolean(),\n onset: instantSchema.exactOptional(),\n expires: instantSchema.exactOptional(),\n codes: z.array(regionCodeSchema).readonly(),\n shapes: z.array(mapShapeSchema).readonly(),\n unshaped: z.array(regionCodeSchema).readonly(),\n places: z.array(historyPlaceSchema).readonly(),\n })\n .readonly(),\n);\n\n/** This schema checks the history of one incident. */\nexport const historyIncidentSchema: z.ZodType<HistoryIncident, HistoryIncident> = schemaOf<HistoryIncident>()(\n z\n .strictObject({\n anchor: reportIdSchema,\n reports: z.array(reportIdSchema).min(1, \"An incident has one report or more.\").readonly(),\n status: statusSchema,\n kind: kindSchema,\n changes: z.array(historyChangeSchema).readonly(),\n })\n .readonly(),\n);\n\n/** This schema checks the shapes of one region code of the history. */\nexport const historyRegionSchema: z.ZodType<HistoryRegion, HistoryRegion> = schemaOf<HistoryRegion>()(\n z.strictObject({ code: regionCodeSchema, shapes: z.array(mapShapeSchema).readonly() }).readonly(),\n);\n\n/** This schema checks the answer of the history route of the runtime. */\nexport const historyPayloadSchema: z.ZodType<HistoryPayload, HistoryPayload> = schemaOf<HistoryPayload>()(\n z\n .strictObject({\n format: z.literal(HISTORY_FORMAT),\n at: instantSchema.nullable(),\n since: instantSchema.nullable(),\n next: instantSchema.nullable(),\n incidents: z.array(historyIncidentSchema).readonly(),\n regions: z.array(historyRegionSchema).readonly(),\n })\n .readonly(),\n);\n\n/** This schema checks one row of the interests of a person: an edge, and the id of the edge that replaced it. */\nexport const interestRowSchema: z.ZodType<InterestRow, InterestRow> = schemaOf<InterestRow>()(\n z.strictObject({ edge: interestEdgeSchema, replacedBy: z.string().min(1).exactOptional() }).readonly(),\n);\n\n/** This schema checks the interests of one person in the answer of the interests route of the runtime. */\nexport const interestsPersonSchema: z.ZodType<InterestsPerson, InterestsPerson> = schemaOf<InterestsPerson>()(\n z\n .strictObject({\n person: personIdSchema,\n label: z.string().exactOptional(),\n routing: z.enum([\"graph\", \"places\"]),\n rows: z.array(interestRowSchema).readonly(),\n mutes: z.array(muteSchema).readonly(),\n labels: z.record(z.string(), z.string()).readonly(),\n problem: z.string().exactOptional(),\n })\n .readonly(),\n);\n\n/** This schema checks the answer of the interests route of the runtime. */\nexport const interestsPayloadSchema: z.ZodType<InterestsPayload, InterestsPayload> = schemaOf<InterestsPayload>()(\n z.strictObject({ format: z.literal(INTERESTS_FORMAT), people: z.array(interestsPersonSchema).readonly() }).readonly(),\n);\n\n/**\n * This function reads the JSON text of the settings of one copy. It checks the JSON, then the schema, then\n * `copyProblems`. The problems hold no address and no URL.\n */\nexport function parseCopySettings(text: string): Result<CopySettings, readonly string[]> {\n const json = tryCatch((): unknown => JSON.parse(text), () => [\"The settings of the copy are not valid JSON.\"]);\n if (json.tag === \"err\") return json;\n const checked = checkWith(copySettingsSchema, json.value);\n if (checked.tag === \"err\") return checked;\n const problems = copyProblems(checked.value);\n return problems.length > 0 ? err(problems) : checked;\n}\n\n/**\n * This function checks a value at a trust boundary. The result is the value, or one problem for each\n * issue of the schema. A problem names the path and the rule. It does not hold the value, because the\n * value can be private.\n */\nexport function checkWith<T>(schema: z.ZodType<T, T>, value: unknown): Result<T, readonly string[]> {\n const parsed = schema.safeParse(value);\n if (parsed.success) return ok(parsed.data);\n return err(parsed.error.issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`));\n}\n\n/** The text of the path of an issue, for example `places[0].codes[1]`. The root is `(root)`. */\nfunction pathText(path: readonly PropertyKey[]): string {\n const text = path.map((part, index) => (typeof part === \"number\" ? `[${part}]` : `${index === 0 ? \"\" : \".\"}${String(part)}`)).join(\"\");\n return text === \"\" ? \"(root)\" : text;\n}\n\n/** A configuration that passed the schema and the load, with the recipient of each person. The configuration is the merge of the root and its parts. */\nexport interface ParsedConfig {\n readonly config: AlertConfig;\n readonly recipients: readonly Recipient[];\n /** The opt-in list of the texts, with the value of each number. */\n readonly optIn: readonly OptInRecord[];\n}\n\n/** The JSON text of one part of the private configuration, with the name of the part. */\nexport interface PartText {\n readonly name: string;\n readonly text: string;\n}\n\n/**\n * This function reads the JSON text of the private configuration and the texts of its parts. It checks the JSON and\n * the schema of each text. Then it merges the parts with `mergeParts` and checks the references of the merge with\n * `loadConfig`. The runtime starts only with an `ok` result. The problems hold no value of the configuration and no\n * value of a secret. A problem of a part starts with the name of the part.\n */\nexport function parseConfig(\n text: string,\n channels: readonly ChannelDescriptor[],\n secret: SecretLookup,\n parts: readonly PartText[] = [],\n services?: ContactServices,\n): Result<ParsedConfig, readonly string[]> {\n const problems: string[] = [];\n // The message of the JSON parser can quote the text, so the problem does not use it.\n const json = tryCatch((): unknown => JSON.parse(text), () => [\"The configuration is not valid JSON.\"]);\n const checked = json.tag === \"err\" ? json : checkWith(alertConfigSchema, json.value);\n if (checked.tag === \"err\") problems.push(...checked.error);\n const named: NamedPart[] = [];\n parts.forEach(({ name, text: partText }, index) => {\n // The merge refuses a bad name.\n const label = partLabel(name, index);\n const partJson = tryCatch((): unknown => JSON.parse(partText), () => [`${label} is not valid JSON.`]);\n const part = partJson.tag === \"err\" ? partJson : checkWith(configPartSchema, partJson.value);\n if (part.tag === \"err\") problems.push(...part.error.map((problem) => (partJson.tag === \"err\" ? problem : `${label}: ${problem}`)));\n else named.push({ name, part: part.value });\n });\n if (checked.tag === \"err\" || problems.length > 0) return err(problems);\n const merged = mergeParts(checked.value, named);\n if (merged.tag === \"err\") return merged;\n const loaded = loadConfig(merged.value, channels, secret, services);\n return loaded.problems.length > 0 ? err(loaded.problems) : ok({ config: merged.value, recipients: loaded.recipients, optIn: loaded.optIn });\n}\n","/**\n * The lifelines of a community and the needs of a person under them (AL-106).\n *\n * The lifelines are the 8 FEMA Community Lifelines. The source is the FEMA Community Lifelines\n * Implementation Toolkit, version 2.1 (2023), with the FEMA page of the lifelines (last update 2024-03-08).\n * Version 2.1 added Water Systems as the 8th lifeline, and it changed the name \"Food, Water, Shelter\" to\n * \"Food, Hydration, Shelter\".\n *\n * A need is a thing that a person uses each day, for example water to drink. Each need has a lifeline, a\n * level, a unit and an amount for each person each day. The module names no person, no household and no\n * place. The people and their amounts are input data.\n *\n * The file `lifelines.lock.json` holds each code of a lifeline and each code of a need. A test holds the\n * lock, thus the removal of a code is a deliberate step.\n */\n\nimport type { Level } from \"./contracts.ts\";\n\n/** The page of FEMA that gives the names of the lifelines. */\nexport const LIFELINES_SOURCE = \"https://www.fema.gov/emergency-managers/practitioners/lifelines\";\n\n/** The toolkit of FEMA that added the 8th lifeline: version 2.1, 2023. */\nexport const LIFELINES_TOOLKIT = \"https://www.fema.gov/sites/default/files/documents/fema_lifelines-toolkit-v2.1_2023.pdf\";\n\n/** The codes of the 8 FEMA Community Lifelines, in the order of FEMA. */\nexport const LIFELINES = [\"safety\", \"food-hydration-shelter\", \"health\", \"energy\", \"communications\", \"transportation\", \"hazmat\", \"water\"] as const;\n\n/** The code of one FEMA Community Lifeline. */\nexport type Lifeline = (typeof LIFELINES)[number];\n\n/** The name of each lifeline, as FEMA writes it. */\nexport const LIFELINE_LABELS: Readonly<Record<Lifeline, string>> = {\n safety: \"Safety and Security\",\n \"food-hydration-shelter\": \"Food, Hydration, Shelter\",\n health: \"Health and Medical\",\n energy: \"Energy\",\n communications: \"Communications\",\n transportation: \"Transportation\",\n hazmat: \"Hazardous Materials\",\n water: \"Water Systems\",\n};\n\n/** This function tells if a text is the code of a lifeline. */\nexport function isLifeline(code: string): code is Lifeline {\n return (LIFELINES as readonly string[]).includes(code);\n}\n\n/**\n * The levels of a need, from the most serious. A `life` need keeps a person alive. A `health` need keeps\n * a person well. A `comfort` need makes the time easier.\n */\nexport const NEED_LEVELS = [\"life\", \"health\", \"comfort\"] as const;\n\n/** The level of one need. */\nexport type NeedLevel = (typeof NEED_LEVELS)[number];\n\n/** The level of an alert when a need of each level is at risk. */\nexport const NEED_ALERT_LEVELS: Readonly<Record<NeedLevel, Level>> = {\n life: \"life-safety\",\n health: \"urgent\",\n comfort: \"notice\",\n};\n\n/** A dotted code of a need in lower case, for example `hydration.drink` or `food.energy`. */\nexport type NeedCode = string;\n\n/** A need: a thing that a person uses each day. */\nexport interface Need {\n readonly code: NeedCode;\n readonly lifeline: Lifeline;\n readonly level: NeedLevel;\n /** The unit of the amount, in the grammar of `@mark1russell7/quantity`, for example `L`, `kcal`, `Wh` or `{dose}`. */\n readonly unit: string;\n /** The default amount for each person each day, in `unit`. A person can have a different amount. */\n readonly perPersonDay: number;\n}\n\n/** The source of a default amount: the title of a page, its URL and the date that the page gives. */\nexport interface NeedSource {\n readonly title: string;\n readonly url: string;\n /** The date of the page, `YYYY-MM-DD`: its last update or the date that its content is current. */\n readonly date: string;\n}\n\n/** A need with the source of its default amount. */\nexport interface CitedNeed extends Need {\n readonly source: NeedSource;\n /** What the amount includes, when the source tells it. */\n readonly note?: string;\n}\n\n/** The volume of one US gallon in litres. The definition is exactly 231 cubic inches. */\nexport const US_GALLON_L = 3.785411784;\n\n/**\n * The needs with a default amount from an official source. A need with no such source is not in the list.\n * A user gives it as input data.\n */\nexport const NEEDS: readonly CitedNeed[] = [\n {\n code: \"hydration.drink\",\n lifeline: \"food-hydration-shelter\",\n level: \"life\",\n unit: \"L\",\n perPersonDay: US_GALLON_L,\n source: { title: \"Ready.gov: Water\", url: \"https://www.ready.gov/water\", date: \"2021-02-22\" },\n note: \"The amount of Ready.gov is at least one gallon for each person each day, for drinking and sanitation.\",\n },\n {\n code: \"food.energy\",\n lifeline: \"food-hydration-shelter\",\n level: \"health\",\n unit: \"kcal\",\n perPersonDay: 2000,\n source: { title: \"FDA: How to Understand and Use the Nutrition Facts Label\", url: \"https://www.fda.gov/food/nutrition-facts-label/how-understand-and-use-nutrition-facts-label\", date: \"2024-03-05\" },\n note: \"The FDA uses 2,000 calories each day as a general guide for nutrition advice. A person can need more or less.\",\n },\n];\n\nconst NEED_CODE = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\n/** This function tells if a text has the form of a code of a need: two or more dotted parts in lower case. */\nexport function isNeedCode(code: string): boolean {\n return NEED_CODE.test(code);\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,MAAa,gBAAgB;;;;;AAwN7B,MAAa,aAAa;CACxB;EAAE,IAAI;EAAgB,OAAO;CAAoB;CACjD;EAAE,IAAI;EAAe,OAAO;CAA0C;CACtE;EAAE,IAAI;EAAQ,OAAO;CAAqC;CAC1D;EAAE,IAAI;EAAkB,OAAO;CAA8B;CAC7D;EAAE,IAAI;EAAiB,OAAO;CAAyB;CACvD;EAAE,IAAI;EAAmB,OAAO;CAAkC;CAClE;EAAE,IAAI;EAAe,OAAO;CAAsB;CAClD;EAAE,IAAI;EAAkB,OAAO;CAA6B;CAC5D;EAAE,IAAI;EAAqB,OAAO;CAAoB;CACtD;EAAE,IAAI;EAAoB,OAAO;CAAiB;CAClD;EAAE,IAAI;EAAiB,OAAO;CAAqC;CACnE;EAAE,IAAI;EAAyB,OAAO;CAAwB;CAC9D;EAAE,IAAI;EAAoB,OAAO;CAA+B;CAChE;EAAE,IAAI;EAAuB,OAAO;CAAsB;CAC1D;EAAE,I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