@stigmer/cli 3.17.0 → 3.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/commands/bootstrap.d.ts +3 -0
  2. package/commands/bootstrap.d.ts.map +1 -0
  3. package/commands/bootstrap.js +75 -0
  4. package/commands/bootstrap.js.map +1 -0
  5. package/commands/marketplace.d.ts.map +1 -1
  6. package/commands/marketplace.js +7 -7
  7. package/commands/marketplace.js.map +1 -1
  8. package/config/resolve.d.ts.map +1 -1
  9. package/config/resolve.js +8 -7
  10. package/config/resolve.js.map +1 -1
  11. package/local/bootstrap.d.ts +32 -13
  12. package/local/bootstrap.d.ts.map +1 -1
  13. package/local/bootstrap.js +105 -64
  14. package/local/bootstrap.js.map +1 -1
  15. package/local/daemon/launch.d.ts +1 -1
  16. package/local/daemon/launch.d.ts.map +1 -1
  17. package/local/paths.d.ts +1 -1
  18. package/local/paths.js +1 -1
  19. package/local/plugins/defaults.d.ts +27 -7
  20. package/local/plugins/defaults.d.ts.map +1 -1
  21. package/local/plugins/defaults.js +55 -28
  22. package/local/plugins/defaults.js.map +1 -1
  23. package/local/runtime/runtimes-install.d.ts.map +1 -1
  24. package/local/runtime/runtimes-install.js +7 -4
  25. package/local/runtime/runtimes-install.js.map +1 -1
  26. package/local/seedpack-retire.d.ts +63 -0
  27. package/local/seedpack-retire.d.ts.map +1 -0
  28. package/local/seedpack-retire.js +361 -0
  29. package/local/seedpack-retire.js.map +1 -0
  30. package/local/system-org.d.ts +15 -0
  31. package/local/system-org.d.ts.map +1 -0
  32. package/local/system-org.js +57 -0
  33. package/local/system-org.js.map +1 -0
  34. package/marketplace/config.d.ts +3 -1
  35. package/marketplace/config.d.ts.map +1 -1
  36. package/marketplace/config.js +24 -11
  37. package/marketplace/config.js.map +1 -1
  38. package/marketplace/github.d.ts +37 -0
  39. package/marketplace/github.d.ts.map +1 -1
  40. package/marketplace/github.js +70 -1
  41. package/marketplace/github.js.map +1 -1
  42. package/marketplace/install.d.ts +13 -6
  43. package/marketplace/install.d.ts.map +1 -1
  44. package/marketplace/install.js +63 -16
  45. package/marketplace/install.js.map +1 -1
  46. package/marketplace/official.js +4 -4
  47. package/marketplace/official.js.map +1 -1
  48. package/marketplace/render.d.ts.map +1 -1
  49. package/marketplace/render.js +10 -4
  50. package/marketplace/render.js.map +1 -1
  51. package/package.json +7 -7
  52. package/program.js +2 -2
  53. package/program.js.map +1 -1
  54. package/resources/apply/declarative.js +2 -2
  55. package/resources/apply/declarative.js.map +1 -1
  56. package/resources/plugin.d.ts.map +1 -1
  57. package/resources/plugin.js +12 -9
  58. package/resources/plugin.js.map +1 -1
  59. package/src/commands/bootstrap.test.ts +253 -0
  60. package/src/commands/bootstrap.ts +91 -0
  61. package/src/commands/install.test.ts +28 -9
  62. package/src/commands/marketplace.test.ts +28 -14
  63. package/src/commands/marketplace.ts +9 -7
  64. package/src/config/resolve.test.ts +2 -2
  65. package/src/config/resolve.ts +8 -7
  66. package/src/local/bootstrap.test.ts +110 -38
  67. package/src/local/bootstrap.ts +179 -89
  68. package/src/local/daemon/launch.ts +1 -1
  69. package/src/local/paths.ts +1 -1
  70. package/src/local/plugins/defaults.test.ts +46 -13
  71. package/src/local/plugins/defaults.ts +77 -34
  72. package/src/local/runtime/runtimes-install.test.ts +2 -0
  73. package/src/local/runtime/runtimes-install.ts +7 -4
  74. package/src/local/seedpack-retire.test.ts +499 -0
  75. package/src/local/seedpack-retire.ts +474 -0
  76. package/src/local/system-org.test.ts +124 -0
  77. package/src/local/system-org.ts +63 -0
  78. package/src/marketplace/__fixtures__/cursor-marketplace.ts +5 -2
  79. package/src/marketplace/config.test.ts +47 -22
  80. package/src/marketplace/config.ts +27 -12
  81. package/src/marketplace/github.test.ts +77 -1
  82. package/src/marketplace/github.ts +115 -1
  83. package/src/marketplace/install.test.ts +84 -17
  84. package/src/marketplace/install.ts +73 -15
  85. package/src/marketplace/official.ts +4 -4
  86. package/src/marketplace/read.test.ts +1 -1
  87. package/src/marketplace/render.ts +13 -4
  88. package/src/program.ts +2 -2
  89. package/src/resources/apply/declarative.integration.test.ts +2 -2
  90. package/src/resources/apply/declarative.ts +2 -2
  91. package/src/resources/connect/discover.test.ts +1 -1
  92. package/src/resources/plugin.ts +11 -10
  93. package/commands/seedpack.d.ts +0 -3
  94. package/commands/seedpack.d.ts.map +0 -1
  95. package/commands/seedpack.js +0 -98
  96. package/commands/seedpack.js.map +0 -1
  97. package/local/seedpack/apply.d.ts +0 -72
  98. package/local/seedpack/apply.d.ts.map +0 -1
  99. package/local/seedpack/apply.js +0 -145
  100. package/local/seedpack/apply.js.map +0 -1
  101. package/local/seedpack/content.d.ts +0 -61
  102. package/local/seedpack/content.d.ts.map +0 -1
  103. package/local/seedpack/content.js +0 -178
  104. package/local/seedpack/content.js.map +0 -1
  105. package/src/commands/seedpack.ts +0 -116
  106. package/src/local/seedpack/apply.test.ts +0 -287
  107. package/src/local/seedpack/apply.ts +0 -199
  108. package/src/local/seedpack/content.test.ts +0 -169
  109. package/src/local/seedpack/content.ts +0 -222
