@operato/twin-kernel 0.11.31 → 0.11.33

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,128 @@
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 { workingTimeOfWeek } from "./work-calendar-time.js";
29
+ import { isoDurationHours } from '@operato/ops-contract';
30
+ function paramOf(op, id) {
31
+ return op.parameters?.find(p => p.id === id)?.value;
32
+ }
33
+ function availabilityOf(records) {
34
+ /* 신뢰도를 선언하지 않은 설비는 고장 없음이다(계약의 규칙) — 1 로 센다. */
35
+ const ratios = records.map(r => (r.mtbfMs && r.mttrMs ? r.mtbfMs / (r.mtbfMs + r.mttrMs) : 1));
36
+ return ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1;
37
+ }
38
+ /**
39
+ * 이 공장이 선언된 물량을 낼 수 있는가 — 공정마다, 자원 축마다.
40
+ *
41
+ * 순수 함수다. 커널 상태를 읽지 않고 넘겨받은 것만 본다 — 그래야 "이 설비를 두 대 더 놓으면?" 을
42
+ * 실행해 보지 않고 물을 수 있다(what-if 의 가장 싼 형태).
43
+ */
44
+ export function analyzeCapacity(input) {
45
+ const { hoursPerWeek, daysPerWeek } = workingTimeOfWeek(input.calendar, input.sampleWeekStartMs, input.utcOffsetMinutes);
46
+ /*
47
+ * 수요는 **가동 시간당**이다. 하루 50대는 쉬는 시간에는 안 나오므로 168시간으로 나누면 안 된다 —
48
+ * 그렇게 나누면 필요한 대수가 실제보다 적게 나오고, 공장은 매주 조금씩 밀린다.
49
+ */
50
+ const demandPerHour = hoursPerWeek > 0 ? (input.unitsPerDay * daysPerWeek) / hoursPerWeek : 0;
51
+ /* 축별 공급 — 등급 이름으로 센다. 사람은 자격을 여럿 가질 수 있어 등급 간 합이 인원수를 넘는다
52
+ (같은 사람이 두 줄에 선다). 동시에 두 공정을 하지는 못하므로 이 계산은 **낙관적**이다. */
53
+ const equipmentByKind = new Map();
54
+ for (const e of input.equipment ?? []) {
55
+ const list = equipmentByKind.get(e.kind) ?? [];
56
+ list.push(e);
57
+ equipmentByKind.set(e.kind, list);
58
+ }
59
+ const countByClass = (rows, field) => {
60
+ const out = new Map();
61
+ for (const r of rows ?? [])
62
+ for (const c of r[field] ?? [])
63
+ out.set(c, (out.get(c) ?? 0) + 1);
64
+ return out;
65
+ };
66
+ const personsByClass = countByClass(input.persons, 'personnelClassIds');
67
+ const assetsByClass = countByClass(input.assets, 'assetClassIds');
68
+ const slotsByLocationType = new Map();
69
+ for (const l of input.locations ?? [])
70
+ if (l.type)
71
+ slotsByLocationType.set(l.type, (slotsByLocationType.get(l.type) ?? 0) + Math.max(l.capacity ?? 1, 1));
72
+ const order = input.route?.length
73
+ ? input.route.map(k => input.operations.find(o => o.key === k)).filter((o) => !!o)
74
+ : [...input.operations];
75
+ /* 하류 수율을 거슬러 올라가며 소요량을 부풀린다 — 도장에서 5% 를 잃으면 그 앞은 더 만들어야 한다. */
76
+ let downstream = 1;
77
+ const reversed = [];
78
+ for (const op of [...order].reverse()) {
79
+ const cycleHours = isoDurationHours(op.duration) + isoDurationHours(paramOf(op, 'setupDuration'));
80
+ downstream *= Number(paramOf(op, 'yield') ?? 1);
81
+ const requiredPerHour = downstream > 0 ? demandPerHour / downstream : Infinity;
82
+ const requirements = [];
83
+ const add = (axis, className, quantity, available, availability) => {
84
+ const q = Math.max(quantity, 1);
85
+ requirements.push({
86
+ axis, className, quantity: q, available, availability,
87
+ perHour: cycleHours > 0 ? (Math.floor(available / q) / cycleHours) * availability : Infinity
88
+ });
89
+ };
90
+ /* 설비 — 표준 EquipmentSpecification(등급+대수). 그것이 없으면 예전 표기(resourceType 한 대). */
91
+ const equipSpecs = op.equipmentSpecification?.length
92
+ ? op.equipmentSpecification.map(s => ({ className: s.equipmentClass ?? op.resourceType ?? '', quantity: s.quantity }))
93
+ : op.resourceType ? [{ className: op.resourceType, quantity: 1 }] : [];
94
+ for (const s of equipSpecs) {
95
+ if (!s.className)
96
+ continue;
97
+ const records = equipmentByKind.get(s.className) ?? [];
98
+ add('equipment', s.className, s.quantity, records.length, availabilityOf(records));
99
+ }
100
+ for (const s of op.personnelSpecification ?? [])
101
+ if (s.personnelClass)
102
+ add('personnel', s.personnelClass, s.quantity, personsByClass.get(s.personnelClass) ?? 0, 1);
103
+ for (const s of op.physicalAssetSpecification ?? [])
104
+ if (s.assetClass)
105
+ add('asset', s.assetClass, s.quantity, assetsByClass.get(s.assetClass) ?? 0, 1);
106
+ if (op.locationType)
107
+ add('location', op.locationType, 1, slotsByLocationType.get(op.locationType) ?? 0, 1);
108
+ /* 공정의 능력 = 요구들 중 가장 낮은 것. 전량 확보 규칙이라 하나만 모자라도 그만큼만 처리된다. */
109
+ const constraint = requirements.length ? requirements.reduce((a, b) => (a.perHour <= b.perHour ? a : b)) : undefined;
110
+ const perHour = constraint ? constraint.perHour : Infinity;
111
+ reversed.push({ operation: op.key, cycleHours, perHour, requiredPerHour, ok: perHour >= requiredPerHour, constraint, requirements });
112
+ }
113
+ const operations = reversed.reverse();
114
+ /* 병목 = 여유가 가장 적은 공정. 라인 전체의 상한은 그 공정이 정한다. */
115
+ const tightest = operations.length
116
+ ? operations.reduce((a, b) => (a.perHour / a.requiredPerHour <= b.perHour / b.requiredPerHour ? a : b))
117
+ : undefined;
118
+ const headroom = operations.length ? Math.min(...operations.map(o => o.perHour / o.requiredPerHour)) : Infinity;
119
+ return {
120
+ workingHoursPerWeek: hoursPerWeek,
121
+ workingDaysPerWeek: daysPerWeek,
122
+ demandPerHour,
123
+ operations,
124
+ ...(tightest ? { bottleneck: { operation: tightest.operation, axis: tightest.constraint?.axis, className: tightest.constraint?.className } } : {}),
125
+ maxUnitsPerDay: input.unitsPerDay * headroom,
126
+ ok: operations.every(o => o.ok)
127
+ };
128
+ }
@@ -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,10 @@ 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 './work-calendar-time.ts';
14
+ export * from './operations-capability.ts';
11
15
  export * from './job-response.ts';
