@starci/hfs 4.7.16 → 4.7.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.7.17 - 2026-10-21
4
+ - Fixed: the sonar row of `starci app release gate --sonar` no longer passes on the scanner's exit code alone: it reads `.scannerwork/report-task.txt`, polls `api/ce/task` until the analysis ends and reads `api/qualitygates/project_status` with the same token; ERROR is red as `RELEASE_SONAR_GATE_FAILED` naming each failed condition, a 600-second wait is `RELEASE_SONAR_GATE_TIMEOUT` and an unreadable answer `RELEASE_SONAR_GATE_UNREADABLE`; canon pins follow the matching package cohort.
5
+
6
+ - Fixed: `npx @starci/cli app scaffold` works from the published packages alone: the Sonar exclusions come from the jest preset copy @starci/hfs ships (`runtime/packages/jest-preset/sonar-exclusions.json`, `bundledPresets`), not from a @starci/jest-preset installed beside the CLI (it was `HFS_SYNC_PRESET_MISSING`); `starci app upgrade` reads the same copy instead of a hand-kept list.
7
+ - Fixed: a new scaffold path is git-initialised with an unborn main before any file is written (`HFS_SCAFFOLD_GIT_INIT_FAILED` when git cannot), as the verb promised, so `starci npm ci` can install the hooks; an existing empty unborn main repository is still accepted.
8
+
3
9
  ## 4.7.16 - 2026-10-21
4
10
  - Fixed: `DB_MIGRATION_DESTRUCTIVE` counts a be/src source as a reference of a dropped or altered column only when the source names the column's table too, so a same-named column of another table (`public.brain_lessons.origin` beside a drop of `transactions.origin`) no longer blocks a contract migration; table and other object drops keep the leaf match; canon pins follow the matching package cohort.
5
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starci/hfs",
3
- "version": "4.7.16",
3
+ "version": "4.7.17",
4
4
  "description": "The StarCi app command implementation for scaffolding, linting, checking and synchronizing one product repository.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/gate.mjs CHANGED
