@luhtech/site-template 0.5.1 → 0.6.1

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/README.md CHANGED
@@ -188,6 +188,80 @@ field-inspection, hard-hat, building, field-team, zone-map, change-order,
188
188
  crane) reads as borrowed Ectropy content anywhere else. No icons were
189
189
  added, removed, or renamed -- documentation only.
190
190
 
191
+ ## Real diagrams, and a real interactive tool (0.6.0)
192
+
193
+ `content/page.schema.json` v1.2.0 (d-2026-09-09-sr-page-diagrams-and-tool-schema)
194
+ added an optional `diagrams[]` array to `section` -- a real, discriminated-union
195
+ payload distinct from `figures[]` (one cited stat with provenance, not a
196
+ rendered visual). Three new, generic, real components render it:
197
+
198
+ - `RingComparison.astro` -- build-time-computed, area-proportional
199
+ (`r = k*sqrt(value)`, never linear -- linear radii visually exaggerate
200
+ ratios) concentric revenue/cost rings. `{rings: {label,revenue,cost}[]}`.
201
+ - `VectorSum.astro` -- **client-side** computed (unlike the other two):
202
+ real trig (`vx += cos(θ)·magnitude`) draws each input ray and the real
203
+ computed resultant. `{rays: {label,values:number[]}[]}`.
204
+ - `DataLineChart.astro` -- build-time-generated polyline from a real
205
+ `{x,y}[]` dataset, reusable for any dataset-backed chart.
206
+
207
+ `Diagram.astro` dispatches a `section.diagrams[]` entry to the right one by
208
+ `diagramType`, mirroring `Block.astro`'s dispatch-by-type convention.
209
+ `sections/Article.astro` renders `diagrams[]` after the body's `blocks[]`,
210
+ not interleaved -- the article chunk vocabulary (lede/section/pullquote/
211
+ stat/close) has no per-block diagram-anchor mechanism yet, an honest v1
212
+ limitation, not a hidden one.
213
+
214
+ **The interactive tool.** `content/tool.schema.json` (new, v1.1.0) is the
215
+ real contract `article.schema.json`'s `relatedToolRef` has pointed at since
216
+ v4.2.0: typed `inputs[]`/`outputFields[]`, a `computationRef` naming the
217
+ real client-side implementation, and (v1.1.0) an optional `presentation`
218
+ object -- `heroOutputId`, `chart{xLabel,yLabel}`, `methodNotes[]`,
219
+ `sources[]`, `disclosure` -- so a tool renders a hero KPI, a live chart
220
+ drawn from the computation's own returned points, a collapsible method/math
221
+ disclosure, and a cited sources footer, not just a flat output grid. Added
222
+ after reviewing a set of reference example tools (clickable-diagram +
223
+ inspector, KPI grid, chart, method notes, sources) that the flatter v1.0.0
224
+ design undershot; the bespoke clickable-diagram/inspector/scenario-ledger
225
+ layer those examples also use is deliberately out of scope -- genuinely
226
+ bespoke per-tool illustration work, not schema-parametrizable regardless.
227
+
228
+ `loadTool()` (new, `@luhtech/site-template/content`) reads and ajv-validates
229
+ a `content/tool.schema.json` instance from disk, same convention and error
230
+ handling as `loadPage`/`loadSite`. `ToolCalculator.astro` renders it: real
231
+ inputs, a live-computed result gated behind a contact-capture form, and
232
+ (when the instance's `presentation` block is present) the hero KPI/chart/
233
+ method-notes/sources described above. `<Section>`/`<Article>` gained
234
+ optional `tool`/`toolSubmitEndpoint`/`route`/`ventureRef` passthrough props
235
+ (same shape as `site`'s own passthrough) so a page with a `section.toolRef`
236
+ can load the resolved tool once at the page level and thread it down.
237
+
238
+ `src/lib/capacity-model.ts` is a faithful, function-for-function TypeScript
239
+ port of a real internal capacity-design/queueing/stochastic-optimization
240
+ model (`optimalPlan()`'s own newsvendor-flavoured search over nameplate
241
+ capacity, evaluated under a 25-node stratified-quantile demand distribution)
242
+ -- ported this way specifically because an earlier draft tool computed
243
+ `capacity = plannedDemand*(1+reserveRatio)` with `reserveRatio` as a raw
244
+ user input, which contradicted the real model (the reserve ratio is an
245
+ *output* of the optimization, never something a user sets directly).
246
+ `test/capacity-model.test.mjs` checks the port against the Python source's
247
+ own printed reference output at several points, not assumed-correct.
248
+ `npm test` runs Node's native TypeScript type-stripping (`--experimental-
249
+ strip-types`) to import `.ts` test subjects directly -- no build step, no
250
+ `ts-node`.
251
+
252
+ ## RingComparison: a loss reads at a glance (0.6.1)
253
+
254
+ Found in real local review (LuhTech-Business's "The Shape of a Strategy",
255
+ the real three-company example where C's cost genuinely exceeds its
256
+ revenue): the component computed correct, area-proportional radii from
257
+ day one, but with no dollar labels and no color distinction, a real loss
258
+ case was easy to miss at a glance -- exactly the finding the source essay
259
+ exists to make legible. `RingComparison.astro` now renders each ring's
260
+ real revenue/cost values as text, and a ring where `cost > revenue`
261
+ switches to a red dashed stroke with an explicit "at a loss" label --
262
+ computed from the same real props, not a second data path to keep in
263
+ sync.
264
+
191
265
  ## Migrating a venture site
192
266
 
193
267
  A migration is: author `content/site.<venture>.json` + `content/pages/*.json`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luhtech/site-template",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "description": "Shared Astro component library + content-instance contract for LuhTech venture marketing sites -- one template renders every site from content/page.schema.json + content/site.schema.json instances.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -29,7 +29,7 @@
29
29
  "luhtech-page-claims": "./bin/luhtech-page-claims.mjs"
30
30
  },
31
31
  "scripts": {
32
- "test": "node --test test/*.test.mjs"
32
+ "test": "node --experimental-strip-types --test test/*.test.mjs"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "astro": "^7.2",
@@ -44,6 +44,7 @@
44
44
  "content/page.schema.json": "1.0.0",
45
45
  "content/site.schema.json": "1.0.0",
46
46
  "content/capability-claim.schema.json": "0.2.0",
47
+ "content/tool.schema.json": "1.1.0",
47
48
  "portfolio/brand-identity.schema.json": "1.2.0"
48
49
  }
49
50
  }
@@ -0,0 +1,23 @@
1
+ ---
2
+ // d-2026-09-09-sr-page-diagrams-and-tool-schema. Dispatches one
3
+ // page.schema.json section.diagrams[] entry to its real rendering
4
+ // component by diagramType -- same dispatch convention Block.astro
5
+ // already uses for blockType.
6
+ import RingComparison from './diagrams/RingComparison.astro';
7
+ import VectorSum from './diagrams/VectorSum.astro';
8
+ import DataLineChart from './diagrams/DataLineChart.astro';
9
+
10
+ export interface Props {
11
+ diagram: { diagramId: string; diagramType: string; caption?: string; data: any };
12
+ class?: string;
13
+ }
14
+ const { diagram, class: className = 'my-8' } = Astro.props;
15
+ ---
16
+ <figure class={className}>
17
+ {diagram.diagramType === 'ring-comparison' && <RingComparison rings={diagram.data.rings} />}
18
+ {diagram.diagramType === 'vector-sum' && <VectorSum rays={diagram.data.rays} />}
19
+ {diagram.diagramType === 'data-line-chart' && (
20
+ <DataLineChart points={diagram.data.points} xLabel={diagram.data.xLabel} yLabel={diagram.data.yLabel} annotations={diagram.data.annotations} />
21
+ )}
22
+ {diagram.caption && <figcaption class="text-sm text-ink/60 mt-2 text-center">{diagram.caption}</figcaption>}
23
+ </figure>
@@ -53,8 +53,17 @@ export interface Props {
53
53
  site?: any;
54
54
  companyLabel?: string;
55
55
  icons?: SectionIcons;
56
+ // Passed through uniformly to whichever component actually looks at
57
+ // them -- today only sectionKind:"article" (Article.astro) reads these,
58
+ // for a real toolRef section rendering its resolved tool instance
59
+ // (loaded once by the page caller via loadTool(), same pattern as
60
+ // site/page themselves), same passthrough shape as `site` above.
61
+ tool?: any;
62
+ toolSubmitEndpoint?: string;
63
+ route?: string;
64
+ ventureRef?: string;
56
65
  }
57
- const { section, site, companyLabel, icons } = Astro.props;
66
+ const { section, site, companyLabel, icons, tool, toolSubmitEndpoint, route, ventureRef } = Astro.props;
58
67
  const Component = SECTION_COMPONENTS[section.sectionKind];
59
68
  if (!Component) {
60
69
  throw new Error(`Section.astro: unknown sectionKind "${section.sectionKind}" (id: ${section.sectionId})`);
@@ -62,6 +71,8 @@ if (!Component) {
62
71
  ---
63
72
  {section.sectionKind === 'cta' ? (
64
73
  <Cta section={section} leadCapture={site?.leadCapture} companyLabel={companyLabel} />
74
+ ) : section.sectionKind === 'article' ? (
75
+ <Component section={section} icons={icons} tool={tool} toolSubmitEndpoint={toolSubmitEndpoint} route={route} ventureRef={ventureRef} />
65
76
  ) : (
66
77
  <Component section={section} icons={icons} />
67
78
  )}
@@ -0,0 +1,301 @@
1
+ ---
2
+ // d-2026-09-09-sr-tool-schema-presentation-block. Real, client-side
3
+ // interactive tool: renders a content/tool.schema.json instance's real
4
+ // inputs[], computes its real output via a small client-side computation
5
+ // registry keyed by the tool's own computationRef (the schema carries the
6
+ // contract, this file carries one real implementation per registered
7
+ // computationRef -- same separation the schema's own description states),
8
+ // then gates the full result behind a real contact-capture form that
9
+ // POSTs to the real submission endpoint.
10
+ //
11
+ // v2 (supersedes the earlier flat-KPI-grid-only version before it ever
12
+ // shipped): renders the schema's optional presentation block -- a hero
13
+ // KPI, a live chart drawn from the computation's own returned points, a
14
+ // collapsible method/math disclosure, a cited sources footer, and a
15
+ // plain-language disclosure caption. Found necessary by reviewing a set
16
+ // of reference example tools (clickable-diagram+inspector, KPI grid,
17
+ // chart, method-notes, sources) against the earlier, flatter design,
18
+ // which undershot that bar.
19
+ //
20
+ // computationRef 'prefab-capacity-optimal-plan-v1' is a faithful port
21
+ // (src/lib/capacity-model.ts) of prefab_capacity_certainty_model.py, a
22
+ // real capacity-design/queueing/stochastic-optimization model -- NOT a
23
+ // hand-picked closed-form formula. An earlier draft of this tool computed
24
+ // capacity = plannedDemand*(1+reserveRatio) with reserveRatio as a raw
25
+ // user input; that contradicted the real model, where the reserve ratio
26
+ // is an OUTPUT of optimalPlan()'s search, never something a user dials in.
27
+ export interface ToolField {
28
+ id: string;
29
+ label: string;
30
+ type: 'number' | 'currency-usd' | 'percent' | 'integer' | 'string';
31
+ unit?: string;
32
+ min?: number;
33
+ max?: number;
34
+ helpText?: string;
35
+ }
36
+ export interface ToolMethodNote {
37
+ tag: string;
38
+ title: string;
39
+ formula?: string;
40
+ body: string;
41
+ }
42
+ export interface ToolSource {
43
+ label: string;
44
+ href: string;
45
+ }
46
+ export interface ToolPresentation {
47
+ heroOutputId?: string;
48
+ disclosure?: string;
49
+ chart?: { xLabel: string; yLabel: string; caption?: string };
50
+ methodNotes?: ToolMethodNote[];
51
+ sources?: ToolSource[];
52
+ }
53
+ export interface Tool {
54
+ toolId: string;
55
+ title: string;
56
+ description?: string;
57
+ computationRef: string;
58
+ inputs: ToolField[];
59
+ outputFields: ToolField[];
60
+ presentation?: ToolPresentation;
61
+ }
62
+ export interface Props {
63
+ tool: Tool;
64
+ submitEndpoint: string;
65
+ route: string;
66
+ ventureRef?: string;
67
+ class?: string;
68
+ }
69
+ const { tool, submitEndpoint, route, ventureRef, class: className = 'my-8' } = Astro.props;
70
+ const dataId = `tool-${tool.toolId}`;
71
+ const pres = tool.presentation ?? {};
72
+ const heroField = pres.heroOutputId ? tool.outputFields.find((f) => f.id === pres.heroOutputId) : undefined;
73
+ const restFields = tool.outputFields.filter((f) => f.id !== pres.heroOutputId);
74
+ ---
75
+ <div
76
+ class={`rounded-lg border border-ink/15 bg-ink/[0.02] p-6 sm:p-8 ${className}`}
77
+ data-tool={dataId}
78
+ data-tool-id={tool.toolId}
79
+ data-computation-ref={tool.computationRef}
80
+ data-submit-endpoint={submitEndpoint}
81
+ data-route={route}
82
+ data-venture-ref={ventureRef ?? ''}
83
+ >
84
+ <p class="font-display font-semibold text-lg mb-1">{tool.title}</p>
85
+ {tool.description && <p class="text-sm text-ink/70 mb-6">{tool.description}</p>}
86
+
87
+ <div class="grid sm:grid-cols-2 gap-4" data-tool-inputs>
88
+ {tool.inputs.map((f) => (
89
+ <label class="block">
90
+ <span class="text-xs font-mono uppercase tracking-wide text-ink/50">{f.label}{f.unit ? ` (${f.unit})` : ''}</span>
91
+ <input
92
+ type="number"
93
+ data-field={f.id}
94
+ min={f.min}
95
+ max={f.max}
96
+ step={f.type === 'percent' ? '0.01' : '1'}
97
+ class="mt-1 w-full rounded-md border border-ink/20 px-3 py-2 text-sm bg-canvas focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent-primary"
98
+ />
99
+ {f.helpText && <span class="block text-xs text-ink/50 mt-1">{f.helpText}</span>}
100
+ </label>
101
+ ))}
102
+ </div>
103
+
104
+ <div class="mt-6" data-tool-results hidden>
105
+ {heroField && (
106
+ <div class="rounded-md bg-accent-primary/10 border border-accent-primary/30 px-5 py-4 mb-4">
107
+ <p class="text-xs font-mono uppercase tracking-wide text-accent-primary/80">{heroField.label}</p>
108
+ <p class="font-display text-3xl font-bold text-accent-primary mt-1" data-output={heroField.id}>—</p>
109
+ </div>
110
+ )}
111
+ {restFields.length > 0 && (
112
+ <div class="grid sm:grid-cols-3 gap-4">
113
+ {restFields.map((f) => (
114
+ <div class="rounded-md bg-ink/[0.03] px-4 py-3">
115
+ <p class="text-xs font-mono uppercase tracking-wide text-ink/50">{f.label}</p>
116
+ <p class="font-display text-xl font-semibold text-ink mt-1" data-output={f.id}>—</p>
117
+ </div>
118
+ ))}
119
+ </div>
120
+ )}
121
+ {pres.disclosure && <p class="text-xs text-ink/50 mt-3 italic">{pres.disclosure}</p>}
122
+
123
+ {pres.chart && (
124
+ <div class="mt-6 border-t border-ink/10 pt-6">
125
+ <p class="text-sm font-medium mb-2">{pres.chart.caption ?? `${pres.chart.yLabel} vs. ${pres.chart.xLabel}`}</p>
126
+ <svg data-tool-chart viewBox="0 0 640 280" class="w-full h-auto" role="img" aria-label={`${pres.chart.yLabel} vs ${pres.chart.xLabel}`}></svg>
127
+ <div class="flex justify-between text-[10px] font-mono text-ink/50 mt-1">
128
+ <span>{pres.chart.xLabel}</span>
129
+ <span>{pres.chart.yLabel}</span>
130
+ </div>
131
+ </div>
132
+ )}
133
+
134
+ {pres.methodNotes && pres.methodNotes.length > 0 && (
135
+ <details class="mt-6 border-t border-ink/10 pt-4">
136
+ <summary class="text-sm font-medium cursor-pointer">What this tool is computing</summary>
137
+ <div class="mt-3 space-y-3">
138
+ {pres.methodNotes.map((n) => (
139
+ <div class="rounded-md bg-ink/[0.03] px-4 py-3">
140
+ <p class="text-xs font-mono uppercase tracking-wide text-ink/50">{n.tag} · {n.title}</p>
141
+ {n.formula && <p class="font-mono text-xs text-ink mt-1.5 overflow-x-auto">{n.formula}</p>}
142
+ <p class="text-sm text-ink/70 mt-1.5">{n.body}</p>
143
+ </div>
144
+ ))}
145
+ </div>
146
+ </details>
147
+ )}
148
+ </div>
149
+
150
+ <div class="mt-6 border-t border-ink/10 pt-6" data-tool-capture hidden>
151
+ <p class="text-sm font-medium mb-3">Get the full result emailed to you</p>
152
+ <div class="grid sm:grid-cols-2 gap-3">
153
+ <input type="text" data-contact="firstName" placeholder="First name" class="rounded-md border border-ink/20 px-3 py-2 text-sm bg-canvas" />
154
+ <input type="text" data-contact="lastName" placeholder="Last name" class="rounded-md border border-ink/20 px-3 py-2 text-sm bg-canvas" />
155
+ <input type="email" data-contact="email" placeholder="Work email" class="rounded-md border border-ink/20 px-3 py-2 text-sm bg-canvas" required />
156
+ <input type="text" data-contact="company" placeholder="Company" class="rounded-md border border-ink/20 px-3 py-2 text-sm bg-canvas" />
157
+ </div>
158
+ <button type="button" data-tool-submit class="mt-4 px-5 py-2.5 rounded-md bg-accent-primary text-canvas font-medium text-sm transition-all hover:opacity-90">
159
+ Email me the result
160
+ </button>
161
+ <p class="text-xs text-ink/50 mt-3" data-tool-status></p>
162
+ </div>
163
+
164
+ {pres.sources && pres.sources.length > 0 && (
165
+ <div class="mt-6 border-t border-ink/10 pt-4 text-xs text-ink/50 font-mono">
166
+ Sources: {pres.sources.map((s, i) => (
167
+ <>
168
+ <a href={s.href} class="underline hover:text-ink/80">{s.label}</a>
169
+ {i < pres.sources!.length - 1 ? ' · ' : ''}
170
+ </>
171
+ ))}
172
+ </div>
173
+ )}
174
+ </div>
175
+
176
+ <script>
177
+ import { optimalPlan } from '../lib/capacity-model';
178
+
179
+ interface ComputeResult {
180
+ outputs: Record<string, number>;
181
+ chart?: { points: { x: number; y: number }[] };
182
+ }
183
+
184
+ // Real computation registry, keyed by computationRef -- the schema
185
+ // carries the contract (tool.schema.json), this is the one real
186
+ // implementation registered under 'prefab-capacity-optimal-plan-v1',
187
+ // a faithful port of prefab_capacity_certainty_model.py's optimalPlan()
188
+ // (src/lib/capacity-model.ts), not a hand-picked formula.
189
+ const COMPUTATIONS: Record<string, (inputs: Record<string, string>) => ComputeResult> = {
190
+ 'prefab-capacity-optimal-plan-v1': (inputs) => {
191
+ const Dtrue = Number(inputs.annualDemand) || 0;
192
+ const theta = (Number(inputs.contractedShare) || 0) / 100;
193
+ const { best, curve } = optimalPlan(Dtrue, theta);
194
+ return {
195
+ outputs: {
196
+ optimalNameplate: Math.round(best.D),
197
+ expectedMargin: best.Em,
198
+ serviceLevel: best.Sv * 100,
199
+ },
200
+ chart: { points: curve.map(([D, Em]) => ({ x: D, y: Em })) },
201
+ };
202
+ },
203
+ };
204
+
205
+ function drawChart(svg: SVGSVGElement, points: { x: number; y: number }[]) {
206
+ const W = 640, H = 280, PAD_L = 56, PAD_R = 16, PAD_T = 16, PAD_B = 20;
207
+ const plotW = W - PAD_L - PAD_R, plotH = H - PAD_T - PAD_B;
208
+ const xs = points.map((p) => p.x), ys = points.map((p) => p.y);
209
+ const minX = Math.min(...xs), maxX = Math.max(...xs);
210
+ const minY = Math.min(...ys), maxY = Math.max(...ys);
211
+ const xRange = maxX - minX || 1, yRange = maxY - minY || 1;
212
+ const sx = (x: number) => PAD_L + ((x - minX) / xRange) * plotW;
213
+ const sy = (y: number) => PAD_T + plotH - ((y - minY) / yRange) * plotH;
214
+
215
+ const NS = 'http://www.w3.org/2000/svg';
216
+ svg.innerHTML = '';
217
+ const axisX = document.createElementNS(NS, 'line');
218
+ axisX.setAttribute('x1', String(PAD_L)); axisX.setAttribute('y1', String(PAD_T + plotH));
219
+ axisX.setAttribute('x2', String(PAD_L + plotW)); axisX.setAttribute('y2', String(PAD_T + plotH));
220
+ axisX.setAttribute('stroke', 'currentColor'); axisX.setAttribute('stroke-opacity', '0.2');
221
+ svg.appendChild(axisX);
222
+ const axisY = document.createElementNS(NS, 'line');
223
+ axisY.setAttribute('x1', String(PAD_L)); axisY.setAttribute('y1', String(PAD_T));
224
+ axisY.setAttribute('x2', String(PAD_L)); axisY.setAttribute('y2', String(PAD_T + plotH));
225
+ axisY.setAttribute('stroke', 'currentColor'); axisY.setAttribute('stroke-opacity', '0.2');
226
+ svg.appendChild(axisY);
227
+
228
+ const poly = document.createElementNS(NS, 'polyline');
229
+ poly.setAttribute('points', points.map((p) => `${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(' '));
230
+ poly.setAttribute('fill', 'none');
231
+ poly.setAttribute('stroke', 'currentColor');
232
+ poly.setAttribute('class', 'text-accent-primary');
233
+ poly.setAttribute('stroke-width', '1.75');
234
+ svg.appendChild(poly);
235
+
236
+ // mark the best (max-y) point -- the real optimum the tool selected
237
+ const bestPoint = points.reduce((a, b) => (b.y > a.y ? b : a), points[0]);
238
+ const dot = document.createElementNS(NS, 'circle');
239
+ dot.setAttribute('cx', String(sx(bestPoint.x))); dot.setAttribute('cy', String(sy(bestPoint.y)));
240
+ dot.setAttribute('r', '4'); dot.setAttribute('fill', 'currentColor'); dot.setAttribute('class', 'text-accent-primary');
241
+ svg.appendChild(dot);
242
+ }
243
+
244
+ document.querySelectorAll<HTMLElement>('[data-tool]').forEach((root) => {
245
+ const computationRef = root.dataset.computationRef ?? '';
246
+ const toolId = root.dataset.toolId ?? '';
247
+ const submitEndpoint = root.dataset.submitEndpoint ?? '';
248
+ const route = root.dataset.route ?? '';
249
+ const ventureRef = root.dataset.ventureRef || undefined;
250
+ const compute = COMPUTATIONS[computationRef];
251
+ if (!compute) return;
252
+
253
+ const inputEls = Array.from(root.querySelectorAll<HTMLInputElement>('[data-field]'));
254
+ const resultsEl = root.querySelector<HTMLElement>('[data-tool-results]');
255
+ const captureEl = root.querySelector<HTMLElement>('[data-tool-capture]');
256
+ const statusEl = root.querySelector<HTMLElement>('[data-tool-status]');
257
+ const chartSvg = root.querySelector<SVGSVGElement>('[data-tool-chart]');
258
+ let lastOutput: Record<string, number> | null = null;
259
+
260
+ const recompute = () => {
261
+ if (inputEls.some((el) => el.value === '')) return;
262
+ const inputs: Record<string, string> = {};
263
+ inputEls.forEach((el) => { inputs[el.dataset.field as string] = el.value; });
264
+ const result = compute(inputs);
265
+ lastOutput = result.outputs;
266
+ Object.entries(result.outputs).forEach(([key, value]) => {
267
+ const out = root.querySelector(`[data-output="${key}"]`);
268
+ if (out) out.textContent = typeof value === 'number' ? value.toLocaleString(undefined, { maximumFractionDigits: 1 }) : String(value);
269
+ });
270
+ if (chartSvg && result.chart) drawChart(chartSvg, result.chart.points);
271
+ resultsEl?.removeAttribute('hidden');
272
+ captureEl?.removeAttribute('hidden');
273
+ };
274
+ inputEls.forEach((el) => el.addEventListener('input', recompute));
275
+
276
+ const submitBtn = root.querySelector('[data-tool-submit]');
277
+ submitBtn?.addEventListener('click', async () => {
278
+ if (!lastOutput) return;
279
+ const contact: Record<string, string> = {};
280
+ root.querySelectorAll<HTMLInputElement>('[data-contact]').forEach((el) => { contact[el.dataset.contact as string] = el.value; });
281
+ if (!contact.email) {
282
+ if (statusEl) statusEl.textContent = 'A work email is required.';
283
+ return;
284
+ }
285
+ const inputs: Record<string, number> = {};
286
+ inputEls.forEach((el) => { inputs[el.dataset.field as string] = Number(el.value); });
287
+ if (statusEl) statusEl.textContent = 'Sending...';
288
+ try {
289
+ const res = await fetch(submitEndpoint, {
290
+ method: 'POST',
291
+ headers: { 'Content-Type': 'application/json' },
292
+ body: JSON.stringify({ toolId, route, ventureRef, inputs, output: lastOutput, contact }),
293
+ });
294
+ if (!res.ok) throw new Error(`status ${res.status}`);
295
+ if (statusEl) statusEl.textContent = 'Sent -- check your inbox.';
296
+ } catch {
297
+ if (statusEl) statusEl.textContent = 'Something went wrong -- try again in a moment.';
298
+ }
299
+ });
300
+ });
301
+ </script>
@@ -0,0 +1,64 @@
1
+ ---
2
+ // d-2026-09-09-sr-page-diagrams-and-tool-schema. Real, build-time
3
+ // generated line chart from a real {x,y}[] dataset (replaces the source
4
+ // essay's own technique of hand-typing 439 coordinate pairs -- here the
5
+ // real dataset is passed as data and a real polyline is generated from
6
+ // it at build time, reusable for any future dataset-backed chart, not
7
+ // just the one it was first built for). Computed server-side (Astro
8
+ // frontmatter), matching RingComparison.astro's convention -- the data
9
+ // is fixed at author time, no client-side recomputation needed.
10
+ export interface Props {
11
+ points: { x: number; y: number }[];
12
+ xLabel?: string;
13
+ yLabel?: string;
14
+ annotations?: { x: number; y: number; label: string }[];
15
+ class?: string;
16
+ }
17
+ const { points, xLabel, yLabel, annotations = [], class: className = 'w-full h-auto' } = Astro.props;
18
+
19
+ const W = 640;
20
+ const H = 280;
21
+ const PAD_L = 44;
22
+ const PAD_R = 16;
23
+ const PAD_T = 16;
24
+ const PAD_B = 36;
25
+ const plotW = W - PAD_L - PAD_R;
26
+ const plotH = H - PAD_T - PAD_B;
27
+
28
+ const xs = points.map((p) => p.x);
29
+ const ys = points.map((p) => p.y);
30
+ const minX = Math.min(...xs);
31
+ const maxX = Math.max(...xs);
32
+ const minY = Math.min(...ys, ...annotations.map((a) => a.y));
33
+ const maxY = Math.max(...ys, ...annotations.map((a) => a.y));
34
+ const xRange = maxX - minX || 1;
35
+ const yRange = maxY - minY || 1;
36
+
37
+ const sx = (x: number) => PAD_L + ((x - minX) / xRange) * plotW;
38
+ const sy = (y: number) => PAD_T + plotH - ((y - minY) / yRange) * plotH;
39
+
40
+ const polylinePoints = points.map((p) => `${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(' ');
41
+ ---
42
+ <svg
43
+ xmlns="http://www.w3.org/2000/svg"
44
+ viewBox={`0 0 ${W} ${H}`}
45
+ class={className}
46
+ role="img"
47
+ aria-label={`Line chart of ${points.length} real data points${yLabel ? `, ${yLabel}` : ''}${xLabel ? ` over ${xLabel}` : ''}`}
48
+ >
49
+ <line x1={PAD_L} y1={PAD_T} x2={PAD_L} y2={PAD_T + plotH} stroke="currentColor" stroke-opacity="0.2" />
50
+ <line x1={PAD_L} y1={PAD_T + plotH} x2={PAD_L + plotW} y2={PAD_T + plotH} stroke="currentColor" stroke-opacity="0.2" />
51
+ <polyline points={polylinePoints} fill="none" stroke="currentColor" class="text-accent-primary" stroke-width="1.75" />
52
+ {annotations.map((a) => (
53
+ <g>
54
+ <circle cx={sx(a.x)} cy={sy(a.y)} r="3" class="text-accent-secondary" fill="currentColor" />
55
+ <text x={sx(a.x)} y={sy(a.y) - 8} text-anchor="middle" font-family="JetBrains Mono, monospace" font-size="9" fill="currentColor" fill-opacity="0.7">{a.label}</text>
56
+ </g>
57
+ ))}
58
+ {yLabel && (
59
+ <text x={PAD_L} y={12} font-family="JetBrains Mono, monospace" font-size="10" fill="currentColor" fill-opacity="0.5">{yLabel}</text>
60
+ )}
61
+ {xLabel && (
62
+ <text x={PAD_L + plotW} y={H - 6} text-anchor="end" font-family="JetBrains Mono, monospace" font-size="10" fill="currentColor" fill-opacity="0.5">{xLabel}</text>
63
+ )}
64
+ </svg>
@@ -0,0 +1,73 @@
1
+ ---
2
+ // d-2026-09-09-sr-page-diagrams-and-tool-schema. Real, parameterized
3
+ // revenue/cost ring comparison -- one company is two concentric circles
4
+ // (the outer is revenue, the inner is cost; the ring between them is the
5
+ // business, per the real source essay this pattern comes from). Radii
6
+ // are area-proportional (r = k*sqrt(value)), never linear -- a linear
7
+ // radius scale visually exaggerates ratios between companies, which
8
+ // would misrepresent the real numbers passed in. Computed at build time
9
+ // (Astro frontmatter, server-side), matching DiagramVoxelCell.astro's
10
+ // own convention -- no runtime JS needed since the data is fixed at
11
+ // author time, not user-editable (unlike VectorSum.astro's live
12
+ // client-side computation, kept live because the source diagram it
13
+ // ports draws its resultant from a real, generated data array).
14
+ export interface Props {
15
+ rings: { label: string; revenue: number; cost: number }[];
16
+ class?: string;
17
+ highlightClass?: string;
18
+ }
19
+ const { rings, class: className = 'w-full h-auto', highlightClass = 'text-accent-primary' } = Astro.props;
20
+
21
+ const CELL_W = 180;
22
+ const PAD = 16;
23
+ const MAX_R = (CELL_W - PAD * 2) / 2;
24
+ const maxRevenue = Math.max(...rings.map((r) => r.revenue), 1);
25
+ const scale = MAX_R / Math.sqrt(maxRevenue);
26
+
27
+ const width = rings.length * CELL_W;
28
+ const height = CELL_W + 76;
29
+
30
+ const fmtUSD = (n: number) => `$${n.toLocaleString('en-US')}M`;
31
+
32
+ const cells = rings.map((r, i) => {
33
+ const cx = i * CELL_W + CELL_W / 2;
34
+ const cy = CELL_W / 2 + 20;
35
+ const revenueR = Math.max(Math.sqrt(r.revenue) * scale, 4);
36
+ const costR = Math.max(Math.sqrt(r.cost) * scale, 2);
37
+ // Real signal, not decoration: cost exceeding revenue means the ring
38
+ // between them has vanished -- the company is running at a loss (the
39
+ // real source essay's own "cost circle has grown past its revenue"
40
+ // case). Flagged, not just left to a same-color radius difference a
41
+ // reader could easily miss.
42
+ const atLoss = r.cost > r.revenue;
43
+ return { ...r, cx, cy, revenueR, costR, atLoss };
44
+ });
45
+ const maxR = Math.max(...cells.map((c) => Math.max(c.revenueR, c.costR)));
46
+ ---
47
+ <svg
48
+ xmlns="http://www.w3.org/2000/svg"
49
+ viewBox={`0 0 ${width} ${height}`}
50
+ class={className}
51
+ role="img"
52
+ aria-label={`Revenue and cost ring comparison across ${rings.length} companies: ${rings.map((r) => `${r.label} revenue ${fmtUSD(r.revenue)}, cost ${fmtUSD(r.cost)}`).join('; ')}`}
53
+ >
54
+ {cells.map((c) => (
55
+ <g>
56
+ <circle cx={c.cx} cy={c.cy} r={c.revenueR} fill="currentColor" fill-opacity="0.06" stroke="currentColor" stroke-width="1.5" />
57
+ <circle
58
+ cx={c.cx}
59
+ cy={c.cy}
60
+ r={c.costR}
61
+ class={c.atLoss ? 'text-red-600' : highlightClass}
62
+ fill="currentColor"
63
+ fill-opacity="0.18"
64
+ stroke="currentColor"
65
+ stroke-width={c.atLoss ? 2 : 1.5}
66
+ stroke-dasharray={c.atLoss ? '4 3' : undefined}
67
+ />
68
+ <text x={c.cx} y={c.cy + maxR + 20} text-anchor="middle" font-family="Inter, sans-serif" font-weight="600" font-size="13" fill="currentColor">{c.label}</text>
69
+ <text x={c.cx} y={c.cy + maxR + 36} text-anchor="middle" font-family="JetBrains Mono, monospace" font-size="10" fill="currentColor" fill-opacity="0.6">rev {fmtUSD(c.revenue)}</text>
70
+ <text x={c.cx} y={c.cy + maxR + 50} text-anchor="middle" font-family="JetBrains Mono, monospace" font-size="10" class={c.atLoss ? 'text-red-600' : undefined} fill="currentColor" fill-opacity={c.atLoss ? 1 : 0.6}>cost {fmtUSD(c.cost)}{c.atLoss ? ' -- at a loss' : ''}</text>
71
+ </g>
72
+ ))}
73
+ </svg>
@@ -0,0 +1,98 @@
1
+ ---
2
+ // d-2026-09-09-sr-page-diagrams-and-tool-schema. Real, client-side
3
+ // computed vector-sum diagram, ported from the real source essay's own
4
+ // live-generated version (vanilla JS, createElementNS, real trig) --
5
+ // kept client-side deliberately rather than flattened to static build-
6
+ // time SVG (unlike RingComparison.astro/DataLineChart.astro), matching
7
+ // the source's own reasoning: this is a genuinely computational diagram
8
+ // (a resultant IS a computation, not just a rendered fact), and the same
9
+ // real trig utility here is the direct basis for the capacity/reserve
10
+ // calculator's own client-side computation (Phase B).
11
+ //
12
+ // Each ray gets an angle (evenly spaced around the circle, so cells at
13
+ // opposing angles genuinely cancel per the source essay's own point) and
14
+ // a magnitude (sum of its real values[] array). The resultant is the
15
+ // real vector sum: Σ magnitude·cos(θ), Σ magnitude·sin(θ) -- never a
16
+ // hardcoded arrow.
17
+ export interface Props {
18
+ rays: { label: string; values: number[] }[];
19
+ class?: string;
20
+ resultantClass?: string;
21
+ }
22
+ const { rays, class: className = 'w-full h-auto', resultantClass = 'text-accent-primary' } = Astro.props;
23
+ const dataId = `vector-sum-${Math.random().toString(36).slice(2, 9)}`;
24
+ ---
25
+ <svg
26
+ xmlns="http://www.w3.org/2000/svg"
27
+ viewBox="0 0 300 300"
28
+ class={className}
29
+ role="img"
30
+ aria-label={`Vector sum of ${rays.length} rays, showing the resultant direction`}
31
+ data-vector-sum={dataId}
32
+ >
33
+ <circle cx="150" cy="150" r="120" fill="none" stroke="currentColor" stroke-opacity="0.12" />
34
+ <g data-rays></g>
35
+ <line data-resultant x1="150" y1="150" x2="150" y2="150" class={resultantClass} stroke="currentColor" stroke-width="2.5" marker-end={`url(#${dataId}-arrow)`} />
36
+ <defs>
37
+ <marker id={`${dataId}-arrow`} viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
38
+ <path d="M0,0 L10,5 L0,10 z" class={resultantClass} fill="currentColor" />
39
+ </marker>
40
+ </defs>
41
+ </svg>
42
+ <script define:vars={{ dataId, rays }}>
43
+ {
44
+ const svg = document.querySelector(`svg[data-vector-sum="${dataId}"]`);
45
+ if (svg) {
46
+ const cx = 150;
47
+ const cy = 150;
48
+ const maxLen = 110;
49
+ const raysGroup = svg.querySelector('[data-rays]');
50
+ const magnitudes = rays.map((r) => r.values.reduce((a, b) => a + b, 0));
51
+ const maxMag = Math.max(...magnitudes.map(Math.abs), 1);
52
+
53
+ let vx = 0;
54
+ let vy = 0;
55
+ rays.forEach((ray, i) => {
56
+ const angle = (2 * Math.PI * i) / rays.length - Math.PI / 2;
57
+ const magnitude = magnitudes[i];
58
+ const len = (magnitude / maxMag) * maxLen;
59
+ const x2 = cx + Math.cos(angle) * len;
60
+ const y2 = cy + Math.sin(angle) * len;
61
+ vx += Math.cos(angle) * magnitude;
62
+ vy += Math.sin(angle) * magnitude;
63
+
64
+ const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
65
+ line.setAttribute('x1', String(cx));
66
+ line.setAttribute('y1', String(cy));
67
+ line.setAttribute('x2', String(x2));
68
+ line.setAttribute('y2', String(y2));
69
+ line.setAttribute('stroke', 'currentColor');
70
+ line.setAttribute('stroke-opacity', '0.35');
71
+ line.setAttribute('stroke-width', '1.5');
72
+ raysGroup?.appendChild(line);
73
+
74
+ const label = document.createElementNS('http://www.w3.org/2000/svg', 'text');
75
+ label.setAttribute('x', String(cx + Math.cos(angle) * (maxLen + 14)));
76
+ label.setAttribute('y', String(cy + Math.sin(angle) * (maxLen + 14)));
77
+ label.setAttribute('text-anchor', 'middle');
78
+ label.setAttribute('font-family', 'JetBrains Mono, monospace');
79
+ label.setAttribute('font-size', '9');
80
+ label.setAttribute('fill', 'currentColor');
81
+ label.setAttribute('fill-opacity', '0.6');
82
+ label.textContent = ray.label;
83
+ raysGroup?.appendChild(label);
84
+ });
85
+
86
+ // Real vector sum, normalized against the sum of magnitudes (not
87
+ // maxMag) so the resultant length reflects how much cancellation
88
+ // actually occurred -- the whole point of the source diagram.
89
+ const sumOfMagnitudes = magnitudes.reduce((a, b) => a + Math.abs(b), 0) || 1;
90
+ const resultantScale = maxLen / sumOfMagnitudes;
91
+ const rx2 = cx + vx * resultantScale;
92
+ const ry2 = cy + vy * resultantScale;
93
+ const resultant = svg.querySelector('[data-resultant]');
94
+ resultant?.setAttribute('x2', String(rx2));
95
+ resultant?.setAttribute('y2', String(ry2));
96
+ }
97
+ }
98
+ </script>
@@ -5,10 +5,29 @@
5
5
  // site-bridge). Blocks render in sequence exactly as authored -- lede first,
6
6
  // then paragraph/pullquote/stat blocks in the article's own order, closing
7
7
  // with a `close` block if the source article ended with one.
8
+ // diagrams[]/toolRef added v1.2.0 (d-2026-09-09-sr-page-diagrams-and-
9
+ // tool-schema): rendered after the body blocks, not interleaved within
10
+ // them -- the chunk vocabulary (lede/section/pullquote/stat/close) has
11
+ // no per-block diagram-anchor mechanism yet, so a section's real
12
+ // diagrams appear together as supporting visualization following the
13
+ // prose, honest about where they actually sit today rather than
14
+ // pretending precise inline placement exists.
8
15
  import Block from '../Block.astro';
16
+ import Diagram from '../Diagram.astro';
17
+ import ToolCalculator from '../ToolCalculator.astro';
9
18
 
10
- export interface Props { section: any }
11
- const { section } = Astro.props;
19
+ export interface Props {
20
+ section: any;
21
+ // Resolved content/tool.schema.json instance for section.toolRef, when
22
+ // present -- the page-level caller loads it (loadTool()) and passes it
23
+ // down, same pattern as site/page themselves being loaded once at the
24
+ // page level rather than re-resolved per component.
25
+ tool?: any;
26
+ toolSubmitEndpoint?: string;
27
+ route?: string;
28
+ ventureRef?: string;
29
+ }
30
+ const { section, tool, toolSubmitEndpoint, route, ventureRef } = Astro.props;
12
31
  ---
13
32
  <section id={section.sectionId} class="py-8" data-reveal>
14
33
  {section.eyebrow && <p class="text-sm font-mono uppercase tracking-wide text-accent-primary mb-3">{section.eyebrow}</p>}
@@ -17,4 +36,14 @@ const { section } = Astro.props;
17
36
  <div class="max-w-2xl space-y-5">
18
37
  {section.blocks?.map((b: any) => <Block block={b} />)}
19
38
  </div>
39
+ {section.diagrams?.length > 0 && (
40
+ <div class="max-w-2xl space-y-8 mt-8">
41
+ {section.diagrams.map((d: any) => <Diagram diagram={d} />)}
42
+ </div>
43
+ )}
44
+ {section.toolRef && tool && toolSubmitEndpoint && (
45
+ <div class="max-w-2xl">
46
+ <ToolCalculator tool={tool} submitEndpoint={toolSubmitEndpoint} route={route ?? ''} ventureRef={ventureRef} />
47
+ </div>
48
+ )}
20
49
  </section>
@@ -5,3 +5,5 @@ export type { LoadedSite } from './loadSite.js';
5
5
  export { loadBrand } from './loadBrand.js';
6
6
  export type { LoadedBrand } from './loadBrand.js';
7
7
  export { applyBrandDefaults } from './bindBrand.js';
8
+ export { loadTool } from './loadTool.js';
9
+ export type { LoadedTool, ToolFieldSpec, ToolPresentationSpec, ToolMethodNoteSpec, ToolSourceSpec } from './loadTool.js';
@@ -3,7 +3,7 @@ import Ajv from 'ajv';
3
3
  import addFormats from 'ajv-formats';
4
4
  import { fetchSchema, fetchSupportSchema } from './schemaFetch.js';
5
5
 
6
- const PAGE_PIN = '1.1.0';
6
+ const PAGE_PIN = '1.2.0';
7
7
  const CAPABILITY_CLAIM_PIN = '0.2.0';
8
8
 
9
9
  let validatorPromise: ReturnType<typeof buildValidator> | null = null;
@@ -58,6 +58,13 @@ export interface PageCrossLink {
58
58
  href: string;
59
59
  }
60
60
 
61
+ export interface PageDiagram {
62
+ diagramId: string;
63
+ diagramType: string;
64
+ caption?: string;
65
+ data: unknown;
66
+ }
67
+
61
68
  export interface PageSection {
62
69
  sectionId: string;
63
70
  sectionKind: string;
@@ -69,6 +76,8 @@ export interface PageSection {
69
76
  ctas?: PageCta[];
70
77
  crossLinks?: PageCrossLink[];
71
78
  figures?: unknown[];
79
+ diagrams?: PageDiagram[];
80
+ toolRef?: string;
72
81
  [key: string]: unknown;
73
82
  }
74
83
 
@@ -0,0 +1,89 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import Ajv from 'ajv';
3
+ import addFormats from 'ajv-formats';
4
+ import { fetchSchema, fetchSupportSchema } from './schemaFetch.js';
5
+
6
+ const TOOL_PIN = '1.1.0';
7
+
8
+ let validatorPromise: ReturnType<typeof buildValidator> | null = null;
9
+
10
+ async function buildValidator() {
11
+ const ajv = new Ajv({ strict: false, allErrors: true });
12
+ addFormats(ajv);
13
+
14
+ const [toolSchema, definitionsSchema, graphSchema] = await Promise.all([
15
+ fetchSchema('content/tool.schema.json', TOOL_PIN),
16
+ fetchSupportSchema('_definitions/definitions.schema.json'),
17
+ fetchSupportSchema('_definitions/graph.schema.json'),
18
+ ]);
19
+
20
+ ajv.addSchema(definitionsSchema as object);
21
+ ajv.addSchema(graphSchema as object);
22
+
23
+ return ajv.compile(toolSchema as object);
24
+ }
25
+
26
+ export interface ToolFieldSpec {
27
+ id: string;
28
+ label: string;
29
+ type: 'number' | 'currency-usd' | 'percent' | 'integer' | 'string';
30
+ unit?: string;
31
+ min?: number;
32
+ max?: number;
33
+ helpText?: string;
34
+ }
35
+
36
+ export interface ToolMethodNoteSpec {
37
+ tag: string;
38
+ title: string;
39
+ formula?: string;
40
+ body: string;
41
+ }
42
+
43
+ export interface ToolSourceSpec {
44
+ label: string;
45
+ href: string;
46
+ }
47
+
48
+ export interface ToolPresentationSpec {
49
+ heroOutputId?: string;
50
+ disclosure?: string;
51
+ chart?: { xLabel: string; yLabel: string; caption?: string };
52
+ methodNotes?: ToolMethodNoteSpec[];
53
+ sources?: ToolSourceSpec[];
54
+ }
55
+
56
+ export interface LoadedTool {
57
+ toolId: string;
58
+ title: string;
59
+ description?: string;
60
+ computationRef: string;
61
+ inputs: ToolFieldSpec[];
62
+ outputFields: ToolFieldSpec[];
63
+ presentation?: ToolPresentationSpec;
64
+ [key: string]: unknown;
65
+ }
66
+
67
+ /**
68
+ * Reads a content/tool.schema.json instance from disk and ajv-validates it
69
+ * against the pinned live schema (+ its real $ref chain). Throws on any
70
+ * validation failure -- same convention as loadPage/loadSite.
71
+ */
72
+ export async function loadTool(path: string): Promise<LoadedTool> {
73
+ const raw = readFileSync(path, 'utf-8');
74
+ const instance = JSON.parse(raw);
75
+
76
+ if (!validatorPromise) validatorPromise = buildValidator();
77
+ const validate = await validatorPromise;
78
+
79
+ if (!validate(instance)) {
80
+ const errors = (validate.errors ?? [])
81
+ .map((e) => ` ${e.instancePath || '/'} ${e.message}`)
82
+ .join('\n');
83
+ throw new Error(
84
+ `${path} failed content/tool.schema.json@${TOOL_PIN} validation:\n${errors}`
85
+ );
86
+ }
87
+
88
+ return instance as LoadedTool;
89
+ }
@@ -0,0 +1,323 @@
1
+ // Faithful TypeScript port of prefab_capacity_certainty_model.py, LuhTech's
2
+ // own internal capacity-design + queueing + stochastic-optimization model
3
+ // (baseline anchored to the EC_Skids switchgear family --
4
+ // Prefab_SupplyDemand_Model.xlsx / prefab_optimize.py). Illustrative
5
+ // internal engineering baseline, not an audited financial forecast --
6
+ // Erik's own framing when he supplied the source file ("draft runs, will
7
+ // require edit potentially").
8
+ //
9
+ // This is deliberately a direct, function-for-function port (same names,
10
+ // same formulas, same default parameters) rather than a re-derivation --
11
+ // every function here should be checkable line-by-line against the
12
+ // Python source. optimalPlan() is the real newsvendor-flavoured core
13
+ // result: with demand centred on Dtrue and dispersion set by contract
14
+ // coverage theta, what nameplate capacity maximises expected margin
15
+ // dollars, subject to a service-level floor? The reserve/capacity ratio
16
+ // this implies is an OUTPUT of that search, never a value a caller sets
17
+ // directly -- ported this way specifically because an earlier hand-picked
18
+ // closed-form formula (capacity = plannedDemand*(1+reserveRatio), with
19
+ // reserveRatio as a raw input) contradicted this real mechanism.
20
+ //
21
+ // Ported a second time, independently, into Ectropy-Business's api-gateway
22
+ // for the server-side integrity-boundary recompute (never trust a
23
+ // client-submitted result) -- both ports are checked against the same
24
+ // Python reference table (capacity-model.test.ts), not shared as one
25
+ // package yet (a real, later follow-on once the model has shipped twice
26
+ // and proven stable).
27
+
28
+ export interface ModelParams {
29
+ W: number; Kel: number; tmax: number; crew: number;
30
+ shifts: number; hpd: number; days: number; avail: number;
31
+ a: number; lam: number; kap: number; ustar: number; theta: number; ce2: number;
32
+ rate: number; asp: number; mat: number;
33
+ otMult: number; subMark: number; varOH: number;
34
+ plantFix: number; lineFix: number;
35
+ leadDays: number; zone: number;
36
+ aOT: number; aS2: number; s2on: boolean; rho: number; SL: number;
37
+ beta: number; subLateMo: number;
38
+ Ast: number; Awip: number;
39
+ rentPSF: number; ownShell: boolean;
40
+ }
41
+
42
+ export const DEFAULT_PARAMS: ModelParams = {
43
+ W: 260.0, Kel: 40, tmax: 16.0, crew: 2.0,
44
+ shifts: 1.0, hpd: 8.0, days: 250.0, avail: 0.85,
45
+ a: 0.0, lam: 0.35, kap: 0.60, ustar: 0.85, theta: 0.50, ce2: 0.45,
46
+ rate: 85.0, asp: 600_000.0, mat: 380_000.0,
47
+ otMult: 1.5, subMark: 1.18, varOH: 0.06,
48
+ plantFix: 400_000.0, lineFix: 220_000.0,
49
+ leadDays: 35.0, zone: 5,
50
+ aOT: 0.20, aS2: 0.85, s2on: false, rho: 0.70, SL: 0.95,
51
+ beta: 0.12, subLateMo: 2.0,
52
+ Ast: 750.0, Awip: 350.0,
53
+ rentPSF: 11.50, ownShell: false,
54
+ };
55
+
56
+ const CA2_SPEC = 1.80, CA2_CON = 0.15;
57
+ const SIG_SPEC = 0.35, SIG_CON = 0.04;
58
+ const CRF_EQ = 0.12 / (1 - Math.pow(1.12, -7)); // 0.2191, 7-yr equipment
59
+ const CRF_FAC = 0.12 / (1 - Math.pow(1.12, -10)); // 0.1770, 10-yr facility
60
+
61
+ export interface Design {
62
+ A: number; Weff: number; tmaxE: number; takt: number; tTarget: number; eta: number;
63
+ Nser: number; mReq: number; N: number; tbar: number; tb: number; u: number; floorD: number;
64
+ }
65
+
66
+ export function design(D: number, p: ModelParams = DEFAULT_PARAMS): Design {
67
+ const A = p.shifts * p.hpd * p.days * p.avail;
68
+ const Weff = p.W * (1 - p.a * p.lam);
69
+ const tmaxE = p.tmax * (1 - p.a * p.kap);
70
+ const takt = A / D;
71
+ const tTarget = p.ustar * takt;
72
+ const elem = Weff / p.Kel;
73
+ let eta = 1.0 / (1.0 + 0.5 * elem / (p.crew * tTarget));
74
+ eta = Math.min(0.97, Math.max(0.55, eta));
75
+ const Nser = Math.ceil(Weff / (p.crew * tTarget * eta));
76
+ const mReq = Math.ceil(tmaxE / (p.crew * tTarget));
77
+ const N = Nser + (mReq - 1);
78
+ const tbar = Weff / (p.crew * N);
79
+ const tb = tbar / eta;
80
+ const u = Math.min(0.985, tb / takt);
81
+ return { A, Weff, tmaxE, takt, tTarget, eta, Nser, mReq, N, tbar, tb, u, floorD: A * p.crew * p.ustar / tmaxE };
82
+ }
83
+
84
+ /** Factory flow time (hours). Kingman VUT applied at DECOUPLING POINTS only:
85
+ * stations inside a paced zone are coupled, so queues form at zone boundaries.
86
+ * Pooling inside a zone shrinks its CV (variance of a sum of n iid -> CV^2/n). */
87
+ export function ctLine(u: number, d: Design, p: ModelParams = DEFAULT_PARAMS, ca2?: number): number {
88
+ if (ca2 === undefined) ca2 = CA2_SPEC * (1 - p.theta) + CA2_CON * p.theta;
89
+ u = Math.min(Math.max(u, 0.02), 0.985);
90
+ const N = d.N, ce2 = p.ce2, z = Math.max(1, Math.trunc(p.zone));
91
+ const Z = Math.ceil(N / z);
92
+ let CT = 0.0, cai = ca2;
93
+ for (let k = 0; k < Z; k++) {
94
+ const n = Math.min(z, N - k * z);
95
+ const te = n * d.tbar;
96
+ const ce2z = ce2 / n;
97
+ const V = (cai + ce2z) / 2;
98
+ const U = u / (1 - u);
99
+ CT += V * U * te + te;
100
+ cai = u * u * ce2z + (1 - u * u) * cai;
101
+ }
102
+ return CT;
103
+ }
104
+
105
+ /** Nameplate and the flexed capacity ceilings from the demand-matching levers. */
106
+ export function flexCapacity(D: number, d: Design, p: ModelParams = DEFAULT_PARAMS): [number, number, number] {
107
+ const nameplate = d.u > 0 ? D / d.u : D;
108
+ return [nameplate, nameplate * (1 + p.aOT), nameplate * (1 + p.aOT + (p.s2on ? p.aS2 : 0))];
109
+ }
110
+
111
+ export interface Capex {
112
+ stations: number; tooling: number; mh: number; mhName: string; crane: number; bays: number;
113
+ test: number; nTest: number; paint: number; paintIn: boolean; mes: number; mesName: string;
114
+ elec: number; elecName: string; kva: number; fitout: number; slab: number; shell: number;
115
+ equip: number; fac: number; total: number; gross: number; wip: number; CT: number; cSt: number;
116
+ }
117
+
118
+ /** Continuous-with-steps facility build-out capital. */
119
+ export function capex(D: number, d: Design, p: ModelParams = DEFAULT_PARAMS): Capex {
120
+ const N = d.N, takt = d.takt;
121
+ const tSt = p.crew * takt * p.ustar;
122
+ const cSt = 45_000 + 85_000 * Math.pow(20.0 / Math.max(tSt, 0.5), 0.65);
123
+ const cStAuto = p.a * 320_000 * p.lam;
124
+ const stations = N * (cSt + cStAuto);
125
+ const tooling = 240_000 + N * 9_000 + p.Kel * 11_000;
126
+ let mh: [string, number, number];
127
+ if (takt > 24) mh = ['Forklift + floor-marked lanes', 0, 0];
128
+ else if (takt > 8) mh = ['Air-caster carts, guided lanes', 180_000, 9_000];
129
+ else if (takt > 3) mh = ['Powered roller / skillet, paced', 1_450_000, 38_000];
130
+ else mh = ['Indexed AGV line, lift + rotate', 3_600_000, 52_000];
131
+ const mhC = mh[1] + N * mh[2];
132
+ const bays = Math.ceil(N / 6);
133
+ const craneC = bays * 420_000;
134
+ const nTest = Math.ceil(D / 55);
135
+ const testC = nTest ? 680_000 + (nTest - 1) * 520_000 : 0;
136
+ const paintIn = D >= 120;
137
+ const paintC = paintIn ? 1_350_000 : 0;
138
+ const mesC = D < 60 ? 0 : (D < 180 ? 420_000 : 1_600_000);
139
+ const mesName = D < 60 ? 'Spreadsheets + ERP module'
140
+ : D < 180 ? 'MES lite - routings, traveller, e-sign'
141
+ : 'Full MES + ShopOS traceability, inline test capture';
142
+ const kva = 350 + 42 * N + 250 * nTest + p.a * 180 * N;
143
+ let elec: [number, string];
144
+ if (kva < 900) elec = [0, 'Existing 1200 A / 480 V service'];
145
+ else if (kva < 1900) elec = [340_000, 'Upgrade to 2500 A switchboard'];
146
+ else if (kva < 3400) elec = [760_000, 'Upgrade to 4000 A service'];
147
+ else elec = [1_900_000, 'Own 12.47 kV service + pad transformer'];
148
+ const CT = ctLine(d.u, d, p);
149
+ const wip = CT / takt;
150
+ const prod = N * p.Ast + wip * p.Awip;
151
+ const shared = 12_000 + 55 * D;
152
+ const gross = (prod + shared) / 0.62;
153
+ const fitout = gross * 38;
154
+ const slab = prod * 14;
155
+ const shell = p.ownShell ? gross * 148 : 0;
156
+ const equip = stations + tooling + mhC + craneC + testC + paintC + mesC + elec[0];
157
+ const fac = fitout + slab + shell;
158
+ return {
159
+ stations, tooling, mh: mhC, mhName: mh[0], crane: craneC, bays,
160
+ test: testC, nTest, paint: paintC, paintIn, mes: mesC,
161
+ mesName, elec: elec[0], elecName: elec[1], kva, fitout, slab, shell,
162
+ equip, fac, total: equip + fac, gross, wip, CT, cSt,
163
+ };
164
+ }
165
+
166
+ /** Acklam's rational approximation to the inverse standard-normal CDF. */
167
+ function ppf(q: number): number {
168
+ const a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02,
169
+ 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00];
170
+ const b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02,
171
+ 6.680131188771972e+01, -1.328068155288572e+01];
172
+ const c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00,
173
+ -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00];
174
+ const dd = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00,
175
+ 3.754408661907416e+00];
176
+ const pl = 0.02425, ph = 1 - 0.02425;
177
+ if (q < pl) {
178
+ const t = Math.sqrt(-2 * Math.log(q));
179
+ return (((((c[0] * t + c[1]) * t + c[2]) * t + c[3]) * t + c[4]) * t + c[5]) /
180
+ ((((dd[0] * t + dd[1]) * t + dd[2]) * t + dd[3]) * t + 1);
181
+ }
182
+ if (q > ph) {
183
+ const t = Math.sqrt(-2 * Math.log(1 - q));
184
+ return -(((((c[0] * t + c[1]) * t + c[2]) * t + c[3]) * t + c[4]) * t + c[5]) /
185
+ ((((dd[0] * t + dd[1]) * t + dd[2]) * t + dd[3]) * t + 1);
186
+ }
187
+ const t = q - 0.5, r = t * t;
188
+ return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * t /
189
+ (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
190
+ }
191
+
192
+ const NQ = 25;
193
+ // Stratified quantile nodes: equal-probability slices of the demand distribution.
194
+ const GH: [number, number][] = Array.from({ length: NQ }, (_, i) => [ppf((i + 0.5) / NQ), 1.0 / NQ]);
195
+
196
+ export interface PnlResult {
197
+ Dr: number; served: number; lost: number; u: number; CTd: number; ot: number; s2: number; sub: number;
198
+ unit: number; marginD: number; margin: number; service: number; onTime: boolean; w?: number;
199
+ }
200
+
201
+ /** P&L and service outcome for ONE realised demand, with the plant already built for
202
+ * Dplan. Capital, floor space and standing payroll are sunk at the design point. */
203
+ export function pnlAt(Dr: number, Dplan: number, d: Design, cx: Capex, p: ModelParams, ca2: number): PnlResult {
204
+ const vc = p.mat + p.W * p.rate + p.mat * p.varOH;
205
+ const cOT = p.W * (p.rate * p.otMult - p.rate);
206
+ const [nameplate, kOT, kMax] = flexCapacity(Dplan, d, p);
207
+ const subCap = p.beta * nameplate; // supply-constrained market: overflow is scarce
208
+ Dr = Math.max(1.0, Dr);
209
+ const sub = Math.min(Math.max(0.0, Dr - kMax), subCap);
210
+ const lost = Math.max(0.0, Dr - kMax - subCap); // orders you simply cannot take
211
+ const served = Dr - lost;
212
+ const inhouse = served - sub;
213
+ const over = Math.max(0.0, inhouse - nameplate);
214
+ const ot = Math.min(over, kOT - nameplate);
215
+ const s2 = Math.max(0.0, over - ot);
216
+ const ur = Math.min(0.985, Math.max(0.05,
217
+ d.u * inhouse / (nameplate * (1 + p.rho * (ot + s2) / nameplate))));
218
+ // Sustained premium hours are not free variability-wise: fatigue, rushed work, rework on
219
+ // overtime; lower proficiency and thinner supervision on a stood-up second shift.
220
+ const ce2_eff = p.ce2 * (1 + 1.75 * ot / nameplate + 0.60 * s2 / nameplate);
221
+ const q: ModelParams = { ...p, ce2: ce2_eff };
222
+ const CTd = ctLine(ur, d, q, ca2) / (p.hpd * p.shifts * p.avail);
223
+ const lateUnit = Math.max(0.0, CTd - p.leadDays) / 21.0 * 0.04 * p.asp;
224
+ const sunk = (d.N * p.crew * d.A * p.rate
225
+ + (p.plantFix + p.lineFix) * 12
226
+ + cx.equip * CRF_EQ + cx.fac * CRF_FAC + 0.06 * cx.equip
227
+ + (p.ownShell ? 0 : cx.gross * p.rentPSF));
228
+ const varUnit = p.mat + p.mat * p.varOH + (cx.paintIn ? 900 : 2800);
229
+ const cost = (sunk + varUnit * inhouse + ot * cOT + s2 * p.W * p.rate * 0.10
230
+ + sub * p.subMark * vc
231
+ + sub * p.subLateMo * 0.04 * p.asp + lateUnit * inhouse);
232
+ const rev = p.asp * served;
233
+ return {
234
+ Dr, served, lost, u: ur, CTd, ot, s2, sub,
235
+ unit: cost / Math.max(served, 1e-9), marginD: rev - cost,
236
+ margin: (rev - cost) / Math.max(rev, 1e-9),
237
+ // a unit counts as delivered on the promise only if it came off YOUR line
238
+ // inside the promised flow time. Subcontracted and unserved orders do not.
239
+ service: (CTd <= p.leadDays ? inhouse : 0.0) / Dr,
240
+ onTime: CTd <= p.leadDays && sub < 0.5 && lost < 0.5,
241
+ };
242
+ }
243
+
244
+ export interface Evaluation {
245
+ d: Design; cx: Capex; base: PnlResult; nodes: PnlResult[]; sig: number; ca2: number;
246
+ Eunit: number; Emargin: number; ECT: number; pLate: number; p10: number;
247
+ Esub: number; Elost: number; EmarginD: number; Eservice: number; p10D: number; jensen: number; raw: number;
248
+ }
249
+
250
+ /** Full deterministic + distributional evaluation at a planned volume. */
251
+ export function evaluate(Dplan: number, p: ModelParams = DEFAULT_PARAMS): Evaluation {
252
+ const d = design(Dplan, p);
253
+ const cx = capex(Dplan, d, p);
254
+ const sig = SIG_SPEC * (1 - p.theta) + SIG_CON * p.theta;
255
+ const ca2 = CA2_SPEC * (1 - p.theta) + CA2_CON * p.theta;
256
+ const base = pnlAt(Dplan, Dplan, d, cx, p, ca2);
257
+ const sw = GH.reduce((s, [, w]) => s + w, 0);
258
+ const s_ln = Math.sqrt(Math.log(1 + sig * sig)); // lognormal: demand stays positive, E[D]=Dplan
259
+ const nodes: PnlResult[] = GH.map(([z, w]) => {
260
+ const r = pnlAt(Dplan * Math.exp(s_ln * z - 0.5 * s_ln * s_ln), Dplan, d, cx, p, ca2);
261
+ r.w = w / sw;
262
+ return r;
263
+ });
264
+ const E = (k: keyof PnlResult) => nodes.reduce((s, n) => s + (n.w as number) * (n[k] as number), 0);
265
+ const pLate = nodes.reduce((s, n) => s + (n.onTime ? 0 : (n.w as number)), 0);
266
+ const dsort = [...nodes].sort((a, b) => a.margin - b.margin);
267
+ let cum = 0, p10 = dsort[0].margin;
268
+ for (const n of dsort) { cum += n.w as number; if (cum >= 0.10) { p10 = n.margin; break; } }
269
+ const dsD = [...nodes].sort((a, b) => a.marginD - b.marginD);
270
+ cum = 0; let p10D = dsD[0].marginD;
271
+ for (const n of dsD) { cum += n.w as number; if (cum >= 0.10) { p10D = n.marginD; break; } }
272
+ const hpd_eff = p.hpd * p.shifts * p.avail;
273
+ return {
274
+ d, cx, base, nodes, sig, ca2,
275
+ Eunit: E('unit'), Emargin: E('margin'), ECT: E('CTd'), pLate, p10,
276
+ Esub: E('sub'), Elost: E('lost'), EmarginD: E('marginD'), Eservice: E('service'),
277
+ p10D, jensen: E('CTd') - base.CTd,
278
+ raw: p.W * (1 - p.a * p.lam) / p.crew / hpd_eff,
279
+ };
280
+ }
281
+
282
+ export type PlanCurvePoint = [D: number, Em: number, Sv: number, nameplate: number];
283
+ export interface OptimalPlan { D: number; Em: number; Sv: number; }
284
+
285
+ /** The newsvendor-flavoured core result: with demand centred on Dtrue and dispersion set
286
+ * by contract coverage, what nameplate maximises expected margin dollars? */
287
+ export function optimalPlan(
288
+ Dtrue: number, theta: number, p: ModelParams = DEFAULT_PARAMS, lo = 15, hi = 320
289
+ ): { best: OptimalPlan; curve: PlanCurvePoint[] } {
290
+ const q: ModelParams = { ...p, theta };
291
+ const SL = p.SL ?? 0.95;
292
+ const sig = SIG_SPEC * (1 - theta) + SIG_CON * theta;
293
+ const ca2 = CA2_SPEC * (1 - theta) + CA2_CON * theta;
294
+ const s_ln = Math.sqrt(Math.log(1 + sig * sig));
295
+ const sw = GH.reduce((s, [, w]) => s + w, 0);
296
+ let best: OptimalPlan | null = null;
297
+ let bestOK = false;
298
+ const curve: PlanCurvePoint[] = [];
299
+ let D = lo;
300
+ while (D <= hi) {
301
+ const d = design(D, q);
302
+ const cx = capex(D, d, q);
303
+ const ns = GH.map(([z, w]) => {
304
+ const n = pnlAt(Dtrue * Math.exp(s_ln * z - 0.5 * s_ln * s_ln), D, d, cx, q, ca2);
305
+ return [w / sw, n] as [number, PnlResult];
306
+ });
307
+ const Em = ns.reduce((s, [w, n]) => s + w * n.marginD, 0);
308
+ const Sv = ns.reduce((s, [w, n]) => s + w * n.service, 0);
309
+ curve.push([D, Em, Sv, D / d.u]);
310
+ // policy: the demand-matching levers are SURGE capacity held against variance, not a
311
+ // substitute for nameplate. Regular time must cover the median of realised demand.
312
+ const med = Dtrue * Math.exp(-0.5 * s_ln * s_ln);
313
+ const regOK = D / d.u >= med;
314
+ const ok = Sv >= SL && regOK;
315
+ if (best === null || (ok ? 1 : 0) > (bestOK ? 1 : 0) ||
316
+ ((ok ? 1 : 0) === (bestOK ? 1 : 0) && Em > best.Em)) {
317
+ best = { D, Em, Sv };
318
+ bestOK = ok;
319
+ }
320
+ D += D < 60 ? 1 : 2;
321
+ }
322
+ return { best: best as OptimalPlan, curve };
323
+ }