@starci/hfs 4.11.12 → 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 (56) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +1 -1
  3. package/db/migrate.mjs +1 -1
  4. package/db/postgres.mjs +38 -3
  5. package/package.json +1 -1
  6. package/release/index.mjs +6 -5
  7. package/release/lint-baseline.mjs +123 -0
  8. package/release/urgent.mjs +19 -4
  9. package/runtime/knowledge/hfs/canon-pins.yaml +7 -7
  10. package/runtime/knowledge/hfs/rules.yaml +3 -3
  11. package/runtime/knowledge/patterns/be/webhooks.yaml +3 -2
  12. package/runtime/scripts/api/sops/lib.mjs +25 -3
  13. package/runtime/scripts/api/sops/seal.mjs +4 -3
  14. package/runtime/scripts/hfs/rules/canon-copy-drift.mjs +54 -7
  15. package/runtime/scripts/hfs/secret-init.mjs +15 -0
  16. package/runtime/scripts/hfs/secret-sops.mjs +65 -33
  17. package/runtime/scripts/lib/sops-envelope.mjs +36 -11
  18. package/scaffold/add-compose.mjs +3 -0
  19. package/scaffold/add-inbox-lite.mjs +45 -23
  20. package/scaffold/lite-exports.mjs +13 -0
  21. package/src/main.mjs +5 -5
  22. package/stack/age-install.mjs +10 -2
  23. package/stack/cli.mjs +5 -3
  24. package/stack/context.mjs +2 -2
  25. package/stack/deploy.mjs +6 -2
  26. package/stack/remote.mjs +29 -8
  27. package/stack/sealed.mjs +15 -11
  28. package/stack/server-key.mjs +31 -7
  29. package/stack/urgent-floor.mjs +101 -7
  30. package/templates/app/ci-workflows/github/workflows/stack-key-restore.yml +1 -1
  31. package/templates/app/ci-workflows-lite/github/workflows/stack-key-restore.yml +1 -1
  32. package/templates/be/inbox/entities.index.ts.tpl +4 -0
  33. package/templates/be/inbox/entity.ts.tpl +29 -0
  34. package/templates/be/inbox/index.ts.tpl +1 -0
  35. package/templates/be/inbox/platform/inbox/inbox.decorators.ts.tpl +5 -2
  36. package/templates/be/inbox/platform/inbox/inbox.port.ts.tpl +29 -1
  37. package/templates/be/inbox/platform/inbox/inbox.service.spec.ts.tpl +65 -1
  38. package/templates/be/inbox/platform/inbox/inbox.service.ts.tpl +48 -10
  39. package/templates/be/inbox/platform/inbox/index.ts.tpl +2 -2
  40. package/templates/be/inbox/service.spec.ts.tpl +39 -15
  41. package/templates/be/inbox/service.ts.tpl +13 -13
  42. package/templates/be/inbox/webhook-door.spec.ts.tpl +4 -1
  43. package/templates/be/skeleton/src/modules/domain/note/note.service.ts +3 -4
  44. package/templates/be/skeleton/src/modules/domain/note/persistence/note.rows.ts +4 -0
  45. package/templates/be/skeleton/src/modules/platform/database/errors/database.error.ts +3 -0
  46. package/templates/be/skeleton/src/modules/platform/database/index.ts +1 -0
  47. package/templates/be/skeleton/src/modules/platform/database/returned-rows.policy.spec.ts +84 -0
  48. package/templates/be/skeleton/src/modules/platform/database/returned-rows.policy.ts +61 -0
  49. package/templates/be/skeleton/src/modules/platform/http-security/persistence/rate-limit.rows.ts +5 -0
  50. package/templates/be/skeleton/src/modules/platform/http-security/rate-limit.guard.ts +3 -3
  51. package/templates/be/skeleton-lite/src/modules/platform/database/errors/database.error.ts +3 -0
  52. package/templates/be/skeleton-lite/src/modules/platform/database/index.ts +1 -0
  53. package/templates/be/skeleton-lite/src/modules/platform/http-security/rate-limit.guard.spec.ts +41 -33
  54. package/templates/be/skeleton-lite/src/modules/platform/http-security/rate-limit.guard.ts +15 -9
  55. package/templates/be/inbox/database-client.spec.ts.tpl +0 -45
  56. package/templates/be/inbox/database-client.ts.tpl +0 -45
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
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
+
24
+ ## 4.11.13 - 2026-10-29
25
+
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.
27
+ - Fixed: every seal keeps the member's full recipient set (`secret-sops.mjs` `sealRecipients`): the caller's set, else the environment's `.sops.yaml` rule, else the set the existing member is sealed to, under a private one-rule sops config when no rule of the app matches (sops refuses an unmatched file even with `--age`). `set`, `migrate`, `split` and the edit verbs on a production member keep the server recipient.
28
+ - Changed: one age identity lookup for every decrypt of a member, `decryptionIdentity` (`secret-init.mjs`): the environment, the app's `.claude/secret.env`, its main checkout's, the harness CLI's secret.env (`hostIdentity`), then sops' keys.txt. `defaultSops` uses it, `stack`, `release` and `db` hand their context `hostIdentity` (`stackContext`, `release/index.mjs` `contextOf`, `main.mjs`), so a stack deploy opens its members with the same identity `app secret` does; `stack/sealed.mjs` `hasAgeIdentity` reads the seam's finding instead of guessing from files.
29
+ - Changed: a member that cannot be opened is refused naming the member, the format it was read as, its recipients, where the identity came from and its recipient, and why: a failed selected sops run names its class (`sopsFailureClass`: no-matching-identity, mac-mismatch, unparsable-document, timeout, exit-<n>) instead of "the selected invocation was not qualified" alone.
30
+ - Changed: the deploy's sealed SSH members (`deploy.remote.sealed`) are read as what they are: a `.enc.yaml` member through `decrypt(file, "yaml")` and its key, a legacy `.enc` through the binary envelope. The keys are `SEALED_SSH_KEYS` (`stack/remote.mjs`): `privateKey` of `sshKey`, `knownHosts` of `knownHosts`; the `key` and `known_hosts` aliases are gone, and a member without its key is refused naming the keys it holds.
31
+ - Fixed: `server-key` resolves age-keygen as root, the way it calls it (`RESOLVE_AGE_KEYGEN`, `ageKeygenScript`: root's PATH, then `/usr/local/bin`, `/usr/bin`, `/bin`): on AlmaLinux 10 sudo's secure_path leaves `/usr/local/bin` out, so the deploy user's `command -v age-keygen` passed and the root script exited 127 ("age-keygen failed on the server"). The static age installer links age and age-keygen from `/usr/bin` and counts age as present only when root sees it too; `stack-key-restore.yml` (both editions) adds `/usr/local/bin` to its root shell's PATH.
32
+ - Changed: the bundled canon pins name hfs 4.11.13, eslint-canon-be 3.8.12, eslint-canon-fe 9.5.14 and the Grammar family 0.15.25.
33
+
3
34
  ## 4.11.12 - 2026-10-29
4
35
 
5
36
  - Changed: the skeleton canon gate (`src/scaffold-template-canon-be.spec.mjs`) lints every file under `be/src/modules/platform` of both editions with the starci-be rules, no longer `platform/http` alone; both editions are green.
package/README.md CHANGED
@@ -230,7 +230,7 @@ one key its whole text or several one `KEY=value` line each, `--from-file KEY=pa
230
230
  A member is sealed to its environment's rule of the managed `.sops.yaml`; `recipients <env> [--add|--remove <age1...|owner>]`
231
231
  rewrites that rule (`environmentRecipients`, `secret-init.mjs`), and `init` takes the owner's identity as the app's recipient.
232
232
  Re-sealing a member whose every key the set replaces needs no age identity; adding a key to one does, and the identity is found
233
- by itself (`localAgeIdentity`): SOPS_AGE_KEY or SOPS_AGE_KEY_FILE of the environment, else of the app's git-ignored
233
+ by itself (`decryptionIdentity`, the one lookup every decrypt of a member uses: secret, stack, release, db): SOPS_AGE_KEY or SOPS_AGE_KEY_FILE of the environment, else of the app's git-ignored
234
234
  `.claude/secret.env`, else of its main checkout's when the app is a git worktree, else the `hostIdentity` the harness CLI passes
235
235
  (its own secret.env), else the sops `keys.txt`; with none, the verb refuses before asking for a value, naming every place it
236
236
  looked and the one line that fixes it. `audit [<env>]` names every deviation and exits 1; `migrate <env> <member> [--to
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.12",
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).
@@ -18,9 +18,9 @@ import { RELEASE_CODE, VERSION, normalizeRelease, releaseGate } from './gate.mjs
18
18
  import { releasePush } from './push.mjs';
19
19
  import { releaseUrgentPush } from './urgent.mjs';
20
20
 
21
- const IO_KEYS = ['cwd', 'stdout', 'stderr', 'env', 'sops'];
21
+ const IO_KEYS = ['cwd', 'stdout', 'stderr', 'env', 'sops', 'hostIdentity'];
22
22
 
23
- /** The stack context of one invocation: the IO of the app (cwd, writers, env, sops) over the injectable seams of `io.stackIo` (spawn, sleep, now, fetch). */
23
+ /** The stack context of one invocation: the IO of the app (cwd, writers, env, sops, hostIdentity) over the injectable seams of `io.stackIo` (spawn, sleep, now, fetch). */
24
24
  export function contextOf(io = {}) {
25
25
  const own = Object.fromEntries(IO_KEYS.filter((key) => io[key] !== undefined).map((key) => [key, io[key]]));
26
26
  return stackContext({ ...io.stackIo, ...own });
@@ -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.24
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.11
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.13
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.24
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.24
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.12
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.
@@ -116,7 +116,11 @@ function isolatedSopsEnv(env, inlineName = 'SOPS_AGE_KEY') {
116
116
  return out;
117
117
  }
118
118
 
119
- const held = reason => ({ status: null, stdout: '', stderr: '', error: Object.assign(new Error(`SOPS selected identity [${reason}]: the selected invocation was not qualified`), { name: 'SopsIdentityRefusal', identityRefusal: reason }) });
119
+ /**
120
+ * A refusal of the selected invocation. `detail` says what failed in public words; `facts` carries only public values the caller
121
+ * names in its own refusal (`publicRecipient`, the selected identity's recipient; `sopsFailure`, the class of a failed sops run).
122
+ */
123
+ const held = (reason, detail = 'the selected invocation was not qualified', facts = {}) => ({ status: null, stdout: '', stderr: '', error: Object.assign(new Error(`SOPS selected identity [${reason}]: ${detail}`), { name: 'SopsIdentityRefusal', identityRefusal: reason, ...facts }) });
120
124
  const nativeFile = file => {
121
125
  if (typeof file !== 'string' || !path.isAbsolute(file) || /\.(?:[cm]?js|cmd|bat|ps1|sh)$/i.test(file)) return false;
122
126
  let fd;
@@ -175,11 +179,29 @@ const selectedAdmission = (selection, spec, invocation, env) => {
175
179
 
176
180
  const decryptArgs = (file, inputType, outputType) => ['decrypt', '--input-type', inputType, '--output-type', outputType, '--filename-override', file, '--enable-local-keyservice=true', '--decryption-order', 'age'];
177
181
 
182
+ /**
183
+ * The class of a failed sops run, read from its stderr and exit; sops prints no value there, and only the class leaves. Classes:
184
+ * no-matching-identity (no age entry opens with the identity), mac-mismatch (the document changed after it was sealed),
185
+ * unparsable-document (the bytes are not the format they were read as), timeout, or exit-<n>.
186
+ */
187
+ export function sopsFailureClass(result) {
188
+ if (result?.error?.code === 'ETIMEDOUT' || result?.signal === 'SIGTERM') return 'timeout';
189
+ const text = Buffer.isBuffer(result?.stderr) ? result.stderr.toString('utf8') : String(result?.stderr ?? '');
190
+ if (/MAC mismatch/iu.test(text)) return 'mac-mismatch';
191
+ if (/no identity matched|failed to get the data key|could not decrypt data key|0 successful groups/iu.test(text)) return 'no-matching-identity';
192
+ if (/unmarshal|could not parse|error loading file|invalid character|yaml:/iu.test(text)) return 'unparsable-document';
193
+ return `exit-${String(result?.status ?? 'none')}`;
194
+ }
195
+
178
196
  const decryptSelected = (run, exe, file, input, spec, recipient) => {
197
+ const facts = { publicRecipient: recipient };
179
198
  const envelope = selectedAgeEnvelope(decoded(input), spec.inputType, recipient);
180
- if (!envelope.ok) return held(envelope.reason);
199
+ if (!envelope.ok) return held(envelope.reason, `the ${spec.inputType} envelope was refused for the selected recipient ${recipient}`, facts);
181
200
  const result = run(exe, decryptArgs(file, spec.inputType, spec.outputType), input);
182
- if (!captured(result)) return held('selected-decryption-failed');
201
+ if (!captured(result)) {
202
+ const failure = sopsFailureClass(result);
203
+ return held('selected-decryption-failed', `sops could not decrypt the ${spec.inputType} document with the selected recipient ${recipient} (${failure})`, { ...facts, sopsFailure: failure });
204
+ }
183
205
  return { status: 0, stdout: decoded(result.stdout), stderr: '', error: null };
184
206
  };
185
207
 
@@ -7,10 +7,11 @@ import { resolveSops, runSelectedSops } from './lib.mjs';
7
7
 
8
8
  /**
9
9
  * Run `<bin> encrypt` (bin null: the sops resolveSops finds) over `plaintext` of format `inputType` (json, yaml or dotenv). Sops reads stdin only with a `--filename-override`, the path the sealed
10
- * file will have: recipients are age keys (`--age`), and when none are given sops picks them from the repository's .sops.yaml for that path. {status, stdout, stderr, error}.
10
+ * file will have: recipients are age keys (`--age`), and when none are given sops picks them from the repository's .sops.yaml for that path. `config` names
11
+ * the sops configuration to read instead of the repository's (a rule-less member sealed to its own recipients). {status, stdout, stderr, error}.
11
12
  */
12
- export function seal(bin, { inputType, plaintext, recipients = [], filenameOverride }, { invocation = null, env = process.env, cwd = undefined, maxBuffer = 16 * 1024 * 1024, timeout = undefined } = {}) {
13
- const args = ['encrypt', '--input-type', inputType, '--output-type', inputType, '--filename-override', filenameOverride];
13
+ export function seal(bin, { inputType, plaintext, recipients = [], filenameOverride, config = null }, { invocation = null, env = process.env, cwd = undefined, maxBuffer = 16 * 1024 * 1024, timeout = undefined } = {}) {
14
+ const args = [...(config ? ['--config', config] : []), 'encrypt', '--input-type', inputType, '--output-type', inputType, '--filename-override', filenameOverride];
14
15
  if (recipients.length) args.push('--age', recipients.join(','));
15
16
  const selected = sopsIdentityEnv(env);
16
17
  if (selected.error?.identityRefusal === 'inline-context-unqualified') return runSelectedSops(bin, { operation: 'seal', params: { inputType, plaintext, recipients, filenameOverride } }, { selection: selected, invocation, env, cwd, maxBuffer, timeout });