@operato/twin-kernel 0.11.30 → 0.11.32

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.
@@ -0,0 +1,8 @@
1
+ import { type CapacityAnalysis, type CapacityInput } from '@operato/ops-contract';
2
+ /**
3
+ * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
4
+ *
5
+ * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
6
+ * 실행해 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
7
+ */
8
+ export declare function analyzeCapacity(input: CapacityInput): CapacityAnalysis;
@@ -0,0 +1,127 @@
1
+ /*
2
+ * 용량 분석 — **실행해 보기 전에 "이 공장이 그 물량을 낼 수 있는가" 에 답한다.**
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 를 갖는다).
27
+ */
28
+ import { isoDurationHours, workingTimeOfWeek } from '@operato/ops-contract';
29
+ function paramOf(op, id) {
30
+ return op.parameters?.find(p => p.id === id)?.value;
31
+ }
32
+ function availabilityOf(records) {
33
+ /* 신뢰도를 선언하지 않은 설비는 고장 없음이다(계약의 규칙) — 1 로 센다. */
34
+ const ratios = records.map(r => (r.mtbfMs && r.mttrMs ? r.mtbfMs / (r.mtbfMs + r.mttrMs) : 1));
35
+ return ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1;
36
+ }
37
+ /**
38
+ * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
39
+ *
40
+ * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
41
+ * 실행해 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
42
+ */
43
+ export function analyzeCapacity(input) {
44
+ const { hoursPerWeek, daysPerWeek } = workingTimeOfWeek(input.calendar, input.sampleWeekStartMs, input.utcOffsetMinutes);
45
+ /*
46
+ * 수요는 **가동 시간당**이다. 하루 50대는 쉬는 시간에는 안 나오므로 168시간으로 나누면 안 된다 —
47
+ * 그렇게 나누면 필요한 대수가 실제보다 적게 나오고, 공장은 매주 조금씩 밀린다.
48
+ */
49
+ const demandPerHour = hoursPerWeek > 0 ? (input.unitsPerDay * daysPerWeek) / hoursPerWeek : 0;
50
+ /* 축별 공급 — 등급 이름으로 센다. 사람은 자격을 여럿 가질 수 있어 등급 간 합이 인원수를 넘는다
51
+ (같은 사람이 두 줄에 선다). 동시에 두 공정을 하지는 못하므로 이 계산은 **낙관적**이다. */
52
+ const equipmentByKind = new Map();
53
+ for (const e of input.equipment ?? []) {
54
+ const list = equipmentByKind.get(e.kind) ?? [];
55
+ list.push(e);
56
+ equipmentByKind.set(e.kind, list);
57
+ }
58
+ const countByClass = (rows, field) => {
59
+ const out = new Map();
60
+ for (const r of rows ?? [])
61
+ for (const c of r[field] ?? [])
62
+ out.set(c, (out.get(c) ?? 0) + 1);
63
+ return out;
64
+ };
65
+ const personsByClass = countByClass(input.persons, 'personnelClassIds');
66
+ const assetsByClass = countByClass(input.assets, 'assetClassIds');
67
+ const slotsByLocationType = new Map();
68
+ for (const l of input.locations ?? [])
69
+ if (l.type)
70
+ slotsByLocationType.set(l.type, (slotsByLocationType.get(l.type) ?? 0) + Math.max(l.capacity ?? 1, 1));
71
+ const order = input.route?.length
72
+ ? input.route.map(k => input.operations.find(o => o.key === k)).filter((o) => !!o)
73
+ : [...input.operations];
74
+ /* 하류 수율을 거슬러 올라가며 소요량을 부풀린다 — 도장에서 5% 를 잃으면 그 앞은 더 만들어야 한다. */
75
+ let downstream = 1;
76
+ const reversed = [];
77
+ for (const op of [...order].reverse()) {
78
+ const cycleHours = isoDurationHours(op.duration) + isoDurationHours(paramOf(op, 'setupDuration'));
79
+ downstream *= Number(paramOf(op, 'yield') ?? 1);
80
+ const requiredPerHour = downstream > 0 ? demandPerHour / downstream : Infinity;
81
+ const requirements = [];
82
+ const add = (axis, className, quantity, available, availability) => {
83
+ const q = Math.max(quantity, 1);
84
+ requirements.push({
85
+ axis, className, quantity: q, available, availability,
86
+ perHour: cycleHours > 0 ? (Math.floor(available / q) / cycleHours) * availability : Infinity
87
+ });
88
+ };
89
+ /* 설비 — 표준 EquipmentSpecification(등급+대수). 그것이 없으면 예전 표기(resourceType 한 대). */
90
+ const equipSpecs = op.equipmentSpecification?.length
91
+ ? op.equipmentSpecification.map(s => ({ className: s.equipmentClass ?? op.resourceType ?? '', quantity: s.quantity }))
92
+ : op.resourceType ? [{ className: op.resourceType, quantity: 1 }] : [];
93
+ for (const s of equipSpecs) {
94
+ if (!s.className)
95
+ continue;
96
+ const records = equipmentByKind.get(s.className) ?? [];
97
+ add('equipment', s.className, s.quantity, records.length, availabilityOf(records));
98
+ }
99
+ for (const s of op.personnelSpecification ?? [])
100
+ if (s.personnelClass)
101
+ add('personnel', s.personnelClass, s.quantity, personsByClass.get(s.personnelClass) ?? 0, 1);
102
+ for (const s of op.physicalAssetSpecification ?? [])
103
+ if (s.assetClass)
104
+ add('asset', s.assetClass, s.quantity, assetsByClass.get(s.assetClass) ?? 0, 1);
105
+ if (op.locationType)
106
+ add('location', op.locationType, 1, slotsByLocationType.get(op.locationType) ?? 0, 1);
107
+ /* 공정의 능력 = 요구들 중 가장 낮은 것. 전량 확보 규칙이라 하나만 모자라도 그만큼만 처리된다. */
108
+ const constraint = requirements.length ? requirements.reduce((a, b) => (a.perHour <= b.perHour ? a : b)) : undefined;
109
+ const perHour = constraint ? constraint.perHour : Infinity;
110
+ reversed.push({ operation: op.key, cycleHours, perHour, requiredPerHour, ok: perHour >= requiredPerHour, constraint, requirements });
111
+ }
112
+ const operations = reversed.reverse();
113
+ /* 병목 = 여유가 가장 적은 공정. 라인 전체의 상한은 그 공정이 정한다. */
114
+ const tightest = operations.length
115
+ ? operations.reduce((a, b) => (a.perHour / a.requiredPerHour <= b.perHour / b.requiredPerHour ? a : b))
116
+ : undefined;
117
+ const headroom = operations.length ? Math.min(...operations.map(o => o.perHour / o.requiredPerHour)) : Infinity;
118
+ return {
119
+ workingHoursPerWeek: hoursPerWeek,
120
+ workingDaysPerWeek: daysPerWeek,
121
+ demandPerHour,
122
+ operations,
123
+ ...(tightest ? { bottleneck: { operation: tightest.operation, axis: tightest.constraint?.axis, className: tightest.constraint?.className } } : {}),
124
+ maxUnitsPerDay: input.unitsPerDay * headroom,
125
+ ok: operations.every(o => o.ok)
126
+ };
127
+ }
@@ -481,7 +481,7 @@ export class EmsKernel extends FlowEngine {
481
481
  /*
482
482
  * ── 「사실」이라 말할 수 있는 조건은 **둘을 다 아는 것**이다 (2026-08-28, 고침) ─
483
483
  *
484
- * 앞 판은 `since ? 'declared' : 'inferred'` 였다. 그래서 **기준점을 뒤늦게 알게 되는 원본**에서
484
+ * 앞 버전은 `since ? 'declared' : 'inferred'` 였다. 그래서 **기준점을 뒤늦게 알게 되는 원본**에서
485
485
  * 첫 되돌아감이 「짐작인데 사실로」 기록됐다 — 인티그레이션 레인이 짚었다.
486
486
  *
487
487
  * 표본 1..N 기준점 없음
@@ -501,7 +501,7 @@ export class EmsKernel extends FlowEngine {
501
501
  /*
502
502
  * ── 종류를 알면 기준점 없이도 경계를 안다 (2026-08-28) ─────────────────────
503
503
  *
504
- * 앞 판은 `since` 만 보았다. 그래서 하루 누적을 선언한 원본이 기준점을 주지 않으면 매일 자정이
504
+ * 앞 버전은 `since` 만 보았다. 그래서 하루 누적을 선언한 원본이 기준점을 주지 않으면 매일 자정이
505
505
  * 계기 교체로 기록됐다 — 종류를 말해 주었는데도.
506
506
  *
507
507
  * 그리고 **같은 날 안에서** 줄어든 것은 종류가 무엇이든 이상이다: 하루 누적의 경계는 자정이고,
@@ -1603,7 +1603,7 @@ export class EmsKernel extends FlowEngine {
1603
1603
  /*
1604
1604
  * ── 발전 기간도 **시계로** 마감한다 (2026-08-30) ───────────────────────────
1605
1605
  *
1606
- * 앞 판은 새 표본이 올 때만 날짜가 바뀐 것을 알아챘다. 그런데 태양광은 해가 지면 값을 보내지
1606
+ * 앞 버전은 새 표본이 올 때만 날짜가 바뀐 것을 알아챘다. 그런데 태양광은 해가 지면 값을 보내지
1607
1607
  * 않는다 — 어제 마지막 표본이 19:40 이면 어제 하루치가 **다음 날 아침 첫 표본**에야 확정된다.
1608
1608
  * 밤새 「어제 얼마 냈나」에 답이 없다.
1609
1609
  *
@@ -7,8 +7,7 @@ import type { AllocationPolicy, SlotView } from './allocation-policy.ts';
7
7
  import { type FoldedOrders, type OrderFoldPolicy } from '@operato/ops-contract';
8
8
  import type { DurationEstimator, DurationContext } from './duration-estimator.ts';
9
9
  import type { OperationDef, IsoDuration, OpMaterialSpecification } from '@operato/ops-contract';
10
- import { type CapacityAnalysis } from '@operato/ops-contract';
11
- import { type CommittedDemand, type OperationsCapabilityReport } from '@operato/ops-contract';
10
+ import type { CapacityAnalysis, CommittedDemand, OperationsCapabilityReport } from '@operato/ops-contract';
12
11
  export interface FlowLocation {
13
12
  id: string;
14
13
  type: string;
@@ -1429,7 +1428,7 @@ export declare abstract class FlowEngine implements TwinKernel {
1429
1428
  *
1430
1429
  * ── 왜 여기인가 ────────────────────────────────────────────────────────────
1431
1430
  * 부르는 자리 하나를 막으면 다른 자리에서 같은 일이 난다 — `emitOrder` 를 부르는 곳만 열다섯이다.
1432
- * 그리고 `revision` 이 여기서 오르므로, 여기서 막지 않으면 **적지 않고도 판만 올라간다.**
1431
+ * 그리고 `revision` 이 여기서 오르므로, 여기서 막지 않으면 **적지 않고도 버전만 올라간다.**
1433
1432
  *
1434
1433
  * ── 무엇을 같다고 보나 ─────────────────────────────────────────────────────
1435
1434
  * `data` 가 바이트까지 같으면 같다. 시각은 `data` 에 없다(여기서 붙인다) — 그래서 「같은 사실을
@@ -9,7 +9,7 @@
9
9
  * 통합 타입은 도메인 필드를 옵셔널로 넓혀(FlowItem.gtin?, FlowOrder.shipmentEpc? 등) 두 도메인을 담는다.
10
10
  * (roadmap Phase5 발견 → 추출. [[project_flow_single_base_vision]] FlowLocation 단일 base 방향과 정합.)
11
11
  */
12
- import { isWorkShiftExecutionBasis } from '@operato/ops-contract';
12
+ import { isTaskTerminal, isWorkShiftExecutionBasis } from '@operato/ops-contract';
13
13
  import { OP_EVENT, CMD, USE_UOM, locationStatusOf, readBoardEquipment, equipmentClassMembership, readBoardLocations, readBoardAssets, classClosure, capabilityOf, requiredTestsFor, priorityRank, dueStatusOf, isOrderTerminal, effectivityAt, offCalendarAt, offCalendarReasonAt, minuteOfDayAt, activeShiftAt, subLotIdOf, itemKeyOf, itemClassOf, identityGroundingOf, outsideLimit, computeOee } from '@operato/ops-contract';
14
14
  import { ObservedReducer } from "./observed-reducer.js";
15
15
  /* 주체를 정하는 규칙은 유입 문과 한 벌이다 — 두 곳에 적으면 한쪽만 고쳐진다. */
@@ -17,11 +17,12 @@ import { resolveSubject } from '@operato/ops-contract';
17
17
  import { WMS_ORDER_KIND } from '@operato/ops-contract';
18
18
  import { transformationEvent, aggregationEvent, objectEvent, parseEpc, DISP, ILMD_ATTR, CBV_BIZSTEP, PRIVATE_BIZSTEP, objectUri, bizTransactionUri, gdtiUri } from '@operato/ops-contract';
19
19
  import { allocationPolicyOf } from "./allocation-policy.js";
20
- import { ORDER_FOLD_DEFAULT, emptyFoldedOrders, foldOrdersInto, foldedOrderCount, pruneFoldedHours, orderFoldPolicyOf, planOrderFold } from '@operato/ops-contract';
20
+ import { ORDER_FOLD_DEFAULT, foldedOrderCount, orderFoldPolicyOf } from '@operato/ops-contract';
21
+ import { emptyFoldedOrders, foldOrdersInto, planOrderFold, pruneFoldedHours } from "./order-fold.js";
21
22
  import { OP_PARAM } from '@operato/ops-contract';
22
23
  import { parseIsoDuration } from '@operato/ops-contract';
23
- import { analyzeCapacity } from '@operato/ops-contract';
24
- import { operationsCapabilityOf } from '@operato/ops-contract';
24
+ import { analyzeCapacity } from "./capacity.js";
25
+ import { operationsCapabilityOf } from "./operations-capability.js";
25
26
  /* 에너지 상태 필드는 **능력 선언에서 뽑는다** — 손으로 적으면 능력에 필드를 더한 날 스냅샷이 빠진다. */
26
27
  import { stateFieldsOf } from '@operato/ops-contract';
27
28
  const BASE_EPOCH = Date.parse('2026-01-01T00:00:00Z');
@@ -1431,7 +1432,7 @@ export class FlowEngine {
1431
1432
  */
1432
1433
  const filtering = purpose === 'seed';
1433
1434
  for (const t of snap.tasks ?? []) {
1434
- if (filtering && t.status === 'completed') {
1435
+ if (filtering && isTaskTerminal(t)) {
1435
1436
  droppedCompleted++;
1436
1437
  continue;
1437
1438
  }
@@ -2913,7 +2914,7 @@ export class FlowEngine {
2913
2914
  slotViews(locationType) {
2914
2915
  const reserved = new Map();
2915
2916
  for (const t of this.tasks.values())
2916
- if (t.status !== 'completed')
2917
+ if (!isTaskTerminal(t))
2917
2918
  reserved.set(t.toNode, (reserved.get(t.toNode) ?? 0) + 1);
2918
2919
  const views = [];
2919
2920
  for (const n of this.locations.values())
@@ -3011,7 +3012,7 @@ export class FlowEngine {
3011
3012
  *
3012
3013
  * ── 왜 여기인가 ────────────────────────────────────────────────────────────
3013
3014
  * 부르는 자리 하나를 막으면 다른 자리에서 같은 일이 난다 — `emitOrder` 를 부르는 곳만 열다섯이다.
3014
- * 그리고 `revision` 이 여기서 오르므로, 여기서 막지 않으면 **적지 않고도 판만 올라간다.**
3015
+ * 그리고 `revision` 이 여기서 오르므로, 여기서 막지 않으면 **적지 않고도 버전만 올라간다.**
3015
3016
  *
3016
3017
  * ── 무엇을 같다고 보나 ─────────────────────────────────────────────────────
3017
3018
  * `data` 가 바이트까지 같으면 같다. 시각은 `data` 에 없다(여기서 붙인다) — 그래서 「같은 사실을
package/dist/index.d.ts CHANGED
@@ -8,6 +8,9 @@ export * from './duration-estimator.ts';
8
8
  export * from './observed-reducer.ts';
9
9
  export * from './state-projector.ts';
10
10
  export * from './task-fold.ts';
11
+ export * from './order-fold.ts';
12
+ export * from './capacity.ts';
13
+ export * from './operations-capability.ts';
11
14
  export * from './job-response.ts';
12
15
  export * from './runtime.ts';
13
16
  export * from './flow-engine.ts';
package/dist/index.js CHANGED
@@ -22,6 +22,9 @@ export * from "./duration-estimator.js";
22
22
  export * from "./observed-reducer.js";
23
23
  export * from "./state-projector.js";
24
24
  export * from "./task-fold.js";
25
+ export * from "./order-fold.js";
26
+ export * from "./capacity.js";
27
+ export * from "./operations-capability.js";
25
28
  export * from "./job-response.js";
26
29
  export * from "./runtime.js";
27
30
  export * from "./flow-engine.js";
@@ -1,7 +1,8 @@
1
1
  import type { ISOTime, MaterialActual } from '@operato/ops-contract';
2
2
  import { type TaskDeltaRow } from './task-fold.ts';
3
3
  /** 표준 `JobState` — 우리 작업 상태를 표준 낱말로 옮긴다. */
4
- export type JobState = 'ready' | 'running' | 'completed';
4
+ /** ISA-95 JobResponse 의 상태 중 우리가 아는 것 — 취소된 작업은 `aborted`(2026-11-19). */
5
+ export type JobState = 'ready' | 'running' | 'completed' | 'aborted';
5
6
  /** 자원 실적 한 줄 — 표준 `OpPersonnelActualType`/`OpEquipmentActualType` 의 우리 부분집합. */
6
7
  export interface ResourceActual {
7
8
  /** 표준 `PersonID`/`EquipmentID`. */
@@ -38,7 +38,7 @@ export function foldJobResponses(rows) {
38
38
  }
39
39
  return records.map(rec => {
40
40
  const x = extra.get(rec.taskId) ?? {};
41
- const jobState = rec.completedMs !== undefined ? 'completed' : rec.startedMs !== undefined ? 'running' : 'ready';
41
+ const jobState = rec.completedMs !== undefined ? 'completed' : rec.cancelledMs !== undefined ? 'aborted' : rec.startedMs !== undefined ? 'running' : 'ready';
42
42
  const one = (ids) => ids?.length ? ids.map(id => ({ id, quantity: 1 })) : undefined;
43
43
  return {
44
44
  id: rec.taskId,
@@ -46,7 +46,7 @@ export function foldJobResponses(rows) {
46
46
  ...(rec.facets.kind ? { workType: rec.facets.kind } : {}),
47
47
  jobState,
48
48
  ...(iso(rec.startedMs) ? { startTime: iso(rec.startedMs) } : {}),
49
- ...(iso(rec.completedMs) ? { endTime: iso(rec.completedMs) } : {}),
49
+ ...(iso(rec.completedMs ?? rec.cancelledMs) ? { endTime: iso(rec.completedMs ?? rec.cancelledMs) } : {}),
50
50
  ...(one(x.personnel) ? { personnelActual: one(x.personnel) } : {}),
51
51
  ...(one(x.resources) ? { equipmentActual: one(x.resources) } : {}),
52
52
  ...(one(x.assets) ? { physicalAssetActual: one(x.assets) } : {}),
package/dist/kernel.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * 입고: 도착 → receiving(Txn PO + Agg 팔레트←케이스 + Object) → putaway → storing.
6
6
  * 출고: SO 오더 → 할당(Txn SO) → pick(bin→staging) → picking → packing(Agg 화물←팔레트) → staging → shipping(DELETE).
7
7
  */
8
- import { CMD } from '@operato/ops-contract';
8
+ import { CMD, isTaskTerminal } from '@operato/ops-contract';
9
9
  import { firstFitPolicy } from "./allocation-policy.js";
10
10
  import { FlowEngine, allocatedQty } from "./flow-engine.js";
11
11
  import { planMakeToOrder } from "./make-to-order.js";
@@ -310,7 +310,7 @@ export class WmsKernel extends FlowEngine {
310
310
  /** 이 오더가 실행 중인 생산 사슬이 있나 — 이송·가공·되돌리기 중 하나라도 열려 있으면 그렇다. */
311
311
  hasOpenMakeChain(orderId) {
312
312
  for (const t of this.tasks.values()) {
313
- if (t.orderId !== orderId || t.status === 'completed')
313
+ if (t.orderId !== orderId || isTaskTerminal(t))
314
314
  continue;
315
315
  if (t.kind === 'feed' || t.intent === 'process')
316
316
  return true;
@@ -94,7 +94,7 @@ export declare class MesKernel extends FlowEngine {
94
94
  * 은 스스로 「자재 반입→보관→공정 변환→완제품 반출 … 양끝 야드 물류(YMS·WMS·MES)」라 말한다 —
95
95
  * **한 선언이 사이트 전체를 덮고, 도메인마다 다른 트윈이 그 일부를 지난다.**
96
96
  *
97
- * 그래서 MES 판(여섯 노드)이 `receive`→`dock-door` · `park`→`yard-slot` · `dispatch`→`gate` 때문에
97
+ * 그래서 MES 버전(여섯 노드)이 `receive`→`dock-door` · `park`→`yard-slot` · `dispatch`→`gate` 때문에
98
98
  * **아예 열리지 않았다.** 셋 다 이 트윈이 지나지 않는 공정이다. 없는 사정을 상상하지 말라던 규율을
99
99
  * 지키려다, **있는 사정을 못 본 채로** 검사를 넓힌 것이 잘못이었다.
100
100
  *
@@ -256,7 +256,7 @@ export class MesKernel extends FlowEngine {
256
256
  * 은 스스로 「자재 반입→보관→공정 변환→완제품 반출 … 양끝 야드 물류(YMS·WMS·MES)」라 말한다 —
257
257
  * **한 선언이 사이트 전체를 덮고, 도메인마다 다른 트윈이 그 일부를 지난다.**
258
258
  *
259
- * 그래서 MES 판(여섯 노드)이 `receive`→`dock-door` · `park`→`yard-slot` · `dispatch`→`gate` 때문에
259
+ * 그래서 MES 버전(여섯 노드)이 `receive`→`dock-door` · `park`→`yard-slot` · `dispatch`→`gate` 때문에
260
260
  * **아예 열리지 않았다.** 셋 다 이 트윈이 지나지 않는 공정이다. 없는 사정을 상상하지 말라던 규율을
261
261
  * 지키려다, **있는 사정을 못 본 채로** 검사를 넓힌 것이 잘못이었다.
262
262
  *
@@ -22,10 +22,11 @@
22
22
  import { computeOee, isWorkShiftExecutionBasis } from '@operato/ops-contract';
23
23
  import { OP_EVENT, capabilityOf, itemKeyOf, judgeAgainstSpec, requiredTestsFor, locationStatusOf, readBoardEquipment, readBoardLocations, readBoardAssets, effectivityAt, offCalendarAt, offCalendarReasonAt, activeShiftAt } from '@operato/ops-contract';
24
24
  import { ILMD_ATTR, parseEpc, referencedLocationIds } from '@operato/ops-contract';
25
- import { emptyFoldedOrders, foldOrdersInto, foldedOrderCount, pruneFoldedHours, isOrderTerminal, orderFoldPolicyOf, planOrderFold, standsNewOrderRow } from '@operato/ops-contract';
25
+ import { foldedOrderCount, isOrderTerminal, orderFoldPolicyOf } from '@operato/ops-contract';
26
26
  import { expiryFromAttributes, lotFromAttributes } from '@operato/ops-contract';
27
27
  /* 클래스 마스터 표는 상태를 들므로 커널에 있다(§`class-master-table`). */
28
28
  import { ClassMasterTable } from "./class-master-table.js";
29
+ import { emptyFoldedOrders, foldOrdersInto, planOrderFold, pruneFoldedHours, standsNewOrderRow } from "./order-fold.js";
29
30
  /**
30
31
  * 투영이 들고 있는 물품 — **계약(ItemState)을 축소하지 않는다.**
31
32
  *
@@ -0,0 +1,8 @@
1
+ import { type OperationsCapabilityInput, type OperationsCapabilityReport } from '@operato/ops-contract';
2
+ /**
3
+ * 생산 능력 보고서 — 있는 용량 분석 위에 **구간 · 종류 · 약정**을 올린다.
4
+ *
5
+ * 용량 분석을 두 번 부른다(전량 · 가용). 같은 함수를 두 번 부르는 것이 요점이다: 달성불가를 따로
6
+ * 계산하면 규칙이 두 벌이 되고, 두 벌은 어긋난다.
7
+ */
8
+ export declare function operationsCapabilityOf(input: OperationsCapabilityInput): OperationsCapabilityReport;
@@ -0,0 +1,78 @@
1
+ /*
2
+ * 생산 능력 보고서(ISA-95 Part 4 `OperationsCapability`)를 짓는다 — 표준 열거형과 보고서 모양은
3
+ * `@operato/ops-contract` 의 `operations-capability.ts` 에 있고, 그 머리 주석이 이 보고서의 뜻을 설명한다.
4
+ * 짓는 일은 용량 분석을 두 번 부르는 엔진의 판정이라 여기 둔다(2026-11-19 계약에서 이동).
5
+ */
6
+ import { workingHoursBetween } from '@operato/ops-contract';
7
+ import { analyzeCapacity } from "./capacity.js";
8
+ /**
9
+ * 생산 능력 보고서 — 있는 용량 분석 위에 **구간 · 종류 · 약정**을 올린다.
10
+ *
11
+ * 용량 분석을 두 번 부른다(전량 · 가용). 같은 함수를 두 번 부르는 것이 요점이다: 달성불가를 따로
12
+ * 계산하면 규칙이 두 벌이 되고, 두 벌은 어긋난다.
13
+ */
14
+ export function operationsCapabilityOf(input) {
15
+ const fromMs = Date.parse(input.window.fromTime);
16
+ const toMs = Date.parse(input.window.toTime);
17
+ if (!Number.isFinite(fromMs) || !Number.isFinite(toMs)) {
18
+ throw new Error(`능력의 구간을 읽을 수 없다: ${input.window.fromTime} ~ ${input.window.toTime}`);
19
+ }
20
+ if (toMs <= fromMs)
21
+ throw new Error(`능력의 구간이 뒤집혔다: ${input.window.fromTime} ~ ${input.window.toTime}`);
22
+ const workingHours = workingHoursBetween(input.calendar ?? input.capacity.calendar, fromMs, toMs, input.utcOffsetMinutes);
23
+ const full = analyzeCapacity(input.capacity);
24
+ const usable = input.usableCapacity ? analyzeCapacity(input.usableCapacity) : undefined;
25
+ /** 비율(시간당) → 구간의 양. 상한이 무한(요구가 없는 공정)이면 **모른다**. */
26
+ const amountOf = (perHour) => (Number.isFinite(perHour) ? perHour * workingHours : null);
27
+ const committedOf = (operation) => {
28
+ let sum = 0;
29
+ for (const d of input.demands ?? []) {
30
+ if (d.operation !== undefined && d.operation !== operation)
31
+ continue;
32
+ /* 납기가 없으면 이 구간의 약정이 아니다 — 짐작해서 넣으면 남은 능력이 실제보다 적게 보인다. */
33
+ if (!d.dueTime)
34
+ continue;
35
+ const due = Date.parse(d.dueTime);
36
+ if (!Number.isFinite(due) || due < fromMs || due >= toMs)
37
+ continue;
38
+ sum += Math.max(0, d.remaining);
39
+ }
40
+ return sum;
41
+ };
42
+ const perOperation = full.operations.map(op => {
43
+ const total = amountOf(op.perHour);
44
+ const committed = committedOf(op.operation);
45
+ /*
46
+ * 달성불가 = 전량 기준 − 가용 자원 기준. 자원의 현재 사실을 못 받았으면 **모른다**(0 이 아니다).
47
+ * 음수가 되는 일은 없어야 하지만(가용 ⊆ 전량), 되면 그것을 감추지 않고 0 으로 깎는다 — 부분집합이
48
+ * 아닌 입력을 받은 것이므로 값을 지어내는 대신 아래 `available` 이 어긋남을 드러낸다.
49
+ */
50
+ let unattainable = null;
51
+ let unattainableBy;
52
+ if (usable) {
53
+ const left = usable.operations.find(o => o.operation === op.operation);
54
+ const usableAmount = amountOf(left?.perHour ?? NaN);
55
+ unattainable = total != null && usableAmount != null ? Math.max(0, total - usableAmount) : null;
56
+ /* 잃은 몫이 있을 때만 원인을 말한다 — 잃은 것이 없는데 "여기부터" 라고 하면 없는 일을 만든다. */
57
+ if (unattainable != null && unattainable > 0 && left?.constraint)
58
+ unattainableBy = left.constraint;
59
+ }
60
+ const available = total == null || unattainable == null ? null : total - committed - unattainable;
61
+ return {
62
+ operation: op.operation,
63
+ total,
64
+ committed,
65
+ unattainable,
66
+ available,
67
+ ...(op.constraint ? { constraint: op.constraint } : {}),
68
+ ...(unattainableBy ? { unattainableBy } : {})
69
+ };
70
+ });
71
+ return {
72
+ operationsType: input.operationsType ?? 'Production',
73
+ window: { fromTime: input.window.fromTime, toTime: input.window.toTime, workingHours },
74
+ perOperation,
75
+ ...(full.bottleneck ? { bottleneck: full.bottleneck } : {}),
76
+ ...(input.publishedDate ? { publishedDate: input.publishedDate } : {})
77
+ };
78
+ }
@@ -0,0 +1,31 @@
1
+ import { type FoldableOrderView, type FoldedOrders, type OrderFoldPolicy } from '@operato/ops-contract';
2
+ export declare function emptyFoldedOrders(): FoldedOrders;
3
+ /**
4
+ * **이번에 접을 오더** — id 목록을 돌려준다(순서는 오래된 종결부터).
5
+ *
6
+ * · 열린 오더는 접지 않는다(`isOrderTerminal` 한 곳이 판정한다).
7
+ * · 보류(`held`)된 오더는 끝났어도 접지 않는다 — 제어판이 재개하려고 들고 있다.
8
+ * · 종결 시각을 모르는 오더는 접지 않는다 — 언제 끝났는지 지어내지 않는다. 두 구동은 종결을 볼 때 시각을 적는다.
9
+ * · 시간: 종결된 지 `afterMs` 가 지났으면 접는다.
10
+ * · 건수: 그러고도 뜨거운 종결 오더가 `maxTerminal` 보다 많으면 오래된 것부터 더 접는다.
11
+ */
12
+ export declare function planOrderFold(orders: readonly FoldableOrderView[], nowMs: number, policy?: OrderFoldPolicy): string[];
13
+ /** 접은 오더를 세는 수에 더한다 — 새 값을 돌려준다(들어온 것을 바꾸지 않는다). */
14
+ export declare function foldOrdersInto(folded: FoldedOrders | null | undefined, orders: readonly FoldableOrderView[]): FoldedOrders;
15
+ /**
16
+ * **뜨거운 줄이 없는 오더의 레코드가 새 줄을 세우나.**
17
+ *
18
+ * 폴링 원본은 같은 종결을 다시 보낸다. 접힌 오더의 종결이 다시 오면 줄이 다시 서고 다음 경계에서 또 접혀 세는 수가 두 번
19
+ * 는다. 그래서 **종결 레코드이고, 그 레코드 자신의 시각이 경계보다 이르면** 줄을 세우지 않는다(결정 2).
20
+ *
21
+ * 비교하는 시각은 레코드의 `eventTime` 이다 — 도착 시각으로 재면 늦게 온 정당한 종결이 접힌 것으로 오인된다(판정 조건 1).
22
+ * 종결이 아닌 레코드(재개)는 새 뜨거운 줄이다 — 드물고 맞는 거동이라 막지 않는다. 이미 뜨거운 줄이 있는 오더의 레코드는
23
+ * 이 판정을 지나지 않는다(그것은 그 줄의 갱신이다).
24
+ */
25
+ export declare function standsNewOrderRow(record: {
26
+ status?: string;
27
+ requested?: number;
28
+ fulfilled?: number;
29
+ }, eventTimeMs: number | undefined, folded: FoldedOrders | null | undefined): boolean;
30
+ /** 창 밖 칸을 버린다 — 접을 때 부른다. 새 값을 돌려준다. */
31
+ export declare function pruneFoldedHours(folded: FoldedOrders, nowMs: number, policy?: OrderFoldPolicy): FoldedOrders;
@@ -0,0 +1,81 @@
1
+ /*
2
+ * **끝난 오더를 접는다** — ADR-0092. 접는 판정은 시뮬(`FlowEngine`)과 미러(`ObservedReducer`)가 함께 부르는 엔진의 일이라
3
+ * 여기 둔다(2026-11-19 계약에서 이동). 한쪽만 다르게 접으면 적합성 하네스가 어긋남으로 잡는다(결정 4). 경계의 선언과 접힌 쪽의
4
+ * 모양, 화면 · 호스트가 읽는 수는 `@operato/ops-contract` 의 `order-fold.ts` 에 남는다.
5
+ */
6
+ import { finishedWindowStartMs, hourStartOf, isOrderTerminal, ORDER_FOLD_DEFAULT } from '@operato/ops-contract';
7
+ export function emptyFoldedOrders() {
8
+ return { counts: {}, boundaryMs: null };
9
+ }
10
+ /**
11
+ * **이번에 접을 오더** — id 목록을 돌려준다(순서는 오래된 종결부터).
12
+ *
13
+ * · 열린 오더는 접지 않는다(`isOrderTerminal` 한 곳이 판정한다).
14
+ * · 보류(`held`)된 오더는 끝났어도 접지 않는다 — 제어판이 재개하려고 들고 있다.
15
+ * · 종결 시각을 모르는 오더는 접지 않는다 — 언제 끝났는지 지어내지 않는다. 두 구동은 종결을 볼 때 시각을 적는다.
16
+ * · 시간: 종결된 지 `afterMs` 가 지났으면 접는다.
17
+ * · 건수: 그러고도 뜨거운 종결 오더가 `maxTerminal` 보다 많으면 오래된 것부터 더 접는다.
18
+ */
19
+ export function planOrderFold(orders, nowMs, policy = ORDER_FOLD_DEFAULT) {
20
+ const candidates = orders
21
+ .filter(o => isOrderTerminal(o) && !o.held && typeof o.terminalAtMs === 'number' && Number.isFinite(o.terminalAtMs))
22
+ .sort((a, b) => a.terminalAtMs - b.terminalAtMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
23
+ const cutoff = nowMs - policy.afterMs;
24
+ const byTime = candidates.filter(o => o.terminalAtMs <= cutoff);
25
+ const stay = candidates.length - byTime.length;
26
+ const byCount = stay > policy.maxTerminal ? candidates.slice(byTime.length, byTime.length + (stay - policy.maxTerminal)) : [];
27
+ return [...byTime, ...byCount].map(o => o.id);
28
+ }
29
+ /** 접은 오더를 세는 수에 더한다 — 새 값을 돌려준다(들어온 것을 바꾸지 않는다). */
30
+ export function foldOrdersInto(folded, orders) {
31
+ const out = {
32
+ counts: Object.fromEntries(Object.entries(folded?.counts ?? {}).map(([k, v]) => [k, { ...v }])),
33
+ boundaryMs: folded?.boundaryMs ?? null
34
+ };
35
+ const hours = Object.fromEntries(Object.entries(folded?.hours ?? {}).map(([h, byKind]) => [h, Object.fromEntries(Object.entries(byKind).map(([k, v]) => [k, { ...v }]))]));
36
+ for (const o of orders) {
37
+ const kind = String(o.kind ?? '');
38
+ const status = String(o.status ?? '');
39
+ const byStatus = (out.counts[kind] ??= {});
40
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
41
+ if (typeof o.terminalAtMs === 'number' && Number.isFinite(o.terminalAtMs)) {
42
+ out.boundaryMs = out.boundaryMs === null ? o.terminalAtMs : Math.max(out.boundaryMs, o.terminalAtMs);
43
+ const slot = ((hours[String(hourStartOf(o.terminalAtMs))] ??= {})[kind] ??= {});
44
+ slot[status] = (slot[status] ?? 0) + 1;
45
+ }
46
+ }
47
+ if (Object.keys(hours).length)
48
+ out.hours = hours;
49
+ return out;
50
+ }
51
+ /**
52
+ * **뜨거운 줄이 없는 오더의 레코드가 새 줄을 세우나.**
53
+ *
54
+ * 폴링 원본은 같은 종결을 다시 보낸다. 접힌 오더의 종결이 다시 오면 줄이 다시 서고 다음 경계에서 또 접혀 세는 수가 두 번
55
+ * 는다. 그래서 **종결 레코드이고, 그 레코드 자신의 시각이 경계보다 이르면** 줄을 세우지 않는다(결정 2).
56
+ *
57
+ * 비교하는 시각은 레코드의 `eventTime` 이다 — 도착 시각으로 재면 늦게 온 정당한 종결이 접힌 것으로 오인된다(판정 조건 1).
58
+ * 종결이 아닌 레코드(재개)는 새 뜨거운 줄이다 — 드물고 맞는 거동이라 막지 않는다. 이미 뜨거운 줄이 있는 오더의 레코드는
59
+ * 이 판정을 지나지 않는다(그것은 그 줄의 갱신이다).
60
+ */
61
+ export function standsNewOrderRow(record, eventTimeMs, folded) {
62
+ if (!isOrderTerminal(record))
63
+ return true;
64
+ const boundary = folded?.boundaryMs;
65
+ if (boundary === null || boundary === undefined)
66
+ return true;
67
+ if (typeof eventTimeMs !== 'number' || !Number.isFinite(eventTimeMs))
68
+ return true;
69
+ return eventTimeMs > boundary;
70
+ }
71
+ /** 창 밖 칸을 버린다 — 접을 때 부른다. 새 값을 돌려준다. */
72
+ export function pruneFoldedHours(folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
73
+ if (!folded.hours)
74
+ return folded;
75
+ const start = finishedWindowStartMs(nowMs, policy);
76
+ const kept = Object.fromEntries(Object.entries(folded.hours).filter(([h]) => Number(h) >= start));
77
+ const out = { counts: folded.counts, boundaryMs: folded.boundaryMs };
78
+ if (Object.keys(kept).length)
79
+ out.hours = kept;
80
+ return out;
81
+ }
@@ -43,6 +43,8 @@ export interface TaskRecord {
43
43
  startedMs?: number;
44
44
  /** 완료 시각. **나중** 것 — 완료는 종결 상태라 작업당 하나이고 재전송이면 나중 것이 사실이다. */
45
45
  completedMs?: number;
46
+ /** 취소 시각(2026-11-19). 완료가 아니다 — 성과 폴드의 작업 시간에 들어가지 않고, 실적은 `aborted` 다. */
47
+ cancelledMs?: number;
46
48
  facets: TaskFacets;
47
49
  }
48
50
  export interface TaskFoldResult {
package/dist/task-fold.js CHANGED
@@ -58,6 +58,8 @@ export function foldTaskRecords(rows) {
58
58
  rec.startedMs = rec.startedMs != null ? Math.min(rec.startedMs, at) : at;
59
59
  else if (d.status === 'completed')
60
60
  rec.completedMs = rec.completedMs != null ? Math.max(rec.completedMs, at) : at;
61
+ else if (d.status === 'cancelled')
62
+ rec.cancelledMs = rec.cancelledMs != null ? Math.max(rec.cancelledMs, at) : at;
61
63
  }
62
64
  return { records: [...byTask.values()], rowsRead, latestMs };
63
65
  }
@@ -15,7 +15,7 @@
15
15
  * - drop(기본): 트레일러를 야드 슬롯에 내려놓고(주차) 창 도래 시 호슬러가 도크로 pull. 야드 버퍼 사용.
16
16
  * - live: 게이트에서 대기하다 창 도래 시 도크로 직행(야드 미경유). 게이트/도크를 더 오래 점유.
17
17
  */
18
- import { itemKeyOf } from '@operato/ops-contract';
18
+ import { isTaskTerminal, itemKeyOf } from '@operato/ops-contract';
19
19
  import { firstFitPolicy } from "./allocation-policy.js";
20
20
  import { FlowEngine } from "./flow-engine.js";
21
21
  import { DISP, objectEvent, transactionEvent } from '@operato/ops-contract';
@@ -130,7 +130,7 @@ export class YmsKernel extends FlowEngine {
130
130
  }
131
131
  return;
132
132
  }
133
- const inflight = [...this.tasks.values()].some(t => t.status !== 'completed' && t.toNode === door.id);
133
+ const inflight = [...this.tasks.values()].some(t => !isTaskTerminal(t) && t.toNode === door.id);
134
134
  if (door.occupancy > 0 || inflight)
135
135
  return; // 도어 사용중/예약됨 → 대기(직렬화)
136
136
  const mode = this.apptMode.get(o.id) ?? 'drop';