@operato/twin-kernel 0.0.6 → 0.2.0

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.
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { OP_EVENT, CMD } from "./contract.js";
13
13
  import { transformationEvent, aggregationEvent, objectEvent, DISP } from "./epcis.js";
14
+ import { parseIsoDuration } from "./iso-duration.js";
14
15
  const BASE_EPOCH = Date.parse('2026-01-01T00:00:00Z');
15
16
  function mulberry32(seed) {
16
17
  let a = seed >>> 0;
@@ -116,14 +117,25 @@ export class FlowEngine {
116
117
  nodes = new Map();
117
118
  items = new Map();
118
119
  movers = new Map();
120
+ /** 사람 — 선언하지 않으면 빈 맵(인원 제약 없는 트윈, 기존 거동). */
121
+ persons = new Map();
122
+ /** 물리 자산 — 선언하지 않으면 빈 맵(자산 제약 없는 트윈, 기존 거동). */
123
+ assets = new Map();
119
124
  tasks = new Map();
120
125
  orders = new Map();
121
126
  revision = 0;
122
127
  clockMs = 0;
123
128
  rng = mulberry32(1);
124
129
  policy;
125
- /** duration 시임(선택) — 미주입 시 도메인 상수. 씬/보드 바인딩이 거리·속도 기반 estimator 주입. */
130
+ /** duration 시임(선택) — 미주입 시 명세, 명세도 없으면 도메인 상수. 이력 보정 추정기가 여기 들어온다. */
126
131
  durationEstimator;
132
+ /**
133
+ * 오퍼레이션 명세(선택) — 작업 종류(`FlowTask.kind` = `OperationDef.key`) → 소요·변동·모수.
134
+ * 도메인 정의에서 실어 온다(`loadOperations`). 없으면 커널 기본값을 쓰고 그 사실을 `specCoverage()` 가 밝힌다.
135
+ */
136
+ operationSpecs = new Map();
137
+ /** 명세 소비 기록 — 무엇을 선언값으로, 무엇을 기본값으로 계산했나(정직한 자기보고). */
138
+ specUse = new Map();
127
139
  epcSeq = 0;
128
140
  taskSeq = 0;
129
141
  orderSeq = 0;
@@ -140,9 +152,13 @@ export class FlowEngine {
140
152
  // ── TwinKernel (mechanics, 도메인 무관) ───────────────────────────────────
141
153
  loadBoard(def) {
142
154
  for (const n of def.nodes)
143
- this.nodes.set(n.id, { id: n.id, type: n.type, capacity: n.capacity, occupancy: 0, status: 'idle', parentId: n.parentId });
155
+ this.nodes.set(n.id, { id: n.id, type: n.type, capacity: n.capacity, parallelism: n.parallelism, occupancy: 0, status: 'idle', parentId: n.parentId });
156
+ for (const p of def.persons ?? [])
157
+ this.persons.set(p.id, { id: p.id, personnelClass: p.personnelClass, status: 'idle', taskId: null, window: p.window });
158
+ for (const a of def.assets ?? [])
159
+ this.assets.set(a.id, { id: a.id, assetClass: a.assetClass, location: a.homeNode, status: 'idle', taskId: null });
144
160
  for (const m of def.movers) {
145
- const mover = { id: m.id, kind: m.kind, location: m.homeNode, status: 'idle', taskId: null, runMs: 0, setupMs: 0, downMs: 0, goodCount: 0, scrapCount: 0 };
161
+ const mover = { id: m.id, kind: m.kind, location: m.homeNode, status: 'idle', taskId: null, runMs: 0, setupMs: 0, downMs: 0, goodCount: 0, scrapCount: 0, window: m.window };
146
162
  if (m.mtbfMs !== undefined) {
147
163
  mover.mtbfMs = m.mtbfMs;
148
164
  mover.mttrMs = m.mttrMs;
@@ -174,13 +190,89 @@ export class FlowEngine {
174
190
  * 진행 중 개별 task 의 내부 상태는 관측만으론 복원 불가 → 재계획에 맡김(정직한 한계).
175
191
  */
176
192
  hydrateObserved(snap, orders = []) {
177
- for (const n of snap.nodes)
178
- this.nodes.set(n.id, { id: n.id, type: n.type, capacity: n.capacity ?? 0, occupancy: n.occupancy ?? 0, status: 'idle', parentId: n.parentId });
193
+ /* **관측된 것을 버리지 않는다.** 예전에는 노드·무버 상태를 'idle' 로, OEE 누적을 0 으로 덮고
194
+ * 물품의 로트·단위·소속·마스터데이터를 떨어뜨렸다. 씨앗이 잃은 것은 **예측도 모른다**
195
+ * 고장 난 설비를 정상으로, 진행 중인 일을 없는 것으로 놓고 미래를 굴리면 답이 낙관 쪽으로 치우친다. */
196
+ for (const n of snap.nodes) {
197
+ this.nodes.set(n.id, { id: n.id, type: n.type, capacity: n.capacity ?? 0, parallelism: n.parallelism, occupancy: n.occupancy ?? 0, status: n.status ?? 'idle', parentId: n.parentId });
198
+ }
179
199
  this.items.clear();
180
- for (const it of snap.items)
181
- this.items.set(it.epc, { epc: it.epc, location: it.location, disposition: it.disposition ?? DISP.sellable, gtin: it.gtin, qty: it.qty ?? 1 });
182
- for (const m of snap.movers)
183
- this.movers.set(m.id, { id: m.id, kind: m.kind, location: m.location ?? '', status: 'idle', taskId: null, runMs: 0, setupMs: 0, downMs: 0, goodCount: 0, scrapCount: 0 });
200
+ for (const it of snap.items) {
201
+ this.items.set(it.epc, {
202
+ epc: it.epc, location: it.location, disposition: it.disposition ?? DISP.sellable,
203
+ gtin: it.gtin, gtinKey: it.gtinKey, lot: it.lot, qty: it.qty ?? 1, uom: it.uom,
204
+ parent: it.parent, expiry: it.expiry, ilmd: it.ilmd
205
+ });
206
+ }
207
+ for (const m of snap.movers) {
208
+ /*
209
+ * 관측된 계측을 이어받는다 — **없어서 0 이었던 게 아니라 잘못 읽어서 0 이었다.**
210
+ * `OeeMetrics` 의 이름은 `runMs`·`setupMs`·`downMs`·`goodCount`·`scrapCount` 인데 예전 코드가
211
+ * `oee.good`·`oee.scrap`(존재하지 않는 키)을 읽어 항상 0 으로 떨어졌고, 시간 누적은 아예 0 으로
212
+ * 시작했다. 그래서 씨앗이 "가동 이력이 전혀 없는 설비" 로 출발해 예측의 OEE 가 리셋됐다.
213
+ *
214
+ * 라이브(미러)에서 이 값의 출처: 원 시스템이 시간 누적을 보내 주는 것이 아니라, 호스트가
215
+ * `equipment.status` 전이 구간을 적분하고 `quality.output` 카운터를 모아 파생한다. 그 파생에는
216
+ * 한계가 있다 — busy 를 가동으로 근사하고 **셋업을 분리하지 못해 0** 으로 둔다. 여기서는 받은
217
+ * 값을 그대로 이어받고, 없으면 0 에서 시작한다(꾸미지 않는다).
218
+ */
219
+ const oee = m.oee;
220
+ this.movers.set(m.id, {
221
+ id: m.id, kind: m.kind, location: m.location ?? '', status: m.status ?? 'idle', taskId: null,
222
+ runMs: oee?.runMs ?? 0, setupMs: oee?.setupMs ?? 0, downMs: oee?.downMs ?? 0,
223
+ goodCount: oee?.goodCount ?? 0, scrapCount: oee?.scrapCount ?? 0
224
+ });
225
+ }
226
+ /* 사람을 이어 붙인다 — **없으면 인원 요구가 영원히 채워지지 않는다.** 관측 상태에 사람이 있는데
227
+ * 씨앗이 버리면, 인원을 요구하는 공정의 작업이 하나도 시작되지 못하고 예측이 멈춘다(0 명 < 2 명).
228
+ * 배정 상태(busy/taskId)는 아래 작업 복원이 다시 세우므로 여기서는 등급·교대만 살린다. */
229
+ for (const p of snap.persons ?? []) {
230
+ this.persons.set(p.id, { id: p.id, personnelClass: p.personnelClass, status: 'idle', taskId: null });
231
+ }
232
+ /* 자산도 같다 — 잃으면 자산을 요구하는 작업이 영원히 못 나간다(빈 팔레트 0개 < 1개). */
233
+ for (const a of snap.assets ?? []) {
234
+ this.assets.set(a.id, { id: a.id, assetClass: a.assetClass, location: a.location, status: 'idle', taskId: null, carrying: a.carrying });
235
+ }
236
+ /* 진행 중이던 작업을 이어 붙인다 — 없으면 예측이 "일이 하나도 없는 현장" 에서 출발한다.
237
+ * 남은 시간을 모르면 **진척을 꾸미지 않고** 미착수(created)로 되돌린다: 그 일이 남아 있다는 사실은
238
+ * 지키면서, 얼마나 진행됐는지는 모른다고 말하는 쪽이 정직하다(커널이 다시 배정해 굴린다). */
239
+ for (const t of snap.tasks ?? []) {
240
+ if (t.status === 'completed')
241
+ continue;
242
+ const known = typeof t.remainingMs === 'number' && Number.isFinite(t.remainingMs);
243
+ this.tasks.set(t.id, {
244
+ id: t.id, kind: t.kind,
245
+ status: known && t.status === 'in-progress' ? 'in-progress' : 'created',
246
+ itemEpc: t.itemRefs?.[0] ?? '',
247
+ fromNode: t.fromNode ?? '', toNode: t.toNode ?? '',
248
+ resource: known && t.status === 'in-progress' ? (t.resourceRef ?? null) : null,
249
+ remainingMs: known ? t.remainingMs : (t.durationMs ?? 0),
250
+ durationMs: t.durationMs ?? (known ? t.remainingMs : 0),
251
+ orderId: t.orderId,
252
+ intent: t.intent
253
+ });
254
+ /* 진행 중으로 살린 작업은 그 자원을 점유한 상태여야 한다(자원이 동시에 다른 일을 받지 않게). */
255
+ if (known && t.status === 'in-progress' && t.resourceRef) {
256
+ const mv = this.movers.get(t.resourceRef);
257
+ if (mv) {
258
+ mv.status = 'busy';
259
+ mv.taskId = t.id;
260
+ }
261
+ }
262
+ /* 사람도 같다 — 진행 중이던 작업에 투입돼 있던 사람은 여전히 묶여 있어야 한다. */
263
+ if (known && t.status === 'in-progress') {
264
+ const restored = this.tasks.get(t.id);
265
+ if (restored)
266
+ restored.personnel = t.personnel ? [...t.personnel] : undefined;
267
+ for (const id of t.personnel ?? []) {
268
+ const pp = this.persons.get(id);
269
+ if (pp) {
270
+ pp.status = 'busy';
271
+ pp.taskId = t.id;
272
+ }
273
+ }
274
+ }
275
+ }
184
276
  for (const o of orders) {
185
277
  const lines = (o.lines ?? []).map(l => ({ gtin: l.gtin, requested: l.requested - (l.fulfilled ?? 0) })).filter(l => l.requested > 0);
186
278
  const remaining = lines.reduce((s, l) => s + l.requested, 0);
@@ -326,7 +418,7 @@ export class FlowEngine {
326
418
  return;
327
419
  this.generating = true;
328
420
  for (const g of this.gens)
329
- g.nextMs = this.clockMs + this.intervalMs(g.spec);
421
+ g.nextMs = this.nextFireMs(g.spec, this.clockMs);
330
422
  },
331
423
  pause: () => { this.generating = false; },
332
424
  reset: () => { this.generating = false; this.gens = []; },
@@ -348,13 +440,25 @@ export class FlowEngine {
348
440
  nodes: [...this.nodes.values()].map(n => ({ ...n })),
349
441
  items: [...this.items.values()].map(i => ({ epc: i.epc, gtin: i.gtin, qty: i.qty, location: i.location, disposition: i.disposition, expiry: i.expiry })),
350
442
  movers: [...this.movers.values()].map(m => {
351
- const s = { id: m.id, kind: m.kind, location: m.location, status: m.status, taskId: m.taskId ?? undefined, oee: this.oeeOf(m), held: m.held };
443
+ const s = { id: m.id, kind: m.kind, location: m.location, status: m.status, taskId: m.taskId ?? undefined, oee: this.oeeOf(m), held: m.held, ...(this.offShift(m) ? { offShift: true } : {}) };
352
444
  const t = m.taskId ? this.tasks.get(m.taskId) : undefined;
353
445
  if (t && t.status === 'in-progress' && t.intent !== 'process')
354
446
  s.motion = { fromNode: t.fromNode, toNode: t.toNode, startedAtSimMs: this.clockMs - (t.durationMs - t.remainingMs), durationMs: t.durationMs, progress: this.progressOf(t), elapsedMs: t.durationMs - t.remainingMs };
355
447
  return s;
356
448
  }),
357
- tasks: [...this.tasks.values()].map(t => ({ id: t.id, kind: t.kind, status: t.status, itemRefs: [t.itemEpc], fromNode: t.fromNode, toNode: t.toNode, resourceRef: t.resource ?? undefined, orderId: t.orderId, progress: t.status === 'in-progress' ? this.progressOf(t) : undefined })),
449
+ assets: [...this.assets.values()].map(a => {
450
+ const st = { id: a.id, assetClass: a.assetClass, location: a.location, status: a.status, taskId: a.taskId ?? undefined };
451
+ if (a.carrying)
452
+ st.carrying = a.carrying;
453
+ return st;
454
+ }),
455
+ persons: [...this.persons.values()].map(p => {
456
+ const st = { id: p.id, personnelClass: p.personnelClass, status: p.status, taskId: p.taskId ?? undefined };
457
+ if (this.personOffShift(p))
458
+ st.offShift = true;
459
+ return st;
460
+ }),
461
+ tasks: [...this.tasks.values()].map(t => ({ id: t.id, kind: t.kind, status: t.status, itemRefs: [t.itemEpc], fromNode: t.fromNode, toNode: t.toNode, resourceRef: t.resource ?? undefined, orderId: t.orderId, progress: t.status === 'in-progress' ? this.progressOf(t) : undefined, ...(t.personnel?.length ? { personnel: t.personnel.slice() } : {}) })),
358
462
  orders: [...this.orders.values()].map(o => ({ id: o.id, kind: o.kind, status: o.status, progress: o.requested ? o.fulfilled / o.requested : 0, held: o.held })),
359
463
  attentions: this.computeAttentions()
360
464
  };
@@ -398,14 +502,149 @@ export class FlowEngine {
398
502
  }
399
503
  clone.rng.state = this.rng.state; // RNG 연속성 → 생성 포함 결정적 분기
400
504
  clone.durationEstimator = this.durationEstimator; // 무상태 시임 — 참조 공유(policy 와 동형)
505
+ /* 명세는 불변(정의) → 참조 공유. 사용 기록은 fork 자기 것(무엇을 기본값으로 굴렸는지 fork 별로 다르다). */
506
+ clone.operationSpecs = this.operationSpecs;
507
+ clone.specUse = new Map([...this.specUse.entries()].map(([k, u]) => [k, { duration: u.duration, variability: u.variability, params: new Set(u.params) }]));
401
508
  return clone;
402
509
  }
403
510
  // ── 보호 헬퍼 (도메인 hook 에서 사용) ──────────────────────────────────────
404
511
  now() { return new Date(BASE_EPOCH + this.clockMs).toISOString(); }
405
512
  randInt(min, max) { return max <= min ? min : min + Math.floor(this.rng() * (max - min + 1)); }
406
- /** task 소요 산출 — estimator 주입 시 그 값, 미주입/undefined 시 도메인 상수(fallback). "얼마"만 소비, "경로"는 씬. */
513
+ /**
514
+ * 오퍼레이션 명세를 싣는다 — 도메인 정의(ISA-95 OperationsSegment)의 시뮬 명세를 커널이 소비하는 입구.
515
+ * 같은 key 를 다시 실으면 덮어쓴다(정의가 권위).
516
+ */
517
+ loadOperations(ops = []) {
518
+ for (const o of ops)
519
+ if (o?.key)
520
+ this.operationSpecs.set(o.key, o);
521
+ }
522
+ /**
523
+ * task 소요 산출 — 우선순위: **① 추정기(이력 보정) → ② 명세(ISA-95 Duration + 변동) → ③ 도메인 상수.**
524
+ *
525
+ * 이 순서인 이유: 실측에서 배운 값이 선언값을 이기고, 선언값이 우리가 코드에 박아 둔 상수를 이긴다.
526
+ * 셋 중 무엇을 썼는지는 `specCoverage()` 로 드러낸다 — 상수를 쓴 것이 조용히 넘어가지 않게.
527
+ * "얼마"만 소비하고 "경로"는 씬이 소유한다(좌표-free 유지).
528
+ */
407
529
  durationOf(ctx, fallbackMs) {
408
- return this.durationEstimator?.estimate(ctx) ?? fallbackMs;
530
+ const estimated = this.durationEstimator?.estimate(ctx);
531
+ /* 추정기가 답한 것은 **실측·계산에서 온 값**이므로 선언값과 구별해 기록한다 — "현장이 선언했다" 와
532
+ * "이력에서 배웠다" 는 예측의 자격이 다르다(후자가 더 강하다). 뭉개면 그 차이가 사라진다. */
533
+ if (typeof estimated === 'number') {
534
+ this.noteSpecUse(ctx.kind, 'measured');
535
+ return estimated;
536
+ }
537
+ if (estimated) {
538
+ /* 분포까지 아는 추정치 — **관측된 퍼짐**으로 흔든다. 평균만 쓰면 변동이 0 이라 줄이 생기지 않는다. */
539
+ this.noteSpecUse(ctx.kind, 'measured', estimated.spread?.distribution);
540
+ return this.sampleSpread(estimated.meanMs, estimated.spread);
541
+ }
542
+ const spec = this.operationSpecs.get(ctx.kind);
543
+ const declared = parseIsoDuration(spec?.duration);
544
+ if (declared === undefined) {
545
+ this.noteSpecUse(ctx.kind, 'default');
546
+ return fallbackMs;
547
+ }
548
+ this.noteSpecUse(ctx.kind, 'declared');
549
+ return this.applyVariability(declared, spec?.variability);
550
+ }
551
+ /**
552
+ * 소요시간 변동 표본 — **엔진 난수원으로만** 뽑는다(fork 결정성). 표준 밖 확장이므로 미지정이면 상수.
553
+ * 모수가 모자라면(uniform 에 min/max 없음 등) 변동을 발명하지 않고 평균을 그대로 쓴다.
554
+ */
555
+ applyVariability(meanMs, v) {
556
+ if (!v || v.distribution === 'constant')
557
+ return meanMs;
558
+ if (v.distribution === 'exponential')
559
+ return -Math.log(1 - this.rng()) * meanMs;
560
+ const minMs = parseIsoDuration(v.min);
561
+ const maxMs = parseIsoDuration(v.max);
562
+ if (minMs === undefined || maxMs === undefined)
563
+ return meanMs;
564
+ return this.sampleSpread(meanMs, { distribution: v.distribution, minMs, maxMs, modeMs: parseIsoDuration(v.mode) });
565
+ }
566
+ /**
567
+ * 퍼짐 표본 — **엔진 난수원으로만** 뽑는다(fork 결정성). 선언 명세(ISO 표기)와 실측 분포(ms)가
568
+ * 같은 수식을 쓴다: 한쪽만 고치면 두 경로가 다른 답을 낸다.
569
+ * 모수가 모자라거나 뒤집혀 있으면 **퍼짐을 발명하지 않고** 평균을 그대로 쓴다.
570
+ */
571
+ sampleSpread(meanMs, spread) {
572
+ if (!spread)
573
+ return meanMs;
574
+ const { minMs, maxMs } = spread;
575
+ if (!Number.isFinite(minMs) || !Number.isFinite(maxMs) || maxMs < minMs)
576
+ return meanMs;
577
+ if (spread.distribution === 'uniform')
578
+ return minMs + this.rng() * (maxMs - minMs);
579
+ // triangular — 최빈값 미지정이면 평균을 최빈값으로 본다(구간 밖이면 안으로 클램프).
580
+ const mode = Math.min(maxMs, Math.max(minMs, spread.modeMs ?? meanMs));
581
+ const u = this.rng();
582
+ const span = maxMs - minMs;
583
+ if (span <= 0)
584
+ return minMs;
585
+ const c = (mode - minMs) / span;
586
+ return u < c ? minMs + Math.sqrt(u * span * (mode - minMs)) : maxMs - Math.sqrt((1 - u) * span * (maxMs - mode));
587
+ }
588
+ /** 명세 모수(숫자) — 선언 없으면 undefined(0 으로 꾸미지 않는다). 소비처가 기본값을 정한다. */
589
+ paramNumber(opKey, id) {
590
+ const p = this.operationSpecs.get(opKey)?.parameters?.find(x => x.id === id);
591
+ if (!p)
592
+ return undefined;
593
+ const n = Number(p.value);
594
+ if (!Number.isFinite(n))
595
+ return undefined;
596
+ this.noteParamUse(opKey, id);
597
+ return n;
598
+ }
599
+ /** 명세 모수(기간) — ISO 8601 문자열을 밀리초로. 선언 없으면 undefined. */
600
+ paramDuration(opKey, id) {
601
+ const p = this.operationSpecs.get(opKey)?.parameters?.find(x => x.id === id);
602
+ const ms = parseIsoDuration(p?.value);
603
+ if (ms !== undefined)
604
+ this.noteParamUse(opKey, id);
605
+ return ms;
606
+ }
607
+ noteSpecUse(kind, duration, variability) {
608
+ const cur = this.specUse.get(kind);
609
+ if (cur) {
610
+ cur.duration = duration;
611
+ if (variability)
612
+ cur.variability = variability;
613
+ return;
614
+ }
615
+ this.specUse.set(kind, { duration, ...(variability ? { variability } : {}), params: new Set() });
616
+ }
617
+ noteParamUse(kind, id) {
618
+ const cur = this.specUse.get(kind);
619
+ if (cur)
620
+ cur.params.add(id);
621
+ else
622
+ this.specUse.set(kind, { duration: 'default', params: new Set([id]) });
623
+ }
624
+ /**
625
+ * 시뮬 명세 자기보고 — **어디까지 데이터로 말했고 어디부터 우리가 박아 둔 상수인가.**
626
+ *
627
+ * 시뮬레이션 결과를 받는 쪽이 이걸 봐야 한다: 소요시간이 전부 기본값이면 그 예측으로 말할 수 있는 것은
628
+ * "같은 조건에서의 상대 비교" 뿐이고 "몇 시에 끝난다" 는 근거가 없다. 그 구분을 숫자로 드러낸다.
629
+ */
630
+ specCoverage() {
631
+ const operations = [...this.specUse.entries()].map(([kind, u]) => {
632
+ const spec = this.operationSpecs.get(kind);
633
+ /* 실측 분포를 쓴 경우가 우선 — 선언 명세의 변동보다 실제로 굴린 것이 사실이다. */
634
+ const variability = u.variability ?? spec?.variability?.distribution;
635
+ return {
636
+ kind,
637
+ duration: u.duration,
638
+ ...(variability ? { variability } : {}),
639
+ parameters: [...u.params].sort()
640
+ };
641
+ });
642
+ return {
643
+ operations,
644
+ measuredDurations: operations.filter(o => o.duration === 'measured').length,
645
+ declaredDurations: operations.filter(o => o.duration === 'declared').length,
646
+ defaultDurations: operations.filter(o => o.duration === 'default').length
647
+ };
409
648
  }
410
649
  /** skuMix 에서 weight 로 gtin 선택(rng) — 도착/오더 자극의 품목 결정. */
411
650
  pickGtin(mix) {
@@ -534,13 +773,244 @@ export class FlowEngine {
534
773
  for (const h of this.handlers)
535
774
  h(e);
536
775
  }
537
- emitTask(t) { this.emitOp(OP_EVENT.task, { taskId: t.id, orderId: t.orderId, kind: t.kind, status: t.status, fromNode: t.fromNode, toNode: t.toNode, itemRefs: [t.itemEpc], resourceRef: t.resource ?? undefined }); }
776
+ /**
777
+ * 작업 전이 방출 — **커널이 아는 것을 미러도 알게** 한다.
778
+ *
779
+ * 예전에는 진척·남은 시간·의도를 싣지 않아, 미러 상태를 씨앗으로 한 예측이 "진행 중인 일이 없는
780
+ * 현장" 에서 출발했고, 소비처는 무자원 체류를 기록 누락으로 오해할 수밖에 없었다.
781
+ * 진척은 진행 중일 때만 뜻이 있으므로 그때만 싣는다(생성·완료 시점의 0/1 은 노이즈).
782
+ */
783
+ emitTask(t) {
784
+ const inProgress = t.status === 'in-progress';
785
+ const done = Math.max(0, (t.durationMs ?? 0) - (t.remainingMs ?? 0));
786
+ this.emitOp(OP_EVENT.task, {
787
+ taskId: t.id, orderId: t.orderId, kind: t.kind, status: t.status,
788
+ fromNode: t.fromNode, toNode: t.toNode, itemRefs: [t.itemEpc], resourceRef: t.resource ?? undefined,
789
+ intent: t.intent,
790
+ ...(t.personnel?.length ? { personnel: t.personnel.slice() } : {}),
791
+ ...(t.assets?.length ? { assets: t.assets.slice() } : {}),
792
+ ...(t.durationMs ? { durationMs: t.durationMs } : {}),
793
+ ...(inProgress ? { remainingMs: t.remainingMs, progress: t.durationMs ? done / t.durationMs : undefined } : {})
794
+ });
795
+ }
796
+ /** 사람 상태 전이 — 설비와 별개 채널(어휘가 다르다: 고장이 아니라 교대·투입). */
797
+ emitAsset(a) {
798
+ this.emitOp(OP_EVENT.asset, { assetId: a.id, assetClass: a.assetClass, status: a.status, location: a.location, taskId: a.taskId ?? undefined, carrying: a.carrying });
799
+ }
800
+ emitPerson(p) {
801
+ this.emitOp(OP_EVENT.person, { personId: p.id, personnelClass: p.personnelClass, status: p.status, taskId: p.taskId ?? undefined, ...(this.personOffShift(p) ? { offShift: true } : {}) });
802
+ }
538
803
  emitMover(m, motion) { this.emitOp(OP_EVENT.equipment, { moverId: m.id, kind: m.kind, status: m.status, location: m.location, motion }); }
539
804
  emitOrder(o) { this.emitOp(OP_EVENT.order, { orderId: o.id, kind: o.kind, status: o.status, requested: o.requested, fulfilled: o.fulfilled, held: o.held }); }
540
805
  // ── 내부 mechanics ─────────────────────────────────────────────────────────
806
+ /**
807
+ * 자극 간격 — **계약이 선언한 네 분포를 실제로 판정한다.**
808
+ *
809
+ * 예전에는 `poisson` 만 구현하고 나머지는 전부 상수로 떨어졌다. 계약이 `uniform`·`profile` 을
810
+ * 선언하고 있었으므로, 그것을 지정한 사람은 자기가 요청한 분포로 도는 줄 알았다 — **조용한 거짓**이다.
811
+ *
812
+ * constant 간격이 일정(평균 그대로)
813
+ * poisson 무기억 도착(지수 간격) — 평균 유지
814
+ * uniform 0..2×평균 균등 — 평균을 유지하면서 흔들린다(교과서적 U(0,2μ))
815
+ * profile 시간대별 배율(`profile[시]`)로 도착률을 조절 — 하루 안의 수요 곡선
816
+ */
541
817
  intervalMs(spec) {
542
- const base = 3_600_000 / spec.rate.meanPerHour;
543
- return spec.rate.distribution === 'poisson' ? -Math.log(1 - this.rng()) * base : base;
818
+ const perHour = spec.rate.meanPerHour * this.profileFactor(spec.rate);
819
+ if (!(perHour > 0))
820
+ return Number.POSITIVE_INFINITY; // 그 시간대엔 도착이 없다(0 을 1/0=∞ 로 정직하게)
821
+ const base = 3_600_000 / perHour;
822
+ switch (spec.rate.distribution) {
823
+ case 'poisson':
824
+ return -Math.log(1 - this.rng()) * base;
825
+ case 'uniform':
826
+ return this.rng() * 2 * base;
827
+ case 'profile':
828
+ case 'constant':
829
+ default:
830
+ return base;
831
+ }
832
+ }
833
+ /**
834
+ * 시간대 배율 — `profile[시]`. `profile` 분포일 때만 적용하며, 배열이 짧으면 **순환**한다
835
+ * (24개면 하루, 8개면 8시간 주기). 미지정·다른 분포면 1(무영향).
836
+ * 시(hour)는 **시뮬 시각 자신의 프레임**(BASE_EPOCH 기준 UTC)이다 — 계약에 표준시가 없으므로
837
+ * 현지 시간대 해석은 아직 하지 않는다(꾸미지 않는다).
838
+ */
839
+ /**
840
+ * 다음 발화 시각 — **발화가 없는 시간대를 영원한 침묵으로 만들지 않는다.**
841
+ *
842
+ * 배율 0(그 시간대 도착 없음)이면 간격이 무한이 된다. 그것을 그대로 예약하면 이후 어떤 시간대가
843
+ * 와도 깨어나지 않는다 — 그래서 **다음 정시로 미뤄 다시 판정**한다(시간대가 바뀌면 배율도 바뀐다).
844
+ * 시나리오 시작과 구동 루프가 같은 규칙을 쓰도록 한 곳에 둔다(예전에는 시작 경로만 따로였다).
845
+ */
846
+ nextFireMs(spec, from) {
847
+ const interval = this.intervalMs(spec);
848
+ if (Number.isFinite(interval))
849
+ return from + interval;
850
+ const hourMs = 3_600_000;
851
+ return Math.floor(from / hourMs) * hourMs + hourMs; // 다음 정시에 재판정
852
+ }
853
+ profileFactor(rate) {
854
+ if (rate.distribution !== 'profile')
855
+ return 1;
856
+ const p = rate.profile;
857
+ if (!p?.length)
858
+ return 1;
859
+ const f = p[this.hourOfDay() % p.length];
860
+ return Number.isFinite(f) && f >= 0 ? f : 1;
861
+ }
862
+ /**
863
+ * 필요 물리 자산을 확보한다 — 인원과 **같은 규칙**(등급으로 요구, 부분 투입 없음, 확정은 나중).
864
+ * 자산은 사람과 달리 교대가 없고 **자리**가 있다(빈 팔레트가 어디 있는지가 다음 문제이지만,
865
+ * 지금은 자리를 따지지 않는다 — 따지려면 자산 이송 작업이 먼저 있어야 한다).
866
+ */
867
+ claimAssets(t) {
868
+ const need = this.operationSpecs.get(t.kind)?.physicalAssetSpecification;
869
+ if (!need?.length)
870
+ return [];
871
+ const picked = [];
872
+ for (const req of need) {
873
+ const want = Math.max(0, Math.floor(req.quantity ?? 0));
874
+ if (!want)
875
+ continue;
876
+ const avail = [...this.assets.values()].filter(a => a.status === 'idle' && !picked.includes(a.id) && (req.assetClass === undefined || a.assetClass === req.assetClass));
877
+ if (avail.length < want)
878
+ return null;
879
+ for (let i = 0; i < want; i++)
880
+ picked.push(avail[i].id);
881
+ }
882
+ return picked;
883
+ }
884
+ /** 확보한 자산을 작업에 묶는다 — 싣는 물류단위(SSCC)가 있으면 연결한다(GRAI ↔ SSCC). */
885
+ assignAssets(t, gear) {
886
+ if (!gear.length)
887
+ return;
888
+ t.assets = gear;
889
+ for (const id of gear) {
890
+ const a = this.assets.get(id);
891
+ if (!a)
892
+ continue;
893
+ a.status = 'in-use';
894
+ a.taskId = t.id;
895
+ if (t.itemEpc)
896
+ a.carrying = t.itemEpc;
897
+ this.emitAsset(a);
898
+ }
899
+ }
900
+ /**
901
+ * 작업이 끝나면 자산을 놓아 준다 — **사람과 다른 점: 자산은 도착 자리에 남는다**(물건이므로).
902
+ * 싣고 있던 것은 놓는다(빈 팔레트로 돌아간다 — 회수·재사용의 출발점).
903
+ */
904
+ releaseAssets(t) {
905
+ for (const id of t.assets ?? []) {
906
+ const a = this.assets.get(id);
907
+ if (!a)
908
+ continue;
909
+ a.status = 'idle';
910
+ a.taskId = null;
911
+ a.location = t.toNode || a.location;
912
+ a.carrying = undefined;
913
+ this.emitAsset(a);
914
+ }
915
+ }
916
+ /**
917
+ * 필요 인원을 확보한다 — **등급으로 요구하고 등급으로 고른다**(특정인 지목이 아니다).
918
+ * 요구가 없으면 빈 배열, 모자라면 `null`(작업은 기다린다 — **부분 투입으로 시작하지 않는다**).
919
+ * 여기서는 고르기만 하고 잡지 않는다: 설비까지 확보된 뒤 `assignCrew` 가 확정한다
920
+ * (반쯤 잡고 실패하면 사람이 아무 일도 못 하면서 묶인다).
921
+ */
922
+ claimPersonnel(t) {
923
+ const need = this.operationSpecs.get(t.kind)?.personnelSpecification;
924
+ if (!need?.length)
925
+ return [];
926
+ const picked = [];
927
+ for (const req of need) {
928
+ const want = Math.max(0, Math.floor(req.quantity ?? 0));
929
+ if (!want)
930
+ continue;
931
+ const avail = [...this.persons.values()].filter(p => p.status === 'idle' &&
932
+ !picked.includes(p.id) &&
933
+ !this.personOffShift(p) &&
934
+ (req.personnelClass === undefined || p.personnelClass === req.personnelClass));
935
+ if (avail.length < want)
936
+ return null; // 한 등급이라도 모자라면 시작하지 않는다
937
+ for (let i = 0; i < want; i++)
938
+ picked.push(avail[i].id);
939
+ }
940
+ return picked;
941
+ }
942
+ /** 확보한 사람을 작업에 묶는다(설비까지 확정된 뒤). */
943
+ assignCrew(t, crew) {
944
+ if (!crew.length)
945
+ return;
946
+ t.personnel = crew;
947
+ for (const id of crew) {
948
+ const p = this.persons.get(id);
949
+ if (!p)
950
+ continue;
951
+ p.status = 'busy';
952
+ p.taskId = t.id;
953
+ this.emitPerson(p);
954
+ }
955
+ }
956
+ /** 작업이 끝나면 사람을 놓아 준다 — 설비 해제와 별개 경로. */
957
+ releaseCrew(t) {
958
+ for (const id of t.personnel ?? []) {
959
+ const p = this.persons.get(id);
960
+ if (!p)
961
+ continue;
962
+ p.status = 'idle';
963
+ p.taskId = null;
964
+ this.emitPerson(p);
965
+ }
966
+ }
967
+ /** 사람의 교대 판정 — 자원(offShift)과 같은 규칙. */
968
+ personOffShift(p) {
969
+ const w = p.window;
970
+ if (!w)
971
+ return false;
972
+ const h = this.hourOfDay();
973
+ return !(w.startHour <= w.endHour ? h >= w.startHour && h < w.endHour : h >= w.startHour || h < w.endHour);
974
+ }
975
+ /**
976
+ * 이 자리가 동시 처리 한도에 찼는가 — `parallelism` 을 선언한 자리만 판정한다(미선언=제약 없음).
977
+ * 세는 대상은 **그 자리에서 진행 중인 작업**(`toNode` 기준, in-progress). 대기 중인 작업은 세지 않는다.
978
+ */
979
+ stationFull(nodeId) {
980
+ if (!nodeId)
981
+ return false;
982
+ const limit = this.nodes.get(nodeId)?.parallelism;
983
+ if (!(typeof limit === 'number' && limit > 0))
984
+ return false;
985
+ let running = 0;
986
+ for (const t of this.tasks.values())
987
+ if (t.status === 'in-progress' && t.toNode === nodeId)
988
+ running++;
989
+ return running >= limit;
990
+ }
991
+ /** 교대 밖인가 — 자원이 지금 일하지 않는 이유 중 고장·계획정지와 구별되는 세 번째. */
992
+ offShift(m) {
993
+ const w = m.window;
994
+ if (!w)
995
+ return false;
996
+ const h = this.hourOfDay();
997
+ return !(w.startHour <= w.endHour ? h >= w.startHour && h < w.endHour : h >= w.startHour || h < w.endHour);
998
+ }
999
+ /** 시뮬 시각의 시(0..23) — 운영시간·시간대 배율의 기준. */
1000
+ hourOfDay() {
1001
+ return new Date(BASE_EPOCH + this.clockMs).getUTCHours();
1002
+ }
1003
+ /**
1004
+ * 운영시간 안인가 — `window {startHour, endHour}`. **선언만 되고 소비처가 없던 필드**를 판정한다.
1005
+ * `startHour <= endHour` 면 같은 날 구간, 넘어가면 자정을 가로지르는 구간(야간 교대: 22→6).
1006
+ * 미지정이면 언제나 참(24시간 가동).
1007
+ */
1008
+ inWindow(spec) {
1009
+ const w = spec.window;
1010
+ if (!w)
1011
+ return true;
1012
+ const h = this.hourOfDay();
1013
+ return w.startHour <= w.endHour ? h >= w.startHour && h < w.endHour : h >= w.startHour || h < w.endHour;
544
1014
  }
545
1015
  /** 지수분포 표본(고장/수리 간격) — mean 을 평균으로 하는 무기억 프로세스. */
546
1016
  sampleExp(meanMs) { return -Math.log(1 - this.rng()) * meanMs; }
@@ -582,6 +1052,18 @@ export class FlowEngine {
582
1052
  generate() {
583
1053
  for (const g of this.gens) {
584
1054
  while (this.clockMs >= g.nextMs) {
1055
+ const next = this.nextFireMs(g.spec, g.nextMs);
1056
+ /* 배율 0(도착 없는 시간대) — 발화하지 않고 다음 정시에 다시 판정한다. */
1057
+ if (this.intervalMs(g.spec) === Number.POSITIVE_INFINITY) {
1058
+ g.nextMs = next;
1059
+ continue;
1060
+ }
1061
+ /* 운영시간 밖이면 **자극을 만들지 않고 다음 슬롯으로 넘긴다** — 문을 닫은 시간에 트럭이 오지
1062
+ * 않는다. 예전에는 window 를 아무도 보지 않아 24시간 가동으로만 굴렀다. */
1063
+ if (!this.inWindow(g.spec)) {
1064
+ g.nextMs = next;
1065
+ continue;
1066
+ }
585
1067
  // 자극 클래스(공급/수요)로 hook 분기 — 도메인 kind 라벨이 아니라 stimulus 로 라우팅(무방언).
586
1068
  // stimulus 미지정 시 레거시 kind 로 추론(하위호환). 도메인은 kind 를 자유 명명하고 stimulus 로 분류.
587
1069
  const stimulus = g.spec.stimulus ?? (g.spec.kind === 'outbound-order' ? 'order' : 'arrival');
@@ -589,7 +1071,7 @@ export class FlowEngine {
589
1071
  this.onOrder(g.spec);
590
1072
  else
591
1073
  this.onArrival(g.spec);
592
- g.nextMs += this.intervalMs(g.spec);
1074
+ g.nextMs = next;
593
1075
  }
594
1076
  }
595
1077
  }
@@ -603,14 +1085,29 @@ export class FlowEngine {
603
1085
  for (const t of this.tasks.values()) {
604
1086
  if (t.status !== 'created')
605
1087
  continue;
606
- if (t.intent === 'dwell') { // 무자원 체류 자원 배정 없이 즉시 진행
1088
+ /* 필요 인원 오퍼레이션 명세가 요구하면 등급별로 사람을 잡는다. 모자라면 **기다린다**
1089
+ * (설비가 놀아도 사람이 없으면 일이 안 된다 — 그 줄이 현장의 실제 병목인 경우가 많다). */
1090
+ const crew = this.claimPersonnel(t);
1091
+ if (crew === null)
1092
+ continue; // 인원 부족 → 다음 작업(다른 등급은 가능할 수 있다)
1093
+ /* 필요 물리 자산 — 빈 팔레트가 없으면 출고가 못 나간다. 인원과 같은 규칙(부분 투입 없음). */
1094
+ const gear = this.claimAssets(t);
1095
+ if (gear === null)
1096
+ continue;
1097
+ if (t.intent === 'dwell') { // 무설비 체류 — 설비 배정 없이 진행(인원 요구가 있으면 위에서 확보됨)
607
1098
  t.status = 'in-progress';
608
1099
  t.remainingMs = t.durationMs;
1100
+ this.assignCrew(t, crew);
1101
+ this.assignAssets(t, gear);
609
1102
  this.emitTask(t);
610
1103
  continue;
611
1104
  }
612
- // resourceType 있으면 kind 무버만; 없으면 아무 유휴 무버.
613
- const mover = [...this.movers.values()].find(m => m.status === 'idle' && !m.held && (t.resourceType === undefined || m.kind === t.resourceType));
1105
+ /* 자리의 동시 처리 수를 넘지 않는다 자원이 남아도 스테이션이 한 대씩만 깎으면 줄을 선다.
1106
+ * 제약이 없으면 대기가 생기지 않아 병목이 사라지고 예측이 낙관 쪽으로 치우친다. */
1107
+ if (this.stationFull(t.toNode))
1108
+ continue;
1109
+ // resourceType 있으면 그 kind 무버만; 없으면 아무 유휴 무버. 교대 밖 자원은 배정하지 않는다.
1110
+ const mover = [...this.movers.values()].find(m => m.status === 'idle' && !m.held && !this.offShift(m) && (t.resourceType === undefined || m.kind === t.resourceType));
614
1111
  if (!mover)
615
1112
  continue; // 맞는 유휴 자원 없음 → 다음 task(break 아님: 다른 타입은 가용할 수 있음)
616
1113
  // 체인지오버: task 의 changeoverKey 가 무버 직전 키와 다르면 셋업 부착(첫 작업은 셋업 없음).
@@ -625,6 +1122,8 @@ export class FlowEngine {
625
1122
  t.status = 'in-progress';
626
1123
  t.resource = mover.id;
627
1124
  t.remainingMs = t.durationMs;
1125
+ this.assignCrew(t, crew);
1126
+ this.assignAssets(t, gear);
628
1127
  this.emitTask(t);
629
1128
  // process: 제자리 변환(모션 없음). transport: 이동 모션 방출.
630
1129
  if (t.intent === 'process')
@@ -643,6 +1142,8 @@ export class FlowEngine {
643
1142
  continue;
644
1143
  this.onTaskComplete(t);
645
1144
  t.status = 'completed';
1145
+ this.releaseCrew(t); // 사람은 설비와 별개로 해제한다(dwell 도 사람은 잡고 있었을 수 있다)
1146
+ this.releaseAssets(t); // 자산도 같다 — 자산은 도착 자리에 남는다(사람과 달리 물건이므로)
646
1147
  if (!t.resource) {
647
1148
  this.emitTask(t);
648
1149
  continue;