dsforge-harness 0.1.1 → 0.1.2

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/bin/dsforge.js CHANGED
@@ -52,6 +52,9 @@ Usage:
52
52
  npx dsforge-harness init Install the dsforge skill + CLAUDE.md into this project
53
53
  npx dsforge-harness verify <proj> <scr> Run the full verifier (node) for a project/screen
54
54
  npx dsforge-harness check3 <proj> <scr> Run only the code-vs-DS check (node)
55
+ npx dsforge-harness check-recall <proj> <cur> <prior>
56
+ From-scratch recall-leak check: compare a screen's non-spec
57
+ content against a prior screen (node)
55
58
  npx dsforge-harness help This message
56
59
 
57
60
  check1 / check2 / extract-tokens run inside Claude Code via the Figma MCP (see the skill).
@@ -62,6 +65,7 @@ switch (cmd) {
62
65
  case 'init': init(); break;
63
66
  case 'verify': runScript('verify.js', rest); break;
64
67
  case 'check3': runScript('check3.js', rest); break;
68
+ case 'check-recall': runScript('check-recall.js', rest); break;
65
69
  case undefined:
66
70
  case 'help':
67
71
  case '-h':
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "dsforge-harness",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Verified design→design-system→code harness: a functional spec becomes Figma mockups, a token-bound design system, and token-faithful code, with automated check gates and two human review gates. Ships as a Claude Code plugin/skill.",
5
5
  "bin": { "dsforge": "bin/dsforge.js" },
6
- "scripts": { "test": "node plugins/dsforge/skills/dsforge/validators/test/check-layout.test.js" },
6
+ "scripts": { "test": "node plugins/dsforge/skills/dsforge/validators/test/run-all.js" },
7
7
  "files": ["bin/", "plugins/", "templates/", "README.md"],
8
8
  "keywords": ["design-to-code", "design-system", "figma", "design-tokens", "verification", "claude-code", "claude", "skill"],
9
9
  "license": "MIT",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsforge",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Verified design→design-system→code harness: a functional spec becomes Figma mockups, a token-bound design system, and token-faithful code, with automated check gates (DS audit, mockup-vs-spec, code-vs-DS) and two human review gates.",
5
5
  "author": { "name": "jsiksn" },
6
6
  "homepage": "https://github.com/jsiksn/dsforge",
@@ -76,6 +76,14 @@ appear *verbatim*) before building any mockup.
76
76
  - **[HUMAN GATE 2] final screen review.**
77
77
 
78
78
  ### Branch B — no DS yet (order reversed: mockups → DS → code)
79
+ > **From-scratch isolation (REQUIRED).** Branch B derives each screen from the **spec alone**. Do **not**
80
+ > look at, copy, or "carry over" any previous screen or its data — not an earlier Branch-A screen, not a
81
+ > sibling Branch-B screen. If a prior screen is in your context, a from-scratch build will *recall* it:
82
+ > colours/fonts change but the **layout/IA and the non-spec incidental content** (placeholder ids, dates,
83
+ > filter labels, footer text) come back identical, which is a leak, not a design. So: generate **fresh
84
+ > placeholders** for anything the spec doesn't define (and mark "(제안)/(proposed)"); the only inputs are the
85
+ > **spec + empty files**. Cross-check with `check-recall.js` (below). **Re-test in a session that has never
86
+ > seen the other screen** — a recall can't be ruled out in a context that already contains it.
79
87
  1. **Skip the audit** — there is no DS to audit. Go straight from the spec to visual proposals.
80
88
  2. **Per screen, build 2–3 mockup options** (the count from step 4) with `use_figma` — each a **full
81
89
  viewport + app shell**, **auto-layout, aligned, filling the viewport, realistic density, no floating
@@ -149,14 +157,28 @@ separate page** (`Screens`). Never pile the DS and the screens onto one page.
149
157
  exact invocation.
150
158
 
151
159
  ## How the validators run
