@jini-ai/core 0.7.2 → 0.7.3-next.2

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 (343) hide show
  1. package/README.md +40 -12
  2. package/dist/admin-runtime/admin-api-error.d.ts +68 -0
  3. package/dist/admin-runtime/admin-api-error.js +72 -0
  4. package/dist/admin-runtime/admin-config-error.d.ts +8 -0
  5. package/dist/admin-runtime/admin-config-error.js +11 -0
  6. package/dist/admin-runtime/controller-store.d.ts +20 -0
  7. package/dist/admin-runtime/controller-store.js +32 -0
  8. package/dist/admin-runtime/index.d.ts +13 -0
  9. package/dist/admin-runtime/index.js +12 -0
  10. package/dist/admin-runtime/panel-access.d.ts +88 -0
  11. package/dist/admin-runtime/panel-access.js +76 -0
  12. package/dist/admin-runtime/query-suffix.d.ts +5 -0
  13. package/dist/admin-runtime/query-suffix.js +5 -0
  14. package/dist/agent-handles/element-handles.d.ts +134 -0
  15. package/dist/agent-handles/element-handles.js +45 -0
  16. package/dist/agent-handles/field-descriptor.d.ts +28 -0
  17. package/dist/agent-handles/field-descriptor.js +3 -0
  18. package/dist/agent-handles/handle.d.ts +109 -0
  19. package/dist/agent-handles/handle.js +109 -0
  20. package/dist/agent-handles/index.d.ts +9 -0
  21. package/dist/agent-handles/index.js +6 -0
  22. package/dist/agent-handles/list-handles.d.ts +46 -0
  23. package/dist/agent-handles/list-handles.js +67 -0
  24. package/dist/agent-handles/secret-attrs.d.ts +14 -0
  25. package/dist/agent-handles/secret-attrs.js +13 -0
  26. package/dist/approval-batch-chain.d.ts +45 -0
  27. package/dist/approval-batch-chain.js +75 -0
  28. package/dist/approval.d.ts +33 -14
  29. package/dist/approval.js +57 -43
  30. package/dist/batch-tool-inputs.js +24 -20
  31. package/dist/contracts/admin-module.d.ts +166 -0
  32. package/dist/contracts/admin-module.js +14 -0
  33. package/dist/contracts/agents/definition.d.ts +459 -0
  34. package/dist/contracts/agents/definition.js +2 -0
  35. package/dist/contracts/agents/index.d.ts +7 -0
  36. package/dist/contracts/agents/index.js +2 -0
  37. package/dist/contracts/agents/launch.d.ts +64 -0
  38. package/dist/contracts/agents/launch.js +2 -0
  39. package/dist/contracts/agents/model-catalog.d.ts +213 -0
  40. package/dist/contracts/agents/model-catalog.js +4 -0
  41. package/dist/contracts/agents/native-tool-policy.d.ts +42 -0
  42. package/dist/contracts/agents/native-tool-policy.js +2 -0
  43. package/dist/contracts/ai-trace/capture.d.ts +17 -0
  44. package/dist/contracts/ai-trace/capture.js +43 -0
  45. package/dist/contracts/ai-trace/classify.d.ts +12 -0
  46. package/dist/contracts/ai-trace/classify.js +16 -0
  47. package/dist/contracts/ai-trace/index.d.ts +13 -0
  48. package/dist/contracts/ai-trace/index.js +6 -0
  49. package/dist/contracts/ai-trace/recorder.d.ts +64 -0
  50. package/dist/contracts/ai-trace/recorder.js +283 -0
  51. package/dist/contracts/ai-trace/sinks.d.ts +51 -0
  52. package/dist/contracts/ai-trace/sinks.js +153 -0
  53. package/dist/contracts/ai-trace/types.d.ts +123 -0
  54. package/dist/contracts/ai-trace/types.js +17 -0
  55. package/dist/contracts/ai-trace/usage.d.ts +16 -0
  56. package/dist/contracts/ai-trace/usage.js +45 -0
  57. package/dist/contracts/blob.d.ts +31 -0
  58. package/dist/contracts/blob.js +10 -0
  59. package/dist/contracts/capabilities.d.ts +95 -0
  60. package/dist/contracts/capabilities.js +111 -0
  61. package/dist/contracts/charts.d.ts +75 -0
  62. package/dist/contracts/charts.js +4 -0
  63. package/dist/contracts/env.d.ts +96 -0
  64. package/dist/contracts/env.js +6 -0
  65. package/dist/contracts/events/change-set.d.ts +106 -0
  66. package/dist/contracts/events/change-set.js +2 -0
  67. package/dist/contracts/events/command.d.ts +118 -0
  68. package/dist/contracts/events/command.js +2 -0
  69. package/dist/contracts/events/ports.d.ts +172 -0
  70. package/dist/contracts/events/ports.js +2 -0
  71. package/dist/contracts/events.d.ts +5 -0
  72. package/dist/contracts/events.js +2 -0
  73. package/dist/contracts/forms.d.ts +110 -0
  74. package/dist/contracts/forms.js +4 -0
  75. package/dist/contracts/hosted-mcp/config.d.ts +19 -0
  76. package/dist/contracts/hosted-mcp/record.d.ts +61 -4
  77. package/dist/contracts/mail/email-sender.d.ts +118 -0
  78. package/dist/contracts/mail/email-sender.js +20 -0
  79. package/dist/contracts/mail/smtp-payload.d.ts +32 -0
  80. package/dist/contracts/mail/smtp-payload.js +2 -0
  81. package/dist/contracts/mail.d.ts +2 -0
  82. package/dist/contracts/mail.js +1 -1
  83. package/dist/contracts/observability.d.ts +235 -0
  84. package/dist/contracts/observability.js +28 -0
  85. package/dist/contracts/plugin-sdk.d.ts +186 -0
  86. package/dist/contracts/plugin-sdk.js +39 -0
  87. package/dist/contracts/runtime/command.d.ts +41 -0
  88. package/dist/contracts/runtime/command.js +60 -0
  89. package/dist/contracts/runtime/environment.d.ts +18 -0
  90. package/dist/contracts/runtime/environment.js +26 -0
  91. package/dist/contracts/runtime/file-lock.d.ts +94 -0
  92. package/dist/contracts/runtime/file-lock.js +25 -0
  93. package/dist/contracts/runtime/fs.d.ts +33 -0
  94. package/dist/contracts/runtime/fs.js +2 -0
  95. package/dist/contracts/runtime/http.d.ts +89 -0
  96. package/dist/contracts/runtime/http.js +2 -0
  97. package/dist/contracts/runtime/platform.d.ts +3 -0
  98. package/dist/contracts/runtime/platform.js +2 -0
  99. package/dist/contracts/runtime/process.d.ts +40 -0
  100. package/dist/contracts/runtime/process.js +31 -0
  101. package/dist/contracts/runtime/reader.d.ts +11 -0
  102. package/dist/contracts/runtime/reader.js +2 -0
  103. package/dist/contracts/runtime/terminal.d.ts +99 -0
  104. package/dist/contracts/runtime/terminal.js +2 -0
  105. package/dist/contracts/runtime/testing.d.ts +84 -0
  106. package/dist/contracts/runtime/testing.js +116 -0
  107. package/dist/contracts/runtime.d.ts +10 -0
  108. package/dist/contracts/runtime.js +10 -0
  109. package/dist/contracts/server/api-error.d.ts +43 -0
  110. package/dist/contracts/server/api-error.js +49 -0
  111. package/dist/contracts/server/auth.d.ts +20 -0
  112. package/dist/contracts/server/auth.js +21 -0
  113. package/dist/contracts/server/conformance.d.ts +25 -0
  114. package/dist/contracts/server/conformance.js +50 -0
  115. package/dist/contracts/server/json-route.d.ts +176 -0
  116. package/dist/contracts/server/json-route.js +155 -0
  117. package/dist/contracts/server/middleware.d.ts +35 -0
  118. package/dist/contracts/server/middleware.js +56 -0
  119. package/dist/contracts/server/origin.d.ts +44 -0
  120. package/dist/contracts/server/origin.js +32 -0
  121. package/dist/contracts/server/query.d.ts +16 -0
  122. package/dist/contracts/server/query.js +69 -0
  123. package/dist/contracts/server/rate-limit.d.ts +20 -0
  124. package/dist/contracts/server/rate-limit.js +8 -0
  125. package/dist/contracts/server/request-body.d.ts +26 -0
  126. package/dist/contracts/server/request-body.js +82 -0
  127. package/dist/contracts/server/result.d.ts +17 -0
  128. package/dist/contracts/server/result.js +5 -0
  129. package/dist/contracts/server/route-table.d.ts +54 -0
  130. package/dist/contracts/server/route-table.js +119 -0
  131. package/dist/contracts/server/same-origin-write.d.ts +18 -0
  132. package/dist/contracts/server/same-origin-write.js +31 -0
  133. package/dist/contracts/server/security-headers.d.ts +30 -0
  134. package/dist/contracts/server/security-headers.js +35 -0
  135. package/dist/contracts/server/sse.d.ts +82 -0
  136. package/dist/contracts/server/sse.js +103 -0
  137. package/dist/contracts/server/testing.d.ts +59 -0
  138. package/dist/contracts/server/testing.js +68 -0
  139. package/dist/contracts/server/verified-origin/configured-origin.d.ts +37 -0
  140. package/dist/contracts/server/verified-origin/configured-origin.js +103 -0
  141. package/dist/contracts/server/verified-origin/index.d.ts +7 -0
  142. package/dist/contracts/server/verified-origin/index.js +6 -0
  143. package/dist/contracts/server/verified-origin/loopback-host.d.ts +9 -0
  144. package/dist/contracts/server/verified-origin/loopback-host.js +17 -0
  145. package/dist/contracts/server/verified-origin/origin.d.ts +64 -0
  146. package/dist/contracts/server/verified-origin/origin.js +162 -0
  147. package/dist/contracts/server/verified-origin/ports.d.ts +38 -0
  148. package/dist/contracts/server/verified-origin/ports.js +2 -0
  149. package/dist/contracts/server/verified-origin/repo.memory.d.ts +32 -0
  150. package/dist/contracts/server/verified-origin/repo.memory.js +34 -0
  151. package/dist/contracts/server/verified-origin/site-path.d.ts +113 -0
  152. package/dist/contracts/server/verified-origin/site-path.js +188 -0
  153. package/dist/contracts/server/verified-origin/types.d.ts +33 -0
  154. package/dist/contracts/server/verified-origin/types.js +30 -0
  155. package/dist/contracts/server.d.ts +46 -2
  156. package/dist/contracts/server.js +17 -3
  157. package/dist/contracts/storage/kernel.d.ts +86 -0
  158. package/dist/contracts/storage/kernel.js +38 -0
  159. package/dist/contracts/storage/migration.d.ts +32 -0
  160. package/dist/contracts/storage/migration.js +2 -0
  161. package/dist/contracts/storage/rows.d.ts +33 -0
  162. package/dist/contracts/storage/rows.js +42 -0
  163. package/dist/contracts/storage/sqlite.d.ts +113 -0
  164. package/dist/contracts/storage/sqlite.js +8 -0
  165. package/dist/contracts/storage/values.d.ts +25 -0
  166. package/dist/contracts/storage/values.js +25 -0
  167. package/dist/contracts/storage.d.ts +8 -0
  168. package/dist/contracts/storage.js +6 -0
  169. package/dist/contracts/vault/invariants.d.ts +26 -0
  170. package/dist/contracts/vault/invariants.js +49 -0
  171. package/dist/contracts/vault.d.ts +1 -0
  172. package/dist/contracts/vault.js +1 -1
  173. package/dist/env/coercers.d.ts +21 -0
  174. package/dist/env/coercers.js +68 -0
  175. package/dist/env/describe-env-for-diagnostics.d.ts +16 -0
  176. package/dist/env/describe-env-for-diagnostics.js +23 -0
  177. package/dist/env/format-env-issue.d.ts +13 -0
  178. package/dist/env/format-env-issue.js +22 -0
  179. package/dist/env/parse-env.d.ts +24 -0
  180. package/dist/env/parse-env.js +102 -0
  181. package/dist/env/value-echo.d.ts +17 -0
  182. package/dist/env/value-echo.js +42 -0
  183. package/dist/errors/approved-cause.d.ts +36 -0
  184. package/dist/errors/approved-cause.js +17 -0
  185. package/dist/errors/bindings.d.ts +61 -0
  186. package/dist/errors/bindings.js +57 -0
  187. package/dist/errors/catalog.d.ts +84 -0
  188. package/dist/errors/catalog.js +151 -0
  189. package/dist/errors/disclosure.d.ts +48 -0
  190. package/dist/errors/disclosure.js +27 -0
  191. package/dist/errors/error-id.d.ts +26 -0
  192. package/dist/errors/error-id.js +23 -0
  193. package/dist/errors/idioms.d.ts +73 -0
  194. package/dist/errors/idioms.js +85 -0
  195. package/dist/errors/incident-text.d.ts +16 -0
  196. package/dist/errors/incident-text.js +77 -0
  197. package/dist/errors/reporter.d.ts +94 -0
  198. package/dist/errors/reporter.js +152 -0
  199. package/dist/errors/sentences.d.ts +68 -0
  200. package/dist/errors/sentences.js +93 -0
  201. package/dist/errors/testing.d.ts +50 -0
  202. package/dist/errors/testing.js +44 -0
  203. package/dist/fetch/cache.d.ts +12 -5
  204. package/dist/fetch/cache.js +46 -47
  205. package/dist/fetch/index.d.ts +1 -1
  206. package/dist/fetch/loader-read.d.ts +6 -2
  207. package/dist/fetch/loader-read.js +4 -4
  208. package/dist/format-error-for-log.d.ts +15 -0
  209. package/dist/format-error-for-log.js +55 -0
  210. package/dist/gated-mutations/gateway.d.ts +2 -0
  211. package/dist/gated-mutations/gateway.js +4 -1
  212. package/dist/host-read-vocabulary.d.ts +47 -0
  213. package/dist/host-read-vocabulary.js +44 -0
  214. package/dist/index.d.ts +5 -1
  215. package/dist/index.js +4 -0
  216. package/dist/list-page.d.ts +93 -0
  217. package/dist/list-page.js +154 -0
  218. package/dist/model-facing-tool-errors.d.ts +67 -5
  219. package/dist/model-facing-tool-errors.js +155 -19
  220. package/dist/net/endpoint-policy.d.ts +39 -0
  221. package/dist/net/endpoint-policy.js +218 -0
  222. package/dist/net/fetch-timeouts.d.ts +38 -0
  223. package/dist/net/fetch-timeouts.js +31 -0
  224. package/dist/net/index.d.ts +4 -0
  225. package/dist/net/index.js +4 -0
  226. package/dist/net/loopback.d.ts +13 -0
  227. package/dist/net/loopback.js +39 -0
  228. package/dist/optimistic-concurrency.d.ts +183 -0
  229. package/dist/optimistic-concurrency.js +222 -0
  230. package/dist/primitives/errors.d.ts +9 -0
  231. package/dist/primitives/errors.js +12 -0
  232. package/dist/primitives/ids.d.ts +0 -2
  233. package/dist/primitives/ids.js +1 -4
  234. package/dist/primitives/index.d.ts +3 -0
  235. package/dist/primitives/index.js +2 -0
  236. package/dist/primitives/logger.d.ts +36 -1
  237. package/dist/primitives/logger.js +125 -9
  238. package/dist/primitives/node-shape.d.ts +24 -0
  239. package/dist/primitives/node-shape.js +21 -0
  240. package/dist/primitives/time.d.ts +9 -2
  241. package/dist/primitives/time.js +4 -3
  242. package/dist/provider-registry.js +26 -20
  243. package/dist/records.d.ts +40 -7
  244. package/dist/records.js +37 -3
  245. package/dist/redact.d.ts +1 -84
  246. package/dist/redact.js +2 -826
  247. package/dist/redaction-collectors.d.ts +7 -0
  248. package/dist/redaction-collectors.js +152 -0
  249. package/dist/redaction-exact-secrets.d.ts +14 -0
  250. package/dist/redaction-exact-secrets.js +115 -0
  251. package/dist/redaction-labels.d.ts +14 -0
  252. package/dist/redaction-labels.js +156 -0
  253. package/dist/redaction-patterns.d.ts +54 -0
  254. package/dist/redaction-patterns.js +178 -0
  255. package/dist/redaction-spans.d.ts +31 -0
  256. package/dist/redaction-spans.js +83 -0
  257. package/dist/registration-kit.d.ts +1 -1
  258. package/dist/revision-conflict-error.d.ts +18 -0
  259. package/dist/revision-conflict-error.js +20 -0
  260. package/dist/secret-shapes.d.ts +50 -0
  261. package/dist/secret-shapes.js +105 -0
  262. package/dist/settings/agent-tools.js +22 -8
  263. package/dist/settings/agent-value-write-tools.d.ts +4 -1
  264. package/dist/settings/agent-value-write-tools.js +7 -6
  265. package/dist/settings/agent-writable-preferences.d.ts +3 -1
  266. package/dist/settings/agent-writable-preferences.js +1 -1
  267. package/dist/settings/agent-write-denylist.d.ts +7 -4
  268. package/dist/settings/agent-write-denylist.js +1 -1
  269. package/dist/settings/{express/cms-adapter.d.ts → cms-adapter.d.ts} +3 -2
  270. package/dist/settings/{express/cms-adapter.js → cms-adapter.js} +21 -11
  271. package/dist/settings/definitions-dispatch.js +3 -1
  272. package/dist/settings/ensure-definitions.js +3 -1
  273. package/dist/settings/errors.d.ts +1 -13
  274. package/dist/settings/errors.js +2 -15
  275. package/dist/settings/index.d.ts +11 -2
  276. package/dist/settings/index.js +10 -2
  277. package/dist/settings/purge-service.js +63 -86
  278. package/dist/settings/{express/contracts.d.ts → route-policy.d.ts} +53 -47
  279. package/dist/settings/{express/shared.js → route-policy.js} +1 -16
  280. package/dist/settings/settings.d.ts +19 -11
  281. package/dist/settings/settings.js +9 -11
  282. package/dist/settings/tool-registrations.d.ts +3 -3
  283. package/dist/settings/tool-registrations.js +130 -125
  284. package/dist/settings/types.d.ts +1 -1
  285. package/dist/settings/write-definition-rename.d.ts +37 -0
  286. package/dist/settings/write-definition-rename.js +119 -0
  287. package/dist/settings/write-definition-retype.d.ts +61 -0
  288. package/dist/settings/write-definition-retype.js +109 -0
  289. package/dist/settings/write-definition-status.d.ts +81 -0
  290. package/dist/settings/write-definition-status.js +121 -0
  291. package/dist/settings/write-reset.d.ts +34 -0
  292. package/dist/settings/write-reset.js +73 -0
  293. package/dist/settings/write-service.d.ts +16 -287
  294. package/dist/settings/write-service.js +49 -681
  295. package/dist/settings/write-value-revisions.d.ts +68 -0
  296. package/dist/settings/write-value-revisions.js +124 -0
  297. package/dist/settings/write-values.d.ts +96 -0
  298. package/dist/settings/write-values.js +83 -0
  299. package/dist/surface-exchanges.d.ts +2 -2
  300. package/dist/text/dictionary-translator.d.ts +19 -0
  301. package/dist/text/dictionary-translator.js +14 -0
  302. package/dist/text/format-byte-size.d.ts +25 -0
  303. package/dist/text/format-byte-size.js +25 -0
  304. package/dist/text/format-timestamp.d.ts +22 -0
  305. package/dist/text/format-timestamp.js +57 -0
  306. package/dist/text/index.d.ts +12 -0
  307. package/dist/text/index.js +9 -0
  308. package/dist/text/is-abort-error.d.ts +5 -0
  309. package/dist/text/is-abort-error.js +5 -0
  310. package/dist/text/mime.d.ts +5 -0
  311. package/dist/text/mime.js +21 -0
  312. package/dist/text/redact-urls.d.ts +7 -0
  313. package/dist/text/redact-urls.js +5 -0
  314. package/dist/text/resolve-active-tab-id.d.ts +13 -0
  315. package/dist/text/resolve-active-tab-id.js +15 -0
  316. package/dist/text/sanitize-untrusted-text.d.ts +1 -1
  317. package/dist/text/sanitize-untrusted-text.js +2 -1
  318. package/dist/text/tagged-text-suppression.d.ts +103 -0
  319. package/dist/text/tagged-text-suppression.js +143 -0
  320. package/dist/text/template-i18n.d.ts +37 -0
  321. package/dist/text/template-i18n.js +48 -0
  322. package/dist/tool-call-text.d.ts +59 -0
  323. package/dist/tool-call-text.js +62 -0
  324. package/dist/tool-input-envelope.js +8 -4
  325. package/dist/tool-input-normalization.js +8 -1
  326. package/dist/tool-input-repairs.d.ts +58 -0
  327. package/dist/tool-input-repairs.js +154 -0
  328. package/dist/tool-tokens.js +1 -1
  329. package/dist/user-facing-error.d.ts +1 -1
  330. package/dist/user-facing-error.js +3 -1
  331. package/package.json +235 -14
  332. package/plugin-directory.d.ts +2 -2
  333. package/plugin-directory.js +16 -10
  334. package/dist/settings/express/contracts.js +0 -2
  335. package/dist/settings/express/http-request.d.ts +0 -33
  336. package/dist/settings/express/http-request.js +0 -50
  337. package/dist/settings/express/http.d.ts +0 -10
  338. package/dist/settings/express/http.js +0 -196
  339. package/dist/settings/express/index.d.ts +0 -5
  340. package/dist/settings/express/index.js +0 -4
  341. package/dist/settings/express/shared.d.ts +0 -68
  342. package/dist/settings/express/stream.d.ts +0 -24
  343. package/dist/settings/express/stream.js +0 -171
