@operato/twin-kernel 0.11.31 → 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
+ }
@@ -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;
@@ -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())
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;
@@ -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';
@@ -41,6 +41,7 @@ __export(index_exports, {
41
41
  allocatedEpcs: () => allocatedEpcs,
42
42
  allocatedQty: () => allocatedQty,
43
43
  allocationPolicyOf: () => allocationPolicyOf,
44
+ analyzeCapacity: () => analyzeCapacity,
44
45
  attributeEnergy: () => attributeEnergy,
45
46
  compareStates: () => compareStates,
46
47
  constantDuration: () => constantDuration,
@@ -50,22 +51,28 @@ __export(index_exports, {
50
51
  demandWindowStart: () => demandWindowStart,
51
52
  deriveAttentions: () => deriveAttentions,
52
53
  electricityCost: () => electricityCost,
54
+ emptyFoldedOrders: () => emptyFoldedOrders,
53
55
  energyIntensity: () => energyIntensity,
54
56
  energyOfWindows: () => energyOfWindows,
55
57
  fefoPolicy: () => fefoPolicy,
56
58
  firstFitPolicy: () => firstFitPolicy,
57
59
  foldJobResponses: () => foldJobResponses,
60
+ foldOrdersInto: () => foldOrdersInto,
58
61
  foldTaskRecords: () => foldTaskRecords,
59
62
  journalProjector: () => journalProjector,
60
63
  monteCarloForecast: () => monteCarloForecast,
61
64
  monteCarloForecastAsync: () => monteCarloForecastAsync,
65
+ operationsCapabilityOf: () => operationsCapabilityOf,
62
66
  partialFitPolicy: () => partialFitPolicy,
63
67
  planMakeToOrder: () => planMakeToOrder,
68
+ planOrderFold: () => planOrderFold,
64
69
  producedByIndex: () => producedByIndex,
70
+ pruneFoldedHours: () => pruneFoldedHours,
65
71
  replay: () => replay,
66
72
  replayFrom: () => replayFrom,
67
73
  replaySegments: () => replaySegments,
68
- replayWithCheckpoint: () => replayWithCheckpoint
74
+ replayWithCheckpoint: () => replayWithCheckpoint,
75
+ standsNewOrderRow: () => standsNewOrderRow
69
76
  });
70
77
  module.exports = __toCommonJS(index_exports);
71
78
 
@@ -233,6 +240,11 @@ function ratedUsageOf(r) {
233
240
  }
234
241
 
235
242
  // ../ops-contract/dist/contract.js
243
+ var TASK_STATUS = ["created", "assigned", "in-progress", "completed", "cancelled"];
244
+ var TASK_TERMINAL_STATUS = ["completed", "cancelled"];
245
+ function isTaskTerminal(t) {
246
+ return TASK_TERMINAL_STATUS.includes(String(t?.status ?? ""));
247
+ }
236
248
  var ORDER_TERMINAL_STATUS = ["completed", "cancelled"];
237
249
  function isOrderTerminal(o) {
238
250
  const status = String(o?.status ?? "").trim().toLowerCase();
@@ -942,9 +954,6 @@ function isoDurationHours(iso2) {
942
954
  throw new Error(`\uAE30\uAC04 \uD45C\uAE30\uB97C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${iso2}`);
943
955
  return Number(m[1] ?? 0) * 24 + Number(m[2] ?? 0) + Number(m[3] ?? 0) / 60 + Number(m[4] ?? 0) / 3600;
944
956
  }
945
- function paramOf(op, id) {
946
- return op.parameters?.find((p) => p.id === id)?.value;
947
- }
948
957
  function workingTimeOfWeek(calendar, weekStartMs, utcOffsetMinutes) {
949
958
  if (!calendar?.length)
950
959
  return { hoursPerWeek: 7 * 24, daysPerWeek: 7 };
@@ -963,83 +972,6 @@ function workingTimeOfWeek(calendar, weekStartMs, utcOffsetMinutes) {
963
972
  declared.add(d);
964
973
  return { hoursPerWeek: minutes / 60, daysPerWeek: declared.size || touched.size };
965
974
  }
966
- function availabilityOf(records) {
967
- const ratios = records.map((r) => r.mtbfMs && r.mttrMs ? r.mtbfMs / (r.mtbfMs + r.mttrMs) : 1);
968
- return ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1;
969
- }
970
- function analyzeCapacity(input) {
971
- const { hoursPerWeek, daysPerWeek } = workingTimeOfWeek(input.calendar, input.sampleWeekStartMs, input.utcOffsetMinutes);
972
- const demandPerHour = hoursPerWeek > 0 ? input.unitsPerDay * daysPerWeek / hoursPerWeek : 0;
973
- const equipmentByKind = /* @__PURE__ */ new Map();
974
- for (const e of input.equipment ?? []) {
975
- const list = equipmentByKind.get(e.kind) ?? [];
976
- list.push(e);
977
- equipmentByKind.set(e.kind, list);
978
- }
979
- const countByClass = (rows, field) => {
980
- const out = /* @__PURE__ */ new Map();
981
- for (const r of rows ?? [])
982
- for (const c of r[field] ?? [])
983
- out.set(c, (out.get(c) ?? 0) + 1);
984
- return out;
985
- };
986
- const personsByClass = countByClass(input.persons, "personnelClassIds");
987
- const assetsByClass = countByClass(input.assets, "assetClassIds");
988
- const slotsByLocationType = /* @__PURE__ */ new Map();
989
- for (const l of input.locations ?? [])
990
- if (l.type)
991
- slotsByLocationType.set(l.type, (slotsByLocationType.get(l.type) ?? 0) + Math.max(l.capacity ?? 1, 1));
992
- const order = input.route?.length ? input.route.map((k) => input.operations.find((o) => o.key === k)).filter((o) => !!o) : [...input.operations];
993
- let downstream = 1;
994
- const reversed = [];
995
- for (const op of [...order].reverse()) {
996
- const cycleHours = isoDurationHours(op.duration) + isoDurationHours(paramOf(op, "setupDuration"));
997
- downstream *= Number(paramOf(op, "yield") ?? 1);
998
- const requiredPerHour = downstream > 0 ? demandPerHour / downstream : Infinity;
999
- const requirements = [];
1000
- const add = (axis, className, quantity, available, availability) => {
1001
- const q = Math.max(quantity, 1);
1002
- requirements.push({
1003
- axis,
1004
- className,
1005
- quantity: q,
1006
- available,
1007
- availability,
1008
- perHour: cycleHours > 0 ? Math.floor(available / q) / cycleHours * availability : Infinity
1009
- });
1010
- };
1011
- const equipSpecs = op.equipmentSpecification?.length ? op.equipmentSpecification.map((s) => ({ className: s.equipmentClass ?? op.resourceType ?? "", quantity: s.quantity })) : op.resourceType ? [{ className: op.resourceType, quantity: 1 }] : [];
1012
- for (const s of equipSpecs) {
1013
- if (!s.className)
1014
- continue;
1015
- const records = equipmentByKind.get(s.className) ?? [];
1016
- add("equipment", s.className, s.quantity, records.length, availabilityOf(records));
1017
- }
1018
- for (const s of op.personnelSpecification ?? [])
1019
- if (s.personnelClass)
1020
- add("personnel", s.personnelClass, s.quantity, personsByClass.get(s.personnelClass) ?? 0, 1);
1021
- for (const s of op.physicalAssetSpecification ?? [])
1022
- if (s.assetClass)
1023
- add("asset", s.assetClass, s.quantity, assetsByClass.get(s.assetClass) ?? 0, 1);
1024
- if (op.locationType)
1025
- add("location", op.locationType, 1, slotsByLocationType.get(op.locationType) ?? 0, 1);
1026
- const constraint = requirements.length ? requirements.reduce((a, b) => a.perHour <= b.perHour ? a : b) : void 0;
1027
- const perHour = constraint ? constraint.perHour : Infinity;
1028
- reversed.push({ operation: op.key, cycleHours, perHour, requiredPerHour, ok: perHour >= requiredPerHour, constraint, requirements });
1029
- }
1030
- const operations = reversed.reverse();
1031
- const tightest = operations.length ? operations.reduce((a, b) => a.perHour / a.requiredPerHour <= b.perHour / b.requiredPerHour ? a : b) : void 0;
1032
- const headroom = operations.length ? Math.min(...operations.map((o) => o.perHour / o.requiredPerHour)) : Infinity;
1033
- return {
1034
- workingHoursPerWeek: hoursPerWeek,
1035
- workingDaysPerWeek: daysPerWeek,
1036
- demandPerHour,
1037
- operations,
1038
- ...tightest ? { bottleneck: { operation: tightest.operation, axis: tightest.constraint?.axis, className: tightest.constraint?.className } } : {},
1039
- maxUnitsPerDay: input.unitsPerDay * headroom,
1040
- ok: operations.every((o) => o.ok)
1041
- };
1042
- }
1043
975
 
1044
976
  // ../ops-contract/dist/epcis.js
1045
977
  var EPCIS_CONTEXT = "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld";
@@ -1780,8 +1712,9 @@ var EMS_TYPES = [
1780
1712
  level: "Other",
1781
1713
  label: "twin.type.incoming",
1782
1714
  /* 수전 지점 — 계약전력이 걸리는 자리이고, 요금의 근거가 되는 수요는 여기서 잰다.
1783
- ISO 50001 의 「에너지 유입」 경계이기도 하다(조직의 에너지 검토가 여기서 시작한다). */
1784
- standardClass: { iec61850: "MMTR", iso50001: "EnergyInput" },
1715
+ 조직의 에너지 검토가 여기서 시작하지만, ISO 50001 은 이 경계에 **분류 이름을 주지 않는다** — 그래서
1716
+ 그 칸을 비운다(예전의 `EnergyInput` 은 표준의 낱말이 아니었다. 2026-11-19 내용 점검). */
1717
+ standardClass: { iec61850: "MMTR" },
1785
1718
  identity: { scheme: "kernel:id" },
1786
1719
  capabilities: ["metered"]
1787
1720
  },
@@ -1791,8 +1724,17 @@ var EMS_TYPES = [
1791
1724
  /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
1792
1725
  level: "Other",
1793
1726
  label: "twin.type.feeder",
1794
- /* 분기 회로 — 부하 분해의 단위. 계약전력의 하위 배분이 여기서 정해진다. */
1795
- standardClass: { iec61850: "Feeder", iso50001: "EnergyUse" },
1727
+ /*
1728
+ * 분기 회로 — 부하 분해의 단위. 계약전력의 하위 배분이 여기서 정해진다.
1729
+ *
1730
+ * **두 칸 다 비운다**(2026-11-19 내용 점검). 예전 값은 둘 다 맞지 않았다:
1731
+ * · `Feeder` 는 IEC 61850 논리 노드가 아니다. 그 표준에서 급전 구간은 SCL 의 `Bay`(설비 구성의 자리)이고,
1732
+ * 이 칸이 담는 논리 노드(MMTR·MMXU·XCBR…)와 다른 층이다. 회로의 계량은 그 회로에 달린 계량기(`meter`)가 진다.
1733
+ * · ISO 50001 의 「energy use」는 **용도**(환기·조명처럼 에너지를 어디에 쓰나)이지 회로가 아니다. 회로 하나에
1734
+ * 여러 용도가 걸리고, 한 용도가 여러 회로에 걸친다 — 대응시키면 SEU 분석이 회로를 용도로 센다.
1735
+ * 표준의 이름이 없는 것을 「없다」고 두는 것이 파일 머리의 규율이다.
1736
+ */
1737
+ standardClass: {},
1796
1738
  identity: { scheme: "kernel:id" },
1797
1739
  capabilities: ["metered"]
1798
1740
  },
@@ -1818,7 +1760,8 @@ var EMS_TYPES = [
1818
1760
  role: "equipment",
1819
1761
  label: "twin.type.meter",
1820
1762
  /* 계량기 — 측정 논리 노드(MMXU=측정단위, MMTR=적산). 자산으로도 하나다(ISO 55000). */
1821
- standardClass: { iec61850: "MMXU", iso55000: "Asset", iso50001: "MeasurementPoint" },
1763
+ /* ISO 50001 칸은 비운다 — 계측 지점은 그 표준이 이름 붙인 분류가 아니다(파일 머리의 규율, 2026-11-19 내용 점검). */
1764
+ standardClass: { iec61850: "MMXU", iso55000: "Asset" },
1822
1765
  identity: { scheme: "kernel:id" },
1823
1766
  capabilities: ["metered", "operable"]
1824
1767
  },
@@ -1843,7 +1786,8 @@ var EMS_TYPES = [
1843
1786
  role: "equipment",
1844
1787
  label: "twin.type.pv-array",
1845
1788
  /* 태양광 어레이 — IEC 61850-7-420(분산자원)의 `DPVA`. 발전과 계량은 다른 능력이다. */
1846
- standardClass: { iec61850: "DPVA", iso55000: "Asset", iso50001: "RenewableSupply" },
1789
+ /* ISO 50001 칸은 비운다 — 「재생 공급」은 그 표준의 분류 이름이 아니다(파일 머리의 규율, 2026-11-19 내용 점검). */
1790
+ standardClass: { iec61850: "DPVA", iso55000: "Asset" },
1847
1791
  identity: { scheme: "kernel:id" },
1848
1792
  capabilities: ["energyGenerating", "metered", "operable"]
1849
1793
  },
@@ -1987,9 +1931,6 @@ function orderFoldPolicyOf(declared) {
1987
1931
  return { error: "order fold maxTerminal must be at least 1 (ADR-0092)" };
1988
1932
  return { policy };
1989
1933
  }
1990
- function emptyFoldedOrders() {
1991
- return { counts: {}, boundaryMs: null };
1992
- }
1993
1934
  function foldedOrderCount(folded) {
1994
1935
  let n = 0;
1995
1936
  for (const byStatus of Object.values(folded?.counts ?? {}))
@@ -1997,61 +1938,12 @@ function foldedOrderCount(folded) {
1997
1938
  n += c;
1998
1939
  return n;
1999
1940
  }
2000
- function planOrderFold(orders, nowMs, policy = ORDER_FOLD_DEFAULT) {
2001
- const candidates = orders.filter((o) => isOrderTerminal(o) && !o.held && typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)).sort((a, b) => a.terminalAtMs - b.terminalAtMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
2002
- const cutoff = nowMs - policy.afterMs;
2003
- const byTime = candidates.filter((o) => o.terminalAtMs <= cutoff);
2004
- const stay = candidates.length - byTime.length;
2005
- const byCount = stay > policy.maxTerminal ? candidates.slice(byTime.length, byTime.length + (stay - policy.maxTerminal)) : [];
2006
- return [...byTime, ...byCount].map((o) => o.id);
2007
- }
2008
- function foldOrdersInto(folded, orders) {
2009
- const out = {
2010
- counts: Object.fromEntries(Object.entries(folded?.counts ?? {}).map(([k, v]) => [k, { ...v }])),
2011
- boundaryMs: folded?.boundaryMs ?? null
2012
- };
2013
- const hours = Object.fromEntries(Object.entries(folded?.hours ?? {}).map(([h, byKind]) => [h, Object.fromEntries(Object.entries(byKind).map(([k, v]) => [k, { ...v }]))]));
2014
- for (const o of orders) {
2015
- const kind = String(o.kind ?? "");
2016
- const status = String(o.status ?? "");
2017
- const byStatus = out.counts[kind] ??= {};
2018
- byStatus[status] = (byStatus[status] ?? 0) + 1;
2019
- if (typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)) {
2020
- out.boundaryMs = out.boundaryMs === null ? o.terminalAtMs : Math.max(out.boundaryMs, o.terminalAtMs);
2021
- const slot = (hours[String(hourStartOf(o.terminalAtMs))] ??= {})[kind] ??= {};
2022
- slot[status] = (slot[status] ?? 0) + 1;
2023
- }
2024
- }
2025
- if (Object.keys(hours).length)
2026
- out.hours = hours;
2027
- return out;
2028
- }
2029
- function standsNewOrderRow(record, eventTimeMs, folded) {
2030
- if (!isOrderTerminal(record))
2031
- return true;
2032
- const boundary = folded?.boundaryMs;
2033
- if (boundary === null || boundary === void 0)
2034
- return true;
2035
- if (typeof eventTimeMs !== "number" || !Number.isFinite(eventTimeMs))
2036
- return true;
2037
- return eventTimeMs > boundary;
2038
- }
2039
1941
  function hourStartOf(ms2) {
2040
1942
  return Math.floor(ms2 / ORDER_FOLD_HOUR_MS) * ORDER_FOLD_HOUR_MS;
2041
1943
  }
2042
1944
  function finishedWindowStartMs(nowMs, policy = ORDER_FOLD_DEFAULT) {
2043
1945
  return hourStartOf(nowMs) - policy.afterMs;
2044
1946
  }
2045
- function pruneFoldedHours(folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
2046
- if (!folded.hours)
2047
- return folded;
2048
- const start = finishedWindowStartMs(nowMs, policy);
2049
- const kept = Object.fromEntries(Object.entries(folded.hours).filter(([h]) => Number(h) >= start));
2050
- const out = { counts: folded.counts, boundaryMs: folded.boundaryMs };
2051
- if (Object.keys(kept).length)
2052
- out.hours = kept;
2053
- return out;
2054
- }
2055
1947
 
2056
1948
  // ../ops-contract/dist/referenced-location.js
2057
1949
  function referencedLocationIds(def) {
@@ -2139,7 +2031,6 @@ function isWorkShiftExecutionBasis(value) {
2139
2031
  }
2140
2032
 
2141
2033
  // ../ops-contract/dist/operational-ingest.js
2142
- var TASK_STATUS = ["created", "assigned", "in-progress", "completed"];
2143
2034
  var SPECS = {
2144
2035
  task: {
2145
2036
  eventType: OP_EVENT.task,
@@ -2579,63 +2470,6 @@ function workingHoursBetween(calendar, fromMs, toMs, utcOffsetMinutes) {
2579
2470
  minutes++;
2580
2471
  return minutes / 60;
2581
2472
  }
2582
- function operationsCapabilityOf(input) {
2583
- const fromMs = Date.parse(input.window.fromTime);
2584
- const toMs = Date.parse(input.window.toTime);
2585
- if (!Number.isFinite(fromMs) || !Number.isFinite(toMs)) {
2586
- throw new Error(`\uB2A5\uB825\uC758 \uAD6C\uAC04\uC744 \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${input.window.fromTime} ~ ${input.window.toTime}`);
2587
- }
2588
- if (toMs <= fromMs)
2589
- throw new Error(`\uB2A5\uB825\uC758 \uAD6C\uAC04\uC774 \uB4A4\uC9D1\uD614\uB2E4: ${input.window.fromTime} ~ ${input.window.toTime}`);
2590
- const workingHours = workingHoursBetween(input.calendar ?? input.capacity.calendar, fromMs, toMs, input.utcOffsetMinutes);
2591
- const full = analyzeCapacity(input.capacity);
2592
- const usable = input.usableCapacity ? analyzeCapacity(input.usableCapacity) : void 0;
2593
- const amountOf = (perHour) => Number.isFinite(perHour) ? perHour * workingHours : null;
2594
- const committedOf = (operation) => {
2595
- let sum = 0;
2596
- for (const d of input.demands ?? []) {
2597
- if (d.operation !== void 0 && d.operation !== operation)
2598
- continue;
2599
- if (!d.dueTime)
2600
- continue;
2601
- const due = Date.parse(d.dueTime);
2602
- if (!Number.isFinite(due) || due < fromMs || due >= toMs)
2603
- continue;
2604
- sum += Math.max(0, d.remaining);
2605
- }
2606
- return sum;
2607
- };
2608
- const perOperation = full.operations.map((op) => {
2609
- const total = amountOf(op.perHour);
2610
- const committed = committedOf(op.operation);
2611
- let unattainable = null;
2612
- let unattainableBy;
2613
- if (usable) {
2614
- const left = usable.operations.find((o) => o.operation === op.operation);
2615
- const usableAmount = amountOf(left?.perHour ?? NaN);
2616
- unattainable = total != null && usableAmount != null ? Math.max(0, total - usableAmount) : null;
2617
- if (unattainable != null && unattainable > 0 && left?.constraint)
2618
- unattainableBy = left.constraint;
2619
- }
2620
- const available = total == null || unattainable == null ? null : total - committed - unattainable;
2621
- return {
2622
- operation: op.operation,
2623
- total,
2624
- committed,
2625
- unattainable,
2626
- available,
2627
- ...op.constraint ? { constraint: op.constraint } : {},
2628
- ...unattainableBy ? { unattainableBy } : {}
2629
- };
2630
- });
2631
- return {
2632
- operationsType: input.operationsType ?? "Production",
2633
- window: { fromTime: input.window.fromTime, toTime: input.window.toTime, workingHours },
2634
- perOperation,
2635
- ...full.bottleneck ? { bottleneck: full.bottleneck } : {},
2636
- ...input.publishedDate ? { publishedDate: input.publishedDate } : {}
2637
- };
2638
- }
2639
2473
 
2640
2474
  // ../ops-contract/dist/oee.js
2641
2475
  function computeOee(c, nowMs) {
@@ -2653,7 +2487,7 @@ function computeOee(c, nowMs) {
2653
2487
  missing.push("planned-run-time-per-item");
2654
2488
  else if (c.runMs <= 0)
2655
2489
  missing.push("actual-production-time");
2656
- const performance2 = c.plannedRunTimePerItemMs != null && c.runMs > 0 ? Math.min(1, c.plannedRunTimePerItemMs * produced / c.runMs) : void 0;
2490
+ const performance2 = c.plannedRunTimePerItemMs != null && c.runMs > 0 ? c.plannedRunTimePerItemMs * produced / c.runMs : void 0;
2657
2491
  const overall = availability != null && performance2 != null && quality != null ? availability * performance2 * quality : void 0;
2658
2492
  return {
2659
2493
  ...availability != null ? { availability } : {},
@@ -2670,6 +2504,33 @@ function computeOee(c, nowMs) {
2670
2504
  };
2671
2505
  }
2672
2506
 
2507
+ // ../ops-contract/dist/material-move.js
2508
+ var MOVE_KIND = {
2509
+ /** warehouse → plant: a pick for a production order put this container at the line. */
2510
+ issue: "issue",
2511
+ /** warehouse → plant: the issue was taken back - what was still on the way came back (ADR-0143 decision 5). */
2512
+ issueCancel: "issue-cancel",
2513
+ /** plant → warehouse: the line took this much of an issue. */
2514
+ receipt: "receipt",
2515
+ /** plant → warehouse: what is left at the line goes back (decision 3). */
2516
+ return: "return",
2517
+ /** plant → warehouse: finished goods leave the line for the warehouse (decision 4). */
2518
+ handover: "handover",
2519
+ /** warehouse → plant: this much of a return arrived. */
2520
+ returnReceived: "return-received",
2521
+ /** warehouse → plant: this much of a handover arrived. */
2522
+ handoverReceived: "handover-received",
2523
+ /** site → site: a transfer left for the peer site, one lot (ADR-0154 decision 1). */
2524
+ transfer: "transfer",
2525
+ /** site → site: this much of a transfer arrived at the peer site. */
2526
+ transferReceived: "transfer-received"
2527
+ };
2528
+ var RECEIVED_MOVE_KIND = {
2529
+ [MOVE_KIND.return]: MOVE_KIND.returnReceived,
2530
+ [MOVE_KIND.handover]: MOVE_KIND.handoverReceived,
2531
+ [MOVE_KIND.transfer]: MOVE_KIND.transferReceived
2532
+ };
2533
+
2673
2534
  // src/divergence.ts
2674
2535
  function diffBy(predicted, actual, idOf, valOf) {
2675
2536
  const p = new Map(predicted.map((e) => [idOf(e), valOf(e)]));
@@ -2929,6 +2790,56 @@ var ClassMasterTable = class {
2929
2790
  }
2930
2791
  };
2931
2792
 
2793
+ // src/order-fold.ts
2794
+ function emptyFoldedOrders() {
2795
+ return { counts: {}, boundaryMs: null };
2796
+ }
2797
+ function planOrderFold(orders, nowMs, policy = ORDER_FOLD_DEFAULT) {
2798
+ const candidates = orders.filter((o) => isOrderTerminal(o) && !o.held && typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)).sort((a, b) => a.terminalAtMs - b.terminalAtMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
2799
+ const cutoff = nowMs - policy.afterMs;
2800
+ const byTime = candidates.filter((o) => o.terminalAtMs <= cutoff);
2801
+ const stay = candidates.length - byTime.length;
2802
+ const byCount = stay > policy.maxTerminal ? candidates.slice(byTime.length, byTime.length + (stay - policy.maxTerminal)) : [];
2803
+ return [...byTime, ...byCount].map((o) => o.id);
2804
+ }
2805
+ function foldOrdersInto(folded, orders) {
2806
+ const out = {
2807
+ counts: Object.fromEntries(Object.entries(folded?.counts ?? {}).map(([k, v]) => [k, { ...v }])),
2808
+ boundaryMs: folded?.boundaryMs ?? null
2809
+ };
2810
+ const hours = Object.fromEntries(
2811
+ Object.entries(folded?.hours ?? {}).map(([h, byKind]) => [h, Object.fromEntries(Object.entries(byKind).map(([k, v]) => [k, { ...v }]))])
2812
+ );
2813
+ for (const o of orders) {
2814
+ const kind = String(o.kind ?? "");
2815
+ const status = String(o.status ?? "");
2816
+ const byStatus = out.counts[kind] ??= {};
2817
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
2818
+ if (typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)) {
2819
+ out.boundaryMs = out.boundaryMs === null ? o.terminalAtMs : Math.max(out.boundaryMs, o.terminalAtMs);
2820
+ const slot = (hours[String(hourStartOf(o.terminalAtMs))] ??= {})[kind] ??= {};
2821
+ slot[status] = (slot[status] ?? 0) + 1;
2822
+ }
2823
+ }
2824
+ if (Object.keys(hours).length) out.hours = hours;
2825
+ return out;
2826
+ }
2827
+ function standsNewOrderRow(record, eventTimeMs, folded) {
2828
+ if (!isOrderTerminal(record)) return true;
2829
+ const boundary = folded?.boundaryMs;
2830
+ if (boundary === null || boundary === void 0) return true;
2831
+ if (typeof eventTimeMs !== "number" || !Number.isFinite(eventTimeMs)) return true;
2832
+ return eventTimeMs > boundary;
2833
+ }
2834
+ function pruneFoldedHours(folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
2835
+ if (!folded.hours) return folded;
2836
+ const start = finishedWindowStartMs(nowMs, policy);
2837
+ const kept = Object.fromEntries(Object.entries(folded.hours).filter(([h]) => Number(h) >= start));
2838
+ const out = { counts: folded.counts, boundaryMs: folded.boundaryMs };
2839
+ if (Object.keys(kept).length) out.hours = kept;
2840
+ return out;
2841
+ }
2842
+
2932
2843
  // src/observed-reducer.ts
2933
2844
  var UNKNOWN_TYPE = "unknown";
2934
2845
  function effectiveOf(r) {
@@ -4115,6 +4026,135 @@ function allocationPolicyOf(name) {
4115
4026
  return found;
4116
4027
  }
4117
4028
 
4029
+ // src/capacity.ts
4030
+ function paramOf(op, id) {
4031
+ return op.parameters?.find((p) => p.id === id)?.value;
4032
+ }
4033
+ function availabilityOf(records) {
4034
+ const ratios = records.map((r) => r.mtbfMs && r.mttrMs ? r.mtbfMs / (r.mtbfMs + r.mttrMs) : 1);
4035
+ return ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1;
4036
+ }
4037
+ function analyzeCapacity(input) {
4038
+ const { hoursPerWeek, daysPerWeek } = workingTimeOfWeek(input.calendar, input.sampleWeekStartMs, input.utcOffsetMinutes);
4039
+ const demandPerHour = hoursPerWeek > 0 ? input.unitsPerDay * daysPerWeek / hoursPerWeek : 0;
4040
+ const equipmentByKind = /* @__PURE__ */ new Map();
4041
+ for (const e of input.equipment ?? []) {
4042
+ const list = equipmentByKind.get(e.kind) ?? [];
4043
+ list.push(e);
4044
+ equipmentByKind.set(e.kind, list);
4045
+ }
4046
+ const countByClass = (rows, field) => {
4047
+ const out = /* @__PURE__ */ new Map();
4048
+ for (const r of rows ?? []) for (const c of r[field] ?? []) out.set(c, (out.get(c) ?? 0) + 1);
4049
+ return out;
4050
+ };
4051
+ const personsByClass = countByClass(input.persons, "personnelClassIds");
4052
+ const assetsByClass = countByClass(input.assets, "assetClassIds");
4053
+ const slotsByLocationType = /* @__PURE__ */ new Map();
4054
+ for (const l of input.locations ?? [])
4055
+ if (l.type) slotsByLocationType.set(l.type, (slotsByLocationType.get(l.type) ?? 0) + Math.max(l.capacity ?? 1, 1));
4056
+ const order = input.route?.length ? input.route.map((k) => input.operations.find((o) => o.key === k)).filter((o) => !!o) : [...input.operations];
4057
+ let downstream = 1;
4058
+ const reversed = [];
4059
+ for (const op of [...order].reverse()) {
4060
+ const cycleHours = isoDurationHours(op.duration) + isoDurationHours(paramOf(op, "setupDuration"));
4061
+ downstream *= Number(paramOf(op, "yield") ?? 1);
4062
+ const requiredPerHour = downstream > 0 ? demandPerHour / downstream : Infinity;
4063
+ const requirements = [];
4064
+ const add = (axis, className, quantity, available, availability) => {
4065
+ const q = Math.max(quantity, 1);
4066
+ requirements.push({
4067
+ axis,
4068
+ className,
4069
+ quantity: q,
4070
+ available,
4071
+ availability,
4072
+ perHour: cycleHours > 0 ? Math.floor(available / q) / cycleHours * availability : Infinity
4073
+ });
4074
+ };
4075
+ const equipSpecs = op.equipmentSpecification?.length ? op.equipmentSpecification.map((s) => ({ className: s.equipmentClass ?? op.resourceType ?? "", quantity: s.quantity })) : op.resourceType ? [{ className: op.resourceType, quantity: 1 }] : [];
4076
+ for (const s of equipSpecs) {
4077
+ if (!s.className) continue;
4078
+ const records = equipmentByKind.get(s.className) ?? [];
4079
+ add("equipment", s.className, s.quantity, records.length, availabilityOf(records));
4080
+ }
4081
+ for (const s of op.personnelSpecification ?? [])
4082
+ if (s.personnelClass) add("personnel", s.personnelClass, s.quantity, personsByClass.get(s.personnelClass) ?? 0, 1);
4083
+ for (const s of op.physicalAssetSpecification ?? [])
4084
+ if (s.assetClass) add("asset", s.assetClass, s.quantity, assetsByClass.get(s.assetClass) ?? 0, 1);
4085
+ if (op.locationType) add("location", op.locationType, 1, slotsByLocationType.get(op.locationType) ?? 0, 1);
4086
+ const constraint = requirements.length ? requirements.reduce((a, b) => a.perHour <= b.perHour ? a : b) : void 0;
4087
+ const perHour = constraint ? constraint.perHour : Infinity;
4088
+ reversed.push({ operation: op.key, cycleHours, perHour, requiredPerHour, ok: perHour >= requiredPerHour, constraint, requirements });
4089
+ }
4090
+ const operations = reversed.reverse();
4091
+ const tightest = operations.length ? operations.reduce((a, b) => a.perHour / a.requiredPerHour <= b.perHour / b.requiredPerHour ? a : b) : void 0;
4092
+ const headroom = operations.length ? Math.min(...operations.map((o) => o.perHour / o.requiredPerHour)) : Infinity;
4093
+ return {
4094
+ workingHoursPerWeek: hoursPerWeek,
4095
+ workingDaysPerWeek: daysPerWeek,
4096
+ demandPerHour,
4097
+ operations,
4098
+ ...tightest ? { bottleneck: { operation: tightest.operation, axis: tightest.constraint?.axis, className: tightest.constraint?.className } } : {},
4099
+ maxUnitsPerDay: input.unitsPerDay * headroom,
4100
+ ok: operations.every((o) => o.ok)
4101
+ };
4102
+ }
4103
+
4104
+ // src/operations-capability.ts
4105
+ function operationsCapabilityOf(input) {
4106
+ const fromMs = Date.parse(input.window.fromTime);
4107
+ const toMs = Date.parse(input.window.toTime);
4108
+ if (!Number.isFinite(fromMs) || !Number.isFinite(toMs)) {
4109
+ throw new Error(`\uB2A5\uB825\uC758 \uAD6C\uAC04\uC744 \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${input.window.fromTime} ~ ${input.window.toTime}`);
4110
+ }
4111
+ if (toMs <= fromMs) throw new Error(`\uB2A5\uB825\uC758 \uAD6C\uAC04\uC774 \uB4A4\uC9D1\uD614\uB2E4: ${input.window.fromTime} ~ ${input.window.toTime}`);
4112
+ const workingHours = workingHoursBetween(input.calendar ?? input.capacity.calendar, fromMs, toMs, input.utcOffsetMinutes);
4113
+ const full = analyzeCapacity(input.capacity);
4114
+ const usable = input.usableCapacity ? analyzeCapacity(input.usableCapacity) : void 0;
4115
+ const amountOf = (perHour) => Number.isFinite(perHour) ? perHour * workingHours : null;
4116
+ const committedOf = (operation) => {
4117
+ let sum = 0;
4118
+ for (const d of input.demands ?? []) {
4119
+ if (d.operation !== void 0 && d.operation !== operation) continue;
4120
+ if (!d.dueTime) continue;
4121
+ const due = Date.parse(d.dueTime);
4122
+ if (!Number.isFinite(due) || due < fromMs || due >= toMs) continue;
4123
+ sum += Math.max(0, d.remaining);
4124
+ }
4125
+ return sum;
4126
+ };
4127
+ const perOperation = full.operations.map((op) => {
4128
+ const total = amountOf(op.perHour);
4129
+ const committed = committedOf(op.operation);
4130
+ let unattainable = null;
4131
+ let unattainableBy;
4132
+ if (usable) {
4133
+ const left = usable.operations.find((o) => o.operation === op.operation);
4134
+ const usableAmount = amountOf(left?.perHour ?? NaN);
4135
+ unattainable = total != null && usableAmount != null ? Math.max(0, total - usableAmount) : null;
4136
+ if (unattainable != null && unattainable > 0 && left?.constraint) unattainableBy = left.constraint;
4137
+ }
4138
+ const available = total == null || unattainable == null ? null : total - committed - unattainable;
4139
+ return {
4140
+ operation: op.operation,
4141
+ total,
4142
+ committed,
4143
+ unattainable,
4144
+ available,
4145
+ ...op.constraint ? { constraint: op.constraint } : {},
4146
+ ...unattainableBy ? { unattainableBy } : {}
4147
+ };
4148
+ });
4149
+ return {
4150
+ operationsType: input.operationsType ?? "Production",
4151
+ window: { fromTime: input.window.fromTime, toTime: input.window.toTime, workingHours },
4152
+ perOperation,
4153
+ ...full.bottleneck ? { bottleneck: full.bottleneck } : {},
4154
+ ...input.publishedDate ? { publishedDate: input.publishedDate } : {}
4155
+ };
4156
+ }
4157
+
4118
4158
  // src/flow-engine.ts
4119
4159
  var BASE_EPOCH = Date.parse("2026-01-01T00:00:00Z");
4120
4160
  function effectiveOnly(r) {
@@ -5204,7 +5244,7 @@ var FlowEngine = class {
5204
5244
  let droppedCompleted = 0;
5205
5245
  const filtering = purpose === "seed";
5206
5246
  for (const t of snap.tasks ?? []) {
5207
- if (filtering && t.status === "completed") {
5247
+ if (filtering && isTaskTerminal(t)) {
5208
5248
  droppedCompleted++;
5209
5249
  continue;
5210
5250
  }
@@ -6476,7 +6516,7 @@ var FlowEngine = class {
6476
6516
  /** 정책에 넘길 특정 타입 자리의 관측 뷰 — 예약(그 자리로 향하는 in-flight task) 포함. */
6477
6517
  slotViews(locationType) {
6478
6518
  const reserved = /* @__PURE__ */ new Map();
6479
- for (const t of this.tasks.values()) if (t.status !== "completed") reserved.set(t.toNode, (reserved.get(t.toNode) ?? 0) + 1);
6519
+ for (const t of this.tasks.values()) if (!isTaskTerminal(t)) reserved.set(t.toNode, (reserved.get(t.toNode) ?? 0) + 1);
6480
6520
  const views = [];
6481
6521
  for (const n of this.locations.values()) if (n.type === locationType) views.push({ id: n.id, capacity: n.capacity, occupancy: n.occupancy, reserved: reserved.get(n.id) ?? 0 });
6482
6522
  return views;
@@ -7926,7 +7966,7 @@ var WmsKernel = class extends FlowEngine {
7926
7966
  /** 이 오더가 실행 중인 생산 사슬이 있나 — 이송·가공·되돌리기 중 하나라도 열려 있으면 그렇다. */
7927
7967
  hasOpenMakeChain(orderId) {
7928
7968
  for (const t of this.tasks.values()) {
7929
- if (t.orderId !== orderId || t.status === "completed") continue;
7969
+ if (t.orderId !== orderId || isTaskTerminal(t)) continue;
7930
7970
  if (t.kind === "feed" || t.intent === "process") return true;
7931
7971
  if (t.kind === "putaway" && t.orderId === orderId) return true;
7932
7972
  }
@@ -8134,7 +8174,7 @@ var YmsKernel = class extends FlowEngine {
8134
8174
  }
8135
8175
  return;
8136
8176
  }
8137
- const inflight = [...this.tasks.values()].some((t) => t.status !== "completed" && t.toNode === door.id);
8177
+ const inflight = [...this.tasks.values()].some((t) => !isTaskTerminal(t) && t.toNode === door.id);
8138
8178
  if (door.occupancy > 0 || inflight) return;
8139
8179
  const mode = this.apptMode.get(o.id) ?? "drop";
8140
8180
  if (mode === "drop" && this.locations.get(trailer.location)?.type !== "yard-slot") return;
@@ -10345,6 +10385,7 @@ function foldTaskRecords(rows) {
10345
10385
  if (d.status === "created") rec.createdMs = at;
10346
10386
  else if (d.status === "in-progress") rec.startedMs = rec.startedMs != null ? Math.min(rec.startedMs, at) : at;
10347
10387
  else if (d.status === "completed") rec.completedMs = rec.completedMs != null ? Math.max(rec.completedMs, at) : at;
10388
+ else if (d.status === "cancelled") rec.cancelledMs = rec.cancelledMs != null ? Math.max(rec.cancelledMs, at) : at;
10348
10389
  }
10349
10390
  return { records: [...byTask.values()], rowsRead, latestMs };
10350
10391
  }
@@ -10372,7 +10413,7 @@ function foldJobResponses(rows) {
10372
10413
  }
10373
10414
  return records.map((rec) => {
10374
10415
  const x = extra.get(rec.taskId) ?? {};
10375
- const jobState = rec.completedMs !== void 0 ? "completed" : rec.startedMs !== void 0 ? "running" : "ready";
10416
+ const jobState = rec.completedMs !== void 0 ? "completed" : rec.cancelledMs !== void 0 ? "aborted" : rec.startedMs !== void 0 ? "running" : "ready";
10376
10417
  const one = (ids) => ids?.length ? ids.map((id) => ({ id, quantity: 1 })) : void 0;
10377
10418
  return {
10378
10419
  id: rec.taskId,
@@ -10380,7 +10421,7 @@ function foldJobResponses(rows) {
10380
10421
  ...rec.facets.kind ? { workType: rec.facets.kind } : {},
10381
10422
  jobState,
10382
10423
  ...iso(rec.startedMs) ? { startTime: iso(rec.startedMs) } : {},
10383
- ...iso(rec.completedMs) ? { endTime: iso(rec.completedMs) } : {},
10424
+ ...iso(rec.completedMs ?? rec.cancelledMs) ? { endTime: iso(rec.completedMs ?? rec.cancelledMs) } : {},
10384
10425
  ...one(x.personnel) ? { personnelActual: one(x.personnel) } : {},
10385
10426
  ...one(x.resources) ? { equipmentActual: one(x.resources) } : {},
10386
10427
  ...one(x.assets) ? { physicalAssetActual: one(x.assets) } : {},
@@ -10655,6 +10696,7 @@ function electricityCost(input) {
10655
10696
  allocatedEpcs,
10656
10697
  allocatedQty,
10657
10698
  allocationPolicyOf,
10699
+ analyzeCapacity,
10658
10700
  attributeEnergy,
10659
10701
  compareStates,
10660
10702
  constantDuration,
@@ -10664,20 +10706,26 @@ function electricityCost(input) {
10664
10706
  demandWindowStart,
10665
10707
  deriveAttentions,
10666
10708
  electricityCost,
10709
+ emptyFoldedOrders,
10667
10710
  energyIntensity,
10668
10711
  energyOfWindows,
10669
10712
  fefoPolicy,
10670
10713
  firstFitPolicy,
10671
10714
  foldJobResponses,
10715
+ foldOrdersInto,
10672
10716
  foldTaskRecords,
10673
10717
  journalProjector,
10674
10718
  monteCarloForecast,
10675
10719
  monteCarloForecastAsync,
10720
+ operationsCapabilityOf,
10676
10721
  partialFitPolicy,
10677
10722
  planMakeToOrder,
10723
+ planOrderFold,
10678
10724
  producedByIndex,
10725
+ pruneFoldedHours,
10679
10726
  replay,
10680
10727
  replayFrom,
10681
10728
  replaySegments,
10682
- replayWithCheckpoint
10729
+ replayWithCheckpoint,
10730
+ standsNewOrderRow
10683
10731
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@operato/twin-kernel",
3
- "version": "0.11.31",
3
+ "version": "0.11.32",
4
4
  "type": "module",
5
5
  "description": "Twin Domain Kernel — framework-agnostic, zero-dep (domain + sim + 3-channel contract). WMS/YMS/MES, EPCIS 2.0 · ISA-95.",
6
6
  "publishConfig": {
@@ -37,6 +37,6 @@
37
37
  "test": "node --test test/*.test.ts"
38
38
  },
39
39
  "dependencies": {
40
- "@operato/ops-contract": "^0.9.43"
40
+ "@operato/ops-contract": "^0.9.44"
41
41
  }
42
42
  }