152
- - `check3.js`, `verify.js` → **Node** (run via `npx dsforge check3 <project> <screen>` / `npx dsforge verify <project>`, or `node validators/check3.js <project> <screen>` from the app root).
160
+ - `check3.js`, `verify.js`, `check-recall.js` → **Node** (run via `npx dsforge check3 <project> <screen>` /
161
+ `npx dsforge verify <project>` / `npx dsforge check-recall <project> <cur> <prior>`, or `node validators/<x>.js …`
162
+ from the app root). `check3` also enforces **size-token dimension fidelity** when the descriptor declares
163
+ `sizeBindings` (each bound element's dimension must come from its size token + `box-sizing: border-box`).
164
+ `check-recall` is the **from-scratch recall guard** — for Branch B screens, compare each new screen's
165
+ non-spec content against any prior screen; a high overlap means the build recalled it instead of deriving
166
+ it from the spec.
153
167
  - `check1.js`, `check2.js`, `check-layout.js`, `extract-tokens.js` → **Figma MCP `use_figma`** (paste the
154
168
  script body, pass the descriptor as config). See each file's top comment. `check-layout.js` is the visual
155
- floor — run it (hardFails 0) before GATE 1.
169
+ floor — run it (hardFails 0) before GATE 1. `check2.js` also emits a `textFingerprint` that `check-recall`
170
+ consumes for the mockup-stage comparison.
156
171
 
157
172
  ## Disciplines (non-negotiable)
158
173
  - **Tokens only** — no hand-entered hex/px except the structural exceptions declared in the descriptor
159
174
  (`structuralPxAllow`: 1px hairlines, focus-ring width, etc.).
175
+ - **Size tokens bind dimensions** — when a DS size token exists for an element's dimension (row / input /
176
+ button / bar height, etc.), set that dimension *from the token* (`height: var(--…-size-…)`) with
177
+ `box-sizing: border-box`. Never let the rendered size fall out of padding+border arithmetic — that drifts
178
+ ~1px per element and accumulates. `check3` enforces this via the descriptor's `sizeBindings`.
179
+ - **From-scratch isolation** — in Branch B, derive each screen from the **spec + empty files only**; never
180
+ reference or copy a prior screen or its data, generate fresh placeholders, and guard with `check-recall.js`
181
+ (re-test in a session that never saw the other screen).
160
182
  - **Zero fabrication** — anything not in the spec is marked "(제안)/(proposed)" with placeholder values.
161
183
  - **Measure, don't estimate** — verify by reading nodes/code, never by trusting a build report.
162
184
  Traverse **inside** component instances.
@@ -177,8 +199,9 @@ who independently re-derives the numbers. Don't collapse the two.
177
199
  intent are what the human gates are for.
178
200
 
179
201
  ## Bundled resources
180
- - `validators/` — the verifier + token extractor (`extract-tokens, check1, check2, check-layout, check3, verify`),
181
- plus `projects/_TEMPLATE.json` (fill per project) and `projects/ezp.json` (filled example).
202
+ - `validators/` — the verifier + token extractor (`extract-tokens, check1, check2, check-layout, check3,
203
+ check-recall, verify`), plus `projects/_TEMPLATE.json` (fill per project), `projects/ezp.json` (filled
204
+ example), and `test/` (node regression tests, run via `npm test`).
182
205
  - `references/` — methodology & runbook (`00`–`03`) and `examples/` (real runs).
183
206
  - `assets/code-scaffold-reference-ezp/` — reference React implementation (token-bound shell/forms/table
184
207
  + two screens). A *pattern* to regenerate for your DS, not a drop-in. The `ezp` name is the test DS.
@@ -67,7 +67,7 @@
67
67
  .ezp-table-wrap { border: 1px solid var(--ezp-light-200); border-radius: var(--ezp-radius-md); overflow: hidden; }
68
68
  .ezp-table { width: 100%; border-collapse: separate; border-spacing: 0; }
69
69
  .ezp-th { background: var(--ezp-light-50); color: var(--ezp-light-600); text-align: left; padding: var(--ezp-space-sm) var(--ezp-space-md); border-bottom: 1px solid var(--ezp-light-200); white-space: nowrap; }
70
- .ezp-td { padding: var(--ezp-space-sm) var(--ezp-space-md); border-bottom: 1px solid var(--ezp-light-200); color: var(--ezp-light-1100); vertical-align: middle; background: var(--ezp-white); }
70
+ .ezp-td { height: var(--ezp-size-table-row-height); box-sizing: border-box; padding: 0 var(--ezp-space-md); border-bottom: 1px solid var(--ezp-light-200); color: var(--ezp-light-1100); vertical-align: middle; background: var(--ezp-white); } /* row height bound to size/table-row-height (30px), not padding+border arithmetic; border-box so the 1px border doesn't drift the row ~1px/row (P4) */
71
71
  .ezp-tr:last-child .ezp-td { border-bottom: none; }
72
72
  .ezp-cell-name { color: var(--ezp-logo-blue); cursor: pointer; } /* 상세 진입 affordance (link) */
73
73
  .ezp-cell-action { text-align: right; }
