@stigmer/cli 3.19.0 → 3.20.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 (106) hide show
  1. package/commands/apply.d.ts.map +1 -1
  2. package/commands/apply.js +42 -100
  3. package/commands/apply.js.map +1 -1
  4. package/commands/validate.js +3 -4
  5. package/commands/validate.js.map +1 -1
  6. package/local/bootstrap.d.ts +1 -2
  7. package/local/bootstrap.d.ts.map +1 -1
  8. package/local/bootstrap.js +13 -41
  9. package/local/bootstrap.js.map +1 -1
  10. package/local/daemon/launch.d.ts +2 -2
  11. package/local/daemon/launch.d.ts.map +1 -1
  12. package/local/daemon/launch.js +2 -2
  13. package/local/daemon/launch.js.map +1 -1
  14. package/local/plugins/defaults.js +2 -2
  15. package/local/plugins/defaults.js.map +1 -1
  16. package/package.json +7 -7
  17. package/registry/index.d.ts +2 -2
  18. package/registry/index.d.ts.map +1 -1
  19. package/registry/index.js +2 -2
  20. package/registry/index.js.map +1 -1
  21. package/registry/metadata.d.ts +9 -0
  22. package/registry/metadata.d.ts.map +1 -1
  23. package/registry/metadata.js +14 -5
  24. package/registry/metadata.js.map +1 -1
  25. package/registry/registry.d.ts +9 -0
  26. package/registry/registry.d.ts.map +1 -1
  27. package/registry/registry.js +16 -1
  28. package/registry/registry.js.map +1 -1
  29. package/registry/verb-support.d.ts.map +1 -1
  30. package/registry/verb-support.js +0 -13
  31. package/registry/verb-support.js.map +1 -1
  32. package/resources/apply/apply.d.ts +11 -12
  33. package/resources/apply/apply.d.ts.map +1 -1
  34. package/resources/apply/apply.js +12 -21
  35. package/resources/apply/apply.js.map +1 -1
  36. package/resources/apply/handlers.js +2 -2
  37. package/resources/apply/handlers.js.map +1 -1
  38. package/resources/delete.d.ts.map +1 -1
  39. package/resources/delete.js +0 -1
  40. package/resources/delete.js.map +1 -1
  41. package/resources/get-bindings.d.ts.map +1 -1
  42. package/resources/get-bindings.js +0 -5
  43. package/resources/get-bindings.js.map +1 -1
  44. package/resources/list.d.ts.map +1 -1
  45. package/resources/list.js +0 -1
  46. package/resources/list.js.map +1 -1
  47. package/resources/validate.d.ts.map +1 -1
  48. package/resources/validate.js +0 -2
  49. package/resources/validate.js.map +1 -1
  50. package/src/commands/apply.ts +35 -150
  51. package/src/commands/validate.ts +2 -4
  52. package/src/local/bootstrap.test.ts +15 -59
  53. package/src/local/bootstrap.ts +12 -53
  54. package/src/local/daemon/launch.ts +4 -4
  55. package/src/local/plugins/defaults.ts +2 -2
  56. package/src/registry/index.ts +7 -1
  57. package/src/registry/metadata.ts +15 -5
  58. package/src/registry/registry.test.ts +1 -7
  59. package/src/registry/registry.ts +17 -1
  60. package/src/registry/verb-support.ts +0 -13
  61. package/src/resources/apply/apply.integration.test.ts +15 -3
  62. package/src/resources/apply/apply.ts +15 -26
  63. package/src/resources/apply/handlers.ts +2 -2
  64. package/src/resources/delete.ts +0 -1
  65. package/src/resources/get-bindings.ts +0 -5
  66. package/src/resources/list.ts +0 -1
  67. package/src/resources/validate.test.ts +0 -1
  68. package/src/resources/validate.ts +0 -2
  69. package/local/seedpack-retire.d.ts +0 -63
  70. package/local/seedpack-retire.d.ts.map +0 -1
  71. package/local/seedpack-retire.js +0 -361
  72. package/local/seedpack-retire.js.map +0 -1
  73. package/resources/apply/declarative.d.ts +0 -106
  74. package/resources/apply/declarative.d.ts.map +0 -1
  75. package/resources/apply/declarative.js +0 -397
  76. package/resources/apply/declarative.js.map +0 -1
  77. package/resources/apply/synth/project-track.d.ts +0 -21
  78. package/resources/apply/synth/project-track.d.ts.map +0 -1
  79. package/resources/apply/synth/project-track.js +0 -102
  80. package/resources/apply/synth/project-track.js.map +0 -1
  81. package/resources/apply/synth/reader.d.ts +0 -18
  82. package/resources/apply/synth/reader.d.ts.map +0 -1
  83. package/resources/apply/synth/reader.js +0 -55
  84. package/resources/apply/synth/reader.js.map +0 -1
  85. package/resources/apply/synth/runtime.d.ts +0 -8
  86. package/resources/apply/synth/runtime.d.ts.map +0 -1
  87. package/resources/apply/synth/runtime.js +0 -32
  88. package/resources/apply/synth/runtime.js.map +0 -1
  89. package/resources/apply/synth/synthesize.d.ts +0 -43
  90. package/resources/apply/synth/synthesize.d.ts.map +0 -1
  91. package/resources/apply/synth/synthesize.js +0 -115
  92. package/resources/apply/synth/synthesize.js.map +0 -1
  93. package/src/local/seedpack-retire.test.ts +0 -499
  94. package/src/local/seedpack-retire.ts +0 -474
  95. package/src/resources/apply/declarative.integration.test.ts +0 -204
  96. package/src/resources/apply/declarative.test.ts +0 -132
  97. package/src/resources/apply/declarative.ts +0 -491
  98. package/src/resources/apply/synth/capstone.integration.test.ts +0 -134
  99. package/src/resources/apply/synth/project-track.integration.test.ts +0 -194
  100. package/src/resources/apply/synth/project-track.ts +0 -126
  101. package/src/resources/apply/synth/reader.test.ts +0 -90
  102. package/src/resources/apply/synth/reader.ts +0 -68
  103. package/src/resources/apply/synth/runtime.test.ts +0 -29
  104. package/src/resources/apply/synth/runtime.ts +0 -39
  105. package/src/resources/apply/synth/synthesize.test.ts +0 -109
  106. package/src/resources/apply/synth/synthesize.ts +0 -161
