@teamkeel/solver 0.0.0-stage → 0.509.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.
Files changed (50) hide show
  1. package/dist/index.cjs +6878 -0
  2. package/dist/index.d.cts +9 -0
  3. package/dist/index.d.ts +9 -0
  4. package/dist/index.js +6850 -0
  5. package/dist/internal.cjs +17244 -0
  6. package/dist/internal.d.cts +1275 -0
  7. package/dist/internal.d.ts +1275 -0
  8. package/dist/internal.js +17164 -0
  9. package/dist/layout-ZQ45Tlkb.d.cts +2111 -0
  10. package/dist/layout-efr1Ke_2.d.ts +2111 -0
  11. package/dist/layout.cjs +19 -0
  12. package/dist/layout.d.cts +2 -0
  13. package/dist/layout.d.ts +2 -0
  14. package/dist/layout.js +1 -0
  15. package/dist/record-results-BWnJIpkK.d.ts +222 -0
  16. package/dist/record-results-DPczGZWH.d.cts +222 -0
  17. package/dist/types-DIFPlxBZ.d.cts +1865 -0
  18. package/dist/types-DIFPlxBZ.d.ts +1865 -0
  19. package/fixtures/operation/bakery/operation.json +350 -0
  20. package/fixtures/operation/bakery/plan.json +872 -0
  21. package/fixtures/operation/bakery/readback.json +114 -0
  22. package/fixtures/operation/bakery/score.json +1520 -0
  23. package/fixtures/operation/bakery/timeline.json +2376 -0
  24. package/fixtures/operation/clinic/operation.json +223 -0
  25. package/fixtures/operation/clinic/plan.json +383 -0
  26. package/fixtures/operation/clinic/readback.json +83 -0
  27. package/fixtures/operation/clinic/score.json +1305 -0
  28. package/fixtures/operation/clinic/timeline.json +2283 -0
  29. package/fixtures/operation/field-service/operation.json +194 -0
  30. package/fixtures/operation/field-service/plan.json +172 -0
  31. package/fixtures/operation/field-service/readback.json +73 -0
  32. package/fixtures/operation/field-service/score.json +585 -0
  33. package/fixtures/operation/field-service/timeline.json +661 -0
  34. package/fixtures/operation/filling/operation.json +245 -0
  35. package/fixtures/operation/filling/plan.json +525 -0
  36. package/fixtures/operation/filling/readback.json +87 -0
  37. package/fixtures/operation/filling/score.json +756 -0
  38. package/fixtures/operation/filling/timeline.json +1322 -0
  39. package/fixtures/operation/shop/operation.json +320 -0
  40. package/fixtures/operation/shop/plan.json +664 -0
  41. package/fixtures/operation/shop/readback.json +130 -0
  42. package/fixtures/operation/shop/score.json +1106 -0
  43. package/fixtures/operation/shop/timeline.json +2734 -0
  44. package/fixtures/operation/warehouse-day/operation.json +517 -0
  45. package/fixtures/operation/warehouse-day/plan.json +477 -0
  46. package/fixtures/operation/warehouse-day/readback.json +207 -0
  47. package/fixtures/operation/warehouse-day/score.json +979 -0
  48. package/fixtures/operation/warehouse-day/timeline.json +1420 -0
  49. package/package.json +63 -4
  50. package/README.md +0 -3
