@cclabsnz/sf-core 0.4.0 → 0.5.1

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.
package/CHANGELOG.md CHANGED
@@ -10,7 +10,63 @@ CycloneDX SBOM for the build.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
- Merged to `main`, not yet released.
13
+ Nothing yet.
14
+
15
+ ## [0.5.1] — 2026-09-09
16
+
17
+ ### Fixed
18
+
19
+ - **The unsupported-schema-version finding offered a remedy that does not exist.** Its `fix` read
20
+ "Re-extract the graph with this version of the tool, or run the migration to 1.2.0", and no
21
+ migration was ever written — `docs/` in the consuming repo explicitly declines to write one. A
22
+ reader hitting it went looking for a command that is not there, unsure whether they had missed a
23
+ step or the tool was wrong.
24
+
25
+ It survived because it was unreachable. `SUPPORTED_GRAPH_SCHEMA_VERSION` was set once and never
26
+ moved, so no document could disagree with it and the finding could not fire; 0.5.0's bump to
27
+ `1.2.0` was the first thing that made it reachable, in the same release that first published it
28
+ to a second consumer. The existing test asserted only that `fix` was non-empty, which is the
29
+ letter of that field's contract — "a finding a reader cannot act on is a bug report" — and could
30
+ not tell an action apart from a promise. A test now pins that the fix does not direct anyone to
31
+ run a migration, while still allowing it to say that none exists, which is worth saying.
32
+
33
+ ## [0.5.0] — 2026-09-09
34
+
35
+ **The canonical org graph, and a merge that refuses to state something false.**
36
+
37
+ ### Added
38
+
39
+ - **The canonical org graph.** `CanonicalGraph`, `GraphNode`/`GraphEdge`, `GRAPH_SCHEMA`,
40
+ `validateGraph`, `GRAPH_KIND_TABLE` and the `GRAPH_RULES` codes, moved here from the
41
+ `sf-orgviz` plugin that owned them. Two tools can now produce fragments of one schema without
42
+ either depending on the other. `GRAPH_KIND_TABLE` declares which producer owns each node kind,
43
+ so the split is enforced rather than documented — ownership is per kind and not per layer
44
+ because node ids are `prefix.name`, which makes disjoint kinds the thing that actually keeps
45
+ ids disjoint.
46
+ - **`mergeGraphs(fragments)`.** Unions fragments and refuses the merge when it would state
47
+ something false: fragments from different orgs, fragments at different schema versions, one
48
+ node id claimed twice, or a producer emitting a kind it does not own. A rejection returns no
49
+ graph at all, because a partial merge that still looks like a complete picture is worse than
50
+ none. `capturedAt` on a merged graph is the **oldest** fragment's — a merged picture is only as
51
+ fresh as its stalest part, and taking the newest would let a fresh run make a stale one look
52
+ current — and coverage is unioned, so a fact one producer could not read stays unread after
53
+ merging with one that could.
54
+ - **Attribute contributions.** A producer may state a measurement about a node another producer
55
+ owns, applied under the contributor's own namespace so that who asserted a value stays
56
+ answerable and two producers writing one key cannot become a silent last-writer-wins. An
57
+ unresolved contribution is reported rather than fatal: it means a fragment is missing, not that
58
+ the graph is wrong.
59
+ - **`roleOf(objectName)`.** The seven-role Salesforce object classifier, ported from
60
+ `sf-orgintel`, returning the already-published `ObjectLayer`. Renamed from `layerOf` on the way
61
+ in, because this package also exports `layerOfKind`, which classifies on an entirely different
62
+ axis.
63
+
64
+ ### Changed
65
+
66
+ - `ajv` moved from a development dependency to a runtime one. The graph validator ships from here
67
+ now, so consumers receive it transitively; this package previously declared no runtime
68
+ dependencies at all. The existing `fast-uri@3` override, which exists because of ajv's own
69
+ dependency chain, is unchanged.
14
70
 
15
71
  ## [0.4.0] — 2026-09-09
16
72
 
