@principal-ai/subsystems-core 0.53.0 → 0.53.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.
package/src/index.ts CHANGED
@@ -24,8 +24,9 @@ export { formatTopicReferenceLink, parseTopicReferenceLink } from './storage/top
24
24
  export { toSharedTopic } from './storage/topic-share';
25
25
  export type { SharedTopic, SharedTopicAsset, SharedTopicProjection, SharedTopicReference } from './storage/topic-share';
26
26
 
27
- // Infrastructure-as-code read side: what wrangler / terraform declare, and the
28
- // shape a live-deployment observation takes. Pure — text and JSON in.
27
+ // Infrastructure-as-code read side: what wrangler / terraform declare, the
28
+ // shape a live-deployment observation takes, and the checks that produce one
29
+ // from a credential the caller supplies. Browser-safe — no Node built-ins.
29
30
  export * from './infra';
30
31
 
31
32
  // Cross-field validation (the rules the JSON Schema can't express). Structural
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Infrastructure-as-code read side. Pure and browser-safe.
2
+ * Infrastructure-as-code read side. Browser-safe. Everything is pure except
3
+ * `./observe`, which asks a provider's API what is running, with a credential
4
+ * the caller supplies.
3
5
  */
4
6
 
5
7
  export { infraResourceKey, mergeInfraManifests } from './types';
@@ -19,3 +21,21 @@ export { extractTerraformManifest, terraformStateObservations } from './terrafor
19
21
  export type { ExtractTerraformOptions } from './terraform';
20
22
  export { infraContainerId, infraDeploymentRef, infraToC4 } from './c4';
21
23
  export type { InfraC4Container, InfraC4Deployment, InfraC4Edge } from './c4';
