diff --git a/CHANGELOG.md b/CHANGELOG.md index 1831154..34220ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,401 +1,54 @@ # Changelog -The format follows [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project -adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). As of `1.0.0` the -public API, the request and result schemas, the numeric and units policy, the validation -rules and the compatibility policy are frozen: breaking any of them costs a major version. +What changed in `@packvium/engine` on npm, release by release. The format follows +[Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.2.0] - -An additive release. A packing result can now be turned into a document an operator can -work from, in all four languages; and, in Python, a proposed catalog change can be -compared, replayed against history and published through an approval step rather than -argued about. - -Nothing here breaks 1.1.0. Every schema change is additive, the frozen Python surface is -unchanged, and the PHP surface grows one new namespace and nothing else. - -### Added - -- **Execution plans, in all four languages.** `packvium.execution`, - `Packvium\Execution\Plan`, `packvium_core::execution` and `@packvium/engine`'s - `execution.js` derive a work order from an already validated result: what to lift, why a - carton was chosen, and what was not packed with its proof level unsoftened. The adapter - calls no solver and no validator — a test in each language asserts that — and given the - same result all four emit a byte-identical canonical form. - - Two properties are part of the format rather than notes about it. Everything the solver - or validator decided sits under `facts`; every human-readable sentence sits under - `presentation` and names the fields it came from in `cites`, so a consumer that reads - only `facts` loses nothing it may rely on. And the step order is **injected**: supply - `loading_orders` and each step is numbered, omit it and the container reports - `order: "unavailable"` with every placement still listed. There is no third behaviour, - because presenting the order the solver happened to walk its candidates in as an order - that is safe to lift boxes in would be a claim nothing supports. - -- **Operator locks, in Python.** `packvium.locks` lets an operator pin a placement and get - a *second* result beside the approved one — never an edit of it, so "what was approved" - and "what was proposed" stay two artifacts. A lock becomes an ordinary placement - constraint, so the re-solve is the same portfolio under the same independent validator: - **a lock cannot produce a placement the engine would otherwise refuse**, and the - strongest thing it can do is reserve its own slot. A lock the solve cannot honour is - reported as unpreserved and names the lock rather than raising; a lock set that - contradicts itself is refused before any solve runs. - - Python-only, deliberately: a lock has no representation in the request schema, so there - is nothing to hand another engine. - -- **Scenario comparison, recommendations and historical replay, in Python.** - `packvium.simulation` compares two pinned scenarios order by order and returns a Pareto - report per order — never a blended delta, because a single number can name a winner that - is worse on the axis a caller actually cares about. `packvium.recommendations` turns that - comparison into a proposal, or returns nothing at all when the paired cohort is too - small, and publishes only through an explicit approval step. `packvium.holdout` replays a - proposal against decisions held out of the evidence that produced it, over the append-only - ledger in `packvium.outcomes`; a packing the injected validator rejects is that arm's - failure at any cost, and realised damage, returns and repacks are reported against the - carton that actually shipped rather than credited to the one that was never tried. - - This surface is supported and **not yet signature-frozen** — a parameter may be renamed - or a returned value gain a field in a minor release, announced here rather than blocked - by a gate. Pin the version if you depend on its exact shape; `docs/PUBLIC-API.md` says - which surfaces carry the stronger promise. - -- **`pack_from_dict` accepts a keyword-only `extensions` registry (Python).** Additive: it - defaults to `None` and every existing call keeps its meaning and its answer. It exists so - a lock can enter the engine as an ordinary request-derived constraint rather than through - a second, lock-aware search path. The registry **adds to** the compiled policy rules and - does not replace them. - -- **Two new worked examples.** `execution` (Python, PHP and Node) turns a result into - numbered steps and shows what "byte-identical" does and does not promise; `intelligence` - (Python) proves a carton change is worth publishing before publishing it. - -### Changed - -- **The solvers do less repeated work, again.** Byte-identical results everywhere. Group - batching in the Rust extreme-point solver drops two quadratic scans over group members - for a single pass, and the PHP and Python grid-admission and load-ordering paths reuse a - prototype profile and a canonical order instead of rebuilding them per candidate. - -- **Every example names its own time budget.** An example that solved on the library default - could print a different answer on a busy machine. Each now sets `time_limit_ms`, far above - what its solve needs; every printed answer is unchanged. - -### Fixed - -- **The JavaScript engine could return fewer placements than it reported packed.** When the - per-container beam search stopped early — on its node limit, the deadline or the effort - budget — it chose the surviving leader without the batches it had not reached yet, so those - items were neither placed nor listed as unpacked while the result still said `feasible`. It - needs `solver_profile: "quality"` or an explicit `container_plan_beam_width` above 1, and it - shipped in `@packvium/engine` `1.0.0` and `1.1.0`. The default profiles never reach that - path, and Python, PHP and Rust were never affected. If you run the JavaScript engine on the - `quality` profile, check `packed_item_count` against the placements you actually received - from those versions. - -- **The intelligence modules would not have imported on Python 3.9**, which is the minimum - the package declares. Six modules used `dataclass(slots=True)` from the standard library; - that argument does not exist before 3.10, so importing any of them raised `TypeError` on a - supported runtime. They now route through the package's own compatibility shim, as the - rest of the package already did. - -- **`@packvium/engine` did not expose its execution plan.** The module was named in the - package manifest but not in `exports`, so `import '@packvium/engine/execution.js'` failed - with `ERR_PACKAGE_PATH_NOT_EXPORTED` and the main entry re-exported neither function. The - subpath is now declared, with TypeScript declarations beside it. - -- **A non-finite metric is refused rather than ranked as optimal.** `NaN` makes both `>` and - `<` false, so an axis carrying one was silently counted equal and a candidate whose metrics - were all `NaN` arrived on the Pareto frontier beside a clean one. It is now refused by a - named error that says which candidate and which axis. Infinities are still accepted: they - are ends of the number line, and a caller encoding "unpriceable" as an infinite cost gets - the answer they mean. - -## [1.1.0] - -An additive release on the 1.0.0 freeze. Route-aware unloading becomes a property of the -container rather than of the whole solve, and the result contract grows the reserved, -typed shape a future optimality gap needs. Every schema change is additive: a request that -omits the new field gets the answer it got before, and both frozen public API surfaces are -unchanged. - -The four engines' candidate hot paths were also profiled and rewritten. That work changes -no result — all 399 corpus fixtures are byte-identical — and it is in this release because -two of its findings were correctness fixes rather than speed. - -### Added - -- **Doors on a container: `container.access_directions`.** Naming which walls an item can - be pulled through, so that nothing due at a later stop stands between an earlier item and - a door. Previously this could only be stated once for a whole solve; a container now - states its own doors and falls back to that setting when it states none. An empty list - leaves the rule inert — it is not read as a sealed container, and it is deliberately not - read as all six walls, which would switch a real constraint on for callers who never set - the field. Implemented in all four engines, and refused by none. -- **A reserved shape for reporting an optimality gap.** The result schema now declares the - names, types and ceilings a gap will use, together with the rule that an attained bound - carries no gap at all rather than a zero. No engine emits any of them yet. The existing - extension point on that object stays open, so a producer accepted by the 1.0 schema is - still accepted by 1.1. - -### Changed - -- **The solvers do less repeated work.** Byte-identical results everywhere, with the - largest gains where a scene has many contacts: on a 120-item contact-heavy request the - Rust engine goes from 10.1 s to 1.4 s and the JavaScript fallback from 1.70 s to 0.76 s; - on a 200-item adversarial free-space scene JavaScript goes from 3.25 s to 0.58 s. Some - scenes are unchanged and one is marginally slower. **This is not a speed-leadership - claim** — measured against other libraries on identical hardware, that claim is false on - latency, and no Packvium surface makes it. -- **Every published package manifest now names its author, licence, repository, issue - tracker and homepage.** Absent fields are read as an anonymous package. -- **`@packvium/engine` no longer declares `@packvium/native` as an optional dependency.** - That package is not published, so the entry named something npm could not fetch. Nothing - a caller can observe changes: the install already succeeded and answered from the - JavaScript engine, and `index.js` still loads `@packvium/native` by literal specifier, so - installing it yourself alongside the engine still selects the compiled backend. - -### Fixed - -- **The Rust engine accepted placements the validator refused.** Support-ratio comparison - used a floating-point epsilon wide enough to admit an area a whole square tick short of - the requirement. It is now the same exact integer rule the other three engines use. -- **The JavaScript fallback accepted door names no other engine would.** An unknown - direction was refused only on requests that took the general solving path; a request - simple enough to be answered by the compact-grid shortcut was answered instead of - refused. -- **The JavaScript fallback broke identifier ties by host locale.** That is neither stable - across machines nor equal to the code-point order the other engines use, so two hosts - could order the same items differently. Every tie-break now uses the shared code-point - order. -- **A container's doors could be answered from another container's cached corridor.** Two - containers of the same size with different doors are two different questions; the cache - key did not separate them, which could have silently accepted a placement that walls an - item in. -- **The PHP package could not be loaded on PHP 7.3 or 7.4.** The package advertises - `php: >=7.3` and carries a second, downgraded source tree for runtimes below 8.2. In - `1.0.0` that tree contained one line of PHP 8.1 syntax, so the whole of it failed to - parse on both older runtimes. `1.1.0` is the first version whose legacy tree loads. If - you are on PHP 8.2 or newer you were never affected — the canonical tree is what your - runtime selects. - -- **The engine package no longer loads its native backend through a computed specifier.** - Every module the package can load can now be resolved by reading the source. Behaviour - is identical: an absent, unbuilt or incompatible native addon still means the pure - JavaScript engine answers instead. +## [1.3.0] -### Not claimed - -- **A reported optimality gap.** The names are reserved and typed; nothing emits them. -- **`container.pallet_overhang_limit`.** Reserved in the request schema and refused by all - four engines. -- **Identical placements across engines.** Unchanged from 1.0.0: different engines may - return different, equally valid arrangements, and that is measured and budgeted. -- **Optimal packings for arbitrary requests.** 3D packing remains NP-hard. -- **Fastest engine.** Still false on latency and still claimed nowhere. - -## [1.0.0] - -The stable core release. It freezes the contract that already exists rather than adding a -feature wave: the public API, the request and result schemas, the numeric and units policy, -the validation rules and the compatibility policy will not break without a major version. - -### Read this before depending on 1.0.0 - -- **Platforms exercised for this release: Linux x86_64, Linux aarch64 and macOS arm64.** - Python wheels are built and installed into a clean Python 3.9 on all three; the PHP FFI - bridge is verified against the real shared library on PHP 8.2, 8.3, 8.4 and 8.5 on both - Linux architectures. **Windows and macOS x86_64 native binaries are not built and not - published.** Without a native binary the pure Python and PHP engines run unchanged — that - is the documented default, and it costs speed rather than correctness. -- **Release artifacts carry no build-provenance attestation.** `gh attestation verify` will - not succeed against 1.0.0. The SBOM and SHA-256 manifests are the integrity evidence for - this release; check them before installing from anywhere other than the official - registry. - -### Added - -- **A sound lower bound on the objective, in every engine.** Computed from the request - alone before a search begins, and identical across the Python, PHP, Rust and JavaScript - implementations on 381 corpus cases. It is not a result field: reporting an optimality - gap would widen the contract this release exists to freeze. -- **A declared numeric ceiling shared by all four engines.** A sum too large to stay exact - returns a structured refusal instead of a number that one language would round and - another would not. The limit is stated by the library rather than inherited from each - language, so the four agree about which requests are answerable. -- **A published coverage frontier for optimality claims.** Where the bound is actually - attained is measured and committed, so `optimal` is bounded by evidence rather than used - as a label. - -### Fixed - -- **A bound could be returned that JavaScript cannot represent exactly.** Values above - `2^53-1` are now refused rather than silently rounded in one engine and exact in the - others. -- **The prebuilt Node addon had no quality floor.** It is now held to a per-fixture budget - like the other independent engines. - -### Not claimed - -- **Identical placements across engines.** Different engines may return different, equally - valid arrangements. This is measured and budgeted, not accidental — and it includes the - JavaScript fallback and the prebuilt native addon, which differ on 18 of 397 corpus - fixtures. -- **Optimal packings for arbitrary requests.** 3D packing remains NP-hard; the bound says - what is provable, not that every answer is optimal. -- **Fastest engine.** Measured against other libraries on identical hardware, that claim is - false on latency, and no Packvium surface makes it. On the report's separate two-axis - time-and-peak-memory frontier, `packvium-rust` is Pareto-optimal in 6 of 9 profiles and - the only engine of ten never dominated. The latency result and the trade-off result are - reported together; neither is a general speed-leadership claim. - -## [0.1.3] - -An additive release. No packing request/result field or solver algorithm changed. +Portable operational artifacts, and a faster `quality` profile. Nothing breaks 1.2.0. ### Added -- **First-party carrier connectors for UPS, FedEx, DHL Express and USPS**, and a live - rate-card contract behind them. Connectors prepare ordinary rate-table data before a - deterministic solve; no network call, clock or carrier module enters a packing engine. - A rate card records which tariff version priced a quote and when it was fetched, and a - card that has gone stale is refused rather than served. - -### Fixed - -- **`@packvium/browser` now works under Node**, not only in a browser. The WebAssembly - loader generated for the `web` target fetches its own `.wasm` from a `file:` URL, which - Node's `fetch` refuses — so server-side rendering, a Vitest node environment and - `node --test` failed at initialization on 0.1.1 and 0.1.2. The package now selects a - Node entry point that reads the module off disk. Browser behaviour is unchanged. -- **The PHP package's compatibility tree could not autoload a class on old PHP.** Its - entry point was the one shipped file the downgrade did not process, and it used a PHP 8 - function to match the namespace prefix. Three of its solver files also could not be - parsed by PHP 8.0 or 8.1, which that tree also serves. Both are fixed, and the tree is - installed and loaded on 7.3, 7.4, 8.0 and 8.1 before release. -- **The compatibility tree did not place items where the canonical engine does on PHP 7.** - Several solver comparators were partial and relied on `usort` being stable, which PHP - guarantees only from 8.0, so three shared fixtures came back with a different rotation - chosen. The tie-breaking is explicit now — identical results on every supported version — - and no released package ever carried it, because none was installable below 8.2. +- **`@packvium/engine/artifacts.js`** — `buildOperationalArtifact(request, result, { loadingOrders })` + and `canonicalArtifactJson()`. One `packvium-operational-artifact/v1` document carries the + execution plan, exact geometry, the values a work order shows, and the request that produced + it. Every Packvium engine builds the same bytes from the same result. +- **`@packvium/engine/artifact-exports.js`** — `exportJson`, `exportCsv` (RFC 4180, 18 columns) + and `exportWorkOrderHtml`: a printable work order in one HTML file with no scripts and no + external resources. +- TypeScript declarations for both, and `examples/artifacts.mjs`. ### Changed -- **`packvium/packvium` now requires `php: >=7.3` instead of `>=8.2`.** One package - carries both the canonical PHP 8.2+ source and a generated `src-legacy/` tree, and its - `autoload.php` selects by `PHP_VERSION_ID`; PHP parses only what it loads. - `composer require packvium/packvium` is the right command on 7.3 through 8.5, and every - one of those versions is held to the same committed placement results. Nothing changes - for an 8.2+ consumer: the same files load, under the same names. -- Every package's `homepage` now points at . +- **The beam search behind `solver_profile: "quality"` does less repeated work.** Results are + byte-identical. On the wide cases measured (48 items, beam width 12) it took about half the + time and 34–49 MB less memory. +- A pinned catalog version resolves without scanning the version history. +- `canonicalPlanJson` writes RFC 8785 through the same writer as the artifact. Every plan the + engine produces keeps its 1.2.0 bytes. -## [0.1.2] +## [1.2.0] -An additive documentation and integration release. No packing request/result field or -solver algorithm changed. +Execution plans, and a fix for items going missing on the `quality` profile. Nothing breaks 1.1.0. ### Added -- **Runnable examples and guided capability maps.** Python, PHP and Node now ship worked - examples covering every objective and the major constraint, units, serialization, - nested-packing and commerce paths. Their printed answers are retained and checked on - every release, and each package executes its own examples in its test suite. -- **A versioned carrier-connector contract and reference implementation in the public - workspace.** Connectors prepare ordinary rate-table data before a deterministic solve; - no network call or carrier module enters a packing engine. The contract, offline replay - harness, registry and synthetic carrier are application components rather than new - packing-package API fields. - -### Changed - -- Every package README now links the whole Packvium family — Python, PHP, Rust, Node, - browser, PHP FFI bridge and Python native selector — and the PyPI, npm, Packagist and - crates.io manifests carry repository, homepage and keyword metadata. The PyPI page shows - the same README as GitHub and states the real Python floor, 3.9. - -### Fixed - -- Connector responses are revalidated at runtime and bound to the registered carrier and - requested service. Incomplete brackets, cross-currency price comparison and mutable - replay/value-object state are refused instead of silently producing a wrong price. -- Linux x86_64 and ARM64 evidence follows the declared suite version, preventing a - current gate from rewriting a previous release's receipt. -- PHP 7.4 artifact generation safely completes the locked downgrade tool's partial-write - case and still fails closed if its single retry does not finish. - -## [0.1.1] - -A patch over `0.1.0`. Every package is released together at the new version, including -the ones `0.1.0` did not break, so that one version number still describes one tested -set. +- **`@packvium/engine/execution.js`** — `buildExecutionPlan(request, result, { loadingOrders })`, + `canonicalPlanJson(plan)` and `placementReference()`, with TypeScript declarations. Turns a + validated result into a work order: what to lift, why a carton was chosen, what was not + packed. Step order comes from `loadingOrders` or is reported as `"unavailable"`. +- `examples/execution.mjs`. ### Fixed -- **`lowest_landed_cost` could choose a container its own rate card cannot price.** When - one container billed lighter than another but its rate table ran out before the - shipment's billed weight, the search preferred it — returning the one packing you - cannot actually buy over a priced alternative. Every engine now compares candidates by - the money the rate table charges rather than by billed weight, which also fixes the - case this objective exists for: a bracket step or a minimum charge can make the - cheaper shipment the heavier one. If no container on offer can price the load, the - request is refused with a message naming the container, its billed weight and the last - bracket, in all four languages — previously two of them returned a result carrying a - sentinel cost, and two aborted requests that had a shippable answer. `RateTable` gains - a non-throwing `charge_minor_or_none` / `chargeMinorOrNull`; the throwing form is - unchanged. No request or result field changed. - -- **`@packvium/engine@0.1.0` could not be imported.** The published tarball was missing - a runtime module that the fallback engine imports, so the first `import` of the package - threw `ERR_MODULE_NOT_FOUND`. npm versions are immutable, which is why the fix has to - arrive as a new version rather than a re-upload. Package assembly now dry-packs the - tarball and resolves every relative import in the real published inventory, so a - missing runtime file fails the release build instead of the consumer's first import. - Only the Node package was affected; the Python, PHP and Rust `0.1.0` releases install - and run correctly. - -### Added - -- **Commercial and control-plane API.** Three deterministic functions over one canonical - JSON document: `quote` returns a landed cost together with the tariff version that - produced it, `evaluate_policy` returns an eligibility decision together with the rule id - and version that decided it, and `catalog_version_info` returns the metadata of one - pinned catalog version. Exported as `packvium.commerce` (Python), `Packvium\Commerce\` - (PHP), `packvium_core::commerce` (Rust, plus three C ABI entry points) and `commerce` - on `@packvium/engine` and `@packvium/browser`. Prices are exact integers in minor - currency units and every inexact division rounds up, so a quote is reproducible rather - than approximately equal. No packing-request or packing-result field changed. Each - package ships a runnable `commerce` example; the contract is in `docs/COMMERCE-API.md`. - -## [0.1.0] - -First release. - -### Added - -- Exact fixed-point units: length in 1/16000 mm, weight in 1/8 µg. Integer, decimal, - fractional (`3/16`) and mixed-fraction (`12 3/8`) input across mm, cm, m, in and ft. - Common fractional inches through 1/128 are exact integers. -- Immutable domain model — items, item instances, containers, obstacles, rotations, - placements, requests and results. A call cannot mutate its inputs. -- Hard placement constraints: container boundaries, collisions, weight limits, permitted - orientations, floor-only, non-stackable, direct top-load limits, minimum support ratio, - tag compatibility and rectangular obstacles. -- A solver portfolio chosen per problem — regular grid, layer, extreme-point, - maximal-space and bounded exact-small — with deadlines and a deterministic seed. -- Lexicographic objective ranking with top-K alternatives. -- Independent post-solve validation: every returned solution is re-checked by logic - separate from the search that produced it. A solution that fails is reported as - `invalid_result` rather than returned as if it were sound. -- Structured reasons for every unplaced item. -- JSON serialization and a command-line interface reading a request on standard input. -- Sequential nested packing — a packed container becomes an item at the next level. -- Extension points for custom placement constraints, item orderings, candidate scorers, - container selectors, solution scorers and complete solvers. +- **The JavaScript engine could return fewer placements than it reported packed.** With + `solver_profile: "quality"` or `container_plan_beam_width` above 1, a beam search that stopped + early dropped the items it had not reached: neither placed nor listed as unpacked, and the + result still said `feasible`. Affected `1.0.0` and `1.1.0`; the default profiles were not. + If you used the `quality` profile, compare `packed_item_count` with the placements you received. -### Known limitations +## Earlier releases -Rigid axis-aligned cuboids only. No global optimality guarantee for the heuristic -profiles, no transport physics, and top-load limits apply to what rests directly on an -item rather than to a whole stack. See `docs/GUARANTEES.md` for the full statement of -what is and is not promised. +Up to 1.1.0 one changelog covered every Packvium language. Those entries are kept in +this repository's GitHub Releases for each tag. diff --git a/README.md b/README.md index 1296559..d65f1bf 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ and execute without a project around it. | [`units.mjs`](examples/units.mjs) | Why lengths travel as strings: fractional inches kept exact, one tick deciding a fit, and the point where a JavaScript number stops being exact and a quote is refused rather than rounded. | | [`commerce.mjs`](examples/commerce.mjs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | | [`execution.mjs`](examples/execution.mjs) | Turn a result into dock instructions — and the clearest place to see what "byte-identical" does and does not promise: the four adapters agree on any given result, while this engine is free to reach a different packing than Python does. | +| [`artifacts.mjs`](examples/artifacts.mjs) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable HTML work order, and a refusal for a format it does not know. | ```bash node examples/basic.mjs @@ -124,6 +125,9 @@ node examples/basic.mjs - Loading and removal sequence helpers for already placed boxes. - Execution plans through `buildExecutionPlan()` / `canonicalPlanJson()`: a work-order view of a result, with solver facts separated from the text that cites them. +- Portable operational artifacts through `buildOperationalArtifact()` from `artifacts.js`, exported + by `artifact-exports.js` as canonical JSON, CSV or a self-contained HTML work order — the same + bytes the Python, PHP and Rust packages write. - Deterministic carrier quotes, policy evaluation and effective-dated catalog lookup through `commerce`. diff --git a/artifact-exports.d.ts b/artifact-exports.d.ts new file mode 100644 index 0000000..baeec25 --- /dev/null +++ b/artifact-exports.d.ts @@ -0,0 +1,22 @@ +// Types for `@packvium/engine/artifact-exports.js` — exports of an operational artifact. +// +// Each export is a pure function of the artifact and is byte-identical across engines. Every +// one throws `OperationalArtifactError` with code `unknown_format` for a document whose +// `format` is not `packvium-operational-artifact/v1`. The CSV and HTML exports print only +// strings, integers and null: any other value in a printed position throws `invalid_value`. +import type { OperationalArtifact } from './artifacts.js'; + +export const CSV_COLUMNS: readonly [ + 'record', 'container_index', 'container_type', 'sequence', 'item_type', 'orientation', + 'x_ticks', 'y_ticks', 'z_ticks', 'x', 'y', 'z', 'length', 'width', 'height', 'length_unit', + 'reason', 'proof_level', +]; + +/** The artifact's RFC 8785 canonical form. */ +export function exportJson(artifact:OperationalArtifact):string; + +/** RFC 4180: a header row, one `step` row per work-order line, one `unplaced` row per item, CRLF endings. */ +export function exportCsv(artifact:OperationalArtifact):string; + +/** One self-contained HTML work order: inline print styles, no script, no external resource. */ +export function exportWorkOrderHtml(artifact:OperationalArtifact):string; diff --git a/artifact-exports.js b/artifact-exports.js new file mode 100644 index 0000000..5405fef --- /dev/null +++ b/artifact-exports.js @@ -0,0 +1,236 @@ +/** + * JSON, CSV and print-ready work orders from an operational artifact. + * + * Held to `packvium.artifact_exports`. Each export is a pure function of the artifact: no + * solver, carrier, renderer or clock, so an export is replayable from the artifact it came + * from and four engines emit the same bytes. + * + * - JSON is the artifact's RFC 8785 canonical form. + * - CSV has one row per packing step and one per unplaced item. It is RFC 4180: a header row, + * CRLF after every row, and a field quoted only when it holds a comma, quote, CR or LF. + * - The work order is one self-contained HTML document: inline print styles, no script, no + * external resource, ASCII source with entities for the few typographic characters. + * + * Values are copied, never re-rendered or reinterpreted. That includes a CSV field beginning + * with `=`: prefixing it would change an identifier a warehouse system matches on. + */ + +import { FORMAT, OperationalArtifactError, canonicalArtifactJson } from './artifacts.js'; + +export const CSV_COLUMNS = Object.freeze([ + 'record', 'container_index', 'container_type', 'sequence', 'item_type', 'orientation', + 'x_ticks', 'y_ticks', 'z_ticks', 'x', 'y', 'z', 'length', 'width', 'height', 'length_unit', + 'reason', 'proof_level', +]); + +const CSV_SPECIAL = /[,"\r\n]/; + +const STYLE = 'body{font-family:system-ui,sans-serif;margin:24px;color:#111}' + + 'h1{font-size:20px}h2{font-size:16px;margin-top:24px}' + + 'table{border-collapse:collapse;width:100%;margin:8px 0 16px}' + + 'th,td{border:1px solid #999;padding:4px 6px;text-align:left;font-size:12px;vertical-align:top}' + + 'th{background:#eee}' + + '.facts td:first-child{width:28%;font-weight:600}' + + '@media print{body{margin:0}section.container{break-after:page}tr{break-inside:avoid}}'; + +const DASH = '—'; + +const HTML_ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; + +export function exportJson(artifact) { + return canonicalArtifactJson(requireArtifact(artifact)); +} + +export function exportCsv(artifact) { + const document = requireArtifact(artifact); + const workOrder = document.work_order; + const rows = [CSV_COLUMNS]; + for (const container of workOrder.containers) { + for (const line of container.lines) { + const reference = line.placement; + const ticks = reference.position_ticks; + const { position, dimensions } = line; + rows.push([ + 'step', reference.container_index, container.container_type, get(line, 'sequence'), + reference.item_type, reference.orientation, ticks.x, ticks.y, ticks.z, + position.x, position.y, position.z, + dimensions.length, dimensions.width, dimensions.height, workOrder.length_unit, + null, null, + ]); + } + } + for (const unplaced of document.plan.unplaced) { + const { facts } = unplaced; + rows.push(['unplaced', null, null, null, facts.item_type, null, null, null, null, + null, null, null, null, null, null, null, facts.reason, facts.proof_level]); + } + return rows.map((row) => `${row.map(csvField).join(',')}\r\n`).join(''); +} + +export function exportWorkOrderHtml(artifact) { + const document = requireArtifact(artifact); + const { plan, work_order: workOrder, provenance } = document; + const lines = [ + '', + '', + '', + '', + 'Packing work order', + ``, + '', + '', + '

