本文へ移動

スケジューリングとリソース ​

計画を計算するのはスケジューラーで、GanttChart はそれを描くだけです。buildWorkPeriods は週ごとのシフトと例外日から稼働カレンダーを作り、scheduleTasks はカレンダーを考慮して最早・最遅の日付、フロート、クリティカルパスを計算します(FS・SS・FF・SF とラグに対応)。levelResources は割り当ての負荷が能力に収まるようにタスクを遅らせます。ほかに、1 つの編集の波及、ステータス日や実績からの再スケジュール、アーンドバリューの計算、PERT ネットワーク図、リソース別の表示、タスクがその時刻に始まる理由の説明、候補の計画と現在の計画の比較のための関数があります。

循環や実行不可能な計画は例外ではなく、診断付きの結果として返るので、そのままユーザーに示せます。

最小の例 ​

ts
import { buildWorkPeriods, scheduleTasks, scheduledBarFields, type TimelineBar } from '@eightkk/vue-weave/core'

const hour = 3_600_000
const start = Date.parse('2026-11-09T00:00:00Z')
const range = { start, end: start + 28 * 24 * hour }
// 月曜から金曜、日本時間の 8:00〜17:00
const weekly = [1, 2, 3, 4, 5].map(weekday => ({ weekday, startMinute: 8 * 60, endMinute: 17 * 60 }))
const periods = buildWorkPeriods(range, { utcOffsetMinutes: 540, weekly })

const plan = scheduleTasks({
  range,
  quantum: 60_000,
  calendars: [{ id: 'plant', periods }],
  defaultCalendarId: 'plant',
  tasks: [{ id: 'cut', duration: 6 * hour }, { id: 'weld', duration: 10 * hour }],
  dependencies: [{ id: 'cut-weld', from: 'cut', to: 'weld', type: 'FS' }],
})
const bars: TimelineBar[] = plan.ok
  ? plan.tasks.map(task => ({ id: task.id, rowId: task.id, label: task.id, ...scheduledBarFields(task) }))
  : []

例: スケジューリング、建設工程。ガイド: スケジューリング、リソースと計画の分析。型: scheduleTasks、ScheduleInput、levelResources、computeEarnedValue。

英語の詳細

ここから下の詳細なリファレンスは英語です。

Calendars, scheduling and resource load ​

normalizeWorkPeriods(periods, range) returns sorted, clipped, merged half-open intervals. The range and period endpoints must be safe integers, and each interval must have positive length. buildWorkPeriods(range, week) generates these periods from weekly shifts, a fixed UTC offset or an IANA timeZone, and civil-date overrides; it uses epoch milliseconds.

scheduleTasks(input) returns a ScheduleResult. Successful results contain tasks (in input order, without inactive tasks), criticalDependencyIds and the project finish, and, only when they are not empty, manualConflicts and inactiveTaskIds. Each ScheduledTask reports totalFloat (working time for tasks, elapsed time for milestones) and workFloat (working time on the task calendar for both tasks and milestones). Cycle or infeasible results contain no partial schedule.