@@ -1,7 +1,7 @@
1
1
  import { nowIso as kernelNowIso } from "../primitives/index.js";
2
- import { AliasDepthExceededError, DefinitionInvalidError, DefinitionNotFoundError, DefinitionTombstonedError, ForbiddenError, PrincipalNotFoundError, RenameRetypeConflictError, ScopeNotAllowedError, SettingsRevisionConflictError, ValueValidationFailedError, } from "./errors.js";
3
- import { invalidateDefinitionNamespaceCache, resolveDefinitionRaw, validateDefinitionInput, validateValueAgainstSchema, } from "./settings.js";
4
- import { SCOPE_BIT } from "./types.js";
2
+ import { DefinitionInvalidError, DefinitionNotFoundError, DefinitionTombstonedError, ForbiddenError } from "./errors.js";
3
+ import { invalidateDefinitionNamespaceCache, validateDefinitionInput } from "./settings.js";
4
+ import {} from "./types.js";
5
5
  /**
6
6
  * behavior.spec.md §1.3 / `[internal-invariant]` — the self-vs-other
7
7
  * permission derivation. `targetPrincipalId` omitted or equal to the caller
@@ -22,6 +22,48 @@ export function deriveRequiredPermission(input) {
22
22
  const isSelf = input.targetPrincipalId == null || input.targetPrincipalId === input.callerPrincipalId;
23
23
  return isSelf ? "settings.user.self.write" : "settings.user.write";
24
24
  }
25
+ /** One definition, one transaction: the row and its `register` revision commit together. Returns the new setting id. */
26
+ async function saveRegisteredDefinition({ deps, definitionInput, callerPrincipalId }) {
27
+ return deps.repo.transaction(async () => {
28
+ const now = kernelNowIso({ clock: deps.clock });
29
+ const settingId = deps.ids.newId();
30
+ await deps.repo.saveDefinition({
31
+ settingId,
32
+ version: 1,
33
+ workspaceId: definitionInput.workspaceId,
34
+ namespace: definitionInput.namespace,
35
+ key: definitionInput.key,
36
+ ownerKind: definitionInput.ownerKind,
37
+ ownerId: definitionInput.ownerId ?? null,
38
+ schema: definitionInput.schema,
39
+ defaultValue: definitionInput.defaultValue,
40
+ scopes: definitionInput.scopes,
41
+ secret: false,
42
+ status: "active",
43
+ aliasOfNamespace: null,
44
+ aliasOfKey: null,
45
+ coercionTag: null,
46
+ createdAt: now,
47
+ updatedAt: now,
48
+ });
49
+ await deps.repo.appendRevision({
50
+ entityKind: "definition",
51
+ settingId,
52
+ scope: null,
53
+ workspaceId: definitionInput.workspaceId,
54
+ principalId: null,
55
+ op: "register",
56
+ beforeJson: null,
57
+ afterJson: null,
58
+ defVersion: 1,
59
+ actor: callerPrincipalId,
60
+ originPluginId: null,
61
+ changeSetId: null,
62
+ createdAt: now,
63
+ });
64
+ return settingId;
65
+ });
66
+ }
25
67
  /** chokepoint write: authorize `settings.definitions.manage` -> validate -> write + revision, one per definition, each its own tx. See docs/decisions/DR-003-settings-ledger-invariants.md. */