@@ -0,0 +1,1275 @@
1
+ import { L as LitRef, I as Ir, a as Id, C, N, R as RuleRow, b as Rule$1, G as Goal$1, K as KpiDisplay, c as Kpi$1, d as Item, e as Changeover$1, f as Note, D as Decision, S as SetItem, P as ProcessStep, g as StructureGroup, h as Clock, i as ResourceKind, j as Producer, M as ModelRecord, E as EngineResult, O as OperationDoc, k as RunStatus, l as RunReason, m as ServiceSpan, n as EdgeRef, V as Values02, o as Declared, F as Flow, p as DocumentIssue, T as Timeline } from './layout-efr1Ke_2.js';
2
+ export { B as BAND_KINDS, q as BAR_KINDS, r as CAUSE_KINDS, s as EQUIPMENT_KINDS, t as EngineHost, u as Global, v as GoalAnchor, H as HeldDecision, w as ItemFact, x as LATE_AGAINST, y as LEVER_KINDS, z as MARK_KINDS, A as ModeOption, J as NounKind, Q as OPERATION_SCHEMA, U as Process, W as READBACK_SCHEMA, X as Service, Y as SpanItem, Z as SpanValue, _ as TIMELINE_SCHEMA, $ as TimedDecision, a0 as Usage, a1 as decisionValues, a2 as evalC, a3 as evalEnv, a4 as evalN, a5 as operationJsonSchema, a6 as overlaps, a7 as readBackDoc, a8 as readBackJsonSchema, a9 as rowAmount, aa as rowApplies, ab as timelineJsonSchema, ac as timelineJsonSchema0, ad as validateOperationShape, ae as validateTimelineShape } from './layout-efr1Ke_2.js';
3
+ import { B as BuildIssue, S as SolveResult, C as Ctx$1, A as ApplyContext } from './record-results-BWnJIpkK.js';
4
+ import { w as ReadBack, x as Printed, t as IrIssue } from './types-DIFPlxBZ.js';
5
+ import 'kysely';
6
+
7
+ /** A construct that can appear in an IR 0.2 build. */
8
+ type ConstructId = "flows" | "service" | "usage" | "vessels" | "modes" | "goals";
9
+ interface ConstructInfo {
10
+ id: ConstructId;
11
+ /** What it is called in messages: "Compiling <label> is not built yet". */
12
+ label: string;
13
+ /** The spec section that defines it. */
14
+ section: string;
15
+ /** The slice-2 plan that builds it. */
16
+ plan: string;
17
+ }
18
+ declare const CONSTRUCTS: readonly ConstructInfo[];
19
+ declare function constructInfo(id: ConstructId): ConstructInfo;
20
+ /** The construct each 0.2 literal belongs to. */
21
+ declare const LIT_CONSTRUCT: Record<Extract<LitRef["kind"], "mode" | "first" | "last">, ConstructId>;
22
+ interface ConstructUse {
23
+ id: ConstructId;
24
+ /** JSON Pointer of the construct's first use. */
25
+ path: string;
26
+ }
27
+ /**
28
+ * The constructs `ir` uses, each once, in `CONSTRUCTS` order, with the pointer of its first use.
29
+ * Scan order (which decides "first"): the 0.2 collections, decisions, rules, goals,
30
+ * then trees (`walkIrTrees`). An empty collection is not a use.
31
+ */
32
+ declare function constructsUsed(ir: Ir): ConstructUse[];
33
+
34
+ /** A data row the builder can name: an `id`, and a `name` it shows when there is no label callback. */
35
+ interface Row {
36
+ readonly id: string;
37
+ readonly name?: string;
38
+ }
39
+
40
+ type TimeLike = Date | string;
41
+ type DurationLike = number | `${number}${"s" | "m" | "h" | "d"}`;
42
+ declare const PLAIN_MS: {
43
+ readonly second: 1000;
44
+ readonly minute: 60000;
45
+ readonly hour: 3600000;
46
+ readonly day: 86400000;
47
+ };
48
+ type PlainUnit = keyof typeof PLAIN_MS;
49
+
50
+ /** A length: a number of the clock's plain unit (minutes by default), `"90m"`, or one per item. */
51
+ type LengthLimit<T extends Row> = DurationLike | ((item: T) => DurationLike);
52
+
53
+ /** What trees need at `finish`. */
54
+ interface Ctx {
55
+ /** The decision key of a step. */
56
+ key(step: object): Id;
57
+ clock: BuildClock;
58
+ /** The authored rule whose rows are being written, if any. */
59
+ rule: Id | null;
60
+ /** A rule had a limit that fell between clock units and was rounded. */
61
+ limitRounded(rule: Id): void;
62
+ }
63
+ /** Something with items: a process. */
64
+ interface ItemsOwner<T extends Row> {
65
+ readonly item: string;
66
+ readonly items: readonly T[];
67
+ /** item id → label */
68
+ readonly labels: ReadonlyMap<Id, string>;
69
+ }
70
+ /** `time` counts clock units from the clock's start; `duration` is a length in clock units. */
71
+ type ValueKind = "time" | "duration" | "number";
72
+ /** A number per item: a stage's start or end. */
73
+ declare class EachNum<T extends Row> {
74
+ readonly owner: ItemsOwner<T>;
75
+ readonly kind: ValueKind;
76
+ readonly term: (ctx: Ctx, item: T) => N;
77
+ constructor(owner: ItemsOwner<T>, kind: ValueKind, term: (ctx: Ctx, item: T) => N);
78
+ /** Holds when the value is at or before `limit(item)`; broken by the units after it. */
79
+ atOrBefore(limit: (item: T) => TimeLike): EachCond<T>;
80
+ /** Holds when the value is at or after `limit(item)`; broken by the units before it. */
81
+ atOrAfter(limit: (item: T) => TimeLike): EachCond<T>;
82
+ /** The largest value over the items; 0 when there are none. */
83
+ max(): Num;
84
+ /** The smallest value over the items; 0 when there are none. */
85
+ min(): Num;
86
+ /** This value less `other`, per item: `fill.start.minus(mix.end)` is the wait between them. */
87
+ get minus(): (b: EachNum<T>) => EachNum<T>;
88
+ /** Holds when this length is at most `limit` (a length, or one per item); broken by the units over it. */
89
+ get atMost(): (limit: LengthLimit<T>) => EachCond<T>;
90
+ /** Holds when this length is at least `limit`; broken by the units short of it. */
91
+ get atLeast(): (limit: LengthLimit<T>) => EachCond<T>;
92
+ /** How far this length runs past `limit`, per item; 0 when it doesn't. */
93
+ get overBy(): (limit: LengthLimit<T>) => EachNum<T>;
94
+ /** The total over the items: one value for a goal or a KPI. */
95
+ get sum(): () => Num;
96
+ }
97
+ /** A condition per item: a rule's rows. `measures` is `time` when a break is counted in clock units. */
98
+ declare class EachCond<T extends Row> {
99
+ readonly owner: ItemsOwner<T>;
100
+ readonly measures: "time" | null;
101
+ readonly row: (ctx: Ctx, item: T) => C;
102
+ /** One row for the whole model, without an item reference. */
103
+ readonly global: boolean;
104
+ constructor(owner: ItemsOwner<T>, measures: "time" | null, row: (ctx: Ctx, item: T) => C,
105
+ /** One row for the whole model, without an item reference. */
106
+ global?: boolean);
107
+ /** Spec §2.3 addition 4: how many items break this condition, as one value (a late count). */
108
+ get countBroken(): () => Num;
109
+ }
110
+ /** One number over the whole plan: a goal's or a KPI's value. */
111
+ declare class Num {
112
+ readonly kind: ValueKind;
113
+ readonly tree: (ctx: Ctx) => N;
114
+ constructor(kind: ValueKind, tree: (ctx: Ctx) => N);
115
+ }
116
+
117
+ /**
118
+ * How far from its own level's best the goal may end up. For a time or a length: a length, as
119
+ * `"30m"`, `{ minutes: 30 }` or a plain number of the clock's plain unit. For a number: a number
120
+ * in the goal's unit, or `{ [unit]: n }` naming it. When the goal has `display`, `{ [display.unit]: n }`
121
+ * is in the display unit and is multiplied by `display.divideBy`.
122
+ */
123
+ type WithinOption = DurationLike | Record<string, number>;
124
+ /** Show the goal as `value / divideBy` in `unit`. */
125
+ type DisplayOption = {
126
+ divideBy: number;
127
+ unit: string;
128
+ };
129
+ /** `.hold(value, opts)`: a goal held after its level at the value it had there, never optimised. */
130
+ interface HoldOptions {
131
+ /** 1 is most important. @default 1 */
132
+ priority?: number;
133
+ /**
134
+ * Which way is worse. `"minimize"` holds the value at or below what its level reached,
135
+ * `"maximize"` at or above. @default "minimize"
136
+ */
137
+ direction?: "minimize" | "maximize";
138
+ unit?: string;
139
+ /**
140
+ * §5.6: how far past its level's value the goal may end up, in the same units as a goal's
141
+ * `within`. @default 0, held at the value exactly
142
+ */
143
+ within?: WithinOption;
144
+ }
145
+
146
+ type Detail$1 = NonNullable<RuleRow["detail"]>;
147
+ interface HardOptions<X> {
148
+ /** The detail a broken row shows. @default `{ <item>: <item's label> }` */
149
+ explain?: (x: X) => Detail$1;
150
+ /** What a broken row's amount counts. @default the clock's unit for time checks */
151
+ unit?: string;
152
+ }
153
+ interface SoftOptions<X> extends HardOptions<X> {
154
+ /** 1 is most important. 0 is the level closing and deadlines bend at, ahead of every goal. @default 1 */
155
+ priority?: number;
156
+ /**
157
+ * What the broken items do, as the words after a count: `finish late` makes the score say
158
+ * "2 of 8 jobs finish late (40 minutes in total)". Write it for a plural subject, as a plain
159
+ * present-tense phrase: for a count of one the score says "1 of 8 jobs finishes late".
160
+ * @default the rule's own sentence
161
+ */
162
+ summary?: string;
163
+ }
164
+ interface GoalOptions {
165
+ /** @default 1 */
166
+ weight?: number;
167
+ /** 1 is most important. @default 1 */
168
+ priority?: number;
169
+ unit?: string;
170
+ /** §5.6: how far from its level's best the goal may be. */
171
+ within?: WithinOption;
172
+ /** Show the goal as `value / divideBy` in `unit`. */
173
+ display?: DisplayOption;
174
+ }
175
+ interface KpiOptions {
176
+ /** @default `clock` for a time, `minutes` for a length, `quantity` otherwise */
177
+ display?: KpiDisplay;
178
+ unit?: string;
179
+ }
180
+ type Check = EachCond<any> | Changeover<any, any, any>;
181
+ declare class Rule {
182
+ readonly id: string;
183
+ readonly says: string;
184
+ readonly hardness: "hard" | "soft";
185
+ readonly weight: number | null;
186
+ readonly priority: number | null;
187
+ readonly check: Check;
188
+ readonly opts: HardOptions<any>;
189
+ constructor(id: string, says: string, hardness: "hard" | "soft", weight: number | null, priority: number | null, check: Check, opts: HardOptions<any>);
190
+ ir(shared: Ctx): Rule$1;
191
+ }
192
+ declare class RuleBuilder {
193
+ readonly b: ModelBuilder;
194
+ readonly id: string;
195
+ readonly says: string;
196
+ constructor(b: ModelBuilder, id: string, says: string);
197
+ /** The rule must hold. A changeover may only be hard. */
198
+ hard<T extends Row>(check: EachCond<T>, opts?: HardOptions<T>): Rule;
199
+ hard<T extends Row, R extends Row>(check: Changeover<T, R, any>, opts?: HardOptions<ChangeoverRow<T, R>>): Rule;
200
+ /** The rule should hold; each unit it is broken by costs `weight` points at its priority. */
201
+ soft<T extends Row>(weight: number, check: EachCond<T>, opts?: SoftOptions<T>): Rule;
202
+ }
203
+ declare class Goal {
204
+ readonly id: string;
205
+ readonly says: string;
206
+ readonly direction: "minimize" | "maximize";
207
+ readonly value: Num;
208
+ readonly opts: GoalOptions;
209
+ constructor(id: string, says: string, direction: "minimize" | "maximize", value: Num, opts: GoalOptions);
210
+ ir(ctx: Ctx): Goal$1;
211
+ }
212
+ declare class GoalBuilder {
213
+ #private;
214
+ readonly b: ModelBuilder;
215
+ readonly id: string;
216
+ readonly says: string;
217
+ constructor(b: ModelBuilder, id: string, says: string);
218
+ minimize(value: Num, opts?: GoalOptions): Goal;
219
+ maximize(value: Num, opts?: GoalOptions): Goal;
220
+ /** §5.6: a goal held at its level's value, never optimised. */
221
+ get hold(): (value: Num, opts?: HoldOptions) => Goal;
222
+ }
223
+ declare class Kpi {
224
+ readonly label: string;
225
+ readonly value: Num;
226
+ readonly opts: KpiOptions;
227
+ constructor(label: string, value: Num, opts: KpiOptions);
228
+ ir(ctx: Ctx, key: string): Kpi$1;
229
+ }
230
+
231
+ /** What a pair with no time in your data means. Missing is never zero. */
232
+ type Missing = {
233
+ use: DurationLike;
234
+ note?: string;
235
+ } | {
236
+ forbid: true;
237
+ note?: string;
238
+ } | "error";
239
+ interface ChangeoverOptions<T extends Row, C extends Row> {
240
+ /** An item's class id: one of `classes`. Items of one class follow each other with no gap. */
241
+ classOf: (item: T) => string;
242
+ /** The classes, with the names text uses. */
243
+ classes: readonly C[];
244
+ /** The gap when class `to` follows class `from`, or `undefined` (or `null`) when your data has none. */
245
+ between: (from: C, to: C) => DurationLike | null | undefined;
246
+ missing: Missing;
247
+ /** The gap before the first item on each resource. Say `0` if there is none. */
248
+ beforeFirst: DurationLike;
249
+ }
250
+ /** One pair a changeover rule checks, as `explain` sees it. `after` is null before the first item. */
251
+ interface ChangeoverRow<T extends Row, R extends Row> {
252
+ on: R;
253
+ after: T | null;
254
+ before: T;
255
+ /** The gap in clock units; null when the pair may never meet. */
256
+ minutes: number | null;
257
+ /** Filled by the `missing` policy. */
258
+ assumed: boolean;
259
+ }
260
+ declare class Changeover<T extends Row, R extends Row, C extends Row> {
261
+ #private;
262
+ readonly stage: Stage<T, R>;
263
+ /** The hard rule that enforces it; set by `.hard(changeover)`. */
264
+ rule: Id | null;
265
+ readonly classes: Item[];
266
+ readonly classOf: Record<Id, Id>;
267
+ readonly table: Record<Id, Record<Id, number | null>>;
268
+ readonly beforeFirst: number;
269
+ readonly assumed: {
270
+ from: Id;
271
+ to: Id;
272
+ }[];
273
+ /** Total gap time the plan spends changing over, in clock units. */
274
+ readonly minutes: {
275
+ sum(): Num;
276
+ };
277
+ constructor(stage: Stage<T, R>, opts: ChangeoverOptions<T, C>);
278
+ /** The IR's structural form. Only once a rule uses it. */
279
+ ir(): Changeover$1;
280
+ /** An assumption note per cell the `missing` policy filled. */
281
+ notes(unitName: string): Note[];
282
+ /** The rows of the rule that enforces it: the gap after each arc, or never that arc. */
283
+ rows(ctx: Ctx, explain?: (row: ChangeoverRow<T, R>) => Detail$1): RuleRow[];
284
+ }
285
+
286
+ /** The condition "the mode takes this option": for `only`, an order's `when`, and `.then`. */
287
+ declare class ModeIs {
288
+ readonly mode: Mode<string>;
289
+ readonly option: string;
290
+ /** `cond`, holding only when this option is chosen: `way.is("b").then(prep.end.atOrBefore(…))`. */
291
+ then<T extends Row>(cond: EachCond<T>): EachCond<T>;
292
+ }
293
+ /** A length that depends on the option: give it as a stage's `duration`. */
294
+ declare class ModePick {
295
+ readonly mode: Mode<string>;
296
+ readonly values: Readonly<Record<string, DurationLike>>;
297
+ }
298
+ /** A day-level choice between ways of working. The plan names the chosen option. */
299
+ declare class Mode<O extends string> {
300
+ readonly id: string;
301
+ readonly says: string;
302
+ readonly options: readonly O[];
303
+ /** A length that depends on the option: one entry per option. */
304
+ pick(values: Record<O, DurationLike>): ModePick;
305
+ /** The condition "this option is chosen". */
306
+ is(option: O): ModeIs;
307
+ }
308
+ /** Whether `item` exists: `mode.is(option)` for an item that exists under one option, else `true`. */
309
+ type OnlyOption<T extends Row> = (item: T) => ModeIs | true;
310
+
311
+ /**
312
+ * When an item's set-up may start if the item is first on its resource: a time (or clock units),
313
+ * a value from the plan such as `step.end.max()`, or one item's start or end on a step, plus a lead.
314
+ */
315
+ type NotBefore = TimeLike | number | Num | {
316
+ after: EachNum<any>;
317
+ item: string;
318
+ plus?: DurationLike;
319
+ };
320
+ interface ServiceOptions<T extends Row, R extends Row, K extends Row> {
321
+ /** An item's class id: one of `classes`. */
322
+ classOf: (item: T) => string;
323
+ /** The classes, with the names text uses. */
324
+ classes: readonly K[];
325
+ /**
326
+ * The time between consecutive items of these classes on resource `on`: 0 for no span, `null`
327
+ * when `to` may never follow `from` there, `undefined` when the data has none (then `missing`
328
+ * decides).
329
+ */
330
+ changeover: (from: K, to: K, on: R) => DurationLike | null | undefined;
331
+ /** A span before the first item on each resource. */
332
+ setup?: {
333
+ minutes: (on: R) => DurationLike;
334
+ /** When the set-up may start, for an item that is first. @default the clock's start */
335
+ notBefore?: (item: T) => NotBefore;
336
+ };
337
+ /** A span after the last item on each resource: an end-of-day clean is a cleandown. */
338
+ cleandown?: {
339
+ minutes: (on: R) => DurationLike;
340
+ };
341
+ /** A first item's set-up time, by item and resource. Exclusive with `setup`. */
342
+ setupBy?: (item: T, on: R) => DurationLike;
343
+ /** A last item's clean-down time, by item and resource. Exclusive with `cleandown`. */
344
+ cleandownBy?: (item: T, on: R) => DurationLike;
345
+ /** What every service span takes of a usage, by the usage's id. One usage at most. */
346
+ uses?: Readonly<Record<string, number>>;
347
+ /**
348
+ * A changeover with time starts the moment the item before it ends, and the resource may then
349
+ * wait, serviced, for the next item. Without it a changeover ends as the next item starts.
350
+ * Set-ups and cleandowns are the same either way. @default false
351
+ */
352
+ eager?: boolean;
353
+ /** What a pair with no time in your data means. @default "error" */
354
+ missing?: Missing;
355
+ /** The generated rule's sentence. @default built from what is declared */
356
+ says?: string;
357
+ }
358
+ /** A step's set-ups, changeovers and cleandowns. Listed in `s.usage`, it counts their share. */
359
+ declare class ServiceSpans<T extends Row = Row> {
360
+ readonly step: Stage<T, any> | Occupies<T, any>;
361
+ readonly uses: Readonly<Record<string, number>>;
362
+ }
363
+
364
+ /** A time on the clock: an instant, or clock units from its start. */
365
+ type At = TimeLike | number;
366
+ interface SupplyOptions {
367
+ /** What is counted, e.g. `person`. */
368
+ unit: string;
369
+ /** From each `at` on, `count` is on hand, until the next step; 0 before the first. */
370
+ steps: readonly {
371
+ at: At;
372
+ count: number;
373
+ }[];
374
+ }
375
+ declare class Supply {
376
+ readonly id: string;
377
+ readonly unit: string;
378
+ readonly steps: readonly {
379
+ at: At;
380
+ count: number;
381
+ }[];
382
+ }
383
+ interface FixedOptions {
384
+ from: At;
385
+ /** How long it lasts. */
386
+ for: DurationLike;
387
+ /** How much it takes while it lasts. */
388
+ uses: number;
389
+ /** Checked against the usage's unit when given. */
390
+ unit?: string;
391
+ }
392
+ /** Work at a fixed time, such as opening up. */
393
+ declare class Fixed {
394
+ readonly id: string;
395
+ readonly opts: FixedOptions;
396
+ }
397
+ interface SpanOptions {
398
+ /** A time (including a time expression), or steps: from the earliest start of their items. */
399
+ from: At | Num | readonly Step[];
400
+ /** Until the latest end of these steps' items, and never before `from`. */
401
+ until: readonly Step[];
402
+ uses: number;
403
+ }
404
+ /** Work that lasts while any of some steps is running (an envelope span). */
405
+ declare class Span {
406
+ readonly id: string;
407
+ readonly says: string;
408
+ readonly opts: SpanOptions;
409
+ }
410
+ /** What each item of a step takes while it runs. */
411
+ declare class StepUsage<T extends Row = Row> {
412
+ readonly step: Stage<T, any> | Occupies<T, any>;
413
+ readonly amount: (item: T) => number;
414
+ }
415
+ type Term = StepUsage<any> | ServiceSpans<any> | Fixed | Span;
416
+ interface UsageOptions {
417
+ under: Supply;
418
+ /** The finest amount: every amount is a whole number of these. @default 1 */
419
+ precision?: number;
420
+ /** @default the supply's unit */
421
+ unit?: string;
422
+ /** The generated rule's sentence. @default built from the ids */
423
+ says?: string;
424
+ }
425
+ declare class Usage {
426
+ readonly id: string;
427
+ readonly terms: readonly Term[];
428
+ readonly under: Supply;
429
+ readonly scale: number;
430
+ readonly unit: string;
431
+ readonly says: string;
432
+ }
433
+
434
+ /** May `item` take `vessel`? Return `true` for yes. */
435
+ type WhereOption<T extends Row, R extends Row> = (item: T, vessel: R) => boolean;
436
+ /** How much of `vessel` `item` fills: a whole number in the author's scaled unit. */
437
+ type FillOption<T extends Row, R extends Row> = (item: T, vessel: R) => number;
438
+ /** Stage id → that stage's length by item and vessel; `fill` is the item's fill there, if given. */
439
+ type DurationsOption<T extends Row, R extends Row> = Record<string, (item: T, vessel: R, fill: number | undefined) => DurationLike>;
440
+ interface InOptions<T extends Row> {
441
+ /** Only these items get a row. */
442
+ for?: (item: T) => boolean;
443
+ }
444
+ /** A hold's vessels, and conditions on which one an item takes. */
445
+ type HeldOn<T extends Row, R extends Row> = Resources<R> & {
446
+ /**
447
+ * Holds when the item takes one of the vessels `pick(item)` lists (of those it may take); an
448
+ * item for which `pick` gives null gets no row. Use it in a rule: `.soft(20, vessel.on.in(…))`.
449
+ */
450
+ in(pick: (item: T) => readonly string[] | null, opts?: InOptions<T>): EachCond<T>;
451
+ };
452
+
453
+ interface ProcessOptions<T extends Row> {
454
+ /** What one item is called; the item set's id and the prefix of step keys, e.g. `batch`. */
455
+ item: string;
456
+ /** The item set's label, e.g. `Batches`. @default the `item` */
457
+ label?: string;
458
+ /** An item's label. @default `row.name`, else `row.id` */
459
+ name?: (row: T) => string;
460
+ }
461
+ interface StageOptions<T extends Row, R extends Row> {
462
+ /** Omit the implicit order after the preceding stage; flows can supply it instead. */
463
+ after?: null;
464
+ /** The resources it runs on; each item takes one. Omit for a stage with no resource. */
465
+ on?: Resources<R>;
466
+ /** How long it takes: a length, or one per item (and resource); §4.7: or a mode's `pick`. */
467
+ duration: DurationLike | ModePick | ((item: T, on: R) => DurationLike | ModePick);
468
+ /** Which resources an item may use. @default all of them */
469
+ where?: (item: T, on: R) => boolean;
470
+ /** @default the id, capitalised */
471
+ label?: string;
472
+ /** §4.7: whether the item exists, as a condition on the chosen modes. */
473
+ only?: OnlyOption<T>;
474
+ }
475
+ interface OccupiesOptions<R extends Row, T extends Row = Row> {
476
+ on: Resources<R>;
477
+ /** The stage whose start takes the resource. */
478
+ from: string;
479
+ /** The stage whose end releases it. */
480
+ until: string;
481
+ /** Held this long after release (a turnaround). @default 0 */
482
+ plus?: DurationLike;
483
+ label?: string;
484
+ /** §4.5: which vessels an item may take. */
485
+ where?: WhereOption<T, R>;
486
+ /** §4.5: how much of a vessel an item fills. */
487
+ fill?: FillOption<T, R>;
488
+ /** §4.5: stage id → the stage's length by item and vessel, when it follows the vessel taken. */
489
+ durations?: DurationsOption<T, R>;
490
+ }
491
+ declare class Process<T extends Row> implements ItemsOwner<T> {
492
+ #private;
493
+ readonly b: ModelBuilder;
494
+ readonly item: string;
495
+ readonly label: string;
496
+ readonly items: readonly T[];
497
+ readonly labels: Map<Id, string>;
498
+ readonly steps: (Stage<T, Row> | Occupies<T, Row>)[];
499
+ constructor(b: ModelBuilder, rows: readonly T[], opts: ProcessOptions<T>);
500
+ /** A timed step. It starts after the stage declared before it ends. */
501
+ stage<R extends Row = Row>(id: string, opts: StageOptions<T, R>): Stage<T, R>;
502
+ /** Hold a resource from `from`'s start to `until`'s end. Both stages must be declared first. */
503
+ occupies<R extends Row>(id: string, opts: OccupiesOptions<R, T>): Occupies<T, R>;
504
+ itemSet(): {
505
+ id: string;
506
+ label: string;
507
+ items: SetItem[];
508
+ };
509
+ irProcess(ctx: Ctx): {
510
+ id: string;
511
+ label: string;
512
+ itemSet: string;
513
+ steps: ProcessStep[];
514
+ };
515
+ decisions(ctx: Ctx): Decision[];
516
+ structure(ctx: Ctx): StructureGroup[];
517
+ /** `one-at-a-time:<resource>` for every resource a step runs on or holds. */
518
+ generatedRules(ctx: Ctx): Rule$1[];
519
+ }
520
+ declare class Stage<T extends Row, R extends Row> {
521
+ readonly process: Process<T>;
522
+ readonly id: string;
523
+ readonly label: string;
524
+ readonly after: Stage<T, Row> | null;
525
+ readonly on: Resources<R> | null;
526
+ /** item → units (no resource) or item → resource → units. */
527
+ readonly duration: Record<Id, number> | Record<Id, Record<Id, number>>;
528
+ readonly rounded: {
529
+ n: number;
530
+ };
531
+ readonly start: EachNum<T>;
532
+ readonly end: EachNum<T>;
533
+ changeoverDecl: Changeover<T, R, Row> | null;
534
+ constructor(process: Process<T>, id: string, opts: StageOptions<T, R>);
535
+ /** §4.3: set-ups, changeovers and cleandowns as spans on the resource. */
536
+ get service(): <K extends Row>(opts: ServiceOptions<T, R, K>) => ServiceSpans<T>;
537
+ /** §4.4: what this stage draws on a supply while it runs. */
538
+ get usage(): (amount: (item: T) => number) => StepUsage<T>;
539
+ /** Sequence-dependent gaps between consecutive items on one resource. Use it in a hard rule. */
540
+ changeover<C extends Row>(opts: ChangeoverOptions<T, C>): Changeover<T, R, C>;
541
+ decision(ctx: Ctx): Decision;
542
+ }
543
+ declare class Occupies<T extends Row, R extends Row> {
544
+ readonly process: Process<T>;
545
+ readonly id: string;
546
+ readonly label: string;
547
+ readonly on: HeldOn<T, R>;
548
+ readonly from: Stage<T, Row>;
549
+ readonly until: Stage<T, Row>;
550
+ readonly plus: number;
551
+ readonly rounded: {
552
+ n: number;
553
+ };
554
+ constructor(process: Process<T>, id: string, opts: OccupiesOptions<R, T>);
555
+ /** §4.3: cleans between holds, as spans on the vessel. */
556
+ get service(): <K extends Row>(opts: ServiceOptions<T, R, K>) => ServiceSpans<T>;
557
+ /** §4.4: what this hold draws on a supply. */
558
+ get usage(): (amount: (item: T) => number) => StepUsage<T>;
559
+ /** §4.5: how much of `vessel` `item` fills. */
560
+ get fillOf(): (item: T, vessel: R) => number;
561
+ decision(ctx: Ctx): Decision;
562
+ }
563
+
564
+ /** One pair: an item id of `from`, and one of `to`. Any other fields are the author's. */
565
+ interface FlowPairRow {
566
+ readonly up: string;
567
+ readonly down: string;
568
+ }
569
+ /** A value for every pair, or one worked out from each pair. */
570
+ type PerPair<P, X> = X | ((pair: P) => X);
571
+ /** §4.1: the held step whose vessel sits between the two steps, with the amount and the rates. */
572
+ interface HoldingOptions<P extends FlowPairRow, R extends Row> {
573
+ /** The hold, from `occupies`. */
574
+ step: Occupies<any, R>;
575
+ /** The held item of each pair; by default `pair.up`. */
576
+ item?: (pair: P) => string;
577
+ /** Amount per clock unit going in, and coming out. */
578
+ upRate: PerPair<P, number>;
579
+ downRate: PerPair<P, number>;
580
+ /** The amount that goes through, a whole number in the author's scaled unit. */
581
+ amount: PerPair<P, number>;
582
+ /** What each vessel holds, in the same unit as `amount`. */
583
+ capacity: (vessel: R) => number;
584
+ }
585
+ interface FlowOptions<P extends FlowPairRow, R extends Row> {
586
+ kind: "after" | "alongside";
587
+ /** A stage whose items the pairs name. */
588
+ from: Stage<any, any>;
589
+ to: Stage<any, any>;
590
+ pairs: readonly P[];
591
+ /** `after`: the least and most wait from the upstream end to the downstream start. */
592
+ atLeast?: PerPair<P, DurationLike>;
593
+ atMost?: PerPair<P, DurationLike>;
594
+ /** `alongside`: the downstream starts at least `lag` after the upstream starts, ends `tail` after it ends. */
595
+ lag?: PerPair<P, DurationLike>;
596
+ tail?: PerPair<P, DurationLike>;
597
+ holding?: HoldingOptions<P, R>;
598
+ }
599
+ /** A declared flow. Its rule is in the build once declared; it is not returned in `rules`. */
600
+ declare class FlowDecl {
601
+ readonly id: string;
602
+ readonly says: string;
603
+ }
604
+
605
+ /** A step of a process: what `decisions` names. */
606
+ type Step = Stage<any, any> | Occupies<any, any>;
607
+ /** What `model` returns. Only returned rules, goals and KPIs are in the build. */
608
+ interface ModelSpec {
609
+ /** Decision names for plans and apply; a step not listed is keyed `<item>.<step>`. */
610
+ decisions?: Record<string, Step>;
611
+ /** Authored rules, in the order views list them. */
612
+ rules?: readonly Rule[];
613
+ goals?: readonly Goal[];
614
+ /** KPIs by the key plans use. */
615
+ kpis?: Record<string, Kpi>;
616
+ }
617
+ /** Resources from one `s.resources` call. */
618
+ interface Resources<R extends Row> {
619
+ readonly group: string;
620
+ readonly rows: readonly R[];
621
+ }
622
+ interface ResourceOptions<R extends Row> {
623
+ /** The group's name, e.g. `lines`; views and generated rules use it. */
624
+ group: string;
625
+ /** The label for a row. @default `row.name`, else `row.id` */
626
+ name?: (row: R) => string;
627
+ /** The glyph family. @default `other`, with a warning */
628
+ kind?: ResourceKind;
629
+ /** Slice 1 supports 1 only. @default 1 */
630
+ capacity?: 1;
631
+ }
632
+ interface ClockOptions {
633
+ /** One clock unit: `1s`, `1m`, `1h` or `1d`. */
634
+ resolution: DurationLike;
635
+ /** IANA zone the plan is shown in. */
636
+ zone: string;
637
+ from: TimeLike;
638
+ to: TimeLike;
639
+ /** What a plain number means in a duration. @default "minute" */
640
+ unit?: PlainUnit;
641
+ }
642
+ interface BuildClock extends Clock {
643
+ plain: PlainUnit;
644
+ /** Clock units from `from`, possibly fractional. */
645
+ at(t: TimeLike, what: string): number;
646
+ /** What one unit is called: `minutes`. */
647
+ unitName: string;
648
+ }
649
+ declare class ModelBuilder {
650
+ #private;
651
+ readonly solverName: string;
652
+ readonly warnings: Note[];
653
+ readonly assumptions: Note[];
654
+ constructor(solverName: string);
655
+ /** The clock every time in the model is measured on. Call it first. */
656
+ clock(opts: ClockOptions): BuildClock;
657
+ /** Declare resources from rows: one resource per row, id from `row.id`. */
658
+ resources<R extends Row>(rows: readonly R[], opts: ResourceOptions<R>): Resources<R>;
659
+ /** Items that move through named steps. Items are sorted by id. */
660
+ process<T extends Row>(rows: readonly T[], opts: ProcessOptions<T>): Process<T>;
661
+ /** A rule: `.hard(check)` or `.soft(weight, check)`. Return it in `rules`. */
662
+ rule(id: string, says: string): RuleBuilder;
663
+ /** A goal: `.minimize(value)` or `.maximize(value)`. Return it in `goals`. */
664
+ goal(id: string, says: string): GoalBuilder;
665
+ /** A value to report. Return it in `kpis` under the key plans use. */
666
+ kpi(label: string, value: Num, opts?: KpiOptions): Kpi;
667
+ get flow(): <P extends FlowPairRow, R extends Row = Row>(id: string, says: string, opts: FlowOptions<P, R>) => FlowDecl;
668
+ get supply(): (id: string, opts: SupplyOptions) => Supply;
669
+ get fixed(): (id: string, opts: FixedOptions) => Fixed;
670
+ get span(): (id: string, says: string, opts: SpanOptions) => Span;
671
+ get usage(): (id: string, terms: readonly Term[], opts: UsageOptions) => Usage;
672
+ get mode(): <const O extends string>(id: string, says: string, options: readonly O[]) => Mode<O>;
673
+ /** Write the build. `spec` is what `model` returned. */
674
+ finish(spec: ModelSpec, producer?: Producer): Ir;
675
+ }
676
+
677
+ /** One loader per named data entry; each gets the caller's context and the solve's params. */
678
+ type Loaders<P, I> = {
679
+ [K in keyof I]: (ctx: unknown, params: P) => Promise<I[K]> | I[K];
680
+ };
681
+ interface SolverDefinition<P, I, D> {
682
+ data: Loaders<P, I>;
683
+ /** Derived facts from the data: pure, synchronous, never policy. @default the data, unchanged */
684
+ prepare?: (data: I, params: P) => D;
685
+ /** Declares decisions, rules, goals and KPIs over the prepared data. */
686
+ model: (s: ModelBuilder, prepared: D) => ModelSpec;
687
+ }
688
+ interface Solver<P, I, D> {
689
+ readonly kind: "solver";
690
+ readonly name: string;
691
+ readonly def: SolverDefinition<P, I, D>;
692
+ }
693
+ /** Define a solver. `name` is what runs and views show, e.g. `FillingDay`. */
694
+ declare function solver<P, I, D = I>(name: string, def: SolverDefinition<P, I, D>): Solver<P, I, D>;
695
+ /**
696
+ * Run every loader the caller did not supply, concurrently. A caller may supply any entry by name,
697
+ * and then its loader does not run.
698
+ */
699
+ declare function loadData<P extends object, I, D>(s: Solver<P, I, D>, ctx: unknown, params: P, supplied?: Partial<I>): Promise<I>;
700
+ /** `prepare`, or the data unchanged. `prepare` must be synchronous. */
701
+ declare function prepareData<P, I, D>(s: Solver<P, I, D>, data: I, params: P): D;
702
+ interface Build {
703
+ ir: Ir | null;
704
+ hash: string | null;
705
+ issues: BuildIssue[];
706
+ }
707
+ /**
708
+ * Run the model over prepared data and return the build. A `ModelError`
709
+ * is a `model-error` issue and no build; any other exception is a bug and
710
+ * is thrown. A build the IR check reports issues on is not returned either: it must never be
711
+ * stored or hashed for reuse.
712
+ */
713
+ declare function buildSolver<P, I, D>(s: Solver<P, I, D>, prepared: D, opts?: {
714
+ producer?: Producer;
715
+ }): Build;
716
+
717
+ interface Problem {
718
+ readonly list: string;
719
+ readonly id: string;
720
+ readonly says: string;
721
+ }
722
+ /** `apply` does not run when there is no plan. Nothing is written; the run records `no plan` and its problems. */
723
+ declare function statusOf(build: OperationBuild, run: EngineResult | null, broken: readonly unknown[]): "planned" | "overfull" | "no plan";
724
+ /** Rows no member can take, which no bending can plan. */
725
+ declare function checkData(record: ModelRecord, data: unknown): Problem[];
726
+
727
+ type Fields = Record<string, unknown>;
728
+ /** A solver written with the operation surface: today's Solver, plus its model's record and its apply. */
729
+ interface OperationSolver extends Solver<Fields, Fields, unknown> {
730
+ readonly operation: {
731
+ readonly record: ModelRecord;
732
+ readonly apply: OperationApply;
733
+ };
734
+ }
735
+ /** What `buildOperation` returns: the build, and what the compiler lowered (`null` with no IR). */
736
+ interface OperationBuild extends Build {
737
+ readonly lowers: OperationDoc["lowers"] | null;
738
+ readonly problems: readonly Problem[];
739
+ }
740
+ declare function isOperationSolver(x: unknown): x is OperationSolver;
741
+ /** `apply` does not run when there is no plan. Nothing is written; the run records `no plan` and its problems. */
742
+ type OperationApply = (result: SolveResult<Ctx$1>, ctx: ApplyContext<unknown, unknown>) => Promise<void>;
743
+
744
+ interface TreeVisitor {
745
+ root?(kind: "numbers" | "conditions", tree: N | C, at: string): void;
746
+ n?(n: N, at: string): void;
747
+ c?(c: C, at: string): void;
748
+ }
749
+ declare function walkIrTrees(ir: Ir, v: TreeVisitor): void;
750
+
751
+ declare const PLAN_SCHEMA = "keel.solver.plan/1";
752
+ interface PlanSpan {
753
+ decision: Id;
754
+ item: Id;
755
+ kind: "work" | "changeover" | "held" | "service";
756
+ /** Service only (plan/1): which kind of service span. */
757
+ service?: ServiceSpan["kind"];
758
+ /** Service only: the item it comes before, absent after the last. */
759
+ before?: Id;
760
+ /** The process step the span belongs to, when the decision is part of a process. */
761
+ step?: Id;
762
+ /** Changeover and service: the item before, absent before the first item. */
763
+ after?: Id;
764
+ /** Changeover only: the rule that enforces it. */
765
+ rule?: Id;
766
+ /**
767
+ * plan/1, spec §2.3 addition 8: on each span a held decision writes, a copy of its
768
+ * `HeldDecision.until`, the edge that releases the hold, so a view can link a hold to the work
769
+ * it is kept for.
770
+ */
771
+ holdsFor?: EdgeRef;
772
+ start: string;
773
+ end: string;
774
+ }
775
+ interface PlanKpi {
776
+ /** ISO instant for `clock`, else a number in `unit`. */
777
+ value: number | string;
778
+ unit: string | null;
779
+ display: KpiDisplay;
780
+ text: string;
781
+ }
782
+ /** plan/1: a service span in ISO times. `after` and `before` as on `PlanSpan`. */
783
+ interface PlanServiceSpan {
784
+ kind: ServiceSpan["kind"];
785
+ after?: Id;
786
+ before?: Id;
787
+ start: string;
788
+ end: string;
789
+ }
790
+ /** plan/1: a usage over time: from `at` on, `used` of the supply's `cap`. */
791
+ interface PlanUsagePoint {
792
+ at: string;
793
+ used: number;
794
+ cap: number;
795
+ }
796
+ /**
797
+ * plan/1, §6.3a: a candidate the step returned but did not keep.
798
+ */
799
+ interface PlanCandidate {
800
+ candidate: number;
801
+ signature: string;
802
+ /** Points per priority level, as the engine counted them. */
803
+ objective: number[];
804
+ score: {
805
+ hardKept: boolean;
806
+ goals: Record<Id, number>;
807
+ };
808
+ }
809
+ interface Plan {
810
+ schema: typeof PLAN_SCHEMA;
811
+ run: string;
812
+ build: string;
813
+ status: RunStatus;
814
+ reason: RunReason;
815
+ clock: {
816
+ from: string;
817
+ to: string;
818
+ zone: string;
819
+ unitMs: number;
820
+ };
821
+ resources: {
822
+ id: Id;
823
+ label: string;
824
+ kind: ResourceKind;
825
+ group: string;
826
+ }[];
827
+ /** Each item set's items, with their `describe` title and facts when the solver gives them. */
828
+ items: Record<Id, SetItem[]>;
829
+ values: Record<Id, Record<Id, {
830
+ on: Id | null;
831
+ start: string;
832
+ end: string;
833
+ }>>;
834
+ /** Every resource, spans in time order. */
835
+ byResource: Record<Id, PlanSpan[]>;
836
+ kpis: Record<Id, PlanKpi>;
837
+ assumptions: Note[];
838
+ warnings: Note[];
839
+ /** mode → chosen option. */
840
+ modes?: Record<Id, Id>;
841
+ /** decision → resource → service spans. */
842
+ service?: Record<Id, Record<Id, PlanServiceSpan[]>>;
843
+ /** usage → points in time order (plan 08). */
844
+ usages?: Record<Id, PlanUsagePoint[]>;
845
+ /** §6.3a: present only when the step returned more than one candidate (plan 11). */
846
+ candidates?: PlanCandidate[];
847
+ }
848
+
849
+ declare const SCORE_SCHEMA = "keel.solver.score/1";
850
+ /** score/1, §4.4: a usage's peak, its slack in each supply window, and the rows it broke (plan 08). */
851
+ interface UsageScore {
852
+ id: Id;
853
+ peak: number;
854
+ slack: {
855
+ from: string;
856
+ to: string;
857
+ slack: number;
858
+ }[];
859
+ broken: Id[];
860
+ }
861
+ /** score/1, §4.1: a flow's broken pairs, by what broke (plan 09). */
862
+ interface FlowScore {
863
+ id: Id;
864
+ /** One entry per pair and row kind that broke, the worst amount for that kind; by pair, then kind. */
865
+ broken: {
866
+ pair: number;
867
+ up: Id;
868
+ down: Id;
869
+ kind: "lag" | "tail" | "holding" | "wait";
870
+ /** How far it broke: clock units for a wait, lag or tail; the flow's scaled amount over capacity for holding. */
871
+ by: number;
872
+ }[];
873
+ }
874
+ type Detail = RuleRow["detail"];
875
+ interface Justification {
876
+ row: Id;
877
+ items: Id[];
878
+ amount: number;
879
+ unit: string | null;
880
+ says: string;
881
+ detail: Detail;
882
+ excused: boolean;
883
+ /** The value the limit was compared with: an ISO instant for a time, else a number; null when none. */
884
+ actual: string | number | null;
885
+ /** Which side of its limit the value fell: past the upper bound, short of the lower; null when the row has no limit. */
886
+ side: "over" | "under" | null;
887
+ }
888
+ interface RuleScore {
889
+ id: Id;
890
+ says: string;
891
+ hardness: "hard" | "soft";
892
+ from: "generated" | "author";
893
+ declared: Declared | null;
894
+ priority: number | null;
895
+ weight: number | null;
896
+ broken: number;
897
+ /** Soft rules: weight × the amounts. Hard rules: null. */
898
+ penalty: number | null;
899
+ justifications: Justification[];
900
+ }
901
+ interface StructureScore {
902
+ id: Id;
903
+ says: string;
904
+ step: Id;
905
+ broken: number;
906
+ /** Up to three broken row ids. */
907
+ examples: Id[];
908
+ }
909
+ interface Part {
910
+ id: Id;
911
+ kind: "rule" | "goal";
912
+ value: number;
913
+ unit: string | null;
914
+ weight: number;
915
+ points: number;
916
+ /** Of this priority's points, rounded to 4 places. */
917
+ share: number;
918
+ }
919
+ interface GoalScore {
920
+ id: Id;
921
+ says: string;
922
+ direction: "minimize" | "maximize";
923
+ value: number;
924
+ unit: string | null;
925
+ weight: number;
926
+ priority: number;
927
+ points: number;
928
+ /**
929
+ * score/1, §5.6. `anchor` is the goal's value in the plan its own level returned, and `proven`
930
+ * whether that level was proved; `within` its tolerance (0 for a goal held without one); `held`
931
+ * whether the final value is within `within` of the anchor, and `slack` how far it is from
932
+ * breaking that. `hold` marks a hold-only goal.
933
+ */
934
+ anchor?: number;
935
+ proven?: boolean;
936
+ within?: number;
937
+ held?: boolean;
938
+ slack?: number;
939
+ hold?: true;
940
+ }
941
+ interface ItemRule {
942
+ id: Id;
943
+ kept: boolean;
944
+ /** Σ amounts broken for this item. */
945
+ amount: number;
946
+ /** The rows that applied to this item: plain rows, `imp` rows whose condition held, broken rows. */
947
+ rows: Id[];
948
+ }
949
+ interface Score {
950
+ schema: typeof SCORE_SCHEMA;
951
+ run: string;
952
+ build: string;
953
+ says: string;
954
+ /** `rules` lists broken rules only: a structure-only failure is `kept: false`, `broken > 0`, `rules: []` (see `structure`). */
955
+ hard: {
956
+ kept: boolean;
957
+ broken: number;
958
+ rules: Id[];
959
+ };
960
+ structure: StructureScore[];
961
+ priorities: number[];
962
+ byPriority: {
963
+ priority: number;
964
+ points: number;
965
+ parts: Part[];
966
+ }[];
967
+ rules: RuleScore[];
968
+ goals: GoalScore[];
969
+ byItem: Record<Id, {
970
+ rules: ItemRule[];
971
+ }>;
972
+ usages?: UsageScore[];
973
+ flows?: FlowScore[];
974
+ /** mode → chosen option. */
975
+ modes?: Record<Id, Id>;
976
+ }
977
+ interface ScoreIssue {
978
+ code: "score-mismatch";
979
+ path: string;
980
+ message: string;
981
+ }
982
+ /**
983
+ * The priority levels a build is scored at, ascending: its soft rules' and goals' priorities and
984
+ * nothing else. A construct's objective joins the level of the rule or goal it is of, so the
985
+ * engine's levels must be exactly these (its `objective.byLevel` is compared index by index).
986
+ */
987
+ declare function priorityLevels(ir: Ir): number[];
988
+ /**
989
+ * Score a finished plan. Throws `ScoreError` when the build does not pass `checkIr` or the values
990
+ * leave an item out. `issues` has `score-mismatch` when the engine counted different points.
991
+ */
992
+ declare function scorePlan(ir: Ir, values: Values02, result: Pick<EngineResult, "status" | "reason" | "objective">, opts: {
993
+ run: string;
994
+ }): {
995
+ plan: Plan;
996
+ score: Score;
997
+ issues: ScoreIssue[];
998
+ };
999
+ /**
1000
+ * One check per decision: each item's span lies in the clock, has the set duration on an allowed
1001
+ * resource, and a held span runs from its start edge to its release. `values` must fit the build
1002
+ * (`planOf` refuses values that do not); a missing edge value reads as broken, not as a crash.
1003
+ * 0.2: an item absent under `modes` is skipped (evalEnv checked it is { on: null, 0, 0 }); a
1004
+ * length follows the chosen option (`byMode`) or the vessel taken (`via`); a held item takes a
1005
+ * vessel `where` allows; a held edge reads the referenced item.
1006
+ */
1007
+ declare function decisionChecks(ir: Ir, values: Values02["decisions"], modes?: Record<Id, Id>): StructureScore[];
1008
+
1009
+ type FlowRowKind = FlowScore["broken"][number]["kind"];
1010
+ /** A point in time: item `item` of `decision`'s start or end, plus `add` clock units. */
1011
+ interface FlowSide {
1012
+ decision: Id;
1013
+ item: Id;
1014
+ edge: "start" | "end";
1015
+ add: number;
1016
+ }
1017
+ /** `lo ≤ plus − minus ≤ hi`; a holding row holds only when the held item is on `under.vessel`. */
1018
+ interface FlowRow {
1019
+ pair: number;
1020
+ kind: FlowRowKind;
1021
+ plus: FlowSide;
1022
+ minus: FlowSide;
1023
+ lo: number | null;
1024
+ hi: number | null;
1025
+ under?: {
1026
+ decision: Id;
1027
+ item: Id;
1028
+ vessel: Id;
1029
+ };
1030
+ }
1031
+ /** A flow's rows, pair by pair, in the order `FLOW_ROW_KINDS` gives. */
1032
+ declare function flowRows(f: Flow): FlowRow[];
1033
+
1034
+ /**
1035
+ * A span's `from` as both readers take it (ruling 08-B6): each `max` term on the start of an item
1036
+ * that exists under one option only (`presence`) holds only under that option. An absent item is
1037
+ * pinned to 0–0, so unguarded its start would pull the span's start to 0. The end side needs no
1038
+ * guard: an absent item ends at 0, and a span never ends before its `from`.
1039
+ */
1040
+ declare function presentFrom(ir: Ir, from: N): N;
1041
+
1042
+ type Level = "plan" | "schedule";
1043
+
1044
+ /** The read-back: the sentences, the refusals (the one list `refusals` makes), and the two columns. */
1045
+ declare function readBack(record: ModelRecord, data?: unknown, opts?: {
1046
+ zone?: string;
1047
+ date?: string;
1048
+ }): ReadBack;
1049
+
1050
+ /**
1051
+ * `buildSolver`, plus the `lowers` the compiler wrote. Plan 05's runtime builds operation solvers
1052
+ * with it. `zone` is the project's IANA time zone (UTC when absent) and `date` the day to plan, as
1053
+ * "YYYY-MM-DD" text. A zone or a date that isn't one
1054
+ * comes back as a `model-error` issue, with no IR and no `lowers`. `level` is the level to compile,
1055
+ * the schedule when absent: a one-day build's `lowers` is `{ plan: null, schedule }`.
1056
+ */
1057
+ declare function buildOperation(s: OperationSolver, prepared: unknown, opts?: {
1058
+ producer?: Producer;
1059
+ zone?: string;
1060
+ date?: string;
1061
+ level?: Level;
1062
+ }): OperationBuild;
1063
+
1064
+ declare function solveResult(record: ModelRecord, run: SolveInput): SolveResult<Ctx$1>;
1065
+ /** What nothing has read on `result` so far: the plan's choice, then each decided step in the model's order. */
1066
+ declare function unreadOf(result: SolveResult<Ctx$1>): readonly Unread[];
1067
+
1068
+ /** A decided step, or the plan's choice, that apply never read (spec 4.4): a warning in the preview, never a refusal. */
1069
+ interface Unread {
1070
+ /** The step's about, "processes.job.steps.cut", or the plan's, "plans.fortnight". */
1071
+ readonly about: string;
1072
+ readonly says: string;
1073
+ }
1074
+ /** One solve's run, as `solveResult` reads it: the build, its plan and the prepared data. */
1075
+ interface SolveInput {
1076
+ readonly ir: Ir;
1077
+ readonly plan: Plan;
1078
+ readonly data: unknown;
1079
+ }
1080
+
1081
+ /** What the runtime hands `applyContext`. */
1082
+ interface ApplyRuntime {
1083
+ /** The generated `models`: each Keel model's API by its name in `ctx.models` (`job` for Job). */
1084
+ readonly models: unknown;
1085
+ /** The apply's transaction, as Kysely. */
1086
+ readonly db: unknown;
1087
+ /** The apply's time: the same in its preview and its commit. */
1088
+ readonly now: Date;
1089
+ }
1090
+ declare function applyContext(rt: ApplyRuntime): ApplyContext<unknown, unknown>;
1091
+ /** Runs the author's apply. Its throw goes up: the runtime rolls the transaction back and says what it threw. */
1092
+ declare function runApply(apply: OperationApply, result: SolveResult<Ctx$1>, ctx: ApplyContext<unknown, unknown>): Promise<void>;
1093
+
1094
+ declare function print(record: ModelRecord): Printed;
1095
+
1096
+ interface OperationInput {
1097
+ /** The solver's name, as its root has it. */
1098
+ readonly solver: string;
1099
+ readonly record: ModelRecord;
1100
+ readonly lowers: OperationDoc["lowers"];
1101
+ /** The deploy's check of the read-back (spec 4.3), when it has run. */
1102
+ readonly confirmed?: OperationDoc["confirmed"];
1103
+ }
1104
+ declare function deriveOperation(input: OperationInput): OperationDoc;
1105
+ /**
1106
+ * The operation document's meaning check, after its shape (CARRY "For plan 06"):
1107
+ * - every `about` once;
1108
+ * - a downtime on equipment, a use on equipment or a person, an `until` on a later step of the same
1109
+ * process, a wait's `after` on an earlier one and its `excluding` on one of the same process, a
1110
+ * rule reading nouns;
1111
+ * - /1's links: a rule's or tier's `level` naming a plan or schedule, and the one its about sits
1112
+ * under; a schedule's `plan` naming a plan; a capacity check under its plan's about, on a schedule
1113
+ * that runs that plan's periods;
1114
+ * - each process's steps ordered 1..n, and the document's tones counted from 0;
1115
+ * - every lowered id naming a noun, a process's demand (`<process about>.due` is no noun) or a plan
1116
+ * capacity, and every ranked level (`levels`) naming a priority, after the parts;
1117
+ * - at least one level;
1118
+ * - the hash.
1119
+ * A shape problem comes alone. Otherwise the problems come in this order: each noun's, in the
1120
+ * nouns' order (and within a noun, its `about` first); then the lowers', schedule after plan, each
1121
+ * part in the lowering's order; then the hash, last, as the check of the document as a whole.
1122
+ */
1123
+ declare function checkOperation(doc: unknown): DocumentIssue[];
1124
+
1125
+ /**
1126
+ * The timeline's meaning check, after its shape, against the run's operation document (`null` for a
1127
+ * low-level solver's run, the floor) (CARRY "For plan 06"):
1128
+ * - `operation` is that document's hash, or `null` on the floor;
1129
+ * - every period, row and item id once;
1130
+ * - a row's noun is equipment or a person (on the floor, `null`), and its facts are about a noun or a
1131
+ * demand;
1132
+ * - a band is about a noun;
1133
+ * - a bar never runs backwards, and a hold or a downtime bar has a length (a work bar may have none:
1134
+ * a step can take no time). Its row, period and item are the timeline's. A work bar's `about` is a
1135
+ * step; a downtime bar's is a downtime, or its row's equipment when it stands for several of that
1136
+ * piece's downtimes; and a hold's is a step or a process's `leaves`, as is a hold's `holdsFor`;
1137
+ * - a mark's `about` is its kind's demand of a process, and its item and row are the timeline's;
1138
+ * - an item's process and period are there, and its facts are about a noun or a demand. Each step is
1139
+ * its process's, and on its row it has a work or hold bar, with its work bars there inside it;
1140
+ * - a cause's and a lever's `about` is a noun or a demand, and a cause's refs name an item, a row and
1141
+ * a step;
1142
+ * - the floor, which has no nouns, has no row facts, bands, causes, late, marks or finish.
1143
+ * On a /1 document only (a stored /0 gets none of these):
1144
+ * - a period's fits name a capacity check of a plan, its cuts' cells are its own cells, and its
1145
+ * tight lines are about a noun. A closed period has no cells, no fits and no day;
1146
+ * - the plan level is about a plan, and its latest and spread are open periods;
1147
+ * - the kept round is in the rounds' list, and each round's measures are about a priority;
1148
+ * - an item's fulfils name a cell of the timeline;
1149
+ * - a page is one of its own pages, and its pages name the timeline's periods. On a page a cause's
1150
+ * item may be on another page, so it isn't checked;
1151
+ * - the floor has no plan level, no rounds, no fits and no cuts.
1152
+ * On a /2 document with an operation document, also (a stored /1 gets none of these):
1153
+ * - `plan.capacity` is the `about` of the plan noun's capacity, or `null` where it has none;
1154
+ * - each crew's `about`, when set, names a role noun, and each stock row's `material` a material noun.
1155
+ * `crews`, `stock` and the round plans are empty until 07.
1156
+ * Left unchecked on purpose:
1157
+ * - the floor's IR ids: its bars', steps' and item facts' `about`s, and its items' `process`;
1158
+ * - `items[].broken[].rule`, which may be an IR id (a builder's per-row rule), so without the IR it
1159
+ * can't be told from a typo;
1160
+ * - the round plans' rows, periods and priorities, and `stock`'s periods, which are empty until 07
1161
+ * fills them: 07 adds their checks.
1162
+ * Problems come in document order: the timeline's own order (`periods`, `rows`, `crews`, `bands`,
1163
+ * `bars`, `marks`, `items`, `setsFinish`), and an item's (`id`, `process`, `label`, `period`,
1164
+ * `facts`, `late`, `fulfils`, `steps`, `broken`). A shape problem comes alone.
1165
+ */
1166
+ declare function checkTimeline(doc: unknown, operation: OperationDoc | null): DocumentIssue[];
1167
+
1168
+ interface TimelineBase {
1169
+ /** The run's id. */
1170
+ readonly run: string;
1171
+ readonly ir: Ir;
1172
+ readonly plan: Plan;
1173
+ /** `null` while the run is unscored. */
1174
+ readonly score: Score | null;
1175
+ /** The prepared data the build read. */
1176
+ readonly data: unknown;
1177
+ /**
1178
+ * The run's level (spec 4.3's `level`): which of the document's lowerings the run is read
1179
+ * through. With none, the schedule's, else the plan's: slice 1's every run is a day's schedule.
1180
+ */
1181
+ readonly level?: "plan" | "schedule";
1182
+ }
1183
+ /** An operation solver's run: its document, its model's record and its build's read-back. */
1184
+ interface FromOperation {
1185
+ readonly operation: OperationDoc;
1186
+ /** The model's record: each piece's and process's list, `where` and `amount`, which the operation
1187
+ * document leaves out, so a row's facts and an item's amount can be read from `data`. */
1188
+ readonly record: ModelRecord;
1189
+ /** The build's read-back (spec 4.3's `read_back`): its sentences' `assumed` marks, which causes read. */
1190
+ readonly readBack: Pick<ReadBack, "sentences">;
1191
+ }
1192
+ /** A low-level solver's run (the floor, spec 4.2): no operation document, so no nouns. The timeline
1193
+ * comes from the IR and the plan alone. */
1194
+ interface FromFloor {
1195
+ readonly operation: null;
1196
+ readonly record: null;
1197
+ readonly readBack: null;
1198
+ }
1199
+ declare function deriveTimeline(input: TimelineBase & (FromOperation | FromFloor)): Timeline;
1200
+
1201
+ /** The schema string this package writes. */
1202
+ declare const IR_SCHEMA: "keel.solver.ir/0.2";
1203
+ /** The schema string this package reads. */
1204
+ declare const IR_SCHEMAS_READ: readonly string[];
1205
+
1206
+ /** `sha256:<hex>` of the canonical JSON of `ir` without `producer`. */
1207
+ declare function buildHash(ir: object): string;
1208
+ declare function isBuildHash(s: unknown): s is string;
1209
+
1210
+ /** The one order for ids and keys: UTF-16 code units, the default string sort. */
1211
+ declare const compareId: (a: string, b: string) => number;
1212
+ /** A copy of `ir` in canonical order. Idempotent. Does not touch tree internals. */
1213
+ declare function canonicalizeIr(ir: Ir): Ir;
1214
+
1215
+ interface IrCheck {
1216
+ ok: boolean;
1217
+ /** The document typed as IR when shape and version pass (even if later checks fail). */
1218
+ ir: Ir | null;
1219
+ /** The hash of the document as given, when shape and version pass. */
1220
+ hash: string | null;
1221
+ issues: IrIssue[];
1222
+ }
1223
+ /**
1224
+ * Check a parsed build. Pass `claimedHash` when the build arrived with one. Never throws: every
1225
+ * problem, including a document that cannot be hashed, comes back as an issue.
1226
+ */
1227
+ declare function checkIr(doc: unknown, opts?: {
1228
+ claimedHash?: string;
1229
+ }): IrCheck;
1230
+
1231
+ type Src = "ir" | "plan" | "derived" | "layout" | "missing";
1232
+ interface Fact<T> {
1233
+ v: T;
1234
+ src: Src;
1235
+ /** The rule, group or step it came from. */
1236
+ from?: string;
1237
+ why?: string;
1238
+ }
1239
+
1240
+ /** `scorePlanOn`'s options. `zone` and `date` are an operation solver's, passed to its compiler. */
1241
+ interface ScorePlanOnOptions {
1242
+ readonly zone?: string;
1243
+ readonly date?: string;
1244
+ /** An operation solver's level to build: its schedule when left out (`buildOperation`'s default). */
1245
+ readonly level?: Level;
1246
+ /** The score's run id: the plan's own, unless given. */
1247
+ readonly run?: string;
1248
+ }
1249
+ /**
1250
+ * A plan scored on a solver's build: the build, the plan as that build reads it, and its score.
1251
+ * `issues` is the scorer's, and is empty today: the plan carries no objective, so there are no
1252
+ * engine points for the scorer to find a `score-mismatch` against. The field is here so plan 05's
1253
+ * runtime can carry the scorer's issues without a change of shape.
1254
+ */
1255
+ interface ScoredPlan {
1256
+ readonly build: Build;
1257
+ readonly plan: Plan;
1258
+ readonly score: Score;
1259
+ readonly issues: readonly ScoreIssue[];
1260
+ }
1261
+ /**
1262
+ * `score(args, { plan })` (spec 5.7) over prepared data; for an operation solver, at `opts.level` (its schedule when left out): `plan` scored on `s`'s build of
1263
+ * `prepared`. The plan may come from another model: its values are read by decision key, so it
1264
+ * scores here when its keys are this build's, and its build hash isn't asked to match. Every time
1265
+ * in its values and its service spans is checked first: it must be an ISO instant as a plan writes
1266
+ * one, on the build's clock. Its status and reason are the given plan's, not a claim about this
1267
+ * build: a plan another model proved optimal still says `optimal` here. It carries no objective,
1268
+ * so nothing is checked against an engine's points. Throws `ModelError` when the solver doesn't
1269
+ * build, and `ScoreError` (`values-invalid`) when the plan isn't plan/1's shape, a time isn't an
1270
+ * instant on the clock, or the plan's values don't fit the build. The shape is checked first, before
1271
+ * the build (plan 05b, AM8).
1272
+ */
1273
+ declare function scorePlanOn<P, I, D>(s: Solver<P, I, D>, prepared: D, plan: Plan, opts?: ScorePlanOnOptions): ScoredPlan;
1274
+
1275
+ export { C, CONSTRUCTS, Changeover as ChangeoverBuilder, type ConstructId, Decision, type DurationLike, EachCond, EachNum, EngineResult, type Fact, type FlowSide, Goal$1 as Goal, GoalBuilder, IR_SCHEMA, IR_SCHEMAS_READ, Id, Ir, IrIssue, Kpi$1 as Kpi, LIT_CONSTRUCT, LitRef, ModelBuilder, Goal as ModelGoal, Kpi as ModelKpi, Rule as ModelRule, type ModelSpec, N, Num, Occupies, type PlainUnit, Process as ProcessBuilder, type Row, Rule$1 as Rule, RuleBuilder, RunReason, RunStatus, ServiceSpan, SetItem, type Src, Stage, type TimeLike, Values02, applyContext, buildHash, buildOperation, buildSolver, canonicalizeIr, checkData, checkIr, checkOperation, checkTimeline, compareId, constructInfo, constructsUsed, decisionChecks, deriveOperation, deriveTimeline, flowRows, isBuildHash, isOperationSolver, loadData, prepareData, presentFrom, print, priorityLevels, readBack, runApply, scorePlan, scorePlanOn, solveResult, solver, statusOf, unreadOf, walkIrTrees };