12
16
  export * from './runtime.ts';
13
17
  export * from './flow-engine.ts';
package/dist/index.js CHANGED
@@ -22,6 +22,10 @@ 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 "./work-calendar-time.js";
28
+ export * from "./operations-capability.js";
25
29
  export * from "./job-response.js";
26
30
  export * from "./runtime.js";
27
31
  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
  *
@@ -867,6 +868,16 @@ export class ObservedReducer {
867
868
  return;
868
869
  }
869
870
  if (ev.type === 'AggregationEvent') {
871
+ /*
872
+ * ── 부모를 말하지 않은 관측 (2026-11-27, EPCIS 2.0 §7.4.3) ─────────────────
873
+ * 표준은 OBSERVE 에서 parentID 를 선택으로 둔다(부모가 보이지 않았을 수 있다). 아래는 모두 부모를 열쇠로 담김을
874
+ * 적으므로, 부모 없는 관측을 그대로 지나면 열쇠가 undefined 인 담김이 생긴다. 세어서 드러내고 건너뛴다.
875
+ */
876
+ if (!ev.parentID) {
877
+ if (envelope)
878
+ this.noteUnhandled(envelope, 'aggregation-no-parent');
879
+ return;
880
+ }
870
881
  /*
871
882
  * ── 바코드 없이 **수량만** 실린 담김 (2026-08-19) ────────────────────────
872
883
  * 실제 창고는 박스마다 바코드를 붙이지 않는다. 팔레트 하나에 「이 품번 40개」로 입고하는 것이
@@ -964,7 +975,7 @@ export class ObservedReducer {
964
975
  }
965
976
  // ObjectEvent
966
977
  if (ev.action === 'DELETE') {
967
- for (const epc of ev.epcList)
978
+ for (const epc of ev.epcList ?? [])
968
979
  this.remove(epc);
969
980
  /*
970
981
  * ── ★ **수량으로 온 물품도 없어질 수 있어야 한다** (2026-08-25 실측) ────────
@@ -1020,14 +1031,14 @@ export class ObservedReducer {
1020
1031
  * 원본의 「없어졌다」가 줄인다). 순서 판정은 그대로 지난다 — 늦게 온 옛 불출이 그 뒤에 돌아온 물품을 지우지 않게.
1021
1032
  */
1022
1033
  if (loc && this.referenced.has(loc)) {
1023
- for (const epc of ev.epcList) {
1034
+ for (const epc of ev.epcList ?? []) {
1024
1035
  if (envelope && this.stale(`item:${epc}`, envelope))
1025
1036
  continue;
1026
1037
  this.remove(epc);
1027
1038
  }
1028
1039
  return;
1029
1040
  }
1030
- for (const epc of ev.epcList) {
1041
+ for (const epc of ev.epcList ?? []) {
1031
1042
  /* 물품별 순서 판정 — 늦게 온 옛 관측이 최신 위치를 덮지 않게. */
1032
1043
  if (envelope && this.stale(`item:${epc}`, envelope))
1033
1044
  continue;
@@ -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
  }
@@ -0,0 +1,36 @@
1
+ import { type WorkCalendarEntry } from '@operato/ops-contract';
2
+ /**
3
+ * 근무 캘린더에서 **가용 시간과 조업일**을 읽는다 — 1분 간격 샘플링.
4
+ *
5
+ * 교대·휴게·비근무 규칙을 여기 다시 적지 않는다. 규칙은 `inWorkCalendarAt` 한 곳에만 있고, 이 함수는
6
+ * 그것에 묻기만 한다. 두 벌이 되면 달력을 고칠 때 한쪽만 고쳐져 어긋난다.
7
+ *
8
+ * 캘린더가 없으면 **종일 가동**으로 본다(7일 × 24h) — 제약이 없는 것이 아니라 **선언되지 않은** 것이고,
9
+ * 선언이 없으면 커널은 멈출 이유를 모른다.
10
+ */
11
+ export declare function workingTimeOfWeek(calendar: readonly WorkCalendarEntry[] | undefined, weekStartMs: number, utcOffsetMinutes?: number): {
12
+ hoursPerWeek: number;
13
+ daysPerWeek: number;
14
+ };
15
+ /**
16
+ * 이 창에서 **조업이 계획되지 않은 시간**(ms) — 없으면 `undefined`.
17
+ *
18
+ * ── 무엇에 쓰나 ─────────────────────────────────────────────────────────────
19
+ * ISO 22400 의 계획 조업 시간(PBT)에서 뺄 값이다(`OeeCounters.holdMs`). 커널의 PBT 가 「재기 시작한
20
+ * 뒤 흐른 시간 전부」였고, 그래서 주말·야간·휴일이 계획 조업으로 세어졌다.
21
+ *
22
+ * ── 선언이 없으면 `undefined` 다 ────────────────────────────────────────────
23
+ * **0 을 내지 않는다.** 0 은 「비근무 시간이 없다」는 주장이고, 그것은 24시간 365일 도는 현장에
24
+ * 대해서만 참이다. 선언이 없는 것은 **모르는 것**이고, 부르는 쪽이 그 둘을 갈라야 한다 — 0 을 받으면
25
+ * 「달력을 확인했고 쉬는 시간이 없었다」로 읽는다.
26
+ *
27
+ * `workingTimeOfWeek` 이 캘린더가 없을 때 종일 가동으로 보는 것과 방향이 반대로 보이지만, 그쪽은
28
+ * **능력**을 묻는 자리라 「최대 얼마나 돌 수 있나」에 답해야 하고, 이쪽은 **실적 지표**의 분모라
29
+ * 모르는 것을 채우면 그 수가 조용히 틀린다.
30
+ *
31
+ * ── 분 단위로 센다 ──────────────────────────────────────────────────────────
32
+ * `workingTimeOfWeek` 과 같은 방식이다(`inWorkCalendarAt` 을 분마다 묻는다). 구간 대수로 풀면
33
+ * 되풀이·요일·절대 구간이 겹칠 때의 규칙을 여기서 다시 적게 되고, 그 규칙은 이미 그 함수 안에 있다 —
34
+ * 두 곳이 다른 답을 내는 것이 이 저장소에서 여러 번 났다.
35
+ */
36
+ export declare function nonWorkingMsIn(calendar: readonly WorkCalendarEntry[] | undefined, fromMs: number, toMs: number, utcOffsetMinutes?: number): number | undefined;