@happyvertical/smrt-core 0.55.7 → 0.55.8

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 (203) hide show
  1. package/AGENTS.md +2 -1
  2. package/agents/browser-entry.md +44 -0
  3. package/agents/build-knowledge.md +7 -0
  4. package/agents/recipes.md +217 -0
  5. package/agents/revision-guard.md +72 -1
  6. package/dist/audit-context.d.ts.map +1 -1
  7. package/dist/audit-context.js +2 -2
  8. package/dist/audit-context.js.map +1 -1
  9. package/dist/browser.d.ts +2 -1
  10. package/dist/browser.d.ts.map +1 -1
  11. package/dist/browser.js +7 -7
  12. package/dist/cascade.d.ts +1 -1
  13. package/dist/cascade.d.ts.map +1 -1
  14. package/dist/cascade.js +1 -1
  15. package/dist/cascade.js.map +1 -1
  16. package/dist/change-feed.d.ts.map +1 -1
  17. package/dist/change-feed.js +1 -2
  18. package/dist/change-feed.js.map +1 -1
  19. package/dist/class.d.ts +1 -1
  20. package/dist/class.d.ts.map +1 -1
  21. package/dist/class.js +7 -3
  22. package/dist/class.js.map +1 -1
  23. package/dist/collection.d.ts.map +1 -1
  24. package/dist/collection.js +1 -1
  25. package/dist/collection.js.map +1 -1
  26. package/dist/consumer-plugin/index.js +2 -2
  27. package/dist/data-query.d.ts.map +1 -1
  28. package/dist/data-query.js +2 -13
  29. package/dist/data-query.js.map +1 -1
  30. package/dist/database.js +1 -1
  31. package/dist/database.js.map +1 -1
  32. package/dist/dispatch/bus.js +1 -1
  33. package/dist/dispatch/bus.js.map +1 -1
  34. package/dist/embedded-write-queue.d.ts +1 -1
  35. package/dist/embedded-write-queue.d.ts.map +1 -1
  36. package/dist/embedded-write-queue.js +7 -5
  37. package/dist/embedded-write-queue.js.map +1 -1
  38. package/dist/embeddings/hash.js +2 -2
  39. package/dist/embeddings/hash.js.map +1 -1
  40. package/dist/embeddings/storage.d.ts.map +1 -1
  41. package/dist/embeddings/storage.js +1 -2
  42. package/dist/embeddings/storage.js.map +1 -1
  43. package/dist/errors.d.ts.map +1 -1
  44. package/dist/errors.js +1 -0
  45. package/dist/errors.js.map +1 -1
  46. package/dist/generation-snapshot.js +1 -1
  47. package/dist/generators/index.js +1 -1
  48. package/dist/generators/mcp.js +3 -3
  49. package/dist/generators/preflight-route.js +1 -1
  50. package/dist/generators/rest.js +1 -1
  51. package/dist/generators.js +1 -1
  52. package/dist/host.browser.d.ts +12 -0
  53. package/dist/host.browser.d.ts.map +1 -0
  54. package/dist/host.browser.js +30 -0
  55. package/dist/host.browser.js.map +1 -0
  56. package/dist/host.d.ts +18 -0
  57. package/dist/host.d.ts.map +1 -0
  58. package/dist/host.js +15 -0
  59. package/dist/host.js.map +1 -0
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +10 -9
  63. package/dist/knowledge.d.ts.map +1 -1
  64. package/dist/knowledge.js +5 -4
  65. package/dist/knowledge.js.map +1 -1
  66. package/dist/manifest/browser-capability.generated.d.ts +14 -0
  67. package/dist/manifest/browser-capability.generated.d.ts.map +1 -0
  68. package/dist/manifest/browser-capability.generated.js +499 -0
  69. package/dist/manifest/browser-capability.generated.js.map +1 -0
  70. package/dist/manifest/discover-base-classes.js +1 -1
  71. package/dist/manifest/discover-smrt-packages.js +1 -1
  72. package/dist/manifest/generator.js +3 -3
  73. package/dist/manifest/index.js +2 -2
  74. package/dist/manifest/local-manifest-reader.d.ts +48 -0
  75. package/dist/manifest/local-manifest-reader.d.ts.map +1 -0
  76. package/dist/manifest/local-manifest-reader.js +81 -0
  77. package/dist/manifest/local-manifest-reader.js.map +1 -0
  78. package/dist/manifest/manager.d.ts +5 -28
  79. package/dist/manifest/manager.d.ts.map +1 -1
  80. package/dist/manifest/manager.js +10 -56
  81. package/dist/manifest/manager.js.map +1 -1
  82. package/dist/manifest/manifest-loader.d.ts +1 -1
  83. package/dist/manifest/manifest-loader.d.ts.map +1 -1
  84. package/dist/manifest/manifest-loader.js +43 -12
  85. package/dist/manifest/manifest-loader.js.map +1 -1
  86. package/dist/manifest/node-host.d.ts +38 -0
  87. package/dist/manifest/node-host.d.ts.map +1 -0
  88. package/dist/manifest/node-host.js +52 -0
  89. package/dist/manifest/node-host.js.map +1 -0
  90. package/dist/manifest/package-manifest-exports.js +1 -1
  91. package/dist/manifest/static-manifest.d.ts.map +1 -1
  92. package/dist/manifest/static-manifest.js +7 -2
  93. package/dist/manifest/static-manifest.js.map +1 -1
  94. package/dist/manifest/store.d.ts +2 -1
  95. package/dist/manifest/store.d.ts.map +1 -1
  96. package/dist/manifest/store.js +7 -4
  97. package/dist/manifest/store.js.map +1 -1
  98. package/dist/manifest.js +1 -1
  99. package/dist/manifest.json +9 -2
  100. package/dist/native-duckdb.d.ts +28 -0
  101. package/dist/native-duckdb.d.ts.map +1 -0
  102. package/dist/native-duckdb.js +51 -0
  103. package/dist/native-duckdb.js.map +1 -0
  104. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js +169 -0
  105. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js.map +1 -0
  106. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js +13 -0
  107. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js.map +1 -0
  108. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js +198 -0
  109. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js.map +1 -0
  110. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js +243 -0
  111. package/dist/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js.map +1 -0
  112. package/dist/object.d.ts +56 -0
  113. package/dist/object.d.ts.map +1 -1
  114. package/dist/object.js +139 -16
  115. package/dist/object.js.map +1 -1
  116. package/dist/postgres-permissions.d.ts.map +1 -1
  117. package/dist/postgres-permissions.js +3 -3
  118. package/dist/postgres-permissions.js.map +1 -1
  119. package/dist/prebuild/index.js +1 -1
  120. package/dist/recipe-demo.d.ts +70 -0
  121. package/dist/recipe-demo.d.ts.map +1 -0
  122. package/dist/recipe-demo.js +130 -0
  123. package/dist/recipe-demo.js.map +1 -0
  124. package/dist/recipe.d.ts +64 -1
  125. package/dist/recipe.d.ts.map +1 -1
  126. package/dist/recipe.js +30 -0
  127. package/dist/recipe.js.map +1 -1
  128. package/dist/registry/class-registration.js +2 -2
  129. package/dist/registry/class-registration.js.map +1 -1
  130. package/dist/registry/db-cache-key.js +4 -5
  131. package/dist/registry/db-cache-key.js.map +1 -1
  132. package/dist/registry/inheritance-resolver.js +1 -1
  133. package/dist/registry/name-resolver.js +1 -1
  134. package/dist/registry/qualified-name-aliases.js +1 -1
  135. package/dist/registry/schema-builder.d.ts.map +1 -1
  136. package/dist/registry/schema-builder.js +3 -3
  137. package/dist/registry/schema-builder.js.map +1 -1
  138. package/dist/registry.d.ts.map +1 -1
  139. package/dist/registry.js +5 -8
  140. package/dist/registry.js.map +1 -1
  141. package/dist/revision-guard.js +1 -1
  142. package/dist/revision-guard.js.map +1 -1
  143. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  144. package/dist/scanner/manifest-generator.js +19 -10
  145. package/dist/scanner/manifest-generator.js.map +1 -1
  146. package/dist/scanner/recipe-demo-pass.d.ts +14 -0
  147. package/dist/scanner/recipe-demo-pass.d.ts.map +1 -0
  148. package/dist/scanner/recipe-demo-pass.js +33 -0
  149. package/dist/scanner/recipe-demo-pass.js.map +1 -0
  150. package/dist/scanner/types.d.ts +7 -1
  151. package/dist/scanner/types.d.ts.map +1 -1
  152. package/dist/scanner/types.js.map +1 -1
  153. package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
  154. package/dist/schema/ddl/duckdb-strategy.js +1 -1
  155. package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
  156. package/dist/schema/foreign-key-planner.d.ts.map +1 -1
  157. package/dist/schema/foreign-key-planner.js +1 -1
  158. package/dist/schema/foreign-key-planner.js.map +1 -1
  159. package/dist/schema/generator.d.ts.map +1 -1
  160. package/dist/schema/generator.js +10 -14
  161. package/dist/schema/generator.js.map +1 -1
  162. package/dist/schema/schema-aggregator.js +1 -1
  163. package/dist/scripts/browser-entry-evaluation.mjs +157 -0
  164. package/dist/smrt-knowledge.json +27 -12
  165. package/dist/system/browser.d.ts +16 -0
  166. package/dist/system/browser.d.ts.map +1 -0
  167. package/dist/system/browser.js +6 -0
  168. package/dist/system/index.d.ts +1 -6
  169. package/dist/system/index.d.ts.map +1 -1
  170. package/dist/system/index.js +2 -1
  171. package/dist/testing/database.js +1 -1
  172. package/dist/tools/index.js +1 -1
  173. package/dist/unchanged-indexed.d.ts +85 -0
  174. package/dist/unchanged-indexed.d.ts.map +1 -0
  175. package/dist/unchanged-indexed.js +219 -0
  176. package/dist/unchanged-indexed.js.map +1 -0
  177. package/dist/utils/async-context.d.ts +22 -0
  178. package/dist/utils/async-context.d.ts.map +1 -0
  179. package/dist/utils/async-context.js +27 -0
  180. package/dist/utils/async-context.js.map +1 -0
  181. package/dist/utils/import-project-vite.js +1 -1
  182. package/dist/utils/import-workspace-module.js +1 -1
  183. package/dist/utils/json.browser.d.ts +18 -0
  184. package/dist/utils/json.browser.d.ts.map +1 -0
  185. package/dist/utils/json.browser.js +47 -0
  186. package/dist/utils/json.browser.js.map +1 -0
  187. package/dist/utils/sha256.d.ts +15 -0
  188. package/dist/utils/sha256.d.ts.map +1 -0
  189. package/dist/utils/sha256.js +29 -0
  190. package/dist/utils/sha256.js.map +1 -0
  191. package/dist/vite-plugin/changes-route.js +1 -1
  192. package/dist/vite-plugin/dev-plane-route.js +1 -1
  193. package/dist/vite-plugin/events-route.js +1 -1
  194. package/dist/vite-plugin/import-build-aware.js +1 -1
  195. package/dist/vite-plugin/index.js +2 -2
  196. package/dist/vite-plugin/resources-route.js +1 -1
  197. package/dist/vite-plugin/sveltekit-generator.js +2 -2
  198. package/dist/vite-plugin/sveltekit-path.js +1 -1
  199. package/dist/vite-plugin/sveltekit-register-injection.js +1 -1
  200. package/dist/vite-plugin/sveltekit-route-coordinator.js +1 -1
  201. package/dist/vite-plugin/sync-apply-route.js +1 -1
  202. package/dist/vite-plugin/web-collections.js +2 -2
  203. package/package.json +21 -11
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Evaluates the BUILT browser entry (`dist/browser.js`, what the package's
3
+ * `browser` export condition resolves to) in real Chromium (#2838).
4
+ *
5
+ * The bundle-gate proves the module graph contains no Node-only modules; this
6
+ * proves the entry also *runs*: a Vite browser bundle is loaded in a page and
7
+ * the test fails on any evaluation error (`Buffer is not defined` from `pg`,
8
+ * `process is not defined`, a missing export) or any module Vite had to
9
+ * externalize "for browser compatibility". Run `pnpm build` first.
10
+ *
11
+ * Set PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH to use a Chromium other than
12
+ * Playwright's own install.
13
+ */
14
+ import { existsSync } from 'node:fs';
15
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
16
+ import { createServer } from 'node:http';
17
+ import { tmpdir } from 'node:os';
18
+ import { dirname, extname, resolve } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { chromium } from 'playwright-core';
21
+ import { build, createLogger } from 'vite';
22
+
23
+ const packageDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
24
+ const browserEntry = resolve(packageDir, 'dist/browser.js');
25
+ const browserHost = resolve(packageDir, 'dist/host.browser.js');
26
+ if (!existsSync(browserEntry)) {
27
+ throw new Error(`${browserEntry} is missing; run \`pnpm build\` first`);
28
+ }
29
+
30
+ const workDir = await mkdtemp(resolve(tmpdir(), 'smrt-core-browser-entry-'));
31
+ const outputDir = resolve(workDir, 'dist');
32
+ const entry = resolve(workDir, 'entry.ts');
33
+ const contentTypes = { '.js': 'text/javascript', '.map': 'application/json' };
34
+
35
+ try {
36
+ await writeFile(
37
+ entry,
38
+ `import * as core from ${JSON.stringify(browserEntry)};
39
+ import { buildWhere, raw, NestedTransactionError } from ${JSON.stringify(browserHost)};
40
+ const query = buildWhere({ id: 1 });
41
+ if (!query || !raw('count(*)') || typeof NestedTransactionError !== 'function') {
42
+ throw new Error('browser SQL helpers are unavailable');
43
+ }
44
+ const { SmrtObject, ObjectRegistry, smrt } = core;
45
+ const required = ['SmrtObject', 'SmrtCollection', 'SmrtClass', 'smrt', 'smrtRegistry'];
46
+ const missing = required.filter((name) => !(name in core));
47
+ if (missing.length > 0) throw new Error('browser entry lacks exports: ' + missing.join(', '));
48
+ if (typeof process !== 'undefined') throw new Error('page unexpectedly has process');
49
+ if (typeof Buffer !== 'undefined') throw new Error('page unexpectedly has Buffer');
50
+
51
+ // Loading is not enough: a decorated class must register and construct
52
+ // without a filesystem, a manifest or a database.
53
+ @smrt()
54
+ class BrowserWidget extends SmrtObject {
55
+ name = '';
56
+ size = 0;
57
+ constructor(options = {}) {
58
+ super(options);
59
+ Object.assign(this, options);
60
+ }
61
+ }
62
+ const widget = new BrowserWidget({ name: 'probe', size: 3 });
63
+ if (widget.name !== 'probe' || widget.size !== 3) throw new Error('widget fields were not assigned');
64
+ const registered = ObjectRegistry.getClass('BrowserWidget');
65
+ if (!registered) throw new Error('decorated class did not register');
66
+ document.body.textContent = 'browser entry evaluated: ' + Object.keys(core).length + ' exports';
67
+ `,
68
+ );
69
+
70
+ // Vite reports a Node built-in it cannot bundle as a warning and substitutes
71
+ // a throwing stub; treat each one as a failure instead of letting the
72
+ // entry "evaluate" over a stub.
73
+ const externalized = [];
74
+ const logger = createLogger('error');
75
+ const warn = logger.warn.bind(logger);
76
+ logger.warn = (message, options) => {
77
+ if (message.includes('externalized for browser compatibility')) {
78
+ externalized.push(message.split('\n')[0]);
79
+ } else {
80
+ warn(message, options);
81
+ }
82
+ };
83
+ await build({
84
+ configFile: false,
85
+ customLogger: logger,
86
+ logLevel: 'warn',
87
+ root: packageDir,
88
+ oxc: { decorator: { legacy: true } },
89
+ build: {
90
+ outDir: outputDir,
91
+ minify: false,
92
+ rollupOptions: { input: entry, output: { entryFileNames: 'entry.js' } },
93
+ target: 'es2022',
94
+ },
95
+ });
96
+ if (externalized.length > 0) {
97
+ throw new Error(
98
+ `browser entry bundles Node-only modules:\n${[...new Set(externalized)].join('\n')}`,
99
+ );
100
+ }
101
+
102
+ const server = createServer(async (request, response) => {
103
+ const pathname = new URL(request.url ?? '/', 'http://localhost').pathname;
104
+ if (pathname === '/') {
105
+ response.writeHead(200, { 'content-type': 'text/html' });
106
+ response.end('<script type="module" src="/entry.js"></script>');
107
+ return;
108
+ }
109
+ if (pathname === '/favicon.ico') return response.writeHead(204).end();
110
+ const file = resolve(outputDir, `.${pathname}`);
111
+ if (!file.startsWith(`${outputDir}/`)) return response.writeHead(403).end();
112
+ try {
113
+ const content = await readFile(file);
114
+ response.writeHead(200, {
115
+ 'content-type': contentTypes[extname(file)] ?? 'application/octet-stream',
116
+ });
117
+ response.end(content);
118
+ } catch {
119
+ response.writeHead(404).end();
120
+ }
121
+ });
122
+ await new Promise((done) => server.listen(0, '127.0.0.1', done));
123
+ const { port } = server.address();
124
+ let browser;
125
+ try {
126
+ browser = await chromium.launch({
127
+ executablePath:
128
+ process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH ||
129
+ chromium.executablePath(),
130
+ });
131
+ const page = await browser.newPage();
132
+ const errors = [];
133
+ page.on('pageerror', (error) => errors.push(error.stack ?? error.message));
134
+ page.on('console', (message) => {
135
+ if (message.type() === 'error') errors.push(message.text());
136
+ });
137
+ await page.goto(`http://127.0.0.1:${port}`);
138
+ await page
139
+ .waitForFunction(
140
+ () => document.body.textContent?.includes('browser entry evaluated'),
141
+ undefined,
142
+ { timeout: 10_000 },
143
+ )
144
+ .catch(() => {
145
+ throw new Error(
146
+ errors.join('\n') || 'browser entry did not finish evaluating',
147
+ );
148
+ });
149
+ if (errors.length > 0) throw new Error(errors.join('\n'));
150
+ console.log(await page.evaluate(() => document.body.textContent));
151
+ } finally {
152
+ await browser?.close();
153
+ await new Promise((done) => server.close(done));
154
+ }
155
+ } finally {
156
+ await rm(workDir, { force: true, recursive: true });
157
+ }
@@ -3,15 +3,15 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.55.7",
6
+ "packageVersion": "0.55.8",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "13a4d82f38aab38a3855ff59a5da401737310478e72c92d852abffd7bb913d95",
11
- "packageJson": "40a46dfab65d3f006837f24881b7f4cbf72ebcaefaedeeb93a34fb6e063a5de9",
12
- "agents": "9e34f2a3e85666f8ba64d1bdd8e8ed55384421d7bffc263ce0fb3109dfdcafaa",
10
+ "manifest": "7e47fe8ee0b470eca73ea4d14cd0a09789959484dfcad30164be4434c1fbb030",
11
+ "packageJson": "cf03f9ab4af571af05f434fb217f88f197eb6912e05d395a0353df7bb36cfac9",
12
+ "agents": "0a94ccfbd3b7b48e0e88388ba0385f386f3e9b2816d97adf84097fd06bb488de",
13
13
  "moduleDoc:agents/object-runtime.md": "652352cdf1eddd0dcc91f6589b8241d9d99581f54bcc2318520a3ff97cd22cf5",
14
- "moduleDoc:agents/revision-guard.md": "aa6b1ddb5b6b49fa27ebbe575ec7fcd6d5ceb35ee25acc702f877a226eb9a99a",
14
+ "moduleDoc:agents/revision-guard.md": "f6ea32a6860964c98aba14b93587f40b33c8f7d0deccb2c54d21bff45db3da42",
15
15
  "moduleDoc:agents/collection-reads.md": "e5bb79b59c17e79a85a71580a019e6b0b641e498ac4d850073fd5ad634b57cb7",
16
16
  "moduleDoc:agents/query-bounds.md": "3a0601ddaf2bea4e90e3f22e16a2eb3508a6fb8c019e3fb2c1f930c90a377cd5",
17
17
  "moduleDoc:agents/data-query.md": "1b72411d441ce2285bf0c89674e7aa996832a58b552b23a6d43834b907d91355",
@@ -19,13 +19,14 @@
19
19
  "moduleDoc:agents/change-feed.md": "c3d6206758dd1d2e0475177e1938fb7d7b6cfe8a6c4d3c3b56ef62bc7bc7739d",
20
20
  "moduleDoc:agents/change-signals.md": "a2dbe7077483b5a19bd5ea9589b5a08fe847377c8e05d01d57f813c6d9cbc28b",
21
21
  "moduleDoc:agents/generators.md": "55244a454c2ab8937143600eb785f069d949d75fc4da8bfdf78fb801a59facc8",
22
- "moduleDoc:agents/build-knowledge.md": "08f6ea140ab43eead7f5968e93c7891434d43c899a19631f97ce1ef8bcaebc8d",
22
+ "moduleDoc:agents/build-knowledge.md": "695cdcb80eb82347db9203493293da62da44c4dc8cacb489a09be64bc976fb79",
23
23
  "moduleDoc:agents/memory.md": "a86bdf370403d08ecad3be86e341eb322dfe6e6b7a4e8806a6f8be9bf3421da5",
24
24
  "moduleDoc:agents/system-diagnostics.md": "b7ccae18ee312bf788d5470f95fa78d3535f1789247d5372e40ca86538290772",
25
25
  "moduleDoc:agents/registry-snapshot.md": "6234aa540427396d1dda1825a4641b1072e247187d5ddf413ae46c691344ee30",
26
26
  "moduleDoc:agents/model-moves.md": "c64147fee1b7ec242fd1c178e7aea7cc90cafc704dee2738141c7a6d61403cd8",
27
27
  "moduleDoc:agents/run-once.md": "0b858c18c78eca5050257a2af06f16de99327e05e0bf9fee9e6277242e7707ef",
28
- "moduleDoc:agents/recipes.md": "06b63f309ad7d4d33901b6c6fd974f6535855d7aaab4e99e0a032ffae0fb84aa",
28
+ "moduleDoc:agents/recipes.md": "50ddedb14583e073c4af9c15142f4838c4326c1955931f743148e41e15dbdf38",
29
+ "moduleDoc:agents/browser-entry.md": "04d26eff8a65f02e88b20cbb77b1f94f58e29b62178ac6fbec129ee436a732eb",
29
30
  "moduleDoc:agents/test-types.md": "37c009ae2bd21001d83bba6cfab2047465fe32d5443de12661e24ba7d4e2d613"
30
31
  },
