The build standard owns the router model and the line system; one owner per fiber

The routers order reads its model from the build standard (bstd().g, 'keep'
is the old next-model-up rule) and the optical upgrade order its line system
(bstd().sys). The Ops sheet shows "From the build standard: X" with a button
to the sheet. Old saves move a model or line system from an order that was
running into the standard when it has none of its own; a paused order's or
an unhired intern's setting is dropped. opsParam refuses model/sys and points
at bstdSet.

The build standard's order is a generator now: every first job that takes a
fiber dark goes through the optical order's routing test (opsDark, in the
route worker in play), under one shared budget of dark swaps a night (two for
Kevin) and the week-long memory for a failed fiber. A fiber one order worked
on is the other's no more that shift, and decom keeps waves the standard just
upgraded. The plan is checked at every job, since the shift rests between
them: a POP gone or changed by hand meanwhile is skipped. The button still
runs the whole plan at once on the page.
This commit is contained in:
jvanvik 2026-11-07 06:55:01 +01:00
parent 032470f486
commit fbae6fc3ed
22 changed files with 573 additions and 138 deletions

View file

@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows
## [Unreleased] ## [Unreleased]
- The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too.
- Your intern no longer takes a fiber dark for the build standard just because it looks quiet: like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day.
- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse.
- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary. - The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary.
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.

View file

@ -6,16 +6,9 @@ planned or known, not built.
## Promised and not done yet ## Promised and not done yet
1. **Router model and line system set in one place only.** The build standard (`S.popStd.g`, `S.popStd.sys`) and two 1. and 2. are built: the router model and the line system are picked in the Build standard sheet only (the `routers` and
standing-order settings say the same thing: the `routers` order's `model` (upstream 1e7638c) and the `optup` order's `optup` orders read `bstd().g` / `bstd().sys`; sanitize moves an old setting into `S.popStd`), and `std` takes a fiber
`sys` (upstream 647e302). Neither ever steps down, so they do not fight, but a player can pick two different targets. dark on `optup`'s routing test (`opsDark()`), sharing its budget a night, with one owner per fiber a shift (`X.fib`).
Plan: the Build standard sheet becomes the only place to pick them. The `routers` order reads its model from the
standard, and `optup` its line system (their lists turn into a line "from the build standard: X, change"); sanitize
moves an old `model`/`sys` setting into `S.popStd` when the standard has none.
2. **One owner per fiber for line systems and optics.** `std` (sys/opt targets: a quiet fiber, or a parallel link with
room) and `optup` (one full routing without the fiber, one a night) can each darken a fiber in the same shift. Let `std`
use `optup`'s check (`opsDarkOk`) for line-system swaps, or skip fibers `optup` is working on. Today `std` also holds
any fiber that carries an express with traffic; `opsDarkOk` would handle that case by itself.
## Next features ## Next features
@ -58,8 +51,14 @@ planned or known, not built.
the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone
landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every
player shares one address for the rate limits. player shares one address for the rate limits.
- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full; a wave - **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full. The
the standard just upgraded can still be handed back the same day by `decom` if a bigger parallel link carries it. sheet's quote and "Bring everything up now" still judge a line-system swap without routing (`bstdDarkOk()`: a quiet
fiber, under 10% of its capacity, or a parallel link with room; any express with traffic holds its fibers,
`bstdXpBusy()`), so the quote is the bill; only the intern routes to test. A quiet fiber with no way around can still
go dark from the button. An old save's `routers.model` moved into the standard (only from a running order with an
intern hired; a paused one's is dropped) also becomes what new POPs get. A model or line system in the standard is a
ceiling for the `routers` and `optup` orders (their next-one-up rule only applies with "keep"), as an order's own
model was before; `optup` has no per-POP exceptions, so it moves fiber at POPs excepted from `std` too.
- **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG - **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG
and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser. and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser.
- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income - **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income

View file

@ -413,7 +413,7 @@
"bstd.edit":"Build-Standard bearbeiten", "bstd.edit":"Build-Standard bearbeiten",
"bstd.every_exchange":"Wo es einen IX gibt", "bstd.every_exchange":"Wo es einen IX gibt",
"bstd.fastest":"Die schnellste, die reicht", "bstd.fastest":"Die schnellste, die reicht",
"bstd.fiber_note":"Ein Line-System-Tausch legt die Glasfaser einen Tag dunkel: nur wenn sie ruhig ist oder ein paralleler Link ihre Last trägt.", "bstd.fiber_note_two":"Ein Line-System-Tausch legt die Glasfaser einen Tag dunkel. Der Button macht das nur bei ruhiger Faser oder wenn ein paralleler Link ihre Last trägt; dein Praktikant nur, wenn der ganze Verkehr um die Faser herumkommt.",
"bstd.from_level":"(Level {lv})", "bstd.from_level":"(Level {lv})",
"bstd.g_fiber":"Glasfaser und Waves", "bstd.g_fiber":"Glasfaser und Waves",
"bstd.g_port":"Ports und Peering", "bstd.g_port":"Ports und Peering",
@ -3402,6 +3402,7 @@
"ops.fire":"Entlassen", "ops.fire":"Entlassen",
"ops.fired":"{name} hat den Ausweis abgegeben und den guten Tacker mitgenommen. Deine Daueraufträge ruhen.", "ops.fired":"{name} hat den Ausweis abgegeben und den guten Tacker mitgenommen. Deine Daueraufträge ruhen.",
"ops.floor":"Mindestens behalten", "ops.floor":"Mindestens behalten",
"ops.from_bstd":"Aus dem Build-Standard: {x}",
"ops.good_annie":"Am besten beim Peering: geht die Exchanges jeden Tag durch statt wöchentlich und bestellt zweimal pro Woche PNIs.", "ops.good_annie":"Am besten beim Peering: geht die Exchanges jeden Tag durch statt wöchentlich und bestellt zweimal pro Woche PNIs.",
"ops.good_kevin":"Am besten bei Wartung: zwei Line-System-Tausche pro Nacht statt einem, und nie ein dicker Finger.", "ops.good_kevin":"Am besten bei Wartung: zwei Line-System-Tausche pro Nacht statt einem, und nie ein dicker Finger.",
"ops.good_tracy":"Am besten im Vorausplanen: kauft Transit, Ports, Router und Optiken, als wäre der Traffic schon 10 % höher.", "ops.good_tracy":"Am besten im Vorausplanen: kauft Transit, Ports, Router und Optiken, als wäre der Traffic schon 10 % höher.",
@ -3458,7 +3459,7 @@
"ops.o_optics":"Mehr Dark Fiber beleuchten", "ops.o_optics":"Mehr Dark Fiber beleuchten",
"ops.o_optics_d":"Optiken auf heiß laufende Dark Fiber stecken und neue Glasfaser am Tag der Übergabe beleuchten.", "ops.o_optics_d":"Optiken auf heiß laufende Dark Fiber stecken und neue Glasfaser am Tag der Übergabe beleuchten.",
"ops.o_optup":"Optischen Transport ausbauen", "ops.o_optup":"Optischen Transport ausbauen",
"ops.o_optup_d":"Auf Glasfaser, die voll ist und heiß läuft, das Line System eine Größe hochziehen oder die kleinsten Kanäle gegen größere Optiken tauschen (die alten kommen ins Ersatzteillager). Wähl ein Line System, und jede Faser mit einem kleineren wird darauf hochgezogen. Ein Tausch des Line Systems legt die Faser für einen Tag lahm, also nur, wo der Traffic einen Weg drumherum hat und kein Kunde darauf fährt, einer pro Nacht.", "ops.o_optup_std_d":"Auf Glasfaser, die voll ist und heiß läuft, das Line System eine Größe hochziehen oder die kleinsten Kanäle gegen größere Optiken tauschen (die alten kommen ins Ersatzteillager). Steht ein Line System im Build-Standard, wird jede Faser mit einem kleineren darauf hochgezogen. Ein Tausch des Line Systems legt die Faser für einen Tag lahm, also nur, wo der Traffic einen Weg drumherum hat und kein Kunde darauf fährt, einer pro Nacht zusammen mit „Build-Standard einhalten“.",
"ops.o_pni":"PNI mit den Großen", "ops.o_pni":"PNI mit den Großen",
"ops.o_pni_d":"Jede Woche: mit jedem willigen Netz, das an deinen POPs genug Traffic schickt, einen PNI bestellen, in der jeweils kleinsten Größe des Netzes.", "ops.o_pni_d":"Jede Woche: mit jedem willigen Netz, das an deinen POPs genug Traffic schickt, einen PNI bestellen, in der jeweils kleinsten Größe des Netzes.",
"ops.o_ports":"Peering-Reserve halten", "ops.o_ports":"Peering-Reserve halten",
@ -3466,9 +3467,9 @@
"ops.o_repair":"Reparaturen beschleunigen", "ops.o_repair":"Reparaturen beschleunigen",
"ops.o_repair_d":"Für jeden Ausfall mit Eil-Reparatur zahlen, solange das Budget reicht.", "ops.o_repair_d":"Für jeden Ausfall mit Eil-Reparatur zahlen, solange das Budget reicht.",
"ops.o_routers":"Router voraus halten", "ops.o_routers":"Router voraus halten",
"ops.o_routers_desc":"Einen Router dazustellen oder auf die nächste Generation tauschen, wo ein zweiter Router den Traffic trägt, sobald Last oder Ports eine Grenze überschreiten. Wähl ein Modell, und jeder POP mit einem kleineren wird darauf getauscht, der am meisten ausgelastete zuerst, im Rahmen des Budgets.", "ops.o_routers_std_d":"Einen Router dazustellen oder auf die nächste Generation tauschen, wo ein zweiter Router den Traffic trägt, sobald Last oder Ports eine Grenze überschreiten. Steht ein Router-Modell im Build-Standard, wird stattdessen jeder POP mit einem kleineren darauf getauscht, der am meisten ausgelastete zuerst, im Rahmen des Budgets.",
"ops.o_std":"Build-Standard einhalten", "ops.o_std":"Build-Standard einhalten",
"ops.o_std_d":"POPs, Ports und Glasfaser auf deinen Build-Standard bringen, die meistbelasteten zuerst, ein paar Jobs pro Schicht. Vor einem Tausch kommt ein zweiter Router rein, und ein Line System wechselt nur auf einer ruhigen Glasfaser.", "ops.o_std_around_d":"POPs, Ports und Glasfaser auf deinen Build-Standard bringen, die meistbelasteten zuerst, ein paar Jobs pro Schicht. Vor einem Tausch kommt ein zweiter Router rein, und ein Line System wechselt nur, wo der Traffic für den dunklen Tag einen Weg um die Faser hat und kein Kunde darauf fährt, einer pro Nacht zusammen mit „Optischen Transport ausbauen“.",
"ops.o_transit":"Transit-Reserve halten", "ops.o_transit":"Transit-Reserve halten",
"ops.o_transit_d":"Transit an jedem POP über einem Vielfachen seiner 30-Tage-Spitze halten: ein LAG-Member dazu oder eine Portgröße hoch.", "ops.o_transit_d":"Transit an jedem POP über einem Vielfachen seiner 30-Tage-Spitze halten: ein LAG-Member dazu oder eine Portgröße hoch.",
"ops.ops":"Ops", "ops.ops":"Ops",

View file

@ -411,7 +411,7 @@
"bstd.edit":"Editar el estándar de red", "bstd.edit":"Editar el estándar de red",
"bstd.every_exchange":"Donde haya un IX", "bstd.every_exchange":"Donde haya un IX",
"bstd.fastest":"La más rápida que llegue", "bstd.fastest":"La más rápida que llegue",
"bstd.fiber_note":"Cambiar el sistema de línea deja la fibra apagada un día: solo si va tranquila o un enlace paralelo lleva su carga.", "bstd.fiber_note_two":"Cambiar el sistema de línea deja la fibra apagada un día. El botón solo lo hace si va tranquila o un enlace paralelo lleva su carga; tu becario, solo si todo el tráfico puede rodear la fibra.",
"bstd.from_level":"(nivel {lv})", "bstd.from_level":"(nivel {lv})",
"bstd.g_fiber":"Fibra y ondas", "bstd.g_fiber":"Fibra y ondas",
"bstd.g_port":"Puertos y peering", "bstd.g_port":"Puertos y peering",
@ -3400,6 +3400,7 @@
"ops.fire":"Despedir", "ops.fire":"Despedir",
"ops.fired":"{name} devolvió la tarjeta y se llevó la grapadora buena. Tus órdenes permanentes quedan en pausa.", "ops.fired":"{name} devolvió la tarjeta y se llevó la grapadora buena. Tus órdenes permanentes quedan en pausa.",
"ops.floor":"Conservar al menos", "ops.floor":"Conservar al menos",
"ops.from_bstd":"Del estándar de red: {x}",
"ops.good_annie":"La mejor en peering: repasa los exchanges cada día, no cada semana, y pide PNI dos veces por semana.", "ops.good_annie":"La mejor en peering: repasa los exchanges cada día, no cada semana, y pide PNI dos veces por semana.",
"ops.good_kevin":"El mejor en mantenimiento: dos cambios de sistema de línea por noche en vez de uno, y nunca un dedazo.", "ops.good_kevin":"El mejor en mantenimiento: dos cambios de sistema de línea por noche en vez de uno, y nunca un dedazo.",
"ops.good_tracy":"La mejor planificando: compra tránsito, puertos, routers y ópticas como si el tráfico ya fuera un 10 % mayor.", "ops.good_tracy":"La mejor planificando: compra tránsito, puertos, routers y ópticas como si el tráfico ya fuera un 10 % mayor.",
@ -3456,7 +3457,7 @@
"ops.o_optics":"Encender más fibra", "ops.o_optics":"Encender más fibra",
"ops.o_optics_d":"Añadir ópticas a la fibra oscura que va caliente y encender la fibra nueva el día que te la entregan.", "ops.o_optics_d":"Añadir ópticas a la fibra oscura que va caliente y encender la fibra nueva el día que te la entregan.",
"ops.o_optup":"Mejorar el transporte óptico", "ops.o_optup":"Mejorar el transporte óptico",
"ops.o_optup_d":"En la fibra que está llena y va caliente, sube el sistema de línea un tamaño o cambia los canales más pequeños por ópticas más grandes (las viejas van a la estantería). Elige un sistema de línea y cada fibra con uno más pequeño sube a ese. Cambiar el sistema de línea deja la fibra sin servicio un día, así que solo donde el tráfico puede rodearla y ningún cliente va por ella, uno por noche.", "ops.o_optup_std_d":"En la fibra que está llena y va caliente, sube el sistema de línea un tamaño o cambia los canales más pequeños por ópticas más grandes (las viejas van a la estantería). Con un sistema de línea en el estándar de red, cada fibra con uno más pequeño sube a ese. Cambiar el sistema de línea deja la fibra sin servicio un día, así que solo donde el tráfico puede rodearla y ningún cliente va por ella, uno por noche junto con «Mantener el estándar de red».",
"ops.o_pni":"PNI con los grandes", "ops.o_pni":"PNI con los grandes",
"ops.o_pni_d":"Cada semana: pedir un PNI a cada red dispuesta que envíe suficiente tráfico en tus POPs, con el tamaño mínimo de cada red.", "ops.o_pni_d":"Cada semana: pedir un PNI a cada red dispuesta que envíe suficiente tráfico en tus POPs, con el tamaño mínimo de cada red.",
"ops.o_ports":"Margen en puertos de peering", "ops.o_ports":"Margen en puertos de peering",
@ -3464,9 +3465,9 @@
"ops.o_repair":"Acelerar reparaciones", "ops.o_repair":"Acelerar reparaciones",
"ops.o_repair_d":"Pagar la reparación urgente de cada caída que la tenga, mientras dure el presupuesto.", "ops.o_repair_d":"Pagar la reparación urgente de cada caída que la tenga, mientras dure el presupuesto.",
"ops.o_routers":"Routers por delante", "ops.o_routers":"Routers por delante",
"ops.o_routers_desc":"Añadir un router, o pasar a la siguiente generación donde un segundo router lleve el tráfico, cuando la carga o los puertos pasen de un nivel. Elige un modelo y cada POP con uno más pequeño se cambia a ese, primero el más cargado, dentro del presupuesto.", "ops.o_routers_std_d":"Añadir un router, o pasar a la siguiente generación donde un segundo router lleve el tráfico, cuando la carga o los puertos pasen de un nivel. Con un modelo de router en el estándar de red, cada POP con uno más pequeño se cambia a ese, primero el más cargado, dentro del presupuesto.",
"ops.o_std":"Mantener el estándar de red", "ops.o_std":"Mantener el estándar de red",
"ops.o_std_d":"Poner los POP, los puertos y la fibra al nivel de tu estándar de red, los más cargados primero, unos pocos trabajos por turno. Antes de un cambio entra un segundo router, y el sistema de línea solo cambia en una fibra tranquila.", "ops.o_std_around_d":"Poner los POP, los puertos y la fibra al nivel de tu estándar de red, los más cargados primero, unos pocos trabajos por turno. Antes de un cambio entra un segundo router, y el sistema de línea solo cambia donde el tráfico puede rodear la fibra el día que queda a oscuras y ningún cliente va por ella, uno por noche junto con «Mejorar el transporte óptico».",
"ops.o_transit":"Margen de tránsito", "ops.o_transit":"Margen de tránsito",
"ops.o_transit_d":"Mantener el tránsito de cada POP por encima de un múltiplo de su pico de 30 días: un miembro LAG más o un tamaño de puerto mayor.", "ops.o_transit_d":"Mantener el tránsito de cada POP por encima de un múltiplo de su pico de 30 días: un miembro LAG más o un tamaño de puerto mayor.",
"ops.ops":"Ops", "ops.ops":"Ops",

