Evaluating alternatives#

This guide shows how to compare several possible edits in one call and pick the best one. For example, you can check which resource should take a task. It covers building candidates, scoring them with and without leveling, reading the metrics, handling candidates that fail, and committing the winner.

How evaluation works#

project.evaluate takes an array of candidates. A candidate is an object with an id and a changes field. changes is a SchedulingChanges object, the same change set you'd pass to apply. Each candidate is one alternative: "give task B to dev2", "split the review between two people", "add a link". The call scores every candidate against the project's accepted baseline and returns the scores. The project isn't modified, just like with preview.

Every candidate goes through the same run on a disposable copy of the project:

  1. Copy the reference state. That's the accepted baseline, or its cleared copy with clearFirst (see Options).
  2. apply the candidate's changes.
  3. solve(null) and measure the scheduled stage.
  4. When the level option is set, level with those options and measure the leveled stage.

This is the same sequence you'd run to commit the candidate for real. Each candidate starts from the reference state, never from the previous candidate. Both stages are compared with the one baseline.

The result has three parts:

  • baseline: the metrics of the reference state itself. All its deltas are 0.
  • candidates: one entry per candidate, in input order. Each entry holds scheduled metrics, leveled metrics (only with level) and a cost.
  • baselineId: the token of the accepted baseline the candidates were scored against.

Each stage is described by a Metrics object: the project finish and the finish of each focus task, resource overload, conflicts, cycles and a single cost number. Every measurement is an absolute value plus a delta against the baseline, so you can show either one.

Errors come in two levels. Problems with the call itself throw and fail the whole call:

  • no solved baseline: ProjectError with code "no-baseline"
  • a stale baselineId in the options or in any candidate: ProjectError with code "stale-baseline"
  • an unknown focus task, or leveling options that don't fit the baseline: InputError

Everything else fails only its own candidate. That candidate gets an error and no metrics, and the other candidates are scored as usual.

evaluate reports scores, not dates. The result has no task updates and no overallocation windows. Once you've picked a candidate, commit it yourself with apply and level, or look at its dates with preview.

Comparing candidates#

All examples on this page use the same small project: tasks A and B, two working days each, both starting on Monday, August 10, 2026, and both assigned to dev1. The resource dev2 is idle. dev1 is overloaded for two days.

Candidates#

Build each alternative as a { id, changes } object and pass them all to evaluate. An empty change set is a useful candidate too: it scores "leave the plan as it is" next to the other options.

import { Project } from "plen-js";

const project = new Project();
project.solve({
  tasks: [
    { id: "A", start_date: "2026-08-10 08:00", duration: 2 },
    { id: "B", start_date: "2026-08-10 08:00", duration: 2 },
  ],
  resources: [{ id: "dev1" }, { id: "dev2" }],
  assignments: [
    { id: "aA", task: "A", resource: "dev1", value: 1 },
    { id: "aB", task: "B", resource: "dev1", value: 1 },
  ],
});

const result = project.evaluate(
  [
    // Candidate 1: keep the plan as it is.
    { id: "stay", changes: {} },
    // Candidate 2: give task B to dev2.
    { id: "dev2", changes: { assignments: { update: [{ id: "aB", resource: "dev2" }] } } },
  ],
  { focus: "B" },
);

console.log(`baseline: cost ${result.baseline.cost}`);
for (const candidate of result.candidates) {
  console.log(`${candidate.id}: cost ${candidate.cost}`);
}

Output:

baseline: cost 2
stay: cost 2
dev2: cost 0

Without leveling, only the scheduled stage is scored. stay keeps both tasks on dev1 and costs 2, two resource-days of overload. dev2 removes the overload and costs 0.

The candidate id is echoed back so you can match results to inputs. Ids aren't checked for uniqueness, and results keep input order anyway. See project.evaluate.

Options#

The options object has four fields, all optional:

  • level: a LevelingOptions object levels each candidate after scheduling it and adds the leveled stage. false (the default) scores the scheduled stage only. level: true is invalid and throws an InputError; pass {} for the default leveling options.
  • focus: the tasks to report finish dates and focus overload for. There's no implicit "modified task", so list the tasks your candidates are about.
  • baselineId: a baseline token. The call throws ProjectError with code "stale-baseline" when it no longer names the accepted baseline. Each candidate's changes.baselineId is checked the same way.
  • clearFirst: score against a copy with the in-scope leveling_delay and pauses cleared.
Note

focus takes one task id or an array of ids.

Leveling changes the picture. Without it, an overloaded plan looks bad on overload. With it, the overload turns into delay, which is what the user gets after committing and leveling:

