@principal-ai/principal-view-core 0.27.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,243 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { OtelEventPathsValidator } from './OtelEventPathsValidator';
3
+ import type { ExtendedCanvas } from '../types/canvas';
4
+
5
+ function namespaceNode(name: string, opts: { paths?: string[] } = {}): any {
6
+ return {
7
+ id: `ns-${name}`,
8
+ type: 'event-namespace',
9
+ x: 0,
10
+ y: 0,
11
+ width: 100,
12
+ height: 100,
13
+ namespace: {
14
+ name,
15
+ description: `${name} description`,
16
+ paths: opts.paths,
17
+ events: [],
18
+ },
19
+ };
20
+ }
21
+
22
+ function eventNode(
23
+ id: string,
24
+ eventName: string,
25
+ scope: string,
26
+ files: string[] | undefined,
27
+ ): any {
28
+ return {
29
+ id,
30
+ type: 'otel-event',
31
+ x: 0,
32
+ y: 0,
33
+ width: 100,
34
+ height: 100,
35
+ label: eventName,
36
+ event: { name: eventName, attributes: {} },
37
+ otel: { scope, files },
38
+ };
39
+ }
40
+
41
+ function canvas(nodes: any[]): ExtendedCanvas {
42
+ return { nodes, edges: [] } as unknown as ExtendedCanvas;
43
+ }
44
+
45
+ function validate(input: {
46
+ events: Array<{ scope: string; nodes: any[] }>;
47
+ otel: any[][];
48
+ }) {
49
+ const validator = new OtelEventPathsValidator();
50
+ return validator.validate({
51
+ eventsCanvases: input.events.map((e, i) => ({
52
+ canvas: canvas(e.nodes),
53
+ canvasPath: `scope-${i}.events.canvas`,
54
+ scope: e.scope,
55
+ })),
56
+ otelCanvases: input.otel.map((nodes, i) => ({
57
+ canvas: canvas(nodes),
58
+ canvasPath: `otel-${i}.otel.canvas`,
59
+ })),
60
+ });
61
+ }
62
+
63
+ function rules(result: { violations: Array<{ ruleId: string }> }, ruleId: string) {
64
+ return result.violations.filter((v) => v.ruleId === ruleId);
65
+ }
66
+
67
+ describe('OtelEventPathsValidator', () => {
68
+ test('empty input produces no violations', () => {
69
+ const result = validate({ events: [], otel: [] });
70
+ expect(result.violations).toHaveLength(0);
71
+ expect(result.valid).toBe(true);
72
+ });
73
+
74
+ test('skips events whose namespace has no paths declared (opt-in)', () => {
75
+ const result = validate({
76
+ events: [{ scope: 's', nodes: [namespaceNode('events')] }], // no paths
77
+ otel: [[eventNode('e1', 'events.happened', 's', ['src/somewhere/else.ts'])]],
78
+ });
79
+ expect(result.violations).toHaveLength(0);
80
+ expect(result.metrics.eventsSkippedNoPaths).toBe(1);
81
+ expect(result.metrics.eventsChecked).toBe(0);
82
+ });
83
+
84
+ test('file covered by the event’s namespace: no violation', () => {
85
+ const result = validate({
86
+ events: [
87
+ {
88
+ scope: 's',
89
+ nodes: [namespaceNode('events', { paths: ['src/events'] })],
90
+ },
91
+ ],
92
+ otel: [[eventNode('e1', 'events.happened', 's', ['src/events/foo.ts'])]],
93
+ });
94
+ expect(result.violations).toHaveLength(0);
95
+ expect(result.metrics.eventsChecked).toBe(1);
96
+ expect(result.metrics.filesChecked).toBe(1);
97
+ });
98
+
99
+ test('file covered by a different namespace: wrong-namespace error', () => {
100
+ const result = validate({
101
+ events: [
102
+ {
103
+ scope: 's',
104
+ nodes: [
105
+ namespaceNode('validation', { paths: ['src/validation'] }),
106
+ namespaceNode('middleware', { paths: ['src/middleware'] }),
107
+ ],
108
+ },
109
+ ],
110
+ otel: [
111
+ [eventNode('e1', 'validation.started', 's', ['src/middleware/auth.ts'])],
112
+ ],
113
+ });
114
+
115
+ const wrong = rules(result, 'events-otel-files-wrong-namespace');
116
+ expect(wrong).toHaveLength(1);
117
+ expect(wrong[0].severity).toBe('error');
118
+ expect(wrong[0].message).toContain('middleware');
119
+ expect(wrong[0].message).toContain('validation.started');
120
+ expect(result.valid).toBe(false);
121
+ });
122
+
123
+ test('file in no namespace: orphan warning', () => {
124
+ const result = validate({
125
+ events: [
126
+ {
127
+ scope: 's',
128
+ nodes: [namespaceNode('events', { paths: ['src/events'] })],
129
+ },
130
+ ],
131
+ otel: [
132
+ [eventNode('e1', 'events.happened', 's', ['src/nowhere/foo.ts'])],
133
+ ],
134
+ });
135
+
136
+ const orphan = rules(result, 'events-otel-files-orphan');
137
+ expect(orphan).toHaveLength(1);
138
+ expect(orphan[0].severity).toBe('warn');
139
+ expect(orphan[0].message).toContain('src/nowhere/foo.ts');
140
+ expect(result.valid).toBe(true); // only warnings
141
+ });
142
+
143
+ test('parent-child partition: event on parent using child-owned file is flagged', () => {
144
+ const result = validate({
145
+ events: [
146
+ {
147
+ scope: 's',
148
+ nodes: [
149
+ namespaceNode('workflow', { paths: ['src/workflow'] }),
150
+ namespaceNode('workflow.scenarios', { paths: ['src/workflow/scenarios'] }),
151
+ ],
152
+ },
153
+ ],
154
+ otel: [
155
+ // "workflow.started" declared with a file under workflow.scenarios/
156
+ [eventNode('e1', 'workflow.started', 's', ['src/workflow/scenarios/matcher.ts'])],
157
+ ],
158
+ });
159
+
160
+ const wrong = rules(result, 'events-otel-files-wrong-namespace');
161
+ expect(wrong).toHaveLength(1);
162
+ expect(wrong[0].message).toContain('workflow.scenarios');
163
+ });
164
+
165
+ test('parent-child partition: event on child using child-owned file is OK', () => {
166
+ const result = validate({
167
+ events: [
168
+ {
169
+ scope: 's',
170
+ nodes: [
171
+ namespaceNode('workflow', { paths: ['src/workflow'] }),
172
+ namespaceNode('workflow.scenarios', { paths: ['src/workflow/scenarios'] }),
173
+ ],
174
+ },
175
+ ],
176
+ otel: [
177
+ [eventNode('e1', 'workflow.scenarios.matched', 's', ['src/workflow/scenarios/m.ts'])],
178
+ ],
179
+ });
180
+ expect(result.violations).toHaveLength(0);
181
+ });
182
+
183
+ test('scope isolation: namespace paths from scope A do not claim files for scope B events', () => {
184
+ const result = validate({
185
+ events: [
186
+ {
187
+ scope: 'A',
188
+ nodes: [namespaceNode('events', { paths: ['src/events'] })],
189
+ },
190
+ // Scope B has no paths declared at all
191
+ {
192
+ scope: 'B',
193
+ nodes: [namespaceNode('events')],
194
+ },
195
+ ],
196
+ otel: [
197
+ // Event in scope B with a file that WOULD be covered in scope A.
198
+ // Since scope B namespace has no paths → skipped (opt-in).
199
+ [eventNode('e1', 'events.happened', 'B', ['src/events/foo.ts'])],
200
+ ],
201
+ });
202
+
203
+ expect(result.violations).toHaveLength(0);
204
+ expect(result.metrics.eventsSkippedNoPaths).toBe(1);
205
+ });
206
+
207
+ test('events with no scope or no files are skipped', () => {
208
+ const result = validate({
209
+ events: [
210
+ { scope: 's', nodes: [namespaceNode('events', { paths: ['src/events'] })] },
211
+ ],
212
+ otel: [
213
+ [
214
+ eventNode('no-scope', 'events.happened', '', ['src/nowhere.ts']),
215
+ eventNode('no-files', 'events.happened', 's', undefined),
216
+ ],
217
+ ],
218
+ });
219
+ expect(result.violations).toHaveLength(0);
220
+ expect(result.metrics.eventsChecked).toBe(0);
221
+ // The "no-files" event is counted in eventsSkippedNoFiles;
222
+ // the "no-scope" event is skipped silently before namespace resolution.
223
+ expect(result.metrics.eventsSkippedNoFiles).toBe(1);
224
+ });
225
+
226
+ test('multiple otel canvases are all checked', () => {
227
+ const result = validate({
228
+ events: [
229
+ {
230
+ scope: 's',
231
+ nodes: [namespaceNode('events', { paths: ['src/events'] })],
232
+ },
233
+ ],
234
+ otel: [
235
+ [eventNode('e1', 'events.one', 's', ['src/events/ok.ts'])],
236
+ [eventNode('e2', 'events.two', 's', ['src/other/bad.ts'])],
237
+ ],
238
+ });
239
+
240
+ expect(rules(result, 'events-otel-files-orphan')).toHaveLength(1);
241
+ expect(result.metrics.filesChecked).toBe(2);
242
+ });
243
+ });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * OTEL Event Paths Validator (Phase 2)
3
+ *
4
+ * Cross-canvas static check. For every `otel-event` node in an OTEL canvas,
5
+ * cross-reference each entry in `otel.files` against the `paths` declared on
6
+ * the event's namespace in the corresponding events canvas.
7
+ *
8
+ * Enforcement is opt-in per namespace: a namespace without `paths` (or a
9
+ * namespace not declared at all) produces no violations for its events.
10
+ *
11
+ * Pure/browser-safe — no filesystem access.
12
+ */
13
+
14
+ import type { ExtendedCanvas, OtelEventNode } from '../types/canvas';
15
+ import { isOtelEventNode } from '../types/canvas';
16
+ import { NamespacePathIndex, type NamespacePathEntry } from './NamespacePathIndex';
17
+
18
+ /**
19
+ * One events canvas, pre-paired with the scope it owns. Scope pairing is
20
+ * typically derived via the existing scope → filename convention
21
+ * (e.g., scope `principal-view.cli` owns `principal-view-cli.events.canvas`).
22
+ */
23
+ export interface EventsCanvasInput {
24
+ canvas: ExtendedCanvas;
25
+ canvasPath: string;
26
+ scope: string;
27
+ }
28
+
29
+ /**
30
+ * One OTEL canvas whose `otel-event` nodes we want to cross-check.
31
+ */
32
+ export interface OtelCanvasInput {
33
+ canvas: ExtendedCanvas;
34
+ canvasPath: string;
35
+ }
36
+
37
+ export interface OtelEventPathsValidationContext {
38
+ eventsCanvases: EventsCanvasInput[];
39
+ otelCanvases: OtelCanvasInput[];
40
+ }
41
+
42
+ export type OtelEventPathsRuleId =
43
+ | 'events-otel-files-wrong-namespace'
44
+ | 'events-otel-files-orphan';
45
+
46
+ export interface OtelEventPathsViolation {
47
+ ruleId: OtelEventPathsRuleId;
48
+ severity: 'error' | 'warn';
49
+ file: string;
50
+ path?: string;
51
+ message: string;
52
+ impact: string;
53
+ suggestion: string;
54
+ }
55
+
56
+ export interface OtelEventPathsValidationResult {
57
+ valid: boolean;
58
+ violations: OtelEventPathsViolation[];
59
+ metrics: {
60
+ /** Events whose files were cross-checked against namespace paths. */
61
+ eventsChecked: number;
62
+ /** Total files examined across all checked events. */
63
+ filesChecked: number;
64
+ /**
65
+ * Events skipped because the event's namespace has no `paths` declared
66
+ * (or is not declared at all) — enforcement is opt-in per namespace.
67
+ */
68
+ eventsSkippedNoPaths: number;
69
+ /**
70
+ * Events skipped because the `otel-event` node declares no `otel.files`.
71
+ * These events have no claimed implementation location to cross-check.
72
+ */
73
+ eventsSkippedNoFiles: number;
74
+ };
75
+ }
76
+
77
+ export class OtelEventPathsValidator {
78
+ /**
79
+ * Build a path index from the events canvases, keyed by scope.
80
+ * Only namespaces that declare `paths` contribute entries.
81
+ */
82
+ private buildIndex(eventsCanvases: EventsCanvasInput[]): NamespacePathIndex {
83
+ const index = new NamespacePathIndex();
84
+ for (const ec of eventsCanvases) {
85
+ for (const node of ec.canvas.nodes || []) {
86
+ if ((node as any)?.type !== 'event-namespace') continue;
87
+ const ns = (node as any).namespace;
88
+ if (!ns || typeof ns.name !== 'string') continue;
89
+ if (!Array.isArray(ns.paths) || ns.paths.length === 0) continue;
90
+
91
+ const entry: NamespacePathEntry = {
92
+ scope: ec.scope,
93
+ namespace: ns.name,
94
+ paths: ns.paths,
95
+ sourceCanvasPath: ec.canvasPath,
96
+ };
97
+ index.add(entry);
98
+ }
99
+ }
100
+ return index;
101
+ }
102
+
103
+ /** Extract the namespace from an event name (all segments except the last). */
104
+ private extractNamespace(eventName: string): string | null {
105
+ const segments = eventName.split('.');
106
+ if (segments.length < 2) return null;
107
+ return segments.slice(0, -1).join('.');
108
+ }
109
+
110
+ validate(context: OtelEventPathsValidationContext): OtelEventPathsValidationResult {
111
+ const violations: OtelEventPathsViolation[] = [];
112
+ const metrics = {
113
+ eventsChecked: 0,
114
+ filesChecked: 0,
115
+ eventsSkippedNoPaths: 0,
116
+ eventsSkippedNoFiles: 0,
117
+ };
118
+
119
+ const index = this.buildIndex(context.eventsCanvases);
120
+
121
+ for (const oc of context.otelCanvases) {
122
+ for (const node of oc.canvas.nodes || []) {
123
+ if (!isOtelEventNode(node as any)) continue;
124
+ const eventNode = node as OtelEventNode;
125
+ const eventName = eventNode.event?.name;
126
+ const scope = eventNode.otel?.scope;
127
+ const files = eventNode.otel?.files;
128
+
129
+ if (!eventName || !scope) continue; // malformed — other validators catch this
130
+
131
+ const namespace = this.extractNamespace(eventName);
132
+ if (!namespace) continue; // invalid event name — caught by other validators
133
+
134
+ if (!files || files.length === 0) {
135
+ metrics.eventsSkippedNoFiles++;
136
+ continue;
137
+ }
138
+
139
+ // Enforcement is opt-in: if the event's namespace has no declared
140
+ // paths (or isn't declared at all), we don't check its files.
141
+ const eventEntry = index.getEntry(scope, namespace);
142
+ if (!eventEntry) {
143
+ metrics.eventsSkippedNoPaths++;
144
+ continue;
145
+ }
146
+
147
+ metrics.eventsChecked++;
148
+
149
+ for (const file of files) {
150
+ metrics.filesChecked++;
151
+
152
+ const match = index.resolve(scope, file);
153
+ if (match === null) {
154
+ violations.push({
155
+ ruleId: 'events-otel-files-orphan',
156
+ severity: 'warn',
157
+ file: oc.canvasPath,
158
+ path: `nodes[id="${eventNode.id}"].otel.files["${file}"]`,
159
+ message: `Event "${eventName}" declares file "${file}" which is not covered by any namespace's paths in scope "${scope}"`,
160
+ impact: 'The file emits an event but has no declared component home, so its location cannot be validated against namespace conventions.',
161
+ suggestion: `Either add "${file}" (or an ancestor folder) to the "paths" of the "${namespace}" namespace in the events canvas, or move the implementation into one of the namespace's declared paths: ${eventEntry.paths.map((p) => `"${p}"`).join(', ')}.`,
162
+ });
163
+ continue;
164
+ }
165
+
166
+ if (match.entry.namespace === namespace) {
167
+ // File belongs to the event's namespace (longest-prefix match).
168
+ continue;
169
+ }
170
+
171
+ violations.push({
172
+ ruleId: 'events-otel-files-wrong-namespace',
173
+ severity: 'error',
174
+ file: oc.canvasPath,
175
+ path: `nodes[id="${eventNode.id}"].otel.files["${file}"]`,
176
+ message: `Event "${eventName}" declares file "${file}", but namespace "${match.entry.namespace}" (path "${match.matchedPath}") owns that location — not "${namespace}"`,
177
+ impact: 'Event identity disagrees with code location. Consumers discovering the event by name will land in a folder that belongs to a different namespace.',
178
+ suggestion: `Either rename the event to start with "${match.entry.namespace}." (if the code placement is correct), or move the implementation into one of the "${namespace}" namespace's declared paths (${eventEntry.paths.map((p) => `"${p}"`).join(', ')}).`,
179
+ });
180
+ }
181
+ }
182
+ }
183
+
184
+ const errors = violations.filter((v) => v.severity === 'error');
185
+ return {
186
+ valid: errors.length === 0,
187
+ violations,
188
+ metrics,
189
+ };
190
+ }
191
+ }
@@ -12,3 +12,16 @@ export type {
12
12
  ScopeEventsViolation,
13
13
  ScopeEventsValidationResult,
14
14
  } from './ScopeEventsValidator';