View file

@ -411,7 +411,7 @@
"bstd.edit":"Modifier le standard réseau", "bstd.edit":"Modifier le standard réseau",
"bstd.every_exchange":"Partout où il y a un IX", "bstd.every_exchange":"Partout où il y a un IX",
"bstd.fastest":"La plus rapide qui porte", "bstd.fastest":"La plus rapide qui porte",
"bstd.fiber_note":"Changer le système de ligne éteint la fibre pendant un jour : seulement si elle est calme ou qu’un lien parallèle porte sa charge.", "bstd.fiber_note_two":"Changer le système de ligne éteint la fibre pendant un jour. Le bouton ne le fait que si elle est calme ou qu’un lien parallèle porte sa charge ; ton stagiaire, seulement si tout le trafic peut contourner la fibre.",
"bstd.from_level":"(niveau {lv})", "bstd.from_level":"(niveau {lv})",
"bstd.g_fiber":"Fibre et longueurs d’onde", "bstd.g_fiber":"Fibre et longueurs d’onde",
"bstd.g_port":"Ports et peering", "bstd.g_port":"Ports et peering",
@ -3400,6 +3400,7 @@
"ops.fire":"Remercier", "ops.fire":"Remercier",
"ops.fired":"{name} a rendu son badge et emporté la bonne agrafeuse. Tes ordres permanents sont en pause.", "ops.fired":"{name} a rendu son badge et emporté la bonne agrafeuse. Tes ordres permanents sont en pause.",
"ops.floor":"Garder au moins", "ops.floor":"Garder au moins",
"ops.from_bstd":"Selon le standard réseau : {x}",
"ops.good_annie":"La meilleure en peering : passe les exchanges en revue chaque jour, pas chaque semaine, et commande des PNI deux fois par semaine.", "ops.good_annie":"La meilleure en peering : passe les exchanges en revue chaque jour, pas chaque semaine, et commande des PNI deux fois par semaine.",
"ops.good_kevin":"Le meilleur en maintenance : deux changements de système de ligne par nuit au lieu d’un, et jamais une faute de frappe.", "ops.good_kevin":"Le meilleur en maintenance : deux changements de système de ligne par nuit au lieu d’un, et jamais une faute de frappe.",
"ops.good_tracy":"La meilleure pour anticiper : achète transit, ports, routeurs et optiques comme si le trafic était déjà 10 % plus haut.", "ops.good_tracy":"La meilleure pour anticiper : achète transit, ports, routeurs et optiques comme si le trafic était déjà 10 % plus haut.",
@ -3456,7 +3457,7 @@
"ops.o_optics":"Allumer plus de fibre", "ops.o_optics":"Allumer plus de fibre",
"ops.o_optics_d":"Ajouter des optiques sur la fibre noire qui chauffe, et allumer la nouvelle fibre le jour de sa livraison.", "ops.o_optics_d":"Ajouter des optiques sur la fibre noire qui chauffe, et allumer la nouvelle fibre le jour de sa livraison.",
"ops.o_optup":"Améliorer le transport optique", "ops.o_optup":"Améliorer le transport optique",
"ops.o_optup_d":"Sur une fibre pleine qui chauffe, passer le système de ligne à la taille au-dessus, ou échanger les plus petits canaux contre des optiques plus grandes (les anciennes partent sur l’étagère). Choisissez un système de ligne, et chaque fibre équipée d’un plus petit y passe. Un changement de système de ligne coupe la fibre pour une journée : seulement là où le trafic peut la contourner et où aucun client ne passe, un par nuit.", "ops.o_optup_std_d":"Sur une fibre pleine qui chauffe, passer le système de ligne à la taille au-dessus, ou échanger les plus petits canaux contre des optiques plus grandes (les anciennes partent sur l’étagère). Avec un système de ligne dans le standard réseau, chaque fibre équipée d’un plus petit y passe. Un changement de système de ligne coupe la fibre pour une journée : seulement là où le trafic peut la contourner et où aucun client ne passe, un par nuit avec « Tenir le standard réseau ».",
"ops.o_pni":"PNI avec les gros", "ops.o_pni":"PNI avec les gros",
"ops.o_pni_d":"Chaque semaine : commander un PNI avec chaque réseau partant qui envoie assez de trafic sur tes POP, à la taille minimale de chaque réseau.", "ops.o_pni_d":"Chaque semaine : commander un PNI avec chaque réseau partant qui envoie assez de trafic sur tes POP, à la taille minimale de chaque réseau.",
"ops.o_ports":"Garder de la marge sur les ports de peering", "ops.o_ports":"Garder de la marge sur les ports de peering",
@ -3464,9 +3465,9 @@
"ops.o_repair":"Accélérer les réparations", "ops.o_repair":"Accélérer les réparations",
"ops.o_repair_d":"Payer la réparation express de chaque panne qui en a une, tant que le budget suit.", "ops.o_repair_d":"Payer la réparation express de chaque panne qui en a une, tant que le budget suit.",
"ops.o_routers":"Garder les routeurs en avance", "ops.o_routers":"Garder les routeurs en avance",
"ops.o_routers_desc":"Ajouter un routeur, ou passer à la génération suivante là où un second routeur porte le trafic, quand la charge ou les ports dépassent un seuil. Choisissez un modèle, et chaque POP équipé d’un plus petit passe à celui-ci, le plus chargé d’abord, dans la limite du budget.", "ops.o_routers_std_d":"Ajouter un routeur, ou passer à la génération suivante là où un second routeur porte le trafic, quand la charge ou les ports dépassent un seuil. Avec un modèle de routeur dans le standard réseau, chaque POP équipé d’un plus petit passe à celui-ci, le plus chargé d’abord, dans la limite du budget.",
"ops.o_std":"Tenir le standard réseau", "ops.o_std":"Tenir le standard réseau",
"ops.o_std_d":"Mettre POP, ports et fibre au niveau de ton standard réseau, les plus chargés d’abord, quelques chantiers par service. Un second routeur arrive avant un échange, et le système de ligne ne change que sur une fibre calme.", "ops.o_std_around_d":"Mettre POP, ports et fibre au niveau de ton standard réseau, les plus chargés d’abord, quelques chantiers par service. Un second routeur arrive avant un échange, et le système de ligne ne change que là où le trafic peut contourner la fibre le jour où elle est coupée et où aucun client ne passe, un par nuit avec « Améliorer le transport optique ».",
"ops.o_transit":"Garder de la marge de transit", "ops.o_transit":"Garder de la marge de transit",
"ops.o_transit_d":"Garder le transit de chaque POP au-dessus d'un multiple de son pic sur 30 jours : un membre LAG de plus, ou une taille de port au-dessus.", "ops.o_transit_d":"Garder le transit de chaque POP au-dessus d'un multiple de son pic sur 30 jours : un membre LAG de plus, ou une taille de port au-dessus.",
"ops.ops":"Ops", "ops.ops":"Ops",

View file

@ -411,7 +411,7 @@
"bstd.edit":"Modifica lo standard di rete", "bstd.edit":"Modifica lo standard di rete",
"bstd.every_exchange":"Ovunque ci sia un IX", "bstd.every_exchange":"Ovunque ci sia un IX",
"bstd.fastest":"La più veloce che arriva", "bstd.fastest":"La più veloce che arriva",
"bstd.fiber_note":"Cambiare il sistema di linea spegne la fibra per un giorno: solo se è tranquilla o se un link parallelo ne regge il carico.", "bstd.fiber_note_two":"Cambiare il sistema di linea spegne la fibra per un giorno. Il pulsante lo fa solo se è tranquilla o se un link parallelo ne regge il carico; il tuo stagista solo se tutto il traffico può aggirare la fibra.",
"bstd.from_level":"(livello {lv})", "bstd.from_level":"(livello {lv})",
"bstd.g_fiber":"Fibra e wave", "bstd.g_fiber":"Fibra e wave",
"bstd.g_port":"Porte e peering", "bstd.g_port":"Porte e peering",
@ -3400,6 +3400,7 @@
"ops.fire":"Licenzia", "ops.fire":"Licenzia",
"ops.fired":"{name} ha restituito il badge e si è preso la spillatrice buona. I tuoi ordini permanenti sono in pausa.", "ops.fired":"{name} ha restituito il badge e si è preso la spillatrice buona. I tuoi ordini permanenti sono in pausa.",
"ops.floor":"Tieni almeno", "ops.floor":"Tieni almeno",
"ops.from_bstd":"Dallo standard di rete: {x}",
"ops.good_annie":"La migliore nel peering: passa gli exchange ogni giorno, non ogni settimana, e ordina PNI due volte a settimana.", "ops.good_annie":"La migliore nel peering: passa gli exchange ogni giorno, non ogni settimana, e ordina PNI due volte a settimana.",
"ops.good_kevin":"Il migliore nella manutenzione: due cambi di line system per notte invece di uno, e mai un errore di battitura.", "ops.good_kevin":"Il migliore nella manutenzione: due cambi di line system per notte invece di uno, e mai un errore di battitura.",
"ops.good_tracy":"La migliore a pianificare: compra transito, porte, router e ottiche come se il traffico fosse già più alto del 10%.", "ops.good_tracy":"La migliore a pianificare: compra transito, porte, router e ottiche come se il traffico fosse già più alto del 10%.",
@ -3456,7 +3457,7 @@
"ops.o_optics":"Accendi più fibra", "ops.o_optics":"Accendi più fibra",
"ops.o_optics_d":"Aggiungi ottiche alla dark fiber che scotta e accendi la fibra nuova il giorno della consegna.", "ops.o_optics_d":"Aggiungi ottiche alla dark fiber che scotta e accendi la fibra nuova il giorno della consegna.",
"ops.o_optup":"Potenzia il trasporto ottico", "ops.o_optup":"Potenzia il trasporto ottico",
"ops.o_optup_d":"Sulla fibra piena che va calda, porta il line system alla taglia successiva, o scambia i canali più piccoli con ottiche più grandi (le vecchie finiscono a scaffale). Scegli un line system e ogni fibra con uno più piccolo passa a quello. Cambiare line system spegne la fibra per un giorno, quindi solo dove il traffico può girarle intorno e nessun cliente ci passa, uno per notte.", "ops.o_optup_std_d":"Sulla fibra piena che va calda, porta il line system alla taglia successiva, o scambia i canali più piccoli con ottiche più grandi (le vecchie finiscono a scaffale). Con un line system nello standard di rete, ogni fibra con uno più piccolo passa a quello. Cambiare line system spegne la fibra per un giorno, quindi solo dove il traffico può girarle intorno e nessun cliente ci passa, uno per notte insieme a “Tieni lo standard di rete”.",
"ops.o_pni":"PNI con i grandi", "ops.o_pni":"PNI con i grandi",
"ops.o_pni_d":"Ogni settimana: ordina un PNI con ogni rete disponibile che manda abbastanza traffico nei tuoi POP, alla taglia minima di ciascuna rete.", "ops.o_pni_d":"Ogni settimana: ordina un PNI con ogni rete disponibile che manda abbastanza traffico nei tuoi POP, alla taglia minima di ciascuna rete.",
"ops.o_ports":"Margine sulle porte di peering", "ops.o_ports":"Margine sulle porte di peering",
@ -3464,9 +3465,9 @@
"ops.o_repair":"Accelera le riparazioni", "ops.o_repair":"Accelera le riparazioni",
"ops.o_repair_d":"Paga la riparazione urgente di ogni guasto che ce l'ha, finché il budget regge.", "ops.o_repair_d":"Paga la riparazione urgente di ogni guasto che ce l'ha, finché il budget regge.",
"ops.o_routers":"Router sempre avanti", "ops.o_routers":"Router sempre avanti",
"ops.o_routers_desc":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia. Scegli un modello e ogni POP con uno più piccolo passa a quello, prima il più carico, nei limiti del budget.", "ops.o_routers_std_d":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia. Con un modello di router nello standard di rete, ogni POP con uno più piccolo passa a quello, prima il più carico, nei limiti del budget.",
"ops.o_std":"Tieni lo standard di rete", "ops.o_std":"Tieni lo standard di rete",
"ops.o_std_d":"Porta POP, porte e fibra al tuo standard di rete, i più carichi prima, qualche lavoro a turno. Prima di uno scambio arriva un secondo router, e il sistema di linea cambia solo su una fibra tranquilla.", "ops.o_std_around_d":"Porta POP, porte e fibra al tuo standard di rete, i più carichi prima, qualche lavoro a turno. Prima di uno scambio arriva un secondo router, e il sistema di linea cambia solo dove il traffico può girare intorno alla fibra nel giorno in cui è spenta e nessun cliente ci passa, uno per notte insieme a “Potenzia il trasporto ottico”.",
"ops.o_transit":"Margine di transit", "ops.o_transit":"Margine di transit",
"ops.o_transit_d":"Tieni il transit di ogni POP sopra un multiplo del suo picco a 30 giorni: un membro LAG in più, o una porta più grande.", "ops.o_transit_d":"Tieni il transit di ogni POP sopra un multiplo del suo picco a 30 giorni: un membro LAG in più, o una porta più grande.",
"ops.ops":"Ops", "ops.ops":"Ops",

View file