import { Project } from "plen-js";

// Tasks A and B, two days each, both on dev1 in the same week.
function solvedProject() {
  const project = new Project();
  project.solve({
    tasks: [
      { id: "A", start_date: "2026-08-10 08:00", duration: 2 },
      { id: "B", start_date: "2026-08-10 08:00", duration: 2 },
    ],
    resources: [{ id: "dev1" }, { id: "dev2" }],
    assignments: [
      { id: "aA", task: "A", resource: "dev1", value: 1 },
      { id: "aB", task: "B", resource: "dev1", value: 1 },
    ],
  });
  return project;
}

function reassign(assignment, resource) {
  return { assignments: { update: [{ id: assignment, resource }] } };
}

const project = solvedProject();
const result = project.evaluate(
  [
    { id: "stay", changes: {} },
    { id: "dev2", changes: reassign("aB", "dev2") },
  ],
  { level: {}, focus: ["A", "B"] },
);

for (const candidate of result.candidates) {
  const leveled = candidate.leveled;
  if (!leveled) continue;
  const finish = leveled.finish.project;
  console.log(`${candidate.id}: project ends ${finish.date} (${finish.delta} days), cost ${candidate.cost}`);
  for (const task of leveled.finish.tasks) {
    if (task.finish) console.log(`  ${task.id} ends ${task.finish.date} (${task.finish.delta})`);
  }
}

Output:

stay: project ends 2026-08-14 08:00 (2 days), cost 2
  A ends 2026-08-12 08:00 (0)
  B ends 2026-08-14 08:00 (2)
dev2: project ends 2026-08-12 08:00 (0 days), cost 0
  A ends 2026-08-12 08:00 (0)
  B ends 2026-08-12 08:00 (0)

For stay, leveling resolves the overload by pushing B two days later, so the cost is now the delay. For dev2 there's nothing to level.

level runs with the options exactly as you pass them. LevelingOptions.clearFirst defaults to true, so each candidate is re-leveled from zero. After a previous level run, this creates a trap. The stored delays are already in the baseline finish, and they hide the overload the current assignments cause. A candidate that removes the overload then shows a negative finish delta, because leveling from zero drops the old delays.

The clearFirst option of evaluate fixes this. It replaces the reference state with a copy that has the in-scope delays and pauses cleared, solved again. The baseline metrics and every candidate run then use that copy. The scope is level.scope.tasks when you give it, otherwise every task. It's independent of LevelingOptions.clearFirst, so it also works without level.

import { Project } from "plen-js";

// Tasks A and B, two days each, both on dev1 in the same week.
function solvedProject() {
  const project = new Project();
  project.solve({
    tasks: [
      { id: "A", start_date: "2026-08-10 08:00", duration: 2 },
      { id: "B", start_date: "2026-08-10 08:00", duration: 2 },
    ],
    resources: [{ id: "dev1" }, { id: "dev2" }],
    assignments: [
      { id: "aA", task: "A", resource: "dev1", value: 1 },
      { id: "aB", task: "B", resource: "dev1", value: 1 },
    ],
  });
  return project;
}

function reassign(assignment, resource) {
  return { assignments: { update: [{ id: assignment, resource }] } };
}

const project = solvedProject();
// The plan was leveled earlier: B carries a two-day leveling delay.
const leveled = project.level();

const result = project.evaluate([{ id: "dev2", changes: reassign("aB", "dev2") }], {
  baselineId: leveled.baselineId,
  level: {},
  clearFirst: true,
});

// The cleared baseline shows the overload that B's delay was hiding.
console.log(`baseline overload: ${result.baseline.overload.total.value}`);
for (const candidate of result.candidates) {
  const finish = candidate.leveled?.finish.project;
  if (finish) console.log(`${candidate.id}: finish delta ${finish.delta}`);
}

Output:

baseline overload: 2
dev2: finish delta 0

With clearFirst, the baseline reports 2 resource-days of overload and the dev2 candidate a finish delta of 0. Without it, the baseline has no overload and the same candidate shows a finish delta of -2. Both views are valid. clearFirst is the one that matches a commit with level and clearFirst, which re-levels from zero.

Note

The leveling result is a ScheduleResult with an added rounds field; read updates on it.

A few details:

  • baselineId, candidate tokens, level options and focus ids are all checked against the accepted state before anything is cleared. clearFirst adds no new errors.
  • A candidate's own changes.baselineId is dropped before its trial run, because the cleared copy has a different token. The result's baselineId is still the accepted state's.
  • When there's nothing to clear in scope, the output is the same as with clearFirst: false.