@@ -1,388 +1,402 @@
1
- // gate.mjs - `starci app release gate`: the honest release gate. It runs the app's own gates on a clean HEAD and when all required gates pass it
2
- // writes the L4 record <git-common-dir>/starci-release/<HEAD sha>.l4.json (head, tag, per-gate log path and sha256) and creates the annotated tag.
3
- // The canon pre-push hook lets main and v* tags through only for a HEAD with that tag and that record. Nothing is pushed here (see push.mjs).
4
- // The gate list comes from the optional `release:` block of .starcistacks/application-stacks.yaml, else from the app's managed package scripts.
5
- // Commands are argument arrays (never shell strings) run through ctx.spawn; a git tool call always goes through the same seam.
6
- import { createHash } from 'node:crypto';
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
- import { isPlainObject as plain } from '../runtime/engine/plain-object.mjs';
10
- import { qualityServices } from '../runtime/scripts/hfs/ci-declaration.mjs';
11
- import { firstLine, lines, tool } from '../stack/context.mjs';
12
- import { failure, refusal } from '../stack/errors.mjs';
13
- import { produceLintReports } from './lint-report.mjs';
14
-
15
- export const RELEASE_CODE = 'RELEASE_CONFIG_INVALID';
16
- const SONAR_UNREACHABLE = 'SONAR_UNREACHABLE';
17
-
18
- const FIELDS = new Set(['gates', 'tagPrefix', 'defaultBranch', 'tagMatchesVersion']);
19
- const GATE_FIELDS = new Set(['name', 'command', 'summary', 'env']);
20
- const GATE_NAME = /^[a-z][a-z0-9-]*$/u;
21
- const TOKEN = /^[A-Za-z0-9_@%+=:,./\\-]+$/u;
22
- const ENV_KEY = /^[A-Z][A-Z0-9_]*$/u;
23
- const REF_NAME = /^[A-Za-z0-9._/][A-Za-z0-9._/-]*$/u;
24
- const PREFIX = /^[A-Za-z][A-Za-z0-9._-]{0,19}$/u;
25
- export const VERSION = /^(\d+)\.(\d+)\.(\d+)$/u;
26
- const THRESHOLD_MISS = /coverage threshold .* not met/gu;
27
- const WRAPPED = new Set(['npm', 'npx']);
28
- const SCRIPT_GATES = ['typecheck', 'build:be', 'lint', 'build:fe', 'test'];
29
- const MAX_PATCH = 100;
30
-
31
- /** True for a branch or remote name git can take as one argument (no leading dash, only path-like characters). */
32
- export const refName = (value) => typeof value === 'string' && REF_NAME.test(value);
33
-
34
- const scriptGate = (script) => ({
35
- name: script.replaceAll(':', '-'),
36
- command: ['npm', 'run', script],
37
- summary: script === 'test' ? 'jest' : null,
38
- env: {},
39
- });
40
-
41
- /** Default gates run app-check, the enabled audit, then every managed script present in the app. */
42
- function defaultGates(scripts, audit) {
43
- const present = SCRIPT_GATES.filter((script) => typeof scripts?.[script] === 'string');
44
- return [{ name: 'app-check', command: ['npx', 'starci', 'app', 'check'], summary: null, env: {} }, ...(audit ? [audit] : []), ...present.map(scriptGate)];
45
- }
46
-
47
- /** Shared quality settings retain the release reader's audit validation, disabled mode and legacy string host compatibility. */
48
- function releaseServices(services, options) {
49
- const audit = services?.audit ?? {};
50
- if (!plain(audit) || (audit.in !== undefined && (!Array.isArray(audit.in) || !audit.in.every((scope) => typeof scope === 'string'))) || (audit.omitDev !== undefined && typeof audit.omitDev !== 'boolean')) throw refusal(RELEASE_CODE, 'services.audit must be a mapping with a string-list in and boolean omitDev');
51
- const sonar = services?.sonar;
52
- const compatible = typeof sonar?.host === 'string' ? { ...sonar, host: { public: sonar.host } } : sonar;
53
- const quality = qualityServices({ services: { ...services, sonar: compatible } }, options);
54
- if (audit.mode === 'disabled') quality.audit = null;
55
- return quality;
56
- }
57
-
58
- /** The shared audit settings preserve release scope, level and development-dependency selection. */
59
- function auditGate(audit) {
60
- if (!audit || !audit.in.includes('release-gate')) return null;
61
- if (!['info', 'low', 'moderate', 'high', 'critical'].includes(audit.level)) throw refusal(RELEASE_CODE, 'services.audit.level must be an npm audit level');
62
- return { name: 'audit', command: ['npm', 'audit', ...(audit.omitDev ? ['--omit=dev'] : []), `--audit-level=${audit.level}`], summary: null, env: {} };
63
- }
64
-
65
- /** A requested local Sonar scan uses only the declared host and token variable; the token never enters argv. */
66
- function sonarGate(services, env) {
67
- const configured = services?.sonar;
68
- const sonar = configured?.provider === 'sonarcloud' ? { ...configured, host: 'https://sonarcloud.io' } : configured;
69
- const tokenName = sonar?.token;
70
- if (!sonar?.host || !ENV_KEY.test(tokenName) || !env[tokenName]) throw refusal('RELEASE_SONAR_UNAVAILABLE', 'declare an enabled services.sonar host and set its ci.token environment variable');
71
- const command = ['npx', '--yes', '@sonar/scan@4.3.0', `-Dsonar.host.url=${sonar.host}`];
72
- const organization = sonar.organization ?? (sonar.organizationVar ? env[sonar.organizationVar] : null);
73
- if (organization) command.push(`-Dsonar.organization=${organization}`);
74
- if (!command.every((word) => TOKEN.test(word))) throw refusal('RELEASE_SONAR_UNAVAILABLE', 'Sonar host and organization must be plain command arguments');
75
- return { name: 'sonar', command, summary: null, env: { SONAR_TOKEN: env[tokenName] }, provider: sonar,
76
- credentialNames: [...new Set(['SONAR_TOKEN', tokenName])] };
77
- }
78
-
79
- function gateProblems(entry, at, seen) {
80
- const found = [];
81
- for (const key of Object.keys(entry)) if (!GATE_FIELDS.has(key)) found.push(`${at}.${key}: is not a field of a gate`);
82
- if (typeof entry.name !== 'string' || !GATE_NAME.test(entry.name)) found.push(`${at}.name: must match ${GATE_NAME}`);
83
- else if (seen.has(entry.name)) found.push(`${at}.name: ${entry.name} is declared twice`);
84
- const command = entry.command;
85
- if (!Array.isArray(command) || command.length === 0 || !command.every((word) => typeof word === 'string' && TOKEN.test(word))) found.push(`${at}.command: must be a non-empty list of plain words (no shell strings)`);
86
- if (entry.summary !== undefined && entry.summary !== 'jest') found.push(`${at}.summary: must be jest`);
87
- const env = entry.env ?? {};
88
- if (!plain(env) || !Object.entries(env).every(([key, value]) => ENV_KEY.test(key) && typeof value === 'string')) found.push(`${at}.env: must map UPPER_CASE names to string values`);
89
- return found;
90
- }
91
-
92
- function gatesOf(list, problems) {
93
- if (!Array.isArray(list) || list.length === 0) {
94
- problems.push('release.gates: must be a non-empty list');
95
- return [];
96
- }
97
- const seen = new Set();
98
- const gates = [];
99
- list.forEach((entry, index) => {
100
- const at = `release.gates[${index}]`;
101
- const found = plain(entry) ? gateProblems(entry, at, seen) : [`${at}: must be a mapping`];
102
- problems.push(...found);
103
- if (found.length === 0) {
104
- seen.add(entry.name);
105
- gates.push({ name: entry.name, command: entry.command, summary: entry.summary ?? null, env: entry.env ?? {} });
106
- }
107
- });
108
- return gates;
109
- }
110
-
111
- /** Judges the optional `release:` block. Absence is fine (defaults). Returns { config } or { problems }. */
112
- export function normalizeRelease(block, scripts = {}, services = {}, options = {}) {
113
- const raw = block ?? {};
114
- if (!plain(raw)) return { problems: ['release: must be a mapping'] };
115
- const problems = Object.keys(raw).filter((key) => !FIELDS.has(key)).map((key) => `release.${key}: is not a field of the release block`);
116
- const tagPrefix = raw.tagPrefix ?? 'v';
117
- const defaultBranch = raw.defaultBranch ?? 'main';
118
- const tagMatchesVersion = raw.tagMatchesVersion ?? false;
119
- if (typeof tagPrefix !== 'string' || !PREFIX.test(tagPrefix)) problems.push(`release.tagPrefix: must match ${PREFIX}`);
120
- if (!refName(defaultBranch)) problems.push(`release.defaultBranch: must match ${REF_NAME}`);
121
- if (typeof tagMatchesVersion !== 'boolean') problems.push('release.tagMatchesVersion: must be true or false');
122
- const quality = releaseServices(services, options);
123
- const audit = auditGate(quality.audit);
124
- const gates = raw.gates === undefined ? defaultGates(scripts, audit) : gatesOf(raw.gates, problems);
125
- if (raw.gates !== undefined && audit && !gates.some((gate) => gate.name === 'audit')) gates.push(audit);
126
- return problems.length === 0 ? { config: { gates, tagPrefix, defaultBranch, tagMatchesVersion, services: quality } } : { problems };
127
- }
128
-
129
- /* ---- git through the seam */
130
-
131
- /** Runs git in the app root; a missing git or (unless allowFail) a non-zero exit is a failure whose message names the first stderr line. */
132
- export function git(ctx, args, { allowFail = false } = {}) {
133
- const run = tool(ctx, 'git', args, { cwd: ctx.cwd, env: ctx.env });
134
- if (run.error) throw failure('RELEASE_GIT_MISSING', `cannot run git (${run.error.message})`);
135
- if (run.status !== 0 && !allowFail) throw failure('RELEASE_GIT_FAILED', `git ${args.slice(0, 2).join(' ')}: ${firstLine(run.stderr)}`);
136
- return { code: run.status, stdout: String(run.stdout ?? '').trim(), stderr: String(run.stderr ?? '') };
137
- }
138
-
139
- /** The directory that holds the L4 records: <git common dir>/starci-release. */
140
- export const releaseDir = (ctx) => path.join(path.resolve(ctx.cwd, git(ctx, ['rev-parse', '--git-common-dir']).stdout), 'starci-release');
141
-
142
- /** Annotated tags `<prefix><digit>*` that point at HEAD (lightweight tags do not count: the hook ignores them). */
143
- export function annotatedOnHead(ctx, prefix) {
144
- const names = lines(git(ctx, ['tag', '--points-at', 'HEAD', '--list', `${prefix}[0-9]*`]).stdout);
145
- return names.filter((name) => git(ctx, ['cat-file', '-t', `refs/tags/${name}`], { allowFail: true }).stdout === 'tag');
146
- }
147
-
148
- const dirtyPaths = (ctx) => lines(git(ctx, ['status', '--porcelain', '--untracked-files=normal']).stdout);
149
-
150
- /** Tag names that exist locally or on the remote. */
151
- function takenTags(ctx, prefix, remote) {
152
- const local = lines(git(ctx, ['tag', '--list', `${prefix}*`]).stdout);
153
- const listed = lines(git(ctx, ['ls-remote', '--tags', remote], { allowFail: true }).stdout);
154
- const remoteNames = listed.map((line) => line.split('refs/tags/')[1]?.replace(/\^\{\}$/u, '')).filter(Boolean);
155
- return new Set([...local, ...remoteNames]);
156
- }
157
-
158
- /** Next free `<prefix><major>.<minor>.<n>` for the package version. */
159
- function nextFree(prefix, version, taken) {
160
- const [, major, minor] = VERSION.exec(version);
161
- for (let patch = 0; patch < MAX_PATCH; patch += 1) {
162
- const candidate = `${prefix}${major}.${minor}.${patch}`;
163
- if (!taken.has(candidate)) return candidate;
164
- }
165
- throw refusal('RELEASE_NO_FREE_TAG', `no free tag ${prefix}${major}.${minor}.0 to ${prefix}${major}.${minor}.${MAX_PATCH - 1}`);
166
- }
167
-
168
- /** The tag this release uses and its state: on-head (reused), free (will be created) or taken (exists on another commit). */
169
- function chooseTag(ctx, config, { prefix, remote }) {
170
- const onHead = annotatedOnHead(ctx, prefix);
171
- const taken = takenTags(ctx, prefix, remote);
172
- const exact = `${prefix}${config.version}`;
173
- const tag = config.tagMatchesVersion ? exact : (onHead[0] ?? nextFree(prefix, config.version, taken));
174
- if (onHead.includes(tag)) return { tag, state: 'on-head' };
175
- return { tag, state: taken.has(tag) ? 'taken' : 'free' };
176
- }
177
-
178
- /* ---- gate results */
179
-
180
- const sha256 = (file) => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
181
-
182
- const lineAfter = (text, label) => {
183
- const found = text.split('\n').find((line) => line.startsWith(label));
184
- return found === undefined ? null : found.slice(label.length).trim();
185
- };
186
-
187
- /** The jest summary lines of a log: { suites, failedSuites, tests, failed, passed } or null when jest printed none. */
188
- function jestSummary(text) {
189
- const suites = lineAfter(text, 'Test Suites:');
190
- const tests = lineAfter(text, 'Tests:');
191
- if (suites === null || tests === null) return null;
192
- const count = (line, word) => Number(new RegExp(String.raw`(\d+) ${word}`, 'u').exec(line)?.[1] ?? 0);
193
- return {
194
- suites: count(suites, 'total'), failedSuites: count(suites, 'failed'),
195
- tests: count(tests, 'total'), failed: count(tests, 'failed'), passed: count(tests, 'passed'),
196
- };
197
- }
198
-
199
- /** Judges a jest-style gate from its log: green needs suites that all passed, every test passed and no coverage threshold miss. */
200
- function judgeJest(text) {
201
- const summary = jestSummary(text);
202
- const misses = (text.match(THRESHOLD_MISS) ?? []).length;
203
- if (!summary) return { pass: false, detail: 'no jest summary in the log', summary: null, misses };
204
- const pass = summary.suites > 0 && summary.failedSuites === 0 && summary.failed === 0 && summary.passed === summary.tests && misses === 0;
205
- const detail = `suites ${summary.suites - summary.failedSuites}/${summary.suites}, tests ${summary.passed}/${summary.tests}, coverage-threshold misses ${misses}`;
206
- return { pass, detail, summary, misses };
207
- }
208
-
209
- /** [command, args] to start an argv; on Windows npm and npx are .cmd files, so they start through cmd.exe (words are validated, never a shell string). */
210
- export function launch(argv, platform) {
211
- if (platform === 'win32' && WRAPPED.has(argv[0])) return ['cmd.exe', ['/d', '/s', '/c', ...argv]];
212
- return [argv[0], argv.slice(1)];
213
- }
214
-
215
- /** Sonar availability is public and bounded; HTTP uses the existing injected fetch seam. */
216
- async function sonarAvailability(ctx, gate) {
217
- const sonar = gate.provider;
218
- if (!sonar) return null;
219
- let up = false;
220
- try {
221
- const response = await ctx.fetch(sonar.host.replace(/\/$/u, '') + '/api/system/status', { signal: AbortSignal.timeout(10000) });
222
- up = response.ok && (await response.json()).status === 'UP';
223
- } catch { up = false; }
224
- if (up) return null;
225
- const detail = sonar.optional
226
- ? `notice: sonar skipped: ${sonar.host} not reachable (services.sonar.optional)`
227
- : `${SONAR_UNREACHABLE}: ${sonar.host} did not report UP within ten seconds`;
228
- return { skipped: sonar.optional === true, pass: false, detail };
229
- }
230
-
231
- /** Unreachable optional providers remain explicit skipped rows, with a real log and no scan invocation. */
232
- async function runAvailableGate(ctx, gate, options) {
233
- const availability = await sonarAvailability(ctx, gate);
234
- const log = path.join(options.dir, `${gate.name}.log`);
235
- if (!availability) {
236
- if (!gate.provider) return runGate(ctx, gate, options);
237
- // The scanner imports the app's declared external issues report: produce it first with the app's own lint, as the managed CI does.
238
- const started = ctx.now();
239
- const lint = produceLintReports(ctx, { launch, platform: options.platform, env: withoutCredentials(ctx.env, options.credentialNames) });
240
- if (lint.pass) return runGate(ctx, gate, { ...options, preface: lint.text });
241
- fs.writeFileSync(log, lint.text);
242
- return { name: gate.name, command: gate.command.join(' '), pass: false, detail: 'lint report failed (see log)', seconds: Math.round((ctx.now() - started) / 1000),
243
- summary: null, log: path.resolve(log), logSha256: sha256(log), env: Object.keys(gate.env) };
244
- }
245
- fs.writeFileSync(log, availability.detail + '\n');
246
- return { name: gate.name, command: gate.command.join(' '), ...availability, seconds: 0,
247
- summary: null, log: path.resolve(log), logSha256: sha256(log), env: Object.keys(gate.env) };
248
- }
249
-
250
- const withoutCredentials = (values, credentialNames) => {
251
- const selected = new Set(credentialNames);
252
- return Object.fromEntries(Object.entries(values ?? {}).filter(([key]) => !selected.has(key.toUpperCase())));
253
- };
254
-
255
- function runGate(ctx, gate, { dir, platform, credentialNames, preface = '' }) {
256
- const log = path.join(dir, `${gate.name}.log`);
257
- const started = ctx.now();
258
- const [command, args] = launch(gate.command, platform);
259
- // The native scanner alone consumes Sonar credentials; ordinary gates cannot inherit or reintroduce them.
260
- const env = { ...ctx.env, ...(gate.provider ? gate.env : withoutCredentials(gate.env, credentialNames)) };
261
- const run = tool(ctx, command, args, { cwd: ctx.cwd, env });
262
- const output = `${run.stdout ?? ''}${run.stderr ?? ''}`;
263
- const text = gate.name === 'sonar' && gate.env.SONAR_TOKEN ? output.replaceAll(gate.env.SONAR_TOKEN, '[REDACTED]') : output;
264
- fs.writeFileSync(log, preface + text);
265
- const verdict = judgeVerdict(run, gate, text);
266
- if (gate.name === 'sonar' && gate.env.SONAR_TOKEN) verdict.detail = verdict.detail.replaceAll(gate.env.SONAR_TOKEN, '[REDACTED]');
267
- const seconds = Math.round((ctx.now() - started) / 1000);
268
- return {
269
- name: gate.name, command: gate.command.join(' '), pass: verdict.pass, detail: verdict.detail, seconds,
270
- summary: verdict.summary ?? null, log: path.resolve(log), logSha256: sha256(log), env: Object.keys(gate.env),
271
- };
272
- }
273
-
274
- function judgeVerdict(run, gate, text) {
275
- if (run.error) return { pass: false, detail: `cannot run (${run.error.message})` };
276
- if (run.status !== 0) return { pass: false, detail: `exit ${run.status}` };
277
- if (gate.summary === 'jest') return judgeJest(text);
278
- return { pass: true, detail: 'exit 0' };
279
- }
280
-
281
- /* ---- the gate */
282
-
283
- function sourceProblem(ctx, source, head) {
284
- if (source === 'HEAD') return null;
285
- if (!refName(source)) return `--source ${source} is not a ref name`;
286
- const resolved = git(ctx, ['rev-parse', '--verify', `${source}^{commit}`], { allowFail: true });
287
- if (resolved.code !== 0) return `cannot resolve --source ${source}`;
288
- if (resolved.stdout !== head) return `--source ${source} is ${resolved.stdout.slice(0, 10)} but HEAD is ${head.slice(0, 10)}: the hook and the L4 record are about HEAD; check the candidate out first`;
289
- return null;
290
- }
291
-
292
- function tagLine({ tag, state }) {
293
- if (state === 'on-head') return `tag ${tag} (annotated, already on HEAD)`;
294
- if (state === 'taken') return `tag ${tag} (TAKEN by another commit)`;
295
- return `tag ${tag} (free: will be created, annotated)`;
296
- }
297
-
298
- /** Everything that can be known without running a gate: the facts, the red preconditions and the lines that describe them. */
299
- function inspect(ctx, config, options) {
300
- const head = git(ctx, ['rev-parse', 'HEAD']).stdout;
301
- const branch = git(ctx, ['rev-parse', '--abbrev-ref', 'HEAD'], { allowFail: true }).stdout;
302
- const out = [`checkout ${ctx.cwd}`, `HEAD ${head} (${branch})`];
303
- const red = [];
304
- const problem = sourceProblem(ctx, options.source ?? 'HEAD', head);
305
- if (problem) red.push(problem);
306
- const dirty = dirtyPaths(ctx);
307
- if (dirty.length > 0) red.push(`working tree is not clean (${dirty.length} path(s), first: ${dirty[0].slice(0, 100)}): the record would vouch for files that are not in HEAD`);
308
- else out.push('worktree clean');
309
- const prefix = options.tagPrefix ?? config.tagPrefix;
310
- if (!PREFIX.test(prefix)) throw refusal('RELEASE_USAGE', `--tag-prefix must match ${PREFIX}`);
311
- const chosen = chooseTag(ctx, config, { prefix, remote: 'origin' });
312
- if (chosen.state === 'taken') red.push(`tag ${chosen.tag} already exists on another commit (local or remote)`);
313
- out.push(tagLine(chosen));
314
- return { head, chosen, red, out };
315
- }
316
-
317
- function planLines(config, facts, dir, recordPath) {
318
- const out = [`L4 record ${recordPath}`, `logs ${dir}`, '', 'gates (required gates must pass, optional provider outages are skipped, in this order):'];
319
- for (const gate of config.gates) {
320
- const summary = gate.summary ? ` (summary: ${gate.summary})` : '';
321
- out.push(` ${gate.name.padEnd(17)} ${gate.command.join(' ')}${summary}`);
322
- }
323
- out.push(`then: write ${path.basename(recordPath)} and \`git tag -a ${facts.chosen.tag}\` on ${facts.head.slice(0, 10)}; push it with \`starci app release push\`.`);
324
- return out;
325
- }
326
-
327
- function assertUnmoved(ctx, head) {
328
- const now = git(ctx, ['rev-parse', 'HEAD']).stdout;
329
- if (now !== head) throw failure('RELEASE_HEAD_MOVED', `HEAD moved during the gates (${head.slice(0, 10)} -> ${now.slice(0, 10)}). No record.`);
330
- const dirty = dirtyPaths(ctx);
331
- if (dirty.length > 0) throw failure('RELEASE_TREE_DIRTY', `the gates left ${dirty.length} changed or untracked path(s) (first: ${dirty[0].slice(0, 100)}): generated files differ from HEAD. Commit or ignore them properly, then rerun. No record.`);
332
- }
333
-
334
- function writeRecord(ctx, { head, tag, results, recordPath }) {
335
- const record = {
336
- schema: 'starci-app-l4-record/1', head, tag, createdAt: new Date(ctx.now()).toISOString(), producedBy: 'starci app release gate',
337
- note: 'Required gates passed on a clean HEAD; optional provider skips are explicit and every entry links its log and sha256.',
338
- gates: results,
339
- };
340
- fs.mkdirSync(path.dirname(recordPath), { recursive: true });
341
- fs.writeFileSync(recordPath, `${JSON.stringify(record, null, 2)}\n`);
342
- }
343
-
344
- /** Gates run sequentially because each failure prevents subsequent commands and record creation. */
345
- async function runAll(ctx, config, options) {
346
- fs.mkdirSync(options.dir, { recursive: true });
347
- return config.gates.reduce(async (pending, gate) => {
348
- const results = await pending;
349
- if (results.some((result) => !result.pass && !result.skipped)) return results;
350
- return [...results, await runAvailableGate(ctx, gate, options)];
351
- }, Promise.resolve([]));
352
- }
353
-
354
- function summaryOf(result) {
355
- let status = result.pass ? 'PASS' : 'FAIL';
356
- if (result.skipped) status = 'SKIPPED';
357
- return `${status} ${result.name} (${result.detail}, ${result.seconds}s) log ${result.log}`;
358
- }
359
-
360
- /**
361
- * `starci app release gate`: dry run prints the preconditions, the gate list, the head and the tag; --execute runs every gate and, only if required gates pass,
362
- * writes the L4 record and creates the annotated tag. options: { execute, sonar, source, tagPrefix, platform }.
363
- */
364
- export async function releaseGate(ctx, config, options = {}) {
365
- if (options.sonar) config = { ...config, gates: [...config.gates.filter((gate) => gate.name !== 'sonar'), sonarGate(config.services, ctx.env)] };
366
- const credentialNames = config.gates.find(gate => gate.provider)?.credentialNames ?? ['SONAR_TOKEN', config.services?.sonar?.token].filter(Boolean);
367
- ctx = Object.create(ctx, {env: {value: withoutCredentials(ctx.env, credentialNames)}});
368
- // The CI verdict of a release is the candidate run of its own sha, judged by `starci app release push` (candidate-ci.mjs, OWNER RULING candidate-ci 2026-10-18):
369
- // the gate no longer refuses over the latest default-branch run.
370
- const facts = inspect(ctx, config, options);
371
- const common = releaseDir(ctx);
372
- const recordPath = path.join(common, `${facts.head}.l4.json`);
373
- const dir = path.join(common, facts.head.slice(0, 12));
374
- const plan = [...facts.out, ...planLines(config, facts, dir, recordPath)];
375
- const base = { head: facts.head, tag: facts.chosen.tag, record: recordPath, gates: config.gates.map((gate) => gate.name) };
376
- if (facts.red.length > 0) return { ok: false, lines: [...plan, ...facts.red.map((item) => `RED: ${item}`), 'nothing was run.'], data: { ...base, red: facts.red, executed: false } };
377
- if (options.execute !== true) return { ok: true, lines: [...plan, '', 'dry run: no gate was run, nothing written. preconditions OK.'], data: { ...base, red: [], executed: false } };
378
- const results = await runAll(ctx, config, { dir, platform: options.platform ?? process.platform, credentialNames });
379
- const report = results.map(summaryOf);
380
- const failed = results.filter((result) => !result.pass && !result.skipped);
381
- if (failed.length > 0) return { ok: false, lines: [...plan, ...report, `gate(s) red: ${failed.map((item) => item.name).join(', ')}. No L4 record, no tag.`], data: { ...base, executed: true, results } };
382
- assertUnmoved(ctx, facts.head);
383
- writeRecord(ctx, { head: facts.head, tag: facts.chosen.tag, results, recordPath });
384
- const created = facts.chosen.state !== 'on-head';
385
- if (created) git(ctx, ['tag', '-a', facts.chosen.tag, '-m', `release ${facts.chosen.tag}: required gates passed on ${facts.head.slice(0, 12)} (L4 record ${path.basename(recordPath)})`, facts.head]);
386
- const tagged = created ? `annotated tag ${facts.chosen.tag} created on ${facts.head.slice(0, 10)}` : `annotated tag ${facts.chosen.tag} already on ${facts.head.slice(0, 10)}`;
387
- return { ok: true, lines: [...plan, ...report, `L4 record written: ${recordPath}`, tagged], data: { ...base, executed: true, results, tagCreated: created } };
388
- }
1
+ // gate.mjs - `starci app release gate`: the honest release gate. It runs the app's own gates on a clean HEAD and when all required gates pass it
2
+ // writes the L4 record <git-common-dir>/starci-release/<HEAD sha>.l4.json (head, tag, per-gate log path and sha256) and creates the annotated tag.
3
+ // The canon pre-push hook lets main and v* tags through only for a HEAD with that tag and that record. Nothing is pushed here (see push.mjs).
4
+ // The gate list comes from the optional `release:` block of .starcistacks/application-stacks.yaml, else from the app's managed package scripts.
5
+ // Commands are argument arrays (never shell strings) run through ctx.spawn; a git tool call always goes through the same seam.
6
+ import { createHash } from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { isPlainObject as plain } from '../runtime/engine/plain-object.mjs';
10
+ import { qualityServices } from '../runtime/scripts/hfs/ci-declaration.mjs';
11
+ import { firstLine, lines, tool } from '../stack/context.mjs';
12
+ import { failure, refusal } from '../stack/errors.mjs';
13
+ import { produceLintReports } from './lint-report.mjs';
14
+ import { sonarQualityGate } from './sonar-quality-gate.mjs';
15
+
16
+ export const RELEASE_CODE = 'RELEASE_CONFIG_INVALID';
17
+ const SONAR_UNREACHABLE = 'SONAR_UNREACHABLE';
18
+
19
+ const FIELDS = new Set(['gates', 'tagPrefix', 'defaultBranch', 'tagMatchesVersion']);
20
+ const GATE_FIELDS = new Set(['name', 'command', 'summary', 'env']);
21
+ const GATE_NAME = /^[a-z][a-z0-9-]*$/u;
22
+ const TOKEN = /^[A-Za-z0-9_@%+=:,./\\-]+$/u;
23
+ const ENV_KEY = /^[A-Z][A-Z0-9_]*$/u;
24
+ const REF_NAME = /^[A-Za-z0-9._/][A-Za-z0-9._/-]*$/u;
25
+ const PREFIX = /^[A-Za-z][A-Za-z0-9._-]{0,19}$/u;
26
+ export const VERSION = /^(\d+)\.(\d+)\.(\d+)$/u;
27
+ const THRESHOLD_MISS = /coverage threshold .* not met/gu;
28
+ const WRAPPED = new Set(['npm', 'npx']);
29
+ const SCRIPT_GATES = ['typecheck', 'build:be', 'lint', 'build:fe', 'test'];
30
+ const MAX_PATCH = 100;
31
+
32
+ /** True for a branch or remote name git can take as one argument (no leading dash, only path-like characters). */
33
+ export const refName = (value) => typeof value === 'string' && REF_NAME.test(value);
34
+
35
+ const scriptGate = (script) => ({
36
+ name: script.replaceAll(':', '-'),
37
+ command: ['npm', 'run', script],
38
+ summary: script === 'test' ? 'jest' : null,
39
+ env: {},
40
+ });
41
+
42
+ /** Default gates run app-check, the enabled audit, then every managed script present in the app. */
43
+ function defaultGates(scripts, audit) {
44
+ const present = SCRIPT_GATES.filter((script) => typeof scripts?.[script] === 'string');
45
+ return [{ name: 'app-check', command: ['npx', 'starci', 'app', 'check'], summary: null, env: {} }, ...(audit ? [audit] : []), ...present.map(scriptGate)];
46
+ }
47
+
48
+ /** Shared quality settings retain the release reader's audit validation, disabled mode and legacy string host compatibility. */
49
+ function releaseServices(services, options) {
50
+ const audit = services?.audit ?? {};
51
+ if (!plain(audit) || (audit.in !== undefined && (!Array.isArray(audit.in) || !audit.in.every((scope) => typeof scope === 'string'))) || (audit.omitDev !== undefined && typeof audit.omitDev !== 'boolean')) throw refusal(RELEASE_CODE, 'services.audit must be a mapping with a string-list in and boolean omitDev');
52
+ const sonar = services?.sonar;
53
+ const compatible = typeof sonar?.host === 'string' ? { ...sonar, host: { public: sonar.host } } : sonar;
54
+ const quality = qualityServices({ services: { ...services, sonar: compatible } }, options);
55
+ if (audit.mode === 'disabled') quality.audit = null;
56
+ return quality;
57
+ }
58
+
59
+ /** The shared audit settings preserve release scope, level and development-dependency selection. */
60
+ function auditGate(audit) {
61
+ if (!audit || !audit.in.includes('release-gate')) return null;
62
+ if (!['info', 'low', 'moderate', 'high', 'critical'].includes(audit.level)) throw refusal(RELEASE_CODE, 'services.audit.level must be an npm audit level');
63
+ return { name: 'audit', command: ['npm', 'audit', ...(audit.omitDev ? ['--omit=dev'] : []), `--audit-level=${audit.level}`], summary: null, env: {} };
64
+ }
65
+
66
+ /** A requested local Sonar scan uses only the declared host and token variable; the token never enters argv. */
67
+ function sonarGate(services, env) {
68
+ const configured = services?.sonar;
69
+ const sonar = configured?.provider === 'sonarcloud' ? { ...configured, host: 'https://sonarcloud.io' } : configured;
70
+ const tokenName = sonar?.token;
71
+ if (!sonar?.host || !ENV_KEY.test(tokenName) || !env[tokenName]) throw refusal('RELEASE_SONAR_UNAVAILABLE', 'declare an enabled services.sonar host and set its ci.token environment variable');
72
+ const command = ['npx', '--yes', '@sonar/scan@4.3.0', `-Dsonar.host.url=${sonar.host}`];
73
+ const organization = sonar.organization ?? (sonar.organizationVar ? env[sonar.organizationVar] : null);
74
+ if (organization) command.push(`-Dsonar.organization=${organization}`);
75
+ if (!command.every((word) => TOKEN.test(word))) throw refusal('RELEASE_SONAR_UNAVAILABLE', 'Sonar host and organization must be plain command arguments');
76
+ return { name: 'sonar', command, summary: null, env: { SONAR_TOKEN: env[tokenName] }, provider: sonar,
77
+ credentialNames: [...new Set(['SONAR_TOKEN', tokenName])] };
78
+ }
79
+
80
+ function gateProblems(entry, at, seen) {
81
+ const found = [];
82
+ for (const key of Object.keys(entry)) if (!GATE_FIELDS.has(key)) found.push(`${at}.${key}: is not a field of a gate`);
83
+ if (typeof entry.name !== 'string' || !GATE_NAME.test(entry.name)) found.push(`${at}.name: must match ${GATE_NAME}`);
84
+ else if (seen.has(entry.name)) found.push(`${at}.name: ${entry.name} is declared twice`);
85
+ const command = entry.command;
86
+ if (!Array.isArray(command) || command.length === 0 || !command.every((word) => typeof word === 'string' && TOKEN.test(word))) found.push(`${at}.command: must be a non-empty list of plain words (no shell strings)`);
87
+ if (entry.summary !== undefined && entry.summary !== 'jest') found.push(`${at}.summary: must be jest`);
88
+ const env = entry.env ?? {};
89
+ if (!plain(env) || !Object.entries(env).every(([key, value]) => ENV_KEY.test(key) && typeof value === 'string')) found.push(`${at}.env: must map UPPER_CASE names to string values`);
90
+ return found;
91
+ }
92
+
93
+ function gatesOf(list, problems) {
94
+ if (!Array.isArray(list) || list.length === 0) {
95
+ problems.push('release.gates: must be a non-empty list');
96
+ return [];
97
+ }
98
+ const seen = new Set();
99
+ const gates = [];
100
+ list.forEach((entry, index) => {
101
+ const at = `release.gates[${index}]`;
102
+ const found = plain(entry) ? gateProblems(entry, at, seen) : [`${at}: must be a mapping`];
103
+ problems.push(...found);
104
+ if (found.length === 0) {
105
+ seen.add(entry.name);
106
+ gates.push({ name: entry.name, command: entry.command, summary: entry.summary ?? null, env: entry.env ?? {} });
107
+ }
108
+ });
109
+ return gates;
110
+ }
111
+
112
+ /** Judges the optional `release:` block. Absence is fine (defaults). Returns { config } or { problems }. */
113
+ export function normalizeRelease(block, scripts = {}, services = {}, options = {}) {
114
+ const raw = block ?? {};
115
+ if (!plain(raw)) return { problems: ['release: must be a mapping'] };
116
+ const problems = Object.keys(raw).filter((key) => !FIELDS.has(key)).map((key) => `release.${key}: is not a field of the release block`);
117
+ const tagPrefix = raw.tagPrefix ?? 'v';
118
+ const defaultBranch = raw.defaultBranch ?? 'main';
119
+ const tagMatchesVersion = raw.tagMatchesVersion ?? false;
120
+ if (typeof tagPrefix !== 'string' || !PREFIX.test(tagPrefix)) problems.push(`release.tagPrefix: must match ${PREFIX}`);
121
+ if (!refName(defaultBranch)) problems.push(`release.defaultBranch: must match ${REF_NAME}`);
122
+ if (typeof tagMatchesVersion !== 'boolean') problems.push('release.tagMatchesVersion: must be true or false');
123
+ const quality = releaseServices(services, options);
124
+ const audit = auditGate(quality.audit);
125
+ const gates = raw.gates === undefined ? defaultGates(scripts, audit) : gatesOf(raw.gates, problems);
126
+ if (raw.gates !== undefined && audit && !gates.some((gate) => gate.name === 'audit')) gates.push(audit);
127
+ return problems.length === 0 ? { config: { gates, tagPrefix, defaultBranch, tagMatchesVersion, services: quality } } : { problems };
128
+ }
129
+
130
+ /* ---- git through the seam */
131
+
132
+ /** Runs git in the app root; a missing git or (unless allowFail) a non-zero exit is a failure whose message names the first stderr line. */
133
+ export function git(ctx, args, { allowFail = false } = {}) {
134
+ const run = tool(ctx, 'git', args, { cwd: ctx.cwd, env: ctx.env });
135
+ if (run.error) throw failure('RELEASE_GIT_MISSING', `cannot run git (${run.error.message})`);
136
+ if (run.status !== 0 && !allowFail) throw failure('RELEASE_GIT_FAILED', `git ${args.slice(0, 2).join(' ')}: ${firstLine(run.stderr)}`);
137
+ return { code: run.status, stdout: String(run.stdout ?? '').trim(), stderr: String(run.stderr ?? '') };
138
+ }
139
+
140
+ /** The directory that holds the L4 records: <git common dir>/starci-release. */
141
+ export const releaseDir = (ctx) => path.join(path.resolve(ctx.cwd, git(ctx, ['rev-parse', '--git-common-dir']).stdout), 'starci-release');
142
+
143
+ /** Annotated tags `<prefix><digit>*` that point at HEAD (lightweight tags do not count: the hook ignores them). */
144
+ export function annotatedOnHead(ctx, prefix) {
145
+ const names = lines(git(ctx, ['tag', '--points-at', 'HEAD', '--list', `${prefix}[0-9]*`]).stdout);
146
+ return names.filter((name) => git(ctx, ['cat-file', '-t', `refs/tags/${name}`], { allowFail: true }).stdout === 'tag');
147
+ }
148
+
149
+ const dirtyPaths = (ctx) => lines(git(ctx, ['status', '--porcelain', '--untracked-files=normal']).stdout);
150
+
151
+ /** Tag names that exist locally or on the remote. */
152
+ function takenTags(ctx, prefix, remote) {
153
+ const local = lines(git(ctx, ['tag', '--list', `${prefix}*`]).stdout);
154
+ const listed = lines(git(ctx, ['ls-remote', '--tags', remote], { allowFail: true }).stdout);
155
+ const remoteNames = listed.map((line) => line.split('refs/tags/')[1]?.replace(/\^\{\}$/u, '')).filter(Boolean);
156
+ return new Set([...local, ...remoteNames]);
157
+ }
158
+
159
+ /** Next free `<prefix><major>.<minor>.<n>` for the package version. */
160
+ function nextFree(prefix, version, taken) {
161
+ const [, major, minor] = VERSION.exec(version);
162
+ for (let patch = 0; patch < MAX_PATCH; patch += 1) {
163
+ const candidate = `${prefix}${major}.${minor}.${patch}`;
164
+ if (!taken.has(candidate)) return candidate;
165
+ }
166
+ throw refusal('RELEASE_NO_FREE_TAG', `no free tag ${prefix}${major}.${minor}.0 to ${prefix}${major}.${minor}.${MAX_PATCH - 1}`);
167
+ }
168
+
169
+ /** The tag this release uses and its state: on-head (reused), free (will be created) or taken (exists on another commit). */
170
+ function chooseTag(ctx, config, { prefix, remote }) {
171
+ const onHead = annotatedOnHead(ctx, prefix);
172
+ const taken = takenTags(ctx, prefix, remote);
173
+ const exact = `${prefix}${config.version}`;
174
+ const tag = config.tagMatchesVersion ? exact : (onHead[0] ?? nextFree(prefix, config.version, taken));
175
+ if (onHead.includes(tag)) return { tag, state: 'on-head' };
176
+ return { tag, state: taken.has(tag) ? 'taken' : 'free' };
177
+ }
178
+
179
+ /* ---- gate results */
180
+
181
+ const sha256 = (file) => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
182
+
183
+ const lineAfter = (text, label) => {
184
+ const found = text.split('\n').find((line) => line.startsWith(label));
185
+ return found === undefined ? null : found.slice(label.length).trim();
186
+ };
187
+
188
+ /** The jest summary lines of a log: { suites, failedSuites, tests, failed, passed } or null when jest printed none. */
189
+ function jestSummary(text) {
190
+ const suites = lineAfter(text, 'Test Suites:');
191
+ const tests = lineAfter(text, 'Tests:');
192
+ if (suites === null || tests === null) return null;
193
+ const count = (line, word) => Number(new RegExp(String.raw`(\d+) ${word}`, 'u').exec(line)?.[1] ?? 0);
194
+ return {
195
+ suites: count(suites, 'total'), failedSuites: count(suites, 'failed'),
196
+ tests: count(tests, 'total'), failed: count(tests, 'failed'), passed: count(tests, 'passed'),
197
+ };
198
+ }
199
+
200
+ /** Judges a jest-style gate from its log: green needs suites that all passed, every test passed and no coverage threshold miss. */
201
+ function judgeJest(text) {
202
+ const summary = jestSummary(text);
203
+ const misses = (text.match(THRESHOLD_MISS) ?? []).length;
204
+ if (!summary) return { pass: false, detail: 'no jest summary in the log', summary: null, misses };
205
+ const pass = summary.suites > 0 && summary.failedSuites === 0 && summary.failed === 0 && summary.passed === summary.tests && misses === 0;
206
+ const detail = `suites ${summary.suites - summary.failedSuites}/${summary.suites}, tests ${summary.passed}/${summary.tests}, coverage-threshold misses ${misses}`;
207
+ return { pass, detail, summary, misses };
208
+ }
209
+
210
+ /** [command, args] to start an argv; on Windows npm and npx are .cmd files, so they start through cmd.exe (words are validated, never a shell string). */
211
+ export function launch(argv, platform) {
212
+ if (platform === 'win32' && WRAPPED.has(argv[0])) return ['cmd.exe', ['/d', '/s', '/c', ...argv]];
213
+ return [argv[0], argv.slice(1)];
214
+ }
215
+
216
+ /** Sonar availability is public and bounded; HTTP uses the existing injected fetch seam. */
217
+ async function sonarAvailability(ctx, gate) {
218
+ const sonar = gate.provider;
219
+ if (!sonar) return null;
220
+ let up = false;
221
+ try {
222
+ const response = await ctx.fetch(sonar.host.replace(/\/$/u, '') + '/api/system/status', { signal: AbortSignal.timeout(10000) });
223
+ up = response.ok && (await response.json()).status === 'UP';
224
+ } catch { up = false; }
225
+ if (up) return null;
226
+ const detail = sonar.optional
227
+ ? `notice: sonar skipped: ${sonar.host} not reachable (services.sonar.optional)`
228
+ : `${SONAR_UNREACHABLE}: ${sonar.host} did not report UP within ten seconds`;
229
+ return { skipped: sonar.optional === true, pass: false, detail };
230
+ }
231
+
232
+ /** Unreachable optional providers remain explicit skipped rows, with a real log and no scan invocation. */
233
+ async function runAvailableGate(ctx, gate, options) {
234
+ const availability = await sonarAvailability(ctx, gate);
235
+ const log = path.join(options.dir, `${gate.name}.log`);
236
+ if (!availability) {
237
+ if (!gate.provider) return runGate(ctx, gate, options);
238
+ // The scanner imports the app's declared external issues report: produce it first with the app's own lint, as the managed CI does.
239
+ const started = ctx.now();
240
+ const lint = produceLintReports(ctx, { launch, platform: options.platform, env: withoutCredentials(ctx.env, options.credentialNames) });
241
+ if (lint.pass) return judgeQualityGate(ctx, gate, runGate(ctx, gate, { ...options, preface: lint.text }));
242
+ fs.writeFileSync(log, lint.text);
243
+ return { name: gate.name, command: gate.command.join(' '), pass: false, detail: 'lint report failed (see log)', seconds: Math.round((ctx.now() - started) / 1000),
244
+ summary: null, log: path.resolve(log), logSha256: sha256(log), env: Object.keys(gate.env) };
245
+ }
246
+ fs.writeFileSync(log, availability.detail + '\n');
247
+ return { name: gate.name, command: gate.command.join(' '), ...availability, seconds: 0,
248
+ summary: null, log: path.resolve(log), logSha256: sha256(log), env: Object.keys(gate.env) };
249
+ }
250
+
251
+ /**
252
+ * A scanner that exited 0 only uploaded its report: the row passes when the server's quality gate of that analysis is OK
253
+ * (sonar-quality-gate.mjs). The verdict replaces the row's detail and is appended to its log; the row's time includes the wait.
254
+ */
255
+ async function judgeQualityGate(ctx, gate, row) {
256
+ if (!row.pass) return row;
257
+ const started = ctx.now();
258
+ const verdict = await sonarQualityGate(ctx, { cwd: ctx.cwd, host: gate.provider.host, token: gate.env.SONAR_TOKEN });
259
+ const failed = (verdict.conditions ?? []).map((line) => ` failed: ${line}\n`).join('');
260
+ fs.appendFileSync(row.log, `\nquality gate: ${verdict.detail}\n${failed}`);
261
+ return { ...row, pass: verdict.pass, detail: verdict.detail, seconds: row.seconds + Math.round((ctx.now() - started) / 1000), logSha256: sha256(row.log) };
262
+ }
263
+
264
+ const withoutCredentials = (values, credentialNames) => {
265
+ const selected = new Set(credentialNames);
266
+ return Object.fromEntries(Object.entries(values ?? {}).filter(([key]) => !selected.has(key.toUpperCase())));
267
+ };
268
+
269
+ function runGate(ctx, gate, { dir, platform, credentialNames, preface = '' }) {
270
+ const log = path.join(dir, `${gate.name}.log`);
271
+ const started = ctx.now();
272
+ const [command, args] = launch(gate.command, platform);
273
+ // The native scanner alone consumes Sonar credentials; ordinary gates cannot inherit or reintroduce them.
274
+ const env = { ...ctx.env, ...(gate.provider ? gate.env : withoutCredentials(gate.env, credentialNames)) };
275
+ const run = tool(ctx, command, args, { cwd: ctx.cwd, env });
276
+ const output = `${run.stdout ?? ''}${run.stderr ?? ''}`;
277
+ const text = gate.name === 'sonar' && gate.env.SONAR_TOKEN ? output.replaceAll(gate.env.SONAR_TOKEN, '[REDACTED]') : output;
278
+ fs.writeFileSync(log, preface + text);
279
+ const verdict = judgeVerdict(run, gate, text);
280
+ if (gate.name === 'sonar' && gate.env.SONAR_TOKEN) verdict.detail = verdict.detail.replaceAll(gate.env.SONAR_TOKEN, '[REDACTED]');
281
+ const seconds = Math.round((ctx.now() - started) / 1000);
282
+ return {
283
+ name: gate.name, command: gate.command.join(' '), pass: verdict.pass, detail: verdict.detail, seconds,
284
+ summary: verdict.summary ?? null, log: path.resolve(log), logSha256: sha256(log), env: Object.keys(gate.env),
285
+ };
286
+ }
287
+
288
+ function judgeVerdict(run, gate, text) {
289
+ if (run.error) return { pass: false, detail: `cannot run (${run.error.message})` };
290
+ if (run.status !== 0) return { pass: false, detail: `exit ${run.status}` };
291
+ if (gate.summary === 'jest') return judgeJest(text);
292
+ return { pass: true, detail: 'exit 0' };
293
+ }
294
+
295
+ /* ---- the gate */
296
+
297
+ function sourceProblem(ctx, source, head) {
298
+ if (source === 'HEAD') return null;
299
+ if (!refName(source)) return `--source ${source} is not a ref name`;
300
+ const resolved = git(ctx, ['rev-parse', '--verify', `${source}^{commit}`], { allowFail: true });
301
+ if (resolved.code !== 0) return `cannot resolve --source ${source}`;
302
+ if (resolved.stdout !== head) return `--source ${source} is ${resolved.stdout.slice(0, 10)} but HEAD is ${head.slice(0, 10)}: the hook and the L4 record are about HEAD; check the candidate out first`;
303
+ return null;
304
+ }
305
+
306
+ function tagLine({ tag, state }) {
307
+ if (state === 'on-head') return `tag ${tag} (annotated, already on HEAD)`;
308
+ if (state === 'taken') return `tag ${tag} (TAKEN by another commit)`;
309
+ return `tag ${tag} (free: will be created, annotated)`;
310
+ }
311
+
312
+ /** Everything that can be known without running a gate: the facts, the red preconditions and the lines that describe them. */
313
+ function inspect(ctx, config, options) {
314
+ const head = git(ctx, ['rev-parse', 'HEAD']).stdout;
315
+ const branch = git(ctx, ['rev-parse', '--abbrev-ref', 'HEAD'], { allowFail: true }).stdout;
316
+ const out = [`checkout ${ctx.cwd}`, `HEAD ${head} (${branch})`];
317
+ const red = [];
318
+ const problem = sourceProblem(ctx, options.source ?? 'HEAD', head);
319
+ if (problem) red.push(problem);
320
+ const dirty = dirtyPaths(ctx);
321
+ if (dirty.length > 0) red.push(`working tree is not clean (${dirty.length} path(s), first: ${dirty[0].slice(0, 100)}): the record would vouch for files that are not in HEAD`);
322
+ else out.push('worktree clean');
323
+ const prefix = options.tagPrefix ?? config.tagPrefix;
324
+ if (!PREFIX.test(prefix)) throw refusal('RELEASE_USAGE', `--tag-prefix must match ${PREFIX}`);
325
+ const chosen = chooseTag(ctx, config, { prefix, remote: 'origin' });
326
+ if (chosen.state === 'taken') red.push(`tag ${chosen.tag} already exists on another commit (local or remote)`);
327
+ out.push(tagLine(chosen));
328
+ return { head, chosen, red, out };
329
+ }
330
+
331
+ function planLines(config, facts, dir, recordPath) {
332
+ const out = [`L4 record ${recordPath}`, `logs ${dir}`, '', 'gates (required gates must pass, optional provider outages are skipped, in this order):'];
333
+ for (const gate of config.gates) {
334
+ const summary = gate.summary ? ` (summary: ${gate.summary})` : '';
335
+ out.push(` ${gate.name.padEnd(17)} ${gate.command.join(' ')}${summary}`);
336
+ }
337
+ out.push(`then: write ${path.basename(recordPath)} and \`git tag -a ${facts.chosen.tag}\` on ${facts.head.slice(0, 10)}; push it with \`starci app release push\`.`);
338
+ return out;
339
+ }
340
+
341
+ function assertUnmoved(ctx, head) {
342
+ const now = git(ctx, ['rev-parse', 'HEAD']).stdout;
343
+ if (now !== head) throw failure('RELEASE_HEAD_MOVED', `HEAD moved during the gates (${head.slice(0, 10)} -> ${now.slice(0, 10)}). No record.`);
344
+ const dirty = dirtyPaths(ctx);
345
+ if (dirty.length > 0) throw failure('RELEASE_TREE_DIRTY', `the gates left ${dirty.length} changed or untracked path(s) (first: ${dirty[0].slice(0, 100)}): generated files differ from HEAD. Commit or ignore them properly, then rerun. No record.`);
346
+ }
347
+
348
+ function writeRecord(ctx, { head, tag, results, recordPath }) {
349
+ const record = {
350
+ schema: 'starci-app-l4-record/1', head, tag, createdAt: new Date(ctx.now()).toISOString(), producedBy: 'starci app release gate',
351
+ note: 'Required gates passed on a clean HEAD; optional provider skips are explicit and every entry links its log and sha256.',
352
+ gates: results,
353
+ };
354
+ fs.mkdirSync(path.dirname(recordPath), { recursive: true });
355
+ fs.writeFileSync(recordPath, `${JSON.stringify(record, null, 2)}\n`);
356
+ }
357
+
358
+ /** Gates run sequentially because each failure prevents subsequent commands and record creation. */
359
+ async function runAll(ctx, config, options) {
360
+ fs.mkdirSync(options.dir, { recursive: true });
361
+ return config.gates.reduce(async (pending, gate) => {
362
+ const results = await pending;
363
+ if (results.some((result) => !result.pass && !result.skipped)) return results;
364
+ return [...results, await runAvailableGate(ctx, gate, options)];
365
+ }, Promise.resolve([]));
366
+ }
367
+
368
+ function summaryOf(result) {
369
+ let status = result.pass ? 'PASS' : 'FAIL';
370
+ if (result.skipped) status = 'SKIPPED';
371
+ return `${status} ${result.name} (${result.detail}, ${result.seconds}s) log ${result.log}`;
372
+ }
373
+
374
+ /**
375
+ * `starci app release gate`: dry run prints the preconditions, the gate list, the head and the tag; --execute runs every gate and, only if required gates pass,
376
+ * writes the L4 record and creates the annotated tag. options: { execute, sonar, source, tagPrefix, platform }.
377
+ */
378
+ export async function releaseGate(ctx, config, options = {}) {
379
+ if (options.sonar) config = { ...config, gates: [...config.gates.filter((gate) => gate.name !== 'sonar'), sonarGate(config.services, ctx.env)] };
380
+ const credentialNames = config.gates.find(gate => gate.provider)?.credentialNames ?? ['SONAR_TOKEN', config.services?.sonar?.token].filter(Boolean);
381
+ ctx = Object.create(ctx, {env: {value: withoutCredentials(ctx.env, credentialNames)}});
382
+ // The CI verdict of a release is the candidate run of its own sha, judged by `starci app release push` (candidate-ci.mjs, OWNER RULING candidate-ci 2026-10-18):
383
+ // the gate no longer refuses over the latest default-branch run.
384
+ const facts = inspect(ctx, config, options);
385
+ const common = releaseDir(ctx);
386
+ const recordPath = path.join(common, `${facts.head}.l4.json`);
387
+ const dir = path.join(common, facts.head.slice(0, 12));
388
+ const plan = [...facts.out, ...planLines(config, facts, dir, recordPath)];
389
+ const base = { head: facts.head, tag: facts.chosen.tag, record: recordPath, gates: config.gates.map((gate) => gate.name) };
390
+ if (facts.red.length > 0) return { ok: false, lines: [...plan, ...facts.red.map((item) => `RED: ${item}`), 'nothing was run.'], data: { ...base, red: facts.red, executed: false } };
391
+ if (options.execute !== true) return { ok: true, lines: [...plan, '', 'dry run: no gate was run, nothing written. preconditions OK.'], data: { ...base, red: [], executed: false } };
392
+ const results = await runAll(ctx, config, { dir, platform: options.platform ?? process.platform, credentialNames });
393
+ const report = results.map(summaryOf);
394
+ const failed = results.filter((result) => !result.pass && !result.skipped);
395
+ if (failed.length > 0) return { ok: false, lines: [...plan, ...report, `gate(s) red: ${failed.map((item) => item.name).join(', ')}. No L4 record, no tag.`], data: { ...base, executed: true, results } };
396
+ assertUnmoved(ctx, facts.head);
397
+ writeRecord(ctx, { head: facts.head, tag: facts.chosen.tag, results, recordPath });
398
+ const created = facts.chosen.state !== 'on-head';
399
+ if (created) git(ctx, ['tag', '-a', facts.chosen.tag, '-m', `release ${facts.chosen.tag}: required gates passed on ${facts.head.slice(0, 12)} (L4 record ${path.basename(recordPath)})`, facts.head]);
400
+ const tagged = created ? `annotated tag ${facts.chosen.tag} created on ${facts.head.slice(0, 10)}` : `annotated tag ${facts.chosen.tag} already on ${facts.head.slice(0, 10)}`;
401
+ return { ok: true, lines: [...plan, ...report, `L4 record written: ${recordPath}`, tagged], data: { ...base, executed: true, results, tagCreated: created } };
402
+ }
@@ -0,0 +1,68 @@
1
+ // sonar-quality-gate.mjs - the verdict of the release gate's sonar row after the scanner exits 0. The scanner's exit code says only
2
+ // that the report was uploaded; the server computes the analysis afterwards. This reads the task the scanner wrote
3
+ // (`.scannerwork/report-task.txt`), polls `api/ce/task` until the compute-engine task ends, then reads the quality gate of that
4
+ // analysis from `api/qualitygates/project_status` with the same token. OK passes; ERROR is red and names every failed condition;
5
+ // a task that ends FAILED or CANCELED, an unreadable answer and a deadline passed are typed refusals in the row's detail.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ const SONAR_GATE_FAILED = 'RELEASE_SONAR_GATE_FAILED';
10
+ const SONAR_GATE_TIMEOUT = 'RELEASE_SONAR_GATE_TIMEOUT';
11
+ const SONAR_GATE_UNREADABLE = 'RELEASE_SONAR_GATE_UNREADABLE';
12
+ const REPORT_TASK = path.join('.scannerwork', 'report-task.txt');
13
+ const DONE = new Set(['SUCCESS', 'FAILED', 'CANCELED']);
14
+ /** The bound of one compute-engine wait and the pause between polls (milliseconds). */
15
+ const QUALITY_GATE_WAIT = Object.freeze({ deadline: 600_000, interval: 5_000 });
16
+
17
+ /** The `key=value` lines of the scanner's report-task.txt under `cwd`, or null when the scanner wrote none. */
18
+ function reportTask(cwd) {
19
+ let text;
20
+ try { text = fs.readFileSync(path.join(cwd, REPORT_TASK), 'utf8'); } catch { return null; }
21
+ return Object.fromEntries(text.split(/\r?\n/u).map((line) => line.split('=')).filter(([key, ...rest]) => key && rest.length).map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]));
22
+ }
23
+
24
+ /** One authenticated JSON GET; a failed request or a non-JSON body throws. */
25
+ async function getJson(ctx, url, token) {
26
+ const response = await ctx.fetch(url, { headers: { Authorization: `Basic ${Buffer.from(`${token}:`).toString('base64')}` }, signal: AbortSignal.timeout(30_000) });
27
+ if (!response.ok) throw new Error(`HTTP ${response.status} from ${url.split('?')[0]}`);
28
+ return response.json();
29
+ }
30
+
31
+ /** The failed conditions of a quality gate answer, as `metric comparator threshold (actual value)` lines. */
32
+ const failedConditions = (status) => (status?.conditions ?? []).filter((condition) => condition.status === 'ERROR')
33
+ .map((condition) => `${condition.metricKey} ${condition.comparator ?? ''} ${condition.errorThreshold ?? ''} (actual ${condition.actualValue ?? '?'})`.replace(/\s+/gu, ' '));
34
+
35
+ /**
36
+ * The quality-gate verdict of the analysis the scanner just uploaded from `cwd`: `{ pass, detail, conditions? }`. `token` is the
37
+ * scanner's token, `host` the declared server. `ctx.fetch`, `ctx.now` and `ctx.sleep` are the seams; `wait` bounds the poll.
38
+ */
39
+ export async function sonarQualityGate(ctx, { cwd, host, token, wait = QUALITY_GATE_WAIT }) {
40
+ const task = reportTask(cwd);
41
+ if (!task?.ceTaskId) return { pass: false, detail: `${SONAR_GATE_UNREADABLE}: the scanner wrote no ${REPORT_TASK.replaceAll('\\', '/')} with a ceTaskId` };
42
+ const server = String(task.serverUrl || host).replace(/\/$/u, '');
43
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
44
+ const deadline = ctx.now() + wait.deadline;
45
+ let analysisId = null;
46
+ try {
47
+ for (;;) {
48
+ const state = (await getJson(ctx, `${server}/api/ce/task?id=${encodeURIComponent(task.ceTaskId)}`, token))?.task;
49
+ if (DONE.has(state?.status)) {
50
+ if (state.status !== 'SUCCESS') return { pass: false, detail: `${SONAR_GATE_FAILED}: compute-engine task ${task.ceTaskId} ended ${state.status}${state.errorMessage ? `: ${state.errorMessage}` : ''}` };
51
+ analysisId = state.analysisId;
52
+ break;
53
+ }
54
+ if (ctx.now() >= deadline) return { pass: false, detail: `${SONAR_GATE_TIMEOUT}: compute-engine task ${task.ceTaskId} is still ${state?.status ?? 'unknown'} after ${Math.round(wait.deadline / 1000)}s` };
55
+ await sleep(wait.interval);
56
+ }
57
+ const query = analysisId ? `analysisId=${encodeURIComponent(analysisId)}` : `projectKey=${encodeURIComponent(task.projectKey ?? '')}`;
58
+ const status = (await getJson(ctx, `${server}/api/qualitygates/project_status?${query}`, token))?.projectStatus;
59
+ if (status?.status === 'OK') return { pass: true, detail: 'exit 0, quality gate OK' };
60
+ if (status?.status === 'ERROR') {
61
+ const conditions = failedConditions(status);
62
+ return { pass: false, detail: `${SONAR_GATE_FAILED}: quality gate ERROR (${conditions.join('; ') || 'no condition listed'})${task.dashboardUrl ? ` ${task.dashboardUrl}` : ''}`, conditions };
63
+ }
64
+ return { pass: false, detail: `${SONAR_GATE_UNREADABLE}: quality gate status ${status?.status ?? 'missing'}` };
65
+ } catch (error) {
66
+ return { pass: false, detail: `${SONAR_GATE_UNREADABLE}: ${String(error?.message ?? error)}` };
67
+ }
68
+ }
@@ -29,14 +29,14 @@ pins:
29
29
  source: packages/grammar/package.json
