@signet-registry/operator 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +191 -2
  3. package/dist/clients/api.js +257 -0
  4. package/dist/clients/mcp.js +118 -0
  5. package/dist/clients/verify.js +125 -0
  6. package/dist/config/env.js +42 -0
  7. package/dist/keyless.js +52 -0
  8. package/dist/main.js +7 -0
  9. package/dist/operator.js +1729 -0
  10. package/dist/transparency/sample-graph.js +203 -0
  11. package/dist/types.js +111 -0
  12. package/examples/bootstrap/agents/bootstrap-agent.md +5 -0
  13. package/examples/bootstrap/agents/bootstrap-ops-agent.md +8 -0
  14. package/examples/bootstrap/bootstrap.manifest.json +107 -0
  15. package/examples/bootstrap/skills/bootstrap-example.md +8 -0
  16. package/examples/bootstrap/skills/bootstrap-ops.md +8 -0
  17. package/examples/demo/agents/registry-agent.md +34 -0
  18. package/examples/demo/demo.manifest.json +90 -0
  19. package/examples/demo/skills/registry-mcp.md +74 -0
  20. package/examples/demo/skills/tame-llama.md +37 -0
  21. package/examples/signet-demo/agents/signet-demo-agent.md +39 -0
  22. package/examples/signet-demo/agents/signet-security-agent.md +36 -0
  23. package/examples/signet-demo/signet-demo.manifest.json +219 -0
  24. package/examples/signet-demo/skills/access-review.md +40 -0
  25. package/examples/signet-demo/skills/certification-workflow.md +39 -0
  26. package/examples/signet-demo/skills/governance-audit.md +39 -0
  27. package/examples/signet-demo/skills/graph-explorer.md +38 -0
  28. package/examples/signet-demo/skills/mcp-onboarding.md +39 -0
  29. package/examples/signet-demo/skills/policy-authoring.md +39 -0
  30. package/examples/signet-demo/skills/provenance-audit.md +39 -0
  31. package/examples/signet-demo/skills/registry-search.md +38 -0
  32. package/examples/signet-demo/skills/secrets-hygiene.md +39 -0
  33. package/examples/signet-demo/skills/skill-authoring.md +40 -0
  34. package/examples/transparency/README.md +39 -0
  35. package/examples/transparency/sample-graph.spec.json +16 -0
  36. package/package.json +58 -4