@@ -1,474 +0,0 @@
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
- }
@@ -1,204 +0,0 @@
1
- // In-process integration test for declarative apply.
2
- //
3
- // Stands up a Connect backend (agent + skill + project controllers) and drives
4
- // applyDeclarative end to end against a temp project directory: a stigmer.yaml,
5
- // one agent resource, and one skill directory. The assertions lock the
6
- // membership contract — skills are pushed first, member-eligible resources are
7
- // collected as references, and the project is applied with that exact member
8
- // set so the server can reconcile.
9
-
10
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
11
- import { createServer as createHttp2Server, type Http2Server, type ServerHttp2Session } from "node:http2";
12
- import type { AddressInfo } from "node:net";
13
- import { tmpdir } from "node:os";
14
- import { join } from "node:path";
15
- import { create } from "@bufbuild/protobuf";
16
- import { type ConnectRouter, createClient } from "@connectrpc/connect";
17
- import { connectNodeAdapter } from "@connectrpc/connect-node";
18
- import { AgentCommandController } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/command_pb";
19
- import { McpServerCommandController } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/command_pb";
20
- import { SkillSchema } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/api_pb";
21
- import { SkillCommandController } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/command_pb";
22
- import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
23
- import type { Project } from "@stigmer/protos/ai/stigmer/tenancy/project/v1/api_pb";
24
- import { ProjectCommandController } from "@stigmer/protos/ai/stigmer/tenancy/project/v1/command_pb";
25
- import { createNodeClient, createNodeTransport, normalizeEndpoint } from "@stigmer/sdk/node";
26
- import type { Stigmer } from "@stigmer/sdk";
27
- import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
28
- import { applyDeclarative, detectTrack } from "./declarative.js";
29
- import type { ControllerFn } from "./handlers.js";
30
-
31
- let backend: Http2Server;
32
- let stigmer: Stigmer;
33
- let controllerFn: ControllerFn;
34
- const openSessions = new Set<ServerHttp2Session>();
35
-
36
- let appliedProject: Project | undefined;
37
-
38
- // Ordered log of backend calls, for the discovery-before-dependents contract.
39
- let events: string[] = [];
40
-
41
- beforeEach(() => {
42
- appliedProject = undefined;
43
- events = [];
44
- });
45
-
46
- function makeProject(dir: string): void {
47
- writeFileSync(
48
- join(dir, "stigmer.yaml"),
49
- ["kind: Project", "metadata:", " name: Demo", " slug: demo", "spec:", " description: d", ""].join("\n"),
50
- );
51
- writeFileSync(
52
- join(dir, "agent.yaml"),
53
- ["kind: Agent", "metadata:", " name: Reviewer", " slug: reviewer", "spec:", " description: r", ""].join("\n"),
54
- );
55
- mkdirSync(join(dir, "my-skill"));
56
- writeFileSync(join(dir, "my-skill", "SKILL.md"), ["---", "name: my-skill", "---", "# My Skill"].join("\n"));
57
- }
58
-
59
- beforeAll(async () => {
60
- const routes = (router: ConnectRouter) => {
61
- router.service(AgentCommandController, {
62
- apply: (req) => {
63
- events.push("agent.apply");
64
- return req;
65
- },
66
- });
67
- router.service(McpServerCommandController, {
68
- apply: (req) => {
69
- events.push("mcpserver.apply");
70
- return req;
71
- },
72
- connect: () => {
73
- events.push("mcpserver.connect");
74
- return {};
75
- },
76
- });
77
- router.service(SkillCommandController, {
78
- push: (req) =>
79
- create(SkillSchema, {
80
- metadata: { id: "skl_1", slug: "my-skill", version: { id: "v1" } },
81
- spec: { tag: req.tag },
82
- status: { versionHash: "abc123" },
83
- }),
84
- });
85
- router.service(ProjectCommandController, {
86
- apply: (req) => {
87
- appliedProject = req;
88
- return req;
89
- },
90
- });
91
- };
92
-
93
- backend = createHttp2Server(connectNodeAdapter({ routes }));
94
- backend.on("session", (session) => {
95
- openSessions.add(session);
96
- session.on("close", () => openSessions.delete(session));
97
- });
98
- await new Promise<void>((resolve) => backend.listen(0, "127.0.0.1", resolve));
99
- const port = (backend.address() as AddressInfo).port;
100
- const baseUrl = normalizeEndpoint(`127.0.0.1:${port}`);
101
- stigmer = createNodeClient({ baseUrl });
102
- const transport = createNodeTransport({ baseUrl });
103
- controllerFn = (service) => createClient(service, transport);
104
- });
105
-
106
- afterAll(async () => {
107
- for (const session of openSessions) session.destroy();
108
- await new Promise<void>((resolve) => backend.close(() => resolve()));
109
- });
110
-
111
- describe("applyDeclarative", () => {
112
- it("pushes skills, applies resources, and sets project membership", async () => {
113
- const dir = mkdtempSync(join(tmpdir(), "decl-it-"));
114
- try {
115
- makeProject(dir);
116
- const detect = detectTrack(dir);
117
- expect(detect.track).toBe("declarative");
118
-
119
- const result = await applyDeclarative(detect, {
120
- controller: controllerFn,
121
- stigmer,
122
- org: "acme",
123
- info: () => {},
124
- warn: () => {},
125
- });
126
-
127
- expect(result.status).toBe("success");
128
-
129
- // The project was applied with exactly two members: the pushed skill and
130
- // the applied agent (both member-eligible kinds), each carrying org+slug.
131
- expect(appliedProject).toBeDefined();
132
- const members = appliedProject?.spec?.members ?? [];
133
- expect(members).toHaveLength(2);
134
-
135
- const skill = members.find((m) => m.kind === ApiResourceKind.skill);
136
- const agent = members.find((m) => m.kind === ApiResourceKind.agent);
137
- expect(skill).toMatchObject({ org: "acme", slug: "my-skill" });
138
- expect(agent).toMatchObject({ org: "acme", slug: "reviewer" });
139
-
140
- // Org is injected into the project metadata when the YAML omitted it.
141
- expect(appliedProject?.metadata?.org).toBe("acme");
142
- } finally {
143
- rmSync(dir, { recursive: true, force: true });
144
- }
145
- });
146
-
147
- it("discovers MCP capabilities before applying dependent resources", async () => {
148
- // Pins the ordering contract behind apply-time enabled_tools validation
149
- // (stigmer/stigmer#402): the server rejects agent enabled_tools against
150
- // STORED capabilities, so discovery must refresh them between the MCP
151
- // server applies and the applies that depend on them. Regressing to
152
- // discovery-at-the-end resurrects the stale-capabilities race (a project
153
- // upgrade adding a tool + enabling it in an agent would fail its apply).
154
- const dir = mkdtempSync(join(tmpdir(), "decl-it-order-"));
155
- try {
156
- writeFileSync(
157
- join(dir, "stigmer.yaml"),
158
- ["kind: Project", "metadata:", " name: Ordered", " slug: ordered", "spec:", " description: d", ""].join("\n"),
159
- );
160
- // Named so a naive filename sort would apply the agent first — the
161
- // reconciler must order by dependency, not by scan order.
162
- writeFileSync(
163
- join(dir, "a-agent.yaml"),
164
- [
165
- "kind: Agent",
166
- "metadata:",
167
- " name: Consumer",
168
- " slug: consumer",
169
- "spec:",
170
- " description: c",
171
- "",
172
- ].join("\n"),
173
- );
174
- writeFileSync(
175
- join(dir, "z-server.yaml"),
176
- [
177
- "kind: McpServer",
178
- "metadata:",
179
- " name: Tools",
180
- " slug: tools",
181
- "spec:",
182
- " description: t",
183
- " stdio:",
184
- " command: npx",
185
- "",
186
- ].join("\n"),
187
- );
188
-
189
- const detect = detectTrack(dir);
190
- const result = await applyDeclarative(detect, {
191
- controller: controllerFn,
192
- stigmer,
193
- org: "acme",
194
- info: () => {},
195
- warn: () => {},
196
- });
197
-
198
- expect(result.status).toBe("success");
199
- expect(events).toEqual(["mcpserver.apply", "mcpserver.connect", "agent.apply"]);
200
- } finally {
201
- rmSync(dir, { recursive: true, force: true });
202
- }
203
- });
204
- });