@starci/eslint-canon-be 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.8.0 - 2026-10-29
4
+
5
+ - Added: `jobs-scheduler-owner` (R335 `BE_JOBS_SCHEDULER_OWNER`, ruling lite-official-postgres-image): only `platform/jobs/job-tick.service.ts`, its spec and `jobs.module.ts` import `@nestjs/schedule` or `cron`, the `Cron`, `Interval` and `Timeout` decorators are refused everywhere, and a `job-tick.service.ts` must call `advisoryXactLock` and `callDbFunction(..., "job_tick_claim", ...)`. `infra-import-owner` (R90) reads `@nestjs/schedule` and `cron` as owned by `platform/jobs` from the bundled manifest.
6
+ - Changed: the bundled slot manifest 3.11.0 adds the managed lite slot `app.db.image` (`db/Dockerfile`), narrows `ruleParams.db.extensions` to what the official postgres image plus pgvector carries (pgcrypto, pg_trgm, vector, uuid-ossp, unaccent, btree_gist; no pgmq, pg_cron, pg_net or supabase_vault) and gives `@nestjs/schedule` and `cron` one owner, `platform/jobs`, in `infraOwners`; the bundled rule catalog adds R335 `BE_JOBS_SCHEDULER_OWNER` and its R250 and R276 laws name the platform/jobs tick and the db image; the bundled canon pins name hfs 4.11.0, eslint-canon-be 3.8.0, eslint-canon-fe 9.5.2 and the Grammar family 0.15.13 and pin `@nestjs/schedule` 6.1.3 (CommonJS on the Nest 11 line) and `cron` 4.4.0.
7
+
8
+ ## 3.7.1 - 2026-10-29
9
+
10
+ - Changed: the entity registry (persistence.md BE-PERSISTENCE-3, Debug ruling on lite-persistence-typeorm-entities): the bundled slot manifest 3.10.0 adds the lite slot `be.platform.database.entities`, the entity registry (slot fields `role: entity-registry` and `importedBy`, validated by the manifest shape); the bundled architecture machine reads it (`architecture/entity-registry.mjs`): `tier-direction` (R26 `BE_TIER_DIRECTION`) admits the registry's import of a domain or platform capability's `index.ts` that binds only that capability's `<c>Entities`, and `owner-export-bypass` (R30 `ARCH_OWNER_EXPORT_BYPASS`) admits a direct import of the registry from the files `importedBy` names (`apps/*/src/compose/*.ts`, `apps/*/src/app.module.ts`, `src/tests/world/**`); every other import of either shape stays refused, and full has no registry. `import-owner-entry` (R30) admits the deep path `@modules/platform/database/entities` from the same importers only. Spec: `src/entity-registry.spec.ts`.
11
+ - Changed: the bundled canon pins name hfs 4.10.1, eslint-canon-be 3.7.1, eslint-canon-fe 9.5.1 and the Grammar family 0.15.12.
12
+ - Changed: the owner-cycle check (R27 `ARCH_OWNER_CYCLE`) counts the entity registry as a unit of its own, not part of `platform/database`, so naming every `<c>Entities` closes no cycle among capabilities while any other platform/database file importing a domain still does (spec in `src/entity-registry.spec.ts`); the bundled rule catalog's R26 and R30 laws name the entity registry.
13
+
3
14
  ## 3.7.0 - 2026-10-29
4
15
 
5
16
  - Added: the `auth-passport` law (contexts/code/be/api-auth.md BE-AUTH-2): `own-jwks-only` (R329 `BE_AUTH_JWT_OWN_JWKS`) refuses `createRemoteJWKSet`, `decodeJwt` and `decodeProtectedHeader` of jose anywhere and `jwtVerify` outside `integrations/passport`; `refresh-token-cookie-only` (R330 `BE_AUTH_REFRESH_COOKIE`) refuses a `refreshToken`/`refresh_token` property or member and a refresh cookie set or cleared outside `integrations/passport`.
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@ import { pluginForEdition } from "./lib/edition.js";
21
21
  import { recommended as aiGatewayRecommended, rules as aiGatewayRules } from "./ai-gateway.js";
22
22
  import { recommended as authPassportRecommended, rules as authPassportRules } from "./auth-passport.js";
23
23
  import { recommended as noRawSqlRecommended, rules as noRawSqlRules } from "./no-raw-sql.js";
24
+ import { recommended as jobsSchedulerRecommended, rules as jobsSchedulerRules } from "./jobs-scheduler.js";
24
25
  import { recommended as ambientIdRecommended, rules as ambientIdRules } from "./ambient-id.js";
25
26
  import { recommended as appCompositionRecommended, rules as appCompositionRules } from "./app-composition.js";
26
27
  import { recommended as asyncDisciplineRecommended, rules as asyncDisciplineRules } from "./async-discipline.js";
