@happyvertical/smrt-fields 0.60.17 → 0.61.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.
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-fields",
5
- "packageVersion": "0.60.17",
5
+ "packageVersion": "0.61.0",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-fields:FieldPolicyCollection": {
8
8
  "name": "fieldpolicycollection",
@@ -1 +1 @@
1
- {"version":3,"file":"FieldPolicy.d.ts","sourceRoot":"","sources":["../../src/models/FieldPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AA4BlC,OAAO,EAIL,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAE3B,MAAM,aAAa,CAAC;AA6GrB;;;;;;;;;;;;;GAaG;AASH,qBAgBa,WAAY,SAAQ,UAAU;IACzC,6EAA6E;IAE7E,SAAS,EAAE,MAAM,CAAM;IAEvB,wEAAwE;IAExE,SAAS,EAAE,MAAM,CAAM;IAEvB,kEAAkE;IAElE,SAAS,EAAE,oBAAoB,CAAS;IAExC,+EAA+E;IAE/E,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE/B,uDAAuD;IAEvD,MAAM,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE7B;;;;;OAKG;IAEH,QAAQ,EAAE,MAAM,CAAM;IAEtB,mFAAmF;IAMnF,YAAY,EAAE,MAAM,GAAG,IAAI,CAAQ;IAEnC,6EAA6E;IAO7E,UAAU,EAAE,qBAAqB,GAAG,IAAI,CAAQ;IAEhD,yEAAyE;IAMzE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE3B,6EAA6E;IAM7E,KAAK,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE5B;;;;OAIG;IAOH,YAAY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;;;;;;;;;;;;;;;OAqBG;IACH,OAAO,CAAC,8BAA8B;IAatC;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,gCAAgC;IA0ExC,OAAO,CAAC,6BAA6B;IAWrC;;;;;OAKG;YACW,qBAAqB;IAoBnC,OAAO,CAAC,kCAAkC;IAwB1C,OAAO,CAAC,wBAAwB;IAkBhC;;;;;;;;;;;OAWG;YACW,oBAAoB;YAkCpB,mBAAmB;IAQjC;;;;OAIG;YACW,2BAA2B;IAgBzC,OAAO,CAAC,mCAAmC;CAiB5C"}
@@ -0,0 +1,129 @@
1
+ /** Browser-safe field definitions and the canonical layered policy resolver. */
2
+ import type { FieldUIHints } from '@happyvertical/smrt-core';
3
+ import type { ExplainedObjectFieldPolicy, FieldPolicyDelta, FieldPolicyVisibility } from './types.js';
4
+ /** Registry and generated web definitions both satisfy this public metadata shape. */
5
+ export interface PolicyFieldDefinition {
6
+ type: string;
7
+ default?: unknown;
8
+ description?: string;
9
+ required?: boolean;
10
+ nullable?: boolean;
11
+ readonly?: boolean;
12
+ sensitive?: boolean;
13
+ transient?: boolean;
14
+ readPermission?: string;
15
+ idType?: string;
16
+ ui?: FieldUIHints;
17
+ _meta?: Record<string, unknown>;
18
+ }
19
+ /**
20
+ * Narrow a manifest `_meta.ui` bag to the known {@link FieldUIHints} keys with
21
+ * their expected primitive types, dropping junk (mirrors the sanitization the
22
+ * web emission applies in core's `web-collections.ts`).
23
+ */
24
+ export declare function sanitizeFieldUIHints(value: unknown): FieldUIHints | undefined;
25
+ /** Security rail: `sensitive` may live top-level or under `_meta` (STI merges). */
26
+ export declare function isSensitiveField(field: PolicyFieldDefinition): boolean;
27
+ /** Security rail: `readPermission` may live top-level or under `_meta`. */
28
+ export declare function getFieldReadPermission(field: PolicyFieldDefinition): string | undefined;
29
+ export declare function isTransientField(field: PolicyFieldDefinition): boolean;
30
+ /**
31
+ * True when a registered field can receive a policy row. Keep this shared by
32
+ * the resolver and the catalog audit: otherwise a row that never resolves can
33
+ * accidentally be presented as an editable setting.
34
+ */
35
+ export declare function isPolicyAddressableField(field: PolicyFieldDefinition): boolean;
36
+ /**
37
+ * A field is required when flagged required and not explicitly nullable.
38
+ *
39
+ * `nullable` is read from BOTH the top level and `_meta` for the same reason
40
+ * `sensitive`/`readPermission`/`transient` are: registrations reach the
41
+ * registry through several paths (decorator, manifest, STI merge) and land the
42
+ * flag in either place. Checking only one side made the pair asymmetric —
43
+ * `required` was read from both while `nullable` was read from one.
44
+ */
45
+ export declare function isRequiredField(field: PolicyFieldDefinition): boolean;
46
+ /** The manifest/code default for a field, boxed; `undefined` when none. */
47
+ export declare function getCodeDefault(field: PolicyFieldDefinition): {
48
+ value: unknown;
49
+ } | undefined;
50
+ /**
51
+ * A resolved default satisfies the required-field invariant only when it is a
52
+ * value a form could actually submit: explicit `null` and the empty string do
53
+ * not count (a required text field "defaulting" to `''` is still unfilled).
54
+ */
55
+ export declare function isUsableRequiredDefault(defaultBox: {
56
+ value: unknown;
57
+ } | undefined): boolean;
58
+ /**
59
+ * Compute the code-seed visibility for every field of an object using the
60
+ * cold-start rule (#2046): with no `ui.basic` markers anywhere on the object,
61
+ * every field is `basic`; once any field is marked `basic: true`, unmarked
62
+ * fields default to `advanced` (and an explicit `basic: false` is always
63
+ * `advanced`).
64
+ */
65
+ export declare function buildCodeSeedVisibility(fields: ReadonlyMap<string, PolicyFieldDefinition>): Map<string, FieldPolicyVisibility>;
66
+ /** Code-seed delta for one field (visibility supplied by the cold-start pass). */
67
+ export declare function buildCodeSeedDelta(field: PolicyFieldDefinition, visibility: FieldPolicyVisibility): FieldPolicyDelta;
68
+ /** Code-seed grouping key (`ui.group`) — not overridable by stored rows. */
69
+ export declare function getCodeSeedGroup(field: PolicyFieldDefinition): string | null;
70
+ /**
71
+ * True when a reference identifier can be stored in the field's backing
72
+ * column. Native UUID columns accept UUIDs only; `idType: 'text'` opts into
73
+ * arbitrary non-empty string identifiers. Shared by policy defaults and the
74
+ * usage histogram so a poisoned sample can never become an unwriteable
75
+ * suggestion.
76
+ */
77
+ export declare function isStorableReferenceId(field: PolicyFieldDefinition, value: unknown): value is string;
78
+ /**
79
+ * Type-check a parsed default value against the manifest field type.
80
+ *
81
+ * Explicit `null` is allowed only for optional fields (a required field with a
82
+ * null default has no usable default). Unsupported field types reject defaults
83
+ * outright (fail closed).
84
+ */
85
+ export declare function assertDefaultValueMatchesFieldType(objectRef: string, fieldName: string, field: PolicyFieldDefinition, value: unknown): void;
86
+ /** Encoded sparse row shared by stored policies and portable cookbooks. */
87
+ export interface PolicyRow {
88
+ fieldName: string;
89
+ defaultValue?: string | null;
90
+ visibility?: FieldPolicyVisibility | null;
91
+ label?: string | null;
92
+ help?: string | null;
93
+ displayOrder?: number | null;
94
+ locked?: boolean | null;
95
+ readOnly?: boolean | null;
96
+ }
97
+ /** Ordered surviving layer; the server owns authorization and tenant-chain selection. */
98
+ export interface PolicyRowLayer {
99
+ layer: 'app' | 'tenant' | 'user';
100
+ tenantId?: string;
101
+ userId?: string;
102
+ rows: ReadonlyMap<string, PolicyRow>;
103
+ /** Portable rows have not passed the persistent model's write validation. */
104
+ validateDefaults?: boolean;
105
+ }
106
+ /** The one pure resolution kernel used by server resolution and cookbook screens. */
107
+ export declare function resolveFieldPolicyLayers(objectRef: string, fieldMap: ReadonlyMap<string, PolicyFieldDefinition>, rowLayers: readonly PolicyRowLayer[]): ExplainedObjectFieldPolicy;
108
+ /** Select portable identity layers; effective app rows override provider rows sparsely. */
109
+ export declare function cookbookPolicyLayers(definition: {
110
+ objectRef: string;
111
+ replacedQualifiedNames?: readonly string[];
112
+ }, cookbook: {
113
+ policies: readonly (PolicyRow & {
114
+ objectRef: string;
115
+ })[];
116
+ }): PolicyRowLayer[];
117
+ /** Resolve raw cookbook app rows over an already-public generated definition. */
118
+ export declare function resolveCookbookFieldPolicy(definition: {
119
+ objectRef: string;
120
+ replacedQualifiedNames?: readonly string[];
121
+ fields: Readonly<Record<string, PolicyFieldDefinition>>;
122
+ }, cookbook: {
123
+ policies: readonly (PolicyRow & {
124
+ objectRef: string;
125
+ })[];
126
+ }): ExplainedObjectFieldPolicy;
127
+ /** A stored row's sparse contribution (NULL columns contribute nothing). */
128
+ export declare function rowToDelta(row: PolicyRow): FieldPolicyDelta;
129
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../src/policy.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAK7D,OAAO,KAAK,EACV,0BAA0B,EAC1B,gBAAgB,EAEhB,qBAAqB,EAEtB,MAAM,YAAY,CAAC;AAEpB,sFAAsF;AACtF,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,EAAE,CAAC,EAAE,YAAY,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,GAAG,SAAS,CAgB7E;AAED,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAEtE;AAED,2EAA2E;AAC3E,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,qBAAqB,GAC3B,MAAM,GAAG,SAAS,CAMpB;AAED,wBAAg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,EAAE,qBAAqB,CAAC,CAAC,CAAC;CACzD,EACD,QAAQ,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAC,SAAS,GAAG;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,EAAE,CAAA;CAAE,GACrE,0BAA0B,CAqB5B;AAED,4EAA4E;AAC5E,wBAAgB,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,gBAAgB,CA6B3D"}
package/dist/policy.js ADDED
@@ -0,0 +1,221 @@
1
+ import { isFieldUIFormat, isFieldUIWidget } from "@happyvertical/smrt-core/ui-metadata";
2
+ //#region src/policy.ts
3
+ function sanitizeFieldUIHints(value) {
4
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
5
+ const raw = value;
6
+ const ui = {
7
+ ...typeof raw.basic === "boolean" ? { basic: raw.basic } : {},
8
+ ...typeof raw.group === "string" ? { group: raw.group } : {},
9
+ ...typeof raw.order === "number" && Number.isFinite(raw.order) ? { order: raw.order } : {},
10
+ ...typeof raw.locked === "boolean" ? { locked: raw.locked } : {},
11
+ ...isFieldUIWidget(raw.widget) ? { widget: raw.widget } : {},
12
+ ...isFieldUIFormat(raw.format) ? { format: raw.format } : {}
13
+ };
14
+ return Object.keys(ui).length > 0 ? ui : void 0;
15
+ }
16
+ function isSensitiveField(field) {
17
+ return field.sensitive === true || field._meta?.sensitive === true;
18
+ }
19
+ function getFieldReadPermission(field) {
20
+ if (typeof field.readPermission === "string") return field.readPermission;
21
+ const metaPermission = field._meta?.readPermission;
22
+ return typeof metaPermission === "string" ? metaPermission : void 0;
23
+ }
24
+ function isTransientField(field) {
25
+ return field.transient === true || field._meta?.transient === true;
26
+ }
27
+ function isPolicyAddressableField(field) {
28
+ return field._meta?.__smrtSystemField !== true && field.type !== "oneToMany" && field.type !== "manyToMany" && field.type !== "meta";
29
+ }
30
+ function isRequiredField(field) {
31
+ if (field.nullable === true || field._meta?.nullable === true) return false;
32
+ return field.required === true || field._meta?.required === true;
33
+ }
34
+ function getCodeDefault(field) {
35
+ if (field.default !== void 0) return { value: field.default };
36
+ if (field._meta?.default !== void 0) return { value: field._meta.default };
37
+ }
38
+ function isUsableRequiredDefault(defaultBox) {
39
+ if (!defaultBox) return false;
40
+ return defaultBox.value !== null && defaultBox.value !== "";
41
+ }
42
+ function buildCodeSeedVisibility(fields) {
43
+ let hasBasicMarkers = false;
44
+ const hints = /* @__PURE__ */ new Map();
45
+ for (const [name, field] of fields) {
46
+ const ui = sanitizeFieldUIHints(field._meta?.ui ?? field.ui);
47
+ hints.set(name, ui);
48
+ if (ui?.basic === true) hasBasicMarkers = true;
49
+ }
50
+ const visibility = /* @__PURE__ */ new Map();
51
+ for (const [name] of fields) {
52
+ const ui = hints.get(name);
53
+ if (ui?.basic === true) visibility.set(name, "basic");
54
+ else if (ui?.basic === false || hasBasicMarkers) visibility.set(name, "advanced");
55
+ else visibility.set(name, "basic");
56
+ }
57
+ return visibility;
58
+ }
59
+ function buildCodeSeedDelta(field, visibility) {
60
+ const ui = sanitizeFieldUIHints(field._meta?.ui ?? field.ui);
61
+ const help = typeof field.description === "string" ? field.description : typeof field._meta?.description === "string" ? field._meta.description : void 0;
62
+ const codeDefault = getCodeDefault(field);
63
+ return {
64
+ ...codeDefault ? { default: codeDefault } : {},
65
+ ...field.readonly === true ? { readOnly: true } : {},
66
+ visibility,
67
+ ...help !== void 0 ? { help } : {},
68
+ ...ui?.order !== void 0 ? { order: ui.order } : {},
69
+ ...ui?.locked === true ? { locked: true } : {}
70
+ };
71
+ }
72
+ function getCodeSeedGroup(field) {
73
+ return sanitizeFieldUIHints(field._meta?.ui ?? field.ui)?.group ?? null;
74
+ }
75
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
76
+ function usesTextIdStorage(field) {
77
+ return field.idType === "text" || field._meta?.idType === "text";
78
+ }
79
+ function isStorableReferenceId(field, value) {
80
+ if (typeof value !== "string" || value === "") return false;
81
+ return usesTextIdStorage(field) || UUID_PATTERN.test(value);
82
+ }
83
+ function assertDefaultValueMatchesFieldType(objectRef, fieldName, field, value) {
84
+ const label = `Field policy default for "${objectRef}.${fieldName}"`;
85
+ if (value === null) {
86
+ if (isRequiredField(field)) throw new Error(`${label} may not be null: the field is required, so a null default is never a usable default`);
87
+ return;
88
+ }
89
+ switch (field.type) {
90
+ case "text":
91
+ if (typeof value !== "string") throw new Error(`${label} must be a string (field type "text")`);
92
+ return;
93
+ case "integer":
94
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new Error(`${label} must be an integer (field type "integer")`);
95
+ return;
96
+ case "decimal":
97
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${label} must be a finite number (field type "decimal")`);
98
+ return;
99
+ case "boolean":
100
+ if (typeof value !== "boolean") throw new Error(`${label} must be a boolean (field type "boolean")`);
101
+ return;
102
+ case "datetime":
103
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value))) throw new Error(`${label} must be a date-parseable string (field type "datetime")`);
104
+ return;
105
+ case "json": return;
106
+ case "foreignKey":
107
+ case "crossPackageRef":
108
+ if (typeof value !== "string") throw new Error(`${label} must be a string id (field type "${field.type}")`);
109
+ if (!isStorableReferenceId(field, value)) throw new Error(`${label} must be a UUID string (the reference column stores native UUIDs; declare idType 'text' on the field to store arbitrary ids)`);
110
+ return;
111
+ default: throw new Error(`${label} is not supported: defaults cannot target "${String(field.type)}" fields`);
112
+ }
113
+ }
114
+ function resolveFieldPolicyLayers(objectRef, fieldMap, rowLayers) {
115
+ const policyFields = [...fieldMap].filter(([, field]) => isPolicyAddressableField(field));
116
+ const codeVisibility = buildCodeSeedVisibility(fieldMap);
117
+ const fields = {};
118
+ const layers = {};
119
+ for (const [fieldName, fieldDef] of policyFields) {
120
+ const contributions = [];
121
+ const codeDelta = buildCodeSeedDelta(fieldDef, codeVisibility.get(fieldName) ?? "basic");
122
+ contributions.push({
123
+ layer: "code",
124
+ delta: codeDelta
125
+ });
126
+ let state = applyDelta({ visibility: "basic" }, codeDelta);
127
+ for (const layer of rowLayers) {
128
+ const row = layer.rows.get(fieldName);
129
+ if (!row || layer.layer === "user" && state.locked === true) continue;
130
+ const delta = rowToDelta(row);
131
+ if (fieldDef.readonly && delta.readOnly === false) delete delta.readOnly;
132
+ if (fieldDef.readonly && delta.default) throw new Error(`Policy defaults cannot target read-only field ${objectRef}.${fieldName}`);
133
+ if (layer.validateDefaults && delta.default) {
134
+ if (isSensitiveField(fieldDef) || isTransientField(fieldDef) || getFieldReadPermission(fieldDef)) throw new Error(`Cookbook defaults cannot target restricted field ${objectRef}.${fieldName}`);
135
+ assertDefaultValueMatchesFieldType(objectRef, fieldName, fieldDef, delta.default.value);
136
+ }
137
+ contributions.push({
138
+ layer: layer.layer,
139
+ ...layer.tenantId ? { tenantId: layer.tenantId } : {},
140
+ ...layer.userId ? { userId: layer.userId } : {},
141
+ delta
142
+ });
143
+ state = applyDelta(state, delta);
144
+ }
145
+ const required = isRequiredField(fieldDef);
146
+ let visibilityForced = false;
147
+ if (required && !isUsableRequiredDefault(state.default) && state.visibility !== "basic") {
148
+ state = {
149
+ ...state,
150
+ visibility: "basic"
151
+ };
152
+ visibilityForced = true;
153
+ }
154
+ fields[fieldName] = {
155
+ fieldName,
156
+ hasDefault: state.default !== void 0,
157
+ defaultValue: state.default?.value,
158
+ visibility: state.visibility,
159
+ help: state.help ?? null,
160
+ label: state.label ?? null,
161
+ order: state.order ?? null,
162
+ group: getCodeSeedGroup(fieldDef),
163
+ locked: state.locked === true,
164
+ required,
165
+ ...fieldDef.readonly === true || state.readOnly !== void 0 ? { readOnly: fieldDef.readonly === true || state.readOnly === true } : {},
166
+ ...visibilityForced ? { visibilityForced: true } : {}
167
+ };
168
+ layers[fieldName] = contributions;
169
+ }
170
+ return {
171
+ objectRef,
172
+ fields,
173
+ layers
174
+ };
175
+ }
176
+ function cookbookPolicyLayers(definition, cookbook) {
177
+ const aliases = new Set(definition.replacedQualifiedNames ?? []);
178
+ return [...cookbook.policies.filter((row) => row.objectRef !== definition.objectRef && aliases.has(row.objectRef)), ...cookbook.policies.filter((row) => row.objectRef === definition.objectRef)].map((row) => ({
179
+ layer: "app",
180
+ validateDefaults: true,
181
+ rows: /* @__PURE__ */ new Map([[row.fieldName, row]])
182
+ }));
183
+ }
184
+ function resolveCookbookFieldPolicy(definition, cookbook) {
185
+ return resolveFieldPolicyLayers(definition.objectRef, new Map(Object.entries(definition.fields).filter(([name, field]) => ![
186
+ "id",
187
+ "tenantId",
188
+ "createdBy",
189
+ "updatedBy",
190
+ "createdAt",
191
+ "updatedAt"
192
+ ].includes(name) && !isSensitiveField(field) && !isTransientField(field) && !getFieldReadPermission(field))), cookbookPolicyLayers(definition, cookbook));
193
+ }
194
+ function rowToDelta(row) {
195
+ const delta = {};
196
+ if (row.defaultValue !== null && row.defaultValue !== void 0) try {
197
+ delta.default = { value: JSON.parse(row.defaultValue) };
198
+ } catch {}
199
+ if (row.visibility !== null && row.visibility !== void 0) delta.visibility = row.visibility;
200
+ if (row.help !== null && row.help !== void 0) delta.help = row.help;
201
+ if (row.label !== null && row.label !== void 0) delta.label = row.label;
202
+ if (row.displayOrder !== null && row.displayOrder !== void 0) delta.order = row.displayOrder;
203
+ if (row.locked !== null && row.locked !== void 0) delta.locked = row.locked;
204
+ if (row.readOnly != null) delta.readOnly = row.readOnly;
205
+ return delta;
206
+ }
207
+ function applyDelta(state, delta) {
208
+ return {
209
+ default: delta.default ?? state.default,
210
+ visibility: delta.visibility ?? state.visibility,
211
+ help: delta.help ?? state.help,
212
+ label: delta.label ?? state.label,
213
+ order: delta.order ?? state.order,
214
+ locked: delta.locked ?? state.locked,
215
+ readOnly: delta.readOnly ?? state.readOnly
216
+ };
217
+ }
218
+ //#endregion
219
+ export { assertDefaultValueMatchesFieldType, buildCodeSeedDelta, buildCodeSeedVisibility, cookbookPolicyLayers, getCodeDefault, getCodeSeedGroup, getFieldReadPermission, isPolicyAddressableField, isRequiredField, isSensitiveField, isStorableReferenceId, isTransientField, isUsableRequiredDefault, resolveCookbookFieldPolicy, resolveFieldPolicyLayers, rowToDelta, sanitizeFieldUIHints };
220
+
221
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.js","names":[],"sources":["../src/policy.ts"],"sourcesContent":["/** Browser-safe field definitions and the canonical layered policy resolver. */\nimport type { FieldUIHints } from '@happyvertical/smrt-core';\nimport {\n isFieldUIFormat,\n isFieldUIWidget,\n} from '@happyvertical/smrt-core/ui-metadata';\nimport type {\n ExplainedObjectFieldPolicy,\n FieldPolicyDelta,\n FieldPolicyLayerContribution,\n FieldPolicyVisibility,\n ResolvedFieldPolicy,\n} from './types.js';\n\n/** Registry and generated web definitions both satisfy this public metadata shape. */\nexport interface PolicyFieldDefinition {\n type: string;\n default?: unknown;\n description?: string;\n required?: boolean;\n nullable?: boolean;\n readonly?: boolean;\n sensitive?: boolean;\n transient?: boolean;\n readPermission?: string;\n idType?: string;\n ui?: FieldUIHints;\n _meta?: Record<string, unknown>;\n}\n\n/**\n * Narrow a manifest `_meta.ui` bag to the known {@link FieldUIHints} keys with\n * their expected primitive types, dropping junk (mirrors the sanitization the\n * web emission applies in core's `web-collections.ts`).\n */\nexport function sanitizeFieldUIHints(value: unknown): FieldUIHints | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return undefined;\n }\n const raw = value as Record<string, unknown>;\n const ui: FieldUIHints = {\n ...(typeof raw.basic === 'boolean' ? { basic: raw.basic } : {}),\n ...(typeof raw.group === 'string' ? { group: raw.group } : {}),\n ...(typeof raw.order === 'number' && Number.isFinite(raw.order)\n ? { order: raw.order }\n : {}),\n ...(typeof raw.locked === 'boolean' ? { locked: raw.locked } : {}),\n ...(isFieldUIWidget(raw.widget) ? { widget: raw.widget } : {}),\n ...(isFieldUIFormat(raw.format) ? { format: raw.format } : {}),\n };\n return Object.keys(ui).length > 0 ? ui : undefined;\n}\n\n/** Security rail: `sensitive` may live top-level or under `_meta` (STI merges). */\nexport function isSensitiveField(field: PolicyFieldDefinition): boolean {\n return field.sensitive === true || field._meta?.sensitive === true;\n}\n\n/** Security rail: `readPermission` may live top-level or under `_meta`. */\nexport function getFieldReadPermission(\n field: PolicyFieldDefinition,\n): string | undefined {\n if (typeof field.readPermission === 'string') {\n return field.readPermission;\n }\n const metaPermission = field._meta?.readPermission;\n return typeof metaPermission === 'string' ? metaPermission : undefined;\n}\n\nexport function isTransientField(field: PolicyFieldDefinition): boolean {\n return field.transient === true || field._meta?.transient === true;\n}\n\n/**\n * True when a registered field can receive a policy row. Keep this shared by\n * the resolver and the catalog audit: otherwise a row that never resolves can\n * accidentally be presented as an editable setting.\n */\nexport function isPolicyAddressableField(\n field: PolicyFieldDefinition,\n): boolean {\n return (\n field._meta?.__smrtSystemField !== true &&\n field.type !== 'oneToMany' &&\n field.type !== 'manyToMany' &&\n field.type !== 'meta'\n );\n}\n\n/**\n * A field is required when flagged required and not explicitly nullable.\n *\n * `nullable` is read from BOTH the top level and `_meta` for the same reason\n * `sensitive`/`readPermission`/`transient` are: registrations reach the\n * registry through several paths (decorator, manifest, STI merge) and land the\n * flag in either place. Checking only one side made the pair asymmetric —\n * `required` was read from both while `nullable` was read from one.\n */\nexport function isRequiredField(field: PolicyFieldDefinition): boolean {\n if (field.nullable === true || field._meta?.nullable === true) {\n return false;\n }\n return field.required === true || field._meta?.required === true;\n}\n\n/** The manifest/code default for a field, boxed; `undefined` when none. */\nexport function getCodeDefault(\n field: PolicyFieldDefinition,\n): { value: unknown } | undefined {\n if (field.default !== undefined) {\n return { value: field.default };\n }\n if (field._meta?.default !== undefined) {\n return { value: field._meta.default };\n }\n return undefined;\n}\n\n/**\n * A resolved default satisfies the required-field invariant only when it is a\n * value a form could actually submit: explicit `null` and the empty string do\n * not count (a required text field \"defaulting\" to `''` is still unfilled).\n */\nexport function isUsableRequiredDefault(\n defaultBox: { value: unknown } | undefined,\n): boolean {\n if (!defaultBox) {\n return false;\n }\n return defaultBox.value !== null && defaultBox.value !== '';\n}\n\n/**\n * Compute the code-seed visibility for every field of an object using the\n * cold-start rule (#2046): with no `ui.basic` markers anywhere on the object,\n * every field is `basic`; once any field is marked `basic: true`, unmarked\n * fields default to `advanced` (and an explicit `basic: false` is always\n * `advanced`).\n */\nexport function buildCodeSeedVisibility(\n fields: ReadonlyMap<string, PolicyFieldDefinition>,\n): Map<string, FieldPolicyVisibility> {\n let hasBasicMarkers = false;\n const hints = new Map<string, FieldUIHints | undefined>();\n for (const [name, field] of fields) {\n const ui = sanitizeFieldUIHints(field._meta?.ui ?? field.ui);\n hints.set(name, ui);\n if (ui?.basic === true) {\n hasBasicMarkers = true;\n }\n }\n\n const visibility = new Map<string, FieldPolicyVisibility>();\n for (const [name] of fields) {\n const ui = hints.get(name);\n if (ui?.basic === true) {\n visibility.set(name, 'basic');\n } else if (ui?.basic === false || hasBasicMarkers) {\n visibility.set(name, 'advanced');\n } else {\n visibility.set(name, 'basic');\n }\n }\n return visibility;\n}\n\n/** Code-seed delta for one field (visibility supplied by the cold-start pass). */\nexport function buildCodeSeedDelta(\n field: PolicyFieldDefinition,\n visibility: FieldPolicyVisibility,\n): FieldPolicyDelta {\n const ui = sanitizeFieldUIHints(field._meta?.ui ?? field.ui);\n const help =\n typeof field.description === 'string'\n ? field.description\n : typeof field._meta?.description === 'string'\n ? field._meta.description\n : undefined;\n const codeDefault = getCodeDefault(field);\n\n return {\n ...(codeDefault ? { default: codeDefault } : {}),\n ...(field.readonly === true ? { readOnly: true } : {}),\n visibility,\n ...(help !== undefined ? { help } : {}),\n ...(ui?.order !== undefined ? { order: ui.order } : {}),\n ...(ui?.locked === true ? { locked: true } : {}),\n };\n}\n\n/** Code-seed grouping key (`ui.group`) — not overridable by stored rows. */\nexport function getCodeSeedGroup(field: PolicyFieldDefinition): string | null {\n return sanitizeFieldUIHints(field._meta?.ui ?? field.ui)?.group ?? null;\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Whether a reference field stores text ids instead of native UUIDs. */\nfunction usesTextIdStorage(field: PolicyFieldDefinition): boolean {\n return field.idType === 'text' || field._meta?.idType === 'text';\n}\n\n/**\n * True when a reference identifier can be stored in the field's backing\n * column. Native UUID columns accept UUIDs only; `idType: 'text'` opts into\n * arbitrary non-empty string identifiers. Shared by policy defaults and the\n * usage histogram so a poisoned sample can never become an unwriteable\n * suggestion.\n */\nexport function isStorableReferenceId(\n field: PolicyFieldDefinition,\n value: unknown,\n): value is string {\n if (typeof value !== 'string' || value === '') return false;\n return usesTextIdStorage(field) || UUID_PATTERN.test(value);\n}\n\n/**\n * Type-check a parsed default value against the manifest field type.\n *\n * Explicit `null` is allowed only for optional fields (a required field with a\n * null default has no usable default). Unsupported field types reject defaults\n * outright (fail closed).\n */\nexport function assertDefaultValueMatchesFieldType(\n objectRef: string,\n fieldName: string,\n field: PolicyFieldDefinition,\n value: unknown,\n): void {\n const label = `Field policy default for \"${objectRef}.${fieldName}\"`;\n\n if (value === null) {\n if (isRequiredField(field)) {\n throw new Error(\n `${label} may not be null: the field is required, so a null default ` +\n `is never a usable default`,\n );\n }\n return;\n }\n\n switch (field.type) {\n case 'text':\n if (typeof value !== 'string') {\n throw new Error(`${label} must be a string (field type \"text\")`);\n }\n return;\n case 'integer':\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n throw new Error(`${label} must be an integer (field type \"integer\")`);\n }\n return;\n case 'decimal':\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(\n `${label} must be a finite number (field type \"decimal\")`,\n );\n }\n return;\n case 'boolean':\n if (typeof value !== 'boolean') {\n throw new Error(`${label} must be a boolean (field type \"boolean\")`);\n }\n return;\n case 'datetime':\n if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {\n throw new Error(\n `${label} must be a date-parseable string (field type \"datetime\")`,\n );\n }\n return;\n case 'json':\n // Any JSON value (it already survived JSON.parse).\n return;\n case 'foreignKey':\n case 'crossPackageRef':\n if (typeof value !== 'string') {\n throw new Error(\n `${label} must be a string id (field type \"${field.type}\")`,\n );\n }\n // Reference columns are native UUID on PostgreSQL/DuckDB unless the\n // field explicitly opts into text ids — a non-UUID default would\n // validate here but fail at insert time on those dialects.\n if (!isStorableReferenceId(field, value)) {\n throw new Error(\n `${label} must be a UUID string (the reference column stores ` +\n `native UUIDs; declare idType 'text' on the field to store ` +\n `arbitrary ids)`,\n );\n }\n return;\n default:\n throw new Error(\n `${label} is not supported: defaults cannot target ` +\n `\"${String(field.type)}\" fields`,\n );\n }\n}\n\n/** Accumulated merge state for one field while layers apply. */\ninterface MergedPolicyState {\n default?: { value: unknown };\n visibility: FieldPolicyVisibility;\n help?: string;\n label?: string;\n order?: number;\n locked?: boolean;\n readOnly?: boolean;\n}\n\n/** Encoded sparse row shared by stored policies and portable cookbooks. */\nexport interface PolicyRow {\n fieldName: string;\n defaultValue?: string | null;\n visibility?: FieldPolicyVisibility | null;\n label?: string | null;\n help?: string | null;\n displayOrder?: number | null;\n locked?: boolean | null;\n readOnly?: boolean | null;\n}\n\n/** Ordered surviving layer; the server owns authorization and tenant-chain selection. */\nexport interface PolicyRowLayer {\n layer: 'app' | 'tenant' | 'user';\n tenantId?: string;\n userId?: string;\n rows: ReadonlyMap<string, PolicyRow>;\n /** Portable rows have not passed the persistent model's write validation. */\n validateDefaults?: boolean;\n}\n\n/** The one pure resolution kernel used by server resolution and cookbook screens. */\nexport function resolveFieldPolicyLayers(\n objectRef: string,\n fieldMap: ReadonlyMap<string, PolicyFieldDefinition>,\n rowLayers: readonly PolicyRowLayer[],\n): ExplainedObjectFieldPolicy {\n const policyFields = [...fieldMap].filter(([, field]) =>\n isPolicyAddressableField(field),\n );\n const codeVisibility = buildCodeSeedVisibility(fieldMap);\n const fields: Record<string, ResolvedFieldPolicy> = {};\n const layers: Record<string, FieldPolicyLayerContribution[]> = {};\n\n for (const [fieldName, fieldDef] of policyFields) {\n const contributions: FieldPolicyLayerContribution[] = [];\n\n const codeDelta = buildCodeSeedDelta(\n fieldDef,\n codeVisibility.get(fieldName) ?? 'basic',\n );\n contributions.push({ layer: 'code', delta: codeDelta });\n\n let state: MergedPolicyState = applyDelta(\n { visibility: 'basic' },\n codeDelta,\n );\n\n for (const layer of rowLayers) {\n const row = layer.rows.get(fieldName);\n if (!row || (layer.layer === 'user' && state.locked === true)) continue;\n const delta = rowToDelta(row);\n if (fieldDef.readonly && delta.readOnly === false) delete delta.readOnly;\n if (fieldDef.readonly && delta.default) {\n throw new Error(\n `Policy defaults cannot target read-only field ${objectRef}.${fieldName}`,\n );\n }\n if (layer.validateDefaults && delta.default) {\n if (\n isSensitiveField(fieldDef) ||\n isTransientField(fieldDef) ||\n getFieldReadPermission(fieldDef)\n ) {\n throw new Error(\n `Cookbook defaults cannot target restricted field ${objectRef}.${fieldName}`,\n );\n }\n assertDefaultValueMatchesFieldType(\n objectRef,\n fieldName,\n fieldDef,\n delta.default.value,\n );\n }\n contributions.push({\n layer: layer.layer,\n ...(layer.tenantId ? { tenantId: layer.tenantId } : {}),\n ...(layer.userId ? { userId: layer.userId } : {}),\n delta,\n });\n state = applyDelta(state, delta);\n }\n\n // Resolver-side required-field safety net: a required field with no\n // usable resolved default is ALWAYS visible, regardless of stored\n // visibility — write-time enforcement alone breaks when a DIFFERENT row's\n // deletion removes the default a demotion relied on.\n const required = isRequiredField(fieldDef);\n let visibilityForced = false;\n if (\n required &&\n !isUsableRequiredDefault(state.default) &&\n state.visibility !== 'basic'\n ) {\n state = { ...state, visibility: 'basic' };\n visibilityForced = true;\n }\n\n fields[fieldName] = {\n fieldName,\n hasDefault: state.default !== undefined,\n defaultValue: state.default?.value,\n visibility: state.visibility,\n help: state.help ?? null,\n label: state.label ?? null,\n order: state.order ?? null,\n group: getCodeSeedGroup(fieldDef),\n locked: state.locked === true,\n required,\n ...(fieldDef.readonly === true || state.readOnly !== undefined\n ? { readOnly: fieldDef.readonly === true || state.readOnly === true }\n : {}),\n ...(visibilityForced ? { visibilityForced: true } : {}),\n };\n layers[fieldName] = contributions;\n }\n\n return { objectRef, fields, layers };\n}\n\n/** Select portable identity layers; effective app rows override provider rows sparsely. */\nexport function cookbookPolicyLayers(\n definition: { objectRef: string; replacedQualifiedNames?: readonly string[] },\n cookbook: { policies: readonly (PolicyRow & { objectRef: string })[] },\n): PolicyRowLayer[] {\n const aliases = new Set(definition.replacedQualifiedNames ?? []);\n const rows = [\n ...cookbook.policies.filter(\n (row) =>\n row.objectRef !== definition.objectRef && aliases.has(row.objectRef),\n ),\n ...cookbook.policies.filter(\n (row) => row.objectRef === definition.objectRef,\n ),\n ];\n return rows.map((row) => ({\n layer: 'app',\n validateDefaults: true,\n rows: new Map([[row.fieldName, row]]),\n }));\n}\n\n/** Resolve raw cookbook app rows over an already-public generated definition. */\nexport function resolveCookbookFieldPolicy(\n definition: {\n objectRef: string;\n replacedQualifiedNames?: readonly string[];\n fields: Readonly<Record<string, PolicyFieldDefinition>>;\n },\n cookbook: { policies: readonly (PolicyRow & { objectRef: string })[] },\n): ExplainedObjectFieldPolicy {\n return resolveFieldPolicyLayers(\n definition.objectRef,\n new Map(\n Object.entries(definition.fields).filter(\n ([name, field]) =>\n ![\n 'id',\n 'tenantId',\n 'createdBy',\n 'updatedBy',\n 'createdAt',\n 'updatedAt',\n ].includes(name) &&\n !isSensitiveField(field) &&\n !isTransientField(field) &&\n !getFieldReadPermission(field),\n ),\n ),\n cookbookPolicyLayers(definition, cookbook),\n );\n}\n\n/** A stored row's sparse contribution (NULL columns contribute nothing). */\nexport function rowToDelta(row: PolicyRow): FieldPolicyDelta {\n const delta: FieldPolicyDelta = {};\n\n if (row.defaultValue !== null && row.defaultValue !== undefined) {\n try {\n delta.default = { value: JSON.parse(row.defaultValue) };\n } catch {\n // Unparseable stored JSON (should be prevented by save-time validation)\n // contributes nothing rather than poisoning resolution.\n }\n }\n if (row.visibility !== null && row.visibility !== undefined) {\n delta.visibility = row.visibility;\n }\n if (row.help !== null && row.help !== undefined) {\n delta.help = row.help;\n }\n if (row.label !== null && row.label !== undefined) {\n delta.label = row.label;\n }\n if (row.displayOrder !== null && row.displayOrder !== undefined) {\n delta.order = row.displayOrder;\n }\n if (row.locked !== null && row.locked !== undefined) {\n delta.locked = row.locked;\n }\n\n if (row.readOnly != null) delta.readOnly = row.readOnly;\n return delta;\n}\n\nfunction applyDelta(\n state: MergedPolicyState,\n delta: FieldPolicyDelta,\n): MergedPolicyState {\n return {\n default: delta.default ?? state.default,\n visibility: delta.visibility ?? state.visibility,\n help: delta.help ?? state.help,\n label: delta.label ?? state.label,\n order: delta.order ?? state.order,\n locked: delta.locked ?? state.locked,\n readOnly: delta.readOnly ?? state.readOnly,\n };\n}\n"],"mappings":";;AAmCO,SAAS,qBAAqB,OAA0C;CAC7E,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D;CAEF,MAAM,MAAM;CACZ,MAAM,KAAmB;EACvB,GAAI,OAAO,IAAI,UAAU,YAAY,EAAE,OAAO,IAAI,MAAM,IAAI,CAAC;EAC7D,GAAI,OAAO,IAAI,UAAU,WAAW,EAAE,OAAO,IAAI,MAAM,IAAI,CAAC;EAC5D,GAAI,OAAO,IAAI,UAAU,YAAY,OAAO,SAAS,IAAI,KAAK,IAC1D,EAAE,OAAO,IAAI,MAAM,IACnB,CAAC;EACL,GAAI,OAAO,IAAI,WAAW,YAAY,EAAE,QAAQ,IAAI,OAAO,IAAI,CAAC;EAChE,GAAI,gBAAgB,IAAI,MAAM,IAAI,EAAE,QAAQ,IAAI,OAAO,IAAI,CAAC;EAC5D,GAAI,gBAAgB,IAAI,MAAM,IAAI,EAAE,QAAQ,IAAI,OAAO,IAAI,CAAC;CAC9D;CACA,OAAO,OAAO,KAAK,EAAE,CAAA,CAAE,SAAS,IAAI,KAAK,KAAA;AAC3C;AAGO,SAAS,iBAAiB,OAAuC;CACtE,OAAO,MAAM,cAAc,QAAQ,MAAM,OAAO,cAAc;A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AI,UAAU,KAAA,GACtC,MAAM,QAAQ,IAAI;CAEpB,IAAI,IAAI,iBAAiB,QAAQ,IAAI,iBAAiB,KAAA,GACpD,MAAM,QAAQ,IAAI;CAEpB,IAAI,IAAI,WAAW,QAAQ,IAAI,WAAW,KAAA,GACxC,MAAM,SAAS,IAAI;CAGrB,IAAI,IAAI,YAAY,MAAM,MAAM,WAAW,IAAI;CAC/C,OAAO;AACT;AAEA,SAAS,WACP,OACA,OACmB;CACnB,OAAO;EACL,SAAS,MAAM,WAAW,MAAM;EAChC,YAAY,MAAM,cAAc,MAAM;EACtC,MAAM,MAAM,QAAQ,MAAM;EAC1B,OAAO,MAAM,SAAS,MAAM;EAC5B,OAAO,MAAM,SAAS,MAAM;EAC5B,QAAQ,MAAM,UAAU,MAAM;EAC9B,UAAU,MAAM,YAAY,MAAM;CACpC;AACF"}
@@ -3,19 +3,21 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-fields",
6
- "packageVersion": "0.60.17",
6
+ "packageVersion": "0.61.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "88f8fff4453f5c9256a078a36a25c91fb92dd2696a26e5aa336cf0878e9d1951",
11
- "packageJson": "4e95036fbda083e4eaa807f9515a8edf26043c558ee57ba72df19a2c506b9430",
12
- "agents": "ae4bf7b69ae3b28a7900b590dd21b53ea0dfc5fd6778f858ceac97dfd8654187"
10
+ "manifest": "f55b72da48124b844d8b9755447cff68a126cf44a9306b6ed7ddab5a0e039924",
11
+ "packageJson": "ca640eb6f4aa2682b4ddce2241cbec39a819e931a89146aaa07c3252644d70f5",
12
+ "agents": "94320fb58c6d7ef3ced33afc2207eb8cd4fef135f97c55206973dfbd5fdeb3b3",
13
+ "moduleDoc:agents/cookbook-policy.md": "e416094c4867b60730ae337669e03a8c51f74058a6a544c09abb244368a9679d"
13
14
  },
