neuralbrain 0.0.1 → 0.1.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 (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +3 -2
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
package/src/lib/logger.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import pino from 'pino';
2
2
 
3
+ const redact = ['req.headers.authorization', 'apiKey', 'rawKey', 'key'];
4
+
3
5
  export const logger = pino(
4
6
  process.env.NODE_ENV === 'production'
5
- ? {}
6
- : { transport: { target: 'pino-pretty', options: { colorize: true } } }
7
+ ? { redact }
8
+ : { redact, transport: { target: 'pino-pretty', options: { colorize: true } } }
7
9
  );
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs';
2
+ import os from 'os';
2
3
  import path from 'path';
3
4
  import { normalizeProjectId } from './scope';
4
5
  import { getBrainHomeDir } from './brainHome';
@@ -9,13 +10,27 @@ export interface ResolveProjectIdOptions {
9
10
  fallbackToDirname?: boolean;
10
11
  }
11
12
 
13
+ export interface WriteBrainRcOptions {
14
+ autoSubproject?: boolean;
15
+ maxDepth?: number;
16
+ }
17
+
18
+ function sanitizeSegment(raw: string): string {
19
+ return raw
20
+ .toLowerCase()
21
+ .replace(/[^a-z0-9._-]+/g, '-')
22
+ .replace(/^-+|-+$/g, '');
23
+ }
24
+
12
25
  /**
13
26
  * Resolves the canonical project ID slug for a workspace or directory.
14
27
  *
15
28
  * The id names the project's ROOT folder, never whichever subfolder the agent
16
- * happens to be in. Precedence:
17
- * 1. Explicit project ID (validated and normalized).
18
- * 2. .brainrc or .brain.json, found by walking up every parent of cwd (or process.cwd()).
29
+ * happens to be in (unless `.brainrc` opts into `auto_subproject: true`).
30
+ * Precedence:
31
+ * 1. Explicit project ID (validated and normalized, including hierarchical a/b/c).
32
+ * 2. .brainrc or .brain.json, found by walking up from cwd (stopping after
33
+ * os.homedir() if cwd is inside home, or filesystem root otherwise).
19
34
  * 3. If fallbackToDirname: the git repository root's folder name. In a git
20
35
  * worktree that is the MAIN repository, not the worktree folder.
21
36
  * 4. BRAIN_DEFAULT_PROJECT_ID environment variable.
@@ -34,8 +49,12 @@ export function resolveCanonicalProjectId(options?: ResolveProjectIdOptions): st
34
49
  }
35
50
  }
36
51
 
37
- // 2. Walk up from options.cwd || process.cwd(), through every parent
52
+ // 2. Walk up from options.cwd || process.cwd()
38
53
  const startDir = path.resolve(options?.cwd || process.cwd());
54
+ const homeDir = path.resolve(os.homedir());
55
+ const homePrefix = homeDir.endsWith(path.sep) ? homeDir : homeDir + path.sep;
56
+ const stopAtHome = startDir === homeDir || startDir.startsWith(homePrefix);
57
+
39
58
  let currentDir = startDir;
40
59
 
41
60
  for (;;) {
@@ -46,10 +65,18 @@ export function resolveCanonicalProjectId(options?: ResolveProjectIdOptions): st
46
65
  try {
47
66
  const content = fs.readFileSync(candidatePath, 'utf-8');
48
67
  let slug: string | null = null;
68
+ let autoSubproject = false;
69
+ let maxDepth: number | undefined;
70
+
49
71
  try {
50
72
  const parsed = JSON.parse(content);
51
73
  if (parsed && typeof parsed === 'object') {
52
74
  slug = parsed.project_id || parsed.projectId || parsed.project || null;
75
+ autoSubproject = Boolean(parsed.auto_subproject ?? parsed.autoSubproject);
76
+ const rawMaxDepth = parsed.max_depth ?? parsed.maxDepth;
77
+ if (typeof rawMaxDepth === 'number' && Number.isInteger(rawMaxDepth) && rawMaxDepth > 0) {
78
+ maxDepth = rawMaxDepth;
79
+ }
53
80
  } else if (typeof parsed === 'string') {
54
81
  slug = parsed;
55
82
  }
@@ -59,9 +86,28 @@ export function resolveCanonicalProjectId(options?: ResolveProjectIdOptions): st
59
86
  }
60
87
 
61
88
  if (slug && typeof slug === 'string') {
62
- const norm = normalizeProjectId(slug.trim());
63
- if (norm.ok) {
64
- return norm.projectId;
89
+ const baseNorm = normalizeProjectId(slug.trim());
90
+ if (baseNorm.ok) {
91
+ if (autoSubproject && startDir !== currentDir) {
92
+ const rel = path.relative(currentDir, startDir);
93
+ let segments = rel
94
+ .split(path.sep)
95
+ .map(sanitizeSegment)
96
+ .filter((seg) => seg.length > 0 && seg !== '.' && seg !== '..');
97
+
98
+ if (maxDepth !== undefined) {
99
+ segments = segments.slice(0, maxDepth);
100
+ }
101
+
102
+ if (segments.length > 0) {
103
+ const combined = `${baseNorm.projectId}/${segments.join('/')}`;
104
+ const combinedNorm = normalizeProjectId(combined);
105
+ if (combinedNorm.ok) {
106
+ return combinedNorm.projectId;
107
+ }
108
+ }
109
+ }
110
+ return baseNorm.projectId;
65
111
  }
66
112
  }
67
113
  } catch {
@@ -70,6 +116,10 @@ export function resolveCanonicalProjectId(options?: ResolveProjectIdOptions): st
70
116
  }
71
117
  }
72
118
 
119
+ if (stopAtHome && currentDir === homeDir) {
120
+ break;
121
+ }
122
+
73
123
  const parentDir = path.dirname(currentDir);
74
124
  if (parentDir === currentDir) {
75
125
  // Reached filesystem root
@@ -107,10 +157,7 @@ export function resolveCanonicalProjectId(options?: ResolveProjectIdOptions): st
107
157
  }
108
158
 
109
159
  function slugFromFolderName(name: string): string | null {
110
- const sanitized = name
111
- .toLowerCase()
112
- .replace(/[^a-z0-9._-]+/g, '-')
113
- .replace(/^-+|-+$/g, '');
160
+ const sanitized = sanitizeSegment(name);
114
161
  if (!sanitized) return null;
115
162
  const norm = normalizeProjectId(sanitized);
116
163
  return norm.ok ? norm.projectId : null;
@@ -239,11 +286,13 @@ function prunePins(dir: string): void {
239
286
  }
240
287
 
241
288
  /**
242
- * Writes a canonical .brainrc file in projectDir with { "project_id": "<slug>" }.
289
+ * Writes a canonical .brainrc file in projectDir with { "project_id": "<slug>" }
290
+ * (plus optional auto_subproject / max_depth when opted in).
243
291
  */
244
292
  export function writeBrainRc(
245
293
  projectDir: string,
246
- projectId?: string
294
+ projectId?: string,
295
+ options?: WriteBrainRcOptions
247
296
  ): { filePath: string; projectId: string } {
248
297
  const resolvedDir = path.resolve(projectDir);
249
298
  let slug: string | null = null;
@@ -253,11 +302,7 @@ export function writeBrainRc(
253
302
  if (initialNorm.ok) {
254
303
  slug = initialNorm.projectId;
255
304
  } else {
256
- const sanitized = projectId
257
- .trim()
258
- .toLowerCase()
259
- .replace(/[^a-z0-9._-]+/g, '-')
260
- .replace(/^-+|-+$/g, '');
305
+ const sanitized = sanitizeSegment(projectId.trim());
261
306
  const sanitizedNorm = normalizeProjectId(sanitized);
262
307
  if (sanitizedNorm.ok) {
263
308
  slug = sanitizedNorm.projectId;
@@ -267,10 +312,7 @@ export function writeBrainRc(
267
312
 
268
313
  if (!slug) {
269
314
  const basename = path.basename(resolvedDir);
270
- const sanitized = basename
271
- .toLowerCase()
272
- .replace(/[^a-z0-9._-]+/g, '-')
273
- .replace(/^-+|-+$/g, '');
315
+ const sanitized = sanitizeSegment(basename);
274
316
  const norm = normalizeProjectId(sanitized);
275
317
  if (!norm.ok) {
276
318
  throw new Error(`Failed to derive valid project_id for '${projectDir}': ${norm.error}`);
@@ -278,8 +320,20 @@ export function writeBrainRc(
278
320
  slug = norm.projectId;
279
321
  }
280
322
 
323
+ const payload: Record<string, unknown> = { project_id: slug };
324
+ if (options?.autoSubproject) {
325
+ payload.auto_subproject = true;
326
+ if (
327
+ typeof options.maxDepth === 'number' &&
328
+ Number.isInteger(options.maxDepth) &&
329
+ options.maxDepth > 0
330
+ ) {
331
+ payload.max_depth = options.maxDepth;
332
+ }
333
+ }
334
+
281
335
  const filePath = path.join(resolvedDir, '.brainrc');
282
- const content = JSON.stringify({ project_id: slug }, null, 2) + '\n';
336
+ const content = JSON.stringify(payload, null, 2) + '\n';
283
337
  fs.writeFileSync(filePath, content, 'utf-8');
284
338
 
285
339
  return { filePath, projectId: slug };
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Zero-dependency UTC date/time normalization, cron & ISO-8601 recurrence validation,
3
+ * next-occurrence calculation, and duration parsing.
4
+ */
5
+
6
+ const CRON_MACROS: Record<string, string> = {
7
+ '@hourly': '0 * * * *',
8
+ '@daily': '0 0 * * *',
9
+ '@midnight': '0 0 * * *',
10
+ '@weekly': '0 0 * * 0',
11
+ '@monthly': '0 0 1 * *',
12
+ '@yearly': '0 0 1 1 *',
13
+ '@annually': '0 0 1 1 *',
14
+ };
15
+
16
+ const ISO_DURATION_RE =
17
+ /^(?:R\/)?P(?=\d|T\d)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/i;
18
+
19
+ const FIXED_ISO_DURATION_RE =
20
+ /^P(?=\d|T\d)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/i;
21
+
22
+ const SHORT_DURATION_RE = /^(\d+)([smhdw])$/i;
23
+
24
+ function makeSchemaError(message: string): Error {
25
+ const err = new Error(message);
26
+ (err as any).code = 'SCHEMA_INVALID';
27
+ return err;
28
+ }
29
+
30
+ export function normalizeUtcIso(raw: unknown, field: string): string | null {
31
+ if (raw === undefined || raw === null) {
32
+ return null;
33
+ }
34
+
35
+ if (raw instanceof Date) {
36
+ if (Number.isNaN(raw.getTime())) {
37
+ throw makeSchemaError(`${field} must be a valid Date`);
38
+ }
39
+ return raw.toISOString();
40
+ }
41
+
42
+ if (typeof raw !== 'string') {
43
+ throw makeSchemaError(`${field} must be an ISO-8601 date/time string or Date`);
44
+ }
45
+
46
+ const trimmed = raw.trim();
47
+ if (trimmed === '') {
48
+ return null;
49
+ }
50
+
51
+ const parsed = new Date(trimmed);
52
+ if (Number.isNaN(parsed.getTime())) {
53
+ throw makeSchemaError(`${field} '${trimmed}' is not a valid ISO-8601 date/time`);
54
+ }
55
+
56
+ return parsed.toISOString();
57
+ }
58
+
59
+ interface ParsedCron {
60
+ minutes: Set<number>;
61
+ hours: Set<number>;
62
+ doms: Set<number>;
63
+ months: Set<number>;
64
+ dows: Set<number>;
65
+ domWildcard: boolean;
66
+ dowWildcard: boolean;
67
+ }
68
+
69
+ function parseCronField(
70
+ field: string,
71
+ min: number,
72
+ max: number,
73
+ fieldName: string,
74
+ mapValue?: (v: number) => number
75
+ ): { values: Set<number>; isWildcard: boolean } | { error: string } {
76
+ const trimmed = field.trim();
77
+ if (!trimmed) {
78
+ return { error: `Empty cron ${fieldName} field` };
79
+ }
80
+
81
+ const isWildcard = trimmed === '*';
82
+ const values = new Set<number>();
83
+ const addVal = (v: number) => {
84
+ values.add(mapValue ? mapValue(v) : v);
85
+ };
86
+
87
+ for (const rawPart of trimmed.split(',')) {
88
+ const part = rawPart.trim();
89
+ if (!part) {
90
+ return { error: `Empty list entry in cron ${fieldName} field '${field}'` };
91
+ }
92
+
93
+ if (part === '*') {
94
+ for (let v = min; v <= max; v++) addVal(v);
95
+ continue;
96
+ }
97
+
98
+ const starStep = /^\*\/(\d+)$/.exec(part);
99
+ if (starStep) {
100
+ const step = Number(starStep[1]);
101
+ if (!Number.isInteger(step) || step <= 0) {
102
+ return { error: `Invalid step in cron ${fieldName} field '${part}'` };
103
+ }
104
+ for (let v = min; v <= max; v += step) addVal(v);
105
+ continue;
106
+ }
107
+
108
+ const rangeStep = /^(\d+)-(\d+)(?:\/(\d+))?$/.exec(part);
109
+ if (rangeStep) {
110
+ const start = Number(rangeStep[1]);
111
+ const end = Number(rangeStep[2]);
112
+ const step = rangeStep[3] !== undefined ? Number(rangeStep[3]) : 1;
113
+ if (
114
+ !Number.isInteger(start) ||
115
+ !Number.isInteger(end) ||
116
+ !Number.isInteger(step) ||
117
+ start < min ||
118
+ end > max ||
119
+ start > end ||
120
+ step <= 0
121
+ ) {
122
+ return { error: `Invalid range '${part}' for cron ${fieldName} (${min}-${max})` };
123
+ }
124
+ for (let v = start; v <= end; v += step) addVal(v);
125
+ continue;
126
+ }
127
+
128
+ const single = /^(\d+)$/.exec(part);
129
+ if (single) {
130
+ const val = Number(single[1]);
131
+ if (!Number.isInteger(val) || val < min || val > max) {
132
+ return { error: `Value '${part}' out of range for cron ${fieldName} (${min}-${max})` };
133
+ }
134
+ addVal(val);
135
+ continue;
136
+ }
137
+
138
+ return { error: `Unsupported cron token '${part}' in ${fieldName} field` };
139
+ }
140
+
141
+ if (values.size === 0) {
142
+ return { error: `Cron ${fieldName} field '${field}' produced no values` };
143
+ }
144
+
145
+ return { values, isWildcard };
146
+ }
147
+
148
+ function parseCronExpression(expr: string): { ok: true; parsed: ParsedCron; normalized: string } | { ok: false; error: string } {
149
+ const trimmed = expr.trim();
150
+ const macroExpanded = CRON_MACROS[trimmed.toLowerCase()];
151
+ const canonical = (macroExpanded ?? trimmed).replace(/\s+/g, ' ');
152
+ const parts = canonical.split(' ');
153
+ if (parts.length !== 5) {
154
+ return { ok: false, error: `Cron expression must have 5 fields, got ${parts.length}` };
155
+ }
156
+
157
+ const minRes = parseCronField(parts[0], 0, 59, 'minute');
158
+ if ('error' in minRes) return { ok: false, error: minRes.error };
159
+
160
+ const hourRes = parseCronField(parts[1], 0, 23, 'hour');
161
+ if ('error' in hourRes) return { ok: false, error: hourRes.error };
162
+
163
+ const domRes = parseCronField(parts[2], 1, 31, 'day-of-month');
164
+ if ('error' in domRes) return { ok: false, error: domRes.error };
165
+
166
+ const monthRes = parseCronField(parts[3], 1, 12, 'month');
167
+ if ('error' in monthRes) return { ok: false, error: monthRes.error };
168
+
169
+ const dowRes = parseCronField(parts[4], 0, 7, 'day-of-week', (v) => (v === 7 ? 0 : v));
170
+ if ('error' in dowRes) return { ok: false, error: dowRes.error };
171
+
172
+ return {
173
+ ok: true,
174
+ normalized: canonical,
175
+ parsed: {
176
+ minutes: minRes.values,
177
+ hours: hourRes.values,
178
+ doms: domRes.values,
179
+ months: monthRes.values,
180
+ dows: dowRes.values,
181
+ domWildcard: domRes.isWildcard,
182
+ dowWildcard: dowRes.isWildcard,
183
+ },
184
+ };
185
+ }
186
+
187
+ interface ParsedIsoDuration {
188
+ years: number;
189
+ months: number;
190
+ weeks: number;
191
+ days: number;
192
+ hours: number;
193
+ minutes: number;
194
+ seconds: number;
195
+ }
196
+
197
+ function parseIsoDuration(expr: string): ParsedIsoDuration | null {
198
+ const match = ISO_DURATION_RE.exec(expr.trim());
199
+ if (!match) return null;
200
+
201
+ const years = match[1] ? Number(match[1]) : 0;
202
+ const months = match[2] ? Number(match[2]) : 0;
203
+ const weeks = match[3] ? Number(match[3]) : 0;
204
+ const days = match[4] ? Number(match[4]) : 0;
205
+ const hours = match[5] ? Number(match[5]) : 0;
206
+ const minutes = match[6] ? Number(match[6]) : 0;
207
+ const seconds = match[7] ? Number(match[7]) : 0;
208
+
209
+ if (years + months + weeks + days + hours + minutes + seconds <= 0) {
210
+ return null;
211
+ }
212
+
213
+ return { years, months, weeks, days, hours, minutes, seconds };
214
+ }
215
+
216
+ export function validateRecurrence(
217
+ expr: string
218
+ ): { ok: true; kind: 'cron' | 'iso'; normalized: string } | { ok: false; error: string } {
219
+ if (typeof expr !== 'string' || expr.trim() === '') {
220
+ return { ok: false, error: 'Recurrence expression must be a non-empty string' };
221
+ }
222
+
223
+ const trimmed = expr.trim();
224
+ const upper = trimmed.toUpperCase();
225
+
226
+ if (upper.startsWith('P') || upper.startsWith('R/P')) {
227
+ const iso = parseIsoDuration(trimmed);
228
+ if (!iso) {
229
+ return {
230
+ ok: false,
231
+ error: `Invalid ISO-8601 recurrence duration '${trimmed}' (must be non-zero duration)`,
232
+ };
233
+ }
234
+ return { ok: true, kind: 'iso', normalized: upper };
235
+ }
236
+
237
+ const cron = parseCronExpression(trimmed);
238
+ if (!cron.ok) {
239
+ return cron;
240
+ }
241
+ return { ok: true, kind: 'cron', normalized: cron.normalized };
242
+ }
243
+
244
+ export function computeNextOccurrence(expr: string, fromDate: Date): Date {
245
+ if (!(fromDate instanceof Date) || Number.isNaN(fromDate.getTime())) {
246
+ throw makeSchemaError('fromDate must be a valid Date');
247
+ }
248
+
249
+ const validated = validateRecurrence(expr);
250
+ if (!validated.ok) {
251
+ throw makeSchemaError(validated.error);
252
+ }
253
+
254
+ if (validated.kind === 'iso') {
255
+ const dur = parseIsoDuration(validated.normalized)!;
256
+ const totalMonths =
257
+ fromDate.getUTCFullYear() * 12 +
258
+ fromDate.getUTCMonth() +
259
+ dur.years * 12 +
260
+ dur.months;
261
+ const targetYear = Math.floor(totalMonths / 12);
262
+ const targetMonth = totalMonths % 12;
263
+ const daysInTargetMonth = new Date(Date.UTC(targetYear, targetMonth + 1, 0)).getUTCDate();
264
+ const clampedDay = Math.min(fromDate.getUTCDate(), daysInTargetMonth);
265
+
266
+ const baseMs = Date.UTC(
267
+ targetYear,
268
+ targetMonth,
269
+ clampedDay,
270
+ fromDate.getUTCHours(),
271
+ fromDate.getUTCMinutes(),
272
+ fromDate.getUTCSeconds(),
273
+ fromDate.getUTCMilliseconds()
274
+ );
275
+ const extraMs =
276
+ (dur.weeks * 7 + dur.days) * 86_400_000 +
277
+ dur.hours * 3_600_000 +
278
+ dur.minutes * 60_000 +
279
+ dur.seconds * 1_000;
280
+
281
+ return new Date(baseMs + extraMs);
282
+ }
283
+
284
+ const cronRes = parseCronExpression(validated.normalized);
285
+ if (!cronRes.ok) {
286
+ throw makeSchemaError(cronRes.error);
287
+ }
288
+ const cron = cronRes.parsed;
289
+
290
+ // Advance strictly past fromDate to the next whole UTC minute
291
+ const startMs = Math.floor(fromDate.getTime() / 60_000) * 60_000 + 60_000;
292
+ const maxMs = Date.UTC(
293
+ fromDate.getUTCFullYear() + 5,
294
+ fromDate.getUTCMonth(),
295
+ fromDate.getUTCDate(),
296
+ fromDate.getUTCHours(),
297
+ fromDate.getUTCMinutes(),
298
+ 0,
299
+ 0
300
+ );
301
+
302
+ const cursor = new Date(startMs);
303
+ while (cursor.getTime() <= maxMs) {
304
+ const month = cursor.getUTCMonth() + 1;
305
+ if (!cron.months.has(month)) {
306
+ cursor.setUTCMonth(cursor.getUTCMonth() + 1, 1);
307
+ cursor.setUTCHours(0, 0, 0, 0);
308
+ continue;
309
+ }
310
+
311
+ const dom = cursor.getUTCDate();
312
+ const dow = cursor.getUTCDay();
313
+ const domMatch = cron.doms.has(dom);
314
+ const dowMatch = cron.dows.has(dow);
315
+ const dayMatches =
316
+ !cron.domWildcard && !cron.dowWildcard
317
+ ? domMatch || dowMatch
318
+ : domMatch && dowMatch;
319
+
320
+ if (!dayMatches) {
321
+ cursor.setUTCDate(cursor.getUTCDate() + 1);
322
+ cursor.setUTCHours(0, 0, 0, 0);
323
+ continue;
324
+ }
325
+
326
+ const hour = cursor.getUTCHours();
327
+ if (!cron.hours.has(hour)) {
328
+ cursor.setUTCHours(hour + 1, 0, 0, 0);
329
+ continue;
330
+ }
331
+
332
+ const minute = cursor.getUTCMinutes();
333
+ if (!cron.minutes.has(minute)) {
334
+ cursor.setUTCMinutes(minute + 1, 0, 0);
335
+ continue;
336
+ }
337
+
338
+ return cursor;
339
+ }
340
+
341
+ throw makeSchemaError(`No matching occurrence found within 5 years for cron '${expr}'`);
342
+ }
343
+
344
+ export function parseDurationMs(raw: string): number | null {
345
+ if (typeof raw !== 'string') return null;
346
+ const trimmed = raw.trim();
347
+ if (!trimmed) return null;
348
+
349
+ const shortMatch = SHORT_DURATION_RE.exec(trimmed);
350
+ if (shortMatch) {
351
+ const amount = Number(shortMatch[1]);
352
+ const unit = shortMatch[2].toLowerCase();
353
+ if (!Number.isFinite(amount) || amount <= 0) return null;
354
+ const multipliers: Record<string, number> = {
355
+ s: 1_000,
356
+ m: 60_000,
357
+ h: 3_600_000,
358
+ d: 86_400_000,
359
+ w: 604_800_000,
360
+ };
361
+ return amount * multipliers[unit];
362
+ }
363
+
364
+ const isoMatch = FIXED_ISO_DURATION_RE.exec(trimmed);
365
+ if (isoMatch) {
366
+ const weeks = isoMatch[1] ? Number(isoMatch[1]) : 0;
367
+ const days = isoMatch[2] ? Number(isoMatch[2]) : 0;
368
+ const hours = isoMatch[3] ? Number(isoMatch[3]) : 0;
369
+ const minutes = isoMatch[4] ? Number(isoMatch[4]) : 0;
370
+ const seconds = isoMatch[5] ? Number(isoMatch[5]) : 0;
371
+
372
+ const totalMs =
373
+ (weeks * 7 + days) * 86_400_000 +
374
+ hours * 3_600_000 +
375
+ minutes * 60_000 +
376
+ seconds * 1_000;
377
+
378
+ return totalMs > 0 ? totalMs : null;
379
+ }
380
+
381
+ return null;
382
+ }