@@ -0,0 +1,3 @@
1
+ import type { GraphCoverage } from './types.js';
2
+ export declare function summariseGraphCoverage(coverage: GraphCoverage): string[];
3
+ //# sourceMappingURL=coverage.d.ts.map
@@ -0,0 +1,10 @@
1
+ export function summariseGraphCoverage(coverage) {
2
+ const lines = [];
3
+ for (const note of coverage.notes)
4
+ lines.push(` note: ${note}`);
5
+ for (const u of coverage.unavailable) {
6
+ lines.push(` not read: ${u.scope} (${u.reason}) — ${u.detail}`);
7
+ }
8
+ return lines;
9
+ }
10
+ //# sourceMappingURL=coverage.js.map
@@ -0,0 +1,9 @@
1
+ export * from './types.js';
2
+ export * from './kinds.js';
3
+ export * from './rules.js';
4
+ export * from './schema.js';
5
+ export * from './validate.js';
6
+ export * from './coverage.js';
7
+ export * from './roleOf.js';
8
+ export * from './merge.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ // src/graph/index.ts
2
+ export * from './types.js';
3
+ export * from './kinds.js';
4
+ export * from './rules.js';
5
+ export * from './schema.js';
6
+ export * from './validate.js';
7
+ export * from './coverage.js';
8
+ export * from './roleOf.js';
9
+ export * from './merge.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,109 @@
1
+ import type { GraphLayer, GraphLevel, GraphProducer } from './types.js';
2
+ export interface GraphKindEntry {
3
+ layer: GraphLayer;
4
+ level: GraphLevel;
5
+ owner: GraphProducer;
6
+ }
7
+ export declare const GRAPH_KIND_TABLE: {
8
+ readonly org: {
9
+ readonly layer: "landscape";
10
+ readonly level: 0;
11
+ readonly owner: "orgviz";
12
+ };
13
+ readonly trustBoundary: {
14
+ readonly layer: "landscape";
15
+ readonly level: 0;
16
+ readonly owner: "orgviz";
17
+ };
18
+ readonly rollup: {
19
+ readonly layer: "landscape";
20
+ readonly level: 0;
21
+ readonly owner: "orgviz";
22
+ };
23
+ readonly domain: {
24
+ readonly layer: "domain";
25
+ readonly level: 1;
26
+ readonly owner: "orgviz";
27
+ };
28
+ readonly connectedApp: {
29
+ readonly layer: "landscape";
30
+ readonly level: 2;
31
+ readonly owner: "orgviz";
32
+ };
33
+ readonly namedCredential: {
34
+ readonly layer: "landscape";
35
+ readonly level: 2;
36
+ readonly owner: "orgviz";
37
+ };
38
+ readonly integration: {
39
+ readonly layer: "landscape";
40
+ readonly level: 2;
41
+ readonly owner: "orgviz";
42
+ };
43
+ readonly sobject: {
44
+ readonly layer: "data";
45
+ readonly level: 2;
46
+ readonly owner: "orgviz";
47
+ };
48
+ readonly profile: {
49
+ readonly layer: "access";
50
+ readonly level: 2;
51
+ readonly owner: "orgviz";
52
+ };
53
+ readonly permissionSet: {
54
+ readonly layer: "access";
55
+ readonly level: 2;
56
+ readonly owner: "orgviz";
57
+ };
58
+ readonly permissionSetGroup: {
59
+ readonly layer: "access";
60
+ readonly level: 2;
61
+ readonly owner: "orgviz";
62
+ };
63
+ readonly user: {
64
+ readonly layer: "access";
65
+ readonly level: 2;
66
+ readonly owner: "orgviz";
67
+ };
68
+ readonly flow: {
69
+ readonly layer: "process";
70
+ readonly level: 2;
71
+ readonly owner: "orgintel";
72
+ };
73
+ readonly apexClass: {
74
+ readonly layer: "process";
75
+ readonly level: 2;
76
+ readonly owner: "orgintel";
77
+ };
78
+ readonly trigger: {
79
+ readonly layer: "process";
80
+ readonly level: 2;
81
+ readonly owner: "orgintel";
82
+ };
83
+ readonly execution: {
84
+ readonly layer: "runtime";
85
+ readonly level: 2;
86
+ readonly owner: "orgintel";
87
+ };
88
+ readonly field: {
89
+ readonly layer: "data";
90
+ readonly level: 3;
91
+ readonly owner: "orgviz";
92
+ };
93
+ readonly grant: {
94
+ readonly layer: "access";
95
+ readonly level: 3;
96
+ readonly owner: "orgviz";
97
+ };
98
+ readonly flowElement: {
99
+ readonly layer: "process";
100
+ readonly level: 3;
101
+ readonly owner: "orgintel";
102
+ };
103
+ };
104
+ export type GraphNodeKind = keyof typeof GRAPH_KIND_TABLE;
105
+ export declare function isKnownGraphKind(kind: string): kind is GraphNodeKind;
106
+ export declare function levelOfKind(kind: GraphNodeKind): GraphLevel;
107
+ export declare function layerOfKind(kind: GraphNodeKind): GraphLayer;
108
+ export declare function ownerOfKind(kind: GraphNodeKind): GraphProducer;
109
+ //# sourceMappingURL=kinds.d.ts.map
@@ -0,0 +1,39 @@
1
+ export const GRAPH_KIND_TABLE = {
2
+ // Level 0 — the coarsest rollup. Deliberately tiny, so "about a dozen nodes" survives an
3
+ // org with forty connected apps. Spec section 2.2.
4
+ org: { layer: 'landscape', level: 0, owner: 'orgviz' },
5
+ trustBoundary: { layer: 'landscape', level: 0, owner: 'orgviz' },
6
+ rollup: { layer: 'landscape', level: 0, owner: 'orgviz' },
7
+ // Level 1 — mined groupings.
8
+ domain: { layer: 'domain', level: 1, owner: 'orgviz' },
9
+ // Level 2 — concrete entities.
10
+ connectedApp: { layer: 'landscape', level: 2, owner: 'orgviz' },
11
+ namedCredential: { layer: 'landscape', level: 2, owner: 'orgviz' },
12
+ integration: { layer: 'landscape', level: 2, owner: 'orgviz' },
13
+ sobject: { layer: 'data', level: 2, owner: 'orgviz' },
14
+ profile: { layer: 'access', level: 2, owner: 'orgviz' },
15
+ permissionSet: { layer: 'access', level: 2, owner: 'orgviz' },
16
+ permissionSetGroup: { layer: 'access', level: 2, owner: 'orgviz' },
17
+ user: { layer: 'access', level: 2, owner: 'orgviz' },
18
+ flow: { layer: 'process', level: 2, owner: 'orgintel' },
19
+ apexClass: { layer: 'process', level: 2, owner: 'orgintel' },
20
+ trigger: { layer: 'process', level: 2, owner: 'orgintel' },
21
+ execution: { layer: 'runtime', level: 2, owner: 'orgintel' },
22
+ // Level 3 — members.
23
+ field: { layer: 'data', level: 3, owner: 'orgviz' },
24
+ grant: { layer: 'access', level: 3, owner: 'orgviz' },
25
+ flowElement: { layer: 'process', level: 3, owner: 'orgintel' },
26
+ };
27
+ export function isKnownGraphKind(kind) {
28
+ return Object.prototype.hasOwnProperty.call(GRAPH_KIND_TABLE, kind);
29
+ }
30
+ export function levelOfKind(kind) {
31
+ return GRAPH_KIND_TABLE[kind].level;
32
+ }
33
+ export function layerOfKind(kind) {
34
+ return GRAPH_KIND_TABLE[kind].layer;
35
+ }
36
+ export function ownerOfKind(kind) {
37
+ return GRAPH_KIND_TABLE[kind].owner;
38
+ }
39
+ //# sourceMappingURL=kinds.js.map
@@ -0,0 +1,24 @@
1
+ import type { CanonicalGraph, GraphProducer } from './types.js';
2
+ import { type GraphDiagnostic } from './rules.js';
3
+ export interface GraphFragmentCapture {
4
+ producer: GraphProducer | null;
5
+ capturedAt: string;
6
+ }
7
+ export interface GraphMergeReport {
8
+ fragments: GraphFragmentCapture[];
9
+ contributionsApplied: number;
10
+ }
11
+ export interface GraphMergeResult {
12
+ /**
13
+ * Null if and only if one of the four rejections fired: org mismatch, schema version mismatch
14
+ * (including a merged document that would carry an unsupported version), id collision, or kind
15
+ * not owned. An unresolved or unattributed contribution is a different class of thing -- the
16
+ * same class as a dangling edge endpoint, which this design also reports rather than treats as
17
+ * fatal -- so it comes back as a finding alongside a non-null graph, never in place of one.
18
+ */
19
+ graph: CanonicalGraph | null;
20
+ findings: GraphDiagnostic[];
21
+ report: GraphMergeReport;
22
+ }
23
+ export declare function mergeGraphs(fragments: CanonicalGraph[]): GraphMergeResult;
24
+ //# sourceMappingURL=merge.d.ts.map
@@ -0,0 +1,175 @@
1
+ import { SUPPORTED_GRAPH_SCHEMA_VERSION } from './types.js';
2
+ import { GRAPH_RULES } from './rules.js';
3
+ import { isKnownGraphKind, ownerOfKind } from './kinds.js';
4
+ import { codepointCompare } from '../lib/order.js';
5
+ function mergeCoverage(fragments) {
6
+ return {
7
+ notes: fragments.flatMap((f) => f.coverage.notes),
8
+ unavailable: fragments.flatMap((f) => f.coverage.unavailable),
9
+ };
10
+ }
11
+ /** Sorted the same way regardless of the order the caller passed fragments in. Spec section 12. */
12
+ function sortFindings(findings) {
13
+ return findings.sort((a, b) => codepointCompare(a.code, b.code) || codepointCompare(a.id, b.id));
14
+ }
15
+ export function mergeGraphs(fragments) {
16
+ if (fragments.length === 0) {
17
+ return {
18
+ graph: null,
19
+ findings: [
20
+ {
21
+ code: GRAPH_RULES.MERGE_NO_FRAGMENTS,
22
+ id: 'document',
23
+ message: 'No fragments were supplied to merge.',
24
+ fix: 'Pass at least one canonical graph fragment to merge.',
25
+ },
26
+ ],
27
+ report: { fragments: [], contributionsApplied: 0 },
28
+ };
29
+ }
30
+ const report = {
31
+ fragments: fragments.map((f) => ({ producer: f.producer ?? null, capturedAt: f.capturedAt })),
32
+ contributionsApplied: 0,
33
+ };
34
+ const findings = [];
35
+ const orgIds = [...new Set(fragments.map((f) => f.orgId))];
36
+ if (orgIds.length > 1) {
37
+ findings.push({
38
+ code: GRAPH_RULES.MERGE_ORG_MISMATCH,
39
+ id: 'document',
40
+ message: `Fragments describe different orgs: ${orgIds.join(', ')}.`,
41
+ fix: 'Merge fragments captured from one org. Re-run whichever producer targeted the other.',
42
+ });
43
+ }
44
+ const versions = [...new Set(fragments.map((f) => f.schemaVersion))];
45
+ if (versions.length > 1) {
46
+ findings.push({
47
+ code: GRAPH_RULES.MERGE_SCHEMA_VERSION_MISMATCH,
48
+ id: 'document',
49
+ message: `Fragments are at different schema versions: ${versions.join(', ')}.`,
50
+ fix: `Re-produce every fragment with a build that writes ${SUPPORTED_GRAPH_SCHEMA_VERSION}.`,
51
+ });
52
+ }
53
+ else if (versions[0] !== SUPPORTED_GRAPH_SCHEMA_VERSION) {
54
+ // Every fragment agrees with every other, so the mismatch rule above never fires -- but they
55
+ // can all agree on a version this build no longer supports. Two fragments from a pre-bump
56
+ // build are the day-one case: they merge clean and the operator would otherwise only learn
57
+ // about it from a finding naming the merged OUTPUT, not the stale input that caused it.
58
+ findings.push({
59
+ code: GRAPH_RULES.MERGE_SCHEMA_VERSION_MISMATCH,
60
+ id: 'document',
61
+ message: `Fragments agree on schema version ${versions[0]}, which this build does not support.`,
62
+ fix: `Re-produce every fragment with a build that writes ${SUPPORTED_GRAPH_SCHEMA_VERSION}.`,
63
+ });
64
+ }
65
+ const seen = new Map();
66
+ for (const [index, f] of fragments.entries()) {
67
+ for (const node of f.nodes) {
68
+ const first = seen.get(node.id);
69
+ if (first !== undefined) {
70
+ const message = first === index
71
+ ? `Node ${node.id} is claimed twice within fragment ${index + 1}. ` +
72
+ 'One node is one fact; two fragments asserting it is two facts wearing one id.'
73
+ : `Node ${node.id} is claimed by fragment ${first + 1} and fragment ${index + 1}. ` +
74
+ 'One node is one fact; two fragments asserting it is two facts wearing one id.';
75
+ findings.push({
76
+ code: GRAPH_RULES.MERGE_ID_COLLISION,
77
+ id: node.id,
78
+ message,
79
+ fix: 'Give one producer the kind, per GRAPH_KIND_TABLE, and stop the other emitting it.',
80
+ });
81
+ }
82
+ else {
83
+ seen.set(node.id, index);
84
+ }
85
+ }
86
+ }
87
+ for (const f of fragments) {
88
+ // An unnamed producer cannot violate an ownership rule -- a hand-written or older fragment
89
+ // is still merged, and the id-collision rule above covers the harm ownership prevents.
90
+ if (!f.producer)
91
+ continue;
92
+ for (const node of f.nodes) {
93
+ if (!isKnownGraphKind(node.kind))
94
+ continue;
95
+ const owner = ownerOfKind(node.kind);
96
+ if (owner === f.producer)
97
+ continue;
98
+ findings.push({
99
+ code: GRAPH_RULES.MERGE_KIND_NOT_OWNED,
100
+ id: node.id,
101
+ message: `Fragment from ${f.producer} emits kind ${node.kind}, which ${owner} owns.`,
102
+ fix: `Emit ${node.kind} from ${owner}, or move its ownership in GRAPH_KIND_TABLE if the design changed.`,
103
+ });
104
+ }
105
+ }
106
+ if (findings.length > 0)
107
+ return { graph: null, findings: sortFindings(findings), report };
108
+ // Copied, never mutated: the caller may still be holding the fragments it passed in.
109
+ const nodes = fragments.flatMap((f) => f.nodes).map((n) => ({ ...n, attrs: { ...n.attrs } }));
110
+ const edges = fragments.flatMap((f) => f.edges).map((e) => ({ ...e, attrs: { ...e.attrs } }));
111
+ const byId = new Map(nodes.map((n) => [n.id, n]));
112
+ for (const f of fragments) {
113
+ for (const c of f.contributions ?? []) {
114
+ if (!f.producer) {
115
+ // Namespaced by contributor: an unnamespaced patch makes "who asserted this"
116
+ // unanswerable, and two anonymous fragments contributing the same key would be a silent
117
+ // last-writer-wins -- exactly what namespacing exists to prevent. Skipped, not merged
118
+ // under a shared 'unknown' bucket.
119
+ findings.push({
120
+ code: GRAPH_RULES.MERGE_CONTRIBUTION_UNATTRIBUTED,
121
+ id: c.nodeId,
122
+ message: `A fragment with no producer contributes attributes to ${c.nodeId}. An unattributed ` +
123
+ 'contribution cannot be namespaced, so it was not applied.',
124
+ fix: 'Set `producer` on the fragment that contributes attributes, or drop the contribution.',
125
+ });
126
+ continue;
127
+ }
128
+ const target = byId.get(c.nodeId);
129
+ if (!target) {
130
+ findings.push({
131
+ code: GRAPH_RULES.MERGE_CONTRIBUTION_UNRESOLVED,
132
+ id: c.nodeId,
133
+ message: `${f.producer} contributes attributes to ${c.nodeId}, which no fragment provides.`,
134
+ fix: 'Include the fragment that owns that node, or stop contributing to it.',
135
+ });
136
+ continue;
137
+ }
138
+ const ns = f.producer;
139
+ target.attrs[ns] = { ...target.attrs[ns], ...c.attrs };
140
+ report.contributionsApplied += 1;
141
+ }
142
+ }
143
+ // The oldest, not the newest. A merged picture is only as fresh as its stalest part, and
144
+ // taking the newest would let a fresh fragment make a month-old one look current. Compare
145
+ // chronologically, not lexically: two independently-written tools are not guaranteed to agree
146
+ // on timezone offset or fractional-second precision, and a lexical `<` gets those wrong (e.g.
147
+ // '...+05:00' can sort after a numerically earlier '...Z' instant). The ORIGINAL string is
148
+ // kept as the value -- never round-tripped through a Date and re-serialised, which would
149
+ // silently rewrite the caller's format. `Date.parse` returns NaN on an unparseable string, and
150
+ // NaN comparisons are always false, so an unguarded reduce lets a bad value at index 0 always
151
+ // win and a bad value elsewhere always lose, silently. A parseable timestamp is preferred over
152
+ // an unparseable one; only when every fragment is unparseable does the first one's string win.
153
+ const capturedAt = fragments.map((f) => f.capturedAt).reduce((oldest, t) => {
154
+ const oldestParsed = Date.parse(oldest);
155
+ const tParsed = Date.parse(t);
156
+ if (Number.isNaN(oldestParsed))
157
+ return Number.isNaN(tParsed) ? oldest : t;
158
+ if (Number.isNaN(tParsed))
159
+ return oldest;
160
+ return tParsed < oldestParsed ? t : oldest;
161
+ });
162
+ const graph = {
163
+ schemaVersion: fragments[0].schemaVersion,
164
+ capturedAt,
165
+ orgId: fragments[0].orgId,
166
+ nodes: nodes.sort((a, b) => codepointCompare(a.id, b.id)),
167
+ edges: edges.sort((a, b) => codepointCompare(a.from, b.from) ||
168
+ codepointCompare(a.to, b.to) ||
169
+ codepointCompare(a.kind, b.kind) ||
170
+ codepointCompare(a.provenance.source, b.provenance.source)),
171
+ coverage: mergeCoverage(fragments),
172
+ };
173
+ return { graph, findings: sortFindings(findings), report };
174
+ }
175
+ //# sourceMappingURL=merge.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Architectural layers of a Salesforce org's coupling graph.
3
+ *
4
+ * A real org's graph is dominated by objects that carry no business process — User, Profile,
5
+ * PermissionSet, logger tables, custom metadata — because Apex references them constantly.
6
+ * Filtering them out is tempting and wrong: on a production org, business↔security was the
7
+ * second-heaviest relationship in the entire graph, behind only business-internal coupling.
8
+ * That is a genuine architectural finding (the business model is deeply wired into the
9
+ * permission model) and deleting the objects deletes the finding.
10
+ *
11
+ * Classifying instead of filtering keeps every object, and turns the noise into structure.
12
+ */
13
+ import type { ObjectLayer } from '../schemas/index.js';
14
+ export declare const OBJECT_LAYER_DESCRIPTIONS: Readonly<Record<ObjectLayer, string>>;
15
+ /** Which layer an object belongs to. Unrecognised objects are business, never hidden. */
16
+ export declare function roleOf(object: string): ObjectLayer;
17
+ //# sourceMappingURL=roleOf.d.ts.map
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Architectural layers of a Salesforce org's coupling graph.
3
+ *
4
+ * A real org's graph is dominated by objects that carry no business process — User, Profile,
5
+ * PermissionSet, logger tables, custom metadata — because Apex references them constantly.
6
+ * Filtering them out is tempting and wrong: on a production org, business↔security was the
7
+ * second-heaviest relationship in the entire graph, behind only business-internal coupling.
8
+ * That is a genuine architectural finding (the business model is deeply wired into the
9
+ * permission model) and deleting the objects deletes the finding.
10
+ *
11
+ * Classifying instead of filtering keeps every object, and turns the noise into structure.
12
+ */
13
+ export const OBJECT_LAYER_DESCRIPTIONS = {
14
+ integration: 'platform events and external data',
15
+ configuration: 'custom metadata driving behaviour',
16
+ business: 'business process',
17
+ content: 'files, documents and email',
18
+ sharing: 'sharing, history and change tracking',
19
+ security: 'identity and permissions',
20
+ observability: 'logging and instrumentation',
21
+ };
22
+ /**
23
+ * Setup and platform objects. Matched exactly rather than by prefix: `Contract` must not be
24
+ * mistaken for `ContentDocument`, nor `UserStory__c` for `User`.
25
+ */
26
+ const SECURITY_OBJECTS = new Set([
27
+ 'User', 'Profile', 'PermissionSet', 'PermissionSetAssignment', 'PermissionSetGroup',
28
+ 'PermissionSetGroupComponent', 'PermissionSetLicense', 'PermissionSetLicenseAssign',
29
+ 'UserRole', 'UserLicense', 'UserRecordAccess', 'UserPermissionAccess', 'SetupEntityAccess',
30
+ 'CustomPermission', 'Organization', 'LoginHistory', 'AuthSession', 'AuthProvider',
31
+ 'ThirdPartyAccountLink', 'CronTrigger', 'AsyncApexJob', 'ApexClass', 'ApexTrigger',
32
+ 'ApexEmailNotification', 'AuraDefinitionBundle', 'FlowDefinitionView', 'FlowVersionView',
33
+ 'Group', 'GroupMember', 'QueueSobject', 'ObjectPermissions', 'FieldPermissions',
34
+ 'EntityDefinition', 'FieldDefinition', 'Identifier', 'StaticResource', 'Topic',
35
+ 'TopicAssignment', 'SetupAuditTrail', 'NetworkMemberGroup',
36
+ ]);
37
+ const CONTENT_OBJECTS = new Set([
38
+ 'Attachment', 'Document', 'EmailMessage', 'EmailTemplate', 'Note',
39
+ ]);
40
+ /** Which layer an object belongs to. Unrecognised objects are business, never hidden. */
41
+ export function roleOf(object) {
42
+ if (SECURITY_OBJECTS.has(object))
43
+ return 'security';
44
+ if (/^Logger?[A-Z_]/.test(object) || /^Log(Entry|Status|Retention)/.test(object))
45
+ return 'observability';
46
+ if (object.endsWith('__mdt'))
47
+ return 'configuration';
48
+ if (object.endsWith('__e') || object.endsWith('__x'))
49
+ return 'integration';
50
+ if (/(?:Share|History|Feed|ChangeEvent)$/.test(object))
51
+ return 'sharing';
52
+ if (CONTENT_OBJECTS.has(object) || /^Content[A-Z]/.test(object))
53
+ return 'content';
54
+ return 'business';
55
+ }
56
+ //# sourceMappingURL=roleOf.js.map
@@ -0,0 +1,34 @@
1
+ export declare const GRAPH_RULES: {
2
+ readonly NOT_AN_OBJECT: "GRAPH_NOT_AN_OBJECT";
3
+ readonly SCHEMA_VERSION_UNSUPPORTED: "GRAPH_SCHEMA_VERSION_UNSUPPORTED";
4
+ readonly SCHEMA_SHAPE: "GRAPH_SCHEMA_SHAPE";
5
+ readonly EDGE_MISSING_PROVENANCE: "GRAPH_EDGE_MISSING_PROVENANCE";
6
+ readonly DERIVED_MISSING_RULE: "GRAPH_DERIVED_MISSING_RULE";
7
+ readonly ID_NOT_NAMESPACED: "GRAPH_ID_NOT_NAMESPACED";
8
+ readonly ID_DUPLICATE: "GRAPH_ID_DUPLICATE";
9
+ readonly UNKNOWN_KIND: "GRAPH_UNKNOWN_KIND";
10
+ readonly LEVEL_KIND_MISMATCH: "GRAPH_LEVEL_KIND_MISMATCH";
11
+ readonly LAYER_KIND_MISMATCH: "GRAPH_LAYER_KIND_MISMATCH";
12
+ readonly ROOT_HAS_PARENT: "GRAPH_ROOT_HAS_PARENT";
13
+ readonly PARENT_UNRESOLVED: "GRAPH_PARENT_UNRESOLVED";
14
+ readonly LEVEL_PARENT_ORDER: "GRAPH_LEVEL_PARENT_ORDER";
15
+ readonly PARENT_CYCLE: "GRAPH_PARENT_CYCLE";
16
+ readonly EDGE_ENDPOINT_UNRESOLVED: "GRAPH_EDGE_ENDPOINT_UNRESOLVED";
17
+ readonly MERGE_ORG_MISMATCH: "GRAPH_MERGE_ORG_MISMATCH";
18
+ readonly MERGE_SCHEMA_VERSION_MISMATCH: "GRAPH_MERGE_SCHEMA_VERSION_MISMATCH";
19
+ readonly MERGE_ID_COLLISION: "GRAPH_MERGE_ID_COLLISION";
20
+ readonly MERGE_KIND_NOT_OWNED: "GRAPH_MERGE_KIND_NOT_OWNED";
21
+ readonly MERGE_CONTRIBUTION_UNRESOLVED: "GRAPH_MERGE_CONTRIBUTION_UNRESOLVED";
22
+ readonly MERGE_NO_FRAGMENTS: "GRAPH_MERGE_NO_FRAGMENTS";
23
+ readonly MERGE_CONTRIBUTION_UNATTRIBUTED: "GRAPH_MERGE_CONTRIBUTION_UNATTRIBUTED";
24
+ };
25
+ export type GraphRuleCode = (typeof GRAPH_RULES)[keyof typeof GRAPH_RULES];
26
+ export interface GraphDiagnostic {
27
+ code: GraphRuleCode;
28
+ /** The offending node id, or `from->to` for an edge. `document` for whole-file findings. */
29
+ id: string;
30
+ message: string;
31
+ /** A supported fix. Never empty — a finding a reader cannot act on is a bug report. */
32
+ fix: string;
33
+ }
34
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1,30 @@
1
+ // src/graph/rules.ts
2
+ // Stable rule codes. A code is an API: renaming one is a breaking change for anything that
3
+ // keys off validator output, so treat this table the way you would treat an error enum.
4
+ export const GRAPH_RULES = {
5
+ NOT_AN_OBJECT: 'GRAPH_NOT_AN_OBJECT',
6
+ SCHEMA_VERSION_UNSUPPORTED: 'GRAPH_SCHEMA_VERSION_UNSUPPORTED',
7
+ SCHEMA_SHAPE: 'GRAPH_SCHEMA_SHAPE',
8
+ EDGE_MISSING_PROVENANCE: 'GRAPH_EDGE_MISSING_PROVENANCE',
9
+ DERIVED_MISSING_RULE: 'GRAPH_DERIVED_MISSING_RULE',
10
+ ID_NOT_NAMESPACED: 'GRAPH_ID_NOT_NAMESPACED',
11
+ ID_DUPLICATE: 'GRAPH_ID_DUPLICATE',
12
+ UNKNOWN_KIND: 'GRAPH_UNKNOWN_KIND',
13
+ LEVEL_KIND_MISMATCH: 'GRAPH_LEVEL_KIND_MISMATCH',
14
+ LAYER_KIND_MISMATCH: 'GRAPH_LAYER_KIND_MISMATCH',
15
+ ROOT_HAS_PARENT: 'GRAPH_ROOT_HAS_PARENT',
16
+ PARENT_UNRESOLVED: 'GRAPH_PARENT_UNRESOLVED',
17
+ LEVEL_PARENT_ORDER: 'GRAPH_LEVEL_PARENT_ORDER',
18
+ PARENT_CYCLE: 'GRAPH_PARENT_CYCLE',
19
+ EDGE_ENDPOINT_UNRESOLVED: 'GRAPH_EDGE_ENDPOINT_UNRESOLVED',
20
+ // Merge. Separate codes from the validator's, because a reader acts differently on them: a
21
+ // validation finding is about one document, a merge finding is about two disagreeing.
22
+ MERGE_ORG_MISMATCH: 'GRAPH_MERGE_ORG_MISMATCH',
23
+ MERGE_SCHEMA_VERSION_MISMATCH: 'GRAPH_MERGE_SCHEMA_VERSION_MISMATCH',
24
+ MERGE_ID_COLLISION: 'GRAPH_MERGE_ID_COLLISION',
25
+ MERGE_KIND_NOT_OWNED: 'GRAPH_MERGE_KIND_NOT_OWNED',
26
+ MERGE_CONTRIBUTION_UNRESOLVED: 'GRAPH_MERGE_CONTRIBUTION_UNRESOLVED',
27
+ MERGE_NO_FRAGMENTS: 'GRAPH_MERGE_NO_FRAGMENTS',
28
+ MERGE_CONTRIBUTION_UNATTRIBUTED: 'GRAPH_MERGE_CONTRIBUTION_UNATTRIBUTED',
29
+ };
30
+ //# sourceMappingURL=rules.js.map
@@ -0,0 +1,170 @@
1
+ export declare const GRAPH_SCHEMA: {
2
+ type: string;
3
+ required: string[];
4
+ additionalProperties: boolean;
5
+ properties: {
6
+ schemaVersion: {
7
+ type: string;
8
+ };
9
+ capturedAt: {
10
+ type: string;
11
+ };
12
+ orgId: {
13
+ type: string;
14
+ };
15
+ nodes: {
16
+ type: string;
17
+ items: {
18
+ $ref: string;
19
+ };
20
+ };
21
+ edges: {
22
+ type: string;
23
+ items: {
24
+ $ref: string;
25
+ };
26
+ };
27
+ coverage: {
28
+ $ref: string;
29
+ };
30
+ producer: {
31
+ enum: string[];
32
+ };
33
+ contributions: {
34
+ type: string;
35
+ items: {
36
+ $ref: string;
37
+ };
38
+ };
39
+ };
40
+ $defs: {
41
+ provenance: {
42
+ type: string;
43
+ required: string[];
44
+ additionalProperties: boolean;
45
+ properties: {
46
+ source: {
47
+ enum: string[];
48
+ };
49
+ capturedAt: {
50
+ type: string;
51
+ };
52
+ rule: {
53
+ type: string;
54
+ };
55
+ evidence: {
56
+ type: string;
57
+ };
58
+ observations: {
59
+ type: string;
60
+ };
61
+ };
62
+ };
63
+ node: {
64
+ type: string;
65
+ required: string[];
66
+ additionalProperties: boolean;
67
+ properties: {
68
+ id: {
69
+ type: string;
70
+ minLength: number;
71
+ };
72
+ kind: {
73
+ type: string;
74
+ minLength: number;
75
+ };
76
+ layer: {
77
+ enum: string[];
78
+ };
79
+ level: {
80
+ enum: number[];
81
+ };
82
+ parent: {
83
+ type: string[];
84
+ };
85
+ label: {
86
+ type: string;
87
+ };
88
+ attrs: {
89
+ type: string;
90
+ };
91
+ provenance: {
92
+ $ref: string;
93
+ };
94
+ };
95
+ };
96
+ edge: {
97
+ type: string;
98
+ required: string[];
99
+ additionalProperties: boolean;
100
+ properties: {
101
+ from: {
102
+ type: string;
103
+ minLength: number;
104
+ };
105
+ to: {
106
+ type: string;
107
+ minLength: number;
108
+ };
109
+ kind: {
110
+ type: string;
111
+ minLength: number;
112
+ };
113
+ attrs: {
114
+ type: string;
115
+ };
116
+ provenance: {
117
+ $ref: string;
118
+ };
119
+ };
120
+ };
121
+ contribution: {
122
+ type: string;
123
+ required: string[];
124
+ additionalProperties: boolean;
125
+ properties: {
126
+ nodeId: {
127
+ type: string;
128
+ minLength: number;
129
+ };
130
+ attrs: {
131
+ type: string;
132
+ };
133
+ };
134
+ };
135
+ coverage: {
136
+ type: string;
137
+ required: string[];
138
+ additionalProperties: boolean;
139
+ properties: {
140
+ notes: {
141
+ type: string;
142
+ items: {
143
+ type: string;
144
+ };
145
+ };
146
+ unavailable: {
147
+ type: string;
148
+ items: {
149
+ type: string;
150
+ required: string[];
151
+ additionalProperties: boolean;
152
+ properties: {
153
+ scope: {
154
+ type: string;
155
+ minLength: number;
156
+ };
157
+ reason: {
158
+ enum: string[];
159
+ };
160
+ detail: {
161
+ type: string;
162
+ };
163
+ };
164
+ };
165
+ };
166
+ };
167
+ };
168
+ };
169
+ };
170
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,91 @@
1
+ // src/graph/schema.ts
2
+ // JSON Schema for the document envelope and the shape of nodes and edges. Semantic rules that
3
+ // need cross-referencing between nodes (parents, cycles, endpoints) live in validate.ts, since
4
+ // JSON Schema cannot express them.
5
+ export const GRAPH_SCHEMA = {
6
+ type: 'object',
7
+ required: ['schemaVersion', 'capturedAt', 'orgId', 'nodes', 'edges', 'coverage'],
8
+ additionalProperties: false,
9
+ properties: {
10
+ schemaVersion: { type: 'string' },
11
+ capturedAt: { type: 'string' },
12
+ orgId: { type: 'string' },
13
+ nodes: { type: 'array', items: { $ref: '#/$defs/node' } },
14
+ edges: { type: 'array', items: { $ref: '#/$defs/edge' } },
15
+ coverage: { $ref: '#/$defs/coverage' },
16
+ producer: { enum: ['orgviz', 'orgintel'] },
17
+ contributions: { type: 'array', items: { $ref: '#/$defs/contribution' } },
18
+ },
19
+ $defs: {
20
+ provenance: {
21
+ type: 'object',
22
+ required: ['source', 'capturedAt'],
23
+ additionalProperties: false,
24
+ properties: {
25
+ source: { enum: ['metadata', 'runtime', 'derived'] },
26
+ capturedAt: { type: 'string' },
27
+ rule: { type: 'string' },
28
+ evidence: { type: 'string' },
29
+ observations: { type: 'number' },
30
+ },
31
+ },
32
+ node: {
33
+ type: 'object',
34
+ required: ['id', 'kind', 'layer', 'level', 'parent', 'label', 'attrs', 'provenance'],
35
+ additionalProperties: false,
36
+ properties: {
37
+ id: { type: 'string', minLength: 1 },
38
+ kind: { type: 'string', minLength: 1 },
39
+ layer: { enum: ['landscape', 'domain', 'data', 'process', 'access', 'runtime'] },
40
+ level: { enum: [0, 1, 2, 3] },
41
+ parent: { type: ['string', 'null'] },
42
+ label: { type: 'string' },
43
+ attrs: { type: 'object' },
44
+ provenance: { $ref: '#/$defs/provenance' },
45
+ },
46
+ },
47
+ edge: {
48
+ type: 'object',
49
+ required: ['from', 'to', 'kind', 'attrs', 'provenance'],
50
+ additionalProperties: false,
51
+ properties: {
52
+ from: { type: 'string', minLength: 1 },
53
+ to: { type: 'string', minLength: 1 },
54
+ kind: { type: 'string', minLength: 1 },
55
+ attrs: { type: 'object' },
56
+ provenance: { $ref: '#/$defs/provenance' },
57
+ },
58
+ },
59
+ contribution: {
60
+ type: 'object',
61
+ required: ['nodeId', 'attrs'],
62
+ additionalProperties: false,
63
+ properties: {
64
+ nodeId: { type: 'string', minLength: 1 },
65
+ attrs: { type: 'object' },
66
+ },
67
+ },
68
+ coverage: {
69
+ type: 'object',
70
+ required: ['notes', 'unavailable'],
71
+ additionalProperties: false,
72
+ properties: {
73
+ notes: { type: 'array', items: { type: 'string' } },
74
+ unavailable: {
75
+ type: 'array',
76
+ items: {
77
+ type: 'object',
78
+ required: ['scope', 'reason', 'detail'],
79
+ additionalProperties: false,
80
+ properties: {
81
+ scope: { type: 'string', minLength: 1 },
82
+ reason: { enum: ['deferred', 'failed'] },
83
+ detail: { type: 'string' },
84
+ },
85
+ },
86
+ },
87
+ },
88
+ },
89
+ },
90
+ };
91
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,84 @@
1
+ /** What kind of thing a node is. Independent of `GraphLevel`. Spec section 2. */
2
+ export type GraphLayer = 'landscape' | 'domain' | 'data' | 'process' | 'access' | 'runtime';
3
+ /** How zoomed out a node is. Independent of `GraphLayer`. Spec section 2.2. */
4
+ export type GraphLevel = 0 | 1 | 2 | 3;
5
+ /**
6
+ * Which tool emits this kind. Ownership is per kind rather than per layer because
7
+ * sf-orgintel's anatomy collectors gather landscape-layer facts -- sites, products, personas --
8
+ * that sf-orgviz has no reason to extract. Node ids are `prefix.name`, so disjoint kinds give
9
+ * the disjoint ids the merge needs. See sf-orgviz/docs/CONVERGENCE_SPEC.md section 1.1.
10
+ */
11
+ export type GraphProducer = 'orgviz' | 'orgintel';
12
+ export type GraphProvenanceSource = 'metadata' | 'runtime' | 'derived';
13
+ export interface GraphProvenance {
14
+ source: GraphProvenanceSource;
15
+ capturedAt: string;
16
+ /** Required when `source` is 'derived': names the rule that produced this. Spec section 4. */
17
+ rule?: string;
18
+ /** Evidence handle for runtime facts, e.g. an Event Monitoring finding id. */
19
+ evidence?: string;
20
+ observations?: number;
21
+ }
22
+ export interface GraphNode {
23
+ /** Deterministic and content-derived, namespaced by kind: `obj.Account`. Never an index. */
24
+ id: string;
25
+ kind: string;
26
+ layer: GraphLayer;
27
+ level: GraphLevel;
28
+ /** Null at level 0. Above it, null means extracted but not yet grouped. Spec section 2.3. */
29
+ parent: string | null;
30
+ label: string;
31
+ attrs: Record<string, unknown>;
32
+ provenance: GraphProvenance;
33
+ }
34
+ export interface GraphEdge {
35
+ from: string;
36
+ to: string;
37
+ kind: string;
38
+ attrs: Record<string, unknown>;
39
+ provenance: GraphProvenance;
40
+ }
41
+ /** Why part of the org is absent from the document. `deferred` was never attempted. */
42
+ export interface GraphUnavailable {
43
+ /** Stable dotted key naming what is missing, e.g. `landscape.connectedApps`. */
44
+ scope: string;
45
+ reason: 'deferred' | 'failed';
46
+ detail: string;
47
+ }
48
+ /**
49
+ * What could not be gathered. Absence is data: a diagram that silently omits a layer nobody was
50
+ * allowed to read is a lie, and `notes` alone is prose a consumer cannot key off.
51
+ */
52
+ export interface GraphCoverage {
53
+ notes: string[];
54
+ unavailable: GraphUnavailable[];
55
+ }
56
+ /**
57
+ * A measurement about a node another producer owns. `recordCount90d` on an `obj.*` node is the
58
+ * case that forced this: it is a fact about a node sf-orgviz owns, measured by sf-orgintel,
59
+ * which has no other reason to emit that node. Applied under the contributor's namespace, never
60
+ * merged into `attrs` directly. See sf-orgviz/docs/CONVERGENCE_SPEC.md section 3.3.
61
+ */
62
+ export interface AttributeContribution {
63
+ nodeId: string;
64
+ attrs: Record<string, unknown>;
65
+ }
66
+ export interface CanonicalGraph {
67
+ schemaVersion: string;
68
+ capturedAt: string;
69
+ orgId: string;
70
+ nodes: GraphNode[];
71
+ edges: GraphEdge[];
72
+ coverage: GraphCoverage;
73
+ /** Which tool wrote this fragment. Absent on a merged graph, which has no single producer. */
74
+ producer?: GraphProducer;
75
+ contributions?: AttributeContribution[];
76
+ }
77
+ /**
78
+ * 1.2.0 since `producer` and `contributions` were added, both optional. The 1.0.0 schema set
79
+ * additionalProperties:false, so a 1.1.0 reader rejects a 1.2.0 document — breaking under
80
+ * GRAPH_EXPORT_SPEC section 3, hence the exact-equality check and the bump. No documents exist
81
+ * outside this repo's fixtures (sf-orgviz is unpublished), so the migration is the fixture edit.
82
+ */
83
+ export declare const SUPPORTED_GRAPH_SCHEMA_VERSION = "1.2.0";
84
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,10 @@
1
+ // src/graph/types.ts
2
+ // The canonical graph. Layers are projections over this document; there is no second model.
3
+ /**
4
+ * 1.2.0 since `producer` and `contributions` were added, both optional. The 1.0.0 schema set
5
+ * additionalProperties:false, so a 1.1.0 reader rejects a 1.2.0 document — breaking under
6
+ * GRAPH_EXPORT_SPEC section 3, hence the exact-equality check and the bump. No documents exist
7
+ * outside this repo's fixtures (sf-orgviz is unpublished), so the migration is the fixture edit.
8
+ */
9
+ export const SUPPORTED_GRAPH_SCHEMA_VERSION = '1.2.0';
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,8 @@
1
+ import { type GraphDiagnostic } from './rules.js';
2
+ /** Edge identity used in findings, so a reader can locate the offending edge in the file. */
3
+ export declare function graphEdgeId(e: {
4
+ from: string;
5
+ to: string;
6
+ }): string;
7
+ export declare function validateGraph(doc: unknown): GraphDiagnostic[];
8
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1,203 @@
1
+ // src/graph/validate.ts
2
+ // Runs before any renderer touches a document. Returns findings; never throws, never renders
3
+ // partially. Spec section 5.
4
+ import { Ajv } from 'ajv';
5
+ import { GRAPH_SCHEMA } from './schema.js';
6
+ import { GRAPH_RULES } from './rules.js';
7
+ import { SUPPORTED_GRAPH_SCHEMA_VERSION } from './types.js';
8
+ import { isKnownGraphKind, levelOfKind, layerOfKind } from './kinds.js';
9
+ import { codepointCompare } from '../lib/order.js';
10
+ // ajv exports the class as a named export alongside the default, and the named one is what
11
+ // survives the CommonJS-to-NodeNext boundary as a constructable value.
12
+ // `allErrors: true` is deliberate, and the risk Semgrep's ajv-allerrors-true rule guards against
13
+ // does not reach it. That rule is about unbounded error allocation: a schema containing `anyOf`,
14
+ // `oneOf`, `allOf`, `not` or `patternProperties` can make an attacker's input produce errors
15
+ // combinatorially. GRAPH_SCHEMA contains none of those keywords, its six `$ref`s point at flat
16
+ // non-recursive `$defs`, and the schema is a constant in this package — only the document varies,
17
+ // so error count is bounded linearly by the document's own size.
18
+ //
19
+ // It is also load-bearing. This validator's contract is that one run reports every problem with
20
+ // its rule code, the offending id and a fix, so an operator repairs a graph in one pass. Stopping
21
+ // at the first error would report one problem per run against documents that routinely carry
22
+ // thousands of nodes.
23
+ // nosemgrep: javascript.ajv.security.audit.ajv-allerrors-true
24
+ const ajv = new Ajv({ allErrors: true, strict: false });
25
+ const validateShape = ajv.compile(GRAPH_SCHEMA);
26
+ /** Edge identity used in findings, so a reader can locate the offending edge in the file. */
27
+ export function graphEdgeId(e) {
28
+ return `${e.from}->${e.to}`;
29
+ }
30
+ export function validateGraph(doc) {
31
+ if (typeof doc !== 'object' || doc === null || Array.isArray(doc)) {
32
+ return [
33
+ {
34
+ code: GRAPH_RULES.NOT_AN_OBJECT,
35
+ id: 'document',
36
+ message: 'The graph document is not a JSON object.',
37
+ fix: 'Pass the path to a canonical graph document written by this tool.',
38
+ },
39
+ ];
40
+ }
41
+ const candidate = doc;
42
+ if (candidate.schemaVersion !== SUPPORTED_GRAPH_SCHEMA_VERSION) {
43
+ // Loud, not partial: a document from another schema version is not partially loadable,
44
+ // because the fields that changed are exactly the ones a reader would misread.
45
+ return [
46
+ {
47
+ code: GRAPH_RULES.SCHEMA_VERSION_UNSUPPORTED,
48
+ id: 'document',
49
+ message: `schemaVersion is ${String(candidate.schemaVersion)}; this build supports ` +
50
+ `${SUPPORTED_GRAPH_SCHEMA_VERSION}.`,
51
+ // Re-extraction is the only remedy, so it is the only one offered. This previously also
52
+ // promised a migration, which was never written -- and the promise went unnoticed because
53
+ // the finding was unreachable until the schema version first moved.
54
+ fix: `Re-extract the graph with a build that writes ${SUPPORTED_GRAPH_SCHEMA_VERSION}. There is no in-place migration between schema versions.`,
55
+ },
56
+ ];
57
+ }
58
+ if (!validateShape(doc)) {
59
+ // A missing edge provenance is reported under its own code rather than as a generic shape
60
+ // error, because it is the one shape failure that has a specific remedy and because
61
+ // consumers key off the code.
62
+ const g = doc;
63
+ const provenanceFindings = (g.edges ?? [])
64
+ .filter((e) => e !== null && typeof e === 'object' && e.provenance === undefined)
65
+ .map((e) => ({
66
+ code: GRAPH_RULES.EDGE_MISSING_PROVENANCE,
67
+ id: graphEdgeId({ from: String(e.from), to: String(e.to) }),
68
+ message: 'Edge carries no provenance.',
69
+ fix: "Add provenance with source 'metadata', 'runtime' or 'derived'.",
70
+ }));
71
+ if (provenanceFindings.length > 0)
72
+ return provenanceFindings;
73
+ return (validateShape.errors ?? []).map((e) => ({
74
+ code: GRAPH_RULES.SCHEMA_SHAPE,
75
+ id: e.instancePath || 'document',
76
+ message: `${e.instancePath || 'document'} ${e.message ?? 'failed schema validation'}.`,
77
+ fix: 'Correct the field named in the path so it matches the documented shape.',
78
+ }));
79
+ }
80
+ // ajv's compiled function is a type guard, so `doc` is narrowed to its own inferred shape
81
+ // here rather than to ours. The double assertion is deliberate: the schema is what makes the
82
+ // claim true, and it has just run.
83
+ const graph = doc;
84
+ return semanticFindings(graph);
85
+ }
86
+ /**
87
+ * Cross-referencing rules JSON Schema cannot express. Findings are accumulated rather than
88
+ * short-circuited: a reader fixing a document wants the whole list, not one error per run.
89
+ * Sorted by id then code so two runs over the same document report identically.
90
+ */
91
+ function semanticFindings(graph) {
92
+ const findings = [];
93
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
94
+ const seen = new Set();
95
+ for (const n of graph.nodes) {
96
+ if (seen.has(n.id)) {
97
+ findings.push({
98
+ code: GRAPH_RULES.ID_DUPLICATE, id: n.id,
99
+ message: `Duplicate node id ${n.id}.`,
100
+ fix: 'Node ids are content-derived and unique. Two nodes derived the same id — namespace them by kind.',
101
+ });
102
+ }
103
+ seen.add(n.id);
104
+ if (!n.id.includes('.')) {
105
+ findings.push({
106
+ code: GRAPH_RULES.ID_NOT_NAMESPACED, id: n.id,
107
+ message: `Node id ${n.id} is not namespaced by kind.`,
108
+ fix: 'Prefix the id with its kind namespace, for example obj.Account or permset.Sales_Ops.',
109
+ });
110
+ }
111
+ if (!isKnownGraphKind(n.kind)) {
112
+ findings.push({
113
+ code: GRAPH_RULES.UNKNOWN_KIND, id: n.id,
114
+ message: `Unknown kind ${n.kind}.`,
115
+ fix: 'Add the kind to GRAPH_KIND_TABLE in src/graph/kinds.ts with its layer and level, or correct the node.',
116
+ });
117
+ }
118
+ else {
119
+ if (n.level !== levelOfKind(n.kind)) {
120
+ findings.push({
121
+ code: GRAPH_RULES.LEVEL_KIND_MISMATCH, id: n.id,
122
+ message: `Node ${n.id} stores level ${n.level}; kind ${n.kind} is level ${levelOfKind(n.kind)}.`,
123
+ fix: `Set level to ${levelOfKind(n.kind)}. Level is a pure function of kind; the stored value is a convenience copy.`,
124
+ });
125
+ }
126
+ if (n.layer !== layerOfKind(n.kind)) {
127
+ findings.push({
128
+ code: GRAPH_RULES.LAYER_KIND_MISMATCH, id: n.id,
129
+ message: `Node ${n.id} stores layer ${n.layer}; kind ${n.kind} is layer ${layerOfKind(n.kind)}.`,
130
+ fix: `Set layer to ${layerOfKind(n.kind)}.`,
131
+ });
132
+ }
133
+ }
134
+ if (n.level === 0 && n.parent !== null) {
135
+ findings.push({
136
+ code: GRAPH_RULES.ROOT_HAS_PARENT, id: n.id,
137
+ message: `Level 0 node ${n.id} carries a parent.`,
138
+ fix: 'Set parent to null. Level 0 is the root of the containment tree.',
139
+ });
140
+ }
141
+ // A null parent above level 0 is deliberately not a finding. It means extracted but not
142
+ // grouped, and the selector reports it as unattributed. Spec section 2.3.
143
+ if (n.parent !== null) {
144
+ const parent = byId.get(n.parent);
145
+ if (!parent) {
146
+ findings.push({
147
+ code: GRAPH_RULES.PARENT_UNRESOLVED, id: n.id,
148
+ message: `Parent ${n.parent} of ${n.id} is not in the document.`,
149
+ fix: 'Add the parent node, or set parent to null to report this node as unattributed.',
150
+ });
151
+ }
152
+ else if (parent.level >= n.level) {
153
+ findings.push({
154
+ code: GRAPH_RULES.LEVEL_PARENT_ORDER, id: n.id,
155
+ message: `Parent ${parent.id} is level ${parent.level}; child ${n.id} is level ${n.level}.`,
156
+ fix: 'A parent must sit at a strictly lower level than its child.',
157
+ });
158
+ }
159
+ }
160
+ }
161
+ for (const n of graph.nodes) {
162
+ if (inCycle(n.id, byId)) {
163
+ findings.push({
164
+ code: GRAPH_RULES.PARENT_CYCLE, id: n.id,
165
+ message: `Node ${n.id} is part of a parent cycle.`,
166
+ fix: 'Break the cycle: containment must be a tree rooted at a level 0 node.',
167
+ });
168
+ }
169
+ }
170
+ for (const e of graph.edges) {
171
+ const id = graphEdgeId(e);
172
+ if (e.provenance.source === 'derived' && !e.provenance.rule) {
173
+ findings.push({
174
+ code: GRAPH_RULES.DERIVED_MISSING_RULE, id,
175
+ message: 'Derived edge does not name the rule that produced it.',
176
+ fix: 'Set provenance.rule to the identifier of the aggregation rule.',
177
+ });
178
+ }
179
+ for (const endpoint of [e.from, e.to]) {
180
+ if (!byId.has(endpoint)) {
181
+ findings.push({
182
+ code: GRAPH_RULES.EDGE_ENDPOINT_UNRESOLVED, id,
183
+ message: `Edge endpoint ${endpoint} is not in the document.`,
184
+ fix: 'Add the missing node, or remove the edge.',
185
+ });
186
+ }
187
+ }
188
+ }
189
+ return findings.sort((a, b) => codepointCompare(a.id, b.id) || codepointCompare(a.code, b.code));
190
+ }
191
+ /** Walks the parent chain with a visited set, so a cycle terminates instead of hanging. */
192
+ function inCycle(start, byId) {
193
+ const visited = new Set();
194
+ let current = start;
195
+ while (current !== null) {
196
+ if (visited.has(current))
197
+ return true;
198
+ visited.add(current);
199
+ current = byId.get(current)?.parent ?? null;
200
+ }
201
+ return false;
202
+ }
203
+ //# sourceMappingURL=validate.js.map
package/lib/index.d.ts CHANGED
@@ -26,4 +26,5 @@ export type { RiskLevel } from './findings/RiskLevel.js';
26
26
  export { RISK_LEVELS } from './findings/RiskLevel.js';
