@operato/ops-contract 0.9.35 → 0.9.37

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.
@@ -1,4 +1,5 @@
1
1
  import { type RatedUsage, type UsedUsage } from './rated-usage.ts';
2
+ import type { FoldedOrders, OrderFoldPolicy } from './order-fold.ts';
2
3
  export type ISOTime = string;
3
4
  export interface CanonicalEnvelope<T = unknown> {
4
5
  eventId: string;
@@ -2070,6 +2071,11 @@ export interface OrderState {
2070
2071
  id: string;
2071
2072
  kind: string;
2072
2073
  status: string;
2074
+ /**
2075
+ * **언제 끝났나**(ms) — 종결을 말한 레코드 자신의 시각이다(시뮬은 그 사건의 시각, 미러는 그 레코드의 `eventTime`).
2076
+ * 끝난 오더를 접는 경계가 이 값으로 잰다(ADR-0092). 끝나지 않았거나 모르면 없다 — 모르는 오더는 접지 않는다.
2077
+ */
2078
+ terminalAtMs?: number;
2073
2079
  /**
2074
2080
  * **무엇을 만드나** — GS1 품목 참조(단일 품목 작업지시). 여러 품목이면 `lines[].gtin` 이 말한다.
2075
2081
  *
@@ -2580,6 +2586,11 @@ export interface StateSnapshot {
2580
2586
  assets: AssetState[];
2581
2587
  tasks: TaskState[];
2582
2588
  orders: OrderState[];
2589
+ /**
2590
+ * **접힌 오더** — 끝나서 뜨거운 목록에서 걷힌 오더의 세는 수와 경계(ADR-0092). 아직 접은 것이 없으면 싣지 않는다.
2591
+ * 오더 하나를 찾는 길은 저널이다.
2592
+ */
2593
+ foldedOrders?: FoldedOrders;
2583
2594
  attentions?: Attention[];
2584
2595
  /**
2585
2596
  * **담을 줄 몰라 반영하지 못한 사실** — 종류별 수(관측 구동에서만 나온다).
@@ -3832,6 +3843,11 @@ export interface TwinModelDef {
3832
3843
  * 없으면 커널의 기본(`firstFit`)이다 — 선언하지 않은 현장은 지금까지와 같이 돈다.
3833
3844
  */
3834
3845
  allocationPolicy?: AllocationPolicyName;
3846
+ /**
3847
+ * **끝난 오더를 언제 접나** — 종결 뒤 시간(`afterMs`)과 뜨거운 종결 오더 건수(`maxTerminal`). 없는 칸은 커널의 기본
3848
+ * (24시간 · 1,000건, §`ORDER_FOLD_DEFAULT`). 0 · 무한은 거절한다 — 접지 않는 선언은 받지 않는다(ADR-0092).
3849
+ */
3850
+ orderFold?: Partial<OrderFoldPolicy>;
3835
3851
  /** parallelism = 동시 처리 수(LocationState.parallelism 참조). capacity 는 저장 용량. */
3836
3852
  locations: (EffectivePeriod & {
3837
3853
  id: string;
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export * from './domain-definition.ts';
6
6
  export * from './ems-profile.ts';
7
7
  export * from './energy-ingest.ts';
8
8
  export * from './epcis.ts';
9
+ export * from './order-fold.ts';
9
10
  export * from './face2-adapter.ts';
10
11
  export * from './iso-duration.ts';
11
12
  export * from './master-data.ts';
package/dist/index.js CHANGED
@@ -27,6 +27,7 @@ export * from "./domain-definition.js";
27
27
  export * from "./ems-profile.js";
28
28
  export * from "./energy-ingest.js";
29
29
  export * from "./epcis.js";
30
+ export * from "./order-fold.js";
30
31
  export * from "./face2-adapter.js";
31
32
  export * from "./iso-duration.js";
32
33
  export * from "./master-data.js";
@@ -0,0 +1,108 @@
1
+ /** 접는 경계 — 커널이 선언한다(결정 1). */
2
+ export interface OrderFoldPolicy {
3
+ /** 종결된 지 이만큼 지난 오더를 접는다(ms). */
4
+ afterMs: number;
5
+ /** 뜨거운 종결 오더가 이보다 많으면 오래된 것부터 접는다. */
6
+ maxTerminal: number;
7
+ }
8
+ /** 시간 칸의 크기 — 정시 단위다(ADR-0092 결정 2 보탬). `afterMs` 는 이것의 배수여야 한다. */
9
+ export declare const ORDER_FOLD_HOUR_MS: number;
10
+ /** 기본 경계 — 24시간 · 1,000건(ADR-0092 결정 1). 시간만 쓰면 바쁜 현장이 묶이지 않고, 건수만 쓰면 한가한 현장의 어제가 사라진다. */
11
+ export declare const ORDER_FOLD_DEFAULT: OrderFoldPolicy;
12
+ /**
13
+ * 인스턴스가 선언한 경계를 읽는다 — 없는 칸은 기본값, **0 · 음수 · 무한 · 숫자 아님은 거절**한다.
14
+ *
15
+ * 접지 않는 선언은 오늘 상태(끝난 오더가 끝없이 쌓이는 것)로 돌아가는 것이라 받지 않는다(판정 조건 2). 거절은 이유를
16
+ * 말한다 — 조용히 기본값으로 바꾸면 선언한 사람은 자기 값이 쓰이는 줄 안다.
17
+ */
18
+ export declare function orderFoldPolicyOf(declared?: Partial<OrderFoldPolicy> | null): {
19
+ policy: OrderFoldPolicy;
20
+ } | {
21
+ error: string;
22
+ };
23
+ /** 접는 판정이 읽는 오더의 칸 — 두 구동의 오더 모양이 달라도 이것만 있으면 된다. */
24
+ export interface FoldableOrderView {
25
+ id: string;
26
+ kind?: string;
27
+ status?: string;
28
+ held?: boolean;
29
+ requested?: number;
30
+ fulfilled?: number;
31
+ /** 종결된 시각(ms) — 종결을 말한 레코드 자신의 시각이다. 모르면 없다. */
32
+ terminalAtMs?: number;
33
+ }
34
+ /**
35
+ * **접힌 쪽** — 오더 줄은 들지 않고 세는 수와 경계만 든다(결정 2). 체크포인트와 씨앗에 함께 실린다.
36
+ */
37
+ export interface FoldedOrders {
38
+ /** 종류(`kind`, 없으면 빈 문자열) × 종결 상태(`status`) → 건수. */
39
+ counts: Record<string, Record<string, number>>;
40
+ /** 접힌 오더 가운데 가장 늦은 종결 시각(ms). 이보다 이른 종결 레코드는 줄을 세우지 않는다. 아직 접은 것이 없으면 null. */
41
+ boundaryMs: number | null;
42
+ /**
43
+ * **시간 칸** — 종결 시각의 정시(절대 시각 ms 를 문자열로) → 종류 × 종결 상태 → 건수(ADR-0092 결정 2 보탬).
44
+ *
45
+ * 접힌 쪽이 시각 없는 누적만 들면 「최근 T 안에 끝난 수」를 낼 수 없다 — 건수 경계(N)가 먼저 걸리는 바쁜 현장에서
46
+ * 뜨거운 줄로 세면 칩이 N 에서 멈춘다. 칸은 창 안의 것만 들고 창 밖 칸은 접을 때 버린다(칸 수 ≤ T/1h + 1).
47
+ * 종결 시각을 모르는 오더는 칸에 들지 않는다(세는 수 `counts` 에만 든다).
48
+ */
49
+ hours?: Record<string, Record<string, Record<string, number>>>;
50
+ }
51
+ export declare function emptyFoldedOrders(): FoldedOrders;
52
+ /** 접힌 오더의 총수 — 서랍의 「끝난 오더 N건」이 읽는다. */
53
+ export declare function foldedOrderCount(folded: FoldedOrders | null | undefined): number;
54
+ /**
55
+ * **이번에 접을 오더** — id 목록을 돌려준다(순서는 오래된 종결부터).
56
+ *
57
+ * · 열린 오더는 접지 않는다(`isOrderTerminal` 한 곳이 판정한다).
58
+ * · 보류(`held`)된 오더는 끝났어도 접지 않는다 — 제어판이 재개하려고 들고 있다.
59
+ * · 종결 시각을 모르는 오더는 접지 않는다 — 언제 끝났는지 지어내지 않는다. 두 구동은 종결을 볼 때 시각을 적는다.
60
+ * · 시간: 종결된 지 `afterMs` 가 지났으면 접는다.
61
+ * · 건수: 그러고도 뜨거운 종결 오더가 `maxTerminal` 보다 많으면 오래된 것부터 더 접는다.
62
+ */
63
+ export declare function planOrderFold(orders: readonly FoldableOrderView[], nowMs: number, policy?: OrderFoldPolicy): string[];
64
+ /** 접은 오더를 세는 수에 더한다 — 새 값을 돌려준다(들어온 것을 바꾸지 않는다). */
65
+ export declare function foldOrdersInto(folded: FoldedOrders | null | undefined, orders: readonly FoldableOrderView[]): FoldedOrders;
66
+ /**
67
+ * **뜨거운 줄이 없는 오더의 레코드가 새 줄을 세우나.**
68
+ *
69
+ * 폴링 원본은 같은 종결을 다시 보낸다. 접힌 오더의 종결이 다시 오면 줄이 다시 서고 다음 경계에서 또 접혀 세는 수가 두 번
70
+ * 는다. 그래서 **종결 레코드이고, 그 레코드 자신의 시각이 경계보다 이르면** 줄을 세우지 않는다(결정 2).
71
+ *
72
+ * 비교하는 시각은 레코드의 `eventTime` 이다 — 도착 시각으로 재면 늦게 온 정당한 종결이 접힌 것으로 오인된다(판정 조건 1).
73
+ * 종결이 아닌 레코드(재개)는 새 뜨거운 줄이다 — 드물고 맞는 거동이라 막지 않는다. 이미 뜨거운 줄이 있는 오더의 레코드는
74
+ * 이 판정을 지나지 않는다(그것은 그 줄의 갱신이다).
75
+ */
76
+ export declare function standsNewOrderRow(record: {
77
+ status?: string;
78
+ requested?: number;
79
+ fulfilled?: number;
80
+ }, eventTimeMs: number | undefined, folded: FoldedOrders | null | undefined): boolean;
81
+ /** 그 시각이 든 정시(ms) — 칸의 열쇠는 절대 시각의 정시다(판정 2026-09-24). */
82
+ export declare function hourStartOf(ms: number): number;
83
+ /**
84
+ * **「최근 T」 창의 시작** — `지금이 든 정시 − T`. 창은 `[시작, 지금]` 이고 가장 오래된 칸은 늘 든다.
85
+ *
86
+ * 칸으로 세면 창의 끝이 칸 경계에 맞춰진다. 가장 오래된 칸을 넣을지 뺄지가 방송마다 달라지면, 아무 일도 없는데 칩이
87
+ * 한 칸 분량만큼 오르내리고 사람은 그것을 흐름의 변화로 읽는다(UX 조건). 그래서 규칙을 하나로 둔다: 센 폭은 늘
88
+ * T 이상 T + 1시간 미만이다.
89
+ */
90
+ export declare function finishedWindowStartMs(nowMs: number, policy?: OrderFoldPolicy): number;
91
+ /** 창 밖 칸을 버린다 — 접을 때 부른다. 새 값을 돌려준다. */
92
+ export declare function pruneFoldedHours(folded: FoldedOrders, nowMs: number, policy?: OrderFoldPolicy): FoldedOrders;
93
+ /**
94
+ * **최근 T 안에 끝난 흐름 오더의 수** — 씬 오더 상자의 칩이 읽는다(ADR-0092 결정 2 보탬, 판정 2026-09-24).
95
+ *
96
+ * 판정은 KPI 와 같다: 흐름 오더(`isFlowOrder`)이고 종결(`isOrderTerminal`)이다 — 받는 오더는 들지 않고, 취소도
97
+ * 종결이라 든다(KPI 의 `throughput.orders` 와 같은 수). 뜨거운 줄 가운데 창 안에 끝난 것과, 접힌 칸 가운데 창 안의
98
+ * 것을 더한다. 건수 경계(N)가 먼저 걸려도 이 수는 N 에서 멈추지 않는다.
99
+ *
100
+ * `byStatus` 는 같은 수를 **종결 상태별로** 가른 것이다 — 화면은 완료와 취소를 한 칩에 넣지 않는다(UX 판정 09-24: 반대 방향
101
+ * 둘을 한 수에 넣으면 어느 쪽도 말하지 못한다). 합은 늘 `count` 이고, KPI 의 종결 수와 대어 볼 수 있다.
102
+ */
103
+ export declare function finishedFlowOrdersWithin(hot: readonly FoldableOrderView[], folded: FoldedOrders | null | undefined, nowMs: number, policy?: OrderFoldPolicy): {
104
+ fromMs: number;
105
+ toMs: number;
106
+ count: number;
107
+ byStatus: Record<string, number>;
108
+ };
@@ -0,0 +1,169 @@
1
+ import { isOrderTerminal } from "./contract.js";
2
+ import { isFlowOrder } from "./wms-profile.js";
3
+ /** 시간 칸의 크기 — 정시 단위다(ADR-0092 결정 2 보탬). `afterMs` 는 이것의 배수여야 한다. */
4
+ export const ORDER_FOLD_HOUR_MS = 60 * 60 * 1000;
5
+ /** 기본 경계 — 24시간 · 1,000건(ADR-0092 결정 1). 시간만 쓰면 바쁜 현장이 묶이지 않고, 건수만 쓰면 한가한 현장의 어제가 사라진다. */
6
+ export const ORDER_FOLD_DEFAULT = Object.freeze({ afterMs: 24 * 60 * 60 * 1000, maxTerminal: 1000 });
7
+ /**
8
+ * 인스턴스가 선언한 경계를 읽는다 — 없는 칸은 기본값, **0 · 음수 · 무한 · 숫자 아님은 거절**한다.
9
+ *
10
+ * 접지 않는 선언은 오늘 상태(끝난 오더가 끝없이 쌓이는 것)로 돌아가는 것이라 받지 않는다(판정 조건 2). 거절은 이유를
11
+ * 말한다 — 조용히 기본값으로 바꾸면 선언한 사람은 자기 값이 쓰이는 줄 안다.
12
+ */
13
+ export function orderFoldPolicyOf(declared) {
14
+ const policy = { ...ORDER_FOLD_DEFAULT };
15
+ for (const key of ['afterMs', 'maxTerminal']) {
16
+ const v = declared?.[key];
17
+ if (v === undefined || v === null)
18
+ continue;
19
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) {
20
+ return { error: `order fold ${key} must be a positive finite number, got ${String(v)} — a fold that never folds is refused (ADR-0092)` };
21
+ }
22
+ policy[key] = key === 'maxTerminal' ? Math.floor(v) : v;
23
+ }
24
+ /*
25
+ * **T 는 정시의 배수여야 한다** — 「최근 T 완료」 칩은 시간 칸을 세고, 그 이름은 선언한 T 를 그대로 적는다. 배수가
26
+ * 아니면(예: 90분) 실제로 센 폭과 이름이 달라진다(UX 조건 · 판정 2026-09-24).
27
+ */
28
+ if (policy.afterMs % ORDER_FOLD_HOUR_MS !== 0) {
29
+ return { error: `order fold afterMs must be a whole number of hours, got ${policy.afterMs} ms — the window is counted in hour slots (ADR-0092)` };
30
+ }
31
+ if (policy.maxTerminal < 1)
32
+ return { error: 'order fold maxTerminal must be at least 1 (ADR-0092)' };
33
+ return { policy };
34
+ }
35
+ export function emptyFoldedOrders() {
36
+ return { counts: {}, boundaryMs: null };
37
+ }
38
+ /** 접힌 오더의 총수 — 서랍의 「끝난 오더 N건」이 읽는다. */
39
+ export function foldedOrderCount(folded) {
40
+ let n = 0;
41
+ for (const byStatus of Object.values(folded?.counts ?? {}))
42
+ for (const c of Object.values(byStatus))
43
+ n += c;
44
+ return n;
45
+ }
46
+ /**
47
+ * **이번에 접을 오더** — id 목록을 돌려준다(순서는 오래된 종결부터).
48
+ *
49
+ * · 열린 오더는 접지 않는다(`isOrderTerminal` 한 곳이 판정한다).
50
+ * · 보류(`held`)된 오더는 끝났어도 접지 않는다 — 제어판이 재개하려고 들고 있다.
51
+ * · 종결 시각을 모르는 오더는 접지 않는다 — 언제 끝났는지 지어내지 않는다. 두 구동은 종결을 볼 때 시각을 적는다.
52
+ * · 시간: 종결된 지 `afterMs` 가 지났으면 접는다.
53
+ * · 건수: 그러고도 뜨거운 종결 오더가 `maxTerminal` 보다 많으면 오래된 것부터 더 접는다.
54
+ */
55
+ export function planOrderFold(orders, nowMs, policy = ORDER_FOLD_DEFAULT) {
56
+ const candidates = orders
57
+ .filter(o => isOrderTerminal(o) && !o.held && typeof o.terminalAtMs === 'number' && Number.isFinite(o.terminalAtMs))
58
+ .sort((a, b) => a.terminalAtMs - b.terminalAtMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
59
+ const cutoff = nowMs - policy.afterMs;
60
+ const byTime = candidates.filter(o => o.terminalAtMs <= cutoff);
61
+ const stay = candidates.length - byTime.length;
62
+ const byCount = stay > policy.maxTerminal ? candidates.slice(byTime.length, byTime.length + (stay - policy.maxTerminal)) : [];
63
+ return [...byTime, ...byCount].map(o => o.id);
64
+ }
65
+ /** 접은 오더를 세는 수에 더한다 — 새 값을 돌려준다(들어온 것을 바꾸지 않는다). */
66
+ export function foldOrdersInto(folded, orders) {
67
+ const out = {
68
+ counts: Object.fromEntries(Object.entries(folded?.counts ?? {}).map(([k, v]) => [k, { ...v }])),
69
+ boundaryMs: folded?.boundaryMs ?? null
70
+ };
71
+ const hours = Object.fromEntries(Object.entries(folded?.hours ?? {}).map(([h, byKind]) => [h, Object.fromEntries(Object.entries(byKind).map(([k, v]) => [k, { ...v }]))]));
72
+ for (const o of orders) {
73
+ const kind = String(o.kind ?? '');
74
+ const status = String(o.status ?? '');
75
+ const byStatus = (out.counts[kind] ??= {});
76
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
77
+ if (typeof o.terminalAtMs === 'number' && Number.isFinite(o.terminalAtMs)) {
78
+ out.boundaryMs = out.boundaryMs === null ? o.terminalAtMs : Math.max(out.boundaryMs, o.terminalAtMs);
79
+ const slot = ((hours[String(hourStartOf(o.terminalAtMs))] ??= {})[kind] ??= {});
80
+ slot[status] = (slot[status] ?? 0) + 1;
81
+ }
82
+ }
83
+ if (Object.keys(hours).length)
84
+ out.hours = hours;
85
+ return out;
86
+ }
87
+ /**
88
+ * **뜨거운 줄이 없는 오더의 레코드가 새 줄을 세우나.**
89
+ *
90
+ * 폴링 원본은 같은 종결을 다시 보낸다. 접힌 오더의 종결이 다시 오면 줄이 다시 서고 다음 경계에서 또 접혀 세는 수가 두 번
91
+ * 는다. 그래서 **종결 레코드이고, 그 레코드 자신의 시각이 경계보다 이르면** 줄을 세우지 않는다(결정 2).
92
+ *
93
+ * 비교하는 시각은 레코드의 `eventTime` 이다 — 도착 시각으로 재면 늦게 온 정당한 종결이 접힌 것으로 오인된다(판정 조건 1).
94
+ * 종결이 아닌 레코드(재개)는 새 뜨거운 줄이다 — 드물고 맞는 거동이라 막지 않는다. 이미 뜨거운 줄이 있는 오더의 레코드는
95
+ * 이 판정을 지나지 않는다(그것은 그 줄의 갱신이다).
96
+ */
97
+ export function standsNewOrderRow(record, eventTimeMs, folded) {
98
+ if (!isOrderTerminal(record))
99
+ return true;
100
+ const boundary = folded?.boundaryMs;
101
+ if (boundary === null || boundary === undefined)
102
+ return true;
103
+ if (typeof eventTimeMs !== 'number' || !Number.isFinite(eventTimeMs))
104
+ return true;
105
+ return eventTimeMs > boundary;
106
+ }
107
+ /** 그 시각이 든 정시(ms) — 칸의 열쇠는 절대 시각의 정시다(판정 2026-09-24). */
108
+ export function hourStartOf(ms) {
109
+ return Math.floor(ms / ORDER_FOLD_HOUR_MS) * ORDER_FOLD_HOUR_MS;
110
+ }
111
+ /**
112
+ * **「최근 T」 창의 시작** — `지금이 든 정시 − T`. 창은 `[시작, 지금]` 이고 가장 오래된 칸은 늘 든다.
113
+ *
114
+ * 칸으로 세면 창의 끝이 칸 경계에 맞춰진다. 가장 오래된 칸을 넣을지 뺄지가 방송마다 달라지면, 아무 일도 없는데 칩이
115
+ * 한 칸 분량만큼 오르내리고 사람은 그것을 흐름의 변화로 읽는다(UX 조건). 그래서 규칙을 하나로 둔다: 센 폭은 늘
116
+ * T 이상 T + 1시간 미만이다.
117
+ */
118
+ export function finishedWindowStartMs(nowMs, policy = ORDER_FOLD_DEFAULT) {
119
+ return hourStartOf(nowMs) - policy.afterMs;
120
+ }
121
+ /** 창 밖 칸을 버린다 — 접을 때 부른다. 새 값을 돌려준다. */
122
+ export function pruneFoldedHours(folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
123
+ if (!folded.hours)
124
+ return folded;
125
+ const start = finishedWindowStartMs(nowMs, policy);
126
+ const kept = Object.fromEntries(Object.entries(folded.hours).filter(([h]) => Number(h) >= start));
127
+ const out = { counts: folded.counts, boundaryMs: folded.boundaryMs };
128
+ if (Object.keys(kept).length)
129
+ out.hours = kept;
130
+ return out;
131
+ }
132
+ /**
133
+ * **최근 T 안에 끝난 흐름 오더의 수** — 씬 오더 상자의 칩이 읽는다(ADR-0092 결정 2 보탬, 판정 2026-09-24).
134
+ *
135
+ * 판정은 KPI 와 같다: 흐름 오더(`isFlowOrder`)이고 종결(`isOrderTerminal`)이다 — 받는 오더는 들지 않고, 취소도
136
+ * 종결이라 든다(KPI 의 `throughput.orders` 와 같은 수). 뜨거운 줄 가운데 창 안에 끝난 것과, 접힌 칸 가운데 창 안의
137
+ * 것을 더한다. 건수 경계(N)가 먼저 걸려도 이 수는 N 에서 멈추지 않는다.
138
+ *
139
+ * `byStatus` 는 같은 수를 **종결 상태별로** 가른 것이다 — 화면은 완료와 취소를 한 칩에 넣지 않는다(UX 판정 09-24: 반대 방향
140
+ * 둘을 한 수에 넣으면 어느 쪽도 말하지 못한다). 합은 늘 `count` 이고, KPI 의 종결 수와 대어 볼 수 있다.
141
+ */
142
+ export function finishedFlowOrdersWithin(hot, folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
143
+ const fromMs = finishedWindowStartMs(nowMs, policy);
144
+ let count = 0;
145
+ const byStatus = {};
146
+ const add = (status, n) => {
147
+ const key = String(status ?? '');
148
+ byStatus[key] = (byStatus[key] ?? 0) + n;
149
+ count += n;
150
+ };
151
+ for (const o of hot) {
152
+ if (!isFlowOrder(o) || !isOrderTerminal(o))
153
+ continue;
154
+ const at = o.terminalAtMs;
155
+ if (typeof at === 'number' && at >= fromMs && at <= nowMs)
156
+ add(o.status, 1);
157
+ }
158
+ for (const [h, byKind] of Object.entries(folded?.hours ?? {})) {
159
+ if (Number(h) < fromMs || Number(h) > nowMs)
160
+ continue;
161
+ for (const [kind, statuses] of Object.entries(byKind)) {
162
+ if (!isFlowOrder({ kind }))
163
+ continue;
164
+ for (const [status, c] of Object.entries(statuses))
165
+ add(status, c);
166
+ }
167
+ }
168
+ return { fromMs, toMs: nowMs, count, byStatus };
169
+ }
@@ -66,6 +66,8 @@ __export(index_exports, {
66
66
  OPERATIONAL_ATTENTION_TRANSITIONS: () => OPERATIONAL_ATTENTION_TRANSITIONS,
67
67
  OP_EVENT: () => OP_EVENT,
68
68
  OP_PARAM: () => OP_PARAM,
69
+ ORDER_FOLD_DEFAULT: () => ORDER_FOLD_DEFAULT,
70
+ ORDER_FOLD_HOUR_MS: () => ORDER_FOLD_HOUR_MS,
69
71
  ORDER_TERMINAL_STATUS: () => ORDER_TERMINAL_STATUS,
70
72
  PRIORITY_UNSET: () => PRIORITY_UNSET,
71
73
  READ_BASIS: () => READ_BASIS,
@@ -129,15 +131,21 @@ __export(index_exports, {
129
131
  dueStatusOf: () => dueStatusOf,
130
132
  effectivityAt: () => effectivityAt,
131
133
  electricalUpstreamOf: () => electricalUpstreamOf,
134
+ emptyFoldedOrders: () => emptyFoldedOrders,
132
135
  equipmentClassMembership: () => equipmentClassMembership,
133
136
  erpCapabilityGaps: () => erpCapabilityGaps,
134
137
  expiryFromAttributes: () => expiryFromAttributes,
138
+ finishedFlowOrdersWithin: () => finishedFlowOrdersWithin,
139
+ finishedWindowStartMs: () => finishedWindowStartMs,
140
+ foldOrdersInto: () => foldOrdersInto,
141
+ foldedOrderCount: () => foldedOrderCount,
135
142
  gdtiUri: () => gdtiUri,
136
143
  generationFractionAt: () => generationFractionAt,
137
144
  graiUri: () => graiUri,
138
145
  gs1KeyDigitViolation: () => gs1KeyDigitViolation,
139
146
  hierarchyOf: () => hierarchyOf,
140
147
  homeOf: () => homeOf,
148
+ hourStartOf: () => hourStartOf,
141
149
  identityGroundingOf: () => identityGroundingOf,
142
150
  inWorkCalendar: () => inWorkCalendar,
143
151
  inWorkCalendarAt: () => inWorkCalendarAt,
@@ -211,15 +219,18 @@ __export(index_exports, {
211
219
  operationalIdentityField: () => operationalIdentityField,
212
220
  operationalKindOf: () => operationalKindOf,
213
221
  operationsCapabilityOf: () => operationsCapabilityOf,
222
+ orderFoldPolicyOf: () => orderFoldPolicyOf,
214
223
  outsideLimit: () => outsideLimit,
215
224
  parseEpc: () => parseEpc,
216
225
  parseIsoDuration: () => parseIsoDuration,
217
226
  passThroughReversible: () => passThroughReversible,
218
227
  performanceKey: () => performanceKey,
219
228
  periodFactId: () => periodFactId,
229
+ planOrderFold: () => planOrderFold,
220
230
  priorityRank: () => priorityRank,
221
231
  procedureViolations: () => procedureViolations,
222
232
  propertiesOf: () => propertiesOf,
233
+ pruneFoldedHours: () => pruneFoldedHours,
223
234
  quantityIn: () => quantityIn,
224
235
  ratedUsageOf: () => ratedUsageOf,
225
236
  readBoardAssets: () => readBoardAssets,
@@ -239,6 +250,7 @@ __export(index_exports, {
239
250
  splitFlowOrders: () => splitFlowOrders,
240
251
  splitRelationIds: () => splitRelationIds,
241
252
  ssccUri: () => ssccUri,
253
+ standsNewOrderRow: () => standsNewOrderRow,
242
254
  stateFieldsOf: () => stateFieldsOf,
243
255
  subLotIdOf: () => subLotIdOf,
244
256
  tenseOf: () => tenseOf,
@@ -3348,6 +3360,108 @@ function validateEpcisEvent(e) {
3348
3360
  return v;
3349
3361
  }
3350
3362
 
3363
+ // src/order-fold.ts
3364
+ var ORDER_FOLD_HOUR_MS = 60 * 60 * 1e3;
3365
+ var ORDER_FOLD_DEFAULT = Object.freeze({ afterMs: 24 * 60 * 60 * 1e3, maxTerminal: 1e3 });
3366
+ function orderFoldPolicyOf(declared) {
3367
+ const policy = { ...ORDER_FOLD_DEFAULT };
3368
+ for (const key of ["afterMs", "maxTerminal"]) {
3369
+ const v = declared?.[key];
3370
+ if (v === void 0 || v === null) continue;
3371
+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0) {
3372
+ return { error: `order fold ${key} must be a positive finite number, got ${String(v)} \u2014 a fold that never folds is refused (ADR-0092)` };
3373
+ }
3374
+ policy[key] = key === "maxTerminal" ? Math.floor(v) : v;
3375
+ }
3376
+ if (policy.afterMs % ORDER_FOLD_HOUR_MS !== 0) {
3377
+ return { error: `order fold afterMs must be a whole number of hours, got ${policy.afterMs} ms \u2014 the window is counted in hour slots (ADR-0092)` };
3378
+ }
3379
+ if (policy.maxTerminal < 1) return { error: "order fold maxTerminal must be at least 1 (ADR-0092)" };
3380
+ return { policy };
3381
+ }
3382
+ function emptyFoldedOrders() {
3383
+ return { counts: {}, boundaryMs: null };
3384
+ }
3385
+ function foldedOrderCount(folded) {
3386
+ let n = 0;
3387
+ for (const byStatus of Object.values(folded?.counts ?? {})) for (const c of Object.values(byStatus)) n += c;
3388
+ return n;
3389
+ }
3390
+ function planOrderFold(orders, nowMs, policy = ORDER_FOLD_DEFAULT) {
3391
+ const candidates = orders.filter((o) => isOrderTerminal(o) && !o.held && typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)).sort((a, b) => a.terminalAtMs - b.terminalAtMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
3392
+ const cutoff = nowMs - policy.afterMs;
3393
+ const byTime = candidates.filter((o) => o.terminalAtMs <= cutoff);
3394
+ const stay = candidates.length - byTime.length;
3395
+ const byCount = stay > policy.maxTerminal ? candidates.slice(byTime.length, byTime.length + (stay - policy.maxTerminal)) : [];
3396
+ return [...byTime, ...byCount].map((o) => o.id);
3397
+ }
3398
+ function foldOrdersInto(folded, orders) {
3399
+ const out = {
3400
+ counts: Object.fromEntries(Object.entries(folded?.counts ?? {}).map(([k, v]) => [k, { ...v }])),
3401
+ boundaryMs: folded?.boundaryMs ?? null
3402
+ };
3403
+ const hours = Object.fromEntries(
3404
+ Object.entries(folded?.hours ?? {}).map(([h, byKind]) => [h, Object.fromEntries(Object.entries(byKind).map(([k, v]) => [k, { ...v }]))])
3405
+ );
3406
+ for (const o of orders) {
3407
+ const kind = String(o.kind ?? "");
3408
+ const status = String(o.status ?? "");
3409
+ const byStatus = out.counts[kind] ??= {};
3410
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
3411
+ if (typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)) {
3412
+ out.boundaryMs = out.boundaryMs === null ? o.terminalAtMs : Math.max(out.boundaryMs, o.terminalAtMs);
3413
+ const slot = (hours[String(hourStartOf(o.terminalAtMs))] ??= {})[kind] ??= {};
3414
+ slot[status] = (slot[status] ?? 0) + 1;
3415
+ }
3416
+ }
3417
+ if (Object.keys(hours).length) out.hours = hours;
3418
+ return out;
3419
+ }
3420
+ function standsNewOrderRow(record, eventTimeMs, folded) {
3421
+ if (!isOrderTerminal(record)) return true;
3422
+ const boundary = folded?.boundaryMs;
3423
+ if (boundary === null || boundary === void 0) return true;
3424
+ if (typeof eventTimeMs !== "number" || !Number.isFinite(eventTimeMs)) return true;
3425
+ return eventTimeMs > boundary;
3426
+ }
3427
+ function hourStartOf(ms) {
3428
+ return Math.floor(ms / ORDER_FOLD_HOUR_MS) * ORDER_FOLD_HOUR_MS;
3429
+ }
3430
+ function finishedWindowStartMs(nowMs, policy = ORDER_FOLD_DEFAULT) {
3431
+ return hourStartOf(nowMs) - policy.afterMs;
3432
+ }
3433
+ function pruneFoldedHours(folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
3434
+ if (!folded.hours) return folded;
3435
+ const start = finishedWindowStartMs(nowMs, policy);
3436
+ const kept = Object.fromEntries(Object.entries(folded.hours).filter(([h]) => Number(h) >= start));
3437
+ const out = { counts: folded.counts, boundaryMs: folded.boundaryMs };
3438
+ if (Object.keys(kept).length) out.hours = kept;
3439
+ return out;
3440
+ }
3441
+ function finishedFlowOrdersWithin(hot, folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
3442
+ const fromMs = finishedWindowStartMs(nowMs, policy);
3443
+ let count = 0;
3444
+ const byStatus = {};
3445
+ const add = (status, n) => {
3446
+ const key = String(status ?? "");
3447
+ byStatus[key] = (byStatus[key] ?? 0) + n;
3448
+ count += n;
3449
+ };
3450
+ for (const o of hot) {
3451
+ if (!isFlowOrder(o) || !isOrderTerminal(o)) continue;
3452
+ const at2 = o.terminalAtMs;
3453
+ if (typeof at2 === "number" && at2 >= fromMs && at2 <= nowMs) add(o.status, 1);
3454
+ }
3455
+ for (const [h, byKind] of Object.entries(folded?.hours ?? {})) {
3456
+ if (Number(h) < fromMs || Number(h) > nowMs) continue;
3457
+ for (const [kind, statuses] of Object.entries(byKind)) {
3458
+ if (!isFlowOrder({ kind })) continue;
3459
+ for (const [status, c] of Object.entries(statuses)) add(status, c);
3460
+ }
3461
+ }
3462
+ return { fromMs, toMs: nowMs, count, byStatus };
3463
+ }
3464
+
3351
3465
  // src/face2-adapter.ts
3352
3466
  function isAggregationRecord(record) {
3353
3467
  if (!record || typeof record !== "object") return false;
@@ -4981,6 +5095,8 @@ function nonEmpty(value) {
4981
5095
  OPERATIONAL_ATTENTION_TRANSITIONS,
4982
5096
  OP_EVENT,
4983
5097
  OP_PARAM,
5098
+ ORDER_FOLD_DEFAULT,
5099
+ ORDER_FOLD_HOUR_MS,
4984
5100
  ORDER_TERMINAL_STATUS,
4985
5101
  PRIORITY_UNSET,
4986
5102
  READ_BASIS,
@@ -5044,15 +5160,21 @@ function nonEmpty(value) {
5044
5160
  dueStatusOf,
5045
5161
  effectivityAt,
5046
5162
  electricalUpstreamOf,
5163
+ emptyFoldedOrders,
5047
5164
  equipmentClassMembership,
5048
5165
  erpCapabilityGaps,
5049
5166
  expiryFromAttributes,
5167
+ finishedFlowOrdersWithin,
5168
+ finishedWindowStartMs,
5169
+ foldOrdersInto,
5170
+ foldedOrderCount,
5050
5171
  gdtiUri,
5051
5172
  generationFractionAt,
5052
5173
  graiUri,
5053
5174
  gs1KeyDigitViolation,
5054
5175
  hierarchyOf,
5055
5176
  homeOf,
5177
+ hourStartOf,
5056
5178
  identityGroundingOf,
5057
5179
  inWorkCalendar,
5058
5180
  inWorkCalendarAt,
@@ -5126,15 +5248,18 @@ function nonEmpty(value) {
5126
5248
  operationalIdentityField,
5127
5249
  operationalKindOf,
5128
5250
  operationsCapabilityOf,
5251
+ orderFoldPolicyOf,
5129
5252
  outsideLimit,
5130
5253
  parseEpc,
5131
5254
  parseIsoDuration,
5132
5255
  passThroughReversible,
5133
5256
  performanceKey,
5134
5257
  periodFactId,
5258
+ planOrderFold,
5135
5259
  priorityRank,
5136
5260
  procedureViolations,
5137
5261
  propertiesOf,
5262
+ pruneFoldedHours,
5138
5263
  quantityIn,
5139
5264
  ratedUsageOf,
5140
5265
  readBoardAssets,
@@ -5154,6 +5279,7 @@ function nonEmpty(value) {
5154
5279
  splitFlowOrders,
5155
5280
  splitRelationIds,
5156
5281
  ssccUri,
5282
+ standsNewOrderRow,
5157
5283
  stateFieldsOf,
5158
5284
  subLotIdOf,
5159
5285
  tenseOf,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@operato/ops-contract",
3
- "version": "0.9.35",
3
+ "version": "0.9.37",
4
4
  "description": "Operations domain contract — the standard vocabulary that producers and readers agree on (EPCIS 2.0/GS1, ISA-95, IEC 61850/ISO 50001). Types, guards, validation. No state, no engine.",
5
5
  "type": "module",
6
6
  "main": "./dist-cjs/index.cjs",