@principal-ai/subsystems-react 0.23.1 → 0.23.2

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.
@@ -5,11 +5,17 @@ import {
5
5
  convertSubsystemToGroups,
6
6
  getSubsystemRegions,
7
7
  getSubsystemModuleRegions,
8
+ getSubsystemPackageRegions,
8
9
  processGroupNodeId,
9
10
  moduleGroupNodeId,
11
+ packageGroupNodeId,
12
+ buildBoundaryLayoutGroups,
10
13
  buildSubsystemGraph,
14
+ componentPackageKey,
11
15
  deriveNameFromSymbol,
12
16
  constructBadgeLabel,
17
+ constructBadgeColor,
18
+ FRAMEWORK_BADGE_COLOR,
13
19
  rightBadgeLabel,
14
20
  nodeMinWidthForBadges,
15
21
  formatPurl,
@@ -148,6 +154,15 @@ describe('subsystem graph model', () => {
148
154
  ).toBe('custom_entity');
149
155
  });
150
156
 
157
+ test('constructBadgeColor uses React brand only for framework stereotype badges', () => {
158
+ expect(
159
+ constructBadgeColor({ framework: 'react', stereotype: 'component' }),
160
+ ).toBe(FRAMEWORK_BADGE_COLOR.react);
161
+ expect(constructBadgeColor({ framework: 'react' })).toBeNull();
162
+ expect(constructBadgeColor({ stereotype: 'hook' })).toBeNull();
163
+ expect(constructBadgeColor({ framework: 'vue', stereotype: 'component' })).toBeNull();
164
+ });
165
+
151
166
  test('nodeMinWidthForBadges widens for long construct badges and role pairs', () => {
152
167
  const plain = nodeMinWidthForBadges({ construct: 'function' });
153
168
  expect(plain).toBe(150);
@@ -445,6 +460,158 @@ describe('subsystem graph model', () => {
445
460
  expect(nodes.find((n) => n.id === moduleGroupNodeId('src/session/transcript.ts'))).toBeDefined();
446
461
  });
447
462
 
463
+ test('getSubsystemPackageRegions groups by purl repo key, skipping externals', () => {
464
+ const regions = getSubsystemPackageRegions({
465
+ components: [
466
+ { id: 'a', name: 'a', construct: 'function', file: 'a.ts', purl: 'pkg:github/acme/app#a.ts' },
467
+ { id: 'b', name: 'b', construct: 'function', file: 'b.ts', purl: 'pkg:github/acme/app' },
468
+ { id: 'c', name: 'c', construct: 'function', file: 'c.ts', purl: 'pkg:github/other/lib' },
469
+ { id: 'ext', name: 'Stripe', construct: 'external', file: '', purl: 'pkg:npm/stripe' },
470
+ ],
471
+ });
472
+ expect(regions.map((r) => r.key).sort()).toEqual([
473
+ 'pkg:github/acme/app',
474
+ 'pkg:github/other/lib',
475
+ ].sort());
476
+ expect(regions.every((r) => r.kind === 'package')).toBe(true);
477
+ expect(componentPackageKey({ construct: 'external', purl: 'pkg:npm/stripe' })).toBeUndefined();
478
+ });
479
+
480
+ test('buildBoundaryLayoutGroups skips package frames for single-repo graphs', () => {
481
+ const groups = buildBoundaryLayoutGroups({
482
+ components: [
483
+ { id: 'a', name: 'a', construct: 'function', file: 'a.ts', purl: 'pkg:github/acme/app' },
484
+ { id: 'b', name: 'b', construct: 'function', file: 'b.ts', purl: 'pkg:github/acme/app' },
485
+ ],
486
+ });
487
+ expect(groups.filter((g) => g.region.kind === 'package')).toHaveLength(0);
488
+ });
489
+
490
+ test('buildBoundaryLayoutGroups frames packages when multi-repo', () => {
491
+ const groups = buildBoundaryLayoutGroups({
492
+ components: [
493
+ { id: 'a', name: 'a', construct: 'function', file: 'a.ts', purl: 'pkg:github/acme/app' },
494
+ { id: 'b', name: 'b', construct: 'function', file: 'b.ts', purl: 'pkg:github/acme/app' },
495
+ { id: 'c', name: 'c', construct: 'function', file: 'c.ts', purl: 'pkg:github/other/lib' },
496
+ { id: 'd', name: 'd', construct: 'function', file: 'd.ts', purl: 'pkg:github/other/lib' },
497
+ ],
498
+ });
499
+ const pkgs = groups.filter((g) => g.region.kind === 'package');
500
+ expect(pkgs.map((g) => g.region.key).sort()).toEqual([
501
+ 'pkg:github/acme/app',
502
+ 'pkg:github/other/lib',
503
+ ].sort());
504
+ });
505
+
506
+ test('buildBoundaryLayoutGroups nests process under package', () => {
507
+ const groups = buildBoundaryLayoutGroups({
508
+ components: [
509
+ {
510
+ id: 'a',
511
+ name: 'a',
512
+ construct: 'function',
513
+ file: 'a.ts',
514
+ purl: 'pkg:github/acme/app',
515
+ process: 'app/host',
516
+ },
517
+ {
518
+ id: 'b',
519
+ name: 'b',
520
+ construct: 'function',
521
+ file: 'b.ts',
522
+ purl: 'pkg:github/acme/app',
523
+ process: 'app/host',
524
+ },
525
+ {
526
+ id: 'c',
527
+ name: 'c',
528
+ construct: 'function',
529
+ file: 'c.ts',
530
+ purl: 'pkg:github/other/lib',
531
+ process: 'lib/worker',
532
+ },
533
+ {
534
+ id: 'd',
535
+ name: 'd',
536
+ construct: 'function',
537
+ file: 'd.ts',
538
+ purl: 'pkg:github/other/lib',
539
+ process: 'lib/worker',
540
+ },
541
+ ],
542
+ });
543
+ const host = groups.find((g) => g.id === processGroupNodeId('app/host'));
544
+ expect(host?.parentId).toBe(packageGroupNodeId('pkg:github/acme/app'));
545
+ });
546
+
547
+ test('buildSubsystemGraph nests package → process → module', async () => {
548
+ const { nodes } = await buildSubsystemGraph({
549
+ components: [
550
+ {
551
+ id: 'a1',
552
+ name: 'a1',
553
+ construct: 'function',
554
+ file: 'a.ts',
555
+ purl: 'pkg:github/acme/app',
556
+ process: 'app/host',
557
+ module: 'src/a.ts',
558
+ },
559
+ {
560
+ id: 'a2',
561
+ name: 'a2',
562
+ construct: 'function',
563
+ file: 'a.ts',
564
+ purl: 'pkg:github/acme/app',
565
+ process: 'app/host',
566
+ module: 'src/a.ts',
567
+ },
568
+ {
569
+ id: 'b1',
570
+ name: 'b1',
571
+ construct: 'function',
572
+ file: 'b.ts',
573
+ purl: 'pkg:github/other/lib',
574
+ process: 'lib/worker',
575
+ module: 'src/b.ts',
576
+ },
577
+ {
578
+ id: 'b2',
579
+ name: 'b2',
580
+ construct: 'function',
581
+ file: 'b.ts',
582
+ purl: 'pkg:github/other/lib',
583
+ process: 'lib/worker',
584
+ module: 'src/b.ts',
585
+ },
586
+ ],
587
+ relations: [],
588
+ });
589
+ const pkgA = nodes.find((n) => n.id === packageGroupNodeId('pkg:github/acme/app'));
590
+ const proc = nodes.find((n) => n.id === processGroupNodeId('app/host'));
591
+ const mod = nodes.find((n) => n.id === moduleGroupNodeId('src/a.ts'));
592
+ expect(pkgA).toBeDefined();
593
+ expect((proc as { parentId?: string }).parentId).toBe(
594
+ packageGroupNodeId('pkg:github/acme/app'),
595
+ );
596
+ expect((mod as { parentId?: string }).parentId).toBe(processGroupNodeId('app/host'));
597
+ expect((nodes.find((n) => n.id === 'a1') as { parentId?: string }).parentId).toBe(
598
+ moduleGroupNodeId('src/a.ts'),
599
+ );
600
+ });
601
+
602
+ test('packageFrames always draws single-repo package frames when multi-member', () => {
603
+ const groups = buildBoundaryLayoutGroups(
604
+ {
605
+ components: [
606
+ { id: 'a', name: 'a', construct: 'function', file: 'a.ts', purl: 'pkg:github/acme/app' },
607
+ { id: 'b', name: 'b', construct: 'function', file: 'b.ts', purl: 'pkg:github/acme/app' },
608
+ ],
609
+ },
610
+ { packageFrames: 'always' },
611
+ );
612
+ expect(groups.filter((g) => g.region.kind === 'package')).toHaveLength(1);
613
+ });
614
+
448
615
  test('subsystemGraphLayoutKey ignores declarationRef-only changes', () => {
449
616
  const base = doc;
450
617
  const withRef = {
@@ -20,6 +20,7 @@ import {
20
20
  import { computeElkLayout, calculatePathLength } from '../utils/elkLayout';
21
21
  import type { GraphifyComponentDetail } from '../graphify';
22
22
  import type { SubsystemDeclarationRef } from './declarationRef';
23
+ import { purlOwnerName, purlRepoKey } from './paths';
23
24
 
24
25
  /** Structured declaration shape — same union as graphify drill-down payloads. */
25
26
  export type SubsystemConstructDeclaration = GraphifyComponentDetail;
@@ -430,13 +431,15 @@ export function formatPurl(purl: string): string {
430
431
  export type SubsystemGraphNodeType = 'subsystem-component' | 'subsystem-group';
431
432
 
432
433
  /**
433
- * One boundary region — either a process (runtime deployment unit) or a
434
- * module (source file). Nodes without that field sit outside those frames.
434
+ * One boundary region — process (runtime), module (source file), or package
435
+ * (repo identity from `purl`). Nodes without that membership sit outside
436
+ * those frames. Package frames are derived from `purl` (no separate field);
437
+ * they only appear when the graph spans multiple repos (by default).
435
438
  */
436
439
  export interface SubsystemProcessRegion {
437
- /** Discriminator — which field produced this region. */
438
- kind: 'process' | 'module';
439
- /** The `process` or `module` value (e.g. `principal-studio/host`, `src/a.ts`). */
440
+ /** Discriminator — which field / identity produced this region. */
441
+ kind: 'process' | 'module' | 'package';
442
+ /** The `process` / `module` value, or purl repo key for packages. */
440
443
  key: string;
441
444
  /** Display label for the boundary frame. */
442
445
  label: string;
@@ -444,6 +447,22 @@ export interface SubsystemProcessRegion {
444
447
  memberIds: string[];
445
448
  }
446
449
 
450
+ /** Options for which boundary frames are kept. */
451
+ export interface BoundaryFrameOptions {
452
+ /**
453
+ * Keep 1-member process / module / package frames. Default false
454
+ * (singleton rule — frames need 2+ members).
455
+ */
456
+ showSingletonFrames?: boolean;
457
+ /**
458
+ * When package frames are drawn from component `purl`s.
459
+ * - `multi-repo` (default): only when 2+ distinct repo purls
460
+ * - `always`: frame every multi-member package even in a single-repo graph
461
+ * - `never`: no package frames
462
+ */
463
+ packageFrames?: 'multi-repo' | 'always' | 'never';
464
+ }
465
+
447
466
  /** React Flow id for a process boundary group node. */
448
467
  export function processGroupNodeId(processKey: string): string {
449
468
  return `process:${processKey}`;
@@ -454,11 +473,33 @@ export function moduleGroupNodeId(moduleKey: string): string {
454
473
  return `module:${moduleKey}`;
455
474
  }
456
475
 
457
- /** React Flow id for a boundary group of either kind. */
476
+ /** React Flow id for a package (repo) boundary group node. */
477
+ export function packageGroupNodeId(packageKey: string): string {
478
+ return `package:${packageKey}`;
479
+ }
480
+
481
+ /** React Flow id for a boundary group of any kind. */
458
482
  export function boundaryGroupNodeId(region: Pick<SubsystemProcessRegion, 'kind' | 'key'>): string {
459
- return region.kind === 'module'
460
- ? moduleGroupNodeId(region.key)
461
- : processGroupNodeId(region.key);
483
+ if (region.kind === 'module') return moduleGroupNodeId(region.key);
484
+ if (region.kind === 'package') return packageGroupNodeId(region.key);
485
+ return processGroupNodeId(region.key);
486
+ }
487
+
488
+ /**
489
+ * Repo/package key used for package frames — `purl` with fragment stripped.
490
+ * Externals and custom entities are not package-frame members.
491
+ */
492
+ export function componentPackageKey(
493
+ c: Pick<SubsystemComponent, 'purl' | 'construct'>,
494
+ ): string | undefined {
495
+ if (c.construct === 'external' || c.construct === 'custom_entity') return undefined;
496
+ const key = purlRepoKey(c.purl);
497
+ if (!key || key === 'external') return undefined;
498
+ return key;
499
+ }
500
+
501
+ function packageRegionLabel(packageKey: string): string {
502
+ return purlOwnerName(packageKey) ?? formatPurl(packageKey);
462
503
  }
463
504
 
464
505
  /**
@@ -508,42 +549,103 @@ export function getSubsystemModuleRegions(
508
549
  }
509
550
 
510
551
  /**
511
- * One compound frame for ELK / React Flow — module frames may nest under a
512
- * process frame via `parentId`.
552
+ * Derive package (repo) boundary regions from component `purl`s — one per
553
+ * distinct repo key. Does not apply multi-repo / singleton filters; callers
554
+ * decide via {@link buildBoundaryLayoutGroups}.
555
+ */
556
+ export function getSubsystemPackageRegions(
557
+ doc: Pick<SubsystemModelDocument, 'components'>,
558
+ ): SubsystemProcessRegion[] {
559
+ const byPackage = new Map<string, string[]>();
560
+ for (const c of doc.components) {
561
+ const key = componentPackageKey(c);
562
+ if (!key) continue;
563
+ const list = byPackage.get(key) ?? [];
564
+ list.push(c.id);
565
+ byPackage.set(key, list);
566
+ }
567
+ return [...byPackage.entries()].map(([key, memberIds]) => ({
568
+ kind: 'package' as const,
569
+ key,
570
+ label: packageRegionLabel(key),
571
+ memberIds,
572
+ }));
573
+ }
574
+
575
+ /**
576
+ * One compound frame for ELK / React Flow — modules nest under processes,
577
+ * processes under packages, when membership is shared.
513
578
  */
514
579
  export interface BoundaryLayoutGroup {
515
580
  id: string;
516
581
  memberIds: string[];
517
- /** When set, this group is a child of another boundary group (process). */
582
+ /** When set, this group is a child of another boundary group. */
518
583
  parentId?: string;
519
584
  region: SubsystemProcessRegion;
520
585
  }
521
586
 
587
+ function keepRegion(
588
+ r: SubsystemProcessRegion,
589
+ showSingletons: boolean,
590
+ ): boolean {
591
+ return showSingletons || r.memberIds.length >= 2;
592
+ }
593
+
522
594
  /**
523
- * Build the process → module → leaf group tree for layout.
524
- * Multi-member modules nest under a process when every member shares that
525
- * process; process ELK children are nested module group ids plus any
526
- * process members that are not inside a kept module frame.
595
+ * Build the package → process → module → leaf group tree for layout.
596
+ *
597
+ * Package frames come from `purl` (no separate component field). By default
598
+ * they only appear when the graph spans 2+ distinct repos. Multi-member
599
+ * modules nest under a process when every member shares that process;
600
+ * processes nest under a package the same way.
527
601
  */
528
602
  export function buildBoundaryLayoutGroups(
529
603
  doc: Pick<SubsystemModelDocument, 'components'>,
604
+ opts: BoundaryFrameOptions = {},
530
605
  ): BoundaryLayoutGroup[] {
606
+ const showSingletons = opts.showSingletonFrames === true;
607
+ const packageMode = opts.packageFrames ?? 'multi-repo';
531
608
  const byId = new Map(doc.components.map((c) => [c.id, c]));
532
- const modules = getSubsystemModuleRegions(doc).filter((r) => r.memberIds.length >= 2);
533
- const processes = getSubsystemRegions(doc).filter((r) => r.memberIds.length >= 2);
609
+
610
+ const allPackages = getSubsystemPackageRegions(doc);
611
+ const packageEligible =
612
+ packageMode === 'always'
613
+ ? true
614
+ : packageMode === 'never'
615
+ ? false
616
+ : allPackages.length >= 2;
617
+ const packages = packageEligible
618
+ ? allPackages.filter((r) => keepRegion(r, showSingletons))
619
+ : [];
620
+ const keptPackageKeys = new Set(packages.map((r) => r.key));
621
+
622
+ const modules = getSubsystemModuleRegions(doc).filter((r) =>
623
+ keepRegion(r, showSingletons),
624
+ );
625
+ const processes = getSubsystemRegions(doc).filter((r) =>
626
+ keepRegion(r, showSingletons),
627
+ );
534
628
  const keptProcessKeys = new Set(processes.map((r) => r.key));
535
629
 
536
630
  const moduleGroups: BoundaryLayoutGroup[] = modules.map((r) => {
537
631
  const processesOfMembers = new Set<string>();
632
+ const packagesOfMembers = new Set<string>();
538
633
  for (const id of r.memberIds) {
539
- const p = byId.get(id)?.process?.trim();
634
+ const c = byId.get(id);
635
+ const p = c?.process?.trim();
540
636
  if (p) processesOfMembers.add(p);
637
+ const pkg = c ? componentPackageKey(c) : undefined;
638
+ if (pkg) packagesOfMembers.add(pkg);
541
639
  }
542
640
  let parentId: string | undefined;
543
641
  if (processesOfMembers.size === 1) {
544
642
  const p = [...processesOfMembers][0]!;
545
643
  if (keptProcessKeys.has(p)) parentId = processGroupNodeId(p);
546
644
  }
645
+ if (!parentId && packagesOfMembers.size === 1) {
646
+ const pkg = [...packagesOfMembers][0]!;
647
+ if (keptPackageKeys.has(pkg)) parentId = packageGroupNodeId(pkg);
648
+ }
547
649
  return {
548
650
  id: moduleGroupNodeId(r.key),
549
651
  memberIds: [...r.memberIds],
@@ -561,14 +663,51 @@ export function buildBoundaryLayoutGroups(
561
663
  if (!mod) return true;
562
664
  return !nestedModuleKeys.has(mod);
563
665
  });
666
+
667
+ const packagesOfMembers = new Set<string>();
668
+ for (const id of r.memberIds) {
669
+ const c = byId.get(id);
670
+ const pkg = c ? componentPackageKey(c) : undefined;
671
+ if (pkg) packagesOfMembers.add(pkg);
672
+ }
673
+ let parentId: string | undefined;
674
+ if (packagesOfMembers.size === 1) {
675
+ const pkg = [...packagesOfMembers][0]!;
676
+ if (keptPackageKeys.has(pkg)) parentId = packageGroupNodeId(pkg);
677
+ }
678
+
564
679
  return {
565
680
  id: processId,
566
681
  memberIds: [...nestedModules.map((m) => m.id), ...directLeaves],
682
+ parentId,
567
683
  region: r,
568
684
  };
569
685
  });
570
686
 
571
- return [...moduleGroups, ...processGroups];
687
+ const packageGroups: BoundaryLayoutGroup[] = packages.map((r) => {
688
+ const packageId = packageGroupNodeId(r.key);
689
+ const nestedProcesses = processGroups.filter((p) => p.parentId === packageId);
690
+ const nestedModules = moduleGroups.filter((m) => m.parentId === packageId);
691
+ const claimed = new Set<string>();
692
+ for (const p of nestedProcesses) {
693
+ for (const id of p.region.memberIds) claimed.add(id);
694
+ }
695
+ for (const m of nestedModules) {
696
+ for (const id of m.region.memberIds) claimed.add(id);
697
+ }
698
+ const directLeaves = r.memberIds.filter((id) => !claimed.has(id));
699
+ return {
700
+ id: packageId,
701
+ memberIds: [
702
+ ...nestedProcesses.map((p) => p.id),
703
+ ...nestedModules.map((m) => m.id),
704
+ ...directLeaves,
705
+ ],
706
+ region: r,
707
+ };
708
+ });
709
+
710
+ return [...moduleGroups, ...processGroups, ...packageGroups];
572
711
  }
573
712
 
574
713
  export interface SubsystemGraphNodeData extends Record<string, unknown> {
@@ -689,6 +828,14 @@ export const ROLE_COLOR: Record<SubsystemComponentRole, string> = {
689
828
  service: '#0893d2', // blue — external system
690
829
  };
691
830
 
831
+ /**
832
+ * Brand color for the left construct/stereotype badge when a framework owns
833
+ * the label (e.g. `react · component`). Node border stays construct-colored.
834
+ */
835
+ export const FRAMEWORK_BADGE_COLOR: Record<string, string> = {
836
+ react: '#61dafb', // React cyan
837
+ };
838
+
692
839
  export const ROLE_LABEL: Record<SubsystemComponentRole, string> = {
693
840
  entry: 'entry',
694
841
  service: 'service',
@@ -790,14 +937,27 @@ export function constructBadgeLabel(component: {
790
937
  return constructLabel ?? '';
791
938
  }
792
939
 
940
+ /**
941
+ * Left-badge accent: framework brand when the badge shows a framework
942
+ * stereotype (e.g. React cyan for `react · component`); otherwise null so
943
+ * the caller falls back to construct color. Border stays construct-colored.
944
+ */
945
+ export function constructBadgeColor(component: {
946
+ framework?: string;
947
+ stereotype?: string;
948
+ }): string | null {
949
+ if (component.framework == null || component.stereotype == null) return null;
950
+ return FRAMEWORK_BADGE_COLOR[component.framework] ?? null;
951
+ }
952
+
793
953
  /** Default CSS floor for component nodes (padding aside). */
794
954
  export const NODE_CSS_MIN_WIDTH = 150;
795
955
  /** Inset of each top badge from the node edge (`left` / `right` style). */
796
956
  export const BADGE_EDGE_INSET = 5;
797
957
  /** Minimum gap between left construct badge and right role badge. */
798
958
  const BADGE_PAIR_GAP = 8;
799
- /** Badge box chrome: padding 5+5 + border 1+1. */
800
- const BADGE_BOX_CHROME = 12;
959
+ /** Badge box chrome: padding 8+8 + border 2+2. */
960
+ const BADGE_BOX_CHROME = 20;
801
961
  /** Approx monospace uppercase width incl. letter-spacing (~0.5px). */
802
962
  const BADGE_CHAR_WIDTH = 8;
803
963
 
@@ -840,11 +1000,11 @@ export function nodeMinWidthForBadges(component: {
840
1000
  /**
841
1001
  * Convert a subsystem graph document into React Flow nodes. Components that
842
1002
  * carry a `module` get a `parentId` pointing at their module frame
843
- * (`module:<path>`); otherwise a `process` stamps `process:<process>`. Module
844
- * frames may themselves nest under a process frame (stamped on the group node
845
- * in `buildSubsystemGraph`). Nodes without either stay top-level. The initial
846
- * grid clusters by `module ?? process ?? purl`; ELK then refines with compound
847
- * layout.
1003
+ * (`module:<path>`); otherwise a `process` stamps `process:<process>`.
1004
+ * Package (`purl`) parents are stamped later in `buildSubsystemGraph` only
1005
+ * when package frames are kept. Module frames may nest under process →
1006
+ * package. The initial grid clusters by `module ?? process ?? purl`; ELK
1007
+ * then refines with compound layout.
848
1008
  */
849
1009
  export function convertSubsystemToNodes(
850
1010
  doc: SubsystemModelDocument,
@@ -913,14 +1073,15 @@ export function convertSubsystemToNodes(
913
1073
  }
914
1074
 
915
1075
  /**
916
- * Convert boundary regions into React Flow parent (group) nodes. Module
917
- * frames that share a process nest under that process via `parentId`.
1076
+ * Convert boundary regions into React Flow parent (group) nodes. Nesting
1077
+ * (package → process → module) is stamped via `parentId` on groups.
918
1078
  * Positions/sizes are placeholders — ELK compound layout overwrites them.
919
1079
  */
920
1080
  export function convertSubsystemToGroups(
921
1081
  doc: Pick<SubsystemModelDocument, 'components'>,
1082
+ opts: BoundaryFrameOptions = {},
922
1083
  ): SubsystemGraphNode[] {
923
- return buildBoundaryLayoutGroups(doc).map((g) => ({
1084
+ return buildBoundaryLayoutGroups(doc, opts).map((g) => ({
924
1085
  id: g.id,
925
1086
  type: 'subsystem-group' as const,
926
1087
  position: { x: 0, y: 0 },
@@ -988,36 +1149,55 @@ export function subsystemGraphLayoutKey(
988
1149
  */
989
1150
  export async function buildSubsystemGraph(
990
1151
  doc: SubsystemModelDocument,
991
- opts: { maxNodeWidth?: number; showEdgeLabels?: boolean; measuredWidths?: Map<string, number>; measuredHeights?: Map<string, number> } = {},
1152
+ opts: {
1153
+ maxNodeWidth?: number;
1154
+ showEdgeLabels?: boolean;
1155
+ measuredWidths?: Map<string, number>;
1156
+ measuredHeights?: Map<string, number>;
1157
+ } & BoundaryFrameOptions = {},
992
1158
  ): Promise<{
993
1159
  nodes: SubsystemGraphNode[];
994
1160
  edges: SubsystemGraphEdge[];
995
1161
  regions: SubsystemProcessRegion[];
996
1162
  }> {
997
- const { maxNodeWidth, showEdgeLabels, measuredWidths, measuredHeights } = opts;
1163
+ const {
1164
+ maxNodeWidth,
1165
+ showEdgeLabels,
1166
+ measuredWidths,
1167
+ measuredHeights,
1168
+ showSingletonFrames,
1169
+ packageFrames,
1170
+ } = opts;
1171
+ const frameOpts: BoundaryFrameOptions = { showSingletonFrames, packageFrames };
998
1172
  const nodes = convertSubsystemToNodes(doc, { maxNodeWidth });
999
1173
  const edges = convertSubsystemToEdges(doc);
1000
- // Nested boundary tree: process → module → leaves (when both fields set).
1001
- const layoutGroups = buildBoundaryLayoutGroups(doc);
1174
+ // Nested boundary tree: package → process → module → leaves.
1175
+ const layoutGroups = buildBoundaryLayoutGroups(doc, frameOpts);
1002
1176
  const regions = layoutGroups.map((g) => g.region);
1003
1177
  const regionIds = new Set(layoutGroups.map((g) => g.id));
1004
1178
  const byId = new Map(doc.components.map((c) => [c.id, c]));
1005
1179
 
1006
- // Drop leaf parentIds that point at singleton / missing frames; fall back
1007
- // from a dropped module frame to a kept process frame when possible.
1180
+ // Resolve leaf parentIds against kept frames: module → process → package.
1181
+ // Stamp package parents here (not in convertSubsystemToNodes) so single-repo
1182
+ // graphs never provisionally parent under a package that will be dropped.
1008
1183
  for (const n of nodes) {
1009
1184
  if (n.type !== 'subsystem-component') continue;
1010
1185
  const parentId = (n as { parentId?: string }).parentId;
1011
- if (!parentId) continue;
1012
- if (regionIds.has(parentId)) continue;
1013
- const comp = (n.data as SubsystemGraphNodeData).component;
1014
- const processKey = comp?.process?.trim() || byId.get(n.id)?.process?.trim();
1186
+ if (parentId && regionIds.has(parentId)) continue;
1187
+ const comp = (n.data as SubsystemGraphNodeData).component ?? byId.get(n.id);
1188
+ const processKey = comp?.process?.trim();
1015
1189
  const processId = processKey ? processGroupNodeId(processKey) : undefined;
1016
1190
  if (processId && regionIds.has(processId)) {
1017
1191
  (n as { parentId?: string }).parentId = processId;
1018
- } else {
1019
- delete (n as { parentId?: string }).parentId;
1192
+ continue;
1020
1193
  }
1194
+ const packageKey = comp ? componentPackageKey(comp) : undefined;
1195
+ const packageId = packageKey ? packageGroupNodeId(packageKey) : undefined;
1196
+ if (packageId && regionIds.has(packageId)) {
1197
+ (n as { parentId?: string }).parentId = packageId;
1198
+ continue;
1199
+ }
1200
+ if (parentId) delete (n as { parentId?: string }).parentId;
1021
1201
  }
1022
1202
 
1023
1203
  // External edge targets that aren't real components → create stub nodes so
@@ -1090,7 +1270,8 @@ export async function buildSubsystemGraph(
1090
1270
  })),
1091
1271
  });
1092
1272
  const builtGroupIds = new Set(result.groupBounds.keys());
1093
- // Parents before children — process frames, then nested module frames.
1273
+ // Parents before children — package, then process, then module frames.
1274
+ const packageGroupNodes: SubsystemGraphNode[] = [];
1094
1275
  const processGroupNodes: SubsystemGraphNode[] = [];
1095
1276
  const moduleGroupNodes: SubsystemGraphNode[] = [];
1096
1277
  for (const g of layoutGroups) {
@@ -1107,7 +1288,8 @@ export async function buildSubsystemGraph(
1107
1288
  ...(parentId ? { parentId } : {}),
1108
1289
  data: { region: g.region },
1109
1290
  };
1110
- if (g.region.kind === 'process') processGroupNodes.push(group);
1291
+ if (g.region.kind === 'package') packageGroupNodes.push(group);
1292
+ else if (g.region.kind === 'process') processGroupNodes.push(group);
1111
1293
  else moduleGroupNodes.push(group);
1112
1294
  }
1113
1295
  // Clear leaf parentIds that point at groups ELK dropped.
@@ -1119,6 +1301,7 @@ export async function buildSubsystemGraph(
1119
1301
  }
1120
1302
  }
1121
1303
  placedNodes = [
1304
+ ...packageGroupNodes,
1122
1305
  ...processGroupNodes,
1123
1306
  ...moduleGroupNodes,
1124
1307
  ...(result.nodes as SubsystemGraphNode[]),
@@ -1130,6 +1313,7 @@ export async function buildSubsystemGraph(
1130
1313
  // Fall back to the (unpositioned) grid if ELK is unavailable — still
1131
1314
  // emit multi-member frames so parentId targets exist.
1132
1315
  console.warn('[subsystem-graph] ELK layout failed, using manual positions:', err);
1316
+ const packageGroupNodes: SubsystemGraphNode[] = [];
1133
1317
  const processGroupNodes: SubsystemGraphNode[] = [];
1134
1318
  const moduleGroupNodes: SubsystemGraphNode[] = [];
1135
1319
  for (const g of layoutGroups) {
@@ -1142,10 +1326,16 @@ export async function buildSubsystemGraph(
1142
1326
  ...(g.parentId ? { parentId: g.parentId } : {}),
1143
1327
  data: { region: g.region },
1144
1328
  };
1145
- if (g.region.kind === 'process') processGroupNodes.push(group);
1329
+ if (g.region.kind === 'package') packageGroupNodes.push(group);
1330
+ else if (g.region.kind === 'process') processGroupNodes.push(group);
1146
1331
  else moduleGroupNodes.push(group);
1147
1332
  }
1148
- placedNodes = [...processGroupNodes, ...moduleGroupNodes, ...nodes];
1333
+ placedNodes = [
1334
+ ...packageGroupNodes,
1335
+ ...processGroupNodes,
1336
+ ...moduleGroupNodes,
1337
+ ...nodes,
1338
+ ];
1149
1339
  }
1150
1340
  }
1151
1341