27
27
  export * from './platform/index.js';
28
28
  export * from './schemas/index.js';
29
+ export * from './graph/index.js';
29
30
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -19,4 +19,8 @@ export { RISK_LEVELS } from './findings/RiskLevel.js';
19
19
  export * from './platform/index.js';
20
20
  // --- IR schemas (typed contracts + JSON schema access) ---
21
21
  export * from './schemas/index.js';
22
+ // The canonical org graph. Owned here rather than in sf-orgviz so that sf-orgviz and
23
+ // sf-orgintel can both produce fragments of one schema without either depending on the other.
24
+ // See sf-orgviz/docs/CONVERGENCE_SPEC.md section 1.2.
25
+ export * from './graph/index.js';
22
26
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export declare function codepointCompare(a: string, b: string): number;
2
+ //# sourceMappingURL=order.d.ts.map
@@ -0,0 +1,10 @@
1
+ // src/lib/order.ts
2
+ // The one comparator every path that produces output bytes must use. Spec section 12 requires
3
+ // same input -> identical output, byte for byte, across runs and machines. `String.prototype
4
+ // .localeCompare()` with no locale argument resolves against the runtime's ICU and the `LANG`
5
+ // environment variable, so it can reorder output between two machines -- or two Node builds --
6
+ // that never disagree about anything else. Plain codepoint order has no such dependency.
7
+ export function codepointCompare(a, b) {
8
+ return a < b ? -1 : a > b ? 1 : 0;
9
+ }
10
+ //# sourceMappingURL=order.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-core",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Shared platform layer for CloudCounsel Salesforce sf plugins — API clients, org context, event log pull, report shell, and versioned IR schemas.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -31,7 +31,6 @@
31
31
  "@salesforce/core": "^9",
32
32
  "@types/jest": "^29",
33
33
  "@types/node": "^22",
34
- "ajv": "^8",
35
34
  "jest": "^29",
36
35
  "oxlint": "^1.79.0",
37
36
  "ts-jest": "^29",
@@ -82,5 +81,8 @@
82
81
  },
83
82
  "peerDependencies": {
84
83
  "@salesforce/core": "^8 || ^9"
84
+ },
85
+ "dependencies": {
86
+ "ajv": "^8.20.0"
85
87
  }
86
88
  }