30
30
  why: 'the grammar front ends read: the brand layer sets `--font-sans` and `--font-mono` and the grammar reads them; it carries the Input tel kind, the copyable and read-only Input, the IconButton disclosure props and count badge, ChatBubble, FillViewport, Textarea mentions and Enter-to-send, the leading PrimaryRailLayout rail, the plate-less Image, ListRow, the soft Alert, Progress steps, the floating primary IconButton, FlowGraph, the STATE-8 loading views and the bordered selectable TagGroup chips. The runtime source version wins for a @starci package.'
31
31
  '@starci/eslint-canon-be':
32
- version: 3.4.24
32
+ version: 3.4.25
33
33
  group: starci
34
34
  install: registry
35
35
  side: be
36
36
  source: packages/eslint/be/package.json
37
37
  why: 'the back-end ESLint canon: `loadHfs(import.meta.url)` of be/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the be side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; `starciBeConfig({ hfs: loadHfs(import.meta.url) })` is the typed factory and the BE-CONVENTION laws are its rules.'
38
38
  '@starci/eslint-canon-fe':
39
- version: 8.4.23
39
+ version: 8.4.24
40
40
  group: starci
41
41
  install: registry
42
42
  side: fe
@@ -62,7 +62,7 @@ pins:
62
62
  side: both
