From 3410efce24af0d0fd2a44f465f1b652986750fcc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 16 Jul 2026 18:51:39 +0000 Subject: [PATCH 1/6] Lint pass: SMOKE_CHROMIUM override + stale comment fix Full-codebase lint sweep. Two findings fixed: - test/smoke.js accepts a SMOKE_CHROMIUM env var to point the launch at a pre-installed Chromium binary, for sandboxes where Playwright's browser download is unavailable. Default behavior (and CI) unchanged. - js/app-props.js queue-metrics comment still described the old em-dash placeholder; the code shows "n/a". Everything else came back clean: syntax on all JS files, no curly-quote delimiters, em dashes only in code comments (user-facing copy clean), no console.log/debugger/TODO leftovers, no trailing whitespace or tabs, CSS uses tokens outside :root, index.html script order intact (mixins after app.js), model/engine still DOM-free. 197/197 unit tests and the browser smoke test pass. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01BTK8CoB2M6ofpYRXpQEVVL --- js/app-props.js | 2 +- test/smoke.js | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/js/app-props.js b/js/app-props.js index 584817f..62da0b6 100644 --- a/js/app-props.js +++ b/js/app-props.js @@ -1018,7 +1018,7 @@ class AppProps { } // Live queue metrics (throughput, waiting time, peak line). Refreshed each - // step from the queue's runtime fields; "—" until the first unit is served. + // step from the queue's runtime fields; "n/a" until the first unit is served. _fillQueueMetrics(container, node) { const inService = (node._procs || []).length; const waiting = (node._fifo || []).reduce((s, it) => s + (it.amount || 0), 0); diff --git a/test/smoke.js b/test/smoke.js index d973861..8a982ba 100644 --- a/test/smoke.js +++ b/test/smoke.js @@ -4,13 +4,17 @@ // // Requires the app to be served (default http://localhost:8080) and Playwright. // Run: NODE_PATH=$(npm root -g) node test/smoke.js +// SMOKE_CHROMIUM points the launch at a pre-installed Chromium binary for +// sandboxes where Playwright's own browser download is unavailable. 'use strict'; const { chromium } = require('playwright'); const URL = process.env.SMOKE_URL || 'http://localhost:8080/'; (async () => { - const browser = await chromium.launch(); + const browser = await chromium.launch( + process.env.SMOKE_CHROMIUM ? { executablePath: process.env.SMOKE_CHROMIUM } : {} + ); const page = await browser.newPage(); // The display-font feature loads stylesheets from Google Fonts; stub the // request so the smoke run works offline and stays free of network errors. From ca6fef3179777114896a79deee41875542e74aca Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 16 Jul 2026 20:10:24 +0000 Subject: [PATCH 2/6] Economy as code: .econ text format, CLI assertions, JS-module codegen Three DOM-free additions that make an economy a first-class code artifact, documented in docs/ECONOMY_AS_CODE.md: - js/dsl.js: the .econ text format. dslSerialize/dslParse round-trip the diagram JSON losslessly (serialize-parse-serialize is a byte-identical fixpoint; normalizeEconJSON defines semantic equality up to id renaming). Sugar for the common cases, generic key=value attrs diffed against constructor defaults for everything else, so new model fields serialize automatically. File menu: Save as text (.econ); Open file now reads both formats. - js/assertions.js: design tests over a run. Quantifiers always / never / eventually / at end / at step N over the existing formula language, with node labels (sanitized), diagram variables and step in scope. CLI flags --assert, --assert-file, --pass-rate; exit code 2 on failure. Monte Carlo trials are checked individually via new perStep/onTrialEnd hooks in runMonteCarlo. - js/codegen.js: buildEconomyModule bundles model + engine + diagram into a dependency-free UMD file with a createEconomy() API (step/run/get/set/ fire/values/onStep, seed + param overrides). File menu: Export as JS module; CLI: --emit out.js. CLI also converts formats with --to-dsl / --to-json and accepts .econ input everywhere. Docs: README economy-as-code sections, CLAUDE.md architecture + commands, three KB articles. Tests: 15 new unit tests (round-trip kitchen sink, fixpoint, sugar, assertions semantics, generated-module runs under Node, CLI end-to-end including exit codes) and a smoke check for the in-page round trip, codegen fetch path, menu items and KB category. 212/212 unit tests and the browser smoke test pass. Also relicense the project from MIT to AGPL-3.0: canonical license text in LICENSE, SPDX id in package.json, License section in README. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01BTK8CoB2M6ofpYRXpQEVVL --- CLAUDE.md | 17 +- LICENSE | 682 +++++++++++++++++++++++++++++++- README.md | 51 ++- cli.js | 178 ++++++++- docs/ECONOMY_AS_CODE.md | 214 ++++++++++ index.html | 5 + js/app-export.js | 37 ++ js/app.js | 8 +- js/assertions.js | 130 ++++++ js/codegen.js | 120 ++++++ js/dsl.js | 846 ++++++++++++++++++++++++++++++++++++++++ js/engine.js | 12 +- js/kb.js | 47 +++ package.json | 1 + test/run.js | 356 ++++++++++++++++- test/smoke.js | 33 ++ 16 files changed, 2690 insertions(+), 47 deletions(-) create mode 100644 docs/ECONOMY_AS_CODE.md create mode 100644 js/assertions.js create mode 100644 js/codegen.js create mode 100644 js/dsl.js diff --git a/CLAUDE.md b/CLAUDE.md index 0500a96..e16165a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,9 +27,15 @@ node test/run.js # (alias: npm test) NODE_PATH=$(npm root -g) node test/smoke.js # (alias: npm run smoke) # SMOKE_URL overrides the default http://localhost:8080/ -# Headless CLI — simulate a saved diagram JSON from the terminal. +# Headless CLI — simulate a saved diagram (JSON or .econ text) from the terminal. node cli.js diagram.json --steps 500 > trace.csv node cli.js diagram.json --runs 1000 --steps 200 --seed 42 --param rate=3 + +# Economy-as-code (docs/ECONOMY_AS_CODE.md): assertions, format conversion, +# standalone-module codegen. Assertions exit 2 on failure (CI-friendly). +node cli.js economy.econ --assert "always gold < 500" --assert "at end: score >= 10" +node cli.js diagram.json --to-dsl > economy.econ # and .econ --to-json back +node cli.js economy.econ --emit economy.module.js # dependency-free JS module ``` **Running a single unit test:** `test/run.js` has no filter/grep flag — every @@ -60,6 +66,15 @@ it lets `test/run.js` load them into a bare `new Function` sandbox, lets `cli.js run them under Node, and lets Monte Carlo clone a `Diagram` + `SimEngine` per trial. Do not reach for `document`/`window` in these two files. +The economy-as-code layer lives under the same contract: `js/dsl.js` (the `.econ` +text format: `dslSerialize`/`dslParse`/`normalizeEconJSON`), `js/assertions.js` +(`parseAssertion`/`AssertionChecker`/`assertionScope`), and `js/codegen.js` +(`buildEconomyModule`) are DOM-free, load after `model.js`/`engine.js` in +`index.html`, `cli.js`, and `test/run.js`, and are documented in +`docs/ECONOMY_AS_CODE.md`. When you add a serialized field to the model, the +DSL's generic key=value attrs pick it up automatically, but extend the +`kitchenSink()` fixture in `test/run.js` so the round-trip test covers it. + Two engine invariants to preserve when editing the tick: - **Conditions are synchronous.** Activator and connection-condition checks read a start-of-step snapshot (`_tickSnap`, via `_condValueOf`), so a step's outcome does diff --git a/LICENSE b/LICENSE index 6ee69e5..be3f7b2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,661 @@ -MIT License - -Copyright (c) 2026 ZNT - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 57fbcca..51b33d7 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,17 @@ top bar for run/zoom/file controls. - **JSON** save/load, and **SVG / PNG** export of the diagram. - **Shareable URL** — the whole diagram is base64‑encoded in the URL hash (`#d=…`); opening it restores the diagram. `?embed` (or `#embed`) hides the editing chrome for a clean, embeddable view. +### Economy as code +- **`.econ` text format** — save/open the diagram as readable, diff‑friendly text + that lives happily in git (one line per node/connection; full round‑trip with + the canvas). See **[docs/ECONOMY_AS_CODE.md](docs/ECONOMY_AS_CODE.md)**. +- **Assertions** — CLI checks like `always gold < 500` or + `eventually score >= 100` that run per step (and across Monte Carlo trials), + exit non‑zero on failure, and turn balance regressions into CI failures. +- **Export as JS module** — compile the diagram + engine into one + dependency‑free `.js` file with a `createEconomy()` API (`step/run/get/set/ + fire/onStep`), so the economy you designed is the economy your game ships. + For the **why** and **how** behind the model — the tick order, the fair‑allocation algorithm, the one‑step variable lag, and more — see **[docs/CONCEPTS.md](docs/CONCEPTS.md)**. @@ -168,7 +179,36 @@ node cli.js my-diagram.json --runs 500 --csv --param mine_rate=3 > samples.csv `--param name=value` (repeatable) overrides diagram parameters without editing the file; `--seed` makes any run or batch bit‑for‑bit reproducible. Save a diagram with **File → Save as JSON** (or take one from the library) to feed it -to the CLI. +to the CLI. Files ending in `.econ` are parsed as the text format automatically. + +### Economy‑as‑code workflows + +```bash +# design tests: fail CI when a balance change breaks the economy (exit code 2) +node cli.js economy.econ --steps 300 \ + --assert "always gold < 500" \ + --assert "eventually tutorial_done >= 1" \ + --assert "at step 60: churn <= 3" + +# the same assertions across 1000 Monte Carlo trials; tolerate 5% unlucky runs +node cli.js economy.econ --runs 1000 --seed 42 --pass-rate 95 \ + --assert "at end: gold >= 100" + +# assertions can live in a file (one per line, // comments) +node cli.js economy.econ --assert-file economy.checks + +# convert between formats (text ↔ JSON) +node cli.js economy.json --to-dsl > economy.econ +node cli.js economy.econ --to-json > economy.json + +# emit a standalone, dependency-free JS module of the economy +node cli.js economy.econ --emit economy.module.js +node -e "const E=require('./economy.module.js'); + console.log(E.createEconomy({seed:42}).run(200).values())" +``` + +The `.econ` grammar, assertion language, and generated‑module API are documented +in **[docs/ECONOMY_AS_CODE.md](docs/ECONOMY_AS_CODE.md)**. --- @@ -312,3 +352,12 @@ Held until after the in‑progress UI/UX overhaul, so they don't immediately go The simulation model, file architecture, and APIs documented here and in `docs/CONCEPTS.md` are independent of the visual design and should remain accurate across the redesign. + +--- + +## License + +This project is licensed under the **GNU Affero General Public License v3.0** +(AGPL‑3.0). See [LICENSE](LICENSE) for the full text. In short: you are free to +use, study, modify, and share it; if you run a modified version as a network +service, you must offer its source to your users under the same license. diff --git a/cli.js b/cli.js index f9951e9..9a43f2e 100644 --- a/cli.js +++ b/cli.js @@ -1,7 +1,7 @@ #!/usr/bin/env node -// Headless CLI runner — simulate a diagram JSON without a browser. +// Headless CLI runner — simulate a diagram without a browser. // -// node cli.js [options] +// node cli.js [options] // // Options: // --steps N steps to simulate (default 200) @@ -12,10 +12,30 @@ // --csv with --runs>1: print raw per-run final values as CSV // (one row per run) instead of the stats table // -// Single run prints CSV to stdout: step,,,… one row per step. +// Economy-as-code: +// --assert "A" check an assertion over the run (repeatable), e.g. +// "always gold < 500", "eventually score >= 100", +// "at step 25: queue <= 3", "widgets > 50" (= at end). +// With --runs>1 every trial is checked. Exit code 2 when +// assertions fail. +// --assert-file F read assertions from a file (one per line, // comments) +// --pass-rate P with --runs>1: minimum % of trials where every +// assertion holds (default 100) +// --to-dsl print the diagram as .econ text and exit +// --to-json print the diagram as JSON and exit (parses .econ input) +// --emit out.js write a standalone dependency-free JS module of this +// economy (createEconomy API) and exit +// +// Input files ending in .econ (or that fail JSON.parse) are parsed as the +// .econ text format. Single run prints CSV to stdout: step,,… per step. +// Exit codes: 0 ok, 1 usage or file error, 2 assertion failure. +// // Examples: // node cli.js examples/economy.json --steps 500 > trace.csv -// node cli.js economy.json --runs 1000 --seed 42 --param mine_rate=3 +// node cli.js economy.econ --runs 1000 --seed 42 --param mine_rate=3 +// node cli.js economy.json --assert "always gold < 500" --assert "at end: score >= 10" +// node cli.js economy.json --to-dsl > economy.econ +// node cli.js economy.econ --emit economy.module.js 'use strict'; const fs = require('fs'); @@ -24,9 +44,9 @@ const path = require('path'); // Exit quietly when the consumer closes the pipe early (e.g. `| head`). process.stdout.on('error', e => { if (e.code === 'EPIPE') process.exit(0); throw e; }); -// Same loading trick as test/run.js: model.js and engine.js are plain browser -// scripts, evaluated into one function scope. math.js is optional (formulas -// fall back to the legacy evaluator without it). +// Same loading trick as test/run.js: the js/ files are plain browser scripts, +// evaluated into one function scope. math.js is optional (formulas fall back +// to the legacy evaluator without it). try { global.math = require('mathjs'); } catch { /* optional */ } function loadEngine() { @@ -34,7 +54,11 @@ function loadEngine() { const src = fs.readFileSync(path.join(base, 'model.js'), 'utf8') + '\n' + fs.readFileSync(path.join(base, 'engine.js'), 'utf8') + '\n' + - 'return { NodeType, Diagram, SimEngine, SimRandom };'; + fs.readFileSync(path.join(base, 'dsl.js'), 'utf8') + '\n' + + fs.readFileSync(path.join(base, 'assertions.js'), 'utf8') + '\n' + + fs.readFileSync(path.join(base, 'codegen.js'), 'utf8') + '\n' + + 'return { NodeType, Diagram, SimEngine, SimRandom, dslSerialize, dslParse,' + + ' parseAssertion, AssertionChecker, buildEconomyModule };'; // eslint-disable-next-line no-new-func return new Function(src)(); } @@ -45,13 +69,31 @@ function fail(msg) { } function parseArgs(argv) { - const opts = { steps: 200, runs: 1, seed: null, params: {}, csv: false, file: null }; + const opts = { + steps: 200, runs: 1, seed: null, params: {}, csv: false, file: null, + asserts: [], passRate: 100, emit: null, toDsl: false, toJson: false, + }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === '--steps') opts.steps = parseInt(argv[++i], 10); else if (a === '--runs') opts.runs = parseInt(argv[++i], 10); else if (a === '--seed') opts.seed = argv[++i]; else if (a === '--csv') opts.csv = true; + else if (a === '--assert') opts.asserts.push(argv[++i]); + else if (a === '--assert-file') { + const f = argv[++i]; + let text; + try { text = fs.readFileSync(f, 'utf8'); } + catch (e) { fail(`Cannot read ${f}: ${e.message}`); } + for (const line of text.split(/\r?\n/)) { + const s = line.replace(/\/\/.*$/, '').trim(); + if (s) opts.asserts.push(s); + } + } + else if (a === '--pass-rate') opts.passRate = parseFloat(argv[++i]); + else if (a === '--emit') opts.emit = argv[++i]; + else if (a === '--to-dsl') opts.toDsl = true; + else if (a === '--to-json') opts.toJson = true; else if (a === '--param') { const m = String(argv[++i] || '').match(/^([^=]+)=(.+)$/); if (!m) fail(`--param expects name=value, got "${argv[i]}"`); @@ -63,9 +105,10 @@ function parseArgs(argv) { } else if (!a.startsWith('-') && !opts.file) opts.file = a; else fail(`Unknown option: ${a}`); } - if (!opts.file) fail('Usage: node cli.js [--steps N] [--runs N] [--seed S] [--param k=v] [--csv]'); + if (!opts.file) fail('Usage: node cli.js [--steps N] [--runs N] [--seed S] [--param k=v] [--assert A] [--to-dsl] [--emit out.js]'); if (!isFinite(opts.steps) || opts.steps < 1) fail('--steps must be a positive integer'); if (!isFinite(opts.runs) || opts.runs < 1) fail('--runs must be a positive integer'); + if (!isFinite(opts.passRate) || opts.passRate < 0 || opts.passRate > 100) fail('--pass-rate must be 0..100'); return opts; } @@ -75,18 +118,66 @@ function csvCell(s) { } const opts = parseArgs(process.argv.slice(2)); -const { NodeType, Diagram, SimEngine, SimRandom } = loadEngine(); +const { + NodeType, Diagram, SimEngine, SimRandom, + dslSerialize, dslParse, parseAssertion, AssertionChecker, buildEconomyModule, +} = loadEngine(); -let json; -try { json = JSON.parse(fs.readFileSync(opts.file, 'utf8')); } +// ── Load the diagram: JSON, or .econ text ─────────────────────────────────── +let raw; +try { raw = fs.readFileSync(opts.file, 'utf8'); } catch (e) { fail(`Cannot read ${opts.file}: ${e.message}`); } +let json = null; +if (!/\.econ$/i.test(opts.file)) { + try { json = JSON.parse(raw); } catch { /* fall through to .econ */ } +} +if (json === null) { + try { json = dslParse(raw); } + catch (e) { fail(`Cannot parse ${opts.file}: ${e.message}`); } +} json.params = { ...(json.params || {}), ...opts.params }; +if (opts.seed != null) json.seed = String(opts.seed); +// Validate by loading once (throws on structurally broken files). const diagram = new Diagram(); -diagram.loadJSON(json); -// --seed overrides any seed saved in the diagram; reset() then applies it as the -// single RNG authority. Without --seed the diagram's own seed (if any) still holds. -if (opts.seed != null) diagram.seed = opts.seed; +try { diagram.loadJSON(json); } catch (e) { fail(`Invalid diagram: ${e.message}`); } + +// ── Conversion / codegen modes (no simulation) ────────────────────────────── +if (opts.toDsl) { + process.stdout.write(dslSerialize(diagram.toJSON())); + process.exit(0); +} +if (opts.toJson) { + process.stdout.write(JSON.stringify(diagram.toJSON(), null, 2) + '\n'); + process.exit(0); +} +if (opts.emit) { + const base = path.join(__dirname, 'js'); + const mod = buildEconomyModule(diagram.toJSON(), + fs.readFileSync(path.join(base, 'model.js'), 'utf8'), + fs.readFileSync(path.join(base, 'engine.js'), 'utf8'), + { generator: 'cli.js' }); + fs.writeFileSync(opts.emit, mod); + process.stderr.write(`Wrote ${opts.emit} (${(mod.length / 1024).toFixed(0)} KB)\n`); + process.exit(0); +} + +// ── Assertions ────────────────────────────────────────────────────────────── +let parsedAsserts = []; +try { parsedAsserts = opts.asserts.map(parseAssertion); } +catch (e) { fail(`Bad assertion: ${e.message}`); } + +function reportAssertions(results) { + let failed = 0; + for (const r of results) { + const mark = r.pass ? '\x1b[32mPASS\x1b[0m' : '\x1b[31mFAIL\x1b[0m'; + process.stderr.write(`assert ${mark} ${r.src}${r.detail && !r.pass ? ` (${r.detail})` : ''}\n`); + if (!r.pass) failed++; + } + process.stderr.write(`${results.length} assertion${results.length === 1 ? '' : 's'}: ${results.length - failed} passed, ${failed} failed\n`); + return failed; +} + const engine = new SimEngine(diagram); const tracked = [...diagram.nodes.values()].filter(n => n.type !== NodeType.SOURCE || n.limited); @@ -94,20 +185,41 @@ if (opts.runs === 1) { // Single run → per-step CSV trace on stdout. reset() seeds SimRandom from // diagram.seed (set from --seed above, or carried in the saved file). engine.reset(); + const checker = parsedAsserts.length ? new AssertionChecker(parsedAsserts) : null; + if (checker) checker.check(engine); const header = ['step', ...tracked.map(n => csvCell(n.label || n.type))]; process.stdout.write(header.join(',') + '\n'); process.stdout.write(['0', ...tracked.map(n => n.chartValue)].join(',') + '\n'); for (let s = 0; s < opts.steps && !engine.ended; s++) { engine.doStep(); + if (checker) checker.check(engine); process.stdout.write([engine.step, ...tracked.map(n => n.chartValue)].join(',') + '\n'); } SimRandom.seed(null); if (engine.ended) { process.stderr.write(`Goal reached: ${engine.ended.label} at step ${engine.ended.step}\n`); } + if (checker) { + const failed = reportAssertions(checker.finish(engine)); + if (failed > 0) process.exit(2); + } } else { - // Monte Carlo → stats table (or raw per-run CSV with --csv). - const res = engine.runMonteCarlo(opts.runs, opts.steps, { seed: opts.seed }); + // Monte Carlo → stats table (or raw per-run CSV with --csv), with + // assertions checked inside every trial when any were given. + const checkers = new Map(); + const runResults = []; + const mcOpts = { seed: opts.seed }; + if (parsedAsserts.length) { + mcOpts.perStep = (eng, r) => { + if (!checkers.has(r)) checkers.set(r, new AssertionChecker(parsedAsserts)); + checkers.get(r).check(eng); + }; + mcOpts.onTrialEnd = (eng, r) => { + runResults[r] = checkers.get(r).finish(eng); + checkers.delete(r); + }; + } + const res = engine.runMonteCarlo(opts.runs, opts.steps, mcOpts); if (opts.csv) { const header = ['run', ...res.nodes.map(n => csvCell(n.label || n.type))]; process.stdout.write(header.join(',') + '\n'); @@ -130,4 +242,32 @@ if (opts.runs === 1) { + pad(n.p10, 8) + pad(n.p50, 8) + pad(n.p90, 8) + pad(n.max, 8) + '\n'); } } + if (parsedAsserts.length) { + // Per-assertion tally across every run, then the all-assertions pass rate. + let cleanRuns = 0; + const failCounts = parsedAsserts.map(() => 0); + const firstFail = parsedAsserts.map(() => null); + for (let r = 0; r < runResults.length; r++) { + const results = runResults[r] || []; + let clean = true; + results.forEach((res2, i) => { + if (!res2.pass) { + clean = false; + failCounts[i]++; + if (!firstFail[i]) firstFail[i] = { run: r + 1, detail: res2.detail }; + } + }); + if (clean) cleanRuns++; + } + for (let i = 0; i < parsedAsserts.length; i++) { + const fails = failCounts[i]; + const mark = fails === 0 ? '\x1b[32mPASS\x1b[0m' : '\x1b[31mFAIL\x1b[0m'; + const where = fails > 0 ? ` (${fails}/${opts.runs} runs, first: run ${firstFail[i].run}, ${firstFail[i].detail})` : ''; + process.stderr.write(`assert ${mark} ${parsedAsserts[i].src}${where}\n`); + } + const rate = (cleanRuns / opts.runs) * 100; + const ok = rate >= opts.passRate; + process.stderr.write(`${cleanRuns}/${opts.runs} runs passed every assertion (${rate.toFixed(1)}%, required ${opts.passRate}%)\n`); + if (!ok) process.exit(2); + } } diff --git a/docs/ECONOMY_AS_CODE.md b/docs/ECONOMY_AS_CODE.md new file mode 100644 index 0000000..d598c68 --- /dev/null +++ b/docs/ECONOMY_AS_CODE.md @@ -0,0 +1,214 @@ +# Economy as code + +The designer's diagrams don't have to live only on the canvas. Three features +turn an economy into a first-class code artifact: + +1. **The `.econ` text format** — a readable, diff-friendly projection of the + diagram JSON that round-trips losslessly with the canvas. +2. **Assertions** — temporal checks the CLI runs against a simulation (and + against every Monte Carlo trial), with CI-friendly exit codes. +3. **Generated JS modules** — the diagram, the engine, and a small API compiled + into one dependency-free file you can ship inside a game or tool. + +Everything here is implemented in three DOM-free files — `js/dsl.js`, +`js/assertions.js`, `js/codegen.js` — shared verbatim by the browser app, +`cli.js`, and the test suite. + +--- + +## 1. The `.econ` text format + +**File → Save as text (.econ)** writes it; **File → Open file** reads it back +(any file that doesn't start with `{`/`[` is treated as `.econ`). On the CLI, +`--to-dsl` and `--to-json` convert in both directions, and any input file +ending in `.econ` is parsed as text. + +```econ +economy v1 +name: Widget Factory +desc: A tiny two-tier production chain. +seed: 42 +param mine_rate = 3 +type Wood = #8d6e63 + +// nodes: @ x,y [sugar…] [key=value…] +source Mine @ 80,180 color=Wood +pool Warehouse @ 300,180 = 10 of Wood cap=100 goal >= 90 +converter Forge @ 520,180 recipe(2 Wood, 1 #b0bec5) out=#ffa726 +register Score @ 520,60 = "warehouse * 2" + +// connections: -> moves resources, ~> carries state +Mine -> Warehouse : (mine_rate) every=2 75% if="self < 100" +Warehouse -> Forge : 2d6 color=Wood +Warehouse ~> Score name=warehouse +``` + +### Ground rules + +- One statement per line; blank lines are free; `//` starts a comment (`#` is + reserved for colors). +- Node references are **labels**: bare when they look like identifiers, quoted + (`"Gold Mine"`) otherwise. Duplicate labels get `#2`, `#3`, … suffixes in + declaration order (`Gold`, `Gold#2`). +- Anything not covered by the sugar below round-trips as generic `key=value` + attributes whose names are the diagram-JSON field names. Only fields that + differ from that node/connection type's defaults are written, so files stay + minimal — and new model fields serialize automatically without DSL changes. +- Attribute values: numbers and bare words as-is, strings quoted when needed, + booleans `true`/`false`, JSON for arrays/objects + (`waypoints=[{"x":1,"y":2}]`). + +### Header directives + +| Directive | Meaning | +| --- | --- | +| `economy v1` | format marker (optional on input, always written) | +| `name:` / `desc:` | diagram name/description (rest of line; `\n` escapes in desc) | +| `seed: 42` | run seed (reproducible runs) | +| `timeMode: async` | asynchronous time mode | +| `meta scheme=ocean bgColor=#101318 font="Space Grotesk"` | presentation extras | +| `param rate = 3` | a diagram parameter (repeatable) | +| `type Wood = #8d6e63` | named resource type; the name is usable wherever a color is | +| `var luck = dice(2d6) gaussian` | custom variable; kinds `interval(min,max)`, `array(1,2,3)`, `dice(XdY)`, `math(expr)`; modifiers `gaussian` and `per=play` | +| `player enabled rules=[…]` | artificial-player rules (JSON) | + +### Nodes + +` @ x,y …` where kind is `pool`, `source`, `drain`, `gate`, +`converter`, `register`, `delay`, `queue` or `trader`. + +Sugar, all optional: + +- `= 50` / `= 50 of Wood` — starting amount (with color/type). On a register: + `= "formula"` or `= 7` (a fixed value). +- `cap=100` — capacity. +- `goal >= 400` — end condition (any comparison operator). +- `passive` / `interactive` / `starting` — activation mode (default automatic). +- `pull` / `pull=all` — pull flow mode (policy `any` unless `=all`). +- `limited` (source) — finite stock; give the amount with `= 40`. +- `color=Wood` (source) — emitted resource color. +- `recipe(2 Wood, 1 #b0bec5)` (converter) — multi-ingredient recipe; + `in=2` (single-input amount) and `out=#ffa726` (output color) also available. +- Aliases: `cap→capacity, in→inputAmount, out→outputColor, color→resourceColor, + mode→gateMode, time→processTime, every→fireEvery, phase→firePhase`. + +### Connections + +`A -> B` moves resources; `A ~> B` carries state. After the target, an optional +rate clause, then attributes: + +- `: 3` — fixed rate; `: 2d6` — dice; `: (gold * 0.1)` — formula; + `: ~poisson(3, 2)` — distribution (`normal`, `uniform`, `exponential`, + `poisson` with their two parameters). +- `every=3` — fire interval; `40%` — chance per firing. +- `color=Wood` — color filter (also the converter's per-output mint color). +- `if="self > 5"` / `if="gold >= 2"` / `if="self between 2 8"` — condition on + the source's value (`self`) or a named variable. +- `name=gold` — state connection's variable name. +- `trigger`, `triggerChance=50`, `triggerEvery=2`, `reverseTrigger`. +- `act=">= 5"` / `act="between 1 99"` — activator on the target. +- `mod="rate 0.1"`, `mod="step 2"`, `mod="pulse 1"`, `mod="delta 2"`, or a + formula amount: `mod="rate (round(score * 0.1))"`. +- `weight=3` or `weight=(difficulty * 2)` — gate output weight. +- `label="tax"` plus any raw fields (`pathStyle=ortho`, `cpDx=10`, …). + +### Annotations + +```econ +group "Economy Core" @ 50,50 400x300 color=#7cb342 +note @ 620,50 160x80 "Balance this before shipping" +chart "Gold over time" @ 620,160 240x150 type=area tracks=Gold,Score +``` + +### Round-trip guarantees + +`serialize(parse(serialize(x))) === serialize(x)` byte-for-byte, and the parsed +JSON is semantically identical to the original up to node/connection id +renaming and runtime fields (live variable values, thumbnails, timestamps). +`normalizeEconJSON()` in `js/dsl.js` is the canonical comparison form the tests +use. Ids are regenerated deterministically (`n1`, `c1`, …) on parse, so saving +the same economy twice produces identical text — that's what makes diffs clean. + +--- + +## 2. Assertions + +```bash +node cli.js economy.econ --steps 300 \ + --assert "always gold < 500" \ + --assert "eventually score >= 100" \ + --assert "at step 25: queue <= 3" \ + --assert "at end: widgets > 50" \ + --assert "widgets > 50" # bare expression = at end +``` + +| Quantifier | Passes when | +| --- | --- | +| `always E` | E is true at every step, including step 0 | +| `never E` | E is false at every step | +| `eventually E` | E becomes true at one or more steps | +| `at end: E` | E is true at the final step | +| `at step N: E` | E is true at exactly step N (fails if the run ends sooner) | + +The expression language is the same one rates and registers use (math.js +syntax with a plain-JS fallback): comparisons, arithmetic, `and`/`or`, +ternaries, `round/floor/min/max/…`. + +**Scope**: every node's label (sanitized to an identifier — `Gold Mine` becomes +`Gold_Mine`, duplicates get `_2`, `_3`, …) holds its chart value (pool contents, +drain total, register value, limited-source stock, trader trades); all diagram +variables (params, custom variables, state-connection names, register labels) +are visible; `step` is the current step. + +**Exit codes**: `0` all assertions pass, `2` any fail (`1` stays reserved for +usage/file errors), so a CI job is just the command itself. + +**Monte Carlo**: with `--runs N` every trial is checked independently. +`--pass-rate 95` passes the batch when at least 95% of trials satisfy *all* +assertions (default 100). The report shows per-assertion failure counts and the +first failing run. `--assert-file checks.txt` loads one assertion per line +(`//` comments allowed). + +--- + +## 3. Generated JS modules + +**File → Export as JS module** in the app, or: + +```bash +node cli.js economy.econ --emit economy.module.js +``` + +The output is one UMD file (~100 KB, no dependencies) containing the model, +the engine, the diagram, and this API: + +```js +const { createEconomy } = require('./economy.module.js'); // or window.Economy + +const eco = createEconomy({ seed: 42, params: { mine_rate: 3 } }); + +eco.step(); // advance one step +eco.step(5); // advance five +eco.run(200); // advance until a goal ends the run, or 200 steps +eco.t; // current step +eco.ended; // did a goal condition end the run? +eco.get('Gold'); // node value by label (falls back to variables) +eco.set('Gold', 10); // set a pool / limited source / register +eco.fire('Buy'); // fire an interactive node (a player action) +eco.values(); // { label: value } for every tracked node +eco.vars(); // the shared variable store +eco.onStep((values, step) => { ... }); +eco.reset(); // back to step 0 (re-applies the seed) +``` + +Notes: + +- Formulas evaluate with math.js when a global `math` exists (`global.math = + require('mathjs')` in Node); otherwise they fall back to the legacy plain-JS + expression path. Economies without math.js-specific syntax need nothing. +- The RNG (`SimRandom`) is module-level state, exactly like the app: run one + seeded economy at a time per process for bit-exact reproducibility. +- `createEconomy()` parses a fresh copy of the embedded diagram each call, so + instances never share mutable state. +- The module also exports `Diagram`, `SimEngine`, `SimRandom` and `NodeType` + for power users who want to go under the hood. diff --git a/index.html b/index.html index 3b06e86..b547262 100644 --- a/index.html +++ b/index.html @@ -83,10 +83,12 @@ + + @@ -615,6 +617,9 @@

