# Scheduling

> How the critical-path engine computes dates, slack and the critical path, how the eight constraints work, why dragging sets a start-no-earlier-than constraint, how changes propagate, and how to schedule tasks manually.

The Gantt's engine is a critical-path method (CPM) scheduler on working calendars. You describe tasks, durations, links and constraints; the engine works out every date. This page explains the rules it follows, which match MS Project's.

**Live demo: Warehouse fit-out project** (runs on the HTML version of this page). Source of `demos/gantt-project.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGantt, type GanttDependency, type GanttTask } from '@birchui/gantt';
import { button, docsTheme, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'Warehouse fit-out project', height: 560 };

const tasks: GanttTask[] = [
  { id: 'plan', name: 'Planning', type: 'summary', expanded: true },
  { id: 'survey', parentId: 'plan', name: 'Site survey', start: '2027-01-04', duration: 3 },
  { id: 'design', parentId: 'plan', name: 'Racking layout design', duration: 5 },
  { id: 'permits', parentId: 'plan', name: 'Building permits', duration: 10 },
  { id: 'signoff', parentId: 'plan', name: 'Design sign-off', type: 'milestone', duration: 0 },
  { id: 'build', name: 'Fit-out', type: 'summary', expanded: true },
  { id: 'floor', parentId: 'build', name: 'Floor resurfacing', duration: 6 },
  { id: 'electrical', parentId: 'build', name: 'Electrical and lighting', duration: 8 },
  { id: 'racking', parentId: 'build', name: 'Install pallet racking', duration: 7 },
  { id: 'conveyor', parentId: 'build', name: 'Conveyor installation', duration: 9 },
  { id: 'golive', name: 'Go-live', type: 'summary', expanded: true },
  { id: 'wms', parentId: 'golive', name: 'Warehouse system configuration', duration: 6 },
  { id: 'training', parentId: 'golive', name: 'Staff training', duration: 4 },
  { id: 'handover', parentId: 'golive', name: 'Handover to operations', type: 'milestone', duration: 0 },
];

const links: [string, string, GanttDependency['type'], number?][] = [
  ['survey', 'design', 'FS'],
  ['design', 'permits', 'SS', 2],
  ['design', 'signoff', 'FS'],
  ['permits', 'signoff', 'FS'],
  ['signoff', 'floor', 'FS'],
  ['signoff', 'electrical', 'FS'],
  ['floor', 'racking', 'FS', 1],
  ['electrical', 'conveyor', 'SS', 3],
  ['racking', 'conveyor', 'FF'],
  ['signoff', 'wms', 'FS', 5],
  ['conveyor', 'training', 'FS'],
  ['wms', 'training', 'FS'],
  ['training', 'handover', 'FS'],
];

const dependencies: GanttDependency[] = links.map(([from, to, type, lag], index) => ({
  id: `d${index + 1}`,
  from,
  to,
  type,
  ...(lag ? { lag } : {}),
}));

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const gantt = createGantt(body, {
    tasks,
    dependencies,
    projectStart: '2027-01-04',
    viewPreset: 'weekAndDay',
    showCriticalPath: true,
    calendars: [
      {
        id: 'uk',
        name: 'UK working days',
        workingDays: [1, 2, 3, 4, 5],
        exceptions: [{ start: '2027-01-01', isWorking: false, name: "New Year's Day" }],
      },
    ],
    calendarId: 'uk',
    theme: docsTheme(),
    height: '100%',
    ariaLabel: 'Warehouse fit-out schedule',
  });
  const undo = button('Undo', () => gantt.undo());
  const redo = button('Redo', () => gantt.redo());
  const syncHistory = () => {
    undo.disabled = !gantt.canUndo();
    redo.disabled = !gantt.canRedo();
  };
  const describeFinish = () => {
    const { end } = gantt.getProjectRange();
    return `Project finishes ${end.toDateString()}; ${gantt.getCriticalPath().taskIds.length} tasks are critical.`;
  };
  toolbar.append(
    button('Zoom in', () => gantt.zoomIn()),
    button('Zoom out', () => gantt.zoomOut()),
    undo,
    redo,
    'Drag a bar to move it, drag its end to change the duration, or drag from a bar edge to another bar to link them.',
  );
  const offs = [
    gantt.on('tasksScheduled', ({ changed, ms }) => {
      status.textContent = `Rescheduled ${changed.length} task(s) in ${ms.toFixed(1)} ms. ${describeFinish()}`;
      syncHistory();
    }),
    gantt.on('cycleDetected', () => {
      status.textContent = 'That link would create a cycle, so it was not added.';
    }),
    gantt.on('taskClick', ({ task }) => {
      const slack = gantt.getSlack(task.id);
      const critical = slack?.isCritical ? ', on the critical path' : '';
      status.textContent = `${task.name}: ${task.start.toDateString()} to ${task.end.toDateString()}${critical}.`;
    }),
  ];
  syncHistory();
  status.textContent = describeFinish();
  const stopTheme = onDocsThemeChange((theme) => gantt.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    gantt.destroy();
  };
}
```

