@operato/ops-contract 0.9.43 → 0.9.44

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,3 +1,4 @@
1
+ import { isIsoDateTime } from "./epcis.js";
1
2
  /**
2
3
  * Product-neutral evidence for an operational concern that another product's
3
4
  * Twin/AI may analyse. It is not an alarm protocol and never authorises work.
@@ -9,27 +10,106 @@
9
10
  export const OPERATIONAL_ATTENTION_CONTRACT = 'operational.attention.v1';
10
11
  export const OPERATIONAL_ATTENTION_TRANSITIONS = ['opened', 'changed', 'resolved', 'reopened'];
11
12
  export const OPERATIONAL_ATTENTION_IMPACTS = ['medium', 'high'];
12
- export function isOperationalAttentionV1(value) {
13
+ /**
14
+ * A producer-owned, namespaced reason code: `<product>.<code>`, lower case, words joined by `-`
15
+ * (`plant.job-order-past-due`, `yard.late`). The namespace keeps two products' codes from meaning one thing;
16
+ * which product name a sender uses is not checked here.
17
+ */
18
+ export const OPERATIONAL_ATTENTION_KIND_PATTERN = /^[a-z][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/;
19
+ /**
20
+ * Why a value is not an operational.attention.v1 - one line per field, empty when it is one.
21
+ * A receiver keeps these lines with the rejected record, so the sender learns which field to fix.
22
+ */
23
+ export function operationalAttentionErrors(value) {
13
24
  const one = value;
14
- return !!one && typeof one === 'object' &&
15
- one.contract === OPERATIONAL_ATTENTION_CONTRACT &&
16
- nonEmpty(one.domainId) && nonEmpty(one.attentionId) && nonEmpty(one.dedupeKey) &&
17
- nonEmpty(one.kind) && nonEmpty(one.subjectLabel) && nonEmpty(one.observedAt) && nonEmpty(one.evidenceFingerprint) &&
18
- OPERATIONAL_ATTENTION_TRANSITIONS.includes(one.transition) &&
19
- OPERATIONAL_ATTENTION_IMPACTS.includes(one.impact) &&
20
- Array.isArray(one.facts) && one.facts.length > 0 && one.facts.every(isOperationalFactReference);
25
+ if (!one || typeof one !== 'object')
26
+ return ['record: not an object'];
27
+ const errors = [];
28
+ if (one.contract !== OPERATIONAL_ATTENTION_CONTRACT)
29
+ errors.push(`contract: must be ${OPERATIONAL_ATTENTION_CONTRACT}`);
30
+ for (const field of ['domainId', 'attentionId', 'dedupeKey', 'subjectLabel', 'evidenceFingerprint']) {
31
+ if (!nonEmpty(one[field]))
32
+ errors.push(`${field}: required`);
33
+ }
34
+ if (!nonEmpty(one.kind))
35
+ errors.push('kind: required');
36
+ else if (!OPERATIONAL_ATTENTION_KIND_PATTERN.test(one.kind))
37
+ errors.push('kind: must be <product>.<code> in lower case');
38
+ if (!isIsoDateTime(one.observedAt))
39
+ errors.push('observedAt: must be ISO 8601 with seconds and Z or an offset');
40
+ if (!OPERATIONAL_ATTENTION_TRANSITIONS.includes(one.transition)) {
41
+ errors.push(`transition: must be one of ${OPERATIONAL_ATTENTION_TRANSITIONS.join('|')}`);
42
+ }
43
+ if (!OPERATIONAL_ATTENTION_IMPACTS.includes(one.impact)) {
44
+ errors.push(`impact: must be one of ${OPERATIONAL_ATTENTION_IMPACTS.join('|')}`);
45
+ }
46
+ if (!Array.isArray(one.facts) || one.facts.length === 0) {
47
+ errors.push('facts: stable source-fact references are required (at least one {system,type,id})');
48
+ }
49
+ else {
50
+ one.facts.forEach((fact, i) => {
51
+ for (const reason of factReferenceErrors(fact))
52
+ errors.push(`facts[${i}].${reason}`);
53
+ });
54
+ }
55
+ return errors;
56
+ }
57
+ export function isOperationalAttentionV1(value) {
58
+ return operationalAttentionErrors(value).length === 0;
21
59
  }
22
60
  export function assertOperationalAttentionV1(value) {
23
- if (!isOperationalAttentionV1(value)) {
24
- throw new Error('invalid operational.attention.v1: lifecycle fields and stable source-fact references are required');
25
- }
61
+ const errors = operationalAttentionErrors(value);
62
+ if (errors.length)
63
+ throw new Error(`invalid operational.attention.v1: ${errors.join('; ')}`);
26
64
  }
27
- function isOperationalFactReference(value) {
65
+ function factReferenceErrors(value) {
28
66
  const one = value;
29
- return !!one && typeof one === 'object' && nonEmpty(one.system) && nonEmpty(one.type) && nonEmpty(one.id) &&
30
- (one.observedAt === undefined || nonEmpty(one.observedAt)) &&
31
- (one.label === undefined || nonEmpty(one.label));
67
+ if (!one || typeof one !== 'object')
68
+ return ['reference: not an object'];
69
+ const errors = [];
70
+ for (const field of ['system', 'type', 'id']) {
71
+ if (!nonEmpty(one[field]))
72
+ errors.push(`${field}: required (stable source-fact references are required)`);
73
+ }
74
+ if (one.observedAt !== undefined && !isIsoDateTime(one.observedAt)) {
75
+ errors.push('observedAt: must be ISO 8601 with seconds and Z or an offset');
76
+ }
77
+ if (one.label !== undefined && !nonEmpty(one.label))
78
+ errors.push('label: empty');
79
+ return errors;
32
80
  }
33
81
  function nonEmpty(value) {
34
82
  return typeof value === 'string' && value.trim().length > 0;
35
83
  }
84
+ /* ── The producer's record ────────────────────────────────────────────────────────────────────────────────────────
85
+ *
86
+ * What the contract holds of an attention: the record above, the meaning of its words, and what a consumer may rely on -
87
+ * · **one attention per dedupeKey** - its `attentionId` stays the same across every step; a thing that comes back after it
88
+ * resolved is `reopened`, not a new attention;
89
+ * · `evidenceFingerprint` is the same text for the same evidence rows - a consumer treats a repeat of
90
+ * (domain, source, instance, attention, fingerprint) as one.
91
+ * **How a producer decides its steps** (reconcile a scan against what it keeps, which kinds a scan may resolve, how the
92
+ * fingerprint is made) is the producer's policy - it lives with the producers, in `@things-factory/webhook`
93
+ * (`reconcileAttentions`, `attentionFingerprint`; moved there 2026-11-19, contract content review).
94
+ */
95
+ /**
96
+ * **The record a producer sends** for one step of an attention it keeps. Asserted before it leaves - a producer never
97
+ * sends what a consumer would reject.
98
+ */
99
+ export function operationalAttentionOf(producer, attention, transition, observedAt) {
100
+ const record = {
101
+ contract: OPERATIONAL_ATTENTION_CONTRACT,
102
+ domainId: producer.domainId,
103
+ attentionId: attention.attentionId,
104
+ dedupeKey: attention.dedupeKey,
105
+ kind: attention.kind,
106
+ subjectLabel: attention.subjectLabel,
107
+ transition,
108
+ impact: attention.impact,
109
+ observedAt,
110
+ evidenceFingerprint: attention.evidenceFingerprint,
111
+ facts: attention.facts.map(one => ({ system: producer.system, ...one }))
112
+ };
113
+ assertOperationalAttentionV1(record);
114
+ return record;
115
+ }
@@ -34,7 +34,7 @@
34
34
  * 모르는 필드는 **조용히 버리지 않고 거부한다.** `taskID` 처럼 한 글자 틀린 이름은 통과시키면 영원히
35
35
  * 보이지 않는 손실이 된다(이 문에는 아직 옛 발신자가 없어 호환 부담도 없다).
36
36
  */
37
- import { OP_EVENT, BASIS_UNKNOWN, EQUIPMENT_STATUS, PERSON_STATUS, ASSET_STATUS, DISPOSITION_DECISION, MATERIAL_ACTUAL_USE, MATERIAL_LOT_USE, isTestSpecificationBasis, isRecipeExecutionBasis, isMaterialExecutionBasis } from "./contract.js";
37
+ import { OP_EVENT, TASK_STATUS, BASIS_UNKNOWN, EQUIPMENT_STATUS, PERSON_STATUS, ASSET_STATUS, DISPOSITION_DECISION, MATERIAL_ACTUAL_USE, MATERIAL_LOT_USE, isTestSpecificationBasis, isRecipeExecutionBasis, isMaterialExecutionBasis } from "./contract.js";
38
38
  import { isWorkShiftExecutionBasis } from "./work-shift-basis.js";
39
39
  /**
40
40
  * 객체 한 줄이 선언된 안쪽 모양을 지키나 — **선언하지 않은 자리는 보지 않는다.**
@@ -90,11 +90,10 @@ function shapeErrors(where, row, shape) {
90
90
  }
91
91
  /**
92
92
  * 닫아 둔 낱말과 그 이유.
93
- * · 작업 상태 — 성과 폴드가 `completed`·`in-progress` 로 갈린다(`kpi-fold`).
93
+ * · 작업 상태 — 목록은 계약의 `TASK_STATUS` 하나다(`contract.ts` — 그 까닭도 거기). 여기에 다시 적지 않는다.
94
94
  * · 설비 상태 — OEE 누적기가 `busy`·`down` 만 센다. 그 밖의 낱말은 가동률 0% 로 조용히 앉는다.
95
95
  * · 사람·자산 상태 — 배정이 `idle` 을 찾는다. 다른 낱말이면 있는 자원이 없는 것이 된다.
96
96
  */
97
- const TASK_STATUS = ['created', 'assigned', 'in-progress', 'completed'];
98
97
  /*
99
98
  * 설비 상태 — **ISO 22400-2 의 시간 모델에 하나씩 대응한다**(2026-08-30).
100
99
  *
@@ -1,4 +1,4 @@
1
- import { type CapacityAnalysis, type CapacityInput, type CapacityRequirement } from './capacity.ts';
1
+ import type { CapacityAnalysis, CapacityInput, CapacityRequirement } from './capacity.ts';
2
2
  import { type ISOTime, type WorkCalendarEntry } from './contract.ts';
3
3
  /**
4
4
  * 능력의 종류 — **표준 열거형**(B2MML `CapabilityTypeType`). 우리 낱말을 새로 만들지 않는다.
@@ -108,10 +108,3 @@ export interface OperationsCapabilityInput {
108
108
  * 공휴일이 사라지고, 그 오차는 조용하다.
109
109
  */
110
110
  export declare function workingHoursBetween(calendar: readonly WorkCalendarEntry[] | undefined, fromMs: number, toMs: number, utcOffsetMinutes?: number): number;
111
- /**
112
- * 생산 능력 보고서 — 있는 용량 분석 위에 **구간 · 종류 · 약정**을 올린다.
113
- *
114
- * 용량 분석을 두 번 부른다(전량 · 가용). 같은 함수를 두 번 부르는 것이 요점이다: 달성불가를 따로
115
- * 계산하면 규칙이 두 벌이 되고, 두 벌은 어긋난다.
116
- */
117
- export declare function operationsCapabilityOf(input: OperationsCapabilityInput): OperationsCapabilityReport;
@@ -1,31 +1,3 @@
1
- /*
2
- * 생산 능력 — **ISA-95 Part 4 `OperationsCapability`**: "이 현장이 어느 구간에 얼마나 할 수 있는가."
3
- *
4
- * ── 왜 용량 분석만으로는 부족한가 ────────────────────────────────────────────
5
- * `capacity.ts` 는 이미 네 축(설비·인원·자산·자리) 정상상태 상한과 병목을 낸다. 그런데 그것은 **비율**
6
- * 이다(시간당 몇 대). 표준이 게시하라는 것은 **구간의 양**이고, 그 양을 **종류로 구분한다.**
7
- *
8
- * 종류가 없으면 답할 수 없는 질문이 있다 — 그리고 그것이 이 개념을 쓰는 가장 흔한 질문이다:
9
- * **"지금 주문을 더 받을 수 있나."** 상한만 있으면 "시간당 12대" 까지고, 이미 약속한 물량을 빼야
10
- * 비로소 남은 능력이 나온다.
11
- *
12
- * ── 표준의 어휘를 그대로 쓴다 ────────────────────────────────────────────────
13
- * `CapabilityType` 은 자유 문자열이 아니라 **열거형**이다(B2MML-Common.xsd 대조 완료). 그리고 표준은
14
- * `Total` 을 **두 갈래**로 쪼갠다:
15
- *
16
- * · 과거 — `Total = Used + Unused` (쓴 몫 · 못 쓴 몫)
17
- * · 미래 — `Total = Committed + Available + Unattainable` (약정 · 가용 · 달성불가)
18
- *
19
- * 이 보고서는 **미래 쪽**이다. 과거 쪽은 이미 두 곳에 있다(설비 OEE 의 가동/유휴, 호스트의 구간
20
- * 가동률) — 우리가 "가동률이 두 벌이다" 로 본 것이 여기서 설명된다: **두 벌인 것이 맞고, 표준이 그
21
- * 둘을 다른 종류로 부른다.** 합칠 일이 아니라 각자 어느 종류인지 밝힐 일이다.
22
- *
23
- * `Unattainable` 의 표준 정의는 우리 판정과 정확히 겹친다 — *설비 상태·설비 점유·인원 가용성·자재
24
- * 가용성 때문에 앞으로 쓸 수 없는 용량.* 그래서 이 모듈은 그것을 **다시 판정하지 않는다**:
25
- * 부르는 쪽이 "전량 선언 기준" 과 "지금 쓸 수 있는 자원 기준" 두 벌을 주면, 그 **차이가 곧
26
- * 달성불가**다(§unattainableOf). 판정은 한 벌이어야 하고 그 한 벌은 `capabilityOf` 다.
27
- */
28
- import { analyzeCapacity } from "./capacity.js";
29
1
  import { inWorkCalendarAt } from "./contract.js";
30
2
  /**
31
3
  * 구간의 **가동 시간** — 1분 간격으로 캘린더에 묻는다.
@@ -47,74 +19,3 @@ export function workingHoursBetween(calendar, fromMs, toMs, utcOffsetMinutes) {
47
19
  minutes++;
48
20
  return minutes / 60;
49
21
  }
50
- /**
51
- * 생산 능력 보고서 — 있는 용량 분석 위에 **구간 · 종류 · 약정**을 올린다.
52
- *
53
- * 용량 분석을 두 번 부른다(전량 · 가용). 같은 함수를 두 번 부르는 것이 요점이다: 달성불가를 따로
54
- * 계산하면 규칙이 두 벌이 되고, 두 벌은 어긋난다.
55
- */
56
- export function operationsCapabilityOf(input) {
57
- const fromMs = Date.parse(input.window.fromTime);
58
- const toMs = Date.parse(input.window.toTime);
59
- if (!Number.isFinite(fromMs) || !Number.isFinite(toMs)) {
60
- throw new Error(`능력의 구간을 읽을 수 없다: ${input.window.fromTime} ~ ${input.window.toTime}`);
61
- }
62
- if (toMs <= fromMs)
63
- throw new Error(`능력의 구간이 뒤집혔다: ${input.window.fromTime} ~ ${input.window.toTime}`);
64
- const workingHours = workingHoursBetween(input.calendar ?? input.capacity.calendar, fromMs, toMs, input.utcOffsetMinutes);
65
- const full = analyzeCapacity(input.capacity);
66
- const usable = input.usableCapacity ? analyzeCapacity(input.usableCapacity) : undefined;
67
- /** 비율(시간당) → 구간의 양. 상한이 무한(요구가 없는 공정)이면 **모른다**. */
68
- const amountOf = (perHour) => (Number.isFinite(perHour) ? perHour * workingHours : null);
69
- const committedOf = (operation) => {
70
- let sum = 0;
71
- for (const d of input.demands ?? []) {
72
- if (d.operation !== undefined && d.operation !== operation)
73
- continue;
74
- /* 납기가 없으면 이 구간의 약정이 아니다 — 짐작해서 넣으면 남은 능력이 실제보다 적게 보인다. */
75
- if (!d.dueTime)
76
- continue;
77
- const due = Date.parse(d.dueTime);
78
- if (!Number.isFinite(due) || due < fromMs || due >= toMs)
79
- continue;
80
- sum += Math.max(0, d.remaining);
81
- }
82
- return sum;
83
- };
84
- const perOperation = full.operations.map(op => {
85
- const total = amountOf(op.perHour);
86
- const committed = committedOf(op.operation);
87
- /*
88
- * 달성불가 = 전량 기준 − 가용 자원 기준. 자원의 현재 사실을 못 받았으면 **모른다**(0 이 아니다).
89
- * 음수가 되는 일은 없어야 하지만(가용 ⊆ 전량), 되면 그것을 감추지 않고 0 으로 깎는다 — 부분집합이
90
- * 아닌 입력을 받은 것이므로 값을 지어내는 대신 아래 `available` 이 어긋남을 드러낸다.
91
- */
92
- let unattainable = null;
93
- let unattainableBy;
94
- if (usable) {
95
- const left = usable.operations.find(o => o.operation === op.operation);
96
- const usableAmount = amountOf(left?.perHour ?? NaN);
97
- unattainable = total != null && usableAmount != null ? Math.max(0, total - usableAmount) : null;
98
- /* 잃은 몫이 있을 때만 원인을 말한다 — 잃은 것이 없는데 "여기부터" 라고 하면 없는 일을 만든다. */
99
- if (unattainable != null && unattainable > 0 && left?.constraint)
100
- unattainableBy = left.constraint;
101
- }
102
- const available = total == null || unattainable == null ? null : total - committed - unattainable;
103
- return {
104
- operation: op.operation,
105
- total,
106
- committed,
107
- unattainable,
108
- available,
109
- ...(op.constraint ? { constraint: op.constraint } : {}),
110
- ...(unattainableBy ? { unattainableBy } : {})
111
- };
112
- });
113
- return {
114
- operationsType: input.operationsType ?? 'Production',
115
- window: { fromTime: input.window.fromTime, toTime: input.window.toTime, workingHours },
116
- perOperation,
117
- ...(full.bottleneck ? { bottleneck: full.bottleneck } : {}),
118
- ...(input.publishedDate ? { publishedDate: input.publishedDate } : {})
119
- };
120
- }
@@ -48,36 +48,8 @@ export interface FoldedOrders {
48
48
  */
49
49
  hours?: Record<string, Record<string, Record<string, number>>>;
50
50
  }
51
- export declare function emptyFoldedOrders(): FoldedOrders;
52
51
  /** 접힌 오더의 총수 — 서랍의 「끝난 오더 N건」이 읽는다. */
53
52
  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
53
  /** 그 시각이 든 정시(ms) — 칸의 열쇠는 절대 시각의 정시다(판정 2026-09-24). */
82
54
  export declare function hourStartOf(ms: number): number;
83
55
  /**
@@ -88,8 +60,6 @@ export declare function hourStartOf(ms: number): number;
88
60
  * T 이상 T + 1시간 미만이다.
89
61
  */
90
62
  export declare function finishedWindowStartMs(nowMs: number, policy?: OrderFoldPolicy): number;
91
- /** 창 밖 칸을 버린다 — 접을 때 부른다. 새 값을 돌려준다. */
92
- export declare function pruneFoldedHours(folded: FoldedOrders, nowMs: number, policy?: OrderFoldPolicy): FoldedOrders;
93
63
  /**
94
64
  * **최근 T 안에 끝난 흐름 오더의 수** — 씬 오더 상자의 칩이 읽는다(ADR-0092 결정 2 보탬, 판정 2026-09-24).
95
65
  *
@@ -32,9 +32,6 @@ export function orderFoldPolicyOf(declared) {
32
32
  return { error: 'order fold maxTerminal must be at least 1 (ADR-0092)' };
33
33
  return { policy };
34
34
  }
35
- export function emptyFoldedOrders() {
36
- return { counts: {}, boundaryMs: null };
37
- }
38
35
  /** 접힌 오더의 총수 — 서랍의 「끝난 오더 N건」이 읽는다. */
39
36
  export function foldedOrderCount(folded) {
40
37
  let n = 0;
@@ -43,67 +40,6 @@ export function foldedOrderCount(folded) {
43
40
  n += c;
44
41
  return n;
45
42
  }
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
43
  /** 그 시각이 든 정시(ms) — 칸의 열쇠는 절대 시각의 정시다(판정 2026-09-24). */
108
44
  export function hourStartOf(ms) {
109
45
  return Math.floor(ms / ORDER_FOLD_HOUR_MS) * ORDER_FOLD_HOUR_MS;
@@ -118,17 +54,6 @@ export function hourStartOf(ms) {
118
54
  export function finishedWindowStartMs(nowMs, policy = ORDER_FOLD_DEFAULT) {
119
55
  return hourStartOf(nowMs) - policy.afterMs;
120
56
  }
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
57
  /**
133
58
  * **최근 T 안에 끝난 흐름 오더의 수** — 씬 오더 상자의 칩이 읽는다(ADR-0092 결정 2 보탬, 판정 2026-09-24).
134
59
  *
@@ -0,0 +1,74 @@
1
+ import { type EpcisEvent, type EpcisHeader } from './epcis.ts';
2
+ import type { CanonicalAggregationRecord, CanonicalRecord, CanonicalTransformationRecord } from './canonical-record.ts';
3
+ /** The three logistics records the twin takes - object observed, contained, transformed. The twin tells them apart by shape. */
4
+ export type TwinRecord = CanonicalRecord | CanonicalAggregationRecord | CanonicalTransformationRecord;
5
+ /**
6
+ * Why an event is not sent as records. "None" and "not sent" are not written as one value: the order's fact
7
+ * (a TransactionEvent) is carried by the order record, and sending it twice would count it twice in the mirror.
8
+ */
9
+ export type RecordsHeldBack = 'the-order-record-carries-it';
10
+ /**
11
+ * EPCIS fields the canonical records have no place for yet. They are **named, not dropped silently**: the result says which of them
12
+ * the event carried, so a product can tell what the twin will not see (contract review 2026-11-19). A field that would change what
13
+ * the record means is refused instead (`errorDeclaration` - a correction sent as a plain observation would read as a new fact).
14
+ */
15
+ export declare const FIELDS_NOT_CARRIED: readonly ["ilmd", "sourceList", "destinationList", "persistentDisposition", "sensorElementList", "certificationInfo"];
16
+ export type FieldNotCarried = (typeof FIELDS_NOT_CARRIED)[number];
17
+ /**
18
+ * **The EPCIS header fields the canonical records carry** - the one list (contract content review 2026-11-19). `headerOf` writes
19
+ * exactly these and the three record types declare them; carrying one more (say `sourceList`) is a move from
20
+ * `FIELDS_NOT_CARRIED` to here, plus the field on the record types and the receiver's mapping.
21
+ */
22
+ export declare const CARRIED_HEADER_FIELDS: readonly ["bizStep", "disposition", "bizTransactionList", "readPoint", "bizLocation"];
23
+ export type CarriedHeaderField = (typeof CARRIED_HEADER_FIELDS)[number];
24
+ /** What the event is and when - the record's own shape and the envelope carry these, not the header. `@context` is JSON-LD's, not a fact. */
25
+ declare const IDENTITY_HEADER_FIELDS: readonly ["@context", "type", "eventID", "eventTime", "eventTimeZoneOffset", "recordTime"];
26
+ /** Refused rather than sent: it would change what the record means (`correction-not-shaped`). */
27
+ declare const REFUSED_HEADER_FIELDS: readonly ["errorDeclaration"];
28
+ type ListedHeaderField = CarriedHeaderField | FieldNotCarried | (typeof IDENTITY_HEADER_FIELDS)[number] | (typeof REFUSED_HEADER_FIELDS)[number];
29
+ type UnlistedHeaderField = Exclude<keyof EpcisHeader, ListedHeaderField>;
30
+ type NotAHeaderField = Exclude<ListedHeaderField, keyof EpcisHeader>;
31
+ type MissingOnRecords = Exclude<CarriedHeaderField, keyof CanonicalRecord & keyof CanonicalAggregationRecord & keyof CanonicalTransformationRecord>;
32
+ export declare const HEADER_FIELDS_PARTITIONED: [UnlistedHeaderField, NotAHeaderField, MissingOnRecords] extends [never, never, never] ? true : never;
33
+ export interface RecordsOfEvent {
34
+ records: TwinRecord[];
35
+ heldBack?: RecordsHeldBack;
36
+ /** The fields this event carried that the records leave out - absent when none. */
37
+ notCarried?: FieldNotCarried[];
38
+ }
39
+ export type RecordShapeRefusal = 'nothing-observed' | 'quantity-across-many-units' | 'event-type-not-shaped' | 'correction-not-shaped' | 'event-invalid';
40
+ /** Why an event cannot be shaped - an `Error` with a `code` and its `params`. A product turns it into its own refusal. */
41
+ export interface RecordShapeError extends Error {
42
+ code: RecordShapeRefusal;
43
+ params: Record<string, unknown>;
44
+ }
45
+ /** Is this the shaping's refusal? */
46
+ export declare function isRecordShapeError(error: unknown): error is RecordShapeError;
47
+ /**
48
+ * One event as canonical records.
49
+ *
50
+ * Quantities go as the absolute remainder, as the contract says ("so much is left", not "so much was taken") - a lost
51
+ * event is corrected by the next. An event that carries one quantity over several units has not said whose it is: put on
52
+ * both it doubles, dropped it vanishes - so it is refused.
53
+ */
54
+ export declare function recordsOfEvent(event: EpcisEvent): RecordsOfEvent;
55
+ /** A stored ledger row, as far as the outbox needs it. */
56
+ export interface StoredLedgerEvent {
57
+ eventId: string;
58
+ eventTime: string;
59
+ payload: object;
60
+ }
61
+ /** One input for the outbox machine - the machine adds the number and the time it was written. */
62
+ export interface TwinOutboxInput {
63
+ record: TwinRecord;
64
+ eventId: string;
65
+ eventTime: Date;
66
+ }
67
+ /**
68
+ * A stored event as outbox inputs. When one event becomes several records **each gets its own idempotency key**
69
+ * (`<eventId>#<n>`): the receiver drops a second line with a key it has seen, so one key on two lines would lose the
70
+ * second silently. The record carries no time - the envelope does (a record with a field the contract lacks is refused
71
+ * whole).
72
+ */
73
+ export declare function outboxInputsOfEvent(row: StoredLedgerEvent): TwinOutboxInput[];
74
+ export {};
@@ -0,0 +1,129 @@
1
+ import { validateEpcisEvent } from "./epcis.js";
2
+ /**
3
+ * EPCIS fields the canonical records have no place for yet. They are **named, not dropped silently**: the result says which of them
4
+ * the event carried, so a product can tell what the twin will not see (contract review 2026-11-19). A field that would change what
5
+ * the record means is refused instead (`errorDeclaration` - a correction sent as a plain observation would read as a new fact).
6
+ */
7
+ export const FIELDS_NOT_CARRIED = ['ilmd', 'sourceList', 'destinationList', 'persistentDisposition', 'sensorElementList', 'certificationInfo'];
8
+ /**
9
+ * **The EPCIS header fields the canonical records carry** - the one list (contract content review 2026-11-19). `headerOf` writes
10
+ * exactly these and the three record types declare them; carrying one more (say `sourceList`) is a move from
11
+ * `FIELDS_NOT_CARRIED` to here, plus the field on the record types and the receiver's mapping.
12
+ */
13
+ export const CARRIED_HEADER_FIELDS = ['bizStep', 'disposition', 'bizTransactionList', 'readPoint', 'bizLocation'];
14
+ /** What the event is and when - the record's own shape and the envelope carry these, not the header. `@context` is JSON-LD's, not a fact. */
15
+ const IDENTITY_HEADER_FIELDS = ['@context', 'type', 'eventID', 'eventTime', 'eventTimeZoneOffset', 'recordTime'];
16
+ /** Refused rather than sent: it would change what the record means (`correction-not-shaped`). */
17
+ const REFUSED_HEADER_FIELDS = ['errorDeclaration'];
18
+ export const HEADER_FIELDS_PARTITIONED = true;
19
+ function shapeError(code, params, message) {
20
+ return Object.assign(new Error(message), { name: 'RecordShapeError', code, params });
21
+ }
22
+ /** Is this the shaping's refusal? */
23
+ export function isRecordShapeError(error) {
24
+ return error instanceof Error && error.name === 'RecordShapeError';
25
+ }
26
+ function placeOf(ref) {
27
+ return typeof ref?.id === 'string' ? ref.id : undefined;
28
+ }
29
+ function headerOf(event) {
30
+ return {
31
+ bizStep: event.bizStep,
32
+ ...(event.disposition ? { disposition: event.disposition } : {}),
33
+ ...(event.bizTransactionList?.length ? { bizTransactionList: event.bizTransactionList } : {}),
34
+ /* The twin's record takes a place as its value, an EPCIS document as `{ id }` - the sender moves it (connector ruling 2026-09-24). */
35
+ ...(placeOf(event.readPoint) ? { readPoint: placeOf(event.readPoint) } : {}),
36
+ ...(placeOf(event.bizLocation) ? { bizLocation: placeOf(event.bizLocation) } : {})
37
+ };
38
+ }
39
+ /**
40
+ * One event as canonical records.
41
+ *
42
+ * Quantities go as the absolute remainder, as the contract says ("so much is left", not "so much was taken") - a lost
43
+ * event is corrected by the next. An event that carries one quantity over several units has not said whose it is: put on
44
+ * both it doubles, dropped it vanishes - so it is refused.
45
+ */
46
+ export function recordsOfEvent(event) {
47
+ if (event.errorDeclaration) {
48
+ throw shapeError('correction-not-shaped', { event: event.eventID }, 'the event declares an error in an earlier one: the canonical records have no correction, and sent as an observation it would read as a new fact');
49
+ }
50
+ /* The header written below is exactly `CARRIED_HEADER_FIELDS`; anything else the event carried is named. */
51
+ const notCarried = FIELDS_NOT_CARRIED.filter(field => {
52
+ const value = event[field];
53
+ return value !== undefined && value !== null && !(Array.isArray(value) && !value.length);
54
+ });
55
+ const shaped = shapedRecordsOf(event);
56
+ return notCarried.length ? { ...shaped, notCarried } : shaped;
57
+ }
58
+ function shapedRecordsOf(event) {
59
+ switch (event.type) {
60
+ case 'ObjectEvent': {
61
+ const units = event.epcList ?? [];
62
+ const quantities = event.quantityList;
63
+ if (!units.length && !quantities?.length) {
64
+ throw shapeError('nothing-observed', { event: event.eventID }, 'the event names neither a logistic unit nor a quantity: there is nothing to observe');
65
+ }
66
+ if (units.length > 1 && quantities?.length) {
67
+ throw shapeError('quantity-across-many-units', { event: event.eventID, units: units.length }, `the event carries a quantity and ${units.length} units: which unit holds it is not said`);
68
+ }
69
+ if (!units.length) {
70
+ return { records: [{ quantityList: quantities, action: event.action, ...headerOf(event) }] };
71
+ }
72
+ return {
73
+ records: units.map(epc => ({
74
+ epc,
75
+ ...(quantities?.length ? { quantityList: quantities } : {}),
76
+ action: event.action,
77
+ ...headerOf(event)
78
+ }))
79
+ };
80
+ }
81
+ case 'AggregationEvent':
82
+ return {
83
+ records: [
84
+ {
85
+ parentID: event.parentID,
86
+ ...(event.childEPCs?.length ? { childEPCs: event.childEPCs } : {}),
87
+ ...(event.childQuantityList?.length ? { childQuantityList: event.childQuantityList } : {}),
88
+ action: event.action,
89
+ ...headerOf(event)
90
+ }
91
+ ]
92
+ };
93
+ /* What went in and what came out (ADR-0151). A side the event does not name gets no field - an empty list would say "nothing". */
94
+ case 'TransformationEvent':
95
+ return {
96
+ records: [
97
+ {
98
+ ...(event.inputEPCList?.length ? { inputEPCList: event.inputEPCList } : {}),
99
+ ...(event.inputQuantityList?.length ? { inputQuantityList: event.inputQuantityList } : {}),
100
+ ...(event.outputEPCList?.length ? { outputEPCList: event.outputEPCList } : {}),
101
+ ...(event.outputQuantityList?.length ? { outputQuantityList: event.outputQuantityList } : {}),
102
+ ...(event.transformationID ? { transformationID: event.transformationID } : {}),
103
+ ...headerOf(event)
104
+ }
105
+ ]
106
+ };
107
+ /* The order's fact - the order record carries it. Sent as an object observation it would make a thing out of nothing. */
108
+ case 'TransactionEvent':
109
+ return { records: [], heldBack: 'the-order-record-carries-it' };
110
+ default:
111
+ throw shapeError('event-type-not-shaped', { type: event.type }, `${event.type} has no canonical shape: no product writes one`);
112
+ }
113
+ }
114
+ /**
115
+ * A stored event as outbox inputs. When one event becomes several records **each gets its own idempotency key**
116
+ * (`<eventId>#<n>`): the receiver drops a second line with a key it has seen, so one key on two lines would lose the
117
+ * second silently. The record carries no time - the envelope does (a record with a field the contract lacks is refused
118
+ * whole).
119
+ */
120
+ export function outboxInputsOfEvent(row) {
121
+ const event = row.payload;
122
+ /* A stored payload is checked before it is shaped - a ledger row is only as good as what wrote it. */
123
+ const violations = validateEpcisEvent(event);
124
+ if (violations.length)
125
+ throw shapeError('event-invalid', { event: row.eventId, violations }, `the stored event ${row.eventId} is not a valid EPCIS event: ${violations.join(' · ')}`);
126
+ const { records } = recordsOfEvent(event);
127
+ const eventTime = new Date(typeof event.eventTime === 'string' && event.eventTime ? event.eventTime : row.eventTime);
128
+ return records.map((record, index) => ({ record, eventId: records.length > 1 ? `${row.eventId}#${index}` : row.eventId, eventTime }));
129
+ }