@@ -0,0 +1,53 @@
1
+ {
2
+ "project": "smoke",
3
+ "generated": "verify.js (config-driven; numbers only)",
4
+ "check1_DS": {
5
+ "pass": true,
6
+ "tokens": {
7
+ "color": 2,
8
+ "float": 2,
9
+ "text": 1,
10
+ "effect": 1
11
+ },
12
+ "raw": 0,
13
+ "instanceInteriorNodes": 12,
14
+ "states": "3/3"
15
+ },
16
+ "screens": {
17
+ "main": {
18
+ "check2": {
19
+ "pass": true,
20
+ "coverage": 8,
21
+ "fabricationExtra": 0,
22
+ "authoredRaw": 0,
23
+ "dsInternalRaw": 5,
24
+ "viewport": true,
25
+ "shell": true
26
+ },
27
+ "check3": {
28
+ "pass": true,
29
+ "tokens": "5/5",
30
+ "hex": 0,
31
+ "pxViol": 0,
32
+ "content": true,
33
+ "sizeFidelity": "n/a"
34
+ },
35
+ "layout": "not run"
36
+ }
37
+ },
38
+ "selfVerification": {
39
+ "baseline": {
40
+ "tokensTotal": 5,
41
+ "dsRaw": 0
42
+ },
43
+ "checks": {
44
+ "dsRawMatchesIndependent": true,
45
+ "ds_states_elevation": true,
46
+ "tokens72_main": true,
47
+ "authoredHardcode0_main": true,
48
+ "anchorsVerbatim_main": true,
49
+ "fabrication0_main": true
50
+ },
51
+ "reproduced": true
52
+ }
53
+ }
@@ -0,0 +1,76 @@
1
+ /*
2
+ * Check-recall — from-scratch (Branch B) recall-leak audit (generic, config-driven). Node.
3
+ * node validators/check-recall.js <project> <currentScreen> <priorScreen> (cwd = project root)
4
+ *
5
+ * Why: in from-scratch mode a screen must be derived from the SPEC alone. If the executor leaves a prior,
6
+ * in-context screen (e.g. a Branch-A screen) in view, the new one can *recall* it — color/font may change but
7
+ * the structure and the **non-spec incidental content** (placeholder ids, dates, filter labels, footer text)
8
+ * come back byte-for-byte. Those values are not derivable from the spec, so a high non-spec overlap with a
9
+ * prior screen is the fingerprint of recall. check2's fabrication pass can't see this (it only checks that
10
+ * spec anchors are present and no enumerable menu is invented); this compares two screens to each other.
11
+ *
12
+ * Source of each screen's text, in priority order:
13
+ * 1. validators/out/check2-<screen>.json `textFingerprint` (mockup-stage texts, emitted by check2.js), else
14
+ * 2. string/JSX-text literals extracted from screen.code.files (code-stage).
15
+ * Spec set = that screen's own anchors (designAnchors groups + code.anchors + code.orderedArray.items).
16
+ * non-spec = content text minus spec. nonSpecOverlap = |cur∩prior| / |cur|. FAIL if > threshold
17
+ * (descriptor `recall.maxNonSpecOverlap`, default 0.5). READ-ONLY; prints JSON, exit 0.
18
+ */
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const ROOT = process.cwd();
22
+ const [project, curKey, priorKey] = process.argv.slice(2);
23
+ if (!project || !curKey || !priorKey) { console.error('usage: node validators/check-recall.js <project> <currentScreen> <priorScreen>'); process.exit(1); }
24
+ const cfg = JSON.parse(fs.readFileSync(path.join(ROOT, 'validators/projects', project + '.json'), 'utf8'));
25
+ const readOpt = (p) => { try { return fs.readFileSync(p, 'utf8'); } catch (e) { return null; } };
26
+ const norm = (s) => String(s).replace(/\s+/g, ' ').trim();
27
+ const meaningful = (s) => s.length >= 2 && /[\p{L}\p{N}]/u.test(s); // has a letter or digit, not pure punctuation
28
+
29
+ function specAnchors(screen) {
30
+ const out = [];
31
+ if (screen.designAnchors) for (const list of Object.values(screen.designAnchors)) if (Array.isArray(list)) out.push(...list);
32
+ if (screen.code && Array.isArray(screen.code.anchors)) out.push(...screen.code.anchors);
33
+ if (screen.code && screen.code.orderedArray && Array.isArray(screen.code.orderedArray.items)) out.push(...screen.code.orderedArray.items);
34
+ return new Set(out.map(norm).filter(meaningful));
35
+ }
36
+
37
+ function contentText(key, screen) {
38
+ // 1) mockup-stage fingerprint staged by check2
39
+ const c2 = readOpt(path.join(ROOT, 'validators/out', 'check2-' + key + '.json'));
40
+ if (c2) { try { const j = JSON.parse(c2); if (Array.isArray(j.textFingerprint)) return { source: 'check2.textFingerprint', items: j.textFingerprint.map(norm).filter(meaningful) }; } catch (e) {} }
41
+ // 2) code-stage: string + simple JSX-text literals
42
+ const items = [];
43
+ const codeDir = path.dirname(path.join(ROOT, cfg.codeTokensCss));
44
+ for (const rel of (screen.code && screen.code.files) || []) {
45
+ const src = readOpt(path.join(codeDir, rel)); if (!src) continue;
46
+ for (const m of src.matchAll(/'([^'\n]{2,})'|"([^"\n]{2,})"|`([^`\n]{2,})`/g)) items.push(m[1] || m[2] || m[3]);
47
+ for (const m of src.matchAll(/>\s*([^<>{}\n]{2,}?)\s*</g)) items.push(m[1]); // JSX text nodes
48
+ }
49
+ return { source: 'code.literals', items: items.map(norm).filter(meaningful) };
50
+ }
51
+
52
+ function nonSpec(key) {
53
+ const screen = cfg.screens[key];
54
+ if (!screen) { console.error('unknown screen: ' + key); process.exit(1); }
55
+ const spec = specAnchors(screen);
56
+ const isSpec = (s) => spec.has(s) || [...spec].some((a) => a.length >= 3 && (s.includes(a) || a.includes(s)));
57
+ const ct = contentText(key, screen);
58
+ const set = new Set(ct.items.filter((s) => !isSpec(s)));
59
+ return { source: ct.source, total: ct.items.length, nonSpec: set };
60
+ }
61
+
62
+ const cur = nonSpec(curKey);
63
+ const prior = nonSpec(priorKey);
64
+ const shared = [...cur.nonSpec].filter((s) => prior.nonSpec.has(s));
65
+ const denom = cur.nonSpec.size || 1;
66
+ const nonSpecOverlap = +(shared.length / denom).toFixed(3);
67
+ const threshold = (cfg.recall && typeof cfg.recall.maxNonSpecOverlap === 'number') ? cfg.recall.maxNonSpecOverlap : 0.5;
68
+ const pass = nonSpecOverlap <= threshold;
69
+
70
+ console.log(JSON.stringify({
71
+ project, current: curKey, prior: priorKey,
72
+ source: { current: cur.source, prior: prior.source },
73
+ curNonSpecCount: cur.nonSpec.size, priorNonSpecCount: prior.nonSpec.size,
74
+ sharedNonSpecCount: shared.length, sharedNonSpec: shared.slice(0, 40),
75
+ nonSpecOverlap, threshold, pass,
76
+ }, null, 2));
@@ -45,4 +45,6 @@ return {
45
45
  binding: { bound, authoredRaw, dsInternalRaw: internalRaw, ratioPct: +((bound / (bound + authoredRaw + internalRaw)) * 100).toFixed(1), authoredOffenders },
46
46
  viewport: { w: Math.round(screen.width), h: Math.round(screen.height), ok: Math.round(screen.width) === CFG.viewport.w && Math.round(screen.height) === CFG.viewport.h },
47
47
  shell,
48
+ // all mockup TEXT strings (deduped) — consumed by check-recall.js to detect from-scratch recall leaks across screens
49
+ textFingerprint: [...new Set(all.filter((n) => n.type === 'TEXT' && typeof n.characters === 'string').map((n) => n.characters.trim()).filter((s) => s.length >= 2))],
48
50
  };