Packing work order

', + '', + ...factRows(document, plan, provenance), + '
', + ]; + // Python's `zip`: the shorter of the two lists decides how many sections there are. + const count = Math.min(plan.containers.length, workOrder.containers.length); + for (let index = 0; index < count; index += 1) { + lines.push(...containerSection(plan.containers[index], workOrder.containers[index], workOrder)); + } + lines.push(...unplacedSection(plan.unplaced), '', ''); + return `${lines.join('\n')}\n`; +} + +// ------------------------------------------------------------------------------------ HTML + +function factRows(document, plan, provenance) { + const { facts } = plan; + const { replay, solver } = provenance; + const { feasibility } = facts; + const replayText = escape(replay.level) + (replay.because ? ` (${escape(replay.because)})` : ''); + const solverText = solver + ? `${escape(solver.profile)} / ${escape(solver.solver)} / seed ${escape(solver.seed)}` + : DASH; + const catalogs = provenance.catalog_versions_used + .map((catalog) => `${escape(get(catalog, 'catalog_id'))} v${escape(get(catalog, 'version'))}`) + .join(', '); + const rows = [ + ['Status', escape(facts.status)], + ['Objective', orDash(plan.objective)], + ['Containers', escape(facts.container_count)], + ['Score', `[${facts.score.map(escape).join(', ')}]`], + ['Feasibility', orDash(get(feasibility, 'code'))], + ['Replay', replayText], + ['Solver', solverText], + ['Catalogs', catalogs || DASH], + ['Packvium', escape(document.suite_version)], + ]; + return rows.map(([label, value]) => `${label}${value}`); +} + +function containerSection(planContainer, container, workOrder) { + const { facts } = planContainer; + const weightUnit = escape(workOrder.weight_unit); + const lengthUnit = escape(workOrder.length_unit); + const lines = [ + '
', + `