calculateResourceLoad returns ResourceLoadSegment[] with resource ID, start/end, load, available capacity, overload and contributing task IDs. Its optional fifth argument, ResourceLoadOptions, takes inactiveTaskIds (for example a result's inactiveTaskIds): the assignments of those tasks still need a known resource, valid units and no duplicate, but take no capacity, so a plan's full assignment list can be passed; a listed task that is also in tasks throws an Error. Both functions check each assignment with the same checker and messages, in this order: an unknown resource (Unknown resource in assignment: <id>), an unknown task (Unknown task in assignment: <id>), units that are not a positive integer (RangeError Assignment units must be a positive integer) and a second assignment of the same task to the same resource (Duplicate assignment of task <task> to resource <resource>). For calculateResourceLoad the unknown-task message adds that tasks left out of a schedule result as inactive must be listed in options.inactiveTaskIds; levelResources omits that hint, because it reads inactive tasks from its own schedule input. IDs that contain any separator character never collide in the duplicate check. The taskIds array is typed read-only and segments with the same tasks in the same order share one array, so many overlapping tasks do not copy their IDs into every segment; copy it before changing it. It reports conflicts without automatically moving tasks. See the scheduling guide for time units, quantum alignment, calendar rules, failure results and capacity constraints.

ResourceCapacity is { id, capacity, periods?, capacityPeriods? }. Optional capacityPeriods (ResourceCapacityPeriod[]: { start, end, capacity }) replace capacity over fixed half-open intervals of absolute time; outside them capacity applies and outside periods the capacity is 0. Periods need integer endpoints with end > start, a nonnegative integer capacity and must not overlap within a resource (adjacent is fine); otherwise a RangeError names the resource, and a value that is not an array throws an Error. Segments split where the capacity changes, so each segment's capacity and overload hold for its whole interval. ResourceAssignment is { resourceId, taskId, units?, workOffset?, workDuration? }. With workOffset (nonnegative integer, default 0) or workDuration (positive integer, default the rest of the work), the assignment covers only that part of the task's working time, measured along its work segments in the units of the times; a part beyond the work is clipped, and invalid values throw a RangeError. Load is added only during the part, and a task is in taskIds only there. levelResources honours both fields and also requires them to align with the quantum. See Capacity that changes over time and Assignments for part of a task.

Related exported types: WorkShift, WeeklyShift.

Scheduling modes, splits, leveling and time zones ​

APIBehavior
WorkWeek.timeZoneIANA zone name. Shift minutes become local wall-clock times with daylight-saving rules from Intl.DateTimeFormat. Skipped wall times resolve to the transition instant; repeated wall times resolve to the earlier occurrence. Cannot be combined with utcOffsetMinutes. An invalid zone throws RangeError.
ScheduleTask.mode'asap' (default) or 'alap'. An ALAP task takes the latest slot that moves no other task and keeps the project finish. Its result adds earliestStart and earliestEnd; float remains measured from the earliest dates.
ScheduleTask.pausesElapsed half-open intervals removed from this task's working time. Work is split around them.
ScheduleTask.splittable / priorityUsed only by levelResources. splittable lets leveling add pauses. A higher priority (default 0) is placed first.
ScheduleTask.manualA TimeRange of manually scheduled dates, like a manually scheduled task in Microsoft Project. The task stays at exactly these elapsed dates: predecessors, its own bounds, mode and its calendar do not move it and duration is ignored; successors follow it. Its result has manual: true, work (its calendar's working time inside the dates, after pauses; may be empty), its own dates as latest dates, totalFloat and workFloat 0 and critical: false. Links into it bind nothing in any pass but still count for cycles; each one its dates violate is listed in manualConflicts. Dates must align with the quantum and lie inside range with end >= start (RangeError); a manual task that ends after the deadline is infeasible with ['deadline']. See Manual and inactive tasks.
ScheduleTask.inactivetrue leaves the task out of the calculation, like an inactive task in Microsoft Project: it, every link that touches it and its assignments are ignored, and it is not in tasks. It is still validated and its ID still counts; links may name it. A value that is not a boolean throws an Error.
ScheduleTask.parentIdMakes the task a subtask of the task with this ID; a task that other tasks name as parent is a summary task. Its dates are the span of its subtasks, so its duration, calendarId, pauses, splittable and priority are ignored, and fixedStart, startNoLaterThan, finishNoEarlierThan, manual or mode: 'alap' on it throw an Error. Its startNoEarlierThan and finishNoLaterThan bind every subtask. FS and SS links into it bind the start of every subtask; FF and SF links into it throw an Error. Links from it use its rolled-up start or finish. An inactive summary makes its subtasks inactive, and a summary whose subtasks are all inactive is inactive. An unknown parent, a cycle of parent IDs and a link between a summary and its own subtask throw an Error that names the tasks. See Summary tasks.
ScheduledTask.summary / parentIdsummary: true marks a summary task: start/end and latestStart/latestEnd span its subtasks, work is empty, totalFloat and workFloat are the smallest of its subtasks that are not manual (0 when all are manual) and critical is true when a subtask is critical. parentId repeats the input parentId of a subtask. Both are present only with a hierarchy.
ScheduleSuccess.manualConflicts / inactiveTaskIdsScheduleManualConflict[] ({ taskId, dependencyId }): links into manual tasks whose dates violate them, measured in elapsed time against the predecessor's reported dates, in link order. inactiveTaskIds: the inactive tasks in input order. Each is present only when not empty, so a plan that uses neither manual nor inactive tasks has neither field.
ScheduleFailure (cycle)cycles: ScheduleCycle[]. Each cycle has taskIds and dependencyIds of one strongly connected group, in input order.
ScheduleFailure (infeasible)Adds constraints: ScheduleConstraintName[] and dependencyIds, the binding bounds and links that conflict.
levelResources(input)LevelResourcesInput is a ScheduleInput plus resources and assignments. Returns ScheduleFailure or LevelResourcesSuccess: the leveled schedule plus leveledTasks, delays (ResourceDelay[]), overloads and unresolvedTaskIds. Capacity is reserved against capacityPeriods, and a partial assignment (workOffset, workDuration) needs its resource only during its part of the work, so a plan without unresolved tasks has no overload in calculateResourceLoad.

The exported types are ScheduleSuccess, ScheduleFailure, ScheduleCycle, ScheduleConstraintName, ScheduleManualConflict, ResourceLoadOptions, ResourceCapacityPeriod, LevelResourcesInput, LevelResourcesSuccess, LevelResourcesResult, ResourceDelay, ScheduleEdit, ScheduleChange, PropagateEditSuccess and PropagateEditResult. levelResources ranks ready tasks by priority, then total float, then early start, then ID, and gives each the earliest start with enough capacity before its latest feasible dates. Tasks without such a start keep their earliest dates and are reported as unresolved. Manual tasks never move: their capacity is reserved first, and one that finds too little capacity at its dates is reported as unresolved. The scheduling guide defines each step. Optimization policies remain the application's concern.

Recorded actuals ​

rescheduleFromActuals(input, statusDate, actuals) replans from what actually happened instead of a progress share. actuals is a ReadonlyMap from task ID to TaskActuals:

FieldMeaning
intervalsRecorded working intervals, half-open [start, end) in absolute time, possibly several (start, interruption, resume). Each must be finite, have end > start, align with the horizon and quantum and lie inside input.range; otherwise a RangeError with the scheduler's message for the same defect in its own input followed by (actual interval of task <id>): Scheduling dates must align with the horizon and quantum for a non-finite, fractional or misaligned endpoint, Working periods must have finite integer endpoints and positive length for a missing endpoint or an interval that does not end after it starts (as for pauses), and Scheduling dates must lie inside the schedule range. They are never moved, clipped to a calendar or merged with the forecast
remainingWorkOptional working time still to do, in the input's units on the task's calendar; a non-negative multiple of the quantum (RangeError otherwise). Default: duration minus the elapsed length of the intervals (overlaps counted once), at least 0
finishedOptional true when the task is complete. Requires at least one interval (Error)

The status date is validated like that of rescheduleFromStatusDate. Actuals that are not a Map, an unknown task, a summary task or an entry without an intervals array throw an Error; entries of inactive tasks are validated and ignored. The arguments are not modified.

RescheduleFromActualsResult is a union on ok, which equals schedule.ok:

FieldMeaning
scheduleThe forecast ScheduleResult with the input's task and link IDs. A started task spans from its first actual start to its forecast finish and its work is its sorted actual intervals followed by its remaining work; its latest dates and float describe the remaining work. A finished task spans its actuals, with latest dates equal to its dates, float 0 and critical false
planscheduleTasks(input), the original plan
tasksOne ActualsTask per active task in input order
diagnosticsActualsDiagnostic entries, task by task, followed by toPlanningDiagnostics(schedule)
statusDateThe status date

An ActualsTask has id, state (ActualsTaskState: not-started, in-progress or finished), actual (copies of the recorded intervals in input order), remaining (the forecast working segments of the remaining work; empty for finished, manual and summary tasks, milestones and a failed schedule), performedWork, remainingWork, the forecast start and end (after a failure, the span of the actuals, or absent), plan (the task's dates in plan, when it succeeded), offCalendar (the parts of the actuals outside the task's calendar after pauses) and, when they apply, parentId, summary and manual. A summary task sums performedWork and remainingWork of its subtasks and is finished when all of them are.

An ActualsDiagnostic has the shape of a PlanningDiagnostic (id, code, severity, entities with the task, range, empty reasonIds), so both fit in one list. ActualsDiagnosticCode:

CodeSeverityRange
actual-overlaperrorThe overlapping part of two intervals of the task
actual-after-status-datewarningThe part of an interval after the status date
actual-outside-calendarwarningA part of an interval outside the task's working time
actual-contradictionerrorNone: the task is finished but has a positive remainingWork

actualsTimelineBars(result, options?) returns TimelineBar[] in task order, without summary tasks (use GanttChart showSummaries for their rows). A task with actuals gets a solid bar <label> · actual spanning them, with the merged intervals as segments when there are several; a task with remaining work, and an unstarted or manual task, gets an outline bar <label> · forecast over its forecast work. After a failed schedule only actual bars are returned. The original plan becomes a baseline of the task's first bar. ActualsTimelineBarOptions:

OptionDefault
label(taskId)The task ID
rowId(taskId)The task ID
barId(taskId, part)taskId + ':' + part, with part actual or forecast
partLabels{ actual: 'actual', forecast: 'forecast' }, appended to the label after ·
descriptions{ actual: 'Recorded actual work', forecast: 'Remaining work forecast' }, the bars' description
tones{ actual: 'teal', forecast: 'blue' }
baselineIdtimelineBaselineId: the plan becomes the bar's baseline. Another ID adds a named baselines entry; false adds none

Related exported types: RescheduleFromActualsFields.

Earned value management ​

computeEarnedValue(tasks, options) calculates earned value management (EVM) figures for a plan at a status date. It does not schedule anything: pass each task's budget and baseline dates, for example from a scheduleTasks result or a TimelineBar baseline, and its progress and cost so far. See Earned value management for the formulas and assumptions.

EarnedValueTask:

FieldMeaning
idTask ID; an invalid or duplicate ID throws an Error (Invalid task ID: …, Duplicate task ID: …)
budgetBudget at completion (BAC), a finite number ≥ 0 in any currency or effort unit
start, endPlanned (baseline) dates, half-open [start, end), finite with end ≥ start; end === start is a milestone
progressOptional completed share at the status date, 0 to 1 like TimelineBar.progress. Default: the last history record's progress, else 0
actualCostOptional actual cost (AC) up to the status date, finite and ≥ 0. Default: the last history record's cost, else 0
calendarIdOptional calendar of options.calendars; planned value then accrues over its working time only
historyOptional EarnedValueRecord[] ({ time, progress, actualCost? }) before the status date, by strictly increasing time, for the EV and AC curves. A record without actualCost keeps the previous cost

EarnedValueOptions:

OptionMeaning
statusDateRequired finite time. PV counts the planned work in [start, statusDate)
calendars, defaultCalendarIdWorkCalendar[] as for scheduleTasks (only id and periods are read; periods need finite endpoints and positive length, in any unit) and the calendar of tasks without calendarId. Without a calendar, PV accrues linearly over elapsed time
eacMethodEarnedValueEacMethod: 'cpi' (default), 'cpi-spi' or 'budget'
seriesEarnedValueSeriesOptions { step, start?, end? }: calculate the cumulative series every step from start (default: the earliest planned start) to end (default: the latest planned end or the status date). At most maxEarnedValuePoints (100,000) points

EarnedValueResult has statusDate, eacMethod, tasks (an EarnedValueTaskResult with id per task, in input order), totals and series. Each task and the totals are EarnedValueMetrics:

FieldFormulaUndefined when
bacbudget
pvbac × planned share before the status date
evprogress × bac
acactualCost
sv, cvev − pv, ev − ac
spiev / pvpv is 0
cpiev / acac is 0
etc(bac − ev) / index; 0 when ev = bac. The index is cpi ('cpi'), cpi × spi ('cpi-spi') or 1 ('budget'), where an undefined CPI or SPI counts as 1work remains and the index is 0
eacac + etcetc is undefined
vacbac − eaceac is undefined
tcpi(bac − ev) / (bac − ac)bac − ac ≤ 0 (the budget is spent)
percentCompleteev / bacbac is 0

An undefined ratio is left out of the object; no field is ever NaN or Infinity. totals is rollupEarnedValue(tasks, { eacMethod }). Each EarnedValuePoint of series has time and pv, and, at points up to the status date, ev and ac; the status date is always a point inside the series range.

rollupEarnedValue(items, options?) sums bac, pv, ev and ac of any EarnedValueAmounts[] (such as some task results) and derives the indicators from the sums, for a summary row or any group. An empty list gives zeros. Values that are not finite numbers ≥ 0 throw a RangeError (ev of earned value item 0 must be a finite number ≥ 0 (got -1)).

Errors of computeEarnedValue: RangeError for statusDate must be a finite number (got …), Budget of task <id> must be a finite number ≥ 0 (got …), Planned dates of task <id> must be finite with end ≥ start (got …), Progress must be between zero and one: <id> (with (history) for a record), Actual cost must be a finite number ≥ 0: <id> (got …), History times of task <id> must be finite, strictly increasing and not after the status date (got …), Working periods must have finite endpoints and positive length (calendar <id>), series.step must be a finite number > 0 (got …), series.start/series.end that are not finite or end before the start, and a series with too many points; Error for tasks that are not an array, missing options, an invalid or duplicate task or calendar ID, Unknown calendar: <id> (with (task <id>) for a task's calendar), History must be an array: <id>, Invalid history record: <id> and Unknown EAC method: …. The arguments are not modified.

GanttChart needs no new prop to show EVM figures: return them from TimelineColumn.value(row), using rollupEarnedValue over a summary row's tasks, and pass the status date as statusDate. Related exported types: EarnedValueTask, EarnedValueRecord, EarnedValueOptions, EarnedValueSeriesOptions, EarnedValueEacMethod, EarnedValueAmounts, EarnedValueMetrics, EarnedValueTaskResult, EarnedValuePoint, EarnedValueResult.

Network diagram from a schedule ​

scheduleToGraph(result, dependencies, options?) turns a successful scheduleTasks (or propagateEdit, rescheduleFromStatusDate) result into an activity-on-node diagram for NetworkGraph. It returns a ScheduleGraph: nodes (one NetworkNode<ScheduleGraphNodeData> per task in result order, with ID, label, a detail with the early start, early finish and total float, and data of type ScheduleGraphNodeData: task, earlyStart, earlyFinish and critical), edges (one GraphEdge<ScheduleGraphEdgeData> per dependency with the dependency's ID, a label and data of type ScheduleGraphEdgeData: type, critical and, only for a non-zero lag, lag), criticalNodeIds and criticalEdgeIds (the result's criticalDependencyIds). Because the arrays carry these data types, graph.nodes[0].data?.critical and graph.edges[0].data?.lag are typed without casts, and NetworkGraph slots and events infer the same data types. Critical tasks get the criticalTone (default amber) and the others the tone (default blue). For an ALAP task the early dates are earliestStart and earliestEnd. An edge label shows the dependency type when it is not FS and a non-zero lag formatted by formatLag, separated by a space: SS, +2 h, SS +2 h or FF −0.5 h (a lead). An FS dependency without lag, or with a lag of 0, has no label. A dependency that touches a task listed in the result's inactiveTaskIds is left out, so the plan's full dependency list can be passed; a manual task is a node like any other, with zero float.

ScheduleGraphOptions: label(taskId) (default the ID), formatTime (default UTC YYYY-MM-DD HH:mm), formatDuration for the float (default hours of a millisecond duration, for example 1.5 h), formatLag for a non-zero lag (default formatDependencyLag, signed hours of a millisecond lag such as +2 h; called only for a non-zero lag, so charts in other units pass their own, as with GanttChart formatLag), labels (earlyStart, earlyFinish and float prefixes; defaults ES, EF and Float), criticalTone and tone. A failed result, a dependency whose ends are not tasks of the result, a dependency from a task to itself, or a repeated dependency ID (edge IDs must be unique) throws an Error; a lag that is not a finite number throws a RangeError.

vue
<NetworkGraph :nodes="graph.nodes" :edges="graph.edges" :related-ids="graph.criticalNodeIds" :options="{ nodeWidth: 280 }" />

relatedIds highlights the critical tasks and the edges between them; use criticalEdgeIds with an edge slot to style exactly the controlling links.

Resource timelines and unplanned tasks ​

These @eightkk/vue-weave/core helpers show one plan by resource in an ordinary GanttChart. A task assigned to several resources appears once in each resource row; the input task stays one item, so its dates, its work and the resource load are not multiplied by the number of rows. See Resource rows and unplanned tasks for the workflow.

FunctionReturns
projectResourceTimeline(input, options?)ResourceTimelineProjection: { rows, bars, dependencies, laneCount, origins, taskBarIds, dependencyOrigins, omittedDependencyIds, hiddenDependencyIds, unplannedTaskIds }
createResourceTimelineProjector()A memoized projectResourceTimeline that returns the previous projection while the input fields and options are the same objects
resourceTimelineBarId(taskId, resourceId)The projected bar ID, the JSON tuple [taskId, resourceId]
resolveResourceTimelineEdits(projection, edits){ ok: true, scheduleChanges, assignmentReplacements } or a ResourceTimelineRejection
resolveResourceTimelineEdit(projection, edit){ ok: true, scheduleChange?, assignmentReplacement? } or a ResourceTimelineRejection
resourceTimelineCascade(projection, input)A TimelineCascade that runs propagateEdit on task IDs and returns edits of every affected projection
proposeResourceAssignment(state, request){ ok: true, assignments, added, removed } or { ok: false, code: 'already-assigned' | 'not-assigned', reason }
buildPlacementInput(input, placedTaskIds)PlacementResult: { ok, input, diagnostics, unplacedTaskIds, excludedDependencyIds, excludedAssignments, retargetedDependencies? }

ResourceTimelineInput has resources ({ id, label, detail?, data? }, one row each, with the resource ID as row ID), tasks (placed tasks: TimelineBar fields without rowId and lane, copied to each projection), assignments (ResourceAssignment), optional task-level dependencies and optional unplannedTaskIds. Bars are ordered by task and then by row, with lanes from assignLanes; pass laneCount to GanttChart. The default label is task label · resource label, so projections of one task have distinct accessible names; options.barLabel(task, resource) replaces it. Bar IDs come from the task and resource IDs and do not depend on input order. origins maps each bar ID to { taskId, resourceId } and taskBarIds maps each placed task to its bar IDs in row order. An assignment with workOffset or workDuration still gets one bar for the whole task; use assignmentWorkPeriods to show its part.

Chart links use bar IDs, so the scheduler's ScheduleLink array cannot be passed to the chart unchanged. Each task link becomes at most one chart link, with the link's ID, between the first projection of each task in options.preferredBarIds (for example the selected bars) or else its first projection in row order. dependencyOrigins maps chart link IDs to task link IDs, omittedDependencyIds lists drawn links whose tasks have several projections, and hiddenDependencyIds lists links not drawn because a task has no bar. The projection throws an Error for duplicate IDs, unknown or duplicate assignments, unknown link endpoints, a link from a task to itself and a task that is both placed and unplanned. The input is not modified.

resolveResourceTimelineEdits turns GanttChart edits, including several projections of one task from edits or a cascade, into one ResourceTimelineScheduleChange ({ taskId, before, after, mode, source }) per task whose dates change, and one ResourceAssignmentReplacement ({ taskId, fromResourceId, toResourceId }) per bar whose row changes. A diagonal move gives both; apply them as one change. Rejections carry code and the barIds involved: stale (the bar is not in the projection, or its dates or row differ from before), already-assigned (the task already has the target resource), conflicting-schedule (projections of one task with different new dates) and conflicting-assignment (one bar to two rows, or two projections of one task to one row). A target row that is not in the projection throws an Error.

proposeResourceAssignment(state, request) takes { assignments, resourceIds?, taskIds? } and one of { kind: 'add', taskId, resourceId, units? }, { kind: 'remove', taskId, resourceId } and { kind: 'replace', taskId, fromResourceId, toResourceId }. A replacement keeps the position, units and workOffset/workDuration of the replaced assignment. Unknown tasks or resources (when the lists are given) and duplicate assignments in the state throw an Error, and units that are not a positive integer throw a RangeError.

buildPlacementInput(input, placedTaskIds) takes a ScheduleInput with optional assignments, such as a LevelResourcesInput, and returns the same kind of input with only the placed tasks, the links between them and their assignments. A link from an unplaced task to a placed one is reported as { code: 'unplaced-predecessor', taskId, predecessorId, dependencyId } and makes ok false, unless the scheduler would ignore it anyway: a link that touches an inactive task, or a link into a placed task with manual dates, is only excluded. Leaving out an unplaced summary task keeps what binds its placed subtasks. A placed task whose parentId names an unplaced task gets the ID of its nearest placed ancestor instead, or none when no ancestor is placed; the startNoEarlierThan and finishNoLaterThan of the unplaced summaries it skips become its own where they are tighter (the scheduler combines inherited bounds the same way), and a placed task that is inactive only because of an unplaced summary gets inactive: true. An FS or SS link into an unplaced summary binds the summary's placed active leaf subtasks, as in the full plan: from a placed task it is excluded and replaced by one link per leaf, listed in retargetedDependencies as { id, dependencyId, summaryId, taskId } (PlacementRetargetedDependency; the field is present only when not empty), so map criticalDependencyIds and trace IDs back through dependencyId; from an unplaced task it is an unplaced-predecessor diagnostic for each such leaf that is not manual. A link from an unplaced summary is a link from an unplaced task: its rolled-up dates are not part of the placement input. Inactive means inactive as the scheduler sees it, so tasks below an inactive summary and summaries without an active leaf bind nothing either. A placed summary that is active in the full plan but has no placed active leaf subtask (its active subtasks are all unplaced, though inactive ones may be placed) has nothing placed to span, and the placement input does not schedule it with its own duration, which the full plan ignores: it is reported as { code: 'unplaced-subtasks', taskId } (PlacementSummaryDiagnostic), makes ok false and is then treated as an unplaced summary. It, its links and its assignments are left out (in excludedDependencyIds and excludedAssignments, but not in unplacedTaskIds), its placed subtasks move up and take over its bounds, and a link from it is an unplaced-predecessor diagnostic; this applies to nested summaries too. unplaced-subtasks entries come first in diagnostics, in input order, then unplaced-predecessor entries in link order. PlacementDiagnostic is the union of PlacementPredecessorDiagnostic and PlacementSummaryDiagnostic; check code before reading predecessorId or dependencyId. Duplicate or unknown IDs and duplicate assignments still throw an Error. An input with parentId must also meet the scheduler's summary task rules on every task and link, placed or not, and throws scheduleTasks' own Error otherwise: an invalid or unknown parent ID, a parent cycle, fixedStart, startNoLaterThan, finishNoEarlierThan, manual or mode: 'alap' on a summary, a link between a summary and its own subtask, and an FF or SF link into a summary. Other checks of the scheduler, such as durations and link types, are left to the call that schedules the placement input, as for plans without parentId.

Related exported types: ResourceTimelineTask, ResourceTimelineResource, ResourceTimelineOptions, ResourceBarOrigin, EditMode, ResourceTimelineRejectionCode, ResourceTimelineEditResolution, ResourceTimelineEditsResolution, ResourceAssignmentRequest, ResourceAssignmentState, ResourceAssignmentProposal, PlacementInput, PlacementDiagnostic, PlacementPredecessorDiagnostic, PlacementSummaryDiagnostic, PlacementRetargetedDependency.

Planning diagnostics and schedule traces ​

These core helpers explain a plan without changing it. They are pure and return data; wording, translation and the list UI are the application's concern.

ExportContract
scheduleTasks(input, options?)options.explain (default false) adds a trace: ScheduleTrace to a successful result. Overloads type trace only for { explain: true } (ExplainedScheduleResult). Dates, floats, critical flags and criticalDependencyIds are the same with or without it; without it the result has no trace property. Failures never have a trace. Options that are not an object, or an explain that is not a boolean, throw an Error
levelResources(input, options?)The same option and overloads (ExplainedLevelResourcesResult). Dates, leveledTasks, delays, overloads and unresolvedTaskIds are unchanged
collectScheduleReasons(trace, taskId, options?)The task's reasons followed by all their ancestors, breadth first, each once. options.phases limits the starting reasons. Iterative, so long chains do not exhaust the call stack. Throws an Error for an unknown task or parent reason
toPlanningDiagnostics(result, load?)Turns a scheduleTasks or levelResources result into PlanningDiagnostic[]. load (for example calculateResourceLoad output) replaces the result's own overloads; only segments with overload > 0 are listed. A segment with a non-finite date or overload throws a RangeError. Each entry of the result's manualConflicts becomes a manual-conflict warning; a success lists them first, then unresolved tasks, then overloads

ScheduleTrace has reasons (each after its parents) and taskReasonIds (a ReadonlyMap from task ID to its own reason IDs, in input task order, without inactive tasks). Do not store a trace in a snapshot; recalculate it. A ScheduleReason has an id unique within its trace, taskId, phase (ScheduleReasonPhase), kind (ScheduleReasonKind), bound (startLower, endLower, startUpper or endUpper), candidateTime and placedTime, parentReasonIds, and depending on its kind dependencyId, constraint, calendarId, resourceId, demand, capacity, relatedTaskIds and range.

kindMeaning
dependencyA link sets the limit. relatedTaskIds is the other task and the parents are its reasons in the same pass
constraintstartNoEarlierThan, startNoLaterThan, finishNoEarlierThan, finishNoLaterThan or fixedStart. For a constraint that a subtask inherits from a summary task, relatedTaskIds is that summary task
project-boundrange, the input deadline, projectFinish (parents: the reasons of the tasks that finish the project) or, without a constraint, the latest dates that leveling may not pass (parents: that task's latest reasons)
calendarCalendar time off moved the side from candidateTime to placedTime
pauseThe task's own pauses moved it further
capacityIn leveling: resourceId had less remaining capacity than demand in range; capacity is its capacity there and relatedTaskIds the tasks that held it first. A manual task that finds too little capacity at its dates gets these reasons too
manualThe task has manual dates, which fix it: one reason per phase (earliest and leveling with bound startLower, latest with startUpper), with the manual start as candidateTime and placedTime

Tied limits are all reported, compared in working time as the scheduler places tasks. range is left out when a named bound has the same value, as in ScheduleFailure.constraints.

A PlanningDiagnostic has id (a JSON array of the code and identifying values, stable across recalculations), code (PlanningDiagnosticCode), severity (PlanningDiagnosticSeverity), entities (EntityRef[] of kinds task, dependency and resource), optional range, optional constraints (for schedule-infeasible) and reasonIds into the result's trace.

codeseveritySource
schedule-cycleerrorOne per entry of a cycle failure: its tasks and dependencies
schedule-infeasibleerrorAn infeasible failure: the task, its binding dependencies and constraints
manual-conflictwarningEach of manualConflicts, listed first: the manual task, then the violated dependency; the plan stays valid. reasonIds hold the task's manual reason of the earliest phase
leveling-unresolvedwarningEach of unresolvedTaskIds, with its dates; reasonIds are its leveling reasons
resource-overloadwarningEach overloaded segment: the resource, then its tasks; reasonIds are the overlapping capacity reasons

The exported types are PlanningDiagnostic, PlanningDiagnosticCode, PlanningDiagnosticSeverity, ScheduleReason, ScheduleReasonPhase, ScheduleReasonKind, ScheduleReasonBound, ScheduleTrace, ScheduleOptions, CollectScheduleReasonsOptions, ExplainedScheduleSuccess, ExplainedScheduleResult, ExplainedLevelResourcesSuccess and ExplainedLevelResourcesResult. See Explain a plan.

Plan scenario comparison ​

Core helpers that compare a candidate plan with the current plan. They are pure, use loops only, never modify their arguments and return data; the comparison table, wording and adoption are the application's concern. See Compare plan scenarios.

ExportContract
comparePlans(current, candidate)Compares two PlanScenarios and returns a PlanComparison with two separate parts: input (PlanInputDiff, the differences of the inputs) and result (PlanResultDiff, the differences of the calculated schedules). A side without result is calculated with scheduleTasks(input, { explain: true }); a side without load but with input.resources gets calculateResourceLoad of its result. A cycle or an infeasible plan (a project deadline failure included) never throws: it is reported in result.state and the input differences are still returned. Each side is validated by the scheduler's own rules (through scheduleTasks, or the same validation when a result is given) and the shared resource and assignment checks, and every error of a side ends with (current plan) or (candidate plan), for example Duplicate task ID: a (current plan); the class is that of the underlying check. Throws an Error for an invalid or duplicate task, dependency, calendar or resource ID, any other invalid scheduling input the scheduler rejects, a duplicate or unknown assignment, an invalid partial, revision or baseRevision, or a successful result whose task set does not match its input (a task its input does not have as active, a task listed twice, an active task of the input that is missing, or inactiveTaskIds that do not list exactly the inactive tasks of the input, the subtasks of an inactive summary included), so a result calculated before a task was added or removed is rejected. Only task sets are checked: a result for an earlier version of the same tasks (a changed duration, say) cannot be detected, a failed result (cycle or infeasible) is checked only for its shape, and a partial side is checked against the loaded input it is passed with; a RangeError for invalid numbers of the scheduling input, a non-finite task deadline or a load segment with non-finite or unordered dates, a negative overload, or overlapping segments of one resource. Invalid scheduling input throws from scheduleTasks as usual
planComparisonTargets(comparison, index, options?)View projection: the tasks of options.taskIds (default: every task of comparison.result.tasks) as EntityRefs of kind options.entityKind (default task), their targets through a buildViewBindingIndex index (targets, unknown as in resolveViewTargets), and load: for each listed task of result.tasks, a LoadViewTarget for its dates in each scheduled plan on each resource assigned in that plan, for highlightedLoadTargets. Empty ranges and repeats are left out
planBaselines(result, setId)The dates of a successful scheduleTasks or levelResources result as one baseline set: a Map from task ID to TimelineBaseline { id: setId, start, end }. Add the entries to TimelineBar.baselines of the candidate bars and pass setId in baselineIds to draw the current plan under the candidate. Throws an Error for a failed result or an empty or reserved (timelineBaselineId) set ID

PlanScenario: input (PlanComparisonInput: a ScheduleInput whose tasks are PlanComparisonTasks, plus optional resources and assignments), optional precomputed result and load, optional revision (of the current plan), baseRevision (of a candidate: the current revision it was derived from) and partial (true when the plan's data is not completely loaded). PlanComparisonTask adds an optional deadline: a due time that is not a scheduling bound (as TimelineBar.deadline); a scheduled task that ends after it is a deadline violation.

PlanComparison:

FieldMeaning
complete, partialcomplete is false when either side is flagged partial; partial says which
revision{ current?, base?, stale }: stale is true when the current revision and the candidate's baseRevision are both given and differ
emptyTrue when the inputs are equal and so is every compared result
inputsettings (changed top-level input fields such as range, quantum, defaultCalendarId or deadline), and for tasks, dependencies, calendars and resources a PlanCollectionDiff (added and removed IDs and changed { id, fields }); assignments (PlanAssignmentDiff: added, removed, changed { taskId, resourceId, fields } matched by task and resource, with units defaulting to 1, and taskIds with any assignment difference). Fields are compared structurally, so any field, including fields added in later versions, is reported by name
result.statePlanScheduleState per side: scheduled with finish, cycle with cycles, or infeasible with taskId, constraints, dependencyIds and deadline (true when the project deadline is one of the conflicts)
result.comparableTrue when both sides are scheduled. Otherwise tasks lists only edited tasks, consequenceTaskIds is empty and no violation is gained or lost
result.finish{ current?, candidate?, shift? }: the final completion of each scheduled side and candidate - current
result.tasksPlanTaskComparison for each edited task and each task whose dates, critical flag or state differ, current input order first, then added tasks: edited, input (added, removed, changed or unchanged; changed fields or assignments make changed), fields, assignmentsChanged, current and candidate (PlanTaskSide: scheduled with start, end, critical and summary or manual flags, or inactive, absent or unscheduled), startShift and finishShift when both are scheduled, critical (gained or lost), resourceIds per side and reasons
result.editedTaskIds, result.consequenceTaskIdsThe edited tasks, and the tasks whose own input is unchanged but whose result differs
result.criticalDependenciesgained and lost IDs of criticalDependencyIds
result.violationsPlanViolations per scheduled side (current, candidate) and gained and lost ones: deadline (task, due time, finish), manual-conflict (task, dependency) and leveling-unresolved (task), matched by code, task and dependency
result.overloadPlanResourceOverload for every resource of either plan with load: current and candidate cumulative overload (the sum over the resource's segments of overload * (end - start), in the caller's capacity units times time units; undefined on a side without a schedule or without that resource) and change. Values of different resources are never added

reasons holds each side's own reasons of the task from that side's explain trace (present when that side has a trace and the task is scheduled there). They explain why the task got its dates in that plan, not which change caused a difference; comparePlans never names a single cause.

The exported types are PlanComparisonTask, PlanComparisonInput, PlanScenario, PlanScheduleState, PlanTaskSide, PlanFieldChange, PlanCollectionDiff, PlanAssignmentChange, PlanAssignmentDiff, PlanInputDiff, PlanViolation, PlanTaskComparison, PlanResourceOverload, PlanResultDiff, PlanComparison, PlanComparisonTargetOptions and PlanComparisonTargets.

MIT ライセンスで公開しています。