forma-arch 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Luca Dominici
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ Forma
2
+ Copyright 2026 Luca Dominici
3
+
4
+ This product includes software developed as an original work.
5
+
6
+ Conceptual standards referenced (not vendored, not affiliated):
7
+ - The C4 model (https://c4model.com) — CC BY 4.0. Forma is not affiliated with or endorsed by C4.
8
+ - arc42 (https://arc42.org) — CC BY-SA 4.0. Only referenced; template text is not redistributed.
9
+
10
+ No third-party source code is copied into this project.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # Forma
2
+
3
+ **Present your architecture instead of slides.** Forma turns any codebase into an interactive,
4
+ stack-agnostic C4 explorer — big-picture → drill-down to the leaf — generated *from the code* and
5
+ kept true to it by a deterministic drift check. No more slide decks that lie the day after you draw
6
+ them.
7
+
8
+ Forma is the companion to `arbiter`: arbiter governs the process, Forma shows the system and
9
+ guarantees the picture matches reality.
10
+
11
+ ## Why
12
+
13
+ A hand-drawn architecture diagram is stale the moment code changes. Forma walks your source for the
14
+ real structure, infers relationships from cross-references to exported symbol names (heuristic, additive), and **fails a check** when the model
15
+ and the code disagree. What you present is what actually exists.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npx forma-arch <command> # or: npm i -D forma-arch
21
+ ```
22
+
23
+ ## Commands
24
+
25
+ | Command | What it does |
26
+ |---|---|
27
+ | `forma init` | Seed `docs/architecture/c4-topology.json` from your source dirs (best-effort; then curate) |
28
+ | `forma gen` | Walk `src/` leaves + derive container edges from cross-references to exported symbol names → `c4-model.json` |
29
+ | `forma check` | Deterministic drift check — **fails if the model no longer matches the code** |
30
+ | `forma doc` | Project the arc42 scaffold (`ARCHITECTURE.scaffold.md`) from the model |
31
+ | `forma serve` | Open the live explorer at `http://localhost:4173` |
32
+
33
+ ## How it fits together
34
+
35
+ ```
36
+ code ──► forma gen ──► c4-model.json ──┬──► c4-viewer.html (present / explore)
37
+ (single source) ├──► ARCHITECTURE.md (arc42, via forma doc)
38
+ └──► forma check (gate: model == code?)
39
+ ```
40
+
41
+ One source of truth (`c4-model.json`); two renderings (the interactive viewer and the arc42 doc);
42
+ one deterministic check that keeps them honest. The file contract is
43
+ [`lib/schema/c4-model.schema.json`](lib/schema/c4-model.schema.json).
44
+
45
+ ## Model-agnostic by design
46
+
47
+ The engine is plain Node — no LLM required. Structure is auto-walked, relationships are derived from
48
+ code, the check is deterministic. The only human (or agent) step is curating the topology groupings
49
+ and writing the arc42 prose — and *any* model can do that against the documented JSON/Markdown
50
+ contract. The Claude skill in `adapters/` is a thin wrapper, not the product.
51
+
52
+ ## Skins
53
+
54
+ The viewer ships with swappable skins (`holo`, `blueprint`) via a dropdown or `?skin=`. Themes are
55
+ CSS variables; the engine is decoupled from the look.
56
+
57
+ ## License
58
+
59
+ Apache-2.0. Not affiliated with C4 or arc42 — see [`NOTICE`](NOTICE).
package/bin/forma.mjs ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // forma — present your architecture instead of slides.
3
+ // Thin CLI dispatcher over the lib/ engine. Every subcommand is a plain Node script, so any
4
+ // agent (or a human with no AI) drives the same contract. The engine is model-agnostic.
5
+ import { spawnSync } from 'node:child_process'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { dirname, join } from 'node:path'
8
+ import { readFileSync } from 'node:fs'
9
+
10
+ const HERE = dirname(fileURLToPath(import.meta.url))
11
+ const LIB = join(HERE, '..', 'lib')
12
+ const cmd = process.argv[2]
13
+ const rest = process.argv.slice(3)
14
+
15
+ const MAP = { init: 'init.mjs', gen: 'gen.mjs', check: 'check.mjs', doc: 'doc.mjs', serve: 'serve.mjs' }
16
+
17
+ if (cmd === '-v' || cmd === '--version') {
18
+ const pkg = JSON.parse(readFileSync(join(HERE, '..', 'package.json'), 'utf-8'))
19
+ console.log(pkg.version); process.exit(0)
20
+ }
21
+ if (!cmd || cmd === '-h' || cmd === '--help' || !MAP[cmd]) {
22
+ console.log(`forma — present your architecture instead of slides.
23
+
24
+ Usage: forma <command> [--repo <path>]
25
+
26
+ init seed docs/architecture/c4-topology.json from your source dirs (best-effort; then curate)
27
+ gen walk src/ leaves + derive container edges from real code → c4-model.json
28
+ check deterministic drift check — fails if the model no longer matches the code
29
+ doc project the arc42 scaffold (ARCHITECTURE.scaffold.md) from the model
30
+ serve open the live explorer at http://localhost:4173
31
+
32
+ The file contract is lib/schema/c4-model.schema.json. Enrichment (curate the topology, write the
33
+ arc42 prose) is model-agnostic — any agent edits the same JSON/Markdown.`)
34
+ const unknown = cmd && cmd !== '-h' && cmd !== '--help' && !MAP[cmd]
35
+ process.exit(unknown ? 1 : 0)
36
+ }
37
+
38
+ const r = spawnSync(process.execPath, [join(LIB, MAP[cmd]), ...rest], { stdio: 'inherit' })
39
+ process.exit(r.status == null ? 1 : r.status)
package/lib/check.mjs ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // check-c4-model.mjs — NON-VACUOUS anti-drift gate for the C4 model.
3
+ // Fails LOUD (never SKIP). Asserts the committed model against INDEPENDENT ground truth in src/,
4
+ // and flags architecture-doc numbers that disagree with code (the "14 vs 25 tables" trap).
5
+ // Usage: node check-c4-model.mjs [--repo <path>] [--model <path>] [--topology <path>]
6
+ import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
7
+ import { join, dirname } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ const HERE = dirname(fileURLToPath(import.meta.url))
11
+ const arg = (f, d) => { const i = process.argv.indexOf(f); return i > -1 ? process.argv[i + 1] : d }
12
+ const REPO = arg('--repo', process.cwd())
13
+ const MODEL = arg('--model', join(REPO, 'docs/architecture/c4-model.json'))
14
+ const TOPO = arg('--topology', join(REPO, 'docs/architecture/c4-topology.json'))
15
+ const rp = (p) => join(REPO, p)
16
+ const errs = []
17
+ const fail = (m) => errs.push(m)
18
+
19
+ if (!existsSync(MODEL)) { console.error('[check-c4] FAIL: model missing (no SKIP): ' + MODEL); process.exit(1) }
20
+ if (!existsSync(TOPO)) { console.error('[check-c4] FAIL: topology missing: ' + TOPO); process.exit(1) }
21
+ const model = JSON.parse(readFileSync(MODEL, 'utf-8'))
22
+ const topo = JSON.parse(readFileSync(TOPO, 'utf-8'))
23
+
24
+ // 1) schemaVersion present + basic shape
25
+ if (!/^\d+\.\d+\.\d+$/.test(model.schemaVersion || '')) fail('missing/invalid schemaVersion')
26
+ if (!Array.isArray(model.nodes) || model.nodes.length === 0) fail('no nodes')
27
+
28
+ // 2) re-derive leaf counts from src/ INDEPENDENTLY and compare to the model
29
+ function walk(spec) {
30
+ const dir = rp(spec.dir); if (!existsSync(dir)) { fail('leafSource dir missing: ' + spec.dir); return [] }
31
+ const re = new RegExp(spec.match), ex = spec.exclude ? new RegExp(spec.exclude) : null
32
+ return readdirSync(dir).filter((f) => {
33
+ if (spec.filesOnly !== false && statSync(join(dir, f)).isDirectory()) return false
34
+ return re.test(f) && !(ex && ex.test(f))
35
+ })
36
+ }
37
+ for (const spec of topo.leafSources) {
38
+ const live = walk(spec).length
39
+ const inModel = model.nodes.filter((n) => n.parent === spec.parent && n.kind === 'leaf' && n.status === 'current').length
40
+ if (live === 0) fail(`phantom parent "${spec.parent}": src glob ${spec.dir} matches 0 files`)
41
+ if (live !== inModel) fail(`DRIFT: ${spec.parent} — src has ${live} files, model has ${inModel}. Regenerate c4-model.json.`)
42
+ }
43
+
44
+ // 3) OPTIONAL count checks — generic, config-driven (the "14-vs-25 tables" trap, for ANY stack).
45
+ // A repo opts in by adding `countChecks` to its topology, e.g.:
46
+ // "countChecks": [{ "file": "src/db/schema.ts", "pattern": "sqliteTable\\(", "nodeId": "l_db_1",
47
+ // "doc": { "file": "docs/architecture/ARCHITECTURE.md", "pattern": "(\\d+)\\s+tables?" } }]
48
+ // No project-specific constants live here. Absent → nothing runs.
49
+ for (const c of topo.countChecks || []) {
50
+ const f = rp(c.file)
51
+ if (!existsSync(f)) { fail(`countCheck: file missing: ${c.file}`); continue }
52
+ const actual = (readFileSync(f, 'utf-8').match(new RegExp(c.pattern, 'g')) || []).length
53
+ const node = model.nodes.find((n) => n.id === c.nodeId)
54
+ if (!node) { fail(`countCheck: model node "${c.nodeId}" not found`); continue }
55
+ const modelN = parseInt(node.tech, 10)
56
+ if (actual !== modelN) fail(`DRIFT: ${c.file} has ${actual} match(es) of /${c.pattern}/, model node ${c.nodeId} says ${modelN}`)
57
+ if (c.doc && existsSync(rp(c.doc.file))) {
58
+ const claims = [...readFileSync(rp(c.doc.file), 'utf-8').matchAll(new RegExp(c.doc.pattern, 'gi'))].map((m) => parseInt(m[1], 10)).filter((n) => !Number.isNaN(n))
59
+ for (const cl of claims) if (cl !== actual) fail(`DOC DRIFT: ${c.doc.file} claims "${cl}" but ${c.file} has ${actual}.`)
60
+ }
61
+ }
62
+
63
+ // 4) every node evidence path of type "path" must exist (no phantom evidence)
64
+ for (const n of model.nodes) for (const e of n.evidence || []) if (e.type === 'path' && !existsSync(rp(e.ref))) fail(`node ${n.id}: evidence path missing: ${e.ref}`)
65
+
66
+ // 5) planned premises still hold
67
+ for (const p of topo.plannedLeaves || []) if (p.sourceMustContain) {
68
+ const f = rp(p.sourceRef)
69
+ if (!existsSync(f) || !readFileSync(f, 'utf-8').includes(p.sourceMustContain)) fail(`planned "${p.name}" premise broken in ${p.sourceRef}`)
70
+ }
71
+
72
+ if (errs.length) { console.error('[check-c4] FAIL (' + errs.length + '):\n - ' + errs.join('\n - ')); process.exit(1) }
73
+ console.log('[check-c4] OK — model is adherent to src/ (leaves, table count, evidence, planned premises all verified)')
package/lib/doc.mjs ADDED
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ // forma doc — project an arc42 scaffold from c4-model.json.
3
+ // The DETERMINISTIC sections (context/building-block diagrams, container table, ADR index, stack)
4
+ // are filled from the model — so they can never drift from it. The JUDGMENT sections (goals,
5
+ // strategy, decisions, risks) are stubbed with TODO(forma) for a human/agent to write.
6
+ // Output: docs/architecture/ARCHITECTURE.scaffold.md (never overwrites a real ARCHITECTURE.md).
7
+ import { readFileSync, writeFileSync, existsSync, readdirSync } from 'node:fs'
8
+ import { join, relative } from 'node:path'
9
+
10
+ const arg = (f, d) => { const i = process.argv.indexOf(f); return i > -1 ? process.argv[i + 1] : d }
11
+ const REPO = arg('--repo', process.cwd())
12
+ const MODEL = arg('--model', join(REPO, 'docs/architecture/c4-model.json'))
13
+ const OUT = arg('--out', join(REPO, 'docs/architecture/ARCHITECTURE.scaffold.md'))
14
+ if (!existsSync(MODEL)) { console.error('[forma doc] model missing: ' + MODEL + ' — run `forma gen` first.'); process.exit(1) }
15
+ const m = JSON.parse(readFileSync(MODEL, 'utf-8'))
16
+ const byId = new Map(m.nodes.map((n) => [n.id, n]))
17
+ const sid = (s) => String(s).replace(/[^A-Za-z0-9_]/g, '_')
18
+ const name = (id) => (byId.get(id) || { name: id }).name
19
+ const C4 = { person: 'Person', system: 'System', external: 'System_Ext', container: 'Container', component: 'Component', store: 'ContainerDb', boundary: 'Container_Boundary', leaf: 'Component' }
20
+ const q = (s) => String(s == null ? '' : s).replace(/"/g, '')
21
+ const el = (n) => `${C4[n.kind] || 'Container'}(${sid(n.id)}, "${q(n.name)}"${n.tech ? `, "${q(n.tech)}"` : ''})`
22
+ const rels = (ids) => m.edges.filter((e) => ids.has(e.from) && ids.has(e.to)).map((e) => ` Rel(${sid(e.from)}, ${sid(e.to)}, "${(e.label || '').replace(/"/g, '')}")`).join('\n')
23
+
24
+ // context = nodes with no parent
25
+ const ctx = m.nodes.filter((n) => !n.parent)
26
+ const ctxIds = new Set(ctx.map((n) => n.id))
27
+ const contextDiagram = `\`\`\`mermaid\nC4Context\n title System Context\n${ctx.map((n) => ' ' + el(n)).join('\n')}\n${rels(ctxIds)}\n\`\`\``
28
+
29
+ // containers = children of the system node
30
+ const sys = ctx.find((n) => n.kind === 'system') || ctx[0]
31
+ const containers = m.nodes.filter((n) => n.parent === (sys && sys.id))
32
+ const contIds = new Set(containers.map((n) => n.id))
33
+ const containerDiagram = containers.length ? `\`\`\`mermaid\nC4Container\n title Container view — ${sys.name}\n${containers.map((n) => ' ' + el(n)).join('\n')}\n${rels(contIds)}\n\`\`\`` : '_No containers in the model yet._'
34
+ const leafCount = (id) => m.nodes.filter((n) => n.parent === id && n.kind === 'leaf').length
35
+ const containerTable = containers.length
36
+ ? ['| Container | Tech | Leaves | What it does |', '|---|---|---|---|', ...containers.map((n) => `| ${n.name} | ${n.tech || '—'} | ${leafCount(n.id)} | ${(n.func || n.description || 'TODO(forma): describe').replace(/\n/g, ' ')} |`)].join('\n')
37
+ : '_No containers yet._'
38
+
39
+ // ADR index if present
40
+ const adrDir = join(REPO, 'docs/adr')
41
+ let adrs = '_No `docs/adr/` found — record decisions as ADRs._'
42
+ if (existsSync(adrDir)) {
43
+ const files = readdirSync(adrDir).filter((f) => /\.md$/.test(f) && !/readme|template/i.test(f)).sort()
44
+ if (files.length) adrs = files.map((f) => { const t = (readFileSync(join(adrDir, f), 'utf-8').match(/^#\s+(.+)/m) || [, f])[1]; return `- [${t}](../adr/${f})`; }).join('\n')
45
+ }
46
+
47
+ const stack = (m.meta && m.meta.stack) || (sys && sys.tech) || 'TODO'
48
+ const TODO = (s) => `> TODO(forma): ${s}`
49
+ const md = `<!-- forma: arc42 scaffold projected from c4-model.json. Deterministic sections are generated;
50
+ do not edit them by hand — re-run \`forma doc\`. Fill the TODO(forma) prose, then promote to ARCHITECTURE.md. -->
51
+
52
+ # Architecture — ${sys ? sys.name : m.source.repo}
53
+
54
+ > **Format:** [arc42](https://arc42.org/) + [C4](https://c4model.com/). Generated by \`forma doc\` from
55
+ > \`c4-model.json\` (commit \`${(m.source.commit || '').slice(0, 8)}\`). The live explorer is \`c4-viewer.html\`.
56
+
57
+ ## 1. Introduction and Goals
58
+ ${TODO('one paragraph: what this system is and who uses it.')}
59
+ ${TODO('top 3-5 quality goals as a table (goal → driver).')}
60
+
61
+ ## 2. Architecture Constraints
62
+ Stack: **${stack}**.
63
+ ${TODO('list hard constraints (language, deploy target, governance) with sources.')}
64
+
65
+ ## 3. Context and Scope
66
+ ${contextDiagram}
67
+ ${TODO('in-scope / out-of-scope in one line each.')}
68
+
69
+ ## 4. Solution Strategy
70
+ ${TODO('the 3-5 load-bearing decisions and why (one table).')}
71
+
72
+ ## 5. Building Block View
73
+ ${containerTable}
74
+
75
+ ${containerDiagram}
76
+ ${TODO('for each container, a short drilldown paragraph (the explorer shows the leaves).')}
77
+
78
+ ## 6. Runtime View
79
+ ${TODO('1-3 key sequences (a request / a job / a sync) as mermaid sequenceDiagrams.')}
80
+
81
+ ## 7. Deployment View
82
+ ${existsSync(join(REPO, 'Dockerfile')) || existsSync(join(REPO, 'docker')) ? 'A Dockerfile/`docker/` was detected — document the deployment topology.' : TODO('how and where this runs (a mermaid flowchart).')}
83
+
84
+ ## 8. Cross-cutting Concepts
85
+ ${TODO('validation, security, persistence, error handling, i18n — where each lives.')}
86
+
87
+ ## 9. Architecture Decisions
88
+ ${adrs}
89
+
90
+ ## 10. Quality Requirements
91
+ ${TODO('measurable targets (coverage, latency, availability) + how each is verified.')}
92
+
93
+ ## 11. Risks and Technical Debt
94
+ ${TODO('known risks and debt, with links to any register.')}
95
+
96
+ ## 12. Glossary
97
+ ${TODO('domain and project terms.')}
98
+ `
99
+ writeFileSync(OUT, md)
100
+ console.log(`[forma doc] wrote ${relative(REPO, OUT)} — ${containers.length} container(s), context + container diagrams from the model.`)
101
+ console.log('[forma doc] deterministic sections filled; write the TODO(forma) prose, then promote to ARCHITECTURE.md.')