@bastani/atomic 0.9.11-alpha.6 → 0.9.11-alpha.7

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 (140) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/package.json +1 -1
  7. package/dist/builtin/workflows/skills/impeccable/SKILL.md +33 -129
  8. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_asset_producer.toml +11 -3
  9. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_documenter.toml +26 -0
  10. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_finish_reviewer.toml +35 -0
  11. package/dist/builtin/workflows/skills/impeccable/reference/android.md +1 -1
  12. package/dist/builtin/workflows/skills/impeccable/reference/animate.md +72 -189
  13. package/dist/builtin/workflows/skills/impeccable/reference/audit.md +10 -9
  14. package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +2 -2
  15. package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +19 -108
  16. package/dist/builtin/workflows/skills/impeccable/reference/clarify.md +59 -253
  17. package/dist/builtin/workflows/skills/impeccable/reference/colorize.md +51 -222
  18. package/dist/builtin/workflows/skills/impeccable/reference/craft-floor.md +45 -0
  19. package/dist/builtin/workflows/skills/impeccable/reference/craft.md +3 -121
  20. package/dist/builtin/workflows/skills/impeccable/reference/critique.md +28 -20
  21. package/dist/builtin/workflows/skills/impeccable/reference/degraded/asset-producer.md +97 -0
  22. package/dist/builtin/workflows/skills/impeccable/reference/degraded/documenter.md +23 -0
  23. package/dist/builtin/workflows/skills/impeccable/reference/degraded/finish-reviewer.md +32 -0
  24. package/dist/builtin/workflows/skills/impeccable/reference/degraded/manual-edit-applier.md +92 -0
  25. package/dist/builtin/workflows/skills/impeccable/reference/delight.md +47 -279
  26. package/dist/builtin/workflows/skills/impeccable/reference/distill.md +2 -2
  27. package/dist/builtin/workflows/skills/impeccable/reference/doctor.md +53 -0
  28. package/dist/builtin/workflows/skills/impeccable/reference/document.md +60 -73
  29. package/dist/builtin/workflows/skills/impeccable/reference/harden.md +1 -12
  30. package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +17 -4
  31. package/dist/builtin/workflows/skills/impeccable/reference/init.md +64 -163
  32. package/dist/builtin/workflows/skills/impeccable/reference/ios.md +1 -1
  33. package/dist/builtin/workflows/skills/impeccable/reference/layout.md +52 -153
  34. package/dist/builtin/workflows/skills/impeccable/reference/live.md +44 -32
  35. package/dist/builtin/workflows/skills/impeccable/reference/new-work.md +105 -0
  36. package/dist/builtin/workflows/skills/impeccable/reference/{product.md → operate.md} +6 -5
  37. package/dist/builtin/workflows/skills/impeccable/reference/optimize.md +4 -4
  38. package/dist/builtin/workflows/skills/impeccable/reference/overdrive.md +1 -4
  39. package/dist/builtin/workflows/skills/impeccable/reference/polish.md +68 -212
  40. package/dist/builtin/workflows/skills/impeccable/reference/quieter.md +3 -3
  41. package/dist/builtin/workflows/skills/impeccable/reference/routing.md +18 -0
  42. package/dist/builtin/workflows/skills/impeccable/reference/shape.md +38 -144
  43. package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +48 -269
  44. package/dist/builtin/workflows/skills/impeccable/reference/visualize.md +38 -0
  45. package/dist/builtin/workflows/skills/impeccable/scripts/command-metadata.json +1 -1
  46. package/dist/builtin/workflows/skills/impeccable/scripts/concept-seed.mjs +584 -0
  47. package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +117 -9
  48. package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +486 -59
  49. package/dist/builtin/workflows/skills/impeccable/scripts/critique-storage.mjs +16 -45
  50. package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +96 -10
  51. package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +143 -26
  52. package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +181 -12
  53. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +3187 -182
  54. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs +102 -7
  55. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +282 -70
  56. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs +183 -15
  57. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs +22 -7
  58. package/dist/builtin/workflows/skills/impeccable/scripts/detector/findings.mjs +7 -1
  59. package/dist/builtin/workflows/skills/impeccable/scripts/detector/node/file-system.mjs +16 -2
  60. package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +155 -42
  61. package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +2988 -155
  62. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/constants.mjs +11 -0
  63. package/dist/builtin/workflows/skills/impeccable/scripts/doctor.mjs +336 -0
  64. package/dist/builtin/workflows/skills/impeccable/scripts/generate-image.mjs +232 -0
  65. package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +90 -10
  66. package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +410 -78
  67. package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +25 -8
  68. package/dist/builtin/workflows/skills/impeccable/scripts/lib/artifact-schema.mjs +93 -0
  69. package/dist/builtin/workflows/skills/impeccable/scripts/lib/composition-catalog.mjs +165 -0
  70. package/dist/builtin/workflows/skills/impeccable/scripts/lib/concept-catalog.mjs +329 -0
  71. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +20 -5
  72. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-paths.mjs +16 -8
  73. package/dist/builtin/workflows/skills/impeccable/scripts/lib/provider.mjs +1 -0
  74. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-deep.mjs +455 -0
  75. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-notice.mjs +169 -0
  76. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness.mjs +457 -0
  77. package/dist/builtin/workflows/skills/impeccable/scripts/lib/surface-briefs.mjs +151 -0
  78. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-slug.mjs +33 -0
  79. package/dist/builtin/workflows/skills/impeccable/scripts/lib/template-extensions.mjs +146 -0
  80. package/dist/builtin/workflows/skills/impeccable/scripts/live/completion.mjs +10 -1
  81. package/dist/builtin/workflows/skills/impeccable/scripts/live/event-validation.mjs +15 -0
  82. package/dist/builtin/workflows/skills/impeccable/scripts/live/generation-preflight.mjs +149 -0
  83. package/dist/builtin/workflows/skills/impeccable/scripts/live/poll-lanes.mjs +14 -0
  84. package/dist/builtin/workflows/skills/impeccable/scripts/live/session-store.mjs +109 -32
  85. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-lock.mjs +105 -0
  86. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-search.mjs +105 -0
  87. package/dist/builtin/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +8 -6
  88. package/dist/builtin/workflows/skills/impeccable/scripts/live/tanstack-adapter.mjs +280 -0
  89. package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +208 -68
  90. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +563 -112
  91. package/dist/builtin/workflows/skills/impeccable/scripts/live-commit-manual-edits.mjs +3 -0
  92. package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +198 -13
  93. package/dist/builtin/workflows/skills/impeccable/scripts/live-insert.mjs +24 -6
  94. package/dist/builtin/workflows/skills/impeccable/scripts/live-manual-edit-evidence.mjs +6 -1
  95. package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +44 -14
  96. package/dist/builtin/workflows/skills/impeccable/scripts/live-server.mjs +398 -33
  97. package/dist/builtin/workflows/skills/impeccable/scripts/live-status.mjs +9 -5
  98. package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +81 -67
  99. package/dist/builtin/workflows/skills/impeccable/scripts/live.mjs +7 -2
  100. package/dist/builtin/workflows/skills/impeccable/scripts/palette.mjs +76 -81
  101. package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +2 -2
  102. package/dist/builtin/workflows/skills/impeccable/scripts/serve-question.mjs +890 -0
  103. package/dist/builtin/workflows/skills/impeccable/scripts/surface-brief.mjs +74 -0
  104. package/dist/builtin/workflows/src/extension/index.bundle.mjs +201 -22
  105. package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +23 -9
  106. package/dist/builtin/workflows/src/runs/foreground/executor-stage-replay.ts +1 -0
  107. package/dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts +20 -5
  108. package/dist/builtin/workflows/src/runs/foreground/stage-control-registry.ts +10 -0
  109. package/dist/builtin/workflows/src/runs/foreground/stage-delivery-activity.ts +86 -0
  110. package/dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts +6 -2
  111. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +19 -13
  112. package/dist/builtin/workflows/src/runs/foreground/stage-runner-send-user-message.ts +8 -0
  113. package/dist/builtin/workflows/src/runs/foreground/stage-runner-types.ts +16 -0
  114. package/dist/builtin/workflows/src/tui/stage-chat-view-delivery-activity.ts +121 -0
  115. package/dist/builtin/workflows/src/tui/stage-chat-view-live-events.ts +42 -0
  116. package/dist/builtin/workflows/src/tui/stage-chat-view-state.ts +16 -0
  117. package/dist/builtin/workflows/src/tui/stage-chat-view-types.ts +4 -0
  118. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  119. package/dist/modes/interactive/components/chat-session-host-actions.js +2 -14
  120. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  121. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  122. package/dist/modes/interactive/components/chat-session-host-events.js +9 -0
  123. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  124. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +25 -0
  125. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  126. package/dist/modes/interactive/components/chat-session-host-runtime.js +53 -0
  127. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  128. package/dist/modes/interactive/components/chat-session-host.d.ts +13 -0
  129. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/chat-session-host.js +22 -1
  131. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  132. package/dist/modes/interactive/interactive-agent-events.js +9 -3
  133. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  134. package/docs/tui.md +7 -2
  135. package/docs/workflows.md +1 -1
  136. package/npm-shrinkwrap.json +23 -23
  137. package/package.json +2 -2
  138. package/dist/builtin/workflows/skills/impeccable/reference/brand.md +0 -108
  139. package/dist/builtin/workflows/skills/impeccable/reference/codex.md +0 -105
  140. package/dist/builtin/workflows/skills/impeccable/reference/interaction-design.md +0 -189
