@cosmicdrift/kumiko-framework 0.412.0 → 0.413.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 (52) hide show
  1. package/agents/boot-rules.md +343 -0
  2. package/agents/examples/api-docs.md +79 -71
  3. package/agents/examples/golden-path.md +11 -11
  4. package/agents/examples/{contact.md → helpdesk.md} +31 -31
  5. package/agents/examples.md +1 -1
  6. package/agents/features-index.md +2 -2
  7. package/agents/features.md +16 -16
  8. package/dist/engine/boot-validator/boot-report.d.ts +3 -0
  9. package/dist/engine/boot-validator/boot-report.js +2 -2
  10. package/dist/engine/boot-validator/boot-rules.d.ts +570 -0
  11. package/dist/engine/boot-validator/boot-rules.js +20 -0
  12. package/dist/engine/boot-validator/definition-config-events-jobs-rules.d.ts +77 -0
  13. package/dist/engine/boot-validator/definition-config-events-jobs-rules.js +77 -0
  14. package/dist/engine/boot-validator/definition-events-rules.d.ts +42 -0
  15. package/dist/engine/boot-validator/definition-events-rules.js +42 -0
  16. package/dist/engine/boot-validator/definition-feature-rules.d.ts +42 -0
  17. package/dist/engine/boot-validator/definition-feature-rules.js +42 -0
  18. package/dist/engine/boot-validator/definition-field-factories-rules.d.ts +17 -0
  19. package/dist/engine/boot-validator/definition-field-factories-rules.js +17 -0
  20. package/dist/engine/boot-validator/definition-handlers-rules.d.ts +72 -0
  21. package/dist/engine/boot-validator/definition-handlers-rules.js +72 -0
  22. package/dist/engine/boot-validator/definition-ownership-from-rules.d.ts +27 -0
  23. package/dist/engine/boot-validator/definition-ownership-from-rules.js +27 -0
  24. package/dist/engine/boot-validator/definition-probes-rules.d.ts +47 -0
  25. package/dist/engine/boot-validator/definition-probes-rules.js +47 -0
  26. package/dist/engine/boot-validator/definition-role-assignment-rules.d.ts +27 -0
  27. package/dist/engine/boot-validator/definition-role-assignment-rules.js +27 -0
  28. package/dist/engine/boot-validator/definition-ui-extensions-rules.d.ts +197 -0
  29. package/dist/engine/boot-validator/definition-ui-extensions-rules.js +197 -0
  30. package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +32 -0
  31. package/dist/engine/boot-validator/definition-webhook-events-rules.js +32 -0
  32. package/dist/engine/define-feature.js +26 -9
  33. package/dist/engine/define-handler.js +8 -4
  34. package/dist/engine/definition-violations.d.ts +14 -0
  35. package/dist/engine/definition-violations.js +71 -0
  36. package/dist/engine/entity-handlers.js +39 -13
  37. package/dist/engine/event-def.js +32 -12
  38. package/dist/engine/factories.js +16 -5
  39. package/dist/engine/feature-config-events-jobs.js +63 -27
  40. package/dist/engine/feature-entity-handlers.js +15 -6
  41. package/dist/engine/feature-probes.js +29 -9
  42. package/dist/engine/feature-ui-extensions.js +178 -92
  43. package/dist/engine/object-form.js +8 -2
  44. package/dist/engine/ownership.js +17 -5
  45. package/dist/engine/role-assignment.js +17 -5
  46. package/dist/engine/webhook-events.js +20 -6
  47. package/dist/files/file-routes.js +1 -1
  48. package/dist/schema-cli/shared.d.ts +11 -0
  49. package/dist/schema-cli/shared.js +37 -3
  50. package/dist/schema-cli/validate-command.js +10 -3
  51. package/package.json +3 -3
  52. package/src/changes.json +12 -0
@@ -1,5 +1,7 @@
1
1
  import { ENTITY_CONVENTION_QUERY_BRAND } from "@cosmicdrift/kumiko-types/handlers";
2
2
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
3
+ import { bootRuleError } from "./boot-validator/boot-rule.js";
4
+ import { DEFINITION_HANDLER_RULES } from "./boot-validator/definition-handlers-rules.js";
3
5
  import { runPipeline } from "./run-pipeline.js";