@@ -56,9 +56,41 @@ if (screen.code.anchors) {
56
56
  content.anchors = { total: screen.code.anchors.length, present: screen.code.anchors.length - missing.length, missing, verbatim: missing.length === 0 };
57
57
  }
58
58
 
59
+ // ---- size-token dimension fidelity (P4) — opt-in via descriptor `sizeBindings` ----
60
+ // Each binding { selector, dim?, token } requires the element's dimension to be BOUND to the size token's var
61
+ // (not a literal) AND box-sizing:border-box (rule-level or via a global `*` reset), so border/padding cannot
62
+ // inflate the rendered dimension past the token value. Catches the "row height = padding+border ≈ token+1px"
63
+ // drift the hardcode scan misses (padding is a spacing token, the 1px border is in structuralPxAllow).
64
+ const sizeBindings = [...(cfg.sizeBindings || []), ...((screen.code && screen.code.sizeBindings) || [])];
65
+ let sizeFidelity = { applicable: false };
66
+ if (sizeBindings.length) {
67
+ const cssFiles = [...new Set([path.basename(cfg.codeTokensCss), ...(cfg.codeCssFiles || []), ...((screen.code.files) || []).filter((f) => f.endsWith('.css'))])];
68
+ const cssAll = cssFiles.map((f) => { try { return read(path.join(codeDir, f)); } catch (e) { return ''; } }).join('\n');
69
+ const rules = [...cssAll.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map((m) => ({ sels: m[1].split(',').map((s) => s.trim()), body: m[2] }));
70
+ const findRule = (sel) => rules.find((r) => r.sels.includes(sel));
71
+ const globalBorderBox = rules.some((r) => r.sels.some((s) => s.includes('*')) && /box-sizing\s*:\s*border-box/.test(r.body));
72
+ const violations = [];
73
+ for (const bnd of sizeBindings) {
74
+ const dim = bnd.dim || 'height';
75
+ const expectVar = toVar(bnd.token);
76
+ const tokenVal = ds.float[bnd.token];
77
+ const rule = findRule(bnd.selector);
78
+ if (!rule) { violations.push({ selector: bnd.selector, dim, token: bnd.token, issue: 'selectorNotFound' }); continue; }
79
+ const decl = (rule.body.match(new RegExp('(?:^|[;{\\s])' + dim + '\\s*:\\s*([^;]+)')) || [])[1];
80
+ const val = decl ? decl.trim() : '';
81
+ const boundToToken = val.indexOf('var(' + expectVar + ')') !== -1;
82
+ const borderBox = globalBorderBox || /box-sizing\s*:\s*border-box/.test(rule.body);
83
+ if (!val) violations.push({ selector: bnd.selector, dim, token: bnd.token, issue: 'dimMissing', note: 'no ' + dim + ' set; height comes from padding+border (drift)' });
84
+ else if (!boundToToken) violations.push({ selector: bnd.selector, dim, token: bnd.token, issue: /\d+(?:\.\d+)?px/.test(val) ? 'literalNotToken' : 'notTokenBound', got: val, expected: 'var(' + expectVar + ')' + (tokenVal != null ? ' (' + tokenVal + 'px)' : '') });
85
+ else if (!borderBox) violations.push({ selector: bnd.selector, dim, token: bnd.token, issue: 'noBorderBox', note: 'border/padding can inflate ' + dim + ' past the token; add box-sizing:border-box' });
86
+ }
87
+ sizeFidelity = { applicable: true, total: sizeBindings.length, ok: sizeBindings.length - violations.length, violations };
88
+ }
89
+
59
90
  console.log(JSON.stringify({
60
91
  project, screen: screenKey,
61
92
  tokenCompare: { match: tok.match, total: tok.total, pct: +((tok.match / tok.total) * 100).toFixed(1), mismatch: tok.mismatch, missing: tok.missing },
62
93
  hardcode: { hexCount: hexHits.length, hexLiterals: hexHits, pxViolationCount: pxViolations.length, pxViolations, declaredColorLiterals: colorLiterals },
63
94
  content,
95
+ sizeFidelity,
64
96
  }, null, 2));
@@ -31,6 +31,14 @@
31
31
  "2px": "focus ring width/offset",
32
32
  "<NNpx>": "<reason, e.g. control glyph / min-height / viewport>"
33
33
  },
