@camstack/system 1.2.146 → 1.2.147

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.
Files changed (63) hide show
  1. package/dist/addon-runner.js +1 -1
  2. package/dist/addon-runner.mjs +1 -1
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  10. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  11. package/dist/builtins/console-logging/index.js +1 -1
  12. package/dist/builtins/console-logging/index.mjs +1 -1
  13. package/dist/builtins/core-blocks/core-blocks.addon.js +1 -1
  14. package/dist/builtins/core-blocks/core-blocks.addon.mjs +1 -1
  15. package/dist/builtins/device-manager/device-manager.addon.js +2 -2
  16. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  17. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -1
  18. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -1
  19. package/dist/builtins/hub-forwarder/index.js +1 -1
  20. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  21. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  22. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  23. package/dist/builtins/local-auth/local-auth.addon.js +1 -1
  24. package/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  25. package/dist/builtins/local-network/local-network.addon.js +1 -1
  26. package/dist/builtins/local-network/local-network.addon.mjs +1 -1
  27. package/dist/builtins/loki-logging/index.js +1 -1
  28. package/dist/builtins/loki-logging/index.mjs +1 -1
  29. package/dist/builtins/native-metrics/load-series-config.d.ts +74 -0
  30. package/dist/builtins/native-metrics/load-series-reader.d.ts +37 -0
  31. package/dist/builtins/native-metrics/load-series-store.d.ts +232 -0
  32. package/dist/builtins/native-metrics/native-metrics.addon.d.ts +118 -35
  33. package/dist/builtins/native-metrics/native-metrics.addon.js +1463 -199
  34. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1463 -199
  35. package/dist/builtins/native-metrics/node-load-ring.d.ts +214 -0
  36. package/dist/builtins/native-metrics/process-classification.d.ts +51 -0
  37. package/dist/builtins/native-metrics/thread-cpu-sampler.d.ts +116 -0
  38. package/dist/builtins/platform-probe/index.js +1 -1
  39. package/dist/builtins/platform-probe/index.mjs +1 -1
  40. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  41. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  42. package/dist/builtins/snapshot/index.js +1 -1
  43. package/dist/builtins/snapshot/index.mjs +1 -1
  44. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  45. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  46. package/dist/builtins/sqlite-storage/sqlite-settings-backend.d.ts +25 -1
  47. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +0 -0
  48. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +0 -0
  49. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +2 -1
  50. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +2 -1
  51. package/dist/builtins/system-config/system-config.addon.js +1 -1
  52. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  53. package/dist/builtins/winston-logging/index.js +1 -1
  54. package/dist/builtins/winston-logging/index.mjs +1 -1
  55. package/dist/{dist-BVU5JADq.js → dist-Dl6MFXPr.js} +496 -35
  56. package/dist/{dist-CG7kwIZp.mjs → dist-DrBc-7Y3.mjs} +479 -36
  57. package/dist/index.js +2 -2
  58. package/dist/index.mjs +2 -2
  59. package/dist/{manifest-python-deps-CVeckyXx.mjs → manifest-python-deps-DhT0oFOZ.mjs} +1 -1
  60. package/dist/{manifest-python-deps-CktMcXzS.js → manifest-python-deps-FYZBHc3v.js} +1 -1
  61. package/dist/{retired-settings-keys-_PLI9w0k.js → retired-settings-keys-6w_JOqBg.js} +1 -1
  62. package/dist/{retired-settings-keys-Dm1z4mO4.mjs → retired-settings-keys-CF5r4YKq.mjs} +1 -1
  63. package/package.json +1 -1
@@ -3,7 +3,8 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-BVU5JADq.js");
6
+ const require_dist = require("../../dist-Dl6MFXPr.js");
7
+ let node_fs_promises = require("node:fs/promises");
7
8
  let node_child_process = require("node:child_process");
8
9
  let node_util = require("node:util");
9
10
  let node_os = require("node:os");
@@ -465,9 +466,933 @@ function execAsync(cmd, args, timeoutMs = 5e3) {
465
466
  });
466
467
  });
467
468
  }
469
+ /**
470
+ * One node's fixed-capacity circular buffer of samples.
471
+ *
472
+ * Mirrors {@link LogRingBuffer}: write at `head`, wrap, and once full every
473
+ * accepted sample evicts the oldest. `rows` is carried alongside so the fleet
474
+ * budget never has to walk the samples to know what a partition costs.
475
+ */
476
+ var LoadPartition = class {
477
+ capacity;
478
+ slots;
479
+ head = 0;
480
+ count = 0;
481
+ rows = 0;
482
+ /** Newest retained sample's timestamp — the monotonic gate for `push`. */
483
+ newestAtMs = null;
484
+ constructor(capacity) {
485
+ this.capacity = capacity;
486
+ this.slots = Array.from({ length: capacity });
487
+ }
488
+ /**
489
+ * Accept a sample.
490
+ *
491
+ * A sample at or before the newest one already held is REFUSED. The bus drops
492
+ * a node's own broadcast echo, but a cross-node redelivery or a replayed
493
+ * subscription must not be able to double a point — and idempotence here is
494
+ * what lets every reader above treat the series as a set.
495
+ *
496
+ * `accepted` is reported separately from `rowDelta` on purpose: a full ring
497
+ * that evicts a sample of the same size has a delta of zero and is not a
498
+ * refusal, and conflating the two would silently stop advancing the write
499
+ * ordinal on a steady-state cluster.
500
+ */
501
+ push(sample) {
502
+ if (this.newestAtMs !== null && sample.atMs <= this.newestAtMs) return {
503
+ accepted: false,
504
+ rowDelta: 0
505
+ };
506
+ const evicted = this.count === this.capacity ? this.slots[this.head]?.processes.length ?? 0 : 0;
507
+ this.slots[this.head] = sample;
508
+ this.head = (this.head + 1) % this.capacity;
509
+ if (this.count < this.capacity) this.count++;
510
+ this.newestAtMs = sample.atMs;
511
+ const rowDelta = sample.processes.length - evicted;
512
+ this.rows += rowDelta;
513
+ return {
514
+ accepted: true,
515
+ rowDelta
516
+ };
517
+ }
518
+ /** Drop the oldest sample. Returns the rows reclaimed (0 when empty). */
519
+ dropOldest() {
520
+ if (this.count === 0) return 0;
521
+ const index = (this.head - this.count + this.capacity) % this.capacity;
522
+ const victim = this.slots[index];
523
+ this.slots[index] = void 0;
524
+ this.count--;
525
+ const reclaimed = victim?.processes.length ?? 0;
526
+ this.rows -= reclaimed;
527
+ if (this.count === 0) this.newestAtMs = null;
528
+ return reclaimed;
529
+ }
530
+ /** Oldest-first, optionally only what is strictly newer than `sinceMs`. */
531
+ list(sinceMs) {
532
+ const out = [];
533
+ for (let i = 0; i < this.count; i++) {
534
+ const index = (this.head - this.count + i + this.capacity) % this.capacity;
535
+ const sample = this.slots[index];
536
+ if (sample === void 0) continue;
537
+ if (sinceMs !== void 0 && sample.atMs <= sinceMs) continue;
538
+ out.push(sample);
539
+ }
540
+ return out;
541
+ }
542
+ size() {
543
+ return this.count;
544
+ }
545
+ rowCount() {
546
+ return this.rows;
547
+ }
548
+ oldestAtMs() {
549
+ if (this.count === 0) return null;
550
+ const index = (this.head - this.count + this.capacity) % this.capacity;
551
+ return this.slots[index]?.atMs ?? null;
552
+ }
553
+ lastWriteAtMs() {
554
+ return this.newestAtMs;
555
+ }
556
+ };
557
+ /**
558
+ * The partitioned ring: one {@link LoadPartition} per node id.
559
+ *
560
+ * Three bounds, doing three different jobs — the same division as the log
561
+ * buffer, for the same reason:
562
+ *
563
+ * - **`samplesPerNode`** is HARD and per partition. It is what the operator
564
+ * asked for (an hour) and it can never be exceeded.
565
+ * - **`maxTotalProcessRows`** is the FLEET budget, and it is denominated in the
566
+ * thing memory is proportional to. When it bites, the oldest sample of the
567
+ * HEAVIEST partition is dropped — the node creating the pressure is the node
568
+ * that pays, and a quiet node keeps its full hour. The node just written to is
569
+ * NOT protected here: if it is the heaviest, it is the culprit.
570
+ * - **`maxNodes`** is the backstop against an unbounded key space, and it drops
571
+ * whole partitions least-recently-written first, never the one being written.
572
+ *
573
+ * Plus {@link DEFAULT_NODE_IDLE_EVICTION_MS}, which is what stops a node that
574
+ * simply stopped emitting from living in memory forever.
575
+ */
576
+ var NodeLoadRing = class {
577
+ partitions = /* @__PURE__ */ new Map();
578
+ /**
579
+ * Node id → write ordinal of its last accepted sample. A monotonic counter,
580
+ * not a clock: partition eviction must follow the order writes actually
581
+ * happened, and node clocks disagree.
582
+ */
583
+ lastWriteSeq = /* @__PURE__ */ new Map();
584
+ writeSeq = 0;
585
+ totalRows = 0;
586
+ samplesPerNode;
587
+ maxTotalProcessRows;
588
+ maxNodes;
589
+ idleEvictionMs;
590
+ now;
591
+ constructor(options = {}) {
592
+ this.samplesPerNode = options.samplesPerNode ?? 180;
593
+ this.maxTotalProcessRows = options.maxTotalProcessRows ?? 32e3;
594
+ this.maxNodes = options.maxNodes ?? 16;
595
+ this.idleEvictionMs = options.idleEvictionMs ?? 36e5;
596
+ this.now = options.now ?? Date.now;
597
+ }
598
+ /**
599
+ * Retain one snapshot. `processes` is stored by reference — the payload is
600
+ * already an immutable arrival off the bus, and copying it would double the
601
+ * measured cost for nothing.
602
+ *
603
+ * Returns whether the sample was ACCEPTED — that is, whether it was new
604
+ * rather than a replay of a timestamp this node has already delivered.
605
+ *
606
+ * The return value is not diagnostics. It is the idempotence gate the
607
+ * DURABLE tier rides on (`load-series-store.ts`): only an accepted sample is
608
+ * appended to the table, which is what lets that table carry an `INTEGER`
609
+ * rowid key instead of a composite unique index over two million rows. The
610
+ * gate is one monotonic comparison in memory; the index it replaces was
611
+ * measured at ~40 bytes per row.
612
+ */
613
+ record(nodeId, atMs, processes) {
614
+ if (nodeId.length === 0) return false;
615
+ this.sweepIdle();
616
+ let partition = this.partitions.get(nodeId);
617
+ if (partition === void 0) {
618
+ partition = new LoadPartition(this.samplesPerNode);
619
+ this.partitions.set(nodeId, partition);
620
+ }
621
+ const outcome = partition.push({
622
+ atMs,
623
+ processes
624
+ });
625
+ if (!outcome.accepted) {
626
+ if (partition.size() === 0) this.partitions.delete(nodeId);
627
+ return false;
628
+ }
629
+ this.totalRows += outcome.rowDelta;
630
+ this.lastWriteSeq.set(nodeId, ++this.writeSeq);
631
+ if (this.partitions.size > this.maxNodes) this.evictPartitions(this.partitions.size - this.maxNodes, nodeId);
632
+ this.enforceRowBudget();
633
+ return true;
634
+ }
635
+ /**
636
+ * Read one node's retained series, oldest-first.
637
+ *
638
+ * `sinceMs` is EXCLUSIVE: a caller passes the newest timestamp it already
639
+ * holds and gets back only what it is missing. That is the whole contract
640
+ * that lets the admin UI seed from here and then continue live without
641
+ * doubling a point it already drew.
642
+ *
643
+ * A node nobody has recorded answers with an empty series, not an error —
644
+ * unknown is the truth about a node that has not reported.
645
+ */
646
+ read(nodeId, sinceMs) {
647
+ this.sweepIdle();
648
+ const partition = this.partitions.get(nodeId);
649
+ if (partition === void 0) return {
650
+ nodeId,
651
+ samples: [],
652
+ retainedSamples: 0,
653
+ oldestAtMs: null,
654
+ capacity: this.samplesPerNode
655
+ };
656
+ return {
657
+ nodeId,
658
+ samples: partition.list(sinceMs),
659
+ retainedSamples: partition.size(),
660
+ oldestAtMs: partition.oldestAtMs(),
661
+ capacity: this.samplesPerNode
662
+ };
663
+ }
664
+ /** Node ids with a live partition. Observability for the fleet bound. */
665
+ nodeIds() {
666
+ return [...this.partitions.keys()];
667
+ }
668
+ /** Process rows retained across every partition — the number that IS memory. */
669
+ rowCount() {
670
+ return this.totalRows;
671
+ }
672
+ /** Samples retained across every partition. */
673
+ sampleCount() {
674
+ let total = 0;
675
+ for (const partition of this.partitions.values()) total += partition.size();
676
+ return total;
677
+ }
678
+ /**
679
+ * Drop partitions whose newest sample is older than the retention window.
680
+ *
681
+ * Lazy, on write and on read — never a timer. A timer would be a new
682
+ * periodic cost in a subsystem whose entire premise is that it adds none,
683
+ * and a ring that nobody writes to and nobody reads is not growing either.
684
+ */
685
+ sweepIdle() {
686
+ const cutoff = this.now() - this.idleEvictionMs;
687
+ for (const [nodeId, partition] of [...this.partitions.entries()]) {
688
+ const lastWrite = partition.lastWriteAtMs();
689
+ if (lastWrite !== null && lastWrite > cutoff) continue;
690
+ this.dropPartition(nodeId);
691
+ }
692
+ }
693
+ /**
694
+ * Bring the fleet back under the row budget by dropping the OLDEST sample of
695
+ * the HEAVIEST partition, repeatedly.
696
+ *
697
+ * Terminates: every iteration removes one sample from a non-empty partition,
698
+ * and the population of samples is finite and strictly decreasing.
699
+ */
700
+ enforceRowBudget() {
701
+ while (this.totalRows > this.maxTotalProcessRows) {
702
+ const victim = this.heaviestPartition();
703
+ if (victim === null) return;
704
+ const [nodeId, partition] = victim;
705
+ this.totalRows -= partition.dropOldest();
706
+ if (partition.size() === 0) this.dropPartition(nodeId);
707
+ }
708
+ }
709
+ heaviestPartition() {
710
+ let best = null;
711
+ for (const entry of this.partitions.entries()) {
712
+ if (entry[1].size() === 0) continue;
713
+ if (best === null || entry[1].rowCount() > best[1].rowCount()) best = entry;
714
+ }
715
+ return best;
716
+ }
717
+ /** Drop `count` whole partitions, least-recently-written first. */
718
+ evictPartitions(count, protectedNodeId) {
719
+ const order = [...this.partitions.keys()].filter((nodeId) => nodeId !== protectedNodeId).toSorted((a, b) => (this.lastWriteSeq.get(a) ?? 0) - (this.lastWriteSeq.get(b) ?? 0));
720
+ let remaining = count;
721
+ for (const nodeId of order) {
722
+ if (remaining <= 0) return;
723
+ this.dropPartition(nodeId);
724
+ remaining -= 1;
725
+ }
726
+ }
727
+ /** Remove a partition and everything that indexes it. */
728
+ dropPartition(nodeId) {
729
+ const partition = this.partitions.get(nodeId);
730
+ if (partition === void 0) return;
731
+ this.totalRows -= partition.rowCount();
732
+ this.partitions.delete(nodeId);
733
+ this.lastWriteSeq.delete(nodeId);
734
+ }
735
+ };
468
736
  //#endregion