@ -411,7 +411,7 @@
"bstd.edit":"Editar o padrão de rede", "bstd.edit":"Editar o padrão de rede",
"bstd.every_exchange":"Onde houver um IX", "bstd.every_exchange":"Onde houver um IX",
"bstd.fastest":"A mais rápida que alcança", "bstd.fastest":"A mais rápida que alcança",
"bstd.fiber_note":"Trocar o sistema de linha apaga a fibra por um dia: só quando ela está tranquila ou um link paralelo leva a carga.", "bstd.fiber_note_two":"Trocar o sistema de linha apaga a fibra por um dia. O botão só faz isso quando ela está tranquila ou um link paralelo leva a carga; seu estagiário só quando todo o tráfego consegue contornar a fibra.",
"bstd.from_level":"(nível {lv})", "bstd.from_level":"(nível {lv})",
"bstd.g_fiber":"Fibra e waves", "bstd.g_fiber":"Fibra e waves",
"bstd.g_port":"Portas e peering", "bstd.g_port":"Portas e peering",
@ -3400,6 +3400,7 @@
"ops.fire":"Dispensar", "ops.fire":"Dispensar",
"ops.fired":"{name} devolveu o crachá e levou o grampeador bom. Suas ordens permanentes estão em pausa.", "ops.fired":"{name} devolveu o crachá e levou o grampeador bom. Suas ordens permanentes estão em pausa.",
"ops.floor":"Manter pelo menos", "ops.floor":"Manter pelo menos",
"ops.from_bstd":"Do padrão de rede: {x}",
"ops.good_annie":"A melhor em peering: passa pelos exchanges todo dia, não toda semana, e pede PNIs duas vezes por semana.", "ops.good_annie":"A melhor em peering: passa pelos exchanges todo dia, não toda semana, e pede PNIs duas vezes por semana.",
"ops.good_kevin":"O melhor em manutenção: duas trocas de sistema de linha por noite em vez de uma, e nunca um dedo gordo.", "ops.good_kevin":"O melhor em manutenção: duas trocas de sistema de linha por noite em vez de uma, e nunca um dedo gordo.",
"ops.good_tracy":"A melhor em planejar: compra trânsito, portas, roteadores e ópticas como se o tráfego já estivesse 10% maior.", "ops.good_tracy":"A melhor em planejar: compra trânsito, portas, roteadores e ópticas como se o tráfego já estivesse 10% maior.",
@ -3456,7 +3457,7 @@
"ops.o_optics":"Acender mais fibra", "ops.o_optics":"Acender mais fibra",
"ops.o_optics_d":"Adicionar ópticas à fibra escura que está esquentando e acender a fibra nova no dia da entrega.", "ops.o_optics_d":"Adicionar ópticas à fibra escura que está esquentando e acender a fibra nova no dia da entrega.",
"ops.o_optup":"Melhorar o transporte óptico", "ops.o_optup":"Melhorar o transporte óptico",
"ops.o_optup_d":"Na fibra que está cheia e esquentando, sobe o sistema de linha um tamanho ou troca os canais menores por ópticas maiores (as antigas vão para a prateleira). Escolha um sistema de linha e cada fibra com um menor sobe para ele. Trocar o sistema de linha derruba a fibra por um dia, então só onde o tráfego consegue contorná-la e nenhum cliente passa por ela, uma por noite.", "ops.o_optup_std_d":"Na fibra que está cheia e esquentando, sobe o sistema de linha um tamanho ou troca os canais menores por ópticas maiores (as antigas vão para a prateleira). Com um sistema de linha no padrão de rede, cada fibra com um menor sobe para ele. Trocar o sistema de linha derruba a fibra por um dia, então só onde o tráfego consegue contorná-la e nenhum cliente passa por ela, uma por noite junto com “Manter o padrão de rede”.",
"ops.o_pni":"PNI com os grandes", "ops.o_pni":"PNI com os grandes",
"ops.o_pni_d":"Toda semana: pedir um PNI com cada rede disposta que mande tráfego suficiente nos seus POPs, no tamanho mínimo de cada rede.", "ops.o_pni_d":"Toda semana: pedir um PNI com cada rede disposta que mande tráfego suficiente nos seus POPs, no tamanho mínimo de cada rede.",
"ops.o_ports":"Folga nas portas de peering", "ops.o_ports":"Folga nas portas de peering",
@ -3464,9 +3465,9 @@
"ops.o_repair":"Acelerar reparos", "ops.o_repair":"Acelerar reparos",
"ops.o_repair_d":"Pagar o reparo urgente de cada queda que tenha um, enquanto o orçamento durar.", "ops.o_repair_d":"Pagar o reparo urgente de cada queda que tenha um, enquanto o orçamento durar.",
"ops.o_routers":"Roteadores à frente", "ops.o_routers":"Roteadores à frente",
"ops.o_routers_desc":"Adicionar um roteador, ou trocar para a próxima geração onde um segundo roteador segura o tráfego, quando a carga ou as portas passarem de um nível. Escolha um modelo e cada POP com um menor é trocado para ele, o mais carregado primeiro, dentro do orçamento.", "ops.o_routers_std_d":"Adicionar um roteador, ou trocar para a próxima geração onde um segundo roteador segura o tráfego, quando a carga ou as portas passarem de um nível. Com um modelo de roteador no padrão de rede, cada POP com um menor é trocado para ele, o mais carregado primeiro, dentro do orçamento.",
"ops.o_std":"Manter o padrão de rede", "ops.o_std":"Manter o padrão de rede",
"ops.o_std_d":"Colocar POPs, portas e fibra no seu padrão de rede, os mais carregados primeiro, alguns trabalhos por turno. Antes de uma troca entra um segundo roteador, e o sistema de linha só muda numa fibra tranquila.", "ops.o_std_around_d":"Colocar POPs, portas e fibra no seu padrão de rede, os mais carregados primeiro, alguns trabalhos por turno. Antes de uma troca entra um segundo roteador, e o sistema de linha só muda onde o tráfego consegue contornar a fibra no dia em que ela fica apagada e nenhum cliente passa por ela, uma por noite junto com “Melhorar o transporte óptico”.",
"ops.o_transit":"Folga de trânsito", "ops.o_transit":"Folga de trânsito",
"ops.o_transit_d":"Manter o trânsito de cada POP acima de um múltiplo do seu pico de 30 dias: mais um membro LAG, ou um tamanho de porta acima.", "ops.o_transit_d":"Manter o trânsito de cada POP acima de um múltiplo do seu pico de 30 dias: mais um membro LAG, ou um tamanho de porta acima.",
"ops.ops":"Ops", "ops.ops":"Ops",

View file

@ -367,7 +367,10 @@ const API_CMD={
opsToggle:{args:[['k','opsKey']],watch:['ops'], opsToggle:{args:[['k','opsKey']],watch:['ops'],
doc:'Pause or resume one standing order. Keys come from catalog(\'OPSK\'); the sheet in the game shows what each one does.'}, doc:'Pause or resume one standing order. Keys come from catalog(\'OPSK\'); the sheet in the game shows what each one does.'},
opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'], opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'],
doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead, such as the model to standardize routers on.'}, // The routers order's model and the optup order's line system were settings once: they are the build standard's now.
pass:a=>{const b={routers:{model:'g'},optup:{sys:'sys'}}[a.k],t=b&&b[a.p];
if(t)throw new Error(`the ${a.k} order takes its ${t==='g'?'router model':'line system'} from the build standard: set it with bstdSet (k "${t}")`);return a;},
doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead. The routers order\'s model and the optup order\'s line system are not settings: both orders take them from the build standard (bstdSet k "g" and k "sys"; "keep" leaves them to the next model or line system up, when needed).'},
opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'], opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'],
doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'}, doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'},
opsFloor:{args:[['v','string',false]],watch:['ops'], opsFloor:{args:[['v','string',false]],watch:['ops'],
@ -424,7 +427,7 @@ const API_CMD={
popStdClear:{args:[],watch:['popStd'], popStdClear:{args:[],watch:['popStd'],
doc:'Clear the whole build standard; new POPs go back to one basic router.'}, doc:'Clear the whole build standard; new POPs go back to one basic router.'},
bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'], bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'],
doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'}, doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'},
bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'], bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'],
quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};}, quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};},
doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'}, doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'},

View file

@ -62,7 +62,7 @@ const API_STATE_DOC={
core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'},
ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'},
ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'}, ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'},
popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up. g and sys are also the model the routers order and the line system the optup order standardize on.'},
mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'},
demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'},
seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'},

View file

@ -18,20 +18,19 @@ const OPS_AHEAD=1.1,opsIs=id=>!!S&&!!S.ops&&S.ops.intern===id,opsAhead=()=>opsIs
const OPS=[ const OPS=[
{k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||v==='have'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}}, {k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||v==='have'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}},
{k:'ports',i:'🔌',pop:1,cap:50000,t:N_('ops.o_ports'),d:N_('ops.o_ports_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'}}}, {k:'ports',i:'🔌',pop:1,cap:50000,t:N_('ops.o_ports'),d:N_('ops.o_ports_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'}}},
{k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_desc'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}, // The model to standardize on is the build standard's, set in its sheet (96-pop-standard.js): none of its own here.
// A model to standardize on: every POP on a smaller one is swapped to it, busiest first, within the budget. {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_std_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}},
model:{d:'next',ok:v=>v==='next'||(Number.isInteger(v)&&!!RG[v]),l:N_('ops.p_model'),f:v=>v==='next'?tr('ops.model_next'):RG[v].n}}},
// The build standard (96-pop-standard.js): its targets are set in their own sheet, so here it has only the budget. // The build standard (96-pop-standard.js): its targets are set in their own sheet, so here it has only the budget.
{k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_d'),p:{}}, {k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_around_d'),p:{}},
{k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, {k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}},
{k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}},
{k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}}, {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}},
{k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}}, {k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}},
{k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}}}, {k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}}},
// Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to // Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to
// a chosen line system. A line system swap is a day without that fiber: only where the traffic gets around it. // the build standard's line system. A line system swap is a day without that fiber: only where the traffic gets around it.
{k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}, {k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_std_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},
sys:{d:'next',v:['next','roadm','cl'],l:N_('ops.p_sys'),f:v=>v==='next'?tr('ops.sys_next'):DF_SYS[v].n},swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}}, swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}},
{k:'decom',i:'🧹',t:N_('ops.o_decom'),d:N_('ops.o_decom_d'),p:{keep:{d:true,v:[true,false],l:N_('ops.p_keep'),f:v=>v?tr('common.on'):tr('common.off')}}}, {k:'decom',i:'🧹',t:N_('ops.o_decom'),d:N_('ops.o_decom_d'),p:{keep:{d:true,v:[true,false],l:N_('ops.p_keep'),f:v=>v?tr('common.on'):tr('common.off')}}},
]; ];
const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k);
@ -47,10 +46,9 @@ const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern));
const opsCanHire=()=>lvl()>=2; const opsCanHire=()=>lvl()>=2;
const opsName=(long)=>{const I=INTERNS[S.ops.intern];return I?tr(long?I.n:I.s):'';}; const opsName=(long)=>{const I=INTERNS[S.ops.intern];return I?tr(long?I.n:I.s):'';};
function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==undefined&&(P.ok?P.ok(v):P.v.includes(v))?v:P.d;} function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==undefined&&(P.ok?P.ok(v):P.v.includes(v))?v:P.d;}
// Every value a setting can take, in the order its list shows them: providers that sell where you have POPs, and router // Every value a setting can take, in the order its list shows them, providers that sell where you have POPs as well.
// models you can buy, smallest first. The current value is always on the list, so the list can show it. // The current value is always on the list, so the list can show it.
function opsOpts(k,p){const cur=opsP(k,p),L=p==='prov'?['cheap','have',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)] function opsOpts(k,p){const cur=opsP(k,p),L=p==='prov'?['cheap','have',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)]:OPSK[k].p[p].v.slice();
:p==='model'?['next',...RG.map((r,i)=>i).filter(i=>rgOpen(i)).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cap-RG[b].cap||a-b)]:OPSK[k].p[p].v.slice();
if(!L.includes(cur))L.push(cur);return L;} if(!L.includes(cur))L.push(cur);return L;}
const opsCaps=k=>OPSK[k].mo?OPS_CAPS_MO:OPS_CAPS; const opsCaps=k=>OPSK[k].mo?OPS_CAPS_MO:OPS_CAPS;
function opsCap(k){const c=S.ops.cap[k];return opsCaps(k).includes(c)?c:OPSK[k].cap||0;} function opsCap(k){const c=S.ops.cap[k];return opsCaps(k).includes(c)?c:OPSK[k].cap||0;}
@ -64,6 +62,10 @@ function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s
n.intern=typeof o.intern==='string'&&own(INTERNS,o.intern)?o.intern:null;n.hired=int(o.hired,0,1e7,0);n.mon=int(o.mon,0,1e6,0); n.intern=typeof o.intern==='string'&&own(INTERNS,o.intern)?o.intern:null;n.hired=int(o.hired,0,1e7,0);n.mon=int(o.mon,0,1e6,0);
n.floor=OPS_FLOORS.includes(o.floor)?o.floor:n.floor; n.floor=OPS_FLOORS.includes(o.floor)?o.floor:n.floor;
const on=ob(o.on),p=ob(o.p),cap=ob(o.cap),sp=ob(o.spent); const on=ob(o.on),p=ob(o.p),cap=ob(o.cap),sp=ob(o.spent);
// The routers order's model and the optical order's line system moved to the build standard (bstdAdopt()), each only
// from an order that ran: one paused, or with nobody hired, did nothing, and a standard's model costs every new POP.
const ran=k=>!!n.intern&&on[k]===true;
bstdAdopt(s,ran('routers')?ob(p.routers).model:undefined,ran('optup')?ob(p.optup).sys:undefined);
for(const d of OPS){const k=d.k;n.on[k]=on[k]===true;const q=ob(p[k]),r={}; for(const d of OPS){const k=d.k;n.on[k]=on[k]===true;const q=ob(p[k]),r={};
for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r; for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r;
if(d.cap&&opsCaps(k).includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0)); if(d.cap&&opsCaps(k).includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0));
@ -122,8 +124,10 @@ function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.con
// One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. // One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget.
// dirty: a job changed the network, so R (loads, routing) is out of date until the next compute(). // dirty: a job changed the network, so R (loads, routing) is out of date until the next compute().
// up/mo: what this shift paid up front and added to the monthly bill. // up/mo: what this shift paid up front and added to the monthly bill.
// dk: the night's fibers taken dark (n) and routings to test one (t), shared by the orders that do it (opsDarkRoom()).
// fib: the fibers and waves an order worked on this shift, by order: one owner per fiber a shift.
function opsShift(){const r=new Map(),broke=new Set(); function opsShift(){const r=new Map(),broke=new Set();
return {r,broke,dirty:false,up:0,mo:0,did(k,w){this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, return {r,broke,dirty:false,up:0,mo:0,dk:{n:0,t:0},fib:new Map(),did(k,w){this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);},
// A job that costs nothing up front still has to pass the cash floor if it adds to the monthly bill. // A job that costs nothing up front still has to pass the cash floor if it adds to the monthly bill.
// quiet: only asking, so a no is not logged as the budget running out. // quiet: only asking, so a no is not logged as the budget running out.
can(k,cost,mo=0,quiet){const O=S.ops,cap=opsCap(k);if(cost<=0&&!(mo>0))return true; can(k,cost,mo=0,quiet){const O=S.ops,cap=opsCap(k);if(cost<=0&&!(mo>0))return true;
@ -145,14 +149,15 @@ const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;retur
// after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there. // after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there.
const OPS_RUN={ const OPS_RUN={
// Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js). // Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js).
std(X){bstdShift(X);}, *std(X){yield* bstdShift(X);},
*repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}}, *repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}},
*routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next', *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),G=bstd().g,fix=G!=='keep',
load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c))); load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
// A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a // The build standard's model: swap every POP still on a smaller one to the model the standard gives it (bstdModel():
// step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there. // the best unlocked one no bigger, never a step down, never one that does not fit or cannot run the core), the
if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0; // busiest first, while the budget lasts, and only with a second router or no traffic there.
if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue; if(fix)for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c];
if(p.rupDay===S.day||!((p.routers||1)>1||popIdle(c)))continue;const m=bstdModel(G,c);if(m<0)continue;
const cost=swapCost(c,m);if(!X.can('routers',cost))continue; const cost=swapCost(c,m);if(!X.can('routers',cost))continue;
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}} if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}
for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue;
@ -222,19 +227,20 @@ const OPS_RUN={
const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break; const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break;
X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break; X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break;
cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);yield;}}}, cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);yield;}}},
*optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0; *optup(X){const at=opsP('optup','at')/100,sys=bstd().sys,goal=sys==='keep'?'next':sys,swap=opsP('optup','swap');
const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l)); const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l));
const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a)); // A fiber the build standard's order worked on this shift is that order's until tomorrow.
const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)&&(X.fib.get(l.id)||'optup')==='optup').sort((a,b)=>u(b)-u(a));
for(const l of ls){ for(const l of ls){
// The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot. // The line system: one step at a time up to the build standard's, or the next one where the fiber is full and hot.
const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]<SYS_RANK[goal]?goal:null; const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]<SYS_RANK[goal]?goal:null;
if(want&&ups<OPTUP_MAX*(opsIs('kevin')?2:1)&&tries<OPTUP_TRY*(opsIs('kevin')?2:1)){const to=sysNext(l),cost=sysUpCost(l); if(want&&opsDarkRoom(X)){const to=sysNext(l),cost=sysUpCost(l);
if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){tries++;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT); if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(ok){const s0=l.sys,top=goal==='next'?to:goal; if(ok){const s0=l.sys,top=goal==='next'?to:goal;
for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]<SYS_RANK[top];k++){const nx=sysNext(l); for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]<SYS_RANK[top];k++){const nx=sysNext(l);
if(!techOk('sys',nx,DF_SYS[nx].lvl)||!X.can('optup',sysUpCost(l))||!X.pay('optup',()=>{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;} if(!techOk('sys',nx,DF_SYS[nx].lvl)||!X.can('optup',sysUpCost(l))||!X.pay('optup',()=>{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;}
// The fiber is dark until tomorrow: its optics wait. // The fiber is dark until tomorrow: its optics wait.
if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}} if(l.sys!==s0){X.dk.n++;X.fib.set(l.id,'optup');X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}}
// Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and // Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and
// the old optics go on the shelf as spares. // the old optics go on the shelf as spares.
if(!swap)continue; if(!swap)continue;
@ -248,7 +254,7 @@ const OPS_RUN={
const was=dfCap(l); const was=dfCap(l);
X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2}); X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2});
if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;}); if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;});
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}}, if(!(dfCap(l)>was))break;X.fib.set(l.id,'optup');X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}},
*caches(X){const g=opsP('caches','g'); *caches(X){const g=opsP('caches','g');
for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue; for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue;
const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9; const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
@ -269,23 +275,34 @@ const OPS_RUN={
const q=pniRequote(q0);if(!q)continue;if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}}, const q=pniRequote(q0);if(!q)continue;if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}},
// Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102).
// Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a // Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a
// job changed the network and anything could go (opsDecomWaits()). // job changed the network and anything could go (opsDecomWaits()). A wave another order worked on today stays.
*decom(X){for(const ls of opsPairs().values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}, // (Left out of what the pick hands back, not out of the pick: it may still be the spare the pick keeps.)
*decom(X){for(const ls of opsPairs().values())for(const l of opsDecomPick(ls).filter(l=>!X.fib.has(l.id))){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}},
}; };
// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once, // Line system swaps per shift, and how many fibers a shift may test for one with a routing: each test routes the whole
// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week // network once, so a shift costs at most one routing more, and only on a night with a fiber to try. The build standard's
// order and this one share them (X.dk). A fiber that failed the test is not tested again for a week
// (not saved: after a reload it is simply tested again). // (not saved: after a reload it is simply tested again).
const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,roadm:1,cl:2},SYS_TAG={roadm:'ROADM',cl:'C+L'}; const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,roadm:1,cl:2},SYS_TAG={roadm:'ROADM',cl:'C+L'};
// Room tonight for one more fiber going dark. Kevin does maintenance: twice the swaps, and twice the tests.
const opsDarkRoom=X=>{const k=opsIs('kevin')?2:1;return X.dk.n<OPTUP_MAX*k&&X.dk.t<OPTUP_TRY*k;};
// Another live path between the fiber's two cities, without it: a plain walk, no routing. // Another live path between the fiber's two cities, without it: a plain walk, no routing.
function opsAround(l){const adj={};for(const x of S.links){if(x===l||linkDown(x))continue;(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);} function opsAround(l){const adj={};for(const x of S.links){if(x===l||linkDown(x))continue;(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);}
const seen=new Set([l.a]),q=[l.a];while(q.length){const u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;} const seen=new Set([l.a]),q=[l.a];while(q.length){const u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing // A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing
// is the yardstick (routed again first if this shift already changed the network). Both routings are steps the day // is the yardstick (routed again first if this shift already changed the network). Both routings are steps the day
// answers (OPS_ROUTE, then {dark}: opsDarkTrial(), in play in the route worker). // answers (OPS_ROUTE, then {dark}: opsDarkTrial(), in play in the route worker).
// Nothing rides the fiber: no traffic of its own (customers' circuits are in it), none on an express through it (#58).
const opsUnused=l=>{const L=(R&&R.load)||{};return !(L[l.id]>1e-6)&&!xpOver(l.id).some(x=>L[x.id]>1e-6);};
// What a day dark comes to, said without routing: false (a customer rides it, or it carries traffic with no other way
// between its cities), true (nothing rides it, so nothing is lost), null (a routing decides: opsDarkTrial()).
function opsDarkPre(l){if(S.biz.some(b=>b.link===l.id))return false;return opsUnused(l)?true:opsAround(l)?null:false;}
const OPS_ROUTE={route:true}; const OPS_ROUTE={route:true};
function* opsDark(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;} // X.dk.t counts the tests that route.
return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});} function* opsDark(l,X){let k=opsDarkPre(l);if(k===false)return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;k=opsDarkPre(l);}
// The test itself, on the game it is given: R is put back after. if(k!==null)return k;X.dk.t++;return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});}
// The test itself, on the game it is given: R is put back after. The fiber's line system is down for the day (eqDown),
// and every express riding it with it (xpDown()): their traffic has to get around too.
function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0; function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0;
try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);} try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);}
finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}} finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}}
@ -300,8 +317,8 @@ function opsDecomPick(ls,cf=capOf){if(!ls||ls.length<2)return [];const live=ls.f
for(const l of small.reverse()){if(cap-cf(l)<load*1.25)break;if(!opsDecomSafe(l,out))continue;cap-=cf(l);out.push(l);} for(const l of small.reverse()){if(cap-cf(l)<load*1.25)break;if(!opsDecomSafe(l,out))continue;cap-=cf(l);out.push(l);}
return out;} return out;}
// The same test overtaken by an action: its checks, and today's routing as the yardstick, as the game is now. // The same test overtaken by an action: its checks, and today's routing as the yardstick, as the game is now.
function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l||S.biz.some(b=>b.link===l.id)||!opsAround(l))return false; function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const k=opsDarkPre(l);
return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});} return k!==null?k:opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});}
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it (and gone) first. // A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it (and gone) first.
function opsDecomSafe(l,gone=[]){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; function opsDecomSafe(l,gone=[]){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true); const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);