## How dates are computed

1. **Forward pass.** Each task starts as early as its links, constraints and calendar allow: its **early start** and **early finish**.
2. **Backward pass.** From the project's finish, each task is pushed as late as it can go without delaying its successors: its **late start** and **late finish**.
3. **Slack** is the difference between the two. Tasks without slack are **critical**.
4. **Summaries** roll up: they span their subtasks' earliest start and latest finish.

By default every task is scheduled **as soon as possible** (ASAP). Where a task starts depends on whether it has predecessors:

- A task **with** predecessors starts as soon as its links allow, after the project start.
- A task **without** predecessors keeps its own `start` (`unlinkedTaskStart: 'keep'`, the default), or starts at `projectStart` with `unlinkedTaskStart: 'projectStart'`.

`projectStart` defaults to the earliest task start.

## Constraints

A constraint pins a task's start or finish to a date. Set it on the task:

```ts
gantt.updateTask('inspection', { constraint: { type: 'mso', date: '2027-03-15T08:00' } });
gantt.updateTask('signage', { constraint: { type: 'alap' } });
gantt.updateTask('handover', { constraint: null });
```

| Constraint | Name | Effect |
| --- | --- | --- |
| `'asap'` | As soon as possible | The default: start as early as links allow. |
| `'alap'` | As late as possible | Start as late as possible without delaying successors or the project finish. |
| `'snet'` | Start no earlier than | The start is at or after `date`. |
| `'snlt'` | Start no later than | The start is at or before `date`. |
| `'fnet'` | Finish no earlier than | The finish is at or after `date`. |
| `'fnlt'` | Finish no later than | The finish is at or before `date`. |
| `'mso'` | Must start on | The start is exactly `date`. |
| `'mfo'` | Must finish on | The finish is exactly `date`. |

### When links and constraints disagree

`snlt`, `fnlt`, `mso` and `mfo` can contradict the links: an inspection that must finish on Friday while its predecessor only finishes the following Tuesday. In that case **the constraint wins**, as in MS Project:

- the task stays at its constraint date and gets `hasConflict: true`;
- its id is listed in `conflicts` of `tasksScheduled` and of `schedule()`;
- its bar gets the class `lq-gantt-bar--conflict`, and its accessible name says "constraint conflict";
- its predecessors get **negative slack**, which marks them critical: they are already late for the constraint.

```ts
gantt.on('tasksScheduled', ({ conflicts }) => {
  conflictBanner.hidden = conflicts.length === 0;
  conflictBanner.textContent = `${conflicts.length} tasks cannot meet their constraint dates.`;
});
```

## Dragging sets a constraint

When a user drags a bar, moves it with the keyboard, or types a new start date in the grid, the task gets a **start no earlier than** (`snet`) constraint at the new start. This is MS Project's behaviour, and it is what keeps the task where the user put it: without a constraint, an ASAP task with predecessors would snap straight back to the date its links allow.