63
63
  source: packages/prettier-config/package.json
64
64
  '@starci/jest-preset':
65
- version: 2.3.2
65
+ version: 2.3.3
66
66
  group: starci
67
67
  install: registry
68
68
  side: be
@@ -76,14 +76,14 @@ pins:
76
76
  source: packages/test-world/package.json
77
77
  why: 'the shared e2e library of every back end (R47, R48), a devDependency of every back end: the warm stack behind toxiproxy, the network-edge fakes, the Nest boot, the typed useTestWorld handle, useSandbox for contract specs and the outage lock. Kafka is real own infra (the one digest-pinned apache/kafka KRaft image, a broker listener and proxy per slot, slot-prefixed topics, consumer groups and client ids) and Postgres is schema-per-context (a schema and a login role per context in a shared database). Each worker has its own data slot (<ns>_w<k>) with its own databases, Keycloak realm, leased Redis DB, bucket/collection/topic prefixes, fakes host, toxiproxy proxies and outage lock; a run provisions min(jest workers, workers cap, default 2) slots, and state file protocol 2 pairs exactly with @starci/jest-preset (TEST_WORLD_PAIR_MISMATCH otherwise). A modules world boots real peer apps beside its modules, world.apps.<name>.during(fn) is the outage of a peer app, w.keycloak.clientSecret(client) answers the run-generated secret of a confidential realm client, world.keycloak.events/sessions read the realm user events and live sessions, world.infra.postgresql.connection(name) takes one database connection down while the others serve, and world.resolve and scope.resolve take any Nest token. Every path a declaration names (`stack`, seeds, the realm, Dockerfiles) resolves from the app root (the directory of hfs.json); the globalSetup registers the path aliases as TypeScript resolves them. Its CLI main is exported at ./cli for starci app stack.'