4
6
  function pickPreTransactionPhases(def) {
5
7
  return {
@@ -42,10 +44,12 @@ export function defineWriteHandler(def,
42
44
  // a name-and-explanation error message instead.
43
45
  const handlerName = def.name;
44
46
  if (hasHandlerAndPerform(def)) {
45
- throw new Error(`defineWriteHandler("${handlerName}"): both \`handler\` and \`perform\` are set. ` +
46
- `Pick one — \`handler\` for the free-form async function, ` +
47
- `\`perform: stepsPipeline(...)\` for the step-pipeline form. ` +
48
- `(See step-vocabulary.md for which form fits.)`);
47
+ throw bootRuleError(DEFINITION_HANDLER_RULES.handlerAndPerformBoth, {
48
+ message: `defineWriteHandler("${handlerName}"): both \`handler\` and \`perform\` are set. ` +
49
+ `Pick one — \`handler\` for the free-form async function, ` +
50
+ `\`perform: stepsPipeline(...)\` for the step-pipeline form. ` +
51
+ `(See step-vocabulary.md for which form fits.)`,
52
+ });
49
53
  }
50
54
  // Conditional spreads (`...(def.access && { access: def.access })`)
51
55
  // mirror the existing convention in entity-handlers.ts /
@@ -0,0 +1,14 @@
1
+ import type { BootViolation } from "./boot-validator/boot-rule.ts";
2
+ export type DefinitionLoadOutcome<T> = {
3
+ readonly loaded: true;
4
+ readonly value: T;
5
+ } | {
6
+ readonly loaded: false;
7
+ readonly thrown: unknown;
8
+ };
9
+ export declare function collectDefinitionViolations<T>(load: () => Promise<T>): Promise<{
10
+ readonly violations: readonly BootViolation[];
11
+ readonly outcome: DefinitionLoadOutcome<T>;
12
+ }>;
13
+ export declare function runDefinitionStep<T>(feature: string, check: string, step: () => T): T | undefined;
14
+ export declare function collectingRegistrar<R extends object>(feature: string, registrar: R): R;
@@ -0,0 +1,71 @@
1
+ import { isRuntimeCrash, violationsOf } from "./boot-validator/boot-report.js";
2
+ // Collect mode is on globalThis (plain records, no Error instances) so that a schema.ts
3
+ // resolving a second installed framework copy still reports into the same collector.
4
+ const COLLECTOR_KEY = Symbol.for("kumiko.boot.definitionViolationCollector");
5
+ function activeCollector() {
6
+ const existing = Reflect.get(globalThis, COLLECTOR_KEY);
7
+ return Array.isArray(existing) ? existing : undefined;
8
+ }
9
+ export async function collectDefinitionViolations(load) {
10
+ const previous = activeCollector();
11
+ const violations = [];
12
+ Reflect.set(globalThis, COLLECTOR_KEY, violations);
13
+ try {
14
+ const value = await load();
15
+ return { violations, outcome: { loaded: true, value } };
16
+ }
17
+ catch (thrown) {
18
+ return { violations, outcome: { loaded: false, thrown } };
19
+ }
20
+ finally {
21
+ Reflect.set(globalThis, COLLECTOR_KEY, previous);
22
+ }
23
+ }
24
+ // Outside collect mode the step runs untouched and throws on the first problem. In collect
25
+ // mode a failing step is recorded and yields undefined, so the caller carries on to the next one.
26
+ export function runDefinitionStep(feature, check, step) {
27
+ const collector = activeCollector();
28
+ if (collector === undefined)
29
+ return step();
30
+ try {
31
+ return step();
32
+ }
33
+ catch (thrown) {
34
+ if (isRuntimeCrash(thrown)) {
35
+ // Follow-up of an earlier violation (a failed step returned undefined); without one it is a real bug.
36
+ if (collector.length === 0)
37
+ throw thrown;
38
+ return undefined;
39
+ }
40
+ if (thrown instanceof Error)
41
+ collector.push(...violationsOf(thrown, check, feature));
42
+ return undefined;
43
+ }
44
+ }
45
+ function isCallable(value) {
46
+ return typeof value === "function";
47
+ }
48
+ function collectingFunction(feature, label, target) {
49
+ return new Proxy(target, {
50
+ apply: (fn, thisArg, args) => runDefinitionStep(feature, label, () => Reflect.apply(fn, thisArg, args)),
51
+ get(fn, prop, receiver) {
52
+ const value = Reflect.get(fn, prop, receiver);
53
+ if (!isCallable(value) || !Object.hasOwn(fn, prop))
54
+ return value;
55
+ return collectingFunction(feature, `${label}.${String(prop)}`, value);
56
+ },
57
+ });
58
+ }
59
+ // Wrapped only while collecting, so every other path keeps the plain registrar object.
60
+ export function collectingRegistrar(feature, registrar) {
61
+ if (activeCollector() === undefined)
62
+ return registrar;
63
+ return new Proxy(registrar, {
64
+ get(target, prop, receiver) {
65
+ const value = Reflect.get(target, prop, receiver);
66
+ if (!isCallable(value))
67
+ return value;
68
+ return collectingFunction(feature, `r.${String(prop)}`, value);
69
+ },
70
+ });
71
+ }
@@ -10,6 +10,8 @@ import { acknowledgeConventionCrossTenant, reportConventionCrossTenantUse, } fro
10
10
  import { InternalError } from "../errors/index.js";
11
11
  import { isSystemIdentity } from "../pipeline/system-identity-switch.js";
12
12
  import { assertUnreachable } from "../utils/index.js";
13
+ import { bootRuleError } from "./boot-validator/boot-rule.js";
14
+ import { DEFINITION_HANDLER_RULES } from "./boot-validator/definition-handlers-rules.js";
13
15
  import { PAGED_QUERY_HANDLER_BRAND } from "./define-handler.js";
14
16
  import { entityListRuntime, parentVisibilityFor } from "./entity-list-runtime-options.js";
15
17
  import { assertReason } from "./escape-hatch-reason.js";
@@ -71,7 +73,9 @@ function resolveCrossTenantReason(name, options, kind) {
71
73
  }
72
74
  export function assertEscapeHatchAccessIsSystemAdminOnly(name, kind, access) {
73
75
  if (!isSystemAdminOnly(access)) {
74
- throw new Error(`"${name}": a ${kind} handler with escapeHatch reaches across every tenant, so its access must be SystemAdmin-only ({ roles: ["${SYSTEM_ADMIN_ROLE}"] }); got ${JSON.stringify(access)}.`);
76
+ throw bootRuleError(DEFINITION_HANDLER_RULES.escapeHatchAccessNotSystemAdmin, {
77
+ message: `"${name}": a ${kind} handler with escapeHatch reaches across every tenant, so its access must be SystemAdmin-only ({ roles: ["${SYSTEM_ADMIN_ROLE}"] }); got ${JSON.stringify(access)}.`,
78
+ });
75
79
  }
76
80
  }
77
81
  // Upper bound on entity-list `limit`: unbounded/fractional values ran
@@ -120,16 +124,22 @@ export const entityListSchema = z.object({
120
124
  function parseHandlerName(name, validVerbs) {
121
125
  const colonIdx = name.indexOf(":");
122
126
  if (colonIdx < 0) {
123
- throw new Error(`Handler name "${name}" must use the "<entity>:<verb>" pattern (e.g. "note:create").`);
127
+ throw bootRuleError(DEFINITION_HANDLER_RULES.nameWithoutColon, {
128
+ message: `Handler name "${name}" must use the "<entity>:<verb>" pattern (e.g. "note:create").`,
129
+ });
124
130
  }
125
131
  const entityName = name.slice(0, colonIdx);
126
132
  const verbCandidate = name.slice(colonIdx + 1);
127
133
  if (!entityName) {
128
- throw new Error(`Handler name "${name}" is missing the entity part before the colon.`);
134
+ throw bootRuleError(DEFINITION_HANDLER_RULES.nameMissingEntity, {
135
+ message: `Handler name "${name}" is missing the entity part before the colon.`,
136
+ });
129
137
  }
130
138
  const verbs = validVerbs; // @cast-boundary engine-bridge
131
139
  if (!verbs.includes(verbCandidate)) {
132
- throw new Error(`Unknown verb "${verbCandidate}" in handler name "${name}". Standard verbs: ${validVerbs.join("/")}. For custom verbs use the explicit r.writeHandler / r.queryHandler form.`);
140
+ throw bootRuleError(DEFINITION_HANDLER_RULES.verbUnknown, {
141
+ message: `Unknown verb "${verbCandidate}" in handler name "${name}". Standard verbs: ${validVerbs.join("/")}. For custom verbs use the explicit r.writeHandler / r.queryHandler form.`,
142
+ });
133
143
  }
134
144
  return { entityName, verb: verbCandidate }; // @cast-boundary engine-bridge
135
145
  }
@@ -167,33 +177,45 @@ function resolveEntityWriteAgentHints(name, verb, entity, agent, excludedFields)
167
177
  const reason = isIrreversibleDelete
168
178
  ? "delete on an entity without softDelete is irreversible"
169
179
  : `it writes field(s) ${instructionFields.join(", ")} flagged readAsInstruction: true`;
170
- throw new Error(`"${name}": ${reason} — agent.risk must be "high" (got "${agent.risk}").`);
180
+ throw bootRuleError(DEFINITION_HANDLER_RULES.agentRiskNotHigh, {
181
+ message: `"${name}": ${reason} — agent.risk must be "high" (got "${agent.risk}").`,
182
+ });
171
183
  }
172
184
  return { ...agent, risk: "high" };
173
185
  }
174
186
  function assertExcludableFields(name, verb, entity, excludedFields) {
175
187
  if (excludedFields.length > 0 && verb !== "create" && verb !== "update") {
176
- throw new Error(`"${name}": excludeFields only applies to create and update handlers.`);
188
+ throw bootRuleError(DEFINITION_HANDLER_RULES.excludeFieldsVerbUnsupported, {
189
+ message: `"${name}": excludeFields only applies to create and update handlers.`,
190
+ });
177
191
  }
178
192
  for (const fieldName of excludedFields) {
179
193
  const field = entity.fields[fieldName];
180
194
  if (!field) {
181
- throw new Error(`"${name}": excludeFields names unknown field "${fieldName}".`);
195
+ throw bootRuleError(DEFINITION_HANDLER_RULES.excludeFieldsUnknownField, {
196
+ message: `"${name}": excludeFields names unknown field "${fieldName}".`,
197
+ });
182
198
  }
183
199
  if (isInTotalsMatchPair(entity, fieldName)) {
184
- throw new Error(`"${name}": excludeFields cannot name "${fieldName}" — it is part of a totalsMatch pair, which must be written together.`);
200
+ throw bootRuleError(DEFINITION_HANDLER_RULES.excludeFieldsTotalsPair, {
201
+ message: `"${name}": excludeFields cannot name "${fieldName}" — it is part of a totalsMatch pair, which must be written together.`,
202
+ });
185
203
  }
186
204
  const isRequired = "required" in field && field.required === true;
187
205
  const hasDefault = "default" in field && field.default !== undefined;
188
206
  if (verb === "create" && isRequired && !hasDefault) {
189
- throw new Error(`"${name}": excludeFields cannot name "${fieldName}" — it is required without a default, so no row could ever be created.`);
207
+ throw bootRuleError(DEFINITION_HANDLER_RULES.excludeFieldsRequiredWithoutDefault, {
208
+ message: `"${name}": excludeFields cannot name "${fieldName}" — it is required without a default, so no row could ever be created.`,
209
+ });
190
210
  }
191
211
  }
192
212
  }
193
213
  export function defineEntityWriteHandler(name, entity, options) {
194
214
  const { entityName, verb } = parseHandlerName(name, WRITE_VERBS);
195
215
  if (verb === "restore" && !entity.softDelete) {
196
- throw new Error(`"${name}": restore is only valid for entities declared with softDelete: true.`);
216
+ throw bootRuleError(DEFINITION_HANDLER_RULES.restoreWithoutSoftDelete, {
217
+ message: `"${name}": restore is only valid for entities declared with softDelete: true.`,
218
+ });
197
219
  }
198
220
  const excludedFields = options.excludeFields ?? [];
199
221
  assertExcludableFields(name, verb, entity, excludedFields);
@@ -565,7 +587,9 @@ function defaultCrudVerbs(entity) {
565
587
  export function registerCrudHandlers(r, entityName, entity, options) {
566
588
  const verbs = { ...defaultCrudVerbs(entity), ...options?.verbs };
567
589
  if (verbs.restore && entity.softDelete !== true) {
568
- throw new Error(`restore requested but entity "${entityName}" has no softDelete: true`);
590
+ throw bootRuleError(DEFINITION_HANDLER_RULES.restoreWithoutSoftDelete, {
591
+ message: `restore requested but entity "${entityName}" has no softDelete: true`,
592
+ });
569
593
  }
570
594
  if (options?.registerEntity !== false) {
571
595
  r.entity({ name: entityName, ...entity });
@@ -574,8 +598,10 @@ export function registerCrudHandlers(r, entityName, entity, options) {
574
598
  const readOpts = options?.read;
575
599
  const requireAccess = (verb, access) => {
576
600
  if (!access) {
577
- throw new Error(`r.crud("${entityName}", …): no access rule resolved for verb "${verb}". ` +
578
- `Set write.access/read.access in r.crud's options, or verbAccess.${verb}.`);
601
+ throw bootRuleError(DEFINITION_HANDLER_RULES.crudAccessUnresolved, {
602
+ message: `r.crud("${entityName}", …): no access rule resolved for verb "${verb}". ` +
603
+ `Set write.access/read.access in r.crud's options, or verbAccess.${verb}.`,
604
+ });
579
605
  }
580
606
  return access;
581
607
  };
@@ -1,5 +1,7 @@
1
1
  import { normalizeEventPiiSubject } from "@cosmicdrift/kumiko-types/handlers";
2
2
  import { ZodObject } from "zod";
3
+ import { bootRuleError } from "./boot-validator/boot-rule.js";
4
+ import { DEFINITION_EVENT_RULES } from "./boot-validator/definition-events-rules.js";
3
5
  import { qn, toKebab } from "./qualified-name.js";
4
6
  // A payload field that still holds null/undefined after parsing — the case
5
7
  // where an event-PII owner field yields no subject at append time.
@@ -35,13 +37,17 @@ function neverYieldsString(field) {
35
37
  function assertOwnerFieldYieldsPresentString(args) {
36
38
  const { featureName, eventName, field, ownerField, owner } = args;
37
39
  if (neverYieldsString(owner)) {
38
- throw new Error(`[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" is owned by "${ownerField}", whose payload schema is not a string — the subject id must be a non-empty string, so every append would fail. ` +
39
- `Use a string owner field, or declare whenAbsent ("tenant" | "self" | "plaintext").`);
40
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiOwnerNotString, {
41
+ message: `[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" is owned by "${ownerField}", whose payload schema is not a string — the subject id must be a non-empty string, so every append would fail. ` +
42
+ `Use a string owner field, or declare whenAbsent ("tenant" | "self" | "plaintext").`,
43
+ });
40
44
  }
41
45
  if (isAbsentable(owner)) {
42
- throw new Error(`[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" is owned by "${ownerField}", which the payload schema allows to be null/undefined. ` +
43
- `Declare what happens then: { personal: { of: "${ownerField}", whenAbsent: "tenant" } } encrypts under the envelope tenant key, ` +
44
- `whenAbsent: "self" under the event's own record key, whenAbsent: "plaintext" acknowledges that the value ships unencrypted and cannot be crypto-shredded (fw#2776).`);
46
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiOwnerNullable, {
47
+ message: `[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" is owned by "${ownerField}", which the payload schema allows to be null/undefined. ` +
48
+ `Declare what happens then: { personal: { of: "${ownerField}", whenAbsent: "tenant" } } encrypts under the envelope tenant key, ` +
49
+ `whenAbsent: "self" under the event's own record key, whenAbsent: "plaintext" acknowledges that the value ships unencrypted and cannot be crypto-shredded (fw#2776).`,
50
+ });
45
51
  }
46
52
  }
47
53
  // piiFields misconfiguration is a boot-time error, not a silent
@@ -56,19 +62,27 @@ function validateEventPiiFields(featureName, eventName, schema, piiFields) {
56
62
  // so there is no owner-field existence or self-reference check for them.
57
63
  if (normalized.kind !== "user") {
58
64
  if (shape && !(field in shape)) {
59
- throw new Error(`[Feature ${featureName}] defineEvent("${eventName}"): piiFields references "${field}" which is not a field of the payload schema.`);
65
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiFieldNotInSchema, {
66
+ message: `[Feature ${featureName}] defineEvent("${eventName}"): piiFields references "${field}" which is not a field of the payload schema.`,
67
+ });
60
68
  }
61
69
  continue;
62
70
  }
63
71
  if (field === normalized.ownerField) {
64
- throw new Error(`[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" cannot use itself as the owner field — the subject id is a plaintext pseudonymous fk, the pii field is the value it owns.`);
72
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiSelfOwner, {
73
+ message: `[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" cannot use itself as the owner field — the subject id is a plaintext pseudonymous fk, the pii field is the value it owns.`,
74
+ });
65
75
  }
66
76
  if (normalized.ownerField === "id") {
67
- throw new Error(`[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" uses owner field "id" — on entities \`of: "id"\` means record-owned, but on events it would encrypt under a phantom user key that a forget never reaches. Use \`personal: "self"\` for a record-owned event field.`);
77
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiOwnerIsId, {
78
+ message: `[Feature ${featureName}] defineEvent("${eventName}"): piiFields."${field}" uses owner field "id" — on entities \`of: "id"\` means record-owned, but on events it would encrypt under a phantom user key that a forget never reaches. Use \`personal: "self"\` for a record-owned event field.`,
79
+ });
68
80
  }
69
81
  for (const required of [field, normalized.ownerField]) {
70
82
  if (shape && !(required in shape)) {
71
- throw new Error(`[Feature ${featureName}] defineEvent("${eventName}"): piiFields references "${required}" which is not a field of the payload schema.`);
83
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiFieldNotInSchema, {
84
+ message: `[Feature ${featureName}] defineEvent("${eventName}"): piiFields references "${required}" which is not a field of the payload schema.`,
85
+ });
72
86
  }
73
87
  }
74
88
  const owner = shape?.[normalized.ownerField];
@@ -93,7 +107,9 @@ export function createEventDef(options) {
93
107
  // Fail-closed PII stance gate — runs before anything else so
94
108
  // an untyped JS consumer (no compiler to stop it) still can't register
95
109
  // an event without declaring whether its payload carries personal data.
96
- const missingStanceError = () => new Error(`[Feature ${feature}] defineEvent("${eventName}") must declare an explicit PII stance. Pass { piiFields: { <payloadField>: { personal: { of: "<userIdField>" } } } } for payload fields owned by a user (or { personal: "tenant" } / { personal: "self" } for tenant- or record-scoped subjects), or { piiFields: "none" } when the payload holds none.`);
110
+ const missingStanceError = () => bootRuleError(DEFINITION_EVENT_RULES.piiStanceMissing, {
111
+ message: `[Feature ${feature}] defineEvent("${eventName}") must declare an explicit PII stance. Pass { piiFields: { <payloadField>: { personal: { of: "<userIdField>" } } } } for payload fields owned by a user (or { personal: "tenant" } / { personal: "self" } for tenant- or record-scoped subjects), or { piiFields: "none" } when the payload holds none.`,
112
+ });
97
113
  if (options.piiFields === undefined)
98
114
  throw missingStanceError();
99
115
  const piiFields = options.piiFields;
@@ -106,13 +122,17 @@ export function createEventDef(options) {
106
122
  throw missingStanceError();
107
123
  }
108
124
  if (piiFields !== "none" && Object.keys(piiFields).length === 0) {
109
- throw new Error(`[Feature ${feature}] defineEvent("${eventName}"): piiFields: {} is not a stance — use piiFields: "none" to declare the payload holds no personal data.`);
125
+ throw bootRuleError(DEFINITION_EVENT_RULES.piiStanceEmpty, {
126
+ message: `[Feature ${feature}] defineEvent("${eventName}"): piiFields: {} is not a stance — use piiFields: "none" to declare the payload holds no personal data.`,
127
+ });
110
128
  }
111
129
  if (piiFields !== "none")
112
130
  validateEventPiiFields(feature, eventName, schema, piiFields);
113
131
  const version = options.version ?? 1;
114
132
  if (!Number.isInteger(version) || version < 1) {
115
- throw new Error(`[Feature ${feature}] defineEvent("${eventName}"): version must be a positive integer, got ${String(version)}`);
133
+ throw bootRuleError(DEFINITION_EVENT_RULES.versionInvalid, {
134
+ message: `[Feature ${feature}] defineEvent("${eventName}"): version must be a positive integer, got ${String(version)}`,
135
+ });
116
136
  }
117
137
  // @cast-boundary engine-bridge — runtime-string mirrors the
118
138
  // template-literal-type via QualifiedEventName + toKebab. Both
@@ -1,4 +1,7 @@
1
1
  import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
2
+ import { bootRuleError } from "./boot-validator/boot-rule.js";
3
+ import { DEFINITION_FIELD_FACTORY_RULES } from "./boot-validator/definition-field-factories-rules.js";
4
+ import { PII_RULES } from "./boot-validator/pii-retention-rules.js";
2
5
  import { isUserEntityReference } from "./user-entity-reference.js";
3
6
  // `personal: { of: "id" }` means the row itself is the subject, not a
4
7
  // referenced user — resolves to `recordOwned` instead of `userOwned`.
@@ -16,7 +19,9 @@ function resolvePersonalFlags(personal, reason) {
16
19
  return {};
17
20
  if (personal.of === RECORD_OWNER_FIELD) {
18
21
  if (personal.whenAbsent !== undefined) {
19
- throw new Error(`personal: { of: "${RECORD_OWNER_FIELD}", whenAbsent } is meaningless: a row always has an id, so there is never an absent owner (fw#3654)`);
22
+ throw bootRuleError(DEFINITION_FIELD_FACTORY_RULES.personalRecordOwnerWhenAbsent, {
23
+ message: `personal: { of: "${RECORD_OWNER_FIELD}", whenAbsent } is meaningless: a row always has an id, so there is never an absent owner (fw#3654)`,
24
+ });
20
25
  }
21
26
  return { recordOwned: true };
22
27
  }
@@ -69,7 +74,9 @@ function textFieldStanceHint(factoryName) {
69
74
  `{ personal: false, reason: "<why this is not personal data>" }`);
70
75
  }
71
76
  function missingTextFieldStanceError(factoryName) {
72
- return new Error(`${factoryName}(...) must declare an explicit personal-data stance — a text field must state whose data it holds and (unless it isn't personal data) how findable it needs to stay (kumiko-framework#2921). Pass one of: ${textFieldStanceHint(factoryName)}. Run \`kumiko-guards guards --guard="Text-Field Personal-Stance Guard"\` to find remaining call sites.`);
77
+ return bootRuleError(PII_RULES.textWithoutPersonalStance, {
78
+ message: `${factoryName}(...) must declare an explicit personal-data stance — a text field must state whose data it holds and (unless it isn't personal data) how findable it needs to stay (kumiko-framework#2921). Pass one of: ${textFieldStanceHint(factoryName)}. Run \`kumiko-guards guards --guard="Text-Field Personal-Stance Guard"\` to find remaining call sites.`,
79
+ });
73
80
  }
74
81
  function isNonEmptyString(value) {
75
82
  return typeof value === "string" && value.trim().length > 0;
@@ -177,7 +184,9 @@ export function createSelectField(opts) {
177
184
  export function createReferenceField(opts) {
178
185
  const targetsUser = isUserEntityReference(opts.entity);
179
186
  if (targetsUser && opts.personal === false) {
180
- throw new Error(`createReferenceField({ entity: "${opts.entity}" }): personal: false is not allowed for a reference to the user entity — a user id is personal data. Drop the annotation or use { personal: "ref" }.`);
187
+ throw bootRuleError(DEFINITION_FIELD_FACTORY_RULES.userReferenceNotPersonal, {
188
+ message: `createReferenceField({ entity: "${opts.entity}" }): personal: false is not allowed for a reference to the user entity — a user id is personal data. Drop the annotation or use { personal: "ref" }.`,
189
+ });
181
190
  }
182
191
  const withUserDefault = targetsUser && opts.personal === undefined ? { ...opts, personal: "ref" } : opts;
183
192
  return {
@@ -254,8 +263,10 @@ export function createDecimalField(config) {
254
263
  precision < 1 ||
255
264
  scale < 0 ||
256
265
  scale > precision) {
257
- throw new Error(`createDecimalField: precision/scale must be integers with precision ≥ 1 and ` +
258
- `0 ≤ scale ≤ precision, got precision=${precision}, scale=${scale}`);
266
+ throw bootRuleError(DEFINITION_FIELD_FACTORY_RULES.decimalPrecisionScaleInvalid, {
267
+ message: `createDecimalField: precision/scale must be integers with precision ≥ 1 and ` +
268
+ `0 ≤ scale ≤ precision, got precision=${precision}, scale=${scale}`,
269
+ });
259
270
  }
260
271
  return {
261
272
  type: "decimal",
@@ -1,6 +1,8 @@
1
1
  import { escapeHatchGrantsProblem } from "@cosmicdrift/kumiko-types/handlers";
2
2
  import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
3
3
  import { isValidIanaTimeZone } from "../time/iana.js";
4
+ import { bootRuleError } from "./boot-validator/boot-rule.js";
5
+ import { DEFINITION_CONFIG_EVENTS_JOBS_RULES } from "./boot-validator/definition-config-events-jobs-rules.js";
4
6
  import { reasonProblem } from "./escape-hatch-reason.js";
5
7
  import { createEventDef } from "./event-def.js";
6
8
  import { resolveName } from "./handler-helpers.js";
@@ -8,19 +10,25 @@ import { requireArgument, splitNamedDefinition, unwrapArrayForm } from "./object
8
10
  import { QnTypes, qn, toKebab } from "./qualified-name.js";
9
11
  function assertScheduleTrigger(featureName, jobName, trigger) {
10
12
  if ("maintenance" in trigger && trigger.maintenance !== true) {
11
- throw new Error(`[Feature ${featureName}] r.job("${jobName}") declares trigger { maintenance: ${JSON.stringify(trigger.maintenance)} } — ` +
12
- "the only valid value is true; the run time comes from KUMIKO_MAINTENANCE_WINDOW.");
13
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.jobMaintenanceTriggerInvalid, {
14
+ message: `[Feature ${featureName}] r.job("${jobName}") declares trigger { maintenance: ${JSON.stringify(trigger.maintenance)} } — ` +
15
+ "the only valid value is true; the run time comes from KUMIKO_MAINTENANCE_WINDOW.",
16
+ });
13
17
  }
14
18
  if ("wakesSleepingApp" in trigger && trigger.wakesSleepingApp !== undefined) {
15
19
  const isScheduled = "cron" in trigger || "maintenance" in trigger;
16
20
  if (!isScheduled || trigger.wakesSleepingApp !== false) {
17
- throw new Error(`[Feature ${featureName}] r.job("${jobName}") declares trigger { wakesSleepingApp: ${JSON.stringify(trigger.wakesSleepingApp)} } — ` +
18
- "only false is valid, and only on a cron or maintenance trigger; leave it out to wake the app.");
21
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.jobWakesSleepingAppInvalid, {
22
+ message: `[Feature ${featureName}] r.job("${jobName}") declares trigger { wakesSleepingApp: ${JSON.stringify(trigger.wakesSleepingApp)} } — ` +
23
+ "only false is valid, and only on a cron or maintenance trigger; leave it out to wake the app.",
24
+ });
19
25
  }
20
26
  }
21
27
  if ("cron" in trigger && trigger.tz !== undefined && !isValidIanaTimeZone(trigger.tz)) {
22
- throw new Error(`[Feature ${featureName}] r.job("${jobName}") declares trigger { cron, tz: ${JSON.stringify(trigger.tz)} } — ` +
23
- 'tz must be an IANA time zone name such as "Europe/Berlin".');
28
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.jobCronTimezoneInvalid, {
29
+ message: `[Feature ${featureName}] r.job("${jobName}") declares trigger { cron, tz: ${JSON.stringify(trigger.tz)} } — ` +
30
+ 'tz must be an IANA time zone name such as "Europe/Berlin".',
31
+ });
24
32
  }
25
33
  }
26
34
  // Builds config/secrets/claims/events/jobs/notifications registrar methods.
@@ -31,7 +39,9 @@ export function buildConfigEventsJobsMethods(state, name) {
31
39
  // to optional to satisfy both call shapes.
32
40
  const definition = typeof arg1 === "string" && arg2 ? { keys: { [arg1]: arg2 } } : arg1;
33
41
  if (typeof definition === "string") {
34
- throw new Error("config(): single-key form requires a definition as the second argument");
42
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.configSingleKeyNeedsDefinition, {
43
+ message: "config(): single-key form requires a definition as the second argument",
44
+ });
35
45
  }
36
46
  // Qualify eagerly (same as defineEvent) so the handle name matches what
37
47
  // the registry stores — lazy qualification would break compile-time
@@ -69,16 +79,22 @@ export function buildConfigEventsJobsMethods(state, name) {
69
79
  // r.eventMigration() call (folded into defineEvent).
70
80
  function registerEventMigration(eventName, fromVersion, toVersion, transform) {
71
81
  if (toVersion !== fromVersion + 1) {
72
- throw new Error(`[Feature ${name}] defineEvent("${eventName}") migrations: only single-step migrations are allowed — toVersion must be fromVersion + 1 (got ${fromVersion} -> ${toVersion}). ` +
73
- `Chain larger jumps by declaring each step separately.`);
82
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.eventMigrationStepSize, {
83
+ message: `[Feature ${name}] defineEvent("${eventName}") migrations: only single-step migrations are allowed — toVersion must be fromVersion + 1 (got ${fromVersion} -> ${toVersion}). ` +
84
+ `Chain larger jumps by declaring each step separately.`,
85
+ });
74
86
  }
75
87
  if (!Number.isInteger(fromVersion) || fromVersion < 1) {
76
- throw new Error(`[Feature ${name}] defineEvent("${eventName}") migrations: fromVersion must be >= 1, got ${String(fromVersion)}`);
88
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.eventMigrationFromVersionInvalid, {
89
+ message: `[Feature ${name}] defineEvent("${eventName}") migrations: fromVersion must be >= 1, got ${String(fromVersion)}`,
90
+ });
77
91
  }
78
92
  const qualified = qn(toKebab(name), "event", toKebab(eventName));
79
93
  const list = state.eventMigrations[eventName] ?? [];
80
94
  if (list.some((m) => m.fromVersion === fromVersion)) {
81
- throw new Error(`[Feature ${name}] defineEvent("${eventName}") migrations: a migration from v${fromVersion} is already declared. Each step may only be declared once.`);
95
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.eventMigrationDuplicateStep, {
96
+ message: `[Feature ${name}] defineEvent("${eventName}") migrations: a migration from v${fromVersion} is already declared. Each step may only be declared once.`,
97
+ });
82
98
  }
83
99
  const transformFn = typeof transform === "function" ? transform : compileEventMigration(transform);
84
100
  list.push({ eventName: qualified, fromVersion, toVersion, transform: transformFn });
@@ -101,11 +117,15 @@ export function buildConfigEventsJobsMethods(state, name) {
101
117
  ? reasonProblem(jobOptions.escapeHatch.reason)
102
118
  : undefined;
103
119
  if (jobReasonProblem !== undefined) {
104
- throw new Error(`[Feature ${name}] r.job("${jobName}") declares an invalid escapeHatch — ${jobReasonProblem}`);
120
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.jobEscapeHatchInvalid, {
121
+ message: `[Feature ${name}] r.job("${jobName}") declares an invalid escapeHatch — ${jobReasonProblem}`,
122
+ });
105
123
  }
106
124
  const jobGrantsProblem = jobOptions.escapeHatch && escapeHatchGrantsProblem(jobOptions.escapeHatch);
107
125
  if (jobGrantsProblem) {
108
- throw new Error(`[Feature ${name}] r.job("${jobName}") declares an invalid escapeHatch — ${jobGrantsProblem}`);
126
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.jobEscapeHatchInvalid, {
127
+ message: `[Feature ${name}] r.job("${jobName}") declares an invalid escapeHatch — ${jobGrantsProblem}`,
128
+ });
109
129
  }
110
130
  assertScheduleTrigger(name, jobName, jobOptions.trigger);
111
131
  // Resolve NameOrRef(s) in trigger.on. For the multi-trigger form, arrays
@@ -187,14 +207,18 @@ export function buildConfigEventsJobsMethods(state, name) {
187
207
  ? [shortNameOrDefinition, requireArgument(options, name, "metric", "options")]
188
208
  : splitNamedDefinition(shortNameOrDefinition);
189
209
  if (state.metrics[shortName]) {
190
- throw new Error(`[Feature ${name}] Metric "${shortName}" already registered. ` +
191
- `Metric names must be unique per feature.`);
210
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.metricDuplicate, {
211
+ message: `[Feature ${name}] Metric "${shortName}" already registered. ` +
212
+ `Metric names must be unique per feature.`,
213
+ });
192
214
  }
193
215
  state.metrics[shortName] = { shortName, ...metricOptions };
194
216
  },
195
217
  envSchema(schema) {
196
218
  if (state.envSchema !== undefined) {
197
- throw new Error(`[Feature ${name}] r.envSchema() called twice — declare one composed Zod-object per feature.`);
219
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.envSchemaTwice, {
220
+ message: `[Feature ${name}] r.envSchema() called twice — declare one composed Zod-object per feature.`,
221
+ });
198
222
  }
199
223
  state.envSchema = schema;
200
224
  },
@@ -203,12 +227,16 @@ export function buildConfigEventsJobsMethods(state, name) {
203
227
  ? [shortNameOrDefinition, requireArgument(options, name, "secret", "options")]
204
228
  : splitNamedDefinition(shortNameOrDefinition);
205
229
  if (state.secretKeys[shortName]) {
206
- throw new Error(`[Feature ${name}] Secret "${shortName}" already registered. ` +
207
- `Secret key names must be unique per feature.`);
230
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.secretDuplicate, {
231
+ message: `[Feature ${name}] Secret "${shortName}" already registered. ` +
232
+ `Secret key names must be unique per feature.`,
233
+ });
208
234
  }
209
235
  if (secretOptions.writeRoles !== undefined && secretOptions.writeRoles.length === 0) {
210
- throw new Error(`[Feature ${name}] Secret "${shortName}" declares an empty writeRoles list, ` +
211
- `which nobody could ever satisfy. Omit writeRoles to fall back to the secrets handler access.`);
236
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.secretWriteRolesEmpty, {
237
+ message: `[Feature ${name}] Secret "${shortName}" declares an empty writeRoles list, ` +
238
+ `which nobody could ever satisfy. Omit writeRoles to fall back to the secrets handler access.`,
239
+ });
212
240
  }
213
241
  // Qualified name follows the framework's "<feature>:<type>:<name>"
214
242
  // QN convention — same pattern config / jobs / events use. toKebab
@@ -228,12 +256,16 @@ export function buildConfigEventsJobsMethods(state, name) {
228
256
  ? [shortNameOrDefinition, requireArgument(options, name, "secretNamespace", "options")]
229
257
  : splitNamedDefinition(shortNameOrDefinition);
230
258
  if (state.secretNamespaces[shortName]) {
231
- throw new Error(`[Feature ${name}] Secret namespace "${shortName}" already registered. ` +
232
- `Secret namespace names must be unique per feature.`);
259
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.secretNamespaceDuplicate, {
260
+ message: `[Feature ${name}] Secret namespace "${shortName}" already registered. ` +
261
+ `Secret namespace names must be unique per feature.`,
262
+ });
233
263
  }
234
264
  if (namespaceOptions.writeRoles !== undefined && namespaceOptions.writeRoles.length === 0) {
235
- throw new Error(`[Feature ${name}] Secret namespace "${shortName}" declares an empty writeRoles list, ` +
236
- `which nobody could ever satisfy. Omit writeRoles to fall back to the secrets handler access.`);
265
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.secretWriteRolesEmpty, {
266
+ message: `[Feature ${name}] Secret namespace "${shortName}" declares an empty writeRoles list, ` +
267
+ `which nobody could ever satisfy. Omit writeRoles to fall back to the secrets handler access.`,
268
+ });
237
269
  }
238
270
  const qualifiedPrefix = `${toKebab(name)}:${toKebab(shortName)}.`;
239
271
  state.secretNamespaces[shortName] = { shortName, qualifiedPrefix, ...namespaceOptions };
@@ -247,8 +279,10 @@ export function buildConfigEventsJobsMethods(state, name) {
247
279
  ? requireArgument(options, name, "claimKey", "options").type
248
280
  : shortNameOrDefinition.type;
249
281
  if (state.claimKeys[shortName]) {
250
- throw new Error(`[Feature ${name}] Claim key "${shortName}" already declared. ` +
251
- "Claim short-names must be unique per feature.");
282
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.claimKeyDuplicate, {
283
+ message: `[Feature ${name}] Claim key "${shortName}" already declared. ` +
284
+ "Claim short-names must be unique per feature.",
285
+ });
252
286
  }
253
287
  // Claim keys are NOT full QNs — the JWT shape is 2-segment
254
288
  // "<featureName>:<shortName>" (same as Translation keys), not
@@ -280,7 +314,9 @@ function compileEventMigration(spec) {
280
314
  for (const [from, to] of Object.entries(spec.rename ?? {})) {
281
315
  const existing = renameTargets.get(to);
282
316
  if (existing !== undefined) {
283
- throw new Error(`Declarative event migration: rename collision — both "${existing}" and "${from}" rename to "${to}". Only one source may map to a given target.`);
317
+ throw bootRuleError(DEFINITION_CONFIG_EVENTS_JOBS_RULES.eventMigrationRenameCollision, {
318
+ message: `Declarative event migration: rename collision — both "${existing}" and "${from}" rename to "${to}". Only one source may map to a given target.`,
319
+ });
284
320
  }
285
321
  renameTargets.set(to, from);
286
322
  }
@@ -1,5 +1,8 @@
1
1
  import { ENTITY_CONVENTION_QUERY_BRAND } from "@cosmicdrift/kumiko-types/handlers";
2
2
  import { toTableName } from "../db/table-builder.js";
3
+ import { bootRuleError } from "./boot-validator/boot-rule.js";
4
+ import { DEFINITION_HANDLER_RULES } from "./boot-validator/definition-handlers-rules.js";
5
+ import { HANDLER_ACCESS_RULES } from "./boot-validator/entity-handler-access-rules.js";
3
6
  import { isEntityConventionQueryHandler, isPagedQueryHandler, PAGED_QUERY_HANDLER_BRAND, } from "./define-handler.js";
4
7
  import { assertEscapeHatchAccessIsSystemAdminOnly, registerCrudHandlers, } from "./entity-handlers.js";
5
8
  import { agentSlots, transactionPhaseSlots } from "./handler-definition-slots.js";
@@ -19,10 +22,12 @@ function assertHandlerNameFree(state, featureName, kind, handlerName) {
19
22
  verb !== undefined &&
20
23
  state.entities[entityName] !== undefined &&
21
24
  CRUD_REGISTERED_VERBS.has(verb);
22
- throw new Error(`Feature "${featureName}" registers the ${kind} handler "${handlerName}" twice.` +
23
- (crudShaped
24
- ? ` r.crud("${entityName}", ...) already registers that name; use a distinct name or drop the "${verb}" verb from r.crud.`
25
- : " Use a distinct name."));
25
+ throw bootRuleError(DEFINITION_HANDLER_RULES.nameDuplicate, {
26
+ message: `Feature "${featureName}" registers the ${kind} handler "${handlerName}" twice.` +
27
+ (crudShaped
28
+ ? ` r.crud("${entityName}", ...) already registers that name; use a distinct name or drop the "${verb}" verb from r.crud.`
29
+ : " Use a distinct name."),
30
+ });
26
31
  }
27
32
  // Map handler name to entity via colon convention.
28
33
  // "task:create" → entity "task". Bare CRUD verbs (create/update/delete) map
@@ -53,12 +58,16 @@ function tryMapEntity(state, name, handlerName) {
53
58
  // handler that silently falls through to the boot-time default-deny.
54
59
  function assertHandlerHasAccess(featureName, method, handlerName, access) {
55
60
  if (access === undefined || access === null) {
56
- throw new Error(`[Feature ${featureName}] r.${method}({ name: "${handlerName}" }) requires an access rule (access: { roles: [...] } or { openToAll: { reason } })`);
61
+ throw bootRuleError(HANDLER_ACCESS_RULES.accessMissing, {
62
+ message: `[Feature ${featureName}] r.${method}({ name: "${handlerName}" }) requires an access rule (access: { roles: [...] } or { openToAll: { reason } })`,
63
+ });
57
64
  }
58
65
  }
59
66
  function requireInlineHandlerArgs(kind, schema, handler, options) {
60
67
  if (!schema || !handler || !options?.access) {
61
- throw new Error(`${kind} inline form requires schema + handler + options.access`);
68
+ throw bootRuleError(DEFINITION_HANDLER_RULES.inlineFormIncomplete, {
69
+ message: `${kind} inline form requires schema + handler + options.access`,
70
+ });
62
71
  }
63
72
  return { schema, handler, options };
64
73
  }