- A task that already has a **must start on** constraint keeps `mso`, with the new date.
- Dragging a summary moves each of its subtasks by the same amount of working time, and each subtask gets its own `snet` constraint.
- Manually scheduled tasks are moved without a constraint (see below).

To release a task again, remove the constraint and let its links place it:

```ts
gantt.updateTask('content', { constraint: null });
```

`updateTask(id, { start })` from code does **not** add a constraint. On an unlinked task the new start is kept; on a linked task the links win. Set the constraint yourself to get the drag behaviour: `updateTask(id, { start, constraint: { type: 'snet', date: start } })`.

## Slack and the critical path

| Value | Meaning |
| --- | --- |
| Total slack | How far the task can slip without delaying the project finish. |
| Free slack | How far it can slip without delaying any successor. |

Both are reported in **working days** of `hoursPerDay` hours, on the scheduled task (`totalSlack`, `freeSlack`) and through `getSlack(id)`, which also gives milliseconds:

```ts
const slack = gantt.getSlack('content');
```

`slack` is an object such as `{ total: 7.4375, free: 7.4375, totalMs: 214200000, freeMs: 214200000, isCritical: false }`: this task can slip about seven and a half working days.

A task is **critical** when its total slack is zero or negative. `getCriticalPath()` returns the critical tasks and the links between them:

```ts
const { taskIds, dependencyIds } = gantt.getCriticalPath();
```

`showCriticalPath: true` highlights critical bars and the links between them (`--lq-gantt-critical`). The critical path is the chain to watch: any slip there moves the project finish, which `getProjectRange()` reports.

## Propagation and auto-scheduling

When a task changes, the engine reschedules only what the change affects: the task, its successors, their successors, and the summaries above them. A single edit in a 5,000-task project takes about 12 ms (see [Performance](https://docs.birchui.com/gantt/performance.md)).

Every change is followed by `tasksScheduled`:

| Field | Description |
| --- | --- |
| `changed` | Ids of tasks whose dates changed. |
| `ms` | How long scheduling took. |
| `conflicts` | Ids of tasks whose constraint overrode a link. |

```ts
gantt.on('tasksScheduled', ({ changed }) => {
  if (changed.length) void api.post('/schedule/dates', changed.map((id) => pick(gantt.getTask(id)!)));
});
```

With `autoSchedule: false`, edits change the edited task but do not move its successors until you call `schedule()`. Use it for "what-if" planning, where people rearrange several tasks and then press **Reschedule**:

```ts
const gantt = createGantt(container, { tasks, dependencies, autoSchedule: false });
rescheduleButton.addEventListener('click', () => {
  const { changed, conflicts, projectEnd } = gantt.schedule();
  statusLine.textContent = `${changed.length} tasks moved, finish ${projectEnd.toDateString()}, ${conflicts.length} conflicts`;
});
```

`schedule()` always runs a full forward and backward pass and returns a `ScheduleResult` with `changed`, `ms`, `cycles`, `conflicts`, `projectStart` and `projectEnd`.

## Manually scheduled tasks

`manuallyScheduled: true` keeps a task exactly where its `start` and `end` put it, whatever its links say. Use it for work outside your control, such as a vendor's delivery window or a fixed audit.

```ts
const tasks = [
  { id: 'wms', name: 'WMS configuration (vendor)', manuallyScheduled: true, start: '2027-01-05T08:00', end: '2027-01-07T17:00' },
];
```

- Its **successors still follow it**, so the rest of the plan reacts to the vendor's dates.
- Dragging moves its start and end together without adding a constraint; resizing changes its `end`.
- Its bar has the class `lq-gantt-bar--manual`, and MS Project XML exports it as a manually scheduled task.

## Next steps

- [Baselines](https://docs.birchui.com/gantt/baselines.md) to compare the schedule with the plan.
- [Interactions](https://docs.birchui.com/gantt/interactions.md) for dragging and keyboard editing.
- [Headless engine](https://docs.birchui.com/gantt/headless.md) to schedule on a server.