78
78
  '@starci/cli':
79
- version: 1.7.16
79
+ version: 1.7.17
80
80
  group: starci
81
81
  install: registry
82
82
  side: both
83
83
  source: packages/cli/package.json
84
84
  why: 'the only StarCi command package; product repositories install it for starci app, while @starci/hfs remains its pinned transitive implementation.'
85
85
  '@starci/hfs':
86
- version: 4.7.16
86
+ version: 4.7.17
87
87
  group: starci
88
88
  install: registry
89
89
  side: both
@@ -3754,7 +3754,7 @@ rules:
3754
3754
  - {path: packages/eslint/be/sonar-parity-editions.spec.mjs, edition: full}
3755
3755
  - {path: packages/eslint/fe/sonar-parity-editions.spec.mjs, edition: lite}
3756
3756
  - {path: packages/eslint/fe/sonar-parity-editions.spec.mjs, edition: full}
3757
- law: "Code carries none of the smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (S9382; an endless loop is spared), no `charCodeAt`/`fromCharCode` (S7758), no string that only escapes backslashes (S7780; a Next `matcher` is spared, it is read statically), no nested conditional expression (S3358), no `void` on anything but a call (S3735), no unused import (S1128), no import that is only handed on instead of `export ... from` (S7763), no prop of a component's props type the component never reads (S6767, front end), and, through typescript-eslint with type information, no deprecated API (S1874), no object turned into text (S6551) and no `async` function that never awaits and returns no promise (S7503). The files a unit or an end-to-end spec names are outside the scan, so outside these rules."
3757
+ law: "Code carries none of the smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (S9382; an endless loop is spared), no `charCodeAt`/`fromCharCode` (S7758), no string that only escapes backslashes (S7780; a Next `matcher` is spared, it is read statically), no nested conditional expression (S3358), no `void` on anything but a call (S3735), no unused import (S1128), no import that is only handed on instead of `export ... from` (S7763), no prop of a component's props type the component never reads (S6767, front end), no `<video>` or `<audio>` without a captions track unless muted (S4084, front end), and, through typescript-eslint with type information, no deprecated API (S1874), no object turned into text (S6551) and no `async` function that never awaits and returns no promise (S7503). Every other rule of the Sonar way TypeScript profile with an ESLint equivalent (scripts/lib/sonar-way.mjs: eslint-plugin-sonarjs' Sonar way set, the core, typescript-eslint and unicorn rules it builds on) is on at error in both canons. The files a unit or an end-to-end spec names are outside the scan, so outside these rules."
3758
3758
  kinds: [lint, codemod]