The full option list is on the project.evaluate reference. For the leveling options themselves, see Leveling resources.

Metrics and cost#

Every stage reports the same Metrics:

Field What it measures
finish.project Latest end over scheduled tasks. null when the stage has no tasks.
finish.tasks One { id, finish } entry per focus task, in focus order.
overload.total Overload over all resources.
overload.resources Overload per resource, for every resource that's non-zero in the stage or the baseline.
overload.focus Per focus task: the overload per resource in the buckets that intersect the task.
conflicts, cycles How many conflicts and cycles the stage has.
cost One number for ranking, lower is better.

Dates come as a Shift: date plus delta. The delta is the working time from the baseline finish in config.duration_unit, positive when later. A task's delta is measured on its own calendar, the project's on the global calendar. The date has the same form as other result dates: a string by default, a Date with new Project({ dates: "date" }) (see Plain objects and dates). Counts and overload come as an Amount: value plus delta.

Overload is measured the same way the leveler sees it. For each time bucket, it's how far a resource's load goes over its capacity, summed over buckets. The unit is capacity ร— buckets, so on a day basis 2 means "two resource-days over". One bucket size (basis) applies to the baseline and every stage of every candidate: level.basis when you give it, otherwise the one derived from config.duration_unit. The same per-resource sum is what loadProfile shows as excess at that basis.

Focus overload shows where the trouble is. At the scheduled stage it's the overload around the task. At the leveled stage it's what leveling couldn't resolve there. A milestone has zero length and covers no bucket.

The leveled stage has every Metrics field plus converged, rounds and windows, the number of overallocation windows left after leveling.

Note

Leveled metrics have the same fields as Metrics plus converged, rounds and windows.

cost is one fixed heuristic:

cost = max(0, finish.project.delta)
     + overload.total.value
     + 1000 ร— (conflicts.value + cycles.value)

When the basis follows duration_unit, a day of delay and a resource-day of overload weigh the same. An earlier finish doesn't earn a bonus. The 1000 penalty keeps any broken schedule, with conflicts or cycles, behind every valid one. A candidate's cost is the cost of its last stage: leveled when you level, scheduled otherwise. The baseline carries its own cost.

If the heuristic doesn't fit your product, rank on the raw values instead. This function prints the per-resource overload change of each candidate's scheduled stage:

function printOverload(result) {
  for (const candidate of result.candidates) {
    if (!candidate.scheduled) continue;
    for (const row of candidate.scheduled.overload.resources) {
      console.log(
        `${candidate.id}: ${row.resource} overload ${row.overload.value} (${row.overload.delta} vs baseline)`,
      );
    }
  }
}

For the project above, the dev2 candidate prints a row for dev1 with a delta of -2. The row is there because dev1 was overloaded in the baseline, even though it's zero in the stage. Resources come in stage order, then resources that exist only in the baseline. See the Metrics reference.

Failed and cyclic candidates#

A candidate can fail without failing the call. Three cases need handling:

  • Rejected. apply rejects an operation in the change set (the result reports only the first rejection), or solve or level fails on the candidate's input, for example a leveling scope id the candidate removed. The candidate result has an error with a path and a message. scheduled, leveled and cost are absent.
  • Cyclic. The candidate creates a dependency cycle. scheduled is measured on the unchanged dates the cyclic solve returns, and cycles.value is above 0. Leveling stops at round 0 on a cyclic plan, so leveled is absent. The cycle penalty pushes its cost over 1000.
  • Focus task removed. When the candidate removes a focus task, that task's finish and its focus overload resources are null. The rest of the metrics are normal.
import { Project } from "plen-js";

// Tasks A and B, two days each, both on dev1 in the same week.
function solvedProject() {
  const project = new Project();
  project.solve({
    tasks: [
      { id: "A", start_date: "2026-08-10 08:00", duration: 2 },
      { id: "B", start_date: "2026-08-10 08:00", duration: 2 },
    ],
    resources: [{ id: "dev1" }, { id: "dev2" }],
    assignments: [
      { id: "aA", task: "A", resource: "dev1", value: 1 },
      { id: "aB", task: "B", resource: "dev1", value: 1 },
    ],
  });
  return project;
}

function reassign(assignment, resource) {
  return { assignments: { update: [{ id: assignment, resource }] } };
}

