@hegemonart/get-design-done 1.24.2 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +87 -0
  4. package/README.de.md +679 -0
  5. package/README.fr.md +679 -0
  6. package/README.it.md +679 -0
  7. package/README.ja.md +679 -0
  8. package/README.ko.md +679 -0
  9. package/README.md +399 -728
  10. package/README.zh-CN.md +480 -133
  11. package/SKILL.md +2 -0
  12. package/agents/README.md +60 -0
  13. package/agents/design-reflector.md +43 -0
  14. package/agents/gdd-intel-updater.md +34 -1
  15. package/agents/prototype-gate.md +122 -0
  16. package/agents/quality-gate-runner.md +125 -0
  17. package/hooks/budget-enforcer.ts +275 -11
  18. package/hooks/gdd-decision-injector.js +183 -3
  19. package/hooks/gdd-turn-closeout.js +238 -0
  20. package/hooks/hooks.json +10 -0
  21. package/package.json +5 -5
  22. package/reference/STATE-TEMPLATE.md +41 -0
  23. package/reference/config-schema.md +30 -0
  24. package/reference/model-prices.md +40 -19
  25. package/reference/prices/antigravity.md +21 -0
  26. package/reference/prices/augment.md +21 -0
  27. package/reference/prices/claude.md +42 -0
  28. package/reference/prices/cline.md +23 -0
  29. package/reference/prices/codebuddy.md +21 -0
  30. package/reference/prices/codex.md +25 -0
  31. package/reference/prices/copilot.md +21 -0
  32. package/reference/prices/cursor.md +21 -0
  33. package/reference/prices/gemini.md +25 -0
  34. package/reference/prices/kilo.md +21 -0
  35. package/reference/prices/opencode.md +23 -0
  36. package/reference/prices/qwen.md +25 -0
  37. package/reference/prices/trae.md +23 -0
  38. package/reference/prices/windsurf.md +21 -0
  39. package/reference/registry.json +107 -1
  40. package/reference/runtime-models.md +446 -0
  41. package/reference/schemas/runtime-models.schema.json +123 -0
  42. package/scripts/install.cjs +8 -0
  43. package/scripts/lib/budget-enforcer.cjs +446 -0
  44. package/scripts/lib/cost-arbitrage.cjs +294 -0
  45. package/scripts/lib/gdd-state/mutator.ts +454 -0
  46. package/scripts/lib/gdd-state/parser.ts +351 -1
  47. package/scripts/lib/gdd-state/types.ts +193 -0
  48. package/scripts/lib/install/installer.cjs +188 -11
  49. package/scripts/lib/install/parse-runtime-models.cjs +267 -0
  50. package/scripts/lib/install/runtimes.cjs +43 -0
  51. package/scripts/lib/quality-gate-detect.cjs +126 -0
  52. package/scripts/lib/runtime-detect.cjs +96 -0
  53. package/scripts/lib/tier-resolver.cjs +311 -0
  54. package/scripts/validate-frontmatter.ts +138 -1
  55. package/skills/quality-gate/SKILL.md +222 -0
  56. package/skills/router/SKILL.md +79 -10
  57. package/skills/sketch-wrap-up/SKILL.md +47 -2
  58. package/skills/spike-wrap-up/SKILL.md +41 -2
  59. package/skills/turn-closeout/SKILL.md +115 -0
  60. package/skills/verify/SKILL.md +22 -0
@@ -6,7 +6,7 @@
6
6
  const fs = require('node:fs');
7
7
  const path = require('node:path');
8
8
 
9
- const { getRuntime } = require('./runtimes.cjs');
9
+ const { getRuntime, getRuntimeModels } = require('./runtimes.cjs');
10
10
  const { resolveConfigDir } = require('./config-dir.cjs');
