@memberjunction/core-entities-server 6.3.0-edge.2 → 6.3.0-edge.3

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 (171) hide show
  1. package/README.md +13 -0
  2. package/dist/custom/ArtifactSecurityHookHelpers.d.ts.map +1 -1
  3. package/dist/custom/ArtifactSecurityHookHelpers.js +50 -0
  4. package/dist/custom/ArtifactSecurityHookHelpers.js.map +1 -1
  5. package/dist/custom/GraphConceptReadSecurityHook.d.ts +75 -0
  6. package/dist/custom/GraphConceptReadSecurityHook.d.ts.map +1 -0
  7. package/dist/custom/GraphConceptReadSecurityHook.js +574 -0
  8. package/dist/custom/GraphConceptReadSecurityHook.js.map +1 -0
  9. package/dist/custom/GraphRecordChangesReadSecurityHook.d.ts +45 -0
  10. package/dist/custom/GraphRecordChangesReadSecurityHook.d.ts.map +1 -0
  11. package/dist/custom/GraphRecordChangesReadSecurityHook.js +744 -0
  12. package/dist/custom/GraphRecordChangesReadSecurityHook.js.map +1 -0
  13. package/dist/custom/MJAIAgentActionEntityServer.server.d.ts +13 -0
  14. package/dist/custom/MJAIAgentActionEntityServer.server.d.ts.map +1 -0
  15. package/dist/custom/MJAIAgentActionEntityServer.server.js +52 -0
  16. package/dist/custom/MJAIAgentActionEntityServer.server.js.map +1 -0
  17. package/dist/custom/MJAIAgentCategoryEntityServer.server.d.ts +30 -0
  18. package/dist/custom/MJAIAgentCategoryEntityServer.server.d.ts.map +1 -0
  19. package/dist/custom/MJAIAgentCategoryEntityServer.server.js +127 -0
  20. package/dist/custom/MJAIAgentCategoryEntityServer.server.js.map +1 -0
  21. package/dist/custom/MJAIAgentClientToolEntityServer.server.d.ts +12 -0
  22. package/dist/custom/MJAIAgentClientToolEntityServer.server.d.ts.map +1 -0
  23. package/dist/custom/MJAIAgentClientToolEntityServer.server.js +46 -0
  24. package/dist/custom/MJAIAgentClientToolEntityServer.server.js.map +1 -0
  25. package/dist/custom/MJAIAgentEntityServer.server.d.ts +113 -7
  26. package/dist/custom/MJAIAgentEntityServer.server.d.ts.map +1 -1
  27. package/dist/custom/MJAIAgentEntityServer.server.js +1946 -96
  28. package/dist/custom/MJAIAgentEntityServer.server.js.map +1 -1
  29. package/dist/custom/MJAIAgentModalityEntityServer.server.d.ts +13 -0
  30. package/dist/custom/MJAIAgentModalityEntityServer.server.d.ts.map +1 -0
  31. package/dist/custom/MJAIAgentModalityEntityServer.server.js +52 -0
  32. package/dist/custom/MJAIAgentModalityEntityServer.server.js.map +1 -0
  33. package/dist/custom/MJAIAgentNoteEntityServer.server.d.ts +64 -8
  34. package/dist/custom/MJAIAgentNoteEntityServer.server.d.ts.map +1 -1
  35. package/dist/custom/MJAIAgentNoteEntityServer.server.js +263 -9
  36. package/dist/custom/MJAIAgentNoteEntityServer.server.js.map +1 -1
  37. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts +2 -2
  38. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts.map +1 -1
  39. package/dist/custom/MJAIAgentPersonaEntityServer.server.js +10 -8
  40. package/dist/custom/MJAIAgentPersonaEntityServer.server.js.map +1 -1
  41. package/dist/custom/MJAIAgentRelationshipEntityServer.server.d.ts +5 -2
  42. package/dist/custom/MJAIAgentRelationshipEntityServer.server.d.ts.map +1 -1
  43. package/dist/custom/MJAIAgentRelationshipEntityServer.server.js +25 -2
  44. package/dist/custom/MJAIAgentRelationshipEntityServer.server.js.map +1 -1
  45. package/dist/custom/MJAIAgentSkillEntityServer.server.d.ts +12 -0
  46. package/dist/custom/MJAIAgentSkillEntityServer.server.d.ts.map +1 -0
  47. package/dist/custom/MJAIAgentSkillEntityServer.server.js +46 -0
  48. package/dist/custom/MJAIAgentSkillEntityServer.server.js.map +1 -0
  49. package/dist/custom/MJAIAgentStepTypeEntityServer.server.d.ts +28 -0
  50. package/dist/custom/MJAIAgentStepTypeEntityServer.server.d.ts.map +1 -0
  51. package/dist/custom/MJAIAgentStepTypeEntityServer.server.js +117 -0
  52. package/dist/custom/MJAIAgentStepTypeEntityServer.server.js.map +1 -0
  53. package/dist/custom/MJAIAgentTypeEntityServer.server.d.ts +34 -0
  54. package/dist/custom/MJAIAgentTypeEntityServer.server.d.ts.map +1 -0
  55. package/dist/custom/MJAIAgentTypeEntityServer.server.js +231 -0
  56. package/dist/custom/MJAIAgentTypeEntityServer.server.js.map +1 -0
  57. package/dist/custom/MJActionEntityServer.server.d.ts +37 -0
  58. package/dist/custom/MJActionEntityServer.server.d.ts.map +1 -1
  59. package/dist/custom/MJActionEntityServer.server.js +208 -3
  60. package/dist/custom/MJActionEntityServer.server.js.map +1 -1
  61. package/dist/custom/MJComponentEntityServer.server.d.ts +6 -0
  62. package/dist/custom/MJComponentEntityServer.server.d.ts.map +1 -1
  63. package/dist/custom/MJComponentEntityServer.server.js +20 -2
  64. package/dist/custom/MJComponentEntityServer.server.js.map +1 -1
  65. package/dist/custom/MJContentSourceEntityServer.server.d.ts +28 -0
  66. package/dist/custom/MJContentSourceEntityServer.server.d.ts.map +1 -0
  67. package/dist/custom/MJContentSourceEntityServer.server.js +73 -0
  68. package/dist/custom/MJContentSourceEntityServer.server.js.map +1 -0
  69. package/dist/custom/MJContentSourceTypeEntityServer.server.d.ts +25 -0
  70. package/dist/custom/MJContentSourceTypeEntityServer.server.d.ts.map +1 -0
  71. package/dist/custom/MJContentSourceTypeEntityServer.server.js +73 -0
  72. package/dist/custom/MJContentSourceTypeEntityServer.server.js.map +1 -0
  73. package/dist/custom/MJDashboardEntityServer.server.d.ts +6 -0
  74. package/dist/custom/MJDashboardEntityServer.server.d.ts.map +1 -1
  75. package/dist/custom/MJDashboardEntityServer.server.js +24 -2
  76. package/dist/custom/MJDashboardEntityServer.server.js.map +1 -1
  77. package/dist/custom/MJGraphConceptEntityServer.server.d.ts +175 -23
  78. package/dist/custom/MJGraphConceptEntityServer.server.d.ts.map +1 -1
  79. package/dist/custom/MJGraphConceptEntityServer.server.js +584 -41
  80. package/dist/custom/MJGraphConceptEntityServer.server.js.map +1 -1
  81. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +38 -11
  82. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -1
  83. package/dist/custom/MJGraphEdgeEntityServer.server.js +249 -39
  84. package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -1
  85. package/dist/custom/MJGraphEntityServer.server.d.ts +58 -0
  86. package/dist/custom/MJGraphEntityServer.server.d.ts.map +1 -0
  87. package/dist/custom/MJGraphEntityServer.server.js +357 -0
  88. package/dist/custom/MJGraphEntityServer.server.js.map +1 -0
  89. package/dist/custom/MJGraphLinkEntityServer.server.d.ts +98 -0
  90. package/dist/custom/MJGraphLinkEntityServer.server.d.ts.map +1 -0
  91. package/dist/custom/MJGraphLinkEntityServer.server.js +375 -0
  92. package/dist/custom/MJGraphLinkEntityServer.server.js.map +1 -0
  93. package/dist/custom/MJGraphPermissionEntityServer.server.d.ts +29 -0
  94. package/dist/custom/MJGraphPermissionEntityServer.server.d.ts.map +1 -0
  95. package/dist/custom/MJGraphPermissionEntityServer.server.js +141 -0
  96. package/dist/custom/MJGraphPermissionEntityServer.server.js.map +1 -0
  97. package/dist/custom/MJListDetailEntityServer.server.d.ts +4 -4
  98. package/dist/custom/MJListDetailEntityServer.server.js +4 -4
  99. package/dist/custom/MJListEntityServer.server.d.ts +2 -1
  100. package/dist/custom/MJListEntityServer.server.d.ts.map +1 -1
  101. package/dist/custom/MJListEntityServer.server.js +5 -2
  102. package/dist/custom/MJListEntityServer.server.js.map +1 -1
  103. package/dist/custom/MJQueryEntityServer.server.d.ts +51 -3
  104. package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
  105. package/dist/custom/MJQueryEntityServer.server.js +142 -28
  106. package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
  107. package/dist/custom/MJQueryParameterEntityServer.server.d.ts +37 -0
  108. package/dist/custom/MJQueryParameterEntityServer.server.d.ts.map +1 -0
  109. package/dist/custom/MJQueryParameterEntityServer.server.js +160 -0
  110. package/dist/custom/MJQueryParameterEntityServer.server.js.map +1 -0
  111. package/dist/custom/MJQuerySQLEntityServer.server.d.ts +23 -0
  112. package/dist/custom/MJQuerySQLEntityServer.server.d.ts.map +1 -1
  113. package/dist/custom/MJQuerySQLEntityServer.server.js +106 -9
  114. package/dist/custom/MJQuerySQLEntityServer.server.js.map +1 -1
  115. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.d.ts +1 -1
  116. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.d.ts.map +1 -1
  117. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.js +8 -5
  118. package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.js.map +1 -1
  119. package/dist/custom/MJUserRoleEntityServer.server.d.ts.map +1 -1
  120. package/dist/custom/MJUserRoleEntityServer.server.js +9 -0
  121. package/dist/custom/MJUserRoleEntityServer.server.js.map +1 -1
  122. package/dist/custom/MJUserViewEntityServer.server.d.ts +9 -0
  123. package/dist/custom/MJUserViewEntityServer.server.d.ts.map +1 -1
  124. package/dist/custom/MJUserViewEntityServer.server.js +59 -3
  125. package/dist/custom/MJUserViewEntityServer.server.js.map +1 -1
  126. package/dist/custom/agentRelationalGrantGuard.d.ts +73 -0
  127. package/dist/custom/agentRelationalGrantGuard.d.ts.map +1 -0
  128. package/dist/custom/agentRelationalGrantGuard.js +375 -0
  129. package/dist/custom/agentRelationalGrantGuard.js.map +1 -0
  130. package/dist/custom/approvalStamp.d.ts +68 -4
  131. package/dist/custom/approvalStamp.d.ts.map +1 -1
  132. package/dist/custom/approvalStamp.js +107 -13
  133. package/dist/custom/approvalStamp.js.map +1 -1
  134. package/dist/custom/canon/CanonFingerprintRecorderServer.d.ts +20 -0
  135. package/dist/custom/canon/CanonFingerprintRecorderServer.d.ts.map +1 -0
  136. package/dist/custom/canon/CanonFingerprintRecorderServer.js +148 -0
  137. package/dist/custom/canon/CanonFingerprintRecorderServer.js.map +1 -0
  138. package/dist/custom/canon/index.d.ts +2 -0
  139. package/dist/custom/canon/index.d.ts.map +1 -0
  140. package/dist/custom/canon/index.js +2 -0
  141. package/dist/custom/canon/index.js.map +1 -0
  142. package/dist/custom/graph/GraphFindPathServerOperation.d.ts +7 -5
  143. package/dist/custom/graph/GraphFindPathServerOperation.d.ts.map +1 -1
  144. package/dist/custom/graph/GraphFindPathServerOperation.js +41 -12
  145. package/dist/custom/graph/GraphFindPathServerOperation.js.map +1 -1
  146. package/dist/custom/graphPermissionGuard.d.ts +69 -0
  147. package/dist/custom/graphPermissionGuard.d.ts.map +1 -0
  148. package/dist/custom/graphPermissionGuard.js +229 -0
  149. package/dist/custom/graphPermissionGuard.js.map +1 -0
  150. package/dist/custom/graphRlsCacheInvalidation.d.ts +38 -0
  151. package/dist/custom/graphRlsCacheInvalidation.d.ts.map +1 -0
  152. package/dist/custom/graphRlsCacheInvalidation.js +111 -0
  153. package/dist/custom/graphRlsCacheInvalidation.js.map +1 -0
  154. package/dist/custom/queryParentFingerprint.d.ts +36 -0
  155. package/dist/custom/queryParentFingerprint.d.ts.map +1 -0
  156. package/dist/custom/queryParentFingerprint.js +159 -0
  157. package/dist/custom/queryParentFingerprint.js.map +1 -0
  158. package/dist/custom/queryParentSaveChain.d.ts +5 -0
  159. package/dist/custom/queryParentSaveChain.d.ts.map +1 -0
  160. package/dist/custom/queryParentSaveChain.js +25 -0
  161. package/dist/custom/queryParentSaveChain.js.map +1 -0
  162. package/dist/custom/seededMetadataPush.d.ts +7 -0
  163. package/dist/custom/seededMetadataPush.d.ts.map +1 -0
  164. package/dist/custom/seededMetadataPush.js +23 -0
  165. package/dist/custom/seededMetadataPush.js.map +1 -0
  166. package/dist/index.d.ts +19 -0
  167. package/dist/index.d.ts.map +1 -1
  168. package/dist/index.js +19 -0
  169. package/dist/index.js.map +1 -1
  170. package/dist/tsconfig.tsbuildinfo +1 -1
  171. package/package.json +31 -31
@@ -4,11 +4,17 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- import { BaseEntity, RunView, ValidationErrorInfo, ValidationErrorType, } from '@memberjunction/core';
7
+ import { AuthorizationEvaluator, BaseEntity, BaseEntityResult, EntityPermissionType, Metadata, RunView, ValidationErrorInfo, ValidationErrorType, WellKnownUserSource, } from '@memberjunction/core';
8
8
  import { EscapeSQLString, IndexByUUID, RegisterClass, UUIDsEqual, UUIDSet } from '@memberjunction/global';
