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.
- package/.env.example +2 -2
- package/README.md +19 -4
- package/dist/ai/chat.d.ts +1 -2
- package/dist/ai/chat.d.ts.map +1 -1
- package/dist/ai/chat.js +1 -2
- package/dist/ai/chat.js.map +1 -1
- package/dist/ai/config.d.ts +1 -1
- package/dist/ai/config.js +2 -2
- package/dist/ai/config.js.map +1 -1
- package/dist/app.d.ts +1 -0
- package/dist/app.d.ts.map +1 -1
- package/dist/app.js +417 -50
- package/dist/app.js.map +1 -1
- package/dist/cli.d.ts +53 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +437 -37
- package/dist/cli.js.map +1 -1
- package/dist/consolidation/candidates.d.ts.map +1 -1
- package/dist/consolidation/candidates.js +19 -4
- package/dist/consolidation/candidates.js.map +1 -1
- package/dist/consolidation/fixtures.js +1 -1
- package/dist/consolidation/fixtures.js.map +1 -1
- package/dist/consolidation/gate.d.ts.map +1 -1
- package/dist/consolidation/gate.js +145 -109
- package/dist/consolidation/gate.js.map +1 -1
- package/dist/consolidation/runner.d.ts +6 -0
- package/dist/consolidation/runner.d.ts.map +1 -1
- package/dist/consolidation/runner.js +22 -2
- package/dist/consolidation/runner.js.map +1 -1
- package/dist/dashboard/clientScript.d.ts +1 -1
- package/dist/dashboard/clientScript.d.ts.map +1 -1
- package/dist/dashboard/clientScript.js +3774 -905
- package/dist/dashboard/clientScript.js.map +1 -1
- package/dist/dashboard/html.d.ts.map +1 -1
- package/dist/dashboard/html.js +605 -101
- package/dist/dashboard/html.js.map +1 -1
- package/dist/dashboard/styles.d.ts +1 -1
- package/dist/dashboard/styles.d.ts.map +1 -1
- package/dist/dashboard/styles.js +1591 -359
- package/dist/dashboard/styles.js.map +1 -1
- package/dist/learning/embedWorker.d.ts +13 -0
- package/dist/learning/embedWorker.d.ts.map +1 -1
- package/dist/learning/embedWorker.js +329 -59
- package/dist/learning/embedWorker.js.map +1 -1
- package/dist/learning/embedding.d.ts +1 -0
- package/dist/learning/embedding.d.ts.map +1 -1
- package/dist/learning/embedding.js +101 -26
- package/dist/learning/embedding.js.map +1 -1
- package/dist/learning/engine.js +1 -1
- package/dist/learning/engine.js.map +1 -1
- package/dist/learning/search.d.ts +17 -1
- package/dist/learning/search.d.ts.map +1 -1
- package/dist/learning/search.js +2094 -354
- package/dist/learning/search.js.map +1 -1
- package/dist/learning/storeMeta.d.ts +9 -0
- package/dist/learning/storeMeta.d.ts.map +1 -1
- package/dist/learning/storeMeta.js +30 -24
- package/dist/learning/storeMeta.js.map +1 -1
- package/dist/learning/types.d.ts +57 -8
- package/dist/learning/types.d.ts.map +1 -1
- package/dist/lib/condenser.d.ts +112 -0
- package/dist/lib/condenser.d.ts.map +1 -0
- package/dist/lib/condenser.js +1337 -0
- package/dist/lib/condenser.js.map +1 -0
- package/dist/lib/db.d.ts +10 -0
- package/dist/lib/db.d.ts.map +1 -1
- package/dist/lib/db.js +654 -167
- package/dist/lib/db.js.map +1 -1
- package/dist/lib/logger.d.ts.map +1 -1
- package/dist/lib/logger.js +3 -2
- package/dist/lib/logger.js.map +1 -1
- package/dist/lib/projectSlug.d.ts +12 -5
- package/dist/lib/projectSlug.d.ts.map +1 -1
- package/dist/lib/projectSlug.js +62 -23
- package/dist/lib/projectSlug.js.map +1 -1
- package/dist/lib/recurrence.d.ts +16 -0
- package/dist/lib/recurrence.d.ts.map +1 -0
- package/dist/lib/recurrence.js +293 -0
- package/dist/lib/recurrence.js.map +1 -0
- package/dist/lib/scope.d.ts +36 -1
- package/dist/lib/scope.d.ts.map +1 -1
- package/dist/lib/scope.js +183 -19
- package/dist/lib/scope.js.map +1 -1
- package/dist/lib/signalTags.d.ts +39 -0
- package/dist/lib/signalTags.d.ts.map +1 -0
- package/dist/lib/signalTags.js +203 -0
- package/dist/lib/signalTags.js.map +1 -0
- package/dist/lib/spool.d.ts +2 -0
- package/dist/lib/spool.d.ts.map +1 -1
- package/dist/lib/spool.js +176 -65
- package/dist/lib/spool.js.map +1 -1
- package/dist/lib/storeDiagnostics.d.ts +41 -0
- package/dist/lib/storeDiagnostics.d.ts.map +1 -0
- package/dist/lib/storeDiagnostics.js +148 -0
- package/dist/lib/storeDiagnostics.js.map +1 -0
- package/dist/lib/temporal.d.ts +44 -0
- package/dist/lib/temporal.d.ts.map +1 -0
- package/dist/lib/temporal.js +1063 -0
- package/dist/lib/temporal.js.map +1 -0
- package/dist/mcp/server.d.ts +93 -3
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +499 -68
- package/dist/mcp/server.js.map +1 -1
- package/dist/memory/actionStore.d.ts +94 -3
- package/dist/memory/actionStore.d.ts.map +1 -1
- package/dist/memory/actionStore.js +412 -124
- package/dist/memory/actionStore.js.map +1 -1
- package/dist/memory/deadLetterStore.d.ts.map +1 -1
- package/dist/memory/deadLetterStore.js +4 -2
- package/dist/memory/deadLetterStore.js.map +1 -1
- package/dist/memory/embedQueueStore.d.ts +19 -8
- package/dist/memory/embedQueueStore.d.ts.map +1 -1
- package/dist/memory/embedQueueStore.js +55 -25
- package/dist/memory/embedQueueStore.js.map +1 -1
- package/dist/memory/failurePatternStore.d.ts +17 -1
- package/dist/memory/failurePatternStore.d.ts.map +1 -1
- package/dist/memory/failurePatternStore.js +54 -31
- package/dist/memory/failurePatternStore.js.map +1 -1
- package/dist/memory/graphStore.d.ts +133 -3
- package/dist/memory/graphStore.d.ts.map +1 -1
- package/dist/memory/graphStore.js +980 -155
- package/dist/memory/graphStore.js.map +1 -1
- package/dist/memory/noteStore.d.ts +27 -2
- package/dist/memory/noteStore.d.ts.map +1 -1
- package/dist/memory/noteStore.js +89 -26
- package/dist/memory/noteStore.js.map +1 -1
- package/dist/memory/observationStore.d.ts +11 -1
- package/dist/memory/observationStore.d.ts.map +1 -1
- package/dist/memory/observationStore.js +90 -15
- package/dist/memory/observationStore.js.map +1 -1
- package/dist/memory/projectRename.d.ts.map +1 -1
- package/dist/memory/projectRename.js +5 -1
- package/dist/memory/projectRename.js.map +1 -1
- package/dist/memory/rollupSweeper.d.ts.map +1 -1
- package/dist/memory/rollupSweeper.js +43 -23
- package/dist/memory/rollupSweeper.js.map +1 -1
- package/dist/memory/sessionStore.d.ts +25 -7
- package/dist/memory/sessionStore.d.ts.map +1 -1
- package/dist/memory/sessionStore.js +145 -33
- package/dist/memory/sessionStore.js.map +1 -1
- package/dist/memory/trajectoryStore.d.ts +8 -0
- package/dist/memory/trajectoryStore.d.ts.map +1 -1
- package/dist/memory/trajectoryStore.js +196 -130
- package/dist/memory/trajectoryStore.js.map +1 -1
- package/dist/middleware/rateLimiter.d.ts.map +1 -1
- package/dist/middleware/rateLimiter.js +24 -1
- package/dist/middleware/rateLimiter.js.map +1 -1
- package/dist/routes/dashboard.d.ts.map +1 -1
- package/dist/routes/dashboard.js +181 -8
- package/dist/routes/dashboard.js.map +1 -1
- package/dist/routes/mcp.d.ts.map +1 -1
- package/dist/routes/mcp.js +173 -21
- package/dist/routes/mcp.js.map +1 -1
- package/dist/routes/memories.js +9 -1
- package/dist/routes/memories.js.map +1 -1
- package/dist/scripts/doctor.d.ts +26 -2
- package/dist/scripts/doctor.d.ts.map +1 -1
- package/dist/scripts/doctor.js +371 -259
- package/dist/scripts/doctor.js.map +1 -1
- package/dist/scripts/installAgent.d.ts.map +1 -1
- package/dist/scripts/installAgent.js +101 -19
- package/dist/scripts/installAgent.js.map +1 -1
- package/dist/scripts/migrateAgentMemory.js +2 -2
- package/dist/scripts/smokeTest.js +1 -1
- package/dist/scripts/smokeTest.js.map +1 -1
- package/docker-compose.yml +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
- package/plugin/hooks/postToolUse.js +155 -50
- package/plugin/hooks/sessionStart.js +179 -27
- package/plugin/hooks/sessionStop.js +152 -37
- package/plugin/plugin.json +1 -1
- package/plugin/rules/AGENTS.md +10 -8
- package/plugin/skills/brain-memory/REFERENCE.md +15 -14
- package/plugin/skills/brain-memory/SKILL.md +2 -2
- package/plugin/skills/digest/SKILL.md +1 -1
- package/plugin/skills/handoff/SKILL.md +1 -1
- package/plugin/skills/save/SKILL.md +2 -2
- package/plugin/skills/search/SKILL.md +2 -2
- package/src/ai/chat.ts +1 -2
- package/src/ai/config.ts +2 -2
- package/src/app.ts +475 -54
- package/src/cli.ts +500 -38
- package/src/consolidation/candidates.ts +22 -4
- package/src/consolidation/fixtures.ts +1 -1
- package/src/consolidation/gate.ts +177 -140
- package/src/consolidation/runner.ts +26 -2
- package/src/dashboard/clientScript.ts +3774 -905
- package/src/dashboard/html.ts +605 -101
- package/src/dashboard/styles.ts +1591 -359
- package/src/learning/embedWorker.ts +350 -70
- package/src/learning/embedding.ts +141 -28
- package/src/learning/engine.ts +1 -1
- package/src/learning/search.ts +2533 -397
- package/src/learning/storeMeta.ts +36 -29
- package/src/learning/types.ts +66 -8
- package/src/lib/condenser.ts +1515 -0
- package/src/lib/db.ts +690 -171
- package/src/lib/logger.ts +4 -2
- package/src/lib/projectSlug.ts +77 -23
- package/src/lib/recurrence.ts +382 -0
- package/src/lib/scope.ts +220 -22
- package/src/lib/signalTags.ts +257 -0
- package/src/lib/spool.ts +181 -71
- package/src/lib/storeDiagnostics.ts +181 -0
- package/src/lib/temporal.ts +1250 -0
- package/src/mcp/server.ts +559 -88
- package/src/memory/actionStore.ts +642 -171
- package/src/memory/deadLetterStore.ts +4 -2
- package/src/memory/embedQueueStore.ts +63 -27
- package/src/memory/failurePatternStore.ts +84 -31
- package/src/memory/graphStore.ts +1396 -215
- package/src/memory/noteStore.ts +151 -30
- package/src/memory/observationStore.ts +117 -17
- package/src/memory/projectRename.ts +6 -2
- package/src/memory/rollupSweeper.ts +46 -23
- package/src/memory/sessionStore.ts +197 -38
- package/src/memory/trajectoryStore.ts +260 -140
- package/src/middleware/rateLimiter.ts +24 -1
- package/src/routes/dashboard.ts +194 -9
- package/src/routes/mcp.ts +185 -26
- package/src/routes/memories.ts +8 -1
- package/src/scripts/doctor.ts +461 -262
- package/src/scripts/installAgent.ts +106 -19
- package/src/scripts/migrateAgentMemory.ts +2 -2
- 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
|
);
|
package/src/lib/projectSlug.ts
CHANGED
|
@@ -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
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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()
|
|
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
|
|
63
|
-
if (
|
|
64
|
-
|
|
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(
|
|
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
|
+
}
|