3759
3759
  gates: [pre-commit, settle, land, ci]
3760
3760
  failureCodes: ["SCAN_SMELL"]
@@ -3774,6 +3774,7 @@ rules:
3774
3774
  - {kind: eslint-fe, id: no-unused-import}
3775
3775
  - {kind: eslint-fe, id: prefer-export-from}
3776
3776
  - {kind: eslint-fe, id: no-unused-prop-types}
3777
+ - {kind: eslint-fe, id: media-has-caption}
3777
3778
  - id: R236
3778
3779
  code: "RT_GATE_LOOSENING"
3779
3780
  editions: [lite, full]
@@ -38,7 +38,7 @@ versioning:
38
38
  # or environment reads (BE_APP_OPTIONS_COMPOSITION). Secrets use EnvSource.secret(): <NAME>_FILE first, plain <NAME> only
39
39
  # when the file key is absent; .starcistacks owns custody. Capability <capability>.config.ts roles stay unchanged.
40
40
  # 3.3.0 is a minor (alpha.16): it ADDS the optional app.ci-stack-deploy slot, the managed workflow of the starci app stack verbs.
41
- # 3.4.0 is a minor (alpha.24): it ADDS the opt-in be.contract.mcp-tools slot, the committed MCP tool-catalog snapshot of an app.
41
+ # 3.4.0 is a minor (alpha.25): it ADDS the opt-in be.contract.mcp-tools slot, the committed MCP tool-catalog snapshot of an app.
42
42
 
