@quixotic_mnemonics/swastik 0.0.0-stage → 0.1.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.
Files changed (66) hide show
  1. package/_template/README.md +34 -0
  2. package/_template/assets/.gitkeep +1 -0
  3. package/_template/commands/.gitkeep +1 -0
  4. package/_template/config/.gitkeep +1 -0
  5. package/_template/events/.gitkeep +1 -0
  6. package/_template/jobs/.gitkeep +1 -0
  7. package/_template/locales/.gitkeep +1 -0
  8. package/_template/manifest.ts +13 -0
  9. package/_template/migrations/.gitkeep +1 -0
  10. package/_template/repositories/.gitkeep +1 -0
  11. package/_template/services/.gitkeep +1 -0
  12. package/_template/tests/.gitkeep +1 -0
  13. package/_template/ui/.gitkeep +1 -0
  14. package/dist/capabilities.d.ts +110 -0
  15. package/dist/capabilities.js +107 -0
  16. package/dist/commands.d.ts +157 -0
  17. package/dist/commands.js +9 -0
  18. package/dist/components-v2.d.ts +252 -0
  19. package/dist/components-v2.js +263 -0
  20. package/dist/components.d.ts +142 -0
  21. package/dist/components.js +11 -0
  22. package/dist/context.d.ts +59 -0
  23. package/dist/context.js +29 -0
  24. package/dist/entrypoints/admin.d.ts +26 -0
  25. package/dist/entrypoints/admin.js +2 -0
  26. package/dist/entrypoints/core.d.ts +31 -0
  27. package/dist/entrypoints/core.js +2 -0
  28. package/dist/entrypoints/marketplace.d.ts +30 -0
  29. package/dist/entrypoints/marketplace.js +2 -0
  30. package/dist/entrypoints/standard.d.ts +36 -0
  31. package/dist/entrypoints/standard.js +2 -0
  32. package/dist/events.d.ts +15 -0
  33. package/dist/events.js +19 -0
  34. package/dist/index.d.ts +27 -0
  35. package/dist/index.js +21 -0
  36. package/dist/manifest-schema.d.ts +261 -0
  37. package/dist/manifest-schema.js +297 -0
  38. package/dist/manifest.d.ts +47 -0
  39. package/dist/manifest.js +6 -0
  40. package/dist/pages.d.ts +274 -0
  41. package/dist/pages.js +3 -0
  42. package/dist/paging.d.ts +32 -0
  43. package/dist/paging.js +59 -0
  44. package/dist/permits.d.ts +222 -0
  45. package/dist/permits.js +16 -0
  46. package/dist/validate.d.ts +21 -0
  47. package/dist/validate.js +33 -0
  48. package/package.json +78 -4
  49. package/src/capabilities.ts +196 -0
  50. package/src/commands.ts +181 -0
  51. package/src/components-v2.ts +533 -0
  52. package/src/components.ts +162 -0
  53. package/src/context.ts +83 -0
  54. package/src/entrypoints/admin.ts +36 -0
  55. package/src/entrypoints/core.ts +41 -0
  56. package/src/entrypoints/marketplace.ts +38 -0
  57. package/src/entrypoints/standard.ts +44 -0
  58. package/src/events.ts +34 -0
  59. package/src/index.ts +159 -0
  60. package/src/manifest-schema.ts +340 -0
  61. package/src/manifest.ts +68 -0
  62. package/src/pages.ts +282 -0
  63. package/src/paging.ts +72 -0
  64. package/src/permits.ts +250 -0
  65. package/src/validate.ts +42 -0
  66. package/README.md +0 -3