9
- import { MAX_AGENT_INHERITANCE_DEPTH, MJAIAgentEntityExtended, ParseAgentInstantiationConfig, } from '@memberjunction/ai-core-plus';
9
+ import { AGENT_ACCEPTS_SKILLS_RANK, AGENT_ARTIFACT_CREATION_MODE_RANK, AGENT_FINAL_VALIDATION_MODE_RANK, AGENT_ISOLATION_RANK, AGENT_MESSAGE_MODE_RANK, AGENT_SEARCH_SCOPE_ACCESS_RANK, AGENT_SKILL_ACTIVATION_RANK, AGENT_STARTING_VALIDATION_MODE_RANK, BuildAgentTypeConfigurationFromLegacyFields, DeepMergeAgentConfigurations, FindScopeConfigWideningViolations, FoldRebaseAwareChain, HasPathTraversalSegment, IntersectPayloadPathSets, IsAttachmentRootPathWithinAncestor, IsForbiddenMetadataHelperSeam, IsLegacyAIAgentConfigSqlDefault, IsPayloadPathSetWithinAncestor, IsPayloadScopeWithinAncestor, JsonHasAllowWidenFromBaseKey, LEGACY_AI_AGENT_CONFIG_SQL_DEFAULTS, MAX_AGENT_INHERITANCE_DEPTH, MJAIAgentEntityExtended, NARROW_ONLY_PROMPT_PARAM_GATES, NarrowAttachmentRootPath, NarrowPayloadScope, NarrowScopeConfigObjects, ParseAgentConfigJsonObject, ParseAgentConfiguration, ParseAgentHelperPlugins, ParseAgentInstantiationConfig, SyncAgentLegacyColumnsAndConfiguration, VALID_AGENT_HELPER_SEAMS, ValidateAgentConfigurationJson, ValidateLegacyAgentConfigFields, } from '@memberjunction/ai-core-plus';
10
10
  import { AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';
11
11
  import { ValidateJsonAgainstSchemaLite } from './json-schema-lite.js';
12
+ /**
13
+ * Canonical `MJ: Authorizations` capability name granting full administrative authority over
14
+ * AI Agents, Categories, Types, Step Types, and Personas. Evaluated with ancestors via
15
+ * `AuthorizationEvaluator` alongside the legacy administrative role fallback.
16
+ */
17
+ export const AI_AGENT_ADMINISTRATION_AUTHORIZATION = 'AI: Agent Administration';
12
18
  const ADMIN_ROLE_NAMES = new Set([
13
19
  'system administrator',
14
20
  'administrator',
@@ -16,12 +22,10 @@ const ADMIN_ROLE_NAMES = new Set([
16
22
  'administration',
17
23
  'agent administrator',
18
24
  ]);
19
- const ISOLATION_RANK = {
20
- InProcess: 0,
21
- Worker: 1,
22
- Process: 2,
23
- Container: 3,
24
- };
25
+ const ISOLATION_RANK = AGENT_ISOLATION_RANK;
26
+ const SEARCH_ACCESS_RANK = AGENT_SEARCH_SCOPE_ACCESS_RANK;
27
+ const ACCEPTS_SKILLS_RANK = AGENT_ACCEPTS_SKILLS_RANK;
28
+ const SKILL_ACTIVATION_RANK = AGENT_SKILL_ACTIVATION_RANK;
25
29
  /**
26
30
  * Type guard narrowing an `IEntityDataProvider` to `IMetadataProvider` when the provider
27
31
  * implements metadata/entity-instantiation methods (e.g., `SQLServerDataProvider`, `PostgreSQLDataProvider`).
@@ -29,19 +33,196 @@ const ISOLATION_RANK = {
29
33
  export function IsMetadataProvider(provider) {
30
34
  return Boolean(provider && 'GetEntityObject' in provider && 'Entities' in provider);
31
35
  }
36
+ function authorizationsForAdminCheck(provider) {
37
+ const mdProvider = provider && 'Authorizations' in provider && Array.isArray(provider.Authorizations)
38
+ ? provider
39
+ : undefined;
40
+ try {
41
+ const md = mdProvider ?? new Metadata();
42
+ return Array.isArray(md.Authorizations) ? md.Authorizations : [];
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
32
48
  /**
33
- * Returns true when `user` is an Owner-type user or holds an administrative / Agent Administrator role.
49
+ * Returns true when `user` is the server system user, an Owner-type user, holds the
50
+ * `AI: Agent Administration` authorization (direct or via an ancestor authorization), or holds
51
+ * an administrative / `Agent Administrator` role.
34
52
  */
35
- export function IsAgentAdminOrOwnerUser(user) {
53
+ export function IsAgentAdminOrOwnerUser(user, provider) {
36
54
  if (!user) {
37
55
  return true; // System / unauthenticated internal context
38
56
  }
39
- if (user.Type?.trim().toLowerCase() === 'owner') {
57
+ if (user.Type?.trim().toLowerCase() === 'owner' || WellKnownUserSource.Instance.IsSystemUser(user)) {
40
58
  return true;
41
59
  }
60
+ const authorizations = authorizationsForAdminCheck(provider);
61
+ if (authorizations.length > 0) {
62
+ const auth = authorizations.find((a) => a.Name?.trim().toLowerCase() === AI_AGENT_ADMINISTRATION_AUTHORIZATION.toLowerCase());
63
+ if (auth) {
64
+ const evaluator = new AuthorizationEvaluator();
65
+ if (evaluator.UserCanExecuteWithAncestors(auth, user, authorizations)) {
66
+ return true;
67
+ }
68
+ }
69
+ }
42
70
  const roles = user.UserRoles ?? [];
43
71
  return roles.some((ur) => ADMIN_ROLE_NAMES.has((ur.Role ?? '').trim().toLowerCase()));
44
72
  }
73
+ /**
74
+ * Shared `CheckPermissions` helper for admin-governed AI Agent definition entities
75
+ * (`MJ: AI Agent Categories`, `MJ: AI Agent Types`, `MJ: AI Agent Step Types`).
76
+ *
77
+ * Baseline `Developer` and `Integration` role grants on these entities are read-only
78
+ * (`CanRead: true`, `CanCreate/Update/Delete: false`), while `User: System` (and other `Owner`
79
+ * users or holders of the `AI: Agent Administration` authorization / admin roles) may not carry
80
+ * the dedicated `Agent Administrator` role in `UserRoles`. This helper authorizes those admin /
81
+ * owner / system callers for Create/Update/Delete once entity-level API flags allow the operation,
82
+ * while delegating reads and non-admin callers to `super.CheckPermissions`.
83
+ */
84
+ export function CheckAgentAdminEntityPermissions(context, type, throwError, superCheck) {
85
+ if (type === EntityPermissionType.Read) {
86
+ return superCheck(type, throwError);
87
+ }
88
+ const user = context.ActiveUser;
89
+ if (!user) {
90
+ return superCheck(type, throwError);
91
+ }
92
+ const info = context.EntityInfo;
93
+ if (!info || info.VirtualEntity) {
94
+ return superCheck(type, throwError);
95
+ }
96
+ const apiAllowed = (type === EntityPermissionType.Create && info.AllowCreateAPI) ||
97
+ (type === EntityPermissionType.Update && info.AllowUpdateAPI) ||
98
+ (type === EntityPermissionType.Delete && info.AllowDeleteAPI);
99
+ if (!apiAllowed) {
100
+ return superCheck(type, throwError);
101
+ }
102
+ if (IsAgentAdminOrOwnerUser(user, context.ProviderToUse)) {
103
+ return true;
104
+ }
105
+ return superCheck(type, throwError);
106
+ }
107
+ /**
108
+ * Resolves ordered narrow-only default policy layers (`AgentType -> Category Parent Chains`)
109
+ * for an agent chain `[...ancestors, target]`, mirroring `BaseAIEngine.ResolveEffectiveAgentProperties`.
110
+ */
111
+ function collectDefaultPolicyLayers(chain, allCategories, allAgentTypes) {
112
+ const layers = [];
113
+ let effectiveTypeId = null;
114
+ for (let i = chain.length - 1; i >= 0; i--) {
115
+ if (chain[i].TypeID) {
116
+ effectiveTypeId = chain[i].TypeID ?? null;
117
+ break;
118
+ }
119
+ }
120
+ if (effectiveTypeId && allAgentTypes && allAgentTypes.length > 0) {
121
+ const agentType = allAgentTypes.find((at) => UUIDsEqual(at.ID, effectiveTypeId));
122
+ if (agentType) {
123
+ const typeLegacy = BuildAgentTypeConfigurationFromLegacyFields(agentType);
124
+ const typeJson = ParseAgentConfiguration(agentType.DefaultAgentConfiguration);
125
+ const typeLayer = DeepMergeAgentConfigurations(typeLegacy, typeJson);
126
+ if (Object.keys(typeLayer).length > 0) {
127
+ layers.push(typeLayer);
128
+ }
129
+ }
130
+ }
131
+ if (allCategories && allCategories.length > 0) {
132
+ const catsById = IndexByUUID(allCategories);
133
+ const seenCatIds = new UUIDSet();
134
+ for (const node of chain) {
135
+ if (!node.CategoryID) {
136
+ continue;
137
+ }
138
+ const catChain = [];
139
+ const walkVisited = new UUIDSet();
140
+ let curId = node.CategoryID;
141
+ while (curId && !walkVisited.Has(curId)) {
142
+ walkVisited.Add(curId);
143
+ const cat = catsById.Get(curId);
144
+ if (!cat) {
145
+ break;
146
+ }
147
+ catChain.push(cat);
148
+ curId = cat.ParentID ?? null;
149
+ }
150
+ catChain.reverse();
151
+ for (const cat of catChain) {
152
+ if (seenCatIds.Has(cat.ID)) {
153
+ continue;
154
+ }
155
+ seenCatIds.Add(cat.ID);
156
+ const catJson = ParseAgentConfiguration(cat.DefaultConfiguration);
157
+ if (catJson) {
158
+ layers.push(catJson);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ return layers;
164
+ }
165
+ /**
166
+ * Computes the effective monotonic `SearchScopeAccess` ceiling across Category/Type default policy
167
+ * layers and the ancestor agent chain using the exact `R5-6` node-property rule shared with
168
+ * `BaseAIEngine.ResolveAgentConfiguration`:
169
+ * - Only treat an untouched legacy `'None'` (with no explicit JSON value) as unset on a
170
+ * non-instantiable derived row (`BaseAgentID != null && InstantiationMode === 'None'`).
171
+ * - Roots and instantiable templates (`InstantiationMode !== 'None'`) enforce `'None'` as an
172
+ * active ceiling.
173
+ */
174
+ function computeAncestorSearchScopeCeiling(defaultPolicyLayers, ancestors, ancestorConfigs) {
175
+ const narrow = (acc, val) => {
176
+ if (val == null)
177
+ return acc;
178
+ if (acc === null || SEARCH_ACCESS_RANK[val] < SEARCH_ACCESS_RANK[acc]) {
179
+ return val;
180
+ }
181
+ return acc;
182
+ };
183
+ let seed = null;
184
+ for (const layer of defaultPolicyLayers) {
185
+ seed = narrow(seed, layer.scope?.searchScopeAccess);
186
+ }
187
+ if (ancestors.length === 0) {
188
+ return seed;
189
+ }
190
+ const exp0 = ancestorConfigs[0]?.scope?.searchScopeAccess ?? null;
191
+ const leg0 = ancestors[0].SearchScopeAccess ?? null;
192
+ if (exp0 != null && leg0 != null) {
193
+ seed = narrow(seed, SEARCH_ACCESS_RANK[leg0] < SEARCH_ACCESS_RANK[exp0] ? leg0 : exp0);
194
+ }
195
+ else {
196
+ const isNonInst0 = Boolean(ancestors[0].BaseAgentID) && (ancestors[0].InstantiationMode ?? 'None') === 'None';
197
+ seed = narrow(seed, exp0 ?? (leg0 && (leg0 !== 'None' || !isNonInst0) ? leg0 : null));
198
+ }
199
+ return FoldRebaseAwareChain({
200
+ Nodes: ancestors,
201
+ NodeConfigs: ancestorConfigs,
202
+ Seed: seed,
203
+ GetNodeValue: (anc, cfg, idx) => {
204
+ const explicit = cfg?.scope?.searchScopeAccess ?? null;
205
+ const legacy = anc.SearchScopeAccess ?? null;
206
+ const canWiden = idx > 0 && cfg?.allowWidenFromBase === true;
207
+ if (canWiden) {
208
+ if (explicit != null)
209
+ return explicit;
210
+ return legacy != null && legacy !== 'None' ? legacy : undefined;
211
+ }
212
+ if (explicit != null && legacy != null) {
213
+ return SEARCH_ACCESS_RANK[legacy] < SEARCH_ACCESS_RANK[explicit] ? legacy : explicit;
214
+ }
215
+ if (explicit != null)
216
+ return explicit;
217
+ const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
218
+ if (legacy != null && (legacy !== 'None' || !isNonInst)) {
219
+ return legacy;
220
+ }
221
+ return undefined;
222
+ },
223
+ Narrow: (acc, next) => narrow(acc, next),
224
+ });
225
+ }
45
226
  /**
46
227
  * PURE validation core for `BaseAgentID` prototype inheritance integrity and non-Owner (`UI` role)
47
228
  * sandboxing (exported for unit tests and called by {@link MJAIAgentEntityServer.ValidateAsync}):
@@ -63,7 +244,67 @@ export function IsAgentAdminOrOwnerUser(user) {
63
244
  export function ValidateAgentInheritanceAndSandbox(ctx) {
64
245
  const errors = [];
65
246
  const { Target, User, AllAgents, AllPermissions } = ctx;
66
- const isAdmin = IsAgentAdminOrOwnerUser(User);
247
+ const isAdmin = IsAgentAdminOrOwnerUser(User, ctx.Provider);
248
+ // 0. Per-agent helperPlugins security guard (Extension Point #3):
249
+ // - Code-only security seams (limits, actionPolicy, policy, permissions) are forbidden in
250
+ // metadata for ALL users (including administrators).
251
+ // - Non-administrator users cannot configure ANY helperPlugins on personal agent instances.
252
+ const declaredHelperPlugins = [
253
+ ...ParseAgentHelperPlugins(Target.Configuration),
254
+ ...ParseAgentHelperPlugins(Target.TypeConfiguration),
255
+ ];
256
+ const jsonHasHelperPluginsKey = (raw) => {
257
+ if (!raw || raw.trim().length === 0)
258
+ return false;
259
+ try {
260
+ const parsed = JSON.parse(raw);
261
+ return Boolean(parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'helperPlugins'));
262
+ }
263
+ catch {
264
+ return false;
265
+ }
266
+ };
267
+ const hasHelperPluginsKey = jsonHasHelperPluginsKey(Target.Configuration) || jsonHasHelperPluginsKey(Target.TypeConfiguration);
268
+ for (const plugin of declaredHelperPlugins) {
269
+ if (IsForbiddenMetadataHelperSeam(plugin.seam)) {
270
+ errors.push(new ValidationErrorInfo('Configuration', `Helper seam '${plugin.seam}' is code-only and cannot be overridden via agent metadata helperPlugins (driverClass '${plugin.driverClass}'). Use @RegisterClass in server code instead.`, plugin.seam, ValidationErrorType.Failure));
271
+ }
272
+ else if (!VALID_AGENT_HELPER_SEAMS.has(plugin.seam.trim())) {
273
+ errors.push(new ValidationErrorInfo('Configuration', `Helper seam '${plugin.seam}' is not a valid helper seam (driverClass '${plugin.driverClass}'). Valid seams: ${Array.from(VALID_AGENT_HELPER_SEAMS).join(', ')}.`, plugin.seam, ValidationErrorType.Failure));
274
+ }
275
+ }
276
+ const helperConfigDirty = !Target.IsSaved ||
277
+ !Target.DirtyFields ||
278
+ Target.DirtyFields.has('Configuration') ||
279
+ Target.DirtyFields.has('TypeConfiguration');
280
+ if (!isAdmin && User && helperConfigDirty && (declaredHelperPlugins.length > 0 || hasHelperPluginsKey)) {
281
+ errors.push(new ValidationErrorInfo('Configuration', 'Only administrators may configure helperPlugins (including clearing/modifying the key) on an AI Agent.', declaredHelperPlugins.map((p) => `${p.seam}:${p.driverClass}`).join(', '), ValidationErrorType.Failure));
282
+ }
283
+ // 0b. Admin-only Configuration.allowWidenFromBase guard:
284
+ // Non-administrator users cannot set, modify, or clear `allowWidenFromBase` on save.
285
+ const configDirty = !Target.IsSaved || !Target.DirtyFields || Target.DirtyFields.has('Configuration');
286
+ if (!isAdmin &&
287
+ User &&
288
+ configDirty &&
289
+ (JsonHasAllowWidenFromBaseKey(Target.Configuration) ||
290
+ JsonHasAllowWidenFromBaseKey(Target.PreSaveConfiguration))) {
291
+ errors.push(new ValidationErrorInfo('Configuration', 'Only administrators may set, modify, or clear Configuration.allowWidenFromBase on an AI Agent.', Target.Configuration, ValidationErrorType.Failure));
292
+ }
293
+ // 0c. Path-traversal guard on PayloadScope and AttachmentRootPath (ALL users, root or derived,
294
+ // even when allowWidenFromBase === true).
295
+ const preParsedTargetConfig = ParseAgentConfiguration(Target.Configuration);
296
+ const rawTargetPayloadScope = preParsedTargetConfig?.payload?.scope !== undefined
297
+ ? preParsedTargetConfig.payload.scope
298
+ : Target.PayloadScope;
299
+ if (HasPathTraversalSegment(rawTargetPayloadScope)) {
300
+ errors.push(new ValidationErrorInfo('PayloadScope', `PayloadScope ('${rawTargetPayloadScope}') cannot contain '..' path traversal segments.`, rawTargetPayloadScope, ValidationErrorType.Failure));
301
+ }
302
+ const rawTargetAttachRoot = preParsedTargetConfig?.attachments?.rootPath !== undefined
303
+ ? preParsedTargetConfig.attachments.rootPath
304
+ : Target.AttachmentRootPath;
305
+ if (HasPathTraversalSegment(rawTargetAttachRoot)) {
306
+ errors.push(new ValidationErrorInfo('AttachmentRootPath', `AttachmentRootPath ('${rawTargetAttachRoot}') cannot contain '..' path traversal segments.`, rawTargetAttachRoot, ValidationErrorType.Failure));
307
+ }
67
308
  // 1. Non-admin sandbox on root vs derived + ownership + InstantiationMode
68
309
  if (!isAdmin && User) {
69
310
  const effectiveBaseId = Target.BaseAgentID;
@@ -102,8 +343,11 @@ export function ValidateAgentInheritanceAndSandbox(ctx) {
102
343
  errors.push(new ValidationErrorInfo('BaseAgentID', `BaseAgentID '${Target.BaseAgentID}' does not reference an existing AI Agent.`, Target.BaseAgentID, ValidationErrorType.Failure));
103
344
  return errors;
104
345
  }
105
- // Walk up BaseAgentID chain to detect cycles and enforce max depth (5 hops)
346
+ // Walk up BaseAgentID chain to detect cycles, enforce max depth (5 hops), and collect full
347
+ // ancestor chain (`ancestors[0]` = root, `ancestors[ancestors.length - 1]` = immediate baseAgent)
348
+ // so multi-hop capability and limit ceilings are enforced across every ancestor.
106
349
  const visited = new UUIDSet(Target.ID ? [Target.ID] : []);
350
+ const ancestorsBottomUp = [];
107
351
  let cursor = baseAgent;
108
352
  let hops = 1; // Target -> baseAgent is hop 1
109
353
  while (cursor) {
@@ -112,6 +356,7 @@ export function ValidateAgentInheritanceAndSandbox(ctx) {
112
356
  return errors;
113
357
  }
114
358
  visited.Add(cursor.ID);
359
+ ancestorsBottomUp.push(cursor);
115
360
  if (hops > MAX_AGENT_INHERITANCE_DEPTH) {
116
361
  errors.push(new ValidationErrorInfo('BaseAgentID', `Agent prototype inheritance depth exceeds maximum allowed depth of ${MAX_AGENT_INHERITANCE_DEPTH}.`, Target.BaseAgentID, ValidationErrorType.Failure));
117
362
  return errors;
@@ -126,48 +371,914 @@ export function ValidateAgentInheritanceAndSandbox(ctx) {
126
371
  cursor = nextParent;
127
372
  hops++;
128
373
  }
129
- // 3. InstantiationMode & maxInstancesPerUser check on create
374
+ const ancestors = [...ancestorsBottomUp].reverse(); // root -> ... -> baseAgent
375
+ const defaultPolicyLayers = collectDefaultPolicyLayers([...ancestors, Target], ctx.AllCategories, ctx.AllAgentTypes);
376
+ // 3. InstantiationMode & maxInstancesPerUser check on create (R5-7: monotonic Math.min across
377
+ // AgentType -> Categories -> root..baseAgent, counted per root base agent matching
378
+ // ManageMyAgentInstanceAction and BaseAIEngine.ResolveEffectiveAgentProperties)
130
379
  if (!Target.IsSaved) {
131
380
  if (!isAdmin && (baseAgent.InstantiationMode ?? 'None') === 'None') {
132
381
  errors.push(new ValidationErrorInfo('BaseAgentID', `Agent '${baseAgent.Name ?? baseAgent.ID}' does not allow creating derived instances (InstantiationMode is 'None').`, Target.BaseAgentID, ValidationErrorType.Failure));
133
382
  }
134
- const instCfg = ParseAgentInstantiationConfig(baseAgent.TypeConfiguration);
383
+ const ancestorConfigsForInst = ancestors.map((a) => ParseAgentConfiguration(a.Configuration));
384
+ const sanitizePosInt = (v) => typeof v === 'number' && Number.isFinite(v) && Math.floor(v) >= 1 ? Math.floor(v) : null;
385
+ const minInstVal = (a, b) => b === null ? a : a === null ? b : Math.min(a, b);
386
+ let seedMaxPerUser = null;
387
+ for (const layer of defaultPolicyLayers) {
388
+ seedMaxPerUser = minInstVal(seedMaxPerUser, sanitizePosInt(layer.instantiation?.maxInstancesPerUser));
389
+ }
390
+ if (ancestors.length > 0) {
391
+ seedMaxPerUser = minInstVal(seedMaxPerUser, sanitizePosInt(ancestorConfigsForInst[0]?.instantiation?.maxInstancesPerUser));
392
+ seedMaxPerUser = minInstVal(seedMaxPerUser, sanitizePosInt(ParseAgentInstantiationConfig(ancestors[0].TypeConfiguration)?.maxInstancesPerUser));
393
+ }
394
+ const effectiveMaxPerUser = FoldRebaseAwareChain({
395
+ Nodes: ancestors,
396
+ NodeConfigs: ancestorConfigsForInst,
397
+ Seed: seedMaxPerUser,
398
+ GetNodeValue: (anc, cfg, idx) => {
399
+ const fromJson = sanitizePosInt(cfg?.instantiation?.maxInstancesPerUser);
400
+ const fromTypeCfg = sanitizePosInt(ParseAgentInstantiationConfig(anc.TypeConfiguration)?.maxInstancesPerUser);
401
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
402
+ if (fromJson !== null)
403
+ return fromJson;
404
+ return fromTypeCfg !== null ? fromTypeCfg : undefined;
405
+ }
406
+ const combined = minInstVal(fromJson, fromTypeCfg);
407
+ return combined !== null ? combined : undefined;
408
+ },
409
+ Narrow: (acc, next) => minInstVal(acc, next),
410
+ });
135
411
  const ownerId = Target.OwnerUserID ?? User?.ID ?? null;
136
- if (instCfg?.maxInstancesPerUser && ownerId) {
412
+ const isCreatingPersonalInstance = (Target.InstantiationMode ?? 'None') === 'None';
413
+ if (effectiveMaxPerUser !== null && ownerId && isCreatingPersonalInstance) {
414
+ const resolveRootId = (agent) => {
415
+ const seen = new UUIDSet([agent.ID]);
416
+ let cur = agent;
417
+ let depth = 0;
418
+ while (cur.BaseAgentID && depth < MAX_AGENT_INHERITANCE_DEPTH) {
419
+ if (seen.Has(cur.BaseAgentID))
420
+ break;
421
+ seen.Add(cur.BaseAgentID);
422
+ const p = agentsById.Get(cur.BaseAgentID);
423
+ if (!p)
424
+ return cur.BaseAgentID;
425
+ cur = p;
426
+ depth++;
427
+ }
428
+ return cur.ID;
429
+ };
430
+ const rootBaseId = resolveRootId(baseAgent);
137
431
  const existingCount = AllAgents.filter((a) => a.Status === 'Active' &&
138
432
  a.BaseAgentID != null &&
139
- UUIDsEqual(a.BaseAgentID, baseAgent.ID) &&
140
- UUIDsEqual(a.OwnerUserID, ownerId)).length;
141
- if (existingCount >= instCfg.maxInstancesPerUser) {
142
- errors.push(new ValidationErrorInfo('BaseAgentID', `Maximum of ${instCfg.maxInstancesPerUser} active instance(s) of '${baseAgent.Name ?? baseAgent.ID}' per user reached.`, Target.BaseAgentID, ValidationErrorType.Failure));
433
+ (a.InstantiationMode ?? 'None') === 'None' &&
434
+ UUIDsEqual(a.OwnerUserID, ownerId) &&
435
+ UUIDsEqual(resolveRootId(a), rootBaseId)).length;
436
+ if (existingCount >= effectiveMaxPerUser) {
437
+ errors.push(new ValidationErrorInfo('BaseAgentID', `Maximum of ${effectiveMaxPerUser} active instance(s) of '${baseAgent.Name ?? baseAgent.ID}' per user reached.`, Target.BaseAgentID, ValidationErrorType.Failure));
143
438
  }
144
439
  }
145
440
  }
146
- // 4. Non-admin runtime capability & bounds sandbox against baseAgent
441
+ const ancestorConfigs = ancestors.map((a) => ParseAgentConfiguration(a.Configuration));
442
+ const targetConfig = preParsedTargetConfig;
443
+ const targetAllowsWiden = targetConfig?.allowWidenFromBase === true;
444
+ const baseAgentLabel = baseAgent.Name ?? baseAgent.ID;
445
+ // Helper for R2-3 & R3-5: on existing saved instances where DirtyFields is tracked, only
446
+ // re-check narrow-only columns and numeric ceilings that were actually modified (or when
447
+ // Configuration or BaseAgentID itself was modified) so an admin tightening a base agent
448
+ // never breaks unrelated edits (rename/persona) on pre-existing derived instances while
449
+ // attaching/re-parenting BaseAgentID enforces every invariant.
450
+ const shouldEnforceField = (fieldName) => {
451
+ if (!Target.IsSaved || !Target.DirtyFields) {
452
+ return true;
453
+ }
454
+ return (Target.DirtyFields.has(fieldName) ||
455
+ Target.DirtyFields.has('Configuration') ||
456
+ Target.DirtyFields.has('BaseAgentID'));
457
+ };
458
+ const widenHint = (fieldName, detail) => `Derived agent cannot widen ${fieldName} ${detail} beyond base agent '${baseAgentLabel}'. Set Configuration.allowWidenFromBase = true (Admin only) if intentional.`;
459
+ // 4A. Non-admin-only sandbox checks (CanRun, DriverClass, CategoryID, TypeID)
147
460
  if (!isAdmin && User) {
148
461
  const basePerms = AIAgentPermissionHelper.ComputeEffectivePermissionsSync(baseAgent, AllAgents, AllPermissions, User);
149
462
  if (!basePerms.canRun) {
150
- errors.push(new ValidationErrorInfo('BaseAgentID', `You do not have permission to run base agent '${baseAgent.Name ?? baseAgent.ID}'.`, Target.BaseAgentID, ValidationErrorType.Failure));
463
+ errors.push(new ValidationErrorInfo('BaseAgentID', `You do not have permission to run base agent '${baseAgentLabel}'.`, Target.BaseAgentID, ValidationErrorType.Failure));
464
+ }
465
+ // DriverClass: compare unconditionally against nearest non-null ancestor DriverClass
466
+ let effectiveAncestorDriver = null;
467
+ for (let i = ancestors.length - 1; i >= 0; i--) {
468
+ const d = ancestors[i].DriverClass?.trim();
469
+ if (d) {
470
+ effectiveAncestorDriver = d;
471
+ break;
472
+ }
151
473
  }
152
- const baseDriver = baseAgent.DriverClass?.trim() || null;
153
474
  const targetDriver = Target.DriverClass?.trim() || null;
154
- if (Target.DriverClassDirty && targetDriver !== null && targetDriver !== baseDriver) {
475
+ if (targetDriver !== null && targetDriver !== effectiveAncestorDriver) {
155
476
  errors.push(new ValidationErrorInfo('DriverClass', 'Non-administrator users cannot set a custom DriverClass on a derived agent instance.', Target.DriverClass, ValidationErrorType.Failure));
156
477
  }
157
- const baseIsoRank = ISOLATION_RANK[baseAgent.Isolation ?? 'InProcess'] ?? 0;
158
- const targetIsoRank = ISOLATION_RANK[Target.Isolation ?? 'InProcess'] ?? 0;
159
- if (targetIsoRank < baseIsoRank) {
160
- errors.push(new ValidationErrorInfo('Isolation', `Derived agent Isolation ('${Target.Isolation}') cannot be less strict than base agent Isolation ('${baseAgent.Isolation}').`, Target.Isolation, ValidationErrorType.Failure));
478
+ // CategoryID / TypeID sandbox (S2, R2-4): non-admins cannot re-point or assign a derived
479
+ // instance's CategoryID or TypeID away from its base agent chain (or assign a loose category
480
+ // when the pre-save value was null).
481
+ let effectiveAncestorCategoryId = null;
482
+ let effectiveAncestorTypeId = null;
483
+ for (let i = ancestors.length - 1; i >= 0; i--) {
484
+ if (!effectiveAncestorCategoryId && ancestors[i].CategoryID) {
485
+ effectiveAncestorCategoryId = ancestors[i].CategoryID ?? null;
486
+ }
487
+ if (!effectiveAncestorTypeId && ancestors[i].TypeID) {
488
+ effectiveAncestorTypeId = ancestors[i].TypeID ?? null;
489
+ }
161
490
  }
162
- const checkUpperBound = (fieldName, baseLimit, childLimit) => {
163
- if (baseLimit != null && childLimit != null && childLimit > baseLimit) {
164
- errors.push(new ValidationErrorInfo(fieldName, `Derived agent ${fieldName} (${childLimit}) cannot exceed base agent ceiling (${baseLimit}).`, childLimit, ValidationErrorType.Failure));
491
+ if (Target.CategoryID !== undefined) {
492
+ const expectedCat = Target.IsSaved ? (Target.PreSaveCategoryID ?? effectiveAncestorCategoryId) : effectiveAncestorCategoryId;
493
+ if (expectedCat && Target.CategoryID && !UUIDsEqual(Target.CategoryID, expectedCat)) {
494
+ errors.push(new ValidationErrorInfo('CategoryID', 'Non-administrator users cannot reassign CategoryID on a derived agent instance.', Target.CategoryID, ValidationErrorType.Failure));
495
+ }
496
+ else if (!expectedCat && Target.CategoryID && (!Target.IsSaved || !Target.DirtyFields || Target.DirtyFields.has('CategoryID'))) {
497
+ errors.push(new ValidationErrorInfo('CategoryID', 'Non-administrator users cannot assign CategoryID on a derived agent instance.', Target.CategoryID, ValidationErrorType.Failure));
498
+ }
499
+ else if (expectedCat && Target.CategoryID === null && Target.DirtyFields?.has('CategoryID')) {
500
+ errors.push(new ValidationErrorInfo('CategoryID', 'Non-administrator users cannot clear CategoryID on a derived agent instance.', null, ValidationErrorType.Failure));
501
+ }
502
+ }
503
+ if (Target.TypeID !== undefined) {
504
+ const expectedType = Target.IsSaved ? (Target.PreSaveTypeID ?? effectiveAncestorTypeId) : effectiveAncestorTypeId;
505
+ if (expectedType && Target.TypeID && !UUIDsEqual(Target.TypeID, expectedType)) {
506
+ errors.push(new ValidationErrorInfo('TypeID', 'Non-administrator users cannot reassign TypeID on a derived agent instance.', Target.TypeID, ValidationErrorType.Failure));
507
+ }
508
+ else if (!expectedType && Target.TypeID && (!Target.IsSaved || !Target.DirtyFields || Target.DirtyFields.has('TypeID'))) {
509
+ errors.push(new ValidationErrorInfo('TypeID', 'Non-administrator users cannot assign TypeID on a derived agent instance.', Target.TypeID, ValidationErrorType.Failure));
510
+ }
511
+ else if (expectedType && Target.TypeID === null && Target.DirtyFields?.has('TypeID')) {
512
+ errors.push(new ValidationErrorInfo('TypeID', 'Non-administrator users cannot clear TypeID on a derived agent instance.', null, ValidationErrorType.Failure));
513
+ }
514
+ }
515
+ }
516
+ // 4B. Unconditional derived invariants (ALL users, including Admins AND even with allowWidenFromBase === true)
517
+ // - Isolation minimum (InProcess < Worker < Process < Container)
518
+ // - Cross-cascade effectiveMinExecutionsPerRun <= effectiveMaxExecutionsPerRun
519
+ let strictestAncestorIsolation = 'InProcess';
520
+ for (const anc of ancestors) {
521
+ const ancIso = anc.Isolation ?? 'InProcess';
522
+ if ((ISOLATION_RANK[ancIso] ?? 0) > (ISOLATION_RANK[strictestAncestorIsolation] ?? 0)) {
523
+ strictestAncestorIsolation = ancIso;
524
+ }
525
+ }
526
+ const targetIsoRank = ISOLATION_RANK[Target.Isolation ?? 'InProcess'] ?? 0;
527
+ if (shouldEnforceField('Isolation') && targetIsoRank < (ISOLATION_RANK[strictestAncestorIsolation] ?? 0)) {
528
+ errors.push(new ValidationErrorInfo('Isolation', `Derived agent Isolation ('${Target.Isolation}') cannot be less strict than ancestor Isolation ('${strictestAncestorIsolation}').`, Target.Isolation, ValidationErrorType.Failure));
529
+ }
530
+ const computeRebaseAncestorMin = (layerPicker, nodeJsonPicker, nodeLegacyPicker, sqlDefault = null) => {
531
+ const minFin = (a, b) => {
532
+ if (typeof b !== 'number' || !Number.isFinite(b))
533
+ return a;
534
+ return a === null ? b : Math.min(a, b);
535
+ };
536
+ let seed = null;
537
+ for (const layer of defaultPolicyLayers) {
538
+ seed = minFin(seed, layerPicker(layer));
539
+ }
540
+ if (ancestors.length > 0) {
541
+ const exp0 = nodeJsonPicker(ancestorConfigs[0]);
542
+ const leg0 = nodeLegacyPicker(ancestors[0]);
543
+ const leg0Eff = exp0 === undefined && sqlDefault !== null && leg0 === sqlDefault && seed !== null ? null : leg0;
544
+ seed = minFin(seed, exp0);
545
+ seed = minFin(seed, leg0Eff);
546
+ }
547
+ return FoldRebaseAwareChain({
548
+ Nodes: ancestors,
549
+ NodeConfigs: ancestorConfigs,
550
+ Seed: seed,
551
+ GetNodeValue: (anc, cfg, idx) => {
552
+ const explicit = nodeJsonPicker(cfg);
553
+ const legacy = nodeLegacyPicker(anc);
554
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
555
+ if (explicit === null)
556
+ return null;
557
+ if (typeof explicit === 'number' && Number.isFinite(explicit))
558
+ return explicit;
559
+ if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy !== sqlDefault)
560
+ return legacy;
561
+ return undefined;
562
+ }
563
+ if (typeof explicit === 'number' && Number.isFinite(explicit)) {
564
+ if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy !== sqlDefault) {
565
+ return Math.min(explicit, legacy);
566
+ }
567
+ return explicit;
568
+ }
569
+ if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy !== sqlDefault) {
570
+ return legacy;
571
+ }
572
+ return undefined;
573
+ },
574
+ Narrow: (acc, next) => minFin(acc, next),
575
+ });
576
+ };
577
+ // Cross-cascade effectiveMinExecutionsPerRun <= effectiveMaxExecutionsPerRun
578
+ const ancestorMaxExecutions = computeRebaseAncestorMin((l) => l.subAgentExecution?.maxExecutionsPerRun, (cfg) => cfg?.subAgentExecution?.maxExecutionsPerRun, (a) => a.MaxExecutionsPerRun);
579
+ const targetMaxExecutions = targetConfig?.subAgentExecution?.maxExecutionsPerRun !== undefined
580
+ ? targetConfig.subAgentExecution.maxExecutionsPerRun
581
+ : Target.MaxExecutionsPerRun;
582
+ const effectiveMaxExecAcrossCascade = targetAllowsWiden
583
+ ? targetMaxExecutions !== undefined
584
+ ? targetMaxExecutions
585
+ : ancestorMaxExecutions
586
+ : typeof targetMaxExecutions === 'number' && Number.isFinite(targetMaxExecutions)
587
+ ? ancestorMaxExecutions !== null
588
+ ? Math.min(ancestorMaxExecutions, targetMaxExecutions)
589
+ : targetMaxExecutions
590
+ : ancestorMaxExecutions;
591
+ let effectiveMinExecAcrossCascade = null;
592
+ for (const layer of defaultPolicyLayers) {
593
+ if (typeof layer.subAgentExecution?.minExecutionsPerRun === 'number') {
594
+ effectiveMinExecAcrossCascade = layer.subAgentExecution.minExecutionsPerRun;
595
+ }
596
+ }
597
+ for (let i = 0; i < ancestors.length; i++) {
598
+ const v = ancestorConfigs[i]?.subAgentExecution?.minExecutionsPerRun ?? ancestors[i].MinExecutionsPerRun;
599
+ if (typeof v === 'number' && Number.isFinite(v)) {
600
+ effectiveMinExecAcrossCascade = v;
601
+ }
602
+ }
603
+ const targetMinExec = targetConfig?.subAgentExecution?.minExecutionsPerRun !== undefined
604
+ ? targetConfig.subAgentExecution.minExecutionsPerRun
605
+ : Target.MinExecutionsPerRun;
606
+ if (typeof targetMinExec === 'number' && Number.isFinite(targetMinExec)) {
607
+ effectiveMinExecAcrossCascade = targetMinExec;
608
+ }
609
+ else if (targetMinExec === null && targetConfig?.subAgentExecution?.minExecutionsPerRun === null) {
610
+ effectiveMinExecAcrossCascade = null;
611
+ }
612
+ if ((shouldEnforceField('MinExecutionsPerRun') || shouldEnforceField('MaxExecutionsPerRun')) &&
613
+ effectiveMinExecAcrossCascade !== null &&
614
+ effectiveMaxExecAcrossCascade !== null &&
615
+ effectiveMinExecAcrossCascade > effectiveMaxExecAcrossCascade) {
616
+ errors.push(new ValidationErrorInfo('MinExecutionsPerRun', `Effective MinExecutionsPerRun (${effectiveMinExecAcrossCascade}) across the BaseAgentID cascade cannot exceed effective MaxExecutionsPerRun (${effectiveMaxExecAcrossCascade}).`, effectiveMinExecAcrossCascade, ValidationErrorType.Failure));
617
+ }
618
+ // 4C. Non-widening ceiling & capability enforcement for ALL users (including Admins!) unless
619
+ // Configuration.allowWidenFromBase === true (eliminates save-time vs runtime split-brain).
620
+ if (!targetAllowsWiden) {
621
+ const checkMultiHopUpperBound = (fieldName, effectiveCeiling, childLimit, explicitJsonVal, sqlDefault = null) => {
622
+ if (!shouldEnforceField(fieldName)) {
623
+ return;
624
+ }
625
+ if (effectiveCeiling === null) {
626
+ return;
627
+ }
628
+ // Ignore untouched SQL default values when JSON didn't set the key and the field wasn't dirtied
629
+ if (sqlDefault !== null &&
630
+ explicitJsonVal === undefined &&
631
+ childLimit === sqlDefault &&
632
+ Target.DirtyFields &&
633
+ !Target.DirtyFields.has(fieldName)) {
634
+ return;
635
+ }
636
+ if (childLimit === null) {
637
+ const isExplicitClear = (Target.IsSaved &&
638
+ Target.DirtyFields?.has(fieldName) === true &&
639
+ typeof Target.PreSaveLimits?.[fieldName] === 'number') ||
640
+ explicitJsonVal === null;
641
+ if (isExplicitClear) {
642
+ errors.push(new ValidationErrorInfo(fieldName, widenHint(fieldName, `(cleared to null vs ceiling ${effectiveCeiling})`), null, ValidationErrorType.Failure));
643
+ }
644
+ return;
645
+ }
646
+ if (typeof childLimit === 'number' && childLimit > effectiveCeiling) {
647
+ errors.push(new ValidationErrorInfo(fieldName, widenHint(fieldName, `(${childLimit} > ceiling ${effectiveCeiling})`), childLimit, ValidationErrorType.Failure));
648
+ }
649
+ };
650
+ checkMultiHopUpperBound('MaxCostPerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxCostPerRun), Target.MaxCostPerRun, undefined);
651
+ checkMultiHopUpperBound('MaxTokensPerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxTokensPerRun), Target.MaxTokensPerRun, undefined);
652
+ checkMultiHopUpperBound('MaxTimePerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxTimePerRun), Target.MaxTimePerRun, undefined);
653
+ checkMultiHopUpperBound('MaxIterationsPerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxIterationsPerRun), Target.MaxIterationsPerRun, undefined);
654
+ checkMultiHopUpperBound('MaxExecutionsPerRun', ancestorMaxExecutions, targetMaxExecutions, targetConfig?.subAgentExecution?.maxExecutionsPerRun);
655
+ checkMultiHopUpperBound('MaxSubAgentConsultRounds', computeRebaseAncestorMin((l) => l.subAgentExecution?.maxConsultRounds, (cfg) => cfg?.subAgentExecution?.maxConsultRounds, (a) => a.MaxSubAgentConsultRounds), targetConfig?.subAgentExecution?.maxConsultRounds !== undefined
656
+ ? targetConfig.subAgentExecution.maxConsultRounds
657
+ : Target.MaxSubAgentConsultRounds, targetConfig?.subAgentExecution?.maxConsultRounds);
658
+ checkMultiHopUpperBound('ContextWindowMaxTokens', computeRebaseAncestorMin((l) => l.contextWindow?.maxTokens, (cfg) => cfg?.contextWindow?.maxTokens, (a) => a.ContextWindowMaxTokens), targetConfig?.contextWindow?.maxTokens !== undefined
659
+ ? targetConfig.contextWindow.maxTokens
660
+ : Target.ContextWindowMaxTokens, targetConfig?.contextWindow?.maxTokens);
661
+ checkMultiHopUpperBound('MaxNotesToInject', computeRebaseAncestorMin((l) => l.memory?.maxNotesToInject, (cfg) => cfg?.memory?.maxNotesToInject, (a) => a.MaxNotesToInject, 5 // SQL schema default DF_AIAgent_MaxNotesToInject
662
+ ), targetConfig?.memory?.maxNotesToInject !== undefined
663
+ ? targetConfig.memory.maxNotesToInject
664
+ : Target.MaxNotesToInject, targetConfig?.memory?.maxNotesToInject, 5 // SQL schema default DF_AIAgent_MaxNotesToInject
665
+ );
666
+ checkMultiHopUpperBound('MaxExamplesToInject', computeRebaseAncestorMin((l) => l.memory?.maxExamplesToInject, (cfg) => cfg?.memory?.maxExamplesToInject, (a) => a.MaxExamplesToInject, 3 // SQL schema default DF_AIAgent_MaxExamplesToInject
667
+ ), targetConfig?.memory?.maxExamplesToInject !== undefined
668
+ ? targetConfig.memory.maxExamplesToInject
669
+ : Target.MaxExamplesToInject, targetConfig?.memory?.maxExamplesToInject, 3 // SQL schema default DF_AIAgent_MaxExamplesToInject
670
+ );
671
+ const ancestorNoteRetentionDays = computeRebaseAncestorMin((l) => l.memory?.noteRetentionDays, (cfg) => cfg?.memory?.noteRetentionDays, (a) => a.NoteRetentionDays, 90 // SQL schema default DF_AIAgent_NoteRetentionDays
672
+ );
673
+ checkMultiHopUpperBound('NoteRetentionDays', ancestorNoteRetentionDays, targetConfig?.memory?.noteRetentionDays !== undefined
674
+ ? targetConfig.memory.noteRetentionDays
675
+ : Target.NoteRetentionDays, targetConfig?.memory?.noteRetentionDays, 90 // SQL schema default DF_AIAgent_NoteRetentionDays
676
+ );
677
+ const ancestorExampleRetentionDays = computeRebaseAncestorMin((l) => l.memory?.exampleRetentionDays, (cfg) => cfg?.memory?.exampleRetentionDays, (a) => a.ExampleRetentionDays, 180 // SQL schema default DF_AIAgent_ExampleRetentionDays
678
+ );
679
+ checkMultiHopUpperBound('ExampleRetentionDays', ancestorExampleRetentionDays, targetConfig?.memory?.exampleRetentionDays !== undefined
680
+ ? targetConfig.memory.exampleRetentionDays
681
+ : Target.ExampleRetentionDays, targetConfig?.memory?.exampleRetentionDays, 180 // SQL schema default DF_AIAgent_ExampleRetentionDays
682
+ );
683
+ checkMultiHopUpperBound('MaxMessages', computeRebaseAncestorMin((l) => l.attachments?.maxMessages, (cfg) => cfg?.attachments?.maxMessages, (a) => a.MaxMessages), targetConfig?.attachments?.maxMessages !== undefined
684
+ ? targetConfig.attachments.maxMessages
685
+ : Target.MaxMessages, targetConfig?.attachments?.maxMessages);
686
+ checkMultiHopUpperBound('InlineStorageThresholdBytes', computeRebaseAncestorMin((l) => l.attachments?.inlineStorageThresholdBytes, (cfg) => cfg?.attachments?.inlineStorageThresholdBytes, (a) => a.InlineStorageThresholdBytes), targetConfig?.attachments?.inlineStorageThresholdBytes !== undefined
687
+ ? targetConfig.attachments.inlineStorageThresholdBytes
688
+ : Target.InlineStorageThresholdBytes, targetConfig?.attachments?.inlineStorageThresholdBytes);
689
+ checkMultiHopUpperBound('FinalPayloadValidationMaxRetries', computeRebaseAncestorMin((l) => l.payload?.finalValidationMaxRetries, (cfg) => cfg?.payload?.finalValidationMaxRetries, (a) => a.FinalPayloadValidationMaxRetries, 3 // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
690
+ ), targetConfig?.payload?.finalValidationMaxRetries !== undefined
691
+ ? targetConfig.payload.finalValidationMaxRetries
692
+ : Target.FinalPayloadValidationMaxRetries, targetConfig?.payload?.finalValidationMaxRetries, 3 // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
693
+ );
694
+ // instantiation.maxInstancesPerUser ceiling (cannot raise above ancestor ceiling)
695
+ const ancestorMaxInstances = computeRebaseAncestorMin((l) => l.instantiation?.maxInstancesPerUser, (cfg) => cfg?.instantiation?.maxInstancesPerUser, (a) => ParseAgentInstantiationConfig(a.TypeConfiguration)?.maxInstancesPerUser);
696
+ const targetMaxInstances = targetConfig?.instantiation?.maxInstancesPerUser ??
697
+ ParseAgentInstantiationConfig(Target.TypeConfiguration)?.maxInstancesPerUser;
698
+ if (shouldEnforceField('Configuration') &&
699
+ ancestorMaxInstances !== null &&
700
+ typeof targetMaxInstances === 'number' &&
701
+ targetMaxInstances > ancestorMaxInstances) {
702
+ errors.push(new ValidationErrorInfo('Configuration', widenHint('instantiation.maxInstancesPerUser', `(${targetMaxInstances} > ceiling ${ancestorMaxInstances})`), targetMaxInstances, ValidationErrorType.Failure));
703
+ }
704
+ // Narrow-only capabilities validated across BOTH Configuration JSON and legacy columns
705
+ // as well as Category/AgentType default policy layers (rebase-aware across ancestors):
706
+ // 4a. SearchScopeAccess (None: 0 < Assigned: 1 < All: 2)
707
+ const ancestorSearchAccess = computeAncestorSearchScopeCeiling(defaultPolicyLayers, ancestors, ancestorConfigs);
708
+ const targetSearchAccess = targetConfig?.scope?.searchScopeAccess ?? Target.SearchScopeAccess ?? null;
709
+ if (shouldEnforceField('SearchScopeAccess') &&
710
+ ancestorSearchAccess !== null &&
711
+ targetSearchAccess !== null &&
712
+ SEARCH_ACCESS_RANK[targetSearchAccess] > SEARCH_ACCESS_RANK[ancestorSearchAccess]) {
713
+ errors.push(new ValidationErrorInfo('SearchScopeAccess', widenHint('SearchScopeAccess', `('${targetSearchAccess}' > '${ancestorSearchAccess}')`), targetSearchAccess, ValidationErrorType.Failure));
714
+ }
715
+ // 4b. AcceptsSkills (None: 0 < Limited: 1 < All: 2)
716
+ const ancestorAcceptsSkills = FoldRebaseAwareChain({
717
+ Nodes: ancestors,
718
+ NodeConfigs: ancestorConfigs,
719
+ Seed: ancestors[0]?.AcceptsSkills ?? null,
720
+ GetNodeValue: (anc) => anc.AcceptsSkills ?? undefined,
721
+ Narrow: (acc, next) => {
722
+ if (next == null)
723
+ return acc;
724
+ return acc === null || ACCEPTS_SKILLS_RANK[next] < ACCEPTS_SKILLS_RANK[acc] ? next : acc;
725
+ },
726
+ });
727
+ if (shouldEnforceField('AcceptsSkills') &&
728
+ ancestorAcceptsSkills !== null &&
729
+ Target.AcceptsSkills != null &&
730
+ ACCEPTS_SKILLS_RANK[Target.AcceptsSkills] > ACCEPTS_SKILLS_RANK[ancestorAcceptsSkills]) {
731
+ errors.push(new ValidationErrorInfo('AcceptsSkills', widenHint('AcceptsSkills', `('${Target.AcceptsSkills}' > '${ancestorAcceptsSkills}')`), Target.AcceptsSkills, ValidationErrorType.Failure));
732
+ }
733
+ // 4c. SkillActivationMode (RequestedOnly: 0 < Auto: 1)
734
+ const narrowSkill = (acc, v) => {
735
+ if (v == null)
736
+ return acc;
737
+ return acc === null || SKILL_ACTIVATION_RANK[v] < SKILL_ACTIVATION_RANK[acc] ? v : acc;
738
+ };
739
+ let seedAncSkill = null;
740
+ for (const layer of defaultPolicyLayers) {
741
+ seedAncSkill = narrowSkill(seedAncSkill, layer.skills?.activationMode);
742
+ }
743
+ if (ancestors.length > 0) {
744
+ seedAncSkill = narrowSkill(seedAncSkill, ancestorConfigs[0]?.skills?.activationMode);
745
+ seedAncSkill = narrowSkill(seedAncSkill, ancestors[0].SkillActivationMode);
746
+ }
747
+ const ancestorSkillMode = FoldRebaseAwareChain({
748
+ Nodes: ancestors,
749
+ NodeConfigs: ancestorConfigs,
750
+ Seed: seedAncSkill,
751
+ GetNodeValue: (anc, cfg, idx) => {
752
+ const exp = cfg?.skills?.activationMode ?? null;
753
+ const leg = anc.SkillActivationMode ?? null;
754
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
755
+ if (exp != null)
756
+ return exp;
757
+ return leg != null && leg !== 'RequestedOnly' ? leg : undefined;
758
+ }
759
+ if (exp != null && leg != null) {
760
+ return SKILL_ACTIVATION_RANK[leg] < SKILL_ACTIVATION_RANK[exp] ? leg : exp;
761
+ }
762
+ if (exp != null)
763
+ return exp;
764
+ const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
765
+ return leg != null && (leg !== 'RequestedOnly' || !isNonInst) ? leg : undefined;
766
+ },
767
+ Narrow: (acc, next) => narrowSkill(acc, next),
768
+ });
769
+ const targetSkillMode = targetConfig?.skills?.activationMode ?? Target.SkillActivationMode ?? null;
770
+ if (shouldEnforceField('SkillActivationMode') &&
771
+ ancestorSkillMode !== null &&
772
+ targetSkillMode !== null &&
773
+ SKILL_ACTIVATION_RANK[targetSkillMode] > SKILL_ACTIVATION_RANK[ancestorSkillMode]) {
774
+ errors.push(new ValidationErrorInfo('SkillActivationMode', widenHint('SkillActivationMode', `('${targetSkillMode}' > '${ancestorSkillMode}')`), targetSkillMode, ValidationErrorType.Failure));
775
+ }
776
+ // 4d. RequirePlanMode (rebase-aware monotonic OR)
777
+ const seedAncRequirePlan = defaultPolicyLayers.some((l) => l.execution?.requirePlanMode === true) ||
778
+ (ancestors.length > 0 &&
779
+ (ancestorConfigs[0]?.execution?.requirePlanMode === true || ancestors[0].RequirePlanMode === true));
780
+ const ancestorRequiresPlan = FoldRebaseAwareChain({
781
+ Nodes: ancestors,
782
+ NodeConfigs: ancestorConfigs,
783
+ Seed: seedAncRequirePlan,
784
+ GetNodeValue: (anc, cfg, idx) => {
785
+ const exp = cfg?.execution?.requirePlanMode;
786
+ const leg = anc.RequirePlanMode;
787
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
788
+ if (typeof exp === 'boolean')
789
+ return exp;
790
+ return leg === true ? true : undefined;
791
+ }
792
+ if (exp === true || leg === true)
793
+ return true;
794
+ return typeof exp === 'boolean' ? exp : undefined;
795
+ },
796
+ Narrow: (acc, next) => acc || next,
797
+ });
798
+ const targetRequirePlan = targetConfig?.execution?.requirePlanMode ?? Target.RequirePlanMode;
799
+ if (shouldEnforceField('RequirePlanMode') && ancestorRequiresPlan && targetRequirePlan === false) {
800
+ errors.push(new ValidationErrorInfo('RequirePlanMode', widenHint('RequirePlanMode', `(false vs required true)`), false, ValidationErrorType.Failure));
801
+ }
802
+ // 4e. Narrow-only booleans (rebase-aware monotonic AND)
803
+ const computeRebaseAncestorBoolAnd = (layerPicker, nodeJsonPicker, nodeLegacyPicker, sqlDefault) => {
804
+ const foldAnd = (acc, v) => {
805
+ if (typeof v !== 'boolean')
806
+ return acc;
807
+ return acc === null ? v : acc && v;
808
+ };
809
+ let seed = null;
810
+ for (const layer of defaultPolicyLayers) {
811
+ seed = foldAnd(seed, layerPicker(layer));
812
+ }
813
+ if (ancestors.length > 0) {
814
+ const exp0 = nodeJsonPicker(ancestorConfigs[0]);
815
+ const leg0 = nodeLegacyPicker(ancestors[0]);
816
+ seed =
817
+ typeof exp0 === 'boolean' && typeof leg0 === 'boolean'
818
+ ? foldAnd(seed, exp0 && leg0)
819
+ : foldAnd(seed, exp0 ?? leg0);
820
+ }
821
+ return FoldRebaseAwareChain({
822
+ Nodes: ancestors,
823
+ NodeConfigs: ancestorConfigs,
824
+ Seed: seed,
825
+ GetNodeValue: (anc, cfg, idx) => {
826
+ const exp = nodeJsonPicker(cfg);
827
+ const leg = nodeLegacyPicker(anc);
828
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
829
+ if (typeof exp === 'boolean')
830
+ return exp;
831
+ return typeof leg === 'boolean' && leg !== sqlDefault ? leg : undefined;
832
+ }
833
+ if (typeof exp === 'boolean' && typeof leg === 'boolean')
834
+ return exp && leg;
835
+ if (typeof exp === 'boolean')
836
+ return exp;
837
+ if (typeof leg === 'boolean') {
838
+ if (sqlDefault === false && leg === false) {
839
+ const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
840
+ return isNonInst ? undefined : false;
841
+ }
842
+ return leg !== sqlDefault ? leg : undefined;
843
+ }
844
+ return undefined;
845
+ },
846
+ Narrow: (acc, next) => foldAnd(acc, next),
847
+ });
848
+ };
849
+ const checkRebaseNarrowBoolean = (fieldName, ancestorEffective, targetVal) => {
850
+ if (shouldEnforceField(fieldName) && ancestorEffective === false && targetVal === true) {
851
+ errors.push(new ValidationErrorInfo(fieldName, widenHint(fieldName, `(true vs disabled false)`), true, ValidationErrorType.Failure));
852
+ }
853
+ };
854
+ checkRebaseNarrowBoolean('SupportsPlanMode', computeRebaseAncestorBoolAnd((l) => l.execution?.supportsPlanMode, (cfg) => cfg?.execution?.supportsPlanMode, (a) => a.SupportsPlanMode, true), targetConfig?.execution?.supportsPlanMode ?? Target.SupportsPlanMode);
855
+ checkRebaseNarrowBoolean('AcceptUnregisteredFiles', computeRebaseAncestorBoolAnd((l) => l.attachments?.acceptUnregisteredFiles, (cfg) => cfg?.attachments?.acceptUnregisteredFiles, (a) => a.AcceptUnregisteredFiles, false), targetConfig?.attachments?.acceptUnregisteredFiles ?? Target.AcceptUnregisteredFiles);
856
+ checkRebaseNarrowBoolean('AllowEphemeralClientTools', computeRebaseAncestorBoolAnd((l) => l.clientTools?.allowEphemeral, (cfg) => cfg?.clientTools?.allowEphemeral, (a) => a.AllowEphemeralClientTools, true), targetConfig?.clientTools?.allowEphemeral ?? Target.AllowEphemeralClientTools);
857
+ checkRebaseNarrowBoolean('AllowMemoryWrite', computeRebaseAncestorBoolAnd((l) => l.memory?.allowMemoryWrite, (cfg) => cfg?.memory?.allowMemoryWrite, (a) => a.AllowMemoryWrite, true), targetConfig?.memory?.allowMemoryWrite ?? Target.AllowMemoryWrite);
858
+ // 4f. Ranked enum surfaces: ArtifactCreationMode, MessageMode, StartingPayloadValidationMode, FinalPayloadValidationMode
859
+ const checkRankedEnumSurface = (args) => {
860
+ if (!shouldEnforceField(args.fieldName))
861
+ return;
862
+ const narrowEnum = (acc, v) => {
863
+ if (v == null)
864
+ return acc;
865
+ return acc === null || args.ranks[v] < args.ranks[acc] ? v : acc;
866
+ };
867
+ let seed = null;
868
+ for (const layer of defaultPolicyLayers) {
869
+ seed = narrowEnum(seed, args.layerPicker(layer));
870
+ }
871
+ if (ancestors.length > 0) {
872
+ const exp0 = args.jsonPicker(ancestorConfigs[0]);
873
+ const leg0 = args.legacyPicker(ancestors[0]);
874
+ if (exp0 != null && leg0 != null) {
875
+ seed = narrowEnum(seed, args.ranks[leg0] < args.ranks[exp0] ? leg0 : exp0);
876
+ }
877
+ else if (exp0 != null) {
878
+ seed = narrowEnum(seed, exp0);
879
+ }
880
+ else if (leg0 != null && leg0 !== args.sqlDefault) {
881
+ seed = narrowEnum(seed, leg0);
882
+ }
883
+ else if (seed === null && leg0 != null) {
884
+ seed = leg0;
885
+ }
886
+ }
887
+ const ancestorEffective = FoldRebaseAwareChain({
888
+ Nodes: ancestors,
889
+ NodeConfigs: ancestorConfigs,
890
+ Seed: seed,
891
+ GetNodeValue: (anc, cfg, idx) => {
892
+ const exp = args.jsonPicker(cfg) ?? null;
893
+ const leg = args.legacyPicker(anc) ?? null;
894
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
895
+ if (exp != null)
896
+ return exp;
897
+ return leg != null && leg !== args.sqlDefault ? leg : undefined;
898
+ }
899
+ if (exp != null && leg != null) {
900
+ return args.ranks[leg] < args.ranks[exp] ? leg : exp;
901
+ }
902
+ if (exp != null)
903
+ return exp;
904
+ return leg != null && leg !== args.sqlDefault ? leg : undefined;
905
+ },
906
+ Narrow: (acc, next) => narrowEnum(acc, next),
907
+ });
908
+ if (ancestorEffective === null)
909
+ return;
910
+ const expTarget = args.jsonPicker(targetConfig);
911
+ if (expTarget === undefined &&
912
+ args.targetLegacy === args.sqlDefault &&
913
+ Target.DirtyFields &&
914
+ !Target.DirtyFields.has(args.fieldName)) {
915
+ return;
916
+ }
917
+ const targetVal = expTarget ?? args.targetLegacy ?? null;
918
+ if (targetVal != null && args.ranks[targetVal] > args.ranks[ancestorEffective]) {
919
+ errors.push(new ValidationErrorInfo(args.fieldName, widenHint(args.fieldName, `('${targetVal}' > '${ancestorEffective}')`), targetVal, ValidationErrorType.Failure));
920
+ }
921
+ };
922
+ checkRankedEnumSurface({
923
+ fieldName: 'ArtifactCreationMode',
924
+ ranks: AGENT_ARTIFACT_CREATION_MODE_RANK,
925
+ sqlDefault: 'Always',
926
+ layerPicker: (l) => l.artifacts?.creationMode,
927
+ jsonPicker: (cfg) => cfg?.artifacts?.creationMode,
928
+ legacyPicker: (a) => a.ArtifactCreationMode,
929
+ targetLegacy: Target.ArtifactCreationMode,
930
+ });
931
+ checkRankedEnumSurface({
932
+ fieldName: 'MessageMode',
933
+ ranks: AGENT_MESSAGE_MODE_RANK,
934
+ sqlDefault: 'None',
935
+ layerPicker: (l) => l.attachments?.messageMode,
936
+ jsonPicker: (cfg) => cfg?.attachments?.messageMode,
937
+ legacyPicker: (a) => a.MessageMode,
938
+ targetLegacy: Target.MessageMode,
939
+ });
940
+ checkRankedEnumSurface({
941
+ fieldName: 'StartingPayloadValidationMode',
942
+ ranks: AGENT_STARTING_VALIDATION_MODE_RANK,
943
+ sqlDefault: 'Fail',
944
+ layerPicker: (l) => l.payload?.startingValidationMode,
945
+ jsonPicker: (cfg) => cfg?.payload?.startingValidationMode,
946
+ legacyPicker: (a) => a.StartingPayloadValidationMode,
947
+ targetLegacy: Target.StartingPayloadValidationMode,
948
+ });
949
+ checkRankedEnumSurface({
950
+ fieldName: 'FinalPayloadValidationMode',
951
+ ranks: AGENT_FINAL_VALIDATION_MODE_RANK,
952
+ sqlDefault: 'Retry',
953
+ layerPicker: (l) => l.payload?.finalValidationMode,
954
+ jsonPicker: (cfg) => cfg?.payload?.finalValidationMode,
955
+ legacyPicker: (a) => a.FinalPayloadValidationMode,
956
+ targetLegacy: Target.FinalPayloadValidationMode,
957
+ });
958
+ // 4g. AutoArchiveEnabled: cannot flip true -> false when ancestor enforces finite retention
959
+ const ancestorHasFiniteRetention = ancestorNoteRetentionDays !== null || ancestorExampleRetentionDays !== null;
960
+ const seedAncAutoArchive = (() => {
961
+ if (ancestors.length > 0) {
962
+ const exp0 = ancestorConfigs[0]?.memory?.autoArchiveEnabled;
963
+ if (typeof exp0 === 'boolean')
964
+ return exp0;
965
+ const leg0 = ancestors[0].AutoArchiveEnabled;
966
+ if (typeof leg0 === 'boolean' && leg0 !== true)
967
+ return leg0;
968
+ }
969
+ for (let i = defaultPolicyLayers.length - 1; i >= 0; i--) {
970
+ if (typeof defaultPolicyLayers[i].memory?.autoArchiveEnabled === 'boolean') {
971
+ return defaultPolicyLayers[i].memory.autoArchiveEnabled;
972
+ }
973
+ }
974
+ return true;
975
+ })();
976
+ const ancestorAutoArchive = FoldRebaseAwareChain({
977
+ Nodes: ancestors,
978
+ NodeConfigs: ancestorConfigs,
979
+ Seed: seedAncAutoArchive,
980
+ GetNodeValue: (anc, cfg) => {
981
+ const exp = cfg?.memory?.autoArchiveEnabled;
982
+ if (typeof exp === 'boolean')
983
+ return exp;
984
+ const leg = anc.AutoArchiveEnabled;
985
+ return typeof leg === 'boolean' && leg !== true ? leg : undefined;
986
+ },
987
+ Narrow: (acc, next) => (acc === true && ancestorHasFiniteRetention && next === false ? true : next),
988
+ });
989
+ const targetAutoArchive = targetConfig?.memory?.autoArchiveEnabled ?? Target.AutoArchiveEnabled;
990
+ if (shouldEnforceField('AutoArchiveEnabled') &&
991
+ ancestorAutoArchive === true &&
992
+ ancestorHasFiniteRetention &&
993
+ targetAutoArchive === false) {
994
+ errors.push(new ValidationErrorInfo('AutoArchiveEnabled', widenHint('AutoArchiveEnabled', '(false while ancestor enforces finite retention)'), false, ValidationErrorType.Failure));
995
+ }
996
+ // 4h. Payload path glob-sets (Downstream, Upstream, SelfRead, SelfWrite)
997
+ const parsePathList = (raw) => {
998
+ if (!raw || raw.trim().length === 0)
999
+ return null;
1000
+ try {
1001
+ const p = JSON.parse(raw);
1002
+ if (Array.isArray(p) && p.every((item) => typeof item === 'string')) {
1003
+ return p;
1004
+ }
1005
+ }
1006
+ catch {
1007
+ return null;
1008
+ }
1009
+ return null;
1010
+ };
1011
+ const checkPayloadPathSurface = (args) => {
1012
+ if (!shouldEnforceField(args.fieldName))
1013
+ return;
1014
+ let seed = null;
1015
+ for (const layer of defaultPolicyLayers) {
1016
+ const lp = args.jsonPicker(layer);
1017
+ if (Array.isArray(lp)) {
1018
+ seed = IntersectPayloadPathSets(seed, lp);
1019
+ }
1020
+ }
1021
+ if (ancestors.length > 0) {
1022
+ const exp0 = args.jsonPicker(ancestorConfigs[0]);
1023
+ if (Array.isArray(exp0)) {
1024
+ seed = IntersectPayloadPathSets(seed, exp0);
1025
+ }
1026
+ else {
1027
+ const leg0 = parsePathList(args.legacyPicker(ancestors[0]));
1028
+ if (leg0 !== null) {
1029
+ const isDbWildcard = args.treatWildcardAsDbDefault && leg0.length === 1 && leg0[0] === '*';
1030
+ if (!isDbWildcard) {
1031
+ seed = IntersectPayloadPathSets(seed, leg0);
1032
+ }
1033
+ }
1034
+ }
1035
+ }
1036
+ const ancestorPaths = FoldRebaseAwareChain({
1037
+ Nodes: ancestors,
1038
+ NodeConfigs: ancestorConfigs,
1039
+ Seed: seed,
1040
+ GetNodeValue: (anc, cfg, idx) => {
1041
+ const exp = args.jsonPicker(cfg);
1042
+ if (idx > 0 && cfg?.allowWidenFromBase === true && exp === null) {
1043
+ return null;
1044
+ }
1045
+ if (Array.isArray(exp))
1046
+ return [...exp];
1047
+ const leg = parsePathList(args.legacyPicker(anc));
1048
+ if (leg !== null) {
1049
+ const isDbWildcard = args.treatWildcardAsDbDefault && leg.length === 1 && leg[0] === '*';
1050
+ if (!isDbWildcard)
1051
+ return leg;
1052
+ }
1053
+ return undefined;
1054
+ },
1055
+ Narrow: (acc, next) => IntersectPayloadPathSets(acc, next),
1056
+ Rebase: (_acc, next) => (next === null ? null : [...next]),
1057
+ });
1058
+ const expTarget = args.jsonPicker(targetConfig);
1059
+ let targetPaths;
1060
+ if (expTarget !== undefined) {
1061
+ targetPaths = expTarget;
1062
+ }
1063
+ else {
1064
+ const legTarget = parsePathList(args.targetLegacy);
1065
+ if (legTarget !== null) {
1066
+ const isUntouchedWildcard = args.treatWildcardAsDbDefault &&
1067
+ legTarget.length === 1 &&
1068
+ legTarget[0] === '*' &&
1069
+ Target.DirtyFields &&
1070
+ !Target.DirtyFields.has(args.fieldName);
1071
+ if (!isUntouchedWildcard) {
1072
+ targetPaths = legTarget;
1073
+ }
1074
+ }
1075
+ }
1076
+ if (targetPaths === undefined)
1077
+ return;
1078
+ if (!IsPayloadPathSetWithinAncestor(ancestorPaths, targetPaths)) {
1079
+ errors.push(new ValidationErrorInfo(args.fieldName, widenHint(args.fieldName, `(${JSON.stringify(targetPaths)} outside ${JSON.stringify(ancestorPaths)})`), targetPaths, ValidationErrorType.Failure));
165
1080
  }
166
1081
  };
167
- checkUpperBound('MaxCostPerRun', baseAgent.MaxCostPerRun, Target.MaxCostPerRun);
168
- checkUpperBound('MaxTokensPerRun', baseAgent.MaxTokensPerRun, Target.MaxTokensPerRun);
169
- checkUpperBound('MaxTimePerRun', baseAgent.MaxTimePerRun, Target.MaxTimePerRun);
170
- checkUpperBound('MaxIterationsPerRun', baseAgent.MaxIterationsPerRun, Target.MaxIterationsPerRun);
1082
+ checkPayloadPathSurface({
1083
+ fieldName: 'PayloadDownstreamPaths',
1084
+ jsonPicker: (cfg) => cfg?.payload?.downstreamPaths,
1085
+ legacyPicker: (a) => a.PayloadDownstreamPaths,
1086
+ targetLegacy: Target.PayloadDownstreamPaths,
1087
+ treatWildcardAsDbDefault: true,
1088
+ });
1089
+ checkPayloadPathSurface({
1090
+ fieldName: 'PayloadUpstreamPaths',
1091
+ jsonPicker: (cfg) => cfg?.payload?.upstreamPaths,
1092
+ legacyPicker: (a) => a.PayloadUpstreamPaths,
1093
+ targetLegacy: Target.PayloadUpstreamPaths,
1094
+ treatWildcardAsDbDefault: true,
1095
+ });
1096
+ checkPayloadPathSurface({
1097
+ fieldName: 'PayloadSelfReadPaths',
1098
+ jsonPicker: (cfg) => cfg?.payload?.selfReadPaths,
1099
+ legacyPicker: (a) => a.PayloadSelfReadPaths,
1100
+ targetLegacy: Target.PayloadSelfReadPaths,
1101
+ treatWildcardAsDbDefault: false,
1102
+ });
1103
+ checkPayloadPathSurface({
1104
+ fieldName: 'PayloadSelfWritePaths',
1105
+ jsonPicker: (cfg) => cfg?.payload?.selfWritePaths,
1106
+ legacyPicker: (a) => a.PayloadSelfWritePaths,
1107
+ targetLegacy: Target.PayloadSelfWritePaths,
1108
+ treatWildcardAsDbDefault: false,
1109
+ });
1110
+ // 4i. PayloadScope subtree prefix lock
1111
+ if (shouldEnforceField('PayloadScope')) {
1112
+ let seedScope = null;
1113
+ for (const layer of defaultPolicyLayers) {
1114
+ if (typeof layer.payload?.scope === 'string' && layer.payload.scope.trim().length > 0) {
1115
+ seedScope = NarrowPayloadScope(seedScope, layer.payload.scope);
1116
+ }
1117
+ }
1118
+ if (ancestors.length > 0) {
1119
+ const s0 = ancestorConfigs[0]?.payload?.scope ?? ancestors[0].PayloadScope ?? null;
1120
+ if (typeof s0 === 'string' && s0.trim().length > 0) {
1121
+ seedScope = NarrowPayloadScope(seedScope, s0);
1122
+ }
1123
+ }
1124
+ const ancestorPayloadScope = FoldRebaseAwareChain({
1125
+ Nodes: ancestors,
1126
+ NodeConfigs: ancestorConfigs,
1127
+ Seed: seedScope,
1128
+ GetNodeValue: (anc, cfg, idx) => {
1129
+ const exp = cfg?.payload?.scope;
1130
+ if (idx > 0 && cfg?.allowWidenFromBase === true && exp === null)
1131
+ return null;
1132
+ if (typeof exp === 'string' && exp.trim().length > 0)
1133
+ return exp.trim();
1134
+ const leg = anc.PayloadScope?.trim();
1135
+ return leg && leg.length > 0 ? leg : undefined;
1136
+ },
1137
+ Narrow: (acc, next) => NarrowPayloadScope(acc, next),
1138
+ Rebase: (acc, next) => (next === null ? null : HasPathTraversalSegment(next) ? acc : next),
1139
+ });
1140
+ if (ancestorPayloadScope) {
1141
+ const expScope = targetConfig?.payload?.scope;
1142
+ const explicitNullClear = expScope === null || (Target.PayloadScope === null && Target.DirtyFields?.has('PayloadScope'));
1143
+ const candidateScope = expScope !== undefined ? expScope : Target.PayloadScope !== undefined ? Target.PayloadScope : undefined;
1144
+ if (explicitNullClear || (typeof candidateScope === 'string' && candidateScope.trim().length > 0)) {
1145
+ if (!IsPayloadScopeWithinAncestor(ancestorPayloadScope, candidateScope)) {
1146
+ errors.push(new ValidationErrorInfo('PayloadScope', widenHint('PayloadScope', `('${String(candidateScope)}' outside '${ancestorPayloadScope}')`), candidateScope, ValidationErrorType.Failure));
1147
+ }
1148
+ }
1149
+ }
1150
+ }
1151
+ // 4j. AttachmentRootPath subtree prefix lock
1152
+ if (shouldEnforceField('AttachmentRootPath')) {
1153
+ let seedAttachPath = null;
1154
+ for (const layer of defaultPolicyLayers) {
1155
+ if (typeof layer.attachments?.rootPath === 'string' && layer.attachments.rootPath.trim().length > 0) {
1156
+ seedAttachPath = NarrowAttachmentRootPath(seedAttachPath, layer.attachments.rootPath);
1157
+ }
1158
+ }
1159
+ if (ancestors.length > 0) {
1160
+ const r0 = ancestorConfigs[0]?.attachments?.rootPath ?? ancestors[0].AttachmentRootPath ?? null;
1161
+ if (typeof r0 === 'string' && r0.trim().length > 0) {
1162
+ seedAttachPath = NarrowAttachmentRootPath(seedAttachPath, r0);
1163
+ }
1164
+ }
1165
+ const ancestorAttachRoot = FoldRebaseAwareChain({
1166
+ Nodes: ancestors,
1167
+ NodeConfigs: ancestorConfigs,
1168
+ Seed: seedAttachPath,
1169
+ GetNodeValue: (anc, cfg, idx) => {
1170
+ const exp = cfg?.attachments?.rootPath;
1171
+ if (idx > 0 && cfg?.allowWidenFromBase === true && exp === null)
1172
+ return null;
1173
+ if (typeof exp === 'string' && exp.trim().length > 0)
1174
+ return exp.trim();
1175
+ const leg = anc.AttachmentRootPath?.trim();
1176
+ return leg && leg.length > 0 ? leg : undefined;
1177
+ },
1178
+ Narrow: (acc, next) => NarrowAttachmentRootPath(acc, next),
1179
+ Rebase: (acc, next) => (next === null ? null : HasPathTraversalSegment(next) ? acc : next),
1180
+ });
1181
+ if (ancestorAttachRoot) {
1182
+ const expRoot = targetConfig?.attachments?.rootPath;
1183
+ const explicitNullClear = expRoot === null ||
1184
+ (Target.AttachmentRootPath === null && Target.DirtyFields?.has('AttachmentRootPath'));
1185
+ const candidateRoot = expRoot !== undefined
1186
+ ? expRoot
1187
+ : Target.AttachmentRootPath !== undefined
1188
+ ? Target.AttachmentRootPath
1189
+ : undefined;
1190
+ if (explicitNullClear || (typeof candidateRoot === 'string' && candidateRoot.trim().length > 0)) {
1191
+ if (!IsAttachmentRootPathWithinAncestor(ancestorAttachRoot, candidateRoot)) {
1192
+ errors.push(new ValidationErrorInfo('AttachmentRootPath', widenHint('AttachmentRootPath', `('${String(candidateRoot)}' outside '${ancestorAttachRoot}')`), candidateRoot, ValidationErrorType.Failure));
1193
+ }
1194
+ }
1195
+ }
1196
+ }
1197
+ // 4k. ScopeConfig (`scope.secondaryScopeConfig`) per-key intersection
1198
+ if (shouldEnforceField('ScopeConfig')) {
1199
+ const parseScopeObj = (raw) => {
1200
+ if (!raw || raw.trim().length === 0)
1201
+ return null;
1202
+ const parsed = ParseAgentConfigJsonObject(raw);
1203
+ return parsed ? { ...parsed } : null;
1204
+ };
1205
+ let seedScopeObj = null;
1206
+ for (const layer of defaultPolicyLayers) {
1207
+ if (layer.scope?.secondaryScopeConfig) {
1208
+ seedScopeObj = NarrowScopeConfigObjects(seedScopeObj, layer.scope.secondaryScopeConfig);
1209
+ }
1210
+ }
1211
+ if (ancestors.length > 0) {
1212
+ const s0 = ancestorConfigs[0]?.scope?.secondaryScopeConfig ?? parseScopeObj(ancestors[0].ScopeConfig);
1213
+ if (s0) {
1214
+ seedScopeObj = NarrowScopeConfigObjects(seedScopeObj, s0);
1215
+ }
1216
+ }
1217
+ const ancestorScopeObj = FoldRebaseAwareChain({
1218
+ Nodes: ancestors,
1219
+ NodeConfigs: ancestorConfigs,
1220
+ Seed: seedScopeObj,
1221
+ GetNodeValue: (anc, cfg, idx) => {
1222
+ if (idx > 0 && cfg?.allowWidenFromBase === true && cfg?.scope?.secondaryScopeConfig === null) {
1223
+ return null;
1224
+ }
1225
+ const exp = cfg?.scope?.secondaryScopeConfig;
1226
+ if (exp && typeof exp === 'object' && !Array.isArray(exp))
1227
+ return exp;
1228
+ return parseScopeObj(anc.ScopeConfig) ?? undefined;
1229
+ },
1230
+ Narrow: (acc, next) => NarrowScopeConfigObjects(acc, next),
1231
+ Rebase: (_acc, next) => (next ? { ...next } : null),
1232
+ });
1233
+ if (ancestorScopeObj && Object.keys(ancestorScopeObj).length > 0) {
1234
+ const expScopeObj = targetConfig?.scope?.secondaryScopeConfig;
1235
+ if (expScopeObj === null || (Target.ScopeConfig === null && Target.DirtyFields?.has('ScopeConfig'))) {
1236
+ errors.push(new ValidationErrorInfo('ScopeConfig', widenHint('ScopeConfig', '(cleared to null when ancestor enforces scope config)'), null, ValidationErrorType.Failure));
1237
+ }
1238
+ else {
1239
+ const targetScopeObj = expScopeObj ?? parseScopeObj(Target.ScopeConfig);
1240
+ if (targetScopeObj) {
1241
+ const scopeViolations = FindScopeConfigWideningViolations(ancestorScopeObj, targetScopeObj);
1242
+ for (const msg of scopeViolations) {
1243
+ errors.push(new ValidationErrorInfo('ScopeConfig', widenHint('ScopeConfig', `(${msg})`), targetScopeObj, ValidationErrorType.Failure));
1244
+ }
1245
+ }
1246
+ }
1247
+ }
1248
+ }
1249
+ // 4l. AgentTypePromptParams gates (`enableHandoff: false`, `enableTaskGraphs: false`)
1250
+ if (shouldEnforceField('AgentTypePromptParams')) {
1251
+ const ancestorLockedFalseGates = new Set();
1252
+ const applyGateMap = (obj, allowRebase) => {
1253
+ if (!obj)
1254
+ return;
1255
+ for (const gate of NARROW_ONLY_PROMPT_PARAM_GATES) {
1256
+ if (typeof obj[gate] === 'boolean') {
1257
+ if (obj[gate] === false) {
1258
+ ancestorLockedFalseGates.add(gate);
1259
+ }
1260
+ else if (allowRebase && obj[gate] === true) {
1261
+ ancestorLockedFalseGates.delete(gate);
1262
+ }
1263
+ }
1264
+ }
1265
+ };
1266
+ for (const layer of defaultPolicyLayers) {
1267
+ applyGateMap(layer.promptDefaults ?? null, false);
1268
+ }
1269
+ for (let i = 0; i < ancestors.length; i++) {
1270
+ const parsed = ParseAgentConfigJsonObject(ancestors[i].AgentTypePromptParams);
1271
+ applyGateMap(parsed, i > 0 && ancestorConfigs[i]?.allowWidenFromBase === true);
1272
+ }
1273
+ const targetPromptParams = ParseAgentConfigJsonObject(Target.AgentTypePromptParams);
1274
+ if (targetPromptParams && ancestorLockedFalseGates.size > 0) {
1275
+ for (const gate of ancestorLockedFalseGates) {
1276
+ if (targetPromptParams[gate] === true) {
1277
+ errors.push(new ValidationErrorInfo('AgentTypePromptParams', widenHint(`AgentTypePromptParams.${gate}`, '(true vs disabled false)'), true, ValidationErrorType.Failure));
1278
+ }
1279
+ }
1280
+ }
1281
+ }
171
1282
  }
172
1283
  return errors;
173
1284
  }
@@ -180,6 +1291,18 @@ export function ValidateAgentInheritanceAndSandbox(ctx) {
180
1291
  * `IsPrimaryInstance` uniqueness per `(OwnerUserID, RootBaseAgentID)`.
181
1292
  */
182
1293
  let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityExtended {
1294
+ constructor() {
1295
+ super(...arguments);
1296
+ /**
1297
+ * Captures whether the caller actually modified `Configuration` (or is creating a new record)
1298
+ * BEFORE `syncConfigurationWithLegacyColumns` runs in `Save()`, so unrelated legacy-column
1299
+ * edits on pre-existing rows do not trigger full-document JSON re-validation or spuriously
1300
+ * mark `Configuration` dirty for narrow-only checks (R3-10).
1301
+ */
1302
+ this._configDirtyBeforeSync = null;
1303
+ this._dirtyLegacyPatchForValidation = null;
1304
+ this._saveGuardCache = null;
1305
+ }
183
1306
  /** Enable async validation so TypeConfiguration, BaseAgentID chain, and sandbox checks run. */
184
1307
  get DefaultSkipAsyncValidation() {
185
1308
  return false;
@@ -188,44 +1311,80 @@ let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityE
188
1311
  const isCreate = !this.IsSaved;
189
1312
  let baseAgent = null;
190
1313
  let resolvedRootBaseId = null;
191
- if (isCreate && !this.OwnerUserID && this.ContextCurrentUser) {
192
- this.OwnerUserID = this.ContextCurrentUser.ID;
193
- }
194
- if (this.BaseAgentID) {
195
- const allAgents = await this.loadAllAgentsForGuard();
196
- baseAgent = allAgents.find((a) => UUIDsEqual(a.ID, this.BaseAgentID)) ?? null;
197
- if (baseAgent) {
198
- resolvedRootBaseId = this.findRootBaseAgentId(baseAgent, allAgents);
199
- if (isCreate) {
200
- this.inheritDefaultsFromBaseAgent(baseAgent);
201
- const primaryDirty = this.GetFieldByName('IsPrimaryInstance')?.Dirty ?? false;
202
- if (!primaryDirty && !this.IsPrimaryInstance && this.OwnerUserID) {
203
- const existingSiblings = this.findActiveSiblingsForOwnerAndRoot(allAgents, this.OwnerUserID, resolvedRootBaseId, this.ID);
204
- if (existingSiblings.length === 0) {
205
- this.IsPrimaryInstance = true;
1314
+ // Capture caller-dirty legacy fields BEFORE inheritDefaultsFromBaseAgent copies parent
1315
+ // defaults onto legacy columns so newly created derived instances do not freeze inherited
1316
+ // parent values into AIAgent.Configuration JSON.
1317
+ const callerDirtyLegacyFields = this.collectDirtyLegacyConfigFields(isCreate);
1318
+ const callerLegacyPatch = this.buildLegacyPatchFromSet(callerDirtyLegacyFields);
1319
+ this._dirtyLegacyPatchForValidation = Object.keys(callerLegacyPatch).length > 0 ? callerLegacyPatch : null;
1320
+ this._configDirtyBeforeSync = isCreate || (this.GetFieldByName('Configuration')?.Dirty ?? false);
1321
+ try {
1322
+ if (isCreate && !this.OwnerUserID && this.ContextCurrentUser) {
1323
+ this.OwnerUserID = this.ContextCurrentUser.ID;
1324
+ }
1325
+ if (this.BaseAgentID) {
1326
+ const guardBatch = await this.loadGuardMetadataBatch();
1327
+ this._saveGuardCache = guardBatch;
1328
+ const { AllAgents: allAgents, AllCategories: allCategories, AllAgentTypes: allAgentTypes } = guardBatch;
1329
+ baseAgent = allAgents.find((a) => UUIDsEqual(a.ID, this.BaseAgentID)) ?? null;
1330
+ if (baseAgent) {
1331
+ resolvedRootBaseId = this.findRootBaseAgentId(baseAgent, allAgents);
1332
+ if (isCreate) {
1333
+ const ancestorSearchCeiling = this.inheritDefaultsFromBaseAgent(baseAgent, allAgents, allCategories, allAgentTypes);
1334
+ // R5-1 + C-R3-1 + C-R3-2: If the caller explicitly wrote `SearchScopeAccess = 'None'`
1335
+ // (`NeverSet === false`) WITHOUT explicitly setting `Configuration.scope.searchScopeAccess`,
1336
+ // under a broader effective ancestor ceiling (`ancestorSearchCeiling !== 'None'`),
1337
+ // persist `scope.searchScopeAccess = 'None'` into `Configuration` so runtime resolution
1338
+ // honors the explicit restriction instead of treating the leaf column `'None'` as unset.
1339
+ const searchField = this.GetFieldByName('SearchScopeAccess');
1340
+ const explicitConfigSearchAccess = ParseAgentConfiguration(this.Configuration)?.scope?.searchScopeAccess;
1341
+ if (this.SearchScopeAccess === 'None' &&
1342
+ searchField &&
1343
+ searchField.NeverSet === false &&
1344
+ explicitConfigSearchAccess === undefined &&
1345
+ ancestorSearchCeiling !== null &&
1346
+ ancestorSearchCeiling !== 'None') {
1347
+ callerDirtyLegacyFields.add('SearchScopeAccess');
1348
+ }
1349
+ const primaryDirty = this.GetFieldByName('IsPrimaryInstance')?.Dirty ?? false;
1350
+ if (!primaryDirty && !this.IsPrimaryInstance && this.OwnerUserID) {
1351
+ const existingSiblings = this.findActiveSiblingsForOwnerAndRoot(allAgents, this.OwnerUserID, resolvedRootBaseId, this.ID);
1352
+ if (existingSiblings.length === 0) {
1353
+ this.IsPrimaryInstance = true;
1354
+ }
206
1355
  }
207
1356
  }
208
1357
  }
209
1358
  }
1359
+ // Bidirectional v6.x sync between AIAgent.Configuration JSON and deprecated legacy columns
1360
+ this.syncConfigurationWithLegacyColumns(isCreate, callerDirtyLegacyFields);
1361
+ const saved = await super.Save(options);
1362
+ if (!saved) {
1363
+ return false;
1364
+ }
1365
+ // Maintain single IsPrimaryInstance per (OwnerUserID, RootBaseAgentID)
1366
+ if (this.BaseAgentID && this.OwnerUserID && this.IsPrimaryInstance === true) {
1367
+ const rootId = this.RootBaseAgentID ?? resolvedRootBaseId ?? this.BaseAgentID;
1368
+ await this.clearOtherPrimaryInstances(this.OwnerUserID, rootId, this.ID);
1369
+ }
1370
+ return true;
210
1371
  }
211
- const saved = await super.Save(options);
212
- if (!saved) {
213
- return false;
214
- }
215
- // Maintain single IsPrimaryInstance per (OwnerUserID, RootBaseAgentID)
216
- if (this.BaseAgentID && this.OwnerUserID && this.IsPrimaryInstance === true) {
217
- const rootId = this.RootBaseAgentID ?? resolvedRootBaseId ?? this.BaseAgentID;
218
- await this.clearOtherPrimaryInstances(this.OwnerUserID, rootId, this.ID);
1372
+ finally {
1373
+ this._configDirtyBeforeSync = null;
1374
+ this._dirtyLegacyPatchForValidation = null;
1375
+ this._saveGuardCache = null;
219
1376
  }
220
- return true;
221
1377
  }
222
1378
  async Delete(options) {
223
1379
  const user = this.ContextCurrentUser;
224
- if (!IsAgentAdminOrOwnerUser(user) && user) {
1380
+ if (!IsAgentAdminOrOwnerUser(user, this.ProviderToUse) && user) {
225
1381
  const preSaveBase = this.GetFieldByName('BaseAgentID')?.OldValue ?? this.BaseAgentID;
226
1382
  const preSaveOwner = this.GetFieldByName('OwnerUserID')?.OldValue ?? this.OwnerUserID;
227
1383
  if (!preSaveBase || !preSaveOwner || !UUIDsEqual(preSaveOwner, user.ID)) {
228
- this.LatestResult?.Errors.push(new ValidationErrorInfo('OwnerUserID', 'Non-administrator users can only delete their own derived agent instances.', this.ID, ValidationErrorType.Failure));
1384
+ const err = new ValidationErrorInfo('OwnerUserID', 'Non-administrator users can only delete their own derived agent instances.', this.ID, ValidationErrorType.Failure);
1385
+ const deleteResult = new BaseEntityResult(false, '', 'delete');
1386
+ deleteResult.Errors = [err];
1387
+ this.RegisterResultHistoryEntry(deleteResult);
229
1388
  return false;
230
1389
  }
231
1390
  }
@@ -235,14 +1394,123 @@ let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityE
235
1394
  const result = await super.ValidateAsync();
236
1395
  if (!result.Success)
237
1396
  return result;
238
- // 1. BaseAgentID inheritance & non-admin sandbox checks
1397
+ // 0. Configuration JSON syntax & scalar-type validation (R2-2, R3-10, C-R1-7):
1398
+ // - On create or when caller directly modified Configuration, validate the full Configuration JSON
1399
+ // (plus any caller-dirty raw JSON legacy columns such as RerankerConfiguration/ScopeConfig).
1400
+ // - When caller only modified legacy columns on a saved row, validate ONLY the caller-dirty
1401
+ // legacy patch so invalid legacy edits are caught without breaking unrelated saves on
1402
+ // pre-existing rows with older backfilled Configuration payloads.
1403
+ const configDirtyForValidation = this._configDirtyBeforeSync ?? (!this.IsSaved || (this.GetFieldByName('Configuration')?.Dirty ?? false));
1404
+ const dirtyLegacyPatch = this._dirtyLegacyPatchForValidation ?? this.buildLegacyPatchFromSet(this.collectDirtyLegacyConfigFields(!this.IsSaved));
1405
+ if (configDirtyForValidation) {
1406
+ const configErrors = ValidateAgentConfigurationJson(this.Configuration, 'Configuration');
1407
+ if (Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'RerankerConfiguration') ||
1408
+ Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'ScopeConfig')) {
1409
+ const rawJsonSubset = {};
1410
+ if (Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'RerankerConfiguration')) {
1411
+ rawJsonSubset.RerankerConfiguration = dirtyLegacyPatch.RerankerConfiguration;
1412
+ }
1413
+ if (Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'ScopeConfig')) {
1414
+ rawJsonSubset.ScopeConfig = dirtyLegacyPatch.ScopeConfig;
1415
+ }
1416
+ configErrors.push(...ValidateLegacyAgentConfigFields(rawJsonSubset));
1417
+ }
1418
+ if (configErrors.length > 0) {
1419
+ for (const msg of configErrors) {
1420
+ result.Errors.push(new ValidationErrorInfo('Configuration', msg, this.Configuration, ValidationErrorType.Failure));
1421
+ }
1422
+ result.Success = false;
1423
+ return result;
1424
+ }
1425
+ }
1426
+ else if (Object.keys(dirtyLegacyPatch).length > 0) {
1427
+ const legacyErrors = ValidateLegacyAgentConfigFields(dirtyLegacyPatch);
1428
+ if (legacyErrors.length > 0) {
1429
+ for (const msg of legacyErrors) {
1430
+ result.Errors.push(new ValidationErrorInfo('Configuration', msg, this.Configuration, ValidationErrorType.Failure));
1431
+ }
1432
+ result.Success = false;
1433
+ return result;
1434
+ }
1435
+ }
1436
+ // C-R3-3: Always enforce SQL CHECK cross-field pair invariants against live post-sync
1437
+ // entity properties whenever Configuration or either column of the pair changed (covers
1438
+ // single-sided creates, JSON-only updates, and mixed legacy+JSON updates).
1439
+ const compactionTouched = configDirtyForValidation ||
1440
+ Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'CompactionTargetPercent') ||
1441
+ Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'CompactionTriggerPercent') ||
1442
+ (this.GetFieldByName('CompactionTargetPercent')?.Dirty ?? false) ||
1443
+ (this.GetFieldByName('CompactionTriggerPercent')?.Dirty ?? false);
1444
+ if (compactionTouched &&
1445
+ typeof this.CompactionTargetPercent === 'number' &&
1446
+ Number.isFinite(this.CompactionTargetPercent) &&
1447
+ typeof this.CompactionTriggerPercent === 'number' &&
1448
+ Number.isFinite(this.CompactionTriggerPercent) &&
1449
+ this.CompactionTargetPercent >= this.CompactionTriggerPercent) {
1450
+ result.Errors.push(new ValidationErrorInfo('CompactionTargetPercent', `CompactionTargetPercent (${this.CompactionTargetPercent}) must be less than CompactionTriggerPercent (${this.CompactionTriggerPercent}).`, this.CompactionTargetPercent, ValidationErrorType.Failure));
1451
+ result.Success = false;
1452
+ return result;
1453
+ }
1454
+ const execRangeTouched = configDirtyForValidation ||
1455
+ Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'MinExecutionsPerRun') ||
1456
+ Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'MaxExecutionsPerRun') ||
1457
+ (this.GetFieldByName('MinExecutionsPerRun')?.Dirty ?? false) ||
1458
+ (this.GetFieldByName('MaxExecutionsPerRun')?.Dirty ?? false);
1459
+ if (execRangeTouched &&
1460
+ typeof this.MinExecutionsPerRun === 'number' &&
1461
+ Number.isFinite(this.MinExecutionsPerRun) &&
1462
+ typeof this.MaxExecutionsPerRun === 'number' &&
1463
+ Number.isFinite(this.MaxExecutionsPerRun) &&
1464
+ this.MinExecutionsPerRun > this.MaxExecutionsPerRun) {
1465
+ result.Errors.push(new ValidationErrorInfo('MinExecutionsPerRun', `MinExecutionsPerRun (${this.MinExecutionsPerRun}) cannot exceed MaxExecutionsPerRun (${this.MaxExecutionsPerRun}).`, this.MinExecutionsPerRun, ValidationErrorType.Failure));
1466
+ result.Success = false;
1467
+ return result;
1468
+ }
1469
+ // 1. BaseAgentID inheritance, helperPlugins & non-admin sandbox checks
239
1470
  const user = this.ContextCurrentUser;
240
- const isAdmin = IsAgentAdminOrOwnerUser(user);
241
- if (this.BaseAgentID || !isAdmin) {
242
- const [allAgents, allPermissions] = await Promise.all([
243
- this.loadAllAgentsForGuard(),
244
- this.loadAllAgentPermissionsForGuard(),
245
- ]);
1471
+ const isAdmin = IsAgentAdminOrOwnerUser(user, this.ProviderToUse);
1472
+ const hasHelperPluginsKey = (raw) => {
1473
+ if (!raw || raw.trim().length === 0)
1474
+ return false;
1475
+ try {
1476
+ const parsed = JSON.parse(raw);
1477
+ return Boolean(parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'helperPlugins'));
1478
+ }
1479
+ catch {
1480
+ return false;
1481
+ }
1482
+ };
1483
+ const hasDeclaredHelperPlugins = ParseAgentHelperPlugins(this.Configuration).length > 0 ||
1484
+ ParseAgentHelperPlugins(this.TypeConfiguration).length > 0 ||
1485
+ hasHelperPluginsKey(this.Configuration) ||
1486
+ hasHelperPluginsKey(this.TypeConfiguration);
1487
+ const hasPathTraversal = HasPathTraversalSegment(this.PayloadScope) ||
1488
+ HasPathTraversalSegment(this.AttachmentRootPath) ||
1489
+ HasPathTraversalSegment(ParseAgentConfiguration(this.Configuration)?.payload?.scope) ||
1490
+ HasPathTraversalSegment(ParseAgentConfiguration(this.Configuration)?.attachments?.rootPath);
1491
+ const hasAllowWidenKey = JsonHasAllowWidenFromBaseKey(this.Configuration) ||
1492
+ JsonHasAllowWidenFromBaseKey(this.GetFieldByName('Configuration')?.OldValue ?? null);
1493
+ if (this.BaseAgentID || !isAdmin || hasDeclaredHelperPlugins || hasPathTraversal || hasAllowWidenKey) {
1494
+ const guardBatch = this._saveGuardCache ?? (await this.loadGuardMetadataBatch());
1495
+ if (guardBatch.ErrorMessage) {
1496
+ result.Errors.push(new ValidationErrorInfo('BaseAgentID', `Fail-closed: unable to verify agent inheritance and policy guardrails (${guardBatch.ErrorMessage}).`, this.BaseAgentID, ValidationErrorType.Failure));
1497
+ result.Success = false;
1498
+ return result;
1499
+ }
1500
+ const { AllAgents: allAgents, AllPermissions: allPermissions, AllCategories: allCategories, AllAgentTypes: allAgentTypes, } = guardBatch;
1501
+ const dirtyFieldNames = new Set();
1502
+ for (const f of this.Fields) {
1503
+ if (f.Dirty) {
1504
+ if (f.Name === 'Configuration' && this._configDirtyBeforeSync === false) {
1505
+ continue;
1506
+ }
1507
+ dirtyFieldNames.add(f.Name);
1508
+ }
1509
+ }
1510
+ const oldNum = (name) => {
1511
+ const v = this.GetFieldByName(name)?.OldValue;
1512
+ return typeof v === 'number' && Number.isFinite(v) ? v : null;
1513
+ };
246
1514
  const sandboxErrors = ValidateAgentInheritanceAndSandbox({
247
1515
  Target: {
248
1516
  ID: this.ID,
@@ -251,6 +1519,10 @@ let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityE
251
1519
  PreSaveBaseAgentID: this.GetFieldByName('BaseAgentID')?.OldValue ?? this.BaseAgentID,
252
1520
  OwnerUserID: this.OwnerUserID,
253
1521
  PreSaveOwnerUserID: this.GetFieldByName('OwnerUserID')?.OldValue ?? this.OwnerUserID,
1522
+ CategoryID: this.CategoryID,
1523
+ PreSaveCategoryID: this.GetFieldByName('CategoryID')?.OldValue ?? null,
1524
+ TypeID: this.TypeID,
1525
+ PreSaveTypeID: this.GetFieldByName('TypeID')?.OldValue ?? null,
254
1526
  InstantiationMode: this.InstantiationMode,
255
1527
  DriverClass: this.DriverClass,
256
1528
  DriverClassDirty: this.GetFieldByName('DriverClass')?.Dirty ?? false,
@@ -260,10 +1532,65 @@ let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityE
260
1532
  MaxTokensPerRun: this.MaxTokensPerRun,
261
1533
  MaxTimePerRun: this.MaxTimePerRun,
262
1534
  MaxIterationsPerRun: this.MaxIterationsPerRun,
1535
+ SearchScopeAccess: this.SearchScopeAccess,
1536
+ RequirePlanMode: this.RequirePlanMode,
1537
+ SupportsPlanMode: this.SupportsPlanMode,
1538
+ AcceptUnregisteredFiles: this.AcceptUnregisteredFiles,
1539
+ AllowEphemeralClientTools: this.AllowEphemeralClientTools,
1540
+ AcceptsSkills: this.AcceptsSkills,
1541
+ SkillActivationMode: this.SkillActivationMode,
1542
+ AllowMemoryWrite: this.AllowMemoryWrite,
1543
+ MinExecutionsPerRun: this.MinExecutionsPerRun,
1544
+ MaxExecutionsPerRun: this.MaxExecutionsPerRun,
1545
+ MaxSubAgentConsultRounds: this.MaxSubAgentConsultRounds,
1546
+ PayloadDownstreamPaths: this.PayloadDownstreamPaths,
1547
+ PayloadUpstreamPaths: this.PayloadUpstreamPaths,
1548
+ PayloadSelfReadPaths: this.PayloadSelfReadPaths,
1549
+ PayloadSelfWritePaths: this.PayloadSelfWritePaths,
1550
+ PayloadScope: this.PayloadScope,
1551
+ StartingPayloadValidationMode: this.StartingPayloadValidationMode,
1552
+ FinalPayloadValidationMode: this.FinalPayloadValidationMode,
1553
+ FinalPayloadValidationMaxRetries: this.FinalPayloadValidationMaxRetries,
1554
+ ArtifactCreationMode: this.ArtifactCreationMode,
1555
+ MessageMode: this.MessageMode,
1556
+ MaxMessages: this.MaxMessages,
1557
+ AttachmentRootPath: this.AttachmentRootPath,
1558
+ InlineStorageThresholdBytes: this.InlineStorageThresholdBytes,
1559
+ ContextWindowMaxTokens: this.ContextWindowMaxTokens,
1560
+ MaxNotesToInject: this.MaxNotesToInject,
1561
+ MaxExamplesToInject: this.MaxExamplesToInject,
1562
+ NoteRetentionDays: this.NoteRetentionDays,
1563
+ ExampleRetentionDays: this.ExampleRetentionDays,
1564
+ AutoArchiveEnabled: this.AutoArchiveEnabled,
1565
+ ScopeConfig: this.ScopeConfig,
1566
+ AgentTypePromptParams: this.AgentTypePromptParams,
1567
+ Configuration: this.Configuration,
1568
+ PreSaveConfiguration: this.GetFieldByName('Configuration')?.OldValue ?? null,
1569
+ TypeConfiguration: this.TypeConfiguration,
1570
+ DirtyFields: dirtyFieldNames,
1571
+ PreSaveLimits: {
1572
+ MaxCostPerRun: oldNum('MaxCostPerRun'),
1573
+ MaxTokensPerRun: oldNum('MaxTokensPerRun'),
1574
+ MaxTimePerRun: oldNum('MaxTimePerRun'),
1575
+ MaxIterationsPerRun: oldNum('MaxIterationsPerRun'),
1576
+ MaxExecutionsPerRun: oldNum('MaxExecutionsPerRun'),
1577
+ MaxSubAgentConsultRounds: oldNum('MaxSubAgentConsultRounds'),
1578
+ ContextWindowMaxTokens: oldNum('ContextWindowMaxTokens'),
1579
+ MaxNotesToInject: oldNum('MaxNotesToInject'),
1580
+ MaxExamplesToInject: oldNum('MaxExamplesToInject'),
1581
+ NoteRetentionDays: oldNum('NoteRetentionDays'),
1582
+ ExampleRetentionDays: oldNum('ExampleRetentionDays'),
1583
+ MaxMessages: oldNum('MaxMessages'),
1584
+ InlineStorageThresholdBytes: oldNum('InlineStorageThresholdBytes'),
1585
+ FinalPayloadValidationMaxRetries: oldNum('FinalPayloadValidationMaxRetries'),
1586
+ },
263
1587
  },
264
1588
  User: user,
1589
+ Provider: this.ProviderToUse,
265
1590
  AllAgents: allAgents,
266
1591
  AllPermissions: allPermissions,
1592
+ AllCategories: allCategories,
1593
+ AllAgentTypes: allAgentTypes,
267
1594
  });
268
1595
  if (sandboxErrors.length > 0) {
269
1596
  result.Errors.push(...sandboxErrors);
@@ -294,49 +1621,299 @@ let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityE
294
1621
  * like *Pepper* immediately inherit `TypeID`, `AcceptsSkills`, `SkillActivationMode`,
295
1622
  * `ModelSelectionMode`, `Isolation`, and memory settings without requiring every caller to
296
1623
  * manually copy 20 columns.
1624
+ *
1625
+ * Note (C-R1-1 vs R5-1): On GraphQL creates (`NewRecord()` + `SetMany(input)`), untouched
1626
+ * columns arrive with `Dirty === false`, `NeverSet === false`, and their SQL default value.
1627
+ * For general overridable columns (e.g. `InjectNotes = true`), `!Dirty` + SQL default is
1628
+ * treated as untouched so parent values inherit cleanly (meaning an explicit create write equal
1629
+ * to the SQL default under a non-default base inherits the base value unless set via
1630
+ * `Configuration` or updated after create). For the 4 strict-default narrow-only columns
1631
+ * (`SearchScopeAccess`, `AcceptUnregisteredFiles`, `AcceptsSkills`, `SkillActivationMode`),
1632
+ * `NeverSet === true` is required so explicit strict restrictions are never loosened.
297
1633
  */
298
- inheritDefaultsFromBaseAgent(baseAgent) {
299
- const copyIfNotDirty = (fieldName) => {
1634
+ inheritDefaultsFromBaseAgent(baseAgent, allAgents, allCategories, allAgentTypes) {
1635
+ const nonLegacySqlDefaults = {
1636
+ AcceptsSkills: 'None',
1637
+ Isolation: 'InProcess',
1638
+ MaxCostPerRun: null,
1639
+ MaxTokensPerRun: null,
1640
+ MaxTimePerRun: null,
1641
+ MaxIterationsPerRun: null,
1642
+ };
1643
+ const isFieldAtSqlDefault = (fieldName) => {
1644
+ const currentVal = this[fieldName];
1645
+ const keyStr = String(fieldName);
1646
+ if (Object.prototype.hasOwnProperty.call(LEGACY_AI_AGENT_CONFIG_SQL_DEFAULTS, keyStr)) {
1647
+ const legacyKey = keyStr;
1648
+ return IsLegacyAIAgentConfigSqlDefault(legacyKey, currentVal);
1649
+ }
1650
+ if (Object.prototype.hasOwnProperty.call(nonLegacySqlDefaults, keyStr)) {
1651
+ return currentVal === nonLegacySqlDefaults[fieldName];
1652
+ }
1653
+ return false;
1654
+ };
1655
+ // R5-1: Never treat a written (`NeverSet === false`) strict SQL default as untouched on the
1656
+ // 4 narrow-only columns whose SQL default is the strict side (`SearchScopeAccess = 'None'`,
1657
+ // `AcceptUnregisteredFiles = false`, `AcceptsSkills = 'None'`, `SkillActivationMode = 'RequestedOnly'`),
1658
+ // otherwise an explicit caller restriction is silently loosened to the base agent's value!
1659
+ const STRICT_DEFAULT_NARROW_ONLY_FIELDS = new Set([
1660
+ 'SearchScopeAccess',
1661
+ 'AcceptUnregisteredFiles',
1662
+ 'AcceptsSkills',
1663
+ 'SkillActivationMode',
1664
+ ]);
1665
+ const copyIfNotDirty = (fieldName, overrideVal, clampLooseDbDefault) => {
300
1666
  const field = this.GetFieldByName(String(fieldName));
301
- if (field && !field.Dirty) {
302
- const baseVal = baseAgent[fieldName];
303
- if (baseVal !== undefined) {
304
- this[fieldName] = baseVal;
305
- }
1667
+ if (!field)
1668
+ return;
1669
+ const val = overrideVal !== undefined ? overrideVal : baseAgent[fieldName];
1670
+ if (val === undefined)
1671
+ return;
1672
+ const preserveWrittenStrictDefault = STRICT_DEFAULT_NARROW_ONLY_FIELDS.has(String(fieldName));
1673
+ const isUntouched = preserveWrittenStrictDefault
1674
+ ? !field.Dirty && field.NeverSet
1675
+ : !field.Dirty && (field.NeverSet || isFieldAtSqlDefault(fieldName));
1676
+ const isLooseDbDefault = clampLooseDbDefault !== undefined && this[fieldName] === clampLooseDbDefault;
1677
+ if (isUntouched || isLooseDbDefault) {
1678
+ this[fieldName] = val;
306
1679
  }
307
1680
  };
1681
+ // Walk full ancestor chain so newly-created derived instances inherit the strictest
1682
+ // ancestor limits and narrow-only capability booleans (prevents DB defaults like
1683
+ // AllowEphemeralClientTools=1 from colliding with a false ancestor in ValidateAsync).
1684
+ const ancestors = [baseAgent];
1685
+ if (allAgents && allAgents.length > 0) {
1686
+ const byId = IndexByUUID(allAgents);
1687
+ const seen = new UUIDSet([baseAgent.ID]);
1688
+ let cur = baseAgent;
1689
+ while (cur?.BaseAgentID && ancestors.length <= MAX_AGENT_INHERITANCE_DEPTH) {
1690
+ if (seen.Has(cur.BaseAgentID))
1691
+ break;
1692
+ seen.Add(cur.BaseAgentID);
1693
+ const parent = byId.Get(cur.BaseAgentID);
1694
+ if (!parent)
1695
+ break;
1696
+ ancestors.unshift(parent);
1697
+ cur = parent;
1698
+ }
1699
+ }
1700
+ const ancestorConfigs = ancestors.map((a) => ParseAgentConfiguration(a.Configuration));
308
1701
  if (!this.TypeID && baseAgent.TypeID) {
309
1702
  this.TypeID = baseAgent.TypeID;
310
1703
  }
1704
+ if (!this.CategoryID && baseAgent.CategoryID) {
1705
+ this.CategoryID = baseAgent.CategoryID;
1706
+ }
1707
+ const defaultPolicyLayers = collectDefaultPolicyLayers([...ancestors, { CategoryID: this.CategoryID, TypeID: this.TypeID }], allCategories, allAgentTypes);
1708
+ const minFiniteRebase = (layerPicker, jsonPicker, legacyPicker, sqlDefault = null) => {
1709
+ const minVal = (a, b) => {
1710
+ if (typeof b !== 'number' || !Number.isFinite(b))
1711
+ return a;
1712
+ return a === null ? b : Math.min(a, b);
1713
+ };
1714
+ let seed = null;
1715
+ for (const layer of defaultPolicyLayers) {
1716
+ seed = minVal(seed, layerPicker(layer));
1717
+ }
1718
+ if (ancestors.length > 0) {
1719
+ const exp0 = jsonPicker(ancestorConfigs[0]);
1720
+ const leg0 = legacyPicker(ancestors[0]);
1721
+ const leg0Eff = exp0 === undefined && sqlDefault !== null && leg0 === sqlDefault && seed !== null ? null : leg0;
1722
+ seed = minVal(seed, exp0);
1723
+ seed = minVal(seed, leg0Eff);
1724
+ }
1725
+ return FoldRebaseAwareChain({
1726
+ Nodes: ancestors,
1727
+ NodeConfigs: ancestorConfigs,
1728
+ Seed: seed,
1729
+ GetNodeValue: (anc, cfg, idx) => {
1730
+ const exp = jsonPicker(cfg);
1731
+ const leg = legacyPicker(anc);
1732
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
1733
+ if (exp === null)
1734
+ return null;
1735
+ if (typeof exp === 'number' && Number.isFinite(exp))
1736
+ return exp;
1737
+ if (typeof leg === 'number' && Number.isFinite(leg) && leg !== sqlDefault)
1738
+ return leg;
1739
+ return undefined;
1740
+ }
1741
+ if (typeof exp === 'number' && Number.isFinite(exp)) {
1742
+ if (typeof leg === 'number' && Number.isFinite(leg) && leg !== sqlDefault) {
1743
+ return Math.min(exp, leg);
1744
+ }
1745
+ return exp;
1746
+ }
1747
+ if (typeof leg === 'number' && Number.isFinite(leg) && leg !== sqlDefault)
1748
+ return leg;
1749
+ return undefined;
1750
+ },
1751
+ Narrow: (acc, next) => minVal(acc, next),
1752
+ });
1753
+ };
1754
+ const narrowSkillMode = (acc, v) => {
1755
+ if (v == null)
1756
+ return acc;
1757
+ return acc === null || SKILL_ACTIVATION_RANK[v] < SKILL_ACTIVATION_RANK[acc] ? v : acc;
1758
+ };
1759
+ let seedSkill = null;
1760
+ for (const layer of defaultPolicyLayers) {
1761
+ seedSkill = narrowSkillMode(seedSkill, layer.skills?.activationMode);
1762
+ }
1763
+ if (ancestors.length > 0) {
1764
+ seedSkill = narrowSkillMode(seedSkill, ancestorConfigs[0]?.skills?.activationMode);
1765
+ seedSkill = narrowSkillMode(seedSkill, ancestors[0].SkillActivationMode);
1766
+ }
1767
+ const strictestSkillMode = FoldRebaseAwareChain({
1768
+ Nodes: ancestors,
1769
+ NodeConfigs: ancestorConfigs,
1770
+ Seed: seedSkill,
1771
+ GetNodeValue: (anc, cfg, idx) => {
1772
+ const exp = cfg?.skills?.activationMode ?? null;
1773
+ const leg = anc.SkillActivationMode ?? null;
1774
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
1775
+ if (exp != null)
1776
+ return exp;
1777
+ return leg != null && leg !== 'RequestedOnly' ? leg : undefined;
1778
+ }
1779
+ if (exp != null && leg != null) {
1780
+ return SKILL_ACTIVATION_RANK[leg] < SKILL_ACTIVATION_RANK[exp] ? leg : exp;
1781
+ }
1782
+ if (exp != null)
1783
+ return exp;
1784
+ const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
1785
+ return leg != null && (leg !== 'RequestedOnly' || !isNonInst) ? leg : undefined;
1786
+ },
1787
+ Narrow: (acc, next) => narrowSkillMode(acc, next),
1788
+ }) ?? baseAgent.SkillActivationMode ?? 'RequestedOnly';
1789
+ const ancestorSearchCeiling = computeAncestorSearchScopeCeiling(defaultPolicyLayers, ancestors, ancestorConfigs);
1790
+ const strictestSearchAccess = ancestorSearchCeiling ?? 'None';
1791
+ const strictestAcceptsSkills = FoldRebaseAwareChain({
1792
+ Nodes: ancestors,
1793
+ NodeConfigs: ancestorConfigs,
1794
+ Seed: ancestors[0]?.AcceptsSkills ?? baseAgent.AcceptsSkills ?? 'None',
1795
+ GetNodeValue: (anc) => anc.AcceptsSkills ?? undefined,
1796
+ Narrow: (acc, next) => (ACCEPTS_SKILLS_RANK[next] < ACCEPTS_SKILLS_RANK[acc] ? next : acc),
1797
+ });
1798
+ const foldBoolAndRebase = (layerPicker, jsonPicker, legacyPicker, sqlDefault, fallback) => {
1799
+ const fAnd = (acc, v) => typeof v !== 'boolean' ? acc : acc === null ? v : acc && v;
1800
+ let seed = null;
1801
+ for (const layer of defaultPolicyLayers) {
1802
+ seed = fAnd(seed, layerPicker(layer));
1803
+ }
1804
+ if (ancestors.length > 0) {
1805
+ const exp0 = jsonPicker(ancestorConfigs[0]);
1806
+ const leg0 = legacyPicker(ancestors[0]);
1807
+ seed =
1808
+ typeof exp0 === 'boolean' && typeof leg0 === 'boolean'
1809
+ ? fAnd(seed, exp0 && leg0)
1810
+ : fAnd(seed, exp0 ?? leg0);
1811
+ }
1812
+ return (FoldRebaseAwareChain({
1813
+ Nodes: ancestors,
1814
+ NodeConfigs: ancestorConfigs,
1815
+ Seed: seed,
1816
+ GetNodeValue: (anc, cfg, idx) => {
1817
+ const exp = jsonPicker(cfg);
1818
+ const leg = legacyPicker(anc);
1819
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
1820
+ if (typeof exp === 'boolean')
1821
+ return exp;
1822
+ return typeof leg === 'boolean' && leg !== sqlDefault ? leg : undefined;
1823
+ }
1824
+ if (typeof exp === 'boolean' && typeof leg === 'boolean')
1825
+ return exp && leg;
1826
+ if (typeof exp === 'boolean')
1827
+ return exp;
1828
+ return typeof leg === 'boolean' && leg !== sqlDefault ? leg : undefined;
1829
+ },
1830
+ Narrow: (acc, next) => fAnd(acc, next),
1831
+ }) ?? fallback);
1832
+ };
1833
+ const seedReqPlan = defaultPolicyLayers.some((l) => l.execution?.requirePlanMode === true) ||
1834
+ (ancestors.length > 0 &&
1835
+ (ancestorConfigs[0]?.execution?.requirePlanMode === true || ancestors[0].RequirePlanMode === true));
1836
+ const strictestRequirePlan = FoldRebaseAwareChain({
1837
+ Nodes: ancestors,
1838
+ NodeConfigs: ancestorConfigs,
1839
+ Seed: seedReqPlan,
1840
+ GetNodeValue: (anc, cfg, idx) => {
1841
+ const exp = cfg?.execution?.requirePlanMode;
1842
+ const leg = anc.RequirePlanMode;
1843
+ if (idx > 0 && cfg?.allowWidenFromBase === true) {
1844
+ if (typeof exp === 'boolean')
1845
+ return exp;
1846
+ return leg === true ? true : undefined;
1847
+ }
1848
+ if (exp === true || leg === true)
1849
+ return true;
1850
+ return typeof exp === 'boolean' ? exp : undefined;
1851
+ },
1852
+ Narrow: (acc, next) => acc || next,
1853
+ });
311
1854
  copyIfNotDirty('ModelSelectionMode');
312
- copyIfNotDirty('AcceptsSkills');
313
- copyIfNotDirty('SkillActivationMode');
314
- copyIfNotDirty('SearchScopeAccess');
1855
+ copyIfNotDirty('AcceptsSkills', strictestAcceptsSkills);
1856
+ copyIfNotDirty('SkillActivationMode', strictestSkillMode);
1857
+ copyIfNotDirty('SearchScopeAccess', strictestSearchAccess);
315
1858
  copyIfNotDirty('ArtifactCreationMode');
316
1859
  copyIfNotDirty('DefaultArtifactTypeID');
317
1860
  copyIfNotDirty('InjectNotes');
318
- copyIfNotDirty('MaxNotesToInject');
1861
+ copyIfNotDirty('MaxNotesToInject', minFiniteRebase((l) => l.memory?.maxNotesToInject, (cfg) => cfg?.memory?.maxNotesToInject, (a) => a.MaxNotesToInject, 5 // SQL schema default DF_AIAgent_MaxNotesToInject
1862
+ ) ?? baseAgent.MaxNotesToInject);
319
1863
  copyIfNotDirty('NoteInjectionStrategy');
320
1864
  copyIfNotDirty('InjectExamples');
321
- copyIfNotDirty('MaxExamplesToInject');
1865
+ copyIfNotDirty('MaxExamplesToInject', minFiniteRebase((l) => l.memory?.maxExamplesToInject, (cfg) => cfg?.memory?.maxExamplesToInject, (a) => a.MaxExamplesToInject, 3 // SQL schema default DF_AIAgent_MaxExamplesToInject
1866
+ ) ?? baseAgent.MaxExamplesToInject);
322
1867
  copyIfNotDirty('ExampleInjectionStrategy');
323
- copyIfNotDirty('AllowMemoryWrite');
1868
+ copyIfNotDirty('NoteRetentionDays', minFiniteRebase((l) => l.memory?.noteRetentionDays, (cfg) => cfg?.memory?.noteRetentionDays, (a) => a.NoteRetentionDays, 90 // SQL schema default DF_AIAgent_NoteRetentionDays
1869
+ ));
1870
+ copyIfNotDirty('ExampleRetentionDays', minFiniteRebase((l) => l.memory?.exampleRetentionDays, (cfg) => cfg?.memory?.exampleRetentionDays, (a) => a.ExampleRetentionDays, 180 // SQL schema default DF_AIAgent_ExampleRetentionDays
1871
+ ));
1872
+ copyIfNotDirty('AutoArchiveEnabled');
1873
+ copyIfNotDirty('AllowMemoryWrite', foldBoolAndRebase((l) => l.memory?.allowMemoryWrite, (cfg) => cfg?.memory?.allowMemoryWrite, (a) => a.AllowMemoryWrite, true, baseAgent.AllowMemoryWrite), true);
324
1874
  copyIfNotDirty('DeclareActionsAsNativeTools');
325
- copyIfNotDirty('Isolation');
326
- copyIfNotDirty('SupportsPlanMode');
327
- copyIfNotDirty('RequirePlanMode');
1875
+ let strictestIso = baseAgent.Isolation ?? 'InProcess';
1876
+ for (const a of ancestors) {
1877
+ const iso = a.Isolation ?? 'InProcess';
1878
+ if ((ISOLATION_RANK[iso] ?? 0) > (ISOLATION_RANK[strictestIso] ?? 0)) {
1879
+ strictestIso = iso;
1880
+ }
1881
+ }
1882
+ copyIfNotDirty('Isolation', strictestIso, 'InProcess');
1883
+ copyIfNotDirty('SupportsPlanMode', foldBoolAndRebase((l) => l.execution?.supportsPlanMode, (cfg) => cfg?.execution?.supportsPlanMode, (a) => a.SupportsPlanMode, true, baseAgent.SupportsPlanMode), true);
1884
+ copyIfNotDirty('RequirePlanMode', strictestRequirePlan, false);
1885
+ copyIfNotDirty('AllowEphemeralClientTools', foldBoolAndRebase((l) => l.clientTools?.allowEphemeral, (cfg) => cfg?.clientTools?.allowEphemeral, (a) => a.AllowEphemeralClientTools, true, baseAgent.AllowEphemeralClientTools), true);
1886
+ copyIfNotDirty('AcceptUnregisteredFiles', foldBoolAndRebase((l) => l.attachments?.acceptUnregisteredFiles, (cfg) => cfg?.attachments?.acceptUnregisteredFiles, (a) => a.AcceptUnregisteredFiles, false, baseAgent.AcceptUnregisteredFiles));
1887
+ copyIfNotDirty('MaxCostPerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxCostPerRun));
1888
+ copyIfNotDirty('MaxTokensPerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxTokensPerRun));
1889
+ copyIfNotDirty('MaxTimePerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxTimePerRun));
1890
+ copyIfNotDirty('MaxIterationsPerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxIterationsPerRun));
1891
+ copyIfNotDirty('MaxExecutionsPerRun', minFiniteRebase((l) => l.subAgentExecution?.maxExecutionsPerRun, (cfg) => cfg?.subAgentExecution?.maxExecutionsPerRun, (a) => a.MaxExecutionsPerRun));
1892
+ copyIfNotDirty('MaxSubAgentConsultRounds', minFiniteRebase((l) => l.subAgentExecution?.maxConsultRounds, (cfg) => cfg?.subAgentExecution?.maxConsultRounds, (a) => a.MaxSubAgentConsultRounds));
1893
+ copyIfNotDirty('MessageMode');
1894
+ copyIfNotDirty('MaxMessages', minFiniteRebase((l) => l.attachments?.maxMessages, (cfg) => cfg?.attachments?.maxMessages, (a) => a.MaxMessages));
1895
+ copyIfNotDirty('AttachmentRootPath');
1896
+ copyIfNotDirty('InlineStorageThresholdBytes', minFiniteRebase((l) => l.attachments?.inlineStorageThresholdBytes, (cfg) => cfg?.attachments?.inlineStorageThresholdBytes, (a) => a.InlineStorageThresholdBytes));
1897
+ copyIfNotDirty('PayloadDownstreamPaths');
1898
+ copyIfNotDirty('PayloadUpstreamPaths');
1899
+ copyIfNotDirty('PayloadSelfReadPaths');
1900
+ copyIfNotDirty('PayloadSelfWritePaths');
1901
+ copyIfNotDirty('PayloadScope');
1902
+ copyIfNotDirty('StartingPayloadValidationMode');
1903
+ copyIfNotDirty('FinalPayloadValidationMode');
1904
+ copyIfNotDirty('FinalPayloadValidationMaxRetries', minFiniteRebase((l) => l.payload?.finalValidationMaxRetries, (cfg) => cfg?.payload?.finalValidationMaxRetries, (a) => a.FinalPayloadValidationMaxRetries, 3 // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
1905
+ ) ?? baseAgent.FinalPayloadValidationMaxRetries);
1906
+ copyIfNotDirty('ScopeConfig');
328
1907
  copyIfNotDirty('EnableContextCompression');
329
1908
  copyIfNotDirty('ContextCompressionMessageThreshold');
330
1909
  copyIfNotDirty('ContextCompressionPromptID');
331
1910
  copyIfNotDirty('ContextCompressionMessageRetentionCount');
332
1911
  copyIfNotDirty('RerankerConfiguration');
333
- copyIfNotDirty('ContextWindowMaxTokens');
1912
+ copyIfNotDirty('ContextWindowMaxTokens', minFiniteRebase((l) => l.contextWindow?.maxTokens, (cfg) => cfg?.contextWindow?.maxTokens, (a) => a.ContextWindowMaxTokens));
334
1913
  copyIfNotDirty('CompactionTriggerPercent');
335
1914
  copyIfNotDirty('CompactionTargetPercent');
336
1915
  copyIfNotDirty('ConversationSummaryPromptID');
337
- if (!this.CategoryID && baseAgent.CategoryID) {
338
- this.CategoryID = baseAgent.CategoryID;
339
- }
1916
+ return ancestorSearchCeiling;
340
1917
  }
341
1918
  findRootBaseAgentId(start, allAgents) {
342
1919
  const agentsById = IndexByUUID(allAgents);
@@ -392,21 +1969,294 @@ let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityE
392
1969
  }
393
1970
  }
394
1971
  }
1972
+ async loadGuardMetadataBatch() {
1973
+ // R5 Follow-up #5 & C-R4-2: single batched RunViews with ResultType: 'simple' + minimal
1974
+ // explicit Fields (replaces 7 full-table entity_object queries on derived creates) and
1975
+ // fail-closed on read errors OR FLS-omitted requested guard columns.
1976
+ const AGENT_GUARD_FIELDS = [
1977
+ 'ID', 'Name', 'BaseAgentID', 'RootBaseAgentID', 'OwnerUserID', 'Status',
1978
+ 'CategoryID', 'TypeID', 'InstantiationMode', 'DriverClass', 'Isolation',
1979
+ 'MaxCostPerRun', 'MaxTokensPerRun', 'MaxTimePerRun', 'MaxIterationsPerRun',
1980
+ 'Configuration', 'TypeConfiguration', 'AgentTypePromptParams', 'ModelSelectionMode', 'AcceptsSkills',
1981
+ 'SkillActivationMode', 'SearchScopeAccess', 'ScopeConfig', 'ArtifactCreationMode',
1982
+ 'DefaultArtifactTypeID', 'InjectNotes', 'MaxNotesToInject', 'NoteInjectionStrategy',
1983
+ 'InjectExamples', 'MaxExamplesToInject', 'ExampleInjectionStrategy',
1984
+ 'NoteRetentionDays', 'ExampleRetentionDays', 'AutoArchiveEnabled',
1985
+ 'AllowMemoryWrite', 'DeclareActionsAsNativeTools', 'SupportsPlanMode',
1986
+ 'RequirePlanMode', 'AllowEphemeralClientTools', 'AcceptUnregisteredFiles',
1987
+ 'MinExecutionsPerRun', 'MaxExecutionsPerRun', 'MaxSubAgentConsultRounds',
1988
+ 'PayloadDownstreamPaths', 'PayloadUpstreamPaths', 'PayloadSelfReadPaths',
1989
+ 'PayloadSelfWritePaths', 'PayloadScope', 'StartingPayloadValidationMode',
1990
+ 'FinalPayloadValidationMode', 'FinalPayloadValidationMaxRetries',
1991
+ 'MessageMode', 'MaxMessages', 'AttachmentRootPath', 'InlineStorageThresholdBytes',
1992
+ 'EnableContextCompression', 'ContextCompressionMessageThreshold',
1993
+ 'ContextCompressionPromptID', 'ContextCompressionMessageRetentionCount',
1994
+ 'RerankerConfiguration', 'ContextWindowMaxTokens', 'CompactionTriggerPercent',
1995
+ 'CompactionTargetPercent', 'ConversationSummaryPromptID',
1996
+ ];
1997
+ const PERMISSION_GUARD_FIELDS = [
1998
+ 'ID', 'AgentID', 'UserID', 'RoleID', 'CanView', 'CanRun', 'CanEdit', 'CanDelete',
1999
+ ];
2000
+ const CATEGORY_GUARD_FIELDS = ['ID', 'ParentID', 'DefaultConfiguration'];
2001
+ const TYPE_GUARD_FIELDS = [
2002
+ 'ID', 'DefaultAgentConfiguration', 'ContextCompressionMessageThreshold',
2003
+ 'ContextCompressionPromptID', 'ContextCompressionMessageRetentionCount',
2004
+ 'ContextWindowMaxTokens', 'CompactionTriggerPercent', 'CompactionTargetPercent',
2005
+ 'ConversationSummaryPromptID',
2006
+ ];
2007
+ // R7-1: Filter requested guard fields against the active provider's entity metadata so
2008
+ // hosts/databases whose schema has not yet received newly added columns (e.g. PostgreSQL
2009
+ // prior to the twin migration for AIAgent.Configuration) neither emit "not found in entity"
2010
+ // log noise nor misclassify schema-absent columns as field-level security denials.
2011
+ const hasEntityLookup = (p) => Boolean(p && 'EntityByName' in p && typeof p.EntityByName === 'function');
2012
+ const metadataProvider = IsMetadataProvider(this.ProviderToUse)
2013
+ ? this.ProviderToUse
2014
+ : hasEntityLookup(this.RunViewProviderToUse)
2015
+ ? this.RunViewProviderToUse
2016
+ : null;
2017
+ const filterExistingFields = (entityName, requested) => {
2018
+ const entityInfo = metadataProvider?.EntityByName(entityName);
2019
+ if (!entityInfo) {
2020
+ return [...requested];
2021
+ }
2022
+ return requested.filter((fieldName) => Boolean(entityInfo.FieldByName(fieldName)));
2023
+ };
2024
+ const agentFields = filterExistingFields('MJ: AI Agents', AGENT_GUARD_FIELDS);
2025
+ const permissionFields = filterExistingFields('MJ: AI Agent Permissions', PERMISSION_GUARD_FIELDS);
2026
+ const categoryFields = filterExistingFields('MJ: AI Agent Categories', CATEGORY_GUARD_FIELDS);
2027
+ const typeFields = filterExistingFields('MJ: AI Agent Types', TYPE_GUARD_FIELDS);
2028
+ const rv = new RunView(this.RunViewProviderToUse);
2029
+ const results = await rv.RunViews([
2030
+ {
2031
+ EntityName: 'MJ: AI Agents',
2032
+ ResultType: 'simple',
2033
+ Fields: agentFields,
2034
+ },
2035
+ {
2036
+ EntityName: 'MJ: AI Agent Permissions',
2037
+ ResultType: 'simple',
2038
+ Fields: permissionFields,
2039
+ },
2040
+ {
2041
+ EntityName: 'MJ: AI Agent Categories',
2042
+ ResultType: 'simple',
2043
+ Fields: categoryFields,
2044
+ },
2045
+ {
2046
+ EntityName: 'MJ: AI Agent Types',
2047
+ ResultType: 'simple',
2048
+ Fields: typeFields,
2049
+ },
2050
+ ], this.ContextCurrentUser);
2051
+ const failed = results.find((r) => !r.Success);
2052
+ if (failed) {
2053
+ return {
2054
+ AllAgents: [],
2055
+ AllPermissions: [],
2056
+ AllCategories: [],
2057
+ AllAgentTypes: [],
2058
+ ErrorMessage: failed.ErrorMessage || 'Guard metadata RunViews query failed',
2059
+ };
2060
+ }
2061
+ // R6 Follow-up #5, C-R4-2 & R7-1: Fail closed if field-level security silently omitted ANY
2062
+ // metadata-present requested guard column from a `'simple'` RunView projection (e.g. denied
2063
+ // `DefaultConfiguration`, `MaxCostPerRun`, `TypeConfiguration`, `RequirePlanMode`, etc.).
2064
+ const requiredGuardFieldsByResult = [
2065
+ { Entity: 'MJ: AI Agents', Rows: results[0].Results, RequiredFields: agentFields },
2066
+ { Entity: 'MJ: AI Agent Permissions', Rows: results[1].Results, RequiredFields: permissionFields },
2067
+ { Entity: 'MJ: AI Agent Categories', Rows: results[2].Results, RequiredFields: categoryFields },
2068
+ { Entity: 'MJ: AI Agent Types', Rows: results[3].Results, RequiredFields: typeFields },
2069
+ ];
2070
+ for (const check of requiredGuardFieldsByResult) {
2071
+ if (check.Rows.length > 0) {
2072
+ const sample = check.Rows[0];
2073
+ const missingField = check.RequiredFields.find((f) => !sample || !Object.prototype.hasOwnProperty.call(sample, f));
2074
+ if (missingField) {
2075
+ return {
2076
+ AllAgents: [],
2077
+ AllPermissions: [],
2078
+ AllCategories: [],
2079
+ AllAgentTypes: [],
2080
+ ErrorMessage: `Required security guard field '${missingField}' was omitted from '${check.Entity}' query result (possible field-level security restriction).`,
2081
+ };
2082
+ }
2083
+ }
2084
+ }
2085
+ return {
2086
+ AllAgents: results[0].Results,
2087
+ AllPermissions: results[1].Results,
2088
+ AllCategories: results[2].Results,
2089
+ AllAgentTypes: results[3].Results,
2090
+ };
2091
+ }
395
2092
  async loadAllAgentsForGuard() {
396
2093
  const rv = new RunView(this.RunViewProviderToUse);
397
2094
  const res = await rv.RunView({
398
2095
  EntityName: 'MJ: AI Agents',
399
- ResultType: 'entity_object',
2096
+ ResultType: 'simple',
2097
+ Fields: ['ID', 'BaseAgentID', 'RootBaseAgentID'],
400
2098
  }, this.ContextCurrentUser);
401
2099
  return res.Success ? res.Results : [];
402
2100
  }
403
- async loadAllAgentPermissionsForGuard() {
404
- const rv = new RunView(this.RunViewProviderToUse);
405
- const res = await rv.RunView({
406
- EntityName: 'MJ: AI Agent Permissions',
407
- ResultType: 'entity_object',
408
- }, this.ContextCurrentUser);
409
- return res.Success ? res.Results : [];
2101
+ buildLegacyConfigValues() {
2102
+ return {
2103
+ ModelSelectionMode: this.ModelSelectionMode,
2104
+ DefaultPromptEffortLevel: this.DefaultPromptEffortLevel,
2105
+ ChatHandlingOption: this.ChatHandlingOption,
2106
+ SupportsPlanMode: this.SupportsPlanMode,
2107
+ RequirePlanMode: this.RequirePlanMode,
2108
+ DeclareActionsAsNativeTools: this.DeclareActionsAsNativeTools,
2109
+ EnableContextCompression: this.EnableContextCompression,
2110
+ ContextCompressionMessageThreshold: this.ContextCompressionMessageThreshold,
2111
+ ContextCompressionPromptID: this.ContextCompressionPromptID,
2112
+ ContextCompressionMessageRetentionCount: this.ContextCompressionMessageRetentionCount,
2113
+ ContextWindowMaxTokens: this.ContextWindowMaxTokens,
2114
+ CompactionTriggerPercent: this.CompactionTriggerPercent,
2115
+ CompactionTargetPercent: this.CompactionTargetPercent,
2116
+ ConversationSummaryPromptID: this.ConversationSummaryPromptID,
2117
+ InjectNotes: this.InjectNotes,
2118
+ MaxNotesToInject: this.MaxNotesToInject,
2119
+ NoteInjectionStrategy: this.NoteInjectionStrategy,
2120
+ InjectExamples: this.InjectExamples,
2121
+ MaxExamplesToInject: this.MaxExamplesToInject,
2122
+ ExampleInjectionStrategy: this.ExampleInjectionStrategy,
2123
+ NoteRetentionDays: this.NoteRetentionDays,
2124
+ ExampleRetentionDays: this.ExampleRetentionDays,
2125
+ AutoArchiveEnabled: this.AutoArchiveEnabled,
2126
+ AllowMemoryWrite: this.AllowMemoryWrite,
2127
+ RerankerConfiguration: this.RerankerConfiguration,
2128
+ PayloadDownstreamPaths: this.PayloadDownstreamPaths,
2129
+ PayloadUpstreamPaths: this.PayloadUpstreamPaths,
2130
+ PayloadSelfReadPaths: this.PayloadSelfReadPaths,
2131
+ PayloadSelfWritePaths: this.PayloadSelfWritePaths,
2132
+ PayloadScope: this.PayloadScope,
2133
+ StartingPayloadValidation: this.StartingPayloadValidation,
2134
+ StartingPayloadValidationMode: this.StartingPayloadValidationMode,
2135
+ FinalPayloadValidation: this.FinalPayloadValidation,
2136
+ FinalPayloadValidationMode: this.FinalPayloadValidationMode,
2137
+ FinalPayloadValidationMaxRetries: this.FinalPayloadValidationMaxRetries,
2138
+ ExecutionMode: this.ExecutionMode,
2139
+ MinExecutionsPerRun: this.MinExecutionsPerRun,
2140
+ MaxExecutionsPerRun: this.MaxExecutionsPerRun,
2141
+ MaxSubAgentConsultRounds: this.MaxSubAgentConsultRounds,
2142
+ MessageMode: this.MessageMode,
2143
+ MaxMessages: this.MaxMessages,
2144
+ AttachmentRootPath: this.AttachmentRootPath,
2145
+ InlineStorageThresholdBytes: this.InlineStorageThresholdBytes,
2146
+ AcceptUnregisteredFiles: this.AcceptUnregisteredFiles,
2147
+ ArtifactCreationMode: this.ArtifactCreationMode,
2148
+ DefaultArtifactTypeID: this.DefaultArtifactTypeID,
2149
+ SearchScopeAccess: this.SearchScopeAccess,
2150
+ ScopeConfig: this.ScopeConfig,
2151
+ SkillActivationMode: this.SkillActivationMode,
2152
+ AllowEphemeralClientTools: this.AllowEphemeralClientTools,
2153
+ RecordingDefault: this.RecordingDefault,
2154
+ };
2155
+ }
2156
+ isFieldExplicitlyWritten(fieldName, isCreate) {
2157
+ const field = this.GetFieldByName(fieldName);
2158
+ if (!field) {
2159
+ return false;
2160
+ }
2161
+ if (!isCreate) {
2162
+ return field.Dirty === true;
2163
+ }
2164
+ if (field.Dirty === true) {
2165
+ return true;
2166
+ }
2167
+ if (field.NeverSet !== false) {
2168
+ return false;
2169
+ }
2170
+ // On GraphQL CreateRecord (`NewRecord()` + `SetMany(input)`), ResolverBase populates every
2171
+ // writable field with its SQL default, leaving `Dirty === false` while flipping `NeverSet`
2172
+ // to `false`. Treat `!Dirty` + SQL default value as untouched so defaults never freeze into
2173
+ // `AIAgent.Configuration` and clobber BaseAgent / Category / AgentType cascade (C-R1-1).
2174
+ if (fieldName === 'Configuration') {
2175
+ return this.Configuration !== null && this.Configuration !== undefined;
2176
+ }
2177
+ if (Object.prototype.hasOwnProperty.call(LEGACY_AI_AGENT_CONFIG_SQL_DEFAULTS, fieldName)) {
2178
+ const legacyKey = fieldName;
2179
+ const legacyValues = this.buildLegacyConfigValues();
2180
+ return !IsLegacyAIAgentConfigSqlDefault(legacyKey, legacyValues[legacyKey]);
2181
+ }
2182
+ return true;
2183
+ }
2184
+ collectDirtyLegacyConfigFields(isCreate) {
2185
+ const dirtyLegacyFields = new Set();
2186
+ const legacyValues = this.buildLegacyConfigValues();
2187
+ const keys = Object.keys(legacyValues);
2188
+ for (const key of keys) {
2189
+ const field = this.GetFieldByName(key);
2190
+ if (!field) {
2191
+ continue;
2192
+ }
2193
+ if (!isCreate) {
2194
+ if (field.Dirty === true) {
2195
+ dirtyLegacyFields.add(key);
2196
+ }
2197
+ }
2198
+ else if (field.Dirty === true ||
2199
+ (field.NeverSet === false && !IsLegacyAIAgentConfigSqlDefault(key, legacyValues[key]))) {
2200
+ dirtyLegacyFields.add(key);
2201
+ }
2202
+ }
2203
+ return dirtyLegacyFields;
2204
+ }
2205
+ buildLegacyPatchFromSet(dirtyFields) {
2206
+ const patch = {};
2207
+ if (dirtyFields.size === 0) {
2208
+ return patch;
2209
+ }
2210
+ const legacyValues = this.buildLegacyConfigValues();
2211
+ for (const key of dirtyFields) {
2212
+ if (legacyValues[key] !== undefined) {
2213
+ patch[key] = legacyValues[key];
2214
+ }
2215
+ }
2216
+ // R5 Follow-up #6: include stored counterparts for cross-field pair constraints when only one side is dirty
2217
+ if (dirtyFields.has('CompactionTargetPercent') && !dirtyFields.has('CompactionTriggerPercent')) {
2218
+ patch.CompactionTriggerPercent = legacyValues.CompactionTriggerPercent;
2219
+ }
2220
+ else if (dirtyFields.has('CompactionTriggerPercent') && !dirtyFields.has('CompactionTargetPercent')) {
2221
+ patch.CompactionTargetPercent = legacyValues.CompactionTargetPercent;
2222
+ }
2223
+ if (dirtyFields.has('MinExecutionsPerRun') && !dirtyFields.has('MaxExecutionsPerRun')) {
2224
+ patch.MaxExecutionsPerRun = legacyValues.MaxExecutionsPerRun;
2225
+ }
2226
+ else if (dirtyFields.has('MaxExecutionsPerRun') && !dirtyFields.has('MinExecutionsPerRun')) {
2227
+ patch.MinExecutionsPerRun = legacyValues.MinExecutionsPerRun;
2228
+ }
2229
+ return patch;
2230
+ }
2231
+ syncConfigurationWithLegacyColumns(isCreate, dirtyLegacyFields) {
2232
+ const configField = this.GetFieldByName('Configuration');
2233
+ if (!configField) {
2234
+ // Database schema has not yet received the Configuration column (e.g., PostgreSQL prior to twin migration).
2235
+ return;
2236
+ }
2237
+ const legacyValues = this.buildLegacyConfigValues();
2238
+ const configDirty = this.isFieldExplicitlyWritten('Configuration', isCreate);
2239
+ const previousConfigJson = !isCreate && typeof configField.OldValue === 'string' ? configField.OldValue : null;
2240
+ const syncResult = SyncAgentLegacyColumnsAndConfiguration({
2241
+ IsNewRecord: isCreate,
2242
+ ConfigurationJson: this.Configuration,
2243
+ PreviousConfigurationJson: previousConfigJson,
2244
+ ConfigurationDirty: configDirty,
2245
+ LegacyValues: legacyValues,
2246
+ DirtyLegacyFields: dirtyLegacyFields,
2247
+ });
2248
+ for (const [key, value] of Object.entries(syncResult.LegacyColumnUpdates)) {
2249
+ if (value !== undefined) {
2250
+ this.assignLegacyConfigField(key, value);
2251
+ }
2252
+ }
2253
+ if (syncResult.ShouldUpdateConfiguration) {
2254
+ this.Configuration = syncResult.ConfigurationJson;
2255
+ }
2256
+ }
2257
+ assignLegacyConfigField(fieldName, value) {
2258
+ const target = this;
2259
+ target[fieldName] = value;
410
2260
  }
411
2261
  async loadTypeConfigSchema() {
412
2262
  if (!this.TypeID) {