Container ${ordinal(container.container_index)}: ${orDash(container.container_type)}

`, + `

Payload ${escape(container.payload_weight)} ${weightUnit} · ` + + `Gross ${escape(container.gross_weight)} ${weightUnit} · ` + + `Utilization ${orDash(facts.volume_utilization)}

`, + planContainer.order === 'loading' + ? '

Order: loading. Follow the steps in sequence.

' + : '

Order: unavailable. No safe loading order was supplied, so the steps are not numbered.

', + '', + `` + + ``, + '', + ]; + for (const line of container.lines) { + const { placement: reference, position, dimensions: size } = line; + lines.push( + `` + + `` + + `` + + `` + + '', + ); + } + lines.push('', '
StepItemOrientationPosition x, y, z (${lengthUnit})Size l × w × h (${lengthUnit})Done
${escape(get(line, 'sequence'))}${escape(reference.item_type)}${escape(reference.orientation)}${escape(position.x)}, ${escape(position.y)}, ${escape(position.z)}${escape(size.length)} × ${escape(size.width)} × ${escape(size.height)}☐
', '
'); + return lines; +} + +function unplacedSection(entries) { + const lines = ['
', '

Not packed

']; + if (entries.length === 0) { + lines.push('

Every item was packed.

', '
'); + return lines; + } + lines.push('', '', ''); + for (const { facts } of entries) { + lines.push(`` + + ``); + } + lines.push('', '
ItemReasonProof
${orDash(facts.item_type)}${orDash(facts.reason)}${orDash(facts.proof_level)}
', ''); + return lines; +} + +/** + * A container's 1-based number on the sheet. Computed, so it is checked like `text`: + * `0.5 + 1` would print `1.5` in one engine and be refused in another. + */ +function ordinal(index) { + if (typeof index !== 'number' || !Number.isInteger(index)) { + throw new OperationalArtifactError('invalid_value', `container index ${String(index)} is not an integer`); + } + return text(index + 1); +} + +function escape(value) { + return text(value).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]); +} + +function orDash(value) { + return value === null || value === undefined ? DASH : escape(value); +} + +// ------------------------------------------------------------------------------------- CSV + +function csvField(value) { + const spelled = text(value); + return CSV_SPECIAL.test(spelled) ? `"${spelled.replace(/"/g, '""')}"` : spelled; +} + +/** + * The one rendering every engine shares: a string as itself, an integer in decimal, null as + * nothing. Anything else -- a boolean, a fractional number, an object or array -- has a + * different default spelling in each language, so it is refused rather than printed four ways. + */ +function text(value) { + if (value === null || value === undefined) return ''; + if (typeof value === 'string') return value; + if (typeof value !== 'number' || !Number.isInteger(value)) { + throw new OperationalArtifactError('invalid_value', + `a ${describe(value)} has no single rendering in a work order`); + } + // Beyond 2^53 - 1 the parser has already rounded the integer, so its decimal would differ. + if (!Number.isSafeInteger(value)) { + throw new OperationalArtifactError('number_out_of_range', + `${value} is beyond what every engine holds exactly`); + } + return String(value); +} + +function describe(value) { + if (Array.isArray(value)) return 'list'; + return typeof value === 'number' ? 'non-integer number' : typeof value; +} + +/** Python's `Mapping.get`, reading only the object's own keys. */ +function get(mapping, name) { + const readable = mapping !== null && typeof mapping === 'object' && !Array.isArray(mapping) + && Object.prototype.hasOwnProperty.call(mapping, name); + return readable ? mapping[name] : null; +} + +/** An export reads only a document it knows how to read, and says so when it cannot. */ +function requireArtifact(artifact) { + const found = get(artifact, 'format'); + if (found !== FORMAT) { + throw new OperationalArtifactError('unknown_format', + `cannot export format ${JSON.stringify(found)}; this exporter reads ${FORMAT}`); + } + return artifact; +} diff --git a/artifacts.d.ts b/artifacts.d.ts new file mode 100644 index 0000000..0d6fd65 --- /dev/null +++ b/artifacts.d.ts @@ -0,0 +1,48 @@ +// Types for `@packvium/engine/artifacts.js` — the operational artifact. +// +// `docs/OPERATIONAL-ARTIFACTS.md` is the contract. The artifact wraps the execution plan +// unchanged, adds tick-string geometry and the result's rendered work-order values, and records +// provenance without wall-clock time. Its RFC 8785 spelling is byte-identical across engines. +import type { PackingRequest, PackingResult } from './index.js'; +import type { ExecutionPlan, PlacementReference } from './execution.js'; + +export const FORMAT: 'packvium-operational-artifact/v1'; +export const SUITE_VERSION: string; + +/** The closed set of refusal codes shared by all four engines. */ +export type OperationalArtifactErrorCode = + | 'invalid_request' | 'invalid_result' | 'invalid_plan_input' | 'mixed_units' + | 'number_out_of_range' | 'invalid_string' | 'invalid_value' | 'unknown_format' | 'invalid_json'; + +export class OperationalArtifactError extends Error{constructor(code:OperationalArtifactErrorCode,message:string);readonly code:OperationalArtifactErrorCode} + +/** Integer tick counts as decimal strings: no engine has to hold them as a native number. */ +export interface TickDimensions{length:string;width:string;height:string} + +export interface ArtifactSolver{profile:string;solver:string;seed:number;time_limit_reached:boolean;effort_limit_reached:boolean} + +/** `because` names the field that ruled out an exact replay, never a sentence. */ +export type ArtifactReplay = + | {level:'exact';because:null} + | {level:'not_guaranteed';because:'provenance.solver'|'provenance.solver.time_limit_reached'}; + +export interface ArtifactProvenance{request:PackingRequest;catalog_versions_used:unknown[];solver:ArtifactSolver|null;replay:ArtifactReplay} + +export interface GeometryPlacement{placement:PlacementReference;dimensions:TickDimensions} +export interface GeometryContainer{container_index:number;inner_dimensions:TickDimensions;placements:GeometryPlacement[]} + +/** Rendered values copied from the result, all in the work order's units. */ +export interface WorkOrderLine{sequence?:number;placement:PlacementReference;position:{x:string;y:string;z:string};dimensions:{length:string;width:string;height:string}} +export interface WorkOrderContainer{container_index:number;container_type:string|null;payload_weight:string;gross_weight:string;lines:WorkOrderLine[]} +export interface WorkOrder{length_unit:string|null;weight_unit:string|null;containers:WorkOrderContainer[]} + +export interface OperationalArtifact{format:'packvium-operational-artifact/v1';suite_version:string;provenance:ArtifactProvenance;plan:ExecutionPlan;geometry:{containers:GeometryContainer[]};work_order:WorkOrder} + +/** + * Build the artifact for one validated result. Calls no solver, validator, renderer or clock. + * `loadingOrders` is passed straight to `buildExecutionPlan`. Throws `OperationalArtifactError`. + */ +export function buildOperationalArtifact(request:PackingRequest,result:PackingResult,options?:{loadingOrders?:Record}):OperationalArtifact; + +/** The RFC 8785 canonical form. Throws `OperationalArtifactError` for a value with no spelling. */ +export function canonicalArtifactJson(artifact:OperationalArtifact):string; diff --git a/artifacts.js b/artifacts.js new file mode 100644 index 0000000..66a7c98 --- /dev/null +++ b/artifacts.js @@ -0,0 +1,324 @@ +/** + * The portable operational artifact. + * + * `docs/OPERATIONAL-ARTIFACTS.md` is the contract and `packvium.artifacts` is the reference. + * The artifact is the one document that can be drawn, printed and traced offline, and it adds + * nothing a solver decided: it reads the request, the result and the optional loading orders + * -- the plan's own inputs -- and calls no solver, validator, renderer or clock. The plan + * inside it is exactly what `buildExecutionPlan` emits for the same inputs. Placements are + * found by the plan's placement reference, never by `item_id`. + * + * Held to byte-identical canonical output with Python, PHP and Rust. Where a document breaks + * two rules, the checks run in Python's order, because the error code is compared too. + */ + +import { CanonicalJsonError, canonicalJson } from './canonical-json.js'; +import { ExecutionPlanError, buildExecutionPlan, placementReference } from './execution.js'; + +export const FORMAT = 'packvium-operational-artifact/v1'; + +/** + * The suite version of this builder, the same string in all four engines of one release. + * The engine's own name is deliberately not recorded: four correct builders naming themselves + * would emit four different documents. + */ +export const SUITE_VERSION = '1.3.0'; + +/** The deterministic part of `result.algorithm`; `duration_ms` is wall-clock time. */ +const SOLVER_FIELDS = ['profile', 'solver', 'seed', 'time_limit_reached', 'effort_limit_reached']; +const DIMENSION_AXES = ['length', 'width', 'height']; +const POSITION_AXES = ['x', 'y', 'z']; + +/** + * The builder was handed something an artifact cannot carry. `code` is one of the closed set + * shared by all four engines (see `docs/OPERATIONAL-ARTIFACTS.md`). + */ +export class OperationalArtifactError extends Error { + constructor(code, message) { + super(message); + this.name = 'OperationalArtifactError'; + this.code = code; + } +} + +/** + * Build the artifact for one validated result. O(R + P) for a request of size R and P + * placements, plus key sorting when it is serialized. + * + * `loadingOrders` maps a container index to a permutation of its placement indices and is + * passed straight to the plan builder. + */ +export function buildOperationalArtifact(request, result, { loadingOrders } = {}) { + if (!isMapping(request)) throw refusal('invalid_request', 'a request is a JSON object'); + if (!isMapping(result)) throw refusal('invalid_result', 'a result is a JSON object'); + requireObjects(result); + const plan = planOf(request, result, loadingOrders); + + const containers = list(get(result, 'containers'), 'result.containers'); + const { lengthUnit, weightUnit } = unitsOf(containers); + const artifact = { + format: FORMAT, + suite_version: SUITE_VERSION, + provenance: provenanceOf(request, result), + plan, + geometry: { containers: containers.map((container, index) => geometryOf(index, container)) }, + work_order: { + length_unit: lengthUnit, + weight_unit: weightUnit, + containers: containers.map((container, index) => workOrderContainer( + index, container, plan.containers[index], lengthUnit, weightUnit)), + }, + }; + // Refused here rather than when someone serializes it: an artifact that exists must have + // one spelling in every engine. + canonicalArtifactJson(artifact); + return artifact; +} + +/** The artifact's RFC 8785 canonical form, the bytes four engines are compared on. */ +export function canonicalArtifactJson(artifact) { + try { + return canonicalJson(artifact); + } catch (error) { + if (error instanceof CanonicalJsonError) throw refusal(error.code, error.message); + throw error; + } +} + +function planOf(request, result, loadingOrders) { + try { + return buildExecutionPlan(request, result, { loadingOrders }); + } catch (error) { + if (error instanceof ExecutionPlanError) throw refusal('invalid_plan_input', error.message); + throw error; + } +} + +// ------------------------------------------------------------------------------ provenance + +function provenanceOf(request, result) { + const solver = solverOf(get(result, 'algorithm')); + const catalogs = list(get(result, 'catalog_versions_used'), 'result.catalog_versions_used'); + catalogs.forEach(requireCatalog); + return { + // Embedded, not digested: only the request itself lets someone replay the artifact + // without a lookup. + request, + catalog_versions_used: catalogs, + solver, + replay: replayOf(solver), + }; +} + +/** + * The result schema's closed catalog reference. The work order prints these fields, so a + * mistyped one would print differently in every engine. + */ +function requireCatalog(catalog) { + if (typeof field(catalog, 'catalog_id', 'catalog_versions_used[]') !== 'string') { + throw refusal('invalid_result', 'catalog_versions_used[].catalog_id is not a string'); + } + for (const name of ['version', 'effective_at', 'resolved_at']) { + const value = field(catalog, name, 'catalog_versions_used[]'); + if (typeof value !== 'number' || !Number.isInteger(value)) { + throw refusal('invalid_result', `catalog_versions_used[].${name} is not an integer`); + } + } +} + +function solverOf(algorithm) { + if (algorithm === null) return null; + if (!isMapping(algorithm)) throw refusal('invalid_result', 'result.algorithm is not an object'); + const missing = SOLVER_FIELDS.filter((name) => !hasOwn(algorithm, name)); + if (missing.length) { + throw refusal('invalid_result', `result.algorithm has no ${missing.join(', ')}`); + } + for (const flag of ['time_limit_reached', 'effort_limit_reached']) { + if (typeof algorithm[flag] !== 'boolean') { + throw refusal('invalid_result', `result.algorithm.${flag} is not a boolean`); + } + } + const solver = {}; + for (const name of SOLVER_FIELDS) solver[name] = algorithm[name]; + return solver; +} + +/** + * `exact` only when a replay must reproduce the result. A search stopped by wall-clock time + * cannot be reproduced, and a result that does not say how it was solved cannot be promised + * to; claiming otherwise would be softening a proof level by another name. + */ +function replayOf(solver) { + if (solver === null) return { level: 'not_guaranteed', because: 'provenance.solver' }; + if (solver.time_limit_reached) { + return { level: 'not_guaranteed', because: 'provenance.solver.time_limit_reached' }; + } + return { level: 'exact', because: null }; +} + +// -------------------------------------------------------------------------------- geometry + +function geometryOf(index, container) { + return { + container_index: index, + inner_dimensions: tickDimensions(field(container, 'inner_dimensions', `containers[${index}]`)), + placements: placementsOf(index, container).map((placement) => ({ + placement: placementReference(index, placement), + dimensions: tickDimensions(field(placement, 'dimensions', `containers[${index}].placements[]`)), + })), + }; +} + +/** + * Lengths as decimal strings of ticks: the scene contract's spelling, and one no engine has to + * hold as a native number. + */ +function tickDimensions(dimensions) { + const spelled = {}; + for (const axis of DIMENSION_AXES) spelled[axis] = ticksOf(field(dimensions, axis, 'dimensions')); + return spelled; +} + +function ticksOf(scalar) { + const ticks = field(scalar, 'ticks', 'exact scalar'); + if (typeof ticks !== 'number' || !Number.isInteger(ticks)) { + throw refusal('invalid_result', `ticks ${String(ticks)} is not an integer`); + } + // Beyond 2^53 - 1 the parser has already rounded the integer the result wrote, so the + // decimal string would name a different length than the other engines copy. + if (!Number.isSafeInteger(ticks)) { + throw refusal('number_out_of_range', `ticks ${ticks} is beyond what every engine holds exactly`); + } + return String(ticks); +} + +// ------------------------------------------------------------------------------ work order + +/** + * The display units, read from the result rather than re-derived from request defaults: the + * result already rendered every value in them. + */ +function unitsOf(containers) { + if (containers.length === 0) return { lengthUnit: null, weightUnit: null }; + const [first] = containers; + const length = field(field(field(first, 'inner_dimensions', 'containers[0]'), 'length', 'inner_dimensions'), + 'unit', 'length'); + const weight = field(field(first, 'payload_weight', 'containers[0]'), 'unit', 'payload_weight'); + return { lengthUnit: length, weightUnit: weight }; +} + +function workOrderContainer(index, container, planContainer, lengthUnit, weightUnit) { + const byReference = placementsByReference(index, container); + // One line per plan step, in plan step order: the order is the plan's, looked up, never + // derived a second time. + const lines = planContainer.steps.map((step) => { + const placement = byReference.get(referenceKey(step.placement)); + const line = {}; + if (hasOwn(step, 'sequence')) line.sequence = step.sequence; + const position = field(placement, 'position', 'placement'); + const dimensions = field(placement, 'dimensions', 'placement'); + line.placement = step.placement; + line.position = renderedValues(position, POSITION_AXES, 'position', lengthUnit); + line.dimensions = renderedValues(dimensions, DIMENSION_AXES, 'dimensions', lengthUnit); + return line; + }); + return { + container_index: index, + container_type: get(container, 'container_type'), + payload_weight: renderedValue(field(container, 'payload_weight', `containers[${index}]`), weightUnit), + gross_weight: renderedValue(field(container, 'gross_weight', `containers[${index}]`), weightUnit), + lines, + }; +} + +function renderedValues(mapping, axes, where, unit) { + const values = {}; + for (const axis of axes) values[axis] = renderedValue(field(mapping, axis, where), unit); + return values; +} + +/** A hash lookup per step, so the work order stays O(P) rather than scanning per line. */ +function placementsByReference(index, container) { + const placements = placementsOf(index, container); + const found = new Map(); + for (const placement of placements) { + found.set(referenceKey(placementReference(index, placement)), placement); + } + if (found.size !== placements.length) { + throw refusal('invalid_result', + `two placements in container ${index} share an origin, type and orientation`); + } + return found; +} + +function referenceKey(reference) { + const ticks = reference.position_ticks; + return JSON.stringify([reference.item_type, reference.orientation, ticks.x, ticks.y, ticks.z]); +} + +/** The result's rendered value, copied and never re-rendered. */ +function renderedValue(scalar, unit) { + const found = field(scalar, 'unit', 'exact scalar'); + if (found !== unit) { + throw refusal('mixed_units', `a value in ${String(found)} where the result uses ${String(unit)}`); + } + const value = field(scalar, 'value', 'exact scalar'); + if (typeof value !== 'string') { + throw refusal('invalid_result', `value ${String(value)} is not a string`); + } + return value; +} + +// --------------------------------------------------------------------------------- helpers + +/** + * Every list entry the artifact and its plan read is an object, checked before either reads + * one, so a malformed result is refused by name in every engine instead of failing wherever + * each language first touches it. Linear in the entries it checks. + */ +function requireObjects(result) { + for (const name of ['containers', 'unpacked_items', 'alternatives', 'catalog_versions_used']) { + if (!list(get(result, name), `result.${name}`).every(isMapping)) { + throw refusal('invalid_result', `result.${name} holds a non-object entry`); + } + } + list(get(result, 'containers'), 'result.containers').forEach((container, index) => { + if (!placementsOf(index, container).every(isMapping)) { + throw refusal('invalid_result', `containers[${index}].placements holds a non-object entry`); + } + }); +} + +function placementsOf(index, container) { + return list(get(container, 'placements'), `containers[${index}].placements`); +} + +function list(value, where) { + if (value === null) return []; + if (!Array.isArray(value)) throw refusal('invalid_result', `${where} is not a list`); + return [...value]; +} + +function field(mapping, name, where) { + if (!isMapping(mapping) || !hasOwn(mapping, name)) { + throw refusal('invalid_result', `${where} has no ${name}`); + } + return mapping[name]; +} + +/** Python's `Mapping.get`: an absent key reads as null, and never from the prototype. */ +function get(mapping, name) { + return isMapping(mapping) && hasOwn(mapping, name) ? (mapping[name] ?? null) : null; +} + +function isMapping(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function hasOwn(mapping, name) { + return Object.prototype.hasOwnProperty.call(mapping, name); +} + +function refusal(code, message) { + return new OperationalArtifactError(code, message); +} diff --git a/canonical-json.js b/canonical-json.js new file mode 100644 index 0000000..37f17da --- /dev/null +++ b/canonical-json.js @@ -0,0 +1,113 @@ +/** + * RFC 8785 canonical JSON: the one spelling four engines can agree on byte for byte. + * + * Held to `packvium._canonical_json`. RFC 8785 follows JavaScript, so most of the rules are + * what `JSON.stringify` already does for a well-formed string and a finite number; what this + * module adds is the key sort (`JSON.stringify` keeps insertion order) and the refusals. + * + * - Object keys are sorted by UTF-16 code units, which is what `Array.prototype.sort` compares. + * - Strings escape `"`, `\` and U+0000..U+001F (`\b \t \n \f \r` by name, the rest as + * lowercase `\u00xx`); everything else is literal. + * - Numbers are written as ECMAScript's `Number::toString` writes them. No whitespace. + * + * Refused, with the code the other engines use: a number beyond 2^53 - 1 or not finite + * (`number_out_of_range`), a string carrying a lone surrogate (`invalid_string`), and any value + * JSON cannot spell (`invalid_value`). + * + * The traversal order is Python's on purpose: every key of an object is spelled before any of + * its values, then values are written in sorted key order. When a document breaks two rules, + * that order decides which code is reported, and the code is compared across engines. + */ + +const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + if (index) parts.push(','); + parts.push(spelled.get(key), ':'); + write(value[key], parts); + }); + parts.push('}'); +} + +function spellString(text) { + if (LONE_SURROGATE.test(text)) { + throw new CanonicalJsonError('invalid_string', 'a string carries a lone UTF-16 surrogate'); + } + // For a well-formed string `JSON.stringify` escapes exactly the RFC 8785 set, with + // lowercase hex, and writes `/`, U+007F, U+2028 and U+2029 literally. + return JSON.stringify(text); +} + +function spellNumber(value) { + if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER) { + throw new CanonicalJsonError('number_out_of_range', + `${value} is beyond what every engine holds exactly`); + } + // `String(-0)` is `0`, as RFC 8785 requires. + return String(value); +} + +function isPlainObject(value) { + if (typeof value !== 'object') return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function describe(value) { + if (value === undefined) return 'undefined'; + if (typeof value !== 'object') return typeof value; + return value.constructor?.name ?? 'object'; +} diff --git a/commerce-model.js b/commerce-model.js index 2a61c58..54f4738 100644 --- a/commerce-model.js +++ b/commerce-model.js @@ -51,15 +51,17 @@ export function exact(value) { * would make this implementation disagree with the other three on exactly those inputs. */ export function compareCodePoints(left, right) { - const a = Array.from(left); - const b = Array.from(right); - const shared = Math.min(a.length, b.length); - for (let index = 0; index < shared; index += 1) { - const difference = a[index].codePointAt(0) - b[index].codePointAt(0); - if (difference !== 0) return difference < 0 ? -1 : 1; + let leftIndex = 0; + let rightIndex = 0; + while (leftIndex < left.length && rightIndex < right.length) { + const a = left.codePointAt(leftIndex); + const b = right.codePointAt(rightIndex); + if (a !== b) return a < b ? -1 : 1; + leftIndex += a > 0xffff ? 2 : 1; + rightIndex += b > 0xffff ? 2 : 1; } - if (a.length === b.length) return 0; - return a.length < b.length ? -1 : 1; + if (leftIndex === left.length) return rightIndex === right.length ? 0 : -1; + return 1; } // ------------------------------------------------------------------------------ rating diff --git a/commerce.js b/commerce.js index b578438..4ed1786 100644 --- a/commerce.js +++ b/commerce.js @@ -307,7 +307,7 @@ function parseCatalogVersion(value, path, _identity, number, history) { function parseRollback(fields, path, number, history) { checkKeys(fields, path, ['rollback_to', 'published_at'], ['effective_at', 'note']); const toVersion = asInteger(fields.rollback_to, `${path}.rollback_to`); - const target = history.find((version) => version.number === toVersion); + const target = catalogVersionByNumber(history, toVersion); if (target === undefined) { fail(path, `rollback_to names version ${toVersion}, which is not published yet`); } @@ -613,9 +613,13 @@ export function catalogVersionInfo(document, request) { return ok('catalog', catalogPayload(catalogId, resolved, resolvedAt)); } +function catalogVersionByNumber(history, number) { + return number >= 1 && number <= history.length ? history[number - 1] : undefined; +} + function resolveCatalogVersion(history, version, asOf) { if (version !== undefined) { - return history.find((candidate) => candidate.number === version) ?? 'catalog_version_not_found'; + return catalogVersionByNumber(history, version) ?? 'catalog_version_not_found'; } if (asOf === undefined) { return history.length > 1 ? 'ambiguous_catalog_reference' : history[0]; diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 44a9cea..1e5eb73 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -48,7 +48,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.2.0` freezes the public API. Field names, status codes, the objective +Version `1.3.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index ecf9af0..d24251f 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -512,6 +512,47 @@ solve runs. Python only, and deliberately so: a lock has no representation in the request schema, since that field is held for the next contract freeze, so there is nothing to hand another engine. +Since 1.3.0 the canonical form is RFC 8785, the spelling the operational artifact uses. For +every plan an engine emits the bytes are the ones 1.2.0 wrote. + +## Operational artifact + +One portable document built from a validated result. It carries: +- the execution plan, unchanged; +- the geometry needed to draw it; +- the rendered values a work order prints; +- the provenance needed to replay it: the request itself, the catalogs, the deterministic part + of the solver record, and an honest replay level. + +It is exported as JSON, RFC 4180 CSV, or a self-contained printable HTML work order. Like the +plan it is a view, not a decision: no solver, validator, renderer or clock is called. The +contract is OPERATIONAL-ARTIFACTS.md. + +| Language | Builder | Exports | +| --- | --- | --- | +| Python | `packvium.artifacts.build_operational_artifact(request, result, loading_orders=...)`, `.canonical_artifact_json(artifact)` | `packvium.artifact_exports.export_json(artifact)`, `.export_csv(artifact)`, `.export_work_order_html(artifact)` | +| PHP | `Packvium\Artifacts\OperationalArtifact` | `Packvium\Artifacts\ArtifactExports` | +| Rust | `packvium_core::artifacts::build_artifact_json(request_json, result_json, loading_orders_json)` | `packvium_core::artifact_exports::export_json`, `export_csv`, `export_work_order_html` | +| JavaScript | `buildOperationalArtifact(request, result, {loadingOrders})`, `canonicalArtifactJson(artifact)` from `@packvium/engine`'s `artifacts.js` | `exportJson`, `exportCsv`, `exportWorkOrderHtml` from `artifact-exports.js` | + +All four are held to **byte-identical** output on all three exports. The comparison covers +every golden result with its own request and a real loading order, plus edge cases no fixture +contains. The schema is closed. + +**Placements are addressed by the plan's `placement_ref`, never by `item_id`**, in geometry, in +work-order lines, in CSV rows and in the visualizer. Work-order lines are the plan's steps, +looked up in the plan's order and never re-ordered. + +**Replay is stated, not assumed.** `provenance.replay.level` is `exact` only when solving the +embedded request again must reproduce the result. When the search stopped on wall-clock time, +or the result does not record how it was solved, the level is `not_guaranteed`, and `because` +names the field that decided it. + +**Refusals use one closed set of codes** in every language (`invalid_request`, `invalid_result`, +`invalid_plan_input`, `mixed_units`, `number_out_of_range`, `invalid_string`, `invalid_value`, +`unknown_format`, `invalid_json`). An export or reader handed a format it does not know refuses +it rather than guessing. + ## Scenario and recommendation API Scenario what-if comparison and catalog/rule recommendation publication, exported as diff --git a/examples/artifacts.mjs b/examples/artifacts.mjs new file mode 100644 index 0000000..61b3447 --- /dev/null +++ b/examples/artifacts.mjs @@ -0,0 +1,93 @@ +/** + * Hand a packing result to a warehouse system that has no engine. + * + * Run it: + * + * node examples/artifacts.mjs + * + * An execution plan says what to lift first. A warehouse or transport system needs more than + * that before it can act on its own: how big each box is, what the load weighs, a sheet to + * print for the dock, and a record of which request and solver produced it. + * + * The operational artifact is that one document. It wraps the plan unchanged and adds geometry, + * display values and provenance, and it exports to JSON, CSV and a printable HTML work order + * without calling a solver, a renderer or a clock. Every Packvium engine builds the same bytes + * from the same request and result -- though this engine may reach a different, equally valid + * packing than Python does, and then the artifact describes that packing. + */ + +import { pack } from '../index.js'; +import { buildOperationalArtifact, OperationalArtifactError } from '../artifacts.js'; +import { exportCsv, exportJson, exportWorkOrderHtml } from '../artifact-exports.js'; + +const request = { + units: { length: 'mm' }, + configuration: { + // A safety fuse far above what this solve needs, so the answer never depends on load. + time_limit_ms: 60000, + }, + items: [ + { id: 'printer', quantity: 1, weight: '12 kg', + dimensions: { length: '420', width: '300', height: '250' }, + metadata: { sales_order: 'SO-1042' } }, + { id: 'toner', quantity: 3, weight: '1.5 kg', + dimensions: { length: '300', width: '100', height: '100' } }, + ], + containers: [ + { id: 'crate', quantity: 1, inner_dimensions: { length: '800', width: '400', height: '400' } }, + ], +}; + +const result = pack(request); +const rule = '='.repeat(78); + +function section(title) { + console.log(); + console.log(rule); + console.log(title); + console.log(rule); +} + +section('1. One document that carries everything a consumer needs'); + +// No loading order is passed, so the plan lists every placement unnumbered. An engine's +// sequence API supplies a safe order; the artifact never invents one. +const artifact = buildOperationalArtifact(request, result); +console.log(` format: ${artifact.format}`); +console.log(` plan steps: ${artifact.plan.containers[0].steps.length}`); +console.log(` crate inside: ${artifact.geometry.containers[0].inner_dimensions.length} ticks long`); +console.log(` order: ${artifact.plan.containers[0].order}`); +console.log(` sales order: ${artifact.provenance.request.items[0].metadata.sales_order}`); +console.log(); +console.log(' The request is inside the artifact, not a hash of it: only the request itself lets'); +console.log(' someone replay the artifact without a lookup. The order is `unavailable` because'); +console.log(' none was supplied, and the work order says so instead of numbering boxes by'); +console.log(' accident.'); + +section('2. A CSV a warehouse system can import'); + +for (const row of exportCsv(artifact).split('\r\n').slice(0, 3)) console.log(` ${row}`); +console.log(); +console.log(' One row per step, then one per item that was not packed. The tick columns are the'); +console.log(' identifiers a system matches on; the rendered columns are for people.'); + +section('3. A work order to print'); + +const html = exportWorkOrderHtml(artifact); +console.log(` ${Buffer.byteLength(html)} bytes of HTML, one section per container, one checkbox per step`); +console.log(` contains a script or an external resource: ${html.includes('}):ExecutionPlan; -/** The one byte-comparable spelling, with keys sorted recursively and arrays left in place. */ +/** What `canonicalPlanJson` throws. The class is internal, so match on `code`, not `instanceof`. */ +export interface CanonicalJsonError extends Error{code:'number_out_of_range'|'invalid_string'|'invalid_value'} + +/** + * The one byte-comparable spelling: RFC 8785, keys sorted by UTF-16 code units, arrays left in + * place. Throws a `CanonicalJsonError` for a number beyond 2^53 - 1 or not finite, a lone + * surrogate, or a value JSON cannot spell. + */ export function canonicalPlanJson(plan:ExecutionPlan):string; diff --git a/execution.js b/execution.js index 12cb154..7d70ed1 100644 --- a/execution.js +++ b/execution.js @@ -8,12 +8,9 @@ * forever. * * Held to byte-identical output with `packvium.execution`, `Packvium\Execution\Plan` and - * `packvium_core::execution`. JavaScript is the one that needs care for that: `JSON.stringify` - * emits keys in insertion order, so this module sorts them itself, and it is also this - * project's known odd one out for string order -- `sort()` compares UTF-16 code units where - * the other three compare code points. Every key sorted here is an ASCII identifier this - * module writes, so the two orders coincide; a key derived from caller data would not be - * safe to sort this way and none is. + * `packvium_core::execution`. The spelling they are compared on is RFC 8785 + * (`canonical-json.js`), which sorts keys by UTF-16 code units in every engine, so a key + * outside the Basic Multilingual Plane no longer orders differently here. * * Two rules do the work, and both are about not quietly becoming a decision-maker. * Authoritative solver facts and human text are separated in the *output*, under `facts` @@ -23,6 +20,8 @@ * instance count rather than a semantic property". */ +import { canonicalJson } from './canonical-json.js'; + /** The plan's own format tag; not the packing schema's version, and it does not move with it. */ export const FORMAT = 'packvium-execution-plan/v1'; @@ -212,24 +211,13 @@ export function buildExecutionPlan(request, result, { loadingOrders = {} } = {}) } /** - * Sort object keys recursively, leaving arrays in place. - * - * A list stays a list: sorting one would reorder steps, which are ordered on purpose. - */ -function sortKeys(value) { - if (Array.isArray(value)) return value.map(sortKeys); - if (value === null || typeof value !== 'object') return value; - const sorted = {}; - for (const key of Object.keys(value).sort()) sorted[key] = sortKeys(value[key]); - return sorted; -} - -/** - * The one byte-comparable spelling of a plan. + * The one byte-comparable spelling of a plan: RFC 8785, shared with the operational artifact + *. Objects are key-sorted and arrays keep their order, so steps are never reordered. * - * `JSON.stringify` emits insertion order, so the sort above is what makes this comparable - * with Python's `sort_keys=True`, PHP's recursive `ksort` and `serde_json`'s `BTreeMap`. + * Until 1.3.0 this was `JSON.stringify` over recursively sorted keys. That is the same bytes + * for every plan an engine emits, but it wrote `null` for a non-finite number and escaped a + * lone surrogate, where the canonical form refuses both with a `CanonicalJsonError`. */ export function canonicalPlanJson(plan) { - return JSON.stringify(sortKeys(plan)); + return canonicalJson(plan); } diff --git a/fallback.js b/fallback.js index a9db2d7..0ac48d2 100644 --- a/fallback.js +++ b/fallback.js @@ -707,7 +707,7 @@ function cellKey(ix,iy,iz){return (ix*4096+iy)*4096+iz} function makeIndex(d){return {cx:Math.max(1,ceilDiv(Math.max(1,d[0]),CELLS_PER_AXIS)), cy:Math.max(1,ceilDiv(Math.max(1,d[1]),CELLS_PER_AXIS)), cz:Math.max(1,ceilDiv(Math.max(1,d[2]),CELLS_PER_AXIS)), - cells:new Map(),seen:[],gen:0}} + cells:new Map(),owned:new WeakSet(),seen:[],gen:0}} function cellRange(index,box){return [ Math.floor(box.x/index.cx),ceilDiv(Math.max(box.x+box.d[0],box.x+1),index.cx), Math.floor(box.y/index.cy),ceilDiv(Math.max(box.y+box.d[1],box.y+1),index.cy), @@ -715,11 +715,18 @@ function cellRange(index,box){return [ function indexAdd(index,position,box){const [ix1,ix2,iy1,iy2,iz1,iz2]=cellRange(index,box); index.seen[position]=0; for(let ix=ix1;ix[key,bucket.slice()])), - seen:index.seen.slice(),gen:index.gen}} + const key=cellKey(ix,iy,iz);let bucket=index.cells.get(key); + if(!bucket||!index.owned.has(bucket)){ + bucket=bucket?bucket.slice():[];index.cells.set(key,bucket);index.owned.add(bucket)} + bucket.push(position)}} +function copyIndex(index){ + // Both sides now share buckets; neither may append until it owns a private copy. + index.owned=new WeakSet(); + return {cx:index.cx,cy:index.cy,cz:index.cz,cells:new Map(index.cells),owned:new WeakSet(), + seen:index.seen.slice(),gen:index.gen}} + +// Private-module test access to per-call index state; not re-exported by index.js. +export const __spatialIndexForTests=Object.freeze({make:makeIndex,add:indexAdd,copy:copyIndex}); function comparePoints(a,b){return a[2]-b[2]||a[1]-b[1]||a[0]-b[0]} function insertPoint(points,point){let low=0,high=points.length; while(low>1;if(comparePoints(points[mid],point)<=0)low=mid+1;else high=mid} @@ -1944,7 +1951,7 @@ const tryPackIntoTemplate=(tmpl,itemsRemaining)=>{const state={tmpl,placements:[ for(const point of pointsFrom(best))insertPoint(points,point)} if(!ok){state.placements=snapshotPlacements;state.payload=snapshotPayload;used=snapshotUsed; if(snapshotPoints)points.splice(0,points.length,...snapshotPoints); - if(snapshotIndex){index.cells=snapshotIndex.cells;index.seen=snapshotIndex.seen}next.push(...batch)}} + if(snapshotIndex){index.cells=snapshotIndex.cells;index.owned=snapshotIndex.owned;index.seen=snapshotIndex.seen}next.push(...batch)}} return {state,next,used} }; const packBeamIntoTemplate=(tmpl,itemsRemaining)=>{ @@ -1971,12 +1978,18 @@ const packBeamIntoTemplate=(tmpl,itemsRemaining)=>{ if(!future.some(item=>item.nesting!=null))possible=Math.min(possible,maxCount(sortedVolumes??sortCosts(future.map(item=>volume(item.d))),volume(tmpl.d)-node.used)); if(tmpl.max!=null)possible=Math.min(possible,maxCount(sortedWeights??sortCosts(future.map(item=>BigInt(item.w))),BigInt(Math.max(0,tmpl.max-node.state.payload)))); return node.unplaced.length+future.length-possible}; - const compareNode=(a,b,future=[],sortedVolumes=null,sortedWeights=null)=>{let difference=lowerBound(a,future,sortedVolumes,sortedWeights)-lowerBound(b,future,sortedVolumes,sortedWeights);if(difference)return difference; + // Compared states are complete; placement always mutates a fresh clone first. + // Weak keys let discarded branches release their cached strings with their state. + const stateKeys=new WeakMap(); + const stateKey=state=>{let key=stateKeys.get(state);if(key===undefined){ + key={maxZ:state.placements.reduce((z,p)=>Math.max(z,p.z+p.ed[2]),0),signature:undefined};stateKeys.set(state,key)}return key}; + const signature=state=>{const key=stateKey(state);if(key.signature===undefined)key.signature=state.placements.map(p=>`${p.item.id}@${p.x},${p.y},${p.z}`).join('|');return key.signature}; + const compareNode=(a,b,bounds=null)=>{let difference=bounds===null?a.unplaced.length-b.unplaced.length:bounds.get(a)-bounds.get(b);if(difference)return difference; difference=a.unplaced.length-b.unplaced.length;if(difference)return difference; difference=b.state.placements.length-a.state.placements.length;if(difference)return difference; - const az=a.state.placements.reduce((z,p)=>Math.max(z,p.z+p.ed[2]),0),bz=b.state.placements.reduce((z,p)=>Math.max(z,p.z+p.ed[2]),0); + const az=stateKey(a.state).maxZ,bz=stateKey(b.state).maxZ; if(az!==bz)return az-bz;if(a.used!==b.used)return a.used>b.used?-1:1; - const signature=node=>node.state.placements.map(p=>`${p.item.id}@${p.x},${p.y},${p.z}`).join('|');return compareCodePoints(signature(a),signature(b))}; + return compareCodePoints(signature(a.state),signature(b.state))}; const greedy=tryPackIntoTemplate(tmpl,itemsRemaining);let beam=[fresh()],incumbent=fresh();incumbent.state=greedy.state;incumbent.used=greedy.used;incumbent.unplaced=greedy.next;let nodes=0; // The batch the loop stopped before, when it stopped early (node limit, deadline or // effort). Surviving beam nodes have consumed only the batches before it, so completing @@ -1998,7 +2011,8 @@ const packBeamIntoTemplate=(tmpl,itemsRemaining)=>{ if(!expansions.length||exhausted){pendingFrom=position;break} const futureVolumes=future.some(item=>item.nesting!=null)?null:sortCosts(future.map(item=>volume(item.d))); const futureWeights=tmpl.max!=null?sortCosts(future.map(item=>BigInt(item.w))):null; - expansions.sort((a,b)=>compareNode(a,b,future,futureVolumes,futureWeights));beam=expansions.slice(0,containerPlanBeamWidth)} + const bounds=new Map(expansions.map(node=>[node,lowerBound(node,future,futureVolumes,futureWeights)])); + expansions.sort((a,b)=>compareNode(a,b,bounds));beam=expansions.slice(0,containerPlanBeamWidth)} // Without the unreached tail a beam leader looks better than every complete incumbent, // and choosing it dropped those items outright: neither placed nor reported unpacked. const pending=pendingFrom===null?[]:batches.slice(pendingFrom).flat(); diff --git a/index.js b/index.js index df0e823..1229d15 100644 --- a/index.js +++ b/index.js @@ -69,7 +69,7 @@ export function rebalanceWeight(request, result, { maxMoves = 64 } = {}) { return rebalanceFallback(request, result, { maxMoves }); } -export const version = () => native?.version?.() ?? '1.2.0-js-fallback'; +export const version = () => native?.version?.() ?? '1.3.0-js-fallback'; /** * The exported commercial and control-plane API: a quote, a policy decision and catalog diff --git a/package.json b/package.json index 1f8d0f0..50975eb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name":"@packvium/engine", - "version":"1.2.0", + "version":"1.3.0", "description":"Native-first 3D cartonization with deterministic JS fallback", "author":{"name":"Packvium","url":"https://packvium.com"}, "keywords":["3d-bin-packing","bin-packing","cartonization","packing","container-loading","logistics","shipping","deterministic"], @@ -10,8 +10,8 @@ "type":"module", "main":"index.js", "types":"index.d.ts", - "exports":{".":{"types":"./index.d.ts","import":"./index.js"},"./execution.js":{"types":"./execution.d.ts","import":"./execution.js"}}, - "files":["index.js","fallback.js","contact-graph.js","policy.js","commerce.js","commerce-model.js","execution.js","examples","index.d.ts","execution.d.ts","README.md","SECURITY.md"], + "exports":{".":{"types":"./index.d.ts","import":"./index.js"},"./execution.js":{"types":"./execution.d.ts","import":"./execution.js"},"./artifacts.js":{"types":"./artifacts.d.ts","import":"./artifacts.js"},"./artifact-exports.js":{"types":"./artifact-exports.d.ts","import":"./artifact-exports.js"}}, + "files":["index.js","fallback.js","contact-graph.js","policy.js","commerce.js","commerce-model.js","execution.js","canonical-json.js","artifacts.js","artifact-exports.js","examples","index.d.ts","execution.d.ts","artifacts.d.ts","artifact-exports.d.ts","README.md","SECURITY.md"], "engines":{"node":">=16"}, "scripts":{ "test":"node test/run-tests.mjs", diff --git a/test/artifacts.test.mjs b/test/artifacts.test.mjs new file mode 100644 index 0000000..cf64803 --- /dev/null +++ b/test/artifacts.test.mjs @@ -0,0 +1,533 @@ +/** + * The operational artifact and its exports in JavaScript. + * + * docs/OPERATIONAL-ARTIFACTS.md is the contract and `packvium.artifacts` is the reference; these + * tests mirror `packvium-python/tests/test_artifacts.py` and `test_canonical_json.py`. The + * modules are imported by package name, so a missing `exports` entry fails here and not only in + * a consumer's project. Strings that carry surrogates or line separators are built from code + * points, so this source stays ASCII. + */ + +import { strict as assert } from 'node:assert'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { + FORMAT, + OperationalArtifactError, + SUITE_VERSION, + buildOperationalArtifact, + canonicalArtifactJson, +} from '@packvium/engine/artifacts.js'; +import { + CSV_COLUMNS, + exportCsv, + exportJson, + exportWorkOrderHtml, +} from '@packvium/engine/artifact-exports.js'; +import { buildExecutionPlan, canonicalPlanJson } from '@packvium/engine/execution.js'; + +const PACKAGE_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const TICKS_PER_MM = 16000; +const LINE_SEPARATOR = String.fromCharCode(0x2028); + +const scalar = (ticks, unit = 'mm') => ({ + ticks, unit, value: String(Math.trunc(ticks / (unit === 'mm' ? TICKS_PER_MM : 8000))), +}); + +const placement = (itemType, xMm, lengthMm = 10, orientation = 'LWH') => ({ + item_id: `${itemType}#${xMm}`, + item_type: itemType, + orientation, + position: { x: scalar(xMm * TICKS_PER_MM), y: scalar(0), z: scalar(0) }, + dimensions: { + length: scalar(lengthMm * TICKS_PER_MM), width: scalar(10 * TICKS_PER_MM), height: scalar(10 * TICKS_PER_MM), + }, + support_ratio: '1.000000', + top_load: scalar(0, 'g'), +}); + +const ALGORITHM = { + profile: 'balanced', solver: 'extreme_point', seed: 7, duration_ms: 41, + time_limit_reached: false, effort_limit_reached: false, +}; + +function result({ algorithm = ALGORITHM, placements, unpacked } = {}) { + const built = { + status: 'feasible', + objective: 'default', + score: [1, 0, 250], + feasibility: { code: 'all_items_packed' }, + optimality: null, + containers: [{ + id: 'crate#1', + container_type: 'crate', + inner_dimensions: { + length: scalar(100 * TICKS_PER_MM), width: scalar(100 * TICKS_PER_MM), height: scalar(100 * TICKS_PER_MM), + }, + payload_weight: scalar(8000, 'g'), + gross_weight: scalar(16000, 'g'), + volume_utilization: '0.002000', + placements: placements ?? [placement('box', 0), placement('tin', 10, 5)], + }], + unpacked_items: unpacked ?? [], + catalog_versions_used: [{ catalog_id: 'cartons', version: 3, effective_at: 10, resolved_at: 11 }], + }; + if (algorithm !== null) built.algorithm = algorithm; + return built; +} + +const REQUEST = { + items: [{ id: 'box', dimensions: { length: 10, width: 10, height: 10 }, minimum_support_ratio: 0.25 }], + containers: [{ id: 'crate', inner_dimensions: { length: 100, width: 100, height: 100 } }], +}; + +function codeOf(run) { + try { + run(); + } catch (error) { + assert.ok(error instanceof OperationalArtifactError, `${error.name}: ${error.message}`); + return error.code; + } + assert.fail('expected an OperationalArtifactError'); +} + +const artifactOf = (options) => buildOperationalArtifact(REQUEST, result(options), { loadingOrders: { 0: [1, 0] } }); + +// ------------------------------------------------------------------------ canonical JSON + +// RFC 8785 numbers are ECMAScript's own, so these pin the rules rather than the arithmetic. +const NUMBERS = [ + [0.25, '0.25'], [1.0, '1'], [-0, '0'], [4.5, '4.5'], [0.1, '0.1'], [2e-3, '0.002'], + [0.000001, '0.000001'], [1e-7, '1e-7'], [1.5e-7, '1.5e-7'], [1e-27, '1e-27'], [-1.5, '-1.5'], + [123456789.5, '123456789.5'], [333333333.33333329, '333333333.3333333'], + [9007199254740991, '9007199254740991'], [5e-324, '5e-324'], [100.0, '100'], +]; + +test('numbers are written as ECMAScript writes them', () => { + for (const [value, spelled] of NUMBERS) assert.equal(canonicalArtifactJson(value), spelled); + assert.equal(canonicalArtifactJson([0, -7, true, false, null]), '[0,-7,true,false,null]'); +}); + +test('keys are sorted by UTF-16 code units, not code points', () => { + // U+FFFD sorts after U+1F600 by code point and before it by UTF-16 code unit. + const replacement = String.fromCharCode(0xFFFD); + const grin = String.fromCodePoint(0x1F600); + assert.equal(canonicalArtifactJson({ [replacement]: 1, [grin]: 2, a: 0 }), + `{"a":0,"${grin}":2,"${replacement}":1}`); +}); + +test('only the characters RFC 8785 names are escaped', () => { + const others = `/${String.fromCharCode(0x7F, 0x2028, 0x2029)}\u00e9`; + const text = `"\\\b\t\n\f\r${String.fromCharCode(0, 0x1F)}${others}`; + assert.equal(canonicalArtifactJson(text), `"\\"\\\\\\b\\t\\n\\f\\r\\u0000\\u001f${others}"`); + for (let code = 0; code < 0x20; code += 1) { + assert.match(canonicalArtifactJson(String.fromCharCode(code)), /^"\\([btnfr]|u00[0-9a-f]{2})"$/); + } +}); + +test('there is no whitespace, nesting is preserved and arrays keep their order', () => { + assert.equal(canonicalArtifactJson({ b: [1, { d: [], c: {} }], a: 'x' }), '{"a":"x","b":[1,{"c":{},"d":[]}]}'); +}); + +test('a number no engine holds exactly is refused', () => { + for (const value of [2 ** 53, -(2 ** 53), Infinity, -Infinity, NaN]) { + assert.equal(codeOf(() => canonicalArtifactJson({ n: value })), 'number_out_of_range', String(value)); + } +}); + +test('a lone surrogate is refused in a value and in a key', () => { + const high = String.fromCharCode(0xD800); + const low = String.fromCharCode(0xDC00); + for (const value of [high, `a${low}`, `${low}${high}`, { [low]: 1 }, [`x${high}y`]]) { + assert.equal(codeOf(() => canonicalArtifactJson(value)), 'invalid_string'); + } + assert.equal(canonicalArtifactJson(high + low), `"${high}${low}"`, 'a pair is well formed'); +}); + +test('a value JSON cannot spell is refused', () => { + // eslint-disable-next-line no-sparse-arrays + const values = [undefined, { a: undefined }, () => 1, 1n, Symbol('s'), new Map(), new Set([1]), + new Date(0), [1, , 2], { [Symbol('k')]: 1 }]; + for (const value of values) assert.equal(codeOf(() => canonicalArtifactJson(value)), 'invalid_value'); +}); + +test('the plan uses the same canonical form', () => { + const plan = buildExecutionPlan(REQUEST, result(), { loadingOrders: { 0: [1, 0] } }); + assert.equal(canonicalPlanJson(plan), canonicalArtifactJson(plan)); + assert.throws(() => canonicalPlanJson({ ...plan, objective: String.fromCharCode(0xDFFF) }), + (error) => error.code === 'invalid_string'); +}); + +// -------------------------------------------------------------------------- the document + +test('the plan inside is exactly the plan builder output', () => { + const orders = { 0: [1, 0] }; + const artifact = buildOperationalArtifact(REQUEST, result(), { loadingOrders: orders }); + assert.equal(artifact.format, FORMAT); + assert.equal(artifact.suite_version, SUITE_VERSION); + assert.equal(canonicalPlanJson(artifact.plan), + canonicalPlanJson(buildExecutionPlan(REQUEST, result(), { loadingOrders: orders }))); +}); + +test('the suite version is the package version', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')); + assert.equal(SUITE_VERSION, manifest.version); +}); + +test('the request is embedded as given, with its fractional numbers', () => { + const artifact = buildOperationalArtifact(REQUEST, result()); + assert.deepEqual(artifact.provenance.request, REQUEST); + assert.ok(canonicalArtifactJson(artifact).includes('"minimum_support_ratio":0.25')); +}); + +test('geometry is in result order, in tick strings, addressed by placement reference', () => { + const [container] = buildOperationalArtifact(REQUEST, result()).geometry.containers; + assert.deepEqual(container.inner_dimensions, { length: '1600000', width: '1600000', height: '1600000' }); + assert.deepEqual(container.placements.map((entry) => entry.placement.item_type), ['box', 'tin']); + assert.equal(container.placements[1].dimensions.length, '80000'); + assert.ok(!JSON.stringify(container).includes('item_id')); +}); + +test('work order lines follow the plan steps and copy rendered values', () => { + const artifact = artifactOf(); + const workOrder = artifact.work_order; + const [container] = workOrder.containers; + assert.deepEqual([workOrder.length_unit, workOrder.weight_unit], ['mm', 'g']); + assert.deepEqual([container.payload_weight, container.gross_weight], ['1', '2']); + assert.deepEqual(container.lines.map((line) => [line.sequence, line.placement.item_type]), [[1, 'tin'], [2, 'box']]); + assert.deepEqual(container.lines[0].position, { x: '10', y: '0', z: '0' }); + assert.deepEqual(artifact.plan.containers[0].steps.map((step) => step.placement), + container.lines.map((line) => line.placement)); +}); + +test('without a loading order no line is numbered', () => { + const { lines } = buildOperationalArtifact(REQUEST, result()).work_order.containers[0]; + assert.ok(lines.every((line) => !('sequence' in line))); +}); + +test('a result without containers has no units and no lines', () => { + const empty = { ...result(), containers: [] }; + assert.deepEqual(buildOperationalArtifact(REQUEST, empty).work_order, + { length_unit: null, weight_unit: null, containers: [] }); +}); + +// ---------------------------------------------------------------------------- provenance + +test('the solver is the deterministic part of the algorithm and wall clock never enters', () => { + const artifact = buildOperationalArtifact(REQUEST, result()); + assert.deepEqual(artifact.provenance.solver, { + profile: 'balanced', solver: 'extreme_point', seed: 7, time_limit_reached: false, effort_limit_reached: false, + }); + assert.deepEqual(artifact.provenance.replay, { level: 'exact', because: null }); + assert.equal(artifact.provenance.catalog_versions_used[0].catalog_id, 'cartons'); + assert.ok(!canonicalArtifactJson(artifact).includes('duration_ms')); +}); + +test('a search stopped by the clock is not promised an exact replay', () => { + const { replay } = buildOperationalArtifact(REQUEST, result({ + algorithm: { ...ALGORITHM, time_limit_reached: true }, + })).provenance; + assert.deepEqual(replay, { level: 'not_guaranteed', because: 'provenance.solver.time_limit_reached' }); +}); + +test('a result that does not say how it was solved is not promised one either', () => { + const { provenance } = buildOperationalArtifact(REQUEST, result({ algorithm: null })); + assert.equal(provenance.solver, null); + assert.deepEqual(provenance.replay, { level: 'not_guaranteed', because: 'provenance.solver' }); +}); + +// ------------------------------------------------------------------------------ refusals + +test('a request that is not an object is refused', () => { + for (const request of [[], null, 'request']) { + assert.equal(codeOf(() => buildOperationalArtifact(request, result())), 'invalid_request'); + } + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, [])), 'invalid_result'); +}); + +test('a loading order that is not a permutation is refused by the plan', () => { + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, result(), { loadingOrders: { 0: [0, 0] } })), + 'invalid_plan_input'); +}); + +test('values in two units are refused rather than printed as one', () => { + const mixed = result(); + mixed.containers[0].placements[0].position.x.unit = 'cm'; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, mixed)), 'mixed_units'); +}); + +test('two placements with one reference are refused', () => { + const duplicated = result({ placements: [placement('box', 0), placement('box', 0)] }); + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, duplicated)), 'invalid_result'); +}); + +test('a container without inner dimensions is refused', () => { + const broken = result(); + delete broken.containers[0].inner_dimensions; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, broken)), 'invalid_result'); +}); + +test('an algorithm record that is incomplete or mistyped is refused', () => { + for (const algorithm of [{ profile: 'fast' }, { ...ALGORITHM, time_limit_reached: 'no' }, 'fast']) { + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, result({ algorithm }))), 'invalid_result'); + } +}); + +test('a catalog reference that is incomplete or mistyped is refused', () => { + const catalog = { catalog_id: 'cartons', version: 3, effective_at: 10, resolved_at: 11 }; + const broken = [ + { ...catalog, version: 1.5 }, { ...catalog, effective_at: true }, { ...catalog, resolved_at: '11' }, + { ...catalog, catalog_id: 7 }, { catalog_id: 'cartons', version: 3, effective_at: 10 }, + ]; + for (const entry of broken) { + const mistyped = { ...result(), catalog_versions_used: [entry] }; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, mistyped)), 'invalid_result', JSON.stringify(entry)); + } +}); + +test('a non-object list entry is refused as an invalid result before the plan is built', () => { + // A non-permutation order would be `invalid_plan_input` from the plan builder; the entry + // check runs first, so every engine names the malformed result instead. + const orders = { loadingOrders: { 0: [0, 0] } }; + const cases = [ + { ...result(), containers: ['crate'] }, + { ...result(), unpacked_items: [null] }, + { ...result(), alternatives: [[1, 0]] }, + { ...result(), alternatives: { score: [1] } }, + { ...result(), catalog_versions_used: ['cartons'] }, + result({ placements: [placement('box', 0), 'tin'] }), + ]; + for (const broken of cases) { + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, broken, orders)), 'invalid_result'); + } +}); + +test('a field is read from the object itself, never from its prototype', () => { + // `field in object` would find `constructor` on every object; a missing key must stay missing. + const broken = result(); + broken.containers[0].inner_dimensions = Object.create({ length: scalar(1), width: scalar(1), height: scalar(1) }); + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, broken)), 'invalid_result'); +}); + +test('a request number JavaScript cannot hold is refused', () => { + assert.equal(codeOf(() => buildOperationalArtifact({ ...REQUEST, metadata: { order: 2 ** 53 } }, result())), + 'number_out_of_range'); +}); + +test('a tick count beyond 2^53 - 1 is refused rather than written as a rounded length', () => { + const huge = result(); + huge.containers[0].inner_dimensions.width.ticks = 2 ** 60; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, huge)), 'number_out_of_range'); +}); + +test('a result that is not an object is refused', () => { + for (const notAnObject of [null, 'result', 42, [result()]]) { + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, notAnObject)), 'invalid_result', String(notAnObject)); + } +}); + +test('a list field that is not a list is refused before the plan is built', () => { + // `{}` and a string would each be iterated differently by the four languages' plan builders. + const orders = { loadingOrders: { 0: [0, 0] } }; + for (const [name, value] of [['containers', {}], ['unpacked_items', 'jack'], ['catalog_versions_used', {}]]) { + const broken = { ...result(), [name]: value }; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, broken, orders)), 'invalid_result', name); + } +}); + +test('geometry ticks that are not an integer are refused', () => { + // A fraction, a boolean or a numeric string has no single decimal spelling across engines; + // copying the string would also hide that the result broke its own schema. + for (const ticks of [1.5, true, '160000', null]) { + const inner = result(); + inner.containers[0].inner_dimensions.width.ticks = ticks; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, inner)), 'invalid_result', `inner ${String(ticks)}`); + const placed = result(); + placed.containers[0].placements[1].dimensions.height.ticks = ticks; + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, placed)), 'invalid_result', `placement ${String(ticks)}`); + } +}); + +test('a rendered value that is not a string is refused rather than re-rendered', () => { + // The work order copies the result's rendering; a number here would be rendered by this + // engine instead, which is exactly what the artifact promises never to do. + const edits = [ + (built) => { built.containers[0].placements[0].position.x.value = 0; }, + (built) => { built.containers[0].placements[1].dimensions.length.value = null; }, + (built) => { built.containers[0].payload_weight.value = 1; }, + (built) => { built.containers[0].gross_weight.value = ['2']; }, + ]; + for (const edit of edits) { + const broken = result(); + edit(broken); + assert.equal(codeOf(() => buildOperationalArtifact(REQUEST, broken)), 'invalid_result', String(edit)); + } +}); + +test('a printed integer beyond 2^53 - 1 is refused rather than printed rounded', () => { + // Reachable only through an artifact edited after it was built: the builder would have + // refused the same number. JSON refuses it too, so the exports agree. + const edited = JSON.parse(JSON.stringify(artifactOf())); + edited.work_order.containers[0].lines[0].placement.position_ticks.x = 2 ** 60; + assert.equal(codeOf(() => exportCsv(edited)), 'number_out_of_range'); + assert.equal(codeOf(() => exportJson(edited)), 'number_out_of_range'); + const heading = JSON.parse(JSON.stringify(artifactOf())); + heading.work_order.containers[0].container_index = Number.MAX_SAFE_INTEGER; + assert.equal(codeOf(() => exportWorkOrderHtml(heading)), 'number_out_of_range', 'the index plus one'); +}); + +test('the builder imports no solver, validator, renderer or clock', () => { + const allowed = { + 'canonical-json.js': [], + 'artifacts.js': ['./canonical-json.js', './execution.js'], + 'artifact-exports.js': ['./artifacts.js'], + }; + for (const [name, imports] of Object.entries(allowed)) { + const source = fs.readFileSync(path.join(PACKAGE_ROOT, name), 'utf8'); + const found = [...source.matchAll(/^import\s[^;]*?from\s+'([^']+)';/gms)].map((match) => match[1]).sort(); + assert.deepEqual(found, imports, name); + for (const forbidden of ['require(', 'Date', 'performance', 'Math.random', 'import(']) { + assert.ok(!source.includes(forbidden), `${name} uses ${forbidden}`); + } + } +}); + +// ------------------------------------------------------------------------------- exports + +test('the JSON export is the canonical artifact', () => { + const artifact = artifactOf(); + assert.equal(exportJson(artifact), canonicalArtifactJson(artifact)); + assert.deepEqual(JSON.parse(exportJson(artifact)), JSON.parse(JSON.stringify(artifact))); +}); + +test('a printed value that is not a string, an integer or null is refused by CSV and HTML', () => { + // Each builds: the artifact carries these values faithfully. Only printing them has no + // spelling every engine shares. + const printed = [ + [result(), (built) => { built.feasibility = { code: true }; }, [exportWorkOrderHtml]], + [result(), (built) => { built.containers[0].volume_utilization = 0.5; }, [exportWorkOrderHtml]], + [result(), (built) => { built.containers[0].container_type = { name: 'crate' }; }, [exportCsv, exportWorkOrderHtml]], + [result({ unpacked: [{ item_type: ['jack'], reason: 'r', proof: { level: 'proven' } }] }), () => {}, [exportCsv, exportWorkOrderHtml]], + [result({ algorithm: { ...ALGORITHM, seed: false } }), () => {}, [exportWorkOrderHtml]], + ]; + for (const [built, change, exporters] of printed) { + change(built); + const artifact = buildOperationalArtifact(REQUEST, built); + assert.equal(typeof exportJson(artifact), 'string'); + for (const exporter of exporters) assert.equal(codeOf(() => exporter(artifact)), 'invalid_value', exporter.name); + } +}); + +test('integers print in decimal and null prints as nothing', () => { + const artifact = artifactOf(); + artifact.work_order.containers[0].container_type = null; + artifact.work_order.containers[0].lines[0].placement.orientation = -0; + const [, row] = exportCsv(artifact).split('\r\n'); + assert.equal(row, 'step,0,,1,tin,0,160000,0,0,10,0,0,5,10,10,mm,,'); +}); + +test('the container heading number is refused unless the index is an integer', () => { + // The heading prints `container_index + 1`, a computed value, so it is held to the same rule + // as a copied one. CSV prints the plan reference's index, not this one, and is unaffected. + const artifact = artifactOf(); + assert.ok(exportWorkOrderHtml(artifact).includes('

Container 1: crate

')); + for (const index of [0.5, true, false, '0', null]) { + const edited = JSON.parse(JSON.stringify(artifact)); + edited.work_order.containers[0].container_index = index; + assert.equal(codeOf(() => exportWorkOrderHtml(edited)), 'invalid_value', String(index)); + } +}); + +test('every export refuses a document it cannot read', () => { + for (const exporter of [exportJson, exportCsv, exportWorkOrderHtml]) { + assert.equal(codeOf(() => exporter({ ...artifactOf(), format: 'packvium-operational-artifact/v2' })), + 'unknown_format'); + assert.equal(codeOf(() => exporter(['not', 'an', 'artifact'])), 'unknown_format'); + assert.equal(codeOf(() => exporter(null)), 'unknown_format'); + } +}); + +test('the CSV has a header, one row per step in order and one per unplaced item', () => { + const unpacked = [{ + item_id: 'jack#1', item_type: 'jack', reason: 'no_compatible_container_dimensions', details: [], + proof: { level: 'proven' }, + }]; + const rows = exportCsv(artifactOf({ unpacked })).split('\r\n'); + assert.equal(rows[0], CSV_COLUMNS.join(',')); + assert.equal(rows[1], 'step,0,crate,1,tin,LWH,160000,0,0,10,0,0,5,10,10,mm,,'); + assert.equal(rows[2], 'step,0,crate,2,box,LWH,0,0,0,0,0,0,10,10,10,mm,,'); + assert.equal(rows[3], 'unplaced,,,,jack,,,,,,,,,,,,no_compatible_container_dimensions,proven'); + assert.equal(rows[4], ''); + assert.equal(rows.length, 5); +}); + +test('a CSV field is quoted only when it must be and never rewritten', () => { + const quoted = result({ + placements: [placement('a,"b"', 0), placement('=SUM(A1)', 10), placement('two\nlines', 20), + placement(`sep${LINE_SEPARATOR}arator`, 30)], + }); + const text = exportCsv(buildOperationalArtifact(REQUEST, quoted)); + assert.ok(text.includes(',"a,""b""",')); + assert.ok(text.includes(',=SUM(A1),')); + assert.ok(text.includes(',"two\nlines",')); + assert.ok(text.includes(`,sep${LINE_SEPARATOR}arator,`)); +}); + +test('the work order is self-contained, escaped and lists every step', () => { + const escaped = result({ placements: [placement('&\'"', 0), placement('tin', 10, 5)] }); + const html = exportWorkOrderHtml(buildOperationalArtifact(REQUEST, escaped, { loadingOrders: { 0: [1, 0] } })); + assert.ok(html.startsWith('\n') && html.endsWith('\n')); + assert.ok(!html.includes('&\'')); + assert.equal(html.split('☐').length - 1, 2); + assert.ok(html.includes('Order: loading.') && html.includes('extreme_point') && html.includes('cartons v3')); + assert.ok(/^[\x00-\x7F]*$/.test(html), 'the source is ASCII'); +}); + +test('the work order says when there is no order and when everything was packed', () => { + const html = exportWorkOrderHtml(buildOperationalArtifact(REQUEST, result())); + assert.ok(html.includes('Order: unavailable.')); + assert.ok(html.includes('

Every item was packed.

')); +}); + +test('exports are deterministic and leave the artifact untouched', () => { + const artifact = artifactOf(); + const before = canonicalArtifactJson(artifact); + for (const exporter of [exportJson, exportCsv, exportWorkOrderHtml]) { + assert.equal(exporter(artifact), exporter(artifact)); + } + assert.equal(canonicalArtifactJson(artifact), before); +}); + +// ---------------------------------------------------------------------------- the corpus + +// The golden corpus and the requests it answers live in the workspace only; a published copy +// of this package does not carry them. +const CONFORMANCE = path.resolve(PACKAGE_ROOT, '../../../conformance'); +const GOLDEN = path.join(CONFORMANCE, 'golden'); +const FIXTURES = path.join(CONFORMANCE, 'fixtures'); +const hasCorpus = fs.existsSync(GOLDEN) && fs.existsSync(FIXTURES); + +test('every golden result with its request builds an artifact every export can read', + { skip: hasCorpus ? false : 'the corpus lives in the workspace only' }, () => { + let built = 0; + for (const name of fs.readdirSync(GOLDEN).filter((entry) => entry.endsWith('.json')).sort()) { + const golden = JSON.parse(fs.readFileSync(path.join(GOLDEN, name), 'utf8')); + const fixture = path.join(FIXTURES, name); + if (golden === null || typeof golden !== 'object' || !('status' in golden) || !fs.existsSync(fixture)) continue; + const request = JSON.parse(fs.readFileSync(fixture, 'utf8')); + const loadingOrders = {}; + (golden.containers ?? []).forEach((container, index) => { + loadingOrders[index] = (container.placements ?? []).map((_, position) => position).reverse(); + }); + const artifact = buildOperationalArtifact(request, golden, { loadingOrders }); + assert.deepEqual(JSON.parse(exportJson(artifact)).plan, JSON.parse(canonicalPlanJson(artifact.plan)), name); + exportCsv(artifact); + exportWorkOrderHtml(artifact); + built += 1; + } + assert.ok(built >= 398, `built ${built}`); + }); diff --git a/test/commerce-edge-cases.test.mjs b/test/commerce-edge-cases.test.mjs index 2906a5a..72d2079 100644 --- a/test/commerce-edge-cases.test.mjs +++ b/test/commerce-edge-cases.test.mjs @@ -301,3 +301,42 @@ test('an explicitly null optional field means the same as an omitted one', () => test('canonical output leaves non-ASCII and slashes unescaped', () => { assert.equal(canonicalJson({ note: 'zóna/1 🙂' }), '{"note":"zóna/1 🙂"}'); }); + + +test('code-point ordering matches an independent array oracle through surrogate boundaries', () => { + const alphabet = ['a', 'z', '\u0000', 'é', '\uff21', '😀', '\ud800', '\udc00']; + const strings = ['', ...alphabet]; + for (const left of alphabet) for (const right of alphabet) strings.push(left + right); + strings.push('x'.repeat(1024), 'x'.repeat(1024) + '😀', 'x'.repeat(1024) + '\uff21'); + const oracle = (left, right) => { + const a = Array.from(left, value => value.codePointAt(0)); + const b = Array.from(right, value => value.codePointAt(0)); + for (let i = 0; i < Math.min(a.length, b.length); i++) { + if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1; + } + return Math.sign(a.length - b.length); + }; + for (const left of strings) for (const right of strings) { + assert.equal(compareCodePoints(left, right), oracle(left, right), JSON.stringify([left, right])); + } + assert.deepEqual([...strings].sort(compareCodePoints), [...strings].sort(oracle)); +}); + + +test('catalog pinned lookups preserve boundaries and rollback across a long history', () => { + const versions = Array.from({length: 64}, (_, index) => ({ + effective_at: (index + 1) % 7, published_at: index + 1, snapshot: {}, + })); + const document = catalogDocument(...versions, {rollback_to: 1, published_at: 100, effective_at: 6}); + for (const version of [1, 2, 32, 64, 65]) { + const result = catalogVersionInfo(document, {catalog_id: 'c', version, resolved_at: 100}); + assert.equal(result.status, 'ok'); + assert.equal(result.catalog.version, version); + } + for (const version of [-10, 0, 66, Number.MAX_SAFE_INTEGER]) { + const result = catalogVersionInfo(document, {catalog_id: 'c', version, resolved_at: 100}); + assert.equal(result.status, 'rejected'); + } + assert.equal(catalogVersionInfo(document, {catalog_id: 'c', as_of: 6, resolved_at: 100}).catalog.version, 65); + assert.equal(catalogVersionInfo(document, {catalog_id: 'c', as_of: 0, resolved_at: 100}).catalog.version, 63); +}); diff --git a/test/fallback.test.mjs b/test/fallback.test.mjs index 82e1f92..e9642bb 100644 --- a/test/fallback.test.mjs +++ b/test/fallback.test.mjs @@ -4,7 +4,7 @@ import test from 'node:test'; import { Deadline, SequenceReplayError, UNSUPPORTED_FIELDS, UnsupportedFeatureError, - BoundOverflowError, __inspectHullShapeForTests, __objectiveBoundsForTests, + BoundOverflowError, __spatialIndexForTests, __inspectHullShapeForTests, __objectiveBoundsForTests, __occupiesLessThanItsBoxForTests, __candidatePrefixForTests, __groupBatchesForTests, aggregateTermination, explainUnpackedItem, explanationForUnpackedItem, packFallback, rebalanceWeight, verifyLoadingPrefixBusinessRules, @@ -2320,3 +2320,26 @@ function compareScores(left, right) { } return 0; } + + +test('spatial forks share reads but isolate writes from parents and siblings', () => { + const {make, add, copy} = __spatialIndexForTests; + const box = {x: 0, y: 0, z: 0, d: [2,2,2]}; + const base = make([8,8,8]); add(base, 0, box); + const child = copy(base), grandchild = copy(child); + for (const [key, bucket] of base.cells) { + assert.strictEqual(child.cells.get(key), bucket); + assert.strictEqual(grandchild.cells.get(key), bucket); + } + add(base, 1, box); + const privateBuckets = new Map(base.cells); + add(base, 2, box); + add(child, 3, box); + add(grandchild, 4, box); + for (const [key, bucket] of base.cells) { + assert.strictEqual(bucket, privateBuckets.get(key)); + assert.deepEqual(bucket, [0,1,2]); + assert.deepEqual(child.cells.get(key), [0,3]); + assert.deepEqual(grandchild.cells.get(key), [0,4]); + } +}); diff --git a/test/package-exports.test.mjs b/test/package-exports.test.mjs index e5eac4b..c063121 100644 --- a/test/package-exports.test.mjs +++ b/test/package-exports.test.mjs @@ -35,6 +35,29 @@ test('the execution plan resolves by package name, not only by relative path', a assert.equal(execution.FORMAT, 'packvium-execution-plan/v1'); }); +test('the operational artifact and its exports resolve by package name', async () => { + const artifacts = await import(`${manifest.name}/artifacts.js`); + assert.equal(typeof artifacts.buildOperationalArtifact, 'function'); + assert.equal(typeof artifacts.canonicalArtifactJson, 'function'); + assert.equal(typeof artifacts.OperationalArtifactError, 'function'); + assert.equal(artifacts.FORMAT, 'packvium-operational-artifact/v1'); + const exports = await import(`${manifest.name}/artifact-exports.js`); + for (const name of ['exportJson', 'exportCsv', 'exportWorkOrderHtml']) { + assert.equal(typeof exports[name], 'function', name); + } + assert.equal(exports.CSV_COLUMNS[0], 'record'); +}); + +test('a module an export imports is published even when it is not exported itself', () => { + // `canonical-json.js` is internal: absent from `exports` on purpose, but `artifacts.js` and + // `execution.js` import it, so a tarball without it would break both at load time. + const published = new Set(manifest.files); + for (const name of ['canonical-json.js', 'artifacts.js', 'artifact-exports.js', 'artifacts.d.ts', 'artifact-exports.d.ts']) { + assert.ok(published.has(name), `"files" does not publish ${name}`); + } + assert.ok(!('./canonical-json.js' in manifest.exports), 'canonical-json.js is not public API'); +}); + test('every declared export target exists, and so does the types file beside it', () => { for (const [subpath, entry] of Object.entries(manifest.exports)) { for (const [condition, target] of Object.entries(entry)) {