@@ -0,0 +1,474 @@
1
+ // Retiring the seedpack: the one-time removal, on an existing local install,
2
+ // of the system content an older release seeded (a `stigmer-seedpack`
3
+ // Project in the system org and its member agents, skills, MCP servers and
4
+ // workflows). Newer releases seed nothing but the default plugins, so the
5
+ // rows have no owner left; `stigmer up` runs this step once and reports
6
+ // exactly what it did. This module goes when the Project kind goes.
7
+ //
8
+ // Shape: the client-side mirror of the server's plugin uninstall
9
+ // (GuardMembersUnreferenced then CascadeDeleteMembers in the plugin
10
+ // controller). Before anything is deleted, every agent the identity can see
11
+ // is read and its spec walked for ApiResourceReferences, the same walk the
12
+ // server's ValidateReferences runs; a member some user-authored agent still
13
+ // references is KEPT and the report names the referrer, because an
14
+ // individual delete never refuses on that ground and a dangling reference
15
+ // found at the user's next session is the worse outcome. The one deliberate
16
+ // difference from the server's guard, and its reason: the guard refuses the
17
+ // whole uninstall and tells the user to detach first; a retire inside `up`
18
+ // has no user to ask, so it keeps only what is referenced and removes the
19
+ // rest. Members referencing each other are the seedpack's own business and
20
+ // never keep anything. A member the default plugins ADOPTED (the bootstrap
21
+ // runs first, and the plugin push takes over the system-content row it
22
+ // replaces in place, so the seedpack's `assistant` keeps its id and every
23
+ // conversation with it) now carries `stigmer.ai/plugin` and is reported as
24
+ // such, never deleted: the store says what was adopted, this module keeps
25
+ // no list of its own. Deletes run children-first in reference order
26
+ // (workflows, agents, skills, MCP servers) through the same SDK calls
27
+ // `stigmer delete` binds, so a refusal reaches the user as the server's
28
+ // own sentence; the Project row goes last and the marker file with it. A
29
+ // failure part-way leaves a Project whose members are still listed, and the
30
+ // next `up` converges.
31
+ //
32
+ // Known limit, shared with the server's guard: a workflow names the agent it
33
+ // calls by a DSL string, not a reference, so a user workflow that calls a
34
+ // seedpack agent is not seen and not protected.
35
+
36
+ import { existsSync, rmSync } from "node:fs";
37
+ import { join } from "node:path";
38
+ import type { DescMessage } from "@bufbuild/protobuf";
39
+ import { reflect } from "@bufbuild/protobuf/reflect";
40
+ import type { ReflectMessage } from "@bufbuild/protobuf/reflect";
41
+ import { AgentSchema } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
42
+ import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
43
+ import type { ApiResourceReference } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
44
+ import { type Stigmer, isNotFound } from "@stigmer/sdk";
45
+ import { log } from "../logger.js";
46
+ import { defaultRegistry } from "../registry/index.js";
47
+ import { DELETE_HANDLERS } from "../resources/delete.js";
48
+ import { getterFor } from "../resources/get-bindings.js";
49
+ import { SYSTEM_ORG } from "./system-org.js";
50
+
51
+ /**
52
+ * The seedpack Project's slug, as every release before this one wrote it
53
+ * (the server derived it from `metadata.name` in the seedpack's manifest).
54
+ * Pinned bytes of installs that predate this release.
55
+ */
56
+ export const SEEDPACK_PROJECT_SLUG = "stigmer-seedpack";
57
+
58
+ /**
59
+ * The marker older releases wrote in the data dir to skip an unchanged
60
+ * seedpack. Nothing reads it any more; the retire removes it so a data dir
61
+ * carries no trace of a mechanism that no longer exists.
62
+ */
63
+ export const SEEDPACK_MARKER_FILE = ".seedpack-bootstrapped";
64
+
65
+ /** The order members are removed in: a referrer before what it references. */
66
+ const REMOVAL_ORDER: readonly ApiResourceKind[] = [
67
+ ApiResourceKind.workflow,
68
+ ApiResourceKind.agent,
69
+ ApiResourceKind.skill,
70
+ ApiResourceKind.mcp_server,
71
+ ];
72
+
73
+ const REFERRER_PAGE_SIZE = 100;
74
+
75
+ /** A member of the seedpack Project, addressed the way the Project stored it. */
76
+ export interface SeedpackMember {
77
+ readonly kind: ApiResourceKind;
78
+ readonly org: string;
79
+ readonly slug: string;
80
+ }
81
+
82
+ export type MemberOutcome =
83
+ | { readonly action: "removed"; readonly member: SeedpackMember }
84
+ | { readonly action: "already-gone"; readonly member: SeedpackMember }
85
+ | {
86
+ readonly action: "adopted";
87
+ readonly member: SeedpackMember;
88
+ /** The plugin that now manages the row: its slug, or its id when the plugin row is gone. */
89
+ readonly byPlugin: string;
90
+ }
91
+ | {
92
+ readonly action: "kept-referenced";
93
+ readonly member: SeedpackMember;
94
+ /** The referrers, as "agent 'org/slug'". */
95
+ readonly by: readonly string[];
96
+ }
97
+ | {
98
+ readonly action: "kept-refused";
99
+ readonly member: SeedpackMember;
100
+ /** The server's sentence. */
101
+ readonly reason: string;
102
+ };
103
+
104
+ export type RetireResult =
105
+ | { readonly present: false }
106
+ | {
107
+ readonly present: true;
108
+ readonly outcomes: readonly MemberOutcome[];
109
+ /** False when the Project row itself could not be deleted; the reason is reported. */
110
+ readonly projectRemoved: boolean;
111
+ readonly projectRefusal?: string;
112
+ };
113
+
114
+ export interface RetireOptions {
115
+ /** The local data dir holding the marker file. */
116
+ readonly markerDir: string;
117
+ }
118
+
119
+ /**
120
+ * Retire the seedpack Project the system org may hold. Idempotent: no
121
+ * Project, no work beyond one read and a stale marker's removal.
122
+ */
123
+ export async function retireSeedpack(
124
+ stigmer: Stigmer,
125
+ options: RetireOptions,
126
+ ): Promise<RetireResult> {
127
+ const project = await readProject(stigmer);
128
+ if (project === undefined) {
129
+ removeMarker(options.markerDir);
130
+ return { present: false };
131
+ }
132
+
133
+ const members = (project.members ?? []).map(toMember);
134
+ const referrers = await indexReferrers(stigmer, members);
135
+ const pluginSlugs = new Map<string, string>();
136
+
137
+ const outcomes: MemberOutcome[] = [];
138
+ for (const member of inRemovalOrder(members)) {
139
+ const by = referrers.get(keyOf(member));
140
+ if (by !== undefined) {
141
+ outcomes.push({ action: "kept-referenced", member, by });
142
+ continue;
143
+ }
144
+ outcomes.push(await removeMember(stigmer, member, pluginSlugs));
145
+ }
146
+
147
+ let projectRemoved = true;
148
+ let projectRefusal: string | undefined;
149
+ try {
150
+ await stigmer.project.delete(project.id);
151
+ } catch (error) {
152
+ projectRemoved = false;
153
+ projectRefusal = messageOf(error);
154
+ log.warn("seedpack project delete refused", { error: projectRefusal });
155
+ }
156
+ removeMarker(options.markerDir);
157
+
158
+ return projectRefusal === undefined
159
+ ? { present: true, outcomes, projectRemoved }
160
+ : { present: true, outcomes, projectRemoved, projectRefusal };
161
+ }
162
+
163
+ /** The report `stigmer up` prints, one block on stderr through `say`. */
164
+ export function renderRetireReport(
165
+ result: RetireResult,
166
+ say: (line: string) => void,
167
+ ): void {
168
+ if (!result.present) return;
169
+
170
+ const removed = result.outcomes.filter(
171
+ (outcome) => outcome.action === "removed",
172
+ ).length;
173
+ const adopted = result.outcomes.filter(
174
+ (outcome) => outcome.action === "adopted",
175
+ ).length;
176
+ const kept = result.outcomes.filter(
177
+ (outcome) =>
178
+ outcome.action === "kept-referenced" ||
179
+ outcome.action === "kept-refused",
180
+ );
181
+ const tail = [
182
+ adopted === 0 ? "" : `${count(adopted, "resource")} now managed by a plugin`,
183
+ kept.length === 0 ? "" : `kept ${count(kept.length, "resource")}`,
184
+ ].filter((part) => part !== "");
185
+ say(
186
+ `Retired the system content an older release installed: removed ${count(removed, "resource")}` +
187
+ (tail.length === 0 ? "." : `, ${tail.join(", ")}.`),
188
+ );
189
+ for (const outcome of result.outcomes) {
190
+ switch (outcome.action) {
191
+ case "removed":
192
+ case "already-gone":
193
+ break;
194
+ case "adopted":
195
+ say(
196
+ ` ${describe(outcome.member)} is now managed by plugin '${outcome.byPlugin}'; its instances and conversations continue`,
197
+ );
198
+ break;
199
+ case "kept-referenced":
200
+ say(
201
+ ` kept ${describe(outcome.member)}: referenced by ${outcome.by.join(", ")}`,
202
+ );
203
+ break;
204
+ case "kept-refused":
205
+ say(` kept ${describe(outcome.member)}: ${outcome.reason}`);
206
+ break;
207
+ default: {
208
+ const exhaustive: never = outcome;
209
+ throw new Error(`unhandled outcome ${String(exhaustive)}`);
210
+ }
211
+ }
212
+ }
213
+ if (kept.length > 0) {
214
+ say(
215
+ " A kept resource's icon no longer resolves. Once its referrer is edited, remove it with 'stigmer delete <kind> <org>/<slug>'.",
216
+ );
217
+ }
218
+ if (!result.projectRemoved) {
219
+ say(
220
+ ` The '${SEEDPACK_PROJECT_SLUG}' project row could not be removed: ${result.projectRefusal ?? "unknown reason"}. Run 'stigmer up' again to retry.`,
221
+ );
222
+ }
223
+ }
224
+
225
+ interface SeedpackProject {
226
+ readonly id: string;
227
+ readonly members: readonly ApiResourceReference[] | undefined;
228
+ }
229
+
230
+ async function readProject(
231
+ stigmer: Stigmer,
232
+ ): Promise<SeedpackProject | undefined> {
233
+ try {
234
+ const project = await stigmer.project.getByReference({
235
+ org: SYSTEM_ORG,
236
+ slug: SEEDPACK_PROJECT_SLUG,
237
+ });
238
+ return { id: project.metadata?.id ?? "", members: project.spec?.members };
239
+ } catch (error) {
240
+ if (isNotFound(error)) return undefined;
241
+ throw error;
242
+ }
243
+ }
244
+
245
+ function toMember(ref: ApiResourceReference): SeedpackMember {
246
+ // Stored references are absolute, but an empty org can only mean the
247
+ // Project's own.
248
+ return { kind: ref.kind, org: ref.org || SYSTEM_ORG, slug: ref.slug };
249
+ }
250
+
251
+ function keyOf(member: SeedpackMember): string {
252
+ return `${member.kind}:${member.org}/${member.slug}`;
253
+ }
254
+
255
+ function inRemovalOrder(
256
+ members: readonly SeedpackMember[],
257
+ ): SeedpackMember[] {
258
+ const ordered: SeedpackMember[] = [];
259
+ for (const kind of REMOVAL_ORDER) {
260
+ ordered.push(...members.filter((member) => member.kind === kind));
261
+ }
262
+ ordered.push(
263
+ ...members.filter((member) => !REMOVAL_ORDER.includes(member.kind)),
264
+ );
265
+ return ordered;
266
+ }
267
+
268
+ /**
269
+ * Every member some agent outside the seedpack references, mapped to the
270
+ * agents that reference it. Reads each agent in every organization the
271
+ * identity sees: the listing is search-backed and carries no spec.
272
+ */
273
+ async function indexReferrers(
274
+ stigmer: Stigmer,
275
+ members: readonly SeedpackMember[],
276
+ ): Promise<Map<string, string[]>> {
277
+ const memberKeys = new Set(members.map(keyOf));
278
+ const referrers = new Map<string, string[]>();
279
+ if (memberKeys.size === 0) return referrers;
280
+
281
+ const orgs = (await stigmer.organization.findMyOrganizations()).entries
282
+ .map((org) => org.metadata?.slug ?? "")
283
+ .filter((slug) => slug !== "");
284
+
285
+ for (const org of orgs) {
286
+ for (let page = 1; ; page += 1) {
287
+ const listing = await stigmer.agent.list({
288
+ org,
289
+ page: { num: page, size: REFERRER_PAGE_SIZE },
290
+ });
291
+ for (const entry of listing.entries) {
292
+ const self = `${ApiResourceKind.agent}:${entry.org || org}/${entry.slug}`;
293
+ if (memberKeys.has(self)) continue;
294
+ const agent = await stigmer.agent.get(entry.id);
295
+ const label = `agent '${entry.org || org}/${entry.slug}'`;
296
+ for (const ref of collectSpecReferences(AgentSchema, agent)) {
297
+ const key = `${ref.kind}:${ref.org || org}/${ref.slug}`;
298
+ if (!memberKeys.has(key)) continue;
299
+ const list = referrers.get(key) ?? [];
300
+ if (!list.includes(label)) list.push(label);
301
+ referrers.set(key, list);
302
+ }
303
+ }
304
+ if (page >= listing.totalPages) break;
305
+ }
306
+ }
307
+ return referrers;
308
+ }
309
+
310
+ /**
311
+ * The membership label the server stamps on every resource a plugin
312
+ * materialises; its value is the plugin's id. Read here, never written: a
313
+ * seedpack member carrying it was adopted by a default plugin moments ago.
314
+ */
315
+ const PLUGIN_LABEL = "stigmer.ai/plugin";
316
+
317
+ async function removeMember(
318
+ stigmer: Stigmer,
319
+ member: SeedpackMember,
320
+ pluginSlugs: Map<string, string>,
321
+ ): Promise<MemberOutcome> {
322
+ const getter = getterFor(member.kind);
323
+ const deleter = DELETE_HANDLERS.get(member.kind);
324
+ if (getter === undefined || deleter === undefined) {
325
+ return {
326
+ action: "kept-refused",
327
+ member,
328
+ reason: "this CLI has no delete for that kind",
329
+ };
330
+ }
331
+ let id: string;
332
+ try {
333
+ const found = await getter(stigmer, {
334
+ kind: "ref",
335
+ org: member.org,
336
+ slug: member.slug,
337
+ });
338
+ const metadata = (
339
+ found.message as {
340
+ metadata?: { id?: string; labels?: Record<string, string> };
341
+ }
342
+ ).metadata;
343
+ id = metadata?.id ?? "";
344
+ const pluginId = metadata?.labels?.[PLUGIN_LABEL];
345
+ if (pluginId !== undefined && pluginId !== "") {
346
+ return {
347
+ action: "adopted",
348
+ member,
349
+ byPlugin: await pluginSlugOf(stigmer, pluginId, pluginSlugs),
350
+ };
351
+ }
352
+ } catch (error) {
353
+ if (isNotFound(error)) return { action: "already-gone", member };
354
+ return { action: "kept-refused", member, reason: messageOf(error) };
355
+ }
356
+ try {
357
+ await deleter(stigmer, id, false);
358
+ return { action: "removed", member };
359
+ } catch (error) {
360
+ if (isNotFound(error)) return { action: "already-gone", member };
361
+ return { action: "kept-refused", member, reason: messageOf(error) };
362
+ }
363
+ }
364
+
365
+ /** The adopting plugin's slug, read once per id; a plugin row that is gone names itself. */
366
+ async function pluginSlugOf(
367
+ stigmer: Stigmer,
368
+ pluginId: string,
369
+ cache: Map<string, string>,
370
+ ): Promise<string> {
371
+ const known = cache.get(pluginId);
372
+ if (known !== undefined) return known;
373
+ let slug = pluginId;
374
+ try {
375
+ slug = (await stigmer.plugin.get(pluginId)).metadata?.slug || pluginId;
376
+ } catch (error) {
377
+ if (!isNotFound(error)) throw error;
378
+ }
379
+ cache.set(pluginId, slug);
380
+ return slug;
381
+ }
382
+
383
+ function removeMarker(markerDir: string): void {
384
+ const marker = join(markerDir, SEEDPACK_MARKER_FILE);
385
+ if (existsSync(marker)) rmSync(marker, { force: true });
386
+ }
387
+
388
+ function describe(member: SeedpackMember): string {
389
+ const info = defaultRegistry().getByKind(member.kind);
390
+ const noun = info?.singular ?? ApiResourceKind[member.kind] ?? "resource";
391
+ return `${noun} '${member.org}/${member.slug}'`;
392
+ }
393
+
394
+ function count(n: number, noun: string): string {
395
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
396
+ }
397
+
398
+ function messageOf(error: unknown): string {
399
+ return error instanceof Error ? error.message : String(error);
400
+ }
401
+
402
+ // --- The reference walk: every ApiResourceReference in a resource's spec ---
403
+ //
404
+ // The same traversal the server runs in its ValidateReferences step and its
405
+ // plugin uninstall guard (singular, repeated and map-valued message fields,
406
+ // recursively), so a reference field added to a spec is seen here without a
407
+ // change. Server-internal there and not exported to clients; mirrored here
408
+ // for the one client that asks the reverse question.
409
+
410
+ const API_RESOURCE_REFERENCE_TYPE =
411
+ "ai.stigmer.commons.apiresource.ApiResourceReference";
412
+
413
+ interface SpecReference {
414
+ readonly kind: ApiResourceKind;
415
+ readonly slug: string;
416
+ readonly org: string;
417
+ }
418
+
419
+ function collectSpecReferences(
420
+ schema: DescMessage,
421
+ msg: Parameters<typeof reflect>[1],
422
+ ): SpecReference[] {
423
+ const refs: SpecReference[] = [];
424
+ const root = reflect(schema, msg);
425
+ const spec = root.fields.find(
426
+ (field) => field.name === "spec" && field.fieldKind === "message",
427
+ );
428
+ if (spec === undefined || spec.fieldKind !== "message" || !root.isSet(spec)) {
429
+ return refs;
430
+ }
431
+ walk(root.get(spec), (ref) => {
432
+ refs.push({
433
+ kind: numberField(ref, "kind") as ApiResourceKind,
434
+ slug: stringField(ref, "slug"),
435
+ org: stringField(ref, "org"),
436
+ });
437
+ });
438
+ return refs;
439
+ }
440
+
441
+ function walk(msg: ReflectMessage, fn: (ref: ReflectMessage) => void): void {
442
+ for (const field of msg.fields) {
443
+ if (field.fieldKind === "list") {
444
+ if (field.listKind !== "message") continue;
445
+ for (const item of msg.get(field)) visit(item as ReflectMessage, fn);
446
+ } else if (field.fieldKind === "map") {
447
+ if (field.mapKind !== "message") continue;
448
+ for (const [, value] of msg.get(field)) {
449
+ visit(value as ReflectMessage, fn);
450
+ }
451
+ } else if (field.fieldKind === "message") {
452
+ if (msg.isSet(field)) visit(msg.get(field), fn);
453
+ }
454
+ }
455
+ }
456
+
457
+ function visit(sub: ReflectMessage, fn: (ref: ReflectMessage) => void): void {
458
+ if (sub.desc.typeName === API_RESOURCE_REFERENCE_TYPE) fn(sub);
459
+ else walk(sub, fn);
460
+ }
461
+
462
+ function stringField(msg: ReflectMessage, name: string): string {
463
+ const field = msg.fields.find((f) => f.name === name);
464
+ if (field === undefined) return "";
465
+ const value = msg.get(field);
466
+ return typeof value === "string" ? value : "";
467
+ }
468
+
469
+ function numberField(msg: ReflectMessage, name: string): number {
470
+ const field = msg.fields.find((f) => f.name === name);
471
+ if (field === undefined) return 0;
472
+ const value = msg.get(field);
473
+ return typeof value === "number" ? value : 0;
474
+ }
@@ -0,0 +1,124 @@
1
+ // Pins the system org's "ensure" over a real Connect backend: an org the
2
+ // identity already sees is `present` with no create; an absent one is
3
+ // created as the Organization as code (slug, name, label, self-managed) and
4
+ // reported `created`; a create that loses the race to another launcher
5
+ // (ALREADY_EXISTS) is `present`, not an error; any other refusal propagates
6
+ // with the server's sentence.
7
+
8
+ import {
9
+ createServer as createHttp2Server,
10
+ type Http2Server,
11
+ type ServerHttp2Session,
12
+ } from "node:http2";
13
+ import type { AddressInfo } from "node:net";
14
+ import { create } from "@bufbuild/protobuf";
15
+ import { Code, ConnectError, type ConnectRouter } from "@connectrpc/connect";
16
+ import { connectNodeAdapter } from "@connectrpc/connect-node";
17
+ import {
18
+ type Organization,
19
+ OrganizationSchema,
20
+ } from "@stigmer/protos/ai/stigmer/tenancy/organization/v1/api_pb";
21
+ import { OrganizationCommandController } from "@stigmer/protos/ai/stigmer/tenancy/organization/v1/command_pb";
22
+ import { ManagementMode } from "@stigmer/protos/ai/stigmer/tenancy/organization/v1/enum_pb";
23
+ import { OrganizationsSchema } from "@stigmer/protos/ai/stigmer/tenancy/organization/v1/io_pb";
24
+ import { OrganizationQueryController } from "@stigmer/protos/ai/stigmer/tenancy/organization/v1/query_pb";
25
+ import { createNodeClient, normalizeEndpoint } from "@stigmer/sdk/node";
26
+ import type { Stigmer } from "@stigmer/sdk";
27
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
28
+ import { SYSTEM_ORG, SYSTEM_ORG_LABEL, ensureSystemOrg } from "./system-org.js";
29
+
30
+ let backend: Http2Server;
31
+ let stigmer: Stigmer;
32
+ const openSessions = new Set<ServerHttp2Session>();
33
+
34
+ /** The orgs the backend holds, by slug. */
35
+ let held: Map<string, Organization>;
36
+ let creates: Organization[];
37
+ /** What `create` answers with instead of creating, when set. */
38
+ let refuseCreate: ConnectError | undefined;
39
+
40
+ beforeAll(async () => {
41
+ const routes = (router: ConnectRouter) => {
42
+ router.service(OrganizationQueryController, {
43
+ findMyOrganizations: () =>
44
+ create(OrganizationsSchema, { entries: [...held.values()] }),
45
+ });
46
+ router.service(OrganizationCommandController, {
47
+ create: (org) => {
48
+ creates.push(org);
49
+ if (refuseCreate !== undefined) throw refuseCreate;
50
+ const slug = org.metadata?.slug ?? "";
51
+ const row = create(OrganizationSchema, org);
52
+ if (row.metadata !== undefined) row.metadata.id = `org_${slug}`;
53
+ held.set(slug, row);
54
+ return row;
55
+ },
56
+ });
57
+ };
58
+ backend = createHttp2Server(connectNodeAdapter({ routes }));
59
+ backend.on("session", (session) => {
60
+ openSessions.add(session);
61
+ session.on("close", () => openSessions.delete(session));
62
+ });
63
+ await new Promise<void>((resolve) => backend.listen(0, "127.0.0.1", resolve));
64
+ const port = (backend.address() as AddressInfo).port;
65
+ stigmer = createNodeClient({
66
+ baseUrl: normalizeEndpoint(`127.0.0.1:${port}`),
67
+ });
68
+ });
69
+
70
+ afterAll(async () => {
71
+ for (const session of openSessions) session.destroy();
72
+ await new Promise<void>((resolve) => backend.close(() => resolve()));
73
+ });
74
+
75
+ beforeEach(() => {
76
+ held = new Map();
77
+ creates = [];
78
+ refuseCreate = undefined;
79
+ });
80
+
81
+ describe("ensureSystemOrg", () => {
82
+ it("is present, with no create, when the identity already sees it", async () => {
83
+ held.set(
84
+ SYSTEM_ORG,
85
+ create(OrganizationSchema, { metadata: { slug: SYSTEM_ORG } }),
86
+ );
87
+ expect(await ensureSystemOrg(stigmer)).toBe("present");
88
+ expect(creates).toHaveLength(0);
89
+ });
90
+
91
+ it("creates the Organization as code when absent", async () => {
92
+ held.set(
93
+ "acme",
94
+ create(OrganizationSchema, { metadata: { slug: "acme" } }),
95
+ );
96
+ expect(await ensureSystemOrg(stigmer)).toBe("created");
97
+ expect(creates).toHaveLength(1);
98
+ const sent = creates[0]!;
99
+ expect(sent.metadata?.slug).toBe(SYSTEM_ORG);
100
+ expect(sent.metadata?.org).toBe(SYSTEM_ORG);
101
+ expect(sent.metadata?.name).toBe("Stigmer");
102
+ expect(sent.metadata?.labels).toEqual({ [SYSTEM_ORG_LABEL]: "true" });
103
+ expect(sent.spec?.managementMode).toBe(ManagementMode.self_managed);
104
+ expect(sent.spec?.description).not.toBe("");
105
+ });
106
+
107
+ it("treats a create lost to another launcher as present", async () => {
108
+ refuseCreate = new ConnectError(
109
+ `organization '${SYSTEM_ORG}' already exists`,
110
+ Code.AlreadyExists,
111
+ );
112
+ expect(await ensureSystemOrg(stigmer)).toBe("present");
113
+ });
114
+
115
+ it("propagates any other refusal with the server's sentence", async () => {
116
+ refuseCreate = new ConnectError(
117
+ "reserved labels are platform-managed",
118
+ Code.PermissionDenied,
119
+ );
120
+ await expect(ensureSystemOrg(stigmer)).rejects.toThrow(
121
+ /reserved labels are platform-managed/,
122
+ );
123
+ });
124
+ });
@@ -0,0 +1,63 @@
1
+ // The system organization, as code: the one `stigmer` org every Stigmer
2
+ // backend carries, which the official default plugins are installed into
3
+ // and the local CLI falls back to when no org is configured.
4
+ //
5
+ // This is the only place the org is defined. The bootstrap creates it when
6
+ // a backend does not have it (a fresh local data dir, a raw self-hosted
7
+ // server); on the hosted platform it already exists, owned by IAM, and the
8
+ // create never fires. Its slug is the same in both editions, so nothing
9
+ // here is configurable: a bootstrap that could be pointed at another org
10
+ // would put the platform's public defaults where no cross-org lookup finds
11
+ // them.
12
+ //
13
+ // "Ensure" is find-then-create with the race closed by the server: two
14
+ // launchers racing the same check see one `already-exists`, and that IS the
15
+ // desired end state, so it is reported as `present`, never rethrown. Any
16
+ // other refusal (a self-hosted authorizer that denies the reserved label,
17
+ // a backend that refuses the create) propagates with the server's sentence;
18
+ // the caller decides how loud to be.
19
+
20
+ import { ManagementMode } from "@stigmer/protos/ai/stigmer/tenancy/organization/v1/enum_pb";
21
+ import { type Stigmer, StigmerError } from "@stigmer/sdk";
22
+
23
+ /** The system organization's slug, identical across editions. */
24
+ export const SYSTEM_ORG = "stigmer";
25
+
26
+ /**
27
+ * Marks the system org so an operator can tell it from a user's own org in
28
+ * any listing. Informational: no server or client code path reads it.
29
+ */
30
+ export const SYSTEM_ORG_LABEL = "stigmer.ai/system";
31
+
32
+ export type EnsureSystemOrgOutcome = "present" | "created";
33
+
34
+ /**
35
+ * Make sure the system organization exists on the backend `stigmer` is bound
36
+ * to. Idempotent; a lost create race counts as `present`.
37
+ */
38
+ export async function ensureSystemOrg(
39
+ stigmer: Stigmer,
40
+ ): Promise<EnsureSystemOrgOutcome> {
41
+ const mine = await stigmer.organization.findMyOrganizations();
42
+ if (mine.entries.some((org) => org.metadata?.slug === SYSTEM_ORG)) {
43
+ return "present";
44
+ }
45
+ try {
46
+ // Organizations are self-owning: the org field is the slug itself, the
47
+ // shape the console's create form and the e2e harness both use.
48
+ await stigmer.organization.create({
49
+ name: "Stigmer",
50
+ slug: SYSTEM_ORG,
51
+ org: SYSTEM_ORG,
52
+ description: "System organization for Stigmer installations",
53
+ labels: { [SYSTEM_ORG_LABEL]: "true" },
54
+ managementMode: ManagementMode.self_managed,
55
+ });
56
+ return "created";
57
+ } catch (error) {
58
+ if (error instanceof StigmerError && error.code === "already-exists") {
59
+ return "present";
60
+ }
61
+ throw error;
62
+ }
63
+ }
@@ -1,12 +1,15 @@
1
1
  // A small Cursor-dialect marketplace written to a directory for the
2
2
  // marketplace suites: two plugins offered (one with a skill, one MCP-only,
3
3
  // the second under a nested source directory) and one entry whose directory
4
- // is missing, so every suite sees an offered list and a dropped entry.
4
+ // is missing, so every suite sees an offered list and a dropped entry. It
5
+ // names itself `acme-plugins`: the vendors' own names are built into every
6
+ // client, so a fixture under one of them would meet the reserved-name
7
+ // refusal instead of being added.
5
8
 
6
9
  import { mkdirSync, writeFileSync } from "node:fs";
7
10
  import { dirname, join } from "node:path";
8
11
 
9
- export const CURSOR_MARKETPLACE_NAME = "cursor-plugins";
12
+ export const CURSOR_MARKETPLACE_NAME = "acme-plugins";
10
13
 
11
14
  export function writeCursorMarketplace(root: string): void {
12
15
  const write = (rel: string, content: string): void => {