@happyvertical/smrt-fields 0.40.61 → 0.40.62

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 (68) hide show
  1. package/README.md +125 -112
  2. package/dist/chunks/FieldPolicyCollection--RxukfCX.js +1218 -0
  3. package/dist/chunks/FieldPolicyCollection--RxukfCX.js.map +1 -0
  4. package/dist/collections/FieldPolicySuggestionCollection.d.ts +160 -0
  5. package/dist/collections/FieldPolicySuggestionCollection.d.ts.map +1 -0
  6. package/dist/collections/FieldUsageCounterCollection.d.ts +143 -0
  7. package/dist/collections/FieldUsageCounterCollection.d.ts.map +1 -0
  8. package/dist/deterministic-id.d.ts +18 -0
  9. package/dist/deterministic-id.d.ts.map +1 -0
  10. package/dist/field-definitions.d.ts +8 -0
  11. package/dist/field-definitions.d.ts.map +1 -1
  12. package/dist/index.d.ts +8 -2
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1565 -1077
  15. package/dist/index.js.map +1 -1
  16. package/dist/manifest.json +1442 -188
  17. package/dist/models/FieldPolicySuggestion.d.ts +132 -0
  18. package/dist/models/FieldPolicySuggestion.d.ts.map +1 -0
  19. package/dist/models/FieldUsageCounter.d.ts +178 -0
  20. package/dist/models/FieldUsageCounter.d.ts.map +1 -0
  21. package/dist/models/FieldUsageReportReceipt.d.ts +25 -0
  22. package/dist/models/FieldUsageReportReceipt.d.ts.map +1 -0
  23. package/dist/smrt-knowledge.json +402 -5
  24. package/dist/svelte/__tests__/FieldPolicyControlPanel.test.js +54 -0
  25. package/dist/svelte/__tests__/ObjectForm.test.js +131 -0
  26. package/dist/svelte/__tests__/UsageLearning.test.js +140 -0
  27. package/dist/svelte/__tests__/fixtures/ObjectFormActionsFixture.svelte +21 -4
  28. package/dist/svelte/__tests__/fixtures/ObjectFormActionsFixture.svelte.d.ts +5 -1
  29. package/dist/svelte/__tests__/fixtures/ObjectFormActionsFixture.svelte.d.ts.map +1 -1
  30. package/dist/svelte/__tests__/fixtures/SuggestionGearFixture.svelte +23 -0
  31. package/dist/svelte/__tests__/fixtures/SuggestionGearFixture.svelte.d.ts +10 -0
  32. package/dist/svelte/__tests__/fixtures/SuggestionGearFixture.svelte.d.ts.map +1 -0
  33. package/dist/svelte/components/FieldPolicyControlPanel.svelte +28 -1
  34. package/dist/svelte/components/FieldPolicyControlPanel.svelte.d.ts +3 -0
  35. package/dist/svelte/components/FieldPolicyControlPanel.svelte.d.ts.map +1 -1
  36. package/dist/svelte/components/FieldPolicyGearButton.svelte +8 -1
  37. package/dist/svelte/components/FieldPolicyGearButton.svelte.d.ts.map +1 -1
  38. package/dist/svelte/components/FieldPolicyGearProvider.svelte +34 -0
  39. package/dist/svelte/components/FieldPolicyGearProvider.svelte.d.ts +3 -0
  40. package/dist/svelte/components/FieldPolicyGearProvider.svelte.d.ts.map +1 -1
  41. package/dist/svelte/components/FieldPolicySuggestionQueue.svelte +135 -0
  42. package/dist/svelte/components/FieldPolicySuggestionQueue.svelte.d.ts +11 -0
  43. package/dist/svelte/components/FieldPolicySuggestionQueue.svelte.d.ts.map +1 -0
  44. package/dist/svelte/components/ObjectForm.svelte +91 -2
  45. package/dist/svelte/components/ObjectForm.svelte.d.ts +11 -1
  46. package/dist/svelte/components/ObjectForm.svelte.d.ts.map +1 -1
  47. package/dist/svelte/gear-context.svelte.d.ts +2 -0
  48. package/dist/svelte/gear-context.svelte.d.ts.map +1 -1
  49. package/dist/svelte/index.d.ts +6 -1
  50. package/dist/svelte/index.d.ts.map +1 -1
  51. package/dist/svelte/index.js +4 -1
  52. package/dist/svelte/suggestions.d.ts +38 -0
  53. package/dist/svelte/suggestions.d.ts.map +1 -0
  54. package/dist/svelte/suggestions.js +68 -0
  55. package/dist/svelte/usage-capture.d.ts +63 -0
  56. package/dist/svelte/usage-capture.d.ts.map +1 -0
  57. package/dist/svelte/usage-capture.js +61 -0
  58. package/dist/types.d.ts +40 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/dist/types.js +7 -1
  61. package/dist/types.js.map +1 -1
  62. package/dist/usage-learning.d.ts +201 -0
  63. package/dist/usage-learning.d.ts.map +1 -0
  64. package/dist/usage-schedules.d.ts +110 -0
  65. package/dist/usage-schedules.d.ts.map +1 -0
  66. package/dist/users-module.d.ts +30 -0
  67. package/dist/users-module.d.ts.map +1 -0
  68. package/package.json +8 -8
package/dist/types.d.ts CHANGED
@@ -272,5 +272,45 @@ export interface FieldPolicyEditorStateDenied {
272
272
  status: 403;
273
273
  }
274
274
  export type FieldPolicyEditorStateResult = FieldPolicyEditorState | FieldPolicyEditorStateDenied;
275
+ export type FieldPolicySuggestionKind = 'promote' | 'default';
276
+ export declare const FIELD_POLICY_SUGGESTION_KINDS: readonly FieldPolicySuggestionKind[];
277
+ export type FieldPolicySuggestionStatus = 'pending' | 'accepted' | 'dismissed';
278
+ export declare const FIELD_POLICY_SUGGESTION_STATUSES: readonly FieldPolicySuggestionStatus[];
279
+ /** One bounded client-side form submission sample. */
280
+ export interface FieldUsageReportEntry {
281
+ objectRef: string;
282
+ fieldName: string;
283
+ value?: unknown;
284
+ /** Used only for value-less samples; server comparison wins when present. */
285
+ matchedDefault?: boolean;
286
+ }
287
+ export interface FieldUsageReportResult {
288
+ accepted: number;
289
+ dropped: number;
290
+ }
291
+ export interface FieldPolicySuggestionData {
292
+ id: string;
293
+ objectRef: string;
294
+ fieldName: string;
295
+ tenantId: string;
296
+ kind: FieldPolicySuggestionKind;
297
+ proposedValue: string | null;
298
+ evidence: Record<string, unknown>;
299
+ status: FieldPolicySuggestionStatus;
300
+ cooldownUntil: string | null;
301
+ decidedBy: string | null;
302
+ decidedAt: string | null;
303
+ }
304
+ export interface PendingFieldPolicySuggestionsResult {
305
+ suggestions: FieldPolicySuggestionData[];
306
+ total: number;
307
+ }
308
+ export interface AcceptFieldPolicySuggestionResult {
309
+ suggestion: FieldPolicySuggestionData;
310
+ policyRowId: string;
311
+ }
312
+ export interface DismissFieldPolicySuggestionResult {
313
+ suggestion: FieldPolicySuggestionData;
314
+ }
275
315
  export type { SmrtClassOptions };