26
68
  export async function registerDefinitions(required) {
27
69
  const { deps, input } = required;
@@ -39,373 +81,18 @@ export async function registerDefinitions(required) {
39
81
  const validation = validateDefinitionInput(definitionInput);
40
82
  if (!validation.valid)
41
83
  throw validation.error;
42
- await deps.repo.transaction(async () => {
43
- const now = kernelNowIso({ clock: deps.clock });
44
- const settingId = deps.ids.newId();
45
- await deps.repo.saveDefinition({
46
- settingId,
47
- version: 1,
48
- workspaceId: definitionInput.workspaceId,
49
- namespace: definitionInput.namespace,
50
- key: definitionInput.key,
51
- ownerKind: definitionInput.ownerKind,
52
- ownerId: definitionInput.ownerId ?? null,
53
- schema: definitionInput.schema,
54
- defaultValue: definitionInput.defaultValue,
55
- scopes: definitionInput.scopes,
56
- secret: false,
57
- status: "active",
58
- aliasOfNamespace: null,
59
- aliasOfKey: null,
60
- coercionTag: null,
61
- createdAt: now,
62
- updatedAt: now,
63
- });
64
- await deps.repo.appendRevision({
65
- entityKind: "definition",
66
- settingId,
67
- scope: null,
68
- workspaceId: definitionInput.workspaceId,
69
- principalId: null,
70
- op: "register",
71
- beforeJson: null,
72
- afterJson: null,
73
- defVersion: 1,
74
- actor: input.callerPrincipalId,
75
- originPluginId: null,
76
- changeSetId: null,
77
- createdAt: now,
78
- });
79
- registered.push(settingId);
80
- });
81
- invalidateDefinitionNamespaceCache(deps.repo, definitionInput.namespace);
84
+ registered.push(await saveRegisteredDefinition({ deps, definitionInput, callerPrincipalId: input.callerPrincipalId }));
85
+ invalidateDefinitionNamespaceCache({ repo: deps.repo, namespace: definitionInput.namespace });
82
86
  }
83
87
  return { registered };
84
88
  }
