forjajs 1.7.3 → 2.0.1
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/CHANGELOG.md +31 -0
- package/README.md +223 -217
- package/README.pt-BR.md +323 -0
- package/dist/apps/dashboard/app/api/forja/[...path]/route.d.ts +10 -0
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +36 -0
- package/dist/apps/dashboard/app/api/forja/approval.d.ts +1 -0
- package/dist/apps/dashboard/app/api/forja/approval.js +8 -0
- package/dist/apps/dashboard/app/dashboard-client.d.ts +1 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +62 -0
- package/dist/apps/dashboard/app/layout.d.ts +9 -0
- package/dist/apps/dashboard/app/layout.jsx +7 -0
- package/dist/apps/dashboard/app/page.d.ts +1 -0
- package/dist/apps/dashboard/app/page.jsx +5 -0
- package/dist/apps/dashboard/app/providers.d.ts +4 -0
- package/dist/apps/dashboard/app/providers.jsx +7 -0
- package/dist/apps/dashboard/next.config.d.mts +6 -0
- package/dist/apps/dashboard/next.config.mjs +8 -0
- package/dist/apps/dashboard/src/index.d.ts +14 -0
- package/dist/apps/dashboard/src/index.js +16 -0
- package/dist/apps/server/src/app.module.d.ts +5 -0
- package/dist/apps/server/src/app.module.js +16 -0
- package/dist/apps/server/src/forja-nest.module.d.ts +59 -0
- package/dist/apps/server/src/forja-nest.module.js +316 -0
- package/dist/apps/server/src/index.d.ts +15 -0
- package/dist/apps/server/src/index.js +7 -0
- package/dist/apps/server/src/main.d.ts +12 -0
- package/dist/apps/server/src/main.js +105 -0
- package/dist/apps/worker/src/main.d.ts +12 -0
- package/dist/apps/worker/src/main.js +18 -0
- package/dist/lib/core/health.js +1 -1
- package/dist/packages/adapter-git/src/index.d.ts +27 -0
- package/dist/packages/adapter-git/src/index.js +53 -0
- package/dist/packages/adapter-nest/src/index.d.ts +71 -0
- package/dist/packages/adapter-nest/src/index.js +142 -0
- package/dist/packages/adapter-sqlite/src/index.d.ts +99 -0
- package/dist/packages/adapter-sqlite/src/index.js +108 -0
- package/dist/packages/context/src/index.d.ts +52 -0
- package/dist/packages/context/src/index.js +108 -0
- package/dist/packages/contracts/src/index.d.ts +368 -0
- package/dist/packages/contracts/src/index.js +27 -0
- package/dist/packages/core/src/index.d.ts +68 -0
- package/dist/packages/core/src/index.js +141 -0
- package/dist/packages/evals/src/index.d.ts +22 -0
- package/dist/packages/evals/src/index.js +65 -0
- package/dist/packages/events/src/index.d.ts +47 -0
- package/dist/packages/events/src/index.js +96 -0
- package/dist/packages/graph/src/index.d.ts +80 -0
- package/dist/packages/graph/src/index.js +163 -0
- package/dist/packages/mcp/src/index.d.ts +119 -0
- package/dist/packages/mcp/src/index.js +153 -0
- package/dist/packages/observability/src/index.d.ts +132 -0
- package/dist/packages/observability/src/index.js +86 -0
- package/dist/packages/orchestration/src/index.d.ts +122 -0
- package/dist/packages/orchestration/src/index.js +178 -0
- package/dist/packages/planner/src/index.d.ts +22 -0
- package/dist/packages/planner/src/index.js +70 -0
- package/dist/packages/plugin-sdk/src/index.d.ts +56 -0
- package/dist/packages/plugin-sdk/src/index.js +55 -0
- package/dist/packages/policy/src/index.d.ts +80 -0
- package/dist/packages/policy/src/index.js +136 -0
- package/dist/packages/runtime/src/index.d.ts +91 -0
- package/dist/packages/runtime/src/index.js +217 -0
- package/dist/packages/sandbox/src/index.d.ts +64 -0
- package/dist/packages/sandbox/src/index.js +108 -0
- package/dist/packages/scheduler/src/index.d.ts +56 -0
- package/dist/packages/scheduler/src/index.js +123 -0
- package/dist/packages/sdk/src/index.d.ts +122 -0
- package/dist/packages/sdk/src/index.js +40 -0
- package/dist/packages/validator/src/index.d.ts +36 -0
- package/dist/packages/validator/src/index.js +60 -0
- package/docs/architecture/FORJA-2.0-ARCHITECTURE.md +109 -0
- package/docs/architecture/FORJA-2.0-IMPACT-FOUNDATION.md +273 -0
- package/docs/security/FORJA-2.0-RELEASE-AUDIT-2026-08-01.md +95 -0
- package/docs/vision/FORJA-2.0-VISION.md +72 -0
- package/memory/50-orchestration/handoffs/2026-07-31_architect_foundation-contracts.md +15 -0
- package/memory/50-orchestration/handoffs/2026-07-31_backend-nest.md +22 -0
- package/memory/50-orchestration/handoffs/2026-07-31_context-engine.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_control-plane.md +28 -0
- package/memory/50-orchestration/handoffs/2026-07-31_core-capability-registry.md +15 -0
- package/memory/50-orchestration/handoffs/2026-07-31_evals-plugin-sdk.md +22 -0
- package/memory/50-orchestration/handoffs/2026-07-31_events-scheduler.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_graphloop.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_mcp.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_nest-bootstrap.md +28 -0
- package/memory/50-orchestration/handoffs/2026-07-31_next-dashboard.md +22 -0
- package/memory/50-orchestration/handoffs/2026-07-31_observability.md +27 -0
- package/memory/50-orchestration/handoffs/2026-07-31_orchestration.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_planner-validator.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_policy-engine.md +14 -0
- package/memory/50-orchestration/handoffs/2026-07-31_runtime-control-plane.md +23 -0
- package/memory/50-orchestration/handoffs/2026-07-31_runtime-controlado.md +15 -0
- package/memory/50-orchestration/handoffs/2026-07-31_sandbox.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_sdk.md +27 -0
- package/memory/50-orchestration/handoffs/2026-07-31_sqlite-adapter.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_worker-dashboard-boundary.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_approval-server-identity.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_dashboard-auth-query.md +24 -0
- package/memory/50-orchestration/handoffs/2026-08-01_graphloop-approvals.md +23 -0
- package/memory/90-decisions/0034-forja-2-core-e-contratos.md +29 -0
- package/memory/90-decisions/0035-forja-2-local-first-e-autonomia.md +23 -0
- package/memory/90-decisions/0036-forja-2-capability-registry.md +30 -0
- package/memory/90-decisions/0037-forja-2-policy-engine-obrigatorio.md +28 -0
- package/memory/90-decisions/0038-forja-2-runtime-controlado.md +28 -0
- package/memory/90-decisions/0039-forja-2-event-bus-scheduler-local-first.md +31 -0
- package/memory/90-decisions/0040-forja-2-context-engine-budget-cache.md +32 -0
- package/memory/90-decisions/0041-forja-2-graphloop-separado-codegraph.md +32 -0
- package/memory/90-decisions/0042-forja-2-planner-validator-independentes.md +29 -0
- package/memory/90-decisions/0043-forja-2-orchestration-entities.md +16 -0
- package/memory/90-decisions/0044-forja-2-sandbox-worktree.md +19 -0
- package/memory/90-decisions/0045-forja-2-sqlite-adapter.md +19 -0
- package/memory/90-decisions/0046-forja-2-mcp-adapter.md +18 -0
- package/memory/90-decisions/0047-forja-2-backend-nest-adapter.md +19 -0
- package/memory/90-decisions/0048-forja-2-sdk-transport.md +18 -0
- package/memory/90-decisions/0049-forja-2-observability-control-plane.md +18 -0
- package/memory/90-decisions/0050-forja-2-control-plane-application-ports.md +18 -0
- package/memory/90-decisions/0051-forja-2-runtime-control-plane-composition.md +18 -0
- package/memory/90-decisions/0052-forja-2-deterministic-evaluation.md +15 -0
- package/memory/90-decisions/0053-forja-2-plugin-sdk-permissionado.md +16 -0
- package/memory/90-decisions/0054-forja-2-worker-dashboard-boundary.md +15 -0
- package/memory/90-decisions/0055-forja-2-next-dashboard-distribution.md +16 -0
- package/memory/90-decisions/0056-forja-2-dashboard-proxy-auth-query.md +16 -0
- package/memory/90-decisions/0057-forja-2-graphloop-approvals-dashboard.md +15 -0
- package/memory/90-decisions/0058-forja-2-approval-server-identity.md +15 -0
- package/package.json +26 -2
- package/README.en.md +0 -329
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { type AgentIdentity, type Checkpoint, type EntityId, type EvaluationResult, type ExecutionResult, type RuntimeRun, type RunId, type TokenBudget } from '../../contracts/src/index.ts';
|
|
2
|
+
import type { CapabilityExecutionRequest, CapabilityRegistry } from '../../core/src/index.ts';
|
|
3
|
+
export interface RuntimeLimits {
|
|
4
|
+
readonly maxSteps: number;
|
|
5
|
+
readonly maxTokens: number;
|
|
6
|
+
readonly maxFiles: number;
|
|
7
|
+
readonly maxDurationMs: number;
|
|
8
|
+
readonly maxRetries: number;
|
|
9
|
+
readonly maxParallel: number;
|
|
10
|
+
}
|
|
11
|
+
export interface RuntimePlanStep {
|
|
12
|
+
readonly capabilityId: string;
|
|
13
|
+
readonly payload: unknown;
|
|
14
|
+
readonly estimatedTokens: number;
|
|
15
|
+
readonly files?: readonly string[];
|
|
16
|
+
readonly projectId?: string;
|
|
17
|
+
readonly environment?: string;
|
|
18
|
+
readonly categories?: readonly string[];
|
|
19
|
+
readonly approval?: CapabilityExecutionRequest['approval'];
|
|
20
|
+
}
|
|
21
|
+
export interface RuntimePlanner {
|
|
22
|
+
plan(objective: string, context: unknown): readonly RuntimePlanStep[] | Promise<readonly RuntimePlanStep[]>;
|
|
23
|
+
}
|
|
24
|
+
export interface RuntimeValidator {
|
|
25
|
+
validate(run: RuntimeRun, results: readonly ExecutionResult[]): EvaluationResult | Promise<EvaluationResult>;
|
|
26
|
+
}
|
|
27
|
+
export interface RuntimeContextBuilder {
|
|
28
|
+
build(objective: string): unknown | Promise<unknown>;
|
|
29
|
+
}
|
|
30
|
+
export interface CheckpointStore {
|
|
31
|
+
save(checkpoint: Checkpoint): void | Promise<void>;
|
|
32
|
+
get(runId: RunId): Checkpoint | undefined | Promise<Checkpoint | undefined>;
|
|
33
|
+
}
|
|
34
|
+
export interface RuntimeMemory {
|
|
35
|
+
remember(run: RuntimeRun, result: ExecutionResult): void | Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
export interface RuntimeStartRequest {
|
|
38
|
+
readonly objective: string;
|
|
39
|
+
readonly agent: AgentIdentity;
|
|
40
|
+
readonly budget: TokenBudget;
|
|
41
|
+
readonly policy: CapabilityExecutionRequest['policy'];
|
|
42
|
+
readonly limits?: Partial<RuntimeLimits>;
|
|
43
|
+
readonly sprintId?: EntityId;
|
|
44
|
+
readonly taskId?: EntityId;
|
|
45
|
+
readonly correlationId?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface RuntimeDependencies {
|
|
48
|
+
readonly registry: CapabilityRegistry;
|
|
49
|
+
readonly planner: RuntimePlanner;
|
|
50
|
+
readonly validator: RuntimeValidator;
|
|
51
|
+
readonly contextBuilder?: RuntimeContextBuilder;
|
|
52
|
+
readonly checkpointStore?: CheckpointStore;
|
|
53
|
+
readonly memory?: RuntimeMemory;
|
|
54
|
+
}
|
|
55
|
+
export declare class RuntimeError extends Error {
|
|
56
|
+
constructor(message: string);
|
|
57
|
+
}
|
|
58
|
+
export declare class InMemoryCheckpointStore implements CheckpointStore {
|
|
59
|
+
private readonly checkpoints;
|
|
60
|
+
save(checkpoint: Checkpoint): void;
|
|
61
|
+
get(runId: RunId): Checkpoint | undefined;
|
|
62
|
+
}
|
|
63
|
+
export declare class RuntimeEngine {
|
|
64
|
+
private readonly dependencies;
|
|
65
|
+
private readonly limits;
|
|
66
|
+
private readonly runs;
|
|
67
|
+
private readonly plans;
|
|
68
|
+
private readonly results;
|
|
69
|
+
private readonly nextSteps;
|
|
70
|
+
private readonly policies;
|
|
71
|
+
private readonly requestedPauses;
|
|
72
|
+
private readonly startedAt;
|
|
73
|
+
constructor(dependencies: RuntimeDependencies, limits?: Partial<RuntimeLimits>);
|
|
74
|
+
start(request: RuntimeStartRequest): Promise<RuntimeRun>;
|
|
75
|
+
execute(runId: RunId): Promise<RuntimeRun>;
|
|
76
|
+
resume(runId: RunId): Promise<RuntimeRun>;
|
|
77
|
+
pause(runId: RunId): RuntimeRun;
|
|
78
|
+
cancel(runId: RunId): Promise<RuntimeRun>;
|
|
79
|
+
get(runId: RunId): RuntimeRun;
|
|
80
|
+
private validateAndFinish;
|
|
81
|
+
private stop;
|
|
82
|
+
private update;
|
|
83
|
+
private saveCheckpoint;
|
|
84
|
+
private metrics;
|
|
85
|
+
private auditFields;
|
|
86
|
+
private error;
|
|
87
|
+
private message;
|
|
88
|
+
private isTerminal;
|
|
89
|
+
private nonNegativeInteger;
|
|
90
|
+
private validateLimits;
|
|
91
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { CONTRACT_VERSION, validateTokenBudget, } from "../../contracts/src/index.js";
|
|
3
|
+
const DEFAULT_LIMITS = {
|
|
4
|
+
maxSteps: 20,
|
|
5
|
+
maxTokens: 10000,
|
|
6
|
+
maxFiles: 50,
|
|
7
|
+
maxDurationMs: 300000,
|
|
8
|
+
maxRetries: 2,
|
|
9
|
+
maxParallel: 1,
|
|
10
|
+
};
|
|
11
|
+
export class RuntimeError extends Error {
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'RuntimeError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export class InMemoryCheckpointStore {
|
|
18
|
+
checkpoints = new Map();
|
|
19
|
+
save(checkpoint) {
|
|
20
|
+
this.checkpoints.set(checkpoint.runId, checkpoint);
|
|
21
|
+
}
|
|
22
|
+
get(runId) {
|
|
23
|
+
return this.checkpoints.get(runId);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class RuntimeEngine {
|
|
27
|
+
dependencies;
|
|
28
|
+
limits;
|
|
29
|
+
runs = new Map();
|
|
30
|
+
plans = new Map();
|
|
31
|
+
results = new Map();
|
|
32
|
+
nextSteps = new Map();
|
|
33
|
+
policies = new Map();
|
|
34
|
+
requestedPauses = new Set();
|
|
35
|
+
startedAt = new Map();
|
|
36
|
+
constructor(dependencies, limits = {}) {
|
|
37
|
+
this.dependencies = dependencies;
|
|
38
|
+
this.limits = { ...DEFAULT_LIMITS, ...limits };
|
|
39
|
+
this.validateLimits(this.limits);
|
|
40
|
+
}
|
|
41
|
+
async start(request) {
|
|
42
|
+
validateTokenBudget(request.budget);
|
|
43
|
+
if (request.objective.trim().length === 0)
|
|
44
|
+
throw new RuntimeError('Runtime objective is required');
|
|
45
|
+
const runId = randomUUID();
|
|
46
|
+
const fields = this.auditFields(request.correlationId ?? runId);
|
|
47
|
+
const run = {
|
|
48
|
+
...fields,
|
|
49
|
+
runId,
|
|
50
|
+
objective: request.objective,
|
|
51
|
+
agent: request.agent,
|
|
52
|
+
sprintId: request.sprintId,
|
|
53
|
+
taskId: request.taskId,
|
|
54
|
+
policy: { effect: 'ALLOW_WITH_LIMITS', reason: 'Policy is evaluated per capability', policyId: 'runtime-per-capability', limits: { maxTokens: this.limits.maxTokens, maxFiles: this.limits.maxFiles, maxRetries: this.limits.maxRetries } },
|
|
55
|
+
budget: request.budget,
|
|
56
|
+
state: 'created',
|
|
57
|
+
steps: 0,
|
|
58
|
+
evidence: [],
|
|
59
|
+
changedFiles: [],
|
|
60
|
+
metrics: { attempts: 0, retries: 0, durationMs: 0, inputTokens: 0, outputTokens: 0 },
|
|
61
|
+
};
|
|
62
|
+
this.runs.set(runId, run);
|
|
63
|
+
this.results.set(runId, []);
|
|
64
|
+
this.nextSteps.set(runId, 0);
|
|
65
|
+
this.policies.set(runId, request.policy);
|
|
66
|
+
this.startedAt.set(runId, Date.now());
|
|
67
|
+
try {
|
|
68
|
+
this.update(runId, { state: 'planning' });
|
|
69
|
+
const context = this.dependencies.contextBuilder === undefined ? undefined : await this.dependencies.contextBuilder.build(request.objective);
|
|
70
|
+
const plan = [...await this.dependencies.planner.plan(request.objective, context)];
|
|
71
|
+
if (plan.length > this.limits.maxSteps)
|
|
72
|
+
return this.stop(runId, 'blocked', this.error('MAX_STEPS_EXCEEDED', 'Plan exceeds maximum steps', false));
|
|
73
|
+
this.plans.set(runId, plan);
|
|
74
|
+
await this.saveCheckpoint(runId, 'planning', 0);
|
|
75
|
+
return this.get(runId);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
return this.stop(runId, 'failed', this.error('PLANNING_FAILED', this.message(error), false));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async execute(runId) {
|
|
82
|
+
const current = this.get(runId);
|
|
83
|
+
if (this.isTerminal(current.state))
|
|
84
|
+
return current;
|
|
85
|
+
const plan = this.plans.get(runId);
|
|
86
|
+
if (plan === undefined)
|
|
87
|
+
return this.stop(runId, 'failed', this.error('PLAN_NOT_FOUND', 'Runtime plan is missing', false));
|
|
88
|
+
this.update(runId, { state: 'running' });
|
|
89
|
+
while (true) {
|
|
90
|
+
const run = this.get(runId);
|
|
91
|
+
if (this.requestedPauses.has(runId)) {
|
|
92
|
+
this.requestedPauses.delete(runId);
|
|
93
|
+
return this.stop(runId, 'paused');
|
|
94
|
+
}
|
|
95
|
+
if (run.state === 'cancelled')
|
|
96
|
+
return run;
|
|
97
|
+
const index = this.nextSteps.get(runId) ?? 0;
|
|
98
|
+
if (index >= plan.length)
|
|
99
|
+
return this.validateAndFinish(runId);
|
|
100
|
+
if (run.steps >= this.limits.maxSteps)
|
|
101
|
+
return this.stop(runId, 'blocked', this.error('MAX_STEPS_EXCEEDED', 'Runtime step limit reached', false));
|
|
102
|
+
if (Date.now() - (this.startedAt.get(runId) ?? Date.now()) > this.limits.maxDurationMs)
|
|
103
|
+
return this.stop(runId, 'blocked', this.error('MAX_DURATION_EXCEEDED', 'Runtime duration limit reached', false));
|
|
104
|
+
const step = plan[index];
|
|
105
|
+
const estimatedTokens = this.nonNegativeInteger(step.estimatedTokens, 'estimatedTokens');
|
|
106
|
+
const files = [...new Set([...run.changedFiles, ...(step.files ?? [])])];
|
|
107
|
+
if (files.length > this.limits.maxFiles)
|
|
108
|
+
return this.stop(runId, 'blocked', this.error('MAX_FILES_EXCEEDED', 'Runtime file limit reached', false));
|
|
109
|
+
let attempt = 0;
|
|
110
|
+
let result;
|
|
111
|
+
do {
|
|
112
|
+
attempt += 1;
|
|
113
|
+
const beforeAttempt = this.get(runId);
|
|
114
|
+
const projectedTokens = beforeAttempt.budget.usedTokens + estimatedTokens;
|
|
115
|
+
if (projectedTokens > beforeAttempt.budget.totalTokens || projectedTokens > this.limits.maxTokens)
|
|
116
|
+
return this.stop(runId, 'blocked', this.error('TOKEN_BUDGET_EXCEEDED', 'Runtime token budget reached', false));
|
|
117
|
+
this.update(runId, { steps: beforeAttempt.steps + 1, budget: { ...beforeAttempt.budget, usedTokens: projectedTokens }, metrics: this.metrics(beforeAttempt, { attempts: beforeAttempt.metrics.attempts + 1, inputTokens: beforeAttempt.metrics.inputTokens + estimatedTokens }) });
|
|
118
|
+
result = await this.dependencies.registry.execute({
|
|
119
|
+
input: { capabilityId: step.capabilityId, payload: step.payload },
|
|
120
|
+
agent: run.agent,
|
|
121
|
+
policy: this.policies.get(runId) ?? (() => { throw new RuntimeError('Runtime policy is missing'); })(),
|
|
122
|
+
projectId: step.projectId,
|
|
123
|
+
environment: step.environment,
|
|
124
|
+
categories: step.categories,
|
|
125
|
+
files: step.files,
|
|
126
|
+
budget: beforeAttempt.budget,
|
|
127
|
+
approval: step.approval,
|
|
128
|
+
});
|
|
129
|
+
this.results.get(runId)?.push(result);
|
|
130
|
+
if (result.status === 'succeeded')
|
|
131
|
+
break;
|
|
132
|
+
if (!result.error?.retryable || attempt > this.limits.maxRetries)
|
|
133
|
+
break;
|
|
134
|
+
const afterAttempt = this.get(runId);
|
|
135
|
+
this.update(runId, { metrics: this.metrics(afterAttempt, { retries: afterAttempt.metrics.retries + 1 }) });
|
|
136
|
+
} while (attempt <= this.limits.maxRetries);
|
|
137
|
+
if (result.status !== 'succeeded') {
|
|
138
|
+
const state = result.error?.code === 'APPROVAL_REQUIRED' ? 'awaiting_approval' : result.error?.code === 'POLICY_DENIED' ? 'blocked' : 'failed';
|
|
139
|
+
return this.stop(runId, state, result.error);
|
|
140
|
+
}
|
|
141
|
+
this.update(runId, { evidence: [...this.get(runId).evidence, ...result.evidence], changedFiles: files });
|
|
142
|
+
await this.dependencies.memory?.remember(this.get(runId), result);
|
|
143
|
+
this.nextSteps.set(runId, index + 1);
|
|
144
|
+
await this.saveCheckpoint(runId, 'running', index + 1);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async resume(runId) {
|
|
148
|
+
const run = this.get(runId);
|
|
149
|
+
if (run.state !== 'paused' && run.state !== 'awaiting_approval')
|
|
150
|
+
throw new RuntimeError(`Run is not resumable: ${run.state}`);
|
|
151
|
+
return this.execute(runId);
|
|
152
|
+
}
|
|
153
|
+
pause(runId) {
|
|
154
|
+
const run = this.get(runId);
|
|
155
|
+
if (run.state === 'running')
|
|
156
|
+
this.requestedPauses.add(runId);
|
|
157
|
+
return run;
|
|
158
|
+
}
|
|
159
|
+
async cancel(runId) {
|
|
160
|
+
const run = this.get(runId);
|
|
161
|
+
if (this.isTerminal(run.state))
|
|
162
|
+
return run;
|
|
163
|
+
this.requestedPauses.delete(runId);
|
|
164
|
+
return this.stop(runId, 'cancelled');
|
|
165
|
+
}
|
|
166
|
+
get(runId) {
|
|
167
|
+
const run = this.runs.get(runId);
|
|
168
|
+
if (run === undefined)
|
|
169
|
+
throw new RuntimeError(`Run not found: ${runId}`);
|
|
170
|
+
return run;
|
|
171
|
+
}
|
|
172
|
+
async validateAndFinish(runId) {
|
|
173
|
+
this.update(runId, { state: 'validating' });
|
|
174
|
+
try {
|
|
175
|
+
const run = this.get(runId);
|
|
176
|
+
const validation = await this.dependencies.validator.validate(run, this.results.get(runId) ?? []);
|
|
177
|
+
const state = validation.status === 'accepted' ? 'completed' : validation.status === 'blocked' ? 'blocked' : 'failed';
|
|
178
|
+
return this.stop(runId, state, undefined, validation);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
return this.stop(runId, 'failed', this.error('VALIDATION_FAILED', this.message(error), false));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
stop(runId, state, error, validation) {
|
|
185
|
+
const run = this.get(runId);
|
|
186
|
+
const durationMs = Date.now() - (this.startedAt.get(runId) ?? Date.now());
|
|
187
|
+
this.update(runId, { state, error, validation, metrics: this.metrics(run, { durationMs }) });
|
|
188
|
+
void this.saveCheckpoint(runId, state, this.nextSteps.get(runId) ?? 0);
|
|
189
|
+
return this.get(runId);
|
|
190
|
+
}
|
|
191
|
+
update(runId, patch) {
|
|
192
|
+
this.runs.set(runId, { ...this.get(runId), ...patch, updatedAt: new Date().toISOString() });
|
|
193
|
+
}
|
|
194
|
+
async saveCheckpoint(runId, state, step) {
|
|
195
|
+
const store = this.dependencies.checkpointStore;
|
|
196
|
+
if (store === undefined)
|
|
197
|
+
return;
|
|
198
|
+
const run = this.get(runId);
|
|
199
|
+
const checkpoint = { ...this.auditFields(run.correlationId), id: randomUUID(), runId, step, state, checksum: createHash('sha256').update(JSON.stringify({ runId, step, state, files: run.changedFiles })).digest('hex'), resumable: state === 'paused' || state === 'awaiting_approval' || state === 'running' };
|
|
200
|
+
await store.save(checkpoint);
|
|
201
|
+
}
|
|
202
|
+
metrics(run, patch) {
|
|
203
|
+
return { ...run.metrics, ...patch };
|
|
204
|
+
}
|
|
205
|
+
auditFields(correlationId) {
|
|
206
|
+
const now = new Date().toISOString();
|
|
207
|
+
return { schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId };
|
|
208
|
+
}
|
|
209
|
+
error(code, message, retryable) { return { code, message, retryable }; }
|
|
210
|
+
message(error) { return error instanceof Error ? error.message : 'Unknown runtime error'; }
|
|
211
|
+
isTerminal(state) { return state === 'completed' || state === 'failed' || state === 'cancelled' || state === 'blocked' || state === 'rolled_back'; }
|
|
212
|
+
nonNegativeInteger(value, field) { if (!Number.isInteger(value) || value < 0)
|
|
213
|
+
throw new RuntimeError(`${field} must be a non-negative integer`); return value; }
|
|
214
|
+
validateLimits(limits) { for (const [name, value] of Object.entries(limits))
|
|
215
|
+
if (!Number.isInteger(value) || value < 1)
|
|
216
|
+
throw new RuntimeError(`Runtime limit ${name} must be a positive integer`); }
|
|
217
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type EntityId, type EvaluationResult, type RunId, type SandboxCommand, type SandboxDiff, type SandboxExecution, type SandboxSession } from '../../contracts/src/index.ts';
|
|
2
|
+
export interface SandboxStore {
|
|
3
|
+
save(session: SandboxSession): void | Promise<void>;
|
|
4
|
+
get(id: EntityId): SandboxSession | undefined | Promise<SandboxSession | undefined>;
|
|
5
|
+
}
|
|
6
|
+
export interface SandboxValidation {
|
|
7
|
+
readonly status: EvaluationResult['status'];
|
|
8
|
+
readonly evidenceIds: readonly EntityId[];
|
|
9
|
+
readonly summary: string;
|
|
10
|
+
}
|
|
11
|
+
export interface SandboxDiffData {
|
|
12
|
+
readonly files: readonly string[];
|
|
13
|
+
readonly additions: number;
|
|
14
|
+
readonly deletions: number;
|
|
15
|
+
readonly evidenceIds: readonly EntityId[];
|
|
16
|
+
}
|
|
17
|
+
export interface SandboxBackend {
|
|
18
|
+
create(session: SandboxSession): void | Promise<void>;
|
|
19
|
+
prepare(session: SandboxSession): void | Promise<void>;
|
|
20
|
+
execute(session: SandboxSession, command: SandboxCommand): SandboxCommandResult | Promise<SandboxCommandResult>;
|
|
21
|
+
validate(session: SandboxSession): SandboxValidation | Promise<SandboxValidation>;
|
|
22
|
+
diff(session: SandboxSession): SandboxDiffData | Promise<SandboxDiffData>;
|
|
23
|
+
promote(session: SandboxSession): void | Promise<void>;
|
|
24
|
+
reject(session: SandboxSession): void | Promise<void>;
|
|
25
|
+
destroy(session: SandboxSession): void | Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
export interface SandboxCommandResult {
|
|
28
|
+
readonly exitCode: number;
|
|
29
|
+
readonly stdout: string;
|
|
30
|
+
readonly stderr: string;
|
|
31
|
+
readonly durationMs: number;
|
|
32
|
+
readonly evidenceIds?: readonly EntityId[];
|
|
33
|
+
}
|
|
34
|
+
export declare class SandboxError extends Error {
|
|
35
|
+
constructor(message: string);
|
|
36
|
+
}
|
|
37
|
+
export declare class InMemorySandboxStore implements SandboxStore {
|
|
38
|
+
private readonly sessions;
|
|
39
|
+
save(session: SandboxSession): void;
|
|
40
|
+
get(id: EntityId): SandboxSession | undefined;
|
|
41
|
+
}
|
|
42
|
+
export declare class SandboxEngine {
|
|
43
|
+
private readonly store;
|
|
44
|
+
private readonly backend;
|
|
45
|
+
constructor(store: SandboxStore, backend: SandboxBackend);
|
|
46
|
+
create(input: {
|
|
47
|
+
readonly runId: RunId;
|
|
48
|
+
readonly root: string;
|
|
49
|
+
readonly backend?: SandboxSession['backend'];
|
|
50
|
+
readonly correlationId?: string;
|
|
51
|
+
}): Promise<SandboxSession>;
|
|
52
|
+
prepare(id: EntityId): Promise<SandboxSession>;
|
|
53
|
+
execute(id: EntityId, command: SandboxCommand): Promise<SandboxExecution>;
|
|
54
|
+
validate(id: EntityId): Promise<SandboxValidation>;
|
|
55
|
+
diff(id: EntityId): Promise<SandboxDiff>;
|
|
56
|
+
promote(id: EntityId, diff: SandboxDiff): Promise<SandboxSession>;
|
|
57
|
+
reject(id: EntityId): Promise<SandboxSession>;
|
|
58
|
+
destroy(id: EntityId): Promise<SandboxSession>;
|
|
59
|
+
private require;
|
|
60
|
+
private requireState;
|
|
61
|
+
private updated;
|
|
62
|
+
private checksum;
|
|
63
|
+
private audit;
|
|
64
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { CONTRACT_VERSION, } from "../../contracts/src/index.js";
|
|
3
|
+
export class SandboxError extends Error {
|
|
4
|
+
constructor(message) { super(message); this.name = 'SandboxError'; }
|
|
5
|
+
}
|
|
6
|
+
export class InMemorySandboxStore {
|
|
7
|
+
sessions = new Map();
|
|
8
|
+
save(session) { this.sessions.set(session.id, session); }
|
|
9
|
+
get(id) { return this.sessions.get(id); }
|
|
10
|
+
}
|
|
11
|
+
export class SandboxEngine {
|
|
12
|
+
store;
|
|
13
|
+
backend;
|
|
14
|
+
constructor(store, backend) { this.store = store; this.backend = backend; }
|
|
15
|
+
async create(input) {
|
|
16
|
+
if (input.root.trim().length === 0)
|
|
17
|
+
throw new SandboxError('Sandbox root is required');
|
|
18
|
+
const session = this.audit(input.correlationId ?? `sandbox:${input.runId}`, {
|
|
19
|
+
id: randomUUID(), runId: input.runId, backend: input.backend ?? 'git_worktree', root: input.root,
|
|
20
|
+
state: 'created', promoted: false,
|
|
21
|
+
});
|
|
22
|
+
try {
|
|
23
|
+
await this.backend.create(session);
|
|
24
|
+
await this.store.save(session);
|
|
25
|
+
return session;
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
const failed = this.updated(session, { state: 'failed' });
|
|
29
|
+
await this.store.save(failed);
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async prepare(id) {
|
|
34
|
+
const session = await this.require(id);
|
|
35
|
+
this.requireState(session, ['created']);
|
|
36
|
+
await this.backend.prepare(session);
|
|
37
|
+
const updated = this.updated(session, { state: 'prepared' });
|
|
38
|
+
await this.store.save(updated);
|
|
39
|
+
return updated;
|
|
40
|
+
}
|
|
41
|
+
async execute(id, command) {
|
|
42
|
+
const session = await this.require(id);
|
|
43
|
+
this.requireState(session, ['prepared']);
|
|
44
|
+
if (command.executable.trim().length === 0)
|
|
45
|
+
throw new SandboxError('Sandbox command executable is required');
|
|
46
|
+
const running = this.updated(session, { state: 'executing' });
|
|
47
|
+
await this.store.save(running);
|
|
48
|
+
try {
|
|
49
|
+
const result = await this.backend.execute(running, command);
|
|
50
|
+
const validating = this.updated(running, { state: 'validating' });
|
|
51
|
+
await this.store.save(validating);
|
|
52
|
+
return this.audit(`execution:${id}:${command.executable}`, { sessionId: id, command, exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr, durationMs: result.durationMs, evidenceIds: [...(result.evidenceIds ?? [])] });
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
await this.store.save(this.updated(running, { state: 'failed' }));
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async validate(id) {
|
|
60
|
+
const session = await this.require(id);
|
|
61
|
+
this.requireState(session, ['validating']);
|
|
62
|
+
const result = await this.backend.validate(session);
|
|
63
|
+
const nextState = result.status === 'accepted' ? 'ready_to_promote' : result.status === 'rejected' ? 'rejected' : 'validating';
|
|
64
|
+
await this.store.save(this.updated(session, { state: nextState }));
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
async diff(id) {
|
|
68
|
+
const session = await this.require(id);
|
|
69
|
+
this.requireState(session, ['ready_to_promote']);
|
|
70
|
+
const result = await this.backend.diff(session);
|
|
71
|
+
const evidenceIds = [...result.evidenceIds];
|
|
72
|
+
return this.audit(`diff:${id}:${result.files.join(',')}`, { sessionId: id, checksum: this.checksum(result), files: [...result.files], additions: result.additions, deletions: result.deletions, evidenceIds });
|
|
73
|
+
}
|
|
74
|
+
async promote(id, diff) {
|
|
75
|
+
const session = await this.require(id);
|
|
76
|
+
this.requireState(session, ['ready_to_promote']);
|
|
77
|
+
if (diff.sessionId !== id || diff.checksum.length === 0)
|
|
78
|
+
throw new SandboxError('Promotion requires a valid diff for the same sandbox');
|
|
79
|
+
await this.backend.promote(session);
|
|
80
|
+
const updated = this.updated(session, { state: 'promoted', promoted: true });
|
|
81
|
+
await this.store.save(updated);
|
|
82
|
+
return updated;
|
|
83
|
+
}
|
|
84
|
+
async reject(id) {
|
|
85
|
+
const session = await this.require(id);
|
|
86
|
+
this.requireState(session, ['created', 'prepared', 'executing', 'validating', 'ready_to_promote', 'failed']);
|
|
87
|
+
await this.backend.reject(session);
|
|
88
|
+
const updated = this.updated(session, { state: 'rejected' });
|
|
89
|
+
await this.store.save(updated);
|
|
90
|
+
return updated;
|
|
91
|
+
}
|
|
92
|
+
async destroy(id) {
|
|
93
|
+
const session = await this.require(id);
|
|
94
|
+
if (session.state === 'destroyed')
|
|
95
|
+
return session;
|
|
96
|
+
await this.backend.destroy(session);
|
|
97
|
+
const updated = this.updated(session, { state: 'destroyed' });
|
|
98
|
+
await this.store.save(updated);
|
|
99
|
+
return updated;
|
|
100
|
+
}
|
|
101
|
+
async require(id) { const value = await this.store.get(id); if (!value)
|
|
102
|
+
throw new SandboxError(`Sandbox not found: ${id}`); return value; }
|
|
103
|
+
requireState(session, allowed) { if (!allowed.includes(session.state))
|
|
104
|
+
throw new SandboxError(`Invalid sandbox transition from ${session.state}`); }
|
|
105
|
+
updated(value, changes) { return { ...value, ...changes, updatedAt: new Date().toISOString() }; }
|
|
106
|
+
checksum(value) { return createHash('sha256').update(JSON.stringify({ files: [...value.files].sort(), additions: value.additions, deletions: value.deletions, evidenceIds: [...value.evidenceIds].sort() })).digest('hex'); }
|
|
107
|
+
audit(correlationId, value) { const now = new Date().toISOString(); return { ...value, schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId }; }
|
|
108
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { DomainEvent } from '../../contracts/src/index.ts';
|
|
2
|
+
export type ScheduleTrigger = {
|
|
3
|
+
readonly kind: 'one-shot';
|
|
4
|
+
readonly at: string;
|
|
5
|
+
} | {
|
|
6
|
+
readonly kind: 'cron';
|
|
7
|
+
readonly expression: string;
|
|
8
|
+
} | {
|
|
9
|
+
readonly kind: 'condition';
|
|
10
|
+
readonly evaluate: (now: Date) => boolean | Promise<boolean>;
|
|
11
|
+
} | {
|
|
12
|
+
readonly kind: 'event';
|
|
13
|
+
readonly eventType: string;
|
|
14
|
+
readonly aggregateId?: string;
|
|
15
|
+
};
|
|
16
|
+
export interface ScheduleContext {
|
|
17
|
+
readonly scheduleId: string;
|
|
18
|
+
readonly trigger: ScheduleTrigger['kind'];
|
|
19
|
+
readonly key: string;
|
|
20
|
+
readonly now: Date;
|
|
21
|
+
readonly event?: DomainEvent;
|
|
22
|
+
}
|
|
23
|
+
export interface Schedule {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly trigger: ScheduleTrigger;
|
|
26
|
+
readonly maxRetries: number;
|
|
27
|
+
readonly action: (context: ScheduleContext) => void | Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export interface ScheduleDeadLetter {
|
|
30
|
+
readonly scheduleId: string;
|
|
31
|
+
readonly key: string;
|
|
32
|
+
readonly attempts: number;
|
|
33
|
+
readonly error: string;
|
|
34
|
+
readonly failedAt: string;
|
|
35
|
+
}
|
|
36
|
+
export declare class SchedulerError extends Error {
|
|
37
|
+
constructor(message: string);
|
|
38
|
+
}
|
|
39
|
+
export declare function matchesCron(expression: string, date: Date): boolean;
|
|
40
|
+
export declare class Scheduler {
|
|
41
|
+
private readonly schedules;
|
|
42
|
+
private readonly completed;
|
|
43
|
+
private readonly running;
|
|
44
|
+
private readonly retries;
|
|
45
|
+
private readonly deadLetters;
|
|
46
|
+
private readonly maxParallel;
|
|
47
|
+
constructor(maxParallel?: number);
|
|
48
|
+
register(schedule: Schedule): void;
|
|
49
|
+
cancel(scheduleId: string): boolean;
|
|
50
|
+
tick(now?: Date): Promise<readonly string[]>;
|
|
51
|
+
onEvent(event: DomainEvent): Promise<readonly string[]>;
|
|
52
|
+
list(): readonly Schedule[];
|
|
53
|
+
getDeadLetters(): readonly ScheduleDeadLetter[];
|
|
54
|
+
private candidate;
|
|
55
|
+
private run;
|
|
56
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
export class SchedulerError extends Error {
|
|
2
|
+
constructor(message) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = 'SchedulerError';
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export function matchesCron(expression, date) {
|
|
8
|
+
const fields = expression.trim().split(/\s+/);
|
|
9
|
+
if (fields.length !== 5)
|
|
10
|
+
throw new SchedulerError('Cron expression must have 5 fields');
|
|
11
|
+
const values = [date.getUTCMinutes(), date.getUTCHours(), date.getUTCDate(), date.getUTCMonth() + 1, date.getUTCDay()];
|
|
12
|
+
const ranges = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 6]];
|
|
13
|
+
return fields.every((field, index) => matchesCronField(field, values[index], ranges[index][0], ranges[index][1]));
|
|
14
|
+
}
|
|
15
|
+
function matchesCronField(field, value, min, max) {
|
|
16
|
+
return field.split(',').some((part) => {
|
|
17
|
+
const [base, stepText] = part.split('/');
|
|
18
|
+
const step = stepText === undefined ? 1 : Number(stepText);
|
|
19
|
+
if (!Number.isInteger(step) || step < 1)
|
|
20
|
+
throw new SchedulerError(`Invalid cron step: ${part}`);
|
|
21
|
+
if (base === '*')
|
|
22
|
+
return (value - min) % step === 0;
|
|
23
|
+
if (base.includes('-')) {
|
|
24
|
+
const [start, end] = base.split('-').map(Number);
|
|
25
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < min || end > max || start > end)
|
|
26
|
+
throw new SchedulerError(`Invalid cron range: ${part}`);
|
|
27
|
+
return value >= start && value <= end && (value - start) % step === 0;
|
|
28
|
+
}
|
|
29
|
+
const exact = Number(base);
|
|
30
|
+
if (!Number.isInteger(exact) || exact < min || exact > max)
|
|
31
|
+
throw new SchedulerError(`Invalid cron value: ${part}`);
|
|
32
|
+
return value === exact;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
export class Scheduler {
|
|
36
|
+
schedules = new Map();
|
|
37
|
+
completed = new Set();
|
|
38
|
+
running = new Set();
|
|
39
|
+
retries = new Map();
|
|
40
|
+
deadLetters = [];
|
|
41
|
+
maxParallel;
|
|
42
|
+
constructor(maxParallel = 1) {
|
|
43
|
+
if (!Number.isInteger(maxParallel) || maxParallel < 1)
|
|
44
|
+
throw new SchedulerError('maxParallel must be a positive integer');
|
|
45
|
+
this.maxParallel = maxParallel;
|
|
46
|
+
}
|
|
47
|
+
register(schedule) {
|
|
48
|
+
if (schedule.id.trim().length === 0)
|
|
49
|
+
throw new SchedulerError('Schedule id is required');
|
|
50
|
+
if (this.schedules.has(schedule.id))
|
|
51
|
+
throw new SchedulerError(`Schedule already exists: ${schedule.id}`);
|
|
52
|
+
if (!Number.isInteger(schedule.maxRetries) || schedule.maxRetries < 0)
|
|
53
|
+
throw new SchedulerError('Schedule maxRetries must be a non-negative integer');
|
|
54
|
+
this.schedules.set(schedule.id, schedule);
|
|
55
|
+
}
|
|
56
|
+
cancel(scheduleId) {
|
|
57
|
+
return this.schedules.delete(scheduleId);
|
|
58
|
+
}
|
|
59
|
+
async tick(now = new Date()) {
|
|
60
|
+
const due = [];
|
|
61
|
+
for (const schedule of this.schedules.values()) {
|
|
62
|
+
const candidate = await this.candidate(schedule, now);
|
|
63
|
+
if (candidate !== undefined && !this.completed.has(candidate.key) && !this.running.has(candidate.key))
|
|
64
|
+
due.push({ schedule, ...candidate });
|
|
65
|
+
}
|
|
66
|
+
const selected = due.slice(0, Math.max(0, this.maxParallel - this.running.size));
|
|
67
|
+
await Promise.all(selected.map(({ schedule, key, event }) => this.run(schedule, key, now, event)));
|
|
68
|
+
return selected.map(({ schedule }) => schedule.id);
|
|
69
|
+
}
|
|
70
|
+
async onEvent(event) {
|
|
71
|
+
const due = [...this.schedules.values()].filter((schedule) => schedule.trigger.kind === 'event' && schedule.trigger.eventType === event.type && (schedule.trigger.aggregateId === undefined || schedule.trigger.aggregateId === event.aggregateId));
|
|
72
|
+
const eligible = due.filter((schedule) => !this.completed.has(`${schedule.id}:event:${event.id}`) && !this.running.has(`${schedule.id}:event:${event.id}`));
|
|
73
|
+
const selected = eligible.slice(0, Math.max(0, this.maxParallel - this.running.size));
|
|
74
|
+
await Promise.all(selected.map((schedule) => this.run(schedule, `${schedule.id}:event:${event.id}`, new Date(event.createdAt), event)));
|
|
75
|
+
return selected.map((schedule) => schedule.id);
|
|
76
|
+
}
|
|
77
|
+
list() {
|
|
78
|
+
return [...this.schedules.values()];
|
|
79
|
+
}
|
|
80
|
+
getDeadLetters() {
|
|
81
|
+
return [...this.deadLetters];
|
|
82
|
+
}
|
|
83
|
+
async candidate(schedule, now) {
|
|
84
|
+
const trigger = schedule.trigger;
|
|
85
|
+
if (trigger.kind === 'one-shot') {
|
|
86
|
+
const at = new Date(trigger.at);
|
|
87
|
+
if (Number.isNaN(at.getTime()))
|
|
88
|
+
throw new SchedulerError(`Invalid one-shot date: ${trigger.at}`);
|
|
89
|
+
return now >= at ? { key: `${schedule.id}:one-shot:${trigger.at}` } : undefined;
|
|
90
|
+
}
|
|
91
|
+
if (trigger.kind === 'cron')
|
|
92
|
+
return matchesCron(trigger.expression, now) ? { key: `${schedule.id}:cron:${now.toISOString().slice(0, 16)}` } : undefined;
|
|
93
|
+
if (trigger.kind === 'condition')
|
|
94
|
+
return await trigger.evaluate(now) ? { key: `${schedule.id}:condition:${now.toISOString()}` } : undefined;
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
async run(schedule, key, now, event) {
|
|
98
|
+
this.running.add(key);
|
|
99
|
+
const attempts = this.retries.get(key) ?? 0;
|
|
100
|
+
let currentAttempt = attempts;
|
|
101
|
+
try {
|
|
102
|
+
while (currentAttempt <= schedule.maxRetries) {
|
|
103
|
+
currentAttempt += 1;
|
|
104
|
+
try {
|
|
105
|
+
await schedule.action({ scheduleId: schedule.id, trigger: schedule.trigger.kind, key, now, event });
|
|
106
|
+
this.completed.add(key);
|
|
107
|
+
this.retries.delete(key);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
this.retries.set(key, currentAttempt);
|
|
112
|
+
if (currentAttempt > schedule.maxRetries) {
|
|
113
|
+
this.deadLetters.push({ scheduleId: schedule.id, key, attempts: currentAttempt, error: error instanceof Error ? error.message : 'Unknown scheduler error', failedAt: new Date().toISOString() });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
this.running.delete(key);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|