@archcode-io/engine 0.2.0-preview.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +202 -0
  3. package/README.md +88 -0
  4. package/dist/src/capacity.d.ts +67 -0
  5. package/dist/src/capacity.js +227 -0
  6. package/dist/src/check.d.ts +21 -0
  7. package/dist/src/check.js +192 -0
  8. package/dist/src/compiled.d.ts +61 -0
  9. package/dist/src/compiled.js +91 -0
  10. package/dist/src/cst.d.ts +76 -0
  11. package/dist/src/cst.js +1 -0
  12. package/dist/src/diagnostics.d.ts +9 -0
  13. package/dist/src/diagnostics.js +1 -0
  14. package/dist/src/edit.d.ts +48 -0
  15. package/dist/src/edit.js +442 -0
  16. package/dist/src/index.d.ts +25 -0
  17. package/dist/src/index.js +24 -0
  18. package/dist/src/layout/balance.d.ts +34 -0
  19. package/dist/src/layout/balance.js +327 -0
  20. package/dist/src/layout/elk.d.ts +64 -0
  21. package/dist/src/layout/elk.js +267 -0
  22. package/dist/src/layout/host.d.ts +23 -0
  23. package/dist/src/layout/host.js +23 -0
  24. package/dist/src/layout/label.d.ts +49 -0
  25. package/dist/src/layout/label.js +113 -0
  26. package/dist/src/layout/measure.d.ts +11 -0
  27. package/dist/src/layout/measure.js +27 -0
  28. package/dist/src/layout/ortho.d.ts +54 -0
  29. package/dist/src/layout/ortho.js +206 -0
  30. package/dist/src/layout/route.d.ts +57 -0
  31. package/dist/src/layout/route.js +230 -0
  32. package/dist/src/lens.d.ts +83 -0
  33. package/dist/src/lens.js +377 -0
  34. package/dist/src/lexer.d.ts +7 -0
  35. package/dist/src/lexer.js +135 -0
  36. package/dist/src/model.d.ts +63 -0
  37. package/dist/src/model.js +114 -0
  38. package/dist/src/parser.d.ts +7 -0
  39. package/dist/src/parser.js +305 -0
  40. package/dist/src/render/svg.d.ts +56 -0
  41. package/dist/src/render/svg.js +289 -0
  42. package/dist/src/serialize.d.ts +10 -0
  43. package/dist/src/serialize.js +12 -0
  44. package/dist/src/tokens.d.ts +26 -0
  45. package/dist/src/tokens.js +15 -0
  46. package/dist/src/vocab.d.ts +38 -0
  47. package/dist/src/vocab.js +58 -0
  48. package/package.json +61 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ All notable changes to the ArchCode engine. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