@@ -0,0 +1,340 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * The module manifest — the specified contract.
5
+ *
6
+ * Authority: `docs/spec/modules/module-anatomy-manifest.md` (SPEC-03-MODULES) and
7
+ * `docs/contracts/module-manifest.schema.json`. Where the two once disagreed with this file, this
8
+ * file was the gap; it now expresses the contract.
9
+ *
10
+ * The shape is a **discriminated union on `hardcoded`**: a `hardcoded: true` build is a private
11
+ * build pinned to one guild, so it carries `hardcodeGuildId` and admits only `releaseStatus:
12
+ * 'private'`; a `hardcoded: false` build forbids `hardcodeGuildId` and admits either release status.
13
+ * On top of the union the **visibility triad** runs as one `superRefine`, so a violating manifest
14
+ * fails with a single error naming the conflicting fields together rather than three independent
15
+ * ones.
16
+ */
17
+ export const moduleTierSchema = z.enum([
18
+ "admin",
19
+ "core",
20
+ "standard",
21
+ "marketplace",
22
+ ]);
23
+
24
+ export const moduleVisibilitySchema = z.enum(["public", "unlisted", "private"]);
25
+
26
+ /**
27
+ * UR-20261119-145 — DEPRECATED, and kept only because it is public API.
28
+ *
29
+ * `releaseStatus` left the manifest in UR-20261118-138: nothing read it, and the runtime gate it was meant
30
+ * to be is deferred in `ADR-017`. This schema and its `ModuleReleaseStatus` type are still exported from
31
+ * `@quixotic_mnemonics/swastik`, so deleting them is a breaking change for any module author who imported the name —
32
+ * and there are none yet, which is exactly why it should be done deliberately rather than as a tidy-up.
33
+ *
34
+ * Nothing in the framework references either one. When the gate in ADR-017 is built, this either returns as
35
+ * a real field or is removed in the same change; until then it is a name with no behaviour, and it says so.
36
+ */
37
+ export const moduleReleaseStatusSchema = z.enum(["private", "public"]);
38
+
39
+ export const marketplaceCategorySchema = z.enum([
40
+ "audio",
41
+ "community",
42
+ "security",
43
+ "integrations",
44
+ "utility",
45
+ ]);
46
+
47
+ /** Mirrors the DI container's `Lifetime` (src/di/container.ts). */
48
+ export const serviceLifetimeSchema = z.enum([
49
+ "singleton",
50
+ "transient",
51
+ "scoped",
52
+ ]);
53
+
54
+ export const commandManifestSchema = z.object({
55
+ name: z.string().min(1),
56
+ description: z.string().min(1),
57
+ guildOnly: z.boolean().default(true),
58
+ requiresDefer: z.boolean().default(false),
59
+ ephemeral: z.boolean().default(false),
60
+ nsfw: z.boolean().default(false),
61
+ permissions: z
62
+ .object({
63
+ discord: z.array(z.string()).default([]),
64
+ })
65
+ .default({ discord: [] }),
66
+ defaultMemberPermissions: z.string().nullable().optional(),
67
+ // UR-20261119-146 — `rbacRequirement` was DELETED from here. Nothing in the backend read it: the
68
+ // requirement that is enforced lives in the module's own `defineCommand({ permissions: { rbac } })`, which
69
+ // `toCommandDefinition` maps to `RBAC_TO_RANK` and the resolver consumes as `requiredRank`. Two
70
+ // declarations existed and only the code-level one worked, so the field a module author would naturally
71
+ // reach for was the dead one - the same defect class as `releaseStatus` (REC-058) and `buildId` (REC-049).
72
+ });
73
+
74
+ export const eventCatalogEntrySchema = z.object({
75
+ name: z
76
+ .string()
77
+ .regex(
78
+ /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*){2}$/,
79
+ "event name must be {domain}.{entity}.{action}",
80
+ ),
81
+ description: z.string().min(1),
82
+ // §18 — every catalog entry declares a payload schema; a change to it is a breaking change.
83
+ payload: z.record(z.string(), z.unknown()),
84
+ });
85
+
86
+ export const crossModuleReadSchema = z.object({
87
+ targetModule: z.string().min(1),
88
+ accessor: z
89
+ .string()
90
+ .regex(
91
+ /ForCrossModuleRead$/,
92
+ 'accessor name must end with "ForCrossModuleRead"',
93
+ ),
94
+ });
95
+
96
+ /**
97
+ * `depends` entries are `{ token, version }` pins, never bare tokens: Stage 11 runs a
98
+ * range-satisfaction evaluator over them (see `topo-sort.ts`).
99
+ */
100
+ export const dependencyEntrySchema = z
101
+ .object({
102
+ token: z.string().min(1),
103
+ version: z.string().min(1),
104
+ })
105
+ .strict();
106
+
107
+ /** `provides` entries are `{ token, contract }` — the contract names a TS interface `tsc` checks. */
108
+ export const providedServiceSchema = z
109
+ .object({
110
+ token: z.string().min(1),
111
+ contract: z.string().min(1),
112
+ })
113
+ .strict();
114
+
115
+ /** `services` entries are `{ token, class, lifetime, deps }`. */
116
+ export const declaredServiceSchema = z
117
+ .object({
118
+ token: z.string().min(1),
119
+ class: z.string().min(1),
120
+ lifetime: serviceLifetimeSchema,
121
+ deps: z.array(z.string()).default([]),
122
+ })
123
+ .strict();
124
+
125
+ /** §1.3 / ADR-012 / ADR-013 — a module's declared UI identity: banner, accent, logo icon, name. */
126
+ export const moduleUiSchema = z
127
+ .object({
128
+ banner: z.string().min(1).optional(),
129
+ accent: z
130
+ .string()
131
+ .regex(/^#[0-9a-fA-F]{6}$/, "accent must be a #RRGGBB hex colour")
132
+ .optional(),
133
+ icon: z.string().min(1).optional(),
134
+ /**
135
+ * UR-20261012-066 — the module-relative path to the logo image the core registers as the emoji
136
+ * named by `icon`. Mirrors `banner`: a module-supplied asset, declared by the module that owns it.
137
+ */
138
+ iconAsset: z.string().min(1).optional(),
139
+ /**
140
+ * UR-20261029-112 — a module's OWN indicator set: emoji name -> module-relative image.
141
+ *
142
+ * The framework uploaded these from its own `assets/` before, so a module's indicator artwork
143
+ * lived in the host. The module now names each emoji it needs and points at its own file; the
144
+ * core resolves and registers them, and holds no copy.
145
+ */
146
+ icons: z.record(z.string().min(1), z.string().min(1)).optional(),
147
+ displayName: z.string().min(1).optional(),
148
+ // UR-20261119-139 - `devUsername` moved to the TOP LEVEL. It was under `ui`, which made the
149
+ // developer's identity a rendering detail; the maintainer's definition puts it in the manifest as the
150
+ // attribution the renderer grammar reads. One field, in one place, so the two cannot disagree.
151
+ })
152
+ .strict();
153
+
154
+ const commonManifestFields = {
155
+ name: z
156
+ .string()
157
+ .min(1)
158
+ .regex(/^[a-z][a-z0-9-]*$/, "module name must be lowercase-kebab-case"),
159
+ version: z
160
+ .string()
161
+ .regex(/^\d+\.\d+\.\d+$/, 'version must be semver, e.g. "1.0.0"'),
162
+ description: z.string().min(1).max(120),
163
+ tier: moduleTierSchema,
164
+ devGuildOnly: z.boolean().optional(),
165
+ /**
166
+ * UR-20261119-139 - THE MANIFEST NAMES THE DEVELOPER BY USERNAME, NEVER BY ID.
167
+ *
168
+ * The maintainer drew the line the corpus had blurred: a **developer username** is a Dumby account
169
+ * username, promoted to a developer account with friction, and it is what the renderer's attribution
170
+ * grammar and the manifest speak. A **developer id** is issued by application, is what the compliance
171
+ * and management team enforce against, and never appears in a manifest at all - it lives in the
172
+ * credential record and in the license subject.
173
+ *
174
+ * Optional, and ABSENT MEANS FIRST-PARTY: the seven core modules and hello-world ship inside the image
175
+ * and have no registered account to name. Absence is only reachable by a module built into the image,
176
+ * because the upload endpoint refuses a submission without it.
177
+ */
178
+ devUsername: z.string().min(1).optional(),
179
+ /**
180
+ * UR-20261119-139 - the ADMIN tier's guild binding.
181
+ *
182
+ * The tier was designed for "our own bot-owner modules on our development server"; the maintainer's
183
+ * adaptation is that any developer may have such a module, scoped to their own development guild -
184
+ * exactly as a persona is scoped to its bound guild. `devGuildOnly` is the catalogue-side claim;
185
+ * `devGuildId` is the BINDING, and it is required for `tier: admin` (tier-rules) and enforced by the
186
+ * loader and the dispatch path, so the claim can no longer be declared and ignored.
187
+ */
188
+ devGuildId: z.string().min(1).optional(),
189
+ /** The ONLY catalogue field with a consumer: `mdis.service.ts` filters `visibility !== 'private'`. */
190
+ visibility: moduleVisibilitySchema,
191
+ marketplaceCategory: marketplaceCategorySchema.optional(),
192
+ depends: z.array(dependencyEntrySchema).default([]),
193
+ provides: z.array(providedServiceSchema).default([]),
194
+ intents: z.array(z.string()).default([]),
195
+ partials: z.array(z.string()).default([]),
196
+ commands: z.array(commandManifestSchema).default([]),
197
+ events: z.array(z.string()).default([]),
198
+ services: z.array(declaredServiceSchema).default([]),
199
+ repositories: z.array(z.string()).default([]),
200
+ jobs: z.array(z.string()).default([]),
201
+ tasks: z.array(z.string()).default([]),
202
+ routes: z.array(z.string()).default([]),
203
+ middleware: z.array(z.string()).default([]),
204
+ // UR-20261116-132 — the customId prefixes this module ANSWERS, so a control a module owns is
205
+ // declared rather than hidden. The loader refuses a handler whose prefix is not listed here.
206
+ components: z.array(z.string().min(1)).default([]),
207
+ migrations: z.array(z.string()).default([]),
208
+ locales: z.array(z.string()).default(["en-US"]),
209
+ config: z.record(z.string(), z.unknown()).default({}),
210
+ eventsCatalog: z.array(eventCatalogEntrySchema).default([]),
211
+ dashboardSchema: z.record(z.string(), z.unknown()).optional(),
212
+ ui: moduleUiSchema.optional(),
213
+ /**
214
+ * UR-20261126-247 R3 — ADR-001 BAN 2, LAYER 2: THE MANIFEST DECLARES HOW IT RENDERS.
215
+ *
216
+ * Division 1 §1.8 has claimed since ADR-001 that load-time validation "refuses any module whose
217
+ * declared render contract requires classic embeds". It could not: there was no field to declare, so
218
+ * there was nothing to refuse. This is the field. It admits exactly one value — `blocks` — because the
219
+ * only conforming answer is the one the framework already assumes; a manifest that declares anything
220
+ * else fails validation at load, which is the layer-2 refusal the spec describes.
221
+ *
222
+ * Optional, and ABSENT MEANS `blocks`: every module that ships today returns blocks or data, and a
223
+ * required field would have been eight manifest edits that changed no behaviour. Declaring it is for
224
+ * a module author who wants the contract stated, and for the gate that checks the corpus's claim.
225
+ */
226
+ render: z
227
+ .object({
228
+ contract: z.enum(["blocks"]),
229
+ })
230
+ .strict()
231
+ .optional(),
232
+ crossModuleReads: z.array(crossModuleReadSchema).default([]),
233
+ };
234
+
235
+ /**
236
+ * UR-20261118-138 - the union is gone with `hardcoded`.
237
+ *
238
+ * The schema used to be a discriminated union on `hardcoded`, and `hardcoded`, `releaseStatus` and
239
+ * `visibility` were then validated against each other as a "triad". Tracing every consumer showed the
240
+ * shape of the problem: `hardcoded` was read by NOTHING, `releaseStatus` was read by NOTHING, and the
241
+ * triad rule was therefore three fields keeping each other consistent, two of which nothing consumed.
242
+ * It looked meaningful because it validated, and it meant nothing because nothing read it - the same
243
+ * defect class as `RenderDescriptor.buildId` (REC-049).
244
+ *
245
+ * `hardcodeGuildId` existed only to pair with `hardcoded` and had no consumer either, so it went too.
246
+ *
247
+ * What remains is what the code actually uses: `tier` (fatal-vs-degraded, privilege), `visibility` (the
248
+ * catalogue filter in mdis.service.ts), `devUsername` (the developer's account name, optional and absent
249
+ * for first-party) and `devGuildId` (the admin tier's guild binding). `required` is derived from `tier` at
250
+ * the loader rather than declared.
251
+ */
252
+ export const moduleManifestSchema = z
253
+ .object(commonManifestFields)
254
+ .strict()
255
+ .superRefine((manifest, ctx) => {
256
+ const problems = providesIsNamespacedAndFirstParty(manifest);
257
+ if (problems.length > 0) {
258
+ ctx.addIssue({
259
+ code: "custom",
260
+ message: `manifest "${manifest.name}" violates the service seam: ${problems.join("; ")}`,
261
+ });
262
+ }
263
+ });
264
+
265
+ /**
266
+ * 2026-11-16 — the service seam, closed at validation (`REC-052`).
267
+ *
268
+ * `provides` used to accept any non-empty token for any module, and the registry resolved it
269
+ * last-wins, so a licensed module could declare `core.PersonaRuntime` and take a core capability by
270
+ * loading later. Three rules now, all refused at validation rather than at load:
271
+ *
272
+ * 1. A `core.*` token is FIRST-PARTY ONLY. The discriminator is `devId: 'dev_first_party'`, which is
273
+ * safe to key on because the manifest's `devId` is checked against the authenticated principal at
274
+ * upload and at deploy — a licensed developer cannot claim it and have the claim survive the
275
+ * endpoint. It is not trusted here on its own; it is trusted because the endpoint already proved it.
276
+ * 2. A `core.*` token requires `tier: 'core'`. A first-party standard-tier module (hello-world) may
277
+ * not reach the core base through the service seam any more than through an import.
278
+ * 3. Every token is NAMESPACED — `core.*` or `module.<slug>.*` — and no manifest may declare the same
279
+ * token twice. The guard's `MODULE_TOKEN_PATTERN` already gave module-namespaced tokens their own
280
+ * namespace; this is the same rule, stated where the manifest is validated.
281
+ */
282
+ export const providesIsNamespacedAndFirstParty = (manifest: {
283
+ readonly name: string;
284
+ readonly devUsername?: string | undefined;
285
+ readonly tier: string;
286
+ readonly provides: readonly { readonly token: string }[];
287
+ }): readonly string[] => {
288
+ const problems: string[] = [];
289
+ const seen = new Set<string>();
290
+ for (const { token } of manifest.provides) {
291
+ if (seen.has(token))
292
+ problems.push(`token '${token}' is declared more than once`);
293
+ seen.add(token);
294
+ if (token.startsWith("core.")) {
295
+ if (manifest.devUsername !== undefined) {
296
+ problems.push(
297
+ `token '${token}' is a core capability, and core capabilities are first-party only (declared by '${manifest.devUsername}')`,
298
+ );
299
+ }
300
+ if (manifest.tier !== "core") {
301
+ problems.push(
302
+ `token '${token}' is a core capability, and only tier 'core' may provide one (tier is '${manifest.tier}')`,
303
+ );
304
+ }
305
+ continue;
306
+ }
307
+ if (!/^module\.[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_.]+$/.test(token)) {
308
+ problems.push(
309
+ `token '${token}' is not namespaced — use 'module.<slug>.<name>'`,
310
+ );
311
+ }
312
+ }
313
+ return problems;
314
+ };
315
+
316
+ export type ModuleManifest = z.infer<typeof moduleManifestSchema>;
317
+ export type DependencyEntry = z.infer<typeof dependencyEntrySchema>;
318
+ export type ProvidedService = z.infer<typeof providedServiceSchema>;
319
+ export type DeclaredService = z.infer<typeof declaredServiceSchema>;
320
+ export type ModuleVisibility = z.infer<typeof moduleVisibilitySchema>;
321
+ export type ModuleReleaseStatus = z.infer<typeof moduleReleaseStatusSchema>;
322
+
323
+ /**
324
+ * UR-20261118-138 - `required` is DERIVED, not declared.
325
+ *
326
+ * It used to be a manifest field, and every manifest restated its own tier with it: all seven core
327
+ * modules said `required: true`, `hello-world` said `false`. The loader's only use for it was deciding
328
+ * fatal-versus-degraded on a load failure, and core/admin are already the tiers §13.2 makes permanent
329
+ * and un-disableable. So the field was a second way to say `tier`, and a manifest could say it WRONGLY -
330
+ * `tier: standard, required: true` was schema-valid and would have made a marketplace module fatal to
331
+ * the boot.
332
+ *
333
+ * One function, so there is one answer.
334
+ */
335
+ export function isRequiredTier(
336
+ tier: z.infer<typeof moduleTierSchema>,
337
+ ): boolean {
338
+ return tier === "core" || tier === "admin";
339
+ }
340
+ export type MarketplaceCategory = z.infer<typeof marketplaceCategorySchema>;
@@ -0,0 +1,68 @@
1
+ export const moduleTiers = ['admin', 'core', 'standard', 'marketplace'] as const;
2
+
3
+ export type ModuleTier = (typeof moduleTiers)[number];
4
+
5
+ import type { ModuleManifest } from './manifest-schema.js';
6
+ import type { z } from 'zod';
7
+ import { commandManifestSchema } from './manifest-schema.js';
8
+
9
+ export type { ModuleManifest } from './manifest-schema.js';
10
+ export type {
11
+ DependencyEntry,
12
+ ProvidedService,
13
+ DeclaredService,
14
+ ModuleVisibility,
15
+ ModuleReleaseStatus,
16
+ MarketplaceCategory,
17
+ } from './manifest-schema.js';
18
+ export * from './manifest-schema.js';
19
+
20
+ /** The per-command entry of a manifest, derived from the shared schema. */
21
+ export type ModuleCommandManifest = z.infer<typeof commandManifestSchema>;
22
+
23
+ export interface ModuleLifecycle<Container = unknown> {
24
+ onLoad?: (container: Container) => Promise<void> | void;
25
+ onReady?: (container: Container) => Promise<void> | void;
26
+ /**
27
+ * UR-20261012-071 — §11.7: start active processes on the DISABLED → ENABLED transition (a polling
28
+ * loop, an external connection, a scheduled task). Optional; idempotent; ≤ 5 s.
29
+ *
30
+ * These are GLOBAL transitions — load, re-enable, shutdown — not per-guild ones. §13.7 is explicit
31
+ * that a per-guild toggle "never touches the module's loaded state, DI registrations, or event
32
+ * subscriptions", so disabling a module in ONE guild must not stop a process that other guilds are
33
+ * still served by. The per-guild case is handled by the execution gates (UR-20261012-069).
34
+ */
35
+ onEnable?: (container: Container) => Promise<void> | void;
36
+ /**
37
+ * UR-20261012-071 — §11.7: stop them on the ENABLED → DISABLED transition. Optional; idempotent;
38
+ * ≤ 5 s. A throw is logged and the module still transitions to DISABLED. Always runs BEFORE
39
+ * `onUnload`.
40
+ */
41
+ onDisable?: () => Promise<void> | void;
42
+ /**
43
+ * UR-20261012-072 — §11.7: "cleanup on an unrecoverable error". Called when the framework gives up
44
+ * on the module — a load or ready failure it cannot recover from. Idempotent; a throw here is
45
+ * logged and does not change the outcome.
46
+ */
47
+ onError?: (error: Error) => Promise<void> | void;
48
+ /**
49
+ * UR-20261012-072 — §11.7: "react to a per-guild config change without a reload". Called when THIS
50
+ * module's per-guild config is written, so a module can refresh cached values rather than recompute
51
+ * them on every read. Idempotent.
52
+ */
53
+ onConfigChange?: (
54
+ guildId: string,
55
+ config: Readonly<Record<string, unknown>>,
56
+ ) => Promise<void> | void;
57
+ onUnload?: () => Promise<void> | void;
58
+ }
59
+
60
+ export interface SwastikModule<Container = unknown> extends ModuleLifecycle<Container> {
61
+ manifest: ModuleManifest;
62
+ }
63
+
64
+ export function defineModule<Container = unknown>(
65
+ moduleDefinition: SwastikModule<Container>,
66
+ ): SwastikModule<Container> {
67
+ return moduleDefinition;
68
+ }