43
43
  # Field meaning, per slot.
44
44
  # id stable name, never changes meaning inside a major.
@@ -1,7 +1,7 @@
1
1
  // GENERATED by scripts/cli/gen-catalog.mjs — do not edit
2
2
  export const CATALOG = {
3
3
  "schema": "starci/cli-catalog@1",
4
- "hash": "c7ef5f72727b2b906b541669c413050b7abd34206c123a87fe90502330271856",
4
+ "hash": "ce01a03c949f8154644bec5d1068bf0b5316478f328b2231b2369c937f89e118",
5
5
  "global": [
6
6
  {
7
7
  "name": "json",
@@ -1234,6 +1234,9 @@ export const CATALOG = {
1234
1234
  "declared release.gates gets audit appended if missing",
1235
1235
  "--sonar appends @sonar/scan@4.3.0 against services.sonar.host (host.public for a host mapping), plus organization for sonarcloud;",
1236
1236
  "disabled or unavailable Sonar or an unset token refuses RELEASE_SONAR_UNAVAILABLE",
1237
+ "a scanner exit 0 is not a pass: the row polls api/ce/task until the analysis ends, then reads api/qualitygates/project_status with the same token",
1238
+ "OK passes; ERROR is red as RELEASE_SONAR_GATE_FAILED naming each failed condition, as is a FAILED or CANCELED task",
1239
+ "a task still running after 600 s is RELEASE_SONAR_GATE_TIMEOUT; no report-task, an HTTP error or no gate is RELEASE_SONAR_GATE_UNREADABLE",
1237
1240
  "OWNER RULING candidate-ci (2026-10-18): the gate no longer reads the default-branch CI; the verdict is the candidate run of the sha",
1238
1241
  "push --execute sends HEAD to refs/heads/release/candidate-<version> first and waits for its ci.yml run (it triggers on release/candidate-*)",
1239
1242
  "green moves the branch and the tag in one atomic push; red refuses RELEASE_CANDIDATE_CI_RED naming the failing jobs",
@@ -1246,7 +1249,7 @@ export const CATALOG = {
1246
1249
  "runtimeSide": "host"
1247
1250
  },
1248
1251
  "scaffold": {
1249
- "summary": "create a full or lite StarCi app, including an empty unborn main Git repository",
1252
+ "summary": "create a full or lite StarCi app in its own Git repository (unborn main)",
1250
1253
  "owner": "@starci/hfs",
1251
1254
  "positional": [
1252
1255
  {
@@ -0,0 +1 @@
1
+ ["**/*.spec.ts", "**/*.e2e-spec.ts", "**/dist/**", "**/coverage/**"]
package/scaffold/app.mjs CHANGED
@@ -10,7 +10,8 @@
10
10
  // is in sync by construction. The lockfile is never written by hand: once the files are written, npm resolves the real one
11
11
  // (`npm install --package-lock-only`, no node_modules, no scripts), so `npm ci` installs the new app as it is. When npm cannot
12
12
  // resolve it the scaffold fails (HFS_SCAFFOLD_LOCK_FAILED), names the step and unlinks its own generated entries. Replaced or
13
- // occupied entries are retained with a cleanup message. The only existing root accepted is an empty unborn main Git repository.
13
+ // occupied entries are retained with a cleanup message. The only existing root accepted is an empty unborn main Git repository; a
14
+ // new path is made one first (git init, branch main).
14
15
  import fs from 'node:fs';
15
16
  import path from 'node:path';
16
17
  import { spawnSync } from 'node:child_process';
@@ -27,6 +28,7 @@ import { initializeAppIdentity } from '../runtime/scripts/hfs/secret-init.mjs';
27
28
  import { declaredSealedMembers, materializeDeclaredPlaceholders } from '../runtime/scripts/hfs/sealed-members.mjs';
28
29
  import { revParseQuery } from '../runtime/scripts/api/git/rev-parse-query.mjs';
29
30
  import { lsFiles } from '../runtime/scripts/api/git/ls-files.mjs';
31
+ import { init as gitInit } from '../runtime/scripts/api/git/init.mjs';
30
32
  import { insidePath, samePath } from '../runtime/scripts/lib/path-key.mjs';
31
33
  import { byCodeUnit } from '../report/order.mjs';
32
34
  import { sonarGateName } from '../sync/sonar-key.mjs';
@@ -629,8 +631,9 @@ function emitScaffoldDatabaseTypes(root, name, writes, emitTypes) {
629
631
 
630
632
  /**
631
633
  * `starci app scaffold <name>`: writes the new app under `into`, resolves its lockfile with npm (`lock`, npmLock), and returns
632
- * `{ root, files }` (app-relative paths, sorted). `presets` is what sync loads from the installed @starci/jest-preset (the Sonar
633
- * exclusions); the CLI passes the one it resolves. Failure removes only scaffold-owned entries, retaining an existing .git.
634
+ * `{ root, files }` (app-relative paths, sorted). A new path is first made an empty repository with unborn main (`initGit`), so the
635
+ * app always lives in its own Git repository. `presets` are the jest preset's Sonar exclusions; the CLI passes the copy @starci/hfs
636
+ * ships (bundledPresets). Failure removes only scaffold-owned entries, retaining the .git.
634
637
  */
635
638
  /** Seal declared starter members to a fresh app recipient through the scaffold rollback owner. */
636
639
  function initializeScaffoldSecrets(root, writes) {
@@ -641,13 +644,25 @@ function initializeScaffoldSecrets(root, writes) {
641
644
  return [...initialized.files, ...materialized.members];
642
645
  }
643
646
 
644
- export function scaffoldApp({ name, into, presets, edition = 'full', authCallback = false, registryVisibility = 'public', manifest = loadSlotManifest(), pins = bundledPins(), lock = npmLock, emitTypes = generateDbTypes, now = () => new Date() }) {
647
+ /**
648
+ * A new app path becomes the one accepted existing root first: an empty repository with unborn main (git init), so the app is always
649
+ * created inside its own Git repository and `starci npm ci` can install the hooks. A failed init is a refusal before any file is written.
650
+ */
651
+ function bornRepository(root, initGit) {
652
+ fs.mkdirSync(root, { recursive: true });
653
+ const made = initGit(root, { branch: 'main' });
654
+ if (!made?.ok) throw new ScaffoldError('HFS_SCAFFOLD_GIT_INIT_FAILED', `git init could not create the repository of ${root} (${String(made?.stderr ?? '').trim() || 'no output'}); remove ${root}, check git, then run starci app scaffold again`);
655
+ return fs.lstatSync(root);
656
+ }
657
+
658
+ export function scaffoldApp({ name, into, presets, edition = 'full', authCallback = false, registryVisibility = 'public', manifest = loadSlotManifest(), pins = bundledPins(), lock = npmLock, emitTypes = generateDbTypes, initGit = gitInit, now = () => new Date() }) {
645
659
  if (!NAME.test(String(name))) throw new ScaffoldError('HFS_SCAFFOLD_NAME_INVALID', `the app name ${name} must be kebab-case (a project name: ${NAME})`);
646
660
  const root = path.resolve(into, name);
647
- const original = fs.lstatSync(root, { throwIfNoEntry: false });
648
- if (original && !emptyUnbornGit(root, original)) throw new ScaffoldError('HFS_SCAFFOLD_EXISTS', `${root} already exists; only a plain directory containing solely .git with unborn main and an empty index can be scaffolded`);
661
+ const existing = fs.lstatSync(root, { throwIfNoEntry: false });
662
+ if (existing && !emptyUnbornGit(root, existing)) throw new ScaffoldError('HFS_SCAFFOLD_EXISTS', `${root} already exists; only a plain directory containing solely .git with unborn main and an empty index can be scaffolded`);
649
663
  if (!['public', 'private'].includes(registryVisibility)) throw new ScaffoldError('HFS_SCAFFOLD_REGISTRY_VISIBILITY', `--registry-visibility accepts public or private (got ${registryVisibility})`);
650
664
  if (typeof authCallback !== 'boolean') throw new ScaffoldError('HFS_SCAFFOLD_NAME_INVALID', 'authCallback must be a boolean');
665
+ const original = existing ?? bornRepository(root, initGit);
651
666
  const declaration = starterDeclaration(name, manifest, edition);
652
667
  if (authCallback) enableAuthCallback(declaration);
653
668
  const app = resolveRepoDeclaration(manifest, declaration);
package/src/main.mjs CHANGED
@@ -69,7 +69,7 @@ import { formatCoverageReport } from '../runtime/scripts/hfs/coverage-from.mjs';
69
69
  import { HFS_DECLARATION_FILE, HfsSlotsError, loadSlotManifest, readRepoDeclaration } from '../runtime/scripts/hfs/slots.mjs';
70
70
  import { formatFindings } from '../sync/format.mjs';
71
71
  import { main as syncMain } from '../sync/cli.mjs';
72
- import { SyncError, loadPresets } from '../sync/index.mjs';
72
+ import { SyncError, bundledPresets } from '../sync/index.mjs';
73
73
  import { managedFindings } from '../sync/managed.mjs';
74
74
  import { emitContracts } from '../emit/contracts.mjs';
75
75
  import { dbTypesEmitter } from '../emit/db-types.mjs';
@@ -282,14 +282,10 @@ async function lintMain(argv, { cwd, stdout, presets, prettier }) {
282
282
  }
283
283
 
284
284
  /**
285
- * The jest preset a new app renders its Sonar exclusions from: the one installed beside this @starci/hfs. None is a refusal,
286
- * never a render without it.
285
+ * The jest preset a new app renders its Sonar exclusions from: the copy this @starci/hfs ships (bundledPresets), the same version the
286
+ * scaffold pins, so `npx @starci/cli app scaffold` works before any dependency of the app is installed.
287
287
  */
288
- async function scaffoldPresets() {
289
- try { return await loadPresets(path.dirname(fileURLToPath(import.meta.url))); } catch (error) {
290
- throw new SyncError('HFS_SYNC_PRESET_MISSING', `${error.message.replace(/^[A-Z_]+: /, '')}; install @starci/jest-preset beside @starci/cli, then run starci app scaffold <name>`);
291
- }
292
- }
288
+ const scaffoldPresets = () => bundledPresets();
293
289
 
294
290
  function globalValueArgument(arg, args) {
295
291
  const inline = arg.startsWith('--cwd=') || arg.startsWith('--edition=');
@@ -389,7 +385,7 @@ function addMain(opts, { cwd: repoRoot, stdout: out }) {
389
385
  async function scaffoldMain(opts, { cwd, edition = 'full', presets, lock, stdout: out }) {
390
386
  const [name, ...extra] = opts.positional;
391
387
  if (!name || extra.length) throw new Error('starci app scaffold takes `<name> [--into <dir>] [--edition full|lite] [--registry-visibility public|private]`');
392
- const { root: created, files } = scaffoldApp({ name, into: path.resolve(cwd, opts.into ?? '.'), edition, presets: presets ?? await scaffoldPresets(), ...(opts['registry-visibility'] === undefined ? {} : { registryVisibility: opts['registry-visibility'] }), ...(lock ? { lock } : {}) });
388
+ const { root: created, files } = scaffoldApp({ name, into: path.resolve(cwd, opts.into ?? '.'), edition, presets: presets ?? scaffoldPresets(), ...(opts['registry-visibility'] === undefined ? {} : { registryVisibility: opts['registry-visibility'] }), ...(lock ? { lock } : {}) });
393
389
  out(`starci app scaffold: created ${created} (${files.length} files); next: starci npm ci (the lockfile, then the git hooks through npm run prepare; after a raw npm ci --ignore-scripts run npm run prepare), then starci app lint\n`);
394
390
  return 0;
395
391
  }
package/sync/index.mjs CHANGED
@@ -158,6 +158,24 @@ export async function loadPresets(root) {
158
158
  return { sonarExclusions: require(resolved).sonarExclusions() };
159
159
  }
160
160
 
161
+ /**
162
+ * The jest preset's Sonar exclusions as @starci/hfs ships them: `@starci/jest-preset/sonar-exclusions.json`, copied byte for byte into
163
+ * packages/hfs/runtime by scripts/hfs/sync-runtime.mjs, so a fresh `starci app scaffold` (nothing installed yet) and an upgrade render the
164
+ * same list the app's installed preset answers. A missing copy is a refusal, never a render without it.
165
+ */
166
+ const BUNDLED_SONAR_EXCLUSIONS = new URL('../runtime/packages/jest-preset/sonar-exclusions.json', import.meta.url);
167
+
168
+ /** The presets ({ sonarExclusions }) of the jest preset version this @starci/hfs pins, read from its bundled copy. */
169
+ export function bundledPresets() {
170
+ let list;
171
+ try {
172
+ list = JSON.parse(fs.readFileSync(BUNDLED_SONAR_EXCLUSIONS, 'utf8'));
173
+ } catch {
174
+ throw new SyncError('HFS_SYNC_PRESET_MISSING', '@starci/hfs ships no runtime/packages/jest-preset/sonar-exclusions.json; reinstall @starci/hfs at its published version');
175
+ }
176
+ return { sonarExclusions: list.join(',') };
177
+ }
178
+
161
179
  /** Where the be unit run writes the lcov report (jest `coverageDirectory` coverage under be/, reporter lcov), from the app root. */
162
180
  const LCOV_REPORT = 'be/coverage/lcov.info';
163
181
 
@@ -11,6 +11,6 @@ export const createRetryLink = () =>
11
11
  delay: { initial: RETRY_POLICY.initialDelayMs, max: RETRY_POLICY.maxDelayMs, jitter: true },
12
12
  attempts: {
13
13
  max: RETRY_POLICY.maxAttempts,
14
- retryIf: (error) => error !== undefined && !CombinedGraphQLErrors.is(error),
14
+ retryIf: (error) => !CombinedGraphQLErrors.is(error),
15
15
  },
16
16
  })
package/upgrade/index.mjs CHANGED
@@ -18,6 +18,7 @@ import { byCodeUnit } from "../report/order.mjs";
18
18
  import {
19
19
  TEMPLATES_DIR,
20
20
  appSource,
21
+ bundledPresets,
21
22
  checkTargets,
22
23
  imageFiles,
23
24
  loadHfs,
@@ -48,7 +49,7 @@ const FULL_DEPENDENCIES = Object.freeze(["nest-commander"]);
48
49
  // ruling lacks (a current lite app already has it, and the e2e world's @starci/test-world is what full adds). These are the preset's two
49
50
  // public sync inputs; once apply resolves the new dependency, normal full sync reads them from @starci/jest-preset again.
50
51
  export const UPGRADE_PRESETS = Object.freeze({
51
- sonarExclusions: "**/*.spec.ts,**/*.e2e-spec.ts,**/dist/**,**/coverage/**",
52
+ sonarExclusions: bundledPresets().sonarExclusions,
52
53
  coverageSources: Object.freeze([
53
54
  "src/**/*.service.ts",
54
55
  "src/features/cli/**/*.cli.ts",