View file

@ -26,6 +26,13 @@ function bstd(d=S&&S.popStd){const o={},ob=d&&typeof d==='object'&&!Array.isArra
// Back to the saved form: the model and router count, and any other target that is not "keep". Nothing set: null. // Back to the saved form: the model and router count, and any other target that is not "keep". Nothing set: null.
function bstdPut(o){const d={};for(const x of BSTD)if(x.k==='rt'||o[x.k]!==x.d)d[x.k]=o[x.k];return Object.keys(d).length>1||d.rt>1?d:null;} function bstdPut(o){const d={};for(const x of BSTD)if(x.k==='rt'||o[x.k]!==x.d)d[x.k]=o[x.k];return Object.keys(d).length>1||d.rt>1?d:null;}
function popStdSanitize(s){s.popStd=s.popStd&&typeof s.popStd==='object'&&!Array.isArray(s.popStd)?bstdPut(bstd(s.popStd)):null;} function popStdSanitize(s){s.popStd=s.popStd&&typeof s.popStd==='object'&&!Array.isArray(s.popStd)?bstdPut(bstd(s.popStd)):null;}
// Saves from when the intern's orders had their own router model (routers) and line system (optup): the standard takes
// them where it has none of its own; one that names its own keeps it. 'next' was no choice at all: nothing moves.
// opsSanitize() passes only what an order that was running used (undefined otherwise): the rest is dropped.
function bstdAdopt(s,g,sys){const D=bstd(s.popStd);let n=0;
if(D.g==='keep'&&Number.isInteger(g)&&bstdOk(BSTDK.g,g)){D.g=g;n++;}
if(D.sys==='keep'&&sys!=='keep'&&bstdOk(BSTDK.sys,sys)){D.sys=sys;n++;}
if(n)s.popStd=bstdPut(D);}
// A bank that forbids generators (Stormy Weather's covenant): the standard never installs one while that loan runs. // A bank that forbids generators (Stormy Weather's covenant): the standard never installs one while that loan runs.
const bstdNoGen=()=>(S.loans||[]).some(l=>(l.covs||[]).includes('nogen')); const bstdNoGen=()=>(S.loans||[]).some(l=>(l.covs||[]).includes('nogen'));
// The model a POP should get: the standard's if you can buy it, else the best main-line model that is unlocked and no // The model a POP should get: the standard's if you can buy it, else the best main-line model that is unlocked and no
@ -80,12 +87,14 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J
const take=(c,n,dry)=>{if(n<=0)return true;if(room(c)<n)return false;if(!dry)rmn[c]-=n;return true;}; const take=(c,n,dry)=>{if(n<=0)return true;if(room(c)<n)return false;if(!dry)rmn[c]-=n;return true;};
const job=(grp,k,ch,w,cost,mo,go,x)=>{const j={grp,k,ch,w,cost,mo,go,...x};J.push(j);return j;}; const job=(grp,k,ch,w,cost,mo,go,x)=>{const j={grp,k,ch,w,cost,mo,go,...x};J.push(j);return j;};
for(const c of cs){const p=S.pops[c],ch='p:'+c;let g=p.rgen||0,rt=p.routers||1,sw=null,s2=null; for(const c of cs){const p=S.pops[c],ch='p:'+c;let g=p.rgen||0,rt=p.routers||1,sw=null,s2=null;
const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;}; // A router job checks the POP still has what the plan counted on: the intern's shift rests between jobs, and the player
// may click meanwhile (the button, a router by hand). So does a PNI job: one ordered meanwhile is not upgraded.
const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;if(n!==r0)return false;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;};
const m=p.rupDay===S.day?-1:bstdModel(D.g,c); const m=p.rupDay===S.day?-1:bstdModel(D.g,c);
if(m>=0){ if(m>=0){
// One router carrying traffic: a second goes in first, so the swap rolls through with no maintenance window. // One router carrying traffic: a second goes in first, so the swap rolls through with no maintenance window.
if(rt===1&&!popIdle(c))add(); if(rt===1&&!popIdle(c))add();
const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;} const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{if((S.pops[c].rgen||0)!==old)return false;ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;}
while(rt<D.rt&&rt<RMAX)add(); while(rt<D.rt&&rt<RMAX)add();
// A building and a generator do not wait for the routers, nor for each other. // A building and a generator do not wait for the routers, nor for each other.
if(D.site2&&!p.site2)s2=job('pop','site2','s:'+c,c,SITE2_COST,SITE2_MO,()=>{ACT.addSite({city:c});return !!S.pops[c].site2;},{c}); if(D.site2&&!p.site2)s2=job('pop','site2','s:'+c,c,SITE2_COST,SITE2_MO,()=>{ACT.addSite({city:c});return !!S.pops[c].site2;},{c});
@ -108,7 +117,7 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J
const opts=NET[net].pops.filter(c=>S.pops[c]&&here(c)&&!by[net].has(c)).map(c=>({c,v:pniVal(net,c)})).filter(o=>o.v.worth).sort((a,b)=>b.v.want-a.v.want||(a.c<b.c?-1:1)); const opts=NET[net].pops.filter(c=>S.pops[c]&&here(c)&&!by[net].has(c)).map(c=>({c,v:pniVal(net,c)})).filter(o=>o.v.worth).sort((a,b)=>b.v.want-a.v.want||(a.c<b.c?-1:1));
for(const {c,v} of opts){if(k<=0)break;let q=null;for(let t=Math.max(v.tier,pniMin(net));t>=pniMin(net)&&!q;t--){const x=pniQuote(c,net,t,resv(c));if(x&&!x.why)q=x;} for(const {c,v} of opts){if(k<=0)break;let q=null;for(let t=Math.max(v.tier,pniMin(net));t>=pniMin(net)&&!q;t--){const x=pniQuote(c,net,t,resv(c));if(x&&!x.why)q=x;}
if(!q||!take(c,q.slots))continue;const tier=q.tier;k--; if(!q||!take(c,q.slots))continue;const tier=q.tier;k--;
job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}} job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||x.ex||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}}
// Fiber and waves, hottest first. A POP excepted from the order keeps its links as they are too. // Fiber and waves, hottest first. A POP excepted from the order keeps its links as they are too.
if(D.sys!=='keep'||D.opt!=='keep'||D.wv!=='keep'){const sp={...(S.spares||{})},dk=new Map(),wv=new Map(); if(D.sys!=='keep'||D.opt!=='keep'||D.wv!=='keep'){const sp={...(S.spares||{})},dk=new Map(),wv=new Map();
const ls=S.links.filter(l=>(l.kind==='df'||l.kind==='wave')&&here(l.a)&&here(l.b)&&S.pops[l.a]&&S.pops[l.b]).map(l=>({l,u:(R.load[l.id]||0)/Math.max(1e-9,capOf(l))})).sort((a,b)=>b.u-a.u||(a.l.id<b.l.id?-1:1)); const ls=S.links.filter(l=>(l.kind==='df'||l.kind==='wave')&&here(l.a)&&here(l.b)&&S.pops[l.a]&&S.pops[l.b]).map(l=>({l,u:(R.load[l.id]||0)/Math.max(1e-9,capOf(l))})).sort((a,b)=>b.u-a.u||(a.l.id<b.l.id?-1:1));
@ -124,10 +133,12 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J
let sys=l.sys;const lit=l.ready<=S.day,nx=D.sys!=='keep'&&BSTD_SYS[sys]<BSTD_SYS[D.sys]&&sysNext({sys}); let sys=l.sys;const lit=l.ready<=S.day,nx=D.sys!=='keep'&&BSTD_SYS[sys]<BSTD_SYS[D.sys]&&sysNext({sys});
// A lit fiber goes dark for a day. Busy with nothing parallel to carry it: it keeps its line system for now, and // A lit fiber goes dark for a day. Busy with nothing parallel to carry it: it keeps its line system for now, and
// gets the best optics that one takes. A parallel fiber goes dark first in this plan: it waits for next time. // gets the best optics that one takes. A parallel fiber goes dark first in this plan: it waits for next time.
// The intern's plan leaves the rest to the shift's own test (opsDark(): a routing without the fiber), as the optical
// order does: here only what is known without one (opsDarkPre()), and a fiber that failed the test this week.
if(nx&&techOk('sys',nx,DF_SYS[nx].lvl)){ if(nx&&techOk('sys',nx,DF_SYS[nx].lvl)){
if(lit&&!bstdDarkOk(l))J.held.push(l); if(lit&&!(intern?!(OPTUP_NO.get(l.id)>S.day)&&opsDarkPre(l)!==false:bstdDarkOk(l)))J.held.push(l);
else if(lit&&!bstdDarkOk(l,dk)){J.held.push(l);continue;} else if(lit&&(intern?pairLinks(l.a,l.b).some(x=>x!==l&&dk.get(x.id)):!bstdDarkOk(l,dk))){J.held.push(l);continue;}
else{const busy=lit&&bstdBusy(l); else{const busy=lit&&(intern?!opsUnused(l):bstdBusy(l));
while(BSTD_SYS[sys]<BSTD_SYS[D.sys]){const to=sysNext({sys});if(!to||!techOk('sys',to,DF_SYS[to].lvl))break; while(BSTD_SYS[sys]<BSTD_SYS[D.sys]){const to=sysNext({sys});if(!to||!techOk('sys',to,DF_SYS[to].lvl))break;
const s0=sys;job('fiber','sys',ch,l.a+'|'+l.b,sysCost(to)*(to==='cl'&&l.own?Math.max(1,l.pairs|0):1),0,()=>{if(l.sys!==s0)return false;ACT.upSys({id:l.id});return l.sys===to;},{l,dark:lit,busy});sys=to;} const s0=sys;job('fiber','sys',ch,l.a+'|'+l.b,sysCost(to)*(to==='cl'&&l.own?Math.max(1,l.pairs|0):1),0,()=>{if(l.sys!==s0)return false;ACT.upSys({id:l.id});return l.sys===to;},{l,dark:lit,busy});sys=to;}
if(lit)dk.set(l.id,busy);}} if(lit)dk.set(l.id,busy);}}
@ -178,25 +189,32 @@ function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen
// The new ones could not go in (ports, cash): the old optics go back in from the shelf. // The new ones could not go in (ports, cash): the old optics go back in from the shelf.
(l.ch=l.ch||[]).push(...Array(k).fill(o0));S.spares[o0]-=k;return false;}});} (l.ch=l.ch||[]).push(...Array(k).fill(o0));S.spares[o0]-=k;return false;}});}
return out;} return out;}
// A line-system swap darkens the fiber for a day: only while it carries little, or its parallel links can take its load. // The button's test of a line-system swap, which darkens the fiber for a day: only while it carries little, or its
// parallel links can take its load. No routing, so the quote is what the click does. (The intern routes: opsDark().)
// ex: fibers already going dark today (id → whether they carry traffic): they carry nothing for this one, and one whose // ex: fibers already going dark today (id → whether they carry traffic): they carry nothing for this one, and one whose
// traffic leans on its parallel links keeps them lit. // traffic leans on its parallel links keeps them lit.
const bstdBusy=l=>((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1); const bstdBusy=l=>((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1);
// Express lightpaths (#58) ride the fiber's glass: its own load says nothing about them, and its parallel links do not // Express lightpaths (#58) ride the fiber's glass: its own load says nothing about them, and its parallel links do not
// carry them, so an express with any traffic at all keeps the fiber lit (the line system waits, as for a busy fiber). // carry them, so an express with any traffic at all keeps the fiber lit (the line system waits, as for a busy fiber).
// The intern's routing test needs no such rule: an express goes dark with its fiber there (opsDarkTrial()).
const bstdXpBusy=l=>xpSlots(l)>0&&xpOver(l.id).some(x=>((R.load&&R.load[x.id])||0)>1e-6); const bstdXpBusy=l=>xpSlots(l)>0&&xpOver(l.id).some(x=>((R.load&&R.load[x.id])||0)>1e-6);
function bstdDarkOk(l,ex){if(bstdXpBusy(l))return false;const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; function bstdDarkOk(l,ex){if(bstdXpBusy(l))return false;const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true;
return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);} return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);}
// Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. /* Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took.
// one: at most one fiber goes dark (the intern's shift); max: at most that many jobs tried, done or failed, so a shift's dark(j, ex): may the first job that darkens a fiber go ahead (ex: fibers gone dark so far, as bstdDarkOk() takes them),
// work stays bounded whatever goes wrong. Returns what was done. a generator, so a test can route (yields included); done1(j, first): after each job done (first: it took a fiber dark).
function bstdDo(J,can,pay,one,max=1e9){const stop=new Set(),done=new Set(),dark=new Map();let n=0; max: at most that many jobs tried, done or failed, so a shift's work stays bounded whatever goes wrong. A bare yield
after each job is a place to let a frame through. Returns what was done. */
function* bstdRun(J,can,pay,dark,done1,max=1e9){const stop=new Set(),done=new Set(),dk=new Map();let n=0;
for(const j of J){if(n>=max)break;if(stop.has(j.ch))continue;if(j.dep&&!j.dep.every(d=>done.has(d))){stop.add(j.ch);continue;} for(const j of J){if(n>=max)break;if(stop.has(j.ch))continue;if(j.dep&&!j.dep.every(d=>done.has(d))){stop.add(j.ch);continue;}
if(j.dark&&!dark.has(j.l.id)&&((one&&dark.size)||!bstdDarkOk(j.l,dark))){stop.add(j.ch);continue;} // The money first: no fiber is tested for a job the budget cannot pay, and asked again after a test that routed.
if(!can(j)){stop.add(j.ch);continue;}n++; const first=!!j.dark&&!dk.has(j.l.id);
if(!can(j)||first&&(!(yield* dark(j,dk))||!can(j))){stop.add(j.ch);continue;}n++;
if(!pay(j)){stop.add(j.ch);continue;} if(!pay(j)){stop.add(j.ch);continue;}
if(j.dark)dark.set(j.l.id,!!j.busy);done.add(j);} if(j.dark)dk.set(j.l.id,!!j.busy);done.add(j);if(done1)done1(j,first);yield;}
return [...done];} return [...done];}
// The button: the whole plan at once, on the page, every fiber judged as the plan judged it.
function bstdDo(J,can,pay){const g=bstdRun(J,can,pay,function*(j,ex){return bstdDarkOk(j.l,ex);});for(;;){const s=g.next();if(s.done)return s.value;}}
// What a job costs as it runs (an optics swap is priced again then: see bstdOptJobs). // What a job costs as it runs (an optics swap is priced again then: see bstdOptJobs).
const bstdPrice=j=>j.price?j.price():j.cost; const bstdPrice=j=>j.price?j.price():j.cost;
// The sheet's summary and the MCP quote: how much is below the standard, and what bringing it all up costs. The plan is // The sheet's summary and the MCP quote: how much is below the standard, and what bringing it all up costs. The plan is
@ -206,5 +224,14 @@ function bstdQuote(intern){const J=bstdPlan(intern),P=new Set(),Q=new Set(),L=ne
return {cost:Math.round(cost),mo:Math.round(mo),pops:P.size,ports:Q.size,links:L.size,n:J.length,held:J.held.map(l=>l.a+'|'+l.b)};} return {cost:Math.round(cost),mo:Math.round(mo),pops:P.size,ports:Q.size,links:L.size,n:J.length,held:J.held.map(l=>l.a+'|'+l.b)};}
// The optics order lights the standard's fastest optics while this order keeps to a standard that wants them. // The optics order lights the standard's fastest optics while this order keeps to a standard that wants them.
const bstdFast=()=>!!(S.popStd&&opsHired()&&S.ops.on.std&&bstd().opt==='fast'); const bstdFast=()=>!!(S.popStd&&opsHired()&&S.ops.on.std&&bstd().opt==='fast');
// The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a time. /* The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a
function bstdShift(X){bstdDo(bstdPlan(true),j=>X.can('std',bstdPrice(j),j.mo),j=>X.pay('std',()=>j.go())&&(X.did('std',j.w),true),true,BSTD_MAX);} time. A fiber goes dark only on the optical order's test (opsDark(): a routing without it, in play in the route
worker), within the night's dark swaps that order shares (opsDarkRoom()), and a fiber that fails waits a week. One
owner per fiber: a fiber or wave the optical order worked on this shift is left alone, and what this order works on
is its own until tomorrow (X.fib: that order and decom leave it alone). The plan is made once a shift, and the shift
rests between jobs: a POP decommissioned or a link given up meanwhile is not worked on (the links last: a walk of them,
only for a job the budget lets through). */
function* bstdShift(X){const mine=j=>(!j.c||!!S.pops[j.c])&&(!j.l||(X.fib.get(j.l.id)||'std')==='std');
yield* bstdRun(bstdPlan(true),j=>mine(j)&&X.can('std',bstdPrice(j),j.mo)&&(!j.l||S.links.includes(j.l)),j=>X.pay('std',()=>j.go())&&(X.did('std',j.w),true),
function*(j){const l=j.l;if(OPTUP_NO.get(l.id)>S.day||!opsDarkRoom(X))return false;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);return ok;},
(j,first)=>{if(j.l)X.fib.set(j.l.id,'std');if(first)X.dk.n++;},BSTD_MAX);}