85
- async function resolveScopedDefinitionOrThrow(deps, input) {
86
- const definitionWorkspaceId = input.scope === "global" ? null : (input.workspaceId ?? null);
87
- const definition = await resolveDefinitionRaw(deps, {
88
- namespace: input.namespace,
89
- key: input.key,
90
- workspaceId: definitionWorkspaceId,
91
- });
92
- if (!definition) {
93
- throw new DefinitionNotFoundError(`setting '${input.namespace}.${input.key}' was not found`);
94
- }
95
- if (definition.status === "tombstone") {
96
- throw new DefinitionTombstonedError(`setting '${input.namespace}.${input.key}' has been tombstoned`);
97
- }
98
- if ((definition.scopes & SCOPE_BIT[input.scope]) === 0) {
99
- throw new ScopeNotAllowedError(`setting '${input.namespace}.${input.key}' does not allow scope '${input.scope}'`);
100
- }
101
- return definition;
102
- }
103
- /**
104
- * Every non-global write must land in the workspace it was AUTHORIZED against.
105
- *
106
- * `authorize()` is called with `authWorkspaceId` while the value row and revision are written with
107
- * `input.workspaceId`. Nothing forces the two to match unless this guard runs — a caller that
108
- * constructs the input directly (rather than through a route that validates the body against the
109
- * ambient workspace) could otherwise pass a mismatched target and have the write land in a
110
- * workspace neither `authorize()` call was actually evaluated against.
111
- *
112
- * A host's HTTP routes should reject a mismatched body id at the route layer (the real fix, closer
113
- * to the request). This is the backstop: it holds for every internal caller that constructs the
114
- * input directly, and makes a future caller incapable of reintroducing the gap.
115
- *
116
- * `ForbiddenError` rather than a validation error because the condition is exactly "you are not
117
- * authorized to write to that workspace".
118
- *
119
- * `scope: "global"` is exempt: the platform partition has no workspace, and `set`/`clear` already
120
- * force `workspaceId: null` on that path.
121
- */
122
- function assertTargetWorkspaceMatchesAuth(input) {
123
- if (input.scope === "global")
124
- return;
125
- if (input.workspaceId === undefined)
126
- return;
127
- if (input.workspaceId === input.authWorkspaceId)
128
- return;
129
- throw new ForbiddenError(`principal '${input.callerPrincipalId}' authorized against workspace '${input.authWorkspaceId}' ` +
130
- `but the write targets workspace '${input.workspaceId}'`);
131
- }
132
- /**
133
- * — for scope=user writes targeting another principal, verify
134
- * that principal resolves to an active user whose own `workspace_id` equals
135
- * the request's `workspaceId` (structural scoping — a principal
136
- * belongs to exactly one workspace, not a membership join).
137
- * See docs/decisions/DR-003-settings-ledger-invariants.md.
138
- */
139
- async function assertTargetPrincipalInWorkspace(deps, input) {
140
- if (input.scope !== "user")
141
- return;
142
- if (!input.principalId || input.principalId === input.callerPrincipalId)
143
- return;
144
- if (!input.workspaceId)
145
- return;
146
- const principal = await deps.principals.findActiveById({ workspaceId: input.workspaceId, id: input.principalId });
147
- if (!principal) {
148
- throw new PrincipalNotFoundError(`principal '${input.principalId}' was not found in workspace '${input.workspaceId}'`, input.principalId, input.workspaceId);
149
- }
150
- }
151
- /**
152
- * Check the addressed value after appendRevision has taken the ledger lock. On Postgres, a read
153
- * before that lock can see the same old seq in two READ COMMITTED transactions and lose an update.
154
- * The caller's enclosing transaction rolls the appended revision back on conflict.
155
- * @complexity At most one scoped value read; no reads when the option is omitted.
156
- */
157
- /** The one stored value the write addresses, at its own scope. */
158
- function readAddressedValue({ repo, settingId, input }) {
159
- if (input.scope === "global")
160
- return repo.getGlobalValue(settingId);
161
- if (input.scope === "workspace")
162
- return repo.getWorkspaceValue({ workspaceId: input.workspaceId, settingId });
163
- return repo.getUserValue({ workspaceId: input.workspaceId, principalId: input.principalId ?? input.callerPrincipalId, settingId });
164
- }
165
- async function assertExpectedRevision(required, optional = {}) {
166
- if (optional.expectedRevisionSeq === undefined)
167
- return;
168
- const { repo, settingId, input } = required;
169
- const current = await readAddressedValue({ repo, settingId, input });
170
- const actualRevisionSeq = current?.seq ?? 0;
171
- if (actualRevisionSeq !== optional.expectedRevisionSeq) {
172
- throw new SettingsRevisionConflictError({ expectedRevisionSeq: optional.expectedRevisionSeq, actualRevisionSeq });
173
- }
174
- }
175
- /**
176
- * Authorize -> validate -> value + revision in one transaction. An optional expectedRevisionSeq
177
- * refuses a stale scoped value and rolls back its revision; omission keeps unconditional writes.
178
- * @example await set({ deps, input }, { expectedRevisionSeq: snapshotSeq });
179
- * See docs/decisions/DR-003-settings-ledger-invariants.md.
180
- */
181
- export async function set(required, optional = {}) {
182
- const { deps, input } = required;
183
- const permission = input.requiredPermissionOverride ??
184
- deriveRequiredPermission({
185
- scope: input.scope,
186
- targetPrincipalId: input.principalId,
187
- callerPrincipalId: input.callerPrincipalId,
188
- });
189
- const authWorkspaceId = input.authWorkspaceId ?? input.workspaceId ?? input.callerPrincipalId;
190
- assertTargetWorkspaceMatchesAuth({ ...input, authWorkspaceId });
191
- const authResult = await deps.authorize({
192
- principalId: input.callerPrincipalId,
193
- permission,
194
- workspaceId: authWorkspaceId,
195
- entityType: "setting-value",
196
- });
197
- if (!authResult.allowed) {
198
- throw new ForbiddenError(`principal '${input.callerPrincipalId}' is not authorized for '${permission}' (${authResult.reason})`);
199
- }
200
- const definition = await resolveScopedDefinitionOrThrow(deps, input);
201
- if (!validateValueAgainstSchema(definition.schema, input.value)) {
202
- throw new ValueValidationFailedError(`value for '${input.namespace}.${input.key}' does not match the definition schema`);
203
- }
204
- await assertTargetPrincipalInWorkspace(deps, input);
205
- return deps.repo.transaction(async () => {
206
- const now = kernelNowIso({ clock: deps.clock });
207
- const revisionSeq = await deps.repo.appendRevision({
208
- entityKind: "value",
209
- settingId: definition.settingId,
210
- scope: input.scope,
211
- workspaceId: input.scope === "global" ? null : (input.workspaceId ?? null),
212
- principalId: input.scope === "user" ? (input.principalId ?? input.callerPrincipalId) : null,
213
- op: "set",
214
- beforeJson: null,
215
- afterJson: input.value,
216
- defVersion: definition.version,
217
- actor: input.callerPrincipalId,
218
- originPluginId: null,
219
- changeSetId: null,
220
- createdAt: now,
221
- });
222
- await assertExpectedRevision({ repo: deps.repo, settingId: definition.settingId, input }, optional);
223
- const base = {
224
- settingId: definition.settingId,
225
- scope: input.scope,
226
- valueJson: input.value,
227
- state: "set",
228
- defVersion: definition.version,
229
- seq: revisionSeq,
230
- updatedBy: input.callerPrincipalId,
231
- updatedAt: now,
232
- originPluginId: null,
233
- };
234
- if (input.scope === "global") {
235
- await deps.repo.saveGlobalValue({ ...base, workspaceId: null, principalId: null });
236
- }
237
- else if (input.scope === "workspace") {
238
- await deps.repo.saveWorkspaceValue({
239
- ...base,
240
- workspaceId: input.workspaceId ?? null,
241
- principalId: null,
242
- });
243
- }
244
- else {
245
- await deps.repo.saveUserValue({
246
- ...base,
247
- workspaceId: input.workspaceId ?? null,
248
- principalId: input.principalId ?? input.callerPrincipalId,
249
- });
250
- }
251
- return { value: input.value, revisionSeq };
252
- });
253
- }
254
- /**
255
- * Authorize -> cleared value + revision in one transaction; the optional concurrency guard has
256
- * the same semantics as `set`. With skipTransaction, the enclosing caller must propagate errors
257
- * so its transaction rolls back the appended revision on conflict.
258
- * @example await clear({ deps, input }, { expectedRevisionSeq: snapshotSeq });
259
- * See docs/decisions/DR-003-settings-ledger-invariants.md.
260
- */
261
- export async function clear(required, optional = {}) {
262
- const { deps, input } = required;
263
- if (!input.skipAuthorize) {
264
- const permission = deriveRequiredPermission({
265
- scope: input.scope,
266
- targetPrincipalId: input.principalId,
267
- callerPrincipalId: input.callerPrincipalId,
268
- });
269
- const authWorkspaceId = input.authWorkspaceId ?? input.workspaceId ?? input.callerPrincipalId;
270
- assertTargetWorkspaceMatchesAuth({ ...input, authWorkspaceId });
271
- const authResult = await deps.authorize({
272
- principalId: input.callerPrincipalId,
273
- permission,
274
- workspaceId: authWorkspaceId,
275
- entityType: "setting-value",
276
- });
277
- if (!authResult.allowed) {
278
- throw new ForbiddenError(`principal '${input.callerPrincipalId}' is not authorized for '${permission}' (${authResult.reason})`);
279
- }
280
- }
281
- const definition = await resolveScopedDefinitionOrThrow(deps, input);
282
- await assertTargetPrincipalInWorkspace(deps, input);
283
- const runClear = async () => {
284
- const now = kernelNowIso({ clock: deps.clock });
285
- const revisionSeq = await deps.repo.appendRevision({
286
- entityKind: "value",
287
- settingId: definition.settingId,
288
- scope: input.scope,
289
- workspaceId: input.scope === "global" ? null : (input.workspaceId ?? null),
290
- principalId: input.scope === "user" ? (input.principalId ?? input.callerPrincipalId) : null,
291
- op: "clear",
292
- beforeJson: null,
293
- afterJson: null,
294
- defVersion: definition.version,
295
- actor: input.callerPrincipalId,
296
- originPluginId: null,
297
- changeSetId: null,
298
- createdAt: now,
299
- });
300
- await assertExpectedRevision({ repo: deps.repo, settingId: definition.settingId, input }, optional);
301
- const base = {
302
- settingId: definition.settingId,
303
- scope: input.scope,
304
- valueJson: null,
305
- state: "cleared",
306
- defVersion: definition.version,
307
- seq: revisionSeq,
308
- updatedBy: input.callerPrincipalId,
309
- updatedAt: now,
310
- originPluginId: null,
311
- };
312
- if (input.scope === "global") {
313
- await deps.repo.saveGlobalValue({ ...base, workspaceId: null, principalId: null });
314
- }
315
- else if (input.scope === "workspace") {
316
- await deps.repo.saveWorkspaceValue({
317
- ...base,
318
- workspaceId: input.workspaceId ?? null,
319
- principalId: null,
320
- });
321
- }
322
- else {
323
- await deps.repo.saveUserValue({
324
- ...base,
325
- workspaceId: input.workspaceId ?? null,
326
- principalId: input.principalId ?? input.callerPrincipalId,
327
- });
328
- }
329
- return { revisionSeq };
330
- };
331
- // `skipTransaction` means an enclosing caller already owns the boundary, so
332
- // this write joins it and a later failure rolls this one back too.
333
- return input.skipTransaction ? runClear() : deps.repo.transaction(runClear);
334
- }
335
- /**
336
- * — an explicit, human-invoked orchestrator: authorize
337
- * the matching `settings.reset.*` permission once, then loop `clear` for
338
- * every setting in the namespace in the reset-authorized internal context
339
- * (`skipAuthorize: true`) — the outer reset permission is sufficient on its
340
- * own; each inner clear still emits its own `op='clear'` revision.
341
- *
342
- * `revisionSeqs` collects each inner `clear` call's own `revisionSeq` so a
343
- * host's admin HTTP route can surface the full contract without a second
344
- * read. Existing callers that only read `.clearedCount` are unaffected.
345
- * See docs/decisions/DR-003-settings-ledger-invariants.md.
346
- */
347
- export async function resetNamespace(required, keysInNamespace) {
348
- const { deps, input } = required;
349
- const resetPermission = `settings.reset.${input.scope}`;
350
- const authWorkspaceId = input.authWorkspaceId ?? input.workspaceId ?? input.callerPrincipalId;
351
- // Asserted once here rather than per inner `clear()`: those run with `skipAuthorize: true`, which
352
- // short-circuits the same check inside `clear()`. This is the only gate for the whole loop.
353
- assertTargetWorkspaceMatchesAuth({ ...input, authWorkspaceId });
354
- const authResult = await deps.authorize({
355
- principalId: input.callerPrincipalId,
356
- permission: resetPermission,
357
- workspaceId: authWorkspaceId,
358
- entityType: "setting-namespace",
359
- });
360
- if (!authResult.allowed) {
361
- throw new ForbiddenError(`principal '${input.callerPrincipalId}' is not authorized for '${resetPermission}' (${authResult.reason})`);
362
- }
363
- // One transaction around the whole loop, so a reset is all-or-nothing.
364
- //
365
- // Each `clear()` opens its own transaction and commits on its own, so a
366
- // failure partway through used to leave the namespace HALF reset — some keys
367
- // durably cleared, the rest untouched — while the caller received an error and
368
- // could reasonably assume nothing had happened. "Reset this namespace" is not
369
- // a meaningful operation if it can apply to an arbitrary prefix of the keys.
370
- //
371
- // This works because each inner `clear()` is passed `skipTransaction: true`
372
- // and so writes into THIS frame instead of opening its own. That is explicit
373
- // at the call site by design: an earlier version made `transaction` reentrant
374
- // via an instance-level depth counter, which could not tell a genuine nested
375
- // call from an unrelated concurrent one and silently merged the two.
376
- //
377
- // Both adapters honour the rollback: a SQLite adapter via ROLLBACK, and
378
- // `repo.memory.ts` via a snapshot/restore journal.
379
- return deps.repo.transaction(async () => {
380
- let clearedCount = 0;
381
- const revisionSeqs = [];
382
- for (const key of keysInNamespace) {
383
- const result = await clear({
384
- deps,
385
- input: {
386
- namespace: input.namespace,
387
- key,
388
- scope: input.scope,
389
- workspaceId: input.workspaceId,
390
- principalId: input.principalId,
391
- callerPrincipalId: input.callerPrincipalId,
392
- skipAuthorize: true,
393
- skipTransaction: true,
394
- },
395
- });
396
- revisionSeqs.push(result.revisionSeq);
397
- clearedCount++;
398
- }
399
- return { clearedCount, revisionSeqs };
400
- });
401
- }
402
89
  /**
403
90
  * The single authorization gate shared by every definition-
404
91
  * lifecycle op (rename/retype/deprecate/tombstone), matching
405
92
  * `registerDefinitions`'s own `settings.definitions.manage` check (same
406
93
  * permission also gates `purge`/`coerce` per §7 — high privilege, human-only).
407
94
  */