@@ -0,0 +1,1729 @@
1
+ import { createHash, randomUUID, generateKeyPairSync, createPrivateKey, createPublicKey, sign as signBytes } from 'node:crypto';
2
+ import { mkdir, rm, readFile, writeFile } from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import { spawn } from 'node:child_process';
5
+ import { z } from 'zod';
6
+ import { buildKeylessBundle } from './keyless.js';
7
+ import { cfAccessHeaders, loadEnv } from './config/env.js';
8
+ import { AgentSeedSpecSchema, BootstrapManifestSchema, SkillSeedSpecSchema, } from './types.js';
9
+ import { HttpRegistryOperatorApiClient, RegistryOperatorApiError } from './clients/api.js';
10
+ import { RegistryOperatorMcpClient } from './clients/mcp.js';
11
+ import { sha256Hex, isTrustedKeyUsableAt, verifyEnvelopeSignatures, verifyProvenanceSignature } from './clients/verify.js';
12
+ import { buildTransparencySampleGraphSpec, readTransparencySampleGraphSpec, seedTransparencySampleGraph, } from './transparency/sample-graph.js';
13
+ const AuthCreateApiKeyResultSchema = z.object({
14
+ token: z.string().min(1),
15
+ key_id: z.string().min(1),
16
+ owner_label: z.string().min(1),
17
+ });
18
+ const DEFAULT_DEMO_MANIFEST_RELATIVE_PATH = path.join('client', 'registry-cli', 'examples', 'demo', 'demo.manifest.json');
19
+ const RUN_ARTIFACTS_RELATIVE_DIR = path.join('data', 'registry-operator');
20
+ export async function runCli(argv) {
21
+ const env = loadEnv();
22
+ const command = parseArgs(argv);
23
+ applyCfAccessArgs(env, command.args);
24
+ switch (command.group) {
25
+ case 'local':
26
+ if (command.action === 'up')
27
+ return await runLocalUp(env);
28
+ if (command.action === 'down')
29
+ return await runLocalDown(env);
30
+ return await runLocalReset(env, command.args);
31
+ case 'auth':
32
+ return await runCreateApiKey(env, command.args);
33
+ case 'seed':
34
+ if (command.action === 'skill')
35
+ return await runSeedSkill(env, command.args);
36
+ if (command.action === 'agent')
37
+ return await runSeedAgent(env, command.args);
38
+ if (command.action === 'transparency-sample')
39
+ return await runSeedTransparencySample(env, command.args);
40
+ return await runSeedBootstrap(env, command.args);
41
+ case 'verify':
42
+ if (command.action === 'api')
43
+ return await runVerifyApi(env, command.args);
44
+ if (command.action === 'mcp')
45
+ return await runVerifyMcp(env, command.args);
46
+ if (command.action === 'okta-config')
47
+ return await runVerifyOktaConfig(env);
48
+ if (command.action === 'publication')
49
+ return await runVerifyPublication(env, command.args);
50
+ if (command.action === 'artifact')
51
+ return await runVerifyArtifact(env, command.args);
52
+ if (command.action === 'provenance')
53
+ return await runVerifyProvenance(env, command.args);
54
+ if (command.action === 'report-signatures')
55
+ return await runVerifyReportSignatures(env, command.args);
56
+ return await runVerifyBrowserSession(env, command.args);
57
+ case 'bootstrap':
58
+ return await runBootstrapTest(env, command.args);
59
+ case 'sign':
60
+ return await runSignKeyless(env, command.args);
61
+ }
62
+ }
63
+ export function parseArgs(argv) {
64
+ const [group, action, ...rest] = argv;
65
+ if (!group || !action) {
66
+ throw new Error('Usage: registry-operator <group> <action> [--options]');
67
+ }
68
+ const args = parseOptions(rest);
69
+ if (group === 'local' && (action === 'up' || action === 'down' || action === 'reset')) {
70
+ return { group: 'local', action, args };
71
+ }
72
+ if (group === 'auth' && action === 'create-api-key') {
73
+ return { group: 'auth', action, args };
74
+ }
75
+ if (group === 'seed' && (action === 'skill' || action === 'agent' || action === 'bootstrap' || action === 'transparency-sample')) {
76
+ return { group: 'seed', action, args };
77
+ }
78
+ if (group === 'verify' && (action === 'api' || action === 'mcp' || action === 'okta-config' || action === 'browser-session' || action === 'publication' || action === 'artifact' || action === 'provenance' || action === 'report-signatures')) {
79
+ return { group: 'verify', action, args };
80
+ }
81
+ if (group === 'bootstrap' && action === 'test') {
82
+ return { group: 'bootstrap', action, args };
83
+ }
84
+ if (group === 'sign' && action === 'keyless') {
85
+ return { group: 'sign', action, args };
86
+ }
87
+ throw new Error(`Unknown command: ${group} ${action}`);
88
+ }
89
+ export function buildSkillSeedPlan(spec, specDir) {
90
+ if (!spec.author) {
91
+ throw new Error(`Skill ${spec.skill_key} is missing author after defaults resolution.`);
92
+ }
93
+ return {
94
+ itemId: spec.item_id ?? spec.skill_key,
95
+ dependsOn: spec.depends_on ?? [],
96
+ tags: spec.tags ?? [],
97
+ draft: {
98
+ skill_key: spec.skill_key,
99
+ author: spec.author,
100
+ artifact_path: resolveSpecPath(specDir, spec.artifact_path),
101
+ artifact_media_type: spec.artifact_media_type,
102
+ ...(spec.display_name ? { display_name: spec.display_name } : {}),
103
+ ...(spec.description ? { description: spec.description } : {}),
104
+ ...(spec.source_path ? { source_path: spec.source_path } : { source_path: spec.artifact_path }),
105
+ ...(spec.commit_sha ? { commit_sha: spec.commit_sha } : {}),
106
+ ...(spec.git_tag ? { git_tag: spec.git_tag } : {}),
107
+ ...(spec.artifact_signature ? { artifact_signature: spec.artifact_signature } : {}),
108
+ ...(spec.lineage ? { lineage: spec.lineage } : {}),
109
+ },
110
+ ...(spec.validate_note ? { validateNote: spec.validate_note } : {}),
111
+ ...(spec.publish_note ? { publishNote: spec.publish_note } : {}),
112
+ certify: spec.certify,
113
+ ...(spec.certify_note ? { certifyNote: spec.certify_note } : {}),
114
+ };
115
+ }
116
+ export function buildAgentCreatePlan(spec, specDir) {
117
+ return {
118
+ itemId: spec.item_id ?? spec.agent_key,
119
+ dependsOn: spec.depends_on ?? [],
120
+ tags: spec.tags ?? [],
121
+ agent_key: spec.agent_key,
122
+ ...(spec.harness_name ? { harness_name: spec.harness_name } : {}),
123
+ ...(spec.display_name ? { display_name: spec.display_name } : {}),
124
+ ...(spec.description ? { description: spec.description } : {}),
125
+ ...(spec.source_path ? { source_path: spec.source_path } : spec.artifact_path ? { source_path: spec.artifact_path } : {}),
126
+ ...(spec.artifact_path ? { artifact_path: resolveSpecPath(specDir, spec.artifact_path) } : {}),
127
+ ...(spec.artifact_path ? { artifact_media_type: spec.artifact_media_type } : {}),
128
+ skill_refs: spec.skill_refs.map((value) => typeof value === 'string'
129
+ ? value.startsWith('urn:')
130
+ ? { skill_urn: value }
131
+ : { skill_key: value }
132
+ : {
133
+ ...(value.skill_key ? { skill_key: value.skill_key } : {}),
134
+ ...(value.skill_urn ? { skill_urn: value.skill_urn } : {}),
135
+ ...(value.skill_item_id ? { skill_item_id: value.skill_item_id } : {}),
136
+ }),
137
+ };
138
+ }
139
+ export function resolveBootstrapManifest(manifest, manifestPath, options = {}) {
140
+ const specDir = path.dirname(manifestPath);
141
+ const profile = options.profile ? resolveProfile(manifest, options.profile) : undefined;
142
+ const rawSkills = manifest.skills.map((skill) => ({
143
+ ...manifest.defaults?.skill,
144
+ ...skill,
145
+ item_id: skill.item_id ?? skill.skill_key,
146
+ depends_on: skill.depends_on ?? [],
147
+ tags: skill.tags ?? [],
148
+ }));
149
+ const rawAgents = manifest.agents.map((agent) => ({
150
+ ...manifest.defaults?.agent,
151
+ ...agent,
152
+ item_id: agent.item_id ?? agent.agent_key,
153
+ depends_on: agent.depends_on ?? [],
154
+ tags: agent.tags ?? [],
155
+ }));
156
+ const selectedSkillIds = buildSelectionSet(rawSkills.map((item) => item.item_id), profile?.skill_item_ids, options.skillItemIds);
157
+ const selectedAgentIds = buildSelectionSet(rawAgents.map((item) => item.item_id), profile?.agent_item_ids, options.agentItemIds);
158
+ const selectedSkills = rawSkills.filter((skill) => selectedSkillIds.has(skill.item_id));
159
+ const selectedAgents = rawAgents.filter((agent) => selectedAgentIds.has(agent.item_id));
160
+ const selectedSkillMap = new Map(selectedSkills.map((skill) => [skill.item_id, skill]));
161
+ const selectedAgentMap = new Map(selectedAgents.map((agent) => [agent.item_id, agent]));
162
+ for (const skill of selectedSkills) {
163
+ for (const dep of skill.depends_on) {
164
+ if (!selectedSkillMap.has(dep)) {
165
+ throw new Error(`Skill ${skill.item_id} depends on unknown or unselected skill item ${dep}.`);
166
+ }
167
+ }
168
+ }
169
+ const orderedSkills = topologicalOrder(selectedSkills, (item) => item.item_id, (item) => item.depends_on ?? [], 'skill');
170
+ const builtSkills = orderedSkills.map((skill) => buildSkillSeedPlan(SkillSeedSpecSchema.parse(skill), specDir));
171
+ const builtSkillMap = new Map(builtSkills.map((skill) => [skill.itemId, skill]));
172
+ const resolvedAgents = selectedAgents.map((agent) => {
173
+ for (const dep of agent.depends_on ?? []) {
174
+ if (!selectedAgentMap.has(dep) && !selectedSkillMap.has(dep)) {
175
+ throw new Error(`Agent ${agent.item_id} depends on unknown or unselected item ${dep}.`);
176
+ }
177
+ }
178
+ const normalizedRefs = agent.skill_refs.map((ref) => normalizeSkillRef(ref, builtSkillMap));
179
+ return buildAgentCreatePlan(AgentSeedSpecSchema.parse({
180
+ ...agent,
181
+ skill_refs: normalizedRefs,
182
+ }), specDir);
183
+ });
184
+ const orderedAgents = topologicalOrder(resolvedAgents, (item) => item.itemId, (item) => item.dependsOn.filter((dep) => selectedAgentMap.has(dep)), 'agent');
185
+ return {
186
+ ...(manifest.pack ? { pack: manifest.pack } : {}),
187
+ ...(options.profile ? { profile: options.profile } : {}),
188
+ ...(manifest.signing ? { signing: manifest.signing } : {}),
189
+ skills: builtSkills,
190
+ agents: orderedAgents,
191
+ };
192
+ }
193
+ export function assertResetAllowed(args) {
194
+ if (!args.force) {
195
+ throw new Error('Refusing to reset local state without --force.');
196
+ }
197
+ }
198
+ async function runLocalUp(env) {
199
+ await runShell('make', ['up'], { cwd: path.join(env.REPO_ROOT, 'infra') });
200
+ console.log('Local stack started.');
201
+ }
202
+ async function runLocalDown(env) {
203
+ await runShell('make', ['down'], { cwd: path.join(env.REPO_ROOT, 'infra') });
204
+ console.log('Local stack stopped.');
205
+ }
206
+ async function runLocalReset(env, args) {
207
+ assertResetAllowed(args);
208
+ await clearSparqlDatasetsForReset(env);
209
+ await runLocalDown(env).catch(() => undefined);
210
+ const targets = [
211
+ path.join(env.REPO_ROOT, 'data', 'api'),
212
+ path.join(env.REPO_ROOT, 'data', 'mcp'),
213
+ path.join(env.REPO_ROOT, 'data', 'registry-operator'),
214
+ path.join(env.REPO_ROOT, 'data', 'webapp'),
215
+ path.join(env.REPO_ROOT, 'data', 'registry', 'graph'),
216
+ path.join(env.REPO_ROOT, 'data', 'registry', 'objects'),
217
+ path.join(env.REPO_ROOT, '.cookies'),
218
+ ];
219
+ for (const target of targets) {
220
+ await rm(target, { recursive: true, force: true });
221
+ }
222
+ console.log('Local bind-mounted state cleared.');
223
+ }
224
+ async function runCreateApiKey(env, args) {
225
+ const plane = asString(args.plane) ?? 'api';
226
+ const ownerLabel = asString(args['owner-label']) ?? 'Registry Operator';
227
+ const result = await createApiKey(env, plane === 'mcp' ? 'mcp' : 'api', ownerLabel);
228
+ console.log(JSON.stringify(result, null, 2));
229
+ }
230
+ async function runSeedSkill(env, args) {
231
+ await waitForApiAndGraphReadiness(env);
232
+ const specPath = requireStringArg(args, 'spec');
233
+ const apiToken = requireStringArg(args, 'api-token');
234
+ const spec = SkillSeedSpecSchema.parse(JSON.parse(await readFile(specPath, 'utf8')));
235
+ const plan = buildSkillSeedPlan(spec, path.dirname(specPath));
236
+ if (args['dry-run']) {
237
+ console.log(JSON.stringify({ plan }, null, 2));
238
+ return;
239
+ }
240
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
241
+ const drafted = await api.createSkillDraft(plan, apiToken);
242
+ await api.validateSkillVersion({
243
+ skill_key: plan.draft.skill_key,
244
+ version: drafted.version,
245
+ author: plan.draft.author,
246
+ ...(plan.validateNote ? { note: plan.validateNote } : {}),
247
+ }, apiToken);
248
+ await api.publishSkillVersion({
249
+ skill_key: plan.draft.skill_key,
250
+ version: drafted.version,
251
+ author: plan.draft.author,
252
+ ...(plan.publishNote ? { note: plan.publishNote } : {}),
253
+ }, apiToken);
254
+ if (plan.certify) {
255
+ await api.certifySkillVersion({
256
+ skill_key: plan.draft.skill_key,
257
+ version: drafted.version,
258
+ author: plan.draft.author,
259
+ ...(plan.certifyNote ? { note: plan.certifyNote } : {}),
260
+ }, apiToken);
261
+ }
262
+ const active = await api.getActiveSkillVersion(plan.draft.skill_key, apiToken);
263
+ console.log(JSON.stringify({
264
+ skill_key: plan.draft.skill_key,
265
+ version: drafted.version,
266
+ active,
267
+ }, null, 2));
268
+ }
269
+ async function runSeedAgent(env, args) {
270
+ await waitForApiAndGraphReadiness(env);
271
+ const specPath = requireStringArg(args, 'spec');
272
+ const apiToken = requireStringArg(args, 'api-token');
273
+ const spec = AgentSeedSpecSchema.parse(JSON.parse(await readFile(specPath, 'utf8')));
274
+ const plan = buildAgentCreatePlan(spec, path.dirname(specPath));
275
+ if (args['dry-run']) {
276
+ console.log(JSON.stringify({ plan }, null, 2));
277
+ return;
278
+ }
279
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
280
+ const created = await api.createAgent(plan, apiToken);
281
+ console.log(JSON.stringify(created, null, 2));
282
+ }
283
+ async function runSeedBootstrap(env, args) {
284
+ await waitForApiAndGraphReadiness(env);
285
+ const manifestPath = resolveManifestPath(env, asString(args.manifest));
286
+ const apiToken = requireStringArg(args, 'api-token');
287
+ const manifest = await readBootstrapManifest(manifestPath);
288
+ const resolved = resolveBootstrapManifest(manifest, manifestPath, {
289
+ profile: asString(args.profile),
290
+ skillItemIds: toStringArray(args['skill-item-id']),
291
+ agentItemIds: toStringArray(args['agent-item-id']),
292
+ });
293
+ if (args['dry-run']) {
294
+ console.log(JSON.stringify({ ok: true, resolved }, null, 2));
295
+ return;
296
+ }
297
+ await seedResolvedBootstrapManifest(env, resolved, apiToken);
298
+ console.log(JSON.stringify({ ok: true, manifest: manifestPath, resolved }, null, 2));
299
+ }
300
+ async function runSeedTransparencySample(env, args) {
301
+ const dryRun = Boolean(args['dry-run']);
302
+ const specPath = asString(args.spec);
303
+ const sampleSlug = asString(args['sample-slug']);
304
+ const day = asString(args.day);
305
+ const humanProofReport = Boolean(args['human-proof-report']);
306
+ if (specPath && (sampleSlug || day)) {
307
+ throw new Error('Use either --spec or --sample-slug/--day for transparency-sample, not both.');
308
+ }
309
+ const spec = specPath
310
+ ? await readTransparencySampleGraphSpec(path.resolve(specPath))
311
+ : buildTransparencySampleGraphSpec({
312
+ ...(sampleSlug ? { sampleSlug } : {}),
313
+ ...(day ? { day } : {}),
314
+ });
315
+ if (dryRun) {
316
+ console.log(JSON.stringify({ ok: true, spec }, null, 2));
317
+ return;
318
+ }
319
+ await waitForApiAndGraphReadiness(env);
320
+ const apiToken = requireStringArg(args, 'api-token');
321
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
322
+ const seeded = await seedTransparencySampleGraph(api, apiToken, { spec });
323
+ const log = await api.getTransparencyLog(seeded.spec.logId, apiToken);
324
+ const verification = await api.getTransparencyLogVerification(seeded.spec.logId, apiToken);
325
+ const timeline = await api.getTransparencyLogTimeline(seeded.spec.logId, apiToken);
326
+ if (humanProofReport) {
327
+ console.log(JSON.stringify(buildTransparencyHumanProofReport({
328
+ apiOrigin: env.API_ORIGIN,
329
+ seeded,
330
+ log,
331
+ verification,
332
+ timeline,
333
+ }), null, 2));
334
+ return;
335
+ }
336
+ console.log(JSON.stringify({
337
+ ok: true,
338
+ sample: seeded,
339
+ log,
340
+ verification,
341
+ timeline,
342
+ }, null, 2));
343
+ }
344
+ function buildTransparencyHumanProofReport(input) {
345
+ const verificationStatus = readStringField(input.verification, 'verification_status');
346
+ const checkpointSignatureValid = readBooleanField(input.verification, 'checkpoint_signature_valid');
347
+ const checkpointConsistencyVerified = readBooleanField(input.verification, 'checkpoint_consistency_verified');
348
+ const witnessQuorumMet = readBooleanField(input.verification, 'witness_quorum_met');
349
+ const witnessQuorumRequired = readNumberField(input.verification, 'witness_quorum_required');
350
+ const checkpointHistory = readArrayField(input.verification, 'checkpoint_history');
351
+ const observations = readArrayField(input.verification, 'observations');
352
+ const disagreements = readArrayField(input.verification, 'disagreements');
353
+ const gossipEvents = readArrayField(input.verification, 'gossip_events');
354
+ const timelineEvents = readArrayField(input.timeline, 'events');
355
+ const currentCheckpoint = readObjectField(input.log, 'current_checkpoint');
356
+ return {
357
+ ok: true,
358
+ report_type: 'human-proof-report',
359
+ sample_id: input.seeded.spec.sampleSlug,
360
+ log_id: input.seeded.spec.logId,
361
+ trust_verdict: {
362
+ verification_status: verificationStatus,
363
+ checkpoint_signature_valid: checkpointSignatureValid,
364
+ checkpoint_consistency_verified: checkpointConsistencyVerified,
365
+ witness_quorum_met: witnessQuorumMet,
366
+ witness_quorum_required: witnessQuorumRequired,
367
+ },
368
+ current_checkpoint: {
369
+ tree_size: readNumberField(currentCheckpoint, 'tree_size'),
370
+ root_hash: readStringField(currentCheckpoint, 'root_hash'),
371
+ note_format: readStringField(currentCheckpoint, 'note_format'),
372
+ signature_count: readNumberField(currentCheckpoint, 'signature_count'),
373
+ },
374
+ network_evidence: {
375
+ checkpoint_history_count: checkpointHistory.length,
376
+ observation_count: observations.length,
377
+ disagreement_count: disagreements.length,
378
+ disagreement_kinds: [...new Set(disagreements.map((item) => readStringField(item, 'kind')).filter(Boolean))],
379
+ gossip_event_count: gossipEvents.length,
380
+ timeline_event_count: timelineEvents.length,
381
+ },
382
+ payload_proofs: {
383
+ primary_checkpoint_payload_sha256: input.seeded.checkpointTwoPayloadSha,
384
+ conflicting_observation_payload_sha256: input.seeded.checkpointTwoAltPayloadSha,
385
+ },
386
+ inspect_urls: {
387
+ log: `${input.apiOrigin}/v1/transparency-logs/${encodeURIComponent(input.seeded.spec.logId)}`,
388
+ verification: `${input.apiOrigin}/v1/transparency-logs/${encodeURIComponent(input.seeded.spec.logId)}/verification`,
389
+ timeline: `${input.apiOrigin}/v1/transparency-logs/${encodeURIComponent(input.seeded.spec.logId)}/timeline`,
390
+ },
391
+ what_to_look_for: [
392
+ 'Current checkpoint should have a valid signature and append-only growth.',
393
+ 'Witness quorum should be met for the later checkpoint.',
394
+ 'Disagreement kinds show the intentionally conflicting network observations.',
395
+ 'Payload SHA256 values let humans compare the trusted and conflicting sample notes.',
396
+ ],
397
+ };
398
+ }
399
+ async function runVerifyApi(env, args) {
400
+ await waitForApiAndGraphReadiness(env);
401
+ const manifestPath = resolveManifestPath(env, asString(args.manifest));
402
+ const apiToken = requireStringArg(args, 'api-token');
403
+ const manifest = await readBootstrapManifest(manifestPath);
404
+ const resolved = resolveBootstrapManifest(manifest, manifestPath, {
405
+ profile: asString(args.profile),
406
+ skillItemIds: toStringArray(args['skill-item-id']),
407
+ agentItemIds: toStringArray(args['agent-item-id']),
408
+ });
409
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
410
+ const skills = [];
411
+ for (const skill of resolved.skills) {
412
+ const value = await api.getActiveSkillVersion(skill.draft.skill_key, apiToken);
413
+ skills.push({ item_id: skill.itemId, skill_key: skill.draft.skill_key, active: value });
414
+ }
415
+ const agents = [];
416
+ for (const agent of resolved.agents) {
417
+ const value = await api.getAgent(agent.agent_key, apiToken);
418
+ agents.push({ item_id: agent.itemId, agent_key: agent.agent_key, agent: value });
419
+ }
420
+ console.log(JSON.stringify({ skills, agents }, null, 2));
421
+ }
422
+ async function runVerifyMcp(env, args) {
423
+ await waitForMcpAndGraphReadiness(env);
424
+ const manifestPath = resolveManifestPath(env, asString(args.manifest));
425
+ const mcpToken = requireStringArg(args, 'mcp-token');
426
+ const manifest = await readBootstrapManifest(manifestPath);
427
+ const resolved = resolveBootstrapManifest(manifest, manifestPath, {
428
+ profile: asString(args.profile),
429
+ skillItemIds: toStringArray(args['skill-item-id']),
430
+ agentItemIds: toStringArray(args['agent-item-id']),
431
+ });
432
+ const mcp = new RegistryOperatorMcpClient({ mcpOrigin: env.MCP_ORIGIN, extraHeaders: cfAccessHeaders(env) });
433
+ const result = await mcp.verifyBootstrap({
434
+ token: mcpToken,
435
+ agentKeys: resolved.agents.map((agent) => agent.agent_key),
436
+ skillKeys: resolved.skills.map((skill) => skill.draft.skill_key),
437
+ });
438
+ console.log(JSON.stringify(result, null, 2));
439
+ }
440
+ // Verify a published version before loading it: server verdicts plus
441
+ // independent client-side checks (canonical digest recomputation and detached
442
+ // signature verification against trusted keys fetched from the registry).
443
+ // Non-strict mode passes for a publication with no signatures (vacuous
444
+ // validity); --strict additionally requires the server verdict, at least one
445
+ // valid signature, and a matching frozen-envelope artifact when present.
446
+ /**
447
+ * Resolve trusted signing keys to their PEMs (stored as CAS artifacts),
448
+ * mirroring the registry's resolver: the key must be `trusted` and inside
449
+ * its validity window before its PEM is used. Revoked/expired/not-yet-valid
450
+ * keys stay absent so local verdicts match the server's
451
+ * `trusted_public_key_resolved` semantics (a revoked key's signatures must
452
+ * read as invalid, not verified).
453
+ */
454
+ async function loadTrustedPublicKeyPems(api, keyRefs, apiToken) {
455
+ const publicKeys = new Map();
456
+ const now = new Date().toISOString();
457
+ for (const keyRef of new Set(keyRefs)) {
458
+ if (!keyRef)
459
+ continue;
460
+ try {
461
+ const key = await api.getPublicKey(keyRef, apiToken);
462
+ const publicKey = key['public_key'];
463
+ const properties = publicKey?.properties;
464
+ if (!properties || !isTrustedKeyUsableAt(properties, now))
465
+ continue;
466
+ const artifacts = Array.isArray(key['artifacts']) ? key['artifacts'] : [];
467
+ const sha = parseArtifactUrnSha256(artifacts[0]?.artifact_urn);
468
+ if (!sha)
469
+ continue;
470
+ const { bytes } = await api.getArtifactBytes(sha, apiToken);
471
+ publicKeys.set(keyRef, new TextDecoder().decode(bytes));
472
+ }
473
+ catch {
474
+ // Unresolvable or untrusted keys stay absent; their signatures fail verification.
475
+ }
476
+ }
477
+ return publicKeys;
478
+ }
479
+ async function runVerifyPublication(env, args) {
480
+ const skillKey = asString(args.skill);
481
+ const agentKey = asString(args.agent);
482
+ const version = Number(asString(args.version));
483
+ const strict = args.strict === true;
484
+ const apiToken = asString(args['api-token']);
485
+ if ((!skillKey && !agentKey) || (skillKey && agentKey) || !Number.isInteger(version) || version <= 0) {
486
+ throw new Error('Usage: registry-operator verify publication (--skill <key> | --agent <key>) --version <n> [--strict] [--api-token <token>]');
487
+ }
488
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
489
+ const envelope = skillKey
490
+ ? await api.getSkillPublicationEnvelope(skillKey, version, apiToken)
491
+ : await api.getAgentPublicationEnvelope(agentKey, version, apiToken);
492
+ const serverVerification = skillKey
493
+ ? await api.getSkillPublicationVerification(skillKey, version, apiToken)
494
+ : await api.getAgentPublicationVerification(agentKey, version, apiToken);
495
+ const signatures = Array.isArray(envelope['detached_signatures'])
496
+ ? envelope['detached_signatures']
497
+ : [];
498
+ // Resolve every trusted signing key to its PEM, enforcing the same trust
499
+ // status + validity window as the registry. Keyless signatures carry no
500
+ // registered key: their trust policy lives with the registry, so their
501
+ // verdict is taken from the server verification.
502
+ const publicKeys = await loadTrustedPublicKeyPems(api, signatures
503
+ .filter((signature) => !signature.keyless)
504
+ .map((signature) => signature.key_ref)
505
+ .filter((keyRef) => Boolean(keyRef)), apiToken);
506
+ const clientVerdict = verifyEnvelopeSignatures({
507
+ envelope: {
508
+ canonical_json: String(envelope['canonical_json'] ?? ''),
509
+ canonical_json_sha256: String(envelope['canonical_json_sha256'] ?? ''),
510
+ detached_signatures: signatures.map((signature) => ({
511
+ key_ref: signature.key_ref ?? '',
512
+ algorithm: signature.algorithm ?? '',
513
+ ...(signature.signed_payload ? { signed_payload: signature.signed_payload } : {}),
514
+ envelope_sha256: signature.envelope_sha256 ?? '',
515
+ signature: signature.signature ?? '',
516
+ })),
517
+ },
518
+ resolvePublicKey: (keyRef) => publicKeys.get(keyRef),
519
+ });
520
+ const serverChecks = Array.isArray(serverVerification['signature_checks'])
521
+ ? serverVerification['signature_checks']
522
+ : [];
523
+ const serverCheckByArtifact = new Map(serverChecks.map((check) => [check.artifact_urn ?? '', check]));
524
+ // Merge client-side verdicts (trusted keys) with server-derived keyless
525
+ // verdicts. The helper maps signatures 1:1, so index alignment holds.
526
+ const combinedSignatures = signatures.map((signature, index) => {
527
+ if (signature.keyless) {
528
+ const signedPayload = signature.signed_payload ?? 'canonical_json';
529
+ const expectedDigest = signedPayload === 'canonical_rdf'
530
+ ? (typeof envelope['canonical_rdf_sha256'] === 'string'
531
+ ? envelope['canonical_rdf_sha256']
532
+ : undefined)
533
+ : String(envelope['canonical_json_sha256'] ?? '');
534
+ const digestMatches = expectedDigest !== undefined && expectedDigest.length > 0 && signature.envelope_sha256 === expectedDigest;
535
+ const serverCheck = serverCheckByArtifact.get(signature.artifact_urn ?? '') ??
536
+ serverChecks.find((check) => check.key_ref === signature.key_ref);
537
+ const keylessVerified = serverCheck?.keyless?.verified === true;
538
+ return {
539
+ key_ref: signature.key_ref ?? '',
540
+ algorithm: signature.algorithm ?? '',
541
+ signed_payload: signedPayload,
542
+ digest_matches: digestMatches,
543
+ signature_valid: digestMatches && keylessVerified,
544
+ signature_kind: 'keyless',
545
+ keyless: {
546
+ identity: serverCheck?.keyless?.identity ?? signature.keyless.identity ?? '',
547
+ issuer: serverCheck?.keyless?.issuer ?? signature.keyless.issuer ?? '',
548
+ verified: keylessVerified,
549
+ ...(serverCheck?.keyless?.failure_kind ? { failure_kind: serverCheck.keyless.failure_kind } : {}),
550
+ ...(serverCheck?.keyless?.error ? { error: serverCheck.keyless.error } : {}),
551
+ ...(serverCheck?.keyless?.validity_evaluated_at
552
+ ? { validity_evaluated_at: serverCheck.keyless.validity_evaluated_at }
553
+ : {}),
554
+ ...(serverCheck?.keyless?.tlog ? { tlog: serverCheck.keyless.tlog } : {}),
555
+ },
556
+ };
557
+ }
558
+ return { ...clientVerdict.signatures[index], signature_kind: 'trusted_key' };
559
+ });
560
+ const allSignaturesValid = combinedSignatures.every((signature) => signature.signature_valid);
561
+ const serverStatus = String(serverVerification['verification_status'] ?? 'unknown');
562
+ const validSignatures = combinedSignatures.filter((signature) => signature.signature_valid).length;
563
+ const frozenPresent = serverVerification['publication_envelope_artifact_present'] === true;
564
+ const strictFailures = [];
565
+ if (strict) {
566
+ if (serverStatus !== 'verified')
567
+ strictFailures.push(`server verification_status is ${serverStatus}`);
568
+ if (validSignatures === 0)
569
+ strictFailures.push('no valid detached signature');
570
+ if (frozenPresent && serverVerification['publication_envelope_artifact_sha256_matches'] === false) {
571
+ strictFailures.push('frozen envelope artifact digest mismatch');
572
+ }
573
+ }
574
+ const verified = clientVerdict.canonical_json_sha256_matches && allSignaturesValid && strictFailures.length === 0;
575
+ console.log(JSON.stringify({
576
+ publication_urn: envelope['publication_urn'] ?? null,
577
+ strict,
578
+ server: {
579
+ verification_status: serverStatus,
580
+ transparency_verification_status: serverVerification['transparency_verification_status'] ?? null,
581
+ publication_envelope_artifact_present: frozenPresent,
582
+ publication_envelope_artifact_sha256_matches: serverVerification['publication_envelope_artifact_sha256_matches'] ?? null,
583
+ live_envelope_matches_frozen_artifact: serverVerification['live_envelope_matches_frozen_artifact'] ?? null,
584
+ },
585
+ client: {
586
+ canonical_json_sha256_matches: clientVerdict.canonical_json_sha256_matches,
587
+ all_signatures_valid: allSignaturesValid,
588
+ signatures: combinedSignatures,
589
+ },
590
+ valid_signatures: validSignatures,
591
+ strict_failures: strictFailures,
592
+ verdict: verified ? 'verified' : 'unverified',
593
+ }, null, 2));
594
+ if (!verified) {
595
+ throw new Error('Publication did not verify.');
596
+ }
597
+ }
598
+ async function runVerifyProvenance(env, args) {
599
+ const skillKey = asString(args.skill);
600
+ const agentKey = asString(args.agent);
601
+ const version = Number(asString(args.version));
602
+ const strict = args.strict === true;
603
+ const apiToken = asString(args['api-token']);
604
+ if ((!skillKey && !agentKey) || (skillKey && agentKey) || !Number.isInteger(version) || version <= 0) {
605
+ throw new Error('Usage: registry-operator verify provenance (--skill <key> | --agent <key>) --version <n> [--strict] [--api-token <token>]');
606
+ }
607
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
608
+ const provenance = skillKey
609
+ ? await api.getSkillProvenance(skillKey, version, apiToken)
610
+ : await api.getAgentProvenance(agentKey, version, apiToken);
611
+ const evidence = provenance['evidence'];
612
+ const currentSha = typeof evidence?.canonical_rdf_sha256 === 'string' ? evidence.canonical_rdf_sha256 : undefined;
613
+ if (!currentSha) {
614
+ throw new Error('Provenance response did not include the canonical export evidence.');
615
+ }
616
+ // Transport integrity: fetch the canonical artifact at its digest and
617
+ // recompute the hash locally.
618
+ const { bytes: currentBytes } = await api.getArtifactBytes(currentSha, apiToken);
619
+ const transportDigestMatches = sha256Hex(currentBytes) === currentSha;
620
+ const servedSignatures = Array.isArray(provenance['provenance_signatures'])
621
+ ? provenance['provenance_signatures']
622
+ : [];
623
+ // Resolve every trusted signing key to its PEM, enforcing the same trust
624
+ // status + validity window as the registry.
625
+ const publicKeys = await loadTrustedPublicKeyPems(api, servedSignatures.map((row) => row.key_ref).filter((keyRef) => Boolean(keyRef)), apiToken);
626
+ // Reproduce each verdict locally: fetch the stored signature record, the
627
+ // canonical artifact it binds, and check the crypto against the key.
628
+ const signatures = [];
629
+ for (const row of servedSignatures) {
630
+ const recordSha = parseArtifactUrnSha256(row.artifact_urn);
631
+ let record = null;
632
+ try {
633
+ if (recordSha) {
634
+ const { bytes } = await api.getArtifactBytes(recordSha, apiToken);
635
+ record = JSON.parse(new TextDecoder().decode(bytes));
636
+ }
637
+ }
638
+ catch {
639
+ // Missing/unreadable signature record: the signature fails verification.
640
+ }
641
+ const key_ref = typeof record?.['key_ref'] === 'string' ? record['key_ref'] : (row.key_ref ?? '');
642
+ const algorithm = typeof record?.['algorithm'] === 'string' ? record['algorithm'] : (row.algorithm ?? '');
643
+ const provenance_sha256 = typeof record?.['provenance_sha256'] === 'string' ? record['provenance_sha256'] : (row.provenance_sha256 ?? '');
644
+ const signature = typeof record?.['signature'] === 'string' ? record['signature'] : undefined;
645
+ if (!signature || !provenance_sha256) {
646
+ signatures.push({ key_ref, algorithm, provenance_sha256, digest_matches: false, signature_valid: false, verdict: 'invalid' });
647
+ continue;
648
+ }
649
+ let signedBytes = null;
650
+ try {
651
+ const { bytes } = await api.getArtifactBytes(provenance_sha256, apiToken);
652
+ signedBytes = bytes;
653
+ }
654
+ catch {
655
+ // Missing/unreadable signed artifact: the signature fails verification.
656
+ }
657
+ if (!signedBytes) {
658
+ signatures.push({ key_ref, algorithm, provenance_sha256, digest_matches: false, signature_valid: false, verdict: 'invalid' });
659
+ continue;
660
+ }
661
+ signatures.push(verifyProvenanceSignature({
662
+ canonicalRdfBytes: signedBytes,
663
+ currentProvenanceSha256: currentSha,
664
+ signature: { key_ref, algorithm, provenance_sha256, signature },
665
+ resolvePublicKey: (ref) => publicKeys.get(ref),
666
+ }));
667
+ }
668
+ const validSignatures = signatures.filter((check) => check.verdict === 'valid').length;
669
+ const staleSignatures = signatures.filter((check) => check.verdict === 'stale').length;
670
+ const invalidSignatures = signatures.filter((check) => check.verdict === 'invalid').length;
671
+ const strictFailures = strict && validSignatures === 0 ? ['no current provenance signature'] : [];
672
+ const verified = transportDigestMatches && invalidSignatures === 0 && strictFailures.length === 0;
673
+ console.log(JSON.stringify({
674
+ entity: provenance['entity'] ?? null,
675
+ strict,
676
+ current_provenance_sha256: currentSha,
677
+ transport_digest_matches: transportDigestMatches,
678
+ signatures,
679
+ valid_signatures: validSignatures,
680
+ stale_signatures: staleSignatures,
681
+ invalid_signatures: invalidSignatures,
682
+ strict_failures: strictFailures,
683
+ verdict: verified ? 'verified' : 'unverified',
684
+ }, null, 2));
685
+ if (!verified) {
686
+ throw new Error('Provenance did not verify.');
687
+ }
688
+ }
689
+ async function runVerifyReportSignatures(env, args) {
690
+ const skillKey = asString(args.skill);
691
+ const agentKey = asString(args.agent);
692
+ const version = Number(asString(args.version));
693
+ const strict = args.strict === true;
694
+ const apiToken = asString(args['api-token']);
695
+ if ((!skillKey && !agentKey) || (skillKey && agentKey) || !Number.isInteger(version) || version <= 0) {
696
+ throw new Error('Usage: registry-operator verify report-signatures (--skill <key> | --agent <key>) --version <n> [--strict] [--api-token <token>]');
697
+ }
698
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
699
+ const served = skillKey
700
+ ? await api.getSkillReportSignatures(skillKey, version, apiToken)
701
+ : await api.getAgentReportSignatures(agentKey, version, apiToken);
702
+ const rows = Array.isArray(served['report_signatures'])
703
+ ? served['report_signatures']
704
+ : [];
705
+ // Resolve every trusted signing key to its PEM, enforcing the same trust
706
+ // status + validity window as the registry.
707
+ const publicKeys = await loadTrustedPublicKeyPems(api, rows.map((row) => row.key_ref).filter((keyRef) => Boolean(keyRef)), apiToken);
708
+ // Reproduce each verdict locally: the stored signature record, the target
709
+ // report (must still declare the signed digest), and the canonical RDF
710
+ // artifact the signature binds.
711
+ const signatures = [];
712
+ for (const row of rows) {
713
+ const recordSha = parseArtifactUrnSha256(row.artifact_urn);
714
+ let record = null;
715
+ try {
716
+ if (recordSha) {
717
+ const { bytes } = await api.getArtifactBytes(recordSha, apiToken);
718
+ record = JSON.parse(new TextDecoder().decode(bytes));
719
+ }
720
+ }
721
+ catch {
722
+ // Missing/unreadable signature record: the row fails verification.
723
+ }
724
+ const key_ref = typeof record?.['key_ref'] === 'string' ? record['key_ref'] : (row.key_ref ?? '');
725
+ const algorithm = typeof record?.['algorithm'] === 'string' ? record['algorithm'] : (row.algorithm ?? '');
726
+ const report_artifact_urn = typeof record?.['report_artifact_urn'] === 'string' ? record['report_artifact_urn'] : (row.report_artifact_urn ?? '');
727
+ const report_canonical_rdf_sha256 = typeof record?.['report_canonical_rdf_sha256'] === 'string'
728
+ ? record['report_canonical_rdf_sha256']
729
+ : (row.report_canonical_rdf_sha256 ?? '');
730
+ const signature = typeof record?.['signature'] === 'string' ? record['signature'] : undefined;
731
+ const failRow = {
732
+ key_ref,
733
+ algorithm,
734
+ report_artifact_present: false,
735
+ digest_matches: false,
736
+ signature_valid: false,
737
+ verdict: 'invalid',
738
+ };
739
+ if (!signature || !report_canonical_rdf_sha256) {
740
+ signatures.push(failRow);
741
+ continue;
742
+ }
743
+ const reportSha = parseArtifactUrnSha256(report_artifact_urn);
744
+ let report_artifact_present = false;
745
+ try {
746
+ if (reportSha) {
747
+ const { bytes } = await api.getArtifactBytes(reportSha, apiToken);
748
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
749
+ report_artifact_present = parsed.payload?.rdf?.canonical_rdf_sha256 === report_canonical_rdf_sha256;
750
+ }
751
+ }
752
+ catch {
753
+ report_artifact_present = false;
754
+ }
755
+ let signedBytes = null;
756
+ try {
757
+ const { bytes } = await api.getArtifactBytes(report_canonical_rdf_sha256, apiToken);
758
+ signedBytes = bytes;
759
+ }
760
+ catch {
761
+ // Missing/unreadable canonical artifact: the signature fails verification.
762
+ }
763
+ if (!signedBytes) {
764
+ signatures.push({ ...failRow, report_artifact_present });
765
+ continue;
766
+ }
767
+ const check = verifyProvenanceSignature({
768
+ canonicalRdfBytes: signedBytes,
769
+ signature: { key_ref, algorithm, provenance_sha256: report_canonical_rdf_sha256, signature },
770
+ resolvePublicKey: (ref) => publicKeys.get(ref),
771
+ });
772
+ signatures.push({
773
+ key_ref: check.key_ref,
774
+ algorithm: check.algorithm,
775
+ report_artifact_present,
776
+ digest_matches: check.digest_matches,
777
+ signature_valid: check.signature_valid,
778
+ verdict: report_artifact_present && check.verdict === 'valid' ? 'valid' : 'invalid',
779
+ });
780
+ }
781
+ const validSignatures = signatures.filter((check) => check.verdict === 'valid').length;
782
+ const invalidSignatures = signatures.filter((check) => check.verdict === 'invalid').length;
783
+ const strictFailures = strict && validSignatures === 0 ? ['no valid report signature'] : [];
784
+ const verified = invalidSignatures === 0 && strictFailures.length === 0;
785
+ console.log(JSON.stringify({
786
+ strict,
787
+ report_signatures: signatures,
788
+ valid_signatures: validSignatures,
789
+ invalid_signatures: invalidSignatures,
790
+ strict_failures: strictFailures,
791
+ verdict: verified ? 'verified' : 'unverified',
792
+ }, null, 2));
793
+ if (!verified) {
794
+ throw new Error('Report signatures did not verify.');
795
+ }
796
+ }
797
+ async function runVerifyArtifact(env, args) {
798
+ const apiToken = asString(args['api-token']);
799
+ const sha256 = asString(args.sha256) ?? parseArtifactUrnSha256(asString(args['artifact-urn']));
800
+ if (!sha256 || !/^[0-9a-f]{64}$/.test(sha256)) {
801
+ throw new Error('Usage: registry-operator verify artifact (--sha256 <hex> | --artifact-urn <urn>) [--api-token <token>]');
802
+ }
803
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
804
+ const { bytes, contentDigest } = await api.getArtifactBytes(sha256, apiToken);
805
+ const computed = sha256Hex(bytes);
806
+ const contentDigestMatches = contentDigest ? contentDigestMatchesSha256(contentDigest, sha256) : null;
807
+ const digestVerified = computed === sha256 && contentDigestMatches !== false;
808
+ console.log(JSON.stringify({
809
+ sha256,
810
+ size_bytes: bytes.byteLength,
811
+ computed_sha256: computed,
812
+ digest_verified: digestVerified,
813
+ content_digest: contentDigest ?? null,
814
+ content_digest_matches: contentDigestMatches,
815
+ }, null, 2));
816
+ if (!digestVerified) {
817
+ throw new Error('Artifact bytes do not match their digest.');
818
+ }
819
+ }
820
+ function parseArtifactUrnSha256(urn) {
821
+ const match = urn ? /^urn:sg:artifact:sha256:([0-9a-f]{64})$/.exec(urn) : null;
822
+ return match?.[1];
823
+ }
824
+ // RFC 9530 Content-Digest structured field: sha-256=:BASE64:
825
+ function contentDigestMatchesSha256(header, sha256HexValue) {
826
+ const match = /sha-256=:([^:]+):/.exec(header);
827
+ if (!match)
828
+ return true;
829
+ return match[1] === Buffer.from(sha256HexValue, 'hex').toString('base64');
830
+ }
831
+ async function runVerifyOktaConfig(env) {
832
+ const result = await validateOktaConfig(env);
833
+ console.log(JSON.stringify(result, null, 2));
834
+ }
835
+ async function runVerifyBrowserSession(env, args) {
836
+ await waitForApiAndGraphReadiness(env);
837
+ await waitForHttpService('webapp', new URL('/healthz', env.WEBAPP_ORIGIN));
838
+ const okta = await validateOktaConfig(env);
839
+ const graphBackend = await detectGraphBackend(env);
840
+ const apiHealth = await fetchHealth(new URL('/healthz', env.API_ORIGIN));
841
+ const webappHealth = await fetchHealth(new URL('/healthz', env.WEBAPP_ORIGIN));
842
+ const manifestPath = asString(args.manifest);
843
+ console.log(JSON.stringify({
844
+ okta,
845
+ graph_backend: graphBackend,
846
+ api_health: apiHealth,
847
+ webapp_health: webappHealth,
848
+ ...(manifestPath ? { manifest: resolveManifestPath(env, manifestPath) } : {}),
849
+ next_step: 'Follow service/webapp/knowledge-manager/OKTA_BROWSER_FLOW_RUNBOOK.md for the real browser-based allowed/denied proof.',
850
+ }, null, 2));
851
+ }
852
+ async function runBootstrapTest(env, args) {
853
+ const manifestPath = resolveManifestPath(env, asString(args.manifest));
854
+ const doReset = Boolean(args.reset);
855
+ const doUp = Boolean(args.up);
856
+ const lane = asString(args.lane) ?? 'api-mcp';
857
+ if (doReset) {
858
+ await runLocalReset(env, { force: args.force });
859
+ }
860
+ if (doUp) {
861
+ await runLocalUp(env);
862
+ }
863
+ await waitForApiAndGraphReadiness(env);
864
+ await waitForMcpAndGraphReadiness(env);
865
+ const apiToken = asString(args['api-token']);
866
+ const mcpToken = asString(args['mcp-token']);
867
+ const apiKey = apiToken
868
+ ? { token: apiToken, key_id: 'provided', owner_label: 'provided' }
869
+ : await createApiKey(env, 'api', asString(args['api-owner-label']) ?? 'Registry Operator API');
870
+ const mcpKey = mcpToken
871
+ ? { token: mcpToken, key_id: 'provided', owner_label: 'provided' }
872
+ : await createApiKey(env, 'mcp', asString(args['mcp-owner-label']) ?? 'Registry Operator MCP');
873
+ const manifest = await readBootstrapManifest(manifestPath);
874
+ const resolved = resolveBootstrapManifest(manifest, manifestPath, {
875
+ profile: asString(args.profile),
876
+ skillItemIds: toStringArray(args['skill-item-id']),
877
+ agentItemIds: toStringArray(args['agent-item-id']),
878
+ });
879
+ const graphBackend = await detectGraphBackend(env);
880
+ if (args['dry-run']) {
881
+ console.log(JSON.stringify({ ok: true, lane, graph_backend: graphBackend, resolved }, null, 2));
882
+ return;
883
+ }
884
+ await seedResolvedBootstrapManifest(env, resolved, apiKey.token);
885
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
886
+ const verifiedSkillKeys = [];
887
+ for (const skill of resolved.skills) {
888
+ await api.getActiveSkillVersion(skill.draft.skill_key, apiKey.token);
889
+ verifiedSkillKeys.push(skill.draft.skill_key);
890
+ }
891
+ const verifiedAgentKeys = [];
892
+ for (const agent of resolved.agents) {
893
+ await api.getAgent(agent.agent_key, apiKey.token);
894
+ verifiedAgentKeys.push(agent.agent_key);
895
+ }
896
+ const mcp = new RegistryOperatorMcpClient({ mcpOrigin: env.MCP_ORIGIN, extraHeaders: cfAccessHeaders(env) });
897
+ const mcpResult = await mcp.verifyBootstrap({
898
+ token: mcpKey.token,
899
+ agentKeys: resolved.agents.map((agent) => agent.agent_key),
900
+ skillKeys: resolved.skills.map((skill) => skill.draft.skill_key),
901
+ });
902
+ let oktaLane;
903
+ if (lane === 'okta-browser') {
904
+ const okta = await validateOktaConfig(env);
905
+ const apiHealth = await fetchHealth(new URL('/healthz', env.API_ORIGIN));
906
+ const webappHealth = await fetchHealth(new URL('/healthz', env.WEBAPP_ORIGIN));
907
+ oktaLane = {
908
+ okta,
909
+ api_health: apiHealth,
910
+ webapp_health: webappHealth,
911
+ next_browser_step: 'Use service/webapp/knowledge-manager/OKTA_BROWSER_FLOW_RUNBOOK.md to complete the real browser login and allowed/denied write proof over the seeded content.',
912
+ };
913
+ }
914
+ const cursorMcpConfig = buildCursorMcpConfig(env, mcpKey.token);
915
+ const nextPrompts = buildNextPrompts(resolved);
916
+ const mockOktaDemoCommand = buildMockOktaDemoCommand(env);
917
+ const artifacts = await writeBootstrapRunArtifacts(env, {
918
+ manifestPath,
919
+ lane,
920
+ graphBackend,
921
+ resolved,
922
+ apiKey,
923
+ mcpKey,
924
+ cursorMcpConfig,
925
+ nextPrompts,
926
+ mockOktaDemoCommand,
927
+ seededSkills: verifiedSkillKeys,
928
+ seededAgents: verifiedAgentKeys,
929
+ mcpResult,
930
+ oktaLane,
931
+ });
932
+ console.log(JSON.stringify({
933
+ ok: true,
934
+ lane,
935
+ ...(resolved.pack ? { pack: resolved.pack } : {}),
936
+ ...(resolved.profile ? { profile: resolved.profile } : {}),
937
+ graph_backend: graphBackend,
938
+ seeded_skills: verifiedSkillKeys,
939
+ seeded_agents: verifiedAgentKeys,
940
+ api_token: apiKey.token,
941
+ mcp_token: mcpKey.token,
942
+ mcp: mcpResult,
943
+ artifacts,
944
+ cursor_mcp_config: cursorMcpConfig,
945
+ next_prompts: nextPrompts,
946
+ mock_okta_demo_command: mockOktaDemoCommand,
947
+ ...(oktaLane ? { okta_lane: oktaLane } : {}),
948
+ next_manual_step: 'Paste cursor_mcp_config into your MCP client, then run the prompts in next_prompts.',
949
+ }, null, 2));
950
+ }
951
+ async function seedResolvedBootstrapManifest(env, manifest, apiToken) {
952
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
953
+ const signer = manifest.signing?.enabled
954
+ ? await prepareDemoSigner(env, api, apiToken, manifest.signing.owner)
955
+ : undefined;
956
+ for (const skill of manifest.skills) {
957
+ const drafted = await api.createSkillDraft(skill, apiToken);
958
+ await api.validateSkillVersion({
959
+ skill_key: skill.draft.skill_key,
960
+ version: drafted.version,
961
+ author: skill.draft.author,
962
+ ...(skill.validateNote ? { note: skill.validateNote } : {}),
963
+ }, apiToken);
964
+ if (signer) {
965
+ await signAndPublishSeededSkill(api, apiToken, signer, {
966
+ skill_key: skill.draft.skill_key,
967
+ version: drafted.version,
968
+ author: skill.draft.author,
969
+ ...(skill.publishNote ? { note: skill.publishNote } : {}),
970
+ });
971
+ }
972
+ else {
973
+ await api.publishSkillVersion({
974
+ skill_key: skill.draft.skill_key,
975
+ version: drafted.version,
976
+ author: skill.draft.author,
977
+ ...(skill.publishNote ? { note: skill.publishNote } : {}),
978
+ }, apiToken);
979
+ }
980
+ if (skill.certify) {
981
+ await api.certifySkillVersion({
982
+ skill_key: skill.draft.skill_key,
983
+ version: drafted.version,
984
+ author: skill.draft.author,
985
+ ...(skill.certifyNote ? { note: skill.certifyNote } : {}),
986
+ }, apiToken);
987
+ }
988
+ }
989
+ for (const agent of manifest.agents) {
990
+ await api.createAgent(agent, apiToken);
991
+ }
992
+ void env;
993
+ }
994
+ const DEMO_SIGNING_KEY_REF = 'demo://signet/demo-signing-key';
995
+ // Demo signing keys are generated on first use and persisted under
996
+ // data/registry-operator/ (never committed), so re-seeding keeps the same
997
+ // trusted key instead of accumulating fresh ones.
998
+ async function prepareDemoSigner(env, api, apiToken, owner) {
999
+ const signingKeyPath = path.join(env.REPO_ROOT, RUN_ARTIFACTS_RELATIVE_DIR, 'demo-signing-key.pem');
1000
+ let privateKey;
1001
+ try {
1002
+ privateKey = createPrivateKey(await readFile(signingKeyPath, 'utf8'));
1003
+ }
1004
+ catch {
1005
+ const pair = generateKeyPairSync('ed25519');
1006
+ privateKey = pair.privateKey;
1007
+ await mkdir(path.dirname(signingKeyPath), { recursive: true });
1008
+ await writeFile(signingKeyPath, privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), {
1009
+ mode: 0o600,
1010
+ });
1011
+ }
1012
+ const publicKeyPem = createPublicKey(privateKey).export({ type: 'spki', format: 'pem' }).toString();
1013
+ try {
1014
+ await api.createTrustedPublicKey({
1015
+ key_ref: DEMO_SIGNING_KEY_REF,
1016
+ algorithm: 'ed25519',
1017
+ public_key_pem: publicKeyPem,
1018
+ owner,
1019
+ }, apiToken);
1020
+ }
1021
+ catch (err) {
1022
+ // Already registered by a previous seed run.
1023
+ if (!(err instanceof RegistryOperatorApiError) || err.status !== 409)
1024
+ throw err;
1025
+ }
1026
+ return { keyRef: DEMO_SIGNING_KEY_REF, owner, privateKey };
1027
+ }
1028
+ // Single-request sign-then-publish: prepare pins the exact envelope publish
1029
+ // will freeze, the client signs those bytes, and one publish request freezes
1030
+ // the signed payload. Re-seeding an already-published version (prepare
1031
+ // conflicts) falls back to the envelope-attach semantics so an existing
1032
+ // signature is detected instead of duplicated, and a published-but-unsigned
1033
+ // version can still be repaired.
1034
+ async function signAndPublishSeededSkill(api, apiToken, signer, input) {
1035
+ let prepared;
1036
+ try {
1037
+ prepared = await api.prepareSkillPublication(input.skill_key, input.version, {
1038
+ author: input.author,
1039
+ ...(input.note ? { note: input.note } : {}),
1040
+ }, apiToken);
1041
+ }
1042
+ catch (err) {
1043
+ if (err instanceof RegistryOperatorApiError && err.code === 'SKILL_VERSION_PREPARE_CONFLICT') {
1044
+ await signSeededSkill(api, apiToken, signer, input);
1045
+ return;
1046
+ }
1047
+ throw err;
1048
+ }
1049
+ const canonicalJson = prepared['canonical_json'];
1050
+ const preparedPublicationUrn = prepared['prepared_publication_urn'];
1051
+ if (typeof canonicalJson !== 'string' ||
1052
+ canonicalJson.length === 0 ||
1053
+ typeof preparedPublicationUrn !== 'string') {
1054
+ throw new Error(`Prepared publication unavailable for signing ${input.skill_key}@v${input.version}.`);
1055
+ }
1056
+ const signature = `base64:${signBytes(null, Buffer.from(canonicalJson, 'utf8'), signer.privateKey).toString('base64')}`;
1057
+ await api.publishSkillVersion({
1058
+ skill_key: input.skill_key,
1059
+ version: input.version,
1060
+ author: input.author,
1061
+ ...(input.note ? { note: input.note } : {}),
1062
+ prepared_publication_urn: preparedPublicationUrn,
1063
+ signatures: [{ signer: signer.owner, key_ref: signer.keyRef, algorithm: 'ed25519', signature }],
1064
+ }, apiToken);
1065
+ }
1066
+ async function signSeededSkill(api, apiToken, signer, input) {
1067
+ const envelope = await api.getSkillPublicationEnvelope(input.skill_key, input.version, apiToken);
1068
+ const signatures = Array.isArray(envelope['detached_signatures'])
1069
+ ? envelope['detached_signatures']
1070
+ : [];
1071
+ if (signatures.some((signature) => signature.key_ref === signer.keyRef)) {
1072
+ return; // Re-seeding: this key already signed the frozen envelope.
1073
+ }
1074
+ const canonicalJson = envelope['canonical_json'];
1075
+ if (typeof canonicalJson !== 'string' || canonicalJson.length === 0) {
1076
+ throw new Error(`Publication envelope unavailable for signing ${input.skill_key}@v${input.version}.`);
1077
+ }
1078
+ const signature = `base64:${signBytes(null, Buffer.from(canonicalJson, 'utf8'), signer.privateKey).toString('base64')}`;
1079
+ await api.createSkillDetachedSignature(input.skill_key, input.version, { signer: signer.owner, key_ref: signer.keyRef, algorithm: 'ed25519', signature }, apiToken);
1080
+ }
1081
+ // Single-request keyless publish: prepare the candidate envelope, exchange
1082
+ // the CI OIDC identity at Fulcio for a short-lived certificate, sign the
1083
+ // exact candidate bytes, and publish with the sigstore bundle in one mutating
1084
+ // request (optionally certifying).
1085
+ async function runSignKeyless(env, args) {
1086
+ const skillKey = asString(args['skill']);
1087
+ const agentKey = asString(args['agent']);
1088
+ const version = Number(asString(args['version']));
1089
+ const author = requireStringArg(args, 'author');
1090
+ const apiToken = requireStringArg(args, 'api-token');
1091
+ const note = asString(args['note']);
1092
+ const fulcioUrl = asString(args['fulcio-url']);
1093
+ const rekorUrl = asString(args['rekor-url']);
1094
+ const oidcToken = asString(args['oidc-token']);
1095
+ if ((!skillKey && !agentKey) || (skillKey && agentKey)) {
1096
+ throw new Error('Missing required --skill or --agent argument (exactly one).');
1097
+ }
1098
+ if (!Number.isInteger(version) || version <= 0) {
1099
+ throw new Error('Missing required --version argument (positive integer).');
1100
+ }
1101
+ const target = skillKey ? `skill ${skillKey}` : `agent ${agentKey}`;
1102
+ const api = new HttpRegistryOperatorApiClient({ apiOrigin: env.API_ORIGIN, extraHeaders: cfAccessHeaders(env) });
1103
+ const prepared = skillKey
1104
+ ? await api.prepareSkillPublication(skillKey, version, {
1105
+ author,
1106
+ ...(note ? { note } : {}),
1107
+ }, apiToken)
1108
+ : await api.prepareAgentPublication(agentKey, version, {
1109
+ author,
1110
+ ...(note ? { note } : {}),
1111
+ }, apiToken);
1112
+ const canonicalJson = prepared['canonical_json'];
1113
+ const preparedPublicationUrn = prepared['prepared_publication_urn'];
1114
+ if (typeof canonicalJson !== 'string' || canonicalJson.length === 0 || typeof preparedPublicationUrn !== 'string') {
1115
+ throw new Error(`Prepared publication unavailable for keyless signing ${target}@v${version}.`);
1116
+ }
1117
+ const signed = await buildKeylessBundle({
1118
+ data: Buffer.from(canonicalJson, 'utf8'),
1119
+ ...(oidcToken ? { oidcToken } : {}),
1120
+ ...(fulcioUrl ? { fulcioBaseURL: fulcioUrl } : {}),
1121
+ ...(rekorUrl ? { rekorBaseURL: rekorUrl } : {}),
1122
+ });
1123
+ const signatures = [{ signer: signed.identity, keyless_bundle: signed.bundle }];
1124
+ if (skillKey) {
1125
+ await api.publishSkillVersion({
1126
+ skill_key: skillKey,
1127
+ version,
1128
+ author,
1129
+ ...(note ? { note } : {}),
1130
+ prepared_publication_urn: preparedPublicationUrn,
1131
+ signatures,
1132
+ }, apiToken);
1133
+ }
1134
+ else {
1135
+ await api.publishAgentVersion({
1136
+ agent_key: agentKey,
1137
+ version,
1138
+ author,
1139
+ ...(note ? { note } : {}),
1140
+ prepared_publication_urn: preparedPublicationUrn,
1141
+ signatures,
1142
+ }, apiToken);
1143
+ }
1144
+ let certified = false;
1145
+ if (args['certify'] === true) {
1146
+ if (skillKey) {
1147
+ await api.certifySkillVersion({
1148
+ skill_key: skillKey,
1149
+ version,
1150
+ author,
1151
+ ...(note ? { note } : {}),
1152
+ }, apiToken);
1153
+ }
1154
+ else {
1155
+ await api.certifyAgentVersion({
1156
+ agent_key: agentKey,
1157
+ version,
1158
+ author,
1159
+ ...(note ? { note } : {}),
1160
+ }, apiToken);
1161
+ }
1162
+ certified = true;
1163
+ }
1164
+ console.log(JSON.stringify({
1165
+ ...(skillKey ? { skill_key: skillKey } : { agent_key: agentKey }),
1166
+ version,
1167
+ identity: signed.identity,
1168
+ issuer: signed.issuer,
1169
+ prepared_publication_urn: preparedPublicationUrn,
1170
+ published: true,
1171
+ certified,
1172
+ }, null, 2));
1173
+ }
1174
+ async function createApiKey(env, plane, ownerLabel) {
1175
+ const serviceDir = plane === 'api' ? path.join(env.REPO_ROOT, 'service', 'api') : path.join(env.REPO_ROOT, 'service', 'mcp');
1176
+ const hostDatabaseUrl = await resolveHostDatabaseUrlForPlane(env, plane);
1177
+ const args = ['run', '--silent', 'create-api-key', '--', '--owner-label', ownerLabel];
1178
+ if (plane === 'api') {
1179
+ // Bootstrap/operator keys need write access: the API defaults
1180
+ // management-created keys to read-only and scope enforcement is on by
1181
+ // default, so seeding would fail with INSUFFICIENT_SCOPE without this.
1182
+ args.push('--scopes', 'read,write');
1183
+ }
1184
+ const result = await runShell('npm', args, {
1185
+ cwd: serviceDir,
1186
+ ...(hostDatabaseUrl ? { env: { DATABASE_URL: hostDatabaseUrl } } : {}),
1187
+ });
1188
+ return AuthCreateApiKeyResultSchema.parse(JSON.parse(result.stdout));
1189
+ }
1190
+ async function readBootstrapManifest(manifestPath) {
1191
+ const raw = JSON.parse(await readFile(manifestPath, 'utf8'));
1192
+ return BootstrapManifestSchema.parse(raw);
1193
+ }
1194
+ function resolveProfile(manifest, profileName) {
1195
+ const profile = manifest.profiles?.[profileName];
1196
+ if (!profile) {
1197
+ throw new Error(`Unknown bootstrap profile: ${profileName}`);
1198
+ }
1199
+ return profile;
1200
+ }
1201
+ function buildSelectionSet(allIds, profileIds, explicitIds) {
1202
+ const ids = explicitIds?.length ? explicitIds : profileIds?.length ? profileIds : allIds;
1203
+ return new Set(ids);
1204
+ }
1205
+ function normalizeSkillRef(ref, builtSkillMap) {
1206
+ if (typeof ref === 'string') {
1207
+ return ref.startsWith('urn:') ? { skill_urn: ref } : { skill_key: ref };
1208
+ }
1209
+ if (ref.skill_item_id) {
1210
+ const resolved = builtSkillMap.get(ref.skill_item_id);
1211
+ if (!resolved) {
1212
+ throw new Error(`Unknown skill_item_id reference: ${ref.skill_item_id}`);
1213
+ }
1214
+ return { skill_key: resolved.draft.skill_key };
1215
+ }
1216
+ return {
1217
+ ...(ref.skill_key ? { skill_key: ref.skill_key } : {}),
1218
+ ...(ref.skill_urn ? { skill_urn: ref.skill_urn } : {}),
1219
+ };
1220
+ }
1221
+ function topologicalOrder(items, idOf, depsOf, label) {
1222
+ const byId = new Map(items.map((item) => [idOf(item), item]));
1223
+ const visiting = new Set();
1224
+ const visited = new Set();
1225
+ const ordered = [];
1226
+ function visit(item) {
1227
+ const id = idOf(item);
1228
+ if (visited.has(id))
1229
+ return;
1230
+ if (visiting.has(id)) {
1231
+ throw new Error(`Cycle detected in ${label} dependencies at ${id}.`);
1232
+ }
1233
+ visiting.add(id);
1234
+ for (const dep of depsOf(item)) {
1235
+ const depItem = byId.get(dep);
1236
+ if (!depItem)
1237
+ continue;
1238
+ visit(depItem);
1239
+ }
1240
+ visiting.delete(id);
1241
+ visited.add(id);
1242
+ ordered.push(item);
1243
+ }
1244
+ for (const item of items) {
1245
+ visit(item);
1246
+ }
1247
+ return ordered;
1248
+ }
1249
+ function parseOptions(argv) {
1250
+ const out = {};
1251
+ for (let i = 0; i < argv.length; i += 1) {
1252
+ const token = argv[i];
1253
+ if (!token?.startsWith('--'))
1254
+ continue;
1255
+ const key = token.slice(2);
1256
+ const next = argv[i + 1];
1257
+ if (!next || next.startsWith('--')) {
1258
+ out[key] = true;
1259
+ continue;
1260
+ }
1261
+ if (key in out) {
1262
+ const current = out[key];
1263
+ out[key] = Array.isArray(current) ? [...current, next] : [String(current), next];
1264
+ }
1265
+ else {
1266
+ out[key] = next;
1267
+ }
1268
+ i += 1;
1269
+ }
1270
+ return out;
1271
+ }
1272
+ function resolveManifestPath(env, provided) {
1273
+ if (provided) {
1274
+ return path.resolve(provided);
1275
+ }
1276
+ return path.join(env.REPO_ROOT, DEFAULT_DEMO_MANIFEST_RELATIVE_PATH);
1277
+ }
1278
+ function resolveSpecPath(specDir, value) {
1279
+ return path.isAbsolute(value) ? value : path.resolve(specDir, value);
1280
+ }
1281
+ function requireStringArg(args, key) {
1282
+ const value = asString(args[key]);
1283
+ if (!value) {
1284
+ throw new Error(`Missing required --${key} argument.`);
1285
+ }
1286
+ return value;
1287
+ }
1288
+ function asString(value) {
1289
+ return typeof value === 'string' ? value : undefined;
1290
+ }
1291
+ /** Overlay `--cf-access-client-id/-secret` flags onto env (env still wins if no flag). */
1292
+ function applyCfAccessArgs(env, args) {
1293
+ const id = asString(args['cf-access-client-id']);
1294
+ const secret = asString(args['cf-access-client-secret']);
1295
+ if (id)
1296
+ env.SIGNET_CF_ACCESS_CLIENT_ID = id;
1297
+ if (secret)
1298
+ env.SIGNET_CF_ACCESS_CLIENT_SECRET = secret;
1299
+ }
1300
+ function toStringArray(value) {
1301
+ if (Array.isArray(value)) {
1302
+ return value;
1303
+ }
1304
+ if (typeof value === 'string') {
1305
+ return [value];
1306
+ }
1307
+ return undefined;
1308
+ }
1309
+ function readObjectField(value, key) {
1310
+ const candidate = value?.[key];
1311
+ return candidate && typeof candidate === 'object' && !Array.isArray(candidate)
1312
+ ? candidate
1313
+ : undefined;
1314
+ }
1315
+ function readArrayField(value, key) {
1316
+ const candidate = value?.[key];
1317
+ return Array.isArray(candidate)
1318
+ ? candidate.filter((item) => Boolean(item) && typeof item === 'object')
1319
+ : [];
1320
+ }
1321
+ function readStringField(value, key) {
1322
+ const candidate = value?.[key];
1323
+ return typeof candidate === 'string' ? candidate : undefined;
1324
+ }
1325
+ function readBooleanField(value, key) {
1326
+ const candidate = value?.[key];
1327
+ return typeof candidate === 'boolean' ? candidate : undefined;
1328
+ }
1329
+ function readNumberField(value, key) {
1330
+ const candidate = value?.[key];
1331
+ return typeof candidate === 'number' ? candidate : undefined;
1332
+ }
1333
+ export async function validateOktaConfig(env) {
1334
+ const apiEnvFile = env.API_ENV_FILE;
1335
+ const webappEnvFile = env.WEBAPP_ENV_FILE;
1336
+ const apiEnv = await readDotEnvFile(apiEnvFile);
1337
+ const webappEnv = await readDotEnvFile(webappEnvFile);
1338
+ const apiMissing = collectMissing(apiEnv, [
1339
+ 'AUTH_MODE',
1340
+ 'OKTA_MODE',
1341
+ 'OKTA_ISSUER',
1342
+ 'OKTA_AUDIENCE',
1343
+ 'OKTA_REQUIRED_SCOPES',
1344
+ 'OKTA_GROUPS_CLAIM',
1345
+ ]);
1346
+ const webappMissing = collectMissing(webappEnv, [
1347
+ 'AUTH_MODE',
1348
+ 'OKTA_MODE',
1349
+ 'OKTA_ISSUER',
1350
+ 'OKTA_CLIENT_ID',
1351
+ 'OKTA_REDIRECT_URI',
1352
+ 'OKTA_SCOPES',
1353
+ 'DATABASE_URL',
1354
+ ]);
1355
+ return {
1356
+ ok: apiMissing.length === 0 && webappMissing.length === 0,
1357
+ api_env_file: apiEnvFile,
1358
+ webapp_env_file: webappEnvFile,
1359
+ api_missing: apiMissing,
1360
+ webapp_missing: webappMissing,
1361
+ api_mode: apiEnv.AUTH_MODE,
1362
+ webapp_mode: webappEnv.AUTH_MODE,
1363
+ };
1364
+ }
1365
+ async function fetchHealth(url) {
1366
+ try {
1367
+ const response = await fetch(url);
1368
+ return {
1369
+ ok: response.ok,
1370
+ status: response.status,
1371
+ };
1372
+ }
1373
+ catch (err) {
1374
+ return {
1375
+ ok: false,
1376
+ error: err instanceof Error ? err.message : String(err),
1377
+ };
1378
+ }
1379
+ }
1380
+ async function readDotEnvFile(filePath) {
1381
+ const content = await readFile(filePath, 'utf8');
1382
+ const values = {};
1383
+ for (const line of content.split(/\r?\n/)) {
1384
+ const trimmed = line.trim();
1385
+ if (!trimmed || trimmed.startsWith('#'))
1386
+ continue;
1387
+ const separator = trimmed.indexOf('=');
1388
+ if (separator <= 0)
1389
+ continue;
1390
+ const key = trimmed.slice(0, separator).trim();
1391
+ const value = trimmed.slice(separator + 1).trim();
1392
+ values[key] = value;
1393
+ }
1394
+ return values;
1395
+ }
1396
+ async function safeReadDotEnvFile(filePath) {
1397
+ return await readDotEnvFile(filePath).catch(() => ({}));
1398
+ }
1399
+ async function readGraphBackendConfigs(env) {
1400
+ const apiEnv = await safeReadDotEnvFile(env.API_ENV_FILE);
1401
+ const mcpEnv = await safeReadDotEnvFile(env.MCP_ENV_FILE);
1402
+ return {
1403
+ api: {
1404
+ backend: apiEnv.REGISTRY_GRAPH_BACKEND ?? 'unknown',
1405
+ ...(apiEnv.REGISTRY_SPARQL_QUERY_URL ? { sparql_query_url: apiEnv.REGISTRY_SPARQL_QUERY_URL } : {}),
1406
+ ...(apiEnv.REGISTRY_SPARQL_UPDATE_URL ? { sparql_update_url: apiEnv.REGISTRY_SPARQL_UPDATE_URL } : {}),
1407
+ ...(apiEnv.REGISTRY_SPARQL_USERNAME ? { sparql_username: apiEnv.REGISTRY_SPARQL_USERNAME } : {}),
1408
+ ...(apiEnv.REGISTRY_SPARQL_PASSWORD ? { sparql_password: apiEnv.REGISTRY_SPARQL_PASSWORD } : {}),
1409
+ },
1410
+ mcp: {
1411
+ backend: mcpEnv.REGISTRY_GRAPH_BACKEND ?? 'unknown',
1412
+ ...(mcpEnv.REGISTRY_SPARQL_QUERY_URL ? { sparql_query_url: mcpEnv.REGISTRY_SPARQL_QUERY_URL } : {}),
1413
+ ...(mcpEnv.REGISTRY_SPARQL_UPDATE_URL ? { sparql_update_url: mcpEnv.REGISTRY_SPARQL_UPDATE_URL } : {}),
1414
+ ...(mcpEnv.REGISTRY_SPARQL_USERNAME ? { sparql_username: mcpEnv.REGISTRY_SPARQL_USERNAME } : {}),
1415
+ ...(mcpEnv.REGISTRY_SPARQL_PASSWORD ? { sparql_password: mcpEnv.REGISTRY_SPARQL_PASSWORD } : {}),
1416
+ },
1417
+ };
1418
+ }
1419
+ async function resolveHostDatabaseUrlForPlane(env, plane) {
1420
+ const envFile = plane === 'api' ? env.API_ENV_FILE : env.MCP_ENV_FILE;
1421
+ const values = await safeReadDotEnvFile(envFile);
1422
+ const databaseUrl = values.DATABASE_URL;
1423
+ if (!databaseUrl)
1424
+ return undefined;
1425
+ return mapContainerFileUrlToHost(databaseUrl, env.REPO_ROOT);
1426
+ }
1427
+ function mapContainerFileUrlToHost(value, repoRoot) {
1428
+ const prefix = 'file:/workspace/data/';
1429
+ if (!value.startsWith(prefix)) {
1430
+ return value;
1431
+ }
1432
+ const relative = value.slice(prefix.length);
1433
+ return `file:${path.join(repoRoot, 'data', relative)}`;
1434
+ }
1435
+ function collectMissing(values, requiredKeys) {
1436
+ return requiredKeys.filter((key) => !(values[key]?.length));
1437
+ }
1438
+ export async function detectGraphBackend(env) {
1439
+ const configs = await readGraphBackendConfigs(env);
1440
+ const apiGraphBackend = configs.api.backend;
1441
+ const mcpGraphBackend = configs.mcp.backend;
1442
+ return {
1443
+ api: {
1444
+ backend: apiGraphBackend,
1445
+ ...(configs.api.sparql_query_url ? { sparql_query_url: normalizeHostFacingUrl(configs.api.sparql_query_url) } : {}),
1446
+ ...(configs.api.sparql_update_url ? { sparql_update_url: normalizeHostFacingUrl(configs.api.sparql_update_url) } : {}),
1447
+ },
1448
+ mcp: {
1449
+ backend: mcpGraphBackend,
1450
+ ...(configs.mcp.sparql_query_url ? { sparql_query_url: normalizeHostFacingUrl(configs.mcp.sparql_query_url) } : {}),
1451
+ ...(configs.mcp.sparql_update_url ? { sparql_update_url: normalizeHostFacingUrl(configs.mcp.sparql_update_url) } : {}),
1452
+ },
1453
+ lane: apiGraphBackend === 'sparql' || mcpGraphBackend === 'sparql'
1454
+ ? 'jena-first'
1455
+ : apiGraphBackend === 'json_file' && mcpGraphBackend === 'json_file'
1456
+ ? 'local-json-default'
1457
+ : 'mixed',
1458
+ };
1459
+ }
1460
+ export function normalizeHostFacingUrl(value) {
1461
+ try {
1462
+ const url = new URL(value);
1463
+ if (url.hostname === 'registry-graph') {
1464
+ url.hostname = 'localhost';
1465
+ }
1466
+ return url.toString();
1467
+ }
1468
+ catch {
1469
+ return value;
1470
+ }
1471
+ }
1472
+ async function waitForApiAndGraphReadiness(env) {
1473
+ await waitForHttpService('api', new URL('/healthz', env.API_ORIGIN));
1474
+ const configs = await readGraphBackendConfigs(env);
1475
+ await waitForSparqlTargets(collectSparqlTargets([configs.api]));
1476
+ }
1477
+ async function waitForMcpAndGraphReadiness(env) {
1478
+ await waitForHttpService('mcp', new URL('/healthz', env.MCP_ORIGIN));
1479
+ const configs = await readGraphBackendConfigs(env);
1480
+ await waitForSparqlTargets(collectSparqlTargets([configs.mcp]));
1481
+ }
1482
+ export function collectSparqlTargets(configs) {
1483
+ const targets = [];
1484
+ const seen = new Set();
1485
+ for (const cfg of configs) {
1486
+ if (cfg.backend !== 'sparql' || !cfg.sparql_query_url)
1487
+ continue;
1488
+ const queryUrl = normalizeHostFacingUrl(cfg.sparql_query_url);
1489
+ const updateUrl = normalizeHostFacingUrl(cfg.sparql_update_url ?? deriveUpdateUrl(cfg.sparql_query_url));
1490
+ const dedupeKey = `${queryUrl}|${updateUrl}|${cfg.sparql_username ?? ''}`;
1491
+ if (seen.has(dedupeKey))
1492
+ continue;
1493
+ seen.add(dedupeKey);
1494
+ targets.push({
1495
+ queryUrl,
1496
+ updateUrl,
1497
+ ...(cfg.sparql_username ? { username: cfg.sparql_username } : {}),
1498
+ ...(cfg.sparql_password ? { password: cfg.sparql_password } : {}),
1499
+ });
1500
+ }
1501
+ return targets;
1502
+ }
1503
+ async function waitForHttpService(name, url, timeoutMs = 90_000) {
1504
+ const startedAt = Date.now();
1505
+ let delayMs = 500;
1506
+ let lastError = 'not started';
1507
+ while (Date.now() - startedAt < timeoutMs) {
1508
+ const health = await fetchHealth(url);
1509
+ if (health.ok) {
1510
+ return;
1511
+ }
1512
+ lastError = 'error' in health ? String(health.error) : `status ${health.status}`;
1513
+ await sleep(delayMs);
1514
+ delayMs = Math.min(delayMs * 2, 5_000);
1515
+ }
1516
+ throw new Error(`Timed out waiting for ${name} readiness at ${url.toString()}: ${lastError}`);
1517
+ }
1518
+ async function waitForSparqlTargets(targets, timeoutMs = 90_000) {
1519
+ for (const target of targets) {
1520
+ await waitForSparqlReady(target, timeoutMs);
1521
+ }
1522
+ }
1523
+ async function waitForSparqlReady(target, timeoutMs) {
1524
+ const startedAt = Date.now();
1525
+ let delayMs = 500;
1526
+ let lastError = 'not ready';
1527
+ while (Date.now() - startedAt < timeoutMs) {
1528
+ try {
1529
+ const headers = new Headers({
1530
+ 'content-type': 'application/sparql-query',
1531
+ accept: 'application/sparql-results+json',
1532
+ });
1533
+ applyBasicAuthHeader(headers, target.username, target.password);
1534
+ const response = await fetch(target.queryUrl, {
1535
+ method: 'POST',
1536
+ headers,
1537
+ body: 'ASK {}',
1538
+ });
1539
+ if (response.ok) {
1540
+ return;
1541
+ }
1542
+ lastError = `status ${response.status}`;
1543
+ }
1544
+ catch (err) {
1545
+ lastError = err instanceof Error ? err.message : String(err);
1546
+ }
1547
+ await sleep(delayMs);
1548
+ delayMs = Math.min(delayMs * 2, 5_000);
1549
+ }
1550
+ throw new Error(`Timed out waiting for SPARQL readiness at ${target.queryUrl}: ${lastError}`);
1551
+ }
1552
+ async function clearSparqlDatasetsForReset(env) {
1553
+ const configs = await readGraphBackendConfigs(env);
1554
+ const targets = collectSparqlTargets([configs.api, configs.mcp]);
1555
+ if (targets.length === 0) {
1556
+ return;
1557
+ }
1558
+ // Both paths below either reach readiness or throw: the first attempt is
1559
+ // given a short window, then the graph service is started and the wait is
1560
+ // repeated without a deadline of its own.
1561
+ try {
1562
+ await waitForSparqlTargets(targets, 5_000);
1563
+ }
1564
+ catch {
1565
+ await runShell('docker', ['compose', '-f', 'docker-compose.yml', '-f', 'docker-compose.override.yml', 'up', '-d', 'registry-graph'], { cwd: path.join(env.REPO_ROOT, 'infra') });
1566
+ await waitForSparqlTargets(targets);
1567
+ }
1568
+ for (const target of targets) {
1569
+ const headers = new Headers({
1570
+ 'content-type': 'application/sparql-update',
1571
+ });
1572
+ applyBasicAuthHeader(headers, target.username, target.password);
1573
+ const response = await fetch(target.updateUrl, {
1574
+ method: 'POST',
1575
+ headers,
1576
+ body: 'CLEAR ALL',
1577
+ });
1578
+ if (!response.ok) {
1579
+ throw new Error(`Failed to clear SPARQL dataset at ${target.updateUrl} (${response.status})`);
1580
+ }
1581
+ }
1582
+ console.log('SPARQL dataset cleared.');
1583
+ }
1584
+ function applyBasicAuthHeader(headers, username, password) {
1585
+ if (!username || !password)
1586
+ return;
1587
+ const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
1588
+ headers.set('authorization', `Basic ${token}`);
1589
+ }
1590
+ function deriveUpdateUrl(queryUrl) {
1591
+ return queryUrl.endsWith('/sparql') ? `${queryUrl.slice(0, -'/sparql'.length)}/update` : queryUrl;
1592
+ }
1593
+ async function sleep(ms) {
1594
+ await new Promise((resolve) => setTimeout(resolve, ms));
1595
+ }
1596
+ function buildCursorMcpConfig(env, mcpToken) {
1597
+ return {
1598
+ mcpServers: {
1599
+ 'signet': {
1600
+ url: new URL('/mcp', env.MCP_ORIGIN).toString(),
1601
+ headers: {
1602
+ Authorization: `Bearer ${mcpToken}`,
1603
+ },
1604
+ },
1605
+ },
1606
+ };
1607
+ }
1608
+ function buildNextPrompts(resolved) {
1609
+ if (resolved.pack?.pack_id === 'blessed-first-user-demo') {
1610
+ return [
1611
+ 'Use registry.list_agents to find the registry demo agent.',
1612
+ 'Use registry.get_agent to load cursor:registry-agent and summarize its linked skills.',
1613
+ 'Use registry.list_skills to find the tame llama skill.',
1614
+ 'Use registry.get_skill to load skill:tame-llama.',
1615
+ 'Now answer: How do we tame a llama?',
1616
+ ];
1617
+ }
1618
+ const firstAgent = resolved.agents[0]?.agent_key;
1619
+ const firstSkill = resolved.skills[0]?.draft.skill_key;
1620
+ return [
1621
+ `Use registry.list_agents to find ${firstAgent ?? 'the seeded agent'}.`,
1622
+ `Use registry.get_agent to load ${firstAgent ?? 'the seeded agent'} and summarize its linked skills.`,
1623
+ `Use registry.list_skills to find ${firstSkill ?? 'the seeded skill'}.`,
1624
+ `Use registry.get_skill to load ${firstSkill ?? 'the seeded skill'}.`,
1625
+ ];
1626
+ }
1627
+ function buildMockOktaDemoCommand(env) {
1628
+ const webappDir = path.join(env.REPO_ROOT, 'service', 'webapp', 'knowledge-manager');
1629
+ return `cd ${webappDir} && npx playwright install chromium && npm run demo:mock-okta`;
1630
+ }
1631
+ async function writeBootstrapRunArtifacts(env, input) {
1632
+ const runId = randomUUID();
1633
+ const packId = sanitizePathSegment(input.resolved.pack?.pack_id ?? 'adhoc-pack');
1634
+ const packDir = path.join(env.REPO_ROOT, RUN_ARTIFACTS_RELATIVE_DIR, packId);
1635
+ const resumeFile = path.join(packDir, 'resume.json');
1636
+ const reportFile = path.join(packDir, `report-${runId}.json`);
1637
+ await mkdir(packDir, { recursive: true });
1638
+ const report = {
1639
+ run_id: runId,
1640
+ created_at: new Date().toISOString(),
1641
+ lane: input.lane,
1642
+ manifest: input.manifestPath,
1643
+ ...(input.resolved.pack ? { pack: input.resolved.pack } : {}),
1644
+ ...(input.resolved.profile ? { profile: input.resolved.profile } : {}),
1645
+ graph_backend: input.graphBackend,
1646
+ seeded_skills: input.seededSkills,
1647
+ seeded_agents: input.seededAgents,
1648
+ credentials: {
1649
+ api: redactIssuedKey(input.apiKey),
1650
+ mcp: redactIssuedKey(input.mcpKey),
1651
+ },
1652
+ cursor_mcp_config: {
1653
+ ...input.cursorMcpConfig,
1654
+ mcpServers: {
1655
+ 'signet': {
1656
+ url: input.cursorMcpConfig.mcpServers['signet'].url,
1657
+ headers: {
1658
+ Authorization: '[REDACTED]',
1659
+ },
1660
+ },
1661
+ },
1662
+ },
1663
+ next_prompts: input.nextPrompts,
1664
+ mock_okta_demo_command: input.mockOktaDemoCommand,
1665
+ mcp: input.mcpResult,
1666
+ ...(input.oktaLane ? { okta_lane: input.oktaLane } : {}),
1667
+ };
1668
+ await writeFile(reportFile, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
1669
+ await writeFile(resumeFile, `${JSON.stringify({
1670
+ run_id: runId,
1671
+ latest_report_file: reportFile,
1672
+ pack_dir: packDir,
1673
+ manifest: input.manifestPath,
1674
+ ...(input.resolved.pack ? { pack: input.resolved.pack } : {}),
1675
+ ...(input.resolved.profile ? { profile: input.resolved.profile } : {}),
1676
+ lane: input.lane,
1677
+ graph_backend: input.graphBackend,
1678
+ credentials: {
1679
+ api: redactIssuedKey(input.apiKey),
1680
+ mcp: redactIssuedKey(input.mcpKey),
1681
+ },
1682
+ }, null, 2)}\n`, 'utf8');
1683
+ return {
1684
+ run_id: runId,
1685
+ pack_dir: packDir,
1686
+ resume_file: resumeFile,
1687
+ report_file: reportFile,
1688
+ };
1689
+ }
1690
+ function sanitizePathSegment(value) {
1691
+ return value.replace(/[^a-zA-Z0-9._-]+/g, '-');
1692
+ }
1693
+ function redactIssuedKey(value) {
1694
+ return {
1695
+ key_id: value.key_id,
1696
+ owner_label: value.owner_label,
1697
+ token_present: value.token.length > 0,
1698
+ token_sha256_prefix: createHash('sha256').update(value.token, 'utf8').digest('hex').slice(0, 12),
1699
+ };
1700
+ }
1701
+ async function runShell(command, args, input) {
1702
+ return await new Promise((resolve, reject) => {
1703
+ const child = spawn(command, args, {
1704
+ cwd: input.cwd,
1705
+ stdio: ['ignore', 'pipe', 'pipe'],
1706
+ env: {
1707
+ ...process.env,
1708
+ ...input.env,
1709
+ },
1710
+ });
1711
+ let stdout = '';
1712
+ let stderr = '';
1713
+ child.stdout.on('data', (chunk) => {
1714
+ stdout += chunk.toString();
1715
+ });
1716
+ child.stderr.on('data', (chunk) => {
1717
+ stderr += chunk.toString();
1718
+ });
1719
+ child.on('error', reject);
1720
+ child.on('close', (code) => {
1721
+ if (code === 0) {
1722
+ resolve({ stdout: stdout.trim(), stderr: stderr.trim() });
1723
+ }
1724
+ else {
1725
+ reject(new Error(`${command} ${args.join(' ')} failed (${code})\n${stderr || stdout}`));
1726
+ }
1727
+ });
1728
+ });
1729
+ }