@starci/hfs 4.11.13 → 4.11.15

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 (43) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/db/migrate.mjs +1 -1
  3. package/db/postgres.mjs +38 -3
  4. package/package.json +1 -1
  5. package/release/index.mjs +4 -3
  6. package/release/lint-baseline.mjs +123 -0
  7. package/release/urgent.mjs +19 -4
  8. package/runtime/knowledge/hfs/canon-pins.yaml +7 -7
  9. package/runtime/knowledge/hfs/rules.yaml +3 -3
  10. package/runtime/knowledge/patterns/be/webhooks.yaml +3 -2
  11. package/runtime/scripts/hfs/rules/canon-copy-drift.mjs +54 -7
  12. package/scaffold/add-compose.mjs +3 -0
  13. package/scaffold/add-inbox-lite.mjs +45 -23
  14. package/scaffold/lite-exports.mjs +13 -0
  15. package/src/main.mjs +2 -2
  16. package/stack/cli.mjs +5 -3
  17. package/stack/deploy.mjs +6 -2
  18. package/stack/urgent-floor.mjs +101 -7
  19. package/templates/be/inbox/entities.index.ts.tpl +4 -0
  20. package/templates/be/inbox/entity.ts.tpl +29 -0
  21. package/templates/be/inbox/index.ts.tpl +1 -0
  22. package/templates/be/inbox/platform/inbox/inbox.decorators.ts.tpl +5 -2
  23. package/templates/be/inbox/platform/inbox/inbox.port.ts.tpl +29 -1
  24. package/templates/be/inbox/platform/inbox/inbox.service.spec.ts.tpl +65 -1
  25. package/templates/be/inbox/platform/inbox/inbox.service.ts.tpl +48 -10
  26. package/templates/be/inbox/platform/inbox/index.ts.tpl +2 -2
  27. package/templates/be/inbox/service.spec.ts.tpl +39 -15
  28. package/templates/be/inbox/service.ts.tpl +13 -13
  29. package/templates/be/inbox/webhook-door.spec.ts.tpl +4 -1
  30. package/templates/be/skeleton/src/modules/domain/note/note.service.ts +3 -4
  31. package/templates/be/skeleton/src/modules/domain/note/persistence/note.rows.ts +4 -0
  32. package/templates/be/skeleton/src/modules/platform/database/errors/database.error.ts +3 -0
  33. package/templates/be/skeleton/src/modules/platform/database/index.ts +1 -0
  34. package/templates/be/skeleton/src/modules/platform/database/returned-rows.policy.spec.ts +84 -0
  35. package/templates/be/skeleton/src/modules/platform/database/returned-rows.policy.ts +61 -0
  36. package/templates/be/skeleton/src/modules/platform/http-security/persistence/rate-limit.rows.ts +5 -0
  37. package/templates/be/skeleton/src/modules/platform/http-security/rate-limit.guard.ts +3 -3
  38. package/templates/be/skeleton-lite/src/modules/platform/database/errors/database.error.ts +3 -0
  39. package/templates/be/skeleton-lite/src/modules/platform/database/index.ts +1 -0
  40. package/templates/be/skeleton-lite/src/modules/platform/http-security/rate-limit.guard.spec.ts +41 -33
  41. package/templates/be/skeleton-lite/src/modules/platform/http-security/rate-limit.guard.ts +15 -9
  42. package/templates/be/inbox/database-client.spec.ts.tpl +0 -45
  43. package/templates/be/inbox/database-client.ts.tpl +0 -45
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.11.15 - 2026-10-29
4
+
5
+ - Added: `platform/database/returned-rows.policy.ts` in the skeleton of both editions, exported from the database barrel: `rowShape({ column: kind })` builds the guard of the rows a RETURNING clause answers (kinds `string`, `number`, `boolean`, `date`, `json`, and `string?`, `number?`, `boolean?`, `date?` that also admit SQL null; a column the statement does not return is refused), and `returnedRows(raw, isRow)` narrows the result of `manager.query` or the `raw` of a query builder's `execute()` to typed rows with no cast. A result that is not a list of rows (the `[rows, count]` of a bare UPDATE included) or a row the guard refuses throws the new `DATABASE_RETURNING_ROW_REJECTED` (internal) of both editions' `DatabaseErrorCode`. The policy spec proves every kind, null, a missing column and both refusals.
6
+ - Changed: the skeleton's RETURNING call sites read their rows through it: full `NoteService.create` (`isNoteRow` beside `NoteRow` in `note.rows.ts`) and the full `RateLimitGuard` (`isRateWindowRow` in `rate-limit.rows.ts`); the lite webhook receipt insert (`webhook-inbox.client.ts`, the `inbox` templates' `database-client.ts.tpl`), with a spec for a receipt row of another shape.
7
+ - Changed: the lite `RateLimitGuard` counts a live window in one query builder `UPDATE ... SET hits = hits + 1 ... RETURNING hits` read through `returnedRows`, no longer an `increment` followed by a `findOneBy` (BE-PERSISTENCE-4: an UPDATE that answers rows stays one statement); the spec reads the counting builder's calls and refuses a returned row whose hits are not a number.
8
+ - Added: the lite inbox capability (`templates/be/inbox/platform/inbox`, written by the first `add webhook`) carries the entity receipt port: `EntityInbox extends Inbox` with `claimRow(source, eventId, tx, { entity, row })`, which claims the delivery and, only for the winning claim, inserts the provider's receipt entity row (`orIgnore`, `returning("id")`, read through `returnedRows`) in the caller transaction, answering the receipt id (`InboxReceiptId`) or undefined for a repeat. `PostgresInbox` implements it, and `InjectEntityInbox()` (a `TypedParameterDecorator<EntityInbox>` on the same `INBOX` token) injects it, so an app no longer hand-rolls the port or injects `@InjectInbox()` into an `EntityInbox` parameter. The barrel exports `InjectEntityInbox` and the types `EntityInbox` and `InboxEntityReceipt`. Specs: `inbox.service.spec.ts.tpl` (claim then insert, a repeat inserts nothing, an existing receipt, a receipt row of another shape, a missing delivery id) and `src/inbox-scaffold.spec.mjs` (the written decorator, barrel and class).
9
+ - Added: the first start of the urgent floor (owner ruling `urgent-first-start`): `stack deploy --urgent --first-start --db-service <service>` deploys a release whose self-hosted database it starts itself. In place of the backup and test decrypt (nothing exists to back up, and the database is reachable only inside the stack), a `first-start` step between the stack deploy and converge waits up to 180s for the service's container to accept connections (`pg_isready`), proves the database empty (no `supabase_migrations.schema_migrations`, no table in `public`) and runs migrate preview then execute inside that container (db/bootstrap.sql first, as the `--db-url-env` role); the record, the rollback target, readiness verify and automatic rollback hold. Codes: `STACK_FIRST_START_USAGE`, `STACK_FIRST_START_NO_DATABASE`, `STACK_FIRST_START_NOT_EMPTY`, `STACK_FIRST_START_MIGRATE_RED`; each red first start rolls the release back.
10
+ - Added: `release push --urgent --lint-baseline <tag>` (owner ruling `urgent-lint-baseline`, `release/lint-baseline.mjs`): the managed lint (`npm run lint`) runs over the whole app at HEAD and at the tag, in a throwaway worktree that borrows HEAD's node_modules as directory junctions (unlinked before the worktree is removed, which is skipped when one is left), each writing a Sonar report (`-- --sonar`); a HEAD finding the tag has (engine, rule, file and message; then engine, rule and message for a moved file) is the accepted backlog, anything beyond it is new and red, and a lint that could not run on either side is red. The lint row of the urgent record names both counts, both reports with their sha256 and the first new findings; `lint-new.json` lists them all. Codes: `RELEASE_URGENT_LINT_BASELINE_TAG`, `RELEASE_URGENT_LINT_BASELINE_UNMANAGED`. Specs: `src/release-lint-baseline.spec.mjs` (matching, and a real git worktree with a stand-in `npm run lint`).
11
+ - Added: `inContainer(target, container)` in `db/postgres.mjs`: the db verbs' client tools run inside the database's container through `docker exec` against 127.0.0.1, each `-f` file copied in first (`docker cp`), the password on the exec's stdin (never argv, a file or an environment); `migrateDatabase` takes such a prebuilt `target`. Specs: `src/db-in-container.spec.mjs`, the first-start cases of `src/stack-urgent-floor.spec.mjs`.
12
+ - Changed: `InboxEntityReceipt.row` is a builder, `row(deliveryId)`, called with the delivery id the claim trimmed, so the receipt row keys exactly what was claimed (`claim` and `claimRow` share the refusal of a missing or blank id, `DATABASE_WEBHOOK_DELIVERY_ID_REQUIRED`).
13
+ - Changed: the lite provider intake `add webhook` writes claims through the `EntityInbox`: `<Provider>InboxService` injects `@InjectEntityInbox() inbox: EntityInbox` and awaits `claimRow("webhook.<provider>", request.eventId, manager, { entity: <Provider>InboxEntity, row } satisfies InboxEntityReceipt<...>)` first in its transaction, returning when it answers undefined, then publishes the recorded event. The receipt is an entity row: `persistence/entities/<provider>-inbox.entity.ts` (`<Provider>InboxEntity` over `public.<provider>_inbox`) and its `<provider>InboxEntities` list, exported from the domain barrel and spread into `PRIMARY_ENTITIES` of `platform/database/entities.ts`. The raw receipt insert is gone: no `webhook-inbox.client.ts` (`recordWebhookDelivery`, `webhookReceiptInsert`) is written or exported. A shared inbox written before the `EntityInbox` port refuses a further provider (`HFS_ADD_INBOX_ENTITY_PORT`). The new inbox exports now have that caller in a fresh `add webhook` app.
14
+ - Fixed: lite `add webhook` exports `CorrelationRequest` and `isCorrelationId` from `platform/logging` (the door and the event bus import them), its door spec overrides the `ReadinessService` the http-security module provides (it needs the database probe and retry timer the door never reaches), and an area group already spread in the API root (`...domainModules(tokens.verify)`) is no longer spread a second time with another argument (`add-compose.mjs`, also for `add table`).
15
+ - Fixed: the lite inbox spec's "rolls the claim back when later work in the receipt transaction fails" failed on every generated app: its claim is a database-function call (`SELECT * FROM "public"."inbox_claim_event"($1, $2)`), which `fakeTransaction` did not record as a write; `@starci/jest-preset` 2.5.1 records it, and the template asserts it unchanged.
16
+ - Changed: the bundled canon pins name hfs 4.11.15, eslint-canon-be 3.8.14, eslint-canon-fe 9.5.16, the Grammar family 0.15.27 and jest-preset 2.5.1.
17
+
18
+ ## 4.11.14 - 2026-10-29
19
+
20
+ - Fixed: R253 (`HFS_CANON_COPY_DRIFT`, `rules/canon-copy-drift.mjs`) judges a hash-sensitive canon copy against the be/skeleton of the @starci/hfs version the app pins (its lockfile's resolution of `node_modules/@starci/hfs`, else an exact package.json pin), never against a newer hfs that runs the check: this package's own templates serve when it is that version or the app pins none, else an installed copy at the pinned version; with neither at hand the copy is left to the app's own run of its pinned hfs. A skeleton change reaches an app only when the app raises its hfs.
21
+ - Changed: the bundled canon pins name hfs 4.11.14, eslint-canon-be 3.8.13, eslint-canon-fe 9.5.15 and the Grammar family 0.15.26.
22
+ - Spec: `src/hfs-secret-custody.spec.mjs` pins an older hfs with an installed copy whose skeleton differs: a copy equal to the pinned skeleton is clean, one equal to this package's skeleton drifts, and with no copy of the pinned version nothing is judged against another.
23
+
3
24
  ## 4.11.13 - 2026-10-29
4
25
 
5
26
  - Fixed: a member sealed to an environment's whole recipient set (the owner key and the deploy server key, the production standard after `server-key --execute`) opens with either identity alone. The selected-identity decrypt (`runtime/scripts/lib/sops-envelope.mjs` `selectedAgeEnvelope`) refused every envelope whose age list held more than one entry (`unsupported-age-set`), so every production read failed once the server key joined; it now admits a set that holds the selected recipient and refuses an empty entry or gap (`invalid-age-entry`) and a recipient named twice (`duplicate-age-recipient`); a dotenv envelope reads every `sops_age__list_<n>__` entry.
package/db/migrate.mjs CHANGED
@@ -132,7 +132,7 @@ export function buildModel(root, decl) {
132
132
  /* ---- the target */
133
133
 
134
134
  /** The database of `--url-env` (default DATABASE_URL). */
135
- export const resolveTarget = (ctx, options = {}) => dbTarget(ctx, options.urlEnv ?? DEFAULT_DB_URL_ENV);
135
+ export const resolveTarget = (ctx, options = {}) => options.target ?? dbTarget(ctx, options.urlEnv ?? DEFAULT_DB_URL_ENV);
136
136
 
137
137
  /** True for a database on this machine's loopback (the local db service): applying to it needs no arming. */
138
138
  export const isLoopback = (url) => ['127.0.0.1', 'localhost', '[::1]'].includes(new URL(url).hostname);
package/db/postgres.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  // postgres.mjs - the one door of the `starci app db` verbs to a self-hosted PostgreSQL: psql and pg_dump through ctx.spawn (never a
2
2
  // shell). The database is named by an environment variable holding a postgres connection URL (`--url-env <NAME>`, default
3
- // DATABASE_URL); the password travels only in the child's PGPASSWORD, never in argv, a file, a line or an error.
3
+ // DATABASE_URL); the password travels only in the child's PGPASSWORD, never in argv, a file, a line or an error. An in-container target
4
+ // (`inContainer`) runs the same tools inside the database's own container through docker exec, the password on stdin.
5
+ import path from 'node:path';
4
6
  import { failure, refusal } from '../stack/errors.mjs';
5
7
  import { firstLine, tool } from '../stack/context.mjs';
6
8
 
@@ -34,10 +36,43 @@ export function dbTarget(ctx, name = DEFAULT_DB_URL_ENV) {
34
36
  return { kind: 'url', how: `connection string from ${name}`, urlEnv: name, url: parsed.url, env: parsed.password ? { PGPASSWORD: parsed.password } : {}, secrets: [value, parsed.password].filter(Boolean) };
35
37
  }
36
38
 
39
+ /** Where a `-f` file of an in-container target is copied before the client reads it. */
40
+ const CONTAINER_DIR = '/tmp/starci-db';
41
+ /** The shell an in-container client runs under: the password comes in on stdin into PGPASSWORD, then the tool runs with its arguments. */
42
+ const STDIN_PASSWORD = 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec "$@"';
43
+
44
+ /**
45
+ * `target` reached inside the running container `container` (`docker exec` through this invocation's daemon), for a database only the stack's
46
+ * network reaches (the first start of a self-hosted database, `stack deploy --urgent --first-start`): the image's own client tools run there
47
+ * against the URL's database on 127.0.0.1, a `-f` file is copied in first, and the password travels on the exec's stdin, never in argv, a file
48
+ * or an environment of this machine.
49
+ */
50
+ export function inContainer(target, container) {
51
+ const url = new URL(target.url);
52
+ url.hostname = '127.0.0.1';
53
+ return { ...target, how: `${target.how}, inside container ${container.slice(0, 12)}`, url: url.toString(), container };
54
+ }
55
+
56
+ /** Runs `command` of an in-container target: copies each `-f` file in, then execs the tool through the stdin-password shell. */
57
+ function containerRun(ctx, target, command, args) {
58
+ const short = target.container.slice(0, 12);
59
+ const step = (what, run) => {
60
+ if (run.error || run.status !== 0) throw failure('DB_CLI_FAILED', `${what} in container ${short} failed: ${scrub(firstLine(run.stderr), target.secrets)}`);
61
+ };
62
+ step('mkdir', tool(ctx, 'docker', ['exec', target.container, 'mkdir', '-p', CONTAINER_DIR]));
63
+ const inside = args.map((arg, index) => {
64
+ if (args[index - 1] !== '-f') return arg;
65
+ const copied = `${CONTAINER_DIR}/${index}-${path.basename(arg)}`;
66
+ step(`docker cp of ${path.basename(arg)}`, tool(ctx, 'docker', ['cp', arg, `${target.container}:${copied}`]));
67
+ return copied;
68
+ });
69
+ return tool(ctx, 'docker', ['exec', '-i', target.container, 'sh', '-c', STDIN_PASSWORD, 'sh', command, ...inside], { input: `${target.env.PGPASSWORD ?? ''}\n` });
70
+ }
71
+
37
72
  /** Runs a PostgreSQL client tool against `target`; a failure names the first stderr line with every secret scrubbed (or withholds it). */
38
73
  export function pgTool(ctx, target, command, args, { withhold = false, code = 'DB_CLI_FAILED' } = {}) {
39
- const run = tool(ctx, command, args, { cwd: ctx.cwd, env: { ...ctx.env, ...target.env } });
40
- if (run.error) throw failure('DB_CLI_MISSING', `cannot run ${command}; install the PostgreSQL client tools (psql, pg_dump)`);
74
+ const run = target.container ? containerRun(ctx, target, command, args) : tool(ctx, command, args, { cwd: ctx.cwd, env: { ...ctx.env, ...target.env } });
75
+ if (run.error) throw failure('DB_CLI_MISSING', target.container ? `cannot run docker exec ${command} in container ${target.container.slice(0, 12)}` : `cannot run ${command}; install the PostgreSQL client tools (psql, pg_dump)`);
41
76
  if (run.status !== 0) throw failure(code, withhold ? `${command} failed; output withheld` : `${command} failed: ${scrub(firstLine(run.stderr), target.secrets)}`);
42
77
  return { stdout: run.stdout ?? '', text: `${run.stdout ?? ''}${run.stderr ?? ''}` };
43
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starci/hfs",
3
- "version": "4.11.13",
3
+ "version": "4.11.15",
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/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // index.mjs - `starci app release <gate|push>` and the plumbing the release and database verbs share: the context built from the app's IO, strict flag
2
2
  // parsing, the optional `release:` / `database:` blocks of .starcistacks/application-stacks.yaml, text and --json output and the exit-code mapping.
3
3
  // starci app release gate [--execute] [--sonar] [--source <ref>] [--tag-prefix <prefix>] [--backfill <tag>] [--json]
4
- // starci app release push [--execute] [--remote <name>] [--urgent --reason <text>] [--json]
4
+ // starci app release push [--execute] [--remote <name>] [--urgent --reason <text> [--lint-baseline <tag>]] [--json]
5
5
  // `harness` of the app IO ({ version, role, openTicket }) is what the starci CLI hands in: the caller's role an urgent record names and the ticket
6
6
  // queue a red back-fill files into.
7
7
  // Every action is a dry run unless --execute is given. A refusal is a StackError (exit 2); a failed step returns ok false (exit 1).
@@ -95,11 +95,12 @@ const ACTIONS = {
95
95
  }),
96
96
  },
97
97
  push: {
98
- spec: { boolean: ['--execute', '--json', '--urgent'], value: ['--remote', '--reason'] },
98
+ spec: { boolean: ['--execute', '--json', '--urgent'], value: ['--remote', '--reason', '--lint-baseline'] },
99
99
  run: (ctx, flags, harness) => {
100
100
  if (flags.reason !== undefined && flags.urgent !== true) throw refusal('RELEASE_USAGE', '--reason belongs to an urgent release (--urgent)');
101
+ if (flags['lint-baseline'] !== undefined && flags.urgent !== true) throw refusal('RELEASE_USAGE', '--lint-baseline belongs to an urgent release (--urgent)');
101
102
  const config = loadReleaseConfig(ctx.cwd);
102
- if (flags.urgent === true) return releaseUrgentPush(ctx, config, { execute: flags.execute === true, remote: flags.remote, reason: flags.reason, role: harness?.role ?? ctx.env.STARCI_ROLE });
103
+ if (flags.urgent === true) return releaseUrgentPush(ctx, config, { execute: flags.execute === true, remote: flags.remote, reason: flags.reason, lintBaseline: flags['lint-baseline'], role: harness?.role ?? ctx.env.STARCI_ROLE });
103
104
  return releasePush(ctx, config, { execute: flags.execute === true, remote: flags.remote });
104
105
  },
105
106
  },
@@ -0,0 +1,123 @@
1
+ // lint-baseline.mjs - the lint row of an urgent release judged against a baseline release tag (`release push --urgent --lint-baseline <tag>`,
2
+ // owner ruling urgent-lint-baseline 2026-10-29: an app whose lint backlog predates the release ships when the release adds no finding of its own).
3
+ // The managed lint (`npm run lint`, which ends in `starci app lint`) runs twice, each writing its findings as a Sonar Generic Issue Import file
4
+ // (`-- --sonar <file>`): at HEAD, and at the baseline tag in a throwaway `git worktree` that borrows HEAD's installs (each node_modules folder is
5
+ // linked in as a directory junction, unlinked before the worktree is removed, never deleted through). A finding is the same finding when its
6
+ // engine, rule, file and message match (lines move); a finding left over is then matched on engine, rule and message alone (a file that moved).
7
+ // What HEAD holds beyond the baseline is new: zero new findings is green, any is red, and a lint that could not run on either side is red. The
8
+ // row names both counts and both reports with their sha256, and the new findings go to lint-new.json beside the record, so the back-fill's full
9
+ // gate (which this changes nothing in) still sees the whole backlog.
10
+ import { createHash, randomBytes } from 'node:crypto';
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { refusal } from '../stack/errors.mjs';
15
+ import { git, runGate } from './gate.mjs';
16
+
17
+ /** The owner's ruling a baseline-judged lint row cites. */
18
+ export const LINT_BASELINE_RULING = 'owner ruling urgent-lint-baseline 2026-10-29: an urgent release whose lint is red only with findings its baseline tag already had ships; a new finding is red';
19
+ const LINK_DEPTH = 3;
20
+ const NEW_SHOWN = 50;
21
+
22
+ const sha256 = (file) => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
23
+
24
+ /** The findings of a Sonar Generic Issue Import file as { engine, rule, file, line, message }, or null when it is missing or unreadable. */
25
+ export function sonarFindings(file) {
26
+ let doc;
27
+ try { doc = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
28
+ if (!doc || !Array.isArray(doc.issues)) return null;
29
+ return doc.issues.map((issue) => ({
30
+ engine: String(issue.engineId ?? ''), rule: String(issue.ruleId ?? ''), file: String(issue.primaryLocation?.filePath ?? ''),
31
+ line: issue.primaryLocation?.textRange?.startLine ?? null, message: String(issue.primaryLocation?.message ?? ''),
32
+ }));
33
+ }
34
+
35
+ /** The findings of `head` the `baseline` does not hold: matched on engine, rule, file and message, then the rest on engine, rule and message. */
36
+ export function newFindings(head, baseline) {
37
+ const take = (pool, key) => { const left = pool.get(key) ?? 0; if (left === 0) return false; pool.set(key, left - 1); return true; };
38
+ const exact = (finding) => `${finding.engine}\u0000${finding.rule}\u0000${finding.file}\u0000${finding.message}`;
39
+ const loose = (finding) => `${finding.engine}\u0000${finding.rule}\u0000${finding.message}`;
40
+ const exactPool = new Map();
41
+ for (const finding of baseline) exactPool.set(exact(finding), (exactPool.get(exact(finding)) ?? 0) + 1);
42
+ const unmatched = head.filter((finding) => !take(exactPool, exact(finding)));
43
+ const loosePool = new Map();
44
+ for (const finding of baseline) {
45
+ const left = exactPool.get(exact(finding)) ?? 0;
46
+ if (left > 0) { exactPool.set(exact(finding), left - 1); loosePool.set(loose(finding), (loosePool.get(loose(finding)) ?? 0) + 1); }
47
+ }
48
+ return unmatched.filter((finding) => !take(loosePool, loose(finding)));
49
+ }
50
+
51
+ /** Every node_modules folder of `root` within LINK_DEPTH levels (never inside one), app-relative. */
52
+ function installFolders(root) {
53
+ const found = [];
54
+ const walk = (rel, depth) => {
55
+ let entries;
56
+ try { entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { return; }
57
+ for (const entry of entries) {
58
+ if (!entry.isDirectory() || entry.name === '.git') continue;
59
+ const child = rel ? path.join(rel, entry.name) : entry.name;
60
+ if (entry.name === 'node_modules') found.push(child);
61
+ else if (depth < LINK_DEPTH) walk(child, depth + 1);
62
+ }
63
+ };
64
+ walk('', 0);
65
+ return found;
66
+ }
67
+
68
+ /** Removes a link made by this module: the link alone, never what it points at. */
69
+ function unlink(link) {
70
+ try { fs.unlinkSync(link); } catch { try { fs.rmdirSync(link); } catch { /* already gone */ } }
71
+ }
72
+
73
+ /** The lint of `gate` with its findings written to `report`: { row, findings } (findings null when the lint could not run). */
74
+ function lintTo(ctx, gate, { name, report, dir, platform }) {
75
+ fs.rmSync(report, { force: true });
76
+ const row = runGate(ctx, { ...gate, name, command: [...gate.command, '--', '--sonar', report] }, { dir, platform, credentialNames: [] });
77
+ const ran = row.pass || row.detail === 'exit 1';
78
+ return { row, findings: ran ? sonarFindings(report) : null };
79
+ }
80
+
81
+ /**
82
+ * The lint row of an urgent release against `tag`: { name, command, pass, detail, log, logSha256, baseline }. Refuses a tag that is not a
83
+ * commit. `dir` is the record folder of HEAD, where both reports, both logs and lint-new.json are written.
84
+ */
85
+ export function baselineLint(ctx, gate, { tag, dir, platform }) {
86
+ const commit = git(ctx, ['rev-parse', '--verify', '--quiet', `${tag}^{commit}`], { allowFail: true });
87
+ if (commit.code !== 0 || commit.stdout === '') throw refusal('RELEASE_URGENT_LINT_BASELINE_TAG', `--lint-baseline ${tag} names no commit`);
88
+ fs.mkdirSync(dir, { recursive: true });
89
+ const headReport = path.join(dir, 'lint-head.sonar.json');
90
+ const head = lintTo(ctx, gate, { name: 'lint', report: headReport, dir, platform });
91
+ const row = (pass, detail, baseline = null) => ({ ...head.row, pass, detail, baseline: baseline && { tag, commit: commit.stdout, ruling: LINT_BASELINE_RULING, ...baseline } });
92
+ if (head.findings === null) return row(false, `the lint at HEAD could not run (${head.row.detail})`);
93
+ if (head.findings.length === 0) return row(true, 'no finding at HEAD', { findings: 0, headFindings: 0, newFindings: 0 });
94
+ const tree = path.join(os.tmpdir(), `starci-lint-baseline-${randomBytes(4).toString('hex')}`);
95
+ const links = [];
96
+ const added = git(ctx, ['worktree', 'add', '--detach', tree, commit.stdout], { allowFail: true });
97
+ if (added.code !== 0) return row(false, `the baseline worktree of ${tag} could not be made`);
98
+ try {
99
+ for (const rel of installFolders(ctx.cwd)) {
100
+ const link = path.join(tree, rel);
101
+ if (fs.existsSync(link) || !fs.existsSync(path.dirname(link))) continue;
102
+ fs.symlinkSync(path.join(ctx.cwd, rel), link, 'junction');
103
+ links.push(link);
104
+ }
105
+ const baseReport = path.join(dir, 'lint-baseline.sonar.json');
106
+ const base = lintTo(Object.create(ctx, { cwd: { value: tree } }), gate, { name: 'lint-baseline', report: baseReport, dir, platform });
107
+ if (base.findings === null) return row(false, `the lint at the baseline ${tag} could not run (${base.row.detail}; log ${base.row.log})`);
108
+ const fresh = newFindings(head.findings, base.findings);
109
+ fs.writeFileSync(path.join(dir, 'lint-new.json'), `${JSON.stringify(fresh, null, 2)}\n`);
110
+ const counts = {
111
+ findings: base.findings.length, headFindings: head.findings.length, newFindings: fresh.length,
112
+ headReport, headReportSha256: sha256(headReport), baselineReport: baseReport, baselineReportSha256: sha256(baseReport), baselineLog: base.row.log,
113
+ newShown: fresh.slice(0, NEW_SHOWN).map((finding) => `${finding.file}:${finding.line ?? '-'} ${finding.rule} ${finding.message}`),
114
+ };
115
+ const detail = `${head.findings.length} finding(s) at HEAD, ${base.findings.length} at ${tag}, ${fresh.length} new${fresh.length > 0 ? ` (${path.join(dir, 'lint-new.json')})` : ''}`;
116
+ return row(fresh.length === 0, detail, counts);
117
+ } finally {
118
+ links.reverse().forEach(unlink);
119
+ // A link still present would let the removal delete through it into HEAD's installs: the worktree then stays for a person to unlink.
120
+ if (links.every((link) => !fs.existsSync(link))) git(ctx, ['worktree', 'remove', '--force', tree], { allowFail: true });
121
+ else ctx.stderr?.(`lint baseline: ${tree} keeps a linked node_modules; unlink it (cmd /c rmdir <link>) before removing the worktree\n`);
122
+ }
123
+ }
@@ -11,6 +11,7 @@ import { firstLine } from '../stack/context.mjs';
11
11
  import { failure, refusal } from '../stack/errors.mjs';
12
12
  import { assertUnmoved, git, inspect, releaseDir, runGate, summaryOf } from './gate.mjs';
13
13
  import { assertNames, branchRefs, probe, tagRefs } from './push.mjs';
14
+ import { baselineLint } from './lint-baseline.mjs';
14
15
  import { URGENT_RULING, URGENT_SCHEMA, greenRow, recordRow, writeUrgent } from './records.mjs';
15
16
 
16
17
  /** The fast local checks of an urgent release, by gate name, in the order they run. */
@@ -46,11 +47,19 @@ function changedLint(ctx, gate, prefix) {
46
47
  return { gate: { ...gate, command: ['npx', 'starci', 'app', 'lint', '--changed', ...files] }, note: `${files.length} file(s) changed since ${since}` };
47
48
  }
48
49
 
49
- /** The urgent checks this app declares, from its release gates; a lint row is narrowed to the changed files. */
50
- function urgentGates(ctx, config, prefix) {
50
+ /**
51
+ * The urgent checks this app declares, from its release gates; a lint row is narrowed to the changed files, or, with `lintBaseline` (a release
52
+ * tag), judged whole against that tag's findings (lint-baseline.mjs), which only the managed lint can be.
53
+ */
54
+ function urgentGates(ctx, config, prefix, lintBaseline) {
51
55
  const declared = URGENT_CHECKS.map((name) => config.gates.find((gate) => gate.name === name)).filter(Boolean);
52
56
  if (declared.length === 0) throw refusal('RELEASE_URGENT_NO_CHECKS', `the release gates declare none of ${URGENT_CHECKS.join(', ')}: an urgent release still runs its fast local checks`);
53
- return declared.map((gate) => (gate.name === 'lint' ? { name: gate.name, ...changedLint(ctx, gate, prefix) } : { name: gate.name, gate, note: null }));
57
+ return declared.map((gate) => {
58
+ if (gate.name !== 'lint') return { name: gate.name, gate, note: null };
59
+ if (lintBaseline === undefined) return { name: gate.name, ...changedLint(ctx, gate, prefix) };
60
+ if (gate.command.join(' ') !== MANAGED_LINT) throw refusal('RELEASE_URGENT_LINT_BASELINE_UNMANAGED', `--lint-baseline judges the managed lint (${MANAGED_LINT}), and this app's lint gate runs ${gate.command.join(' ')}`);
61
+ return { name: gate.name, gate, baseline: lintBaseline, note: `the whole app, judged against ${lintBaseline}: only a finding new since it is red (owner ruling urgent-lint-baseline)` };
62
+ });
54
63
  }
55
64
 
56
65
  /** Runs (or reuses) each check in order and stops at the first red one. Returns the rows of the record. */
@@ -62,6 +71,12 @@ function runChecks(ctx, checks, { common, head, dir, platform }) {
62
71
  rows.push({ name: check.name, command: null, pass: true, reused: false, detail: check.note, log: null, logSha256: null });
63
72
  continue;
64
73
  }
74
+ if (check.baseline !== undefined) {
75
+ const row = baselineLint(ctx, check.gate, { tag: check.baseline, dir, platform });
76
+ rows.push({ ...row, reused: false, note: check.note });
77
+ if (!row.pass) break;
78
+ continue;
79
+ }
65
80
  const command = check.gate.command.join(' ');
66
81
  const reused = greenRow(common, head, check.name, command);
67
82
  if (reused) {
@@ -97,7 +112,7 @@ export async function releaseUrgentPush(ctx, config, options = {}) {
97
112
  const { head, chosen } = facts;
98
113
  const common = releaseDir(ctx);
99
114
  const dir = path.join(common, head.slice(0, 12));
100
- const checks = urgentGates(ctx, config, config.tagPrefix);
115
+ const checks = urgentGates(ctx, config, config.tagPrefix, options.lintBaseline);
101
116
  const out = [...facts.out, `urgent ${URGENT_RULING}`, `reason ${reason}`, `role ${role}`, ...planOf(checks)];
102
117
  const data = { head, tag: chosen.tag, remote, branch, urgent: true, reason, role, checks: [], pushed: false };
103
118
  if (facts.red.length > 0) return { ok: false, lines: [...out, ...facts.red.map((item) => `RED: ${item}`), 'nothing run, nothing pushed.'], data: { ...data, red: facts.red } };
@@ -31,35 +31,35 @@ pins:
31
31
  source: packages/event-stream/package.json
32
32
  why: 'the one server-sent-events client of every front end (fe-stack event-stream, owner:event-stream-package): the transport client layer (modules/api/sse/clients) creates one instance for the app with the bearer token source and the stream operations follow on it; it carries Last-Event-ID resume, the capped doubling backoff, the heartbeat timeout, the single 401 renewal and the useSWRSubscription adapter, so no app keeps a hand-written reader.'
33
33
  '@starci/grammar':
34
- version: 0.15.25
34
+ version: 0.15.27
35
35
  group: starci
36
36
  install: registry
37
37
  side: fe
38
38
  source: packages/grammar/package.json
39
39
  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.'
40
40
  '@starci/eslint-canon-be':
41
- version: 3.8.12
41
+ version: 3.8.14
42
42
  group: starci
43
43
  install: registry
44
44
  side: be
45
45
  source: packages/eslint-canon-be/package.json
46
46
  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.'
47
47
  '@starci/eslint-canon-fe':
48
- version: 9.5.14
48
+ version: 9.5.16
49
49
  group: starci
50
50
  install: registry
51
51
  side: fe
52
52
  source: packages/eslint-canon-fe/package.json
53
53
  why: 'the front-end ESLint canon: `loadHfs(import.meta.url)` of fe/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the fe 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; the front end has no tests (FE_NO_TESTS R97 in hfs) and no-vietnamese-in-source (R91) applies.'
54
54
  '@starci/eslint-grammar-core':
55
- version: 0.15.25
55
+ version: 0.15.27
56
56
  group: starci
57
57
  install: registry
58
58
  side: fe
59
59
  source: packages/eslint-grammar-core/package.json
60
60
  why: 'the StarCi Grammar component API lint, versioned with @starci/grammar; front ends compose this family package with the universal FE canon.'
61
61
  '@starci/eslint-grammar-offset-pop':
62
- version: 0.15.25
62
+ version: 0.15.27
63
63
  group: starci
64
64
  install: registry
65
65
  side: fe
@@ -85,7 +85,7 @@ pins:
85
85
  side: both
86
86
  source: packages/prettier-config/package.json
87
87
  '@starci/jest-preset':
88
- version: 2.5.0
88
+ version: 2.5.1
89
89
  group: starci
90
90
  install: registry
91
91
  side: be
@@ -106,7 +106,7 @@ pins:
106
106
  source: packages/ai-router/package.json
107
107
  why: 'the AI pool router of a back end: a NestJS module that routes OpenAI-compatible chat, stream and embeddings calls across keys, models and providers, with @starci/ai-router/testing for its specs; @starci/jest-preset compiles it as an ESM-only dependency.'
108
108
  '@starci/hfs':
109
- version: 4.11.13
109
+ version: 4.11.15
110
110
  group: starci
111
111
  install: registry
112
112
  side: both
@@ -1629,7 +1629,7 @@ rules:
1629
1629
  witness:
1630
1630
  - {"path":"packages/eslint/be/r80-inbox-dedupe-required.spec.mjs","edition":"lite","codes":["BE_INBOX_DEDUPE_MISSING"]}
1631
1631
  - {"path":"packages/eslint/be/r80-inbox-dedupe-required.spec.mjs","edition":"full","codes":["BE_INBOX_DEDUPE_MISSING"]}
1632
- law: "Every service method that takes a delivery (a public method of a `*.service.ts` whose first parameter has an `eventId`) makes `claim(source, eventId)` on the `Inbox` port its first awaited expression and returns early when the claim answers `false`; consumers stay thin doors (R88) and dispatch one command to the handler whose service claims. SignedWebhook controllers verify first and call one domain recording intake directly (R182, R183); a reactor or job dispatches the processing command after the inbox receipt commits."
1632
+ law: "Every service method that takes a delivery (a public method of a `*.service.ts` whose first parameter has an `eventId`) makes `claim(source, eventId)` on the `Inbox` port, or `claimRow(source, eventId, tx, receipt)` on its `EntityInbox` extension (the claim, then the receipt entity row inserted only for the winning claim), its first awaited expression and returns early on a repeat: when `claim` answers `false` or `claimRow` answers no receipt id (`undefined`); consumers stay thin doors (R88) and dispatch one command to the handler whose service claims. SignedWebhook controllers verify first and call one domain recording intake directly (R182, R183); a reactor or job dispatches the processing command after the inbox receipt commits."
1633
1633
  kinds: [lint, design]
1634
1634
  gates: [pre-commit, settle, land, ci]
1635
1635
  failureCodes: ["BE_INBOX_DEDUPE_MISSING"]
@@ -4233,7 +4233,7 @@ rules:
4233
4233
  code: "HFS_AGE_KEY_CUSTODY"
4234
4234
  editions: [lite, full]
4235
4235
  docs: [docs/host-secrets.md#application-secret-rules]
4236
- law: "The age identity that seals and opens an app's `.starcistacks/<env>/secrets/*.enc` is host-local custody only: it lives in the untracked `.claude/secret.env` (as `SOPS_AGE_KEY`, which wins over the legacy `keys.txt` and is handed to sops through the `SOPS_AGE_KEY` child environment, never as an argument and never printed) or in the sops config dir's `keys.txt`; a tracked `.claude/secret.env`, `keys.txt` or `*.agekey` is the identity committed. The three files the secret custody depends on - `src/modules/platform/config/env-source.config.ts`, `src/modules/platform/http-security/origin.guard.ts` and `src/modules/platform/http-security/webhook-signature.service.ts` - are hash-sensitive canon, not files to edit: their bytes equal the `be/skeleton` template they were scaffolded from, judged by sha256."
4236
+ law: "The age identity that seals and opens an app's `.starcistacks/<env>/secrets/*.enc` is host-local custody only: it lives in the untracked `.claude/secret.env` (as `SOPS_AGE_KEY`, which wins over the legacy `keys.txt` and is handed to sops through the `SOPS_AGE_KEY` child environment, never as an argument and never printed) or in the sops config dir's `keys.txt`; a tracked `.claude/secret.env`, `keys.txt` or `*.agekey` is the identity committed. The three files the secret custody depends on - `src/modules/platform/config/env-source.config.ts`, `src/modules/platform/http-security/origin.guard.ts` and `src/modules/platform/http-security/webhook-signature.service.ts` - are hash-sensitive canon, not files to edit: their bytes equal the `be/skeleton` template of the @starci/hfs version the app pins (never of a newer hfs running the check), judged by sha256."
4237
4237
  kinds: [check]
4238
4238
  gates: [settle, land, ci]
4239
4239
  failureCodes: ["HFS_AGE_KEY_CUSTODY", "HFS_CANON_COPY_DRIFT"]
@@ -4418,7 +4418,7 @@ rules:
4418
4418
  - id: R263
4419
4419
  code: "BE_WEBHOOK_SCOPE"
4420
4420
  amendedBy: [owner:oauth-redirect-not-webhook, owner:webhook-receipt-port]
4421
- law: "SignedWebhook public metadata belongs only to a webhook HTTP door or an exact domain verifier declared in its HTTP module's exported webhookVerifiers array. A public controller route containing webhook, callback or events belongs in the webhook door; the one exception is a third-party OAuth redirect (owner:oauth-redirect-not-webhook): a GET route that declares PublicReason.AuthHandshake and whose path is not a webhook or events path, which has no signature to verify and is not a door. A POST, a webhook or events path, and any other reason are still judged. A receipt transaction may call a domain receipt port (owner:webhook-receipt-port): a class with no base class whose constructor takes only platform ports and TypeORM, one of them the platform Inbox; a call on any other domain service or on a bus inside the transaction is processing. Domain intake methods identified by a first *Id parameter or DTO property, or raw-body signature input, claim the shared Inbox with the stable delivery key and return early on a duplicate before doing work. The receipt transaction records the inbox delivery and publishes its typed outbox event; process callbacks, domain processing and command dispatch run only after commit in a reactor or job."
4421
+ law: "SignedWebhook public metadata belongs only to a webhook HTTP door or an exact domain verifier declared in its HTTP module's exported webhookVerifiers array. A public controller route containing webhook, callback or events belongs in the webhook door; the one exception is a third-party OAuth redirect (owner:oauth-redirect-not-webhook): a GET route that declares PublicReason.AuthHandshake and whose path is not a webhook or events path, which has no signature to verify and is not a door. A POST, a webhook or events path, and any other reason are still judged. A receipt transaction may call a domain receipt port (owner:webhook-receipt-port): a class with no base class whose constructor takes only platform ports and TypeORM, one of them the platform Inbox or its EntityInbox; a call on any other domain service or on a bus inside the transaction is processing. Domain intake methods identified by a first *Id parameter or DTO property, or raw-body signature input, claim the shared Inbox with the stable delivery key (claim, or claimRow on its EntityInbox with the receipt row and the transaction's own manager) and return early on a duplicate (false from claim, undefined from claimRow) before doing work. The receipt transaction records the inbox delivery and publishes its typed outbox event; process callbacks, domain processing and command dispatch run only after commit in a reactor or job."
4422
4422
  kinds: [lint]
4423
4423
  gates: ["pre-commit","settle","land","ci"]
4424
4424
  failureCodes: ["BE_WEBHOOK_SCOPE", "BE_WEBHOOK_INBOX_KEY"]
@@ -370,8 +370,9 @@ sourceMaintenance: >-
370
370
  verifies first and calls the supplied domain service's record<Provider>Delivery once. Implement that method as the
371
371
  transactional inbox receipt/outbox recording intake above, then add its reactor or job separately.
372
372
  In lite, the generated POST verifies first and calls <Provider>InboxService.record<Provider>Delivery. This record-only
373
- domain intake uses recordWebhookDelivery to insert a pending provider inbox row atomically in the app's Postgres, unique on
374
- (provider, delivery_id), without processing it or marking it complete. Add a reactor or job separately to consume the
373
+ domain intake injects the EntityInbox (InjectEntityInbox) and awaits claimRow first: it claims the delivery id and, for the
374
+ winning claim only, inserts the pending provider inbox row through its <Provider>InboxEntity in the same transaction, unique
375
+ on (provider, delivery_id), without processing it or marking it complete. Add a reactor or job separately to consume the
375
376
  committed pending row and dispatch the processing command (reactors.yaml, jobs.yaml). The --service option validates the
376
377
  future domain processing owner; the webhook writer does not import or call that owner synchronously and does not
377
378
  synthesize a consumer.
@@ -1,18 +1,25 @@
1
1
  // canon-copy-drift.mjs - HFS_CANON_COPY_DRIFT (R253): a handful of scaffolded files are hash-sensitive canon,
2
2
  // not files to edit. The drift judgement is one sha256 against the bytes of the be/skeleton template the file was
3
- // scaffolded from - the file equals canon, or it has drifted. A finding carries the path and both hashes, never
4
- // file content.
3
+ // scaffolded from - the file equals canon, or it has drifted. That template is the one of the @starci/hfs version the app
4
+ // pins (its lockfile's resolution of node_modules/@starci/hfs, else an exact package.json pin), never a newer hfs that
5
+ // happens to run the check: a skeleton change reaches an app only when the app raises its hfs. This package's own
6
+ // templates serve when it is that version or the app pins none; else an installed copy at the pinned version does; with
7
+ // neither at hand the copy is left to the app's own run of its pinned hfs. A finding carries the path and both hashes,
8
+ // never file content.
5
9
  import crypto from 'node:crypto';
6
10
  import fs from 'node:fs';
7
11
  import path from 'node:path';
8
12
  import { found } from './read.mjs';
9
13
 
10
14
  const CANON_COPY = 'HFS_CANON_COPY_DRIFT';
11
- const TEMPLATE_ROOTS = [
15
+ const OWN_ROOT = path.resolve(import.meta.dirname, '../../../..');
16
+ const OWN_TEMPLATE_ROOTS = [
12
17
  path.resolve(import.meta.dirname, '../../../packages/hfs/templates'),
13
- path.resolve(import.meta.dirname, '../../../../templates'),
18
+ path.join(OWN_ROOT, 'templates'),
14
19
  ];
15
20
  const TEMPLATE_DIR = 'be/skeleton/';
21
+ const HFS_LOCK_KEY = 'node_modules/@starci/hfs';
22
+ const EXACT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
16
23
 
17
24
  // The three managed files the standard's secret-custody law pins byte-for-byte.
18
25
  const CANON_PATHS = [
@@ -23,8 +30,46 @@ const CANON_PATHS = [
23
30
  const REGEX_ESCAPE = String.raw`\$&`;
24
31
  const CANON_SUFFIX = new RegExp(`(?:^|/)(${CANON_PATHS.map((rel) => rel.replace(/[.*+?^${}()|[\]\\]/g, REGEX_ESCAPE)).join('|')})$`);
25
32
 
26
- const templateBytes = (rel) => {
27
- for (const root of TEMPLATE_ROOTS) {
33
+ const readJson = (file) => {
34
+ try {
35
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
36
+ } catch {
37
+ return undefined;
38
+ }
39
+ };
40
+ const versionAt = (folder) => readJson(path.join(folder, 'package.json'))?.version;
41
+
42
+ /** The @starci/hfs version the app at `repoRoot` pins: its lockfile's resolution (hoisted first), else an exact package.json pin. */
43
+ export function pinnedHfsVersion(repoRoot) {
44
+ const packages = readJson(path.join(repoRoot, 'package-lock.json'))?.packages ?? {};
45
+ const locked = Object.keys(packages)
46
+ .filter((key) => key === HFS_LOCK_KEY || key.endsWith(`/${HFS_LOCK_KEY}`))
47
+ .sort((left, right) => left.length - right.length)
48
+ .map((key) => packages[key]?.version)
49
+ .find((version) => typeof version === 'string');
50
+ if (locked) return locked;
51
+ const manifest = readJson(path.join(repoRoot, 'package.json')) ?? {};
52
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
53
+ const spec = manifest[field]?.['@starci/hfs'];
54
+ if (typeof spec === 'string' && EXACT.test(spec)) return spec;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /** The template roots of the app's pinned @starci/hfs, or null when no copy of that version is at hand. */
60
+ export function pinnedTemplateRoots(repoRoot) {
61
+ const pin = pinnedHfsVersion(repoRoot);
62
+ if (pin === undefined || versionAt(OWN_ROOT) === pin) return OWN_TEMPLATE_ROOTS;
63
+ const copies = [
64
+ path.join(repoRoot, 'node_modules', '@starci', 'hfs'),
65
+ path.join(repoRoot, 'node_modules', 'starci-harness', 'node_modules', '@starci', 'hfs'),
66
+ ];
67
+ const installed = copies.find((copy) => versionAt(copy) === pin);
68
+ return installed === undefined ? null : [path.join(installed, 'templates')];
69
+ }
70
+
71
+ const templateBytes = (roots, rel) => {
72
+ for (const root of roots) {
28
73
  const file = path.join(root, TEMPLATE_DIR, rel);
29
74
  try {
30
75
  const bytes = fs.readFileSync(file);
@@ -37,10 +82,12 @@ const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex'
37
82
 
38
83
  export function canonCopyDriftFindings({ repoRoot, files, inScope }) {
39
84
  const findings = [];
85
+ const roots = pinnedTemplateRoots(repoRoot);
86
+ if (roots === null) return findings;
40
87
  for (const file of files.filter((f) => !inScope || inScope(f))) {
41
88
  const hit = CANON_SUFFIX.exec(file.replaceAll('\\', '/'));
42
89
  if (!hit) continue;
43
- const expected = templateBytes(hit[1]);
90
+ const expected = templateBytes(roots, hit[1]);
44
91
  if (!expected) continue;
45
92
  let actual;
46
93
  try {
@@ -7,7 +7,10 @@ import { ScaffoldError } from './service.mjs';
7
7
  export function addModuleImport(lines, { importLine, entry, relative, noun }) {
8
8
  const active = compositionCode(lines.join('\n')).split('\n');
9
9
  const imported = active.some(line => line.replace(/;\s*$/, '') === importLine);
10
+ // An area group spread once is registered whatever its argument (the lite root passes `tokens.verify` to domainModules).
11
+ const group = /^\.\.\.(\w+Modules)\(/.exec(entry)?.[1];
10
12
  const registered = active.some(line => line.trim() === `${entry},` ||
13
+ (group !== undefined && line.includes(`...${group}(`)) ||
11
14
  (/\bimports:\s*\[/.test(line) && !line.trim().startsWith('//') && line.replace(/\s+/g, '').includes(entry.replace(/\s+/g, ''))));
12
15
  const lastImport = active.reduce((last, line, index) => line.startsWith('import ') ? index : last, -1);
13
16
  const importsLine = line => /\bimports:\s*\[/.test(line) && !line.trim().startsWith('//');