5
+ [SemVer](https://semver.org/) once 1.0 is out — until then every release may change the API.
6
+
7
+ ## [Unreleased] — 0.2.0-preview
8
+
9
+ The first public preview. Everything below is new.
10
+
11
+ ### Language (v0.2 draft)
12
+
13
+ - Objects: `arch system service webapp app component function job datastore cache gateway broker topic actor external`, placement kinds `env segment cluster node managed`; nested blocks give full ids (`orders.worker`).
14
+ - Relations as verbs (`calls publishes subscribes reads writes uses streams depends_on emits listens`) with `over`, `via a, b`, `port`, `spec`, `as`, a label and a body.
15
+ - Interfaces by pointer: `exposes http openapi://…`, `stores schema sql://…`.
16
+ - Attribute lines with lists, pairs (`dc dc1 vlan 3076`), flags (`transit`) and unit tokens (`8Gi`, `24x7`, `2027-01`).
17
+ - Placement: `run a, b` inside a host, sizing (`cpu mem disk gpu count nodes`), `phase` and `at <moment>` timelines.
18
+ - `view` blocks: pins (`at`, `size`), `route … from side to side label f below via x y`, lenses, `layout`, `agents on|off`.
19
+ - Reserved for v0.3, kept byte for byte by the parser: `decision rule board profile contract`, YAML/JSON dialects as input.
20
+
21
+ ### Engine
22
+
23
+ - Lossless CST with byte-exact round trip; a fuzzer runs random documents through `parse → serialize`.
24
+ - Model lowering with interfaces, placements, timelines and ownership.
25
+ - Semantic diagnostics `AC100–AC109` (unknown reference, ambiguous id, attribute out of scope, …).
26
+ - Compiled form `archcode/v1`: `toCompiled`, `toJSON`, `toYAML`.
27
+ - Lenses (`logical`, `infrastructure`), transit nodes, agents on hosts, phases and moments.
28
+ - Two-phase ELK layout, A* orthogonal router, route repair (`repairRoute`) that keeps a person's arrows when cards move, label placement on either side of the line.
29
+ - ELK host abstraction: bundled in Node, `useElkWorker(url)` in the browser.
30
+ - SVG renderer with dark and light themes; capacity tables.
31
+ - Source edits that touch only the line they mean: `addObject`, `renameObject`, `setAttribute`, `retargetRelation`, `moveInto`, `addRun`, …
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # ArchCode engine
2
+
3
+ The reference implementation of [ArchCode](https://archcode.io) — an open notation for
4
+ describing the architecture of digital systems across C4 levels. Compact enough to paste
5
+ into a README, precise enough to validate, diff and generate from code.
6
+
7
+ ```archcode
8
+ service checkout "Checkout" tech Go
9
+ datastore orders_db "Orders DB" tech PostgreSQL 16
10
+
11
+ checkout writes orders_db over SQL
12
+ ```
13
+
14
+ This package turns text like that into a model, a picture, and data — and back into the
15
+ same text, byte for byte.
16
+
17
+ **Status: v0.2 preview.** The language is a draft; the API below is what the Playground at
18
+ [archcode.io/play](https://archcode.io/play/) runs on and will change before 1.0.
19
+
20
+ ## What is inside
21
+
22
+ | module | what it does |
23
+ |---|---|
24
+ | `parse` / `serialize` | text ⇄ lossless syntax tree — comments, spacing and order survive a round trip, and the fuzzer checks that on every build |
25
+ | `lower` | syntax tree → model: objects with full ids, relations, interfaces, placements, timelines |
26
+ | `check` | semantic diagnostics `AC100…AC109` — unknown references, ambiguous ids, attributes out of scope |
27
+ | `applyLens` | the model as a graph for one lens (`logical`, `infrastructure`), one phase, one moment |
28
+ | `layout` | positions and orthogonal routes (ELK, two-phase); `repairRoute` keeps a person's arrows when cards move |
29
+ | `toSvg` | the picture, dark or light theme |
30
+ | `toCompiled` / `toJSON` / `toYAML` | the model as plain data (schema `archcode/v1`) |
31
+ | `capacityTable` | resources per environment and moment, from `run … cpu 4 mem 8Gi` |
32
+ | `addObject`, `setAttribute`, `retargetRelation`, … | edits that touch only the line they mean |
33
+
34
+ ## Use
35
+
36
+ ```sh
37
+ npm install # once
38
+ npm run build # tsc → dist/
39
+ npm test # unit tests
40
+ npm run fuzz # random documents through parse → serialize, must be identical
41
+ ```
42
+
43
+ ```ts
44
+ import { parse, lower, check, applyLens, layout, toSvg } from './dist/src/index.js';
45
+
46
+ const src = `service a "A"\nservice b "B"\na calls b over HTTPS`;
47
+ const { doc, diagnostics } = parse(src);
48
+ const model = lower(doc);
49
+ diagnostics.push(...check(doc, model));
50
+
51
+ const graph = applyLens(model, { lens: 'logical' });
52
+ const positioned = await layout(graph);
53
+ const svg = toSvg(positioned, '', { theme: 'light' });
54
+ ```
55
+
56
+ The engine has no opinion about where ELK runs. In Node it loads the bundled ELK on first
57
+ use; a browser host calls `useElkWorker('/elk-worker.js')` once and every layout after that
58
+ runs in a Web Worker.
59
+
60
+ Not on npm yet — the first published version will be `0.2.0-preview.x`.
61
+
62
+ ## Layout of the repository
63
+
64
+ ```
65
+ src/ lexer · parser · cst · model · check · compiled · edit · lens · capacity
66
+ src/layout/ elk (layered) · balance (two-phase) · route (A*) · ortho · label · host
67
+ src/render/ svg
68
+ test/ unit tests, fixtures, fuzz.ts
69
+ tools/ layout scoring and strategy experiments
70
+ ```
71
+
72
+ ## The language
73
+
74
+ The specification lives at [archcode.io/docs](https://archcode.io/docs/). Marks in the
75
+ text say what this engine implements, what is partial, and what is reserved for v0.3.
76
+
77
+ ## Contributing
78
+
79
+ ArchCode is at an early stage and we are not taking pull requests yet — see
80
+ [CONTRIBUTING](https://github.com/archcode-io/.github/blob/main/CONTRIBUTING.md) for what
81
+ we do welcome, and for the DCO sign-off that every commit carries.
82
+
83
+ ## License
84
+
85
+ Apache-2.0 — see [LICENSE](LICENSE). The ArchCode language and its specification are a
86
+ separate work under CC BY 4.0.
87
+
88
+ ArchCode is an open standard created and maintained by Baryshev Labs.
@@ -0,0 +1,67 @@
1
+ import type { Model, Placement } from './model.js';
2
+ /**
3
+ * The resources table — the slide every architecture committee asks for
4
+ * (`Ресурсы серверов … Итого`). It is a projection of the placement blocks,
5
+ * never a thing written by hand: every `node`, sized `cluster` and sized `run`
6
+ * contributes its figures times its multiplier, per environment, per moment.
7
+ */
8
+ export interface Figures {
9
+ cpu?: number;
10
+ mem?: number;
11
+ disk?: number;
12
+ gpu?: number;
13
+ }
14
+ export declare const FIGURE_KEYS: (keyof Figures)[];
15
+ export interface CapacityRow {
16
+ id: string;
17
+ /** For a node/cluster: what runs on it asks for, and whether that exceeds it. */
18
+ load?: HostLoad;
19
+ label: string;
20
+ kind: string;
21
+ host?: string;
22
+ /**
23
+ * Pods inside a sized cluster are demand on capacity the cluster row already
24
+ * counts, so they are listed but not summed. A run inside an unsized cluster
25
+ * or a managed service is the only figure there is, and it counts.
26
+ */
27
+ counted: boolean;
28
+ figures: Record<string, Figures & {
29
+ count: number;
30
+ }>;
31
+ }
32
+ export interface CapacityEnv {
33
+ id: string;
34
+ label: string;
35
+ rows: CapacityRow[];
36
+ totals: Record<string, Figures>;
37
+ }
38
+ export interface CapacityTable {
39
+ moments: string[];
40
+ envs: CapacityEnv[];
41
+ }
42
+ /** `4Gi` `800Mi` `2Ti` `16GB` `300` → GiB */
43
+ export declare function toGiB(v: string | undefined): number | undefined;
44
+ /** `0.7/2` (requests/limit) → the limit; `2` → 2 */
45
+ export declare function toCpu(v: string | undefined): number | undefined;
46
+ export declare const SIZING_KEYS: string[];
47
+ /**
48
+ * A placement's sizing, with the logical object's own figures as defaults:
49
+ * `service api cpu 2` placed with a bare `run api` still runs at 2 cpu, and
50
+ * `run api cpu 4` overrides it there.
51
+ */
52
+ export declare function effectiveSizing(m: Model, p: Placement): Record<string, string[]>;
53
+ /**
54
+ * What the things running on a host ask for, against what the host offers.
55
+ * cpu/mem of every `run` × replicas, against the host's figures × count.
56
+ */
57
+ export interface HostLoad {
58
+ cpu?: [number, number];
59
+ mem?: [number, number];
60
+ over: boolean;
61
+ }
62
+ export declare function hostLoad(m: Model, hostId: string): HostLoad | undefined;
63
+ export declare function capacityTable(m: Model, opt?: {
64
+ phase?: string;
65
+ }): CapacityTable;
66
+ /** `12.5` → `12.5`, `0.78125` → `0.8`, `2048` → `2048` */
67
+ export declare const fmt: (n: number | undefined) => string;
@@ -0,0 +1,227 @@
1
+ import { PLACEMENT_KINDS } from './vocab.js';
2
+ export const FIGURE_KEYS = ['cpu', 'mem', 'disk', 'gpu'];
3
+ /** `4Gi` `800Mi` `2Ti` `16GB` `300` → GiB */
4
+ export function toGiB(v) {
5
+ if (!v)
6
+ return undefined;
7
+ v = v.split('/').pop(); // `800Mi/2Gi` (requests/limit) → the limit
8
+ const m = v.match(/^(\d+(?:\.\d+)?)\s*([A-Za-z]*)$/);
9
+ if (!m)
10
+ return undefined;
11
+ const n = parseFloat(m[1]);
12
+ const u = m[2].toLowerCase();
13
+ if (u === 'mi' || u === 'mb' || u === 'm')
14
+ return n / 1024;
15
+ if (u === 'ti' || u === 'tb' || u === 't')
16
+ return n * 1024;
17
+ if (u === 'ki' || u === 'kb' || u === 'k')
18
+ return n / 1024 / 1024;
19
+ return n; // Gi, GB, G, bare
20
+ }
21
+ /** `0.7/2` (requests/limit) → the limit; `2` → 2 */
22
+ export function toCpu(v) {
23
+ if (!v)
24
+ return undefined;
25
+ const last = v.split('/').pop();
26
+ const n = parseFloat(last);
27
+ return Number.isFinite(n) ? n : undefined;
28
+ }
29
+ const num = (v) => { const n = parseFloat(v ?? ''); return Number.isFinite(n) ? n : undefined; };
30
+ export const SIZING_KEYS = ['replicas', 'count', 'nodes', 'cpu', 'mem', 'disk', 'gpu'];
31
+ /**
32
+ * A placement's sizing, with the logical object's own figures as defaults:
33
+ * `service api cpu 2` placed with a bare `run api` still runs at 2 cpu, and
34
+ * `run api cpu 4` overrides it there.
35
+ */
36
+ export function effectiveSizing(m, p) {
37
+ const logical = [...m.objects.values()].find(o => o.id === p.ref || o.localId === p.ref);
38
+ const out = {};
39
+ for (const k of SIZING_KEYS)
40
+ if (logical?.attrs[k])
41
+ out[k] = logical.attrs[k];
42
+ return { ...out, ...p.attrs };
43
+ }
44
+ export function hostLoad(m, hostId) {
45
+ const host = m.objects.get(hostId);
46
+ if (!host || (host.kind !== 'node' && host.kind !== 'cluster'))
47
+ return undefined;
48
+ const cap = figuresOf(host.attrs);
49
+ const mult = num(host.attrs['count']?.[0]) ?? num(host.attrs['nodes']?.[0]) ?? 1;
50
+ const runs = m.placements.filter(p => p.host === hostId);
51
+ if (!runs.length || (cap.cpu === undefined && cap.mem === undefined))
52
+ return undefined;
53
+ const demand = {};
54
+ for (const p of runs) {
55
+ const a = effectiveSizing(m, p);
56
+ const f = figuresOf(a);
57
+ const n = num(a['replicas']?.[0]) ?? 1;
58
+ if (f.cpu !== undefined)
59
+ demand.cpu = (demand.cpu ?? 0) + f.cpu * n;
60
+ if (f.mem !== undefined)
61
+ demand.mem = (demand.mem ?? 0) + f.mem * n;
62
+ }
63
+ const out = { over: false };
64
+ if (cap.cpu !== undefined && demand.cpu !== undefined) {
65
+ out.cpu = [demand.cpu, cap.cpu * mult];
66
+ if (demand.cpu > cap.cpu * mult)
67
+ out.over = true;
68
+ }
69
+ if (cap.mem !== undefined && demand.mem !== undefined) {
70
+ out.mem = [demand.mem, cap.mem * mult];
71
+ if (demand.mem > cap.mem * mult)
72
+ out.over = true;
73
+ }
74
+ if (!out.cpu && !out.mem)
75
+ return undefined;
76
+ return out;
77
+ }
78
+ function figuresOf(attrs) {
79
+ const f = {};
80
+ const cpu = toCpu(attrs['cpu']?.[0]);
81
+ if (cpu !== undefined)
82
+ f.cpu = cpu;
83
+ const mem = toGiB(attrs['mem']?.[0]);
84
+ if (mem !== undefined)
85
+ f.mem = mem;
86
+ const disk = attrs['disk'];
87
+ if (disk?.length) {
88
+ // `disk 300Gi` or `disk system 30Gi data 200Gi` — sum every figure present
89
+ const parts = disk.map(toGiB).filter((x) => x !== undefined);
90
+ if (parts.length)
91
+ f.disk = parts.reduce((a, b) => a + b, 0);
92
+ }
93
+ const gpu = attrs['gpu'];
94
+ if (gpu?.length)
95
+ f.gpu = num(gpu[0]) ?? 1;
96
+ return f;
97
+ }
98
+ /** Moments sort as written dates; relative ones (`+1y`) come after, by size. */
99
+ const momentKey = (w) => (w.startsWith('+') ? `~${w.slice(1).padStart(6, '0')}` : w);
100
+ /** Attributes as they stand at `when`: base, overlaid by every earlier moment. */
101
+ function attrsAt(base, timeline, when) {
102
+ if (when === 'now')
103
+ return base;
104
+ const out = { ...base };
105
+ for (const t of timeline)
106
+ if (momentKey(t.when) <= momentKey(when))
107
+ Object.assign(out, t.attrs);
108
+ return out;
109
+ }
110
+ const scale = (f, n) => {
111
+ const out = {};
112
+ for (const k of FIGURE_KEYS)
113
+ if (f[k] !== undefined)
114
+ out[k] = f[k] * n;
115
+ return out;
116
+ };
117
+ const add = (a, b) => {
118
+ const out = { ...a };
119
+ for (const k of FIGURE_KEYS)
120
+ if (b[k] !== undefined)
121
+ out[k] = (out[k] ?? 0) + b[k];
122
+ return out;
123
+ };
124
+ export function capacityTable(m, opt = {}) {
125
+ const inPhase = (attrs) => !opt.phase || !attrs['phase']?.length || attrs['phase'].includes(opt.phase);
126
+ const envOf = (id) => {
127
+ let cur = id;
128
+ while (cur) {
129
+ const ob = m.objects.get(cur);
130
+ if (!ob?.parent)
131
+ return cur;
132
+ cur = ob.parent;
133
+ }
134
+ return id;
135
+ };
136
+ const hostKind = (id) => m.objects.get(id)?.kind;
137
+ // every moment anyone mentions
138
+ const moments = new Set();
139
+ for (const ob of m.objects.values())
140
+ for (const t of ob.timeline)
141
+ moments.add(t.when);
142
+ for (const p of m.placements)
143
+ for (const t of p.timeline)
144
+ moments.add(t.when);
145
+ const cols = ['now', ...[...moments].sort((a, b) => momentKey(a).localeCompare(momentKey(b)))];
146
+ const envs = new Map();
147
+ const envFor = (id) => {
148
+ const e = envOf(id);
149
+ if (!envs.has(e)) {
150
+ const ob = m.objects.get(e);
151
+ envs.set(e, { id: e, label: ob?.name ?? ob?.localId ?? e, rows: [], totals: {} });
152
+ }
153
+ return envs.get(e);
154
+ };
155
+ const rowOf = (id, label, kind, base, timeline, countKey, host) => {
156
+ const figures = {};
157
+ for (const when of cols) {
158
+ const a = attrsAt(base, timeline, when);
159
+ const count = countKey.map(k => num(a[k]?.[0])).find(x => x !== undefined) ?? 1;
160
+ figures[when] = { ...scale(figuresOf(a), count), count };
161
+ }
162
+ return { id, label, kind, host, figures, counted: true };
163
+ };
164
+ // nodes and sized clusters are resources in themselves
165
+ for (const [id, ob] of m.objects) {
166
+ if (!PLACEMENT_KINDS.has(ob.kind) || !inPhase(ob.attrs))
167
+ continue;
168
+ if (ob.kind === 'node')
169
+ envFor(id).rows.push({ ...rowOf(id, ob.name ?? ob.localId, 'node', ob.attrs, ob.timeline, ['count']), load: hostLoad(m, id) });
170
+ else if (ob.kind === 'cluster' && (ob.attrs['cpu'] || ob.attrs['mem']))
171
+ envFor(id).rows.push({ ...rowOf(id, ob.name ?? ob.localId, 'cluster', ob.attrs, ob.timeline, ['nodes', 'count']), load: hostLoad(m, id) });
172
+ }
173
+ // a sized run inside a cluster or a managed service is a resource too;
174
+ // a run on a node is not — the node already is
175
+ for (const p of m.placements) {
176
+ if (!inPhase(p.attrs) || hostKind(p.host) === 'node' || hostKind(p.host) === undefined)
177
+ continue;
178
+ const a = effectiveSizing(m, p);
179
+ if (!a['cpu'] && !a['mem'] && !a['disk'] && !a['gpu'])
180
+ continue;
181
+ const logical = [...m.objects.values()].find(o => o.id === p.ref || o.localId === p.ref);
182
+ const host = m.objects.get(p.host);
183
+ const row = rowOf(`${p.host}/${p.ref}`, logical?.name ?? p.ref, 'run', a, p.timeline, ['replicas'], p.host);
184
+ row.counted = host.kind !== 'cluster' || (!host.attrs['cpu'] && !host.attrs['mem']);
185
+ envFor(p.host).rows.push(row);
186
+ }
187
+ // what the stores hold: `capacity size 340Gi growth 11Gi/mo` on a datastore or cache,
188
+ // shown in the environment it runs in — a line of its own, not summed into the
189
+ // disk of the hosts (that is sizing; this is content, and it grows)
190
+ const monthsFrom = (when) => {
191
+ if (when === 'now')
192
+ return 0;
193
+ const rel = /^\+(\d+)([dwmy])$/.exec(when);
194
+ if (rel)
195
+ return +rel[1] * { d: 1 / 30, w: 7 / 30, m: 1, y: 12 }[rel[2]];
196
+ const abs = /^(\d{4})(?:-(\d{2}))?/.exec(when);
197
+ if (!abs)
198
+ return undefined;
199
+ const now = new Date();
200
+ return (+abs[1] - now.getUTCFullYear()) * 12 + ((abs[2] ? +abs[2] : 1) - (now.getUTCMonth() + 1));
201
+ };
202
+ for (const p of m.placements) {
203
+ const logical = [...m.objects.values()].find(o => o.id === p.ref || o.localId === p.ref);
204
+ if (!logical || (logical.kind !== 'datastore' && logical.kind !== 'cache') || !inPhase(logical.attrs))
205
+ continue;
206
+ const cap = logical.attrs['capacity'] ?? [];
207
+ const pair = (k) => { const i = cap.indexOf(k); return i >= 0 ? cap[i + 1] : undefined; };
208
+ const size = toGiB(pair('size'));
209
+ if (size === undefined)
210
+ continue;
211
+ const g = /^(\d+(?:\.\d+)?\s*[A-Za-z]*)\/(d|w|mo|m|y)$/.exec(pair('growth') ?? '');
212
+ const perMonth = g ? (toGiB(g[1]) ?? 0) * { d: 30, w: 30 / 7, mo: 1, m: 1, y: 1 / 12 }[g[2]] : 0;
213
+ const figures = {};
214
+ for (const when of cols) {
215
+ const months = monthsFrom(when);
216
+ figures[when] = { disk: Math.round((size + perMonth * Math.max(0, months ?? 0)) * 10) / 10, count: 1 };
217
+ }
218
+ if (m.objects.get(p.host))
219
+ envFor(p.host).rows.push({ id: `${p.host}/${p.ref}#data`, label: `${logical.name ?? p.ref} · data`, kind: 'data', host: p.host, figures, counted: false });
220
+ }
221
+ for (const e of envs.values())
222
+ for (const when of cols)
223
+ e.totals[when] = e.rows.filter(r => r.counted).reduce((acc, r) => add(acc, r.figures[when]), {});
224
+ return { moments: cols, envs: [...envs.values()] };
225
+ }
226
+ /** `12.5` → `12.5`, `0.78125` → `0.8`, `2048` → `2048` */
227
+ export const fmt = (n) => n === undefined ? '' : Number.isInteger(n) ? String(n) : String(Math.round(n * 10) / 10);
@@ -0,0 +1,21 @@
1
+ import type { Doc } from './cst.js';
2
+ import { type Diagnostic } from './diagnostics.js';
3
+ import type { Model } from './model.js';
4
+ /**
5
+ * Semantic diagnostics (spec §17.10). The parser only knows shapes; this pass
6
+ * knows names. It never changes the document and never stops a render — the
7
+ * lens still draws what it can — it only says what a reader would trip on.
8
+ *
9
+ * AC100 duplicate id error
10
+ * AC101 unresolved reference warning
11
+ * AC102 ambiguous reference warning
12
+ * AC103 reserved block kind info (rule · decision · board · profile — kept, not interpreted)
13
+ * AC104 unknown attribute info (`x-…` keys are silent: they are yours)
14
+ * AC105 `archcode <version>` pragma warning (unknown version, or not the first statement)
15
+ * AC106 `at` without a moment error
16
+ * AC107 relation between placement blocks warning (a node does not `call` a cluster — put things inside)
17
+ * AC108 `run` outside a placement block error
18
+ * AC109 `run` of something that cannot run warning (an actor, an external, a topic)
19
+ */
20
+ export declare const LANGUAGE_VERSIONS: Set<string>;
21
+ export declare function check(doc: Doc, m: Model): Diagnostic[];