11
11
  const {
12
12
  mergeClaudeSettings,
@@ -15,6 +15,15 @@ const {
15
15
  isPluginOwned,
16
16
  } = require('./merge.cjs');
17
17
 
18
+ // Phase 26 D-06 — schema for the per-runtime models.json file emitted into
19
+ // each runtime's config directory at install time. Forward-compatible: new
20
+ // fields land additive; breaking changes bump `schema_version`.
21
+ const MODELS_JSON_SCHEMA_VERSION = 1;
22
+ const MODELS_JSON_FILE = 'models.json';
23
+ const MODELS_JSON_SOURCE = 'reference/runtime-models.md';
24
+ const MODELS_JSON_FINGERPRINT_KEY = 'generated_by';
25
+ const MODELS_JSON_FINGERPRINT_VALUE = 'get-design-done';
26
+
18
27
  function loadJsonOr(empty, filePath) {
19
28
  if (!fs.existsSync(filePath)) return empty;
20
29
  const raw = fs.readFileSync(filePath, 'utf8');
@@ -48,13 +57,20 @@ function installRuntime(runtimeId, opts) {
48
57
  const dryRun = Boolean(opts && opts.dryRun);
49
58
  const configDir = resolveConfigDir(runtimeId, opts);
50
59
 
60
+ let result;
51
61
  if (runtime.kind === 'claude-marketplace') {
52
- return installClaudeMarketplace(runtime, configDir, dryRun);
53
- }
54
- if (runtime.kind === 'agents-md') {
55
- return installAgentsMd(runtime, configDir, dryRun);
62
+ result = installClaudeMarketplace(runtime, configDir, dryRun);
63
+ } else if (runtime.kind === 'agents-md') {
64
+ result = installAgentsMd(runtime, configDir, dryRun);
65
+ } else {
66
+ throw new Error(`Unsupported runtime kind: ${runtime.kind}`);
56
67
  }
57
- throw new Error(`Unsupported runtime kind: ${runtime.kind}`);
68
+
69
+ // Phase 26 D-06 — emit per-runtime models.json into the same config-dir.
70
+ // Side-effect attached to the primary result so existing callers see the
71
+ // unchanged shape AND get visibility into the second file.
72
+ result.modelsJson = installModelsJson(runtime, configDir, dryRun, opts);
73
+ return result;
58
74
  }
59
75
 
60
76
  function uninstallRuntime(runtimeId, opts) {
@@ -62,13 +78,20 @@ function uninstallRuntime(runtimeId, opts) {
62
78
  const dryRun = Boolean(opts && opts.dryRun);
63
79
  const configDir = resolveConfigDir(runtimeId, opts);
64
80
 
81
+ let result;
65
82
  if (runtime.kind === 'claude-marketplace') {
66
- return uninstallClaudeMarketplace(runtime, configDir, dryRun);
83
+ result = uninstallClaudeMarketplace(runtime, configDir, dryRun);
84
+ } else if (runtime.kind === 'agents-md') {
85
+ result = uninstallAgentsMd(runtime, configDir, dryRun);
86
+ } else {
87
+ throw new Error(`Unsupported runtime kind: ${runtime.kind}`);
67
88
  }
68
- if (runtime.kind === 'agents-md') {
69
- return uninstallAgentsMd(runtime, configDir, dryRun);
70
- }
71
- throw new Error(`Unsupported runtime kind: ${runtime.kind}`);
89
+
90
+ // Phase 26 D-06 — clean up the models.json we wrote on install.
91
+ // Idempotent: missing file → unchanged; foreign file (no fingerprint) is
92
+ // left alone, mirroring the AGENTS.md skipped-foreign discipline.
93
+ result.modelsJson = uninstallModelsJson(runtime, configDir, dryRun);
94
+ return result;
72
95
  }
73
96
 
74
97
  function installClaudeMarketplace(runtime, configDir, dryRun) {
@@ -203,6 +226,154 @@ function uninstallAgentsMd(runtime, configDir, dryRun) {
203
226
  };
204
227
  }
205
228
 
229
+ // Phase 26 D-06 — `models.json` emission per runtime config-dir.
230
+ //
231
+ // Format (locked by CONTEXT D-06):
232
+ // {
233
+ // "tier_to_model": { "opus": "<model>", "sonnet": "<model>", "haiku": "<model>" },
234
+ // "reasoning_class_to_model": { "high": "<model>", "medium": "<model>", "low": "<model>" },
235
+ // "runtime": "<runtime-id>",
236
+ // "schema_version": 1,
237
+ // "generated_at": "<ISO-timestamp>",
238
+ // "source": "reference/runtime-models.md",
239
+ // "generated_by": "get-design-done"
240
+ // }
241
+ //
242
+ // `generated_by` is the fingerprint uninstall uses to decide whether the
243
+ // file is plugin-owned (mirroring the AGENTS.md fingerprint discipline in
244
+ // merge.cjs).
245
+
246
+ function buildModelsJsonPayload(runtime, opts) {
247
+ const entry = getRuntimeModels(runtime.id, opts);
248
+ if (!entry) return null;
249
+ // Flatten { model: "..." } rows into bare strings per CONTEXT D-06's
250
+ // schema example. provider_model_id (if present in the source) is dropped
251
+ // here — runtime harnesses that need it can re-read runtime-models.md.
252
+ const flatten = (rowMap) => {
253
+ const out = {};
254
+ for (const k of Object.keys(rowMap)) {
255
+ out[k] = rowMap[k].model;
256
+ }
257
+ return out;
258
+ };
259
+ return {
260
+ tier_to_model: flatten(entry.tier_to_model),
261
+ reasoning_class_to_model: flatten(entry.reasoning_class_to_model),
262
+ runtime: runtime.id,
263
+ schema_version: MODELS_JSON_SCHEMA_VERSION,
264
+ generated_at: (opts && opts.now) || new Date().toISOString(),
265
+ source: MODELS_JSON_SOURCE,
266
+ [MODELS_JSON_FINGERPRINT_KEY]: MODELS_JSON_FINGERPRINT_VALUE,
267
+ };
268
+ }
269
+
270
+ function isModelsJsonPluginOwned(parsed) {
271
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
272
+ return parsed[MODELS_JSON_FINGERPRINT_KEY] === MODELS_JSON_FINGERPRINT_VALUE;
273
+ }
274
+
275
+ function installModelsJson(runtime, configDir, dryRun, opts) {
276
+ const target = path.join(configDir, MODELS_JSON_FILE);
277
+ const payload = buildModelsJsonPayload(runtime, opts);
278
+ if (!payload) {
279
+ // Runtime has no entry in runtime-models.md (e.g., research tail). Skip
280
+ // emission rather than writing an incomplete file. Surfaces as
281
+ // "skipped-no-data" in install summary so the operator can see why.
282
+ return {
283
+ path: target,
284
+ action: 'skipped-no-data',
285
+ dryRun,
286
+ reason: `No tier→model entry for runtime "${runtime.id}" in ${MODELS_JSON_SOURCE}`,
287
+ };
288
+ }
289
+ ensureDir(configDir, dryRun);
290
+
291
+ const desired = `${JSON.stringify(payload, null, 2)}\n`;
292
+
293
+ if (fs.existsSync(target)) {
294
+ let current;
295
+ try {
296
+ current = fs.readFileSync(target, 'utf8');
297
+ } catch (err) {
298
+ // Read failure is unusual but non-fatal — surface and continue.
299
+ return {
300
+ path: target,
301
+ action: 'skipped-foreign',
302
+ dryRun,
303
+ reason: `Could not read existing ${MODELS_JSON_FILE}: ${err.message}`,
304
+ };
305
+ }
306
+ let parsed = null;
307
+ try {
308
+ parsed = JSON.parse(current);
309
+ } catch {
310
+ // Corrupted/foreign JSON we did not write — leave it alone.
311
+ return {
312
+ path: target,
313
+ action: 'skipped-foreign',
314
+ dryRun,
315
+ reason: `Existing ${MODELS_JSON_FILE} is not valid JSON; refusing to overwrite.`,
316
+ };
317
+ }
318
+ if (!isModelsJsonPluginOwned(parsed)) {
319
+ return {
320
+ path: target,
321
+ action: 'skipped-foreign',
322
+ dryRun,
323
+ reason: `Existing ${MODELS_JSON_FILE} was not authored by this plugin; refusing to overwrite.`,
324
+ };
325
+ }
326
+ // Compare ignoring `generated_at` so re-runs aren't perpetually "updated"
327
+ // just because the timestamp moved.
328
+ if (modelsJsonContentEqual(parsed, payload)) {
329
+ return { path: target, action: 'unchanged', dryRun };
330
+ }
331
+ if (!dryRun) atomicWrite(target, desired);
332
+ return { path: target, action: 'updated', dryRun };
333
+ }
334
+ if (!dryRun) atomicWrite(target, desired);
335
+ return { path: target, action: 'created', dryRun };
336
+ }
337
+
338
+ function modelsJsonContentEqual(a, b) {
339
+ // Strip `generated_at` from both sides — every other field must match
340
+ // byte-for-byte for the install to be a true no-op.
341
+ const stripTs = (o) => {
342
+ const copy = { ...o };
343
+ delete copy.generated_at;
344
+ return copy;
345
+ };
346
+ return JSON.stringify(stripTs(a)) === JSON.stringify(stripTs(b));
347
+ }
348
+
349
+ function uninstallModelsJson(runtime, configDir, dryRun) {
350
+ const target = path.join(configDir, MODELS_JSON_FILE);
351
+ if (!fs.existsSync(target)) {
352
+ return { path: target, action: 'unchanged', dryRun };
353
+ }
354
+ let parsed = null;
355
+ try {
356
+ parsed = JSON.parse(fs.readFileSync(target, 'utf8'));
357
+ } catch {
358
+ return {
359
+ path: target,
360
+ action: 'skipped-foreign',
361
+ dryRun,
362
+ reason: `Existing ${MODELS_JSON_FILE} is not valid JSON; not removing.`,
363
+ };
364
+ }
365
+ if (!isModelsJsonPluginOwned(parsed)) {
366
+ return {
367
+ path: target,
368
+ action: 'skipped-foreign',
369
+ dryRun,
370
+ reason: `Existing ${MODELS_JSON_FILE} was not authored by this plugin; not removing.`,
371
+ };
372
+ }
373
+ if (!dryRun) fs.unlinkSync(target);
374
+ return { path: target, action: 'removed', dryRun };
375
+ }
376
+
206
377
  function detectInstalled(opts) {
207
378
  const installed = [];
208
379
  const { listRuntimes } = require('./runtimes.cjs');
@@ -241,4 +412,10 @@ module.exports = {
241
412
  installRuntime,
242
413
  uninstallRuntime,
243
414
  detectInstalled,
415
+ // Phase 26 D-06 — exported for tests / external tooling that wants to
416
+ // preview the payload without performing a write.
417
+ buildModelsJsonPayload,
418
+ MODELS_JSON_FILE,
419
+ MODELS_JSON_SCHEMA_VERSION,
420
+ MODELS_JSON_SOURCE,
244
421
  };
@@ -0,0 +1,267 @@
1
+ 'use strict';
2
+ /**
3
+ * parse-runtime-models.cjs — pure parser for reference/runtime-models.md.
4
+ *
5
+ * Reads the per-runtime tier→model adapter source-of-truth (Phase 26 D-01..D-03)
6
+ * and returns a structured object with one entry per runtime. Used by:
7
+ *
8
+ * - scripts/lib/install/installer.cjs (26-03) at install time to emit
9
+ * `models.json` per runtime config-dir.
10
+ * - scripts/lib/tier-resolver.cjs (26-02) at runtime to resolve
11
+ * (runtime, tier) → model.
12
+ *
13
+ * Pure-JS validation against the strict schema at
14
+ * `reference/schemas/runtime-models.schema.json`. No optional dependencies.
15
+ *
16
+ * Public API:
17
+ * parseRuntimeModels({ cwd? }) → {
18
+ * runtimes: [{ id, tier_to_model, reasoning_class_to_model, provenance, single_tier? }, ...],
19
+ * schema_version: 1
20
+ * }
21
+ * parseRuntimeModelsFromString(markdown) → same shape
22
+ *
23
+ * Throws an Error with a specific message on the first validation failure
24
+ * (fail-fast: install-time validation catches typos before runtime).
25
+ */
26
+
27
+ const fs = require('node:fs');
28
+ const path = require('node:path');
29
+
30
+ const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');
31
+ const DEFAULT_PATH = path.join(REPO_ROOT, 'reference', 'runtime-models.md');
32
+
33
+ // Mirrors scripts/lib/install/runtimes.cjs RUNTIMES list (Phase 24 D-02 lock).
34
+ // Re-declared rather than imported to keep this parser dependency-free for
35
+ // downstream consumers that may want to call it from outside the install/ tree.
36
+ // Round-trip tested by tests/parse-runtime-models.test.cjs against the canonical
37
+ // runtimes.cjs list.
38
+ const KNOWN_RUNTIME_IDS = Object.freeze([
39
+ 'claude',
40
+ 'codex',
41
+ 'gemini',
42
+ 'qwen',
43
+ 'kilo',
44
+ 'copilot',
45
+ 'cursor',
46
+ 'windsurf',
47
+ 'antigravity',
48
+ 'augment',
49
+ 'trae',
50
+ 'codebuddy',
51
+ 'cline',
52
+ 'opencode',
53
+ ]);
54
+
55
+ const TIER_KEYS = Object.freeze(['opus', 'sonnet', 'haiku']);
56
+ const REASONING_CLASS_KEYS = Object.freeze(['high', 'medium', 'low']);
57
+
58
+ /**
59
+ * Extract every ```json ... ``` fenced block from a markdown string.
60
+ * Returns an array of { raw, lineNumber } objects.
61
+ */
62
+ function extractJsonBlocks(markdown) {
63
+ const blocks = [];
64
+ const re = /```json\s*\n([\s\S]*?)\n```/g;
65
+ let m;
66
+ while ((m = re.exec(markdown)) !== null) {
67
+ // Compute 1-indexed line number of the fence opening for error messages.
68
+ const lineNumber = markdown.slice(0, m.index).split('\n').length;
69
+ blocks.push({ raw: m[1], lineNumber });
70
+ }
71
+ return blocks;
72
+ }
73
+
74
+ function validateModelRow(row, where) {
75
+ if (!row || typeof row !== 'object' || Array.isArray(row)) {
76
+ throw new Error(`${where}: expected object, got ${typeof row}`);
77
+ }
78
+ if (typeof row.model !== 'string' || row.model.length === 0) {
79
+ throw new Error(`${where}: 'model' must be a non-empty string`);
80
+ }
81
+ const allowedKeys = new Set(['model', 'provider_model_id']);
82
+ for (const k of Object.keys(row)) {
83
+ if (!allowedKeys.has(k)) {
84
+ throw new Error(`${where}: unknown key '${k}' (allowed: ${[...allowedKeys].join(', ')})`);
85
+ }
86
+ }
87
+ if (row.provider_model_id !== undefined) {
88
+ if (typeof row.provider_model_id !== 'string' || row.provider_model_id.length === 0) {
89
+ throw new Error(`${where}: 'provider_model_id' must be a non-empty string when present`);
90
+ }
91
+ }
92
+ }
93
+
94
+ function validateProvenance(arr, where) {
95
+ if (!Array.isArray(arr) || arr.length < 1) {
96
+ throw new Error(`${where}: 'provenance' must be a non-empty array`);
97
+ }
98
+ arr.forEach((row, i) => {
99
+ const w = `${where}[${i}]`;
100
+ if (!row || typeof row !== 'object' || Array.isArray(row)) {
101
+ throw new Error(`${w}: expected object`);
102
+ }
103
+ for (const required of ['source_url', 'retrieved_at', 'last_validated_cycle']) {
104
+ if (typeof row[required] !== 'string' || row[required].length === 0) {
105
+ throw new Error(`${w}: '${required}' must be a non-empty string`);
106
+ }
107
+ }
108
+ // ISO-8601 sanity check (Date.parse accepts the canonical form we emit).
109
+ if (Number.isNaN(Date.parse(row.retrieved_at))) {
110
+ throw new Error(`${w}: 'retrieved_at' must be a valid ISO 8601 timestamp (got ${JSON.stringify(row.retrieved_at)})`);
111
+ }
112
+ const allowedKeys = new Set(['source_url', 'retrieved_at', 'last_validated_cycle', 'note']);
113
+ for (const k of Object.keys(row)) {
114
+ if (!allowedKeys.has(k)) {
115
+ throw new Error(`${w}: unknown key '${k}' (allowed: ${[...allowedKeys].join(', ')})`);
116
+ }
117
+ }
118
+ if (row.note !== undefined && typeof row.note !== 'string') {
119
+ throw new Error(`${w}: 'note' must be a string when present`);
120
+ }
121
+ });
122
+ }
123
+
124
+ function validateRuntimeEntry(entry, where) {
125
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
126
+ throw new Error(`${where}: expected object`);
127
+ }
128
+ // Required keys
129
+ for (const required of ['id', 'tier_to_model', 'reasoning_class_to_model', 'provenance']) {
130
+ if (!(required in entry)) {
131
+ throw new Error(`${where}: missing required key '${required}'`);
132
+ }
133
+ }
134
+ // id enum check
135
+ if (typeof entry.id !== 'string' || !KNOWN_RUNTIME_IDS.includes(entry.id)) {
136
+ throw new Error(
137
+ `${where}: 'id' must be one of ${KNOWN_RUNTIME_IDS.join('|')} (got ${JSON.stringify(entry.id)})`,
138
+ );
139
+ }
140
+ // No unknown top-level keys
141
+ const allowedKeys = new Set(['id', 'single_tier', 'tier_to_model', 'reasoning_class_to_model', 'provenance']);
142
+ for (const k of Object.keys(entry)) {
143
+ if (!allowedKeys.has(k)) {
144
+ throw new Error(`${where}: unknown key '${k}' (allowed: ${[...allowedKeys].join(', ')})`);
145
+ }
146
+ }
147
+ if (entry.single_tier !== undefined && typeof entry.single_tier !== 'boolean') {
148
+ throw new Error(`${where}: 'single_tier' must be a boolean when present`);
149
+ }
150
+
151
+ // tier_to_model: requires opus/sonnet/haiku
152
+ if (!entry.tier_to_model || typeof entry.tier_to_model !== 'object' || Array.isArray(entry.tier_to_model)) {
153
+ throw new Error(`${where}.tier_to_model: expected object`);
154
+ }
155
+ for (const tier of TIER_KEYS) {
156
+ if (!(tier in entry.tier_to_model)) {
157
+ throw new Error(`${where}.tier_to_model: missing required tier '${tier}'`);
158
+ }
159
+ }
160
+ for (const k of Object.keys(entry.tier_to_model)) {
161
+ if (!TIER_KEYS.includes(k)) {
162
+ throw new Error(`${where}.tier_to_model: unknown tier '${k}' (allowed: ${TIER_KEYS.join('|')})`);
163
+ }
164
+ validateModelRow(entry.tier_to_model[k], `${where}.tier_to_model.${k}`);
165
+ }
166
+
167
+ // reasoning_class_to_model: requires high/medium/low
168
+ if (!entry.reasoning_class_to_model || typeof entry.reasoning_class_to_model !== 'object' || Array.isArray(entry.reasoning_class_to_model)) {
169
+ throw new Error(`${where}.reasoning_class_to_model: expected object`);
170
+ }
171
+ for (const klass of REASONING_CLASS_KEYS) {
172
+ if (!(klass in entry.reasoning_class_to_model)) {
173
+ throw new Error(`${where}.reasoning_class_to_model: missing required class '${klass}'`);
174
+ }
175
+ }
176
+ for (const k of Object.keys(entry.reasoning_class_to_model)) {
177
+ if (!REASONING_CLASS_KEYS.includes(k)) {
178
+ throw new Error(`${where}.reasoning_class_to_model: unknown class '${k}' (allowed: ${REASONING_CLASS_KEYS.join('|')})`);
179
+ }
180
+ validateModelRow(entry.reasoning_class_to_model[k], `${where}.reasoning_class_to_model.${k}`);
181
+ }
182
+
183
+ validateProvenance(entry.provenance, `${where}.provenance`);
184
+ }
185
+
186
+ function parseRuntimeModelsFromString(markdown, sourceLabel) {
187
+ const label = sourceLabel || '<runtime-models markdown>';
188
+ if (typeof markdown !== 'string' || markdown.length === 0) {
189
+ throw new Error(`${label}: empty or non-string input`);
190
+ }
191
+
192
+ const blocks = extractJsonBlocks(markdown);
193
+ if (blocks.length < 2) {
194
+ // We expect at least the schema-version block + 1 runtime block.
195
+ throw new Error(`${label}: expected at least one schema-version block and one runtime block, found ${blocks.length} fenced json blocks`);
196
+ }
197
+
198
+ // First block MUST be the { "$schema_version": <int> } header.
199
+ let schemaVersion = null;
200
+ let firstParsed;
201
+ try {
202
+ firstParsed = JSON.parse(blocks[0].raw);
203
+ } catch (err) {
204
+ throw new Error(`${label}: first json block (line ${blocks[0].lineNumber}) failed to parse: ${err.message}`);
205
+ }
206
+ if (
207
+ !firstParsed ||
208
+ typeof firstParsed !== 'object' ||
209
+ Array.isArray(firstParsed) ||
210
+ !('$schema_version' in firstParsed) ||
211
+ Object.keys(firstParsed).length !== 1
212
+ ) {
213
+ throw new Error(`${label}: first json block (line ${blocks[0].lineNumber}) must be { "$schema_version": <int> } and nothing else`);
214
+ }
215
+ if (firstParsed.$schema_version !== 1) {
216
+ throw new Error(
217
+ `${label}: $schema_version must be 1 (got ${JSON.stringify(firstParsed.$schema_version)}). Bump the parser when the schema breaks forward.`,
218
+ );
219
+ }
220
+ schemaVersion = firstParsed.$schema_version;
221
+
222
+ // Remaining blocks are runtime entries.
223
+ const runtimes = [];
224
+ const seenIds = new Set();
225
+ for (let i = 1; i < blocks.length; i++) {
226
+ const block = blocks[i];
227
+ let parsed;
228
+ try {
229
+ parsed = JSON.parse(block.raw);
230
+ } catch (err) {
231
+ throw new Error(`${label}: json block at line ${block.lineNumber} failed to parse: ${err.message}`);
232
+ }
233
+ const where = `${label}#runtimes[${i - 1}] (line ${block.lineNumber})`;
234
+ validateRuntimeEntry(parsed, where);
235
+ if (seenIds.has(parsed.id)) {
236
+ throw new Error(`${where}: duplicate runtime id '${parsed.id}' (already seen earlier in the file)`);
237
+ }
238
+ seenIds.add(parsed.id);
239
+ runtimes.push(parsed);
240
+ }
241
+
242
+ return { schema_version: schemaVersion, runtimes };
243
+ }
244
+
245
+ function parseRuntimeModels({ cwd } = {}) {
246
+ const filePath = cwd ? path.join(cwd, 'reference', 'runtime-models.md') : DEFAULT_PATH;
247
+ let markdown;
248
+ try {
249
+ markdown = fs.readFileSync(filePath, 'utf8');
250
+ } catch (err) {
251
+ const wrapped = new Error(
252
+ `parse-runtime-models: cannot read ${filePath}\n ${err.message}`,
253
+ );
254
+ wrapped.code = 'EPARSE_RUNTIME_MODELS_READ';
255
+ wrapped.path = filePath;
256
+ throw wrapped;
257
+ }
258
+ return parseRuntimeModelsFromString(markdown, filePath);
259
+ }
260
+
261
+ module.exports = {
262
+ parseRuntimeModels,
263
+ parseRuntimeModelsFromString,
264
+ KNOWN_RUNTIME_IDS,
265
+ TIER_KEYS,
266
+ REASONING_CLASS_KEYS,
267
+ };
@@ -161,6 +161,47 @@ function listRuntimeIds() {
161
161
  return RUNTIMES.map((r) => r.id);
162
162
  }
163
163
 
164
+ // Phase 26 D-06 — `tier_to_model` lookup helper.
165
+ //
166
+ // `getRuntimeModels(runtimeId, { cwd? })` resolves the per-runtime tier→model
167
+ // adapter from `reference/runtime-models.md` via `parse-runtime-models.cjs`.
168
+ // Returns `null` when the runtime has no entry in runtime-models.md (i.e.,
169
+ // the data source ships rows for fewer than 14 runtimes during the rolling
170
+ // research tail described in CONTEXT D-02). Caller is responsible for
171
+ // degrading gracefully (e.g., installer skips models.json emission when null).
172
+ //
173
+ // The parsed payload is cached per `cwd` to avoid re-reading the markdown
174
+ // on each runtime in a multi-runtime install loop.
175
+
176
+ const _modelsCache = new Map();
177
+
178
+ function getParsedRuntimeModels(opts) {
179
+ const cwd = (opts && opts.cwd) || null;
180
+ const cacheKey = cwd || '<default>';
181
+ if (_modelsCache.has(cacheKey)) return _modelsCache.get(cacheKey);
182
+ // Lazy require avoids a hard dep cycle if runtimes.cjs is imported in
183
+ // contexts that don't ship the reference/ tree (theoretical — not used today).
184
+ const { parseRuntimeModels } = require('./parse-runtime-models.cjs');
185
+ const parsed = parseRuntimeModels(cwd ? { cwd } : {});
186
+ _modelsCache.set(cacheKey, parsed);
187
+ return parsed;
188
+ }
189
+
190
+ function getRuntimeModels(runtimeId, opts) {
191
+ // Validate the runtime id up-front — this catches typos in the installer
192
+ // entry rather than silently returning null for "claud" vs "claude".
193
+ getRuntime(runtimeId);
194
+ const parsed = getParsedRuntimeModels(opts);
195
+ const entry = parsed.runtimes.find((r) => r.id === runtimeId);
196
+ return entry || null;
197
+ }
198
+
199
+ // Test-only hook: drop the cached parse result. Used by tests that mutate
200
+ // the source markdown between assertions.
201
+ function _resetRuntimeModelsCache() {
202
+ _modelsCache.clear();
203
+ }
204
+
164
205
  module.exports = {
165
206
  RUNTIMES,
166
207
  REPO,
@@ -169,4 +210,6 @@ module.exports = {
169
210
  getRuntime,
170
211
  listRuntimes,
171
212
  listRuntimeIds,
213
+ getRuntimeModels,
214
+ _resetRuntimeModelsCache,
172
215
  };
@@ -0,0 +1,126 @@
1
+ 'use strict';
2
+
3
+ // scripts/lib/quality-gate-detect.cjs — quality-gate detection chain.
4
+ //
5
+ // Phase 25 Plan 25-09: promotes the doc-only auto-detection logic from
6
+ // skills/quality-gate/SKILL.md (Step 1, D-06) into a small testable
7
+ // JS module. Pure function, no I/O, no clock.
8
+ //
9
+ // The 3-tier resolution order (D-06):
10
+ //
11
+ // Tier 1 — Authoritative config:
12
+ // If the (already-loaded) `.design/config.json#quality_gate.commands`
13
+ // array is non-empty, return it verbatim. Skip all later tiers.
14
+ //
15
+ // Tier 2 — Auto-detect from package.json#scripts:
16
+ // If the (already-loaded) package.json#scripts object exists and is
17
+ // non-empty, intersect its keys with the canonical allowlist and
18
+ // emit `npm run <script>` for each match. The allowlist (case-
19
+ // sensitive, exact match):
20
+ //
21
+ // lint
22
+ // typecheck (or `tsc` as a substitute when `typecheck` is absent)
23
+ // test
24
+ // chromatic
25
+ // test:visual
26
+ //
27
+ // Hard exclusions (never included even if present):
28
+ //
29
+ // test:e2e (too slow for a Stage 4.5 gate)
30
+ // test:integration (only excluded when a separate `test` exists)
31
+ //
32
+ // Tier 3 — Skip with notice:
33
+ // Returns an empty array. Caller emits a `quality_gate_skipped`
34
+ // event and writes a `<run/>` with status="skipped".
35
+ //
36
+ // Mirrors the table in skills/quality-gate/SKILL.md verbatim. When the
37
+ // SKILL.md prose changes, change this module in lockstep — the SKILL is
38
+ // the design intent, this is the executable encoding consumers can test
39
+ // against.
40
+
41
+ /**
42
+ * Allowlisted script names (case-sensitive, exact match unless noted).
43
+ * Order matters: it determines the canonical command-list ordering, which
44
+ * in turn drives the deterministic `commands_run` field in events.jsonl
45
+ * and the STATE.md <run/> entry.
46
+ */
47
+ const ALLOWLIST = Object.freeze([
48
+ 'lint',
49
+ 'typecheck',
50
+ 'test',
51
+ 'chromatic',
52
+ 'test:visual',
53
+ ]);
54
+
55
+ /**
56
+ * Hard exclusions. Even when present in package.json#scripts, these are
57
+ * never run by the quality gate — they are too slow / orthogonal to the
58
+ * gate's purpose. Excluding `test:integration` only matters when a
59
+ * separate `test` script exists; we encode that invariant in detect().
60
+ */
61
+ const ALWAYS_EXCLUDED = Object.freeze(['test:e2e']);
62
+
63
+ /**
64
+ * Detection chain.
65
+ *
66
+ * @param {object} inputs
67
+ * @param {string[]|null|undefined} inputs.configCommands
68
+ * Value of `.design/config.json#quality_gate.commands`. `null` or
69
+ * empty array means "no config-side override; fall through to
70
+ * auto-detect". The caller is responsible for reading the file.
71
+ * @param {Record<string, string>|null|undefined} inputs.scripts
72
+ * Value of `package.json#scripts`. `null` means "no package.json".
73
+ * @returns {{commands: string[], tier: 1|2|3, reason?: string}}
74
+ * Detection result. `tier` is the tier that produced the
75
+ * commands (1 / 2 / 3 — see top of file). `reason` is populated
76
+ * on tier 3 only ("no commands resolved").
77
+ */
78
+ function detect(inputs) {
79
+ const configCommands = inputs && inputs.configCommands;
80
+ const scripts = inputs && inputs.scripts;
81
+
82
+ // --- Tier 1: authoritative config wins. ---
83
+ if (Array.isArray(configCommands) && configCommands.length > 0) {
84
+ return { commands: configCommands.slice(), tier: 1 };
85
+ }
86
+
87
+ // --- Tier 2: auto-detect from package.json#scripts. ---
88
+ if (scripts && typeof scripts === 'object') {
89
+ const detected = autoDetect(scripts);
90
+ if (detected.length > 0) {
91
+ return { commands: detected, tier: 2 };
92
+ }
93
+ }
94
+
95
+ // --- Tier 3: nothing resolved → skip with notice. ---
96
+ return { commands: [], tier: 3, reason: 'no commands resolved' };
97
+ }
98
+
99
+ /**
100
+ * Apply the allowlist to a `scripts` map. Pure.
101
+ */
102
+ function autoDetect(scripts) {
103
+ const out = [];
104
+ for (const name of ALLOWLIST) {
105
+ if (name === 'typecheck') {
106
+ // `typecheck` preferred; fall through to `tsc` only if absent.
107
+ if (Object.prototype.hasOwnProperty.call(scripts, 'typecheck')) {
108
+ out.push('npm run typecheck');
109
+ } else if (Object.prototype.hasOwnProperty.call(scripts, 'tsc')) {
110
+ out.push('npm run tsc');
111
+ }
112
+ continue;
113
+ }
114
+ if (Object.prototype.hasOwnProperty.call(scripts, name) && !ALWAYS_EXCLUDED.includes(name)) {
115
+ out.push(`npm run ${name}`);
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+
121
+ module.exports = {
122
+ ALLOWLIST,
123
+ ALWAYS_EXCLUDED,
124
+ detect,
125
+ autoDetect,
126
+ };