408
- async function authorizeDefinitionsManage(deps, callerPrincipalId, authWorkspaceId) {
95
+ export async function authorizeDefinitionsManage(deps, callerPrincipalId, authWorkspaceId) {
409
96
  const authResult = await deps.authorize({
410
97
  principalId: callerPrincipalId,
411
98
  permission: "settings.definitions.manage",
@@ -417,7 +104,7 @@ async function authorizeDefinitionsManage(deps, callerPrincipalId, authWorkspace
417
104
  }
418
105
  }
419
106
  /** Resolves the canonical active definition at (namespace,key,workspaceId), rejecting anything but `status='active'`. */
420
- async function resolveActiveDefinitionOrThrow(deps, input, verb) {
107
+ export async function resolveActiveDefinitionOrThrow(deps, input, verb) {
421
108
  const current = await deps.repo.findActiveDefinition(input);
422
109
  if (!current) {
423
110
  throw new DefinitionNotFoundError(`setting '${input.namespace}.${input.key}' was not found`);
@@ -430,323 +117,4 @@ async function resolveActiveDefinitionOrThrow(deps, input, verb) {
430
117
  }
431
118
  return current;
432
119
  }
433
- /**
434
- * The rename mechanism : a same-tx pair —
435
- * (1) UPDATE the active definition row's `(namespace,key)` to the new name,
436
- * same `setting_id`/`version` (ledgered `op='alias'`); (2) INSERT a fresh v1
437
- * alias marker at the OLD name pointing at the new name. Because identity
438
- * never moves, value rows (keyed on `setting_id` only) stay attached.
439
- *
440
- * Sequential rename (A->B then B->C) retargets every prior marker pointing
441
- * at the OLD name to the NEW name in the same tx. A rename target that
442
- * itself resolves to an existing alias is rejected `ALIAS_DEPTH_EXCEEDED`
443
- * (behavior.spec.md §7: "the rename target resolves to an alias").
444
- *
445
- * Never touches `schema`/`defaultValue`/`scopes` -- a pure rename can never
446
- * trigger `RENAME_RETYPE_CONFLICT` by construction; that guard lives in
447
- * `retypeDefinition` ("no rename+retype in one op").
448
- * See docs/decisions/DR-003-settings-ledger-invariants.md.
449
- */
450
- export async function renameDefinition(required) {
451
- const { deps, input } = required;
452
- await authorizeDefinitionsManage(deps, input.callerPrincipalId, input.authWorkspaceId);
453
- const current = await resolveActiveDefinitionOrThrow(deps, input, "rename");
454
- // A dispatched `rename` item that omits its target arrives here as `""` (see definitions-dispatch);
455
- // without this guard the definition was silently moved to the empty name `.`.
456
- if (!input.newNamespace || !input.newKey) {
457
- throw new DefinitionInvalidError("rename requires a non-empty newNamespace and newKey");
458
- }
459
- if (input.namespace === input.newNamespace && input.key === input.newKey) {
460
- throw new DefinitionInvalidError("rename requires newNamespace/newKey to differ from the current name");
461
- }
462
- const destination = await deps.repo.findActiveDefinition({
463
- namespace: input.newNamespace,
464
- key: input.newKey,
465
- workspaceId: input.workspaceId,
466
- });
467
- if (destination) {
468
- if (destination.status === "alias") {
469
- throw new AliasDepthExceededError(`rename target '${input.newNamespace}.${input.newKey}' resolves to an existing alias marker; a marker's alias_of must point to an active definition (depth <=1)`);
470
- }
471
- throw new DefinitionInvalidError(`rename target '${input.newNamespace}.${input.newKey}' is already in use`);
472
- }
473
- const result = await deps.repo.transaction(async () => {
474
- const now = kernelNowIso({ clock: deps.clock });
475
- // Step 1: move the active row to the new name -- same setting_id, same version.
476
- await deps.repo.saveDefinition({ ...current, namespace: input.newNamespace, key: input.newKey, updatedAt: now });
477
- // Sequential rename: retarget every prior marker pointing at the OLD name to the NEW name.
478
- const siblings = await deps.repo.listActiveDefinitions({ workspaceId: input.workspaceId });
479
- for (const sibling of siblings) {
480
- if (sibling.status === "alias" &&
481
- sibling.aliasOfNamespace === input.namespace &&
482
- sibling.aliasOfKey === input.key) {
483
- await deps.repo.saveDefinition({
484
- ...sibling,
485
- aliasOfNamespace: input.newNamespace,
486
- aliasOfKey: input.newKey,
487
- updatedAt: now,
488
- });
489
- }
490
- }
491
- // Step 2: insert a fresh v1 alias marker at the OLD name pointing at the NEW name.
492
- const markerSettingId = deps.ids.newId();
493
- await deps.repo.saveDefinition({
494
- settingId: markerSettingId,
495
- version: 1,
496
- workspaceId: input.workspaceId,
497
- namespace: input.namespace,
498
- key: input.key,
499
- ownerKind: current.ownerKind,
500
- ownerId: current.ownerId,
501
- schema: current.schema,
502
- defaultValue: current.defaultValue,
503
- scopes: current.scopes,
504
- secret: current.secret,
505
- status: "alias",
506
- aliasOfNamespace: input.newNamespace,
507
- aliasOfKey: input.newKey,
508
- coercionTag: null,
509
- createdAt: now,
510
- updatedAt: now,
511
- });
512
- await deps.repo.appendRevision({
513
- entityKind: "definition",
514
- settingId: current.settingId,
515
- scope: null,
516
- workspaceId: input.workspaceId,
517
- principalId: null,
518
- op: "alias",
519
- beforeJson: null,
520
- afterJson: null,
521
- defVersion: current.version,
522
- actor: input.callerPrincipalId,
523
- originPluginId: null,
524
- changeSetId: null,
525
- createdAt: now,
526
- });
527
- return { settingId: current.settingId, markerSettingId };
528
- });
529
- // Both the old (alias-marker) namespace and the new (active-row) namespace
530
- // need a fresh definition-cache read after a rename.
531
- invalidateDefinitionNamespaceCache(deps.repo, input.namespace);
532
- invalidateDefinitionNamespaceCache(deps.repo, input.newNamespace);
533
- return result;
534
- }
535
- /**
536
- * The retype mechanism : a same-tx pair --
537
- * (1) UPDATE the prior active version's `status` to `deprecated` FIRST (else
538
- * the insert in step 2 collides with the one-active-row-per-slot
539
- * invariant); (2) INSERT the new `version+1` row as `active`, same
540
- * `setting_id`/`namespace`/`key`. Rejected unless every prior version
541
- * (2..N) already carries a total coercer -- `coercionTag` is `null` only for
542
- * version 1 by construction (`types.ts`), so this walks 2..N and requires
543
- * each to be non-null.
544
- * See docs/decisions/DR-003-settings-ledger-invariants.md.
545
- */
546
- export async function retypeDefinition(required) {
547
- const { deps, input } = required;
548
- await authorizeDefinitionsManage(deps, input.callerPrincipalId, input.authWorkspaceId);
549
- const current = await resolveActiveDefinitionOrThrow(deps, input, "retype");
550
- const namespaceOrKeyChanged = (input.newNamespace !== undefined && input.newNamespace !== current.namespace) ||
551
- (input.newKey !== undefined && input.newKey !== current.key);
552
- const schemaChanged = JSON.stringify(input.schema) !== JSON.stringify(current.schema);
553
- if (namespaceOrKeyChanged && schemaChanged) {
554
- throw new RenameRetypeConflictError(`cannot rename and retype '${input.namespace}.${input.key}' in the same operation; submit the rename and the retype as two separate chokepoint calls`);
555
- }
556
- for (let version = 2; version <= current.version; version++) {
557
- const priorVersion = await deps.repo.findDefinitionBySettingId({ settingId: current.settingId, version });
558
- if (!priorVersion || priorVersion.coercionTag == null) {
559
- throw new DefinitionInvalidError(`retype of '${input.namespace}.${input.key}' rejected: version ${version} does not carry a total coercer`);
560
- }
561
- }
562
- const result = await deps.repo.transaction(async () => {
563
- const now = kernelNowIso({ clock: deps.clock });
564
- const newVersion = current.version + 1;
565
- // Step 1: deprecate the prior active version first.
566
- await deps.repo.saveDefinition({ ...current, status: "deprecated", updatedAt: now });
567
- // Step 2: insert the new version as active -- same setting_id/namespace/key.
568
- await deps.repo.saveDefinition({
569
- settingId: current.settingId,
570
- version: newVersion,
571
- workspaceId: current.workspaceId,
572
- namespace: current.namespace,
573
- key: current.key,
574
- ownerKind: current.ownerKind,
575
- ownerId: current.ownerId,
576
- schema: input.schema,
577
- defaultValue: input.defaultValue,
578
- scopes: current.scopes,
579
- secret: current.secret,
580
- status: "active",
581
- aliasOfNamespace: null,
582
- aliasOfKey: null,
583
- coercionTag: input.coercionTag,
584
- createdAt: now,
585
- updatedAt: now,
586
- });
587
- await deps.repo.appendRevision({
588
- entityKind: "definition",
589
- settingId: current.settingId,
590
- scope: null,
591
- workspaceId: current.workspaceId,
592
- principalId: null,
593
- op: "retype",
594
- beforeJson: null,
595
- afterJson: null,
596
- defVersion: newVersion,
597
- actor: input.callerPrincipalId,
598
- originPluginId: null,
599
- changeSetId: null,
600
- createdAt: now,
601
- });
602
- return { settingId: current.settingId, version: newVersion };
603
- });
604
- invalidateDefinitionNamespaceCache(deps.repo, input.namespace);
605
- return result;
606
- }
607
- /** Add source-declared scopes to a core definition without moving or rewriting existing values.
608
- * Boot uses this when a workspace preference gains a personal override. Scope removal is a
609
- * separate migration decision: this operation only adds bits and preserves definition identity.
610
- * @throws DefinitionInvalidError for operator-owned definitions or invalid scope bits.
611
- * @complexity O(1), one definition transaction and cache invalidation.
612
- * @example await extendDefinitionScopes({ deps, input: { namespace, key, workspaceId: null,
613
- * scopes: SCOPE_BIT.user, callerPrincipalId, authWorkspaceId } });
614
- */
615
- export async function extendDefinitionScopes({ deps, input }, _options = {}) {
616
- await authorizeDefinitionsManage(deps, input.callerPrincipalId, input.authWorkspaceId);
617
- const current = await resolveActiveDefinitionOrThrow(deps, input, "extend the scopes of");
618
- const validBits = SCOPE_BIT.global | SCOPE_BIT.workspace | SCOPE_BIT.user;
619
- if (current.ownerKind !== "core" || !Number.isInteger(input.scopes) || input.scopes <= 0 || input.scopes > validBits) {
620
- throw new DefinitionInvalidError("Only core definitions can gain valid source-declared scope bits");
621
- }
622
- const scopes = current.scopes | input.scopes;
623
- if (scopes === current.scopes)
624
- return;
625
- await deps.repo.transaction(async () => {
626
- const now = kernelNowIso({ clock: deps.clock });
627
- await deps.repo.saveDefinition({ ...current, scopes, updatedAt: now });
628
- // Re-registration of metadata, not a value/schema change; retain the existing revision vocabulary.
629
- await deps.repo.appendRevision({ entityKind: "definition", settingId: current.settingId,
630
- scope: null, workspaceId: current.workspaceId, principalId: null, op: "register",
631
- beforeJson: { scopes: current.scopes }, afterJson: { scopes }, defVersion: current.version,
632
- actor: input.callerPrincipalId, originPluginId: null, changeSetId: null, createdAt: now });
633
- });
634
- invalidateDefinitionNamespaceCache(deps.repo, input.namespace);
635
- }
636
- /**
637
- * Reconciles a stored `default_json` that has drifted from the default its
638
- * source declares. Idempotent and a no-op when they already agree.
639
- *
640
- * Why this exists — the bug it closes:
641
- * `ensure-definitions.ts` registers each definition once and then skips it
642
- * forever (`if (existing) continue;`). That makes a changed `defaultValue` in
643
- * SOURCE unreachable in any install that has already booted, for every
644
- * settings-dialog tab a host registers this way. It can surface as a stored
645
- * default staying "system" in the database while source says "light",
646
- * rendering a settings panel with the wrong initial state — a visibly wrong
647
- * value produced by entirely correct-looking source. The next occurrence
648
- * could be a silently wrong default with no visual tell at all.
649
- *
650
- * Why `core`-only:
651
- * `ownerKind` already encodes who owns a definition. `core` definitions
652
- * configure a platform capability and are code-owned, so code is the authority
653
- * on their default and may overwrite a drifted stored one. `site` and `theme`
654
- * definitions are operator-owned — silently overwriting those would destroy a
655
- * deliberate choice, so they are rejected rather than reconciled.
656
- *
657
- * Why this is NOT a `retype`:
658
- * `retype` deprecates the active row and inserts `version+1` because a changed
659
- * SCHEMA means every stored value needs a total coercer. A changed DEFAULT
660
- * needs none — the schema is untouched, so every stored value stays valid and
661
- * only the resolution of UNSET values moves. The row is therefore updated in
662
- * place at the same version, and the paired revision carries the old and new
663
- * default in `beforeJson`/`afterJson` so the change is auditable.
664
- *
665
- * @complexity O(1) — one definition lookup plus at most one row update and one
666
- * revision append, in a single transaction.
667
- */
668
- export async function reconcileDefinitionDefault(required) {
669
- const { deps, input } = required;
670
- await authorizeDefinitionsManage(deps, input.callerPrincipalId, input.authWorkspaceId);
671
- const current = await resolveActiveDefinitionOrThrow(deps, input, "reconcile the default of");
672
- if (current.ownerKind !== "core") {
673
- throw new DefinitionInvalidError(`cannot reconcile the default of '${input.namespace}.${input.key}': only 'core' definitions are code-owned, and this one is '${current.ownerKind}' (operator-owned)`);
674
- }
675
- // Structural compare — `defaultValue` is a `JsonValue`, so `===` would miss a
676
- // changed object/array default.
677
- if (JSON.stringify(current.defaultValue) === JSON.stringify(input.defaultValue)) {
678
- return { settingId: current.settingId, changed: false };
679
- }
680
- if (!validateValueAgainstSchema(current.schema, input.defaultValue)) {
681
- throw new ValueValidationFailedError(`cannot reconcile the default of '${input.namespace}.${input.key}': the source default does not satisfy the definition's own schema (type '${current.schema.type}')`);
682
- }
683
- await deps.repo.transaction(async () => {
684
- const now = kernelNowIso({ clock: deps.clock });
685
- await deps.repo.saveDefinition({ ...current, defaultValue: input.defaultValue, updatedAt: now });
686
- await deps.repo.appendRevision({
687
- entityKind: "definition",
688
- settingId: current.settingId,
689
- scope: null,
690
- workspaceId: current.workspaceId,
691
- principalId: null,
692
- op: "redefault",
693
- beforeJson: current.defaultValue,
694
- afterJson: input.defaultValue,
695
- // Unchanged, deliberately — see the retype contrast above.
696
- defVersion: current.version,
697
- actor: input.callerPrincipalId,
698
- originPluginId: null,
699
- changeSetId: null,
700
- createdAt: now,
701
- });
702
- });
703
- invalidateDefinitionNamespaceCache(deps.repo, input.namespace);
704
- return { settingId: current.settingId, changed: true };
705
- }
706
- /**
707
- * `deprecateDefinition`/`tombstoneDefinition` were a jaccard-1.0
708
- * duplicate pair (same authorize -> resolve -> same-tx status flip + revision
709
- * shape, differing only in the target status string). This is that shape,
710
- * written once; both thin exports below just name their target status.
711
- */
712
- async function transitionDefinitionStatus(deps, input, target) {
713
- await authorizeDefinitionsManage(deps, input.callerPrincipalId, input.authWorkspaceId);
714
- const current = await resolveActiveDefinitionOrThrow(deps, input, target.revisionOp);
715
- const result = await deps.repo.transaction(async () => {
716
- const now = kernelNowIso({ clock: deps.clock });
717
- await deps.repo.saveDefinition({ ...current, status: target.status, updatedAt: now });
718
- await deps.repo.appendRevision({
719
- entityKind: "definition",
720
- settingId: current.settingId,
721
- scope: null,
722
- workspaceId: current.workspaceId,
723
- principalId: null,
724
- op: target.revisionOp,
725
- beforeJson: null,
726
- afterJson: null,
727
- defVersion: current.version,
728
- actor: input.callerPrincipalId,
729
- originPluginId: null,
730
- changeSetId: null,
731
- createdAt: now,
732
- });
733
- return { settingId: current.settingId, version: current.version };
734
- });
735
- invalidateDefinitionNamespaceCache(deps.repo, input.namespace);
736
- return result;
737
- }
738
- /** Flips the active definition's status to `deprecated`, ledgered `op='deprecate'` -- same-tx, chokepoint-gated. */
739
- export async function deprecateDefinition(required) {
740
- return transitionDefinitionStatus(required.deps, required.input, {
741
- status: "deprecated",
742
- revisionOp: "deprecate",
743
- });
744
- }
745
- /** Flips the active definition's status to `tombstone` (kills a core key), ledgered `op='tombstone'` -- same-tx, chokepoint-gated. */
746
- export async function tombstoneDefinition(required) {
747
- return transitionDefinitionStatus(required.deps, required.input, {
748
- status: "tombstone",
749
- revisionOp: "tombstone",
750
- });
751
- }
752
120
  //# sourceMappingURL=write-service.js.map