276
316
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AAElC;;;;;;;GAOG;AACH,MAAM,MAAM,oBAAoB,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE7D;;;;;;;GAOG;AACH,MAAM,MAAM,qBAAqB,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC;AAEpE;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,YAAY,CAAC;AAEpD,eAAO,MAAM,wBAAwB,EAAE,SAAS,oBAAoB,EAInE,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,SAAS,qBAAqB,EAIrE,CAAC;AAEF,MAAM,WAAW,kBAAmB,SAAQ,iBAAiB;IAC3D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,oBAAoB,CAAC;IACjC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB;;;;;;;;;;;;;;OAcG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;;;OAKG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAC1C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM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C,MAAM,EAAE,2BAA2B,CAAC;IACpC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,mCAAmC;IAClD,WAAW,EAAE,yBAAyB,EAAE,CAAC;IACzC,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,iCAAiC;IAChD,UAAU,EAAE,yBAAyB,CAAC;IACtC,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,kCAAkC;IACjD,UAAU,EAAE,yBAAyB,CAAC;CACvC;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
package/dist/types.js CHANGED
@@ -10,7 +10,13 @@ var FIELD_POLICY_VISIBILITIES = [
10
10
  "advanced",
11
11
  "hidden"
12
12
  ];
13
+ var FIELD_POLICY_SUGGESTION_KINDS = ["promote", "default"];
14
+ var FIELD_POLICY_SUGGESTION_STATUSES = [
15
+ "pending",
16
+ "accepted",
17
+ "dismissed"
18
+ ];
13
19
  //#endregion
14
- export { APP_FIELD_POLICY_SCOPE_KEY, FIELD_POLICY_SCOPE_TYPES, FIELD_POLICY_VISIBILITIES };
20
+ export { APP_FIELD_POLICY_SCOPE_KEY, FIELD_POLICY_SCOPE_TYPES, FIELD_POLICY_SUGGESTION_KINDS, FIELD_POLICY_SUGGESTION_STATUSES, FIELD_POLICY_VISIBILITIES };
15
21
 