469
- //#region src/builtins/native-metrics/native-metrics.addon.ts
470
- var execFileAsync = (0, node_util.promisify)(node_child_process.execFile);
737
+ //#region src/builtins/native-metrics/load-series-store.ts
738
+ /**
739
+ * @durable class=audit owner=metrics-native
740
+ * write="one row per process per sample, appended in ONE transaction per
741
+ * sample (`settingsStore.insertMany`) by the HUB's `native-metrics`, off its
742
+ * subscription to `metrics.node-processes-snapshot`. Emission is
743
+ * fixed-cadence, so the write rate is deterministic: nodes x processes /
744
+ * cadence, 7.6 rows/s on the live fleet at the 10 s default. Only a sample
745
+ * the in-memory ring ACCEPTED is written, which is what makes the append
746
+ * idempotent without a unique key."
747
+ * retention="TWO bounds, swept together at most once a minute. By AGE, the
748
+ * operator's `loadSeriesRetentionHours` (default 6, the intention); by ROWS,
749
+ * DEFAULT_MAX_ROWS (the guarantee, which bites regardless of the age knob).
750
+ * Both prune oldest-first through a bounded page — never a full scan — and
751
+ * the row cap logs when it bites. Losing the table loses the cold window
752
+ * only: the ring keeps serving the last hour and the charts keep drawing."
753
+ */
754
+ var LOAD_SERIES_COLLECTION = "metrics:node-load-samples";
755
+ /**
756
+ * Hard ceiling on the table, in ROWS.
757
+ *
758
+ * The guarantee behind the retention knob. Sized against the shipped default
759
+ * and against the worst configuration the knob can express:
760
+ *
761
+ * | cadence | retention | rows (3 nodes, 76 processes) |
762
+ * | --- | --- | --- |
763
+ * | 10 s | 6 h (default) | 164 160 |
764
+ * | 5 s | 6 h | 328 320 |
765
+ * | 5 s | 72 h | 3 939 840 — capped here |
766
+ *
767
+ * 500 000 rows x the measured 87 B = **41.5 MiB**, roughly 3x what the shipped
768
+ * default needs and far below the 2 M rows a three-day retention would reach.
769
+ * It is deliberately NOT a knob: the point of a guarantee is that it is not
770
+ * subject to the same hand that raised the intention. This is the discipline
771
+ * the in-memory ring already adopted (`DEFAULT_MAX_TOTAL_PROCESS_ROWS`) and
772
+ * the one the RTP pre-roll rings still lack — a maximum per instance and no
773
+ * budget at all for the whole, which reached 898 MB across 47 rings
774
+ * (`docs/architecture/load-ledger.md` #5).
775
+ */
776
+ var DEFAULT_MAX_ROWS = 5e5;
777
+ var LOAD_SERIES_COLUMNS = [
778
+ (
779
+ /** `INTEGER PRIMARY KEY` = SQLite rowid alias: the key IS the row's address,
780
+ * so it costs no separate index and no stored string. */
781
+ {
782
+ name: "id",
783
+ type: "INTEGER",
784
+ primaryKey: true,
785
+ notNull: true
786
+ }),
787
+ {
788
+ name: "nodeId",
789
+ type: "TEXT",
790
+ notNull: true
791
+ },
792
+ (
793
+ /** The EMITTING node's timestamp for the sample this row belongs to. Every
794
+ * row of one sample shares it — that is what makes a sample reassemblable. */
795
+ {
796
+ name: "atMs",
797
+ type: "INTEGER",
798
+ notNull: true
799
+ }),
800
+ {
801
+ name: "pid",
802
+ type: "INTEGER",
803
+ notNull: true
804
+ },
805
+ (
806
+ /** `NULL` for a process no addon owns — `root` and `system` both. */
807
+ {
808
+ name: "addonId",
809
+ type: "TEXT"
810
+ }),
811
+ {
812
+ name: "classification",
813
+ type: "TEXT",
814
+ notNull: true
815
+ },
816
+ (
817
+ /** `ps pcpu` x 10. A LIFETIME average, not a rate — see `NodeProcess`. */
818
+ {
819
+ name: "cpuDeci",
820
+ type: "INTEGER",
821
+ notNull: true
822
+ }),
823
+ {
824
+ name: "rssMib",
825
+ type: "INTEGER",
826
+ notNull: true
827
+ },
828
+ (
829
+ /** Instantaneous main-thread CPU% x 10. `NULL` = UNKNOWN, never zero. */
830
+ {
831
+ name: "cpuMainDeci",
832
+ type: "INTEGER"
833
+ }),
834
+ (
835
+ /** Instantaneous V8-helper-pool CPU% x 10. `NULL` = UNKNOWN, never zero. */
836
+ {
837
+ name: "cpuGcDeci",
838
+ type: "INTEGER"
839
+ })
840
+ ];
841
+ var LOAD_SERIES_INDEXES = [(
842
+ /**
843
+ * The ONE index, and it serves both jobs.
844
+ *
845
+ * Reads are always "this node, newer than T" — `nodeId` leads so the
846
+ * equality is a range scan and `atMs` supplies the order without a sort.
847
+ * Prunes are always "this node, oldest first" — the same index, walked from
848
+ * the other end. A second index on `atMs` alone was measured and rejected:
849
+ * it cost 23 B/row (196.0 → 172.8 with the two column drops) to serve a
850
+ * cross-node prune that a per-node loop over three nodes already serves.
851
+ */
852
+ {
853
+ name: "idx_load_samples_node_at",
854
+ columns: ["nodeId", "atMs"]
855
+ })];
856
+ var BYTES_PER_MIB = 1048576;
857
+ /** Tenths → percent. `null` stays `null`: unknown is not zero. */
858
+ function fromDeci(value) {
859
+ return value === null ? null : Math.round(value) / 10;
860
+ }
861
+ /** Percent → tenths, lossless because both producers already round to tenths. */
862
+ function toDeci(value) {
863
+ return value === null ? null : Math.round(value * 10);
864
+ }
865
+ /** Storage row → the shape a reader gets. The ONE decode. */
866
+ function rowToProcess(row) {
867
+ return {
868
+ pid: row.pid,
869
+ addonId: row.addonId,
870
+ classification: row.classification,
871
+ cpuPercent: fromDeci(row.cpuDeci) ?? 0,
872
+ memoryRssBytes: row.rssMib * BYTES_PER_MIB,
873
+ cpuMainPercent: fromDeci(row.cpuMainDeci),
874
+ cpuGcPercent: fromDeci(row.cpuGcDeci)
875
+ };
876
+ }
877
+ /** The shape a reader gets → the storage row. The ONE encode. */
878
+ function processToRow(nodeId, atMs, process) {
879
+ return {
880
+ nodeId,
881
+ atMs,
882
+ pid: process.pid,
883
+ addonId: process.addonId,
884
+ classification: process.classification,
885
+ cpuDeci: toDeci(process.cpuPercent) ?? 0,
886
+ rssMib: Math.round(process.memoryRssBytes / BYTES_PER_MIB),
887
+ cpuMainDeci: toDeci(process.cpuMainPercent),
888
+ cpuGcDeci: toDeci(process.cpuGcPercent)
889
+ };
890
+ }
891
+ /** Group flat rows into samples, oldest-first. A sample is one `atMs`. */
892
+ function rowsToSamples(rows) {
893
+ const byAt = /* @__PURE__ */ new Map();
894
+ for (const row of rows) {
895
+ const held = byAt.get(row.atMs);
896
+ if (held === void 0) byAt.set(row.atMs, [rowToProcess(row)]);
897
+ else held.push(rowToProcess(row));
898
+ }
899
+ return [...byAt.entries()].toSorted((a, b) => a[0] - b[0]).map(([atMs, processes]) => ({
900
+ atMs,
901
+ processes
902
+ }));
903
+ }
904
+ /**
905
+ * The cold tier. Append-only, bounded, and never the authority on anything the
906
+ * hot ring can answer.
907
+ *
908
+ * Every method is best-effort and says so in the log rather than throwing at
909
+ * the emitter: a storage hiccup must cost a gap in a chart, never a dropped
910
+ * snapshot on the bus.
911
+ */
912
+ var LoadSeriesStore = class {
913
+ declared = false;
914
+ lastPruneAtMs = 0;
915
+ store;
916
+ logger;
917
+ nowFn;
918
+ prunePageRows;
919
+ pruneIntervalMs;
920
+ constructor(deps) {
921
+ this.store = deps.store;
922
+ this.logger = deps.logger;
923
+ this.nowFn = deps.now ?? (() => Date.now());
924
+ this.prunePageRows = deps.prunePageRows ?? 2e4;
925
+ this.pruneIntervalMs = deps.pruneIntervalMs ?? 6e4;
926
+ }
927
+ /** Idempotently declare the collection. `false` when the store refused. */
928
+ async declare() {
929
+ if (this.declared) return true;
930
+ try {
931
+ await this.store.declareCollection.mutate({
932
+ collection: LOAD_SERIES_COLLECTION,
933
+ columns: [...LOAD_SERIES_COLUMNS],
934
+ indexes: LOAD_SERIES_INDEXES.map((i) => ({
935
+ name: i.name,
936
+ columns: [...i.columns]
937
+ }))
938
+ });
939
+ this.declared = true;
940
+ return true;
941
+ } catch (err) {
942
+ this.logger.warn("load series declareCollection failed — nothing will be retained on disk", { meta: {
943
+ collection: LOAD_SERIES_COLLECTION,
944
+ error: require_dist.errMsg(err)
945
+ } });
946
+ return false;
947
+ }
948
+ }
949
+ /**
950
+ * Append ONE sample — every process row of it — in ONE transaction.
951
+ *
952
+ * Never a write per row. `insertMany` exists for exactly this: at the 10 s
953
+ * default the fleet produces 7.6 rows/s, and 7.6 separate commits per second
954
+ * on the connection that also serves every cluster-wide configuration read
955
+ * is a constant load nobody asked for.
956
+ */
957
+ async append(nodeId, atMs, processes) {
958
+ if (processes.length === 0) return 0;
959
+ if (!await this.declare()) return 0;
960
+ const records = processes.map((p) => ({ data: { ...processToRow(nodeId, atMs, p) } }));
961
+ try {
962
+ const { inserted } = await this.store.insertMany.mutate({
963
+ collection: LOAD_SERIES_COLLECTION,
964
+ records
965
+ });
966
+ return inserted;
967
+ } catch (err) {
968
+ this.logger.warn("load series sample not retained — this interval will be missing", { meta: {
969
+ nodeId,
970
+ atMs,
971
+ rows: processes.length,
972
+ error: require_dist.errMsg(err)
973
+ } });
974
+ return 0;
975
+ }
976
+ }
977
+ /**
978
+ * Read one node's cold samples, oldest-first.
979
+ *
980
+ * `sinceMs` is EXCLUSIVE, matching the ring, so a caller passing the newest
981
+ * timestamp it holds gets only what it is missing. `limitRows` bounds the
982
+ * read in ROWS (not samples) because rows are what the query costs.
983
+ */
984
+ async read(nodeId, sinceMs, limitRows) {
985
+ if (!await this.declare()) return [];
986
+ try {
987
+ const records = await this.store.query.query({
988
+ collection: LOAD_SERIES_COLLECTION,
989
+ filter: {
990
+ where: { nodeId },
991
+ whereBetween: { atMs: [sinceMs + 1, Number.MAX_SAFE_INTEGER] },
992
+ orderBy: {
993
+ field: "atMs",
994
+ direction: "asc"
995
+ },
996
+ limit: limitRows
997
+ }
998
+ });
999
+ const rows = [];
1000
+ for (const record of records) {
1001
+ const row = recordToRow(record.data);
1002
+ if (row !== null) rows.push(row);
1003
+ }
1004
+ return rowsToSamples(rows);
1005
+ } catch (err) {
1006
+ this.logger.warn("load series cold read failed — answering from the hot window only", { meta: {
1007
+ nodeId,
1008
+ sinceMs,
1009
+ error: require_dist.errMsg(err)
1010
+ } });
1011
+ return [];
1012
+ }
1013
+ }
1014
+ /**
1015
+ * Enforce BOTH bounds, oldest-first, through a bounded page each.
1016
+ *
1017
+ * Rate-limited to {@link pruneIntervalMs}: a bound is not a deadline, and the
1018
+ * append path must not pay a sweep on every sample.
1019
+ */
1020
+ async prune(nodeIds, retention, force = false) {
1021
+ const now = this.nowFn();
1022
+ if (!force && now - this.lastPruneAtMs < this.pruneIntervalMs) return null;
1023
+ this.lastPruneAtMs = now;
1024
+ if (!await this.declare()) return null;
1025
+ let deletedByAge = 0;
1026
+ let deletedByCap = 0;
1027
+ let rowsExamined = 0;
1028
+ const ageCutoff = now - retention.retentionHours * 36e5;
1029
+ for (const nodeId of nodeIds) {
1030
+ const outcome = await this.pruneNodeToCutoff(nodeId, ageCutoff);
1031
+ deletedByAge += outcome.deleted;
1032
+ rowsExamined += outcome.examined;
1033
+ }
1034
+ const total = await this.count();
1035
+ const excess = total === null ? 0 : total - retention.maxRows;
1036
+ if (excess > 0) {
1037
+ const outcome = await this.pruneOldestRows(nodeIds, excess);
1038
+ deletedByCap = outcome.deleted;
1039
+ rowsExamined += outcome.examined;
1040
+ this.logger.warn("load series ROW CAP bit — evicting the oldest samples", { meta: {
1041
+ collection: LOAD_SERIES_COLLECTION,
1042
+ rows: total,
1043
+ cap: retention.maxRows,
1044
+ over: excess,
1045
+ deleted: outcome.deleted,
1046
+ retentionHours: retention.retentionHours,
1047
+ hint: "lower the retention or the sampling cadence — the cap is the guarantee, not the intention"
1048
+ } });
1049
+ }
1050
+ return {
1051
+ deletedByAge,
1052
+ deletedByCap,
1053
+ rowsExamined,
1054
+ capBit: excess > 0
1055
+ };
1056
+ }
1057
+ /** Total rows, or `null` when the store could not answer. */
1058
+ async count() {
1059
+ if (!await this.declare()) return null;
1060
+ try {
1061
+ return await this.store.count.query({ collection: LOAD_SERIES_COLLECTION });
1062
+ } catch (err) {
1063
+ this.logger.warn("load series count failed — the row cap is not enforced this pass", { meta: { error: require_dist.errMsg(err) } });
1064
+ return null;
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Delete this node's rows older than `cutoff`, at most one page's worth.
1069
+ *
1070
+ * The page is the whole point. `deleteWhere({ atMs: [0, cutoff] })` on its
1071
+ * own is one statement but an UNBOUNDED one — a first pass after a retention
1072
+ * change would delete millions of rows inside a single stalling transaction.
1073
+ * So the page is read first (keys only, ordered by the index), its last
1074
+ * `atMs` becomes the EFFECTIVE cutoff, and the delete is bounded by it.
1075
+ */
1076
+ async pruneNodeToCutoff(nodeId, cutoff) {
1077
+ try {
1078
+ const page = await this.store.query.query({
1079
+ collection: LOAD_SERIES_COLLECTION,
1080
+ filter: {
1081
+ where: { nodeId },
1082
+ whereBetween: { atMs: [0, cutoff] },
1083
+ orderBy: {
1084
+ field: "atMs",
1085
+ direction: "asc"
1086
+ },
1087
+ limit: this.prunePageRows
1088
+ },
1089
+ columns: ["atMs"]
1090
+ });
1091
+ if (page.length === 0) return {
1092
+ deleted: 0,
1093
+ examined: 0
1094
+ };
1095
+ const effectiveCutoff = Number(page.at(-1)?.data["atMs"]);
1096
+ if (!Number.isFinite(effectiveCutoff)) return {
1097
+ deleted: 0,
1098
+ examined: page.length
1099
+ };
1100
+ const { deleted } = await this.store.deleteWhere.mutate({
1101
+ collection: LOAD_SERIES_COLLECTION,
1102
+ filter: {
1103
+ where: { nodeId },
1104
+ whereBetween: { atMs: [0, effectiveCutoff] }
1105
+ }
1106
+ });
1107
+ return {
1108
+ deleted,
1109
+ examined: page.length
1110
+ };
1111
+ } catch (err) {
1112
+ this.logger.warn("load series age prune failed — the table keeps growing this pass", { meta: {
1113
+ nodeId,
1114
+ cutoff,
1115
+ error: require_dist.errMsg(err)
1116
+ } });
1117
+ return {
1118
+ deleted: 0,
1119
+ examined: 0
1120
+ };
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Drop the oldest rows across the known nodes until `excess` is covered.
1125
+ *
1126
+ * Same bounded-page technique, walked per node so the one index serves it.
1127
+ * The node holding the oldest rows pays first, which is also the node
1128
+ * producing the pressure when a runaway process count is the cause.
1129
+ */
1130
+ async pruneOldestRows(nodeIds, excess) {
1131
+ let remaining = Math.min(excess, this.prunePageRows);
1132
+ let deleted = 0;
1133
+ let examined = 0;
1134
+ for (const nodeId of nodeIds) {
1135
+ if (remaining <= 0) break;
1136
+ try {
1137
+ const page = await this.store.query.query({
1138
+ collection: LOAD_SERIES_COLLECTION,
1139
+ filter: {
1140
+ where: { nodeId },
1141
+ orderBy: {
1142
+ field: "atMs",
1143
+ direction: "asc"
1144
+ },
1145
+ limit: remaining
1146
+ },
1147
+ columns: ["atMs"]
1148
+ });
1149
+ examined += page.length;
1150
+ if (page.length === 0) continue;
1151
+ const cutoff = Number(page.at(-1)?.data["atMs"]);
1152
+ if (!Number.isFinite(cutoff)) continue;
1153
+ const result = await this.store.deleteWhere.mutate({
1154
+ collection: LOAD_SERIES_COLLECTION,
1155
+ filter: {
1156
+ where: { nodeId },
1157
+ whereBetween: { atMs: [0, cutoff] }
1158
+ }
1159
+ });
1160
+ deleted += result.deleted;
1161
+ remaining -= result.deleted;
1162
+ } catch (err) {
1163
+ this.logger.warn("load series cap prune failed — the cap is not enforced this pass", { meta: {
1164
+ nodeId,
1165
+ error: require_dist.errMsg(err)
1166
+ } });
1167
+ }
1168
+ }
1169
+ return {
1170
+ deleted,
1171
+ examined
1172
+ };
1173
+ }
1174
+ };
1175
+ /** Structural validation on read. A malformed row is skipped, never charted. */
1176
+ function recordToRow(data) {
1177
+ const nodeId = data["nodeId"];
1178
+ const classification = data["classification"];
1179
+ if (typeof nodeId !== "string" || typeof classification !== "string") return null;
1180
+ const atMs = Number(data["atMs"]);
1181
+ const pid = Number(data["pid"]);
1182
+ const cpuDeci = Number(data["cpuDeci"]);
1183
+ const rssMib = Number(data["rssMib"]);
1184
+ if (![
1185
+ atMs,
1186
+ pid,
1187
+ cpuDeci,
1188
+ rssMib
1189
+ ].every((n) => Number.isFinite(n))) return null;
1190
+ const rawAddon = data["addonId"];
1191
+ const optional = (raw) => {
1192
+ if (raw === null || raw === void 0) return null;
1193
+ const n = Number(raw);
1194
+ return Number.isFinite(n) ? n : null;
1195
+ };
1196
+ return {
1197
+ nodeId,
1198
+ atMs,
1199
+ pid,
1200
+ addonId: typeof rawAddon === "string" ? rawAddon : null,
1201
+ classification,
1202
+ cpuDeci,
1203
+ rssMib,
1204
+ cpuMainDeci: optional(data["cpuMainDeci"]),
1205
+ cpuGcDeci: optional(data["cpuGcDeci"])
1206
+ };
1207
+ }
1208
+ //#endregion
1209
+ //#region src/builtins/native-metrics/load-series-config.ts
1210
+ /**
1211
+ * The two knobs of the durable load series, and the arithmetic that makes them
1212
+ * honest.
1213
+ *
1214
+ * ## Where they live, and why there
1215
+ *
1216
+ * In `native-metrics`'s OWN global settings document — the one that already
1217
+ * exists and already carries `samplingIntervalMs`. Fields on a document, never
1218
+ * a method per knob: `system.getLoggingSettings` / `setLoggingSettings` set
1219
+ * that precedent and it holds here.
1220
+ *
1221
+ * They are NOT in the logging document, and that is a decision rather than an
1222
+ * omission. That document is about levels and diagnostic windows; a metrics
1223
+ * cadence and a table's retention are neither. Two documents that both claim a
1224
+ * knob is how this repo has already shipped a switch nobody read.
1225
+ *
1226
+ * They are cluster-wide, not per-node. Every node emits on the same cadence or
1227
+ * the fleet's series cannot be laid over each other, and the table is single
1228
+ * and hub-resident, so a per-node retention would be a promise nothing could
1229
+ * keep.
1230
+ *
1231
+ * ## Refused, not clamped
1232
+ *
1233
+ * A cadence outside 5-60 s is REFUSED. Clamping would silently store 10 when
1234
+ * the operator typed 2 and then report 10 back as though it had been accepted
1235
+ * — the failure mode where a knob and its readback agree on a value nobody
1236
+ * chose. The schema advertises the bounds; this refuses anything else.
1237
+ */
1238
+ /** Why a value was refused — the message an operator is shown verbatim. */
1239
+ var LoadSeriesConfigError = class extends Error {
1240
+ constructor(message) {
1241
+ super(message);
1242
+ this.name = "LoadSeriesConfigError";
1243
+ }
1244
+ };
1245
+ function requireInteger(value, field) {
1246
+ const n = typeof value === "number" ? value : Number(value);
1247
+ if (!Number.isFinite(n)) throw new LoadSeriesConfigError(`${field} must be a number, received ${String(value)}`);
1248
+ return Math.round(n);
1249
+ }
1250
+ /**
1251
+ * Resolve the configuration, REFUSING anything out of range.
1252
+ *
1253
+ * An ABSENT field takes its default — that is not a refusal, it is a document
1254
+ * that has never been written. A PRESENT field outside its bounds throws.
1255
+ */
1256
+ function resolveLoadSeriesConfig(raw) {
1257
+ let cadenceSec = 10;
1258
+ if (raw.loadSeriesCadenceSec !== void 0 && raw.loadSeriesCadenceSec !== null) {
1259
+ cadenceSec = requireInteger(raw.loadSeriesCadenceSec, "loadSeriesCadenceSec");
1260
+ if (cadenceSec < 5 || cadenceSec > 60) throw new LoadSeriesConfigError(`load series cadence must be between 5 and 60 seconds — refused ${cadenceSec}`);
1261
+ }
1262
+ let retentionHours = 6;
1263
+ if (raw.loadSeriesRetentionHours !== void 0 && raw.loadSeriesRetentionHours !== null) {
1264
+ retentionHours = requireInteger(raw.loadSeriesRetentionHours, "loadSeriesRetentionHours");
1265
+ if (retentionHours < 1 || retentionHours > 72) throw new LoadSeriesConfigError(`load series retention must be between 1 and 72 hours — refused ${retentionHours}`);
1266
+ }
1267
+ return {
1268
+ cadenceSec,
1269
+ retentionHours,
1270
+ maxRows: DEFAULT_MAX_ROWS
1271
+ };
1272
+ }
1273
+ /**
1274
+ * Project the cost of a configuration from the numbers the cluster is actually
1275
+ * reporting — nodes and processes OBSERVED, never a constant.
1276
+ *
1277
+ * This is what makes the knob honest: an operator raising retention to three
1278
+ * days sees the row count and the megabytes BEFORE applying it, rather than
1279
+ * discovering them afterwards. `MEASURED_BYTES_PER_ROW` is measured, not
1280
+ * guessed — see `load-series-store.ts`.
1281
+ */
1282
+ function projectLoadSeriesCost(input) {
1283
+ const samplesPerNodeWindow = input.config.retentionHours * 3600 / input.config.cadenceSec;
1284
+ const intendedRows = Math.round(samplesPerNodeWindow * Math.max(input.observedProcessRows, 0));
1285
+ const boundedRows = Math.min(intendedRows, input.config.maxRows);
1286
+ return {
1287
+ intendedRows,
1288
+ boundedRows,
1289
+ estimatedBytes: boundedRows * 87,
1290
+ capBites: intendedRows > input.config.maxRows
1291
+ };
1292
+ }
1293
+ /** Human-readable one-liner for the settings form. */
1294
+ function describeLoadSeriesCost(projection) {
1295
+ const mib = (projection.estimatedBytes / 1048576).toFixed(1);
1296
+ const rows = projection.intendedRows.toLocaleString("en-US");
1297
+ const capped = projection.boundedRows.toLocaleString("en-US");
1298
+ if (!projection.capBites) return `This configuration retains ~${rows} rows ≈ ${mib} MiB on the hub database (NVMe cache), measured at 87 bytes per row.`;
1299
+ return `This configuration WANTS ~${rows} rows, above the ${projection.boundedRows.toLocaleString("en-US")}-row hard cap. The table will hold ~${capped} rows ≈ ${mib} MiB and the OLDEST samples will be evicted, so the effective window is shorter than the retention you asked for.`;
1300
+ }
1301
+ //#endregion
1302
+ //#region src/builtins/native-metrics/load-series-reader.ts
1303
+ /**
1304
+ * The ONE reader over both retention tiers.
1305
+ *
1306
+ * The hot window is the in-memory ring; the cold one is
1307
+ * `metrics:node-load-samples`. A caller never learns which tier a point came
1308
+ * from, and that is a hard requirement rather than a nicety: a second reader
1309
+ * is how two charts start disagreeing about the same node, and it is how "the
1310
+ * ring says X, the table says Y" becomes a question nobody can answer.
1311
+ *
1312
+ * Three things happen here, in this order, and each one is load-bearing:
1313
+ *
1314
+ * 1. **Merge and dedupe on `atMs`.** The two tiers OVERLAP by construction —
1315
+ * the ring holds the last 180 snapshots and the table holds every snapshot
1316
+ * the ring accepted, including those same 180. A snapshot present in both
1317
+ * must contribute exactly once. Identity is `atMs`, because one node emits
1318
+ * one snapshot per tick and a timestamp already held IS that snapshot. The
1319
+ * HOT copy wins on a tie: it is the payload as it arrived, while the cold
1320
+ * one has been through the storage encode.
1321
+ * 2. **Fold per function.** The chart draws one series per addon, so the fold
1322
+ * happens here rather than in the browser.
1323
+ * 3. **Reduce, preserving the extremes.** See `load-series-fold.ts` for why
1324
+ * the representative of a bucket is its MAX and never its mean.
1325
+ *
1326
+ * A GAP stays a gap through all three. Emission is fixed-cadence, so a missing
1327
+ * interval means one thing — nobody reported — and nothing here fills it in.
1328
+ */
1329
+ /**
1330
+ * Merge the two tiers into one deduped, oldest-first list of samples.
1331
+ *
1332
+ * Exported because the dedup is the property worth testing on its own: a
1333
+ * doubled point is invisible in a total and obvious only as a chart that reads
1334
+ * twice as loud as the machine.
1335
+ */
1336
+ function mergeSamples(cold, hot) {
1337
+ const byAt = /* @__PURE__ */ new Map();
1338
+ for (const sample of cold) byAt.set(sample.atMs, sample);
1339
+ for (const sample of hot) byAt.set(sample.atMs, sample);
1340
+ return [...byAt.values()].toSorted((a, b) => a.atMs - b.atMs);
1341
+ }
1342
+ /** `RetainedProcess` is already the fold's row shape — named, not re-derived. */
1343
+ function toFoldRows(processes) {
1344
+ return processes;
1345
+ }
1346
+ /**
1347
+ * Merge, fold and reduce. The whole read path in one pure function, so every
1348
+ * property that matters — dedup, peak survival, an empty bucket staying empty
1349
+ * — is testable without a database or a ring.
1350
+ */
1351
+ function mergeLoadSeries(input) {
1352
+ const samples = mergeSamples(input.cold, input.hot);
1353
+ if (samples.length === 0) return {
1354
+ series: [],
1355
+ bucketMs: input.cadenceMs,
1356
+ retainedSamples: 0,
1357
+ oldestAtMs: null
1358
+ };
1359
+ const byKey = /* @__PURE__ */ new Map();
1360
+ for (const sample of samples) for (const bucket of require_dist.foldSnapshotByFunction(toFoldRows(sample.processes), sample.atMs)) {
1361
+ const held = byKey.get(bucket.key);
1362
+ if (held === void 0) byKey.set(bucket.key, {
1363
+ kind: bucket.kind,
1364
+ points: [bucket.point]
1365
+ });
1366
+ else held.points.push(bucket.point);
1367
+ }
1368
+ const oldestAtMs = samples[0]?.atMs ?? null;
1369
+ const newestAtMs = samples.at(-1)?.atMs ?? oldestAtMs;
1370
+ const spanMs = oldestAtMs === null || newestAtMs === null ? 0 : newestAtMs - oldestAtMs + input.cadenceMs;
1371
+ const bucketMs = input.maxPoints === void 0 ? input.cadenceMs : require_dist.resolveBucketMs(spanMs, input.cadenceMs, input.maxPoints);
1372
+ const origin = oldestAtMs ?? 0;
1373
+ const series = [...byKey.entries()].map(([key, held]) => ({
1374
+ key,
1375
+ kind: held.kind,
1376
+ points: bucketMs > input.cadenceMs ? require_dist.reducePoints(held.points, bucketMs, origin) : held.points
1377
+ }));
1378
+ const weight = (s) => {
1379
+ const last = s.points.at(-1);
1380
+ if (last === void 0) return -1;
1381
+ if (last.cpuMainPercent !== null && last.cpuGcPercent !== null) return last.cpuMainPercent + last.cpuGcPercent;
1382
+ return last.cpuLifetimePercent;
1383
+ };
1384
+ return {
1385
+ series: series.toSorted((a, b) => {
1386
+ const d = weight(b) - weight(a);
1387
+ return d !== 0 ? d : a.key.localeCompare(b.key);
1388
+ }),
1389
+ bucketMs,
1390
+ retainedSamples: samples.length,
1391
+ oldestAtMs
1392
+ };
1393
+ }
1394
+ //#endregion
1395
+ //#region src/builtins/native-metrics/process-classification.ts
471
1396
  /**
472
1397
  * Regex matching camstack-related command lines. We surface anything with
473
1398
  * an obvious camstack fingerprint so operators can spot stray inference
@@ -479,23 +1404,243 @@ var execFileAsync = (0, node_util.promisify)(node_child_process.execFile);
479
1404
  */
480
1405
  var CAMSTACK_CMD_RE = /(camstack|tsx\s+watch\s.*launcher\.ts|packages\/agent\/dist\/cli\.js|inference_pool\.py|bench-(inference-pool|nodeav)|node .*\/packages\/)/;
481
1406
  /**
482
- * Boundary patterns: ancestry walks that pass through a process whose
483
- * command line matches one of these are considered to be inside an
484
- * "intentional camstack tree". Anything reachable by walking up the
485
- * pid tree from such a boundary is `system` — not a ghost.
486
- *
487
- * The boundaries are:
488
- * - `tsx watch .../launcher.ts` — hub launcher (npm run dev:server)
489
- * - `node .../packages/agent/dist/cli.js` agent CLI (dev-cluster, npm run dev:agent)
490
- * - `concurrently` dev-cluster orchestrator that runs hub + admin-ui + agents
491
- * - `npm exec ` / `npm-cli.js` — npm wrappers driving the above
492
- * - `vite` — admin-ui dev server (sibling of hub under concurrently)
493
- *
494
- * The classification logic (`classifyByAncestry`) walks each candidate
495
- * pid up to ppid=1; if any ancestor matches this regex, the candidate
496
- * is `system`. Reaching ppid=1 without crossing a boundary = `ghost`.
1407
+ * Classify one pid.
1408
+ *
1409
+ * Identity-driven, not ancestry-driven: a process is `root` because it IS
1410
+ * this node, `managed` because the kernel named it, and `system` otherwise.
1411
+ * There is no third source of truth to consult and no walk to get wrong.
1412
+ */
1413
+ function classifyProcess(pid, selfPid, managed) {
1414
+ if (pid === selfPid) return "root";
1415
+ if (managed.has(pid)) return "managed";
1416
+ return "system";
1417
+ }
1418
+ /** Turn a `ps` snapshot into the node's process table. */
1419
+ function buildNodeProcesses(input) {
1420
+ const out = [];
1421
+ for (const p of input.psRows) {
1422
+ if (!CAMSTACK_CMD_RE.test(p.command)) continue;
1423
+ const managed = input.managed.get(p.pid);
1424
+ const split = input.cpuSplits.get(p.pid);
1425
+ const classification = classifyProcess(p.pid, input.selfPid, input.managed);
1426
+ out.push({
1427
+ pid: p.pid,
1428
+ ppid: p.ppid,
1429
+ pgid: p.pgid,
1430
+ classification,
1431
+ addonId: managed?.addonId ?? null,
1432
+ nodeId: managed?.nodeId ?? (p.pid === input.selfPid ? input.selfNodeId : null),
1433
+ command: p.command,
1434
+ cpuPercent: p.cpuPercent,
1435
+ memoryRssBytes: p.memoryRssBytes,
1436
+ cpuMainPercent: split?.mainPercent ?? null,
1437
+ cpuGcPercent: split?.gcPercent ?? null,
1438
+ threadCount: split?.threadCount ?? null,
1439
+ uptimeSec: p.uptimeSec
1440
+ });
1441
+ }
1442
+ return out;
1443
+ }
1444
+ //#endregion
1445
+ //#region src/builtins/native-metrics/thread-cpu-sampler.ts
1446
+ /**
1447
+ * Per-process CPU split: the process's OWN threads vs V8's helper-thread pool.
1448
+ *
1449
+ * ## Why this exists
1450
+ *
1451
+ * `ps pcpu` — the number every CPU column in this app renders today — is the
1452
+ * process's CPU averaged over its **entire lifetime**. On a runner that has
1453
+ * been up for three days it barely moves, which makes it useless as a series:
1454
+ * a chart drawn from it is a flat line that cannot show a spike.
1455
+ *
1456
+ * Worse, a single total hides the finding that rewrote the 2026-08-27
1457
+ * diagnosis. Separating the V8 helper threads from the rest showed that ~2
1458
+ * whole cores of the container **were not computing** — hub-main was at 73%
1459
+ * and `stream-broker` at 61% of their CPU in that pool
1460
+ * (`docs/architecture/load-ledger.md`). A CPU chart that does not split the
1461
+ * two renders "busy" where the truth is "allocating too much".
1462
+ *
1463
+ * This module produces both at once, from the source the ledger prescribes:
1464
+ * a delta over `/proc/<pid>/task/<tid>/stat`, classified by thread name.
1465
+ *
1466
+ * ## What `gcPercent` actually contains — read this before quoting it
1467
+ *
1468
+ * It is the CPU of the threads V8 names `V8Worker`: its platform worker pool.
1469
+ * Concurrent marking and sweeping run there, and so does background
1470
+ * compilation. So `gcPercent` is **"the V8 helper pool"**, of which GC is the
1471
+ * dominant but not the only tenant. It is exactly the quantity the load ledger
1472
+ * measured — the 73% / 61% figures are this number — and it is reported under
1473
+ * that name for continuity, not because every jiffy in it is a collection.
1474
+ * The UI labels it `GC / V8 helpers` for the same reason.
1475
+ *
1476
+ * ## Cost
1477
+ *
1478
+ * One `readdir` plus one small `read` per thread, for the camstack-shaped pids
1479
+ * ONLY — on a busy node that is ~10 processes × ~10-40 threads. It rides the
1480
+ * existing 20 s process-snapshot tick and never adds a timer of its own, so it
1481
+ * is strictly cheaper than the full-process-table `ps -eo` scan that tick
1482
+ * already pays. There is no high-frequency sampler here; that is the defect
1483
+ * the load ledger documents.
1484
+ *
1485
+ * ## Linux only
1486
+ *
1487
+ * `/proc/<pid>/task` does not exist on macOS or Windows. Every read returns
1488
+ * `null` there, and `null` must reach the UI as "unknown" — never as zero.
1489
+ */
1490
+ /**
1491
+ * Kernel jiffies per second (`USER_HZ`). `sysconf(_SC_CLK_TCK)` is not exposed
1492
+ * to Node, and this has been 100 on every Linux/x86-64 and arm64 kernel
1493
+ * configuration we ship to. It scales both numerator and denominator of the
1494
+ * ratio identically, so a wrong value would scale all CPU numbers by a
1495
+ * constant — visible immediately, not a silent skew.
1496
+ */
1497
+ var CLOCK_TICKS_PER_SEC = 100;
1498
+ /**
1499
+ * Thread names V8 gives its platform worker pool. `comm` is capped at 15
1500
+ * characters by the kernel, which is why this matches a PREFIX.
1501
+ */
1502
+ var V8_HELPER_THREAD_RE = /^V8Worker/;
1503
+ function parseThreadStat(line) {
1504
+ const close = line.lastIndexOf(")");
1505
+ const open = line.indexOf("(");
1506
+ if (close < 0 || open < 0 || close < open) return null;
1507
+ const comm = line.slice(open + 1, close);
1508
+ const rest = line.slice(close + 1).trim().split(/\s+/);
1509
+ const utime = Number(rest[11]);
1510
+ const stime = Number(rest[12]);
1511
+ const startTicks = Number(rest[19]);
1512
+ if (!Number.isFinite(utime) || !Number.isFinite(stime)) return null;
1513
+ if (!Number.isFinite(startTicks)) return null;
1514
+ return {
1515
+ comm,
1516
+ ticks: utime + stime,
1517
+ startTicks
1518
+ };
1519
+ }
1520
+ var nodeProcFsReader = {
1521
+ listTaskIds: (pid) => (0, node_fs_promises.readdir)(`/proc/${pid}/task`),
1522
+ readTaskStat: (pid, tid) => (0, node_fs_promises.readFile)(`/proc/${pid}/task/${tid}/stat`, "utf8")
1523
+ };
1524
+ /**
1525
+ * Read one instant's tick counts for `pid`, or `null` when the process has no
1526
+ * readable `/proc/<pid>/task` — it exited, we lack permission, or this is not
1527
+ * Linux. `null` is "unknown"; it must never be turned into a zero downstream.
1528
+ */
1529
+ async function readThreadTicks(pid, reader = nodeProcFsReader) {
1530
+ let tids;
1531
+ try {
1532
+ tids = await reader.listTaskIds(pid);
1533
+ } catch {
1534
+ return null;
1535
+ }
1536
+ let mainTicks = 0;
1537
+ let gcTicks = 0;
1538
+ let threadCount = 0;
1539
+ let startTicks = null;
1540
+ const mainThreadTid = String(pid);
1541
+ for (const tid of tids) {
1542
+ let line;
1543
+ try {
1544
+ line = await reader.readTaskStat(pid, tid);
1545
+ } catch {
1546
+ continue;
1547
+ }
1548
+ const parsed = parseThreadStat(line);
1549
+ if (parsed === null) continue;
1550
+ threadCount += 1;
1551
+ if (tid === mainThreadTid) startTicks = parsed.startTicks;
1552
+ if (V8_HELPER_THREAD_RE.test(parsed.comm)) gcTicks += parsed.ticks;
1553
+ else mainTicks += parsed.ticks;
1554
+ }
1555
+ if (threadCount === 0) return null;
1556
+ return {
1557
+ mainTicks,
1558
+ gcTicks,
1559
+ threadCount,
1560
+ atMs: Date.now(),
1561
+ startTicks
1562
+ };
1563
+ }
1564
+ /**
1565
+ * The CPU split between two samples of the SAME process.
1566
+ *
1567
+ * Returns `null` — never a zero — when the window cannot produce a rate:
1568
+ * - the two samples are not separated in time (no window to divide by);
1569
+ * - the pid's `starttime` changed, or is unknown on either side. A changed
1570
+ * starttime means the pid was RECYCLED: this is a different process that
1571
+ * happens to wear the same number. See below for why the tick check alone
1572
+ * does not catch it;
1573
+ * - either tick count went BACKWARDS, which is the same fault seen from the
1574
+ * other side. A negative delta divided by a window would render as a
1575
+ * plausible small number for the wrong process, and a plausible wrong
1576
+ * number is the failure this whole surface exists to avoid.
1577
+ *
1578
+ * ## Why `starttime` and not just the backwards-tick check
1579
+ *
1580
+ * The backwards check only fires when the NEW process has burned FEWER ticks
1581
+ * than the dead one had. A recycled pid landing on a busier process — an
1582
+ * ffmpeg that has been transcoding for a minute inheriting the pid of an
1583
+ * ffmpeg that idled — produces a large POSITIVE delta, which divides cleanly
1584
+ * and renders as a spike. That is not a hypothetical rounding concern now that
1585
+ * the process snapshot attributes each pid to a camera: it would charge one
1586
+ * camera for another camera's whole lifetime of CPU, in a chart built
1587
+ * specifically to answer "why is 617 worse than 615". `starttime` is the pid's
1588
+ * incarnation number and it catches both directions.
1589
+ */
1590
+ function cpuSplitBetween(prev, next) {
1591
+ const windowMs = next.atMs - prev.atMs;
1592
+ if (windowMs <= 0) return null;
1593
+ if (prev.startTicks === null || next.startTicks === null) return null;
1594
+ if (prev.startTicks !== next.startTicks) return null;
1595
+ const mainDelta = next.mainTicks - prev.mainTicks;
1596
+ const gcDelta = next.gcTicks - prev.gcTicks;
1597
+ if (mainDelta < 0 || gcDelta < 0) return null;
1598
+ const windowTicks = windowMs / 1e3 * CLOCK_TICKS_PER_SEC;
1599
+ const pct = (delta) => Math.round(delta / windowTicks * 1e3) / 10;
1600
+ return {
1601
+ mainPercent: pct(mainDelta),
1602
+ gcPercent: pct(gcDelta),
1603
+ threadCount: next.threadCount
1604
+ };
1605
+ }
1606
+ /**
1607
+ * Keeps the previous tick sample per pid so the next process-snapshot tick can
1608
+ * turn it into a rate.
1609
+ *
1610
+ * Bounded by construction: {@link sample} replaces the whole map with only the
1611
+ * pids it was just asked about, so a pid that stops appearing in the scan is
1612
+ * dropped on the following tick rather than accumulating forever.
497
1613
  */
498
- var SUPERVISOR_BOUNDARY_RE = /(tsx\s+watch\s.*launcher\.ts|packages\/agent\/dist\/cli\.js|\.bin\/concurrently|\/concurrently\/dist|\bnpm-cli\.js\b|npm exec |\.bin\/vite|\/vite\/bin\/vite\.js|node_modules\/\.bin\/(vite|concurrently|tsup|rollup|esbuild|tsx)(\s|$))/;
1614
+ var ThreadCpuTracker = class {
1615
+ reader;
1616
+ previous = /* @__PURE__ */ new Map();
1617
+ constructor(reader = nodeProcFsReader) {
1618
+ this.reader = reader;
1619
+ }
1620
+ /**
1621
+ * Sample `pids` and return the split for each one that HAS a usable previous
1622
+ * sample. A pid absent from the result has no answer yet — the caller must
1623
+ * report `null`, not `0`.
1624
+ */
1625
+ async sample(pids) {
1626
+ const out = /* @__PURE__ */ new Map();
1627
+ const nextPrevious = /* @__PURE__ */ new Map();
1628
+ for (const pid of pids) {
1629
+ const next = await readThreadTicks(pid, this.reader);
1630
+ if (next === null) continue;
1631
+ nextPrevious.set(pid, next);
1632
+ const prev = this.previous.get(pid);
1633
+ if (prev === void 0) continue;
1634
+ const split = cpuSplitBetween(prev, next);
1635
+ if (split !== null) out.set(pid, split);
1636
+ }
1637
+ this.previous = nextPrevious;
1638
+ return out;
1639
+ }
1640
+ };
1641
+ //#endregion
1642
+ //#region src/builtins/native-metrics/native-metrics.addon.ts
1643
+ var execFileAsync = (0, node_util.promisify)(node_child_process.execFile);
499
1644
  /**
500
1645
  * Cadence for the per-node metric snapshot bus events. ~5 s matches
501
1646
  * the existing UI polling cadence (ProcessesTab, ProcessResources)
@@ -504,18 +1649,20 @@ var SUPERVISOR_BOUNDARY_RE = /(tsx\s+watch\s.*launcher\.ts|packages\/agent\/dist
504
1649
  */
505
1650
  var METRICS_SNAPSHOT_INTERVAL_MS = 5e3;
506
1651
  /**
507
- * Cadence for the per-node PROCESS-TREE snapshot bus events. Kept
508
- * deliberately coarser than the resources cadence because each tick
509
- * runs a full OS `ps -eo` scan (`runPs`) plus a `$process.list` broker
510
- * call heavy work that was previously paid every 5s regardless of
511
- * whether any UI consumer was subscribed to
512
- * `MetricsNodeProcessesSnapshot`. The event bus exposes no per-category
513
- * subscriber count, so instead of demand-gating we split the cadence:
514
- * 20s cuts the `ps` frequency 4x while the ProcessesTab still gets a
515
- * fresh-on-open payload from the on-demand `listNodeProcesses` cap call.
516
- * The dedup + 60s heartbeat below still apply on top of this.
1652
+ * The process-tree snapshot is FIXED-CADENCE, and its cadence is the
1653
+ * operator's `loadSeriesCadenceSec` (5-60 s, 10 by default).
1654
+ *
1655
+ * It used to emit only ON A CHANGE, with a 60 s fallback heartbeat, and the
1656
+ * dedup is gone rather than tuned. A conditional emit makes a hole in the
1657
+ * series mean two different things "nothing changed" and "nobody reported"
1658
+ * and telling those apart is the entire reason an operator opens this chart
1659
+ * after a spike. Now a gap means exactly one thing.
1660
+ *
1661
+ * It is not free: the emit rate is deterministic, so the durable table's row
1662
+ * count is too (nodes x processes / cadence, no discount for a quiet fleet).
1663
+ * The measured cost of that is in `docs/architecture/load-ledger.md`, and it
1664
+ * is why the retention default is six hours rather than three days.
517
1665
  */
518
- var PROCESS_SNAPSHOT_INTERVAL_MS = 2e4;
519
1666
  /**
520
1667
  * Force a metrics-snapshot emit at least every 60s even when the
521
1668
  * coarsened payload looks unchanged. Without this an idle node
@@ -545,25 +1692,6 @@ function coarsenResourcesSnapshot(snapshot) {
545
1692
  };
546
1693
  return JSON.stringify(round(snapshot));
547
1694
  }
548
- /**
549
- * Coarsen a process list before deduping — pid, addonId, state +
550
- * bucketed cpu%. Drops cmdline / cwd / start time / uptime which
551
- * change every tick on a process that's just running. The result
552
- * is "process X has the same role and roughly the same load" =
553
- * skip emit.
554
- */
555
- function coarsenProcessList(processes) {
556
- const summary = processes.filter((p) => !!p && typeof p === "object").map((p) => {
557
- return [
558
- p["pid"],
559
- p["addonId"],
560
- p["state"],
561
- typeof p["cpuPercent"] === "number" ? Math.round(p["cpuPercent"] / 5) * 5 : null,
562
- typeof p["memoryRss"] === "number" ? Math.round(p["memoryRss"] / (50 * 1024 * 1024)) : null
563
- ];
564
- });
565
- return JSON.stringify(summary);
566
- }
567
1695
  function narrowWorkerState(state) {
568
1696
  switch (state) {
569
1697
  case "starting":
@@ -578,7 +1706,7 @@ function narrowWorkerState(state) {
578
1706
  * Native metrics — CPU, memory, disk usage sampling.
579
1707
  * Settings appear under Cluster → NodeDetail → Settings.
580
1708
  */
581
- var NativeMetricsAddon = class extends require_dist.BaseAddon {
1709
+ var NativeMetricsAddon = class NativeMetricsAddon extends require_dist.BaseAddon {
582
1710
  provider = null;
583
1711
  startedAtMs = Date.now();
584
1712
  snapshotTimer = null;
@@ -590,9 +1718,77 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
590
1718
  * elapsed) is skipped.
591
1719
  */
592
1720
  lastResourcesEmit = null;
593
- lastProcessesEmit = null;
1721
+ /**
1722
+ * Holds the previous `/proc/<pid>/task/*` tick counts so each process scan
1723
+ * can turn them into an instantaneous CPU rate split between the process's
1724
+ * own threads and V8's helper pool. Self-bounding — see `ThreadCpuTracker`.
1725
+ */
1726
+ threadCpu = new ThreadCpuTracker();
1727
+ /**
1728
+ * Retention for the snapshots this addon emits. Fed by SUBSCRIBING to
1729
+ * `metrics.node-processes-snapshot`, never by a second sampler — on the hub
1730
+ * that bus carries every node, so the hub's ring is the cluster's. Bounds and
1731
+ * measured cost live in `node-load-ring.ts`.
1732
+ */
1733
+ loadRing = new NodeLoadRing();
1734
+ /**
1735
+ * The COLD tier, and it exists only on the HUB.
1736
+ *
1737
+ * The table is hub-resident and the hub already hears every node's snapshot
1738
+ * on its bus, so the hub's writer is the cluster's. An agent writing through
1739
+ * the `settings-store` singleton would ship its rows over Moleculer, once
1740
+ * per sample, to reach that very same table.
1741
+ */
1742
+ loadStore = null;
1743
+ /** The resolved knobs. Re-resolved on every settings write. */
1744
+ loadConfig = {
1745
+ cadenceSec: 10,
1746
+ retentionHours: 6,
1747
+ maxRows: DEFAULT_MAX_ROWS
1748
+ };
1749
+ /**
1750
+ * Process rows seen in each node's most recent snapshot — the OBSERVED
1751
+ * numbers the settings form projects its cost from. A constant here would be
1752
+ * a projection that stops being true the first time the fleet changes.
1753
+ */
1754
+ observedRowsByNode = /* @__PURE__ */ new Map();
594
1755
  constructor() {
595
- super({ samplingIntervalMs: 5e3 });
1756
+ super({
1757
+ samplingIntervalMs: 5e3,
1758
+ loadSeriesCadenceSec: 10,
1759
+ loadSeriesRetentionHours: 6
1760
+ });
1761
+ }
1762
+ /** Is this the hub? The same test every other addon uses (`addon-ai`). */
1763
+ get isHub() {
1764
+ return (this.ctx.kernel.cluster?.broker?.nodeID ?? "hub") === "hub";
1765
+ }
1766
+ /** Process rows observed across the whole fleet, for the cost projection. */
1767
+ observedFleetRows() {
1768
+ let total = 0;
1769
+ for (const rows of this.observedRowsByNode.values()) total += rows;
1770
+ return total;
1771
+ }
1772
+ /**
1773
+ * Project a `NodeProcess` onto the series' own row.
1774
+ *
1775
+ * `command`, `ppid`, `pgid`, `nodeId`, `threadCount` and `uptimeSec` are
1776
+ * dropped here, at the single point both tiers pass through, so the hot ring
1777
+ * and the cold table carry the SAME shape and the merged read cannot tell
1778
+ * them apart. `command` in particular is the fattest field in a snapshot and
1779
+ * the same identical string on every runner — the runner id travels in the
1780
+ * environment, not in argv — and nothing that draws this series reads it.
1781
+ */
1782
+ static toRetained(process) {
1783
+ return {
1784
+ pid: process.pid,
1785
+ addonId: process.addonId,
1786
+ classification: process.classification,
1787
+ cpuPercent: process.cpuPercent,
1788
+ memoryRssBytes: process.memoryRssBytes,
1789
+ cpuMainPercent: process.cpuMainPercent,
1790
+ cpuGcPercent: process.cpuGcPercent
1791
+ };
596
1792
  }
597
1793
  async onInitialize() {
598
1794
  const provider = new NativeMetricsProvider();
@@ -612,16 +1808,127 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
612
1808
  listAddonInstances: () => this.listAddonInstances(),
613
1809
  getAddonStats: (params) => this.getAddonStats(params.addonId),
614
1810
  listNodeProcesses: () => this.listNodeProcesses(),
615
- killProcess: (params) => this.killProcess(params),
1811
+ getLoadSeries: (params) => this.readLoadSeries(params),
616
1812
  dumpHeapSnapshot: (params) => this.dumpHeapSnapshot(params)
617
1813
  };
1814
+ this.applyLoadSeriesConfig();
1815
+ if (this.isHub) this.loadStore = new LoadSeriesStore({
1816
+ store: this.ctx.api.settingsStore,
1817
+ logger: this.ctx.logger.child("LoadSeries")
1818
+ });
618
1819
  this.snapshotTimer = setInterval(() => this.emitResourcesSnapshot(), METRICS_SNAPSHOT_INTERVAL_MS);
619
- this.processSnapshotTimer = setInterval(() => this.emitProcessesSnapshot(), PROCESS_SNAPSHOT_INTERVAL_MS);
1820
+ this.startProcessSnapshotTimer();
1821
+ this.ctx.addDisposer(this.ctx.eventBus.subscribe({ category: require_dist.EventCategory.MetricsNodeProcessesSnapshot }, (event) => this.retainSnapshot(event.data.nodeId, event.data.timestamp, event.data.processes)));
620
1822
  return [{
621
1823
  capability: require_dist.metricsProviderCapability,
622
1824
  provider: composed
623
1825
  }];
624
1826
  }
1827
+ /**
1828
+ * Retain one arriving snapshot in BOTH tiers.
1829
+ *
1830
+ * The ring is written FIRST and it is the gate: `record` refuses a timestamp
1831
+ * this node has already delivered, and only an accepted sample reaches the
1832
+ * table. That is what makes the append idempotent without a unique index
1833
+ * over two million rows — the composite key it replaces was measured at ~40
1834
+ * bytes per row (`load-series-store.ts`).
1835
+ *
1836
+ * The durable append is fire-and-forget: a storage stall must cost a gap in
1837
+ * the cold window, never a blocked event-bus handler. Every failure logs.
1838
+ */
1839
+ retainSnapshot(nodeId, atMs, processes) {
1840
+ const retained = processes.map((p) => NativeMetricsAddon.toRetained(p));
1841
+ if (!this.loadRing.record(nodeId, atMs, retained)) return;
1842
+ this.observedRowsByNode.set(nodeId, retained.length);
1843
+ const store = this.loadStore;
1844
+ if (store === null) return;
1845
+ store.append(nodeId, atMs, retained).then(() => store.prune([...this.observedRowsByNode.keys()], this.loadConfig)).catch((err) => {
1846
+ this.ctx.logger.warn("durable load series write failed", { meta: {
1847
+ nodeId,
1848
+ atMs,
1849
+ error: err instanceof Error ? err.message : String(err)
1850
+ } });
1851
+ });
1852
+ }
1853
+ /**
1854
+ * The ONE reader, over both tiers.
1855
+ *
1856
+ * Cold first, hot second, merged and deduped on `atMs` — see
1857
+ * `load-series-reader.ts`. The cold read is bounded in ROWS, because rows
1858
+ * are what a query costs, and the fold + reduction happen HERE rather than
1859
+ * in the browser: six hours at the 10 s cadence is 2 160 snapshots, and
1860
+ * shipping them to a page that will discard most of them is precisely the
1861
+ * cost this subsystem exists to avoid.
1862
+ */
1863
+ async readLoadSeries(params) {
1864
+ const cadenceMs = this.loadConfig.cadenceSec * 1e3;
1865
+ const sinceMs = params.sinceMs ?? 0;
1866
+ const hotSamples = this.loadRing.read(params.forNodeId, params.sinceMs).samples.map((sample) => ({
1867
+ atMs: sample.atMs,
1868
+ processes: sample.processes
1869
+ }));
1870
+ const store = this.loadStore;
1871
+ const merged = mergeLoadSeries({
1872
+ cold: store === null ? [] : await store.read(params.forNodeId, sinceMs, this.loadConfig.maxRows),
1873
+ hot: hotSamples,
1874
+ cadenceMs,
1875
+ ...params.maxPoints !== void 0 ? { maxPoints: params.maxPoints } : {}
1876
+ });
1877
+ return {
1878
+ nodeId: params.forNodeId,
1879
+ series: merged.series,
1880
+ bucketMs: merged.bucketMs,
1881
+ retainedSamples: merged.retainedSamples,
1882
+ oldestAtMs: merged.oldestAtMs,
1883
+ cadenceMs,
1884
+ durable: store !== null
1885
+ };
1886
+ }
1887
+ /**
1888
+ * Re-resolve the knobs and restate the fixed cadence.
1889
+ *
1890
+ * A REFUSED value (out of 5-60 s, or out of 1-72 h) leaves the previous
1891
+ * configuration in force and says so. Refused, never clamped: storing 10
1892
+ * when the operator typed 2 and reading 10 back is a knob and a readback
1893
+ * agreeing on a value nobody chose.
1894
+ */
1895
+ applyLoadSeriesConfig() {
1896
+ try {
1897
+ const next = resolveLoadSeriesConfig({
1898
+ loadSeriesCadenceSec: this.config.loadSeriesCadenceSec,
1899
+ loadSeriesRetentionHours: this.config.loadSeriesRetentionHours
1900
+ });
1901
+ const changed = next.cadenceSec !== this.loadConfig.cadenceSec || next.retentionHours !== this.loadConfig.retentionHours;
1902
+ this.loadConfig = next;
1903
+ if (changed) {
1904
+ const projection = projectLoadSeriesCost({
1905
+ config: next,
1906
+ observedProcessRows: this.observedFleetRows()
1907
+ });
1908
+ this.ctx.logger.info("load series configuration applied", { meta: {
1909
+ nodeId: this.ctx.kernel.localNodeId ?? this.ctx.id,
1910
+ cadenceSec: next.cadenceSec,
1911
+ retentionHours: next.retentionHours,
1912
+ maxRows: next.maxRows,
1913
+ projectedRows: projection.intendedRows,
1914
+ projectedMib: Math.round(projection.estimatedBytes / 1048576 * 10) / 10,
1915
+ capBites: projection.capBites
1916
+ } });
1917
+ }
1918
+ } catch (err) {
1919
+ this.ctx.logger.warn("load series configuration REFUSED — keeping the previous values", { meta: {
1920
+ nodeId: this.ctx.kernel.localNodeId ?? this.ctx.id,
1921
+ cadenceSec: this.loadConfig.cadenceSec,
1922
+ retentionHours: this.loadConfig.retentionHours,
1923
+ error: err instanceof Error ? err.message : String(err)
1924
+ } });
1925
+ }
1926
+ }
1927
+ /** (Re)arm the fixed-cadence process-tree timer at the configured interval. */
1928
+ startProcessSnapshotTimer() {
1929
+ if (this.processSnapshotTimer) clearInterval(this.processSnapshotTimer);
1930
+ this.processSnapshotTimer = setInterval(() => this.emitProcessesSnapshot(), this.loadConfig.cadenceSec * 1e3);
1931
+ }
625
1932
  async onShutdown() {
626
1933
  if (this.snapshotTimer) {
627
1934
  clearInterval(this.snapshotTimer);
@@ -677,10 +1984,14 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
677
1984
  } catch {}
678
1985
  }
679
1986
  /**
680
- * Emit one `metrics.node-processes-snapshot` for this node. Heavy —
681
- * runs a full OS `ps -eo` scan (`runPs`) plus a `$process.list` broker
682
- * call. Fires on the coarser PROCESS_SNAPSHOT_INTERVAL_MS so an idle
683
- * node isn't paying a process-table walk every 5s. Skip on failure.
1987
+ * Emit one `metrics.node-processes-snapshot` for this node.
1988
+ *
1989
+ * Heavy a full OS `ps -eo` scan plus a `$process.list` broker call — and
1990
+ * UNCONDITIONAL. The change-detection that used to guard it is gone: with a
1991
+ * fixed cadence a missing interval means exactly one thing, and that is the
1992
+ * property an operator investigating a spike is actually looking for.
1993
+ *
1994
+ * A failed scan emits nothing, which is the same signal: nobody reported.
684
1995
  */
685
1996
  async emitProcessesSnapshot() {
686
1997
  const eventBus = this.ctx.eventBus;
@@ -689,29 +2000,27 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
689
2000
  const timestamp = Date.now();
690
2001
  try {
691
2002
  const processes = await this.listNodeProcesses();
692
- const coarse = coarsenProcessList(processes);
693
- const prev = this.lastProcessesEmit;
694
- const heartbeatDue = !prev || timestamp - prev.emittedAt >= METRICS_SNAPSHOT_HEARTBEAT_MS;
695
- if (!prev || prev.coarse !== coarse || heartbeatDue) {
696
- this.lastProcessesEmit = {
697
- coarse,
698
- emittedAt: timestamp
699
- };
700
- eventBus.emit(require_dist.createEvent(require_dist.EventCategory.MetricsNodeProcessesSnapshot, {
701
- type: "node",
702
- id: nodeId,
703
- nodeId
704
- }, {
705
- nodeId,
706
- processes,
707
- timestamp
708
- }));
709
- }
710
- } catch {}
2003
+ eventBus.emit(require_dist.createEvent(require_dist.EventCategory.MetricsNodeProcessesSnapshot, {
2004
+ type: "node",
2005
+ id: nodeId,
2006
+ nodeId
2007
+ }, {
2008
+ nodeId,
2009
+ processes,
2010
+ timestamp
2011
+ }));
2012
+ } catch (err) {
2013
+ this.ctx.logger.warn("process snapshot skipped — this interval will be missing", { meta: {
2014
+ nodeId,
2015
+ error: err instanceof Error ? err.message : String(err)
2016
+ } });
2017
+ }
711
2018
  }
712
2019
  async onConfigChanged() {
713
2020
  this.provider?.stopSampling();
714
2021
  this.provider?.startSampling(this.config.samplingIntervalMs);
2022
+ this.applyLoadSeriesConfig();
2023
+ this.startProcessSnapshotTimer();
715
2024
  }
716
2025
  async listWorkerInstances() {
717
2026
  const broker = this.ctx.kernel.cluster?.broker;
@@ -755,137 +2064,29 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
755
2064
  /**
756
2065
  * Walk the OS process table and classify each camstack-shaped process.
757
2066
  *
758
- * Classification (ancestry-driven, NOT pattern-driven):
759
- * - root — the current node's own pid (`process.pid`).
760
- * - managedpid is registered in the kernel's `$process.list`
761
- * (forked addon worker spawned by this hub).
762
- * - system — ancestry walk crosses a SUPERVISOR_BOUNDARY_RE match
763
- * (tsx-watch launcher, agent CLI, concurrently, vite,
764
- * npm exec wrapper). The process belongs to the dev
765
- * tree even if not in `$process.list`. NEVER killable.
766
- * - ghost — ancestry walk reaches `ppid=1` without crossing any
767
- * supervisor boundary AND the parent isn't visible in
768
- * `ps`. A truly orphaned camstack-shaped process. The
769
- * ONLY classification that's eligible for kill.
770
- *
771
- * Old pattern-only ghost detection produced false positives: every
772
- * monorepo-path process matched CAMSTACK_CMD_RE, ancestry walk
773
- * stopping at ppid=hub returned false-positive ghosts whenever a
774
- * concurrently sibling sat above hub. Ancestry-driven classification
775
- * fixes that.
2067
+ * Classification is IDENTITY-driven: `root` is this pid, `managed` is a pid
2068
+ * the kernel's `$process.list` names, and every other camstack-shaped
2069
+ * process is `system`. The rules and why there is no longer an ancestry
2070
+ * walk behind them live in `process-classification.ts`.
776
2071
  */
777
2072
  async listNodeProcesses() {
778
2073
  const ps = await this.runPs();
779
2074
  if (ps.length === 0) return [];
780
- const managedPids = /* @__PURE__ */ new Map();
2075
+ const managed = /* @__PURE__ */ new Map();
781
2076
  const workers = await this.listWorkerInstances();
782
- for (const w of workers) managedPids.set(w.pid, {
2077
+ for (const w of workers) managed.set(w.pid, {
783
2078
  addonId: w.addonId,
784
2079
  nodeId: w.nodeId
785
2080
  });
786
- const hubNodeId = this.ctx.kernel.cluster?.broker?.nodeID ?? "hub";
787
- const selfPid = process.pid;
788
- const psIndex = /* @__PURE__ */ new Map();
789
- for (const p of ps) psIndex.set(p.pid, {
790
- ppid: p.ppid,
791
- command: p.command
2081
+ const camstackPids = ps.filter((p) => CAMSTACK_CMD_RE.test(p.command)).map((p) => p.pid);
2082
+ const cpuSplits = await this.threadCpu.sample(camstackPids);
2083
+ return buildNodeProcesses({
2084
+ psRows: ps,
2085
+ selfPid: process.pid,
2086
+ selfNodeId: this.ctx.kernel.cluster?.broker?.nodeID ?? "hub",
2087
+ managed,
2088
+ cpuSplits
792
2089
  });
793
- /**
794
- * Walk ancestry from `pid` up to ppid=1 (or until we leave the ps
795
- * snapshot). Returns:
796
- * - 'system' — crossed a SUPERVISOR_BOUNDARY_RE ancestor
797
- * - 'ghost' — reached ppid=1 OR the parent isn't visible in ps
798
- * without crossing a boundary
799
- *
800
- * `selfPid` itself is treated as a boundary (this node's own root).
801
- */
802
- const classifyByAncestry = (startPid) => {
803
- let cur = startPid;
804
- for (let depth = 0; depth < 32; depth++) {
805
- const node = psIndex.get(cur);
806
- if (!node) return "ghost";
807
- if (cur === selfPid) return "system";
808
- if (SUPERVISOR_BOUNDARY_RE.test(node.command)) return "system";
809
- if (node.ppid === 1) return "ghost";
810
- if (node.ppid === selfPid) return "system";
811
- cur = node.ppid;
812
- }
813
- return "system";
814
- };
815
- const out = [];
816
- for (const p of ps) {
817
- if (!CAMSTACK_CMD_RE.test(p.command)) continue;
818
- const managed = managedPids.get(p.pid);
819
- let classification;
820
- if (p.pid === selfPid) classification = "root";
821
- else if (managed) classification = "managed";
822
- else classification = classifyByAncestry(p.pid);
823
- const orphaned = classification === "ghost";
824
- out.push({
825
- pid: p.pid,
826
- ppid: p.ppid,
827
- pgid: p.pgid,
828
- classification,
829
- addonId: managed?.addonId ?? null,
830
- nodeId: managed?.nodeId ?? (p.pid === selfPid ? hubNodeId : null),
831
- command: p.command,
832
- cpuPercent: p.cpuPercent,
833
- memoryRssBytes: p.memoryRssBytes,
834
- uptimeSec: p.uptimeSec,
835
- orphaned
836
- });
837
- }
838
- return out;
839
- }
840
- /**
841
- * Send SIGTERM / SIGKILL to a pid. Refuses pids that don't appear in
842
- * `listNodeProcesses()` to prevent arbitrary system kills — a dedicated
843
- * admin-path for resurrected zombies, not a generic shell replacement.
844
- *
845
- * `root`-classified pids (the running launcher / agent CLI / hub itself)
846
- * are also refused: killing them tears down the whole node and the
847
- * operator's intent is almost always to nuke a leaked child, not the
848
- * supervisor that keeps the rest alive. Process restart goes through
849
- * the dedicated `$process.restart` action, not this kill API.
850
- */
851
- async killProcess(input) {
852
- const match = (await this.listNodeProcesses()).find((p) => p.pid === input.pid);
853
- if (!match) return {
854
- success: false,
855
- reason: "pid not in node process table"
856
- };
857
- if (match.classification === "root" || match.classification === "system") {
858
- this.ctx.logger.warn("Refused to kill protected process", { meta: {
859
- pid: input.pid,
860
- classification: match.classification,
861
- addonId: match.addonId,
862
- command: match.command
863
- } });
864
- return {
865
- success: false,
866
- reason: match.classification === "root" ? "cannot kill root (current node supervisor)" : "cannot kill system (intentional dev-tree ancestor — vite, concurrently, npm, etc.)"
867
- };
868
- }
869
- const signal = input.force ? "SIGKILL" : "SIGTERM";
870
- try {
871
- process.kill(input.pid, signal);
872
- this.ctx.logger.info("Killed node process", { meta: {
873
- pid: input.pid,
874
- signal,
875
- classification: match.classification,
876
- addonId: match.addonId
877
- } });
878
- return {
879
- success: true,
880
- signal
881
- };
882
- } catch (err) {
883
- return {
884
- success: false,
885
- reason: err instanceof Error ? err.message : String(err),
886
- signal
887
- };
888
- }
889
2090
  }
890
2091
  /**
891
2092
  * Ask the addon's forked runner to write a V8 heap snapshot (SIGUSR2 → the
@@ -962,7 +2163,29 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
962
2163
  return [];
963
2164
  }
964
2165
  }
2166
+ /**
2167
+ * The knobs live HERE, on the document this addon already owns.
2168
+ *
2169
+ * Fields on an existing document, never a method per knob —
2170
+ * `system.getLoggingSettings` / `setLoggingSettings` set that precedent.
2171
+ * They are deliberately NOT in the logging document: that one is about
2172
+ * levels and diagnostic windows, and two documents both claiming a knob is
2173
+ * how this repo has already shipped a switch nobody read.
2174
+ *
2175
+ * Cluster-wide, not per-node: every node must emit on the same cadence or
2176
+ * the fleet's series cannot be laid over each other, and the table is single
2177
+ * and hub-resident, so a per-node retention would be a promise nothing could
2178
+ * keep.
2179
+ *
2180
+ * The cost line is computed from OBSERVED numbers — the nodes and process
2181
+ * counts the cluster is actually reporting — so an operator raising the
2182
+ * retention sees what it costs BEFORE applying it, not afterwards.
2183
+ */
965
2184
  globalSettingsSchema() {
2185
+ const projection = projectLoadSeriesCost({
2186
+ config: this.loadConfig,
2187
+ observedProcessRows: this.observedFleetRows()
2188
+ });
966
2189
  return this.schema({ sections: [{
967
2190
  id: "native-metrics-settings",
968
2191
  title: "System Metrics",
@@ -977,6 +2200,47 @@ var NativeMetricsAddon = class extends require_dist.BaseAddon {
977
2200
  default: 5e3,
978
2201
  unit: "ms"
979
2202
  })]
2203
+ }, {
2204
+ id: "native-metrics-load-series",
2205
+ title: "Load history",
2206
+ fields: [
2207
+ this.field({
2208
+ type: "number",
2209
+ key: "loadSeriesCadenceSec",
2210
+ label: "Sampling cadence",
2211
+ description: "How often every node reports its process tree. FIXED — a sample is emitted on every interval whether or not anything changed, so a gap in the chart means one thing only: nobody reported. Outside 5-60 s the value is refused.",
2212
+ min: 5,
2213
+ max: 60,
2214
+ step: 1,
2215
+ default: 10,
2216
+ unit: "s"
2217
+ }),
2218
+ this.field({
2219
+ type: "number",
2220
+ key: "loadSeriesRetentionHours",
2221
+ label: "Retention",
2222
+ description: "How long the load history is kept on disk (the hub database, on the NVMe cache — never the recordings disk). This is the INTENTION; the row cap below is the guarantee.",
2223
+ min: 1,
2224
+ max: 72,
2225
+ step: 1,
2226
+ default: 6,
2227
+ unit: "h"
2228
+ }),
2229
+ {
2230
+ type: "info",
2231
+ key: "load-series-cost",
2232
+ label: "What this configuration costs",
2233
+ content: describeLoadSeriesCost(projection),
2234
+ variant: projection.capBites ? "warning" : "info"
2235
+ },
2236
+ {
2237
+ type: "info",
2238
+ key: "load-series-cap",
2239
+ label: "Hard row cap",
2240
+ content: `The table never exceeds ${this.loadConfig.maxRows.toLocaleString("en-US")} rows. When it would, the OLDEST samples are evicted and a warning is logged — so raising the retention can never turn into an incident, only into a shorter effective window.`,
2241
+ variant: "info"
2242
+ }
2243
+ ]
980
2244
  }] });
981
2245
  }
982
2246
  };