@@ -78,6 +79,7 @@ const CONTRIBUTIONS = [
78
79
  { law: "ai-gateway", rules: aiGatewayRules, recommended: aiGatewayRecommended },
79
80
  { law: "auth-passport", rules: authPassportRules, recommended: authPassportRecommended },
80
81
  { law: "no-raw-sql", rules: noRawSqlRules, recommended: noRawSqlRecommended },
82
+ { law: "jobs-scheduler", rules: jobsSchedulerRules, recommended: jobsSchedulerRecommended },
81
83
  { law: "ambient-id", rules: ambientIdRules, recommended: ambientIdRecommended },
82
84
  { law: "app-composition", rules: appCompositionRules, recommended: appCompositionRecommended },
83
85
  { law: "async-discipline", rules: asyncDisciplineRules, recommended: asyncDisciplineRecommended },
@@ -0,0 +1,9 @@
1
+ import type { Recommended, RuleModule } from "./lib/rule.js";
2
+ /** Recurring work is a platform/jobs tick: the scheduler libraries stay in its files, no replica decorator, and the tick holds its fence. */
3
+ export declare const jobsSchedulerOwner: RuleModule;
4
+ /** The rule of the tick scheduler law, by name. */
5
+ export declare const rules: {
6
+ "jobs-scheduler-owner": RuleModule;
7
+ };
8
+ /** On at error in both editions. */
9
+ export declare const recommended: Recommended;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The tick scheduler law (catalog R335 `BE_JOBS_SCHEDULER_OWNER`; contexts/code/be/jobs.md BE-JOBS-6): recurring work is a tick of
3
+ * `platform/jobs`, fired once per minute for the whole deployment.
4
+ *
5
+ * - `jobs-scheduler-owner` refuses an import of `@nestjs/schedule` or `cron` (or a subpath) outside the three files of
6
+ * `platform/jobs` that hold the scheduler (`job-tick.service.ts`, its spec, and `jobs.module.ts`, which composes
7
+ * `ScheduleModule.forRoot()`), refuses the `Cron`, `Interval` and `Timeout` decorators of `@nestjs/schedule` everywhere (a
8
+ * decorated method fires on every replica), and refuses a `job-tick.service.ts` that does not call both `advisoryXactLock`
9
+ * and `callDbFunction(..., "job_tick_claim", ...)`: the lock serialises the replicas and the minute claim lets one enqueue.
10
+ *
11
+ * `infra-import-owner` (R90) holds the coarser half from the same table (`ruleParams.be.infraOwners` gives both libraries to
12
+ * `platform/jobs`); this rule names the files and the fence.
13
+ */
14
+ import path from "node:path";
15
+ import { staticText } from "./lib/ast.js";
16
+ import { hfsOf } from "./lib/hfs.js";
17
+ import { moduleReferences } from "./lib/import-source.js";
18
+ /** The owner id (`<tier>/<capability>`) of the tick scheduler. */
19
+ const JOBS_OWNER = "platform/jobs";
20
+ /** The libraries of the scheduler. */
21
+ const SCHEDULER_LIBRARIES = ["@nestjs/schedule", "cron"];
22
+ /** The files of platform/jobs that may import them. */
23
+ const SCHEDULER_FILES = new Set(["job-tick.service.ts", "job-tick.service.spec.ts", "jobs.module.ts"]);
24
+ /** The file that fires the ticks and must hold the fence. */
25
+ const TICK_SERVICE = "job-tick.service.ts";
26
+ /** The decorators that would fire once per replica. */
27
+ const REPLICA_DECORATORS = new Set(["Cron", "Interval", "Timeout"]);
28
+ /** The database function that claims a tick's minute. */
29
+ const TICK_CLAIM = "job_tick_claim";
30
+ /** True when a module specifier is a scheduler library or a subpath of one. */
31
+ const isSchedulerLibrary = (specifier) => SCHEDULER_LIBRARIES.some((library) => specifier === library || specifier.startsWith(`${library}/`));
32
+ /** Recurring work is a platform/jobs tick: the scheduler libraries stay in its files, no replica decorator, and the tick holds its fence. */
33
+ export const jobsSchedulerOwner = {
34
+ meta: {
35
+ type: "problem",
36
+ docs: { description: "Only the tick scheduler of platform/jobs imports @nestjs/schedule or cron, no file uses a Cron, Interval or Timeout decorator, and the tick service locks and claims each minute before it enqueues." },
37
+ schema: [],
38
+ messages: {
39
+ owner: "`{{library}}` is imported outside the tick scheduler of platform/jobs (job-tick.service.ts, jobs.module.ts). Declare the tick in JOB_TICKS of platform/jobs/job-ticks.contracts.ts instead.",
40
+ decorator: "`@{{name}}` of @nestjs/schedule fires once per replica. Declare the tick in JOB_TICKS of platform/jobs/job-ticks.contracts.ts; JobTickService fires it once per minute for the deployment.",
41
+ fence: "JobTickService must take `advisoryXactLock(tx, \"tick:<name>\")` and claim the minute with `callDbFunction(tx, \"job_tick_claim\", ...)` before it writes the outbox, or every replica enqueues the tick.",
42
+ },
43
+ },
44
+ create(context) {
45
+ const hfs = hfsOf(context);
46
+ const root = hfs.ownerOf(context.filename);
47
+ const inJobs = root !== null && root.split("/").slice(-2).join("/") === JOBS_OWNER;
48
+ const base = path.basename(context.filename);
49
+ const mayImport = inJobs && SCHEDULER_FILES.has(base);
50
+ const tickService = inJobs && base === TICK_SERVICE;
51
+ let locks = false;
52
+ let claims = false;
53
+ return {
54
+ ...moduleReferences((reference) => {
55
+ if (!isSchedulerLibrary(reference.value))
56
+ return;
57
+ if (!mayImport)
58
+ context.report({ node: reference.source, messageId: "owner", data: { library: reference.value } });
59
+ if (reference.value !== "@nestjs/schedule")
60
+ return;
61
+ for (const name of reference.names) {
62
+ if (name !== null && REPLICA_DECORATORS.has(name))
63
+ context.report({ node: reference.node, messageId: "decorator", data: { name } });
64
+ }
65
+ }),
66
+ CallExpression(node) {
67
+ if (!tickService || node.callee.type !== "Identifier")
68
+ return;
69
+ if (node.callee.name === "advisoryXactLock")
70
+ locks = true;
71
+ const second = node.arguments[1];
72
+ if (node.callee.name === "callDbFunction" && staticText(second) === TICK_CLAIM)
73
+ claims = true;
74
+ },
75
+ "Program:exit"(node) {
76
+ if (tickService && !(locks && claims))
77
+ context.report({ node, messageId: "fence" });
78
+ },
79
+ };
80
+ },
81
+ };
82
+ /** The rule of the tick scheduler law, by name. */
83
+ export const rules = { "jobs-scheduler-owner": jobsSchedulerOwner };
84
+ /** On at error in both editions. */
85
+ export const recommended = { "starci-be/jobs-scheduler-owner": "error" };
@@ -51,6 +51,10 @@ export interface HfsSlot {
51
51
  readonly trigger?: string;
52
52
  readonly coverage?: string;
53
53
  readonly allows?: readonly string[];
54
+ /** The one special part a file slot plays that a rule reads: `entity-registry` (persistence.md BE-PERSISTENCE-3). */
55
+ readonly role?: string;
56
+ /** The side-relative path patterns of the only files that may import this file by deep path. */
57
+ readonly importedBy?: readonly string[];
54
58
  }
55
59
  /** A unit-tested role (`ruleParams.be.unitRoles`). */
56
60
  export interface HfsUnitRole {
@@ -7,7 +7,9 @@
7
7
  *
8
8
  * - `import-owner-entry` - a cross-owner import targets the owner's `index.ts` (`@modules/domain/plan`,
9
9
  * `@features/api/plan`), never a file inside it, and an alias that names a tier but no owner (`@modules/domain`) names
10
- * nothing importable. A same-owner import is relative and never goes through the owner's own `index.ts`.
10
+ * nothing importable. A same-owner import is relative and never goes through the owner's own `index.ts`. The entity
11
+ * registry (slot role `entity-registry`, `@modules/platform/database/entities`) is the one file reached by deep path, and only
12
+ * from the files its slot's `importedBy` names (persistence.md BE-PERSISTENCE-3).
11
13
  * - `no-self-module-alias` - inside an owner, imports are relative, never the owner's own alias.
12
14
  * - `no-relative-capability-escape` - a relative import never walks out of its own owner.
13
15
  * - `no-folder-reexport` - a specifier that names a directory is refused; a nested `index.ts` (any index that is not
@@ -23,6 +25,7 @@ import { posix } from "node:path";
23
25
  import { hfsOf } from "./lib/hfs.js";
24
26
  import { baseName } from "./lib/ports.js";
25
27
  import { resolveAlias } from "./lib/specifier.js";
28
+ import { ENTITY_REGISTRY_ROLE, registryImporter } from "../runtime/scripts/hfs/architecture/entity-registry.mjs";
26
29
  /** The tiers whose files belong to an owner with a root `index.ts`. */
27
30
  const OWNER_TIERS = new Set(["feature", "domain", "platform", "integrations"]);
28
31
  /**
@@ -64,6 +67,12 @@ const onSpecifiers = (check) => ({
64
67
  /** The public-surface width: the file's slot budget, else its tier's owner-slot budget, else a back-end owner default. */
65
68
  const indexExportBudget = (hfs, filename) => [hfs.slotOf(filename), `be.${hfs.tierOf(filename)}`, "be.domain", "be.feature"].map((id) => (id ? hfs.slot(id)?.budget?.indexExports : undefined)).find(Number.isInteger);
66
69
  // -- R30: import-owner-entry -----------------------------------------------------------------------
70
+ /** Whether `filename` may reach the import path `target` (absolute, no extension) by deep path: it is the entity registry and its slot's `importedBy` names the importer. */
71
+ const importsRegistry = (hfs, filename, target) => {
72
+ const id = hfs.slotOf(`${target}.ts`);
73
+ const slot = id ? hfs.slot(id) : undefined;
74
+ return slot?.role === ENTITY_REGISTRY_ROLE && registryImporter(null, slot, hfs.relative(filename));
75
+ };
67
76
  /**
68
77
  * A cross-owner import targets the owner's public entry: the alias and the owner, nothing deeper. A same-owner import
69
78
  * is relative and never goes through the owner's own `index.ts` (BE-CONVENTION 2.4).
@@ -111,7 +120,7 @@ export const importOwnerEntry = {
111
120
  return;
112
121
  const ownerAbsolute = absolute(hfs, owner);
113
122
  const inside = alias.target === ownerAbsolute ? "" : alias.target.slice(ownerAbsolute.length + 1);
114
- if (inside !== "" && inside !== "index")
123
+ if (inside !== "" && inside !== "index" && !importsRegistry(hfs, filename, alias.target))
115
124
  context.report({ node, messageId: "deep", data: { specifier } });
116
125
  });
117
126
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starci/eslint-canon-be",
3
- "version": "3.7.0",
3
+ "version": "3.8.0",
4
4
  "description": "The StarCi back-end lint canon: every rule its laws publish, gathered as one flat-config plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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.11
34
+ version: 0.15.13
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.7.0
41
+ version: 3.8.0
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.0
48
+ version: 9.5.2
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.11
55
+ version: 0.15.13
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.11
62
+ version: 0.15.13
63
63
  group: starci
64
64
  install: registry
65
65
  side: fe
@@ -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.10.0
109
+ version: 4.11.0
110
110
  group: starci
111
111
  install: registry
112
112
  side: both
@@ -600,6 +600,16 @@ pins:
600
600
  group: framework
601
601
  side: be
602
602
  why: 'PassportStrategy of integrations/passport; 11.0.5 is CommonJS on the Nest 11 line (12.0.0 is ESM-only and breaks Nest 11 jest under the CommonJS transform of @starci/jest-preset), as nivo-lite runs it.'
603
+ '@nestjs/schedule':
604
+ version: 6.1.3
605
+ group: framework
606
+ side: be
607
+ why: 'the tick scheduler of platform/jobs, the one owner that imports it (R335, ruling lite-official-postgres-image); 6.1.3 is CommonJS on the Nest 11 line (12.x is ESM-only and breaks Nest 11 jest under the CommonJS transform of @starci/jest-preset).'
608
+ cron:
609
+ version: 4.4.0
610
+ group: framework
611
+ side: be
612
+ why: 'CronJob of the platform/jobs tick scheduler; the exact version @nestjs/schedule 6.1.3 depends on, so one cron is installed.'
603
613
  passport:
604
614
  version: 0.7.0
605
615
  group: framework
@@ -474,7 +474,7 @@ rules:
474
474
  witness:
475
475
  - {path: packages/eslint/be/legacy-owner-graph.a16.spec.mjs, editions: [lite, full]}
476
476
  templateNa: "Tier and package direction are constraints on cross-owner import graphs; no dedicated cross-owner graph scaffold is generated."
477
- law: "The tier direction matrix; a shared package never imports an app. Front-end page and layout owners may import overlay entries; every other cross-owner feature-to-feature edge is forbidden, including layout-to-page and overlay-to-overlay. Components never import overlays."
477
+ law: "The tier direction matrix; a shared package never imports an app. Front-end page and layout owners may import overlay entries; every other cross-owner feature-to-feature edge is forbidden, including layout-to-page and overlay-to-overlay. Components never import overlays. The one platform-to-domain edge is the lite entity registry (be.platform.database.entities) importing a capability's `<c>Entities` alone from its `index.ts`."
478
478
  kinds: [lint, design]
479
479
  gates: [settle, land, ci]
480
480
  failureCodes: ["BE_TIER_DIRECTION", "FE_TIER_DIRECTION", "ARCH_PACKAGE_IMPORTS_APP"]
@@ -541,7 +541,7 @@ rules:
541
541
  - {path: packages/eslint/be/a16-r29-r31.spec.mjs, edition: full}
542
542
  - id: R30
543
543
  code: "BE_PUBLIC_SURFACE"
544
- law: "Every owner has one `index.ts`; cross-owner imports use it, same-owner imports are relative and never go through it; it holds only named `export { }` lines, no `export *`, no alias re-export (`export { X as Y }`, `export const Y = X`, `export type Y = X`, `export interface Y extends X {}`: one declaration has one name), within the owner slot's `indexExports` budget (60 for domain and feature owners, 80 for `be.integrations` provider entries); cross-package imports use the package name and a declared export."
544
+ law: "Every owner has one `index.ts`; cross-owner imports use it, except the lite entity registry, reached by deep path only from the files its slot's `importedBy` names; same-owner imports are relative and never go through it; it holds only named `export { }` lines, no `export *`, no alias re-export (`export { X as Y }`, `export const Y = X`, `export type Y = X`, `export interface Y extends X {}`: one declaration has one name), within the owner slot's `indexExports` budget (60 for domain and feature owners, 80 for `be.integrations` provider entries); cross-package imports use the package name and a declared export."
545
545
  kinds: [lint, codemod]
546
546
  gates: [settle, land, ci]
547
547
  failureCodes: ["BE_PUBLIC_SURFACE", "ARCH_OWNER_EXPORT_BYPASS", "ARCH_OWNER_EXPORT_STAR", "HFS_ALIAS_REEXPORT", "ARCH_PACKAGE_EXPORT_BYPASS"]
@@ -4176,7 +4176,7 @@ rules:
4176
4176
  editions: [lite, full]
4177
4177
  docs:
4178
4178
  - {path: docs/application-stacks.md#r250-deploy-scan, editions: [lite, full]}
4179
- law: "In lite and full apps, scheduled work belongs to the back-end queue scheduler, a pg_cron tick that enqueues through the queue outbox or a declared replicated-job. Deployment files, scripts, workflows, compose files and Dockerfiles install no host crontab, cron.d entry, systemd timer, @reboot job or at job; a workflow does not schedule app work. Docker compose up, down and pull run only against an explicitly dev environment. Deploy shell scripts delegate to docker, starci or the app CLI, and contain no node -e, psql, inline SQL or downloaded shell logic."
4179
+ law: "In lite and full apps, scheduled work belongs to the back-end queue scheduler, a platform/jobs tick (R335) that enqueues through the queue outbox or a declared replicated-job. Deployment files, scripts, workflows, compose files and Dockerfiles install no host crontab, cron.d entry, systemd timer, @reboot job or at job; a workflow does not schedule app work. Docker compose up, down and pull run only against an explicitly dev environment. Deploy shell scripts delegate to docker, starci or the app CLI, and contain no node -e, psql, inline SQL or downloaded shell logic."
4180
4180
  kinds: [check]
4181
4181
  gates: [settle, land, ci]
4182
4182
  failureCodes: ["HFS_HOST_CRON", "HFS_DEPLOY_NO_LOGIC", "HFS_DEPLOY_COMPOSE_ON_VPS", "HFS_DEPLOY_SCHEDULER"]
@@ -4701,7 +4701,7 @@ rules:
4701
4701
  - {path: packages/hfs/src/hfs-stacks-full-fixtures.spec.mjs, edition: full}
4702
4702
  - id: R276
4703
4703
  code: "STACKS_LITE_SELFHOSTED_DB"
4704
- law: "Lite runs exactly one database, its db component of image supabase/postgres (pinned by digest) with pgvector for vector search, and no other PostgreSQL, MongoDB or Qdrant backing image, even when declared (owner:lite-vector-is-pgvector, ruling:lite-self-hosted-postgres-passport-minio). A Redis image runs only when hfs.json sides.be.backing declares redis (ruling:R212/case-10), as one minimal instance; a declared Redis runs as exactly one stack service, with AOF persistence (`appendonly yes`, `appendfsync everysec` or `always`, never `no`) on a writable named volume so queue jobs survive a restart and with no maxmemory-policy but noeviction so none is evicted. A queue job Redis loses inside the at most one second `everysec` leaves unwritten is not lost work: every job is born from a Postgres outbox row, and the relay marks that row sent only after Redis confirms the job is in its append-only file (WAITAOF) and still holds it, so a job Redis did not persist leaves its row waiting and the relay adds it again (examples/lite-app queue-relay.service.spec.ts and bullmq-queue-transport.client.spec.ts). A sidecar keeps its own SQLite on a named persistent volume declared by its component and mounted in the rendered model, and never uses the app's declared Redis, which serves the back-end app services only; a sidecar requiring another database, that Redis included, is refused. Full retains its declared backing topology."
4704
+ law: "Lite runs exactly one database, its db component of the image its managed db/Dockerfile builds (the digest-pinned official postgres image plus pgvector, ruling:lite-official-postgres-image) for vector search too, and no other PostgreSQL, MongoDB or Qdrant backing image, even when declared (owner:lite-vector-is-pgvector, ruling:lite-self-hosted-postgres-passport-minio). A Redis image runs only when hfs.json sides.be.backing declares redis (ruling:R212/case-10), as one minimal instance; a declared Redis runs as exactly one stack service, with AOF persistence (`appendonly yes`, `appendfsync everysec` or `always`, never `no`) on a writable named volume so queue jobs survive a restart and with no maxmemory-policy but noeviction so none is evicted. A queue job Redis loses inside the at most one second `everysec` leaves unwritten is not lost work: every job is born from a Postgres outbox row, and the relay marks that row sent only after Redis confirms the job is in its append-only file (WAITAOF) and still holds it, so a job Redis did not persist leaves its row waiting and the relay adds it again (examples/lite-app queue-relay.service.spec.ts and bullmq-queue-transport.client.spec.ts). A sidecar keeps its own SQLite on a named persistent volume declared by its component and mounted in the rendered model, and never uses the app's declared Redis, which serves the back-end app services only; a sidecar requiring another database, that Redis included, is refused. Full retains its declared backing topology."
4705
4705
  kinds: [check]
4706
4706
  gates: ["settle","land","ci"]
4707
4707
  failureCodes: ["STACKS_LITE_SELFHOSTED_DB", "STACKS_SIDECAR_VOLUME_UNDECLARED", "STACKS_SIDECAR_DB_UNSUPPORTED", "STACKS_LITE_REDIS_PERSISTENCE"]
@@ -5849,3 +5849,27 @@ rules:
5849
5849
  source: owner
5850
5850
  quote: "big refactor đi … không viết raw sql như thế theo starci-academy-be"
5851
5851
  ruling: "Lite persistence moves to TypeORM entities on the EntityManager, the shape of full and starci-academy-be (ruling lite-persistence-typeorm-entities)."
5852
+ - id: R335
5853
+ code: "BE_JOBS_SCHEDULER_OWNER"
5854
+ law: "Recurring work is a tick of platform/jobs (ruling lite-official-postgres-image): JOB_TICKS of job-ticks.contracts.ts lists the ticks as data, and only job-tick.service.ts (JobTickService, which registers one CronJob per tick in SchedulerRegistry) and jobs.module.ts (which composes ScheduleModule.forRoot()) import @nestjs/schedule or cron; no file uses the Cron, Interval or Timeout decorator. JobTickService takes advisoryXactLock(tx, \"tick:<name>\") and claims the tick's UTC minute through callDbFunction(tx, \"job_tick_claim\", ...) in the transaction that writes the queue outbox row, so of the replicas that fire a tick exactly one enqueues it once per minute."
5855
+ kinds: [lint]
5856
+ gates: [pre-commit, settle, land, ci]
5857
+ failureCodes: ["BE_JOBS_SCHEDULER_OWNER"]
5858
+ enforcers:
5859
+ - {kind: eslint-be, id: jobs-scheduler-owner}
5860
+ editions: [lite, full]
5861
+ docs: [contexts/code/be/jobs.md]
5862
+ proves:
5863
+ - packages/eslint-canon-be/src/jobs-scheduler.spec.ts
5864
+ exemplifiedBy:
5865
+ - {path: packages/hfs/templates/be/patterns/jobs/platform-lite/job-tick.service.ts.tpl, edition: lite}
5866
+ - {path: packages/eslint-canon-be/src/jobs-scheduler.spec.ts, editions: [lite, full], codes: [BE_JOBS_SCHEDULER_OWNER]}
5867
+ witness:
5868
+ - {path: packages/eslint-canon-be/src/jobs-scheduler.spec.ts, edition: lite, codes: [BE_JOBS_SCHEDULER_OWNER]}
5869
+ - {path: packages/eslint-canon-be/src/jobs-scheduler.spec.ts, edition: full, codes: [BE_JOBS_SCHEDULER_OWNER]}
5870
+ cases:
5871
+ - id: case-1
5872
+ date: "2026-10-29"
5873
+ source: owner
5874
+ quote: "chạy postgresql thuần image chính chủ nhé ko phải supebase"
5875
+ ruling: "The lite db image carries no pg_cron, so recurring work moves to a Nest schedule tick of platform/jobs under an advisory lock and a minute claim (ruling lite-official-postgres-image)."
@@ -7,7 +7,7 @@
7
7
  # catalog READ this file through scripts/hfs/slots.mjs; none of them hardcodes a path.
8
8
  # Shape: modules/schemas/hfs-slots.schema.yaml. The repository side is hfs.json: modules/schemas/hfs-repo.schema.yaml.
9
9
  schema: starci/hfs-slots@3
10
- version: 3.9.0
10
+ version: 3.11.0
11
11
 
12
12
  versioning:
13
13
  # MAJOR.MINOR.PATCH of this manifest. A repository pins only the MAJOR in hfs.json ("hfs": 3).
@@ -48,6 +48,11 @@ versioning:
48
48
  # 2026-10-24: lite may serve SSE, and SSE is the default door for one-way push), and lets fe.modules.api hold the SSE stream operations (sse/).
49
49
  # 3.7.0 is a minor (alpha.31): it ADDS the optional app.scripts.integration slot (scripts/integration/*.mjs, the product test-support scripts that only the integration harness runs) and the optional fe.transport.stream slot, the fetch reader of server-sent-events streams (the stream half of the
50
50
  # transport client layer), and lets fe.hooks.swr hold the SWR subscription hooks (api/sse/subscriptions/useSubscribe<X>Swr.ts, one useSWRSubscription per stream operation).
51
+ # 3.10.0 is a minor (2026-10-29): it ADDS the lite be.platform.database.entities slot, the entity registry (slot fields role and importedBy), so the
52
+ # tier matrix and the public-entry rules admit exactly its <c>Entities imports and its deep importers (persistence.md BE-PERSISTENCE-3).
53
+ # 3.11.0 (ruling:lite-official-postgres-image, 2026-10-29) is, like 3.9.0, a change for lite only: it ADDS the managed app.db.image slot
54
+ # (db/Dockerfile, written by `starci app sync --write`), narrows ruleParams.db.extensions to the extensions that image carries, and gives
55
+ # @nestjs/schedule and cron one owner, platform/jobs (R335).
51
56
 
52
57
  # Field meaning, per slot.
53
58
  # id stable name, never changes meaning inside a major.
@@ -68,6 +73,10 @@ versioning:
68
73
  # outcomeHome true on a file slot: the one file that declares the repository's Outcome union. A repository holds exactly one such
69
74
  # file (modules/api/outcome.ts, the api package's outcome.ts, or modules/db/outcome.ts of a lite app),
70
75
  # and no other file declares an Outcome union (one-outcome-union, FE_TRANSPORT_OWNER).
76
+ # role on a file slot: the one part it plays that a rule reads. entity-registry = the lite PRIMARY_ENTITIES list
77
+ # (be.platform.database.entities): the one platform file that imports capability <c>Entities, imported by deep path
78
+ # only from the files importedBy names (architecture/entity-registry.mjs).
79
+ # importedBy on a slot with a role: the side-relative path patterns of the only files that import its file by deep path.
71
80
  # requires files or directories that must exist inside each instance; <var> is replaced by the bound name,
72
81
  # a leading / means repository root; a trailing / means directory.
73
82
  # requiredInstances variable -> names that must exist as instances (config, logging ... of platform).
@@ -117,8 +126,8 @@ testValues: [unit-beside, e2e, none]
117
126
  # specs (unitRoles, logicRoles, 100 per file, @starci/jest-preset doubles, builders). What differs is ADAPTERS and DELIVERY
118
127
  # (ruling:R212/case-10): schema authority in db/migrations, the queue port on BullMQ over the Redis hfs.json
119
128
  # sides.be.backing declares (as in full, fed by the Postgres outbox), event-bus ports on pgmq-backed topics or in-process
120
- # delivery, cache and locks on Postgres or the declared Redis, schedules on pg_cron (+ pg_net) enqueueing through the queue
121
- # outbox, storage on S3-compatible MinIO (integrations/object-storage) and auth through integrations/passport. Realtime uses SSE or the socket.io gateway
129
+ # delivery, cache and locks on Postgres or the declared Redis, schedules as platform/jobs ticks enqueueing through the queue
130
+ # outbox (R335), storage on S3-compatible MinIO (integrations/object-storage) and auth through integrations/passport. Realtime uses SSE or the socket.io gateway
122
131
  # in the api process, which scales horizontally and stateless (memory hub for one replica or tests; the Redis hub and @socket.io/redis-adapter when Redis is declared, else the Postgres hub and @socket.io/postgres-adapter, for N replicas; websocket only, no sticky sessions). Integration and provider sandbox contract specs are optional;
123
132
  # declared patterns owe their integration proofs (R284). Lite has no e2e world. Production uses declared docker-swarm under
124
133
  # .starcistacks/production/infra/swarm/ (owner ruling 2026-10-14); lite runs its PostgreSQL as the db service of its
@@ -195,8 +204,9 @@ crossApp: apps never import each other; shared code is a packages/<pkg> slot.
195
204
  ruleParams:
196
205
  db:
197
206
  # R259: btree_gist supplies UUID equality for the booking interval exclusion constraint.
198
- # R259: unaccent ships in the supabase/postgres image of the db service, used by Vietnamese-content search functions.
199
- extensions: [pgmq, pg_cron, pgcrypto, pg_trgm, vector, uuid-ossp, pg_net, supabase_vault, unaccent, btree_gist]
207
+ # R259: the extensions the db image carries (ruling:lite-official-postgres-image): the official postgres image's contrib set and pgvector
208
+ # from PGDG; unaccent serves Vietnamese-content search functions. No pg_cron, pg_net, pgmq or supabase_vault.
209
+ extensions: [pgcrypto, pg_trgm, vector, uuid-ossp, unaccent, btree_gist]
200
210
  # R258 DB_CRON_OWNED: THE queue outbox of a lite schema (the relay hands its unsent rows to BullMQ, ruling:R212/case-10). A pg_cron
201
211
  # job enqueues only by inserting one row into this table, writing only these columns, one of which is `queue`.
202
212
  queueOutbox: {table: public.queue, columns: [queue, payload, created_at, correlation_id]}
@@ -245,7 +255,8 @@ ruleParams:
245
255
  bull: [platform/queue]
246
256
  "@nestjs/bull": [platform/queue]
247
257
  kafkajs: [platform/event-bus] # pattern event-bus: Kafka is the only event transport
248
- "@nestjs/schedule": [] # no @Cron / @Interval / @Timeout anywhere: a schedule is a BullMQ job scheduler of a queue
258
+ "@nestjs/schedule": [platform/jobs] # R335: only the tick scheduler of platform/jobs (jobs.scheduler.ts); elsewhere a schedule is a BullMQ job scheduler of a queue
259
+ cron: [platform/jobs] # R335: CronJob of the tick scheduler
249
260
  eventemitter2: []
250
261
  setInterval: [platform/retry, platform/event-bus, platform/queue, platform/http, platform/realtime]
251
262
  setTimeout: [platform/retry, platform/event-bus, platform/queue, platform/http]
@@ -428,6 +439,7 @@ ruleParams:
428
439
  - {name: job_advance, reason: "platform/jobs (add job, lite): the token-guarded step write of jobs.sql"}
429
440
  - {name: job_complete, reason: "platform/jobs (add job, lite): the token-guarded completion of jobs.sql"}
430
441
  - {name: job_fail, reason: "platform/jobs (add job, lite): the token-guarded failure of jobs.sql"}
442
+ - {name: job_tick_claim, reason: "platform/jobs (add job, lite): the once-per-minute claim of a scheduler tick, jobs.sql (R335)"}
431
443
  - {name: queue_write, reason: "platform/queue (add queue, lite): the outbox insert of queue-outbox.sql"}
432
444
  - {name: queue_waiting, reason: "platform/queue (add queue, lite): the relay read FOR UPDATE SKIP LOCKED of queue-outbox.sql"}
433
445
  - {name: queue_mark_sent, reason: "platform/queue (add queue, lite): the relay mark of queue-outbox.sql"}
@@ -851,7 +863,7 @@ slots:
851
863
  "<env>/runtime/{config,env}/**", "<env>/runtime/env/KEYS.md", "<env>/secrets/<slug>.enc", "<env>/secrets/.gitkeep", "<env>/seeds/**"]
852
864
  forbids: ["<env>/runtime/files/**", "**/*.enc outside <env>/secrets/", DESIGN.md, deployment.json, "k8s/ at root"]
853
865
  # Owner ruling 2026-10-14: lite declares docker-swarm production, app runtime config, sealed custody and seed data.
854
- # The db service supplies the database and broker (pgmq, pg_cron); production has no Compose or host cron.
866
+ # The db service supplies the database; schedules are platform/jobs ticks (R335); production has no Compose or host cron.
855
867
  lite:
856
868
  requires: [application-stacks.yaml]
857
869
  allows: [application-stacks.yaml, "<env>/README.md", "<env>/environment.json", "<env>/infra/swarm/**", "<env>/infra/metadata.json",
@@ -915,7 +927,7 @@ slots:
915
927
  rules: [HFS_PLAINTEXT_SECRET]
916
928
 
917
929
  # ----- app root: the database of a lite app (ruling:lite-self-hosted-postgres-passport-minio): a self-hosted PostgreSQL in the app's
918
- # stack (the `db` service, image supabase/postgres for pg_cron, pg_net, pgmq, vector, unaccent and pgcrypto), migrated by
930
+ # stack (the `db` service, built from the managed db/Dockerfile: the official postgres image plus pgvector, ruling:lite-official-postgres-image), migrated by
919
931
  # `starci app db migrate --url-env <NAME>`. A full app keeps its TypeORM migrations under be/ and has no such folder.
920
932
  - id: app.db
921
933
  profiles: [app]
@@ -965,12 +977,26 @@ slots:
965
977
  tier: none
966
978
  tests: none
967
979
  since: 3.9.0
980
+ - id: app.db.image
981
+ profiles: [app]
982
+ editions: [lite]
983
+ # The managed image of the db service (templates/app/db-image, ruling:lite-official-postgres-image): FROM the digest-pinned official
984
+ # postgres image plus postgresql-17-pgvector from PGDG. The stack's db service, the local db container and the scratch database
985
+ # of `starci app db drift` all build it.
986
+ path: "db/Dockerfile"
987
+ presence: required
988
+ tracked: tracked
989
+ managedBy: db-image
990
+ tier: none
991
+ tests: none
992
+ since: 3.11.0
993
+ rules: [HFS_MANAGED_FILE_DRIFT]
968
994
  - id: app.db.bootstrap
969
995
  profiles: [app]
970
996
  editions: [lite]
971
- # The managed pre-migration bootstrap (templates/app/db-bootstrap): the auth, storage and extensions schemas, auth.users with the
972
- # GoTrue column set, auth.uid/role/jwt stubs, the NOLOGIN browser roles and the realtime publication, so migrations written for a
973
- # hosted Supabase apply to the self-hosted db service. `starci app db migrate` applies it before the first migration of an empty database.
997
+ # The managed pre-migration bootstrap (templates/app/db-bootstrap): the auth and storage schemas, auth.users with the GoTrue column
998
+ # set, auth.uid/role/jwt stubs and the NOLOGIN browser roles, so migrations written for a hosted Supabase apply to the db service's
999
+ # official postgres image (nothing else of Supabase: no supabase_admin, extensions schema or realtime publication). `starci app db migrate` applies it before the first migration of an empty database.
974
1000
  path: "db/bootstrap.sql"
975
1001
  presence: required
976
1002
  tracked: tracked
@@ -1711,6 +1737,21 @@ slots:
1711
1737
  coverage: required
1712
1738
  budget: {indexExports: 60}
1713
1739
  rules: [BE_TIER_DIRECTION, ARCH_OWNER_CYCLE, BE_MODULE_SHAPE]
1740
+ - id: be.platform.database.entities
1741
+ since: 3.10.0
1742
+ profiles: [be]
1743
+ editions: [lite]
1744
+ editionWhy: "lite registers the one PRIMARY_ENTITIES list on its single primary connection; full registers each capability's <c>Entities per connection from persistence/connection.ts."
1745
+ path: "src/modules/platform/database/entities.ts"
1746
+ presence: optional
1747
+ tracked: tracked
1748
+ tier: inherit
1749
+ role: entity-registry
1750
+ importedBy: ["apps/*/src/compose/*.ts", "apps/*/src/app.module.ts", "src/tests/world/**"]
1751
+ tests: none
1752
+ coverage: none
1753
+ why: "the entity registry (persistence.md BE-PERSISTENCE-3): it lists every capability's <c>Entities array by name, no glob, as PRIMARY_ENTITIES, the one list the primary connection maps, and exports nothing else. It is the one platform file that imports domain and platform capabilities, each import naming only that capability's <c>Entities from its index.ts (BE_TIER_DIRECTION, ARCH_OWNER_EXPORT_BYPASS); DatabaseModule and the platform/database index never import it, and only the files importedBy names (app composition and the test world) import it, by the deep path @modules/platform/database/entities (BE_PUBLIC_SURFACE), since database.module, this list and the capability indexes would otherwise form a cycle that fails at boot"
1754
+ rules: [BE_TIER_DIRECTION, BE_PUBLIC_SURFACE, BE_SCHEMA_OWNER]
1714
1755
  - id: be.platform.logging
1715
1756
  since: 3.5.0
1716
1757
  profiles: [be]
@@ -1765,7 +1806,7 @@ slots:
1765
1806
  the same QueueOutbox and QueueWorkerRegistry ports and full's BullMQ adapter on the declared Redis (backing: [redis]): the
1766
1807
  relay adds each committed outbox row with the outbox id as the job id, workers retry with exponential backoff and keep a
1767
1808
  job that exhausts its attempts as failed (the dead letter); the outbox table comes from a db migration, and a
1768
- schedule is a BullMQ job scheduler or a pg_cron tick that inserts one outbox row (knowledge/patterns/be/queues.yaml liteAdapter)
1809
+ schedule is a BullMQ job scheduler or a platform/jobs tick that writes one outbox row, R335 (knowledge/patterns/be/queues.yaml liteAdapter)
1769
1810
  requires: [index.ts, queue.module.ts, queue.port.ts, queue.contracts.ts, queue-outbox.service.ts, queue-outbox.service.spec.ts]
1770
1811
  tests: unit-beside
1771
1812
  coverage: required
@@ -0,0 +1,53 @@
1
+ import { braceVariants, globExpression } from '../../lib/glob.mjs';
2
+
3
+ /**
4
+ * The entity registry (persistence.md BE-PERSISTENCE-3): the one file whose slot plays `role: entity-registry`
5
+ * (`be.platform.database.entities`, lite's `src/modules/platform/database/entities.ts`). It lists every capability's `<c>Entities`
6
+ * array as `PRIMARY_ENTITIES`, so it is the one platform file that imports domain and platform capability barrels, and only for
7
+ * that name; and it is imported by deep path only from the files its slot's `importedBy` names (app composition and the test world).
8
+ * The tier matrix (tiers.mjs), the public-entry check (owners.mjs) and the lint rule `import-owner-entry` read it here.
9
+ */
10
+ export const ENTITY_REGISTRY_ROLE = 'entity-registry';
11
+
12
+ /** The tiers whose capabilities contribute an entity list to the registry. */
13
+ const CONTRIBUTING_TIERS = new Set(['domain', 'platform']);
14
+
15
+ /** The entity list a capability exports: `<c>Entities`, `<c>` its folder name in camelCase. */
16
+ export const entityListName = capability => `${capability.replace(/-([a-z0-9])/g, (_, next) => next.toUpperCase())}Entities`;
17
+
18
+ /** The slot of `file` (side-relative or absolute) when it plays the entity-registry role, else null. */
19
+ export function registrySlot(resolver, file) {
20
+ const slot = resolver?.slotOf?.(file);
21
+ return slot?.role === ENTITY_REGISTRY_ROLE ? slot : null;
22
+ }
23
+
24
+ /**
25
+ * Whether `file` is one of the importers the registry slot admits by deep path (`importedBy`, side-relative patterns); an app-wide
26
+ * resolver answers for a side-prefixed path (`be/apps/...`), which is read without its side folder.
27
+ */
28
+ export function registryImporter(resolver, slot, file) {
29
+ const side = resolver?.sideOf?.(file);
30
+ const rel = side ? file.slice(side.length + 1) : file;
31
+ return (slot.importedBy ?? []).some(pattern => braceVariants(pattern).some(variant => globExpression(variant).test(rel)));
32
+ }
33
+
34
+ /** The names an import declaration binds by name; null for a default, namespace or side-effect import and for any re-export. */
35
+ function namedImports(declaration) {
36
+ const clause = declaration?.importClause;
37
+ if (!clause || clause.name || !Array.isArray(clause.namedBindings?.elements) || !clause.namedBindings.elements.length) return null;
38
+ return clause.namedBindings.elements.map(element => (element.propertyName ?? element.name).text);
39
+ }
40
+
41
+ /**
42
+ * Whether an owner-graph edge (side-relative `from` and `to`, `edge.declaration` the TypeScript statement) is the registry naming a
43
+ * capability's entity list: it leaves the registry, imports the public entry (`index.ts`) of a domain or platform capability, and
44
+ * binds that capability's `<c>Entities` and nothing else.
45
+ */
46
+ export function registryListImport(resolver, edge) {
47
+ if (!registrySlot(resolver, edge.from)) return false;
48
+ const owner = resolver.ownerOf(edge.to);
49
+ if (!owner || !CONTRIBUTING_TIERS.has(resolver.slot(owner.slot)?.tier) || edge.to !== `${owner.root}/index.ts`) return false;
50
+ const names = namedImports(edge.edge?.declaration ?? edge.declaration);
51
+ const listName = entityListName(owner.root.split('/').at(-1));
52
+ return names !== null && names.every(name => name === listName);
53
+ }
@@ -4,6 +4,7 @@ import { relativePath, workspaceExportSources } from './typescript.mjs';
4
4
  import { sourceLocation } from '../../lib/ts-ast.mjs';
5
5
  import { globExpression } from '../../lib/glob.mjs';
6
6
  import { posixPath } from '../../lib/path-key.mjs';
7
+ import { registryImporter, registrySlot } from './entity-registry.mjs';
7
8
 
8
9
  function absolute(root, relative) {
9
10
  return canonical(path.resolve(root, ...relative.split('/')));
@@ -68,6 +69,15 @@ function arrangesSchema(config, from, to) {
68
69
  && resolver.classifyPath(relativePath(config.root, to)).slot === 'be.persistence';
69
70
  }
70
71
 
72
+ /**
73
+ * The entity registry (slot role entity-registry, entity-registry.mjs) is imported by deep path, and only from the files its slot's
74
+ * `importedBy` names: app composition and the test world. Any other importer goes through the owner's entry, which never exports it.
75
+ */
76
+ function importsRegistry(config, from, to) {
77
+ const slot = registrySlot(config.hfs, relativePath(config.root, to));
78
+ return slot !== null && registryImporter(config.hfs, slot, relativePath(config.root, from));
79
+ }
80
+
71
81
  function publicEntryViolations(config, context, owners, sourceFiles) {
72
82
  const violations = [];
73
83
  for (const owner of owners) {
@@ -104,6 +114,7 @@ function ownerImportViolations(config, context, owners) {
104
114
  const bypass = privateOwnerChain(context, owners, edge);
105
115
  if (!bypass) continue;
106
116
  if (arrangesSchema(config, from, bypass.chain.at(-1))) continue;
117
+ if (bypass.chain.length === 2 && importsRegistry(config, from, bypass.chain.at(-1))) continue;
107
118
  violations.push({
108
119
  ruleId: 'ARCH_OWNER_EXPORT_BYPASS',
109
120
  path: relativePath(config.root, from),
@@ -1,4 +1,5 @@
1
1
  import { byCodeUnit } from '../../lib/list.mjs';
2
+ import { registryListImport, registrySlot } from './entity-registry.mjs';
2
3
 
3
4
  /**
4
5
  * HFS checks 1 and 2 (knowledge/hfs/slots.yaml `tiers`):
@@ -8,7 +9,9 @@ import { byCodeUnit } from '../../lib/list.mjs';
8
9
  * kind (slot field `trigger`: api, webhooks, realtime, saga, reactors, jobs, cli) importing a feature of another is
9
10
  * BE_KIND_ISOLATION, whose fix is the event bus,
10
11
  * an app never imports another app (BE_SERVICE_ISOLATION / FE_APP_ISOLATION), and a component layer imports only the layers after it;
11
- * 2. owner cycles: a strongly connected component of the owner graph, type-only imports included (ARCH_OWNER_CYCLE),
12
+ * the entity registry naming a capability's `<c>Entities` from its public entry is the one platform-to-domain edge (entity-registry.mjs);
13
+ * 2. owner cycles: a strongly connected component of the owner graph, type-only imports included (ARCH_OWNER_CYCLE), the entity
14
+ * registry counted as a unit of its own,
12
15
  * reported with the cycle path and the import that closes each hop.
13
16
  * Importing inside one owner is always allowed; the public-entry rule stays with owners.mjs (ARCH_OWNER_EXPORT_BYPASS).
14
17
  */
@@ -138,15 +141,23 @@ function inspectTierEdge(graph, edge, tierRule, counts, violations, coverage) {
138
141
  return;
139
142
  }
140
143
  coverage.edgesChecked += 1;
144
+ if (verdict.reason === 'tierDirection' && registryListImport(graph.resolver, edge)) return;
141
145
  reportReasonedTierViolation(graph, edge, verdict, tierRule, counts, violations);
142
146
  }
143
147
 
148
+ /**
149
+ * The cycle unit of a file: its owner unit, except the entity registry (entity-registry.mjs), which is a unit of its own. It sits in
150
+ * platform/database but is composition-level by role (it imports every capability's `<c>Entities`), so it never closes a cycle
151
+ * among capabilities through the owner it lives in.
152
+ */
153
+ const cycleUnit = (graph, resolver, rel) => (registrySlot(resolver, rel) ? `entity-registry:${rel}` : graph.unit(rel));
154
+
144
155
  function ownerAdjacency(graph, resolver) {
145
156
  const adjacency = new Map();
146
157
  const witness = new Map();
147
158
  for (const edge of graph.edges) {
148
- const a = graph.unit(edge.from);
149
- const b = graph.unit(edge.to);
159
+ const a = cycleUnit(graph, resolver, edge.from);
160
+ const b = cycleUnit(graph, resolver, edge.to);
150
161
  if (!a || !b || a === b) continue;
151
162
  if (resolver.tierOf(edge.from) === 'none' || resolver.tierOf(edge.to) === 'none') continue;
152
163
  if (!adjacency.has(a)) adjacency.set(a, new Set());
@@ -87,7 +87,9 @@ export const MANIFEST_KINDS = [APP_KIND, RUNTIME_KIND];
87
87
  export const manifestKind = (m) => (isPlainObject(m) && m.kind !== undefined ? m.kind : APP_KIND);
88
88
  const strList = (v) => stringList(v);
89
89
 
90
- const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy'];
90
+ const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy', 'role', 'importedBy'];
91
+ /** The roles a file slot may play that a rule reads (`role`): the entity registry of persistence.md BE-PERSISTENCE-3 (architecture/entity-registry.mjs). */
92
+ const SLOT_ROLES = ['entity-registry'];
91
93
  /** The fields a slot's `lite` overlay may hold: the same keys it would carry in the slot body, resolved under edition lite. */
92
94
  const LITE_OVERLAY_KEYS = ['path', 'requires', 'allows', 'forbids', 'minInstances', 'requiredInstances', 'why'];
93
95
  /** A runtime slot has no app kind, side composition, layer or managed template; it may name the generator of a generated copy. */
@@ -249,6 +251,8 @@ function slotEntryProblems(slot, at) {
249
251
  else if (Array.isArray(slot.allows) && slot.entries.some((entry) => !slot.allows.includes(entry))) bad.push(`${at}: every entry must be one of the names the slot allows`);
250
252
  }
251
253
  if (slot.outcomeHome !== undefined && !(slot.outcomeHome === true && typeof slot.path === 'string' && slot.path && !slot.path.endsWith('/'))) bad.push(`${at}: outcomeHome is true and belongs to a file slot (the one file that declares the repository's Outcome union)`);
254
+ if (slot.role !== undefined && !(SLOT_ROLES.includes(slot.role) && typeof slot.path === 'string' && slot.path && !slot.path.endsWith('/'))) bad.push(`${at}: role is one of ${SLOT_ROLES.join(', ')} and belongs to a file slot`);
255
+ if (slot.importedBy !== undefined && !(slot.role !== undefined && strList(slot.importedBy) && slot.importedBy.length && new Set(slot.importedBy).size === slot.importedBy.length && slot.importedBy.every(relPath))) bad.push(`${at}: importedBy is a non-empty list of unique relative path patterns of the only files that import the slot's file by deep path, on a slot with a role`);
252
256
  return bad;
253
257
  }
254
258