const project = solvedProject();
const result = project.evaluate(
  [
    { id: "missing", changes: reassign("nope", "dev2") },
    {
      id: "cycle",
      changes: {
        links: {
          add: [
            { id: "ab", source: "A", target: "B", type: "fs" },
            { id: "ba", source: "B", target: "A", type: "fs" },
          ],
        },
      },
    },
    { id: "removed", changes: { tasks: { remove: ["B"] } } },
  ],
  { level: {}, focus: "B" },
);

for (const candidate of result.candidates) {
  if (candidate.error) {
    console.log(`${candidate.id} rejected at ${candidate.error.path}: ${candidate.error.message}`);
    continue;
  }
  const scheduled = candidate.scheduled;
  if (scheduled.cycles.value > 0) {
    console.log(`${candidate.id} is cyclic, leveled: ${candidate.leveled !== undefined}`);
  }
  for (const task of scheduled.finish.tasks) {
    if (task.finish === null) console.log(`${candidate.id} removes focus task ${task.id}`);
  }
  console.log(`${candidate.id} cost ${candidate.cost}`);
}

Output:

missing rejected at assignments.update[0]: unknown assignment id
cycle is cyclic, leveled: false
cycle cost 1002
removed removes focus task B
removed cost 0

Rank only candidates that have a cost. The cyclic candidate has one, but the penalty keeps it at the bottom. Its 1002 is the cycle penalty plus the two resource-days of overload dev1 still has.

Call-level errors still throw. An unknown focus id fails the whole call with an InputError at path focus[i], and a stale token with a ProjectError with code "stale-baseline":

import { InputError, Project, ProjectError } from "plen-js";

const project = new Project();
project.solve({ tasks: [{ id: "A", start_date: "2026-08-10 08:00", duration: 2 }] });

try {
  project.evaluate([], { focus: "X" });
} catch (error) {
  if (error instanceof InputError) console.log(`${error.path}: ${error.message}`);
  else if (error instanceof ProjectError) console.log(error.code);
  else throw error;
}

Output:

focus[0]: unknown task "X"

See Error handling.

Sequential only#

Note

Candidates are scored one after another.

Each candidate runs on its own copy, so candidates are independent, but evaluate runs them one after another on the calling thread. Like every Project method, it's synchronous and CPU-bound, so a large evaluation blocks the event loop until it finishes. In a browser UI or a busy server, move the project to a Worker and call evaluate there. See Run in a worker.

Committing the winner#

evaluate never changes the project. To commit the chosen candidate, run its changes for real: apply the same change set, then level with the same LevelingOptions, step included. With other options, the committed plan isn't the one that was scored. If you scored without level, follow apply with solve(null) instead.

import { Project } from "plen-js";

// Tasks A and B, two days each, both on dev1 in the same week.
function solvedProject() {
  const project = new Project();
  project.solve({
    tasks: [
      { id: "A", start_date: "2026-08-10 08:00", duration: 2 },
      { id: "B", start_date: "2026-08-10 08:00", duration: 2 },
    ],
    resources: [{ id: "dev1" }, { id: "dev2" }],
    assignments: [
      { id: "aA", task: "A", resource: "dev1", value: 1 },
      { id: "aB", task: "B", resource: "dev1", value: 1 },
    ],
  });
  return project;
}

function reassign(assignment, resource) {
  return { assignments: { update: [{ id: assignment, resource }] } };
}

const project = solvedProject();
const candidates = [
  { id: "stay", changes: {} },
  { id: "dev2", changes: reassign("aB", "dev2") },
];
const leveling = {};
const result = project.evaluate(candidates, { level: leveling });

// Lowest cost wins; rejected candidates have no cost.
let best;
result.candidates.forEach((scored, i) => {
  if (scored.cost === undefined) return;
  if (!best || scored.cost < best.cost) best = { cost: scored.cost, candidate: candidates[i] };
});

if (best) {
  // Throws ProjectError("stale-baseline") if the project changed since the evaluation.
  const report = project.apply({ ...best.candidate.changes, baselineId: result.baselineId });
  if (report.rejected.length === 0) {
    // The same options that scored the candidate.
    project.level(leveling);
    console.log(`committed ${best.candidate.id} (cost ${best.cost})`);
  }
}

Output:

committed dev2 (cost 0)

Results come back in input order, so the index of a scored entry is the index of its change set. Setting baselineId to the token from the result makes apply refuse the commit when another edit landed in between. In that case, evaluate again.

If you scored with the clearFirst option of evaluate, commit with level and LevelingOptions.clearFirst (the default) so the commit re-levels from zero, like the scoring did.

To handle a rejected apply, see Recover from rejected changes. To generate candidates automatically instead of writing them by hand, use suggestAssignments, which scores its steps the same way. See Suggesting assignments.