15
+
16
+ export { NamespacePathIndex } from './NamespacePathIndex';
17
+ export type { NamespacePathEntry, NamespacePathMatch } from './NamespacePathIndex';
18
+
19
+ export { OtelEventPathsValidator } from './OtelEventPathsValidator';
20
+ export type {
21
+ OtelEventPathsValidationContext,
22
+ OtelEventPathsValidationResult,
23
+ OtelEventPathsViolation,
24
+ OtelEventPathsRuleId,
25
+ EventsCanvasInput,
26
+ OtelCanvasInput,
27
+ } from './OtelEventPathsValidator';
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Path helpers shared across events-canvas validators.
3
+ *
4
+ * Paths declared in canvases (namespace `paths`, `otel.files`, etc.) are
5
+ * always repo-relative. These helpers give a consistent notion of
6
+ * canonicalization and prefix-based containment so that separate validators
7
+ * don't drift.
8
+ */
9
+
10
+ /**
11
+ * Canonicalize a declared path for comparison.
12
+ * Strips leading `./`, trailing slashes, and collapses duplicate slashes.
13
+ */
14
+ export function normalizePath(p: string): string {
15
+ return p
16
+ .replace(/^\.\//, '')
17
+ .replace(/\/+$/, '')
18
+ .replace(/\/+/g, '/');
19
+ }
20
+
21
+ /**
22
+ * True when `child` is strictly nested under `parent` (not equal).
23
+ * Both inputs should already be normalized.
24
+ */
25
+ export function isPathDescendant(child: string, parent: string): boolean {
26
+ return child.startsWith(parent + '/');
27
+ }
28
+
29
+ /**
30
+ * True when `filepath` is covered by `declaredPath` — either equal to it
31
+ * (file match) or nested under it (folder match). Inputs are normalized
32
+ * internally so callers can pass raw canvas values.
33
+ */
34
+ export function pathCovers(declaredPath: string, filepath: string): boolean {
35
+ const d = normalizePath(declaredPath);
36
+ const f = normalizePath(filepath);
37
+ return d === f || isPathDescendant(f, d);
38
+ }
39
+
40
+ /**
41
+ * Classify the relationship between two declared paths.
42
+ * - 'none': disjoint — no overlap
43
+ * - 'partition': one is strictly a parent of the other — valid nested-namespace case
44
+ * (longest-prefix wins at runtime, parent/child partition the tree)
45
+ * - 'conflict': identical, or overlap that isn't a clean parent-child partition
46
+ */
47
+ export function pathsOverlap(a: string, b: string): 'none' | 'partition' | 'conflict' {
48
+ const na = normalizePath(a);
49
+ const nb = normalizePath(b);
50
+ if (na === nb) return 'conflict';
51
+ if (isPathDescendant(na, nb) || isPathDescendant(nb, na)) return 'partition';
52
+ return 'none';
53
+ }