@operato/ops-contract 0.9.43 → 0.9.45

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.
package/README.md CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  운영 도메인의 **계약** — 사실을 만드는 쪽과 읽는 쪽이 합의해야 하는 것.
4
4
 
5
+ 읽는 쪽은 트윈만이 아닙니다. 운영 제품끼리(창고 ↔ 생산 · 야드 ↔ 창고) 주고받는 사실도 두 제품 이상이 같은 규칙으로 읽어야 하면
6
+ 이 계약에 둡니다(operato-application ADR-0210 결정 12).
7
+
5
8
  ```
6
9
  EPCIS 2.0 · GS1 물품의 이동과 계보
7
10
  ISA-95 자재 · 설비 · 사람 · 공정
@@ -14,6 +17,10 @@ IEC 61850 · ISO 50001 전기 계통과 성과지표
14
17
 
15
18
  여기 없는 것은 **정책과 엔진**입니다. 그 사실로 무엇을 할지는 `@operato/twin-kernel` 이 정합니다.
16
19
 
20
+ 제품의 저장 구조(원장 표의 칼럼)나 범용 시간 계산도 여기 두지 않습니다 — 원장 행은 `@things-factory/webhook`(`ledgerEventRowOf`),
21
+ 기간 계산은 `@things-factory/shell`(`periodOverlaps` · `clipMs` …)에 있습니다(2026-11-19 이동). 생산자 한 곳만 쓰는 낱말(야드의
22
+ `reposition` 등)도 그 생산자의 것입니다 — **두 제품 이상이 같은 규칙으로 읽어야 하는 낱말만** 이름 붙입니다. 읽는 제품에는 트윈도 포함됩니다.
23
+
17
24
  ## 제품 간 AI 분석 입력 — `OperationalAttentionV1`
18
25
 
19
26
  `OperationalAttentionV1`은 Plant·WMS·YMS·EMS가 자신이 관측한 운영 주의 사실을 Twin 또는 AI 분석기에
@@ -51,6 +58,12 @@ assertOperationalAttentionV1(attention)
51
58
  - 분석 수명주기: `opened`, `changed`, `resolved`, `reopened`
52
59
  - 분석 우선순위: `medium`, `high`
53
60
  - 근거: 최소 하나 이상의 안정된 `{ system, type, id }` 원본 사실 참조와 `evidenceFingerprint`
61
+ - 관측 시각: `observedAt`(과 사실 참조의 `observedAt`)은 초까지 있고 `Z` 또는 `±hh:mm` 오프셋이 붙은
62
+ ISO 8601 시각. 수신자는 이 문자열을 중복 판정 열쇠에 쓰므로 시간대를 모르는 시각은 받지 않습니다.
63
+ - 이유 코드: `kind`는 `<제품>.<코드>` 모양의 소문자·하이픈(`plant.job-order-past-due`, `yard.late`).
64
+ 이름공간은 두 제품의 코드가 섞이지 않게 하는 것이며, 어느 제품 이름을 쓰는지는 검사하지 않습니다.
65
+
66
+ 거부할 때는 `operationalAttentionErrors()`가 칸마다 이유를 한 줄씩 냅니다(`observedAt: …`, `facts[0].type: …`).
54
67
 
55
68
  사람이 읽는 제목만 있고 원본 사실 ID가 없는 입력은 거부합니다. AI가 그럴듯한 설명을 만들더라도
56
69
  근거를 다시 열어 볼 수 없으면 운영 분석의 입력이 될 수 없기 때문입니다.
@@ -65,6 +78,26 @@ assertOperationalAttentionV1(attention)
65
78
  새 제품이 붙을 때는 공통 봉투를 넓히기 전에 그 제품의 adapter에서 자기 `kind`·사실 유형·판정 기준을
66
79
  검증합니다. 모든 제품이 실제로 공유하는 필드만 이 계약에 추가합니다.
67
80
 
81
+ ### 계약이 정하는 것과 생산자가 정하는 것 (2026-11-19)
82
+
83
+ 계약은 레코드의 모양(`OperationalAttentionV1` · 그것을 짓고 검사하는 `operationalAttentionOf`)과 낱말의 뜻, 그리고 수신자가
84
+ 기댈 수 있는 불변식만 정합니다.
85
+
86
+ - 한 `dedupeKey` 에 주의 하나 — `attentionId` 는 모든 전이에서 같습니다. 닫혔다가 다시 일어난 것은 새 주의가 아니라 `reopened` 입니다.
87
+ - `evidenceFingerprint` 는 같은 근거 행이면 같은 글자입니다. 수신자는 (domain, source, instance, attention, fingerprint) 가 같으면 하나로 셉니다.
88
+
89
+ **제품 사이의 사실**(`material-move` · `dock-facts`)은 EPCIS · ISA-95 의 것이 아니라 우리 제품끼리 주고받는 레코드입니다. 두 쪽이 같은 읽기를 써야
90
+ 해서(사본 둘이 갈라졌던 일, 2026-11-19) 여기 둡니다. 계약이 정하는 것은 낱말 · 칸 · 읽기의 규칙이고, 받는 쪽이 되풀이를 한 번으로 세는 법(제품들은
91
+ 사업장 · peer · id 로 한 번)이나 같은 오더의 새 요청을 어떻게 다룰지는 받는 제품이 정합니다.
92
+
93
+ **파생의 기준** — 계약의 파생은 선언된 필드만 보고 답하며, 두 구현(생산자와 소비자)이 같은 답을 내야 하는 규칙에 한합니다:
94
+ `locationStatusOf` · `dockDoorStatusOf`(도어의 동시 수 `dockDoorCapacityOf` — 정수, 최소 1, 1.5 는 1). 이 기준을 넘는 판정 — 예약 규칙 · 우선순위 ·
95
+ 아래 생산자의 전이 판정 — 은 계약에 올리지 않습니다.
96
+
97
+ **생산자가 전이를 어떻게 정하는지**(한 번의 판정을 지닌 것과 맞추기, 한 판정이 어느 종류만 닫을 수 있나, 지문을 어떻게 짓나)는
98
+ 생산자의 정책입니다. 생산자들이 함께 쓰는 몸통은 `@things-factory/webhook` 의 `reconcileAttentions` · `attentionFingerprint`(SHA-256)에
99
+ 있습니다 — 이 계약에 두었다가 옮겼습니다(정책은 이 층에 두지 않는다).
100
+
68
101
  ### 기존 webhook을 통한 전송
69
102
 
70
103
  새 URL은 만들지 않는다. attention도 기존 `POST /domain/{domain}/twin/hook/{source}/{instanceId}`로 보내며,
@@ -149,6 +149,7 @@ export declare function asApproved(command: TwinCommand): ApprovedCommand;
149
149
  export interface CommandTypeSpec {
150
150
  /** 트윈 어휘의 종류 이름. 점으로 나눈다(`production.order`). */
151
151
  type: string;
152
+ /** 화면에 보일 이름의 i18n 키(`twin.command.<type>`). 자리·설비 타입의 `label` 과 같은 규칙이다. */
152
153
  label: string;
153
154
  /**
154
155
  * 이 종류가 되돌릴 수 있는가 — **기본을 정하는 자리**.
@@ -90,13 +90,6 @@ export declare function workingTimeOfWeek(calendar: readonly WorkCalendarEntry[]
90
90
  hoursPerWeek: number;
91
91
  daysPerWeek: number;
92
92
  };
93
- /**
94
- * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
95
- *
96
- * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
97
- * 실행해 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
98
- */
99
- export declare function analyzeCapacity(input: CapacityInput): CapacityAnalysis;
100
93
  /**
101
94
  * 이 창에서 **조업이 계획되지 않은 시간**(ms) — 없으면 `undefined`.
102
95
  *
package/dist/capacity.js CHANGED
@@ -1,29 +1,11 @@
1
1
  /*
2
- * 용량 분석 — **실행해 보기 전에 "이 공장이 그 물량을 낼 수 있는가" 에 답한다.**
2
+ * 용량 분석의 **입력 · 보고서 모양**과 근무 캘린더 읽기 — 계약 쪽.
3
3
  *
4
- * ── 왜 커널인가 ──────────────────────────────────────────────────────────────
5
- * 이 계산을 처음에는 레퍼런스 마스터 옆에서 손으로 했다(Rosarito). 그러다 두 가지를 알았다.
6
- *
7
- * 첫째, **입력이 전부 커널에 있다.** 공정 명세(소요·셋업·수율)·설비와 그 신뢰도·인원·물리자산·자리·
8
- * 근무 캘린더. 바깥에서 계산하면 그 값을 옮겨 적게 되고, 한쪽만 고치는 순간 "충분하다" 가 조용히
9
- * 거짓이 된다.
10
- *
11
- * 둘째, **손계산은 설비만 셌다.** 표준 공정 명세는 네 축으로 자원을 요구한다(설비·인원·물리자산·자재)
12
- * — 그리고 현장에서 가장 자주 모자라는 것은 사람이다. 설비만 세는 계산은 "용접 자격자가 2명뿐이라
13
- * 로봇 6대가 논다" 를 구조적으로 못 본다. 네 축을 다 보는 자리는 커널뿐이다.
14
- *
15
- * ── 이것이 시뮬레이션과 다른 점 ─────────────────────────────────────────────
16
- * 시뮬레이션은 **실행해 봐야** 답이 나오고, 변동·고장·줄서기가 섞인 결과를 준다. 이 계산은 **정상상태
17
- * 상한**이다 — 모든 것이 계획대로 흘렀을 때의 상한. 둘은 서로를 대체하지 않는다:
18
- * - 상한이 수요보다 낮으면 **시뮬레이션을 돌릴 필요가 없다.** 무슨 짓을 해도 못 낸다.
19
- * - 상한이 충분한데 시뮬레이션이 못 내면 그것은 **흐름의 문제**다(줄서기·배치·변동).
20
- *
21
- * 그래서 이 계산은 진단이 아니라 **분류**다. 어느 쪽 문제인지부터 갈라 준다.
22
- *
23
- * ── 재지 않는 것 ─────────────────────────────────────────────────────────────
24
- * 자재는 여기서 제약으로 세지 않는다. 자재는 **보충되는 것**이라 대수처럼 고정 공급이 아니고,
25
- * 부족은 조달 문제이지 용량 문제가 아니다(자재 부족은 `work-backlog` 가 흐름에서 잡는다).
26
- * 인원·자산에는 신뢰도 모델이 없다 — 가동률 1로 본다(설비만 mtbf/mttr 를 갖는다).
4
+ * 분석 자체(`analyzeCapacity`)는 엔진의 판정이라 `@operato/twin-kernel` 의 `capacity.ts` 에 있다(2026-11-19 이동).
5
+ * 여기 남은 것은 두 가지다:
6
+ * · 보고서와 입력의 타입 — 커널 밖(호스트 · 화면 · 레퍼런스 마스터)이 그 모양을 읽는다.
7
+ * · 근무 캘린더 읽기(`workingTimeOfWeek` · `nonWorkingMsIn`) — 선언된 캘린더만 보고 답하고, 호스트와 커널이
8
+ * 같은 답을 내야 한다(`inWorkCalendarAt` 과 같은 결). README 「파생의 기준」.
27
9
  */
28
10
  import { inWorkCalendarAt } from "./contract.js";
29
11
  /** ISO 8601 기간 → 시간. 명세가 쓰는 표기 그대로 읽는다(`PT1H40M`). */
@@ -35,9 +17,6 @@ export function isoDurationHours(iso) {
35
17
  throw new Error(`기간 표기를 읽을 수 없다: ${iso}`);
36
18
  return Number(m[1] ?? 0) * 24 + Number(m[2] ?? 0) + Number(m[3] ?? 0) / 60 + Number(m[4] ?? 0) / 3600;
37
19
  }
38
- function paramOf(op, id) {
39
- return op.parameters?.find(p => p.id === id)?.value;
40
- }
41
20
  /**
42
21
  * 근무 캘린더에서 **가용 시간과 조업일**을 읽는다 — 1분 간격 샘플링.
43
22
  *
@@ -74,102 +53,6 @@ export function workingTimeOfWeek(calendar, weekStartMs, utcOffsetMinutes) {
74
53
  declared.add(d);
75
54
  return { hoursPerWeek: minutes / 60, daysPerWeek: declared.size || touched.size };
76
55
  }
77
- function availabilityOf(records) {
78
- /* 신뢰도를 선언하지 않은 설비는 고장 없음이다(계약의 규칙) — 1 로 센다. */
79
- const ratios = records.map(r => (r.mtbfMs && r.mttrMs ? r.mtbfMs / (r.mtbfMs + r.mttrMs) : 1));
80
- return ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1;
81
- }
82
- /**
83
- * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
84
- *
85
- * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
86
- * 실행해 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
87
- */
88
- export function analyzeCapacity(input) {
89
- const { hoursPerWeek, daysPerWeek } = workingTimeOfWeek(input.calendar, input.sampleWeekStartMs, input.utcOffsetMinutes);
90
- /*
91
- * 수요는 **가동 시간당**이다. 하루 50대는 쉬는 시간에는 안 나오므로 168시간으로 나누면 안 된다 —
92
- * 그렇게 나누면 필요한 대수가 실제보다 적게 나오고, 공장은 매주 조금씩 밀린다.
93
- */
94
- const demandPerHour = hoursPerWeek > 0 ? (input.unitsPerDay * daysPerWeek) / hoursPerWeek : 0;
95
- /* 축별 공급 — 등급 이름으로 센다. 사람은 자격을 여럿 가질 수 있어 등급 간 합이 인원수를 넘는다
96
- (같은 사람이 두 줄에 선다). 동시에 두 공정을 하지는 못하므로 이 계산은 **낙관적**이다. */
97
- const equipmentByKind = new Map();
98
- for (const e of input.equipment ?? []) {
99
- const list = equipmentByKind.get(e.kind) ?? [];
100
- list.push(e);
101
- equipmentByKind.set(e.kind, list);
102
- }
103
- const countByClass = (rows, field) => {
104
- const out = new Map();
105
- for (const r of rows ?? [])
106
- for (const c of r[field] ?? [])
107
- out.set(c, (out.get(c) ?? 0) + 1);
108
- return out;
109
- };
110
- const personsByClass = countByClass(input.persons, 'personnelClassIds');
111
- const assetsByClass = countByClass(input.assets, 'assetClassIds');
112
- const slotsByLocationType = new Map();
113
- for (const l of input.locations ?? [])
114
- if (l.type)
115
- slotsByLocationType.set(l.type, (slotsByLocationType.get(l.type) ?? 0) + Math.max(l.capacity ?? 1, 1));
116
- const order = input.route?.length
117
- ? input.route.map(k => input.operations.find(o => o.key === k)).filter((o) => !!o)
118
- : [...input.operations];
119
- /* 하류 수율을 거슬러 올라가며 소요량을 부풀린다 — 도장에서 5% 를 잃으면 그 앞은 더 만들어야 한다. */
120
- let downstream = 1;
121
- const reversed = [];
122
- for (const op of [...order].reverse()) {
123
- const cycleHours = isoDurationHours(op.duration) + isoDurationHours(paramOf(op, 'setupDuration'));
124
- downstream *= Number(paramOf(op, 'yield') ?? 1);
125
- const requiredPerHour = downstream > 0 ? demandPerHour / downstream : Infinity;
126
- const requirements = [];
127
- const add = (axis, className, quantity, available, availability) => {
128
- const q = Math.max(quantity, 1);
129
- requirements.push({
130
- axis, className, quantity: q, available, availability,
131
- perHour: cycleHours > 0 ? (Math.floor(available / q) / cycleHours) * availability : Infinity
132
- });
133
- };
134
- /* 설비 — 표준 EquipmentSpecification(등급+대수). 그것이 없으면 예전 표기(resourceType 한 대). */
135
- const equipSpecs = op.equipmentSpecification?.length
136
- ? op.equipmentSpecification.map(s => ({ className: s.equipmentClass ?? op.resourceType ?? '', quantity: s.quantity }))
137
- : op.resourceType ? [{ className: op.resourceType, quantity: 1 }] : [];
138
- for (const s of equipSpecs) {
139
- if (!s.className)
140
- continue;
141
- const records = equipmentByKind.get(s.className) ?? [];
142
- add('equipment', s.className, s.quantity, records.length, availabilityOf(records));
143
- }
144
- for (const s of op.personnelSpecification ?? [])
145
- if (s.personnelClass)
146
- add('personnel', s.personnelClass, s.quantity, personsByClass.get(s.personnelClass) ?? 0, 1);
147
- for (const s of op.physicalAssetSpecification ?? [])
148
- if (s.assetClass)
149
- add('asset', s.assetClass, s.quantity, assetsByClass.get(s.assetClass) ?? 0, 1);
150
- if (op.locationType)
151
- add('location', op.locationType, 1, slotsByLocationType.get(op.locationType) ?? 0, 1);
152
- /* 공정의 능력 = 요구들 중 가장 낮은 것. 전량 확보 규칙이라 하나만 모자라도 그만큼만 처리된다. */
153
- const constraint = requirements.length ? requirements.reduce((a, b) => (a.perHour <= b.perHour ? a : b)) : undefined;
154
- const perHour = constraint ? constraint.perHour : Infinity;
155
- reversed.push({ operation: op.key, cycleHours, perHour, requiredPerHour, ok: perHour >= requiredPerHour, constraint, requirements });
156
- }
157
- const operations = reversed.reverse();
158
- /* 병목 = 여유가 가장 적은 공정. 라인 전체의 상한은 그 공정이 정한다. */
159
- const tightest = operations.length
160
- ? operations.reduce((a, b) => (a.perHour / a.requiredPerHour <= b.perHour / b.requiredPerHour ? a : b))
161
- : undefined;
162
- const headroom = operations.length ? Math.min(...operations.map(o => o.perHour / o.requiredPerHour)) : Infinity;
163
- return {
164
- workingHoursPerWeek: hoursPerWeek,
165
- workingDaysPerWeek: daysPerWeek,
166
- demandPerHour,
167
- operations,
168
- ...(tightest ? { bottleneck: { operation: tightest.operation, axis: tightest.constraint?.axis, className: tightest.constraint?.className } } : {}),
169
- maxUnitsPerDay: input.unitsPerDay * headroom,
170
- ok: operations.every(o => o.ok)
171
- };
172
- }
173
56
  /**
174
57
  * 이 창에서 **조업이 계획되지 않은 시간**(ms) — 없으면 `undefined`.
175
58
  *
@@ -115,11 +115,28 @@ export interface CanonicalEnvelope<T = unknown> {
115
115
  * 로 부르면 **표준 이름을 쓰면서 다른 뜻으로 쓰는 것**이 된다. 대조 문서가 그 판정을 적어 두었다.
116
116
  *
117
117
  * ── 왜 **닫혀** 있나 ────────────────────────────────────────────────────────
118
- * 커널이 이 넷으로 처리한다: 성과 폴드가 착수·완료로 갈리고(`foldTaskRecords`), 주목 계산이
119
- * `created`·`assigned` 를 대기로 센다, 배정 루프는 `created` 만 집는다. 그러니 낱말이 하나 늘면
120
- * 그 셋이 조용히 달라진다 — 유입 문이 이 넷만 받는 이유다(다른 낱말은 오류 없이 사라진다).
118
+ * 커널이 이 다섯으로 처리한다: 성과 폴드가 착수·완료·취소로 갈리고(`foldTaskRecords`), 주목 계산이
119
+ * `created`·`assigned` 를 대기로 센다, 배정 루프는 `created` 만 집는다, 「끝났나」는 `isTaskTerminal` 이 답한다.
120
+ * 그러니 낱말이 하나 늘면 그 넷이 조용히 달라진다 — 유입 문이 이 다섯만 받는 이유다(다른 낱말은 오류 없이
121
+ * 사라진다). 다섯째 `cancelled` 는 2026-11-19 에 들어왔다(아래 `TASK_TERMINAL_STATUS`).
122
+ *
123
+ * 값의 목록은 `TASK_STATUS` 하나다 — 유입 문(`operational-ingest`)도 이것을 읽는다. 따로 적으면 한쪽만 늘어난다.
124
+ */
125
+ export declare const TASK_STATUS: readonly ["created", "assigned", "in-progress", "completed", "cancelled"];
126
+ export type TaskStatus = (typeof TASK_STATUS)[number];
127
+ /**
128
+ * 작업이 **끝난** 낱말 — 완료와 취소. `cancelled` 는 2026-11-19 에 들어왔다: 야드의 이동 작업은 시작 전에 취소되는데(트레일러가 이미
129
+ * 그 자리에 있다고 실사가 말할 때 등), 그 말이 없으면 미러에서 그 작업이 영원히 진행 중으로 남아 도어 · 슬롯을 「예약됨」으로 잡았다.
130
+ * 「끝났나」는 이 함수로 묻는다 — `status === 'completed'` 로 물으면 취소된 작업이 살아 있는 것으로 읽힌다.
131
+ * 성과 폴드는 취소를 완료로 세지 않는다(`completedMs` 가 없다 — 실적은 `aborted`).
132
+ *
133
+ * `ORDER_TERMINAL_STATUS` 와 지금 값이 같지만 **하나로 묶지 않는다** — 오더의 낱말은 도메인 것이고(계약이 닫지 않는다), 작업의 낱말은
134
+ * 위 `TASK_STATUS` 로 닫혀 있다. 한쪽이 늘 때 다른 쪽이 따라 늘면 안 된다.
121
135
  */
122
- export type TaskStatus = 'created' | 'assigned' | 'in-progress' | 'completed';
136
+ export declare const TASK_TERMINAL_STATUS: readonly ["completed", "cancelled"];
137
+ export declare function isTaskTerminal(t: {
138
+ status?: string;
139
+ }): boolean;
123
140
  /** 오더가 **종결 상태**로 인정되는 낱말 — 이 밖은 진행 중이다(§`isOrderTerminal`). */
124
141
  export declare const ORDER_TERMINAL_STATUS: readonly ["completed", "cancelled"];
125
142
  /**
@@ -1237,6 +1254,10 @@ export interface LocationState {
1237
1254
  *
1238
1255
  * 미지정 = 제약 없음(기존 거동). 0 은 "처리하지 않는 자리"가 아니라 **선언 오류**로 보고 무시한다
1239
1256
  * — 0 으로 막을 일이라면 그 자리에 작업을 보내지 않는 것이 맞다.
1257
+ *
1258
+ * **도크 도어(`dock-door`)는 다르게 읽는다** — 한 번에 붙는 트레일러 수이고 **정수, 최소 1**이다: 미지정 · 0 · 음수는 1, 1.5 는 1
1259
+ * (내림 — 반 대는 붙지 않는다). 도어에 「제약 없음」은 없다: 생산자(예약 거절)와 소비자(도어 포화)가 같은 수를 써야 하므로 그 읽기는
1260
+ * 한 함수(`dockDoorCapacityOf`, yms-profile)뿐이다(2026-11-19 계약 내용 점검).
1240
1261
  */
1241
1262
  parallelism?: number;
1242
1263
  occupancy: number;
package/dist/contract.js CHANGED
@@ -33,6 +33,39 @@
33
33
  * `purpose-conformance`.
34
34
  */
35
35
  import { ratedUsageOf } from "./rated-usage.js";
36
+ // ── State 채널: 스냅샷(코어 명사 프로젝션) ────────────────────────────────
37
+ /**
38
+ * 작업의 상태 — **ISA-95 근거.** 1차 출처: `JobOrderType.DispatchStatus`(지시 쪽) +
39
+ * `JobResponseType.JobState`(실적 쪽). 대조 기록: `design/plans/isa95-coverage.md` §3-2
40
+ * (「`tasks.status` ↔ `DispatchStatus`+`JobState`」).
41
+ *
42
+ * ── 왜 우리 이름을 쓰나 ─────────────────────────────────────────────────────
43
+ * 표준은 **지시(`JobOrder`)와 실적(`JobResponse`)을 나눈다.** 우리 `TaskState` 는 그 둘을 한 몸에
44
+ * 든다 — 상태 전이와 배정 결과를 함께 들고 진행·완료까지 같은 개체가 표현한다. 그래서 `jobOrders`
45
+ * 로 부르면 **표준 이름을 쓰면서 다른 뜻으로 쓰는 것**이 된다. 대조 문서가 그 판정을 적어 두었다.
46
+ *
47
+ * ── 왜 **닫혀** 있나 ────────────────────────────────────────────────────────
48
+ * 커널이 이 다섯으로 처리한다: 성과 폴드가 착수·완료·취소로 갈리고(`foldTaskRecords`), 주목 계산이
49
+ * `created`·`assigned` 를 대기로 센다, 배정 루프는 `created` 만 집는다, 「끝났나」는 `isTaskTerminal` 이 답한다.
50
+ * 그러니 낱말이 하나 늘면 그 넷이 조용히 달라진다 — 유입 문이 이 다섯만 받는 이유다(다른 낱말은 오류 없이
51
+ * 사라진다). 다섯째 `cancelled` 는 2026-11-19 에 들어왔다(아래 `TASK_TERMINAL_STATUS`).
52
+ *
53
+ * 값의 목록은 `TASK_STATUS` 하나다 — 유입 문(`operational-ingest`)도 이것을 읽는다. 따로 적으면 한쪽만 늘어난다.
54
+ */
55
+ export const TASK_STATUS = ['created', 'assigned', 'in-progress', 'completed', 'cancelled'];
56
+ /**
57
+ * 작업이 **끝난** 낱말 — 완료와 취소. `cancelled` 는 2026-11-19 에 들어왔다: 야드의 이동 작업은 시작 전에 취소되는데(트레일러가 이미
58
+ * 그 자리에 있다고 실사가 말할 때 등), 그 말이 없으면 미러에서 그 작업이 영원히 진행 중으로 남아 도어 · 슬롯을 「예약됨」으로 잡았다.
59
+ * 「끝났나」는 이 함수로 묻는다 — `status === 'completed'` 로 물으면 취소된 작업이 살아 있는 것으로 읽힌다.
60
+ * 성과 폴드는 취소를 완료로 세지 않는다(`completedMs` 가 없다 — 실적은 `aborted`).
61
+ *
62
+ * `ORDER_TERMINAL_STATUS` 와 지금 값이 같지만 **하나로 묶지 않는다** — 오더의 낱말은 도메인 것이고(계약이 닫지 않는다), 작업의 낱말은
63
+ * 위 `TASK_STATUS` 로 닫혀 있다. 한쪽이 늘 때 다른 쪽이 따라 늘면 안 된다.
64
+ */
65
+ export const TASK_TERMINAL_STATUS = ['completed', 'cancelled'];
66
+ export function isTaskTerminal(t) {
67
+ return TASK_TERMINAL_STATUS.includes(String(t?.status ?? ''));
68
+ }
36
69
  /** 오더가 **종결 상태**로 인정되는 낱말 — 이 밖은 진행 중이다(§`isOrderTerminal`). */
37
70
  export const ORDER_TERMINAL_STATUS = ['completed', 'cancelled'];
38
71
  /**
@@ -0,0 +1,94 @@
1
+ import { YMS_APPOINTMENT_CANCEL_REASON, YMS_ORDER_KIND, type YmsAppointmentStatus } from './yms-profile.ts';
2
+ export declare const DOCK_FACT_KIND: {
3
+ /** warehouse → yard: this order needs a slot at a door. */
4
+ readonly slotRequest: "slot-request";
5
+ /** warehouse → yard: the order no longer needs it. */
6
+ readonly slotWithdrawn: "slot-withdrawn";
7
+ /**
8
+ * warehouse → yard: these logistic units (SSCC) came off or went onto the trailer at the door, as the warehouse received or
9
+ * shipped them (ADR-0210 decision 2, 2026-11-20) - the yard records the unloading or loading against the appointment's trailer.
10
+ */
11
+ readonly cargo: "cargo";
12
+ /** yard → warehouse: the appointment for a request, as it stands now - booked, moved, cancelled, at the door, done. */
13
+ readonly appointment: "appointment";
14
+ /** yard → warehouse: the yard will not book this request, and why. */
15
+ readonly slotDeclined: "slot-declined";
16
+ };
17
+ export type DockFactKind = (typeof DOCK_FACT_KIND)[keyof typeof DOCK_FACT_KIND];
18
+ export type DockDirection = (typeof YMS_ORDER_KIND)[keyof typeof YMS_ORDER_KIND];
19
+ /** A business document the request carries - the appointment takes it as its own (`desadv`, `po`, `bol` …; no type is allowed). */
20
+ export interface DockDocument {
21
+ type?: string;
22
+ id: string;
23
+ }
24
+ export interface SlotRequestFact {
25
+ factId: string;
26
+ kind: typeof DOCK_FACT_KIND.slotRequest;
27
+ /** The warehouse's order - its name, unique in that warehouse. */
28
+ order: string;
29
+ /** Unloading (`appointment`) or loading (`appointment-out`). */
30
+ direction: DockDirection;
31
+ /** The window the warehouse would like - ISO instants; either may be absent. */
32
+ wantedFrom?: string;
33
+ wantedTo?: string;
34
+ /** The warehouse's own dock zone the goods go to or come from - a reference to its place, not the yard's door. */
35
+ dock?: string;
36
+ documents?: DockDocument[];
37
+ /** What a person at the warehouse wants the yard desk to know. */
38
+ note?: string;
39
+ }
40
+ export interface SlotWithdrawnFact {
41
+ factId: string;
42
+ kind: typeof DOCK_FACT_KIND.slotWithdrawn;
43
+ /** The request it withdraws - its `factId`. */
44
+ request: string;
45
+ reason?: string;
46
+ }
47
+ /**
48
+ * **The units that crossed the door** - what the warehouse received (`appointment`, unloading) or shipped (`appointment-out`,
49
+ * loading) for an order the yard booked. The time is the warehouse's scan, which may differ from the moment the unit left or
50
+ * entered the trailer; the yard records it as it comes. The yard does not count - the units are the warehouse's.
51
+ */
52
+ export interface CargoDockFact {
53
+ factId: string;
54
+ kind: typeof DOCK_FACT_KIND.cargo;
55
+ /** The warehouse order - the yard finds the appointment and its trailer through the order's requests. */
56
+ order: string;
57
+ direction: DockDirection;
58
+ /** The logistic units, SSCC URIs (`urn:epc:id:sscc:…`), each once; never empty. */
59
+ units: string[];
60
+ /** When the warehouse scanned them - an instant with its offset. */
61
+ eventTime: string;
62
+ }
63
+ export interface AppointmentDockFact {
64
+ factId: string;
65
+ kind: typeof DOCK_FACT_KIND.appointment;
66
+ /** The request it answers - its `factId`. */
67
+ request: string;
68
+ /** The warehouse order the request was for - so the warehouse need not keep the request to find it. */
69
+ order: string;
70
+ /** The yard's appointment id. */
71
+ appointment: string;
72
+ status: YmsAppointmentStatus;
73
+ /** The yard's door - a reference to the yard's place. */
74
+ dockDoor: string;
75
+ startAt: string;
76
+ endAt: string;
77
+ cancelReason?: (typeof YMS_APPOINTMENT_CANCEL_REASON)[number];
78
+ }
79
+ export interface SlotDeclinedFact {
80
+ factId: string;
81
+ kind: typeof DOCK_FACT_KIND.slotDeclined;
82
+ request: string;
83
+ order: string;
84
+ reason: string;
85
+ }
86
+ export type DockFact = SlotRequestFact | SlotWithdrawnFact | CargoDockFact | AppointmentDockFact | SlotDeclinedFact;
87
+ /** Whether a record on a stream is a dock fact (the warehouse's door also takes the plant's lot statuses and moves). */
88
+ export declare function isDockRecord(record: unknown): boolean;
89
+ /** **Read one record as a dock fact, or say why not.** The receiver passes the kinds it takes. */
90
+ export declare function dockFactOf(record: unknown, takes?: readonly DockFactKind[]): {
91
+ fact: DockFact;
92
+ } | {
93
+ errors: string[];
94
+ };
@@ -0,0 +1,167 @@
1
+ import { isIsoDateTime } from "./epcis.js";
2
+ import { ssccDigitsOf } from "./gs1.js";
3
+ import { isYmsAppointmentStatus, YMS_APPOINTMENT_CANCEL_REASON, YMS_ORDER_KIND } from "./yms-profile.js";
4
+ /*
5
+ * **The dock between the yard and the warehouse** - the facts the two apps send each other about a slot at a door
6
+ * (ADR-0210 decisions 3 · 11 · 12, 2026-11-19).
7
+ *
8
+ * The yard owns the appointment (decision 3): the warehouse asks for a slot for one of its orders, a person at the yard desk
9
+ * confirms it with a door, a time and a carrier, and the yard tells the warehouse where the appointment stands every time it
10
+ * changes. No foreign key between them - the order name and the appointment id travel in the facts, and the order's
11
+ * documents become the appointment's (its events carry them).
12
+ *
13
+ * Each fact carries an id unique within its sender (`factId`). What a receiver does with a repeat, or with a second request
14
+ * for the same order, is the receiver's (README "계약이 정하는 것"). Closed: an unknown kind is refused.
15
+ *
16
+ * The direction is the yard's order kind on purpose - `appointment` (unloading) or `appointment-out` (loading) is what the
17
+ * appointment will be, so the yard books what it is told without a second word to map.
18
+ *
19
+ * warehouse → yard slot-request · slot-withdrawn · cargo
20
+ * yard → warehouse appointment (where the appointment for a request stands now) · slot-declined
21
+ */
22
+ export const DOCK_FACT_KIND = {
23
+ /** warehouse → yard: this order needs a slot at a door. */
24
+ slotRequest: 'slot-request',
25
+ /** warehouse → yard: the order no longer needs it. */
26
+ slotWithdrawn: 'slot-withdrawn',
27
+ /**
28
+ * warehouse → yard: these logistic units (SSCC) came off or went onto the trailer at the door, as the warehouse received or
29
+ * shipped them (ADR-0210 decision 2, 2026-11-20) - the yard records the unloading or loading against the appointment's trailer.
30
+ */
31
+ cargo: 'cargo',
32
+ /** yard → warehouse: the appointment for a request, as it stands now - booked, moved, cancelled, at the door, done. */
33
+ appointment: 'appointment',
34
+ /** yard → warehouse: the yard will not book this request, and why. */
35
+ slotDeclined: 'slot-declined'
36
+ };
37
+ /** Whether a record on a stream is a dock fact (the warehouse's door also takes the plant's lot statuses and moves). */
38
+ export function isDockRecord(record) {
39
+ const r = record;
40
+ return !!r && typeof r === 'object' && typeof r.factId === 'string' && Object.values(DOCK_FACT_KIND).includes(r.kind);
41
+ }
42
+ /* An instant with its offset - the contract's one measure for time fields (`isIsoDateTime`). */
43
+ const isInstant = (v) => isIsoDateTime(v);
44
+ /** **Read one record as a dock fact, or say why not.** The receiver passes the kinds it takes. */
45
+ export function dockFactOf(record, takes) {
46
+ const r = record;
47
+ if (!r || typeof r !== 'object' || typeof r.factId !== 'string' || typeof r.kind !== 'string')
48
+ return { errors: ['the record is not a dock fact: factId and kind are needed'] };
49
+ const kind = r.kind;
50
+ if (!Object.values(DOCK_FACT_KIND).includes(kind))
51
+ return { errors: [`${kind} is not a dock fact kind`] };
52
+ if (takes && !takes.includes(kind))
53
+ return { errors: [`a dock fact of kind ${kind} is not one this receiver takes`] };
54
+ const errors = [];
55
+ const text = (key) => typeof r[key] === 'string' && r[key].trim() !== '';
56
+ const s = (key) => r[key].trim();
57
+ if (!text('factId'))
58
+ errors.push('factId is empty');
59
+ switch (kind) {
60
+ case DOCK_FACT_KIND.slotRequest: {
61
+ if (!text('order'))
62
+ errors.push('order is missing: a request names the warehouse order');
63
+ if (!Object.values(YMS_ORDER_KIND).includes(r.direction))
64
+ errors.push(`direction must be ${Object.values(YMS_ORDER_KIND).join(' or ')}`);
65
+ for (const key of ['wantedFrom', 'wantedTo'])
66
+ if (r[key] !== undefined && !isInstant(r[key]))
67
+ errors.push(`${key} is not an instant`);
68
+ if (isInstant(r.wantedFrom) && isInstant(r.wantedTo) && Date.parse(r.wantedTo) <= Date.parse(r.wantedFrom))
69
+ errors.push('wantedTo is not after wantedFrom');
70
+ const documents = r.documents;
71
+ if (documents !== undefined && (!Array.isArray(documents) || documents.some(one => !one || typeof one.id !== 'string' || !one.id.trim())))
72
+ errors.push('documents must each have an id');
73
+ if (errors.length)
74
+ return { errors };
75
+ return {
76
+ fact: {
77
+ factId: s('factId'),
78
+ kind,
79
+ order: s('order'),
80
+ direction: r.direction,
81
+ ...(isInstant(r.wantedFrom) ? { wantedFrom: r.wantedFrom } : {}),
82
+ ...(isInstant(r.wantedTo) ? { wantedTo: r.wantedTo } : {}),
83
+ ...(text('dock') ? { dock: s('dock') } : {}),
84
+ ...(Array.isArray(documents) && documents.length
85
+ ? { documents: documents.map(one => ({ ...(one.type ? { type: String(one.type) } : {}), id: one.id.trim() })) }
86
+ : {}),
87
+ ...(text('note') ? { note: s('note') } : {})
88
+ }
89
+ };
90
+ }
91
+ case DOCK_FACT_KIND.slotWithdrawn: {
92
+ if (!text('request'))
93
+ errors.push('request is missing: a withdrawal names the request');
94
+ if (errors.length)
95
+ return { errors };
96
+ return { fact: { factId: s('factId'), kind, request: s('request'), ...(text('reason') ? { reason: s('reason') } : {}) } };
97
+ }
98
+ case DOCK_FACT_KIND.cargo: {
99
+ if (!text('order'))
100
+ errors.push('order is missing: cargo names the warehouse order');
101
+ if (!Object.values(YMS_ORDER_KIND).includes(r.direction))
102
+ errors.push(`direction must be ${Object.values(YMS_ORDER_KIND).join(' or ')}`);
103
+ if (!isInstant(r.eventTime))
104
+ errors.push('eventTime is not an instant');
105
+ const units = r.units;
106
+ if (!Array.isArray(units) || !units.length)
107
+ errors.push('units is empty: cargo names the logistic units that crossed the door');
108
+ else
109
+ for (const unit of units)
110
+ if (typeof unit !== 'string' || !ssccDigitsOf(unit.trim()))
111
+ errors.push(`${String(unit)} is not an SSCC`);
112
+ if (errors.length)
113
+ return { errors };
114
+ return {
115
+ fact: {
116
+ factId: s('factId'),
117
+ kind,
118
+ order: s('order'),
119
+ direction: r.direction,
120
+ units: [...new Set(units.map(unit => unit.trim()))],
121
+ eventTime: r.eventTime
122
+ }
123
+ };
124
+ }
125
+ case DOCK_FACT_KIND.appointment: {
126
+ for (const key of ['request', 'order', 'appointment', 'dockDoor'])
127
+ if (!text(key))
128
+ errors.push(`${key} is missing`);
129
+ if (!isYmsAppointmentStatus(r.status))
130
+ errors.push(`status ${String(r.status)} is not an appointment status`);
131
+ if (!isInstant(r.startAt) || !isInstant(r.endAt))
132
+ errors.push('startAt and endAt must be instants');
133
+ if (r.cancelReason !== undefined && !YMS_APPOINTMENT_CANCEL_REASON.includes(r.cancelReason))
134
+ errors.push(`cancelReason ${String(r.cancelReason)} is not one`);
135
+ if (r.status === 'cancelled' && r.cancelReason === undefined)
136
+ errors.push('a cancelled appointment says why (cancelReason)');
137
+ if (r.status !== 'cancelled' && r.cancelReason !== undefined)
138
+ errors.push('only a cancelled appointment carries a cancelReason');
139
+ if (isInstant(r.startAt) && isInstant(r.endAt) && Date.parse(r.endAt) <= Date.parse(r.startAt))
140
+ errors.push('endAt is not after startAt');
141
+ if (errors.length)
142
+ return { errors };
143
+ return {
144
+ fact: {
145
+ factId: s('factId'),
146
+ kind,
147
+ request: s('request'),
148
+ order: s('order'),
149
+ appointment: s('appointment'),
150
+ status: r.status,
151
+ dockDoor: s('dockDoor'),
152
+ startAt: s('startAt'),
153
+ endAt: s('endAt'),
154
+ ...(r.cancelReason !== undefined ? { cancelReason: r.cancelReason } : {})
155
+ }
156
+ };
157
+ }
158
+ default: {
159
+ for (const key of ['request', 'order', 'reason'])
160
+ if (!text(key))
161
+ errors.push(`${key} is missing`);
162
+ if (errors.length)
163
+ return { errors };
164
+ return { fact: { factId: s('factId'), kind: DOCK_FACT_KIND.slotDeclined, request: s('request'), order: s('order'), reason: s('reason') } };
165
+ }
166
+ }
167
+ }
@@ -14,8 +14,7 @@ export declare const EMS_LOCATION_TYPES: readonly ["incoming", "feeder", "submet
14
14
  * `bidirectional` 은 **그 계량기가 순 유입을 재는 것**이다. 발전을 부하에서 빼는 것이 아니다 — 그
15
15
  * 계량기가 읽은 값이 그 접속점의 사실이고, 요금이 그 값에 매겨진다.
16
16
  *
17
- * 표준 근거: 계량기의 적산 레지스터가 유입·유출로 갈려 있고(IEC 62053 계열), ISO 50001 은 유입 경계를
18
- * 따로 둔다(`EnergyInput`). 우리가 지은 낱말이 아니다.
17
+ * 표준 근거: 계량기의 적산 레지스터가 유입·유출로 갈려 있다(IEC 62053 계열). 우리가 지은 낱말이 아니다.
19
18
  */
20
19
  export declare const METER_DIRECTION: readonly ["import", "export", "bidirectional"];
21
20
  export type MeterDirection = (typeof METER_DIRECTION)[number];