View file

@ -7,7 +7,7 @@ Object.assign(ACT,{
// The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One // The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One
// recompute at the end, and one toast: what got done, and what still waits. // recompute at the end, and one toast: what got done, and what still waits.
bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0; bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0;
opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go(),false).length;}); opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go()).length;});
after();const q=bstdQuote(false),left=q.pops+q.ports+q.links; after();const q=bstdQuote(false),left=q.pops+q.ports+q.links;
toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err'); toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err');
if(bstdShown())bstdModal();}, if(bstdShown())bstdModal();},

View file

@ -9,11 +9,15 @@ function opsVal(k,p,v=opsP(k,p)){const P=OPSK[k].p[p];return p==='prov'?(v==='ch
// A setting as a list to pick from: the option values are positions in the list the action reads again. // A setting as a list to pick from: the option values are positions in the list the action reads again.
const opsSel=(lab,act,args,vals,cur,name)=>`<label class="ops-sel"><span>${lab}</span><select data-chg="${act}" data-args="${esc(JSON.stringify(args))}">${vals.map((v,i)=>`<option value="${i}"${v===cur?' selected':''}>${esc(name(v))}</option>`).join('')}</select></label>`; const opsSel=(lab,act,args,vals,cur,name)=>`<label class="ops-sel"><span>${lab}</span><select data-chg="${act}" data-args="${esc(JSON.stringify(args))}">${vals.map((v,i)=>`<option value="${i}"${v===cur?' selected':''}>${esc(name(v))}</option>`).join('')}</select></label>`;
const opsCapName=(k,v)=>v?tr('common.price_mo',{price:(OPSK[k].mo?'+':'')+fmt$(v)}):tr('ops.no_cap'); const opsCapName=(k,v)=>v?tr('common.price_mo',{price:(OPSK[k].mo?'+':'')+fmt$(v)}):tr('ops.no_cap');
// The router model and the line system are the build standard's, chosen in its sheet only: in their place, what it says
// and the way there. "Keep as is" leaves each order to its own rule: the next model or line system up, when needed.
const OPS_BSTD={routers:{k:'g',l:N_('ops.p_model'),f:v=>v==='keep'?tr('ops.model_next'):RG[v].n},optup:{k:'sys',l:N_('ops.p_sys'),f:v=>v==='keep'?tr('ops.sys_next'):DF_SYS[v].n}};
function opsFromStd(k){const x=OPS_BSTD[k];return x?`<div class="ops-from"><span>${tr(x.l)}</span><b>${esc(tr('ops.from_bstd',{x:x.f(bstd()[x.k])}))}</b>${pzOn()?'':btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}</div>`:'';}
function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0); function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0);
return `<div class="ops-o${on?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${d.i}</span><div class="grow"><div class="nm">${tr(d.t)}</div><div class="meta">${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO),big:fmt$(CACHE_BIG_MO)}):''}</div></div> return `<div class="ops-o${on?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${d.i}</span><div class="grow"><div class="nm">${tr(d.t)}</div><div class="meta">${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO),big:fmt$(CACHE_BIG_MO)}):''}</div></div>
<button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"${k}"}' aria-pressed="${on}" aria-label="${esc(tr(d.t))}">${on?tr('common.on'):tr('ops.paused')}</button></div> <button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"${k}"}' aria-pressed="${on}" aria-label="${esc(tr(d.t))}">${on?tr('common.on'):tr('ops.paused')}</button></div>
${k==='std'?`<div class="meta">${tr('bstd.now_line',{list:S.popStd?esc(bstdLine(bstd())):tr('pop_std.none')})}</div><div class="btns">${btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}</div>`:''} ${k==='std'?`<div class="meta">${tr('bstd.now_line',{list:S.popStd?esc(bstdLine(bstd())):tr('pop_std.none')})}</div><div class="btns">${btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}</div>`:''}
${on?`<div class="ops-p">${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')} ${on?`<div class="ops-p">${opsFromStd(k)}${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')}
${d.cap?opsSel(d.mo?tr('ops.budget_running'):tr('ops.budget'),'opsCap',{k},opsCaps(k),cap,v=>opsCapName(k,v)):''}</div> ${d.cap?opsSel(d.mo?tr('ops.budget_running'):tr('ops.budget'),'opsCap',{k},opsCaps(k),cap,v=>opsCapName(k,v)):''}</div>
${sp||am?`<div class="meta">${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}</div>`:''} ${sp||am?`<div class="meta">${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}</div>`:''}
${k==='ix'&&ppol()!=='open'?`<p class="why">${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}</p>`:''}`:''}</div>`;} ${k==='ix'&&ppol()!=='open'?`<p class="why">${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}</p>`:''}`:''}</div>`;}

View file

