adula 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE.md +10 -0
  2. package/README.md +40 -2
  3. package/build/agent/AGENTS.template.md +28 -0
  4. package/build/agent/capabilities.md +60 -0
  5. package/build/agent/skills/adula-frontend-design/SKILL.md +59 -0
  6. package/build/agent/skills/idea-review/SKILL.md +31 -0
  7. package/build/agent/skills/module-review/SKILL.md +22 -0
  8. package/build/agent/skills/perf-review/SKILL.md +24 -0
  9. package/build/agent/skills/schema-review/SKILL.md +22 -0
  10. package/build/agent/skills/security-review/SKILL.md +24 -0
  11. package/build/agent/skills/ui-review/SKILL.md +22 -0
  12. package/build/commands/capabilities.d.ts +10 -0
  13. package/build/commands/capabilities.js +40 -0
  14. package/build/commands/doctor.d.ts +9 -0
  15. package/build/commands/doctor.js +72 -0
  16. package/build/commands/gaps.d.ts +12 -0
  17. package/build/commands/gaps.js +62 -0
  18. package/build/commands/install.d.ts +9 -0
  19. package/build/commands/install.js +105 -0
  20. package/build/commands/main.d.ts +8 -0
  21. package/build/commands/main.js +33 -0
  22. package/build/commands/module_add.d.ts +8 -0
  23. package/build/commands/module_add.js +57 -0
  24. package/build/commands/module_remove.d.ts +10 -0
  25. package/build/commands/module_remove.js +94 -0
  26. package/build/commands/resource.d.ts +8 -0
  27. package/build/commands/resource.js +29 -0
  28. package/build/commands/resource_snapshot.d.ts +15 -0
  29. package/build/commands/resource_snapshot.js +61 -0
  30. package/build/commands/storage_migrate.d.ts +12 -0
  31. package/build/commands/storage_migrate.js +39 -0
  32. package/build/commands/ui.d.ts +11 -0
  33. package/build/commands/ui.js +210 -0
  34. package/build/commands/upgrade.d.ts +15 -0
  35. package/build/commands/upgrade.js +34 -0
  36. package/build/configure.d.ts +2 -0
  37. package/build/configure.js +79 -0
  38. package/build/database/migrations/1770000000000_core.d.ts +5 -0
  39. package/build/database/migrations/1770000000000_core.js +10 -0
  40. package/build/database/migrations/1770000000001_attachments.d.ts +5 -0
  41. package/build/database/migrations/1770000000001_attachments.js +10 -0
  42. package/build/database/migrations/1770000000002_saved_views.d.ts +5 -0
  43. package/build/database/migrations/1770000000002_saved_views.js +10 -0
  44. package/build/database/migrations/1770000000003_user_invitations.d.ts +5 -0
  45. package/build/database/migrations/1770000000003_user_invitations.js +18 -0
  46. package/build/database/migrations/1770000000004_collaboration.d.ts +5 -0
  47. package/build/database/migrations/1770000000004_collaboration.js +10 -0
  48. package/build/database/migrations/1770000000005_assignments.d.ts +5 -0
  49. package/build/database/migrations/1770000000005_assignments.js +10 -0
  50. package/build/database/migrations/1770000000006_messaging.d.ts +5 -0
  51. package/build/database/migrations/1770000000006_messaging.js +10 -0
  52. package/build/database/migrations/1770000000007_webhooks.d.ts +5 -0
  53. package/build/database/migrations/1770000000007_webhooks.js +10 -0
  54. package/build/database/migrations/1770000000008_imports.d.ts +5 -0
  55. package/build/database/migrations/1770000000008_imports.js +10 -0
  56. package/build/database/migrations/1770000000010_workflows.d.ts +5 -0
  57. package/build/database/migrations/1770000000010_workflows.js +10 -0
  58. package/build/database/migrations/1770000000011_managed_assignments.d.ts +5 -0
  59. package/build/database/migrations/1770000000011_managed_assignments.js +10 -0
  60. package/build/database/migrations/1770000000012_role_keys.d.ts +5 -0
  61. package/build/database/migrations/1770000000012_role_keys.js +10 -0
  62. package/build/database/migrations/1770000000013_notification_targets.d.ts +5 -0
  63. package/build/database/migrations/1770000000013_notification_targets.js +10 -0
  64. package/build/database/migrations/1770000000014_upload_grants.d.ts +5 -0
  65. package/build/database/migrations/1770000000014_upload_grants.js +10 -0
  66. package/build/database/migrations/1770000000015_inbound_webhooks.d.ts +5 -0
  67. package/build/database/migrations/1770000000015_inbound_webhooks.js +10 -0
  68. package/build/database/migrations/1770000000016_adulajs_names.d.ts +6 -0
  69. package/build/database/migrations/1770000000016_adulajs_names.js +11 -0
  70. package/build/index.d.ts +80 -0
  71. package/build/index.js +49 -0
  72. package/build/providers/adula_provider.d.ts +6 -0
  73. package/build/providers/adula_provider.js +10 -0
  74. package/build/src/admin/contracts.d.ts +19 -0
  75. package/build/src/admin/contracts.js +115 -0
  76. package/build/src/admin/controller.d.ts +32 -0
  77. package/build/src/admin/controller.js +167 -0
  78. package/build/src/admin/errors.d.ts +5 -0
  79. package/build/src/admin/errors.js +9 -0
  80. package/build/src/admin/presentation.d.ts +28 -0
  81. package/build/src/admin/presentation.js +1 -0
  82. package/build/src/admin/record_title.d.ts +14 -0
  83. package/build/src/admin/record_title.js +50 -0
  84. package/build/src/admin/resource_service.d.ts +376 -0
  85. package/build/src/admin/resource_service.js +1448 -0
  86. package/build/src/attachments/attachment_service.d.ts +100 -0
  87. package/build/src/attachments/attachment_service.js +270 -0
  88. package/build/src/attachments/doctor.d.ts +4 -0
  89. package/build/src/attachments/doctor.js +28 -0
  90. package/build/src/attachments/storage_migrate.d.ts +39 -0
  91. package/build/src/attachments/storage_migrate.js +64 -0
  92. package/build/src/attachments/upload_grants.d.ts +44 -0
  93. package/build/src/attachments/upload_grants.js +105 -0
  94. package/build/src/auth/ability.d.ts +24 -0
  95. package/build/src/auth/ability.js +34 -0
  96. package/build/src/auth/actor_store.d.ts +14 -0
  97. package/build/src/auth/actor_store.js +70 -0
  98. package/build/src/auth/conditions.d.ts +26 -0
  99. package/build/src/auth/conditions.js +117 -0
  100. package/build/src/auth/packed_rules.d.ts +4 -0
  101. package/build/src/auth/packed_rules.js +13 -0
  102. package/build/src/auth/sql.d.ts +11 -0
  103. package/build/src/auth/sql.js +118 -0
  104. package/build/src/collaboration/assignments.d.ts +129 -0
  105. package/build/src/collaboration/assignments.js +333 -0
  106. package/build/src/collaboration/record_collaboration.d.ts +86 -0
  107. package/build/src/collaboration/record_collaboration.js +348 -0
  108. package/build/src/commands/agent_assets.d.ts +7 -0
  109. package/build/src/commands/agent_assets.js +66 -0
  110. package/build/src/commands/capabilities.d.ts +19 -0
  111. package/build/src/commands/capabilities.js +179 -0
  112. package/build/src/commands/doctor.d.ts +42 -0
  113. package/build/src/commands/doctor.js +375 -0
  114. package/build/src/commands/gap_report.d.ts +56 -0
  115. package/build/src/commands/gap_report.js +110 -0
  116. package/build/src/commands/generator.d.ts +1 -0
  117. package/build/src/commands/generator.js +70 -0
  118. package/build/src/commands/snapshot.d.ts +28 -0
  119. package/build/src/commands/snapshot.js +48 -0
  120. package/build/src/commands/source_markers.d.ts +11 -0
  121. package/build/src/commands/source_markers.js +41 -0
  122. package/build/src/core/activity.d.ts +43 -0
  123. package/build/src/core/activity.js +77 -0
  124. package/build/src/core/administration_guard.d.ts +3 -0
  125. package/build/src/core/administration_guard.js +39 -0
  126. package/build/src/core/health.d.ts +42 -0
  127. package/build/src/core/health.js +44 -0
  128. package/build/src/core/mail_test.d.ts +18 -0
  129. package/build/src/core/mail_test.js +88 -0
  130. package/build/src/core/message_templates.d.ts +83 -0
  131. package/build/src/core/message_templates.js +293 -0
  132. package/build/src/core/module_seed.d.ts +15 -0
  133. package/build/src/core/module_seed.js +31 -0
  134. package/build/src/core/notifications.d.ts +42 -0
  135. package/build/src/core/notifications.js +91 -0
  136. package/build/src/core/org_units.d.ts +30 -0
  137. package/build/src/core/org_units.js +123 -0
  138. package/build/src/core/roles.d.ts +98 -0
  139. package/build/src/core/roles.js +447 -0
  140. package/build/src/core/saved_views.d.ts +37 -0
  141. package/build/src/core/saved_views.js +164 -0
  142. package/build/src/core/settings.d.ts +29 -0
  143. package/build/src/core/settings.js +113 -0
  144. package/build/src/core/setup.d.ts +14 -0
  145. package/build/src/core/setup.js +89 -0
  146. package/build/src/core/ui_preferences.d.ts +12 -0
  147. package/build/src/core/ui_preferences.js +30 -0
  148. package/build/src/core/user_invitations.d.ts +23 -0
  149. package/build/src/core/user_invitations.js +144 -0
  150. package/build/src/core/users.d.ts +44 -0
  151. package/build/src/core/users.js +182 -0
  152. package/build/src/database/configure.d.ts +3 -0
  153. package/build/src/database/configure.js +41 -0
  154. package/build/src/database/schema.d.ts +52 -0
  155. package/build/src/database/schema.js +538 -0
  156. package/build/src/eslint/index.d.ts +3 -0
  157. package/build/src/eslint/index.js +90 -0
  158. package/build/src/events/adonis_jobs.d.ts +9 -0
  159. package/build/src/events/adonis_jobs.js +13 -0
  160. package/build/src/events/outbox.d.ts +19 -0
  161. package/build/src/events/outbox.js +33 -0
  162. package/build/src/events/record_mutation.d.ts +24 -0
  163. package/build/src/events/record_mutation.js +62 -0
  164. package/build/src/integrations/imports.d.ts +74 -0
  165. package/build/src/integrations/imports.js +333 -0
  166. package/build/src/integrations/inbound_webhooks.d.ts +94 -0
  167. package/build/src/integrations/inbound_webhooks.js +276 -0
  168. package/build/src/integrations/openapi.d.ts +39 -0
  169. package/build/src/integrations/openapi.js +323 -0
  170. package/build/src/integrations/print.d.ts +37 -0
  171. package/build/src/integrations/print.js +124 -0
  172. package/build/src/integrations/webhooks.d.ts +98 -0
  173. package/build/src/integrations/webhooks.js +298 -0
  174. package/build/src/mcp/tools.d.ts +8 -0
  175. package/build/src/mcp/tools.js +156 -0
  176. package/build/src/org/org_service.d.ts +2 -0
  177. package/build/src/org/org_service.js +16 -0
  178. package/build/src/resource/define_resource.d.ts +5 -0
  179. package/build/src/resource/define_resource.js +68 -0
  180. package/build/src/resource/registry.d.ts +12 -0
  181. package/build/src/resource/registry.js +101 -0
  182. package/build/src/resource/types.d.ts +155 -0
  183. package/build/src/resource/types.js +1 -0
  184. package/build/src/resource/values.d.ts +5 -0
  185. package/build/src/resource/values.js +88 -0
  186. package/build/src/services/backup.d.ts +14 -0
  187. package/build/src/services/backup.js +59 -0
  188. package/build/src/services/settings.d.ts +21 -0
  189. package/build/src/services/settings.js +30 -0
  190. package/build/src/upgrade/legacy.d.ts +27 -0
  191. package/build/src/upgrade/legacy.js +58 -0
  192. package/build/src/upgrade/rename.d.ts +17 -0
  193. package/build/src/upgrade/rename.js +94 -0
  194. package/build/src/version.d.ts +1 -0
  195. package/build/src/version.js +2 -0
  196. package/build/src/workflows/define_workflow.d.ts +124 -0
  197. package/build/src/workflows/define_workflow.js +123 -0
  198. package/build/src/workflows/engine.d.ts +141 -0
  199. package/build/src/workflows/engine.js +752 -0
  200. package/build/stubs/README.md +6 -0
  201. package/build/stubs/controller.stub +8 -0
  202. package/build/stubs/main.d.ts +5 -0
  203. package/build/stubs/main.js +5 -0
  204. package/build/stubs/main.ts +5 -0
  205. package/build/stubs/modules.stub +6 -0
  206. package/build/stubs/resource_contract.stub +1 -0
  207. package/build/stubs/resource_contract.txt +452 -0
  208. package/build/stubs/routes.stub +16 -0
  209. package/build/stubs/service.stub +9 -0
  210. package/package.json +95 -3