24
+ export {
25
+ CLOUDFLARE_OBSERVED_TYPES,
26
+ NEON_OBSERVED_TYPES,
27
+ observeCloudflare,
28
+ observeNeon,
29
+ parseWranglerAuthToken,
30
+ resolveCloudflareAccount,
31
+ resolveNeonAccount,
32
+ withoutUnknownOverwrites,
33
+ } from './observe';
34
+ export type {
35
+ CloudflareAccess,
36
+ CloudflareAccountResult,
37
+ InfraObserveDeps,
38
+ InfraObserveResult,
39
+ NeonAccess,
40
+ NeonAccountResult,
41
+ } from './observe';
@@ -0,0 +1,232 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { observeNeon, resolveNeonAccount } from './observe';
3
+
4
+ const KEY = `napi_${'k'.repeat(64)}`;
5
+ const NOW = () => new Date('2026-12-05T12:00:00.000Z');
6
+
7
+ type Route = { status?: number; body: unknown };
8
+
9
+ /** A Neon API stand-in: path (with query, when given) → answer. */
10
+ function fakeNeon(routes: Record<string, Route>) {
11
+ const seen: Array<{ method: string; path: string; authorization: string | null }> = [];
12
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
13
+ const url = new URL(String(input));
14
+ expect(url.origin).toBe('https://console.neon.tech');
15
+ const path = url.pathname.replace('/api/v2', '');
16
+ seen.push({
17
+ method: init?.method ?? 'GET',
18
+ path: `${path}${url.search}`,
19
+ authorization: new Headers(init?.headers).get('authorization'),
20
+ });
21
+ const route = routes[`${path}${url.search}`] ?? routes[path];
22
+ if (!route) return Response.json({ code: '', message: 'not found' }, { status: 404 });
23
+ return Response.json(route.body, { status: route.status ?? 200 });
24
+ }) as typeof fetch;
25
+ return { fetchImpl, seen };
26
+ }
27
+
28
+ const branches = (projectId: string) => ({
29
+ [`/projects/${projectId}/branches`]: {
30
+ body: { branches: [{ id: 'br-dev', default: false }, { id: 'br-main', default: true }] },
31
+ },
32
+ });
33
+ const databases = (projectId: string, names: string[]) => ({
34
+ [`/projects/${projectId}/branches/br-main/databases`]: {
35
+ body: { databases: names.map((name) => ({ name })) },
36
+ },
37
+ });
38
+
39
+ describe('resolveNeonAccount', () => {
40
+ test('a key that can list projects is accepted, named after its owner', async () => {
41
+ const { fetchImpl, seen } = fakeNeon({
42
+ '/projects': { body: { projects: [] } },
43
+ '/users/me': { body: { name: 'Ada', last_name: 'Lovelace', email: 'ada@example.com' } },
44
+ });
45
+ expect(await resolveNeonAccount({ token: KEY }, { fetch: fetchImpl })).toEqual({
46
+ ok: true,
47
+ account: 'Ada Lovelace',
48
+ });
49
+ expect(seen.every((call) => call.method === 'GET')).toBe(true);
50
+ expect(seen.every((call) => call.authorization === `Bearer ${KEY}`)).toBe(true);
51
+ });
52
+
53
+ test('a personal key in one organization uses that organization', async () => {
54
+ const { fetchImpl } = fakeNeon({
55
+ '/projects?limit=1': { status: 400, body: { code: '', message: 'org_id is required' } },
56
+ '/projects?limit=1&org_id=org-acme-1': { body: { projects: [] } },
57
+ '/users/me/organizations': { body: { organizations: [{ id: 'org-acme-1', name: 'Acme' }] } },
58
+ });
59
+ expect(await resolveNeonAccount({ token: KEY }, { fetch: fetchImpl })).toEqual({
60
+ ok: true,
61
+ orgId: 'org-acme-1',
62
+ account: 'Acme',
63
+ });
64
+ });
65
+
66
+ test('several organizations: the caller has to choose', async () => {
67
+ const { fetchImpl } = fakeNeon({
68
+ '/projects?limit=1': { status: 400, body: { code: '', message: 'org_id is required' } },
69
+ '/users/me/organizations': {
70
+ body: { organizations: [{ id: 'org-a', name: 'A' }, { id: 'org-b', name: 'B' }] },
71
+ },
72
+ });
73
+ const result = await resolveNeonAccount({ token: KEY }, { fetch: fetchImpl });
74
+ expect(result.ok).toBe(false);
75
+ expect(!result.ok && result.accounts).toEqual([
76
+ { id: 'org-a', name: 'A' },
77
+ { id: 'org-b', name: 'B' },
78
+ ]);
79
+ });
80
+
81
+ test('a chosen organization is used and named', async () => {
82
+ const { fetchImpl } = fakeNeon({
83
+ '/projects?limit=1&org_id=org-b': { body: { projects: [] } },
84
+ '/organizations/org-b': { body: { id: 'org-b', name: 'B' } },
85
+ });
86
+ expect(await resolveNeonAccount({ token: KEY, orgId: 'org-b' }, { fetch: fetchImpl })).toEqual({
87
+ ok: true,
88
+ orgId: 'org-b',
89
+ account: 'B',
90
+ });
91
+ });
92
+
93
+ test('a rejected key says so, and never echoes the key', async () => {
94
+ const { fetchImpl } = fakeNeon({
95
+ '/projects': { status: 401, body: { code: '', message: 'authentication failed' } },
96
+ });
97
+ const result = await resolveNeonAccount({ token: KEY }, { fetch: fetchImpl });
98
+ expect(result).toEqual({ ok: false, error: 'Neon rejected the key: authentication failed' });
99
+ expect(JSON.stringify(result)).not.toContain(KEY);
100
+ });
101
+
102
+ test('a malformed organization id is refused before any request', async () => {
103
+ const { fetchImpl, seen } = fakeNeon({});
104
+ const result = await resolveNeonAccount({ token: KEY, orgId: 'Not An Org' }, { fetch: fetchImpl });
105
+ expect(result.ok).toBe(false);
106
+ expect(seen).toEqual([]);
107
+ });
108
+ });
109
+
110
+ describe('observeNeon', () => {
111
+ test('a database named after its project is deployed; the search is matched exactly', async () => {
112
+ const { fetchImpl, seen } = fakeNeon({
113
+ '/projects?limit=100&search=openbot': {
114
+ body: {
115
+ projects: [
116
+ { id: 'old-moon-1', name: 'openbot-staging' },
117
+ { id: 'calm-sea-2', name: 'openbot' },
118
+ ],
119
+ },
120
+ },
121
+ });
122
+ const result = await observeNeon(
123
+ ['neon:database:openbot', 'cloudflare:worker:openbot', 'neon:role:app'],
124
+ { token: KEY },
125
+ { fetch: fetchImpl, now: NOW },
126
+ );
127
+ expect(result.observations).toEqual([
128
+ {
129
+ resourceKey: 'neon:database:openbot',
130
+ status: 'deployed',
131
+ resourceId: 'calm-sea-2',
132
+ consoleUrl: 'https://console.neon.tech/app/projects/calm-sea-2',
133
+ observedAt: '2026-12-05T12:00:00.000Z',
134
+ source: 'neon-api',
135
+ },
136
+ ]);
137
+ expect(result.skipped).toEqual([{ resourceKey: 'neon:role:app', reason: 'role is not checked yet' }]);
138
+ expect(result.failure).toBeUndefined();
139
+ expect(seen.every((call) => call.method === 'GET')).toBe(true);
140
+ expect(JSON.stringify(result)).not.toContain(KEY);
141
+ });
142
+
143
+ test('a project can be named by id, and the organization is passed along', async () => {
144
+ const { fetchImpl } = fakeNeon({
145
+ '/projects?limit=100&search=calm-sea-2&org_id=org-acme-1': {
146
+ body: { projects: [{ id: 'calm-sea-2', name: 'whatever' }] },
147
+ },
148
+ });
149
+ const result = await observeNeon(
150
+ ['neon:project:calm-sea-2'],
151
+ { token: KEY, orgId: 'org-acme-1' },
152
+ { fetch: fetchImpl, now: NOW },
153
+ );
154
+ expect(result.observations[0]).toMatchObject({ status: 'deployed', resourceId: 'calm-sea-2' });
155
+ });
156
+
157
+ test('project/database looks on the default branch', async () => {
158
+ const { fetchImpl } = fakeNeon({
159
+ '/projects?limit=100&search=shop': { body: { projects: [{ id: 'p1', name: 'shop' }] } },
160
+ '/projects?limit=100&search=nope': { body: { projects: [] } },
161
+ ...branches('p1'),
162
+ ...databases('p1', ['neondb', 'orders']),
163
+ });
164
+ const result = await observeNeon(
165
+ ['neon:database:shop/orders', 'neon:database:shop/missing', 'neon:database:nope/orders'],
166
+ { token: KEY },
167
+ { fetch: fetchImpl, now: NOW },
168
+ );
169
+ expect(result.observations.map((o) => [o.resourceKey, o.status, o.resourceId])).toEqual([
170
+ ['neon:database:shop/orders', 'deployed', 'p1/orders'],
171
+ ['neon:database:shop/missing', 'not-found', undefined],
172
+ ['neon:database:nope/orders', 'not-found', undefined],
173
+ ]);
174
+ });
175
+
176
+ test('a lone name that is no project is looked for as a database in each project', async () => {
177
+ const { fetchImpl } = fakeNeon({
178
+ '/projects?limit=100&search=orders': { body: { projects: [] } },
179
+ '/projects?limit=100&search=ghost': { body: { projects: [] } },
180
+ '/projects?limit=21': { body: { projects: [{ id: 'p1', name: 'a' }, { id: 'p2', name: 'b' }] } },
181
+ ...branches('p1'),
182
+ ...databases('p1', ['neondb']),
183
+ ...branches('p2'),
184
+ ...databases('p2', ['orders']),
185
+ });
186
+ const result = await observeNeon(
187
+ ['neon:database:orders', 'neon:database:ghost'],
188
+ { token: KEY },
189
+ { fetch: fetchImpl, now: NOW },
190
+ );
191
+ expect(result.observations.map((o) => [o.status, o.resourceId])).toEqual([
192
+ ['deployed', 'p2/orders'],
193
+ ['not-found', undefined],
194
+ ]);
195
+ });
196
+
197
+ test('not found is not claimed when a project could not be read or there are too many', async () => {
198
+ const many = Array.from({ length: 21 }, (_, i) => ({ id: `p${i}`, name: `n${i}` }));
199
+ const empty = Object.assign(
200
+ {},
201
+ ...many.map((p) => ({ ...branches(p.id), ...databases(p.id, ['neondb']) })),
202
+ );
203
+ const tooMany = fakeNeon({
204
+ '/projects?limit=100&search=orders': { body: { projects: [] } },
205
+ '/projects?limit=21': { body: { projects: many } },
206
+ ...empty,
207
+ });
208
+ const first = await observeNeon(['neon:database:orders'], { token: KEY }, { fetch: tooMany.fetchImpl, now: NOW });
209
+ expect(first.observations[0]?.status).toBe('unknown');
210
+ expect(first.failure).toContain('project/database');
211
+
212
+ const unreadable = fakeNeon({
213
+ '/projects?limit=100&search=orders': { body: { projects: [] } },
214
+ '/projects?limit=21': { body: { projects: [{ id: 'p1', name: 'a' }] } },
215
+ '/projects/p1/branches': { status: 403, body: { code: '', message: 'forbidden' } },
216
+ });
217
+ const second = await observeNeon(['neon:database:orders'], { token: KEY }, { fetch: unreadable.fetchImpl, now: NOW });
218
+ expect(second.observations[0]?.status).toBe('unknown');
219
+ expect(second.failure).toBe('database: forbidden');
220
+ });
221
+
222
+ test('a failed request is unknown, with the reason', async () => {
223
+ const { fetchImpl } = fakeNeon({
224
+ '/projects': { status: 401, body: { code: '', message: 'authentication failed' } },
225
+ });
226
+ const result = await observeNeon(['neon:project:x'], { token: KEY }, { fetch: fetchImpl, now: NOW });
227
+ expect(result.observations).toEqual([
228
+ { resourceKey: 'neon:project:x', status: 'unknown', observedAt: '2026-12-05T12:00:00.000Z', source: 'neon-api' },
229
+ ]);
230
+ expect(result.failure).toBe('project: authentication failed');
231
+ });
232
+ });
@@ -0,0 +1,202 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ observeCloudflare,
4
+ parseWranglerAuthToken,
5
+ resolveCloudflareAccount,
6
+ withoutUnknownOverwrites,
7
+ } from './observe';
8
+
9
+ const TOKEN = 'cf_test_token_0123456789abcdefghij';
10
+ const ACCOUNT = 'a'.repeat(32);
11
+ const NOW = () => new Date('2026-12-05T12:00:00.000Z');
12
+
13
+ type Route = { status?: number; result?: unknown; errors?: Array<{ code: number; message: string }> };
14
+
15
+ /** A Cloudflare API stand-in: path → answer. Records what it was asked. */
16
+ function fakeCloudflare(routes: Record<string, Route>) {
17
+ const seen: Array<{ method: string; path: string; authorization: string | null }> = [];
18
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
19
+ const url = new URL(String(input));
20
+ const path = url.pathname.replace('/client/v4', '');
21
+ seen.push({
22
+ method: init?.method ?? 'GET',
23
+ path,
24
+ authorization: new Headers(init?.headers).get('authorization'),
25
+ });
26
+ const route = routes[`${path}${url.search}`] ?? routes[path];
27
+ if (!route) {
28
+ return Response.json(
29
+ { success: false, errors: [{ code: 10007, message: 'not found' }] },
30
+ { status: 404 },
31
+ );
32
+ }
33
+ const status = route.status ?? 200;
34
+ return Response.json(
35
+ { success: status < 400, result: route.result ?? null, errors: route.errors ?? [] },
36
+ { status },
37
+ );
38
+ }) as typeof fetch;
39
+ return { fetchImpl, seen };
40
+ }
41
+
42
+ describe('resolveCloudflareAccount', () => {
43
+ test('one visible account that can read Workers is accepted', async () => {
44
+ const { fetchImpl } = fakeCloudflare({
45
+ '/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }] },
46
+ [`/accounts/${ACCOUNT}/workers/subdomain`]: { result: { subdomain: 'acme' } },
47
+ });
48
+ expect(await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl })).toEqual({
49
+ ok: true,
50
+ accountId: ACCOUNT,
51
+ account: 'Acme',
52
+ });
53
+ });
54
+
55
+ test('several accounts: the caller has to choose', async () => {
56
+ const other = 'b'.repeat(32);
57
+ const { fetchImpl } = fakeCloudflare({
58
+ '/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }, { id: other, name: 'Other' }] },
59
+ });
60
+ const result = await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl });
61
+ expect(result).toMatchObject({ ok: false, accounts: [{ id: ACCOUNT }, { id: other }] });
62
+ });
63
+
64
+ test('a token that cannot read Workers is refused with the reason', async () => {
65
+ const { fetchImpl } = fakeCloudflare({
66
+ '/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }] },
67
+ [`/accounts/${ACCOUNT}/workers/subdomain`]: {
68
+ status: 403,
69
+ errors: [{ code: 10000, message: 'Authentication error' }],
70
+ },
71
+ });
72
+ const result = await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl });
73
+ expect(result).toEqual({
74
+ ok: false,
75
+ error: 'The token cannot read Workers on that account: Authentication error',
76
+ });
77
+ });
78
+
79
+ test('a malformed account id is refused before asking anyone', async () => {
80
+ const { fetchImpl, seen } = fakeCloudflare({});
81
+ const result = await resolveCloudflareAccount(
82
+ { token: TOKEN, accountId: 'nope' },
83
+ { fetch: fetchImpl },
84
+ );
85
+ expect(result.ok).toBe(false);
86
+ expect(seen).toEqual([]);
87
+ });
88
+ });
89
+
90
+ describe('observeCloudflare', () => {
91
+ const access = { token: TOKEN, accountId: ACCOUNT };
92
+
93
+ test('deployed, not-found, unknown and skipped are told apart, and nothing but reads is sent', async () => {
94
+ const { fetchImpl, seen } = fakeCloudflare({
95
+ [`/accounts/${ACCOUNT}/workers/scripts/api/subdomain`]: { result: { enabled: true } },
96
+ [`/accounts/${ACCOUNT}/workers/subdomain`]: { result: { subdomain: 'acme' } },
97
+ [`/accounts/${ACCOUNT}/workers/scripts/api/deployments`]: {
98
+ result: {
99
+ deployments: [{ created_on: '2026-12-01T08:00:00Z', versions: [{ version_id: 'v-123' }] }],
100
+ },
101
+ },
102
+ [`/accounts/${ACCOUNT}/r2/buckets/blobs`]: {
103
+ status: 403,
104
+ errors: [{ code: 10000, message: 'Authentication error' }],
105
+ },
106
+ });
107
+ const result = await observeCloudflare(
108
+ [
109
+ 'cloudflare:worker:api',
110
+ 'cloudflare:worker:gone',
111
+ 'cloudflare:r2_bucket:blobs',
112
+ 'cloudflare:hyperdrive:pg',
113
+ 'aws:lambda:ignored',
114
+ 'cloudflare:worker:api',
115
+ ],
116
+ access,
117
+ { fetch: fetchImpl, now: NOW },
118
+ );
119
+
120
+ expect(result.observations).toEqual([
121
+ {
122
+ resourceKey: 'cloudflare:worker:api',
123
+ status: 'deployed',
124
+ liveUrls: ['https://api.acme.workers.dev'],
125
+ consoleUrl: `https://dash.cloudflare.com/${ACCOUNT}/workers/services/view/api/production`,
126
+ version: 'v-123',
127
+ deployedAt: '2026-12-01T08:00:00.000Z',
128
+ observedAt: '2026-12-05T12:00:00.000Z',
129
+ source: 'cloudflare-api',
130
+ },
131
+ {
132
+ resourceKey: 'cloudflare:worker:gone',
133
+ status: 'not-found',
134
+ observedAt: '2026-12-05T12:00:00.000Z',
135
+ source: 'cloudflare-api',
136
+ },
137
+ {
138
+ resourceKey: 'cloudflare:r2_bucket:blobs',
139
+ status: 'unknown',
140
+ observedAt: '2026-12-05T12:00:00.000Z',
141
+ source: 'cloudflare-api',
142
+ },
143
+ ]);
144
+ expect(result.skipped).toEqual([
145
+ { resourceKey: 'cloudflare:hyperdrive:pg', reason: 'hyperdrive is not checked yet' },
146
+ ]);
147
+ expect(result.failure).toBe('r2 bucket: Authentication error');
148
+ expect(seen.every((call) => call.method === 'GET')).toBe(true);
149
+ expect(seen.every((call) => call.authorization === `Bearer ${TOKEN}`)).toBe(true);
150
+ expect(JSON.stringify(result)).not.toContain(TOKEN);
151
+ });
152
+
153
+ test('an unreachable API reads as unknown, never as not-found', async () => {
154
+ const failing = (async () => {
155
+ throw new Error('offline');
156
+ }) as unknown as typeof fetch;
157
+ const result = await observeCloudflare(['cloudflare:worker:api'], access, {
158
+ fetch: failing,
159
+ now: NOW,
160
+ });
161
+ expect(result.observations.map((o) => o.status)).toEqual(['unknown']);
162
+ expect(result.failure).toBe('worker: could not reach the Cloudflare API');
163
+ });
164
+ });
165
+
166
+ describe('withoutUnknownOverwrites', () => {
167
+ test('an unknown is kept only when nothing is known about the resource', () => {
168
+ const at = { observedAt: '2026-12-05T12:00:00.000Z', source: 'cloudflare-api' };
169
+ const kept = withoutUnknownOverwrites(
170
+ [
171
+ { resourceKey: 'a', status: 'unknown', ...at },
172
+ { resourceKey: 'b', status: 'unknown', ...at },
173
+ { resourceKey: 'c', status: 'not-found', ...at },
174
+ ],
175
+ new Set(['a', 'c']),
176
+ );
177
+ expect(kept.map((o) => o.resourceKey)).toEqual(['b', 'c']);
178
+ });
179
+ });
180
+
181
+ describe('parseWranglerAuthToken', () => {
182
+ test('an OAuth login and an API token are usable', () => {
183
+ const oauth = `${'x'.repeat(40)}.${'y'.repeat(40)}`;
184
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: oauth }))).toEqual({
185
+ type: 'oauth',
186
+ token: oauth,
187
+ });
188
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'api_token', token: TOKEN }))).toEqual({
189
+ type: 'api_token',
190
+ token: TOKEN,
191
+ });
192
+ });
193
+
194
+ test('a global API key, a logged-out answer and noise are not', () => {
195
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'api_key', key: 'k', email: 'e' }))).toBeNull();
196
+ expect(parseWranglerAuthToken('Not logged in.')).toBeNull();
197
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: 'short' }))).toBeNull();
198
+ expect(
199
+ parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: `${'x'.repeat(30)}\r\nX-Evil: 1` })),
200
+ ).toBeNull();
201
+ });
202
+ });