@ -21,7 +21,7 @@ function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hire
let h=`<div data-sheet="bstd" style="display:flex;align-items:center"><div><div class="eyebrow">${tr('ops.ops')}</div><h2 style="font-size:26px">${tr('bstd.title')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div> let h=`<div data-sheet="bstd" style="display:flex;align-items:center"><div><div class="eyebrow">${tr('ops.ops')}</div><h2 style="font-size:26px">${tr('bstd.title')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('bstd.tagline')}</p>`; <p class="tagline">${tr('bstd.tagline')}</p>`;
for(const [g,lab] of BSTD_GRP)h+=`<section><h3>${tr(lab)}</h3><div class="ops-p">${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}</div> for(const [g,lab] of BSTD_GRP)h+=`<section><h3>${tr(lab)}</h3><div class="ops-p">${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}</div>
<p class="note">${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note')}</p></section>`; <p class="note">${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note_two')}</p></section>`;
// What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose // What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose
// line system has to wait is below it too, but not on the bill. // line system has to wait is below it too, but not on the bill.
const n={pop:q.pops,port:q.ports,fiber:q.links},w=q.held.length; const n={pop:q.pops,port:q.ports,fiber:q.links},w=q.held.length;
@ -30,7 +30,7 @@ function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hire
+(w?`<p class="meta">${trn('bstd.held',w)}</p>`:'') +(w?`<p class="meta">${trn('bstd.held',w)}</p>`:'')
:`<p class="meta">${S.popStd?tr('bstd.all_up'):tr('bstd.none_set')}</p>`}</section>`; :`<p class="meta">${S.popStd?tr('bstd.all_up'):tr('bstd.none_set')}</p>`}</section>`;
// The intern keeps it there: the order's switch and budget, or a word on hiring one. // The intern keeps it there: the order's switch and budget, or a word on hiring one.
h+=`<section><h3>${tr('ops.o_std')}</h3>${hired?`<div class="ops-o${on?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${INTERNS[S.ops.intern].i}</span><div class="grow"><div class="nm">${esc(tr('bstd.intern_keeps',{name:opsName()}))}</div><div class="meta">${tr('ops.o_std_d')}</div></div> h+=`<section><h3>${tr('ops.o_std')}</h3>${hired?`<div class="ops-o${on?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${INTERNS[S.ops.intern].i}</span><div class="grow"><div class="nm">${esc(tr('bstd.intern_keeps',{name:opsName()}))}</div><div class="meta">${tr('ops.o_std_around_d')}</div></div>
<button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"std"}' aria-pressed="${on}" aria-label="${esc(tr('ops.o_std'))}">${on?tr('common.on'):tr('ops.paused')}</button></div> <button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"std"}' aria-pressed="${on}" aria-label="${esc(tr('ops.o_std'))}">${on?tr('common.on'):tr('ops.paused')}</button></div>
${on?`<div class="ops-p">${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}</div>`:''}</div>` ${on?`<div class="ops-p">${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}</div>`:''}</div>`
:`<p class="meta">${tr('bstd.hire_note')}</p><div class="btns">${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}</div>`}</section>`; :`<p class="meta">${tr('bstd.hire_note')}</p><div class="btns">${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}</div>`}</section>`;

View file

@ -412,7 +412,7 @@
"bstd.edit":"Edit the build standard", "bstd.edit":"Edit the build standard",
"bstd.every_exchange":"Wherever there is an IX", "bstd.every_exchange":"Wherever there is an IX",
"bstd.fastest":"Fastest that reaches", "bstd.fastest":"Fastest that reaches",
"bstd.fiber_note":"A line system swap takes the fiber dark for a day: only on a quiet fiber, or where a parallel link carries its load.", "bstd.fiber_note_two":"A line system swap takes the fiber dark for a day. The button does it only on a quiet fiber or where a parallel link carries its load; your intern only where all the traffic gets around the fiber.",
"bstd.from_level":"(level {lv})", "bstd.from_level":"(level {lv})",
"bstd.g_fiber":"Fiber and waves", "bstd.g_fiber":"Fiber and waves",
"bstd.g_port":"Ports and peering", "bstd.g_port":"Ports and peering",
@ -3401,6 +3401,7 @@
"ops.fire":"Let go", "ops.fire":"Let go",
"ops.fired":"{name} handed in the badge and took the good stapler. Your standing orders are paused.", "ops.fired":"{name} handed in the badge and took the good stapler. Your standing orders are paused.",
"ops.floor":"Keep at least", "ops.floor":"Keep at least",
"ops.from_bstd":"From the build standard: {x}",
"ops.good_annie":"Best at peering: works through the exchanges every day, not weekly, and orders PNIs twice a week.", "ops.good_annie":"Best at peering: works through the exchanges every day, not weekly, and orders PNIs twice a week.",
"ops.good_kevin":"Best at maintenance: two line system swaps a night instead of one, and never a fat finger.", "ops.good_kevin":"Best at maintenance: two line system swaps a night instead of one, and never a fat finger.",
"ops.good_tracy":"Best at planning ahead: buys transit, ports, routers and optics as if traffic were already 10% higher.", "ops.good_tracy":"Best at planning ahead: buys transit, ports, routers and optics as if traffic were already 10% higher.",
@ -3457,7 +3458,7 @@
"ops.o_optics":"Light more fiber", "ops.o_optics":"Light more fiber",
"ops.o_optics_d":"Add optics to dark fiber that runs hot, and light new fiber the day it is handed over.", "ops.o_optics_d":"Add optics to dark fiber that runs hot, and light new fiber the day it is handed over.",
"ops.o_optup":"Upgrade optical transport", "ops.o_optup":"Upgrade optical transport",
"ops.o_optup_d":"On fiber that is full and runs hot, move the line system up a size, or trade the smallest channels for bigger optics (the old ones go on the shelf). Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so only where the traffic gets around it and no customer rides it, one a night.", "ops.o_optup_std_d":"On fiber that is full and runs hot, move the line system up a size, or trade the smallest channels for bigger optics (the old ones go on the shelf). With a line system in the build standard, every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so only where the traffic gets around it and no customer rides it, one a night together with Keep to the build standard.",
"ops.o_pni":"PNI with the big ones", "ops.o_pni":"PNI with the big ones",
"ops.o_pni_d":"Every week: order a PNI with every willing network sending enough traffic at your POPs, at each network's own minimum size.", "ops.o_pni_d":"Every week: order a PNI with every willing network sending enough traffic at your POPs, at each network's own minimum size.",
"ops.o_ports":"Keep peering headroom", "ops.o_ports":"Keep peering headroom",
@ -3465,9 +3466,9 @@
"ops.o_repair":"Rush repairs", "ops.o_repair":"Rush repairs",
"ops.o_repair_d":"Pay for the rush repair on every outage that has one, while the budget lasts.", "ops.o_repair_d":"Pay for the rush repair on every outage that has one, while the budget lasts.",
"ops.o_routers":"Keep routers ahead", "ops.o_routers":"Keep routers ahead",
"ops.o_routers_desc":"Add a router, or swap to the next generation where a second router carries the traffic, when load or ports pass a level. Pick a model, and every POP on a smaller one is swapped to it, the busiest first, within the budget.", "ops.o_routers_std_d":"Add a router, or swap to the next generation where a second router carries the traffic, when load or ports pass a level. With a router model in the build standard, every POP on a smaller one is swapped to it instead, the busiest first, within the budget.",
"ops.o_std":"Keep to the build standard", "ops.o_std":"Keep to the build standard",
"ops.o_std_d":"Bring POPs, ports and fiber up to your build standard, the busiest first, a few jobs a shift. A second router goes in before a swap, and a line system only changes on a quiet fiber.", "ops.o_std_around_d":"Bring POPs, ports and fiber up to your build standard, the busiest first, a few jobs a shift. A second router goes in before a swap, and a line system only changes where the traffic gets around the fiber for its day dark and no customer rides it, one a night together with Upgrade optical transport.",
"ops.o_transit":"Keep transit headroom", "ops.o_transit":"Keep transit headroom",
"ops.o_transit_d":"Keep transit at each POP above a multiple of its 30-day peak: add a LAG member, or move up a port size.", "ops.o_transit_d":"Keep transit at each POP above a multiple of its 30-day peak: add a LAG member, or move up a port size.",
"ops.ops":"Ops", "ops.ops":"Ops",

View file

@ -13,6 +13,11 @@
/* A setting is a list to pick from: two to a row on a phone, the list as wide as its column. */ /* A setting is a list to pick from: two to a row on a phone, the list as wide as its column. */
.ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} .ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)}
.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} .ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px}
/* A setting the build standard owns: a whole row, what it says, and the way to its sheet (under it on a narrow phone). */
.ops-from{flex:1 1 100%;display:flex;flex-wrap:wrap;align-items:center;gap:2px 8px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)}
.ops-from>span{flex:1 1 100%}
.ops-from b{flex:1 1 160px;min-width:0;font:700 14px Nunito,sans-serif;color:var(--text);overflow-wrap:anywhere}
.ops-from .b{flex:none;min-height:36px}
.ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} .ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto}
.ops-good{font-size:12.5px;font-weight:800;color:#6B3FD4;margin-top:2px;line-height:1.3} .ops-good{font-size:12.5px;font-weight:800;color:#6B3FD4;margin-top:2px;line-height:1.3}
.ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)} .ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)}

276
tests/bstd-owner.test.js Normal file
View file

@ -0,0 +1,276 @@
// One owner per fiber: the build standard's order (std) and the optical order (optup) take fibers dark with the same
// test (a routing without the fiber, in the route worker in play), share one budget of dark swaps a night, and never both
// work on one fiber in a shift; the decom order leaves a wave the standard just upgraded. Change Freeze, no failures.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Frankfurt (broadband, 100G Cogentle transit), Amsterdam and Paris with broadband, everyone on four Chonk 800s, level 7.
const BASE = "Date.now=()=>1.7e12;ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(const c of ['ams','par','lon'])ACT.buildPop({city:c});" +
"for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=RG.findIndex(r=>r.n==='Chonk 800');S.pops[c].routers=4;}ACT.launchBB({city:'ams'});ACT.launchBB({city:'par'});compute()";
function game(t, extra = '', opts = {}) {
const h = load(opts);
t.after(() => h.dom.window.close());
h.ev(BASE);
if (extra) h.ev(extra);
return h;
}
const hire = (ev, id) => ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap={std:0,optup:0};S.ops.on.std=true;closeModal()`);
const std = (ev, d) => ev(`S.popStd=bstdPut({...bstd(),...${lit(d)}})`);
// A leased dark fiber, built and lit with these optics; a wave.
const fiber = (ev, a, b, ch, sys = 'lite') => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'df',own:false,sys:'${sys}',ch:${lit(ch)},km:Math.round(kmBetween('${a}','${b}')),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});return id;})()`);
const wave = (ev, a, b, tier) => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'wave',tier:${tier},km:Math.round(kmBetween('${a}','${b}')),cut:0,mo:1,trench:id,day:S.day});return id;})()`);
const L = (ev, id) => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)})||null)`));
const said = ev => JSON.parse(ev('JSON.stringify((S.ops.log[0]&&S.ops.log[0].d===S.day?S.ops.log[0].r:[]).map(x=>[x[0],x[1]]))'));
// Count the fiber tests that route (opsDarkTrial()), on the page here: tests never use the worker.
const COUNT = "window.__tr=0;const _t=opsDarkTrial;opsDarkTrial=function(){__tr++;return _t.apply(this,arguments);};";
test('both orders share one budget of dark swaps a night: one for Annie, two for Kevin, whoever does them', t => {
for (const [id, want] of [['annie', 1], ['kevin', 2]]) {
// Nobody on the far ends: the fibers really are quiet, whenever the shift routes again.
const { ev, errors } = game(t, 'S.pops.ams.bb=null;S.pops.par.bb=null');
const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4']));
ev('compute();for(const l of S.links)R.load[l.id]=0');
hire(ev, id);
std(ev, { sys: 'roadm' });
ev('S.ops.on.optup=true;opsDay(S.day)');
assert.equal(ids.filter(x => L(ev, x).sys === 'roadm').length, want, id + ': fibers swapped tonight');
assert.deepEqual(said(ev), [['std', want]], id + ': the build standard went first, the optical order found no room left');
// Alone, the optical order has the same budget (the line system from the standard).
ev('S.ops.on.std=false;S.day+=2;compute();for(const l of S.links)R.load[l.id]=0;opsDay(S.day)');
assert.equal(ids.filter(x => L(ev, x).sys === 'roadm').length, Math.min(3, 2 * want), id);
assert.deepEqual(said(ev), [['optup', Math.min(want, 3 - want)]]);
assert.deepEqual(errors, []);
}
});
test('a fiber the build standard worked on tonight is its own: the optical order takes it the next night', t => {
// A full Rainbow-in-a-Box fiber to Amsterdam, running hot, and a big wave beside it for the day it goes dark.
const { ev, errors } = game(t);
const f = fiber(ev, 'fra', 'ams', Array(16).fill('zr4'));
wave(ev, 'fra', 'ams', 3);
const hot = `compute();R.load[${lit(f)}]=1e5;`;
hire(ev, 'annie');
std(ev, { opt: 'fast' });
ev(`S.ops.on.optup=true;${hot}opsDay(S.day)`);
assert.deepEqual([L(ev, f).sys, [...new Set(L(ev, f).ch)]], ['lite', ['zr8']], 'the standard swapped its optics; its line system stays tonight');
assert.deepEqual(said(ev), [['std', 1]], 'the optical order left it alone');
ev(`S.day++;${hot}opsDay(S.day)`);
assert.equal(L(ev, f).sys, 'roadm', 'the next night, with nothing left for the standard there, the optical order moves it up');
assert.deepEqual(said(ev), [['optup', 1]]);
assert.deepEqual(errors, []);
});
test("the standard's order takes a fiber dark on the optical order's test: a way around, not just a parallel link, and never a little traffic with none", t => {
// Amsterdam's broadband rides Frankfurt–Amsterdam; Paris closes a ring of fibers with room.
const { ev, errors } = game(t);
const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'ams', 'par', ['zr4', 'zr4']), c = fiber(ev, 'par', 'fra', ['zr4', 'zr4']);
ev(COUNT);
hire(ev, 'annie');
std(ev, { sys: 'roadm' });
// Busy by the plan's own measure, and nothing parallel: the button waits for it, the intern routes and finds the ring.
const busy = `compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`;
ev(busy);
assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false).held)')), ['fra|ams'], 'the button: busy, nothing parallel');
assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')), [], 'the intern: a routing decides');
const served = ev('R.served');
ev('opsDay(S.day)');
assert.equal(ev('__tr'), 1, 'one routing without the fiber');
assert.deepEqual([L(ev, a).sys, L(ev, b).sys, L(ev, c).sys], ['roadm', 'lite', 'lite'], 'the busy one first, one a night');
ev('compute()');
assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through, round the ring');
// A little traffic (well under the plan's "quiet") and no way around: the old test let it go dark; this one never.
const g = game(t);
const x = fiber(g.ev, 'fra', 'ams', ['zr4', 'zr4']);
g.ev('compute()');
assert.ok(g.ev(`R.load[${lit(x)}]`) > 1 && !g.ev(`bstdBusy(S.links.find(l=>l.id===${lit(x)}))`), 'Amsterdam\'s broadband, under 10% of the fiber');
hire(g.ev, 'kevin');
std(g.ev, { sys: 'roadm', opt: 'fast' });
g.ev(COUNT + 'opsDay(S.day)');
assert.deepEqual([L(g.ev, x).sys, L(g.ev, x).eqDown], ['lite', undefined], 'Amsterdam is never cut off for a day');
assert.deepEqual(L(g.ev, x).ch, ['zr8', 'zr8'], 'it gets the fastest optics its line system takes');
assert.equal(g.ev('__tr'), 0, 'known without routing');
assert.deepEqual(errors, []);
assert.deepEqual(g.errors, []);
});
test('with two swaps a night, the second fiber is judged on the routing with the first one dark, not on the loads from before', t => {
// The ring again, Kevin on shift. Once Frankfurt–Amsterdam is dark, Amsterdam's traffic rides Amsterdam–Paris, which
// carried nothing before: its "nothing rides it" is asked again after the shift routes, and is no longer true.
const { ev, errors } = game(t);
const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'ams', 'par', ['zr4', 'zr4']), c = fiber(ev, 'par', 'fra', ['zr4', 'zr4']);
hire(ev, 'kevin');
std(ev, { sys: 'roadm' });
ev(`compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`);
assert.equal(ev(`R.load[${lit(b)}]||0`), 0, 'Amsterdam–Paris is idle today');
const served = ev('R.served');
ev('opsDay(S.day)');
assert.deepEqual([L(ev, a).sys, L(ev, b).sys, L(ev, c).sys], ['roadm', 'lite', 'lite'], 'Amsterdam keeps one way in');
ev('compute()');
assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through');
assert.deepEqual(errors, []);
});
test('two busy fibers side by side: one goes dark tonight, its twin carries it, and the twin goes the next night', t => {
// Amsterdam's broadband split over two Frankfurt–Amsterdam fibers, a few gigabits each: busy, though under the
// button's "quiet". Kevin has room for two swaps, but the twin waits rather than fail the test and wait a week.
const { ev, errors } = game(t);
const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']);
hire(ev, 'kevin');
std(ev, { sys: 'roadm' });
ev('compute()');
assert.ok(ev(`R.load[${lit(a)}]`) > 1 && ev(`R.load[${lit(b)}]`) > 1, 'both carry Amsterdam');
ev('opsDay(S.day)');
assert.deepEqual([[L(ev, a).sys, L(ev, b).sys].sort(), ev('OPTUP_NO.size')], [['lite', 'roadm'], 0], 'one tonight, and no fiber failed');
ev('S.day++;compute();opsDay(S.day)');
assert.deepEqual([L(ev, a).sys, L(ev, b).sys], ['roadm', 'roadm'], 'the twin the next night');
assert.deepEqual(errors, []);
});
test('a fiber that fails the test waits a week, for both orders, and gets the optics its line system takes meanwhile', t => {
// The ring back from Amsterdam is two 10G waves: too thin for Amsterdam's broadband.
const { ev, errors } = game(t);
const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']);
wave(ev, 'ams', 'par', 0); wave(ev, 'par', 'fra', 0);
ev('compute()');
assert.ok(ev(`R.load[${lit(a)}]`) > 10, 'more than the ring carries');
ev(COUNT);
hire(ev, 'annie');
std(ev, { sys: 'roadm', opt: 'fast' });
ev('S.ops.on.optup=true;opsDay(S.day)');
assert.equal(ev('__tr'), 1, 'tested once');
assert.deepEqual([L(ev, a).sys, L(ev, a).ch], ['lite', ['zr4', 'zr4']], 'no swap, and no optics for a line system it did not get');
assert.equal(ev(`OPTUP_NO.get(${lit(a)})`), ev('S.day+OPTUP_WAIT'));
for (let d = 1; d < 7; d++) ev('S.day++;compute();opsDay(S.day)');
assert.equal(ev('__tr'), 1, 'not tested again that week, by either order');
assert.deepEqual([L(ev, a).sys, L(ev, a).ch], ['lite', ['zr8', 'zr8']], 'the fastest optics the old line system takes');
assert.deepEqual(errors, []);
});
test('an express riding the fiber goes dark with it in the test: its traffic has to get around too', t => {
// Frankfurt–Brussels–Paris as an express over two bare ROADM fibers; Paris reaches its transit over it.
const { ev, errors } = game(t, "ACT.buildPop({city:'bru'});S.pops.bru.rgen=S.pops.fra.rgen;S.lvl=8;" +
"window.df=(a,b)=>{const id=uid();S.links.push({id,a,b,kind:'df',own:true,sys:'roadm',ch:[],km:kmBetween(a,b),sub:false,cable:null,mo:100,trench:id,cut:0,day:S.day,ready:S.day,spares:false,pairs:1});return id;};" +
"window.s1=df('fra','bru');window.s2=df('bru','par');compute();ACT.xpBuild({a:'fra',b:'par',via:s1+','+s2,o:'zr4'});window.x=S.links.find(l=>l.kind==='xp').id;compute()");
const [s1, s2, x] = ['s1', 's2', 'x'].map(k => ev(k));
assert.ok(ev('R.load[x]') > 1 && !ev('(R.load[s1]||0)+(R.load[s2]||0)'), 'the express carries Paris; the fibers carry nothing of their own');
ev(COUNT + "window.__xd=[];const _c=compute;compute=function(){if(S.links.find(l=>l.id===s1).eqDown>S.day||S.links.find(l=>l.id===s2).eqDown>S.day)__xd.push(xpDown(S.links.find(l=>l.id===x)));return _c.apply(this,arguments);}");
hire(ev, 'annie');
std(ev, { sys: 'cl' });
const sys = () => [L(ev, s1).sys, L(ev, s2).sys];
// No way around either fiber: known without routing.
assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')).sort(), ['bru|par', 'fra|bru']);
ev('opsDay(S.day)');
assert.deepEqual([sys(), ev('__tr')], [['roadm', 'roadm'], 0]);
// A wave beside the first fiber: it has a way around now, but Paris has none without the express.
wave(ev, 'fra', 'bru', 1);
ev('S.day++;compute();opsDay(S.day)');
assert.equal(ev('__tr'), 1, 'one routing without the fiber');
assert.deepEqual(JSON.parse(ev('JSON.stringify(__xd)')), [true], 'the express was dark in it');
assert.deepEqual(sys(), ['roadm', 'roadm'], 'Paris would be cut off: no swap');
// A wave to Paris carries it round: the swap goes ahead, with the express dark for the day.
wave(ev, 'fra', 'par', 3);
ev('OPTUP_NO.clear();S.day++;compute();opsDay(S.day)');
assert.deepEqual(sys().sort(), ['cl', 'roadm'], 'one of them, one a night');
assert.equal(ev('xpDown(S.links.find(l=>l.id===x))'), true);
ev('compute()');
assert.ok(ev('R.load[x]||0') === 0 && ev('R.served') > 0);
assert.deepEqual(errors, []);
});
test('the decom order never hands back a wave the build standard upgraded that same shift', t => {
const { ev, errors } = game(t);
// A 800G wave and two 100G waves between Frankfurt and Amsterdam, in three trenches.
const big = wave(ev, 'fra', 'ams', 3), w1 = wave(ev, 'fra', 'ams', 1), w2 = wave(ev, 'fra', 'ams', 1);
hire(ev, 'annie');
ev("S.ops.on.decom=true;S.ops.p.decom={keep:false}");
std(ev, { wv: 2 });
// The plan sees a pair that needs all three once the small ones are 400G; the routing after the shift's jobs, which
// decom reads, sees almost nothing on them.
ev(`compute();R.load[${lit(big)}]=700;R.load[${lit(w1)}]=150;R.load[${lit(w2)}]=150`);
assert.equal(ev('bstdQuote(true).n'), 2, 'both small waves go up');
ev('opsDay(S.day)');
const tiers = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='wave').map(l=>l.tier))"));
assert.deepEqual(tiers(), [3, 2, 2], 'both upgraded, both kept today');
assert.deepEqual(said(ev), [['std', 2]]);
// Tomorrow they are the decom order's to judge again.
ev('S.day++;compute();opsDay(S.day)');
assert.deepEqual(tiers(), [3]);
assert.deepEqual(said(ev), [['decom', 2]]);
assert.deepEqual(errors, []);
});
// In play the test is routed in the route worker. jsdom has no Worker: a second page plays it (rwServe() there), as in
// tests/day-steps.test.js. The day is the day dayTick() plays, and the page itself never routes.
test("in play, the standard's fiber test is routed by the route worker, and the day is the day dayTick() plays", t => {
// The ring of fibers, Amsterdam's and Paris's broadband on it.
const RING = "for(const [a,b] of [['fra','ams'],['ams','par'],['par','fra']]){const id=uid();S.links.push({id,a,b,kind:'df',own:false,sys:'lite',ch:['zr4','zr4'],km:Math.round(kmBetween(a,b)),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});}compute();" +
"ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap={};S.ops.on.std=true;closeModal();S.popStd=bstdPut({...bstd(),sys:'roadm'});__reseed(4242);";
const open = seed => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
const ref = open(777), page = open(777), wk = open(1);
for (const h of [ref, page]) { h.ev(BASE); h.ev(RING); }
page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
page.ev('window.__pc=0;const _c=compute;compute=function(){__pc++;return _c.apply(this,arguments);};');
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
let trials = 0;
const pump = () => { for (;;) {
if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; }
if (!page.ev('__q.length')) break;
if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) trials++;
wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); } };
ref.ev('dayTick()');
page.ev('rwDay()'); pump();
assert.equal(trials, 1, 'the fiber test went to the worker');
assert.equal(page.ev('__pc'), 0, 'no routing on the page');
assert.equal(page.ev("S.links.filter(l=>l.sys==='roadm').length"), 1, 'and it passed: the rest of the ring carries its traffic');
const STATE = 'JSON.stringify({S,served:R.served,load:R.load})';
assert.equal(page.ev(STATE), ref.ev(STATE), 'the same day as dayTick()');
assert.deepEqual([...ref.errors, ...page.errors, ...wk.errors], []);
});
// In play the shift rests between the standard's jobs (DAY_REST, rwRest()), and the player can tap meanwhile: every job
// is checked again against the game as it is then, not as the plan found it at the start of the shift.
test('the player acts while the shift rests: nothing past the standard, nothing paid twice, nothing claimed, and no snag for a POP gone', t => {
// Every POP on one router. std: the standard; act: what the player does at the first rest after a job of the shift.
const play = (std, act, setup = '') => {
const { ev, errors } = game(t, "for(const c of ['fra','ams','par','lon'])S.pops[c].routers=1;compute()");
hire(ev, 'annie');
ev(`S.popStd=${std};${setup};window.__later=[];RW.budget=0;RW.later=f=>__later.push(f)`);
ev('rwDay()');
let spent = null;
while (ev('__later.length')) {
if (spent === null && ev('S.ops.spent.std>0')) { spent = ev('S.ops.spent.std'); ev(act); }
ev('__later.shift()()');
}
assert.ok(spent > 0, 'the shift rested after a job');
return { ev, errors, spent };
};
const routers = ev => JSON.parse(ev('JSON.stringify(Object.fromEntries(Object.entries(S.pops).map(([c,p])=>[c,p.routers])))'));
// The button brings every POP up to the standard while the shift rests after its first job.
let { ev, errors, spent } = play('{rt:3}', 'ACT.bstdApply()');
assert.deepEqual(routers(ev), { fra: 3, ams: 3, par: 3, lon: 3 }, 'three routers each, as the standard says');
assert.equal(ev('S.ops.spent.std'), spent, 'the shift paid for nothing after the button');
assert.deepEqual(said(ev), [['std', 1]]);
assert.deepEqual(errors, []);
// The same with a model: the swaps the button did are not the shift's.
({ ev, errors, spent } = play("{g:RG.findIndex(r=>r.n==='Absolute Unit 1.6T'),rt:2}", 'ACT.bstdApply()', "for(const c in S.pops)S.pops[c].routers=2"));
assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(Object.values(S.pops).map(p=>RG[p.rgen].n))])')), ['Absolute Unit 1.6T']);
assert.equal(ev('S.ops.spent.std'), spent);
assert.deepEqual(said(ev), [['std', 1]], 'one swap, not four');
assert.deepEqual(errors, []);
// A PNI the player orders by hand meanwhile, smaller than the plan's: the shift does not order it again as an upgrade.
const net = "NETS.find(n=>n.pops.includes('fra')&&n.pops.includes('ams')&&pniMin(n.id)===0&&peerOk(n.id,'pni','ams').ok&&peerOk(n.id,'pni','fra').ok).id";
({ ev, errors, spent } = play('{rt:2,pni:2}', `pniPlace(pniQuote('ams',${net},0))`,
`S.rules.pnis='instant';window.__net=${net};S.pni.push({id:'P1',city:'fra',net:__net,tier:1,ready:S.day});compute();const _v=pniVal;pniVal=(id,c)=>id===__net&&c==='ams'?{..._v(id,c),worth:true,want:40,tier:1}:_v(id,c)`));
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(x=>x.city==='ams').map(x=>[x.tier,!!x.up]))")), [[0, false]], 'the player\'s own, as ordered');
assert.deepEqual(said(ev), [['std', 4]], 'the routers only');
assert.deepEqual(errors, []);
// Amsterdam decommissioned meanwhile: its jobs are left out, the order runs on, the other POPs get theirs.
({ ev, errors } = play('{rt:3}', "decommission(['ams'])"));
assert.equal(ev('S.ops.on.std'), true, 'the order is still on');
assert.deepEqual(said(ev), [['std', 6]], 'no snag');
assert.deepEqual(routers(ev), { fra: 3, par: 3, lon: 3 });
assert.deepEqual(errors, []);
});

View file

@ -12,7 +12,8 @@ const { lit } = require('../scripts/lib/js-literal');
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');S.rules.pnis='instant';" + const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');S.rules.pnis='instant';" +
"ACT.launchBB({city:'fra'});S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});compute()"; "ACT.launchBB({city:'fra'});S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});compute()";
const AU = "RG.findIndex(r=>r.n==='Absolute Unit 3.2T')"; const AU = "RG.findIndex(r=>r.n==='Absolute Unit 3.2T')";
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;S.ops.cap.std=0;S.ops.on.std=true;closeModal()"); // Kevin by default; a fiber test that counts swaps a night hires Annie (Kevin does two: tests/bstd-owner.test.js).
const hire = (ev, id = 'kevin') => ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap.std=0;S.ops.on.std=true;closeModal()`);
const shift = ev => ev('opsDay(S.day)'); const shift = ev => ev('opsDay(S.day)');
function game(t, extra = '') { function game(t, extra = '') {
const h = load(); const h = load();
@ -144,9 +145,9 @@ test('ports: LAG members up to the standard, split over both buildings; PNIs spr
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('fiber: the line system only on a quiet fiber or with a parallel link, one a shift; faster optics, old ones on the shelf; bigger waves', t => { test('fiber: the line system only on a quiet fiber or with a way around, one a shift; faster optics, old ones on the shelf; bigger waves', t => {
const { ev, errors } = game(t); const { ev, errors } = game(t);
hire(ev); hire(ev, 'annie');
const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')");
ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`);
const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'par', ['zr4']); const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'par', ['zr4']);
@ -189,7 +190,7 @@ test('fiber: the line system only on a quiet fiber or with a parallel link, one
test('quiet fibers take their line system one a shift and buy nothing in between: the intern spends what the quote said', t => { test('quiet fibers take their line system one a shift and buy nothing in between: the intern spends what the quote said', t => {
const { ev, errors } = game(t); const { ev, errors } = game(t);
hire(ev); hire(ev, 'annie');
const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')");
ev(`ACT.buildPop({city:'par'});ACT.buildPop({city:'lon'});for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); ev(`ACT.buildPop({city:'par'});ACT.buildPop({city:'lon'});for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`);
const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4'])); const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4']));

View file

@ -1,5 +1,6 @@
// The intern upgrades optical transport: line systems up a size (only where the traffic gets around the day-long swap and // The intern upgrades optical transport: line systems up a size (only where the traffic gets around the day-long swap and
// no customer rides the fiber), optics traded for bigger ones on full, hot fiber, or every fiber up to a chosen line system. // no customer rides the fiber), optics traded for bigger ones on full, hot fiber, or every fiber up to the build standard's
// line system.
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
@ -21,6 +22,8 @@ function game(t, extra) {
return h; return h;
} }
const order = (ev, p) => ev(`S.ops.on.optup=true;S.ops.p.optup=${JSON.stringify(p)}`); const order = (ev, p) => ev(`S.ops.on.optup=true;S.ops.p.optup=${JSON.stringify(p)}`);
// The line system every fiber should have: the build standard's.
const goal = (ev, sys) => ev(`S.popStd=bstdPut({...bstd(),sys:${JSON.stringify(sys)}})`);
// The fiber runs at 90% of what it carries. // The fiber runs at 90% of what it carries.
const heat = ev => ev("R.load.f=dfCap(S.links[0])*0.9"); const heat = ev => ev("R.load.f=dfCap(S.links[0])*0.9");
const fiber = ev => JSON.parse(ev("JSON.stringify({sys:S.links[0].sys,ch:S.links[0].ch.join(),down:S.links[0].eqDown>S.day})")); const fiber = ev => JSON.parse(ev("JSON.stringify({sys:S.links[0].sys,ch:S.links[0].ch.join(),down:S.links[0].eqDown>S.day})"));
@ -69,10 +72,11 @@ test('no way around, or a customer on the fiber: no swap; bigger optics instead,
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('a chosen line system: every fiber below it is moved up, two steps in one night if need be, one fiber a night', t => { test("the build standard's line system: every fiber below it is moved up, two steps in one night if need be, one fiber a night", t => {
const { ev, errors } = game(t, "S.links[0].ch=['zr4'];" + const { ev, errors } = game(t, "S.links[0].ch=['zr4'];" +
"for(const [i,a,b] of [[2,'fra','par'],[3,'par','ams']])S.links.push({id:'g'+i,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:'t'+i,ready:0,cut:0,mo:1,pairs:1});compute()"); "for(const [i,a,b] of [[2,'fra','par'],[3,'par','ams']])S.links.push({id:'g'+i,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:'t'+i,ready:0,cut:0,mo:1,pairs:1});compute()");
order(ev, { sys: 'cl', at: 90 }); order(ev, { at: 90 });
goal(ev, 'cl');
const want = ev("sysCost('roadm')+sysCost('cl')"); const want = ev("sysCost('roadm')+sysCost('cl')");
const sys = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='df').map(l=>l.sys))")); const sys = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='df').map(l=>l.sys))"));
const c0 = ev('S.cash'); const c0 = ev('S.cash');
@ -82,10 +86,12 @@ test('a chosen line system: every fiber below it is moved up, two steps in one n
for (let n = 0; n < 6 && sys().some(s => s !== 'cl'); n++) ev('S.day+=2;compute();opsDay(S.day)'); for (let n = 0; n < 6 && sys().some(s => s !== 'cl'); n++) ev('S.day+=2;compute();opsDay(S.day)');
assert.deepEqual(sys(), ['cl', 'cl', 'cl', 'cl'].slice(0, sys().length), 'the rest on the nights after'); assert.deepEqual(sys(), ['cl', 'cl', 'cl', 'cl'].slice(0, sys().length), 'the rest on the nights after');
// Nothing is ever moved down. // Nothing is ever moved down.
ev("S.ops.p.optup.sys='roadm';S.day+=2;compute();opsDay(S.day)"); goal(ev, 'roadm');
ev('S.day+=2;compute();opsDay(S.day)');
assert.ok(sys().every(s => s === 'cl')); assert.ok(sys().every(s => s === 'cl'));
// A fiber with no way around is tested once, then left alone for a week: no routing every night for nothing. // A fiber with no way around is tested once, then left alone for a week: no routing every night for nothing.
ev("S.links=S.links.filter(l=>l.id==='f');S.links[0].sys='lite';S.ops.p.optup.sys='cl';S.day+=2;compute()"); goal(ev, 'cl');
ev("S.links=S.links.filter(l=>l.id==='f');S.links[0].sys='lite';S.day+=2;compute()");
const runs = () => ev('window.__runs||0'); const runs = () => ev('window.__runs||0');
ev("window.__runs=0;const c0=compute;compute=function(){window.__runs++;return c0.apply(this,arguments);};opsDay(S.day)"); ev("window.__runs=0;const c0=compute;compute=function(){window.__runs++;return c0.apply(this,arguments);};opsDay(S.day)");
assert.equal(sys()[0], 'lite'); assert.equal(sys()[0], 'lite');
@ -98,7 +104,7 @@ test('a chosen line system: every fiber below it is moved up, two steps in one n
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('the budget holds, the setting is saved, and the sheet shows it as lists', t => { test("the budget holds, the settings are saved, and the sheet shows them as lists and the line system as the standard's", t => {
const { ev, dom, errors } = game(t); const { ev, dom, errors } = game(t);
order(ev, { at: 80 }); order(ev, { at: 80 });
ev('S.ops.cap.optup=10000'); ev('S.ops.cap.optup=10000');
@ -107,16 +113,22 @@ test('the budget holds, the setting is saved, and the sheet shows it as lists',
assert.equal(fiber(ev).sys, 'lite', 'a $10k budget does not buy a line system'); assert.equal(fiber(ev).sys, 'lite', 'a $10k budget does not buy a line system');
assert.ok(ev("S.ops.log[0].r.some(x=>x[0]==='broke')")); assert.ok(ev("S.ops.log[0].r.some(x=>x[0]==='broke')"));
const back = v => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.optup=${v};sanitize(s);return JSON.stringify(s.ops.p.optup);})()`); const back = v => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.optup=${v};sanitize(s);return JSON.stringify(s.ops.p.optup);})()`);
assert.deepEqual(JSON.parse(back("{sys:'cl',swap:false,at:70}")), { at: 70, sys: 'cl', swap: false }); assert.deepEqual(JSON.parse(back("{swap:false,at:70}")), { at: 70, swap: false });
assert.deepEqual(JSON.parse(back("{sys:'lite',swap:'yes'}")), {}); assert.deepEqual(JSON.parse(back("{at:55,swap:'yes'}")), {});
assert.deepEqual(JSON.parse(back('undefined')), {}, 'an old save without the order'); assert.deepEqual(JSON.parse(back('undefined')), {}, 'an old save without the order');
ev("const s=JSON.parse(JSON.stringify(S));delete s.ops.on.optup;sanitize(s);window.__off=s.ops.on.optup"); ev("const s=JSON.parse(JSON.stringify(S));delete s.ops.on.optup;sanitize(s);window.__off=s.ops.on.optup");
assert.equal(ev('__off'), false, 'off in an old save'); assert.equal(ev('__off'), false, 'off in an old save');
dom.window.innerWidth = 360; dom.window.innerWidth = 360;
ev("ACT.phoneTab({t:'noc'})"); ev("ACT.phoneTab({t:'noc'})");
dom.window.document.querySelector('#leftBody [data-act="opsOpen"]').click(); dom.window.document.querySelector('#leftBody [data-act="opsOpen"]').click();
const sel = [...dom.window.document.querySelectorAll('#modalCard select[data-chg="opsParam"]')].find(s => s.dataset.args === '{"k":"optup","p":"sys"}'); const doc = dom.window.document, card = () => [...doc.querySelectorAll('#modalCard .ops-o.on')].find(o => o.querySelector('.nm').textContent === 'Upgrade optical transport');
assert.deepEqual([...sel.options].map(o => o.textContent), ['Next one, when full', 'ROADMaster 9000', 'ROADMaster 9000 C+L']); assert.deepEqual([...card().querySelectorAll('select[data-chg="opsParam"]')].map(s => JSON.parse(s.dataset.args).p), ['at', 'swap'], 'no line system list of its own');
assert.match(dom.window.document.getElementById('modalCard').textContent, /Upgrade optical transport/); // The line system is the build standard's: what it says, and the way to the sheet.
assert.match(card().querySelector('.ops-from').textContent, /^Line systemFrom the build standard: Next one, when full/);
goal(ev, 'cl');
ev('ACT.opsOpen()');
assert.equal(card().querySelector('.ops-from b').textContent, 'From the build standard: ROADMaster 9000 C+L');
card().querySelector('.ops-from [data-act="bstdOpen"]').click();
assert.ok(ev('bstdShown()'), 'the button opens the build standard');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -57,7 +57,7 @@ test('Kevin swaps two line systems a night, the others one', t => {
"S.links=[['f1','fra','ams'],['f2','ams','par'],['f3','par','fra'],['f4','fra','ams']].map(([id,a,b])=>({id,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:id,ready:0,cut:0,mo:1,pairs:1}));compute()"; "S.links=[['f1','fra','ams'],['f2','ams','par'],['f3','par','fra'],['f4','fra','ams']].map(([id,a,b])=>({id,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:id,ready:0,cut:0,mo:1,pairs:1}));compute()";
for (const [id, want] of [['kevin', 2], ['annie', 1], ['tracy', 1]]) { for (const [id, want] of [['kevin', 2], ['annie', 1], ['tracy', 1]]) {
const { ev, errors } = game(t, id, fibers); const { ev, errors } = game(t, id, fibers);
ev("S.ops.on.optup=true;S.ops.p.optup={sys:'roadm'};opsDay(S.day)"); ev("S.ops.on.optup=true;S.popStd=bstdPut({...bstd(),sys:'roadm'});opsDay(S.day)");
assert.equal(ev("S.links.filter(l=>l.sys==='roadm').length"), want, id); assert.equal(ev("S.links.filter(l=>l.sys==='roadm').length"), want, id);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
} }

View file

@ -1,4 +1,5 @@
// The intern standardizes routers on a chosen model within the budget, and every setting in the Ops sheet is a list. // The intern standardizes routers on the build standard's model within the budget; the Ops sheet says where the model
// comes from and leads to the sheet that sets it, and every other setting there is a list.
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
@ -17,12 +18,15 @@ function game(t) {
return h; return h;
} }
const gens = ev => JSON.parse(ev("JSON.stringify(['fra','ams','par'].map(c=>S.pops[c].rgen))")); const gens = ev => JSON.parse(ev("JSON.stringify(['fra','ams','par'].map(c=>S.pops[c].rgen))"));
// The build standard's router model (the standard's other targets stay as they are).
const model = (ev, g) => ev(`S.popStd=bstdPut({...bstd(),g:${g}})`);
test('a chosen model: every POP on a smaller one is swapped to it, at the price of the swap, never as an outage', t => { test("the build standard's model: every POP on a smaller one is swapped to it, at the price of the swap, never as an outage", t => {
const { ev, errors } = game(t); const { ev, errors } = game(t);
const m = ev(MODEL); const m = ev(MODEL);
assert.ok(m > 0 && ev(`rgOpen(${m})`), 'the model is unlocked at level 3'); assert.ok(m > 0 && ev(`rgOpen(${m})`), 'the model is unlocked at level 3');
ev(`S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto',model:${m}};S.ops.cap.routers=0;compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0`); model(ev, m);
ev("S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto'};S.ops.cap.routers=0;compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0");
const want = ev(`swapCost('ams',${m})+swapCost('par',${m})`), c0 = ev('S.cash'); const want = ev(`swapCost('ams',${m})+swapCost('par',${m})`), c0 = ev('S.cash');
ev('opsDay(S.day)'); ev('opsDay(S.day)');
assert.deepEqual(gens(ev), [1, m, m], 'Amsterdam (a second router) and Paris (no traffic yet) are swapped; Frankfurt has one busy router, so no'); assert.deepEqual(gens(ev), [1, m, m], 'Amsterdam (a second router) and Paris (no traffic yet) are swapped; Frankfurt has one busy router, so no');
@ -32,18 +36,19 @@ test('a chosen model: every POP on a smaller one is swapped to it, at the price
// Frankfurt gets its turn once it has a second router. // Frankfurt gets its turn once it has a second router.
ev('S.pops.fra.routers=2;S.day++;compute();opsDay(S.day)'); ev('S.pops.fra.routers=2;S.day++;compute();opsDay(S.day)');
assert.deepEqual(gens(ev), [m, m, m]); assert.deepEqual(gens(ev), [m, m, m]);
// Busy POPs on the chosen model get more routers, never a swap to another one. // Busy POPs on the standard's model get more routers, never a swap to another one.
ev("S.ops.p.routers.how='swap';S.day++;compute();R.nodeLoad.ams=R.nodeCap.ams*0.95;opsDay(S.day)"); ev("S.ops.p.routers.how='swap';S.day++;compute();R.nodeLoad.ams=R.nodeCap.ams*0.95;opsDay(S.day)");
assert.equal(ev('S.pops.ams.rgen'), m, 'no swap away from the chosen model'); assert.equal(ev('S.pops.ams.rgen'), m, 'no swap away from the standard\'s model');
ev("S.ops.p.routers.how='add';S.day++;compute();R.nodeLoad.ams=R.nodeCap.ams*0.95;opsDay(S.day)"); ev("S.ops.p.routers.how='add';S.day++;compute();R.nodeLoad.ams=R.nodeCap.ams*0.95;opsDay(S.day)");
assert.equal(ev('S.pops.ams.routers'), 3, 'a busy POP gets a third router'); assert.equal(ev('S.pops.ams.routers'), 3, 'a busy POP gets a third router');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('the budget decides how far it gets, the busiest POP first; a smaller model is never a downgrade', t => { test('the budget decides how far it gets, the busiest POP first; a smaller model is never a downgrade; a locked one means the best unlocked below it', t => {
const { ev, errors } = game(t); const { ev, errors } = game(t);
const m = ev(MODEL); const m = ev(MODEL);
ev(`S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto',model:${m}};compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;R.nodeLoad.par=R.nodeCap.par*0.5`); model(ev, m);
ev("S.ops.on.routers=true;S.ops.p.routers={at:90,how:'auto'};compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;R.nodeLoad.par=R.nodeCap.par*0.5");
// A budget for one swap: Paris is the busier, so it goes first and Amsterdam waits for next month. // A budget for one swap: Paris is the busier, so it goes first and Amsterdam waits for next month.
const one = ev(`swapCost('par',${m})`); const one = ev(`swapCost('par',${m})`);
ev(`S.ops.cap.routers=OPS_CAPS.filter(c=>c>=${one}).sort((a,b)=>a-b)[0]`); ev(`S.ops.cap.routers=OPS_CAPS.filter(c=>c>=${one}).sort((a,b)=>a-b)[0]`);
@ -54,24 +59,70 @@ test('the budget decides how far it gets, the busiest POP first; a smaller model
// Next month, a new budget: Amsterdam. // Next month, a new budget: Amsterdam.
ev('{const m0=monthIdx(S.day);while(monthIdx(S.day)===m0)S.day++;}compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)'); ev('{const m0=monthIdx(S.day);while(monthIdx(S.day)===m0)S.day++;}compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)');
assert.deepEqual(gens(ev), [1, m, m]); assert.deepEqual(gens(ev), [1, m, m]);
// Choosing a smaller model swaps nothing back. // A smaller model in the standard swaps nothing back.
ev("S.ops.cap.routers=0;S.ops.p.routers.model=RG.findIndex(r=>r.n==='Edge Lord 400');S.day++;compute();opsDay(S.day)"); ev("S.ops.cap.routers=0;S.day++;compute()");
model(ev, "RG.findIndex(r=>r.n==='Edge Lord 400')");
ev('opsDay(S.day)');
assert.deepEqual(gens(ev), [1, m, m]); assert.deepEqual(gens(ev), [1, m, m]);
// A model above the level: the best main-line model unlocked below it, as the standard means for a new POP.
const big = ev("RG.findIndex(r=>r.n==='Arrrhipster 7800R5')");
assert.equal(ev(`rgOpen(${big})`), false);
model(ev, big);
ev('S.pops.fra.routers=2');
const best = ev(`bstdModel(${big},'fra')`);
ev('S.day++;compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)');
assert.equal(ev('S.pops.fra.rgen'), best);
assert.ok(ev('S.pops.fra.rgen') > 1 && ev(`RG[S.pops.fra.rgen].cap<RG[${big}].cap`), 'up, but no further than what is unlocked');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('the setting is saved; an unknown model falls back to the next generation', t => { test('saves: an old model or line system setting moves into the standard when it names none; its own wins; neither stays neither', t => {
const { ev, errors } = game(t); const { ev, errors } = game(t);
const back = v => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.routers=${v};sanitize(s);return JSON.stringify(s.ops.p.routers);})()`); const m = ev(MODEL), el = ev("RG.findIndex(r=>r.n==='Edge Lord 400')");
assert.deepEqual(JSON.parse(back(`{model:${ev(MODEL)}}`)), { model: ev(MODEL) }); // An old save: the routers order's model and the optical order's line system, with or without a standard. x: what
assert.deepEqual(JSON.parse(back('{model:999}')), {}); // else the save says (by default both orders ran, with Kevin hired).
assert.deepEqual(JSON.parse(back("{model:'7'}")), {}); const ON = 's.ops.on.routers=true;s.ops.on.optup=true';
assert.deepEqual(JSON.parse(back('undefined')), {}, 'an old save without it'); const back = (p, std, x = ON) => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p=${p};s.popStd=${std};${x};sanitize(s);return JSON.stringify({p:s.ops.p,std:s.popStd});})()`));
assert.equal(ev("opsP('routers','model')"), 'next'); let r = back(`{routers:{model:${m},at:70},optup:{sys:'cl',swap:false}}`, 'null');
assert.deepEqual(r.std, { g: m, rt: 1, sys: 'cl' }, 'no standard: both move into a new one');
assert.deepEqual(r.p.routers, { at: 70 }, 'the old setting is gone, the others stay');
assert.deepEqual(r.p.optup, { swap: false });
// Only what an order that ran used: a paused order's setting, or one with nobody hired, did nothing, and goes.
r = back(`{routers:{model:${m},at:70},optup:{sys:'cl'}}`, 'null', 's.ops.on.routers=false');
assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, { at: 70 }, {}], 'both paused: no standard');
r = back(`{routers:{model:${m}},optup:{sys:'cl'}}`, 'null', 's.ops.on.routers=true');
assert.deepEqual(r.std, { g: m, rt: 1 }, 'the routers order ran, the optical order was paused');
r = back(`{routers:{model:${m}},optup:{sys:'cl'}}`, '{rt:2}', ON + ';s.ops.intern=null');
assert.deepEqual([r.std, r.p.routers, r.p.optup], [{ rt: 2 }, {}, {}], 'nobody hired: the standard stays as it was');
r = back(`{routers:{model:${m}},optup:{sys:'roadm'}}`, `{g:${el},rt:2,sys:'cl',gen:true}`);
assert.deepEqual(r.std, { g: el, rt: 2, gen: true, sys: 'cl' }, 'a standard that names its own keeps them');
assert.deepEqual([r.p.routers, r.p.optup], [{}, {}]);
r = back(`{routers:{model:${m}},optup:{sys:'roadm'}}`, '{rt:3,lag:2}');
assert.deepEqual(r.std, { g: m, rt: 3, lag: 2, sys: 'roadm' }, 'one without them takes them and keeps the rest');
r = back("{routers:{model:'next'},optup:{sys:'next'}}", 'null');
assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, {}, {}], "'next' was no choice: nothing moves");
r = back("{routers:{model:999},optup:{sys:'warp'}}", 'null');
assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, {}, {}], 'junk moves nowhere');
r = back("{routers:{model:'7'}}", `{g:${el}}`);
assert.deepEqual(r.std, { g: el, rt: 1 });
r = back('undefined', 'undefined');
assert.deepEqual([r.std, r.p.routers, r.p.optup], [null, {}, {}], 'an old save with neither');
// The order reads the standard: none set, it is the next generation when busy.
assert.equal(ev('bstd().g'), 'keep');
// A loaded save whose model sat in a paused order, the intern since fired: new POPs cost what they did.
const lon = ev("popCost('lon')");
ev(`S.ops.p.routers={model:${m}};S.ops.on.routers=false;S.ops.intern=null;S=migrate(JSON.parse(JSON.stringify(S)))`);
assert.deepEqual([ev('S.popStd'), ev("newPopCost('lon')"), ev("JSON.stringify(S.ops.p.routers)")], [null, lon, '{}']);
ev("ACT.buildPop({city:'lon'})");
assert.equal(ev('S.pops.lon.rgen||0'), 0, 'and get the basic router');
// A loaded save that had a model in a running order plays with it: the shift swaps to it.
ev(`ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();S.ops.p.routers={model:${m}};S.ops.on.routers=true;S=migrate(JSON.parse(JSON.stringify(S)));compute();for(const c in R.nodeLoad)R.nodeLoad[c]=0;opsDay(S.day)`);
assert.equal(ev('S.popStd.g'), m);
assert.equal(ev('S.pops.ams.rgen'), m);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('every setting in the Ops sheet is a list to pick from, on a phone too', t => { test('the Ops sheet: the model comes from the build standard, one line and a way there; every other setting is a list, on a phone too', t => {
const { ev, dom, errors } = game(t); const { ev, dom, errors } = game(t);
dom.window.innerWidth = 360; dom.window.innerWidth = 360;
const doc = dom.window.document; const doc = dom.window.document;
@ -88,24 +139,29 @@ test('every setting in the Ops sheet is a list to pick from, on a phone too', t
// Every setting of every order, every budget and the floor. // Every setting of every order, every budget and the floor.
const n = ev('OPS.reduce((a,d)=>a+Object.keys(d.p).length+(d.cap?1:0),0)+1'); const n = ev('OPS.reduce((a,d)=>a+Object.keys(d.p).length+(d.cap?1:0),0)+1');
assert.equal(doc.querySelectorAll('#modalCard .ops-p select').length, n); assert.equal(doc.querySelectorAll('#modalCard .ops-p select').length, n);
// The model list: the next generation, then the models you can buy, smallest first. assert.equal(sel('opsParam', { k: 'routers', p: 'model' }), undefined, 'no model list of its own');
const model = sel('opsParam', { k: 'routers', p: 'model' }); // The routers order: where its model comes from, and the button to the sheet that sets it.
assert.ok(model, 'the routers order has a model list'); const routers = [...doc.querySelectorAll('#modalCard .ops-o.on')].find(o => o.querySelector('.nm').textContent === 'Keep routers ahead');
assert.equal(model.options[0].textContent, 'Next generation, when busy'); assert.ok(routers.querySelector('.ops-from'), 'a line in the routers order');
assert.ok([...model.options].some(o => o.textContent === 'Arrrhipster 7800R')); assert.match(routers.querySelector('.ops-from').textContent, /^ModelFrom the build standard: Next generation, when busy/);
assert.ok(![...model.options].some(o => o.textContent === 'Absolute Unit 3.2T'), 'only models unlocked at your level'); routers.querySelector('.ops-from [data-act="bstdOpen"]').click();
pick(model, 'Arrrhipster 7800R'); assert.ok(ev('bstdShown()'), 'the button opens the build standard');
assert.equal(ev("opsP('routers','model')"), ev(MODEL)); // Set there, it is what the line says.
assert.equal(doc.activeElement && doc.activeElement.dataset.args, JSON.stringify({ k: 'routers', p: 'model' }), 'the keyboard stays on the list'); pick([...doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]')].find(s => JSON.parse(s.dataset.args).k === 'g'), 'Arrrhipster 7800R');
assert.equal(ev('bstd().g'), ev(MODEL));
ev('ACT.opsOpen()');
const r2 = [...doc.querySelectorAll('#modalCard .ops-o.on')].find(o => o.querySelector('.nm').textContent === 'Keep routers ahead');
assert.match(r2.querySelector('.ops-from b').textContent, /^From the build standard: Arrrhipster 7800R$/);
// The rest are still lists.
pick(sel('opsParam', { k: 'transit', p: 'prov' }), 'Already connected'); pick(sel('opsParam', { k: 'transit', p: 'prov' }), 'Already connected');
assert.equal(ev("opsP('transit','prov')"), 'have'); assert.equal(ev("opsP('transit','prov')"), 'have');
pick(sel('opsCap', { k: 'routers' }), 'no limit'); pick(sel('opsCap', { k: 'routers' }), 'no limit');
assert.equal(ev("opsCap('routers')"), 0); assert.equal(ev("opsCap('routers')"), 0);
pick(sel('opsFloor', {}), ev('fmt$(1e6)')); pick(sel('opsFloor', {}), ev('fmt$(1e6)'));
assert.equal(ev('S.ops.floor'), 1e6); assert.equal(ev('S.ops.floor'), 1e6);
// A value from nowhere changes nothing; the MCP tools still step without a value. // A value from nowhere changes nothing; the retired setting is nothing either; the MCP tools still step without a value.
ev("ACT.opsParam({k:'routers',p:'model',v:'99'});ACT.opsCap({k:'routers',v:'-1'});ACT.opsFloor({v:'x'})"); ev("ACT.opsParam({k:'routers',p:'model',v:'1'});ACT.opsCap({k:'routers',v:'-1'});ACT.opsFloor({v:'x'})");
assert.deepEqual([ev("opsP('routers','model')"), ev("opsCap('routers')"), ev('S.ops.floor')], [ev(MODEL), 0, 1e6]); assert.deepEqual([ev('bstd().g'), ev("opsCap('routers')"), ev('S.ops.floor'), ev("JSON.stringify(S.ops.p.routers||{})")], [ev(MODEL), 0, 1e6, '{}']);
ev("ACT.opsParam({k:'routers',p:'how'})"); ev("ACT.opsParam({k:'routers',p:'how'})");
assert.equal(ev("opsP('routers','how')"), 'add'); assert.equal(ev("opsP('routers','how')"), 'add');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -343,6 +343,33 @@ test('a list in a sheet sends its own arguments with the value picked: the build
assert.deepEqual(s.errors(), []); assert.deepEqual(s.errors(), []);
}); });
test('the router model and the line system are set in the build standard only: the orders\' old settings point there', () => {
const { s, T, ev } = sandbox({ pops: [] });
act(T, 'opsHire', { id: 'annie' });
ev('closeModal()');
for (const k of ['routers', 'optup']) act(T, 'opsToggle', { k });
ev('closeModal()');
assert.throws(() => act(T, 'opsParam', { k: 'routers', p: 'model', v: '1' }), /routers order takes its router model from the build standard: set it with bstdSet \(k "g"\)/);
assert.throws(() => act(T, 'opsParam', { k: 'optup', p: 'sys' }), /optup order takes its line system from the build standard: set it with bstdSet \(k "sys"\)/);
assert.equal(ev("JSON.stringify([S.ops.p.routers||{},S.ops.p.optup||{},S.popStd])"), '[{},{},null]', 'nothing changed');
act(T, 'opsParam', { k: 'routers', p: 'how' });
assert.equal(ev("opsP('routers','how')"), 'add', 'its other settings still step');
ev('closeModal()');
// The catalog of orders has no such settings; the docs say where they went.
const O = T('catalog', { name: 'OPSK' });
const ps = JSON.stringify(O);
assert.doesNotMatch(ps, /"model"|"sys"/);
assert.match(T('schema', { section: 'commands' }).opsParam.doc, /bstdSet k "g" and k "sys"/);
// Set there, both orders use it; the Ops sheet says so, with the way to the sheet.
act(T, 'bstdSet', { k: 'sys', v: '2' });
assert.equal(ev('bstd().sys'), 'cl');
act(T, 'opsOpen');
const sc = T('screen');
assert.match(sc.text, /From the build standard: ROADMaster 9000 C\+L/);
assert.ok(sc.buttons.some((b) => b.act === 'bstdOpen'), 'a button to the build standard');
assert.deepEqual(s.errors(), []);
});
test('new_game takes your own ASN and the sandbox chaos dial', () => { test('new_game takes your own ASN and the sandbox chaos dial', () => {
const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x); const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x);
assert.equal(T('new_game', { city: 'ams', asn: 213337, seed: 2 }).asn, 213337); assert.equal(T('new_game', { city: 'ams', asn: 213337, seed: 2 }).asn, 213337);