@@ -68,6 +68,15 @@ const GENERIC_FONTS = new Set([
68
68
  const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
69
69
  const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
70
70
 
71
+ // Em-dash overuse (advisory) thresholds, shared by the regex/static-HTML
72
+ // analyzer and the browser DOM check so both fire on the same saturation
73
+ // pattern. Two gates must hold: an absolute floor of EM_DASH_FLOOR dashes, and
74
+ // a density of at least one dash per EM_DASH_CHARS_PER_DASH characters of body
75
+ // text. A long article that uses a few em-dashes is left alone; a short,
76
+ // dash-per-clause page is not.
77
+ const EM_DASH_FLOOR = 8;
78
+ const EM_DASH_CHARS_PER_DASH = 500;
79
+
71
80
  // Serif faces that show up in italic-display heroes. The rule also fires when
72
81
  // the primary face is unknown but the stack ends in the generic `serif` token,
73
82
  // which catches custom/private faces with a serif fallback.
@@ -97,5 +106,7 @@ export {
97
106
  GENERIC_FONTS,
98
107
  WCAG_LARGE_TEXT_PX,
99
108
  WCAG_LARGE_BOLD_TEXT_PX,
109
+ EM_DASH_FLOOR,
110
+ EM_DASH_CHARS_PER_DASH,
100
111
  KNOWN_SERIF_FONTS,
101
112
  };
@@ -0,0 +1,336 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Deep staleness pass over Impeccable's own project artifacts.
4
+ *
5
+ * node doctor.mjs # human-readable report
6
+ * node doctor.mjs --json # machine-readable, for the skill command
7
+ * node doctor.mjs --fix # apply the mechanical migrations only
8
+ * node doctor.mjs --target <path> # pick a monorepo workspace
9
+ *
10
+ * The boot check in context.mjs reports what a session can afford to measure.
11
+ * This runs everything: git drift, per-workspace sweep, ignore-list validation
12
+ * against the live rule registry, hook script resolution.
13
+ *
14
+ * `--fix` is deliberately narrow. It performs only the migrations marked
15
+ * severity 'auto', the ones with no judgment in them: stamp the product record,
16
+ * move a sidecar out of a retired location. Anything that needs an answer from
17
+ * the user (a platform value, whether an inherited record still describes an
18
+ * app, whether a document has drifted from the code) is reported and left
19
+ * alone. Exit code is 0 unless the run itself failed; findings are not errors.
20
+ */
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+
26
+ import { loadContext, extractPlatform, resolveTargetSelection } from './context.mjs';
27
+ import { parseTargetOptions } from './lib/target-args.mjs';
28
+ import { IMPECCABLE_COMMAND, IMPECCABLE_PROVIDER_ID } from './lib/provider.mjs';
29
+ import { parseDesignMd } from './lib/design-parser.mjs';
30
+ import {
31
+ PRODUCT_SCHEMA_VERSION,
32
+ readProductSchemaVersion,
33
+ stampProductSchema,
34
+ } from './lib/artifact-schema.mjs';
35
+ import {
36
+ checkConfig,
37
+ checkDesignSidecar,
38
+ checkNativePlatformEvidence,
39
+ checkProduct,
40
+ checkProjectRoots,
41
+ checkSurfaceBriefs,
42
+ designSidecarCandidatesFor,
43
+ } from './lib/staleness.mjs';
44
+ import {
45
+ checkDesignCoverage,
46
+ checkDesignDrift,
47
+ checkDetectorIgnores,
48
+ checkHookInstallation,
49
+ checkLegacyLiveState,
50
+ checkWorkspaces,
51
+ loadKnownRuleIds,
52
+ } from './lib/staleness-deep.mjs';
53
+
54
+ const SCRIPTS_DIR = path.dirname(fileURLToPath(import.meta.url));
55
+
56
+ function safeRead(filePath) {
57
+ try {
58
+ return fs.readFileSync(filePath, 'utf-8');
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ function parseArgs(argv) {
65
+ const passthrough = [];
66
+ const flags = { json: false, fix: false, help: false };
67
+ for (const arg of argv) {
68
+ if (arg === '--json') flags.json = true;
69
+ else if (arg === '--fix') flags.fix = true;
70
+ else if (arg === '--help' || arg === '-h') flags.help = true;
71
+ else passthrough.push(arg);
72
+ }
73
+ return { flags, targetOptions: parseTargetOptions(passthrough, { strict: true }) };
74
+ }
75
+
76
+ function usage() {
77
+ return [
78
+ `Usage: node doctor.mjs [--json] [--fix] [--target <path>]`,
79
+ '',
80
+ "Report drift between this project's Impeccable artifacts and what the",
81
+ 'installed version reads: PRODUCT.md, DESIGN.md and its sidecar,',
82
+ '.impeccable/config.json, surface briefs, and the design hook.',
83
+ '',
84
+ ' --json Emit findings as JSON.',
85
+ ' --fix Apply the mechanical migrations (severity "auto") only.',
86
+ ' --target <path> Select a workspace in a monorepo.',
87
+ ].join('\n');
88
+ }
89
+
90
+ async function collect(cwd, targetOptions) {
91
+ const ctx = loadContext(cwd, targetOptions);
92
+ const projectRoot = ctx.projectRoot || cwd;
93
+ const absProductPath = ctx.productPath ? path.resolve(cwd, ctx.productPath) : null;
94
+ const absDesignPath = ctx.designPath ? path.resolve(cwd, ctx.designPath) : null;
95
+ const sidecarCandidates = designSidecarCandidatesFor(projectRoot, ctx.contextDir);
96
+ const knownRuleIds = await loadKnownRuleIds(SCRIPTS_DIR);
97
+
98
+ const selection = resolveTargetSelection(cwd, targetOptions);
99
+ const workspaceCandidates = selection?.targetCandidates || [];
100
+
101
+ const workspaceResult = checkWorkspaces({
102
+ repoRoot: ctx.repoRoot,
103
+ candidates: workspaceCandidates,
104
+ checkNativePlatformEvidence,
105
+ extractPlatform,
106
+ readFile: safeRead,
107
+ });
108
+
109
+ const findings = [
110
+ ...checkProduct(ctx.product, ctx.productPath || 'PRODUCT.md'),
111
+ ...(ctx.product
112
+ ? checkNativePlatformEvidence({
113
+ projectRoot,
114
+ platform: ctx.platform,
115
+ product: ctx.product,
116
+ productPath: ctx.productPath,
117
+ })
118
+ : []),
119
+ ...checkDesignSidecar({ designPath: absDesignPath, sidecarCandidates, projectRoot }),
120
+ ...checkDesignDrift({ designPath: absDesignPath, projectRoot }),
121
+ ...checkDesignCoverage({ design: ctx.design, designPath: ctx.designPath, parseDesignMd }),
122
+ ...checkConfig({ projectRoot, repoRoot: ctx.repoRoot }),
123
+ ...checkDetectorIgnores({ projectRoot, knownRuleIds }),
124
+ ...checkSurfaceBriefs({ candidates: ctx.surfaceBriefCandidates, projectRoot }),
125
+ ...checkHookInstallation({
126
+ projectRoot,
127
+ repoRoot: ctx.repoRoot,
128
+ providerId: IMPECCABLE_PROVIDER_ID,
129
+ }),
130
+ ...checkLegacyLiveState({ projectRoot }),
131
+ ...checkProjectRoots({
132
+ patterns: readProjectRootPatterns(ctx.repoRoot),
133
+ candidates: workspaceCandidates,
134
+ }),
135
+ ...workspaceResult.findings,
136
+ ];
137
+
138
+ return {
139
+ ctx,
140
+ projectRoot,
141
+ absProductPath,
142
+ sidecarCandidates,
143
+ findings,
144
+ workspaces: workspaceResult.workspaces,
145
+ ruleRegistryAvailable: knownRuleIds !== null,
146
+ };
147
+ }
148
+
149
+ // Read straight from disk rather than importing context.mjs's private reader.
150
+ // Only the positive/negative pattern strings matter here.
151
+ function readProjectRootPatterns(repoRoot) {
152
+ if (!repoRoot) return [];
153
+ const patterns = [];
154
+ for (const name of ['config.json', 'config.local.json']) {
155
+ try {
156
+ const raw = JSON.parse(fs.readFileSync(path.join(repoRoot, '.impeccable', name), 'utf-8'));
157
+ if (Array.isArray(raw?.projectRoots)) {
158
+ for (const entry of raw.projectRoots) {
159
+ if (typeof entry === 'string' && entry.trim()) patterns.push(entry.trim());
160
+ }
161
+ }
162
+ } catch { /* missing or malformed: nothing to check */ }
163
+ }
164
+ return patterns;
165
+ }
166
+
167
+ /**
168
+ * Apply the migrations that carry no decision. Returns what was done and what
169
+ * was deliberately left for the user.
170
+ */
171
+ function applyFixes(report) {
172
+ const applied = [];
173
+ const skipped = [];
174
+
175
+ for (const entry of report.findings) {
176
+ if (entry.severity !== 'auto') {
177
+ skipped.push({ id: entry.id, reason: 'needs a decision from the user' });
178
+ continue;
179
+ }
180
+ if (entry.id === 'design-sidecar-legacy-path') {
181
+ const canonical = report.sidecarCandidates[0];
182
+ const present = report.sidecarCandidates.find((candidate) => fs.existsSync(candidate));
183
+ if (!canonical || !present || path.resolve(canonical) === path.resolve(present)) continue;
184
+ if (fs.existsSync(canonical)) {
185
+ skipped.push({ id: entry.id, reason: `${rel(canonical, report.projectRoot)} already exists; not overwriting` });
186
+ continue;
187
+ }
188
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
189
+ fs.renameSync(present, canonical);
190
+ applied.push(`Moved ${rel(present, report.projectRoot)} to ${rel(canonical, report.projectRoot)}.`);
191
+ continue;
192
+ }
193
+ if (entry.id === 'legacy-live-state') {
194
+ // Reported, never deleted here: a running live session still reads these,
195
+ // and losing session state to a doctor run is a worse outcome than a
196
+ // stale file. The report says what to remove and when.
197
+ skipped.push({ id: entry.id, reason: 'delete by hand once no live session is running' });
198
+ continue;
199
+ }
200
+ skipped.push({ id: entry.id, reason: 'no automatic migration implemented' });
201
+ }
202
+
203
+ // Stamping the product record is additive and safe, and it is what stops a
204
+ // later version proposing an interview the user has already sat through.
205
+ const productPath = report.absProductPath;
206
+ if (productPath && report.ctx.product && readProductSchemaVersion(report.ctx.product) === null
207
+ && !report.findings.some((entry) => entry.id === 'product-schema-legacy')) {
208
+ fs.writeFileSync(productPath, stampProductSchema(report.ctx.product), 'utf-8');
209
+ applied.push(`Stamped ${rel(productPath, report.projectRoot)} as product-schema ${PRODUCT_SCHEMA_VERSION}.`);
210
+ }
211
+
212
+ return { applied, skipped };
213
+ }
214
+
215
+ function rel(filePath, root) {
216
+ const value = path.relative(root, filePath);
217
+ return value && !value.startsWith('..') ? value.split(path.sep).join('/') : filePath;
218
+ }
219
+
220
+ const SEVERITY_LABEL = {
221
+ auto: 'automatic',
222
+ mention: 'worth saying',
223
+ route: 'needs a command',
224
+ };
225
+
226
+ function renderText(report, fixes) {
227
+ const lines = [];
228
+ const { findings } = report;
229
+
230
+ lines.push(`Impeccable doctor: ${rel(report.projectRoot, process.cwd()) || '.'}`);
231
+ if (report.ctx.isMonorepo) {
232
+ lines.push(`Monorepo, repo root ${rel(report.ctx.repoRoot, process.cwd()) || '.'}.`);
233
+ }
234
+ lines.push('');
235
+
236
+ if (!findings.length) {
237
+ lines.push('No drift found. Every artifact matches what this version reads.');
238
+ } else {
239
+ const order = ['route', 'mention', 'auto'];
240
+ for (const severity of order) {
241
+ const group = findings.filter((entry) => entry.severity === severity);
242
+ if (!group.length) continue;
243
+ lines.push(`${SEVERITY_LABEL[severity]} (${group.length}):`);
244
+ for (const entry of group) {
245
+ lines.push(` ${entry.id}${entry.path ? ` [${entry.path}]` : ''}`);
246
+ lines.push(` ${entry.summary}`);
247
+ lines.push(` → ${entry.fix}`);
248
+ }
249
+ lines.push('');
250
+ }
251
+ }
252
+
253
+ if (report.workspaces.length) {
254
+ lines.push('Workspaces:');
255
+ for (const workspace of report.workspaces) {
256
+ lines.push(` ${workspace.path} product: ${workspace.productStatus}`
257
+ + ` design: ${workspace.designStatus}`
258
+ + `${workspace.platform ? ` platform: ${workspace.platform}` : ''}`);
259
+ }
260
+ lines.push('');
261
+ }
262
+
263
+ if (!report.ruleRegistryAvailable) {
264
+ lines.push('Note: the bundled detector could not be resolved, so ignored rule ids were not validated.');
265
+ lines.push('');
266
+ }
267
+
268
+ if (fixes) {
269
+ lines.push(fixes.applied.length ? 'Applied:' : 'Applied nothing.');
270
+ for (const entry of fixes.applied) lines.push(` ${entry}`);
271
+ const held = fixes.skipped.filter((entry) => entry.reason !== 'needs a decision from the user');
272
+ if (held.length) {
273
+ lines.push('Left alone:');
274
+ for (const entry of held) lines.push(` ${entry.id}: ${entry.reason}`);
275
+ }
276
+ } else if (findings.some((entry) => entry.severity === 'auto')) {
277
+ lines.push(`Run \`node doctor.mjs --fix\` to apply the automatic migrations, `
278
+ + `or \`${IMPECCABLE_COMMAND} doctor\` to work through all of them.`);
279
+ }
280
+
281
+ return lines.join('\n');
282
+ }
283
+
284
+ async function cli() {
285
+ let parsed;
286
+ try {
287
+ parsed = parseArgs(process.argv.slice(2));
288
+ } catch (err) {
289
+ process.stderr.write(`${err.message}\n`);
290
+ process.exit(1);
291
+ }
292
+ if (parsed.flags.help) {
293
+ process.stdout.write(`${usage()}\n`);
294
+ return;
295
+ }
296
+
297
+ const report = await collect(process.cwd(), parsed.targetOptions);
298
+ const fixes = parsed.flags.fix ? applyFixes(report) : null;
299
+
300
+ if (parsed.flags.json) {
301
+ process.stdout.write(`${JSON.stringify({
302
+ projectRoot: report.projectRoot,
303
+ repoRoot: report.ctx.repoRoot,
304
+ isMonorepo: report.ctx.isMonorepo,
305
+ productPath: report.ctx.productPath,
306
+ designPath: report.ctx.designPath,
307
+ platform: report.ctx.platform,
308
+ ruleRegistryAvailable: report.ruleRegistryAvailable,
309
+ findings: report.findings,
310
+ workspaces: report.workspaces,
311
+ ...(fixes ? { fixes } : {}),
312
+ }, null, 2)}\n`);
313
+ return;
314
+ }
315
+
316
+ process.stdout.write(`${renderText(report, fixes)}\n`);
317
+ }
318
+
319
+ function invokedAsScript() {
320
+ const arg = process.argv[1];
321
+ if (!arg) return false;
322
+ try {
323
+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));
324
+ } catch {
325
+ return false;
326
+ }
327
+ }
328
+
329
+ if (invokedAsScript()) {
330
+ cli().catch((err) => {
331
+ process.stderr.write(`impeccable doctor failed: ${err?.message || err}\n`);
332
+ process.exit(1);
333
+ });
334
+ }
335
+
336
+ export { collect, applyFixes, renderText };
@@ -0,0 +1,232 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * API image generation fallback: renders a mock or world board with the
4
+ * user's own OpenAI key when the harness has no native image generation.
5
+ *
6
+ * context.mjs reports availability (it checks OPENAI_API_KEY); harness-native
7
+ * generation always wins when present. This uses gpt-image-2 and spends the
8
+ * user's API credit (roughly $0.05-0.25 per image at default quality), so the
9
+ * skill states that before the first call in a session.
10
+ *
11
+ * node generate-image.mjs --prompt "..." --out mock.png [--size 1536x1024] [--quality medium]
12
+ * node generate-image.mjs --prompt-file prompt.txt --out mock.png
13
+ */
14
+ import fs from 'node:fs';
15
+ import zlib from 'node:zlib';
16
+
17
+ function arg(name, fallback = null) {
18
+ const i = process.argv.indexOf(`--${name}`);
19
+ if (i === -1) return fallback;
20
+ const v = process.argv[i + 1];
21
+ return v && !v.startsWith('--') ? v : fallback;
22
+ }
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Fake mode (IMPECCABLE_IMAGE_GEN_FAKE=1)
26
+ //
27
+ // Deterministic offline stand-in for the OpenAI call: same prompt -> identical
28
+ // bytes, no network, no key, cost line reads $0.00. Used by the new-work smoke
29
+ // suite so the concept/serve-question/image chain can run without spend. The
30
+ // output renders the prompt over a 2-3 color palette hashed from the prompt,
31
+ // plus a "SYNTHETIC COMP" corner label. SVG carries the readable text; the
32
+ // raster (.png/.webp/.jpg) fallback carries palette stripes and stows the
33
+ // prompt + marker in a PNG tEXt chunk so downstream stays a valid image.
34
+ // ---------------------------------------------------------------------------
35
+
36
+ // FNV-1a 32-bit: tiny, dependency-free, stable across runs and platforms.
37
+ function hash32(str) {
38
+ let h = 0x811c9dc5;
39
+ for (let i = 0; i < str.length; i++) {
40
+ h ^= str.charCodeAt(i);
41
+ h = Math.imul(h, 0x01000193);
42
+ }
43
+ return h >>> 0;
44
+ }
45
+
46
+ function hslToRgb(hDeg, s, l) {
47
+ const h = ((hDeg % 360) + 360) % 360 / 360;
48
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
49
+ const p = 2 * l - q;
50
+ const hue = (t) => {
51
+ let tt = t;
52
+ if (tt < 0) tt += 1;
53
+ if (tt > 1) tt -= 1;
54
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
55
+ if (tt < 1 / 2) return q;
56
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
57
+ return p;
58
+ };
59
+ return [hue(h + 1 / 3), hue(h), hue(h - 1 / 3)].map((c) => Math.round(c * 255));
60
+ }
61
+
62
+ const toHex = ([r, g, b]) =>
63
+ '#' + [r, g, b].map((c) => c.toString(16).padStart(2, '0')).join('');
64
+
65
+ // Two or three deterministic swatches derived from the prompt hash. The band
66
+ // count itself is prompt-derived, so different prompts differ in palette.
67
+ function palette(prompt) {
68
+ const h = hash32(prompt);
69
+ const base = h % 360;
70
+ const bands = 2 + (h >>> 9) % 2; // 2 or 3
71
+ const spread = 40 + (h >>> 3) % 120;
72
+ const out = [];
73
+ for (let i = 0; i < bands; i++) {
74
+ const hue = base + i * spread;
75
+ const light = 0.32 + ((h >>> (i * 5)) % 40) / 100; // 0.32 - 0.71
76
+ out.push(hslToRgb(hue, 0.55, light));
77
+ }
78
+ return out;
79
+ }
80
+
81
+ function svgFake(prompt, [w, h]) {
82
+ const colors = palette(prompt).map(toHex);
83
+ const stops = colors
84
+ .map((c, i) => `<stop offset="${Math.round((i / (colors.length - 1)) * 100)}%" stop-color="${c}"/>`)
85
+ .join('');
86
+ // Greedy word wrap tuned to the canvas width so the prompt stays legible.
87
+ const perLine = Math.max(12, Math.floor(w / 26));
88
+ const words = String(prompt).replace(/\s+/g, ' ').trim().split(' ');
89
+ const lines = [];
90
+ let cur = '';
91
+ for (const word of words) {
92
+ if ((cur + ' ' + word).trim().length > perLine) {
93
+ if (cur) lines.push(cur);
94
+ cur = word;
95
+ } else {
96
+ cur = (cur + ' ' + word).trim();
97
+ }
98
+ if (lines.length >= 10) break;
99
+ }
100
+ if (cur && lines.length < 11) lines.push(cur);
101
+ const escape = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
102
+ const fontSize = Math.round(w / 24);
103
+ const startY = h / 2 - ((lines.length - 1) * fontSize * 1.3) / 2;
104
+ const text = lines
105
+ .map((line, i) => `<text x="${w / 2}" y="${Math.round(startY + i * fontSize * 1.3)}" font-family="Helvetica, Arial, sans-serif" font-size="${fontSize}" fill="#ffffff" text-anchor="middle" dominant-baseline="middle">${escape(line)}</text>`)
106
+ .join('');
107
+ return `<?xml version="1.0" encoding="UTF-8"?>
108
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
109
+ <defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">${stops}</linearGradient></defs>
110
+ <rect width="${w}" height="${h}" fill="url(#g)"/>
111
+ <rect x="0" y="0" width="${w}" height="${h}" fill="#000000" fill-opacity="0.22"/>
112
+ ${text}
113
+ <rect x="${w - Math.round(w / 4.2)}" y="${h - Math.round(h / 16)}" width="${Math.round(w / 4.2)}" height="${Math.round(h / 16)}" fill="#000000" fill-opacity="0.55"/>
114
+ <text x="${w - Math.round(w / 8.4)}" y="${h - Math.round(h / 32)}" font-family="Helvetica, Arial, sans-serif" font-size="${Math.round(w / 60)}" letter-spacing="2" fill="#ffffff" text-anchor="middle" dominant-baseline="middle">SYNTHETIC COMP</text>
115
+ </svg>
116
+ `;
117
+ }
118
+
119
+ // Minimal valid PNG: palette stripes plus a tEXt chunk carrying the marker and
120
+ // prompt, so a .png/.webp fake stays a decodable image and still contains the
121
+ // "SYNTHETIC" bytes downstream tools look for.
122
+ function crc32(buf) {
123
+ let c = 0xffffffff;
124
+ for (let i = 0; i < buf.length; i++) {
125
+ c ^= buf[i];
126
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
127
+ }
128
+ return (c ^ 0xffffffff) >>> 0;
129
+ }
130
+
131
+ function pngChunk(type, data) {
132
+ const typeBuf = Buffer.from(type, 'latin1');
133
+ const body = Buffer.concat([typeBuf, data]);
134
+ const len = Buffer.alloc(4);
135
+ len.writeUInt32BE(data.length, 0);
136
+ const crc = Buffer.alloc(4);
137
+ crc.writeUInt32BE(crc32(body), 0);
138
+ return Buffer.concat([len, body, crc]);
139
+ }
140
+
141
+ function pngFake(prompt, [w, h]) {
142
+ const colors = palette(prompt); // [[r,g,b], ...]
143
+ const bandH = Math.ceil(h / colors.length);
144
+ // Raw image: each scanline prefixed with a 0 filter byte, RGB pixels.
145
+ const stride = w * 3;
146
+ const raw = Buffer.alloc(h * (stride + 1));
147
+ for (let y = 0; y < h; y++) {
148
+ const rowStart = y * (stride + 1);
149
+ raw[rowStart] = 0;
150
+ const [r, g, b] = colors[Math.min(colors.length - 1, Math.floor(y / bandH))];
151
+ for (let x = 0; x < w; x++) {
152
+ const p = rowStart + 1 + x * 3;
153
+ raw[p] = r;
154
+ raw[p + 1] = g;
155
+ raw[p + 2] = b;
156
+ }
157
+ }
158
+ const ihdr = Buffer.alloc(13);
159
+ ihdr.writeUInt32BE(w, 0);
160
+ ihdr.writeUInt32BE(h, 4);
161
+ ihdr[8] = 8; // bit depth
162
+ ihdr[9] = 2; // color type: truecolor RGB
163
+ const idat = zlib.deflateSync(raw, { level: 9 });
164
+ const textData = Buffer.concat([
165
+ Buffer.from('Comment', 'latin1'),
166
+ Buffer.from([0]),
167
+ Buffer.from(`SYNTHETIC COMP: ${String(prompt).replace(/\s+/g, ' ').trim()}`, 'latin1'),
168
+ ]);
169
+ return Buffer.concat([
170
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
171
+ pngChunk('IHDR', ihdr),
172
+ pngChunk('tEXt', textData),
173
+ pngChunk('IDAT', idat),
174
+ pngChunk('IEND', Buffer.alloc(0)),
175
+ ]);
176
+ }
177
+
178
+ function parseSize(sizeStr) {
179
+ const m = String(sizeStr).match(/^(\d+)x(\d+)$/);
180
+ if (!m) return [1536, 1024];
181
+ return [Number(m[1]), Number(m[2])];
182
+ }
183
+
184
+ if (process.env.IMPECCABLE_IMAGE_GEN_FAKE) {
185
+ const fakePromptFile = arg('prompt-file');
186
+ const fakePrompt = fakePromptFile ? fs.readFileSync(fakePromptFile, 'utf8') : arg('prompt');
187
+ const fakeOut = arg('out');
188
+ if (!fakePrompt || !fakeOut) {
189
+ console.error('generate-image: --prompt (or --prompt-file) and --out are required.');
190
+ process.exit(1);
191
+ }
192
+ const dims = parseSize(arg('size', '1536x1024'));
193
+ const bytes = fakeOut.endsWith('.svg')
194
+ ? Buffer.from(svgFake(fakePrompt, dims), 'utf8')
195
+ : pngFake(fakePrompt, dims);
196
+ fs.writeFileSync(fakeOut, bytes);
197
+ console.log(`IMAGE: ${fakeOut} (${dims[0]}x${dims[1]}, fake synthetic comp, $0.00, no API call)`);
198
+ process.exit(0);
199
+ }
200
+
201
+ const key = process.env.OPENAI_API_KEY;
202
+ if (!key) {
203
+ console.error('generate-image: OPENAI_API_KEY is not set; use the harness-native image tool instead.');
204
+ process.exit(1);
205
+ }
206
+ const promptFile = arg('prompt-file');
207
+ const prompt = promptFile ? fs.readFileSync(promptFile, 'utf8') : arg('prompt');
208
+ const out = arg('out');
209
+ if (!prompt || !out) {
210
+ console.error('generate-image: --prompt (or --prompt-file) and --out are required.');
211
+ process.exit(1);
212
+ }
213
+ const size = arg('size', '1536x1024');
214
+ const quality = arg('quality', 'medium');
215
+
216
+ const response = await fetch('https://api.openai.com/v1/images/generations', {
217
+ method: 'POST',
218
+ headers: { Authorization: `Bearer ${key}`, 'content-type': 'application/json' },
219
+ body: JSON.stringify({ model: 'gpt-image-2', prompt, size, quality, n: 1 }),
220
+ });
221
+ if (!response.ok) {
222
+ console.error(`generate-image: API error ${response.status}: ${(await response.text()).slice(0, 300)}`);
223
+ process.exit(1);
224
+ }
225
+ const json = await response.json();
226
+ const b64 = json?.data?.[0]?.b64_json;
227
+ if (!b64) {
228
+ console.error('generate-image: no image in response');
229
+ process.exit(1);
230
+ }
231
+ fs.writeFileSync(out, Buffer.from(b64, 'base64'));
232
+ console.log(`IMAGE: ${out} (${size}, ${quality}, gpt-image-2, billed to your OpenAI key)`);