@estiva-app/ui 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +38 -2
  2. package/dist/gates/app-checks.d.ts +40 -0
  3. package/dist/gates/app-checks.d.ts.map +1 -0
  4. package/dist/gates/chunk-AUXD4GCY.js +478 -0
  5. package/dist/gates/chunk-AUXD4GCY.js.map +7 -0
  6. package/dist/gates/chunk-ZGJ2J5NU.js +754 -0
  7. package/dist/gates/chunk-ZGJ2J5NU.js.map +7 -0
  8. package/dist/gates/cli.d.ts +2 -0
  9. package/dist/gates/cli.d.ts.map +1 -0
  10. package/dist/gates/cli.js +46 -0
  11. package/dist/gates/cli.js.map +7 -0
  12. package/dist/gates/count.d.ts +20 -0
  13. package/dist/gates/count.d.ts.map +1 -0
  14. package/dist/gates/create-app-cli.d.ts +2 -0
  15. package/dist/gates/create-app-cli.d.ts.map +1 -0
  16. package/dist/gates/create-app.d.ts +23 -0
  17. package/dist/gates/create-app.d.ts.map +1 -0
  18. package/dist/gates/create-app.js +30 -0
  19. package/dist/gates/create-app.js.map +7 -0
  20. package/dist/gates/gate-config.d.ts +44 -0
  21. package/dist/gates/gate-config.d.ts.map +1 -0
  22. package/dist/gates/hook.d.ts +18 -0
  23. package/dist/gates/hook.d.ts.map +1 -0
  24. package/dist/gates/index.d.ts +30 -0
  25. package/dist/gates/index.d.ts.map +1 -0
  26. package/dist/gates/index.js +417 -0
  27. package/dist/gates/index.js.map +7 -0
  28. package/dist/gates/status.d.ts +88 -0
  29. package/dist/gates/status.d.ts.map +1 -0
  30. package/dist/gates/token-lint.d.ts +26 -0
  31. package/dist/gates/token-lint.d.ts.map +1 -0
  32. package/package.json +30 -4
  33. package/src/gates/app-checks.ts +226 -0
  34. package/src/gates/cli.ts +61 -0
  35. package/src/gates/count.ts +76 -0
  36. package/src/gates/create-app-cli.ts +25 -0
  37. package/src/gates/create-app.test.ts +72 -0
  38. package/src/gates/create-app.ts +797 -0
  39. package/src/gates/gate-config.ts +78 -0
  40. package/src/gates/gates.test.ts +194 -0
  41. package/src/gates/hook.ts +111 -0
  42. package/src/gates/index.ts +30 -0
  43. package/src/gates/status.ts +545 -0
  44. package/src/gates/token-lint.ts +231 -0