14
15
  "exports": [
15
16
  ".",
16
17
  "./manifest",
17
18
  "./manifest.json",
18
19
  "./playground",
20
+ "./policy",
19
21
  "./svelte"
20
22
  ],
21
23
  "dependencies": {
@@ -1211,7 +1213,14 @@
1211
1213
  "polymorphicAssociations": 0,
1212
1214
  "uuidColumns": 25
1213
1215
  },
1214
- "agentDoc": "# smrt-fields\n\nLayered field policy store and resolution engine (epic #2045). Personalizes\nper-field `{defaultValue, visibility, help, label, order, locked}` for any\n`@smrt()` object at app, tenant, and user scope over the code seed.\n\n## Core pieces\n\n- `FieldPolicy` (`_smrt_field_policies` table) — sparse override rows keyed\n `(objectRef, fieldName, scopeType, scopeKey)`; NULL column = inherit from\n the lower layer, reset = row DELETE (later lower-layer changes flow through)\n- `FieldPolicyCollection` — write surface plus the `resolveBatch` custom\n collection-scoped action (`POST /<collection>/resolve`). NO generated\n surface exposes read verbs: API `list`/`get` on this non-tenant-scoped\n model would enumerate every tenant's and user's rows; the model's CLI is\n writes-only (the generated CLI invokes over HTTP, and the cli↔api\n coherence gate rejects CLI entries without API routes); the runtime\n CLI/MCP surfaces are closed by the collection config (ContentContributions\n precedent). Reads go through `resolveBatch` (context-scoped) or the\n server-side resolver. Keep the api include lists in lockstep: a decorated\n collection's config is the RUNTIME registry authority for its item class,\n while build-time generation reads each manifest object's own config. Both\n transports dispatch the action: generated SvelteKit routes natively, and\n core's runtime `APIGenerator` via its decorator-route dispatch\n (single-segment collection-scoped paths; multi-segment custom paths remain\n SvelteKit-only).\n- `resolveFieldPolicy(objectRef, { tenantId, userId, db })` — merged policy\n- `resolveFieldPolicyExplained(...)` — merged policy plus ordered per-layer\n contributions (code/app/tenant/user) for gear/admin UIs (#2049/#2050)\n\n## Resolution layers (priority low → high)\n\n1. Code seed — manifest field defaults, `description` as help, `_meta.ui`\n hints (#2046: `basic`/`group`/`order`/`locked`; cold-start rule: no\n `basic` markers ⇒ everything basic, any marker ⇒ unmarked fields advanced)\n2. App rows — `scopeType: 'app'`, `tenantId`/`userId` null\n3. Tenant rows — hierarchy walk root → leaf via an injected\n `tenantHierarchyLoader` (smrt-features shape); the default loader\n uses `@happyvertical/smrt-users`' `TenantCollection`; an injected loader\n may return no provider (or no chain for a tenant), which falls back to a\n flat single-tenant chain. `smrt-users` itself is a required Fields runtime\n dependency for policy authorization, not an optional hierarchy dependency.\n A node that breaks permission\n inheritance discards every earlier tenant contribution (chain-structural),\n so only the suffix from the LAST break participates — in merging AND in\n the explained layers, which therefore replay to the merged result\n4. User rows — keyed by `userId` alone (preferences follow the user); both\n defaults AND visibility resolve through this tier\n\n## Invariants\n\n- **Scope shape**: app ⇒ `tenantId`+`userId` null; tenant ⇒ only `tenantId`;\n user ⇒ only `userId`. `scopeKey` (`userId ?? tenantId ?? '__app__'`) exists\n ONLY to keep the `conflictColumns` unique index total — never read it for\n scoping logic.\n- **Manifest as definition registry**: writes validate against the live\n `ObjectRegistry` (never checked-in manifest.json artifacts): unknown\n objectRef/fieldName rejected; defaults type-checked against the field type;\n system fields, relationship pseudo-fields, and STI meta storage fields are\n not policy-addressable (the resolver excludes them, so rows would silently\n never apply).\n- **Security rail**: defaults are refused on `transient`, `sensitive`, and\n `readPermission`-gated fields (both top-level and `_meta` flags checked).\n Reference-field (`foreignKey`/`crossPackageRef`) defaults must be UUID\n strings unless the field declares `idType: 'text'` — the columns are\n native UUID on PostgreSQL/DuckDB and a non-UUID default would fail at\n insert time. `resolveBatch` responses omit sensitive/read-permission-gated\n fields for every caller (fail closed) and transient fields\n (client-emission parity).\n- **Required-field invariant**: demoting a required field to\n advanced/hidden requires a usable resolved default (not null/empty) —\n enforced at write time AND re-enforced at resolution (a required field with\n no usable default always resolves `basic`, flagged `visibilityForced`).\n- **Org lock**: `locked` may be set on app/tenant rows only; while the\n code/app/tenant tiers resolve locked, user-scope writes are rejected and\n existing user rows are skipped at resolution.\n- **Write-time org checks reuse the resolver**: the required-demotion default\n and the user-write lock are computed by `resolveFieldPolicy` over the org\n tiers (default hierarchy loader), so cascading ancestor-tenant defaults and\n locks are honored at save time too. On updates the persisted row is excluded\n from projected lower-layer resolution, so clearing the row's only default\n while demoting a required field is rejected before mutation; that projected\n lookup bypasses the shared cache. The resolver-side safety net remains\n authoritative when a different row is later deleted.\n- **Isolation — a MISSING identity component DENIES, it never skips.** This\n is the package rule; both the write guard\n (`FieldPolicy.assertScopeOwnedByAmbientContext`) and the read guard\n (`assertResolutionAllowedInContext`) obey it. A non-bypass tenant context\n may only resolve/write its own tenant, and the user tier only for its own\n user id — a context carrying permissions but NO `userId` (no `resolveUserId`\n hook configured: API-key auth, service principals, background jobs, a bare\n `withTenant({ tenantId })`) may not touch the user tier at all. Skipping\n that check instead of denying it was a live ownership bypass: user rows are\n `tenantId: null` by design, so nothing else contains such a write. App-scope\n writes inside a tenant context require super-admin bypass. `fields.policy.manage`\n authorizes app/tenant policy mutations; `fields.policy.personalize` authorizes\n only the caller's user tier (default-seeded for built-in roles). With NO ambient\n identity at all (tenancy ALS never entered), policy writes/deletes fail closed;\n trusted system and super-admin contexts retain their explicit bypasses.\n Context-LESS *reads* stay allowed because `resolveFieldPolicy` is a trusted\n server-side API. `save()`/`delete()`\n on an existing row additionally authorize against the row's PERSISTED\n scope, looked up by primary key AND — because a generated create always\n mints a fresh UUID while the `conflictColumns` upsert still replaces the\n occupant — by NATURAL key. `resolveBatch` takes identity exclusively from\n the ambient context; the request body cannot select another tenant or user.\n- **Scope attribution**: inside an ambient context the model DERIVES a\n missing `tenantId` (tenant rows) or `userId` (user rows) from that context,\n and always stamps `updatedBy` from it. Core's mass-assignment guard treats\n `tenantId` as server-managed and strips it from every generated write body\n while `FieldPolicy` is deliberately not `@TenantScoped`, so without this the\n org tier is write-dead over REST/SvelteKit (scope-shape validation throws).\n Deriving grants nothing — the ownership guard already pinned the value to\n the ambient one. An explicit value is never overwritten, so a super-admin\n bypass caller writing ANOTHER tenant's row must go through a server-side\n model call; the generated routes still strip it.\n\n## Caching and invalidation\n\n- Resolver results cached per\n `(dbNamespace, objectRef, tenantId, userId, hierarchyLoader)` with a 30s TTL\n (`cache.ts` mirrors smrt-prompts' `getDbNamespace`). The loader identity is\n part of the key because an injected `tenantHierarchyLoader` yields a\n different ancestor chain — and so different defaults/locks — for the same\n `(db, objectRef, tenant, user)`; it goes LAST so the `(db, objectRef)`\n prefix scan still invalidates every loader's entries.\n- `FieldPolicy.save()`/`.delete()` invalidate ALL entries for the row's\n `(db, objectRef)` — coarser than prompts because tenant hierarchy makes a\n parent-tenant row affect every descendant's resolution.\n- `_smrt_field_policies` rows do NOT ride the client change feed: core's\n change-feed writer deliberately skips `_smrt_`-prefixed system tables, and\n the emit side is private. Live client invalidation is a core-side decision;\n do not add custom push/emit paths here.\n\n## Gotchas\n\n- Defaults have TWO explicit constructor channels, never sniffed:\n `defaultValue` is ALREADY JSON-encoded (the wire contract — generated write\n routes hand the request body straight to the constructor, and #2049's gear\n posts `JSON.stringify(draft.defaultValue)`), while `defaultValueRaw` is a\n plain value that is always serialized, strings included. Passing both throws.\n One option cannot carry both meanings: `'\"TBD\"'` and `'TBD'` are\n indistinguishable, so `{ defaultValue: 'Net 30' }` is a parse error that\n names `defaultValueRaw` in its message. `setDefaultValue()` is the\n method-level plain channel.\n- The sort-order column is `displayOrder` (resolved output exposes `order`):\n a column literally named `order` is an SQL keyword the runtime INSERT path\n does not quote.\n- `FieldPolicy` deliberately has NO class-level `@TenantScoped` (the\n prompts/features precedent): resolution legitimately reads app rows and\n ancestor-tenant rows, which the tenancy interceptor would block. Isolation\n is enforced at the resolver/save boundaries instead.\n- Identity changes (objectRef/fieldName/scope) on a persisted row go through\n delete-then-insert (transactional when the driver supports it) because the\n natural-key upsert would otherwise collide with the primary key.\n- `FieldPolicyCollection` MUST repeat FieldPolicy's `conflictColumns`. A\n decorated collection emits its OWN manifest schema for the item's table, and\n without the natural key that schema falls back to SmrtObject's default unique\n `(slug, context)` index; manifest-driven migrations aggregate both onto\n `_smrt_field_policies`, where the stray index rejects legitimate layered rows\n (all policy rows have NULL slug/context). The runtime registry cannot catch\n this — `getAllSchemas()` is keyed by TABLE name, so the two schemas collapse\n into one entry. Pinned against the generated manifest in\n `generated-surfaces.test.ts`.\n- `withSystemContext()` does NOT unlock tenant/user-scope writes:\n `getCurrentTenant()` returns undefined inside it, so the context-absent rule\n rejects those tiers before any bypass check. Seeds and migrations that must\n write org/user rows use a `superAdminBypass` context instead.\n- The MODEL's `cli`/`mcp` decorator config is dead at runtime: the registry\n re-registers the item slot with the COLLECTION's config wholesale, so\n `FieldPolicyCollection`'s `cli: false, mcp: false` is what actually closes\n those surfaces. Keep both in lockstep anyway — build-time generation reads\n the model's own config. Related: `ObjectRegistry.getTableName(\n 'FieldPolicyCollection')` resolves to the UNPREFIXED collection fallback\n `field_policies`; persistence uses the item class\n (`_smrt_field_policies`), and both are pinned in\n `generated-surfaces.test.ts`.\n\n## Svelte generated forms (#2049)\n\n- `ObjectForm` accepts direct generated `fields` plus a resolved `policy` for\n SSR and explicit hosts, or accepts only `objectRef` beneath an\n `ObjectFormSourceProvider`. `ObjectFormSourceRegistry` is per app and maps\n canonical refs to generated web collection definitions before calling the\n generated `resolveBatch` custom action. It uses structural types only: this\n package must never import `smrt-web`.\n- Generated custom-action clients resolve `Promise<any>`; validate their\n `policies[objectRef]` response at the registry boundary and fail closed on a\n missing/mismatched definition or policy. The component renders an accessible\n loading state and alert rather than a partial form.\n- Browser manifest types are `text`, `integer`, `decimal`, `boolean`,\n `datetime`, `json`, `foreignKey`, and `crossPackageRef`; there is no `select`\n wire type. Apps use the per-app `FieldInputRegistry.registerField` seam for\n select-like widgets. Reference fields intentionally default to identifier\n inputs unless an app supplies a chooser.\n- `policyToVisibleColumnIds(policy, columns)` feeds smrt-ui `DataTable`'s\n `visibleColumnIds`; it filters policy-hidden mapped fields and restricted\n (`sensitive`/`secret` or `readable: false`) columns, preserves unrestricted\n unmapped computed/action columns, and cannot reveal a static `column.hidden`\n column. Pass `authorizedColumnIds` only when the host explicitly authorizes a\n restricted column; `readable: true` alone does not override sensitivity.\n- `policyToDataSurfaceDescriptor(policy, descriptor)` is the corresponding\n mounted DataSurface adapter. It carries effective labels, help text, order,\n visibility, readable/capability state, and operator/query allowlists into\n discovery metadata while retaining unrestricted computed, row-key, selection,\n and action columns. Static or resolved-policy-hidden structural columns are\n omitted from discovery (the row key remains only as a non-readable identity\n column), and actions that explicitly depend on hidden columns are removed.\n Sensitive/secret and `readable: false` columns also fail closed when omitted\n from the resolved policy; a host must pass `authorizedColumnIds` explicitly\n to expose a restricted descriptor column, and authorization sets the\n effective `readable` metadata to `true` so capabilities and query allowlists\n cannot contradict it.\n- **Two-tier context contract.** `PolicyField` alone reads the context with\n `tryGetFieldPolicyContext()`, because outside a Provider it still has the\n caller's children to render verbatim (incremental adoption). The\n provider-only compositions — `ModeSwitch`, `AdvancedFields`, `FormHelp` —\n read it with the throwing `getFieldPolicyContext()`: their whole output is\n derived from the resolved policy, so degrading would render an empty or\n absent control instead of surfacing the missing Provider. Do not convert one\n of them to the non-throwing accessor in isolation (#2272).\n- **One provider per form.** `FieldPolicyProvider` renders only\n `{@render children?.()}`, so a host wanting `FormHelp` in a page header\n extends the SAME provider over the header rather than hoisting the component\n out. It must not add a second: each provider constructs its own\n `FieldPolicyModeStore` and `setContext` shadows for the subtree, so a\n `FormHelp` above a nested provider stops tracking the `ModeSwitch` inside it.\n `ObjectForm` builds its own provider, so never wrap it in another; its\n `actions` snippet renders INSIDE that provider (context resolves at the render\n site), which is the only way to reach `FormHelp` through it — below the\n fields, since there is no header seam (#2289).\n\n## Defaults control panel (#2050)\n\n- `buildFieldPolicySettingsCatalog()` is the server-side, URL/GET-driven\n catalog builder. It structurally targets `SettingsCatalog`, but this package\n must not import `smrt-svelte`; hosts inject `SettingsCatalog` into\n `FieldPolicyControlPanel` and retain their own route and transport adapters.\n- `policyAudit` is the only routed organization roll-up. It requires\n `fields.policy.manage`, returns only the caller tenant's editable rows and\n read-only app summaries, and represents other users strictly as per-field\n counts. It resolves only requested page refs; never pre-resolve the catalog.\n- Display code/app/org values by replaying the explained resolver layers, not\n by independently calculating precedence. Reset and drift prune are ordinary\n model deletes, so existing scope/permission validation remains authoritative.\n The panel asks for an explicit confirmation before either destructive action;\n SSR hosts can inject that confirmation decision instead of relying on\n `window.confirm`.\n- `fieldPolicyControlPanelNavItem()` is a structural AdminShell tenant-nav\n seam. It never imports `smrt-svelte` or `smrt-web`; the host supplies the\n returned entry and must enforce its real route permission server-side.\n\n## Recipe: `fields.form-customization` (#3719)\n\n`src/recipes.ts` declares `FormCustomizationRecipe`\n(help: `src/form-customization.recipe.md`), emitted in `manifest.json` and\n`smrt-knowledge.json` `recipes`. Contract: [core recipes](../core/agents/recipes.md).\n\n- Models: the four policy/learning tables. No `nav`, deliberately: the tables\n have no generated read surface, so the one management UI is the declared\n `settings-panel` surface `@happyvertical/smrt-fields/svelte#FieldPolicyControlPanel`.\n That component is not zero-prop: the host still injects `SettingsCatalog`,\n the adapter, and loads `buildFieldPolicySettingsCatalog()` data server-side.\n- `runtime = 'server'` is the truthful value while #3618 is open: the root\n entry (resolver, `usage-schedules`) statically imports core's node-only\n `import-workspace-module`. The `/svelte` components are browser-safe because\n they render an already-resolved policy. Flip to `'both'` only when #3618 lands\n and a browser build of the root entry is proven.\n- No `demoSeed` (no fixture exists) and no `playground` surface: the playground\n export is a registry object, not a component. Help field references must\n point at `FieldPolicy` fields that carry `@field({ description })`.\n\n## Related\n\n- `@happyvertical/smrt-prompts` / `smrt-languages` / `smrt-features` — the\n same architecture family (override rows + layered resolver + TTL cache)\n- Core `FieldUIHints` (#2046) — the `@field({ ui })` code seed this package\n resolves over\n",
1216
+ "agentDoc": "# smrt-fields\n\nLayered field policy store and resolution engine (epic #2045). Personalizes\nper-field `{defaultValue, visibility, help, label, order, locked}` for any\n`@smrt()` object at app, tenant, and user scope over the code seed.\n\n## Core pieces\n\n- `FieldPolicy` (`_smrt_field_policies` table) — sparse override rows keyed\n `(objectRef, fieldName, scopeType, scopeKey)`; NULL column = inherit from\n the lower layer, reset = row DELETE (later lower-layer changes flow through)\n- `FieldPolicyCollection` — write surface plus the `resolveBatch` custom\n collection-scoped action (`POST /<collection>/resolve`). NO generated\n surface exposes read verbs: API `list`/`get` on this non-tenant-scoped\n model would enumerate every tenant's and user's rows; the model's CLI is\n writes-only (the generated CLI invokes over HTTP, and the cli↔api\n coherence gate rejects CLI entries without API routes); the runtime\n CLI/MCP surfaces are closed by the collection config (ContentContributions\n precedent). Reads go through `resolveBatch` (context-scoped) or the\n server-side resolver. Keep the api include lists in lockstep: a decorated\n collection's config is the RUNTIME registry authority for its item class,\n while build-time generation reads each manifest object's own config. Both\n transports dispatch the action: generated SvelteKit routes natively, and\n core's runtime `APIGenerator` via its decorator-route dispatch\n (single-segment collection-scoped paths; multi-segment custom paths remain\n SvelteKit-only).\n- `resolveFieldPolicy(objectRef, { tenantId, userId, db })` — merged policy\n- Portable cookbook policy resolution: [agents/cookbook-policy.md](agents/cookbook-policy.md).\n- `resolveFieldPolicyExplained(...)` — merged policy plus ordered per-layer\n contributions (code/app/tenant/user) for gear/admin UIs (#2049/#2050)\n\n## Resolution layers (priority low → high)\n\n1. Code seed — manifest field defaults, `description` as help, `_meta.ui`\n hints (#2046: `basic`/`group`/`order`/`locked`; cold-start rule: no\n `basic` markers ⇒ everything basic, any marker ⇒ unmarked fields advanced)\n2. App rows — `scopeType: 'app'`, `tenantId`/`userId` null\n3. Tenant rows — hierarchy walk root → leaf via an injected\n `tenantHierarchyLoader` (smrt-features shape); the default loader\n uses `@happyvertical/smrt-users`' `TenantCollection`; an injected loader\n may return no provider (or no chain for a tenant), which falls back to a\n flat single-tenant chain. `smrt-users` itself is a required Fields runtime\n dependency for policy authorization, not an optional hierarchy dependency.\n A node that breaks permission\n inheritance discards every earlier tenant contribution (chain-structural),\n so only the suffix from the LAST break participates — in merging AND in\n the explained layers, which therefore replay to the merged result\n4. User rows — keyed by `userId` alone (preferences follow the user); both\n defaults AND visibility resolve through this tier\n\n## Invariants\n\n- **Scope shape**: app ⇒ `tenantId`+`userId` null; tenant ⇒ only `tenantId`;\n user ⇒ only `userId`. `scopeKey` (`userId ?? tenantId ?? '__app__'`) exists\n ONLY to keep the `conflictColumns` unique index total — never read it for\n scoping logic.\n- **Manifest as definition registry**: writes validate against the live\n `ObjectRegistry` (never checked-in manifest.json artifacts): unknown\n objectRef/fieldName rejected; defaults type-checked against the field type;\n system fields, relationship pseudo-fields, and STI meta storage fields are\n not policy-addressable (the resolver excludes them, so rows would silently\n never apply).\n- **Security rail**: defaults are refused on `transient`, `sensitive`, and\n `readPermission`-gated fields (both top-level and `_meta` flags checked).\n Reference-field (`foreignKey`/`crossPackageRef`) defaults must be UUID\n strings unless the field declares `idType: 'text'` — the columns are\n native UUID on PostgreSQL/DuckDB and a non-UUID default would fail at\n insert time. `resolveBatch` responses omit sensitive/read-permission-gated\n fields for every caller (fail closed) and transient fields\n (client-emission parity).\n- **Required-field invariant**: demoting a required field to\n advanced/hidden requires a usable resolved default (not null/empty) —\n enforced at write time AND re-enforced at resolution (a required field with\n no usable default always resolves `basic`, flagged `visibilityForced`).\n- **Org lock**: `locked` may be set on app/tenant rows only; while the\n code/app/tenant tiers resolve locked, user-scope writes are rejected and\n existing user rows are skipped at resolution.\n- **Write-time org checks reuse the resolver**: the required-demotion default\n and the user-write lock are computed by `resolveFieldPolicy` over the org\n tiers (default hierarchy loader), so cascading ancestor-tenant defaults and\n locks are honored at save time too. On updates the persisted row is excluded\n from projected lower-layer resolution, so clearing the row's only default\n while demoting a required field is rejected before mutation; that projected\n lookup bypasses the shared cache. The resolver-side safety net remains\n authoritative when a different row is later deleted.\n- **Isolation — a MISSING identity component DENIES, it never skips.** This\n is the package rule; both the write guard\n (`FieldPolicy.assertScopeOwnedByAmbientContext`) and the read guard\n (`assertResolutionAllowedInContext`) obey it. A non-bypass tenant context\n may only resolve/write its own tenant, and the user tier only for its own\n user id — a context carrying permissions but NO `userId` (no `resolveUserId`\n hook configured: API-key auth, service principals, background jobs, a bare\n `withTenant({ tenantId })`) may not touch the user tier at all. Skipping\n that check instead of denying it was a live ownership bypass: user rows are\n `tenantId: null` by design, so nothing else contains such a write. App-scope\n writes inside a tenant context require super-admin bypass. `fields.policy.manage`\n authorizes app/tenant policy mutations; `fields.policy.personalize` authorizes\n only the caller's user tier (default-seeded for built-in roles). With NO ambient\n identity at all (tenancy ALS never entered), policy writes/deletes fail closed;\n trusted system and super-admin contexts retain their explicit bypasses.\n Context-LESS *reads* stay allowed because `resolveFieldPolicy` is a trusted\n server-side API. `save()`/`delete()`\n on an existing row additionally authorize against the row's PERSISTED\n scope, looked up by primary key AND — because a generated create always\n mints a fresh UUID while the `conflictColumns` upsert still replaces the\n occupant — by NATURAL key. `resolveBatch` takes identity exclusively from\n the ambient context; the request body cannot select another tenant or user.\n- **Scope attribution**: inside an ambient context the model DERIVES a\n missing `tenantId` (tenant rows) or `userId` (user rows) from that context,\n and always stamps `updatedBy` from it. Core's mass-assignment guard treats\n `tenantId` as server-managed and strips it from every generated write body\n while `FieldPolicy` is deliberately not `@TenantScoped`, so without this the\n org tier is write-dead over REST/SvelteKit (scope-shape validation throws).\n Deriving grants nothing — the ownership guard already pinned the value to\n the ambient one. An explicit value is never overwritten, so a super-admin\n bypass caller writing ANOTHER tenant's row must go through a server-side\n model call; the generated routes still strip it.\n\n## Caching and invalidation\n\n- Resolver results cached per\n `(dbNamespace, objectRef, tenantId, userId, hierarchyLoader)` with a 30s TTL\n (`cache.ts` mirrors smrt-prompts' `getDbNamespace`). The loader identity is\n part of the key because an injected `tenantHierarchyLoader` yields a\n different ancestor chain — and so different defaults/locks — for the same\n `(db, objectRef, tenant, user)`; it goes LAST so the `(db, objectRef)`\n prefix scan still invalidates every loader's entries.\n- `FieldPolicy.save()`/`.delete()` invalidate ALL entries for the row's\n `(db, objectRef)` — coarser than prompts because tenant hierarchy makes a\n parent-tenant row affect every descendant's resolution.\n- `_smrt_field_policies` rows do NOT ride the client change feed: core's\n change-feed writer deliberately skips `_smrt_`-prefixed system tables, and\n the emit side is private. Live client invalidation is a core-side decision;\n do not add custom push/emit paths here.\n\n## Gotchas\n\n- Defaults have TWO explicit constructor channels, never sniffed:\n `defaultValue` is ALREADY JSON-encoded (the wire contract — generated write\n routes hand the request body straight to the constructor, and #2049's gear\n posts `JSON.stringify(draft.defaultValue)`), while `defaultValueRaw` is a\n plain value that is always serialized, strings included. Passing both throws.\n One option cannot carry both meanings: `'\"TBD\"'` and `'TBD'` are\n indistinguishable, so `{ defaultValue: 'Net 30' }` is a parse error that\n names `defaultValueRaw` in its message. `setDefaultValue()` is the\n method-level plain channel.\n- The sort-order column is `displayOrder` (resolved output exposes `order`):\n a column literally named `order` is an SQL keyword the runtime INSERT path\n does not quote.\n- `FieldPolicy` deliberately has NO class-level `@TenantScoped` (the\n prompts/features precedent): resolution legitimately reads app rows and\n ancestor-tenant rows, which the tenancy interceptor would block. Isolation\n is enforced at the resolver/save boundaries instead.\n- Identity changes (objectRef/fieldName/scope) on a persisted row go through\n delete-then-insert (transactional when the driver supports it) because the\n natural-key upsert would otherwise collide with the primary key.\n- `FieldPolicyCollection` MUST repeat FieldPolicy's `conflictColumns`. A\n decorated collection emits its OWN manifest schema for the item's table, and\n without the natural key that schema falls back to SmrtObject's default unique\n `(slug, context)` index; manifest-driven migrations aggregate both onto\n `_smrt_field_policies`, where the stray index rejects legitimate layered rows\n (all policy rows have NULL slug/context). The runtime registry cannot catch\n this — `getAllSchemas()` is keyed by TABLE name, so the two schemas collapse\n into one entry. Pinned against the generated manifest in\n `generated-surfaces.test.ts`.\n- `withSystemContext()` does NOT unlock tenant/user-scope writes:\n `getCurrentTenant()` returns undefined inside it, so the context-absent rule\n rejects those tiers before any bypass check. Seeds and migrations that must\n write org/user rows use a `superAdminBypass` context instead.\n- The MODEL's `cli`/`mcp` decorator config is dead at runtime: the registry\n re-registers the item slot with the COLLECTION's config wholesale, so\n `FieldPolicyCollection`'s `cli: false, mcp: false` is what actually closes\n those surfaces. Keep both in lockstep anyway — build-time generation reads\n the model's own config. Related: `ObjectRegistry.getTableName(\n 'FieldPolicyCollection')` resolves to the UNPREFIXED collection fallback\n `field_policies`; persistence uses the item class\n (`_smrt_field_policies`), and both are pinned in\n `generated-surfaces.test.ts`.\n\n## Svelte generated forms (#2049)\n\n- `ObjectForm` accepts direct generated `fields` plus a resolved `policy` for\n SSR and explicit hosts, or accepts only `objectRef` beneath an\n `ObjectFormSourceProvider`. `ObjectFormSourceRegistry` is per app and maps\n canonical refs to generated web collection definitions before calling the\n generated `resolveBatch` custom action. It uses structural types only: this\n package must never import `smrt-web`.\n- Generated custom-action clients resolve `Promise<any>`; validate their\n `policies[objectRef]` response at the registry boundary and fail closed on a\n missing/mismatched definition or policy. The component renders an accessible\n loading state and alert rather than a partial form.\n- Browser manifest types are `text`, `integer`, `decimal`, `boolean`,\n `datetime`, `json`, `foreignKey`, and `crossPackageRef`; there is no `select`\n wire type. Apps use the per-app `FieldInputRegistry.registerField` seam for\n select-like widgets. Reference fields intentionally default to identifier\n inputs unless an app supplies a chooser.\n- `policyToVisibleColumnIds(policy, columns)` feeds smrt-ui `DataTable`'s\n `visibleColumnIds`; it filters policy-hidden mapped fields and restricted\n (`sensitive`/`secret` or `readable: false`) columns, preserves unrestricted\n unmapped computed/action columns, and cannot reveal a static `column.hidden`\n column. Pass `authorizedColumnIds` only when the host explicitly authorizes a\n restricted column; `readable: true` alone does not override sensitivity.\n- `policyToDataSurfaceDescriptor(policy, descriptor)` is the corresponding\n mounted DataSurface adapter. It carries effective labels, help text, order,\n visibility, readable/capability state, and operator/query allowlists into\n discovery metadata while retaining unrestricted computed, row-key, selection,\n and action columns. Static or resolved-policy-hidden structural columns are\n omitted from discovery (the row key remains only as a non-readable identity\n column), and actions that explicitly depend on hidden columns are removed.\n Sensitive/secret and `readable: false` columns also fail closed when omitted\n from the resolved policy; a host must pass `authorizedColumnIds` explicitly\n to expose a restricted descriptor column, and authorization sets the\n effective `readable` metadata to `true` so capabilities and query allowlists\n cannot contradict it.\n- **Two-tier context contract.** `PolicyField` alone reads the context with\n `tryGetFieldPolicyContext()`, because outside a Provider it still has the\n caller's children to render verbatim (incremental adoption). The\n provider-only compositions — `ModeSwitch`, `AdvancedFields`, `FormHelp` —\n read it with the throwing `getFieldPolicyContext()`: their whole output is\n derived from the resolved policy, so degrading would render an empty or\n absent control instead of surfacing the missing Provider. Do not convert one\n of them to the non-throwing accessor in isolation (#2272).\n- **One provider per form.** `FieldPolicyProvider` renders only\n `{@render children?.()}`, so a host wanting `FormHelp` in a page header\n extends the SAME provider over the header rather than hoisting the component\n out. It must not add a second: each provider constructs its own\n `FieldPolicyModeStore` and `setContext` shadows for the subtree, so a\n `FormHelp` above a nested provider stops tracking the `ModeSwitch` inside it.\n `ObjectForm` builds its own provider, so never wrap it in another; its\n `actions` snippet renders INSIDE that provider (context resolves at the render\n site), which is the only way to reach `FormHelp` through it — below the\n fields, since there is no header seam (#2289).\n\n## Defaults control panel (#2050)\n\n- `buildFieldPolicySettingsCatalog()` is the server-side, URL/GET-driven\n catalog builder. It structurally targets `SettingsCatalog`, but this package\n must not import `smrt-svelte`; hosts inject `SettingsCatalog` into\n `FieldPolicyControlPanel` and retain their own route and transport adapters.\n- `policyAudit` is the only routed organization roll-up. It requires\n `fields.policy.manage`, returns only the caller tenant's editable rows and\n read-only app summaries, and represents other users strictly as per-field\n counts. It resolves only requested page refs; never pre-resolve the catalog.\n- Display code/app/org values by replaying the explained resolver layers, not\n by independently calculating precedence. Reset and drift prune are ordinary\n model deletes, so existing scope/permission validation remains authoritative.\n The panel asks for an explicit confirmation before either destructive action;\n SSR hosts can inject that confirmation decision instead of relying on\n `window.confirm`.\n- `fieldPolicyControlPanelNavItem()` is a structural AdminShell tenant-nav\n seam. It never imports `smrt-svelte` or `smrt-web`; the host supplies the\n returned entry and must enforce its real route permission server-side.\n\n## Recipe: `fields.form-customization` (#3719)\n\n`src/recipes.ts` declares `FormCustomizationRecipe`\n(help: `src/form-customization.recipe.md`), emitted in `manifest.json` and\n`smrt-knowledge.json` `recipes`. Contract: [core recipes](../core/agents/recipes.md).\n\n- Models: the four policy/learning tables. No `nav`, deliberately: the tables\n have no generated read surface, so the one management UI is the declared\n `settings-panel` surface `@happyvertical/smrt-fields/svelte#FieldPolicyControlPanel`.\n That component is not zero-prop: the host still injects `SettingsCatalog`,\n the adapter, and loads `buildFieldPolicySettingsCatalog()` data server-side.\n- `runtime = 'server'` is the truthful value while #3618 is open: the root\n entry (resolver, `usage-schedules`) statically imports core's node-only\n `import-workspace-module`. The `/svelte` components are browser-safe because\n they render an already-resolved policy. Flip to `'both'` only when #3618 lands\n and a browser build of the root entry is proven.\n- No `demoSeed` (no fixture exists) and no `playground` surface: the playground\n export is a registry object, not a component. Help field references must\n point at `FieldPolicy` fields that carry `@field({ description })`.\n\n## Related\n\n- `@happyvertical/smrt-prompts` / `smrt-languages` / `smrt-features` — the\n same architecture family (override rows + layered resolver + TTL cache)\n- Core `FieldUIHints` (#2046) — the `@field({ ui })` code seed this package\n resolves over\n",
1217
+ "moduleDocs": [
1218
+ {
1219
+ "path": "agents/cookbook-policy.md",
1220
+ "module": "cookbook-policy",
1221
+ "content": "# Portable cookbook policy resolution\n\n`resolveFieldPolicy(objectRef, { cookbook, ...context })` inserts the active\ncookbook rows after stored app rows and before tenant/user tiers, using the same\n`resolveFieldPolicyLayers` kernel as `./policy`. It bypasses both cache reads and\nwrites so switching cookbook documents never leaks a prior document's policy.\nDatabase authorization, surviving tenant-chain selection, org locks and the\nrequired-field safety net remain unchanged. Portable defaults use the existing\nfield-type/security validation; invalid encoded JSON contributes no override.\nThe browser boundary omits restricted/system metadata; the trusted server\nresolver still includes sensitive fields for its existing batch projection to\nfilter. `readOnly` is portable record-value metadata, not a new database column\nand not the existing `locked` policy-customization flag.\n\nThe `./policy` browser-safe entry extracts existing seed/merge helpers. It imports\nneither the registry, database, tenancy nor model runtime. Client components must\nnever import the server resolver/root. `resolveCookbookFieldPolicy` accepts generated\npublic fields and optional manifest-proven `replacedQualifiedNames`.\n\n`cookbookPolicyLayers` selects raw rows by canonical identity and proven provider\naliases, preserving sparse contributions. Provider rows apply in document order,\nthen effective app rows, so an app label cannot erase the provider's hidden/default\nmetadata. Unrelated same-name models never match. The server uses the live registry's\nsame replacement provenance and the same layer selector; stored policy scope and\nauthorization remain at their original boundary.\n\n## Read-only linked display labels\n\n`getObjectFieldMap` keeps the registry's persisted fields unchanged and adds the\nvirtual `displayLabel` only for a declared, validated one-hop projection. It reuses\n`resolveDisplayLabelProjection`, public relationship/effective target resolution,\n`displayLabelFieldProblem` and the existing security metadata helpers. No collection\nis instantiated and no SQL runs to enumerate policy fields. Actual reads retain the\ncollection's stricter row/tenant/STI authorization and scoped SQL projection.\n\nThe synthetic field matches generated web metadata: text, basic, static `readonly`.\nIts label/visibility may be customized by stored or raw cookbook rows. Static\nread-only metadata is a code-seed contribution and cannot be cleared by a row;\npolicy defaults are rejected at write and resolution boundaries. Registry field maps\nand application schema never acquire a persisted name column.\n\nThe resolver's real Commerce Customer -> Profile canary uses SQLite, actual\ncollections, public runtime registry metadata, the existing web-definition emitter,\nstored policies and raw cookbook rows. The existing `manifestEntry` test fixture\nadapts runtime metadata; this test does not depend on an unrelated Commerce build. It checks Profile names,\nserver/browser policy parity, relabel/hide selection, immutable read-only/default\nrails, and rejection when the effective target becomes sensitive. No Commerce source\nor helper is copied into Fields.\n"
1222
+ }
1223
+ ],
1215
1224
  "recipes": [
1216
1225
  {
1217
1226
  "id": "fields.form-customization",
@@ -5,10 +5,10 @@ description: "Layered field policy store and resolver (defaults, visibility tier
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-05T15:48:19Z"
8
+ at: "2026-11-11T08:10:47Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:b5da9360239e879f176aecf30b728ff2f2e63236b0174e5a79d9544d4518b0a8"
11
+ source_revision: "sha256:a90ab07e867bceea21d2b6a38b710e3506cfc8d35f21c6f6d955e213ddb1e24c"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/fields/package.json"
@@ -16,6 +16,9 @@ sources:
16
16
  - id: "agents"
17
17
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/fields/AGENTS.md"
18
18
  title: "@happyvertical/smrt-fields packages/fields/AGENTS.md"
19
+ - id: "agents-2"
20
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/fields/agents/cookbook-policy.md"
21
+ title: "@happyvertical/smrt-fields packages/fields/agents/cookbook-policy.md"
19
22
  ---
20
23
 
21
24
  # @happyvertical/smrt-fields
@@ -30,6 +33,7 @@ sources:
30
33
  ## Documentation
31
34
 
32
35
  - `packages/fields/AGENTS.md`
36
+ - `packages/fields/agents/cookbook-policy.md`
33
37
 
34
38
  ## Framework dependencies
35
39
 
@@ -51,6 +55,7 @@ sources:
51
55
  - `./manifest`
52
56
  - `./manifest.json`
53
57
  - `./playground`
58
+ - `./policy`
54
59
  - `./svelte`
55
60
 
56
61
  ## Models