The building blocks

+ + + diff --git a/js/app-export.js b/js/app-export.js index 3300e7b..de44220 100644 --- a/js/app-export.js +++ b/js/app-export.js @@ -150,6 +150,43 @@ class AppExport { a.click(); } + // ── Economy-as-code exports ───────────────────────────────────────────────── + + // Download the diagram as .econ text (the human-readable, diff-friendly + // format in js/dsl.js). Same File menu family as Save as JSON. + _exportEcon() { + const text = dslSerialize(this.diagram.toJSON()); + const a = Object.assign(document.createElement('a'), { + href: URL.createObjectURL(new Blob([text], { type: 'text/plain' })), + download: this._exportFilename('econ'), + }); + a.click(); + this._toast('Exported as .econ text. Open it back via File, Open file.'); + } + + // Bundle model + engine + this diagram into a standalone JS module (see + // js/codegen.js). The sources are fetched from our own script files, so this + // needs the app to be served over HTTP (the normal case). + async _exportModule() { + let modelSrc, engineSrc; + try { + [modelSrc, engineSrc] = await Promise.all([ + fetch('js/model.js').then(r => { if (!r.ok) throw new Error(r.status); return r.text(); }), + fetch('js/engine.js').then(r => { if (!r.ok) throw new Error(r.status); return r.text(); }), + ]); + } catch { + this._toast('Could not read the engine sources. Serve the app over HTTP to export a module.'); + return; + } + const mod = buildEconomyModule(this.diagram.toJSON(), modelSrc, engineSrc, { generator: 'the simulations designer' }); + const a = Object.assign(document.createElement('a'), { + href: URL.createObjectURL(new Blob([mod], { type: 'text/javascript' })), + download: this._exportFilename('module.js'), + }); + a.click(); + this._toast('Exported a standalone JS module with a createEconomy() API.'); + } + // ── Shareable URL ─────────────────────────────────────────────────────────── _encodeDiagram() { diff --git a/js/app.js b/js/app.js index d2369ce..32949ac 100644 --- a/js/app.js +++ b/js/app.js @@ -1159,6 +1159,8 @@ class App { document.getElementById('btn-export-svg').addEventListener('click', () => this._exportSVG()); document.getElementById('btn-export-png').addEventListener('click', () => this._exportPNG()); document.getElementById('btn-export-csv').addEventListener('click', () => this._exportCSV()); + document.getElementById('btn-export-econ').addEventListener('click', () => this._exportEcon()); + document.getElementById('btn-export-module').addEventListener('click', () => this._exportModule()); document.getElementById('btn-share').addEventListener('click', () => this._shareURL()); // A11y: hide decorative tool icons from assistive tech (buttons keep text labels). @@ -1174,7 +1176,7 @@ class App { }); document.getElementById('btn-load').addEventListener('click', () => { - const inp = Object.assign(document.createElement('input'), { type: 'file', accept: '.json' }); + const inp = Object.assign(document.createElement('input'), { type: 'file', accept: '.json,.econ' }); inp.onchange = e => { const file = e.target.files[0]; if (!file) return; @@ -1183,9 +1185,11 @@ class App { // Parse + validate on a throwaway Diagram BEFORE touching the current // one: loadJSON clears everything first, so a corrupt file would // otherwise wreck the diagram (and the next autosave persists that). + // Files that don't open with { or [ are treated as .econ text. let data; try { - data = JSON.parse(ev.target.result); + const text = String(ev.target.result); + data = /^\s*[{[]/.test(text) ? JSON.parse(text) : dslParse(text); new Diagram().loadJSON(data); } catch (err) { this._toast(`Invalid file: ${err.message}. Your current diagram is unchanged.`); diff --git a/js/assertions.js b/js/assertions.js new file mode 100644 index 0000000..69559b1 --- /dev/null +++ b/js/assertions.js @@ -0,0 +1,130 @@ +// Economy-as-code: design assertions. +// +// An assertion is a temporal check over a simulation run, written as a +// quantifier plus a formula in the same expression language rates and +// registers use (math.js when loaded, legacy JS fallback otherwise): +// +// always gold < 500 holds at every step (including step 0) +// never wood == 0 inverse of always +// eventually score >= 100 true at one or more steps +// at end: widgets > 50 true at the final step +// at step 25: queue <= 3 true at exactly step 25 +// widgets > 50 bare expression = at end +// +// The colon after a quantifier is optional. Identifiers in scope, later +// entries overriding earlier ones on a name clash: +// 1. every node's label, sanitized to an identifier (spaces and other +// symbols become _, a leading digit gets a _ prefix; duplicate labels +// get _2, _3, … in declaration order), valued at the node's chart value +// (pool contents, drain total, source produced-if-limited, register +// value, trader trades) +// 2. everything in diagram.variables (params, custom variables, state- +// connection names, register labels) +// 3. step, the current step number +// +// DOM-free (loaded by the browser, cli.js and test/run.js; must come after +// model.js, which provides evalFormula/validateFormula). + +/* exported parseAssertion, AssertionChecker, assertionScope */ + +function _assertIdent(label, fallback) { + let s = String(label == null ? '' : label).trim().replace(/[^A-Za-z0-9_$]+/g, '_').replace(/^_+|_+$/g, ''); + if (!s) s = fallback; + if (/^[0-9]/.test(s)) s = '_' + s; + return s; +} + +// The identifier scope described above, for one engine at its current step. +function assertionScope(engine) { + const scope = {}; + const seen = new Map(); + for (const n of engine.diagram.nodes.values()) { + let key = _assertIdent(n.label, n.type); + const count = (seen.get(key) || 0) + 1; + seen.set(key, count); + if (count > 1) key = `${key}_${count}`; + const v = n.chartValue; + scope[key] = isFinite(v) ? v : 0; + } + for (const [k, v] of Object.entries(engine.diagram.variables || {})) { + if (typeof v === 'number' && isFinite(v)) scope[k] = v; + } + scope.step = engine.step; + return scope; +} + +// Parse one assertion string. Returns { quant, atStep, expr, src }. +// quant: 'always' | 'never' | 'eventually' | 'end' | 'step'. +// Throws on an unknown form or an expression neither evaluator can parse. +function parseAssertion(src) { + const s = String(src || '').trim(); + if (!s) throw new Error('empty assertion'); + let quant = 'end', atStep = null, expr = s; + + let m; + if ((m = s.match(/^(always|never|eventually)\s*:?\s+(.+)$/i))) { + quant = m[1].toLowerCase(); + expr = m[2]; + } else if ((m = s.match(/^at\s+end\s*:?\s*(.+)$/i))) { + quant = 'end'; + expr = m[1]; + } else if ((m = s.match(/^at\s+step\s+(\d+)\s*:?\s*(.+)$/i))) { + quant = 'step'; + atStep = parseInt(m[1], 10); + expr = m[2]; + } + expr = expr.trim(); + if (!expr) throw new Error(`assertion "${s}" has no expression`); + if (typeof validateFormula === 'function' && !validateFormula(expr)) { + throw new Error(`assertion expression does not parse: ${expr}`); + } + return { quant, atStep, expr, src: s }; +} + +// Checks a list of parsed assertions over one run. Call check(engine) at +// step 0 (right after reset) and again after every doStep; call finish(engine) +// when the run ends to get results: +// [{ src, quant, pass, failStep, detail }] +class AssertionChecker { + constructor(parsed) { + this.assertions = parsed; + this._state = parsed.map(() => ({ failStep: null, met: false, metStep: null, sawStep: false, last: false })); + } + + check(engine) { + const scope = assertionScope(engine); + const step = engine.step; + for (let i = 0; i < this.assertions.length; i++) { + const a = this.assertions[i], st = this._state[i]; + // 'step' assertions only evaluate at their step; everything else, every step. + if (a.quant === 'step' && step !== a.atStep) continue; + const truthy = evalFormula(a.expr, scope) !== 0; + if (a.quant === 'always' && !truthy && st.failStep === null) st.failStep = step; + else if (a.quant === 'never' && truthy && st.failStep === null) st.failStep = step; + else if (a.quant === 'eventually' && truthy && !st.met) { st.met = true; st.metStep = step; } + else if (a.quant === 'step') { st.sawStep = true; st.last = truthy; } + else if (a.quant === 'end') st.last = truthy; + } + } + + finish(engine) { + return this.assertions.map((a, i) => { + const st = this._state[i]; + let pass, detail = ''; + if (a.quant === 'always' || a.quant === 'never') { + pass = st.failStep === null; + if (!pass) detail = `violated at step ${st.failStep}`; + } else if (a.quant === 'eventually') { + pass = st.met; + detail = pass ? `first true at step ${st.metStep}` : `never true in ${engine.step} steps`; + } else if (a.quant === 'step') { + if (!st.sawStep) { pass = false; detail = `run ended at step ${engine.step}, before step ${a.atStep}`; } + else { pass = st.last; if (!pass) detail = `false at step ${a.atStep}`; } + } else { + pass = st.last; + if (!pass) detail = `false at final step ${engine.step}`; + } + return { src: a.src, quant: a.quant, pass, failStep: st.failStep, detail }; + }); + } +} diff --git a/js/codegen.js b/js/codegen.js new file mode 100644 index 0000000..6b40b4c --- /dev/null +++ b/js/codegen.js @@ -0,0 +1,120 @@ +// Economy-as-code: export a diagram as a standalone JavaScript module. +// +// buildEconomyModule() bundles the model + engine sources (passed in by the +// caller: the app fetches its own script files, cli.js reads them from disk) +// with the diagram JSON and a small runtime API into one dependency-free UMD +// file. The generated module runs in Node (require) and the browser (script +// tag → window.Economy, or any bundler). +// +// const { createEconomy } = require('./economy.js'); +// const eco = createEconomy({ seed: 42, params: { mine_rate: 3 } }); +// eco.run(200); +// console.log(eco.get('Gold'), eco.t, eco.ended); +// +// DOM-free (loaded by the browser, cli.js and test/run.js). + +/* exported buildEconomyModule */ + +function buildEconomyModule(json, modelSrc, engineSrc, opts = {}) { + const globalName = opts.name || 'Economy'; + const econName = (json.meta && json.meta.name) || 'economy'; + const stamp = opts.generator || 'the simulations designer'; + // Double-encode the diagram: the module keeps it as a JSON string and each + // createEconomy() call parses a fresh deep copy. + const diagramLiteral = JSON.stringify(JSON.stringify(json)); + + return `/* + * ${econName} — generated economy module + * Built by ${stamp}. Self-contained: no dependencies, no DOM. + * + * Formulas evaluate with math.js when a global \`math\` is present (optional: + * require('mathjs') and set global.math before loading this file); without it + * they fall back to a plain JS expression evaluator. + * + * The RNG (SimRandom) is shared module state: run one seeded economy at a + * time per process for bit-exact reproducibility. + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.${globalName} = factory(); +}(typeof self !== 'undefined' ? self : this, function () { +'use strict'; + +${modelSrc} + +${engineSrc} + +const DIAGRAM_SRC = ${diagramLiteral}; + +// Runtime handle over one simulation instance. +// opts.seed — override the diagram's run seed (same seed, same run) +// opts.params — override diagram parameters by name +function createEconomy(opts = {}) { + const d = new Diagram(); + d.loadJSON(JSON.parse(DIAGRAM_SRC)); + if (opts.seed != null) d.seed = String(opts.seed); + if (opts.params) d.params = Object.assign({}, d.params, opts.params); + const e = new SimEngine(d); + let stepCb = null; + e.onStep = (s) => { if (stepCb && s > 0) stepCb(api.values(), s); }; + const findNode = (name) => { + for (const n of d.nodes.values()) if (n.label === name) return n; + return null; + }; + const api = { + engine: e, + diagram: d, + get t() { return e.step; }, + get ended() { return !!e.ended; }, + // Put the simulation back at step 0 (and re-apply the seed). + reset() { e.reset(); return api; }, + // Advance n steps (stops early if a goal ends the run). + step(n = 1) { for (let i = 0; i < n && !e.ended; i++) e.doStep(); return api; }, + // Advance until a goal is reached or maxSteps elapse. + run(maxSteps = 1000) { for (let i = 0; i < maxSteps && !e.ended; i++) e.doStep(); return api; }, + // Value by node label (pool contents, drain total, register value, …), + // falling back to the shared variable store (params, state connections). + get(name) { + const n = findNode(name); + if (n) return n.chartValue; + return d.variables[name]; + }, + // Set a pool's or limited source's live amount, or a register's value. + set(name, v) { + const n = findNode(name); + if (!n) throw new Error('set(): no node labeled ' + JSON.stringify(name)); + if (n.type === NodeType.REGISTER) { n.value = Number(v) || 0; return api; } + if (n.type === NodeType.POOL || (n.type === NodeType.SOURCE && n.limited)) { + n.resources = Math.max(0, Number(v) || 0); + n.reconcile(); + return api; + } + throw new Error('set() supports pools, limited sources and registers'); + }, + // Fire an interactive node by label (a player action). + fire(name) { + const n = findNode(name); + if (!n) throw new Error('fire(): no node labeled ' + JSON.stringify(name)); + return e.fireInteractive(n.id); + }, + // {label: value} for every tracked node (infinite sources excluded). + values() { + const out = {}; + for (const n of d.nodes.values()) { + if (n.type === NodeType.SOURCE && !n.limited) continue; + out[n.label] = n.chartValue; + } + return out; + }, + vars() { return Object.assign({}, d.variables); }, + // Subscribe to steps: fn(values, step) after every advance. + onStep(fn) { stepCb = fn; return api; }, + }; + e.reset(); + return api; +} + +return { createEconomy, DIAGRAM_SRC, Diagram, SimEngine, SimRandom, NodeType }; +})); +`; +} diff --git a/js/dsl.js b/js/dsl.js new file mode 100644 index 0000000..9f650b9 --- /dev/null +++ b/js/dsl.js @@ -0,0 +1,846 @@ +// Economy-as-code: the .econ text format. +// +// A human-readable, diff-friendly projection of the diagram JSON. dslSerialize +// turns Diagram.toJSON() output into text; dslParse turns text back into JSON +// ready for Diagram.loadJSON(). Round-trip fidelity is an invariant guarded by +// test/run.js: serialize→parse→serialize must be a fixpoint, and the parsed +// JSON must be semantically identical to the original up to id renaming and +// runtime fields (see normalizeEconJSON). +// +// DOM-free on purpose (same contract as model.js/engine.js): this file is +// loaded by the browser, by cli.js and by test/run.js. It references the +// model globals (MNode, MConnection, NodeType, …), so it must load after +// model.js in every context. +// +// ── Format overview ───────────────────────────────────────────────────────── +// +// economy v1 // header (optional but always emitted) +// name: Widget Factory // diagram meta, rest-of-line +// desc: One line with \n escapes +// seed: 42 +// timeMode: async +// meta scheme=ocean bgColor=#101318 +// param mine_rate = 3 +// type Wood = #8d6e63 // named resource types +// var luck = dice(2d6) gaussian // custom variables +// var boost = math(gold * 0.1) per=play +// player enabled rules=[{...}] // artificial player (rules as JSON) +// +// pool Gold @ 240,180 = 50 of #ffd54f cap=500 goal >= 400 +// source Mine @ 80,180 color=Wood +// converter Forge @ 400,180 recipe(2 Wood, 1 #b0bec5) out=#ffa726 +// register Score @ 560,60 = "gold * 2" +// +// Mine -> Gold : 2 every=3 40% if="self < 100" +// Gold -> Forge : (mine_rate * 2) color=Wood +// Gold ~> Score name=gold +// Forge ~> Mine trigger triggerChance=50 +// +// group "Economy" @ 60,40 520x300 color=#4a9eff +// note @ 620,40 160x80 "Balance me" +// chart "Gold over time" @ 620,160 240x150 type=area tracks=Gold,Score +// +// Lines are independent; `//` starts a comment (never `#`, which is a color). +// Node references are labels, quoted when not bare identifiers, with `#N` +// suffixes disambiguating duplicate labels in declaration order. Everything +// not covered by sugar round-trips as generic key=value attributes, diffed +// against the model constructors' defaults so only non-default fields appear. + +/* exported dslSerialize, dslParse, normalizeEconJSON */ + +const ECON_NODE_KINDS = ['pool', 'source', 'drain', 'gate', 'converter', 'register', 'delay', 'queue', 'trader']; + +// Attribute aliases: short DSL names for common JSON fields, per line kind. +const ECON_NODE_ALIAS = { + cap: 'capacity', in: 'inputAmount', out: 'outputColor', color: 'resourceColor', + mode: 'gateMode', time: 'processTime', every: 'fireEvery', phase: 'firePhase', +}; +const ECON_CONN_ALIAS = { + every: 'interval', color: 'colorFilter', name: 'variableName', +}; +const ECON_ACTIVATIONS = ['automatic', 'passive', 'interactive', 'starting']; + +// ── Small text helpers ────────────────────────────────────────────────────── + +function _econIsBare(s) { return /^[A-Za-z_][A-Za-z0-9_]*$/.test(s); } + +function _econQuote(s) { + return '"' + String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + .replace(/\n/g, '\\n').replace(/\r/g, '') + '"'; +} + +function _econName(s) { return _econIsBare(s) ? s : _econQuote(s); } + +function _econUnescape(s) { + return s.replace(/\\(.)/g, (_, c) => (c === 'n' ? '\n' : c)); +} + +// Format a number exactly (String round-trips JS doubles). +function _econNum(n) { return String(n); } + +// ── Tokenizer ─────────────────────────────────────────────────────────────── +// Split a line into whitespace-separated tokens, except inside double quotes, +// parentheses, brackets or braces (so `recipe(2 Wood, 1 Stone)`, `(gold * 2)` +// and rules=[{"a":"hi there"}] each stay one token). Also strips `//` comments +// at depth 0 outside quotes. + +function _econTokens(line, lineNo) { + const tokens = []; + let cur = '', depth = 0, inQ = false; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (inQ) { + cur += ch; + if (ch === '\\') { cur += line[++i] ?? ''; continue; } + if (ch === '"') inQ = false; + continue; + } + if (ch === '"') { inQ = true; cur += ch; continue; } + if (ch === '(' || ch === '[' || ch === '{') { depth++; cur += ch; continue; } + if (ch === ')' || ch === ']' || ch === '}') { depth--; cur += ch; continue; } + if (depth === 0 && ch === '/' && line[i + 1] === '/' && (cur === '' || /\s/.test(line[i - 1] || ' '))) break; + if (depth === 0 && /\s/.test(ch)) { + if (cur) { tokens.push(cur); cur = ''; } + continue; + } + cur += ch; + } + if (inQ || depth !== 0) throw _econErr(`unbalanced quotes or brackets`, lineNo); + if (cur) tokens.push(cur); + return tokens; +} + +function _econErr(msg, lineNo) { + const e = new Error(`.econ line ${lineNo}: ${msg}`); + e.line = lineNo; + return e; +} + +// ── Attribute value encoding ──────────────────────────────────────────────── + +function _econAttrValue(v) { + if (typeof v === 'number') return _econNum(v); + if (typeof v === 'boolean') return String(v); + if (v === null) return 'null'; + if (typeof v === 'object') return JSON.stringify(v); + const s = String(v); + if (/^-?\d+(\.\d+)?$/.test(s) || !/^[^\s"=]+$/.test(s) || s === '' || + s === 'true' || s === 'false' || s === 'null' || /^[[{(]/.test(s)) return _econQuote(s); + return s; +} + +function _econParseValue(raw, lineNo) { + if (raw.startsWith('"')) { + if (!raw.endsWith('"') || raw.length < 2) throw _econErr(`bad string ${raw}`, lineNo); + return _econUnescape(raw.slice(1, -1)); + } + if (raw === 'true') return true; + if (raw === 'false') return false; + if (raw === 'null') return null; + if (raw.startsWith('{') || raw.startsWith('[')) { + try { return JSON.parse(raw); } + catch (e) { throw _econErr(`bad JSON value: ${e.message}`, lineNo); } + } + const n = Number(raw); + if (raw !== '' && isFinite(n) && /^[-+.\d]/.test(raw)) return n; + return raw; // bare word (color hex, identifier, …) +} + +// ── Serializer ────────────────────────────────────────────────────────────── + +// Assign every node a unique, human-readable reference name derived from its +// label, disambiguating duplicates with #2, #3, … in declaration order. +function _econRefNames(nodes) { + const used = new Map(); // base label → count + const refs = new Map(); // node id → ref string + for (const n of nodes) { + const base = n.label != null ? String(n.label) : ''; + const count = (used.get(base) || 0) + 1; + used.set(base, count); + refs.set(n.id, _econName(base) + (count > 1 ? '#' + count : '')); + } + return refs; +} + +// Non-default fields of `obj` vs a freshly constructed default, as attr text. +// `skip` holds keys already covered by sugar or structure. Uses JSON-level +// comparison so objects/arrays compare by value. Booleans are emitted as +// key=true/false (never bare flags) so the parser needs no per-key knowledge. +function _econExtraAttrs(obj, defaults, skip, alias) { + const rev = {}; + for (const [short, full] of Object.entries(alias || {})) rev[full] = short; + const out = []; + for (const key of Object.keys(obj)) { + if (skip.has(key)) continue; + const v = obj[key]; + if (v === undefined) continue; + if (JSON.stringify(v) === JSON.stringify(defaults[key])) continue; + out.push(`${rev[key] || key}=${_econAttrValue(v)}`); + } + return out; +} + +// Preferred color spelling: a declared resource-type name when one matches, +// else the raw hex. +function _econColorRef(color, types) { + if (!color) return color; + const t = (types || []).find(t => t.color && t.color.toLowerCase() === String(color).toLowerCase()); + return t && t.name ? _econName(t.name) : color; +} + +function dslSerialize(json) { + const out = []; + const types = json.resourceTypes || []; + const meta = json.meta || {}; + out.push('economy v1'); + if (meta.name) out.push(`name: ${meta.name}`); + if (meta.description) out.push(`desc: ${meta.description.replace(/\\/g, '\\\\').replace(/\n/g, '\\n')}`); + if (json.seed) out.push(`seed: ${json.seed}`); + if (json.timeMode && json.timeMode !== 'sync') out.push(`timeMode: ${json.timeMode}`); + { + const extras = []; + if (meta.scheme && meta.scheme !== 'default') extras.push(`scheme=${_econAttrValue(meta.scheme)}`); + if (meta.bgColor) extras.push(`bgColor=${_econAttrValue(meta.bgColor)}`); + if (meta.font) extras.push(`font=${_econAttrValue(meta.font)}`); + if (extras.length) out.push(`meta ${extras.join(' ')}`); + } + for (const [k, v] of Object.entries(json.params || {})) out.push(`param ${k} = ${_econNum(v)}`); + for (const t of types) out.push(`type ${_econName(t.name || '')} = ${t.color}`); + for (const rv of json.customVars || []) { + let kind; + if (rv.kind === 'math') kind = `math(${rv.formula || ''})`; + else if (rv.kind === 'dice') kind = `dice(${rv.dice || '1d6'})`; + else if (rv.kind === 'array') kind = `array(${(rv.values || []).join(', ')})`; + else kind = `interval(${_econNum(rv.min ?? 0)}, ${_econNum(rv.max ?? 0)})`; + const parts = [`var ${_econName(rv.name || '')} = ${kind}`]; + if (rv.dist === 'gaussian') parts.push('gaussian'); + if ((rv.update || 'step') !== 'step') parts.push(`per=${rv.update}`); + out.push(parts.join(' ')); + } + if (json.aiPlayer && (json.aiPlayer.rules || []).length) { + const parts = ['player']; + if (json.aiPlayer.enabled) parts.push('enabled'); + parts.push(`rules=${JSON.stringify(json.aiPlayer.rules)}`); + out.push(parts.join(' ')); + } + + const nodes = json.nodes || []; + const refs = _econRefNames(nodes); + if (nodes.length) out.push(''); + + for (const n of nodes) { + const def = new MNode(n.type, 0, 0).toJSON(); + const skip = new Set(['id', 'type', 'x', 'y', 'label']); + const parts = [n.type, refs.get(n.id), `@ ${_econNum(n.x)},${_econNum(n.y)}`]; + + // Start amount: `= N [of color]` when the colorMap is empty or a single + // entry matching the count; multi-color maps fall through to a generic attr. + const cm = n.colorMap || {}; + const cmKeys = Object.keys(cm); + const single = cmKeys.length === 1 && cm[cmKeys[0]] === n.resources; + if (n.type === 'register') { + if (n.formula) { parts.push(`= ${_econQuote(n.formula)}`); skip.add('formula'); } + else if (n.value) { parts.push(`= ${_econNum(n.value)}`); skip.add('value'); } + } else if (n.resources > 0 && isFinite(n.resources) && (cmKeys.length === 0 || single)) { + let sugar = `= ${_econNum(n.resources)}`; + if (single && cmKeys[0] !== DEFAULT_COLOR) sugar += ` of ${_econColorRef(cmKeys[0], types)}`; + parts.push(sugar); + skip.add('resources'); skip.add('colorMap'); + } + + if (n.capacity != null && isFinite(n.capacity)) { parts.push(`cap=${_econNum(n.capacity)}`); skip.add('capacity'); } + if (n.endEnabled) { + parts.push(`goal ${n.endOperator || '>='} ${_econNum(n.endValue || 0)}`); + skip.add('endEnabled'); skip.add('endOperator'); skip.add('endValue'); + } + if (n.activation && n.activation !== 'automatic') { parts.push(n.activation); skip.add('activation'); } + if (n.flowMode === 'pull') { + parts.push(n.pullPolicy === 'all' ? 'pull=all' : 'pull'); + skip.add('flowMode'); skip.add('pullPolicy'); + } + if (n.type === 'source') { + if (n.limited) { parts.push('limited'); skip.add('limited'); } + if (n.resourceColor && n.resourceColor !== def.resourceColor) { + parts.push(`color=${_econColorRef(n.resourceColor, types)}`); skip.add('resourceColor'); + } + } + if (n.type === 'converter' && Array.isArray(n.inputRecipe) && n.inputRecipe.length) { + const items = n.inputRecipe.map(i => `${_econNum(i.amount ?? 1)} ${_econColorRef(i.color, types)}`); + parts.push(`recipe(${items.join(', ')})`); + skip.add('inputRecipe'); + if (n.inputAmount !== def.inputAmount) { parts.push(`in=${_econNum(n.inputAmount)}`); skip.add('inputAmount'); } + if (n.outputColor !== def.outputColor) { parts.push(`out=${_econColorRef(n.outputColor, types)}`); skip.add('outputColor'); } + } else if (n.type === 'converter') { + if (n.inputAmount !== def.inputAmount) { parts.push(`in=${_econNum(n.inputAmount)}`); skip.add('inputAmount'); } + if (n.outputColor !== def.outputColor) { parts.push(`out=${_econColorRef(n.outputColor, types)}`); skip.add('outputColor'); } + skip.add('inputRecipe'); + } + // Everything else (gateMode, delay, queue fields, fireEvery, …) rides the + // generic default-diff below, with short alias names where defined. + parts.push(..._econExtraAttrs(n, def, skip, ECON_NODE_ALIAS)); + out.push(parts.join(' ')); + } + + for (const g of json.groups || []) { + const parts = ['group', _econQuote(g.label ?? ''), `@ ${_econNum(g.x)},${_econNum(g.y)}`, `${_econNum(g.w)}x${_econNum(g.h)}`]; + if (g.color && g.color !== '#4a9eff') parts.push(`color=${g.color}`); + out.push(parts.join(' ')); + } + for (const nt of json.notes || []) { + const parts = ['note', `@ ${_econNum(nt.x)},${_econNum(nt.y)}`, `${_econNum(nt.w)}x${_econNum(nt.h)}`]; + if (nt.color && nt.color !== '#f6e05e') parts.push(`color=${nt.color}`); + parts.push(_econQuote(nt.text ?? '')); + out.push(parts.join(' ')); + } + for (const ch of json.charts || []) { + const parts = ['chart', _econQuote(ch.label ?? ''), `@ ${_econNum(ch.x)},${_econNum(ch.y)}`, `${_econNum(ch.w)}x${_econNum(ch.h)}`]; + if (ch.chartType && ch.chartType !== 'line') parts.push(`type=${ch.chartType}`); + const tracked = (ch.nodeIds || []).map(id => refs.get(id)).filter(Boolean); + if (tracked.length) parts.push(`tracks=${tracked.join(',')}`); + out.push(parts.join(' ')); + } + + const conns = json.connections || []; + if (conns.length) out.push(''); + for (const c of conns) { + const def = new MConnection('', '', c.type).toJSON(); + const skip = new Set(['id', 'sourceId', 'targetId', 'type']); + const arrow = c.type === 'state' ? '~>' : '->'; + const from = refs.get(c.sourceId), to = refs.get(c.targetId); + if (!from || !to) continue; // dangling connection: not representable, drop + const parts = [from, arrow, to]; + + if (c.type !== 'state') { + // Rate sugar covers the active mode; inactive-mode fields that differ + // from defaults still round-trip via generic attrs below. + const mode = c.rateMode || 'fixed'; + if (mode === 'fixed' && c.rate !== 1) { parts.push(`: ${_econNum(c.rate)}`); skip.add('rate'); skip.add('rateMode'); } + else if (mode === 'fixed') { skip.add('rateMode'); } + else if (mode === 'dice') { parts.push(`: ${c.dice || '1d6'}`); skip.add('dice'); skip.add('rateMode'); } + else if (mode === 'formula' && c.formula) { parts.push(`: (${c.formula})`); skip.add('formula'); skip.add('rateMode'); } + else if (mode === 'distribution') { + parts.push(`: ~${c.distType || 'normal'}(${_econNum(c.distParam1 ?? 5)}, ${_econNum(c.distParam2 ?? 2)})`); + skip.add('distType'); skip.add('distParam1'); skip.add('distParam2'); skip.add('rateMode'); + } + } + if (c.interval && c.interval !== 1) { parts.push(`every=${_econNum(c.interval)}`); skip.add('interval'); } + if (c.chance !== undefined && c.chance !== 100) { parts.push(`${_econNum(c.chance)}%`); skip.add('chance'); } + if (c.colorFilter) { parts.push(`color=${_econColorRef(c.colorFilter, types)}`); skip.add('colorFilter'); } + if (c.condEnabled) { + const ref = (c.condRefMode === 'variable' && c.condVariable) ? c.condVariable : 'self'; + const tail = c.condOperator === 'between' ? `${_econNum(c.condValue)} ${_econNum(c.condValue2 || 0)}` : _econNum(c.condValue); + parts.push(`if=${_econQuote(`${ref} ${c.condOperator} ${tail}`)}`); + for (const k of ['condEnabled', 'condOperator', 'condValue', 'condValue2', 'condRefMode', 'condVariable']) skip.add(k); + } + if (c.variableName) { parts.push(`name=${_econAttrValue(c.variableName)}`); skip.add('variableName'); } + if (c.trigger) { parts.push('trigger'); skip.add('trigger'); } + if (c.reverseTrigger) { parts.push('reverseTrigger'); skip.add('reverseTrigger'); } + if (c.activator) { + const tail = c.actOperator === 'between' ? `${_econNum(c.actValue)} ${_econNum(c.actValue2 || 0)}` : _econNum(c.actValue); + parts.push(`act=${_econQuote(`${c.actOperator} ${tail}`)}`); + for (const k of ['activator', 'actOperator', 'actValue', 'actValue2']) skip.add(k); + } + if (c.modifier) { + const mode = c.modMode || 'rate'; + const amount = c.modFormula ? `(${c.modFormula})` : _econNum(c.modFactor ?? 1); + parts.push(`mod=${_econQuote(`${mode} ${amount}`)}`); + for (const k of ['modifier', 'modMode', 'modFactor', 'modFormula']) skip.add(k); + } + if (c.weightFormula) { parts.push(`weight=(${c.weightFormula})`); skip.add('weightFormula'); skip.add('weight'); } + else if (c.weight !== undefined && c.weight !== 1) { parts.push(`weight=${_econNum(c.weight)}`); skip.add('weight'); } + if (c.label) { parts.push(`label=${_econAttrValue(c.label)}`); skip.add('label'); } + parts.push(..._econExtraAttrs(c, def, skip, ECON_CONN_ALIAS)); + out.push(parts.join(' ')); + } + return out.join('\n') + '\n'; +} + +// ── Parser ────────────────────────────────────────────────────────────────── + +// Read a name token: `Gold`, `"Gold Mine"`, optionally with a `#N` suffix. +// Returns { name, ord } where ord is the 1-based duplicate index. +function _econReadRef(token, lineNo) { + let name, rest; + if (token.startsWith('"')) { + const end = _econFindCloseQuote(token, lineNo); + name = _econUnescape(token.slice(1, end)); + rest = token.slice(end + 1); + } else { + const m = token.match(/^([^#]*)(#\d+)?$/); + name = m ? m[1] : token; + rest = m && m[2] ? m[2] : ''; + } + let ord = 1; + if (rest) { + const m = rest.match(/^#(\d+)$/); + if (!m) throw _econErr(`bad reference suffix in ${token}`, lineNo); + ord = parseInt(m[1], 10); + } + return { name, ord }; +} + +function _econFindCloseQuote(token, lineNo) { + for (let i = 1; i < token.length; i++) { + if (token[i] === '\\') { i++; continue; } + if (token[i] === '"') return i; + } + throw _econErr(`unterminated string ${token}`, lineNo); +} + +// Split `key=value` (value may be quoted / JSON / parenthesized). Returns +// null when the token has no top-level `=`. +function _econSplitAttr(token) { + if (token.startsWith('"')) return null; + const i = token.indexOf('='); + if (i <= 0) return null; + const key = token.slice(0, i); + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null; + return { key, raw: token.slice(i + 1) }; +} + +// Split a comma-separated list at depth 0 (for recipe items, tracks, arrays). +function _econSplitList(s) { + const parts = []; + let cur = '', depth = 0, inQ = false; + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (inQ) { cur += ch; if (ch === '\\') { cur += s[++i] ?? ''; } else if (ch === '"') inQ = false; continue; } + if (ch === '"') { inQ = true; cur += ch; continue; } + if ('([{'.includes(ch)) depth++; + if (')]}'.includes(ch)) depth--; + if (ch === ',' && depth === 0) { parts.push(cur.trim()); cur = ''; continue; } + cur += ch; + } + if (cur.trim()) parts.push(cur.trim()); + return parts; +} + +function dslParse(text) { + const json = { + version: 1, + nodes: [], connections: [], groups: undefined, notes: undefined, charts: undefined, + resourceTypes: undefined, variables: {}, params: undefined, customVars: undefined, + timeMode: undefined, seed: undefined, aiPlayer: undefined, + meta: { name: '', description: '', bgColor: '', scheme: 'default', font: '', thumbnail: '', created: 0, modified: 0 }, + }; + const types = []; // {name, color} + const params = {}; + const customVars = []; + const groups = [], notes = [], charts = []; + const nodeRefs = new Map(); // "nameord" → node json + const nodeOrder = []; + const pendingConns = []; // resolved after all nodes are known + const pendingCharts = []; + + const colorOf = (tok, lineNo) => { + // A color reference: raw value (hex or anything else), or a declared + // resource-type name (bare or quoted). + const v = tok.startsWith('"') ? _econUnescape(tok.slice(1, -1)) : tok; + const t = types.find(t => t.name === v); + return t ? t.color : v; + }; + + const lines = String(text).split(/\r?\n/); + let sawAny = false; + + for (let li = 0; li < lines.length; li++) { + const lineNo = li + 1; + const rawLine = lines[li]; + // Rest-of-line directives are handled before tokenizing (their payload is + // free text, not tokens). + const trimmed = rawLine.trim(); + if (!trimmed || trimmed.startsWith('//')) continue; + const dm = trimmed.match(/^(name|desc|seed|timeMode)\s*:\s*(.*)$/); + if (dm) { + const v = dm[2].trim(); + if (dm[1] === 'name') json.meta.name = v; + else if (dm[1] === 'desc') json.meta.description = _econUnescape(v); + else if (dm[1] === 'seed') json.seed = v; + else if (dm[1] === 'timeMode') json.timeMode = v; + sawAny = true; + continue; + } + + const tokens = _econTokens(trimmed, lineNo); + if (!tokens.length) continue; + const head = tokens[0]; + sawAny = true; + + if (head === 'economy') continue; // version header; v1 is the only version + + if (head === 'meta') { + for (const t of tokens.slice(1)) { + const a = _econSplitAttr(t); + if (!a) throw _econErr(`meta expects key=value, got ${t}`, lineNo); + json.meta[a.key] = _econParseValue(a.raw, lineNo); + } + continue; + } + + if (head === 'param') { + // param name = value + const m = tokens.slice(1).join(' ').match(/^([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(.+)$/); + if (!m) throw _econErr(`param expects name = number`, lineNo); + const v = Number(m[2]); + if (!isFinite(v)) throw _econErr(`param ${m[1]} is not a number: ${m[2]}`, lineNo); + params[m[1]] = v; + continue; + } + + if (head === 'type') { + const m = tokens.slice(1).join(' ').match(/^(.+?)\s*=\s*(\S+)$/); + if (!m) throw _econErr(`type expects Name = #color`, lineNo); + const name = m[1].startsWith('"') ? _econUnescape(m[1].slice(1, -1)) : m[1]; + types.push({ name, color: m[2] }); + continue; + } + + if (head === 'var') { + const joined = tokens.slice(1).join(' '); + const m = joined.match(/^(.+?)\s*=\s*(interval|array|dice|math)\((.*)\)\s*(.*)$/); + if (!m) throw _econErr(`var expects name = kind(args)`, lineNo); + const name = m[1].startsWith('"') ? _econUnescape(m[1].slice(1, -1)) : m[1]; + const rv = { name, kind: m[2] === 'interval' ? 'interval' : m[2], dist: 'uniform', update: 'step' }; + if (m[2] === 'math') rv.formula = m[3].trim(); + else if (m[2] === 'dice') rv.dice = m[3].trim(); + else if (m[2] === 'array') rv.values = _econSplitList(m[3]).map(Number).filter(isFinite); + else { + const args = _econSplitList(m[3]).map(Number); + rv.min = isFinite(args[0]) ? args[0] : 0; + rv.max = isFinite(args[1]) ? args[1] : 0; + } + for (const t of (m[4] ? _econTokens(m[4], lineNo) : [])) { + if (t === 'gaussian') rv.dist = 'gaussian'; + else if (t === 'uniform') rv.dist = 'uniform'; + else { + const a = _econSplitAttr(t); + if (!a) throw _econErr(`unknown var modifier ${t}`, lineNo); + rv[a.key === 'per' ? 'update' : a.key] = _econParseValue(a.raw, lineNo); + } + } + customVars.push(rv); + continue; + } + + if (head === 'player') { + const p = { enabled: false, rules: [] }; + for (const t of tokens.slice(1)) { + if (t === 'enabled') { p.enabled = true; continue; } + const a = _econSplitAttr(t); + if (!a) throw _econErr(`player expects key=value or enabled, got ${t}`, lineNo); + p[a.key] = _econParseValue(a.raw, lineNo); + } + json.aiPlayer = p; + continue; + } + + if (head === 'group' || head === 'note' || head === 'chart') { + let i = 1; + const el = { kind: head, label: '', x: 0, y: 0, w: head === 'note' ? 160 : (head === 'chart' ? 240 : 200), h: head === 'note' ? 80 : (head === 'chart' ? 150 : 140) }; + if (head !== 'note' && tokens[i] && tokens[i].startsWith('"')) { el.label = _econUnescape(tokens[i].slice(1, -1)); i++; } + const rest = []; + for (; i < tokens.length; i++) { + const t = tokens[i]; + if (t === '@') { const p = (tokens[++i] || '').split(','); el.x = Number(p[0]); el.y = Number(p[1]); continue; } + const sz = t.match(/^(-?[\d.]+)x(-?[\d.]+)$/); + if (sz) { el.w = Number(sz[1]); el.h = Number(sz[2]); continue; } + rest.push(t); + } + for (const t of rest) { + if (t.startsWith('"') && head === 'note') { el.text = _econUnescape(t.slice(1, -1)); continue; } + const a = _econSplitAttr(t); + if (!a) throw _econErr(`unexpected token ${t}`, lineNo); + if (head === 'chart' && a.key === 'tracks') { el.tracks = _econSplitList(a.raw); continue; } + if (head === 'chart' && a.key === 'type') { el.chartType = String(_econParseValue(a.raw, lineNo)); continue; } + el[a.key] = _econParseValue(a.raw, lineNo); + } + if (head === 'group') groups.push(el); + else if (head === 'note') notes.push(el); + else { charts.push(el); pendingCharts.push({ el, lineNo }); } + continue; + } + + if (ECON_NODE_KINDS.includes(head)) { + const nd = _econParseNodeLine(head, tokens, lineNo, colorOf); + const key = nd.label + '' + nd._ord; + if (nodeRefs.has(key)) throw _econErr(`duplicate node reference ${nd.label}#${nd._ord}`, lineNo); + nodeRefs.set(key, nd); + nodeOrder.push(nd); + continue; + } + + // Connection line: -> … or ~> … + const arrowIdx = tokens.findIndex(t => t === '->' || t === '~>'); + if (arrowIdx > 0) { + pendingConns.push({ tokens, arrowIdx, lineNo }); + continue; + } + throw _econErr(`unrecognized line: ${trimmed.slice(0, 60)}`, lineNo); + } + + if (!sawAny) throw new Error('.econ: empty document'); + + // Assign deterministic ids and build the resolver. + const resolve = (refTok, lineNo) => { + const { name, ord } = _econReadRef(refTok, lineNo); + const nd = nodeRefs.get(name + '' + ord); + if (!nd) throw _econErr(`unknown node reference ${refTok}`, lineNo); + return nd.id; + }; + nodeOrder.forEach((nd, i) => { nd.id = 'n' + (i + 1); delete nd._ord; }); + + let connSeq = 0; + for (const { tokens, arrowIdx, lineNo } of pendingConns) { + if (arrowIdx !== 1) throw _econErr(`expected ${tokens[arrowIdx]} `, lineNo); + const cd = _econParseConnLine(tokens, arrowIdx, lineNo, resolve, colorOf); + cd.id = 'c' + (++connSeq); + // Canonicalize through the model class so default-suppressed fields come + // out exactly as the app itself would save them. + json.connections.push(new MConnection(cd.sourceId, cd.targetId, cd.type).loadJSON(cd).toJSON()); + } + + json.nodes = nodeOrder.map(nd => new MNode(nd.type, nd.x, nd.y).loadJSON(nd).toJSON()); + if (groups.length) json.groups = groups.map((g, i) => ({ id: 'g' + (i + 1), x: g.x, y: g.y, w: g.w, h: g.h, label: g.label || 'Group', color: g.color || '#4a9eff' })); + if (notes.length) json.notes = notes.map((n, i) => ({ id: 't' + (i + 1), x: n.x, y: n.y, w: n.w, h: n.h, text: n.text || '', color: n.color || '#f6e05e' })); + if (charts.length) { + json.charts = charts.map((c, i) => { + const d = { id: 'ch' + (i + 1), x: c.x, y: c.y, w: c.w, h: c.h, label: c.label || 'Chart', nodeIds: [] }; + if (c.chartType && c.chartType !== 'line') d.chartType = c.chartType; + return d; + }); + for (let i = 0; i < pendingCharts.length; i++) { + const { el, lineNo } = pendingCharts[i]; + const d = json.charts[charts.indexOf(el)]; + d.nodeIds = (el.tracks || []).map(r => resolve(r, lineNo)); + } + } + if (types.length) json.resourceTypes = types; + if (Object.keys(params).length) json.params = params; + if (customVars.length) json.customVars = customVars; + // Round through JSON text so the result carries no undefined-valued keys — + // the same shape a saved file would have after JSON.parse. + return JSON.parse(JSON.stringify(json)); +} + +function _econParseNodeLine(kind, tokens, lineNo, colorOf) { + const nd = new MNode(kind, 0, 0).toJSON(); + nd.id = ''; // assigned after all nodes parse + let i = 1; + if (i >= tokens.length) throw _econErr(`${kind} needs a name`, lineNo); + const ref = _econReadRef(tokens[i++], lineNo); + nd.label = ref.name; + nd._ord = ref.ord; + + while (i < tokens.length) { + const t = tokens[i]; + if (t === '@') { + const p = (tokens[++i] || '').split(','); + nd.x = Number(p[0]); nd.y = Number(p[1]); + if (!isFinite(nd.x) || !isFinite(nd.y)) throw _econErr(`bad position after @`, lineNo); + i++; + continue; + } + if (t === '=') { + const v = tokens[++i]; + if (v === undefined) throw _econErr(`= needs a value`, lineNo); + if (kind === 'register') { + if (v.startsWith('"')) nd.formula = _econUnescape(v.slice(1, -1)); + else nd.value = Number(v); + } else { + const amount = Number(v); + if (!isFinite(amount)) throw _econErr(`bad start amount ${v}`, lineNo); + nd.resources = amount; + let color = kind === 'source' ? null : DEFAULT_COLOR; + if (tokens[i + 1] === 'of') { color = colorOf(tokens[i + 2] || '', lineNo); i += 2; } + if (kind !== 'source' && amount > 0) nd.colorMap = { [color]: amount }; + } + i++; + continue; + } + if (t === 'goal') { + nd.endEnabled = true; + nd.endOperator = tokens[++i] || '>='; + nd.endValue = Number(tokens[++i] || 0); + i++; + continue; + } + if (t.startsWith('recipe(') && kind === 'converter') { + const inner = t.slice('recipe('.length, -1); + nd.inputRecipe = _econSplitList(inner).map(item => { + const m = item.match(/^([\d.]+)\s+(.+)$/); + if (!m) throw _econErr(`recipe item "${item}" expects: amount color`, lineNo); + return { color: colorOf(m[2].trim(), lineNo), amount: Number(m[1]) }; + }); + i++; + continue; + } + if (ECON_ACTIVATIONS.includes(t)) { nd.activation = t; i++; continue; } + if (t === 'pull') { nd.flowMode = 'pull'; i++; continue; } + if (t === 'limited' && kind === 'source') { nd.limited = true; i++; continue; } + const a = _econSplitAttr(t); + if (!a) throw _econErr(`unexpected token ${t}`, lineNo); + if (a.key === 'pull') { nd.flowMode = 'pull'; nd.pullPolicy = String(_econParseValue(a.raw, lineNo)); i++; continue; } + const key = ECON_NODE_ALIAS[a.key] || a.key; + let val = _econParseValue(a.raw, lineNo); + if (key === 'resourceColor' || key === 'outputColor') val = colorOf(a.raw, lineNo); + nd[key] = val; + i++; + } + // Sources keep their stock in `resources` only when limited; the JSON shape + // mirrors MNode.toJSON (resources 0 for unlimited). + if (kind === 'source' && !nd.limited) nd.resources = 0; + return nd; +} + +function _econParseConnLine(tokens, arrowIdx, lineNo, resolve, colorOf) { + const type = tokens[arrowIdx] === '~>' ? 'state' : 'resource'; + const cd = new MConnection('', '', type).toJSON(); + cd.sourceId = resolve(tokens[0], lineNo); + cd.targetId = resolve(tokens[arrowIdx + 1], lineNo); + + let i = arrowIdx + 2; + // Rate clause: `: ` + if (tokens[i] === ':') { + const r = tokens[++i]; + if (r === undefined) throw _econErr(`rate expected after :`, lineNo); + if (/^\d+\s*d\s*\d+$/i.test(r)) { cd.rateMode = 'dice'; cd.dice = r.toLowerCase(); } + else if (r.startsWith('(') && r.endsWith(')')) { cd.rateMode = 'formula'; cd.formula = r.slice(1, -1).trim(); } + else if (r.startsWith('~')) { + const m = r.match(/^~([a-z]+)\((.*)\)$/i); + if (!m) throw _econErr(`bad distribution rate ${r}`, lineNo); + cd.rateMode = 'distribution'; + cd.distType = m[1].toLowerCase(); + const args = _econSplitList(m[2]).map(Number); + if (isFinite(args[0])) cd.distParam1 = args[0]; + if (isFinite(args[1])) cd.distParam2 = args[1]; + } else { + const n = Number(r); + if (!isFinite(n)) throw _econErr(`bad rate ${r}`, lineNo); + cd.rateMode = 'fixed'; cd.rate = n; + } + i++; + } + + for (; i < tokens.length; i++) { + const t = tokens[i]; + const pct = t.match(/^([\d.]+)%$/); + if (pct) { cd.chance = Number(pct[1]); continue; } + if (t === 'trigger') { cd.trigger = true; continue; } + if (t === 'reverseTrigger') { cd.reverseTrigger = true; continue; } + const a = _econSplitAttr(t); + if (!a) throw _econErr(`unexpected token ${t}`, lineNo); + const raw = a.raw; + if (a.key === 'if') { + const s = String(_econParseValue(raw, lineNo)); + const m = s.match(/^(\S+)\s+(\S+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?$/); + if (!m) throw _econErr(`if expects " [n2]"`, lineNo); + cd.condEnabled = true; + cd.condOperator = m[2]; + cd.condValue = Number(m[3]); + if (m[4] !== undefined) cd.condValue2 = Number(m[4]); + if (m[1] !== 'self') { cd.condRefMode = 'variable'; cd.condVariable = m[1]; } + continue; + } + if (a.key === 'act') { + const s = String(_econParseValue(raw, lineNo)); + const m = s.match(/^(\S+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?$/); + if (!m) throw _econErr(`act expects " [n2]"`, lineNo); + cd.activator = true; + cd.actOperator = m[1]; + cd.actValue = Number(m[2]); + if (m[3] !== undefined) cd.actValue2 = Number(m[3]); + continue; + } + if (a.key === 'mod') { + const s = String(_econParseValue(raw, lineNo)); + const m = s.match(/^(step|pulse|delta|rate)\s+(.+)$/); + if (!m) throw _econErr(`mod expects " "`, lineNo); + cd.modifier = true; + cd.modMode = m[1]; + const amt = m[2].trim(); + if (amt.startsWith('(') && amt.endsWith(')')) cd.modFormula = amt.slice(1, -1).trim(); + else { + const n = Number(amt); + if (!isFinite(n)) throw _econErr(`bad mod amount ${amt}`, lineNo); + cd.modFactor = n; + } + continue; + } + if (a.key === 'weight' && raw.startsWith('(') && raw.endsWith(')')) { + cd.weightFormula = raw.slice(1, -1).trim(); + continue; + } + if (a.key === 'color') { cd.colorFilter = colorOf(raw, lineNo); continue; } + const key = ECON_CONN_ALIAS[a.key] || a.key; + cd[key] = _econParseValue(raw, lineNo); + } + return cd; +} + +// ── Normalization ─────────────────────────────────────────────────────────── +// Canonical form for comparing two diagram JSONs "as economies": runtime and +// cosmetic-noise fields are dropped and every id is renamed to its positional +// form, so JSON saved from the app compares equal to the same economy parsed +// back from .econ text. Used by the round-trip tests and handy for diffing. + +function normalizeEconJSON(json) { + const src = JSON.parse(JSON.stringify(json)); + const idMap = new Map(); + (src.nodes || []).forEach((n, i) => idMap.set(n.id, 'n' + (i + 1))); + (src.connections || []).forEach((c, i) => idMap.set(c.id, 'c' + (i + 1))); + (src.groups || []).forEach((g, i) => idMap.set(g.id, 'g' + (i + 1))); + (src.notes || []).forEach((n, i) => idMap.set(n.id, 't' + (i + 1))); + (src.charts || []).forEach((c, i) => idMap.set(c.id, 'ch' + (i + 1))); + const mapId = id => idMap.get(id) || id; + + const out = { + version: 1, + nodes: (src.nodes || []).map(n => { + const d = { ...n, id: mapId(n.id) }; + for (const k of Object.keys(d)) if (d[k] === undefined) delete d[k]; + // A held amount with no color breakdown is runtime-equivalent to the + // same amount in the default color (reconcile() assigns it on first + // touch); canonicalize so both spellings compare equal. + if (d.resources > 0 && isFinite(d.resources) + && (!d.colorMap || JSON.stringify(d.colorMap) === JSON.stringify({ [DEFAULT_COLOR]: d.resources }))) { + d.colorMap = { [DEFAULT_COLOR]: d.resources }; + } + return d; + }), + connections: (src.connections || []).map(c => { + const d = { ...c, id: mapId(c.id), sourceId: mapId(c.sourceId), targetId: mapId(c.targetId) }; + for (const k of Object.keys(d)) if (d[k] === undefined) delete d[k]; + return d; + }), + }; + if ((src.groups || []).length) out.groups = src.groups.map(g => ({ ...g, id: mapId(g.id) })); + if ((src.notes || []).length) out.notes = src.notes.map(n => ({ ...n, id: mapId(n.id) })); + if ((src.charts || []).length) out.charts = src.charts.map(c => ({ ...c, id: mapId(c.id), nodeIds: (c.nodeIds || []).map(mapId) })); + if ((src.resourceTypes || []).length) out.resourceTypes = src.resourceTypes; + if (src.params && Object.keys(src.params).length) out.params = src.params; + if ((src.customVars || []).length) out.customVars = src.customVars.map(rv => { const d = { ...rv }; delete d.value; return d; }); + if (src.timeMode && src.timeMode !== 'sync') out.timeMode = src.timeMode; + if (src.seed) out.seed = String(src.seed); + if (src.aiPlayer && (src.aiPlayer.rules || []).length) out.aiPlayer = src.aiPlayer; + const m = src.meta || {}; + const meta = {}; + if (m.name) meta.name = m.name; + if (m.description) meta.description = m.description; + if (m.bgColor) meta.bgColor = m.bgColor; + if (m.scheme && m.scheme !== 'default') meta.scheme = m.scheme; + if (m.font) meta.font = m.font; + if (Object.keys(meta).length) out.meta = meta; + // Canonical key order everywhere, so comparisons are order-insensitive + // (arrays keep their order; it is semantic). + return _econSortKeys(out); +} + +function _econSortKeys(v) { + if (Array.isArray(v)) return v.map(_econSortKeys); + if (v && typeof v === 'object') { + const out = {}; + for (const k of Object.keys(v).sort()) out[k] = _econSortKeys(v[k]); + return out; + } + return v; +} diff --git a/js/engine.js b/js/engine.js index 4958c33..ec7a28d 100644 --- a/js/engine.js +++ b/js/engine.js @@ -1335,7 +1335,10 @@ class SimEngine { // final value plus goal statistics. Does not touch the live diagram. // opts: { seed (string — makes the whole batch reproducible), // baseJSON (diagram JSON to simulate instead of the live one — used - // by parameter sweeps to vary params without touching the diagram) } + // by parameter sweeps to vary params without touching the diagram), + // perStep(engine, run) (called on each trial's engine right after + // reset and again after every step — assertion checking hook), + // onTrialEnd(engine, run) (called when a trial finishes) } runMonteCarlo(runs = 100, maxSteps = 200, opts = {}) { const job = this._mcTrials(runs, maxSteps, opts); let r = job.next(); @@ -1395,8 +1398,13 @@ class SimEngine { dg.seed = seeded ? `${opts.seed}#${r}` : ''; const eng = new SimEngine(dg); eng.reset(); + if (opts.perStep) opts.perStep(eng, r); let s = 0; - while (s < maxSteps && !eng.ended) { eng.doStep(); s++; } + while (s < maxSteps && !eng.ended) { + eng.doStep(); s++; + if (opts.perStep) opts.perStep(eng, r); + } + if (opts.onTrialEnd) opts.onTrialEnd(eng, r); for (const [id, arr] of samples) { const n = dg.nodes.get(id); arr.push(n ? n.chartValue : 0); diff --git a/js/kb.js b/js/kb.js index 536f8a2..945088f 100644 --- a/js/kb.js +++ b/js/kb.js @@ -700,6 +700,53 @@ const KB_ARTICLES = [ + 'options in the File menu export a snapshot of the canvas for use outside ' + 'the app.', }, + + // ── Economy as code ───────────────────────────────────────────────────────── + { + id: 'econ-text', category: 'Economy as code', title: 'Text format (.econ)', + keywords: 'dsl text code diff git version control readable import export round trip convert', + body: 'Save as text in the File menu writes the diagram as a .econ file, a ' + + 'readable line-based format where every node, connection and setting is ' + + 'one line of text. Because it is plain text, an economy can live in ' + + 'version control next to your game code: diffs show exactly which rate ' + + 'or capacity changed, and edits work in any editor. Open file reads ' + + '.econ files back onto the canvas, and nothing is lost in the round ' + + 'trip. A quick taste: "source Mine @ 80,100" declares a node and ' + + '"Mine -> Gold : 2" connects it to a pool at rate 2. The command line ' + + 'converts both ways with node cli.js diagram.json --to-dsl and ' + + '--to-json.', + }, + { + id: 'econ-assert', category: 'Economy as code', title: 'Assertions', + keywords: 'test ci check invariant always never eventually at end step regression balance guard', + body: 'Assertions are checks that run against a simulation from the command ' + + 'line, so a balance change that breaks your economy fails loudly in CI ' + + 'instead of silently shipping. Write them as a quantifier plus a ' + + 'formula: "always gold < 500" must hold at every step, "never wood == 0" ' + + 'is its opposite, "eventually score >= 100" must become true at some ' + + 'step, and "at step 25: queue <= 3" or a bare "widgets > 50" (checked ' + + 'at the end) pin down a moment. Node labels are the identifiers, with ' + + 'spaces turned into underscores, and diagram variables and step are in ' + + 'scope too. Run node cli.js economy.json --assert "always gold < 500"; ' + + 'a failing check exits with code 2. With --runs the assertions check ' + + 'every Monte Carlo trial, and --pass-rate 95 tolerates rare unlucky ' + + 'runs.', + }, + { + id: 'econ-module', category: 'Economy as code', title: 'Export as JS module', + keywords: 'codegen standalone javascript embed ship game engine module npm node dependency free', + body: 'Export as JS module in the File menu compiles the current diagram, ' + + 'the simulation engine and a small API into one dependency-free ' + + 'JavaScript file. Drop that file into your game or tool and the ' + + 'balanced economy you designed here is the economy you ship, not a ' + + 'reimplementation of it. The module works in Node and the browser: ' + + 'createEconomy() returns a handle with step(), run(), get(), set(), ' + + 'fire() for interactive nodes, values() and onStep(), plus seed and ' + + 'parameter overrides. The same file comes out of the command line with ' + + 'node cli.js economy.json --emit economy.module.js. Formulas use ' + + 'math.js when a global math object is present and fall back to plain ' + + 'JS expressions otherwise.', + }, ]; // Expose for non-module browser scripts and the headless test harness. diff --git a/package.json b/package.json index 18b67b5..9c13538 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "simulations", "private": true, + "license": "AGPL-3.0-only", "scripts": { "test": "node test/run.js", "smoke": "node test/smoke.js" diff --git a/test/run.js b/test/run.js index 8eb98a7..8b82ab3 100644 --- a/test/run.js +++ b/test/run.js @@ -21,8 +21,12 @@ function loadEngine() { const src = fs.readFileSync(path.join(base, 'model.js'), 'utf8') + '\n' + fs.readFileSync(path.join(base, 'engine.js'), 'utf8') + '\n' + + fs.readFileSync(path.join(base, 'dsl.js'), 'utf8') + '\n' + + fs.readFileSync(path.join(base, 'assertions.js'), 'utf8') + '\n' + + fs.readFileSync(path.join(base, 'codegen.js'), 'utf8') + '\n' + 'return { NodeType, ConnectionType, ActivationMode, RateMode, DEFAULT_COLOR,' + - ' MNode, MConnection, MGroup, MNote, MChart, Diagram, SimEngine, evalFormula, rollDice, dominantColor, sampleDist, sampleCustomVar, validateFormula, SimRandom };'; + ' MNode, MConnection, MGroup, MNote, MChart, Diagram, SimEngine, evalFormula, rollDice, dominantColor, sampleDist, sampleCustomVar, validateFormula, SimRandom,' + + ' dslSerialize, dslParse, normalizeEconJSON, parseAssertion, AssertionChecker, assertionScope, buildEconomyModule };'; // eslint-disable-next-line no-new-func return new Function(src)(); } @@ -31,6 +35,7 @@ const API = loadEngine(); const { NodeType, ConnectionType, ActivationMode, RateMode, DEFAULT_COLOR, MNode, MConnection, MGroup, MNote, MChart, Diagram, SimEngine, evalFormula, rollDice, sampleDist, sampleCustomVar, validateFormula, SimRandom, + dslSerialize, dslParse, normalizeEconJSON, parseAssertion, AssertionChecker, assertionScope, buildEconomyModule, } = API; // ── Tiny test harness ─────────────────────────────────────────────────────── @@ -2783,6 +2788,355 @@ testAsync('runMonteCarloAsync completes normally without a cancel signal', async eq(pn.mean, 50, 'async batch matches the deterministic mean'); }); +// ── Economy as code: .econ text format ────────────────────────────────────── +console.log('\nEconomy as code: .econ text format'); + +// A diagram exercising every serializable feature at once. Used by the +// round-trip tests; extend it whenever a new field is added to the model so +// the DSL keeps covering everything. +function kitchenSink() { + const d = new Diagram(); + d.meta.name = 'Kitchen Sink'; + d.meta.description = 'Every feature.\nSecond line.'; + d.meta.scheme = 'ocean'; d.meta.bgColor = '#101318'; d.meta.font = 'Space Grotesk'; + d.seed = 'abc'; + d.timeMode = 'async'; + d.params = { mine_rate: 3, tax: 0.25 }; + d.resourceTypes = [{ name: 'Wood', color: '#8d6e63' }, { name: 'Iron Ore', color: '#b0bec5' }]; + d.customVars = [ + { name: 'luck', kind: 'dice', dice: '2d6', dist: 'gaussian', update: 'step', value: 0 }, + { name: 'span', kind: 'interval', min: 1, max: 10, dist: 'uniform', update: 'play', value: 0 }, + { name: 'pick', kind: 'array', values: [1, 2, 3], dist: 'uniform', update: 'step', value: 0 }, + { name: 'calc', kind: 'math', formula: 'gold * 2', dist: 'uniform', update: 'step', value: 0 }, + ]; + d.aiPlayer = { enabled: true, rules: [{ nodeId: 'x', every: 3, condVar: 'gold', condOp: '>', condVal: 5 }] }; + + const mk = (t, x, y, label) => { const n = new MNode(t, x, y); n.label = label; return d.addNode(n); }; + const pool = mk(NodeType.POOL, 100, 100, 'Gold'); pool.setCount(50, '#ffd54f'); pool.capacity = 500; + pool.endEnabled = true; pool.endOperator = '>='; pool.endValue = 400; + const pool2 = mk(NodeType.POOL, 100, 200, 'Gold'); // duplicate label on purpose + pool2.flowMode = 'pull'; pool2.pullPolicy = 'all'; pool2.activation = 'passive'; + const multi = mk(NodeType.POOL, 100, 300, 'Mixed Bag'); + multi.resources = 30; multi.colorMap = { '#ff0000': 10, '#00ff00': 20 }; + const src1 = mk(NodeType.SOURCE, 0, 100, 'Mine'); src1.resourceColor = '#8d6e63'; + const src2 = mk(NodeType.SOURCE, 0, 200, 'Well'); src2.limited = true; src2.resources = 40; src2.fireEvery = 3; src2.firePhase = 1; + const drain = mk(NodeType.DRAIN, 300, 100, 'Spend'); + const gate = mk(NodeType.GATE, 300, 200, 'Split'); gate.gateMode = 'probabilistic'; + const conv = mk(NodeType.CONVERTER, 300, 300, 'Forge'); conv.inputAmount = 2; + conv.inputRecipe = [{ color: '#8d6e63', amount: 2 }, { color: '#b0bec5', amount: 1 }]; + const reg = mk(NodeType.REGISTER, 500, 100, 'Score'); reg.formula = 'gold * 2 + luck'; + const reg2 = mk(NodeType.REGISTER, 500, 150, 'Manual'); reg2.value = 7; + const delay = mk(NodeType.DELAY, 500, 200, 'Ship'); delay.delay = 4; + const q = mk(NodeType.QUEUE, 500, 300, 'Desk'); q.processTime = 3; q.servers = 2; q.maxLine = 10; q.patience = 5; + const trader = mk(NodeType.TRADER, 700, 100, 'Swap'); trader.activation = 'interactive'; + + const c = (a, b, t) => d.addConnection(new MConnection(a.id, b.id, t)); + const c1 = c(src1, pool); c1.rate = 2; c1.interval = 3; c1.chance = 40; + c1.condEnabled = true; c1.condOperator = 'between'; c1.condValue = 2; c1.condValue2 = 8; + const c2 = c(pool, drain); c2.rateMode = RateMode.DICE; c2.dice = '2d6'; c2.colorFilter = '#ffd54f'; + const c3 = c(pool, gate); c3.rateMode = RateMode.FORMULA; c3.formula = 'mine_rate * 2'; + const c4 = c(gate, conv); c4.rateMode = RateMode.DISTRIBUTION; c4.distType = 'poisson'; c4.distParam1 = 3; + c4.weight = 3; c4.pathStyle = 'ortho'; c4.bendPct = 0.3; c4.waypoints = [{ x: 1, y: 2 }, { x: 3, y: 4 }]; + const c5 = c(gate, delay); c5.weightFormula = 'luck * 2'; c5.labelT = 0.25; c5.label = 'lucky path'; + const c6 = c(pool, reg, ConnectionType.STATE); c6.variableName = 'gold'; + const c7 = c(reg, conv, ConnectionType.STATE); c7.activator = true; c7.actOperator = 'between'; c7.actValue = 1; c7.actValue2 = 99; + const c8 = c(src1, trader, ConnectionType.STATE); c8.trigger = true; c8.triggerChance = 50; c8.triggerEvery = 2; + const c9 = c(drain, pool2, ConnectionType.STATE); c9.reverseTrigger = true; + const c10 = c(reg, pool2, ConnectionType.STATE); c10.modifier = true; c10.modMode = 'delta'; c10.modFactor = 2; + const c11 = c(reg2, multi, ConnectionType.STATE); c11.modifier = true; c11.modFormula = 'round(score * 0.1)'; + const c12 = c(pool2, drain); c12.condEnabled = true; c12.condRefMode = 'variable'; c12.condVariable = 'gold'; + c12.condOperator = '>'; c12.condValue = 5; c12.cpDx = 10; c12.cpDy = -20; + + d.addGroup(Object.assign(new MGroup(50, 50, 400, 300), { label: 'Economy Core', color: '#7cb342' })); + d.addNote(Object.assign(new MNote(600, 50), { text: 'Note with "quotes" and\nnewline' })); + const ch = new MChart(700, 300); ch.label = 'Gold over time'; ch.nodeIds = [pool.id, pool2.id]; ch.chartType = 'area'; + d.addChart(ch); + return d; +} + +test('kitchen-sink diagram round-trips through .econ text', () => { + const json1 = kitchenSink().toJSON(); + const json2 = dslParse(dslSerialize(json1)); + const a = JSON.stringify(normalizeEconJSON(json1)); + const b = JSON.stringify(normalizeEconJSON(json2)); + eq(b, a, 'normalized JSON identical after text round trip'); +}); + +test('serialize∘parse is a fixpoint on .econ text', () => { + const t1 = dslSerialize(kitchenSink().toJSON()); + const t2 = dslSerialize(dslParse(t1)); + eq(t2, t1, 'second serialization byte-identical'); +}); + +test('parsed .econ loads into a Diagram and simulates', () => { + const json = dslParse([ + 'name: Terse Mine', + 'param rate = 2', + 'source Mine @ 80,100', + 'pool Gold @ 240,100 goal >= 19', + 'drain Spend @ 400,100', + 'Mine -> Gold : (rate)', + 'Gold -> Spend : 1', + ].join('\n')); + const d = new Diagram(); d.loadJSON(json); + const e = new SimEngine(d); + e.reset(); + for (let i = 0; i < 50 && !e.ended; i++) e.doStep(); + assert(e.ended, 'goal reached'); + eq(e.ended.step, 18, 'net +1 per step after the first reaches 19 at step 18'); +}); + +test('.econ sugar: recipes, types, colors, conditions, distributions', () => { + const json = dslParse([ + 'type Wood = #8d6e63', + 'source Lumber @ 0,0 color=Wood', + 'pool Store @ 100,0 = 5 of Wood cap=50', + 'converter Mill @ 200,0 recipe(2 Wood, 1 #b0bec5) out=#ffa726', + 'queue Line @ 300,0 time=3 servers=2', + 'Lumber -> Store : ~poisson(3, 2) 40% every=2 if="self < 40"', + 'Store -> Mill : 2d6 color=Wood', + ].join('\n')); + const src = json.nodes.find(n => n.label === 'Lumber'); + eq(src.resourceColor, '#8d6e63', 'type name resolved to color'); + const store = json.nodes.find(n => n.label === 'Store'); + eq(store.capacity, 50, 'cap alias'); + eq(store.colorMap['#8d6e63'], 5, 'start amount typed by name'); + const mill = json.nodes.find(n => n.label === 'Mill'); + eq(mill.inputRecipe.length, 2, 'recipe parsed'); + eq(mill.inputRecipe[0].color, '#8d6e63', 'recipe type name resolved'); + eq(mill.outputColor, '#ffa726', 'out alias'); + const line = json.nodes.find(n => n.label === 'Line'); + eq(line.processTime, 3, 'time alias'); eq(line.servers, 2, 'servers kept'); + const c1 = json.connections[0]; + eq(c1.rateMode, 'distribution', 'distribution rate'); + eq(c1.distType, 'poisson', 'dist type'); eq(c1.distParam1, 3, 'dist p1'); + eq(c1.chance, 40, 'percent token'); eq(c1.interval, 2, 'every alias'); + assert(c1.condEnabled, 'if enables condition'); eq(c1.condOperator, '<', 'cond op'); + const c2 = json.connections[1]; + eq(c2.rateMode, 'dice', 'dice rate'); eq(c2.colorFilter, '#8d6e63', 'color filter via type'); +}); + +test('.econ duplicate labels disambiguate with #N and resolve back', () => { + const d = new Diagram(); + const a = d.addNode(new MNode(NodeType.POOL, 0, 0)); a.label = 'Gold'; + const b = d.addNode(new MNode(NodeType.POOL, 10, 0)); b.label = 'Gold'; + d.addConnection(new MConnection(a.id, b.id)); + const text = dslSerialize(d.toJSON()); + assert(text.includes('Gold#2'), 'second Gold gets a #2 suffix'); + const back = dslParse(text); + eq(back.connections[0].sourceId, back.nodes[0].id, 'first Gold resolved'); + eq(back.connections[0].targetId, back.nodes[1].id, '#2 resolved to second node'); +}); + +test('.econ parse errors carry the line number', () => { + let threw = null; + try { dslParse('pool A @ 0,0\n???'); } catch (e) { threw = e; } + assert(threw, 'throws on garbage'); + eq(threw.line, 2, 'line number attached'); + assert(/line 2/.test(threw.message), 'message names the line'); + threw = null; + try { dslParse('A -> B : 1'); } catch (e) { threw = e; } + assert(threw && /unknown node reference/.test(threw.message), 'unknown ref reported'); +}); + +// ── Economy as code: assertions ───────────────────────────────────────────── +console.log('\nEconomy as code: assertions'); + +function assertRig() { + const { d, e } = setup(); + const s = node(d, NodeType.SOURCE); s.label = 'Mine'; + const p = node(d, NodeType.POOL); p.label = 'Gold Pool'; + conn(d, s, p).rate = 2; + return { d, e, p }; +} + +function runChecked(e, srcs, steps) { + const checker = new AssertionChecker(srcs.map(parseAssertion)); + e.reset(); + checker.check(e); + for (let i = 0; i < steps && !e.ended; i++) { e.doStep(); checker.check(e); } + return checker.finish(e); +} + +test('parseAssertion understands every quantifier form', () => { + eq(parseAssertion('always x > 1').quant, 'always', 'always'); + eq(parseAssertion('never x > 1').quant, 'never', 'never'); + eq(parseAssertion('eventually x > 1').quant, 'eventually', 'eventually'); + eq(parseAssertion('at end: x > 1').quant, 'end', 'at end'); + eq(parseAssertion('at step 25: x > 1').quant, 'step', 'at step'); + eq(parseAssertion('at step 25: x > 1').atStep, 25, 'step number'); + eq(parseAssertion('x > 1').quant, 'end', 'bare expression defaults to end'); + eq(parseAssertion('always: x > 1').expr, 'x > 1', 'optional colon'); + let threw = false; + try { parseAssertion('always +++'); } catch { threw = true; } + assert(threw, 'rejects an unparseable expression'); +}); + +test('always reports the first violating step; never is its inverse', () => { + const { e } = assertRig(); + const res = runChecked(e, ['always Gold_Pool < 5', 'never Gold_Pool >= 5'], 10); + assert(!res[0].pass, 'always fails'); + eq(res[0].failStep, 3, 'first violation at step 3 (2/step: 6 >= 5)'); + assert(!res[1].pass, 'never fails at the same step'); + eq(res[1].failStep, 3, 'same step'); +}); + +test('eventually, at end and at step semantics', () => { + const { e } = assertRig(); + const res = runChecked(e, [ + 'eventually Gold_Pool >= 10', + 'at end: Gold_Pool == 20', + 'at step 4: Gold_Pool == 8', + 'at step 99: Gold_Pool > 0', + 'Gold_Pool == 20', + ], 10); + assert(res[0].pass, 'eventually met'); + assert(/step 5/.test(res[0].detail), 'reports first-true step'); + assert(res[1].pass, 'at end true'); + assert(res[2].pass, 'at step 4 true'); + assert(!res[3].pass, 'step beyond run length fails'); + assert(/before step 99/.test(res[3].detail), 'explains the short run'); + assert(res[4].pass, 'bare expression checked at end'); +}); + +test('assertion scope: sanitized labels, duplicates, variables, step', () => { + const { d, e } = setup(); + const a = node(d, NodeType.POOL); a.label = 'My Gold!'; a.setCount(7); + const b = node(d, NodeType.POOL); b.label = 'My Gold!'; b.setCount(3); + d.params = { bonus: 5 }; + e.reset(); + const scope = assertionScope(e); + eq(scope.My_Gold, 7, 'label sanitized to identifier'); + eq(scope.My_Gold_2, 3, 'duplicate label suffixed'); + eq(scope.bonus, 5, 'params visible via variables'); + eq(scope.step, 0, 'step in scope'); +}); + +test('Monte Carlo perStep/onTrialEnd hooks check every trial', () => { + const { d, e } = setup(); + const s = node(d, NodeType.SOURCE); + const p = node(d, NodeType.POOL); p.label = 'P'; + conn(d, s, p).rate = 1; + const parsed = [parseAssertion('at end: P == 5')]; + const checkers = new Map(); + const results = []; + e.runMonteCarlo(4, 5, { + perStep: (eng, r) => { + if (!checkers.has(r)) checkers.set(r, new AssertionChecker(parsed)); + checkers.get(r).check(eng); + }, + onTrialEnd: (eng, r) => { results[r] = checkers.get(r).finish(eng); }, + }); + eq(results.length, 4, 'one result set per trial'); + assert(results.every(rs => rs[0].pass), 'assertion holds in every trial'); +}); + +// ── Economy as code: generated module ─────────────────────────────────────── +console.log('\nEconomy as code: generated module'); + +function buildTestModule(diagramJSON) { + const base = path.join(__dirname, '..', 'js'); + const src = buildEconomyModule(diagramJSON, + fs.readFileSync(path.join(base, 'model.js'), 'utf8'), + fs.readFileSync(path.join(base, 'engine.js'), 'utf8'), + { generator: 'test/run.js' }); + const mod = { exports: {} }; + // eslint-disable-next-line no-new-func + new Function('module', 'exports', src)(mod, mod.exports); + return mod.exports; +} + +test('generated module simulates the embedded economy', () => { + const { d } = setup(); + const s = node(d, NodeType.SOURCE); s.label = 'Mine'; + const p = node(d, NodeType.POOL); p.label = 'Gold'; + conn(d, s, p).rate = 2; + const Economy = buildTestModule(d.toJSON()); + const eco = Economy.createEconomy(); + eco.run(10); + eq(eco.get('Gold'), 20, 'module run matches the engine'); + eq(eco.t, 10, 'clock advanced'); + eq(eco.values().Gold, 20, 'values() maps labels'); + eco.reset(); + eq(eco.t, 0, 'reset rewinds'); + eq(eco.get('Gold'), 0, 'reset restores the baseline'); +}); + +test('generated module honors seed and param overrides deterministically', () => { + const { d } = setup(); + const s = node(d, NodeType.SOURCE); s.label = 'Mine'; + const p = node(d, NodeType.POOL); p.label = 'Gold'; + const c1 = conn(d, s, p); c1.rateMode = RateMode.DICE; c1.dice = '1d6'; + d.params = { level: 1 }; + const Economy = buildTestModule(d.toJSON()); + const runOnce = () => Economy.createEconomy({ seed: 'k', params: { level: 4 } }).run(20).get('Gold'); + const a = runOnce(), b = runOnce(); + eq(a, b, 'same seed, same result'); + const eco = Economy.createEconomy({ params: { level: 4 } }); + eq(eco.diagram.params.level, 4, 'param override applied'); + const other = Economy.createEconomy({ seed: 'different-seed' }).run(20).get('Gold'); + assert(typeof other === 'number', 'other seed still simulates'); +}); + +test('generated module set() and fire() manipulate the live run', () => { + const { d } = setup(); + const p = node(d, NodeType.POOL); p.label = 'Gold'; p.setCount(5); + const dr = node(d, NodeType.DRAIN); dr.label = 'Sink'; + const btn = node(d, NodeType.POOL); btn.label = 'Buy'; btn.activation = ActivationMode.INTERACTIVE; + conn(d, p, dr).rate = 1; + const Economy = buildTestModule(d.toJSON()); + const eco = Economy.createEconomy(); + eco.set('Gold', 100); + eq(eco.get('Gold'), 100, 'set() writes a pool'); + let threw = false; + try { eco.set('Sink', 1); } catch { threw = true; } + assert(threw, 'set() rejects a drain'); + eco.fire('Buy'); // interactive node fires without throwing + let steps = 0; + eco.onStep(() => steps++); + eco.step(3); + eq(steps, 3, 'onStep callback saw each step'); +}); + +// ── Economy as code: CLI end-to-end ───────────────────────────────────────── +console.log('\nEconomy as code: CLI'); + +test('cli runs .econ input, checks assertions and converts formats', () => { + const { execFileSync } = require('child_process'); + const os = require('os'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'econ-test-')); + const econPath = path.join(dir, 'mine.econ'); + fs.writeFileSync(econPath, [ + 'name: CLI Mine', + 'source Mine @ 0,0', 'pool Gold @ 100,0', 'drain Spend @ 200,0', + 'Mine -> Gold : 2', 'Gold -> Spend : 1', + ].join('\n')); + const cli = path.join(__dirname, '..', 'cli.js'); + const run = (args) => { + try { return { out: execFileSync(process.execPath, [cli, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }), code: 0 }; } + catch (e) { return { out: String(e.stdout || ''), err: String(e.stderr || ''), code: e.status }; } + }; + const ok = run([econPath, '--steps', '10', '--assert', 'always Gold <= 11', '--assert', 'eventually Gold >= 5']); + eq(ok.code, 0, 'passing assertions exit 0'); + const bad = run([econPath, '--steps', '10', '--assert', 'always Gold < 5']); + eq(bad.code, 2, 'failing assertion exits 2'); + assert(/violated at step/.test(bad.err), 'failure detail printed'); + const dsl = run([econPath, '--to-dsl']); + assert(/Mine -> Gold : 2/.test(dsl.out), '--to-dsl emits .econ text'); + const jsonOut = run([econPath, '--to-json']); + const parsed = JSON.parse(jsonOut.out); + eq(parsed.nodes.length, 3, '--to-json emits loadable JSON'); + // First step nets +2 (the pool has nothing to drain yet), then +1 per step. + const mc = run([econPath, '--steps', '10', '--runs', '5', '--seed', '1', '--assert', 'at end: Gold == 11']); + eq(mc.code, 0, 'Monte Carlo assertions pass across trials'); + const emitPath = path.join(dir, 'eco.module.js'); + const emit = run([econPath, '--emit', emitPath]); + eq(emit.code, 0, '--emit exits 0'); + const Economy = require(emitPath); + eq(Economy.createEconomy().run(10).get('Gold'), 11, 'emitted module simulates'); + fs.rmSync(dir, { recursive: true, force: true }); +}); + // ── Results ───────────────────────────────────────────────────────────────── (async () => { if (asyncTests.length) console.log('\nAsync engine API'); diff --git a/test/smoke.js b/test/smoke.js index 8a982ba..c2ef70b 100644 --- a/test/smoke.js +++ b/test/smoke.js @@ -1339,6 +1339,39 @@ const URL = process.env.SMOKE_URL || 'http://localhost:8080/'; ok('P3 share: diagram encodes to a URL hash and decodes back'); else fail('P3 share: ' + JSON.stringify(p3share)); + // Economy as code: .econ round trip in-page, module codegen over fetch, and + // the File-menu entries that expose both. + const econ = await page.evaluate(async () => { + window.app._clearAll(); + const d = window.app.diagram; + const s = d.addNode(new MNode(NodeType.SOURCE, 100, 100)); s.label = 'Mine'; + const p = d.addNode(new MNode(NodeType.POOL, 300, 100)); p.label = 'Gold'; + d.addConnection(new MConnection(s.id, p.id)).rate = 3; + const text = dslSerialize(d.toJSON()); + const back = dslParse(text); + const roundTrip = JSON.stringify(normalizeEconJSON(d.toJSON())) === JSON.stringify(normalizeEconJSON(back)); + // The exact code path _exportModule uses, minus the download click. + const [modelSrc, engineSrc] = await Promise.all([ + fetch('js/model.js').then(r => r.text()), + fetch('js/engine.js').then(r => r.text()), + ]); + const mod = buildEconomyModule(d.toJSON(), modelSrc, engineSrc, { generator: 'smoke' }); + const menuEcon = !!document.getElementById('btn-export-econ'); + const menuModule = !!document.getElementById('btn-export-module'); + const kbHasEcon = KB_ARTICLES.some(a => a.category === 'Economy as code'); + return { + textHasNode: /source Mine @ 100,100/.test(text), + textHasRate: /Mine -> Gold : 3/.test(text), + roundTrip, + modHasApi: mod.includes('createEconomy') && mod.includes('DIAGRAM_SRC'), + menuEcon, menuModule, kbHasEcon, + }; + }); + if (econ.textHasNode && econ.textHasRate && econ.roundTrip && econ.modHasApi + && econ.menuEcon && econ.menuModule && econ.kbHasEcon) + ok('economy as code: .econ round-trips in-page, module codegen builds, menu + KB entries present'); + else fail('economy as code: ' + JSON.stringify(econ)); + // P3: auto-revert reverts to Select after placing a node (on by default). const p3auto = await page.evaluate(() => { window.app._clearAll(); From af990fd0f630a2fe9acc9288e2612307e131089b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 16 Jul 2026 20:22:31 +0000 Subject: [PATCH 3/6] Design tests: Checks rail panel + assertions saved with the diagram Assertions graduate from CLI-only flags to a first-class diagram feature: - Diagram.assertions (array of assertion strings) serializes with the file, round-trips through .econ as `assert "..."` directives, and is covered by the kitchen-sink round-trip fixture. - New Checks rail panel (js/app-analysis.js): edit the saved checks with live parse validation, then verify them against a fresh isolated run (Check once) or inside every trial of a Monte Carlo batch (Check batch, async with progress). Results render as PASS/FAIL rows with failure details and per-assertion fail counts across runs. The live canvas state is never touched; a seeded clone never leaks its RNG stream into the session. - cli.js --check runs the suite saved in the diagram (plus any --assert extras), so a .econ file carries its own tests: `node cli.js economy.econ --check` is a complete CI job. - KB article updated for the panel, docs (README, ECONOMY_AS_CODE.md, CLAUDE.md) extended. Tests: unit coverage for the assert directive, Diagram serialization and --check exit codes (213/213 pass); smoke coverage for the panel render, single + Monte Carlo checking and .econ serialization. Browser smoke passes. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01BTK8CoB2M6ofpYRXpQEVVL --- CLAUDE.md | 1 + README.md | 12 ++- cli.js | 14 ++- docs/ECONOMY_AS_CODE.md | 13 +++ index.html | 6 +- js/app-analysis.js | 208 ++++++++++++++++++++++++++++++++++++++++ js/app-props.js | 1 + js/dsl.js | 14 +++ js/kb.js | 30 +++--- js/model.js | 5 + test/run.js | 29 ++++++ test/smoke.js | 38 ++++++++ 12 files changed, 351 insertions(+), 20 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e16165a..1ba98dc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,6 +34,7 @@ node cli.js diagram.json --runs 1000 --steps 200 --seed 42 --param rate=3 # Economy-as-code (docs/ECONOMY_AS_CODE.md): assertions, format conversion, # standalone-module codegen. Assertions exit 2 on failure (CI-friendly). node cli.js economy.econ --assert "always gold < 500" --assert "at end: score >= 10" +node cli.js economy.econ --check # run assertions saved in the diagram node cli.js diagram.json --to-dsl > economy.econ # and .econ --to-json back node cli.js economy.econ --emit economy.module.js # dependency-free JS module ``` diff --git a/README.md b/README.md index 51b33d7..30b1155 100644 --- a/README.md +++ b/README.md @@ -147,9 +147,11 @@ top bar for run/zoom/file controls. - **`.econ` text format** — save/open the diagram as readable, diff‑friendly text that lives happily in git (one line per node/connection; full round‑trip with the canvas). See **[docs/ECONOMY_AS_CODE.md](docs/ECONOMY_AS_CODE.md)**. -- **Assertions** — CLI checks like `always gold < 500` or - `eventually score >= 100` that run per step (and across Monte Carlo trials), - exit non‑zero on failure, and turn balance regressions into CI failures. +- **Design tests (assertions)** — checks like `always gold < 500` or + `eventually score >= 100`, run per step (and across Monte Carlo trials). + Edit and run them in the **Checks** rail panel; they save with the diagram + (`assert` lines in `.econ`), and `cli.js --check` runs the same suite with a + non‑zero exit on failure — balance regressions become CI failures. - **Export as JS module** — compile the diagram + engine into one dependency‑free `.js` file with a `createEconomy()` API (`step/run/get/set/ fire/onStep`), so the economy you designed is the economy your game ships. @@ -190,6 +192,10 @@ node cli.js economy.econ --steps 300 \ --assert "eventually tutorial_done >= 1" \ --assert "at step 60: churn <= 3" +# or run the suite saved in the diagram itself (the app's Checks rail panel / +# `assert` lines in .econ files) +node cli.js economy.econ --check + # the same assertions across 1000 Monte Carlo trials; tolerate 5% unlucky runs node cli.js economy.econ --runs 1000 --seed 42 --pass-rate 95 \ --assert "at end: gold >= 100" diff --git a/cli.js b/cli.js index 9a43f2e..42345b9 100644 --- a/cli.js +++ b/cli.js @@ -19,6 +19,9 @@ // With --runs>1 every trial is checked. Exit code 2 when // assertions fail. // --assert-file F read assertions from a file (one per line, // comments) +// --check also run the assertions saved in the diagram itself +// (the Checks rail panel in the app; `assert` lines in +// .econ files) // --pass-rate P with --runs>1: minimum % of trials where every // assertion holds (default 100) // --to-dsl print the diagram as .econ text and exit @@ -71,7 +74,7 @@ function fail(msg) { function parseArgs(argv) { const opts = { steps: 200, runs: 1, seed: null, params: {}, csv: false, file: null, - asserts: [], passRate: 100, emit: null, toDsl: false, toJson: false, + asserts: [], passRate: 100, emit: null, toDsl: false, toJson: false, check: false, }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; @@ -90,6 +93,7 @@ function parseArgs(argv) { if (s) opts.asserts.push(s); } } + else if (a === '--check') opts.check = true; else if (a === '--pass-rate') opts.passRate = parseFloat(argv[++i]); else if (a === '--emit') opts.emit = argv[++i]; else if (a === '--to-dsl') opts.toDsl = true; @@ -163,9 +167,15 @@ if (opts.emit) { } // ── Assertions ────────────────────────────────────────────────────────────── +// --check prepends the assertions saved in the diagram itself to any given +// with --assert/--assert-file. +const assertSrcs = [...(opts.check ? diagram.assertions || [] : []), ...opts.asserts]; let parsedAsserts = []; -try { parsedAsserts = opts.asserts.map(parseAssertion); } +try { parsedAsserts = assertSrcs.map(parseAssertion); } catch (e) { fail(`Bad assertion: ${e.message}`); } +if (opts.check && !(diagram.assertions || []).length) { + process.stderr.write('Note: --check given but the diagram has no saved assertions.\n'); +} function reportAssertions(results) { let failed = 0; diff --git a/docs/ECONOMY_AS_CODE.md b/docs/ECONOMY_AS_CODE.md index d598c68..19129b5 100644 --- a/docs/ECONOMY_AS_CODE.md +++ b/docs/ECONOMY_AS_CODE.md @@ -71,6 +71,7 @@ Warehouse ~> Score name=warehouse | `type Wood = #8d6e63` | named resource type; the name is usable wherever a color is | | `var luck = dice(2d6) gaussian` | custom variable; kinds `interval(min,max)`, `array(1,2,3)`, `dice(XdY)`, `math(expr)`; modifiers `gaussian` and `per=play` | | `player enabled rules=[…]` | artificial-player rules (JSON) | +| `assert "always gold < 500"` | a saved design test (see Assertions below; run with `--check`) | ### Nodes @@ -142,6 +143,18 @@ node cli.js economy.econ --steps 300 \ --assert "widgets > 50" # bare expression = at end ``` +Assertions can also be **saved with the diagram** — edit them in the app's +**Checks** rail panel (with one-click checking against a single run or a Monte +Carlo batch), or write `assert "…"` lines in a `.econ` file: + +```econ +assert "always gold < 500" +assert "eventually score >= 100" +``` + +`node cli.js economy.econ --check` runs the saved suite (plus any extra +`--assert` flags), so the economy file carries its own tests. + | Quantifier | Passes when | | --- | --- | | `always E` | E is true at every step, including step 0 | diff --git a/index.html b/index.html index b547262..ada3fb6 100644 --- a/index.html +++ b/index.html @@ -307,7 +307,7 @@