31
32
  "exports": [
@@ -45,6 +46,7 @@
45
46
  "./migrations",
46
47
  "./prebuild",
47
48
  "./prebuild/cli",
49
+ "./recipe-demo",
48
50
  "./runtime",
49
51
  "./scanner",
50
52
  "./scanner/types",
@@ -70,6 +72,7 @@
70
72
  "@happyvertical/smrt-types": "workspace:*",
71
73
  "@happyvertical/sql": "catalog:",
72
74
  "@happyvertical/utils": "catalog:",
75
+ "@noble/hashes": "^2.4.0",
73
76
  "@oxc-project/runtime": "^0.150.0",
74
77
  "cheerio": "^1.2.0",
75
78
  "fast-glob": "3.3.3",
@@ -1127,7 +1130,7 @@
1127
1130
  "polymorphicAssociations": 1,
1128
1131
  "uuidColumns": 3
1129
1132
  },
1130
- "agentDoc": "# @happyvertical/smrt-core\n\nFoundation ORM, registry, schema/code generation, AI integration, and DispatchBus.\nRead the module for the subsystem being edited; root AGENTS covers shared model\nand repository rules.\n\n## Modules\n\n| Source | Scope | Module doc |\n|---|---|---|\n| `src/object.ts`, `src/collection.ts`, `src/child-accessors.ts` | Lifecycle, hydration, operators, STI, child accessors, dispatch | [agents/object-runtime.md](agents/object-runtime.md) |\n| `src/revision-guard.ts` | Guarded writes and PostgreSQL revision precision | [agents/revision-guard.md](agents/revision-guard.md) |\n| `src/collection.ts` | Projections, latest-related, facets, counts, read plans | [agents/collection-reads.md](agents/collection-reads.md) |\n| `src/collection.ts` | Limits, sort whitelist, generated list order | [agents/query-bounds.md](agents/query-bounds.md) |\n| `src/data-query.ts` | Transport-neutral bounded query normalization | [agents/data-query.md](agents/data-query.md) |\n| `src/schema/`, `src/migrations/`, `src/cascade.ts`, `src/system/` | DDL parity, indexes, migrations, delete integrity, retention | [agents/schema-paths.md](agents/schema-paths.md) |\n| `src/postgres-permissions.ts` | Explicit PostgreSQL ACL plans and atomic reconciliation | [deployment permission contract](../../docs/content/postgres-permissions.md) |\n| `src/change-feed.ts` | Durable changes, cursors, table versions, retention | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-feed-authz.ts` | Consumer table/row change-feed authorization hooks (#3020) | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-signals.ts` | Signal bus, replica fan-out, SSE | [agents/change-signals.md](agents/change-signals.md) |\n| `src/generators/`, `src/vite-plugin/web-collections.ts` | REST/CLI/MCP generation, manifest hashes, ETags | [agents/generators.md](agents/generators.md) |\n| `src/vite-plugin/`, `src/consumer-plugin/`, `src/knowledge.ts` | Decorator UI hints, knowledge projection, generation snapshots | [agents/build-knowledge.md](agents/build-knowledge.md) |\n| `src/knowledge-graph.ts` | Cross-package knowledge graph merge and freshness check (#2863) — see [standards](../../docs/content/standards.md) | — |\n| `src/object.ts`, `src/collection.ts`, `src/learning/memory.ts` | Context memory and semantic search | [agents/memory.md](agents/memory.md) |\n| `src/system/diagnostics.ts` | SELECT-only `_smrt_*` diagnostics reader behind smrt-dev-mcp runtime tools (#1824) | [agents/system-diagnostics.md](agents/system-diagnostics.md) |\n| `src/system/registry-snapshot.ts` | Sanitized plain-JSON projection of the booted `ObjectRegistry` for the smrt-dev-mcp runtime dev-plane (#1831); never constructors, validators, values, or absolute paths | [agents/registry-snapshot.md](agents/registry-snapshot.md) |\n| `src/registry/qualified-name-aliases.ts`, `src/migrations/qualified-name-aliases.ts` | Model moves: `previousQualifiedNames` aliases, deprecation, doctor counts, opt-in backfill (#3338) | [agents/model-moves.md](agents/model-moves.md) |\n| `src/run-once.ts` | Shared idempotency seam: insert-only claim + caller work in one transaction, replay on retry, typed in-flight/unknown-outcome answers (#3080) | [agents/run-once.md](agents/run-once.md) |\n| `src/recipe.ts`, `../scanner/src/recipes.ts` | `SmrtRecipe`: declared user-facing units (models, nav, `requires`, curation `options`) collected into manifest and knowledge `recipes` (#3590) | [agents/recipes.md](agents/recipes.md) |\n\n## Cross-module invariants\n\n- `ObjectRegistry` is a `globalThis` singleton so registration survives HMR.\n- Any output that names a database URL (CLI banners, logs, errors) renders it\n with `redactDatabaseUrl` / `redactDatabaseUrlsInText`\n (`src/utils/database-url.ts`, #3527): never the password or query string,\n and never the raw string when it cannot be parsed.\n- Per-class registry work on the hydration path (manifest reconciliation in\n `ensureManifestLoaded()`, the simple-name index behind `findClass()`) is\n memoized per registry generation (`src/registry/generation.ts`, #3047). Any\n new writer of registered classes, their field/method metadata, or loaded\n manifests must go through the tracked maps or call\n `bumpRegistryGeneration()`; `issue-3047-hydration-registry-work.test.ts`\n guards that hydration does not repeat this work per row.\n\n- Production DDL uses manifest generators; `getTestDatabase()` uses registry\n generators. Keep columns, indexes, FK actions, and runtime conflict targets in\n parity (`src/schema/schema-path-parity.test.ts`). Every new query predicate\n needs its index or an explicit reason none is needed.\n- Tenant scoping covers every read and every unique/conflict key. Explicit\n conflict columns are not rewritten; their author must include tenant scope.\n A `tenantId` field makes rows tenant-OWNED without any tenancy declaration:\n the default key leads with `tenant_id`. A new object's natural-key save reads\n the row its upsert would hit and refuses a different owner\n (`TENANT_ISOLATION_VIOLATION`) or adopts a same-owner row's id, so\n `DO UPDATE` never rewrites a primary key or owner. Only an explicit natural\n key adopts: a slug `getSlug()` derived from `name`/`title`/`label` moves to\n a free `-2`, `-3`, … slug and INSERTs. See `agents/schema-paths.md`\n (\"Tenant OWNERSHIP\").\n- Persisted saves use `id` and loaded `updated_at`; new saves use natural keys.\n Preserve revision compare-and-swap ordering through public `save()`,\n `claimRevision()`, and transaction APIs. Embedded saves, deletes, and complete\n `withTransaction()` callbacks share a process-local write queue.\n- Collection model hydration is serial in result order: initialization may query\n the same transaction-bound PostgreSQL client. Use projections for plain rows.\n- Native DuckDB UUIDs must be cast coherently on read before identity reuse;\n custom embedded revision paths use `getCanonicalPersistedRow()`. Never replay\n a mutation to discover result types.\n- `withDatabase(db, callback)` restores only database bindings (including public\n `options.db`); `withTransaction(callback)` also restores identity/revision\n metadata after rollback. Do not use a bound instance concurrently.\n- `runOnce({ db, tenantId, actor, token, content }, work)` (`src/run-once.ts`,\n #3080) claims a key derived from all four inputs — never the token alone,\n which collapses distinct submissions — via `INSERT ... ON CONFLICT\n (claim_key) DO NOTHING RETURNING claim_key` into the hand-DDL\n `_smrt_run_once_claims` system table, and runs `work` in the SAME\n transaction; a completed claim replays its stored result instead of\n re-running, a failed `work` rolls the claim back with the transaction, and\n an unresolved claim raises typed `RunOnceClaimError`\n (`RUN_ONCE_IN_FLIGHT` / `RUN_ONCE_OUTCOME_UNKNOWN`) rather than guessing.\n The claim insert must never raise on conflict: PostgreSQL aborts the whole\n transaction on any raised error, which would take the recovery `SELECT`\n down with it too — this is why it is `DO NOTHING`, not a plain `INSERT`\n caught for `isUniqueViolationError`. Completed claims are bounded by\n `runRetentionSweep()`'s `run-once-claims` task (`system/retention.ts`,\n `DEFAULT_RETENTION_POLICY.runOnceClaims`, default 30 days on\n `completed_at`; `in_progress` rows are never matched) — the window is a\n replay deadline, not just disk hygiene: a token replayed after its claim\n is swept runs `work()` again. See `agents/run-once.md`.\n- `ensureSystemTables(db, typeHint?)` provisions framework tables idempotently;\n call it on a base PostgreSQL connection before caller-owned transactions.\n Bootstrap uses a transaction-scoped advisory lock, taken only when the\n PostgreSQL schema version is not yet stamped: inside a caller's transaction it\n is held until that transaction ends (#2868). Application tables still require migrations;\n runtime table verification checks existence only.\n- Manifest generation fails closed on scanner errors, including unresolved\n decorator spreads. Never emit partial, default-open registration.\n- Generated registration repairs bundled class identity using the exact imported\n constructor, explicit package, and isolated one-object manifest. Never infer\n ownership from paths, simple names, or table names; packages can share names.\n Consumer regression gate: `packages/bundle-gate/src/__tests__/registry-identity.spec.ts`.\n- Decorator registration trusts a class's stack-derived package only when that\n package declares the class (stub, own manifest entry, or explicit\n `packageName`); it then matches the qualified key and never adopts another\n package's same-named registration. Otherwise a loaded (or the cwd project's)\n manifest entry describing the declaring file supplies the identity — apps\n scan workspace-package sources under the app's name (#3110). A class of\n another known package coexists under its qualified key\n (`decorator-different-packages-qualified-coexist`); bundled output needs\n a resolved table that differs first (#3106). Stack\n attribution skips smrt-core (including source-mapped installed\n `smrt-core/src` frames, #3109), decorator-helper, and module-runner frames,\n and drops a frame's Vite `?v=` query (#3490). Library builds stamp each\n decorated class with `static __smrtPackage__` (own property, read at\n decoration as its explicit package) and publish `stampsConstructors`; an\n unstamped class never takes a stamping package's entry by name and table,\n in either order (#3490, `issue-3490-*.test.ts`, `package-stamp.test.ts`).\n Qualified names are `@scope/pkg:Class`; the scope is a deliberate\n discriminator, so manifest generation (`generateManifest`,\n `applyGenerationPasses`, hence `pnpm build`) throws\n `CONFIG_UNSCOPED_PACKAGE_NAME` for an unscoped `package.json` name (#3408).\n Instance and collection registry lookups pass the qualified name. The schema\n planner rejects a table claimed by two unrelated classes\n (`CONFIG_TABLE_NAME_COLLISION`): only one STI family shares a table (#3098);\n collections (including `SmrtReportCollection`) never claim one. Consumer\n gates: `registry/__tests__/issue-3110-*.test.ts`, `issue-3109-*.test.ts`,\n `packages/bundle-gate/src/__tests__/consumer-same-name.spec.ts`.\n- API custom-action eligibility has ONE resolver, `resolveApiMethodExposure()`\n in `generators/custom-action.ts`: both SvelteKit route emitters,\n `resolveApiActionSet`, and `knowledge.ts` read it, and a new consumer must too\n — a local mirror is how a method gets reported unavailable while its route\n file is still written. A public method routes by default only when every\n parameter is JSON-shaped; `@method({ expose })` overrides in both directions,\n `expose: true` bypasses the heuristic ALONE, and an explicit `api.include` or\n `api.routes` entry keeps its pre-#2686 route. Fail closed on scanner\n uncertainty: read `parameters[].typeUnresolved`, never the `'any'` it\n substitutes. Accepting `Date` as wire-able and hydrating it\n (`toCustomActionDate`) are one decision — changing either breaks the other.\n The runtime `APIGenerator` transport stays declaration-gated: `rest.ts`\n dispatch and `preflight-route.ts` prediction both read\n `declaresRuntimeRestRoute()`, which must accept every `ApiCustomRouteConfig`\n option so a sweep moving one onto its method cannot delete the endpoint. Its\n twin `declaresRuntimeRestRouteShape()` deliberately ignores `expose: false`:\n the dispatcher must still SEE a withheld declaration to answer 404, because\n `POST /<collection>/<segment>` resolves to `create` when nothing claims the\n segment. Split unions and type arguments with `splitTopLevel()` — a naive\n `split('|')` truncates `Record<string, Asset | null>` into fragments that\n match no rule and are then accepted, widening the gate. `extractTypeName`\n returns `null` for a generic with an unresolvable ARGUMENT or a union with an\n unresolvable BRANCH so those reach that fail-closed path instead of arriving\n as a bare `'Array'`. Runtime transports read\n `ObjectRegistry.resolveRuntimeMethod()`, which tries the item class's manifest\n entry, then the COLLECTION class's (where a collection-hosted action's\n parameters live), then the live `@method()` store — keyed by CONSTRUCTOR,\n never by simple name (`Account` exists in two packages), and recording\n `isStatic` because an unscanned runtime has no manifest to recover the\n receiver from. `isRestActionRoutable` ANDs \"declared\" with that receiver, so\n it never predicts `allow` for an action dispatch refuses. A declared action\n with no receiver is refused (501 collection-scoped, 404 item-scoped), never\n allowed to fall through into `create`. All eight consumers read the resolver,\n including `packages/smrt-workbench/src/discovery.ts`; it imports the\n `./generators/custom-action` LEAF subpath, not `./generators`, because that\n barrel value-re-exports `MCPGenerator` and so drags `@happyvertical/ai` and\n `@happyvertical/sql` into a build-time helper (2 modules vs 109). Keep\n `custom-action.ts` free of value imports outside `tools/tool-generator`.\n\n## Gotchas\n\n- Optional filesystem support stays lazy: use `createFilesystemAdapter()` in\n `src/filesystem-loader.ts`, not a static files-SDK import. Fully bundled apps\n import `@happyvertical/smrt-core/filesystem` at startup. Use\n `importOptionalDependency()` for similarly heavy optional dependencies.\n- `src/browser.ts` is the `browser`-condition entry of the package root: the\n Node entry (`index.ts`) minus HTTP servers, manifest/knowledge discovery, run-once,\n the Vite plugin, and the test helper. A new export added to `index.ts` must also\n go to `browser.ts` unless it is Node-only; `src/__tests__/browser-entry-parity.test.ts`\n fails otherwise (allowlist: `NODE_ONLY_GROUPS` in that test, each with a reason; the browser\n entry may not publish a name the Node entry lacks), and also\n fails when a workspace package imports a root value the browser entry lacks.\n- `exports['.'].browser` (`dist/browser.js`) is the browser surface. Model\n package roots are bundled for browsers by the bundle-gate browser fixture\n (#3621): anything a model root imports from core must be exported by the\n browser entry and must not reach `node:` built-ins, `pg`, `cosmiconfig`, or\n `jiti`. Keep Node-only code behind a subpath or a lazy import; when a fix\n makes a package pass, delete its entry in\n `packages/bundle-gate/src/browser-gate/expected-failures.ts`.\n- Database retries are transient-only, four attempts total for `get`/`upsert`.\n Use `src/db-errors.ts` classifiers through the cause chain, never message\n matching (SDK driver text can live in `context.originalError`). Constraints,\n bad input, missing tables, and aborted PostgreSQL transactions fail immediately.\n Unique/PK violations become `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL becomes\n `VALIDATION_REQUIRED_FIELD`; other failures keep the driver error as `cause`.\n- Property initializers precede option values; options win. Arrays/objects are\n shallow-cloned. Collection creation caches fields; table verification caches\n by DB URL and table. Preserve these scopes when changing initialization.\n- The Vite plugin loads scanner/schema code from `dist/` when present. Rebuild\n core after editing those sources before testing consumer manifest generation.\n Vite 8 requires `oxc.decorator: { legacy: true, emitDecoratorMetadata: true }`.\n\n## Validation\n\n`typecheck` checks production source first, then the test project in\n`tsconfig.test.json`. Test coverage and the shared relaxed config\ncontract are documented in [agents/test-types.md](agents/test-types.md).\n\nRun focused tests first, then applicable package checks:\n\n```bash\npnpm --filter @happyvertical/smrt-core test\npnpm --filter @happyvertical/smrt-core typecheck\npnpm --filter @happyvertical/smrt-core build\npnpm --filter @happyvertical/smrt-core test:postgres\npnpm check:agents-chain\npnpm smrt dev:knowledge-check\n```\n\nThe PostgreSQL lane is required for numeric types, UUID casts, conflict targets,\ntimestamps, and migrations. Tests generate their manifest before Vitest; restart\nwatch mode after adding decorated classes. Documentation-only changes need\ninstruction-chain and knowledge freshness checks, not the runtime test suite.\n",
1133
+ "agentDoc": "# @happyvertical/smrt-core\n\nFoundation ORM, registry, schema/code generation, AI integration, and DispatchBus.\nRead the module for the subsystem being edited; root AGENTS covers shared model\nand repository rules.\n\n## Modules\n\n| Source | Scope | Module doc |\n|---|---|---|\n| `src/object.ts`, `src/collection.ts`, `src/child-accessors.ts` | Lifecycle, hydration, operators, STI, child accessors, dispatch | [agents/object-runtime.md](agents/object-runtime.md) |\n| `src/revision-guard.ts`, `src/unchanged-indexed.ts`, `src/native-duckdb.ts` | Guarded writes, PostgreSQL revision precision, unchanged indexed columns on referenced DuckDB rows (#3737) | [agents/revision-guard.md](agents/revision-guard.md) |\n| `src/collection.ts` | Projections, latest-related, facets, counts, read plans | [agents/collection-reads.md](agents/collection-reads.md) |\n| `src/collection.ts` | Limits, sort whitelist, generated list order | [agents/query-bounds.md](agents/query-bounds.md) |\n| `src/data-query.ts` | Transport-neutral bounded query normalization | [agents/data-query.md](agents/data-query.md) |\n| `src/schema/`, `src/migrations/`, `src/cascade.ts`, `src/system/` | DDL parity, indexes, migrations, delete integrity, retention | [agents/schema-paths.md](agents/schema-paths.md) |\n| `src/postgres-permissions.ts` | Explicit PostgreSQL ACL plans and atomic reconciliation | [deployment permission contract](../../docs/content/postgres-permissions.md) |\n| `src/change-feed.ts` | Durable changes, cursors, table versions, retention | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-feed-authz.ts` | Consumer table/row change-feed authorization hooks (#3020) | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-signals.ts` | Signal bus, replica fan-out, SSE | [agents/change-signals.md](agents/change-signals.md) |\n| `src/generators/`, `src/vite-plugin/web-collections.ts` | REST/CLI/MCP generation, manifest hashes, ETags | [agents/generators.md](agents/generators.md) |\n| `src/vite-plugin/`, `src/consumer-plugin/`, `src/knowledge.ts` | Decorator UI hints, knowledge projection, generation snapshots | [agents/build-knowledge.md](agents/build-knowledge.md) |\n| `src/knowledge-graph.ts` | Cross-package knowledge graph merge and freshness check (#2863) — see [standards](../../docs/content/standards.md) | — |\n| `src/object.ts`, `src/collection.ts`, `src/learning/memory.ts` | Context memory and semantic search | [agents/memory.md](agents/memory.md) |\n| `src/system/diagnostics.ts` | SELECT-only `_smrt_*` diagnostics reader behind smrt-dev-mcp runtime tools (#1824) | [agents/system-diagnostics.md](agents/system-diagnostics.md) |\n| `src/system/registry-snapshot.ts` | Sanitized plain-JSON projection of the booted `ObjectRegistry` for the smrt-dev-mcp runtime dev-plane (#1831); never constructors, validators, values, or absolute paths | [agents/registry-snapshot.md](agents/registry-snapshot.md) |\n| `src/registry/qualified-name-aliases.ts`, `src/migrations/qualified-name-aliases.ts` | Model moves: `previousQualifiedNames` aliases, deprecation, doctor counts, opt-in backfill (#3338) | [agents/model-moves.md](agents/model-moves.md) |\n| `src/run-once.ts` | Shared idempotency seam: insert-only claim + caller work in one transaction, replay on retry, typed in-flight/unknown-outcome answers (#3080) | [agents/run-once.md](agents/run-once.md) |\n| `src/recipe.ts`, `../scanner/src/recipes.ts` | `SmrtRecipe`: declared user-facing units (models, nav, `requires`, curation `options`) collected into manifest and knowledge `recipes` (#3590) | [agents/recipes.md](agents/recipes.md) |\n| `src/browser.ts`, `src/host.ts`, `src/host.browser.ts` | Browser entry that builds and evaluates without Node-only modules: host seam, `package.json#browser` swaps, `pnpm test:browser` (#2838) | [agents/browser-entry.md](agents/browser-entry.md) |\n\n## Cross-module invariants\n\n- `ObjectRegistry` is a `globalThis` singleton so registration survives HMR.\n- Any output that names a database URL (CLI banners, logs, errors) renders it\n with `redactDatabaseUrl` / `redactDatabaseUrlsInText`\n (`src/utils/database-url.ts`, #3527): never the password or query string,\n and never the raw string when it cannot be parsed.\n- Per-class registry work on the hydration path (manifest reconciliation in\n `ensureManifestLoaded()`, the simple-name index behind `findClass()`) is\n memoized per registry generation (`src/registry/generation.ts`, #3047). Any\n new writer of registered classes, their field/method metadata, or loaded\n manifests must go through the tracked maps or call\n `bumpRegistryGeneration()`; `issue-3047-hydration-registry-work.test.ts`\n guards that hydration does not repeat this work per row.\n\n- Production DDL uses manifest generators; `getTestDatabase()` uses registry\n generators. Keep columns, indexes, FK actions, and runtime conflict targets in\n parity (`src/schema/schema-path-parity.test.ts`). Every new query predicate\n needs its index or an explicit reason none is needed.\n- Tenant scoping covers every read and every unique/conflict key. Explicit\n conflict columns are not rewritten; their author must include tenant scope.\n A `tenantId` field makes rows tenant-OWNED without any tenancy declaration:\n the default key leads with `tenant_id`. A new object's natural-key save reads\n the row its upsert would hit and refuses a different owner\n (`TENANT_ISOLATION_VIOLATION`) or adopts a same-owner row's id, so\n `DO UPDATE` never rewrites a primary key or owner. Only an explicit natural\n key adopts: a slug `getSlug()` derived from `name`/`title`/`label` moves to\n a free `-2`, `-3`, … slug and INSERTs. See `agents/schema-paths.md`\n (\"Tenant OWNERSHIP\").\n- Persisted saves use `id` and loaded `updated_at`; new saves use natural keys.\n Preserve revision compare-and-swap ordering through public `save()`,\n `claimRevision()`, and transaction APIs. Embedded saves, deletes, and complete\n `withTransaction()` callbacks share a process-local write queue.\n- Collection model hydration is serial in result order: initialization may query\n the same transaction-bound PostgreSQL client. Use projections for plain rows.\n- Native DuckDB UUIDs must be cast coherently on read before identity reuse;\n custom embedded revision paths use `getCanonicalPersistedRow()`. Never replay\n a mutation to discover result types.\n- `withDatabase(db, callback)` restores only database bindings (including public\n `options.db`); `withTransaction(callback)` also restores identity/revision\n metadata after rollback. Do not use a bound instance concurrently.\n- `runOnce({ db, tenantId, actor, token, content }, work)` (`src/run-once.ts`,\n #3080) claims a key derived from all four inputs — never the token alone,\n which collapses distinct submissions — via `INSERT ... ON CONFLICT\n (claim_key) DO NOTHING RETURNING claim_key` into the hand-DDL\n `_smrt_run_once_claims` system table, and runs `work` in the SAME\n transaction; a completed claim replays its stored result instead of\n re-running, a failed `work` rolls the claim back with the transaction, and\n an unresolved claim raises typed `RunOnceClaimError`\n (`RUN_ONCE_IN_FLIGHT` / `RUN_ONCE_OUTCOME_UNKNOWN`) rather than guessing.\n The claim insert must never raise on conflict: PostgreSQL aborts the whole\n transaction on any raised error, which would take the recovery `SELECT`\n down with it too — this is why it is `DO NOTHING`, not a plain `INSERT`\n caught for `isUniqueViolationError`. Completed claims are bounded by\n `runRetentionSweep()`'s `run-once-claims` task (`system/retention.ts`,\n `DEFAULT_RETENTION_POLICY.runOnceClaims`, default 30 days on\n `completed_at`; `in_progress` rows are never matched) — the window is a\n replay deadline, not just disk hygiene: a token replayed after its claim\n is swept runs `work()` again. See `agents/run-once.md`.\n- `ensureSystemTables(db, typeHint?)` provisions framework tables idempotently;\n call it on a base PostgreSQL connection before caller-owned transactions.\n Bootstrap uses a transaction-scoped advisory lock, taken only when the\n PostgreSQL schema version is not yet stamped: inside a caller's transaction it\n is held until that transaction ends (#2868). Application tables still require migrations;\n runtime table verification checks existence only.\n- Manifest generation fails closed on scanner errors, including unresolved\n decorator spreads. Never emit partial, default-open registration.\n- Generated registration repairs bundled class identity using the exact imported\n constructor, explicit package, and isolated one-object manifest. Never infer\n ownership from paths, simple names, or table names; packages can share names.\n Consumer regression gate: `packages/bundle-gate/src/__tests__/registry-identity.spec.ts`.\n- Decorator registration trusts a class's stack-derived package only when that\n package declares the class (stub, own manifest entry, or explicit\n `packageName`); it then matches the qualified key and never adopts another\n package's same-named registration. Otherwise a loaded (or the cwd project's)\n manifest entry describing the declaring file supplies the identity — apps\n scan workspace-package sources under the app's name (#3110). A class of\n another known package coexists under its qualified key\n (`decorator-different-packages-qualified-coexist`); bundled output needs\n a resolved table that differs first (#3106). Stack\n attribution skips smrt-core (including source-mapped installed\n `smrt-core/src` frames, #3109), decorator-helper, and module-runner frames,\n and drops a frame's Vite `?v=` query (#3490). Library builds stamp each\n decorated class with `static __smrtPackage__` (own property, read at\n decoration as its explicit package) and publish `stampsConstructors`; an\n unstamped class never takes a stamping package's entry by name and table,\n in either order (#3490, `issue-3490-*.test.ts`, `package-stamp.test.ts`).\n Qualified names are `@scope/pkg:Class`; the scope is a deliberate\n discriminator, so manifest generation (`generateManifest`,\n `applyGenerationPasses`, hence `pnpm build`) throws\n `CONFIG_UNSCOPED_PACKAGE_NAME` for an unscoped `package.json` name (#3408).\n Instance and collection registry lookups pass the qualified name. The schema\n planner rejects a table claimed by two unrelated classes\n (`CONFIG_TABLE_NAME_COLLISION`): only one STI family shares a table (#3098);\n collections (including `SmrtReportCollection`) never claim one. Consumer\n gates: `registry/__tests__/issue-3110-*.test.ts`, `issue-3109-*.test.ts`,\n `packages/bundle-gate/src/__tests__/consumer-same-name.spec.ts`.\n- API custom-action eligibility has ONE resolver, `resolveApiMethodExposure()`\n in `generators/custom-action.ts`: both SvelteKit route emitters,\n `resolveApiActionSet`, and `knowledge.ts` read it, and a new consumer must too\n — a local mirror is how a method gets reported unavailable while its route\n file is still written. A public method routes by default only when every\n parameter is JSON-shaped; `@method({ expose })` overrides in both directions,\n `expose: true` bypasses the heuristic ALONE, and an explicit `api.include` or\n `api.routes` entry keeps its pre-#2686 route. Fail closed on scanner\n uncertainty: read `parameters[].typeUnresolved`, never the `'any'` it\n substitutes. Accepting `Date` as wire-able and hydrating it\n (`toCustomActionDate`) are one decision — changing either breaks the other.\n The runtime `APIGenerator` transport stays declaration-gated: `rest.ts`\n dispatch and `preflight-route.ts` prediction both read\n `declaresRuntimeRestRoute()`, which must accept every `ApiCustomRouteConfig`\n option so a sweep moving one onto its method cannot delete the endpoint. Its\n twin `declaresRuntimeRestRouteShape()` deliberately ignores `expose: false`:\n the dispatcher must still SEE a withheld declaration to answer 404, because\n `POST /<collection>/<segment>` resolves to `create` when nothing claims the\n segment. Split unions and type arguments with `splitTopLevel()` — a naive\n `split('|')` truncates `Record<string, Asset | null>` into fragments that\n match no rule and are then accepted, widening the gate. `extractTypeName`\n returns `null` for a generic with an unresolvable ARGUMENT or a union with an\n unresolvable BRANCH so those reach that fail-closed path instead of arriving\n as a bare `'Array'`. Runtime transports read\n `ObjectRegistry.resolveRuntimeMethod()`, which tries the item class's manifest\n entry, then the COLLECTION class's (where a collection-hosted action's\n parameters live), then the live `@method()` store — keyed by CONSTRUCTOR,\n never by simple name (`Account` exists in two packages), and recording\n `isStatic` because an unscanned runtime has no manifest to recover the\n receiver from. `isRestActionRoutable` ANDs \"declared\" with that receiver, so\n it never predicts `allow` for an action dispatch refuses. A declared action\n with no receiver is refused (501 collection-scoped, 404 item-scoped), never\n allowed to fall through into `create`. All eight consumers read the resolver,\n including `packages/smrt-workbench/src/discovery.ts`; it imports the\n `./generators/custom-action` LEAF subpath, not `./generators`, because that\n barrel value-re-exports `MCPGenerator` and so drags `@happyvertical/ai` and\n `@happyvertical/sql` into a build-time helper (2 modules vs 109). Keep\n `custom-action.ts` free of value imports outside `tools/tool-generator`.\n\n## Gotchas\n\n- Optional filesystem support stays lazy: use `createFilesystemAdapter()` in\n `src/filesystem-loader.ts`, not a static files-SDK import. Fully bundled apps\n import `@happyvertical/smrt-core/filesystem` at startup. Use\n `importOptionalDependency()` for similarly heavy optional dependencies.\n- `src/browser.ts` is the `browser`-condition entry of the package root: the\n Node entry (`index.ts`) minus HTTP servers, manifest/knowledge discovery, run-once,\n the Vite plugin, and the test helper. A new export added to `index.ts` must also\n go to `browser.ts` unless it is Node-only; `src/__tests__/browser-entry-parity.test.ts`\n fails otherwise (allowlist: `NODE_ONLY_GROUPS` in that test, each with a reason; the browser\n entry may not publish a name the Node entry lacks), and also\n fails when a workspace package imports a root value the browser entry lacks.\n- `exports['.'].browser` (`dist/browser.js`) is the browser surface. Model\n package roots are bundled for browsers by the bundle-gate browser fixture\n (#3621): anything a model root imports from core must be exported by the\n browser entry and must not reach `node:` built-ins, `pg`, `cosmiconfig`, or\n `jiti`. Keep Node-only code behind a subpath or a lazy import; when a fix\n makes a package pass, delete its entry in\n `packages/bundle-gate/src/browser-gate/expected-failures.ts`.\n- Database retries are transient-only, four attempts total for `get`/`upsert`.\n Use `src/db-errors.ts` classifiers through the cause chain, never message\n matching (SDK driver text can live in `context.originalError`). Constraints,\n bad input, missing tables, and aborted PostgreSQL transactions fail immediately.\n Unique/PK violations become `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL becomes\n `VALIDATION_REQUIRED_FIELD`; other failures keep the driver error as `cause`.\n- Property initializers precede option values; options win. Arrays/objects are\n shallow-cloned. Collection creation caches fields; table verification caches\n by DB URL and table. Preserve these scopes when changing initialization.\n- The Vite plugin loads scanner/schema code from `dist/` when present. Rebuild\n core after editing those sources before testing consumer manifest generation.\n Vite 8 requires `oxc.decorator: { legacy: true, emitDecoratorMetadata: true }`.\n\n## Validation\n\n`typecheck` checks production source first, then the test project in\n`tsconfig.test.json`. Test coverage and the shared relaxed config\ncontract are documented in [agents/test-types.md](agents/test-types.md).\n\nRun focused tests first, then applicable package checks:\n\n```bash\npnpm --filter @happyvertical/smrt-core test\npnpm --filter @happyvertical/smrt-core typecheck\npnpm --filter @happyvertical/smrt-core build\npnpm --filter @happyvertical/smrt-core test:postgres\npnpm check:agents-chain\npnpm smrt dev:knowledge-check\n```\n\nThe PostgreSQL lane is required for numeric types, UUID casts, conflict targets,\ntimestamps, and migrations. Tests generate their manifest before Vitest; restart\nwatch mode after adding decorated classes. Documentation-only changes need\ninstruction-chain and knowledge freshness checks, not the runtime test suite.\n",
1131
1134
  "moduleDocs": [
1132
1135
  {
1133
1136
  "path": "agents/object-runtime.md",
@@ -1137,7 +1140,7 @@
1137
1140
  {
1138
1141
  "path": "agents/revision-guard.md",
1139
1142
  "module": "revision-guard",
1140
- "content": "# Revision compare-and-swap guard (`src/revision-guard.ts`)\n\nEvery persisted `save()` pins its `UPDATE` to the revision the writer loaded;\n`claimRevision()` does the same without running domain hooks, and\n`delete({ expectedUpdatedAt })` binds the same predicate into its final\n`DELETE`. Zero affected rows raises `RUNTIME_REVISION_CONFLICT` rather than\noverwriting or removing a newer row.\n\n## Why the predicate is not an equality (#2620)\n\nThe guard used to compare `updated_at` to `loadedRevision.toISOString()`. On\nPostgreSQL a JavaScript `Date` is two lossy conversions away from the stored\nvalue, so that predicate matched no row at all in two common situations — and\nthe object then conflicted on *every* later save, permanently, rather than\nlosing a race:\n\n- **Precision.** `updated_at` is a microsecond column. Any row last written by\n raw SQL — `updated_at = CURRENT_TIMESTAMP` / `now()`, including SMRT's own\n migration backfills — carries a sub-millisecond tail a `Date` cannot hold.\n- **Process timezone.** Schemas created before the `TIMESTAMPTZ` mapping still\n hold `updated_at` as `timestamp WITHOUT time zone`, and `pg` hydrates that\n type in the process zone, so on a non-UTC host `toISOString()` renders a wall\n clock the row never held. The same columns are written under three different\n conventions — `pg` serializes a bound `Date` in the process zone,\n `claimRevision()` writes a UTC ISO string, and raw `CURRENT_TIMESTAMP` writes\n in the *server* zone — so no single rendering can match every row.\n\n## What the predicate does instead\n\n`postgresRevisionCondition()` builds\n`date_trunc('milliseconds', updated_at) IN (…)` over both wall-clock renderings\nof the revision, the process-zone one and the UTC one, each tagged `+00` so a\n`timestamptz` comparison honours it and a `timestamp` comparison discards it —\nthe predicate therefore does not depend on the *session* TimeZone either. On a\nUTC process the two renderings coincide and the condition is single-valued.\n\nLost-race semantics are preserved: a concurrent writer advances `updated_at` to\nroughly \"now\", so it must land on the loaded revision — or, on a non-UTC\nprocess only, on that revision shifted by the whole UTC offset — to the\nmillisecond before it could slip past. Collapsing that second rendering so the\npredicate is single-valued on every process is tracked as #2623.\n\n## Rules\n\n- Never rebuild this predicate by hand; call `postgresRevisionCondition()`.\n Every guarded write — `save()`, `claimRevision()`, and the guarded `DELETE` —\n goes through `SmrtObject.revisionPredicate()` so no path is left on the exact\n equality.\n- The condition is PostgreSQL-only. Embedded engines take the process-local\n compare/upsert fallback (`usesEmbeddedRevisionFallback`), and remote LibSQL\n stores ISO text whose exact equality round-trips losslessly.\n- Custom write paths must go through `save()`, `save({ expectedUpdatedAt })`,\n or `claimRevision()` rather than bypassing the CAS ordering contract.\n- The driver-layer half — `pg` hydrating and serializing `timestamp` columns in\n the process zone — is tracked as happyvertical/sdk#1223. The guard\n deliberately assumes neither hydration convention, so a UTC-hydration fix\n there cannot break it.\n\n## Coverage\n\n`src/__tests__/issue-2620-revision-guard-precision-postgres.optional.test.ts`\nruns the whole battery — guarded save, `save({ expectedUpdatedAt })`,\n`claimRevision()`, guarded delete, and their still-conflicts counterparts —\nagainst both `updated_at` column shapes in the registered PostgreSQL suite (`pnpm --filter @happyvertical/smrt-core\ntest:postgres`). `src/__tests__/revision-guard.test.ts` covers the rendering\nitself in the default suite.\n"
1143
+ "content": "# Revision compare-and-swap guard (`src/revision-guard.ts`, `src/unchanged-indexed.ts`)\n\nEvery persisted `save()` pins its `UPDATE` to the revision the writer loaded;\n`claimRevision()` does the same without running domain hooks, and\n`delete({ expectedUpdatedAt })` binds the same predicate into its final\n`DELETE`. Zero affected rows raises `RUNTIME_REVISION_CONFLICT` rather than\noverwriting or removing a newer row.\n\n## Why the predicate is not an equality (#2620)\n\nThe guard used to compare `updated_at` to `loadedRevision.toISOString()`. On\nPostgreSQL a JavaScript `Date` is two lossy conversions away from the stored\nvalue, so that predicate matched no row at all in two common situations — and\nthe object then conflicted on *every* later save, permanently, rather than\nlosing a race:\n\n- **Precision.** `updated_at` is a microsecond column. Any row last written by\n raw SQL — `updated_at = CURRENT_TIMESTAMP` / `now()`, including SMRT's own\n migration backfills — carries a sub-millisecond tail a `Date` cannot hold.\n- **Process timezone.** Schemas created before the `TIMESTAMPTZ` mapping still\n hold `updated_at` as `timestamp WITHOUT time zone`, and `pg` hydrates that\n type in the process zone, so on a non-UTC host `toISOString()` renders a wall\n clock the row never held. The same columns are written under three different\n conventions — `pg` serializes a bound `Date` in the process zone,\n `claimRevision()` writes a UTC ISO string, and raw `CURRENT_TIMESTAMP` writes\n in the *server* zone — so no single rendering can match every row.\n\n## What the predicate does instead\n\n`postgresRevisionCondition()` builds\n`date_trunc('milliseconds', updated_at) IN (…)` over both wall-clock renderings\nof the revision, the process-zone one and the UTC one, each tagged `+00` so a\n`timestamptz` comparison honours it and a `timestamp` comparison discards it —\nthe predicate therefore does not depend on the *session* TimeZone either. On a\nUTC process the two renderings coincide and the condition is single-valued.\n\nLost-race semantics are preserved: a concurrent writer advances `updated_at` to\nroughly \"now\", so it must land on the loaded revision — or, on a non-UTC\nprocess only, on that revision shifted by the whole UTC offset — to the\nmillisecond before it could slip past. Collapsing that second rendering so the\npredicate is single-valued on every process is tracked as #2623.\n\n## Rules\n\n- Never rebuild this predicate by hand; call `postgresRevisionCondition()`.\n Every guarded write — `save()`, `claimRevision()`, and the guarded `DELETE` —\n goes through `SmrtObject.revisionPredicate()` so no path is left on the exact\n equality.\n- The condition is PostgreSQL-only. Embedded engines take the process-local\n compare/upsert fallback (`usesEmbeddedRevisionFallback`), and remote LibSQL\n stores ISO text whose exact equality round-trips losslessly.\n- Custom write paths must go through `save()`, `save({ expectedUpdatedAt })`,\n or `claimRevision()` rather than bypassing the CAS ordering contract.\n- The driver-layer half — `pg` hydrating and serializing `timestamp` columns in\n the process zone — is tracked as happyvertical/sdk#1223. The guard\n deliberately assumes neither hydration convention, so a UTC-hydration fix\n there cannot break it.\n\n## Coverage\n\n`src/__tests__/issue-2620-revision-guard-precision-postgres.optional.test.ts`\nruns the whole battery — guarded save, `save({ expectedUpdatedAt })`,\n`claimRevision()`, guarded delete, and their still-conflicts counterparts —\nagainst both `updated_at` column shapes in the registered PostgreSQL suite (`pnpm --filter @happyvertical/smrt-core\ntest:postgres`). `src/__tests__/revision-guard.test.ts` covers the rendering\nitself in the default suite.\n\n## Unchanged indexed columns on referenced DuckDB rows (#3737)\n\nNative DuckDB rewrites a row (delete + insert) when an *indexed* column is\nassigned, even to its current value, and a foreign key that still references\nthe row then rejects the statement. `save()` serializes the whole model, so\ntoggling one plain field of a referenced parent used to assign `slug`,\n`context`, `tenant_id` and `created_at` unchanged and fail. Unchanged indexed\ncolumns are therefore left out of the write:\n\n- **Where.** Only POSITIVELY native DuckDB (`isPositivelyNativeDuckDb()`: not the\n JSON adapter, which shares the DuckDB client and dialect but persists to\n `<table>.json` only from its own insert/update/upsert/delete, so a raw write\n would be lost on the next process). Identification (`src/native-duckdb.ts`)\n is deterministic: a root is native by structure (`getTableSchema`, no\n JSON-only capability, or an explicit `duckdb` hint), and a transaction\n handle, which carries only the root's `client`, is recognized through the\n root core noted before binding it (`initialize()`, `withDatabase()`,\n `withEmbeddedWriteTransaction()`). A transaction handle of a root core never\n saw stays unidentified and keeps the adapter `upsert`. It applies to the three\n existing-row writers only: the embedded revision write in `save()`\n (`writeEmbeddedRevisionRow`), a new object's natural-key save that adopts an\n existing row (`writeNaturalKeyUpsert`), and `claimRevision()`, which assigns\n only `updated_at`. SQLite and PostgreSQL keep writing exactly what they\n wrote, because they handle an unchanged key harmlessly.\n- **Which columns.** `collectIndexedColumns()`: primary key, `unique`, foreign\n keys, every declared index column (partial and JSON-path included), plus the\n runtime keys `slug`, `context`, `tenant_id`, the conflict columns and the\n ownership columns, for the class and its STI base. Over-inclusive is\n harmless: a column is only skipped when it is also *proven* unchanged. An\n index created outside the registry schema (a hand-written migration) is not\n known and keeps being assigned.\n- **Proof of \"unchanged\".** The stored row is read under the embedded write\n queue after its `updated_at` matched the loaded revision (or, for an adopted\n row, as read for the owner check), through `getCanonicalPersistedRow()` so\n native UUIDs are text. `storedValueEquals()` then compares by column type:\n text exactly, UUIDs case-insensitively, timestamps as instants (a string\n must carry its zone), JSON structurally, booleans and numbers by value;\n `null`/`undefined` match each other, never `''`. Binary values, unzoned\n timestamp strings and anything of a different type are *not* equal. An\n indexed timestamp is proven against the stored value read as text\n (`CAST(col AS VARCHAR)`), at microsecond precision: a hydrated `Date` has\n already lost sub-millisecond digits, so `.678901` stored versus `.678`\n requested is a change and is written. JSON text is only proven when every\n number literal outside its strings round-trips through a double exactly\n (`jsonNumbersRoundTrip()`): `9007199254740993` and `9007199254740992` parse\n to the same double, so text holding an unsafe integer, more digits than a\n double holds, or a non-canonical form such as `1.0`/`1e2` is unprovable and\n assigned. A `bigint` and a `number` compare exactly (`==`), never through a\n double. Any doubt means \"assign it as before\". `id` and `updated_at` are always written.\n- **How.** The adapter's `upsert` cannot restrict its `DO UPDATE SET`, and its\n generic `update()` neither quotes column names (a column named `order` is a\n syntax error) nor binds dates and structures. So the remaining columns go\n through one id-targeted `UPDATE` that core renders itself\n (`buildDuckDbIdUpdate`): every identifier quoted, values bound as the DuckDB\n `upsert` binds them (`NULL` literals, `''` as `CAST(? AS TEXT)`, ISO dates,\n `CAST(? AS JSON)` text). The revision was already verified in-process, so the\n statement carries no revision predicate. Its affected-row count must be\n reported by the driver; an absent or non-numeric count raises\n `RUNTIME_INVALID_STATE` (never retried) instead of reading as success. When nothing is provably unchanged\n the plain `upsert` runs as before.\n- **A changed indexed column is still assigned** and DuckDB still refuses it\n for a referenced parent (a real key change). Tenant isolation is untouched:\n `beforeSave` interceptors and the natural-key owner check run before the\n write, and a differing `tenant_id` is never \"unchanged\".\n\nCoverage: `src/__tests__/unchanged-indexed.test.ts` (the pure decisions),\n`src/__tests__/issue-3737-unchanged-indexed.optional.test.ts` (SQLite, DuckDB\nand, with `SMRT_TEST_POSTGRES_URL`, PostgreSQL against a real referencing\nchild), and `packages/tenancy/src/__tests__/issue-3737-referenced-parent-duckdb.test.ts`\n(the real tenant stack).\n"
1141
1144
  },
1142
1145
  {
1143
1146
  "path": "agents/collection-reads.md",
@@ -1177,7 +1180,7 @@
1177
1180
  {
1178
1181
  "path": "agents/build-knowledge.md",
1179
1182
  "module": "build-knowledge",
1180
- "content": "# Decorators, build integration, and knowledge\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes; see [schema-paths.md](schema-paths.md)), `api`/`mcp`/`cli` (generation config), `ai` (callable methods), `hooks` (beforeSave/afterSave/beforeDelete/afterDelete), `embeddings` (auto-generate), `tenantScoped`, `agent`, `ui` (`{ icon, label, description }` — nav/help hints round-tripped through the manifest as plain data; `description` is the object-level seed for form-level help, #2046).\n\nRegistration sets `SMRT_TABLE_NAME` static property (survives minification).\n\n## @field() UI hints (#2046)\n\n`@field({ ui: { basic, group, order, locked } })` — a static, presentation-only\nseed for the field-policy rail (epic #2045). Carried in the manifest under the\nfield's `_meta.ui` (never a top-level `FieldDefinition` key), readable at\nruntime via `getAllFields()` at `field._meta.ui`, and emitted (sanitized) with\n`description` into generated web-collection definitions and browser MCP tool\nschemas. No schema/persistence/security effect — `sensitive`/`readPermission`\nstay the security rail, and `sensitive`/`transient` fields never emit to the\nclient at all.\n\n`ui.widget` (#3599) adds a presentation widget hint:\n`'textarea' | 'currency' | 'email' | 'url' | 'phone'`. It rides the same\n`_meta.ui` channel and is also emitted (sanitized) into web-collection\ndefinitions. The manifest generator validates it against the field type and\nfails the build otherwise: every widget needs a `text` field (`currency` is a\ncurrency-CODE picker for an ISO 4217 string such as `currency = 'USD'`, not a\nmoney amount; amounts are integer minor units and take no widget); an unknown\nvalue or a non-text field is an error. `ui.widget` is a hint only — it never changes\nthe column type or validation.\n\n## Presentation metadata (#3599)\n\nPure helpers live in `src/ui-metadata.ts`, published browser-safe as\n`@happyvertical/smrt-core/ui-metadata` (also re-exported from the package\nroot). `ManifestGenerator.applyUiMetadata()` runs in `applyGenerationPasses`\nafter inheritance, so every producer (Vite plugin, `ManifestBuilder`,\n`generateManifest`) validates the same way.\n\n- **Display label.** `@smrt({ display: { label: '<field>' } })` names the own\n field generic pickers and assistants use to label a record. Own fields only —\n no paths into other packages; a model whose label lives elsewhere ships a\n selector. Undeclared, it defaults to the first of `name`, `title`, `label`,\n `code` that is a usable own field. Build fails when the declared field is\n missing, `sensitive`, `transient`, or a relationship/json field. The resolved\n field is emitted as `displayLabelField` on the manifest object and in the\n knowledge artifact, and generated MCP/WebMCP `list`/`get`/`update`/`delete`\n descriptions end with ``Records are identified by their `<field>` field.``\n (`describeAction` in `generators/tool-schema.ts`; nothing is added when the\n model has no label field).\n- **Selector slots.** `ModuleUISlot.selects: '@scope/pkg:Model'`\n (`@happyvertical/smrt-types`) marks a package component as THE selector for a\n model. The scanner reads such slots statically from `src/**/ui.ts`\n (`parseUiSelectorsFile`, independent of the class glob) and the manifest\n carries them as `uiSelectors` keyed by slot id. `selects` must be a string\n literal; a duplicate slot id, two selectors for one model, or an own-package\n target that does not exist fails the build. Hosts call\n `findSelectorFor(manifests, qualifiedName)`; generic forms use the selector\n for any `@foreignKey`/`@crossPackageRef` field targeting that model and fall\n back to a generic picker labelled by `displayLabelField`. `display` is read\n per class: an STI subclass that declares none uses the default lookup rather\n than its base's declaration, and a CTI child cannot name a parent's field.\n\n## Worker registration artifact (#3117)\n\nWith `svelteKit.enabled`, a production `vite build` compiles the generated\n`smrt-register.ts` into `.smrt/runtime/register.js` after the server build\n(`src/vite-plugin/worker-registration.ts`, called once from `closeBundle`).\nadapter-node re-bundles the server from its own entries, so the web bundle is\nnever importable by a separate Node process; this artifact is how a deployed\ntask/schedule worker registers the app's local objects (and, through the\n`.smrt/register.js` it imports, consumed packages' objects) with the same\nqualified identities and isolated manifests as the web server. It is a nested\nSSR build with no consumer plugins: only aliases pointing into the project\nsources (e.g. `$lib`) apply, and every other bare import stays external so the\nworker shares the installed `@happyvertical/smrt-core` registry. SvelteKit\nvirtual modules (`$env/*`, `$app/*`) are not available to a worker; an object\nimporting one fails at worker startup. A failure fails the build.\n\n## Lightweight discovery\n\nFilesystem-only discovery, module-doc parsing, and graph freshness are owned by\n`@happyvertical/smrt-scanner/knowledge`. Core's knowledge exports remain compatible\nreexports. Runtime manifest projection and custom-action semantics stay in core.\n\n`src/knowledge-discovery.ts`, exported through `smrt-core/knowledge`, enumerates\ninstalled scope directories and reads canonical AGENTS/legacy CLAUDE docs without\nloading package code, artifacts, or scanning objects. CLI snapshots and MCP share\nthese primitives. Callers retain selection policy: snapshots resolve links and\nfall back to `packages/*` only when no installed SMRT package loads; MCP preserves\nnode_modules paths, deduplicates realpaths, excludes authored workspace links,\nand then enriches the selected packages. Workspace-root/glob discovery remains\nowned by each consumer.\n\n## Domain Knowledge Artifacts\n\n`smrtPlugin()` writes runtime manifests and agent/developer knowledge artifacts:\n\n- local dev/build: `.smrt/manifest.json` and `.smrt/smrt-knowledge.json`\n- package build: `dist/manifest.json` and `dist/smrt-knowledge.json`\n\nKeep `manifest.json` runtime-focused. `smrt-knowledge.json` is the deterministic\nagent contract for downstream review and architecture tools.\n\nThe CLI's schema-command gate reads that same merged file: a pure-consumer\nproject (0 local objects) qualifies on the consumed packages its manifest\nrecords, so a clobbered `objects` map is what made `smrt db:migrate` report\n`missing_local_manifest` (#2925).\n\n`.smrt/manifest.json` has two writers and neither owns all of it: `smrtPlugin()`\ncontributes the project's scanned objects and `smrtConsumer()` the consumed\npackages' entries. Both writes are merge-preserving, keyed on each entry's\nrecorded `packageName` — a plain overwrite in either direction silently drops\nthe other's objects, and the last pass of a multi-environment build is not\nreliably the aggregating one (#1760, #2925). `dist/manifest.json` stays\nlocal-only: a published package must not carry its dependencies' objects.\n\nThe schema-version-1 object projection is additive and high-signal: it retains\nnormalized tenant mode/field, explicit `cti`/`sti` strategy, conflict columns,\nmethod signatures, and field defaults/constraints/readonly/transient flags.\nSensitive fields are removed before both `fields` and `relationships` are\nderived, including legacy flags stored under `_meta`; matching field and\nsnake-case column names are also removed from projected conflict columns, and a\nsensitive custom tenant field is omitted while retaining scope and mode.\nGenerated artifacts assert this boundary with `sensitiveFieldsExcluded: true`;\nthe optional marker keeps schema version 1 additive while letting readers\nidentify older artifacts that require raw-manifest corroboration.\n\nConfig precedence for knowledge is defaults → top-level `knowledge` in\n`smrt.config.ts` → `packages[packageName].knowledge` → plugin option →\nobject-level `@smrt({ knowledge })`.\n\nTest generation uses that same effective configuration and publishes knowledge\nmatching the manifest it generated. Disabling knowledge removes a previous local\nknowledge artifact, so consumers cannot mistake it for current enabled output.\n`new ManifestBuilder(projectRoot)` keeps discovery, package identity, and output\nat that explicit root, including installed providers and external base classes;\nomitting the argument retains the current-working-directory\nbehavior. Both manifest writers retain declared package dependencies when merging\ntheir local and consumed-object projections.\n\nTest manifests carry optional `artifactPurpose: 'test'`; dependency discovery\nskips those artifacts, including `.smrt` fallbacks. Unmarked runtime manifests,\nempty published providers, and source-only development providers remain eligible.\n`ManifestBuilder` accepts explicit `outputMode: 'dev' | 'build'`; omitted mode\nretains legacy filename inference. Vitest selects dev mode explicitly, so tests\nnever replace a production `dist/manifest.json`. Relative output directories are\nresolved against the builder's project root.\n\nWith `svelteKit.enabled`, `smrtPlugin()`'s transform prepends\n`import './smrt-register.js';` to the configured config module\n(`<configPath>/<configFileName>`, `src/vite-plugin/sveltekit-register-injection.ts`)\nonce the register module exists, on the same first line so line numbers hold.\nApps therefore never hand-write the guarded registration import (#3416); a\nconfig module that still has it imports the same module twice, harmlessly.\n\nTracked `src/lib/server/smrt-register.ts` belongs to SvelteKit config/type\ngeneration. Generic library builds consume it but do not cache or restore it\nas an output; otherwise a concurrent config producer's bytes can be replayed\nover a newer registration after dependency eligibility changes.\n\nObject-level `knowledge: false` excludes an object from authored context only;\nit must not change runtime manifest registration. Use\n`knowledge: { tags, summary, risks }` for review-sensitive domain objects.\n\nHTTP knowledge routes are disabled by default. If `knowledge.api.enabled` is\ntrue, generated SvelteKit routes must stay GET-only and guarded by dev mode or\nadmin auth.\n\n\n## Vite Plugin\n\n`src/vite-preset/` (`@happyvertical/smrt-core/vite`, `smrt()`) composes the Oxc\ndecorator block, `smrtConsumer`, then `smrtPlugin` with the template path\nconventions. Its package list comes only from the `smrt({ packages })` option, or\n`smrt.config` `consumer.packages` (smrt-config schema); it never sniffs\n`package.json`, and a missing or malformed list throws. Keep its output\nbyte-identical to the two-plugin form (`src/vite-preset/index.test.ts`). It\nalso dedupes `@sveltejs/kit` (`smrt:shared-runtime`): SvelteKit matches\n`redirect()`/`fail()` by class, and a linked/workspace SMRT SvelteKit entry\nwould otherwise import its own copy and turn redirects into 500s.\n\n```typescript\n// vite.config.ts — required for @smrt() decorators (Vite 8+, oxc transform)\nexport default defineConfig({\n oxc: {\n decorator: {\n legacy: true,\n emitDecoratorMetadata: true,\n },\n },\n});\n```\n\nUnder Vite 8 the oxc transform does not honor the pre-Vite-8 `esbuild.tsconfigRaw`\nrecipe (or tsconfig `experimentalDecorators` reached through SvelteKit's\n`extends \"./.svelte-kit/tsconfig.json\"` chain), so that recipe throws\n`SyntaxError: Invalid or unexpected token` on the first SSR request. Configure\ndecorators through `oxc.decorator` instead. Consumers still pinned on vite<8 need\nthe legacy `esbuild.tsconfigRaw` form with `experimentalDecorators: true,\nemitDecoratorMetadata: true`.\n\nFor independent CI invocations, both `smrtPlugin()` and `smrtConsumer()` accept\nthe same `generationSnapshot: { path, sha256, provenance, sourceRoot }`. The\nschema-v1 snapshot produced by `serializeSmrtGenerationSnapshot()` contains the\nmerged project/dependency manifest, portable source paths, and source-file\ndigests; each plugin selects its own view. Reuse mode fails closed on\nbyte/provenance/path/content drift, skips scans and manifest writes, and still\ngenerates routes, types, registration, and virtual modules. Omit it for normal\nlocal development and watch mode.\n\n## Clean consumer type checks (TypeScript 6)\n\nThe consumer config hook writes `.smrt/register.js` alongside generated types\nafter route preflight succeeds. Generated SvelteKit registration imports that\nmodule, so it must exist during `svelte-kit sync`, before Vite's `buildStart`.\nBoth hosted routes and the legacy `svelteKit: true` mode follow this order.\nThe clean-consumer regression fixture ships real provider declarations and\nchecks the generated imports with `svelte-check`.\nCore's `generate:test` task depends on its own `build`: both publish the local\n`.smrt` manifest/knowledge pair, so Turbo must serialize production before test\ngeneration instead of caching an interleaved pair.\n\n## Model descriptions\n\nEach manifest object and knowledge `objects[]` entry may carry a user-facing\n`description` (for the planner Features tab and similar). The scanner\n(`extractClassJsDocDescription` in `packages/scanner/src/oxc-parser.ts`) reads it\nfrom the parsed source, in priority order: explicit `@smrt({ description })`,\nelse the first paragraph of the class JSDoc (the JSDoc may sit above `export`\nand decorators), minus a leading `ClassName - ` / `ClassName: `, tags\n(`{@link}`, backticks, HTML) and later paragraphs, capped at 200 chars on a\nsentence boundary. `@internal` classes and classes without docs emit no key. It\nis not inherited from a parent class. Generated MCP tool descriptions are\nunchanged (they stay generic).\n"
1183
+ "content": "# Decorators, build integration, and knowledge\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes; see [schema-paths.md](schema-paths.md)), `api`/`mcp`/`cli` (generation config), `ai` (callable methods), `hooks` (beforeSave/afterSave/beforeDelete/afterDelete), `embeddings` (auto-generate), `tenantScoped`, `agent`, `ui` (`{ icon, label, description }` — nav/help hints round-tripped through the manifest as plain data; `description` is the object-level seed for form-level help, #2046).\n\nRegistration sets `SMRT_TABLE_NAME` static property (survives minification).\n\nAn explicit `@smrt({ collection: 'domain.records' })` names the route/permission\nnamespace independently of `tableName`, including standalone non-STI models.\nScanner output preserves it in both `collection` and `decoratorConfig.collection`.\nGenerated registration reads the merged declaration, so older manifests with a\nderived top-level collection still agree with native decorators. Explicit runtime\nregistration options win; absent declarations retain manifest/STI/default naming.\n\n## @field() UI hints (#2046)\n\n`@field({ ui: { basic, group, order, locked } })` — a static, presentation-only\nseed for the field-policy rail (epic #2045). Carried in the manifest under the\nfield's `_meta.ui` (never a top-level `FieldDefinition` key), readable at\nruntime via `getAllFields()` at `field._meta.ui`, and emitted (sanitized) with\n`description` into generated web-collection definitions and browser MCP tool\nschemas. No schema/persistence/security effect — `sensitive`/`readPermission`\nstay the security rail, and `sensitive`/`transient` fields never emit to the\nclient at all.\n\n`ui.widget` (#3599) adds a presentation widget hint:\n`'textarea' | 'currency' | 'email' | 'url' | 'phone'`. It rides the same\n`_meta.ui` channel and is also emitted (sanitized) into web-collection\ndefinitions. The manifest generator validates it against the field type and\nfails the build otherwise: every widget needs a `text` field (`currency` is a\ncurrency-CODE picker for an ISO 4217 string such as `currency = 'USD'`, not a\nmoney amount; amounts are integer minor units and take no widget); an unknown\nvalue or a non-text field is an error. `ui.widget` is a hint only — it never changes\nthe column type or validation.\n\n## Presentation metadata (#3599)\n\nPure helpers live in `src/ui-metadata.ts`, published browser-safe as\n`@happyvertical/smrt-core/ui-metadata` (also re-exported from the package\nroot). `ManifestGenerator.applyUiMetadata()` runs in `applyGenerationPasses`\nafter inheritance, so every producer (Vite plugin, `ManifestBuilder`,\n`generateManifest`) validates the same way.\n\n- **Display label.** `@smrt({ display: { label: '<field>' } })` names the own\n field generic pickers and assistants use to label a record. Own fields only —\n no paths into other packages; a model whose label lives elsewhere ships a\n selector. Undeclared, it defaults to the first of `name`, `title`, `label`,\n `code` that is a usable own field. Build fails when the declared field is\n missing, `sensitive`, `transient`, or a relationship/json field. The resolved\n field is emitted as `displayLabelField` on the manifest object and in the\n knowledge artifact, and generated MCP/WebMCP `list`/`get`/`update`/`delete`\n descriptions end with ``Records are identified by their `<field>` field.``\n (`describeAction` in `generators/tool-schema.ts`; nothing is added when the\n model has no label field).\n- **Selector slots.** `ModuleUISlot.selects: '@scope/pkg:Model'`\n (`@happyvertical/smrt-types`) marks a package component as THE selector for a\n model. The scanner reads such slots statically from `src/**/ui.ts`\n (`parseUiSelectorsFile`, independent of the class glob) and the manifest\n carries them as `uiSelectors` keyed by slot id. `selects` must be a string\n literal; a duplicate slot id, two selectors for one model, or an own-package\n target that does not exist fails the build. Hosts call\n `findSelectorFor(manifests, qualifiedName)`; generic forms use the selector\n for any `@foreignKey`/`@crossPackageRef` field targeting that model and fall\n back to a generic picker labelled by `displayLabelField`. `display` is read\n per class: an STI subclass that declares none uses the default lookup rather\n than its base's declaration, and a CTI child cannot name a parent's field.\n\n## Worker registration artifact (#3117)\n\nWith `svelteKit.enabled`, a production `vite build` compiles the generated\n`smrt-register.ts` into `.smrt/runtime/register.js` after the server build\n(`src/vite-plugin/worker-registration.ts`, called once from `closeBundle`).\nadapter-node re-bundles the server from its own entries, so the web bundle is\nnever importable by a separate Node process; this artifact is how a deployed\ntask/schedule worker registers the app's local objects (and, through the\n`.smrt/register.js` it imports, consumed packages' objects) with the same\nqualified identities and isolated manifests as the web server. It is a nested\nSSR build with no consumer plugins: only aliases pointing into the project\nsources (e.g. `$lib`) apply, and every other bare import stays external so the\nworker shares the installed `@happyvertical/smrt-core` registry. SvelteKit\nvirtual modules (`$env/*`, `$app/*`) are not available to a worker; an object\nimporting one fails at worker startup. A failure fails the build.\n\n## Lightweight discovery\n\nFilesystem-only discovery, module-doc parsing, and graph freshness are owned by\n`@happyvertical/smrt-scanner/knowledge`. Core's knowledge exports remain compatible\nreexports. Runtime manifest projection and custom-action semantics stay in core.\n\n`src/knowledge-discovery.ts`, exported through `smrt-core/knowledge`, enumerates\ninstalled scope directories and reads canonical AGENTS/legacy CLAUDE docs without\nloading package code, artifacts, or scanning objects. CLI snapshots and MCP share\nthese primitives. Callers retain selection policy: snapshots resolve links and\nfall back to `packages/*` only when no installed SMRT package loads; MCP preserves\nnode_modules paths, deduplicates realpaths, excludes authored workspace links,\nand then enriches the selected packages. Workspace-root/glob discovery remains\nowned by each consumer.\n\n## Domain Knowledge Artifacts\n\n`smrtPlugin()` writes runtime manifests and agent/developer knowledge artifacts:\n\n- local dev/build: `.smrt/manifest.json` and `.smrt/smrt-knowledge.json`\n- package build: `dist/manifest.json` and `dist/smrt-knowledge.json`\n\nKeep `manifest.json` runtime-focused. `smrt-knowledge.json` is the deterministic\nagent contract for downstream review and architecture tools.\n\nThe CLI's schema-command gate reads that same merged file: a pure-consumer\nproject (0 local objects) qualifies on the consumed packages its manifest\nrecords, so a clobbered `objects` map is what made `smrt db:migrate` report\n`missing_local_manifest` (#2925).\n\n`.smrt/manifest.json` has two writers and neither owns all of it: `smrtPlugin()`\ncontributes the project's scanned objects and `smrtConsumer()` the consumed\npackages' entries. Both writes are merge-preserving, keyed on each entry's\nrecorded `packageName` — a plain overwrite in either direction silently drops\nthe other's objects, and the last pass of a multi-environment build is not\nreliably the aggregating one (#1760, #2925). `dist/manifest.json` stays\nlocal-only: a published package must not carry its dependencies' objects.\n\nThe schema-version-1 object projection is additive and high-signal: it retains\nnormalized tenant mode/field, explicit `cti`/`sti` strategy, conflict columns,\nmethod signatures, and field defaults/constraints/readonly/transient flags.\nSensitive fields are removed before both `fields` and `relationships` are\nderived, including legacy flags stored under `_meta`; matching field and\nsnake-case column names are also removed from projected conflict columns, and a\nsensitive custom tenant field is omitted while retaining scope and mode.\nGenerated artifacts assert this boundary with `sensitiveFieldsExcluded: true`;\nthe optional marker keeps schema version 1 additive while letting readers\nidentify older artifacts that require raw-manifest corroboration.\n\nConfig precedence for knowledge is defaults → top-level `knowledge` in\n`smrt.config.ts` → `packages[packageName].knowledge` → plugin option →\nobject-level `@smrt({ knowledge })`.\n\nTest generation uses that same effective configuration and publishes knowledge\nmatching the manifest it generated. Disabling knowledge removes a previous local\nknowledge artifact, so consumers cannot mistake it for current enabled output.\n`new ManifestBuilder(projectRoot)` keeps discovery, package identity, and output\nat that explicit root, including installed providers and external base classes;\nomitting the argument retains the current-working-directory\nbehavior. Both manifest writers retain declared package dependencies when merging\ntheir local and consumed-object projections.\n\nTest manifests carry optional `artifactPurpose: 'test'`; dependency discovery\nskips those artifacts, including `.smrt` fallbacks. Unmarked runtime manifests,\nempty published providers, and source-only development providers remain eligible.\n`ManifestBuilder` accepts explicit `outputMode: 'dev' | 'build'`; omitted mode\nretains legacy filename inference. Vitest selects dev mode explicitly, so tests\nnever replace a production `dist/manifest.json`. Relative output directories are\nresolved against the builder's project root.\n\nWith `svelteKit.enabled`, `smrtPlugin()`'s transform prepends\n`import './smrt-register.js';` to the configured config module\n(`<configPath>/<configFileName>`, `src/vite-plugin/sveltekit-register-injection.ts`)\nonce the register module exists, on the same first line so line numbers hold.\nApps therefore never hand-write the guarded registration import (#3416); a\nconfig module that still has it imports the same module twice, harmlessly.\n\nTracked `src/lib/server/smrt-register.ts` belongs to SvelteKit config/type\ngeneration. Generic library builds consume it but do not cache or restore it\nas an output; otherwise a concurrent config producer's bytes can be replayed\nover a newer registration after dependency eligibility changes.\n\nObject-level `knowledge: false` excludes an object from authored context only;\nit must not change runtime manifest registration. Use\n`knowledge: { tags, summary, risks }` for review-sensitive domain objects.\n\nHTTP knowledge routes are disabled by default. If `knowledge.api.enabled` is\ntrue, generated SvelteKit routes must stay GET-only and guarded by dev mode or\nadmin auth.\n\n\n## Vite Plugin\n\n`src/vite-preset/` (`@happyvertical/smrt-core/vite`, `smrt()`) composes the Oxc\ndecorator block, `smrtConsumer`, then `smrtPlugin` with the template path\nconventions. Its package list comes only from the `smrt({ packages })` option, or\n`smrt.config` `consumer.packages` (smrt-config schema); it never sniffs\n`package.json`, and a missing or malformed list throws. Keep its output\nbyte-identical to the two-plugin form (`src/vite-preset/index.test.ts`). It\nalso dedupes `@sveltejs/kit` (`smrt:shared-runtime`): SvelteKit matches\n`redirect()`/`fail()` by class, and a linked/workspace SMRT SvelteKit entry\nwould otherwise import its own copy and turn redirects into 500s.\n\n```typescript\n// vite.config.ts — required for @smrt() decorators (Vite 8+, oxc transform)\nexport default defineConfig({\n oxc: {\n decorator: {\n legacy: true,\n emitDecoratorMetadata: true,\n },\n },\n});\n```\n\nUnder Vite 8 the oxc transform does not honor the pre-Vite-8 `esbuild.tsconfigRaw`\nrecipe (or tsconfig `experimentalDecorators` reached through SvelteKit's\n`extends \"./.svelte-kit/tsconfig.json\"` chain), so that recipe throws\n`SyntaxError: Invalid or unexpected token` on the first SSR request. Configure\ndecorators through `oxc.decorator` instead. Consumers still pinned on vite<8 need\nthe legacy `esbuild.tsconfigRaw` form with `experimentalDecorators: true,\nemitDecoratorMetadata: true`.\n\nFor independent CI invocations, both `smrtPlugin()` and `smrtConsumer()` accept\nthe same `generationSnapshot: { path, sha256, provenance, sourceRoot }`. The\nschema-v1 snapshot produced by `serializeSmrtGenerationSnapshot()` contains the\nmerged project/dependency manifest, portable source paths, and source-file\ndigests; each plugin selects its own view. Reuse mode fails closed on\nbyte/provenance/path/content drift, skips scans and manifest writes, and still\ngenerates routes, types, registration, and virtual modules. Omit it for normal\nlocal development and watch mode.\n\n## Clean consumer type checks (TypeScript 6)\n\nThe consumer config hook writes `.smrt/register.js` alongside generated types\nafter route preflight succeeds. Generated SvelteKit registration imports that\nmodule, so it must exist during `svelte-kit sync`, before Vite's `buildStart`.\nBoth hosted routes and the legacy `svelteKit: true` mode follow this order.\nThe clean-consumer regression fixture ships real provider declarations and\nchecks the generated imports with `svelte-check`.\nCore's `generate:test` task depends on its own `build`: both publish the local\n`.smrt` manifest/knowledge pair, so Turbo must serialize production before test\ngeneration instead of caching an interleaved pair.\n\n## Model descriptions\n\nEach manifest object and knowledge `objects[]` entry may carry a user-facing\n`description` (for the planner Features tab and similar). The scanner\n(`extractClassJsDocDescription` in `packages/scanner/src/oxc-parser.ts`) reads it\nfrom the parsed source, in priority order: explicit `@smrt({ description })`,\nelse the first paragraph of the class JSDoc (the JSDoc may sit above `export`\nand decorators), minus a leading `ClassName - ` / `ClassName: `, tags\n(`{@link}`, backticks, HTML) and later paragraphs, capped at 200 chars on a\nsentence boundary. `@internal` classes and classes without docs emit no key. It\nis not inherited from a parent class. Generated MCP tool descriptions are\nunchanged (they stay generic).\n"
1181
1184
  },
1182
1185
  {
1183
1186
  "path": "agents/memory.md",
@@ -1207,12 +1210,24 @@
1207
1210
  {
1208
1211
  "path": "agents/recipes.md",
1209
1212
  "module": "recipes",
1210
- "content": "# SmrtRecipe: declared units of app functionality (#3590)\n\nA **recipe** is a small, named, user-facing unit (\"Sales\", \"Customers\"),\nsmaller than a package. An app or agent adds a recipe and gets that section:\nnavigation, list and create/edit views, and its prerequisites, without every\nmodel in the owning package. Source: `src/recipe.ts` (authoring base class),\n`packages/scanner/src/recipes.ts` (matcher and validation), types in\n`@happyvertical/smrt-types` (`RecipeDefinition`).\n\n## Authoring\n\n`SmrtRecipe` is an abstract, **non-persisted, non-`@smrt()`** base class\nexported from both core entries (`index.ts` and `browser.ts`). A recipe is a\nsubclass with static properties, in the package that owns its models:\n\n```ts\nexport class SalesRecipe extends SmrtRecipe {\n static id = 'commerce.sales'; // dotted lowercase, unique\n static label = 'Sales';\n static summary = 'Take customer orders and track them.';\n static synonyms = ['sales orders', 'orders'];\n static models = [Order]; // class references\n static nav = [{ label: 'Sales Orders', model: Order }];\n static requires = ['commerce.customers']; // recipe ids, any package\n static options = { Order: { fields: { status: { default: 'draft' } } } };\n}\n```\n\nStatics are read **structurally** (nothing is evaluated), so each must be\nspelled literally; `models` and `nav[].model` take identifiers. Write\n`static options = { ... } as const` so `visibility` stays a literal type.\nThe emitted `options` are keyed by qualified model name.\n\n## How the scanner collects it\n\nThe scanner class pass finds classes by decorator, which a recipe lacks, so\n`recipes.ts` is a second matcher in the style of the agent-surface one: a class\nwhose `extends` resolves to the `SmrtRecipe` import binding from\n`@happyvertical/smrt-core` (named, aliased `SmrtRecipe as R`, or namespace\n`Core.SmrtRecipe`; any core subpath such as `/browser`). A same-named local\nclass or an import from another library is not a recipe. A recipe must extend\n`SmrtRecipe` **directly**. Within one file, extending another recipe or declaring\none as a class expression or inside a block is a scan error rather than a silent\ndrop. Across files it is not detected: a module that never names `SmrtRecipe`\nis not read, so a recipe extending a recipe or intermediate base imported from\nanother module is unsupported and would be missing from the artifacts.\n\nClass references resolve to qualified names (`@scope/pkg:Class`) through the\nimport binding: a relative specifier picks the scanned class by file, then by\nclass name (barrel re-exports keep the name); an aliased import follows the\n*imported* name; `Ns.Class` namespace members and same-file classes work; a\nbare package specifier is rejected (models must belong to this package). When\nthe imported file declares no such class, the barrel fallback binds a same-named\nscanned class, so keep model class names unique within a package. This\nwas chosen over qualified-name strings because it type-checks and survives\nrenames; strings were not needed.\n\nRecipe discovery is independent of the model `include` glob (like intents; it is\nnot gated by the `agentSurface` option), and\n`ScanResults.recipes` is populated by `resolve()`. Every error is a scan error,\nso every producer that reads `scanAndResolve()` (`smrtPlugin`, `ManifestBuilder`)\nfails the build. (The legacy `ManifestGenerator.generateManifest()` path takes\npre-scanned results and never sees recipes.) The adapter qualifies names and emits a top-level `recipes` array in\n`manifest.json`; `buildDomainKnowledgeManifest` projects the same array into\n`smrt-knowledge.json`. A package with no recipe emits no key.\n\n## Build-time validation\n\nIds are dotted lowercase and unique; `models` is non-empty, resolvable, and\nduplicate-free; every `nav` model is in `models`; `requires` are well-formed,\nnot self-referential or duplicated, and acyclic within the package (ids in other\npackages cannot be checked at scan time); `options` name only listed models and\nand only the keys below. Field names are checked in core\n(`ManifestGenerator.assertRecipeOptions`, after inherited fields merge) against\nthe merged manifest, so STI-merged, tenant, and framework-base fields such as\n`parentId` are accepted along with the universal `id`, `slug`, `context`,\n`created_at`, `updated_at`; anything else fails the build.\n\n## options: curation hints, never a second schema\n\nKeyed by model class name. `fields.<name>` accepts the smrt-fields policy\nvocabulary: `default`, `label`, `help`, `order`, `visibility`\n(`basic | advanced | hidden`), `locked`; applying a recipe produces\nfield-policy rows. `exposure.<api|mcp|cli>` accepts only `false` or\nnon-empty `{ exclude: [...] }` naming a CRUD verb (`list`, `get`, `create`,\n`update`, `delete`) or a public instance method the model declares or inherits: `true` and `include` are\nrejected because they can widen what the model already declares. Custom fields are out of scope.\n\n## User-facing help (#3591)\n\nHelp is documentation for the people using the app, not developers. It lives\nbeside the recipe as Markdown and is pointed to by `static help`:\n\n```ts\nexport class SalesRecipe extends SmrtRecipe {\n // ...\n static help = './sales.recipe.md'; // relative to the recipe file, .md only\n}\n```\n\nThe file holds an **Overview** and **Tasks** (short how-tos). A step names a\nfield as `{field:<fieldName>}` or `{field:<Model>.<fieldName>}`; the Markdown\nblock (heading, paragraph, or list item) containing a reference is **tied to\nthat field**. Keep prose in the separate file rather than the recipe class.\nField text itself comes from `@field({ description })`, the user-facing seed\nsmrt-fields uses for form help; every field a recipe shows should carry one.\n\n**Emission.** The scanner reads the file (a missing, empty, non-`.md`, absolute\nor `..`-climbing path is a scan error) and emits\n`help: { markdown, fieldRefs }` on the recipe entry in `manifest.json` and\n`smrt-knowledge.json`, so a static host needs no further request.\n`fieldRefs` (distinct references as written, sorted) is **derived**, never\nauthored. Knowledge fields also carry `description` (sensitive fields stay\nexcluded). `ManifestGenerator.assertRecipeHelp` fails the build on a reference\nto a field the recipe's models do not declare, and on a `fieldRefs` list that\ndisagrees with the Markdown. The scanner has its own copy of the reference\ngrammar (`deriveHelpFieldRefs`; it cannot import core), so that comparison also\nkeeps the two from drifting. A reference to a **sensitive** or universal (`id`,\n`slug`, ...) field also fails the build: neither reaches the knowledge artifact,\nso a host building its field list from it would silently drop the step naming\none; describe such a field in prose without a reference.\n\nKnown limitation: the help file is a generator input, but editing only it does\nnot trigger a dev-server rescan (the watch matches source globs) and generation\nsnapshots do not digest it, so rebuild (or touch a `.ts` source) after editing.\n\n**Rendering.** `src/recipe-help.ts` is pure and browser-safe (exported from\nboth core entries). `renderHelp(help, models, options?)` takes the recipe's\nhelp plus the app's effective field policies (`HelpModel[]`; label, help,\nvisibility, disabled in smrt-fields vocabulary, with `@field` descriptions) and\nreturns `{ blocks, glossary, connect? }`:\n\n- `{field:x}` becomes the effective label;\n- a block tied to a hidden, disabled, undeclared, or **advanced** field (unless\n `showAdvanced`) is dropped; a list item drops alone; a heading whose section\n had content that was all dropped is pruned (a heading that never had content\n stays);\n- the glossary lists each shown field with its effective help, else its\n description. A shown field with neither is **skipped**, not listed blank;\n- `connect` is the collapsed \"Connect other tools\" section: the recipe's\n generated REST routes, MCP tools and CLI commands (`options.surfaces`, from\n the knowledge artifact), minus the recipe's `exposure` narrowing\n (`options.exposure`). Hosts render it last.\n\nThe result is an AST of text nodes (`text`, `code`, `strong`, `em`), never HTML,\nso authored markup stays inert text and nothing needs sanitizing. Only\n`##`-`####` headings, paragraphs, flat lists and bold/italic/code are\nunderstood. `helpToMarkdown(rendered)` flattens it for hosts with their own\nrenderer; render that with raw HTML disabled. `validateHelp(help, models)`\nreturns the build-failure problems for hand-built entries.\n"
1213
+ "content": "# SmrtRecipe: declared units of app functionality (#3590)\n\nA **recipe** is a small, named, user-facing unit (\"Sales\", \"Customers\"),\nsmaller than a package. An app or agent adds a recipe and gets that section:\nnavigation, list and create/edit views, and its prerequisites, without every\nmodel in the owning package. Source: `src/recipe.ts` (authoring base class),\n`packages/scanner/src/recipes.ts` (matcher and validation), types in\n`@happyvertical/smrt-types` (`RecipeDefinition`).\n\n## Authoring\n\n`SmrtRecipe` is an abstract, **non-persisted, non-`@smrt()`** base class\nexported from both core entries (`index.ts` and `browser.ts`). A recipe is a\nsubclass with static properties, in the package that owns its models:\n\n```ts\nexport class SalesRecipe extends SmrtRecipe {\n static id = 'commerce.sales'; // dotted lowercase, unique\n static label = 'Sales';\n static summary = 'Take customer orders and track them.';\n static synonyms = ['sales orders', 'orders'];\n static models = [Order]; // class references\n static nav = [{ label: 'Sales Orders', model: Order }];\n static requires = ['commerce.customers']; // recipe ids, any package\n static options = { Order: { fields: { status: { default: 'draft' } } } };\n}\n```\n\nStatics are read **structurally** (nothing is evaluated), so each must be\nspelled literally; `models` and `nav[].model` take identifiers. Write\n`static options = { ... } as const` so `visibility` stays a literal type.\nThe emitted `options` are keyed by qualified model name.\n\n## Host metadata: group, section, nav detail, alternatives (#3604)\n\nEverything a catalog host (an app shell, an agent, a CLI) needs\nto present a recipe lives on the recipe, so it reads the manifest or knowledge\nartifact instead of importing runtime code. All are optional and additive:\n\n| Static | Shape | Meaning |\n| --- | --- | --- |\n| `group` | `{ id, label, summary? }` | Recipes with the same `group.id` share one card; the first declaration of an id supplies `label` and `summary`. Declaration order is the sub-switch order. |\n| `section` | `{ id, label, icon?, description? }` | Navigation section the recipe suggests for its `nav` entries. The host owns sections and the user may rename them, so keep `id` stable; the same `id` shares a section. |\n| `requiresAny` | `string[][]` | At least one id of each inner list must be on (`[['products.simple', 'products.clothing']]`); adding the recipe with none on adds the first. |\n| `nav[].icon` / `description` | string | Shell icon name and one friendly line for a business owner. The icon must be a key of `SHELL_ICON_PATHS` (smrt-svelte `admin-shell/shell-icons.ts`, camelCase such as `fileText` or `shoppingBag`); the same holds for `section.icon`. `packages/scanner/src/__tests__/workspace-recipes.test.ts` fails on any other name. |\n| `nav[].noun` | string | What \"New\" creates when the label is not countable (\"Stock levels\" -> `stock entry`). |\n| `nav[].key` | slug | Fixed key for the layout id `item:<pkg>:<Model>:<key>`. Required for a second entry over the same model and for a `filter`. |\n| `nav[].filter` | `{ field, value }` | Narrows the entry to rows where `field` equals `value` (Ingredients over Products: `productType` = `material`). Needs a `key`. |\n| `options.<Model>.fields.<f>.required` | boolean | The form refuses to save without a value. |\n\nAcross recipes of one package the scanner also rejects a repeated nav `key`\nover the same model (it names one layout id) and one `group`/`section` id with\ntwo different labels. `packages/scanner/src/__tests__/workspace-recipes.test.ts`\nscans every recipe in the workspace and checks ids, `requires`/`requiresAny`\ntargets (which a single package cannot see) and shared labels.\n\nChild models (line items) are simply listed in `models` without a `nav` entry.\nValidation: `group`/`section` take only their keys, slug ids, non-empty\nstrings; `requiresAny` ids follow the recipe-id format and cannot name the\nrecipe itself; each (model, key) pair appears once in `nav`; a `filter.field`\nmust be a field the model declares (checked in core on the merged manifest,\n`assertRecipeOptions`).\n\nNot part of the recipe declaration (still host-local): a host's\ncross-package `forms` and `extends` (form records spanning profiles, variants\nand SKUs).\n\nUser-facing field text for the recipes comes from `@field({ description })` on\nthe models (the glossary seed), so a package that declares a recipe carries the\ndescriptions of every field the recipe shows. A field the package does not\ndeclare itself (`parentId` from `SmrtHierarchical`) is described by the recipe's\n`options.<Model>.fields.<f>.help`, which wins over the description in the\nglossary. Write all of it in plain words: no API, JSON, REST, MCP, SQL or UUID\noutside help that is about connecting other tools.\n\n## Non-model surfaces, providers, runtime, demo seed (#3708)\n\nMany features are not a list of models: a shell widget (assistant dock,\nnotification bell), a component, a route, a settings panel. All four statics are\noptional and additive; a recipe that declares none emits none of the keys. They\nare emitted on the recipe entry in `manifest.json` and `smrt-knowledge.json`.\nComponents are named by `'<package specifier>#<ExportName>'` and never imported\nat scan time; a host resolves them. Relative or absolute specifiers are rejected.\n\n| Static | Shape | Meaning |\n| --- | --- | --- |\n| `surfaces` | `RecipeSurface[]` | `{ kind: 'shell-widget', slot, export, label, icon? }`, `{ kind: 'route', path, export, label }`, `{ kind: 'settings-panel', export, label }`, `{ kind: 'playground', export, label? }`, `{ kind: 'widget', type, export, label, ... }` (see below). `slot` is a smrt-svelte `ShellSlot`; `path` starts with `/` and has no whitespace, `?`, `#` or `..`. |\n| `providers` | `RecipeProvider[]` | `{ id, kind, options, required, secrets?, browserOptions? }`: lowercase slugs, `options` non-empty and distinct, `required` always written, `secrets` distinct `UPPER_SNAKE` names (never values), `browserOptions` a non-empty subset of `options` that run in a browser with none of the secrets (#3709). Ids are unique per recipe. |\n| `runtime` | `'browser' \\| 'server' \\| 'both'` | Where the recipe's runtime pieces can run. Omitted means `both`; the value is emitted as authored. The build refines it into `demo` (below). |\n| `demoSeed` | `{ export } \\| { data }` | A fixture export reference, or inline JSON of at most 8 KB, for demo hosts. Exactly one key. |\n\nWrite `surfaces` with `as const` (like `options`) so `kind` and `slot` stay\nliteral types. The slot union is `RecipeShellSlot` in smrt-types (types only) and the\nscanner's `RECIPE_SHELL_SLOTS` list copies smrt-svelte's `SHELL_SLOTS`; a\ntype-level test in smrt-svelte and a scanner test keep them equal, so there is\nno runtime dependency on smrt-svelte. Inline `demoSeed.data` must be finite JSON. Every violation (unknown\nkind or slot, extra key, duplicate route path or provider id, malformed\nreference) is a scan error. Example: `events.calendar` in\n`packages/events/src/recipes.ts`.\n\n## Widget surfaces (#3727)\n\n`{ kind: 'widget', ... }` contributes a widget to customizable overviews\n(smrt-svelte `./overview`). The manifest carries everything a host needs to\nregister it; the helper `registerRecipeWidgets` in smrt-svelte does that with an\ninjected module resolver, so nothing is imported at scan time.\n\n```ts\nstatic surfaces = [\n {\n kind: 'widget',\n type: 'sales-total', // registry type, unique per package\n export: '@acme/shop/svelte#SalesTotal', // the component\n label: 'Sales total', // text or an i18n key\n description: 'Order totals for the period.',\n icon: 'chart',\n version: 2, // option-schema version (default 1)\n migrate: '@acme/shop/server#migrateSalesTotal', // needs version above 1\n options: [\n { key: 'model', type: 'model', label: 'Model', required: true },\n { key: 'style', type: 'enum', label: 'Style', default: 'bar',\n choices: [{ value: 'bar', label: 'Bar' }, { value: 'line', label: 'Line' }] },\n ],\n data: { load: '@acme/shop/server#loadSalesTotal', models: ['@acme/shop:Order'] },\n allowedIn: ['shop.home'], // overview ids; omit for any\n defaultSpan: 2, minSpan: 1, maxSpan: 3,\n },\n] as const;\n```\n\nEmitted keys, in this order: `kind`, `type`, `export`, `label`, `description`,\n`icon`, `version`, `migrate`, `options`, `data`, `allowedIn`, `defaultSpan`,\n`minSpan`, `maxSpan`; absent ones are omitted. Rules (each violation is a scan\nerror, same strictness as the other kinds):\n\n- `type` is a lowercase kebab id (`[a-z][a-z0-9-]{0,31}`), unique among a\n recipe's surfaces and across the package's recipes. `export`, `data.load` and\n `migrate` are `'<package specifier>#<ExportName>'`; relative specifiers are\n rejected. `label` is required.\n- `options` is a non-empty list of plain-JSON fields limited to the overview\n option types: `text`, `markdown`, `identifier`, `model`, `integer`, `number`,\n `boolean`, closed `enum` (non-empty distinct `choices`). There is no free-form\n query, expression, URL or SQL type. Keys are camelCase (`[A-Za-z][A-Za-z0-9]{0,31}`)\n and unique; `default` must pass its field's own rule; `min`/`max` only on\n numbers, `maxLength` only on text. Only `key`, `type`, `label`, `help`,\n `required`, `default`, `min`, `max`, `maxLength`, `choices` are accepted.\n- `data` takes `load` and/or `models` (qualified class names, distinct). The\n scanner cannot see other packages, so a model is checked for format only.\n- `allowedIn` is a non-empty list of distinct overview ids\n (`[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}`); spans are integers 1 to 4 with\n `minSpan <= defaultSpan <= maxSpan`.\n\nThe scanner's copies of these rules live in `packages/scanner/src/recipe-widgets.ts`\nand a scanner test compares them to the smrt-svelte source. See\n[overview-surfaces.md](../../smrt-svelte/agents/overview-surfaces.md#recipe-widgets-recipe-widgetsts)\nfor how a host registers them.\n\n## Browser-demo mode: Live, Mock, Sample, Server (#3709)\n\nA catalog host (smrt-planner) labels each feature by how far it runs in a\nbrowser-only demo. The label is **derived at build time**, never authored: the\nmanifest build combines what the bundle-gate measured for the recipe's package\nwith the recipe's own `runtime`, `providers` and `demoSeed`, and emits it as\n`demo` on the recipe entry and `browser` on the package. A recipe that declares\nnone of those keeps its shape except for `demo`, which every recipe of a\nmeasured package gets.\n\n```jsonc\n// manifest.json and smrt-knowledge.json, top level\n\"browser\": {\n \"status\": \"browser-safe\" | \"server-only\",\n \"issues\": [\"#3624\"], // tracking issues; omitted when browser-safe\n \"reason\": \"node:crypto\", // the package's own blocker; omitted when only inherited\n \"via\": [\"@happyvertical/smrt-tenancy\"] // inherited from these; omitted when none\n}\n// on each entry of \"recipes\"\n\"demo\": {\n \"mode\": \"live\" | \"mock\" | \"sample\" | \"server\",\n \"reasons\": [\"Needs a server because ...\"], // plain sentences, in rule order\n \"mocked\": [\"smtp\"] // providers a demo fakes; omitted when none\n}\n```\n\n| Mode | Meaning |\n| --- | --- |\n| `live` | Real browser data layer (PGlite); nothing faked. |\n| `mock` | Runs in the browser, but a provider (sending mail, OAuth) is faked. |\n| `sample` | Runs in the browser on `demoSeed` fixtures only. |\n| `server` | Needs a server; a browser-only host cannot offer it. |\n\n**Package capability.** The browser gate (`packages/bundle-gate`) fails any\nmodel package that is not in its expected-failures list and does not build for\na browser, and any listed package that now builds. So a package is `server-only`\nexactly when it is listed. The ratchet attributes a defect to the package that\nowns the fix, so a dependent passes while still dragging the failure into a\nbrowser bundle; the derivation therefore also marks a package `server-only`\nwhen a workspace package it depends on (transitively, through `dependencies`)\nis, and records them in `via`. `smrt-core` is the platform baseline and does not\npropagate. The table lives in `src/manifest/browser-capability.generated.ts`\n(generated, never edited) and a bundle-gate spec fails when it is stale; see\nthat package's AGENTS.md for the regenerate command. A package the gate does\nnot measure (an app's own, a UI package) emits no `browser`, and its recipes get\na `demo` only when they declare `runtime`, `providers` or `demoSeed`.\n\n**Rules** (`src/recipe-demo.ts`, pure and browser-safe; the worst mode wins,\n`live` < `mock` < `sample` < `server`):\n\n1. `runtime: 'server'` is `server`. `runtime: 'both'` or omitted makes no claim:\n the package capability refines it, so `both` on a `server-only` package is\n `server`.\n2. A `server-only` package is `server`.\n3. A **server provider** is one that lists `secrets` (credentials a browser\n cannot hold). One with a `browserOptions` entry (an in-browser model such as\n `webllm`) is satisfied in a browser and changes nothing. Otherwise it is\n **mockable** when its `options` include `mock`. A *required* server provider\n that is neither is `sample` when the recipe has a `demoSeed` (the fixtures\n stand in for what the provider would feed), else `server`. An optional one\n that is neither leaves the mode alone and adds a reason.\n4. Any mockable server provider makes the recipe `mock` and lands in `mocked`.\n5. Otherwise `live`.\n\n**Contradictions fail the build** (like `assertRecipeOptions`), naming the\nrecipe: `runtime: 'browser'` on a `server-only` package, or beside a required\nserver provider with no in-browser and no `mock` option. Fix by giving the\nprovider a `browserOptions` entry or a `mock` option, making it optional, or\ndeclaring `both`/`server`. An explicit `both` or\n`server` on a `server-only` package is not a contradiction.\n\n**Dependencies between recipes.** `demo` is the recipe's own answer. A host that\nwants the answer including what the recipe needs calls\n`effectiveRecipeDemo(id, recipes)` (exported from both core entries): the worst\nof its own mode and every `requires` (transitively), counting the best known\nalternative of each `requiresAny` list; unknown ids are ignored.\n\n**Importing it in a browser page.** Use the subpath\n`@happyvertical/smrt-core/recipe-demo` (`deriveRecipeDemo`,\n`effectiveRecipeDemo`, `RECIPE_DEMO_MODES` and the demo types). Its module graph\nis `src/recipe-demo.ts` alone, with type-only imports, so it carries no `node:`\nimport. The root entry and `/browser` both also export these names, but both\nreach `manifest/manifest-loader.ts` through the registry, and that module calls\n`createRequire` from `node:module` as it loads, which a browser page cannot\nsatisfy. `src/__tests__/recipe-demo-entry.test.ts` walks the module graph and\nfails if the subpath gains a `node:` or package import.\n\nThe classification runs in `ManifestGenerator.applyGenerationPasses` (the one\npass sequence the Vite plugin, `ManifestBuilder` and `generateManifest()` share)\nthrough `applyRecipeDemo` in `src/scanner/recipe-demo-pass.ts`, after the\nmerged-manifest recipe assertions. It needs the package name, so it cannot run\nin the scanner, which resolves recipes before it knows the package.\n\n## How the scanner collects it\n\nThe scanner class pass finds classes by decorator, which a recipe lacks, so\n`recipes.ts` is a second matcher in the style of the agent-surface one: a class\nwhose `extends` resolves to the `SmrtRecipe` import binding from\n`@happyvertical/smrt-core` (named, aliased `SmrtRecipe as R`, or namespace\n`Core.SmrtRecipe`; any core subpath such as `/browser`). A same-named local\nclass or an import from another library is not a recipe. A recipe must extend\n`SmrtRecipe` **directly**. Within one file, extending another recipe or declaring\none as a class expression or inside a block is a scan error rather than a silent\ndrop. Across files it is not detected: a module that never names `SmrtRecipe`\nis not read, so a recipe extending a recipe or intermediate base imported from\nanother module is unsupported and would be missing from the artifacts.\n\nClass references resolve to qualified names (`@scope/pkg:Class`) through the\nimport binding: a relative specifier picks the scanned class by file, then by\nclass name (barrel re-exports keep the name); an aliased import follows the\n*imported* name; `Ns.Class` namespace members and same-file classes work; a\nbare package specifier is rejected (models must belong to this package). When\nthe imported file declares no such class, the barrel fallback binds a same-named\nscanned class, so keep model class names unique within a package. This\nwas chosen over qualified-name strings because it type-checks and survives\nrenames; strings were not needed.\n\nRecipe discovery is independent of the model `include` glob (like intents; it is\nnot gated by the `agentSurface` option), and\n`ScanResults.recipes` is populated by `resolve()`. Every error is a scan error,\nso every producer that reads `scanAndResolve()` (`smrtPlugin`, `ManifestBuilder`)\nfails the build. (The legacy `ManifestGenerator.generateManifest()` path takes\npre-scanned results and never sees recipes.) The adapter qualifies names and emits a top-level `recipes` array in\n`manifest.json`; `buildDomainKnowledgeManifest` projects the same array into\n`smrt-knowledge.json`. A package with no recipe emits no key.\n\n## Build-time validation\n\nIds are dotted lowercase and unique; `models` is non-empty, resolvable, and\nduplicate-free; every `nav` model is in `models`; `requires` are well-formed,\nnot self-referential or duplicated, and acyclic within the package (ids in other\npackages cannot be checked at scan time); `options` name only listed models and\nand only the keys below. Field names are checked in core\n(`ManifestGenerator.assertRecipeOptions`, after inherited fields merge) against\nthe merged manifest, so STI-merged, tenant, and framework-base fields such as\n`parentId` are accepted along with the universal `id`, `slug`, `context`,\n`created_at`, `updated_at`; anything else fails the build.\n\n## options: curation hints, never a second schema\n\nKeyed by model class name. `fields.<name>` accepts the smrt-fields policy\nvocabulary: `default`, `label`, `help`, `order`, `visibility`\n(`basic | advanced | hidden`), `locked`; applying a recipe produces\nfield-policy rows. `exposure.<api|mcp|cli>` accepts only `false` or\nnon-empty `{ exclude: [...] }` naming a CRUD verb (`list`, `get`, `create`,\n`update`, `delete`) or a public instance method the model declares or inherits: `true` and `include` are\nrejected because they can widen what the model already declares. Custom fields are out of scope.\n\n## User-facing help (#3591)\n\nHelp is documentation for the people using the app, not developers. It lives\nbeside the recipe as Markdown and is pointed to by `static help`:\n\n```ts\nexport class SalesRecipe extends SmrtRecipe {\n // ...\n static help = './sales.recipe.md'; // relative to the recipe file, .md only\n}\n```\n\nThe file holds an **Overview** and **Tasks** (short how-tos). A step names a\nfield as `{field:<fieldName>}` or `{field:<Model>.<fieldName>}`; the Markdown\nblock (heading, paragraph, or list item) containing a reference is **tied to\nthat field**. Keep prose in the separate file rather than the recipe class.\nField text itself comes from `@field({ description })`, the user-facing seed\nsmrt-fields uses for form help; every field a recipe shows should carry one.\n\n**Emission.** The scanner reads the file (a missing, empty, non-`.md`, absolute\nor `..`-climbing path is a scan error) and emits\n`help: { markdown, fieldRefs }` on the recipe entry in `manifest.json` and\n`smrt-knowledge.json`, so a static host needs no further request.\n`fieldRefs` (distinct references as written, sorted) is **derived**, never\nauthored. Knowledge fields also carry `description` (sensitive fields stay\nexcluded). `ManifestGenerator.assertRecipeHelp` fails the build on a reference\nto a field the recipe's models do not declare, and on a `fieldRefs` list that\ndisagrees with the Markdown. The scanner has its own copy of the reference\ngrammar (`deriveHelpFieldRefs`; it cannot import core), so that comparison also\nkeeps the two from drifting. A reference to a **sensitive** or universal (`id`,\n`slug`, ...) field also fails the build: neither reaches the knowledge artifact,\nso a host building its field list from it would silently drop the step naming\none; describe such a field in prose without a reference.\n\nKnown limitation: the help file is a generator input, but editing only it does\nnot trigger a dev-server rescan (the watch matches source globs) and generation\nsnapshots do not digest it, so rebuild (or touch a `.ts` source) after editing.\n\n**Rendering.** `src/recipe-help.ts` is pure and browser-safe (exported from\nboth core entries). `renderHelp(help, models, options?)` takes the recipe's\nhelp plus the app's effective field policies (`HelpModel[]`; label, help,\nvisibility, disabled in smrt-fields vocabulary, with `@field` descriptions) and\nreturns `{ blocks, glossary, connect? }`:\n\n- `{field:x}` becomes the effective label;\n- a block tied to a hidden, disabled, undeclared, or **advanced** field (unless\n `showAdvanced`) is dropped; a list item drops alone; a heading whose section\n had content that was all dropped is pruned (a heading that never had content\n stays);\n- the glossary lists each shown field with its effective help, else its\n description. A shown field with neither is **skipped**, not listed blank;\n- `connect` is the collapsed \"Connect other tools\" section: the recipe's\n generated REST routes, MCP tools and CLI commands (`options.surfaces`, from\n the knowledge artifact), minus the recipe's `exposure` narrowing\n (`options.exposure`). Hosts render it last.\n\nThe result is an AST of text nodes (`text`, `code`, `strong`, `em`), never HTML,\nso authored markup stays inert text and nothing needs sanitizing. Only\n`##`-`####` headings, paragraphs, flat lists and bold/italic/code are\nunderstood. `helpToMarkdown(rendered)` flattens it for hosts with their own\nrenderer; render that with raw HTML disabled. `validateHelp(help, models)`\nreturns the build-failure problems for hand-built entries.\n"
1214
+ },
1215
+ {
1216
+ "path": "agents/browser-entry.md",
1217
+ "module": "browser-entry",
1218
+ "content": "# Browser entry: no Node-only modules (#2838)\n\n`src/browser.ts` is what `package.json#exports[\".\"].browser` resolves to. Its\nmodule graph must build for a browser **and evaluate** in one. Two guards hold\nit:\n\n- `packages/bundle-gate` builds it with Vite browser conditions and fails on\n `node:` built-ins, `pg`, `cosmiconfig`, `jiti` and the rest of\n `FORBIDDEN_NODE_ONLY_MODULES` (core is held to zero even while its ratchet\n entry exists for another reason).\n- `pnpm test:browser` bundles the built `dist/browser.js`, loads it in\n Chromium, registers a decorated class, and fails on any evaluation error or\n any module Vite externalized \"for browser compatibility\". Set\n `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use another Chromium. CI runs it in\n the workbench browser job.\n\n## How a Node-only dependency stays out\n\nNever import it statically from a module the browser graph reaches. Pick one:\n\n| Need | Use |\n|---|---|\n| `getDatabase`, `buildWhere`, `raw`, `NestedTransactionError`, the AI SDK, installed-package discovery | `src/host.ts`. `package.json#browser` maps `./dist/host.js` to `./dist/host.browser.js`; Node and every test resolve `host.ts`. |\n| JSON parse/stringify | `src/utils/json.ts`; the browser build is `utils/json.browser.ts` (native `JSON`). |\n| `node:fs`/`path`/`module` for manifest discovery | `src/manifest/node-host.ts`, which resolves them with `process.getBuiltinModule()`. No host answers \"absent\". |\n| SHA-256 | `sha256Hex` (`src/utils/sha256.ts`, `@noble/hashes`). Not `node:crypto`. |\n| Random ids | `globalThis.crypto.randomUUID()` / `getRandomValues()`. |\n| Async-local state | `createAsyncContext()` (`src/utils/async-context.ts`). Check `propagatesAcrossAwait` before relying on the store. |\n| A whole Node-only module (registry snapshot) | Keep it out of `system/browser.ts` and the browser entry. |\n\n`browser.ts` and `host.browser.ts` are typed against their Node counterparts, so\nthe surfaces cannot drift. A new browser variant needs its source pair, an\n`entries[...]` line in `vite.config.ts` (nothing imports it, so the build would\nnot emit it), and a `browser` mapping; `browser-field.test.ts` checks all three.\n\n## Known limits\n\n- The browser uses `getDatabase` from `@happyvertical/sql/pglite` and\n `buildWhere`, `raw`, and `NestedTransactionError` from the browser-safe\n `@happyvertical/sql/query` entry. It rejects non-PGlite engines.\n- The AI SDK is unavailable in the browser build.\n- The embedded write queue runs unqueued without async-local state; its only\n browser database, PGlite, serializes statements itself.\n- `smrt-config`'s browser loader resolves to `{}`; use `setConfig()`.\n"
1211
1219
  },
1212
1220
  {
1213
1221
  "path": "agents/test-types.md",
1214
1222
  "module": "test-types",
1215
1223
  "content": "# Test typechecking\n\nCore's normal `typecheck` command runs its strict production project followed\nby `tsconfig.test.json`; the existing required CI typecheck task runs that same\ncommand. The test project includes every `*.test.ts` and `*.spec.ts` under\n`src/`, including optional and integration suites. These globs include future\ntests automatically. Do not exclude individual failing tests.\n\nAll sibling packages in epic #2726 should extend the root\n`tsconfig.package-test.json` from a package-local `tsconfig.test.json`, override\n`include` and `exclude` explicitly, and add the test project to their normal\n`typecheck` command after source validation. The shared project emits nothing,\nloads Node and Vitest globals, and relaxes implicit-any, property-initialization,\nexact-optional-property, and unchecked-index checks for fixtures. Production\nprojects keep their strict settings. Module resolution, missing-member, and\nargument compatibility diagnostics remain enabled.\n\nNull checks remain enabled: turning them off also changes narrowing in imported\nproduction source, breaking discriminated unions and guards for unknown values.\nUse existing fixture assertions to justify non-null assertions or narrow values\nat the test boundary. Deliberately invalid inputs and intentional protected\nlifecycle access require a narrowly scoped escape with its reason documented.\nUse public registry APIs when they provide the same behavior.\n\nVerify membership with `tsc -p tsconfig.test.json --listFiles`, and measure the\ntest project separately from the source project when reporting compiler cost.\nBefore claiming that drift is caught, add a temporary included test referencing\na deleted type-only import, a missing member, and an invalid argument; confirm\nthe normal package `typecheck` command fails, then remove the probe and rerun it.\n"
1216
1224
  }
1217
- ]
1225
+ ],
1226
+ "browser": {
1227
+ "status": "server-only",
1228
+ "issues": [
1229
+ "#3635"
1230
+ ],
1231
+ "reason": "model roots import server-only helpers (manifest loader, route helpers, startRestServer) the browser entry deliberately omits; core's own graph reaches no Node-only module (#2838, held by the browser-boundary core-entry test)"
1232
+ }
1218
1233
  }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Browser-safe subset of the system-table surface (#2838).
3
+ *
4
+ * Everything `system/index.ts` exports except the registry snapshot, which
5
+ * sanitizes filesystem paths with `node:path` and exists for the Node-side
6
+ * dev plane (smrt-dev-mcp). `browser.ts` re-exports this module so a page
7
+ * bundle never reaches `node:path`; `system/index.ts` re-exports it too, so
8
+ * the Node entry's surface is unchanged.
9
+ */
10
+ export { ensureSystemTables } from './bootstrap.js';
11
+ export * from './compatibility.js';
12
+ export * from './diagnostics.js';
13
+ export * from './retention.js';
14
+ export { SMRT_SCHEMA_VERSION } from './schema.js';
15
+ export * from './types.js';
16
+ //# sourceMappingURL=browser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/system/browser.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,cAAc,YAAY,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { SMRT_SCHEMA_VERSION } from "./schema.js";
2
+ import { assertPostgresSystemTimestampsCurrent, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, getDatabaseEngine, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, tableExists } from "./compatibility.js";
3
+ import { ensureSystemTables } from "./bootstrap.js";
4
+ import { DIAGNOSTICS_DEFAULT_LIMIT, SYSTEM_DIAGNOSTICS_TABLES, readDispatchHealth, readJobHealth, readMigrationStatus, readRecentChanges, readRegistryDrift, readScheduleHealth, readSystemDiagnostics } from "./diagnostics.js";
5
+ import { DEFAULT_RETENTION_POLICY, clearRetentionTasks, getRetentionTasks, pruneAiUsage, pruneExpiredContexts, pruneRunOnceClaims, registerRetentionTask, runRetentionSweep, unregisterRetentionTask } from "./retention.js";
6
+ export { DEFAULT_RETENTION_POLICY, DIAGNOSTICS_DEFAULT_LIMIT, SMRT_SCHEMA_VERSION, SYSTEM_DIAGNOSTICS_TABLES, assertPostgresSystemTimestampsCurrent, clearRetentionTasks, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, getDatabaseEngine, getRetentionTasks, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, pruneAiUsage, pruneExpiredContexts, pruneRunOnceClaims, readDispatchHealth, readJobHealth, readMigrationStatus, readRecentChanges, readRegistryDrift, readScheduleHealth, readSystemDiagnostics, registerRetentionTask, runRetentionSweep, tableExists, unregisterRetentionTask };
@@ -4,11 +4,6 @@
4
4
  * System-level metadata storage for the SMRT framework.
5
5
  * All tables use _smrt_ prefix and share the application's database.
6
6
  */
7
- export { ensureSystemTables } from './bootstrap.js';
8
- export * from './compatibility.js';
9
- export * from './diagnostics.js';
7
+ export * from './browser.js';
10
8
  export * from './registry-snapshot.js';
11
- export * from './retention.js';
12
- export { SMRT_SCHEMA_VERSION } from './schema.js';
13
- export * from './types.js';
14
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/system/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,cAAc,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/system/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,cAAc,cAAc,CAAC;AAC7B,cAAc,wBAAwB,CAAC"}
@@ -2,6 +2,7 @@ import { SMRT_SCHEMA_VERSION } from "./schema.js";
2
2
  import { assertPostgresSystemTimestampsCurrent, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, getDatabaseEngine, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, tableExists } from "./compatibility.js";
3
3
  import { ensureSystemTables } from "./bootstrap.js";
4
4
  import { DIAGNOSTICS_DEFAULT_LIMIT, SYSTEM_DIAGNOSTICS_TABLES, readDispatchHealth, readJobHealth, readMigrationStatus, readRecentChanges, readRegistryDrift, readScheduleHealth, readSystemDiagnostics } from "./diagnostics.js";
5
- import { BOOTED_PROVENANCE, assertPlainJson, sanitizeMessagePaths, snapshotRegistry } from "./registry-snapshot.js";
6
5
  import { DEFAULT_RETENTION_POLICY, clearRetentionTasks, getRetentionTasks, pruneAiUsage, pruneExpiredContexts, pruneRunOnceClaims, registerRetentionTask, runRetentionSweep, unregisterRetentionTask } from "./retention.js";
6
+ import "./browser.js";
7
+ import { BOOTED_PROVENANCE, assertPlainJson, sanitizeMessagePaths, snapshotRegistry } from "./registry-snapshot.js";
7
8
  export { BOOTED_PROVENANCE, DEFAULT_RETENTION_POLICY, DIAGNOSTICS_DEFAULT_LIMIT, SMRT_SCHEMA_VERSION, SYSTEM_DIAGNOSTICS_TABLES, assertPlainJson, assertPostgresSystemTimestampsCurrent, clearRetentionTasks, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, getDatabaseEngine, getRetentionTasks, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, pruneAiUsage, pruneExpiredContexts, pruneRunOnceClaims, readDispatchHealth, readJobHealth, readMigrationStatus, readRecentChanges, readRegistryDrift, readScheduleHealth, readSystemDiagnostics, registerRetentionTask, runRetentionSweep, sanitizeMessagePaths, snapshotRegistry, tableExists, unregisterRetentionTask };
@@ -3,11 +3,11 @@ import { detectEngine } from "../schema/ddl/index.js";
3
3
  import { getSystemTableDDL } from "../system/schema.js";
4
4
  import { ensurePostgresChangeFeedAppendFunction } from "../change-feed.js";
5
5
  import { ensureLegacySystemTableCompatibility } from "../system/compatibility.js";
6
- import { SchemaGenerator } from "../schema/generator.js";
7
6
  import { recordRegistryDiagnostic } from "../registry/diagnostics.js";
8
7
  import { isFrameworkBaseClass } from "../registry/framework-base-classes.js";
9
8
  import { isCollectionRegistration, resolveCollectionItemClassName, resolveRelatedRegistration } from "../registry/collection-resolution.js";
10
9
  import { ObjectRegistry } from "../registry.js";
10
+ import { SchemaGenerator } from "../schema/generator.js";
11
11
  import { planForeignKeyCreation } from "../schema/foreign-key-planner.js";
12
12
  import { getDatabase } from "@happyvertical/sql";
13
13
  //#region src/testing/database.ts
@@ -1,3 +1,3 @@
1
- import { convertTypeToJsonSchema, generateToolFromMethod, generateToolManifest, shouldIncludeMethod } from "./tool-generator.js";
2
1
  import { executeToolCall, executeToolCalls, formatToolResults, validateToolCall } from "./tool-executor.js";
2
+ import { convertTypeToJsonSchema, generateToolFromMethod, generateToolManifest, shouldIncludeMethod } from "./tool-generator.js";
3
3
  export { convertTypeToJsonSchema, executeToolCall, executeToolCalls, formatToolResults, generateToolFromMethod, generateToolManifest, shouldIncludeMethod, validateToolCall };