@@ -0,0 +1,375 @@
1
+ import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, join, relative } from 'node:path';
3
+ import { ADULA_VERSION } from '../version.js';
4
+ import { agentAssets, managedRules, digest } from './agent_assets.js';
5
+ import { columnName } from '../resource/define_resource.js';
6
+ // The deployment volume and backup scripts share this application-relative path.
7
+ const UPLOADS_PATH = 'storage/uploads';
8
+ const UPLOADS_WARNING_BYTES = 5_000_000_000;
9
+ /** An event the worker has not published within this age suggests that no worker runs. */
10
+ const OUTBOX_STALE_MS = 60_000;
11
+ async function assertContained(root, path) {
12
+ const resolved = relative(await realpath(root), await realpath(path));
13
+ if (resolved === '..' ||
14
+ resolved.startsWith('../') ||
15
+ resolved.startsWith('..\\') ||
16
+ isAbsolute(resolved))
17
+ throw new Error('Path resolves outside the application');
18
+ }
19
+ async function visitFiles(root, directory, visit) {
20
+ const path = join(root, directory);
21
+ try {
22
+ await lstat(path);
23
+ }
24
+ catch (error) {
25
+ if (error.code === 'ENOENT')
26
+ return false;
27
+ throw error;
28
+ }
29
+ await assertContained(root, path);
30
+ const walk = async (current) => {
31
+ const entry = await lstat(current);
32
+ if (entry.isSymbolicLink())
33
+ throw new Error('Symbolic links require manual inspection');
34
+ if (entry.isFile()) {
35
+ await visit(relative(root, current).replaceAll('\\', '/'), entry.size);
36
+ return;
37
+ }
38
+ if (!entry.isDirectory())
39
+ throw new Error('Unsupported filesystem entry');
40
+ const children = await readdir(current);
41
+ for (const child of children.sort())
42
+ await walk(join(current, child));
43
+ };
44
+ const entry = await lstat(path);
45
+ if (!entry.isDirectory())
46
+ throw new Error('Expected a directory');
47
+ await walk(path);
48
+ return true;
49
+ }
50
+ export function assessUploadSize(bytes) {
51
+ const large = bytes > UPLOADS_WARNING_BYTES;
52
+ return {
53
+ check: 'storage.uploads',
54
+ status: large ? 'warn' : 'pass',
55
+ message: `${UPLOADS_PATH} contains ${bytes} bytes (${(bytes / 1_000_000_000).toFixed(2)} GB); ${large
56
+ ? 'above 5 GB, plan an S3 migration and verify the uploaded files before removing local copies'
57
+ : 'within the 5 GB local-storage warning threshold'}`,
58
+ };
59
+ }
60
+ export async function diagnoseUploads(root) {
61
+ try {
62
+ let bytes = 0;
63
+ const exists = await visitFiles(root, UPLOADS_PATH, (_path, size) => {
64
+ bytes += size;
65
+ });
66
+ return exists
67
+ ? assessUploadSize(bytes)
68
+ : {
69
+ check: 'storage.uploads',
70
+ status: 'pass',
71
+ message: `${UPLOADS_PATH} does not exist; no local uploads volume to measure`,
72
+ };
73
+ }
74
+ catch {
75
+ return {
76
+ check: 'storage.uploads',
77
+ status: 'warn',
78
+ message: `Cannot completely measure ${UPLOADS_PATH}; check permissions, directory structure and symbolic links. Size is unknown`,
79
+ };
80
+ }
81
+ }
82
+ async function diagnosePages(root, changed) {
83
+ if (!changed.length)
84
+ return {
85
+ check: 'ui.pages',
86
+ status: 'pass',
87
+ message: 'No copied UI drift detected; page compatibility still requires typecheck and page tests',
88
+ };
89
+ const pages = [];
90
+ const collect = (file) => {
91
+ if (/\.[jt]sx$/.test(file))
92
+ pages.push(file);
93
+ };
94
+ try {
95
+ await visitFiles(root, 'inertia/pages', collect);
96
+ // Module-local page overrides are also project-owned extension points.
97
+ await visitFiles(root, 'app/modules', (file) => {
98
+ if (/^app\/modules\/[^/]+\/pages\//.test(file))
99
+ collect(file);
100
+ });
101
+ }
102
+ catch {
103
+ return {
104
+ check: 'ui.pages',
105
+ status: 'warn',
106
+ message: `UI review required (${changed.join('; ')}), but page sources could not be completely inventoried. Check source permissions and symbolic links, then run typecheck and page tests`,
107
+ };
108
+ }
109
+ return {
110
+ check: 'ui.pages',
111
+ status: 'warn',
112
+ message: `UI review required (${changed.join('; ')}). ${pages.length
113
+ ? `Review all ${pages.length} project-owned page sources: ${pages.sort().join(', ')}`
114
+ : 'No page sources found in inertia/pages or app/modules/*/pages; review overrides in the source checkout'}. This is a conservative inventory, not import dependency analysis; run typecheck and page tests`,
115
+ };
116
+ }
117
+ export async function diagnoseUi(root) {
118
+ try {
119
+ const lock = JSON.parse(await readFile(join(root, 'ui.lock.json'), 'utf8'));
120
+ if (typeof lock.version !== 'string' ||
121
+ typeof lock.adulaCompatibility !== 'string' ||
122
+ !lock.files ||
123
+ typeof lock.files !== 'object' ||
124
+ Array.isArray(lock.files))
125
+ throw new Error('Invalid UI lock');
126
+ const compatible = lock.adulaCompatibility === ADULA_VERSION.split('.').slice(0, 2).join('.');
127
+ const customized = [];
128
+ for (const [file, entry] of Object.entries(lock.files)) {
129
+ if (!/^inertia\/components\/ui\/[a-z][a-z0-9_-]*\.tsx?$/.test(file) ||
130
+ !entry ||
131
+ typeof entry.hash !== 'string' ||
132
+ !/^[a-f0-9]{64}$/.test(entry.hash))
133
+ throw new Error('Invalid UI lock entry');
134
+ const path = join(root, file);
135
+ await assertContained(root, path);
136
+ const info = await lstat(path);
137
+ if (!info.isFile())
138
+ throw new Error('UI component must be a regular file');
139
+ if (digest(await readFile(path, 'utf8')) !== entry.hash)
140
+ customized.push(file);
141
+ }
142
+ const changes = [
143
+ ...(!compatible ? ['UI registry compatibility differs from this AdulaJS version'] : []),
144
+ ...(customized.length ? [`copied UI changed: ${customized.sort().join(', ')}`] : []),
145
+ ];
146
+ return [
147
+ {
148
+ check: 'ui.compatibility',
149
+ status: compatible ? 'pass' : 'fail',
150
+ message: compatible
151
+ ? 'UI registry is compatible with this AdulaJS version'
152
+ : 'UI registry version requires a compatibility review',
153
+ },
154
+ {
155
+ check: 'ui.customizations',
156
+ status: customized.length ? 'warn' : 'pass',
157
+ message: customized.length
158
+ ? `${customized.length} project-owned UI files are customized; review diffs before updates`
159
+ : 'UI files match the installed registry snapshot',
160
+ },
161
+ await diagnosePages(root, changes),
162
+ ];
163
+ }
164
+ catch {
165
+ return [
166
+ {
167
+ check: 'ui.registry',
168
+ status: 'fail',
169
+ message: 'UI lock or component files are missing or invalid; run adula:ui add all',
170
+ },
171
+ ];
172
+ }
173
+ }
174
+ export async function diagnoseAgentSkills(root) {
175
+ let valid = false;
176
+ try {
177
+ const assets = await agentAssets();
178
+ const lock = JSON.parse(await readFile(join(root, 'adula.lock.json'), 'utf8'));
179
+ valid = lock.version === ADULA_VERSION && lock.managedRules === digest(assets.rules);
180
+ for (const [skillPath, content] of Object.entries(assets.skills)) {
181
+ const actual = await readFile(join(root, skillPath), 'utf8');
182
+ valid =
183
+ valid && lock.skills?.[skillPath] === digest(content) && digest(actual) === digest(content);
184
+ }
185
+ }
186
+ catch {
187
+ valid = false;
188
+ }
189
+ return {
190
+ check: 'agent.skills',
191
+ status: valid ? 'pass' : 'fail',
192
+ message: valid
193
+ ? 'Managed skill hashes match this AdulaJS version'
194
+ : 'Run adula:install to synchronize managed rules and skills',
195
+ };
196
+ }
197
+ export async function diagnose(root, settings, production, env, now = Date.now()) {
198
+ const findings = [];
199
+ findings.push(await diagnoseUploads(root));
200
+ const version = await settings.get('adula.version');
201
+ findings.push({
202
+ check: 'adula.version',
203
+ status: version === ADULA_VERSION ? 'pass' : 'fail',
204
+ message: version === ADULA_VERSION
205
+ ? `AdulaJS ${ADULA_VERSION} is installed`
206
+ : 'Run adula:install after migrations; installed AdulaJS version differs',
207
+ });
208
+ const template = await readFile(new URL('../../agent/AGENTS.template.md', import.meta.url), 'utf8');
209
+ let agents = '';
210
+ try {
211
+ agents = await readFile(join(root, 'AGENTS.md'), 'utf8');
212
+ }
213
+ catch { }
214
+ const managed = managedRules;
215
+ findings.push({
216
+ check: 'agent.rules',
217
+ status: managed(agents) === managed(template) ? 'pass' : 'fail',
218
+ message: managed(agents) === managed(template)
219
+ ? 'Managed rules match'
220
+ : 'Managed AGENTS.md was changed or is missing',
221
+ });
222
+ const keys = [
223
+ 'BACKUP_S3_ENDPOINT',
224
+ 'BACKUP_S3_BUCKET',
225
+ 'BACKUP_S3_REGION',
226
+ 'BACKUP_S3_ACCESS_KEY_ID',
227
+ 'BACKUP_S3_SECRET_ACCESS_KEY',
228
+ ];
229
+ const configured = keys.every((key) => Boolean(env[key]));
230
+ findings.push({
231
+ check: 'backup.config',
232
+ status: configured ? 'pass' : production ? 'fail' : 'warn',
233
+ message: configured ? 'Offsite settings are present' : 'Offsite backup is not configured',
234
+ });
235
+ for (const [key, maxDays] of [
236
+ ['backup.lastOffsite', 2],
237
+ ['backup.lastRestoreTest', 90],
238
+ ]) {
239
+ const date = await settings.get(key);
240
+ const fresh = date &&
241
+ Number.isFinite(Date.parse(date)) &&
242
+ now - Date.parse(date) >= 0 &&
243
+ now - Date.parse(date) < maxDays * 86400000;
244
+ findings.push({
245
+ check: key,
246
+ status: fresh ? 'pass' : production ? 'fail' : 'warn',
247
+ message: fresh ? `${key} is current` : `${key} is missing or older than ${maxDays} days`,
248
+ });
249
+ }
250
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
251
+ findings.push({
252
+ check: 'boundaries',
253
+ status: pkg.dependencies?.['patch-package'] ||
254
+ pkg.devDependencies?.['patch-package'] ||
255
+ pkg.pnpm?.patchedDependencies
256
+ ? 'fail'
257
+ : 'pass',
258
+ message: 'Application may not patch AdulaJS internals',
259
+ });
260
+ findings.push(await diagnoseAgentSkills(root));
261
+ if (pkg.dependencies?.['@adula/ui'] || pkg.devDependencies?.['@adula/ui'])
262
+ findings.push(...(await diagnoseUi(root)));
263
+ return findings;
264
+ }
265
+ /** The columns and indexes createResourceTable derives from a definition, one entry each. */
266
+ function tableShape(resource) {
267
+ const shape = new Map();
268
+ for (const flag of ['scoped', 'version', 'submittable', 'customFields'])
269
+ if (resource[flag])
270
+ shape.set(flag, flag);
271
+ for (const [key, field] of Object.entries(resource.fields)) {
272
+ if (field.type === 'hasMany')
273
+ continue;
274
+ const column = field.column ?? columnName(key);
275
+ const traits = [
276
+ field.type === 'belongsTo' ? `belongsTo ${field.resource}` : field.type,
277
+ ...(field.required || field.sequence ? ['required'] : []),
278
+ ...(field.unique ? ['unique'] : []),
279
+ ...(field.searchable ? ['searchable'] : []),
280
+ ];
281
+ shape.set(column, `${column} (${traits.join(', ')})`);
282
+ }
283
+ return shape;
284
+ }
285
+ /**
286
+ * A generated create-migration embeds the definition as it was at scaffold time. While it is
287
+ * still pending, compare that snapshot with the current resource so the table matches (#20).
288
+ */
289
+ export function diagnoseResourceSnapshots(pending, resource) {
290
+ const drift = [];
291
+ for (const { file, source } of pending) {
292
+ const embedded = /createResourceTable\([^,]+,\s*(\{[\s\S]*\})\s*\)\s*\}/.exec(source)?.[1];
293
+ if (!embedded)
294
+ continue;
295
+ let snapshot;
296
+ try {
297
+ snapshot = JSON.parse(embedded);
298
+ }
299
+ catch {
300
+ continue;
301
+ }
302
+ const current = resource(snapshot.name);
303
+ if (!current)
304
+ continue;
305
+ const [before, after] = [tableShape(snapshot), tableShape(current)];
306
+ const changed = [...new Set([...before.keys(), ...after.keys()])]
307
+ .filter((key) => before.get(key) !== after.get(key))
308
+ .map((key) => after.get(key) ?? `without ${before.get(key)}`);
309
+ if (changed.length)
310
+ drift.push(`${file} (${snapshot.name}): ${changed.join('; ')}`);
311
+ }
312
+ return {
313
+ check: 'resources.snapshots',
314
+ status: drift.length ? 'warn' : 'pass',
315
+ message: drift.length
316
+ ? `Pending create-migrations differ from their resource definitions; run node ace adula:resource:snapshot <name> (or update the embedded definition) before migration:run: ${drift.join(' | ')}`
317
+ : 'Pending resource migrations match their definitions',
318
+ };
319
+ }
320
+ /**
321
+ * Workflow recipients address roles by their stable key, or for compatibility by
322
+ * their editable display name. List references that match no role, and those that
323
+ * only match a display name, which a rename in the roles screen would break (#25).
324
+ */
325
+ export function diagnoseWorkflowRoles(workflows, roles) {
326
+ const keys = new Set(roles.flatMap((role) => (typeof role === 'string' || !role.key ? [] : [role.key])));
327
+ const names = new Set(roles.map((role) => (typeof role === 'string' ? role : role.name)));
328
+ const missing = [];
329
+ const byName = [];
330
+ for (const workflow of workflows)
331
+ for (const [key, step] of Object.entries(workflow.steps)) {
332
+ const to = step.type === 'approval' ? step.assignees : step.type === 'notify' ? step.to : null;
333
+ if (!to || typeof to !== 'object' || !('role' in to) || keys.has(to.role))
334
+ continue;
335
+ const reference = `${workflow.name}@${workflow.version}.${key} → "${to.role}"`;
336
+ if (names.has(to.role))
337
+ byName.push(reference);
338
+ else
339
+ missing.push(reference);
340
+ }
341
+ // Plain name lists (older hosts) cannot tell keys from names; only missing roles matter.
342
+ const keyed = roles.some((role) => typeof role !== 'string');
343
+ const messages = [
344
+ ...(missing.length
345
+ ? [
346
+ `Workflow steps address roles that match no role key or name; approvals there fail: ${missing.join(', ')}`,
347
+ ]
348
+ : []),
349
+ ...(keyed && byName.length
350
+ ? [
351
+ `Workflow steps address roles by display name; give each role a key and address it by key so renaming cannot detach approvers: ${byName.join(', ')}`,
352
+ ]
353
+ : []),
354
+ ];
355
+ return {
356
+ check: 'workflows.roles',
357
+ status: messages.length ? 'warn' : 'pass',
358
+ message: messages.length
359
+ ? messages.join(' | ')
360
+ : 'Every role addressed by a workflow step exists',
361
+ };
362
+ }
363
+ /** Events wait in the outbox until a worker publishes them; a stale backlog means none runs (#50). */
364
+ export function diagnoseOutbox(health) {
365
+ const { backlog, oldestAgeMs } = health.outbox;
366
+ const worker = health.heartbeats.worker.healthy ? 'running' : 'not running (no recent heartbeat)';
367
+ const stale = backlog > 0 && oldestAgeMs !== null && oldestAgeMs >= OUTBOX_STALE_MS;
368
+ return {
369
+ check: 'events.outbox',
370
+ status: stale ? 'warn' : 'pass',
371
+ message: stale
372
+ ? `${backlog} unpublished events, the oldest ${Math.round(oldestAgeMs / 1000)} s old; the worker is ${worker}. Listeners run only while \`node ace adula:worker\` runs`
373
+ : `No outbox event is older than ${OUTBOX_STALE_MS / 1000} s; the worker is ${worker}`,
374
+ };
375
+ }
@@ -0,0 +1,56 @@
1
+ export declare const ADULA_ISSUES_URL = "https://github.com/adulash/adulajs/issues";
2
+ /**
3
+ * GAPS.md entry fields, in the order of AdulaJS's gap issue form
4
+ * (.github/ISSUE_TEMPLATE/gap.yml). `id` is the form field id used to prefill it.
5
+ */
6
+ export declare const GAP_FIELDS: readonly [{
7
+ readonly label: "Package";
8
+ readonly id: "package";
9
+ readonly required: true;
10
+ }, {
11
+ readonly label: "Needed by";
12
+ readonly id: "needed";
13
+ readonly required: true;
14
+ }, {
15
+ readonly label: "Tried";
16
+ readonly id: "tried";
17
+ readonly required: true;
18
+ }, {
19
+ readonly label: "Blocked because";
20
+ readonly id: "blocked";
21
+ readonly required: true;
22
+ }, {
23
+ readonly label: "Proposed AdulaJS change";
24
+ readonly id: "proposal";
25
+ readonly required: true;
26
+ }, {
27
+ readonly label: "Reproduction";
28
+ readonly id: "reproduction";
29
+ readonly required: true;
30
+ }, {
31
+ readonly label: "Acceptance";
32
+ readonly id: "acceptance";
33
+ readonly required: true;
34
+ }, {
35
+ readonly label: "Workaround";
36
+ readonly id: "workaround";
37
+ readonly required: false;
38
+ }];
39
+ export declare const GAPS_TEMPLATE = "# AdulaJS gaps\n\nRecord each limitation of AdulaJS as one entry. Describe AdulaJS capability, not this\nproject: reproduce it on a new application from create-app. Run `node ace adula:gaps report`\nto open AdulaJS's gap form prefilled, then write the issue number in `Issue:`.\n\n<!--\n## GAP-001 \u2014 Short title naming AdulaJS capability\nPackage: adula 1.0.0\nNeeded by: AdulaJS capability that is missing, stated without project details\nTried: AdulaJS extension points tried\nBlocked because: why none of them works\nProposed AdulaJS change: the API, option or fix AdulaJS should offer\nReproduction: steps on a new application from create-app\nAcceptance: the test that proves the gap is closed\nWorkaround: none, or what the project does meanwhile\nIssue:\n-->\n";
40
+ export interface GapEntry {
41
+ title: string;
42
+ fields: Record<string, string>;
43
+ issue: string;
44
+ missing: string[];
45
+ url?: string;
46
+ }
47
+ /**
48
+ * Prepares GAPS.md for sharing with AdulaJS maintainers: e-mails, URLs and
49
+ * IPv4 addresses are masked, gap titles are listed for a quick review, and each
50
+ * unreported gap gets a link that opens AdulaJS's gap form prefilled. Nothing is sent.
51
+ */
52
+ export declare function gapReport(content: string, issuesUrl?: string): {
53
+ masked: string;
54
+ titles: string[];
55
+ gaps: GapEntry[];
56
+ };
@@ -0,0 +1,110 @@
1
+ export const ADULA_ISSUES_URL = 'https://github.com/adulash/adulajs/issues';
2
+ /**
3
+ * GAPS.md entry fields, in the order of AdulaJS's gap issue form
4
+ * (.github/ISSUE_TEMPLATE/gap.yml). `id` is the form field id used to prefill it.
5
+ */
6
+ export const GAP_FIELDS = [
7
+ { label: 'Package', id: 'package', required: true },
8
+ { label: 'Needed by', id: 'needed', required: true },
9
+ { label: 'Tried', id: 'tried', required: true },
10
+ { label: 'Blocked because', id: 'blocked', required: true },
11
+ { label: 'Proposed AdulaJS change', id: 'proposal', required: true },
12
+ { label: 'Reproduction', id: 'reproduction', required: true },
13
+ { label: 'Acceptance', id: 'acceptance', required: true },
14
+ { label: 'Workaround', id: 'workaround', required: false },
15
+ ];
16
+ export const GAPS_TEMPLATE = `# AdulaJS gaps
17
+
18
+ Record each limitation of AdulaJS as one entry. Describe AdulaJS capability, not this
19
+ project: reproduce it on a new application from create-app. Run \`node ace adula:gaps report\`
20
+ to open AdulaJS's gap form prefilled, then write the issue number in \`Issue:\`.
21
+
22
+ <!--
23
+ ## GAP-001 — Short title naming AdulaJS capability
24
+ Package: adula 1.0.0
25
+ Needed by: AdulaJS capability that is missing, stated without project details
26
+ Tried: AdulaJS extension points tried
27
+ Blocked because: why none of them works
28
+ Proposed AdulaJS change: the API, option or fix AdulaJS should offer
29
+ Reproduction: steps on a new application from create-app
30
+ Acceptance: the test that proves the gap is closed
31
+ Workaround: none, or what the project does meanwhile
32
+ Issue:
33
+ -->
34
+ `;
35
+ /** Longest value put in one prefilled field; GitHub rejects very long URLs. */
36
+ const FIELD_LIMIT = 1500;
37
+ const labels = [...GAP_FIELDS.map((field) => field.label), 'Issue'];
38
+ const fieldLine = new RegExp(`^(${labels.join('|')}):\\s*(.*)$`);
39
+ function parseGaps(masked) {
40
+ const gaps = [];
41
+ let current;
42
+ let field;
43
+ let comment = false;
44
+ for (const line of masked.split(/\r?\n/)) {
45
+ if (line.trim().startsWith('<!--'))
46
+ comment = true;
47
+ if (comment) {
48
+ if (line.includes('-->'))
49
+ comment = false;
50
+ continue;
51
+ }
52
+ const heading = line.match(/^## (GAP-\d+.*)$/);
53
+ if (heading) {
54
+ current = { title: heading[1].trim(), fields: {}, issue: '', missing: [] };
55
+ gaps.push(current);
56
+ field = undefined;
57
+ continue;
58
+ }
59
+ if (!current)
60
+ continue;
61
+ if (line.startsWith('#')) {
62
+ current = undefined;
63
+ continue;
64
+ }
65
+ const match = line.match(fieldLine);
66
+ if (match) {
67
+ field = match[1];
68
+ if (field === 'Issue')
69
+ current.issue = match[2].trim();
70
+ else
71
+ current.fields[field] = match[2].trim();
72
+ }
73
+ else if (field && field !== 'Issue') {
74
+ current.fields[field] = `${current.fields[field]}\n${line}`.trim();
75
+ }
76
+ }
77
+ return gaps;
78
+ }
79
+ function clip(value) {
80
+ return value.length > FIELD_LIMIT
81
+ ? `${value.slice(0, FIELD_LIMIT)}\n… (shortened; copy the rest from the masked report)`
82
+ : value;
83
+ }
84
+ /**
85
+ * Prepares GAPS.md for sharing with AdulaJS maintainers: e-mails, URLs and
86
+ * IPv4 addresses are masked, gap titles are listed for a quick review, and each
87
+ * unreported gap gets a link that opens AdulaJS's gap form prefilled. Nothing is sent.
88
+ */
89
+ export function gapReport(content, issuesUrl = ADULA_ISSUES_URL) {
90
+ const masked = content
91
+ .replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, '<email>')
92
+ .replace(/https?:\/\/[^\s)]+/g, '<url>')
93
+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, '<ip>');
94
+ const gaps = parseGaps(masked);
95
+ for (const gap of gaps) {
96
+ gap.missing = GAP_FIELDS.filter((field) => field.required && !gap.fields[field.label]).map((field) => field.label);
97
+ if (gap.issue)
98
+ continue;
99
+ const url = new URL(`${issuesUrl}/new`);
100
+ url.searchParams.set('template', 'gap.yml');
101
+ url.searchParams.set('title', gap.title.replace(/^GAP-\d+\s*[—–-]?\s*/, ''));
102
+ for (const field of GAP_FIELDS) {
103
+ const value = gap.fields[field.label];
104
+ if (value)
105
+ url.searchParams.set(field.id, clip(value));
106
+ }
107
+ gap.url = url.toString();
108
+ }
109
+ return { masked, titles: gaps.map((gap) => gap.title), gaps };
110
+ }
@@ -0,0 +1 @@
1
+ export declare function generateResource(root: string, name: string, module: string): Promise<string[]>;
@@ -0,0 +1,70 @@
1
+ import { mkdir, readFile, writeFile, access, glob } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { identifier } from '../resource/define_resource.js';
4
+ import { appendMarkedItem, moduleSource } from './source_markers.js';
5
+ export async function generateResource(root, name, module) {
6
+ identifier(name);
7
+ identifier(module);
8
+ for await (const existing of glob(`app/modules/*/resources/${name}.ts`, { cwd: root }))
9
+ throw new Error(`Refusing to overwrite resource registered at ${existing}`);
10
+ const base = resolve(root, 'app/modules', module);
11
+ const title = name.replace(/_/g, ' ');
12
+ const relative = `app/modules/${module}`;
13
+ const resourceSource = `import { defineResource } from 'adula'\nimport Model from '#modules/${module}/models/${name}'\nimport { validator } from '#modules/${module}/validators/${name}'\n\nexport default defineResource({\n name: '${name}', label: { ar: '${title}', en: '${title}' },\n recordLabel: { ar: '${title}', en: '${title}' }, model: Model, scoped: true,\n fields: { title: { type: 'string', label: { ar: 'العنوان', en: 'Title' }, required: true, searchable: true } },\n list: ['title'], form: ['title'], show: ['title'],\n actions: ['view', 'create', 'update', 'delete'], validator,\n})\n`;
14
+ const migration = {
15
+ name,
16
+ scoped: true,
17
+ fields: {
18
+ title: {
19
+ type: 'string',
20
+ label: { ar: 'العنوان', en: 'Title' },
21
+ required: true,
22
+ searchable: true,
23
+ },
24
+ },
25
+ };
26
+ const files = {
27
+ [`${relative}/resources/${name}.ts`]: resourceSource,
28
+ [`${relative}/models/${name}.ts`]: `import { BaseModel, column } from '@adonisjs/lucid/orm'\nimport { DateTime } from 'luxon'\n\nexport default class extends BaseModel {\n static table = '${name}'\n @column({ isPrimary: true }) declare id: number\n @column() declare title: string\n @column() declare orgUnitId: number\n @column() declare createdBy: number\n @column() declare updatedBy: number\n @column.dateTime({ autoCreate: true }) declare createdAt: DateTime\n @column.dateTime({ autoCreate: true, autoUpdate: true }) declare updatedAt: DateTime\n @column.dateTime() declare deletedAt: DateTime | null\n}\n`,
29
+ [`${relative}/validators/${name}.ts`]: `import vine from '@vinejs/vine'\nexport const validator = vine.create({ title: vine.string().trim().minLength(1).maxLength(255) })\n`,
30
+ [`${relative}/migrations/${Date.now()}_create_${name}.ts`]: `import { BaseSchema } from '@adonisjs/lucid/schema'\nimport { createResourceTable } from 'adula'\nexport default class extends BaseSchema {\n async up() { await createResourceTable(this.db.getWriteClient(), ${JSON.stringify(migration, null, 2)}) }\n async down() { throw new Error('Use an expand/contract migration or restore a backup') }\n}\n`,
31
+ [`${relative}/factories/${name}.ts`]: `import factory from '@adonisjs/lucid/factories'\nimport Model from '#modules/${module}/models/${name}'\nexport default factory.define(Model, ({ faker }) => ({ title: faker.lorem.words(3) })).build()\n`,
32
+ [`tests/functional/${name}.spec.ts`]: `import { resourceContract } from '#tests/helpers/resource_contract'\n\n// Extend this fixture whenever the resource form or its validator changes.\nresourceContract('${name}', ({ unique }) => ({\n input: { title: 'سجل ' + unique },\n expected: { title: 'سجل ' + unique },\n update: { title: 'سجل محدث ' + unique },\n updated: { title: 'سجل محدث ' + unique },\n}))\n`,
33
+ };
34
+ const modulePath = join(base, 'module.ts');
35
+ let current;
36
+ try {
37
+ current = await readFile(modulePath, 'utf8');
38
+ }
39
+ catch (error) {
40
+ if (error.code !== 'ENOENT')
41
+ throw error;
42
+ current = moduleSource(module);
43
+ }
44
+ if (!current.includes('// adula:imports') || !current.includes('/* adula:resources */'))
45
+ throw new Error('Module registration markers are missing; no files were changed');
46
+ const modulesPath = join(root, 'start/modules.ts');
47
+ const modules = await readFile(modulesPath, 'utf8');
48
+ if (!modules.includes('// adula:imports') || !modules.includes('/* adula:modules */'))
49
+ throw new Error('Module index markers are missing; no files were changed');
50
+ for (const file of Object.keys(files)) {
51
+ try {
52
+ await access(join(root, file));
53
+ throw new Error(`Refusing to overwrite ${file}`);
54
+ }
55
+ catch (error) {
56
+ if (error.code !== 'ENOENT')
57
+ throw error;
58
+ }
59
+ }
60
+ for (const [file, content] of Object.entries(files)) {
61
+ const path = join(root, file);
62
+ await mkdir(dirname(path), { recursive: true });
63
+ await writeFile(path, content, { flag: 'wx' });
64
+ }
65
+ await mkdir(base, { recursive: true });
66
+ await writeFile(modulePath, appendMarkedItem(current.replace('// adula:imports', `import resource_${name} from './resources/${name}.js'\n// adula:imports`), '/* adula:resources */', `resource_${name}`));
67
+ if (!modules.includes(`'#modules/${module}/module'`))
68
+ await writeFile(modulesPath, appendMarkedItem(modules.replace('// adula:imports', `import module_${module} from '#modules/${module}/module'\n// adula:imports`), '/* adula:modules */', `module_${module}`));
69
+ return Object.keys(files);
70
+ }
@@ -0,0 +1,28 @@
1
+ import type { Resource } from '../resource/types.js';
2
+ /**
3
+ * The part of a resource definition createResourceTable reads, as a generated
4
+ * create-migration embeds it. Labels are kept so the migration stays readable.
5
+ */
6
+ export declare function resourceSnapshot(resource: Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'customFields' | 'fields'>): {
7
+ fields: {
8
+ [k: string]: {
9
+ sequence?: string | undefined;
10
+ searchable?: boolean | undefined;
11
+ unique?: boolean | undefined;
12
+ required?: boolean | undefined;
13
+ column?: string | undefined;
14
+ resource?: string | undefined;
15
+ type: "string" | "boolean" | "text" | "integer" | "money" | "date" | "datetime" | "json" | "attachment" | "belongsTo" | "user" | "hasMany" | "lookup";
16
+ label: import("../resource/types.js").Label;
17
+ };
18
+ };
19
+ customFields?: boolean | undefined;
20
+ submittable?: boolean | undefined;
21
+ version?: boolean | undefined;
22
+ name: string;
23
+ scoped: boolean;
24
+ };
25
+ /** The resource name embedded in a generated create-migration, if the source is one. */
26
+ export declare function embeddedResource(source: string): string | undefined;
27
+ /** Replaces the embedded definition of a generated create-migration (#20). */
28
+ export declare function rewriteResourceSnapshot(source: string, snapshot: ReturnType<typeof resourceSnapshot>): string;