@@ -0,0 +1,545 @@
1
+ /// <reference types="node" />
2
+ /**
3
+ * gates:status — where the UI Guardrails project stands, read from the code.
4
+ *
5
+ * estiva-gates status one row per ticket
6
+ * estiva-gates status --detail every check under every row
7
+ * estiva-gates status --json machine output, read by estiva-ui's run
8
+ * estiva-gates status --app web the app sits in `web/`, as Ship's does
9
+ *
10
+ * Every row is decided by checks on real files, a real lint run or a real
11
+ * GitHub setting. Nothing here reads a list that someone ticks by hand.
12
+ *
13
+ * **One copy, in the package** (docs/GATES.md §23). Until UIG-10 this engine was
14
+ * `scripts/gates-status.mjs`, the same file copied by hand into estiva-ui, Peek
15
+ * and Ship, with estiva-ui warning when the copies drifted. Now it ships here,
16
+ * and a repo runs it with `estiva-gates status`. A repo still carrying its own
17
+ * copy is named as one when estiva-ui runs it; UIG-32 moves Peek and Ship off
18
+ * theirs.
19
+ *
20
+ * What differs per repo is `scripts/gates-checks.mjs`, beside the app: its
21
+ * checks, or the checks every app runs (`appChecks`) plus its own. It sits with
22
+ * the app because it imports the package — `web/scripts/` in Ship, whose app,
23
+ * and whose install, are in `web/` (UIG-32).
24
+ *
25
+ * The rows and the reasons for each check are in estiva-ui docs/GATES.md §15
26
+ * and §17.
27
+ */
28
+ import { execFileSync } from 'node:child_process'
29
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
30
+ import { createRequire } from 'node:module'
31
+ import { join, relative, resolve } from 'node:path'
32
+ import { pathToFileURL } from 'node:url'
33
+ import type { ESLint as ESLintClass } from 'eslint'
34
+
35
+ export type CheckResult = { result: 'pass' | 'fail' | 'part' | 'unknown'; detail: string }
36
+ type Maybe<T> = T | Promise<T>
37
+
38
+ export interface LintProbe {
39
+ /** The folder ESLint runs from, relative to the repo: `web` in Ship. */
40
+ cwd?: string
41
+ /** The config file, relative to `cwd`. */
42
+ config: string
43
+ /** The path the text is linted as, relative to `cwd`. Nothing is written. */
44
+ file: string
45
+ code: string
46
+ expect: 'error' | 'warning' | 'none'
47
+ /** Words the expected message must contain. */
48
+ mentions?: string
49
+ }
50
+
51
+ /** The helpers a checks file is written with. */
52
+ export interface GateHelpers {
53
+ PASS(detail: string): CheckResult
54
+ FAIL(detail: string): CheckResult
55
+ PART(detail: string): CheckResult
56
+ UNKNOWN(detail: string): CheckResult
57
+ exists(rel: string): boolean
58
+ read(rel: string): string
59
+ listFiles(rel: string, test: (name: string, path: string) => boolean): string[]
60
+ file(rel: string): CheckResult
61
+ committed(rel: string): CheckResult
62
+ contains(rel: string, needle: string | RegExp, label?: string): CheckResult
63
+ lacks(rel: string, needle: string | RegExp, label?: string): CheckResult
64
+ script(pkgRel: string, name: string): CheckResult
65
+ loads(rel: string): Promise<CheckResult>
66
+ ci(script: string | RegExp): CheckResult
67
+ ciJob(job: string, script: string): CheckResult
68
+ hook(settingsRel: string, needle: string): CheckResult
69
+ json(rel: string, test?: (data: unknown) => boolean, label?: string): CheckResult
70
+ lint(probe: LintProbe): Promise<CheckResult>
71
+ protectedBranch(pattern: RegExp): CheckResult
72
+ gh(args: string[], label: string): CheckResult
73
+ share(files: string[], test: (file: string) => boolean, label: string): CheckResult
74
+ }
75
+
76
+ export interface GateCheck {
77
+ what: string
78
+ run: () => Maybe<CheckResult>
79
+ aggregate?: boolean
80
+ }
81
+ export interface GateTicket {
82
+ ref: string
83
+ title?: string
84
+ owner: boolean
85
+ checks: GateCheck[]
86
+ }
87
+ export interface TicketListEntry {
88
+ ref: string
89
+ owner: string
90
+ title: string
91
+ parts?: string[]
92
+ aggregate?: boolean
93
+ }
94
+ export interface GateSpec {
95
+ repo: string
96
+ tickets: GateTicket[]
97
+ /** estiva-ui only: every ticket, and the repos it joins in. */
98
+ all?: TicketListEntry[]
99
+ /** estiva-ui only: the repos beside it. `app` is the folder its app sits in: `web` in Ship. */
100
+ siblings?: { name: string; path: string; env: string; app?: string }[]
101
+ }
102
+
103
+ interface Row {
104
+ ref: string
105
+ title?: string
106
+ owner?: boolean
107
+ ownerRepo?: string
108
+ checks: (CheckResult & { repo: string; what: string })[]
109
+ status?: string
110
+ aggregate?: boolean
111
+ }
112
+ interface Report {
113
+ schema: 1
114
+ repo: string
115
+ branch: string | null
116
+ commit: string | null
117
+ engine: string
118
+ rows: Row[]
119
+ }
120
+
121
+ const { version } = createRequire(import.meta.url)('../../package.json') as { version: string }
122
+ /** What a report says ran it. A copy of the old script reports a hash instead. */
123
+ export const ENGINE = `@estiva-app/ui@${version}`
124
+
125
+ const PASS = (detail: string): CheckResult => ({ result: 'pass', detail })
126
+ const FAIL = (detail: string): CheckResult => ({ result: 'fail', detail })
127
+ const PART = (detail: string): CheckResult => ({ result: 'part', detail })
128
+ const UNKNOWN = (detail: string): CheckResult => ({ result: 'unknown', detail })
129
+ const said = (e: unknown) => {
130
+ const err = e as { stdout?: unknown; stderr?: unknown; message?: string; code?: string }
131
+ return { text: `${err.stdout ?? ''}${err.stderr ?? ''}`, message: String(err.message ?? e), code: err.code }
132
+ }
133
+
134
+ /** The helpers, bound to one repository. */
135
+ export function helpers(ROOT: string): GateHelpers {
136
+ const abs = (rel: string) => resolve(ROOT, rel)
137
+ const exists = (rel: string) => existsSync(abs(rel))
138
+ const read = (rel: string) => readFileSync(abs(rel), 'utf8')
139
+ const git = (...a: string[]) => {
140
+ try {
141
+ return execFileSync('git', a, { cwd: ROOT, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()
142
+ } catch {
143
+ return null
144
+ }
145
+ }
146
+ const listFiles = (rel: string, test: (name: string, path: string) => boolean) => {
147
+ const out: string[] = []
148
+ const walk = (dir: string) => {
149
+ if (!existsSync(dir)) return
150
+ for (const name of readdirSync(dir)) {
151
+ if (['node_modules', '.git', 'dist', 'storybook-static', '.verify-shots'].includes(name)) continue
152
+ const p = join(dir, name)
153
+ if (statSync(p).isDirectory()) walk(p)
154
+ else if (test(name, p)) out.push(relative(ROOT, p).replace(/\\/g, '/'))
155
+ }
156
+ }
157
+ walk(abs(rel))
158
+ return out
159
+ }
160
+ const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
161
+
162
+ return {
163
+ PASS, FAIL, PART, UNKNOWN, exists, read, listFiles,
164
+
165
+ file(rel) {
166
+ return exists(rel) ? PASS(`${rel} exists`) : FAIL(`${rel} does not exist`)
167
+ },
168
+
169
+ committed(rel) {
170
+ if (!exists(rel)) return FAIL(`${rel} does not exist`)
171
+ return git('ls-files', '--error-unmatch', rel) ? PASS(`${rel} is committed`) : FAIL(`${rel} exists but is not committed`)
172
+ },
173
+
174
+ contains(rel, needle, label) {
175
+ if (!exists(rel)) return FAIL(`${rel} does not exist`)
176
+ const hit = typeof needle === 'string' ? read(rel).includes(needle) : needle.test(read(rel))
177
+ return hit ? PASS(label ?? `${rel} has ${needle}`) : FAIL(label ? `not yet: ${label}` : `${rel} has no ${needle}`)
178
+ },
179
+
180
+ lacks(rel, needle, label) {
181
+ if (!exists(rel)) return FAIL(`${rel} does not exist`)
182
+ const hit = typeof needle === 'string' ? read(rel).includes(needle) : needle.test(read(rel))
183
+ return hit ? FAIL(`${rel} still has ${needle}`) : PASS(label ?? `${rel} has no ${needle}`)
184
+ },
185
+
186
+ script(pkgRel, name) {
187
+ if (!exists(pkgRel)) return FAIL(`${pkgRel} does not exist`)
188
+ const cmd = (JSON.parse(read(pkgRel)) as { scripts?: Record<string, string> }).scripts?.[name]
189
+ return cmd ? PASS(`${pkgRel} runs "${name}": ${cmd}`) : FAIL(`${pkgRel} has no "${name}" script`)
190
+ },
191
+
192
+ async loads(rel) {
193
+ if (!exists(rel)) return FAIL(`${rel} does not exist`)
194
+ try {
195
+ const mod = (await import(pathToFileURL(abs(rel)).href)) as { default?: unknown }
196
+ return mod.default ? PASS(`${rel} loads`) : FAIL(`${rel} has no default export`)
197
+ } catch (e) {
198
+ return FAIL(`${rel} does not load: ${said(e).message.split('\n')[0]}`)
199
+ }
200
+ },
201
+
202
+ /** A workflow step that runs `npm run <script>`; a regex matches the script name. */
203
+ ci(script) {
204
+ const files = listFiles('.github/workflows', (n) => /\.ya?ml$/.test(n))
205
+ const name = typeof script === 'string' ? escape(script) : script.source
206
+ const step = new RegExp(`npm run (${name})(?![\\w:-])`)
207
+ for (const f of files) {
208
+ const m = read(f).match(step)
209
+ if (m) return PASS(`${f} runs npm run ${m[1]}`)
210
+ }
211
+ return FAIL(`no workflow runs npm run ${script}`)
212
+ },
213
+
214
+ /**
215
+ * A workflow job, by its id, with a step that runs `npm run <script>`. Branch
216
+ * protection requires a whole job by its name, so a required check needs the
217
+ * job, not the step somewhere (UIG-6). A job is a key two spaces in under
218
+ * `jobs:`, and ends at the next line that is not indented further; a comment
219
+ * line does not count.
220
+ */
221
+ ciJob(job, script) {
222
+ const files = listFiles('.github/workflows', (n) => /\.ya?ml$/.test(n))
223
+ const header = new RegExp(`^ ${escape(job)}:\\s*(#.*)?$`)
224
+ const step = new RegExp(`^(?!\\s*#).*npm run ${escape(script)}(?![\\w:-])`, 'm')
225
+ for (const f of files) {
226
+ const lines = read(f).split(/\r?\n/)
227
+ const from = lines.findIndex((l) => /^jobs:\s*$/.test(l))
228
+ const start = from === -1 ? -1 : lines.findIndex((l, i) => i > from && header.test(l))
229
+ if (start === -1) continue
230
+ const end = lines.findIndex((l, i) => i > start && /^ {0,2}\S/.test(l))
231
+ const body = lines.slice(start + 1, end === -1 ? undefined : end).join('\n')
232
+ return step.test(body) ? PASS(`${f}: the job ${job} runs npm run ${script}`) : FAIL(`${f}: the job ${job} does not run npm run ${script}`)
233
+ }
234
+ return FAIL(`no workflow has a job ${job}`)
235
+ },
236
+
237
+ hook(settingsRel, needle) {
238
+ if (!exists(settingsRel)) return FAIL(`${settingsRel} does not exist`)
239
+ let s: { hooks?: { PreToolUse?: { hooks?: { command?: string }[] }[] } }
240
+ try {
241
+ s = JSON.parse(read(settingsRel))
242
+ } catch {
243
+ return FAIL(`${settingsRel} is not valid JSON`)
244
+ }
245
+ const commands = (s.hooks?.PreToolUse ?? []).flatMap((m) => (m.hooks ?? []).map((x) => x.command ?? ''))
246
+ const hit = commands.find((c) => c.includes(needle))
247
+ if (hit) return PASS(`${settingsRel} has a PreToolUse hook running ${needle}`)
248
+ return FAIL(commands.length ? `${settingsRel} has PreToolUse hooks, none running ${needle}` : `${settingsRel} has no PreToolUse hook`)
249
+ },
250
+
251
+ json(rel, test = () => true, label) {
252
+ if (!exists(rel)) return FAIL(`${rel} does not exist`)
253
+ let data: unknown
254
+ try {
255
+ data = JSON.parse(read(rel))
256
+ } catch {
257
+ return FAIL(`${rel} is not valid JSON`)
258
+ }
259
+ if (!git('ls-files', '--error-unmatch', rel)) return FAIL(`${rel} is not committed`)
260
+ return test(data) ? PASS(label ?? `${rel} is committed and parses`) : FAIL(`${rel} parses, but ${label ?? 'fails its test'}`)
261
+ },
262
+
263
+ /** Lints a line of code that is never written to disk, the way the hook will. */
264
+ async lint({ cwd = '.', config, file, code, expect, mentions }) {
265
+ const cfg = join(cwd, config)
266
+ if (!exists(cfg)) return FAIL(`${cfg} does not exist`)
267
+ let ESLint: typeof ESLintClass
268
+ try {
269
+ const req = createRequire(join(abs(cwd), 'package.json'))
270
+ ;({ ESLint } = (await import(pathToFileURL(req.resolve('eslint')).href)) as { ESLint: typeof ESLintClass })
271
+ } catch (e) {
272
+ return UNKNOWN(`could not load eslint from ${cwd}: ${said(e).message.split('\n')[0]}`)
273
+ }
274
+ let results: ESLintClass.LintResult[]
275
+ try {
276
+ const eslint = new ESLint({ cwd: abs(cwd), overrideConfigFile: config })
277
+ results = await eslint.lintText(code, { filePath: join(abs(cwd), file), warnIgnored: true })
278
+ } catch (e) {
279
+ return UNKNOWN(`${cfg} could not lint ${file}: ${said(e).message.split('\n')[0]}`)
280
+ }
281
+ const messages = results.flatMap((r) => r.messages)
282
+ const ignored = messages.some((m) => /ignored/i.test(m.message) && !m.ruleId)
283
+ const fatal = messages.find((m) => m.fatal && !/ignored/i.test(m.message))
284
+ if (fatal) return UNKNOWN(`${file} did not parse: ${fatal.message}`)
285
+ const want = expect === 'error' ? 2 : expect === 'warning' ? 1 : 0
286
+ if (want === 0) {
287
+ const any = messages.filter((m) => m.ruleId && m.severity === 2)
288
+ return any.length ? FAIL(`${file} gets an error it should not: ${any[0].message}`) : PASS(`${file}: no error${ignored ? ' (not linted)' : ''}`)
289
+ }
290
+ if (ignored) return FAIL(`${cfg} does not lint ${file}`)
291
+ const hit = messages.find((m) => m.ruleId && m.severity === want && (!mentions || m.message.includes(mentions)))
292
+ const kind = want === 2 ? 'error' : 'warning'
293
+ return hit ? PASS(`${file} gets ${want === 2 ? 'an' : 'a'} ${kind}: ${hit.message}`) : FAIL(`${file} gets no ${kind}${mentions ? ` naming ${mentions}` : ''}`)
294
+ },
295
+
296
+ /**
297
+ * A GitHub setting, not a file, so it is asked of GitHub: the checks a merge
298
+ * into the default branch must pass, from the rulesets in force on it
299
+ * (`rules/branches/<branch>`, which anyone who can read the repository may
300
+ * see) and from classic protection as `branches/<branch>` reports it. Not
301
+ * `branches/<branch>/protection`: GitHub answers "Not Found" there to anyone
302
+ * who is not an admin, and it knows nothing of rulesets (UIG-6).
303
+ */
304
+ protectedBranch(pattern) {
305
+ const url = git('remote', 'get-url', 'origin')
306
+ const slug = url?.match(/github\.com[:/](.+?)(?:\.git)?$/)?.[1]
307
+ if (!slug) return UNKNOWN('no GitHub remote')
308
+ const branch = (git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD') ?? 'origin/main').replace(/^origin\//, '')
309
+ const ask = (path: string) => JSON.parse(execFileSync('gh', ['api', path], { stdio: ['ignore', 'pipe', 'pipe'], timeout: 20000 }).toString())
310
+ let rules: { type: string; parameters?: { required_status_checks?: { context: string }[] } }[]
311
+ let classic: { contexts?: string[]; checks?: { context: string }[] } | undefined
312
+ try {
313
+ rules = ask(`repos/${slug}/rules/branches/${branch}`)
314
+ classic = ask(`repos/${slug}/branches/${branch}`).protection?.required_status_checks
315
+ } catch (e) {
316
+ const s = said(e)
317
+ return UNKNOWN(`could not ask GitHub (${s.code === 'ENOENT' ? 'gh is not installed' : s.text.split('\n')[0] || s.message})`)
318
+ }
319
+ const names = [
320
+ ...rules.filter((r) => r.type === 'required_status_checks').flatMap((r) => r.parameters?.required_status_checks ?? []).map((c) => c.context),
321
+ ...(classic?.contexts ?? []),
322
+ ...(classic?.checks ?? []).map((c) => c.context),
323
+ ]
324
+ const hit = names.find((n) => pattern.test(n))
325
+ if (hit) return PASS(`${slug} ${branch} requires "${hit}"`)
326
+ return FAIL(names.length ? `${slug} ${branch} requires ${names.map((n) => `"${n}"`).join(', ')}, none matching ${pattern}` : `${slug} ${branch} requires no check to merge`)
327
+ },
328
+
329
+ gh(args, label) {
330
+ try {
331
+ execFileSync('gh', args, { stdio: ['ignore', 'pipe', 'pipe'], timeout: 20000 })
332
+ return PASS(label)
333
+ } catch (e) {
334
+ const s = said(e)
335
+ if (/could not resolve|not found|HTTP 404/i.test(s.text)) return FAIL(`not yet: ${label}`)
336
+ return UNKNOWN(`could not ask GitHub (${s.code === 'ENOENT' ? 'gh is not installed' : s.text.split('\n')[0] || s.message})`)
337
+ }
338
+ },
339
+
340
+ /** How many of `files` pass `test`: all is a pass, some is a part. */
341
+ share(files, test, label) {
342
+ if (!files.length) return FAIL(`no files to check for: ${label}`)
343
+ const ok = files.filter(test).length
344
+ const detail = `${ok} of ${files.length}: ${label}`
345
+ return ok === files.length ? PASS(detail) : ok ? PART(detail) : FAIL(detail)
346
+ },
347
+ }
348
+ }
349
+
350
+ // ── running the checks ─────────────────────────────────────────────────────
351
+
352
+ const STATUS: Record<string, string> = { done: '✅', started: '🚧', none: '⬜', unknown: '❔' }
353
+
354
+ function statusOf(checks: CheckResult[]) {
355
+ const n = (r: CheckResult['result']) => checks.filter((c) => c.result === r).length
356
+ const pass = n('pass'), part = n('part'), fail = n('fail'), unknown = n('unknown')
357
+ if (!checks.length) return 'unknown'
358
+ if (pass === checks.length) return 'done'
359
+ if (pass + part > 0) return fail === 0 && unknown > 0 ? 'unknown' : 'started'
360
+ return fail > 0 ? 'none' : 'unknown'
361
+ }
362
+
363
+ async function runRepo(ROOT: string, app: string, h: GateHelpers): Promise<{ spec: GateSpec; report: Report }> {
364
+ // The checks file sits with the app, because it imports `appChecks` from the
365
+ // package: in Ship that install is `web/node_modules`, not the repo's top
366
+ // folder (UIG-32). Everything it names is still read from the repo's top.
367
+ const checksFile = join(ROOT, app, 'scripts', 'gates-checks.mjs')
368
+ const define = ((await import(pathToFileURL(checksFile).href)) as { default: (h: GateHelpers) => GateSpec }).default
369
+ const spec = define(h)
370
+ const git = (...a: string[]) => {
371
+ try {
372
+ return execFileSync('git', a, { cwd: ROOT, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()
373
+ } catch {
374
+ return null
375
+ }
376
+ }
377
+ const rows: Row[] = []
378
+ for (const t of spec.tickets) {
379
+ const checks: Row['checks'] = []
380
+ for (const c of t.checks ?? []) {
381
+ if (c.aggregate) continue
382
+ let r: CheckResult
383
+ try {
384
+ r = await c.run()
385
+ } catch (e) {
386
+ r = UNKNOWN(`the check threw: ${said(e).message}`)
387
+ }
388
+ checks.push({ repo: spec.repo, what: c.what, ...r })
389
+ }
390
+ rows.push({ ref: t.ref, title: t.title, owner: t.owner, checks })
391
+ }
392
+ return { spec, report: { schema: 1, repo: spec.repo, branch: git('rev-parse', '--abbrev-ref', 'HEAD'), commit: git('rev-parse', '--short', 'HEAD'), engine: ENGINE, rows } }
393
+ }
394
+
395
+ /**
396
+ * Another repository's report. A repo on the package's engine runs it from its
397
+ * own install; a repo still carrying `scripts/gates-status.mjs` runs that copy.
398
+ *
399
+ * `app` is the folder that repo's app sits in — `web` in Ship — where its
400
+ * install and its checks file are. The report is still of the whole repo.
401
+ */
402
+ function runSibling(dir: string, app: string, shown: string): { report?: Report; error?: string } {
403
+ const copy = join(dir, 'scripts', 'gates-status.mjs')
404
+ const installed = createRequire(join(dir, app, 'package.json'))
405
+ let script = copy
406
+ const args = ['--json']
407
+ if (!existsSync(copy)) {
408
+ try {
409
+ script = join(installed.resolve('@estiva-app/ui/package.json'), '..', 'dist', 'gates', 'cli.js')
410
+ args.unshift('status')
411
+ if (app !== '.') args.push('--app', app)
412
+ } catch {
413
+ return { error: `${shown} has neither its own gates-status.mjs nor @estiva-app/ui installed${app === '.' ? '' : ` in ${app}`}` }
414
+ }
415
+ if (!existsSync(script)) return { error: `${shown} has an @estiva-app/ui with no gates engine: install 0.21.0 or later` }
416
+ }
417
+ try {
418
+ const out = execFileSync(process.execPath, [script, ...args], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], timeout: 300000, maxBuffer: 16 * 1024 * 1024 })
419
+ return { report: JSON.parse(out.toString()) as Report }
420
+ } catch (e) {
421
+ const err = e as { stderr?: unknown; message?: string }
422
+ return { error: `its gates:status failed: ${String(err.stderr ?? err.message).split('\n').filter(Boolean).slice(-1)[0]}` }
423
+ }
424
+ }
425
+
426
+ function pad(s: string, n: number) {
427
+ const len = [...s].length
428
+ return len >= n ? s : s + ' '.repeat(n - len)
429
+ }
430
+
431
+ function printRows(rows: Row[], { showOwner, detail }: { showOwner: boolean; detail: boolean }) {
432
+ const lines: string[] = []
433
+ const width = Math.max(...rows.map((r) => [...(r.title ?? '')].length))
434
+ for (const r of rows) {
435
+ const pass = r.checks.filter((c) => c.result === 'pass').length
436
+ const count = r.checks.length ? `${pass} of ${r.checks.length}` : 'no checks here'
437
+ lines.push(`${STATUS[r.status ?? 'unknown']} ${pad(r.ref, 7)} ${pad(r.title ?? '', width)} ${showOwner ? pad(r.ownerRepo ?? '', 10) : ''}${count}`)
438
+ if (detail || r.status === 'started' || r.status === 'unknown') {
439
+ for (const c of r.checks) {
440
+ const mark = { pass: '✓', part: '½', fail: '✗', unknown: '?' }[c.result]
441
+ lines.push(` ${mark} ${showOwner ? `${pad(c.repo, 10)} ` : ''}${c.what} — ${c.detail}`)
442
+ }
443
+ }
444
+ }
445
+ return lines.join('\n')
446
+ }
447
+
448
+ function summary(rows: Row[]) {
449
+ const n = (s: string) => rows.filter((r) => r.status === s).length
450
+ return `${STATUS.done} ${n('done')} done · ${STATUS.started} ${n('started')} started · ${STATUS.none} ${n('none')} not started · ${STATUS.unknown} ${n('unknown')} could not check`
451
+ }
452
+
453
+ export interface StatusOptions {
454
+ /** The repository to report on. */
455
+ root?: string
456
+ /** The folder that holds the app, relative to `root`: `web` in Ship, `.` elsewhere. */
457
+ app?: string
458
+ json?: boolean
459
+ detail?: boolean
460
+ }
461
+
462
+ /** Print where the project stands. Returns what was printed, or the JSON report. */
463
+ export async function runStatus({ root = process.cwd(), app = '.', json = false, detail = false }: StatusOptions = {}): Promise<string> {
464
+ const ROOT = resolve(root)
465
+ const h = helpers(ROOT)
466
+ const shown = (dir: string) => (relative(ROOT, dir) || dir).replace(/\\/g, '/')
467
+ const { spec, report } = await runRepo(ROOT, app, h)
468
+
469
+ if (json) return JSON.stringify(report)
470
+
471
+ const out: string[] = []
472
+ out.push('UI Guardrails · gates:status', 'Read from the code. Nothing here is a hand-ticked list.', '')
473
+ out.push(`${pad(spec.repo, 10)} ${report.branch} @ ${report.commit}`)
474
+
475
+ if (!spec.all) {
476
+ // A sibling repo on its own: its own rows, then its parts of rows owned elsewhere.
477
+ const own = report.rows.filter((r) => r.owner).map((r) => ({ ...r, ownerRepo: spec.repo, status: statusOf(r.checks) }))
478
+ const parts = report.rows.filter((r) => !r.owner).map((r) => ({ ...r, ownerRepo: '', status: statusOf(r.checks) }))
479
+ out.push('', `Tickets ${spec.repo} owns (${own.length}):`, printRows(own, { showOwner: false, detail }))
480
+ out.push('', `Parts of tickets another repo owns, checked here (${parts.length}):`, printRows(parts, { showOwner: false, detail }))
481
+ out.push('', 'For every ticket across the repos, run npm run gates:status in estiva-ui.')
482
+ return out.join('\n')
483
+ }
484
+
485
+ // estiva-ui: gather the sibling checkouts and join everything into one row per ticket.
486
+ const reports: Report[] = [report]
487
+ const found: { name: string; note: string; missing?: boolean }[] = []
488
+ for (const s of spec.siblings ?? []) {
489
+ const dir = resolve(ROOT, process.env[s.env] ?? s.path)
490
+ if (!existsSync(join(dir, 'package.json'))) {
491
+ found.push({ name: s.name, note: `not found at ${shown(dir)} (set ${s.env} to point at it)`, missing: true })
492
+ continue
493
+ }
494
+ const r = runSibling(dir, s.app ?? '.', shown(dir))
495
+ if (!r.report) {
496
+ found.push({ name: s.name, note: r.error ?? 'no report', missing: true })
497
+ continue
498
+ }
499
+ const copy = r.report.engine !== ENGINE ? (r.report.engine.startsWith('@estiva-app/ui@') ? ` · on ${r.report.engine}'s engine` : ' · runs its own copy of the status engine; UIG-32 moves it onto the package') : ''
500
+ found.push({ name: s.name, note: `${r.report.branch} @ ${r.report.commit}, found at ${shown(dir)}${copy}` })
501
+ reports.push(r.report)
502
+ }
503
+ for (const f of found) out.push(`${pad(f.name, 10)} ${f.note}`)
504
+
505
+ const problems: string[] = []
506
+ const known = new Set(spec.all.map((t) => t.ref))
507
+ for (const rep of reports) {
508
+ for (const r of rep.rows.filter((r) => !known.has(r.ref))) problems.push(`${rep.repo} reports ${r.ref}, which is not one of the tickets`)
509
+ }
510
+ const rows: Row[] = spec.all.map((t) => {
511
+ const pieces = reports.flatMap((rep) => rep.rows.filter((r) => r.ref === t.ref).map((r) => ({ rep, r })))
512
+ const claims = pieces.filter((p) => p.r.owner).map((p) => p.rep.repo)
513
+ const ownerMissing = found.some((f) => f.name === t.owner && f.missing)
514
+ if (!ownerMissing && (claims.length !== 1 || claims[0] !== t.owner)) {
515
+ problems.push(`${t.ref}: should be owned by ${t.owner}, is claimed by ${claims.join(' and ') || 'no repo'}`)
516
+ }
517
+ for (const p of pieces.filter((p) => !p.r.owner && !(t.parts ?? []).includes(p.rep.repo))) {
518
+ problems.push(`${t.ref}: ${p.rep.repo} checks a part of it, but the ticket list does not name ${p.rep.repo}`)
519
+ }
520
+ const checks = pieces.flatMap((p) => p.r.checks)
521
+ for (const f of found.filter((f) => f.missing)) {
522
+ if ((t.parts ?? []).includes(f.name) || t.owner === f.name) checks.push({ repo: f.name, what: `${f.name}'s part`, result: 'unknown', detail: f.note })
523
+ }
524
+ return { ref: t.ref, title: t.title, ownerRepo: t.owner, checks, aggregate: t.aggregate }
525
+ })
526
+ for (const row of rows) row.status = statusOf(row.checks)
527
+ for (const row of rows.filter((r) => r.aggregate)) {
528
+ const others = rows.filter((r) => r !== row)
529
+ const done = others.filter((r) => r.status === 'done').length
530
+ row.checks.push({ repo: 'all', what: 'every other ticket is done', ...(done === others.length ? PASS(`${done} of ${others.length} done`) : FAIL(`${done} of ${others.length} done`)) })
531
+ row.status = statusOf(row.checks)
532
+ }
533
+
534
+ out.push('', printRows(rows, { showOwner: true, detail }), '', summary(rows))
535
+ const owners = Object.entries(rows.reduce<Record<string, number>>((a, r) => ({ ...a, [r.ownerRepo ?? '']: (a[r.ownerRepo ?? ''] ?? 0) + 1 }), {}))
536
+ .map(([k, v]) => `${k} ${v}`)
537
+ .join(', ')
538
+ out.push(`${rows.length} tickets. Owned by ${owners}.`)
539
+ const unchecked = found.filter((f) => f.missing && spec.all!.some((t) => t.owner === f.name)).map((f) => f.name)
540
+ if (problems.length) out.push(`⚠️ Ownership does not add up:\n ${problems.join('\n ')}`)
541
+ else if (unchecked.length) out.push(`❔ Ownership not fully checked: ${unchecked.join(' and ')} could not be read.`)
542
+ else out.push('✅ Each ticket is owned by exactly one repo, and every repo agrees.')
543
+ if (!detail) out.push('Add -- --detail to see every check.')
544
+ return out.join('\n')
545
+ }