16
22
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n SmrtClassOptions,\n SmrtObjectOptions,\n} from '@happyvertical/smrt-core';\n\n/**\n * Scope tier a {@link FieldPolicy} row belongs to.\n *\n * Resolution precedence is code seed → `app` → `tenant` (hierarchy walk,\n * root → leaf) → `user`. Unlike smrt-features (which ships only\n * `global`/`tenant`), the user tier is implemented end to end here — both\n * defaults and visibility resolve through it.\n */\nexport type FieldPolicyScopeType = 'app' | 'tenant' | 'user';\n\n/**\n * Visibility tier for a field in generated/consuming form UIs.\n *\n * - `basic`: shown before the advanced disclosure\n * - `advanced`: shown behind the advanced disclosure\n * - `hidden`: not rendered (requires the field to be optional or have a\n * resolved default — the required-field invariant)\n */\nexport type FieldPolicyVisibility = 'basic' | 'advanced' | 'hidden';\n\n/**\n * `scopeKey` value for app-scope rows. `scopeKey` exists ONLY so the\n * `conflictColumns` unique index stays total while `tenantId`/`userId` are\n * nullable (nullable columns would allow duplicate NULL rows) — the same\n * trick as `PromptOverride.context`.\n */\nexport const APP_FIELD_POLICY_SCOPE_KEY = '__app__';\n\nexport const FIELD_POLICY_SCOPE_TYPES: readonly FieldPolicyScopeType[] = [\n 'app',\n 'tenant',\n 'user',\n];\n\nexport const FIELD_POLICY_VISIBILITIES: readonly FieldPolicyVisibility[] = [\n 'basic',\n 'advanced',\n 'hidden',\n];\n\nexport interface FieldPolicyOptions extends SmrtObjectOptions {\n objectRef?: string;\n fieldName?: string;\n scopeType?: FieldPolicyScopeType;\n tenantId?: string | null;\n userId?: string | null;\n /**\n * ENCODED channel: an already-JSON-encoded default, exactly as the column\n * stores it (`'\"Net 30\"'`, `'42'`, `'null'`), or `null` to inherit.\n *\n * This is the wire contract: the generated write routes hand the request\n * body straight to the constructor, and the #2049/#2050 gear posts\n * `JSON.stringify(draft.defaultValue)`. It must therefore keep meaning\n * \"already encoded\" — auto-serializing here would double-encode every gear\n * write.\n *\n * Use {@link FieldPolicyOptions.defaultValueRaw} for a plain value. The two\n * are mutually exclusive: `'\"TBD\"'` and `'TBD'` are indistinguishable once\n * a single option carries both meanings, so the channel must be explicit\n * rather than sniffed.\n */\n defaultValue?: string | null;\n /**\n * PLAIN channel: any value, always serialized — strings included. The\n * constructor-option twin of {@link FieldPolicy.setDefaultValue}, so\n * `{ defaultValueRaw: 'Net 30' }` stores `'\"Net 30\"'` rather than the\n * unparseable literal `Net 30`.\n */\n defaultValueRaw?: unknown;\n visibility?: FieldPolicyVisibility | null;\n help?: string | null;\n label?: string | null;\n displayOrder?: number | null;\n locked?: boolean | null;\n updatedBy?: string | null;\n}\n\n/**\n * The sparse contribution of one layer (code seed or one stored row).\n *\n * `default` is boxed so an explicit JSON `null` default (meaning \"default to\n * null\") stays distinguishable from \"this layer contributes no default\".\n */\nexport interface FieldPolicyDelta {\n default?: { value: unknown };\n visibility?: FieldPolicyVisibility;\n help?: string;\n label?: string;\n order?: number;\n locked?: boolean;\n}\n\n/** One layer's contribution to a field's resolved policy (explain variant). */\nexport interface FieldPolicyLayerContribution {\n layer: 'code' | 'app' | 'tenant' | 'user';\n /** Chain node id for `tenant` layers (root → leaf order). */\n tenantId?: string;\n /** User id for the `user` layer. */\n userId?: string;\n delta: FieldPolicyDelta;\n}\n\n/** Fully merged policy for a single field. */\nexport interface ResolvedFieldPolicy {\n fieldName: string;\n /** True when any layer resolved a default (including an explicit null). */\n hasDefault: boolean;\n /** Parsed default value; `undefined` when {@link hasDefault} is false. */\n defaultValue: unknown;\n visibility: FieldPolicyVisibility;\n help: string | null;\n label: string | null;\n order: number | null;\n /** Grouping key — code-seed only (`ui.group`), not overridable by rows. */\n group: string | null;\n locked: boolean;\n /** Mirror of the manifest required flag (nullable fields are optional). */\n required: boolean;\n /**\n * True when the resolver forced `basic` visibility because the field is\n * required and no usable default resolved (the resolver-side safety net for\n * the required-field invariant).\n */\n visibilityForced?: boolean;\n}\n\n/** Merged policy for every field of one object. */\nexport interface ResolvedObjectFieldPolicy {\n objectRef: string;\n fields: Record<string, ResolvedFieldPolicy>;\n}\n\n/**\n * Explain variant: merged result plus the ordered per-layer contributions for\n * each field, so admin/gear UIs (#2049/#2050) never re-derive precedence.\n * Layers are listed in application order (code, app, tenant chain root → leaf,\n * user) and contain ONLY contributions that survive into the merged result:\n * tenant ancestors discarded by a permission-inheritance break and user rows\n * suppressed by an effective org lock are omitted, so sequentially replaying\n * the listed deltas reproduces the merged policy.\n */\nexport interface ExplainedObjectFieldPolicy extends ResolvedObjectFieldPolicy {\n layers: Record<string, FieldPolicyLayerContribution[]>;\n}\n\n/** Minimal tenant node consumed by the hierarchy walk (mirrors smrt-features). */\nexport interface FieldPolicyTenantNode {\n id: string;\n inheritPermissions: boolean;\n cascadePermissions: boolean;\n}\n\n/** Provider returning the root → leaf tenant chain (mirrors smrt-features). */\nexport interface FieldPolicyTenantHierarchyProvider {\n getChain(tenantId: string): Promise<FieldPolicyTenantNode[]>;\n}\n\n/**\n * Loader-function DI seam (NOT a container registration): the resolver calls\n * it lazily and treats `null` as \"no hierarchy available\" (flat-tenant\n * fallback). The default loader dynamic-imports `@happyvertical/smrt-users`\n * and returns `null` when it is not installed.\n */\nexport type FieldPolicyTenantHierarchyLoader = (\n options: SmrtClassOptions,\n) => Promise<FieldPolicyTenantHierarchyProvider | null>;\n\nexport interface ResolveFieldPolicyOptions {\n tenantId?: string | null;\n userId?: string | null;\n /**\n * Database holding `_smrt_field_policies`. Without it, only the code seed\n * resolves (stored layers are skipped) — the smrt-prompts precedent.\n */\n db?: SmrtClassOptions['db'];\n tenantHierarchyLoader?: FieldPolicyTenantHierarchyLoader;\n /**\n * Internal write-validation seam: omit persisted rows while evaluating a\n * proposed replacement. Excluded resolutions bypass the shared cache so a\n * projected result can never poison ordinary reads.\n */\n excludePolicyIds?: ReadonlySet<string>;\n}\n\n/**\n * Minimal structural shape of the tenant surface loaded from\n * `@happyvertical/smrt-users` by the default hierarchy loader. Only the\n * permission-cascade fields consumed by the chain walk are modeled.\n */\nexport interface FieldPolicyUsersTenantRecord {\n id: string;\n inheritPermissions?: boolean;\n cascadePermissions?: boolean;\n}\n\nexport interface FieldPolicyUsersModule {\n TenantCollection: {\n create(options: SmrtClassOptions): Promise<{\n get(criteria: {\n id: string;\n }): Promise<FieldPolicyUsersTenantRecord | null>;\n getAncestorsFromRoot(\n tenantId: string,\n ): Promise<FieldPolicyUsersTenantRecord[]>;\n }>;\n };\n}\n\n/** Result shape of the batch resolve action (`FieldPolicyCollection.resolveBatch`). */\nexport interface FieldPolicyBatchResult {\n policies: Record<string, ResolvedObjectFieldPolicy>;\n}\n\n/** A policy row safe to expose through the context-scoped gear action. */\nexport interface FieldPolicyEditorRow {\n defaultValue: string | null;\n displayOrder: number | null;\n fieldName: string;\n help: string | null;\n id: string;\n label: string | null;\n locked: boolean | null;\n scopeType: FieldPolicyScopeType;\n tenantId: string | null;\n updatedBy: string | null;\n userId: string | null;\n visibility: FieldPolicyVisibility | null;\n}\n\n/** Context-derived authorization state for the field-policy gear. */\nexport interface FieldPolicyEditorCapabilities {\n manage: boolean;\n personalize: boolean;\n}\n\n/**\n * Gear bootstrap response. `policy` is always filtered by the public-field\n * rail; raw rows and explanation layers appear only for scopes the caller is\n * authorized to mutate. Row ids are present for reset/delete operations.\n */\nexport interface FieldPolicyEditorState {\n capabilities: FieldPolicyEditorCapabilities;\n /**\n * For the caller's personal layer only, whether removing that layer's\n * default still leaves a usable default at code/app/tenant precedence.\n * This intentionally exposes no lower-layer rows or default values.\n */\n personalLowerDefaultUsable: Record<string, boolean>;\n policy: ExplainedObjectFieldPolicy;\n rows: {\n app: FieldPolicyEditorRow[];\n tenant: FieldPolicyEditorRow[];\n user: FieldPolicyEditorRow[];\n };\n}\n\n/** A stored organization row with the immutable audit metadata needed by #2050. */\nexport interface FieldPolicyAuditRow extends FieldPolicyEditorRow {\n objectRef: string;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\n/** Why a persisted policy row is no longer usable by the live registry. */\nexport type FieldPolicyDriftReason =\n | 'unknown-object'\n | 'unknown-field'\n | 'excluded-field';\n\n/** Drift is deliberately identity-only: stale values are never serialized. */\nexport interface FieldPolicyDriftRow {\n id: string;\n objectRef: string;\n fieldName: string;\n scopeType: FieldPolicyScopeType;\n tenantId: string | null;\n userId: string | null;\n updatedBy: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n reason: FieldPolicyDriftReason;\n prunable: boolean;\n}\n\n/**\n * Tenant-admin catalog read surface. Foreign user rows are represented only\n * by counts; their values and identifiers never leave the collection.\n */\nexport interface FieldPolicyAuditSnapshot {\n orgRows: FieldPolicyAuditRow[];\n appRows: FieldPolicyAuditRow[];\n inheritedOrgKeys: Record<string, string[]>;\n userOverrideCounts: Record<string, Record<string, number>>;\n driftRows: FieldPolicyDriftRow[];\n policies: Record<string, ExplainedObjectFieldPolicy>;\n caller: {\n tenantId: string | null;\n userId: string | null;\n canManageOrg: boolean;\n canPersonalize: boolean;\n };\n}\n\n/** Explicit 403 result used by generated custom-action transports. */\nexport interface FieldPolicyEditorStateDenied {\n code: 'permission_denied';\n message: string;\n ok: false;\n status: 403;\n}\n\nexport type FieldPolicyEditorStateResult =\n | FieldPolicyEditorState\n | FieldPolicyEditorStateDenied;\n\nexport type { SmrtClassOptions };\n"],"mappings":";AA+BO,IAAM,6BAA6B;AAEnC,IAAM,2BAA4D;CACvE;CACA;CACA;AACF;AAEO,IAAM,4BAA8D;CACzE;CACA;CACA;AACF"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n SmrtClassOptions,\n SmrtObjectOptions,\n} from '@happyvertical/smrt-core';\n\n/**\n * Scope tier a {@link FieldPolicy} row belongs to.\n *\n * Resolution precedence is code seed → `app` → `tenant` (hierarchy walk,\n * root → leaf) → `user`. Unlike smrt-features (which ships only\n * `global`/`tenant`), the user tier is implemented end to end here — both\n * defaults and visibility resolve through it.\n */\nexport type FieldPolicyScopeType = 'app' | 'tenant' | 'user';\n\n/**\n * Visibility tier for a field in generated/consuming form UIs.\n *\n * - `basic`: shown before the advanced disclosure\n * - `advanced`: shown behind the advanced disclosure\n * - `hidden`: not rendered (requires the field to be optional or have a\n * resolved default — the required-field invariant)\n */\nexport type FieldPolicyVisibility = 'basic' | 'advanced' | 'hidden';\n\n/**\n * `scopeKey` value for app-scope rows. `scopeKey` exists ONLY so the\n * `conflictColumns` unique index stays total while `tenantId`/`userId` are\n * nullable (nullable columns would allow duplicate NULL rows) — the same\n * trick as `PromptOverride.context`.\n */\nexport const APP_FIELD_POLICY_SCOPE_KEY = '__app__';\n\nexport const FIELD_POLICY_SCOPE_TYPES: readonly FieldPolicyScopeType[] = [\n 'app',\n 'tenant',\n 'user',\n];\n\nexport const FIELD_POLICY_VISIBILITIES: readonly FieldPolicyVisibility[] = [\n 'basic',\n 'advanced',\n 'hidden',\n];\n\nexport interface FieldPolicyOptions extends SmrtObjectOptions {\n objectRef?: string;\n fieldName?: string;\n scopeType?: FieldPolicyScopeType;\n tenantId?: string | null;\n userId?: string | null;\n /**\n * ENCODED channel: an already-JSON-encoded default, exactly as the column\n * stores it (`'\"Net 30\"'`, `'42'`, `'null'`), or `null` to inherit.\n *\n * This is the wire contract: the generated write routes hand the request\n * body straight to the constructor, and the #2049/#2050 gear posts\n * `JSON.stringify(draft.defaultValue)`. It must therefore keep meaning\n * \"already encoded\" — auto-serializing here would double-encode every gear\n * write.\n *\n * Use {@link FieldPolicyOptions.defaultValueRaw} for a plain value. The two\n * are mutually exclusive: `'\"TBD\"'` and `'TBD'` are indistinguishable once\n * a single option carries both meanings, so the channel must be explicit\n * rather than sniffed.\n */\n defaultValue?: string | null;\n /**\n * PLAIN channel: any value, always serialized — strings included. The\n * constructor-option twin of {@link FieldPolicy.setDefaultValue}, so\n * `{ defaultValueRaw: 'Net 30' }` stores `'\"Net 30\"'` rather than the\n * unparseable literal `Net 30`.\n */\n defaultValueRaw?: unknown;\n visibility?: FieldPolicyVisibility | null;\n help?: string | null;\n label?: string | null;\n displayOrder?: number | null;\n locked?: boolean | null;\n updatedBy?: string | null;\n}\n\n/**\n * The sparse contribution of one layer (code seed or one stored row).\n *\n * `default` is boxed so an explicit JSON `null` default (meaning \"default to\n * null\") stays distinguishable from \"this layer contributes no default\".\n */\nexport interface FieldPolicyDelta {\n default?: { value: unknown };\n visibility?: FieldPolicyVisibility;\n help?: string;\n label?: string;\n order?: number;\n locked?: boolean;\n}\n\n/** One layer's contribution to a field's resolved policy (explain variant). */\nexport interface FieldPolicyLayerContribution {\n layer: 'code' | 'app' | 'tenant' | 'user';\n /** Chain node id for `tenant` layers (root → leaf order). */\n tenantId?: string;\n /** User id for the `user` layer. */\n userId?: string;\n delta: FieldPolicyDelta;\n}\n\n/** Fully merged policy for a single field. */\nexport interface ResolvedFieldPolicy {\n fieldName: string;\n /** True when any layer resolved a default (including an explicit null). */\n hasDefault: boolean;\n /** Parsed default value; `undefined` when {@link hasDefault} is false. */\n defaultValue: unknown;\n visibility: FieldPolicyVisibility;\n help: string | null;\n label: string | null;\n order: number | null;\n /** Grouping key — code-seed only (`ui.group`), not overridable by rows. */\n group: string | null;\n locked: boolean;\n /** Mirror of the manifest required flag (nullable fields are optional). */\n required: boolean;\n /**\n * True when the resolver forced `basic` visibility because the field is\n * required and no usable default resolved (the resolver-side safety net for\n * the required-field invariant).\n */\n visibilityForced?: boolean;\n}\n\n/** Merged policy for every field of one object. */\nexport interface ResolvedObjectFieldPolicy {\n objectRef: string;\n fields: Record<string, ResolvedFieldPolicy>;\n}\n\n/**\n * Explain variant: merged result plus the ordered per-layer contributions for\n * each field, so admin/gear UIs (#2049/#2050) never re-derive precedence.\n * Layers are listed in application order (code, app, tenant chain root → leaf,\n * user) and contain ONLY contributions that survive into the merged result:\n * tenant ancestors discarded by a permission-inheritance break and user rows\n * suppressed by an effective org lock are omitted, so sequentially replaying\n * the listed deltas reproduces the merged policy.\n */\nexport interface ExplainedObjectFieldPolicy extends ResolvedObjectFieldPolicy {\n layers: Record<string, FieldPolicyLayerContribution[]>;\n}\n\n/** Minimal tenant node consumed by the hierarchy walk (mirrors smrt-features). */\nexport interface FieldPolicyTenantNode {\n id: string;\n inheritPermissions: boolean;\n cascadePermissions: boolean;\n}\n\n/** Provider returning the root → leaf tenant chain (mirrors smrt-features). */\nexport interface FieldPolicyTenantHierarchyProvider {\n getChain(tenantId: string): Promise<FieldPolicyTenantNode[]>;\n}\n\n/**\n * Loader-function DI seam (NOT a container registration): the resolver calls\n * it lazily and treats `null` as \"no hierarchy available\" (flat-tenant\n * fallback). The default loader dynamic-imports `@happyvertical/smrt-users`\n * and returns `null` when it is not installed.\n */\nexport type FieldPolicyTenantHierarchyLoader = (\n options: SmrtClassOptions,\n) => Promise<FieldPolicyTenantHierarchyProvider | null>;\n\nexport interface ResolveFieldPolicyOptions {\n tenantId?: string | null;\n userId?: string | null;\n /**\n * Database holding `_smrt_field_policies`. Without it, only the code seed\n * resolves (stored layers are skipped) — the smrt-prompts precedent.\n */\n db?: SmrtClassOptions['db'];\n tenantHierarchyLoader?: FieldPolicyTenantHierarchyLoader;\n /**\n * Internal write-validation seam: omit persisted rows while evaluating a\n * proposed replacement. Excluded resolutions bypass the shared cache so a\n * projected result can never poison ordinary reads.\n */\n excludePolicyIds?: ReadonlySet<string>;\n}\n\n/**\n * Minimal structural shape of the tenant surface loaded from\n * `@happyvertical/smrt-users` by the default hierarchy loader. Only the\n * permission-cascade fields consumed by the chain walk are modeled.\n */\nexport interface FieldPolicyUsersTenantRecord {\n id: string;\n inheritPermissions?: boolean;\n cascadePermissions?: boolean;\n}\n\nexport interface FieldPolicyUsersModule {\n TenantCollection: {\n create(options: SmrtClassOptions): Promise<{\n get(criteria: {\n id: string;\n }): Promise<FieldPolicyUsersTenantRecord | null>;\n getAncestorsFromRoot(\n tenantId: string,\n ): Promise<FieldPolicyUsersTenantRecord[]>;\n }>;\n };\n}\n\n/** Result shape of the batch resolve action (`FieldPolicyCollection.resolveBatch`). */\nexport interface FieldPolicyBatchResult {\n policies: Record<string, ResolvedObjectFieldPolicy>;\n}\n\n/** A policy row safe to expose through the context-scoped gear action. */\nexport interface FieldPolicyEditorRow {\n defaultValue: string | null;\n displayOrder: number | null;\n fieldName: string;\n help: string | null;\n id: string;\n label: string | null;\n locked: boolean | null;\n scopeType: FieldPolicyScopeType;\n tenantId: string | null;\n updatedBy: string | null;\n userId: string | null;\n visibility: FieldPolicyVisibility | null;\n}\n\n/** Context-derived authorization state for the field-policy gear. */\nexport interface FieldPolicyEditorCapabilities {\n manage: boolean;\n personalize: boolean;\n}\n\n/**\n * Gear bootstrap response. `policy` is always filtered by the public-field\n * rail; raw rows and explanation layers appear only for scopes the caller is\n * authorized to mutate. Row ids are present for reset/delete operations.\n */\nexport interface FieldPolicyEditorState {\n capabilities: FieldPolicyEditorCapabilities;\n /**\n * For the caller's personal layer only, whether removing that layer's\n * default still leaves a usable default at code/app/tenant precedence.\n * This intentionally exposes no lower-layer rows or default values.\n */\n personalLowerDefaultUsable: Record<string, boolean>;\n policy: ExplainedObjectFieldPolicy;\n rows: {\n app: FieldPolicyEditorRow[];\n tenant: FieldPolicyEditorRow[];\n user: FieldPolicyEditorRow[];\n };\n}\n\n/** A stored organization row with the immutable audit metadata needed by #2050. */\nexport interface FieldPolicyAuditRow extends FieldPolicyEditorRow {\n objectRef: string;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\n/** Why a persisted policy row is no longer usable by the live registry. */\nexport type FieldPolicyDriftReason =\n | 'unknown-object'\n | 'unknown-field'\n | 'excluded-field';\n\n/** Drift is deliberately identity-only: stale values are never serialized. */\nexport interface FieldPolicyDriftRow {\n id: string;\n objectRef: string;\n fieldName: string;\n scopeType: FieldPolicyScopeType;\n tenantId: string | null;\n userId: string | null;\n updatedBy: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n reason: FieldPolicyDriftReason;\n prunable: boolean;\n}\n\n/**\n * Tenant-admin catalog read surface. Foreign user rows are represented only\n * by counts; their values and identifiers never leave the collection.\n */\nexport interface FieldPolicyAuditSnapshot {\n orgRows: FieldPolicyAuditRow[];\n appRows: FieldPolicyAuditRow[];\n inheritedOrgKeys: Record<string, string[]>;\n userOverrideCounts: Record<string, Record<string, number>>;\n driftRows: FieldPolicyDriftRow[];\n policies: Record<string, ExplainedObjectFieldPolicy>;\n caller: {\n tenantId: string | null;\n userId: string | null;\n canManageOrg: boolean;\n canPersonalize: boolean;\n };\n}\n\n/** Explicit 403 result used by generated custom-action transports. */\nexport interface FieldPolicyEditorStateDenied {\n code: 'permission_denied';\n message: string;\n ok: false;\n status: 403;\n}\n\nexport type FieldPolicyEditorStateResult =\n | FieldPolicyEditorState\n | FieldPolicyEditorStateDenied;\n\n// ---------------------------------------------------------------------------\n// Usage capture + promotion suggestions (#2051)\n// ---------------------------------------------------------------------------\n\nexport type FieldPolicySuggestionKind = 'promote' | 'default';\nexport const FIELD_POLICY_SUGGESTION_KINDS: readonly FieldPolicySuggestionKind[] =\n ['promote', 'default'];\n\nexport type FieldPolicySuggestionStatus = 'pending' | 'accepted' | 'dismissed';\nexport const FIELD_POLICY_SUGGESTION_STATUSES: readonly FieldPolicySuggestionStatus[] =\n ['pending', 'accepted', 'dismissed'];\n\n/** One bounded client-side form submission sample. */\nexport interface FieldUsageReportEntry {\n objectRef: string;\n fieldName: string;\n value?: unknown;\n /** Used only for value-less samples; server comparison wins when present. */\n matchedDefault?: boolean;\n}\n\nexport interface FieldUsageReportResult {\n accepted: number;\n dropped: number;\n}\n\nexport interface FieldPolicySuggestionData {\n id: string;\n objectRef: string;\n fieldName: string;\n tenantId: string;\n kind: FieldPolicySuggestionKind;\n proposedValue: string | null;\n evidence: Record<string, unknown>;\n status: FieldPolicySuggestionStatus;\n cooldownUntil: string | null;\n decidedBy: string | null;\n decidedAt: string | null;\n}\n\nexport interface PendingFieldPolicySuggestionsResult {\n suggestions: FieldPolicySuggestionData[];\n total: number;\n}\n\nexport interface AcceptFieldPolicySuggestionResult {\n suggestion: FieldPolicySuggestionData;\n policyRowId: string;\n}\n\nexport interface DismissFieldPolicySuggestionResult {\n suggestion: FieldPolicySuggestionData;\n}\n\nexport type { SmrtClassOptions };\n"],"mappings":";AA+BO,IAAM,6BAA6B;AAEnC,IAAM,2BAA4D;CACvE;CACA;CACA;AACF;AAEO,IAAM,4BAA8D;CACzE;CACA;CACA;AACF;AA0RO,IAAM,gCACX,CAAC,WAAW,SAAS;AAGhB,IAAM,mCACX;CAAC;CAAW;CAAY;AAAW"}
@@ -0,0 +1,201 @@
1
+ import { SmrtObject, SmrtObjectOptions } from '@happyvertical/smrt-core';
2
+ import { DatabaseInterface } from '@happyvertical/sql';
3
+ import { FieldPolicySuggestionKind } from './types.js';
4
+ export interface FieldUsageMaintenanceConfig {
5
+ /** Drop counter buckets older than this (by `period`). Default 90 days. */
6
+ counterMaxAgeMs: number;
7
+ /** Keep at most this many counter rows (oldest pruned first). Default 100k. */
8
+ counterMaxRows: number;
9
+ /** Drop ACCEPTED suggestions decided longer ago than this. Default 180 days. */
10
+ suggestionAcceptedMaxAgeMs: number;
11
+ }
12
+ export declare const FIELD_USAGE_MAINTENANCE_DEFAULTS: FieldUsageMaintenanceConfig;
13
+ export interface FieldUsageSuggestionConfig {
14
+ /** Usage window the thresholds evaluate over. Default 30 days. */
15
+ windowDays: number;
16
+ /** Distinct users required for a `promote` suggestion. Default 5. */
17
+ minDistinctUsers: number;
18
+ /** Submissions required before a `default` suggestion. Default 10. */
19
+ minSetCount: number;
20
+ /**
21
+ * Share of windowed submissions a single value must reach for a `default`
22
+ * suggestion (denominator is TOTAL setCount, so histogram overflow can only
23
+ * make this more conservative). Default 0.8.
24
+ */
25
+ defaultDominanceRatio: number;
26
+ }
27
+ export declare const FIELD_USAGE_SUGGESTION_DEFAULTS: FieldUsageSuggestionConfig;
28
+ export interface FieldUsageMaintenanceSummary {
29
+ countersPruned: number;
30
+ receiptsPruned: number;
31
+ suggestionsPruned: number;
32
+ }
33
+ export interface FieldUsageSuggestionRunSummary {
34
+ /**
35
+ * Suggestions this run wrote. Under overlapping runs both may report a
36
+ * create for the same candidate while the model's active-slot unique index
37
+ * converges them onto ONE row (see `FieldPolicySuggestion.activeKey`) — the
38
+ * tally is per-run work, not a row count.
39
+ */
40
+ created: number;
41
+ /** Candidates suppressed by a pending or cooling-down suggestion. */
42
+ suppressed: number;
43
+ /** Distinct (tenant, objectRef, fieldName) groups evaluated. */
44
+ groupsConsidered: number;
45
+ /**
46
+ * Groups whose evaluation threw and was skipped. A failing group never
47
+ * aborts the run — a global pass must keep serving every other tenant.
48
+ */
49
+ groupsFailed: number;
50
+ /**
51
+ * Bounded sample of failure messages (`MAX_REPORTED_GROUP_FAILURES`) so an
52
+ * operator can see WHY without the summary growing with the queue.
53
+ */
54
+ failures: string[];
55
+ }
56
+ /** Cap on {@link FieldUsageSuggestionRunSummary.failures} entries. */
57
+ export declare const MAX_REPORTED_GROUP_FAILURES = 5;
58
+ export interface FieldUsageCounterRetention {
59
+ maxAgeMs?: number;
60
+ maxRows?: number;
61
+ /** Restrict pruning to one tenant (ambient-context runs). */
62
+ tenantId?: string | null;
63
+ }
64
+ /**
65
+ * Prune counter rows to bound growth. Applies whichever bounds are provided
66
+ * (at least one required): `maxAgeMs` drops buckets whose `period` day is
67
+ * older than the cutoff; `maxRows` keeps only the newest N rows by
68
+ * `(period, id)`, deleting oldest-first. Mirrors core's `pruneChangeFeed`.
69
+ */
70
+ export declare function pruneFieldUsageCounters(db: DatabaseInterface, retention: FieldUsageCounterRetention): Promise<{
71
+ pruned: number;
72
+ }>;
73
+ /**
74
+ * Drop durable anti-inflation receipts at the same age cutoff as counters.
75
+ *
76
+ * Deliberately do NOT delete a receipt merely because its counter row is
77
+ * absent: report ingestion claims its receipt before merging the counter, so
78
+ * an orphan sweep could otherwise reopen the once-per-user/day quota during
79
+ * that in-flight interval. A max-row counter trim likewise leaves its recent
80
+ * receipts until the age cutoff — retaining a de-duplication guard is safer
81
+ * than allowing a second contribution for that day.
82
+ */
83
+ export declare function pruneFieldUsageReportReceipts(db: DatabaseInterface, options: {
84
+ maxAgeMs: number;
85
+ tenantId?: string | null;
86
+ }): Promise<{
87
+ pruned: number;
88
+ }>;
89
+ export interface FieldPolicySuggestionRetention {
90
+ /** Drop ACCEPTED suggestions decided longer ago than this. */
91
+ acceptedMaxAgeMs: number;
92
+ /** Restrict pruning to one tenant (ambient-context runs). */
93
+ tenantId?: string | null;
94
+ /** Clock override for deterministic tests. */
95
+ now?: Date;
96
+ }
97
+ /**
98
+ * Prune settled suggestion rows ONLY (#2051 pin): a dismissed suggestion once
99
+ * its cool-down has fully elapsed (its suppression job is done), and an
100
+ * accepted suggestion once it is old. Pending suggestions are NEVER pruned.
101
+ */
102
+ export declare function pruneFieldPolicySuggestions(db: DatabaseInterface, retention: FieldPolicySuggestionRetention): Promise<{
103
+ pruned: number;
104
+ }>;
105
+ export interface RunFieldUsageMaintenanceOptions extends Partial<FieldUsageMaintenanceConfig> {
106
+ db: DatabaseInterface;
107
+ }
108
+ /**
109
+ * The "aggregation" schedule's work. Ingestion pre-aggregates into period
110
+ * buckets, so the roll-up job's real job is retention: prune counter buckets
111
+ * and durable receipts at the shared age cutoff, then settle old suggestion
112
+ * rows. Max-row trimming leaves recent receipts intact to preserve daily
113
+ * de-duplication while an ingestion merge is in flight.
114
+ */
115
+ export declare function runFieldUsageMaintenance(options: RunFieldUsageMaintenanceOptions): Promise<FieldUsageMaintenanceSummary>;
116
+ export interface RunFieldPolicySuggestionGenerationOptions extends Partial<FieldUsageSuggestionConfig> {
117
+ db: DatabaseInterface;
118
+ /** Clock override for deterministic tests. */
119
+ now?: Date;
120
+ }
121
+ /**
122
+ * The threshold job: evaluate windowed counters per
123
+ * `(tenantId, objectRef, fieldName)` and create PENDING suggestions with
124
+ * human-readable evidence.
125
+ *
126
+ * - `promote`: at least `minDistinctUsers` distinct users set the field to a
127
+ * non-default value in the window AND the org-resolved visibility is not
128
+ * already `basic`.
129
+ * - `default`: at least `minSetCount` TOTAL submissions, a single recorded
130
+ * value covers `defaultDominanceRatio` of those TOTAL submissions (not of
131
+ * the deviations — see `FieldUsageCounter.submissionCount`), and it differs
132
+ * from the org-resolved default. Only histogram-eligible fields
133
+ * (low-cardinality, non-sensitive, non-gated) can ever qualify, and a group
134
+ * containing a legacy bucket with no recorded total is skipped rather than
135
+ * ratioed against the wrong denominator.
136
+ *
137
+ * Dedup: a candidate is suppressed while the same
138
+ * `(tenantId, objectRef, fieldName, kind)` has a PENDING suggestion or a
139
+ * DISMISSED one still inside its cool-down. Accepted history never blocks —
140
+ * once accepted, the resolved policy itself stops regeneration (visibility is
141
+ * basic / the default matches). The pre-check is an optimization only: the
142
+ * single-active guarantee is STRUCTURAL (`FieldPolicySuggestion.activeKey` in
143
+ * `conflictColumns`), so overlapping runs upsert onto one row instead of
144
+ * duplicating.
145
+ *
146
+ * Sensitive, read-permission-gated, and transient fields are skipped
147
+ * entirely: their usage rows are count-only observability data and never
148
+ * produce suggestions.
149
+ */
150
+ export declare function runFieldPolicySuggestionGeneration(options: RunFieldPolicySuggestionGenerationOptions): Promise<FieldUsageSuggestionRunSummary>;
151
+ /**
152
+ * The registered schedule target for the #2051 learning loop (see the module
153
+ * doc for why it is NOT an smrt-agents `Agent` subclass). Rows of its system
154
+ * table are never written — the class exists so `AgentSchedule.agentType`
155
+ * resolves through the `ObjectRegistry` and smrt-jobs can construct it and
156
+ * invoke the two allowlisted methods.
157
+ */
158
+ export declare class FieldUsageLearningAgent extends SmrtObject {
159
+ /**
160
+ * The smrt-jobs opt-in background allowlist (S5 contract): ONLY these two
161
+ * methods are reachable from a persisted job/schedule row.
162
+ */
163
+ static backgroundEligibleMethods: ReadonlyArray<string>;
164
+ constructor(options?: SmrtObjectOptions);
165
+ /** Schedule entry point for {@link runFieldUsageMaintenance}. */
166
+ runUsageMaintenance(args?: Record<string, unknown>): Promise<FieldUsageMaintenanceSummary>;
167
+ /** Schedule entry point for {@link runFieldPolicySuggestionGeneration}. */
168
+ runSuggestionGeneration(args?: Record<string, unknown>): Promise<FieldUsageSuggestionRunSummary>;
169
+ }
170
+ export interface FieldUsageEvidenceInput {
171
+ kind: FieldPolicySuggestionKind;
172
+ objectRef: string;
173
+ fieldName: string;
174
+ windowStart: string;
175
+ windowEnd: string;
176
+ distinctUsers: number;
177
+ /** True when the distinct-user set overflowed (count is a lower bound). */
178
+ distinctUsersAtLeast: boolean;
179
+ /** Submissions that DIFFERED from the resolved default. */
180
+ setCount: number;
181
+ /**
182
+ * TOTAL submissions observed in the window (the dominance denominator).
183
+ * `undefined` only for legacy buckets that never recorded a total, in which
184
+ * case the summary states the deviation count alone.
185
+ */
186
+ submissionCount?: number;
187
+ /** The threshold the candidate cleared (documented in the evidence). */
188
+ threshold: number;
189
+ topValue?: unknown;
190
+ topValueShare?: number;
191
+ }
192
+ /**
193
+ * Human-readable evidence for a suggestion: a `summary` sentence a reviewer
194
+ * can read as-is, plus the structured numbers behind it.
195
+ *
196
+ * The sentence always states BOTH numbers when known — deviations and total
197
+ * submissions — so a reviewer can see the base rate a dominance percentage was
198
+ * computed against instead of trusting a bare ratio.
199
+ */
200
+ export declare function buildFieldUsageEvidence(input: FieldUsageEvidenceInput): Record<string, unknown>;
201
+ //# sourceMappingURL=usage-learning.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-learning.d.ts","sourceRoot":"","sources":["../src/usage-learning.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EACL,UAAU,EACV,KAAK,iBAAiB,EAEvB,MAAM,0BAA0B,CAAC;AAKlC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAuB5D,OAAO,KAAK,EACV,yBAAyB,EAE1B,MAAM,YAAY,CAAC;AASpB,MAAM,WAAW,2BAA2B;IAC1C,2EAA2E;IAC3E,eAAe,EAAE,MAAM,CAAC;IACxB,+EAA+E;IAC/E,cAAc,EAAE,MAAM,CAAC;IACvB,gFAAgF;IAChF,0BAA0B,EAAE,MAAM,CAAC;CACpC;AAED,eAAO,MAAM,gCAAgC,EAAE,2BAI9C,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACzC,kEAAkE;IAClE,UAAU,EAAE,MAAM,CAAC;IACnB,qEAAqE;IACrE,gBAAgB,EAAE,MAAM,CAAC;IACzB,sEAAsE;IACtE,WAAW,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,qBAAqB,EAAE,MAAM,CAAC;CAC/B;A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EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,2EAA2E;IAC3E,oBAAoB,EAAE,OAAO,CAAC;IAC9B,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,wEAAwE;IACxE,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,uBAAuB,GAC7B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAuCzB"}
@@ -0,0 +1,110 @@
1
+ import { DatabaseInterface } from '@happyvertical/sql';
2
+ import { FieldUsageMaintenanceConfig, FieldUsageSuggestionConfig } from './usage-learning.js';
3
+ /** Registry-qualified schedule target (`AgentSchedule.agentType`). */
4
+ export declare const FIELD_USAGE_LEARNING_AGENT_TYPE = "@happyvertical/smrt-fields:FieldUsageLearningAgent";
5
+ /** Method the aggregation/retention schedule invokes. */
6
+ export declare const FIELD_USAGE_MAINTENANCE_METHOD = "runUsageMaintenance";
7
+ /** Method the suggestion-generation schedule invokes. */
8
+ export declare const FIELD_USAGE_SUGGESTION_METHOD = "runSuggestionGeneration";
9
+ /**
10
+ * Default cadence for counter maintenance: daily at 02:30 — in the SCHEDULER
11
+ * HOST'S LOCAL TIME. See {@link ensureFieldUsageLearningSchedules} for why no
12
+ * timezone can be selected here.
13
+ */
14
+ export declare const DEFAULT_FIELD_USAGE_MAINTENANCE_CRON = "30 2 * * *";
15
+ /** Default cadence for suggestion generation: weekly, Monday 03:00 host-local. */
16
+ export declare const DEFAULT_FIELD_USAGE_SUGGESTION_CRON = "0 3 * * 1";
17
+ /**
18
+ * Stable id for a global learning schedule, derived from the agent type and
19
+ * method (the `TenantUsageMetric.recordUsage` precedent).
20
+ *
21
+ * `_smrt_agent_schedules` has no natural-key uniqueness on
22
+ * `(agent_type, method)`, so a check-then-create would let two replicas
23
+ * starting against an empty database each insert their own random-id row —
24
+ * and with `enabled: true` every job would then run twice. A deterministic id
25
+ * makes the insert converge on ONE primary key instead.
26
+ */
27
+ export declare function fieldUsageScheduleId(method: string): Promise<string>;
28
+ /**
29
+ * Structural surface of the agents module the installer consumes (no static
30
+ * import — mirrors `FieldPolicyUsersModule`). `create`/`list`/`save` are the
31
+ * standard SmrtCollection/SmrtObject shapes.
32
+ */
33
+ export interface FieldUsageAgentsScheduleRow {
34
+ id?: string | null;
35
+ enabled?: boolean;
36
+ /**
37
+ * Owning tenant; `null`/absent marks the GLOBAL schedules this installer
38
+ * manages. Read so the existence check cannot mistake a tenant-specific
39
+ * schedule for the global one.
40
+ */
41
+ tenantId?: string | null;
42
+ save?: () => Promise<unknown>;
43
+ }
44
+ export interface FieldUsageAgentsModule {
45
+ AgentScheduleCollection: {
46
+ create(options: {
47
+ db: DatabaseInterface;
48
+ }): Promise<{
49
+ list(options: {
50
+ where: Record<string, unknown>;
51
+ }): Promise<FieldUsageAgentsScheduleRow[]>;
52
+ create(data: Record<string, unknown>): Promise<FieldUsageAgentsScheduleRow>;
53
+ }>;
54
+ };
55
+ }
56
+ export interface EnsureFieldUsageLearningSchedulesOptions {
57
+ db: DatabaseInterface;
58
+ /**
59
+ * Whether the schedules start enabled. DEFAULT FALSE — the learning loop
60
+ * ships dormant; enabling it is an explicit deployment opt-in.
61
+ */
62
+ enabled?: boolean;
63
+ maintenanceCron?: string;
64
+ suggestionCron?: string;
65
+ /** Threshold/retention overrides persisted into the schedules' methodArgs. */
66
+ maintenanceArgs?: Partial<FieldUsageMaintenanceConfig>;
67
+ suggestionArgs?: Partial<FieldUsageSuggestionConfig>;
68
+ /** Injection seam for tests / hosts that already loaded the agents module. */
69
+ agentsModule?: FieldUsageAgentsModule;
70
+ }
71
+ export interface EnsureFieldUsageLearningSchedulesResult {
72
+ /** False when `@happyvertical/smrt-agents` is not installed (no-op). */
73
+ installed: boolean;
74
+ /** Schedules created by THIS call (existing rows are left untouched). */
75
+ created: number;
76
+ }
77
+ /**
78
+ * Idempotently create the two GLOBAL (tenant-null) `AgentSchedule` rows for
79
+ * the learning loop — the aggregation/retention roll-up and the
80
+ * suggestion-generation job. An existing GLOBAL row for the agent type +
81
+ * method is never modified (operator state like enable/disable is preserved).
82
+ *
83
+ * The existence check is scoped to the GLOBAL rows deliberately: a deployment
84
+ * may also run tenant-specific schedules for the same agent type and method
85
+ * (the ambient-context runs the jobs support), and matching one of those would
86
+ * silently skip installing the global schedule this function promises. Tenant
87
+ * rows are read but never touched.
88
+ *
89
+ * Concurrency: each schedule is written under a DETERMINISTIC id
90
+ * ({@link fieldUsageScheduleId}) with insert-only semantics, so two replicas
91
+ * installing at once converge on one row — the pre-check is only the cheap
92
+ * path, and a primary-key collision is treated as "already installed" rather
93
+ * than an error. Insert-only also means an existing row's operator state
94
+ * (enabled/disabled, edited cron) is never overwritten by a later install.
95
+ *
96
+ * **No timezone option, deliberately.** `AgentSchedule` carries a `timezone`
97
+ * column, but `getNextCronDate(cron, _timezone)` ignores the argument and
98
+ * matches against host-local `getHours()`/`getDate()`, and smrt-jobs'
99
+ * `ScheduleRunner` recalculates with the same host-local parser. Accepting a
100
+ * timezone here would advertise control this stack does not have, so these
101
+ * schedules fire in the SCHEDULER HOST'S LOCAL TIME — pick crons accordingly
102
+ * (see `agents/usage-learning.md`). Fixing the agents-side parser is out of
103
+ * scope for this package.
104
+ *
105
+ * System operation: global schedules are platform state, so a non-bypass
106
+ * ambient tenant context is rejected (fail closed) — call this from trusted
107
+ * startup/migration code.
108
+ */
109
+ export declare function ensureFieldUsageLearningSchedules(options: EnsureFieldUsageLearningSchedulesOptions): Promise<EnsureFieldUsageLearningSchedulesResult>;
110
+ //# sourceMappingURL=usage-schedules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-schedules.d.ts","sourceRoot":"","sources":["../src/usage-schedules.ts"],"names":[],"m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M,WAAW,wCAAwC;IACvD,EAAE,EAAE,iBAAiB,CAAC;IACtB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8EAA8E;IAC9E,eAAe,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAC;IACvD,cAAc,CAAC,EAAE,OAAO,CAAC,0BAA0B,CAAC,CAAC;IACrD,8EAA8E;IAC9E,YAAY,CAAC,EAAE,sBAAsB,CAAC;CACvC;AAED,MAAM,WAAW,uCAAuC;IACtD,wEAAwE;IACxE,SAAS,EAAE,OAAO,CAAC;IACnB,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAsB,iCAAiC,CACrD,OAAO,EAAE,wCAAwC,GAChD,OAAO,CAAC,uCAAuC,CAAC,CAuGlD"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Shared detection for OPTIONAL workspace dependencies
3
+ * (`@happyvertical/smrt-users`, and since #2051 `@happyvertical/smrt-agents`
4
+ * for the dormant learning schedules).
5
+ *
6
+ * A leaf module (no package-internal imports) so every dynamic-import seam —
7
+ * the resolver's default tenant-hierarchy loader, the permission catalog
8
+ * registration, and the schedule installer — shares one matcher without
9
+ * creating an import cycle through the resolver/collection/model chain.
10
+ */
11
+ /**
12
+ * Whether an import failure means the named workspace package is simply not
13
+ * installed (→ graceful degradation) rather than installed-but-broken
14
+ * (→ rethrow, surfacing the problem instead of silently degrading).
15
+ *
16
+ * The decision is made on the missing-module TARGET parsed from Node's
17
+ * `Cannot find package/module '<specifier>'` message (walking the full
18
+ * `cause` chain): only a target that IS the package (or one of its subpaths)
19
+ * counts. A transitive failure INSIDE an installed package names the other
20
+ * module as the target — with the package path merely appearing as the
21
+ * importer — and therefore rethrows. `importWorkspaceModule`'s own
22
+ * source-fallback wrapper (`Failed to load <packageName> for ...`) is also
23
+ * accepted: it is thrown only when the package itself cannot be located.
24
+ *
25
+ * Exported for direct testing; not re-exported from the package index.
26
+ */
27
+ export declare function isMissingWorkspaceDependency(error: unknown, packageName: string): boolean;
28
+ /** {@link isMissingWorkspaceDependency} for `@happyvertical/smrt-users`. */
29
+ export declare function isMissingUsersDependency(error: unknown): boolean;
30
+ //# sourceMappingURL=users-module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"users-module.d.ts","sourceRoot":"","sources":["../src/users-module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAWH;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,4BAA4B,CAC1C,KAAK,EAAE,OAAO,EACd,WAAW,EAAE,MAAM,GAClB,OAAO,CAoBT;AAED,4EAA4E;AAC5E,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEhE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-fields",
3
- "version": "0.40.61",
3
+ "version": "0.40.62",
4
4
  "description": "Layered field policy store and resolver (defaults, visibility tiers, help text) for SMRT objects",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -37,10 +37,10 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@happyvertical/sql": "^0.85.5",
40
- "@happyvertical/smrt-core": "0.40.61",
41
- "@happyvertical/smrt-tenancy": "0.40.61",
42
- "@happyvertical/smrt-ui": "0.40.61",
43
- "@happyvertical/smrt-users": "0.40.61"
40
+ "@happyvertical/smrt-core": "0.40.62",
41
+ "@happyvertical/smrt-tenancy": "0.40.62",
42
+ "@happyvertical/smrt-ui": "0.40.62",
43
+ "@happyvertical/smrt-users": "0.40.62"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@sveltejs/package": "^2.5.8",
@@ -52,9 +52,9 @@
52
52
  "typescript": "5.9.3",
53
53
  "vite": "8.1.4",
54
54
  "vitest": "4.1.10",
55
- "@happyvertical/smrt-cli": "0.40.61",
56
- "@happyvertical/smrt-users": "0.40.61",
57
- "@happyvertical/smrt-vitest": "0.40.61"
55
+ "@happyvertical/smrt-cli": "0.40.62",
56
+ "@happyvertical/smrt-users": "0.40.62",
57
+ "@happyvertical/smrt-vitest": "0.40.62"
58
58
  },
59
59
  "keywords": [
60
60
  "smrt",