34
+ "codeCssFiles": ["<component-css-file(s), e.g. app.css>"],
35
+ "_codeCssFiles_note": "OPTIONAL. CSS files (besides codeTokensCss) that hold the component rules check3's sizeBindings look up. Resolved next to codeTokensCss.",
36
+ "sizeBindings": [
37
+ { "selector": "<.css-selector>", "dim": "height", "token": "size/<token>" }
38
+ ],
39
+ "_sizeBindings_note": "OPTIONAL (P4). Each bound element's dim must be height: var(--<ds>-size-<token>) + box-sizing:border-box, else check3 flags drift. Omit to skip the check.",
40
+ "recall": { "maxNonSpecOverlap": 0.5 },
41
+ "_recall_note": "OPTIONAL (P5). Threshold for check-recall.js: fail when a from-scratch screen's non-spec content overlap with a prior screen exceeds this.",
34
42
  "selfVerify": { "tokensTotal": "<total token count expected>", "dsRaw": 0 },
35
43
  "screens": {
36
44
  "<screenKey>": {
@@ -13,6 +13,13 @@
13
13
  "weightMap": { "Bold": 700, "SemiBold": 600, "Medium": 500, "Regular": 400 }
14
14
  },
15
15
  "shell": { "viewport": { "w": 1920, "h": 1080 }, "componentNames": ["side-nav", "gnb"] },
16
+ "codeCssFiles": ["ezp.css"],
17
+ "sizeBindings": [
18
+ { "selector": ".ezp-td", "dim": "height", "token": "size/table-row-height" },
19
+ { "selector": ".ezp-input", "dim": "height", "token": "size/input-height" },
20
+ { "selector": ".ezp-btn-primary", "dim": "height", "token": "size/button-height" }
21
+ ],
22
+ "recall": { "maxNonSpecOverlap": 0.5 },
16
23
  "check1": {
17
24
  "interactiveDetect": "btn|button|form-control|form-select|form-check|form-switch|input|tab|menu|nav|toggle|switch|link|chip|radio|checkbox",
18
25
  "requiredStatesForPass": ["focus", "disabled"],
@@ -0,0 +1,59 @@
1
+ /*
2
+ * Regression test for check-recall.js (P5 from-scratch recall leak). Node, no Figma.
3
+ * node validators/test/check-recall.test.js
4
+ * Builds a temp project with a prior screen + three candidates, runs the real check-recall.js:
5
+ * leak same non-spec placeholders as prior (ids/dates/tags) -> nonSpecOverlap high -> FAIL
6
+ * fresh different placeholders -> nonSpecOverlap 0 -> PASS
7
+ * speconly only the shared SPEC anchors, no placeholders -> non-spec empty -> PASS
8
+ * The speconly case proves the check flags recalled *non-spec* content, not spec text that is meant to repeat.
9
+ */
10
+ 'use strict';
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const os = require('os');
14
+ const cp = require('child_process');
15
+
16
+ const RECALL = path.join(__dirname, '..', 'check-recall.js');
17
+ const root = path.join(os.tmpdir(), 'dsforge-recall-test-' + process.pid);
18
+ const ANCHORS = ['Create dataset', 'Dataset List'];
19
+
20
+ function write(rel, content) { const p = path.join(root, rel); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, content); }
21
+ const lits = (arr) => 'export const D = [' + arr.map((s) => `'${s}'`).join(', ') + '];\n';
22
+
23
+ fs.rmSync(root, { recursive: true, force: true });
24
+ write('app/tokens.css', ':root {}\n');
25
+ write('app/prior.tsx', lits(['model-0001', 'model-0002', 'vision', '2026-06-10', ...ANCHORS]));
26
+ write('app/leak.tsx', lits(['model-0001', 'model-0002', 'vision', '2026-06-10', ...ANCHORS]));
27
+ write('app/fresh.tsx', lits(['alpha-77', 'beta-88', 'audio', '2025-01-02', ...ANCHORS]));
28
+ write('app/spec.tsx', lits([...ANCHORS]));
29
+ const screen = (file) => ({ label: file, code: { files: [file], anchors: ANCHORS } });
30
+ write('validators/projects/t.json', JSON.stringify({
31
+ project: 't', tokenRef: 'validators/out/t-tokens.json', codeTokensCss: 'app/tokens.css',
32
+ recall: { maxNonSpecOverlap: 0.5 },
33
+ screens: { prior: screen('prior.tsx'), leak: screen('leak.tsx'), fresh: screen('fresh.tsx'), speconly: screen('spec.tsx') },
34
+ }));
35
+
36
+ let failed = 0;
37
+ function ok(cond, msg) { console.log((cond ? ' PASS ' : ' FAIL ') + msg); if (!cond) failed++; }
38
+ const run = (cur, prior) => JSON.parse(cp.execSync(`node "${RECALL}" t ${cur} ${prior}`, { cwd: root }).toString());
39
+
40
+ const leak = run('leak', 'prior');
41
+ console.log('leak:', JSON.stringify({ overlap: leak.nonSpecOverlap, shared: leak.sharedNonSpec, pass: leak.pass }));
42
+ ok(leak.pass === false, 'leak: recalled non-spec content -> FAIL');
43
+ ok(leak.nonSpecOverlap > 0.5, 'leak: nonSpecOverlap above threshold');
44
+ ok(leak.sharedNonSpec.includes('model-0001') && leak.sharedNonSpec.includes('2026-06-10'), 'leak: shares ids/dates with prior');
45
+
46
+ const fresh = run('fresh', 'prior');
47
+ console.log('fresh:', JSON.stringify({ overlap: fresh.nonSpecOverlap, pass: fresh.pass }));
48
+ ok(fresh.pass === true, 'fresh: distinct placeholders -> PASS');
49
+ ok(fresh.nonSpecOverlap === 0, 'fresh: zero non-spec overlap');
50
+
51
+ const spec = run('speconly', 'prior');
52
+ console.log('speconly:', JSON.stringify({ curNonSpec: spec.curNonSpecCount, overlap: spec.nonSpecOverlap, pass: spec.pass }));
53
+ ok(spec.pass === true, 'speconly: identical SPEC text is not a leak -> PASS');
54
+ ok(spec.curNonSpecCount === 0, 'speconly: no non-spec content to compare');
55
+
56
+ fs.rmSync(root, { recursive: true, force: true });
57
+ console.log('');
58
+ if (failed) { console.log('check-recall: ' + failed + ' assertion(s) FAILED'); process.exit(1); }
59
+ console.log('check-recall: all assertions passed');
@@ -0,0 +1,63 @@
1
+ /*
2
+ * Regression test for check3.js size-token dimension fidelity (P4). Node, no Figma.
3
+ * node validators/test/check3-size.test.js
4
+ * Builds a temp project tree, runs the real check3.js against it, asserts the sizeFidelity verdict:
5
+ * .good height bound to the size-token var + box-sizing:border-box -> OK
6
+ * .drift no height (row height = padding+border ≈ token+1px, the P4 bug) -> dimMissing
7
+ * .literal height: 30px literal (matches value but not token-bound) -> literalNotToken
8
+ * .nobox bound to token var but no box-sizing -> noBorderBox
9
+ */
10
+ 'use strict';
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const os = require('os');
14
+ const cp = require('child_process');
15
+
16
+ const CHECK3 = path.join(__dirname, '..', 'check3.js');
17
+ const root = path.join(os.tmpdir(), 'dsforge-size-test-' + process.pid);
18
+
19
+ function write(rel, content) { const p = path.join(root, rel); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, content); }
20
+
21
+ fs.rmSync(root, { recursive: true, force: true });
22
+ write('validators/out/t-tokens.json', JSON.stringify({ color: {}, float: { 'size/row': 30 }, text: {} }));
23
+ write('app/tokens.css', ':root { --size-row: 30px; }\n');
24
+ write('app/screen.tsx', 'export const X = 1;\n');
25
+ write('app/comp.css', [
26
+ '.good { height: var(--size-row); box-sizing: border-box; padding: 0 12px; border-bottom: 1px solid var(--c-line); }',
27
+ '.drift { padding: 9px 12px; border-bottom: 1px solid var(--c-line); }',
28
+ '.literal { height: 30px; box-sizing: border-box; }',
29
+ '.nobox { height: var(--size-row); padding: 9px 0; border: 1px solid var(--c-line); }',
30
+ ].join('\n') + '\n');
31
+ write('validators/projects/t.json', JSON.stringify({
32
+ project: 't', tokenRef: 'validators/out/t-tokens.json', codeTokensCss: 'app/tokens.css', codeCssFiles: ['comp.css'],
33
+ tokenCssNaming: { colorPrefix: '--c-', spaceFrom: 'space/', spaceTo: '--space-', sizeFrom: 'size/', sizeTo: '--size-', radiusFrom: 'radius/', radiusTo: '--radius-', textClass: {}, weightMap: {} },
34
+ sizeBindings: [
35
+ { selector: '.good', dim: 'height', token: 'size/row' },
36
+ { selector: '.drift', dim: 'height', token: 'size/row' },
37
+ { selector: '.literal', dim: 'height', token: 'size/row' },
38
+ { selector: '.nobox', dim: 'height', token: 'size/row' },
39
+ ],
40
+ structuralPxAllow: {},
41
+ screens: { main: { label: 'm', code: { files: ['screen.tsx'] } } },
42
+ }));
43
+
44
+ let failed = 0;
45
+ function ok(cond, msg) { console.log((cond ? ' PASS ' : ' FAIL ') + msg); if (!cond) failed++; }
46
+
47
+ const out = JSON.parse(cp.execSync(`node "${CHECK3}" t main`, { cwd: root }).toString());
48
+ const sf = out.sizeFidelity;
49
+ console.log('sizeFidelity:', JSON.stringify(sf));
50
+ const bySel = {}; for (const v of sf.violations) bySel[v.selector] = v.issue;
51
+
52
+ ok(sf.applicable === true, 'applicable when sizeBindings declared');
53
+ ok(sf.total === 4, 'total == 4 bindings');
54
+ ok(!bySel['.good'], '.good (token-bound + border-box) -> no violation');
55
+ ok(bySel['.drift'] === 'dimMissing', '.drift (no height; padding+border) -> dimMissing');
56
+ ok(bySel['.literal'] === 'literalNotToken', '.literal (height: 30px literal) -> literalNotToken');
57
+ ok(bySel['.nobox'] === 'noBorderBox', '.nobox (token-bound, no box-sizing) -> noBorderBox');
58
+ ok(sf.violations.length === 3, 'exactly 3 violations (only .good passes)');
59
+
60
+ fs.rmSync(root, { recursive: true, force: true });
61
+ console.log('');
62
+ if (failed) { console.log('check3 size-fidelity: ' + failed + ' assertion(s) FAILED'); process.exit(1); }
63
+ console.log('check3 size-fidelity: all assertions passed');
@@ -0,0 +1,17 @@
1
+ /*
2
+ * Run all dsforge validator regression tests. Node.
3
+ * node validators/test/run-all.js (or `npm test` from the package root)
4
+ */
5
+ 'use strict';
6
+ const path = require('path');
7
+ const cp = require('child_process');
8
+
9
+ const tests = ['check-layout.test.js', 'check3-size.test.js', 'check-recall.test.js'];
10
+ let failed = 0;
11
+ for (const t of tests) {
12
+ console.log('\n=== ' + t + ' ===');
13
+ const r = cp.spawnSync('node', [path.join(__dirname, t)], { stdio: 'inherit' });
14
+ if (r.status !== 0) failed++;
15
+ }
16
+ console.log('\n' + (failed ? failed + ' test file(s) FAILED' : 'all ' + tests.length + ' test files passed'));
17
+ process.exit(failed ? 1 : 0);
@@ -34,7 +34,9 @@ for (const sk of Object.keys(cfg.screens)) {
34
34
  const shellOk = Object.values(c2.shell).every(Boolean);
35
35
  const c2pass = c2.coverage.pct === 100 && c2.fabrication.extra.length === 0 && c2.binding.authoredRaw === 0 && c2.viewport.ok && shellOk;
36
36
  const contentOk = c3.content.array ? c3.content.array.verbatimAndOrdered : (c3.content.anchors ? c3.content.anchors.verbatim : true);
37
- const c3pass = c3.tokenCompare.match === c3.tokenCompare.total && c3.hardcode.hexCount === 0 && c3.hardcode.pxViolationCount === 0 && contentOk;
37
+ // size-token dimension fidelity (P4) — only enforced when the descriptor declares sizeBindings (backward compatible)
38
+ const sizeOk = c3.sizeFidelity && c3.sizeFidelity.applicable ? c3.sizeFidelity.violations.length === 0 : true;
39
+ const c3pass = c3.tokenCompare.match === c3.tokenCompare.total && c3.hardcode.hexCount === 0 && c3.hardcode.pxViolationCount === 0 && contentOk && sizeOk;
38
40
  // Layout floor (objective breakage) — staged in out/check-layout-<screen>.json by the use_figma run.
39
41
  // Optional: absent for projects that haven't run it, but hardFails 0 is the precondition to the visual gate.
40
42
  const cl = loadOpt('check-layout-' + sk + '.json');
@@ -54,6 +56,7 @@ for (const [sk, r] of Object.entries(screens)) {
54
56
  repro['anchorsVerbatim_' + sk] = r.contentOk;
55
57
  repro['fabrication0_' + sk] = r.c2.fabrication.extra.length === 0 && (!r.c3.content.array || r.c3.content.array.extra.length === 0);
56
58
  if (r.cl) repro['layoutClean_' + sk] = r.layoutPass === true; // only enforced when the layout floor was run
59
+ if (r.c3.sizeFidelity && r.c3.sizeFidelity.applicable) repro['sizeFidelity0_' + sk] = r.c3.sizeFidelity.violations.length === 0; // only when sizeBindings declared
57
60
  }
58
61
  const reproduced = Object.values(repro).every(Boolean);
59
62
 
@@ -62,7 +65,7 @@ const report = {
62
65
  check1_DS: { pass: c1pass, tokens: c1.tokens, raw: c1.binding.raw, instanceInteriorNodes: c1.binding.instanceInteriorNodes, states: c1.variants.withRequiredStates + '/' + c1.variants.interactiveSets },
63
66
  screens: Object.fromEntries(Object.entries(screens).map(([sk, r]) => [sk, {
64
67
  check2: { pass: r.c2pass, coverage: r.c2.coverage.total, fabricationExtra: r.c2.fabrication.extra.length, authoredRaw: r.c2.binding.authoredRaw, dsInternalRaw: r.c2.binding.dsInternalRaw, viewport: r.c2.viewport.ok, shell: r.shellOk },
65
- check3: { pass: r.c3pass, tokens: r.c3.tokenCompare.match + '/' + r.c3.tokenCompare.total, hex: r.c3.hardcode.hexCount, pxViol: r.c3.hardcode.pxViolationCount, content: r.contentOk },
68
+ check3: { pass: r.c3pass, tokens: r.c3.tokenCompare.match + '/' + r.c3.tokenCompare.total, hex: r.c3.hardcode.hexCount, pxViol: r.c3.hardcode.pxViolationCount, content: r.contentOk, sizeFidelity: r.c3.sizeFidelity && r.c3.sizeFidelity.applicable ? r.c3.sizeFidelity.ok + '/' + r.c3.sizeFidelity.total : 'n/a' },
66
69
  layout: r.cl ? { pass: r.layoutPass, hardFails: r.cl.hardFails.length, advisories: r.cl.advisories.length } : 'not run',
67
70
  }])),
68
71
  selfVerification: { baseline: sv, checks: repro, reproduced },