@sequenceholdings/studio-cli 0.4.3 → 0.4.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.
package/README.md CHANGED
@@ -64,7 +64,9 @@ those come from the Studio repo's own publish pipeline, so new `seq-studio`
64
64
  releases install immediately.)
65
65
 
66
66
  All initializers include a short `AGENTS.md` pointing to the target environment's
67
- live `/docs` and `/docs/llms.txt`, plus a `CLAUDE.md` importing it. Agents should
67
+ live `/docs` and `/docs/llms.txt`, plus a `CLAUDE.md` importing it. Use these paths
68
+ on the actual Atlas URL supplied by your platform administrator; a CLI environment
69
+ name is a configuration label, not a hostname. Agents should
68
70
  read those docs at the start of each task and consult them as needed; platform
69
71
  instructions stay in the hosted docs rather than being copied into scaffolds.
70
72
  Existing agent instruction files are preserved or initialization is refused.
@@ -122,25 +124,18 @@ Use interactive login or the realm-specific M2M secret above.
122
124
  ## Environments
123
125
 
124
126
  The CLI ships with a single built-in environment, `local`
125
- (`http://localhost:5001`). The other environments your identity may target
126
- are **discovered** after you authenticate: the CLI calls the platform's
127
- environment-discovery endpoint and caches the result at
128
- `~/.config/lattice/environments.json`.
127
+ (`http://localhost:5001`). Add your organization's deployment with the name
128
+ and URL your administrator gives you. Registration reads the deployment's
129
+ public sign-in settings; it does not grant access.
129
130
 
130
131
  ```bash
131
- seq-studio login # or use the matching M2M secret described above
132
- seq-studio envs refresh # fetch the environments visible to your identity
133
- seq-studio envs list # show them (name, URL, source)
132
+ seq-studio envs add <name> <url> # register your organization's deployment
133
+ seq-studio login --env <name> # sign in to it
134
+ seq-studio envs list # show configured environments (name, URL, source)
134
135
  ```
135
136
 
136
- Discovery also happens lazily: the first time you pass an `-e <env>` that
137
- isn't cached yet, the CLI refreshes the catalog before failing. What you can
138
- see depends on who you are — unauthenticated installs get `local` only, and
139
- authenticated identities get the deployments they're entitled to. Visibility
140
- is not access control: every request is still authorized server-side.
141
-
142
- You can add or override trusted environments yourself in
143
- `~/.config/lattice/config.toml` (user entries win over discovered ones).
137
+ You can also add or override environments yourself in
138
+ `~/.config/lattice/config.toml`.
144
139
  Authenticated requests accept only HTTPS origins at `seqholdings.com` or its
145
140
  subdomains, plus HTTP loopback origins for local development. The CLI
146
141
  revalidates that exact origin immediately before attaching credentials and
@@ -386,6 +381,27 @@ Application role gives them everything the app needs: each member's end-user
386
381
  access plus the member roles and capabilities the role bundles. Grants are made
387
382
  in Atlas too, never in the manifest.
388
383
 
384
+ **Include everything the app runs on.** Roles can only grant what the
385
+ Application includes, and its access review only covers its members, so a
386
+ complete member list is what makes one role enough:
387
+
388
+ - Every primitive the app deploys. A directory of several agents (or
389
+ processes) becomes several members by giving each its own entry with
390
+ `only:` — entries may share a path when each selects different definitions:
391
+
392
+ ```yaml
393
+ primitives:
394
+ - { id: classify, kind: agent, path: agents/desk, only: ["31b3b339c468f584e458a647"] }
395
+ - { id: draft, kind: agent, path: agents/desk, only: [fd65cc240450d380e18af0b8] }
396
+ ```
397
+ - The service accounts its code runs as, under `service_accounts:`, and the
398
+ secrets its functions and pipelines read, under `secrets:`.
399
+ - Anything shared that another app deploys, under `existing:`.
400
+ - After each deploy, act on the **suggested members** it prints: add what the
401
+ app depends on, or mark what you mean to leave out "not needed" on the
402
+ Application's Members page. A member left out keeps working; the
403
+ Application just can't grant it.
404
+
389
405
  - A role's includes can reach `artifact`, `function`, `orm`, `process`, and
390
406
  `agent` primitives: a member's end-user access (`invoker` on functions,
391
407
  processes and agents), one of its registered roles, or one of its capabilities.
@@ -505,6 +521,25 @@ and inherits only other collaborator roles.
505
521
  - { primitive: desk-api, tier: editor }
506
522
  - { primitive: candescent-oauth, tier: editor }
507
523
  ```
524
+ - Something already deployed elsewhere — another app's function, a shared
525
+ namespace, a process, an agent, an artifact or a pipeline — is included
526
+ without deploying it under a top-level `existing:` block, by the name Atlas
527
+ knows it by: a function's slug, a namespace, a process id, an agent id, an
528
+ artifact's slug, or a pipeline's release unit (`pipelines/<name>`).
529
+ Roles, collaborator roles and `uses` reach it like any member.
530
+
531
+ ```yaml
532
+ existing:
533
+ - { id: billing, kind: function, ref: billing-fn }
534
+ - { id: lending, kind: orm, ref: lending }
535
+ - { id: intake, kind: process, ref: loan-intake }
536
+ ```
537
+ - After registering, `seq-studio deploy` prints **suggested members**: what
538
+ the app's members depend on that it doesn't include — secrets they read,
539
+ accounts they run as, functions and agents their process steps run, data
540
+ they declare, and what traces saw them call — with the lines to paste
541
+ (under `secrets:`, `service_accounts:` or `existing:`). Review them, or mark
542
+ ones you mean to leave out "not needed", on the Application's Members page.
508
543
  - Consent is stricter than for runtime roles: bundling a member's tiers needs
509
544
  **admin** on it (owner, for a process), checked on every deploy.
510
545
  - Only the Application's admins create, edit and grant collaborator roles in
@@ -1310,6 +1345,33 @@ manifest declarations. Never put a secret in `build.public_env` or `NEXT_PUBLIC_
1310
1345
  Local execution runs as your OS user; Atlas does not sandbox your laptop's
1311
1346
  filesystem or arbitrary outbound connections.
1312
1347
 
1348
+ For hosted applications, bind an existing managed secret by its name in the
1349
+ target deployment's organization and pin the exact numeric version:
1350
+
1351
+ ```yaml
1352
+ server:
1353
+ secrets:
1354
+ - name: PAYMENTS_KEY
1355
+ secret_name: PAYMENTS_PROVIDER_KEY
1356
+ version: 1
1357
+ egress:
1358
+ - api.payments.example.com
1359
+ ```
1360
+
1361
+ `name` is the runtime environment variable. `secret_name` is an exact
1362
+ `UPPER_SNAKE_CASE` managed-secret name; `secret_id: <UUID>` remains supported
1363
+ instead. Declare exactly one reference. A deployer needs editor access to the
1364
+ selected secret, and that environment must contain the requested version of a
1365
+ single-value secret. This keeps the same source manifest across environments
1366
+ without copying secret values or environment-specific UUIDs into source.
1367
+ Admission records the resolved secret ID, resource and version; retries and
1368
+ rollbacks recheck authority against those original pins, even if a name is later
1369
+ reused. A new deployment resolves names again. Secret versions are never
1370
+ implicitly upgraded. The CLI, Atlas and the application's Artifact SDK must all
1371
+ contain this manifest support; older SDKs reject `secret_name` during the hosted
1372
+ build. The hosted runtime already allows its own Atlas control-plane hostname,
1373
+ so it does not need an environment-specific entry in `server.egress`.
1374
+
1313
1375
  For an immutable hosted preview, commit the source and connect its Git Service
1314
1376
  repository, then run:
1315
1377
 
@@ -1447,8 +1509,11 @@ editor's Git graph. For an existing folder, discover the clone URL with
1447
1509
  `git remote add origin <clone-url>`, then `git fetch origin`. Fetching does not
1448
1510
  set an upstream: inspect the local and remote histories before using
1449
1511
  `git branch --set-upstream-to=origin/<remote-branch> <local-branch>`.
1450
- See [Connect an existing folder](https://docs.seqholdings.com/seq-studio/repositories#connect-an-existing-folder)
1451
- for handling folders with no commits or separate local history. Verify with
1512
+ See “Connect an existing folder” at
1513
+ `<atlas-origin>/docs/seq-studio/repositories#connect-an-existing-folder`
1514
+ for handling folders with no commits or separate local history. Replace
1515
+ `<atlas-origin>` with the actual Atlas URL supplied by your platform administrator
1516
+ for the target environment. Verify with
1452
1517
  `git branch -vv` and `git status --short --branch`. Plain Git needs its own
1453
1518
  credential-manager or PAT prompt setup; it does not read `ATLAS_GIT_PAT`.
1454
1519
 
@@ -14,3 +14,19 @@ export declare function agentComponentRefs({ manifest, rootDir, env, }: {
14
14
  rootDir: string;
15
15
  env: string;
16
16
  }): Promise<Map<string, string>>;
17
+ /** One deployed agent: its id (set in code, the same in every environment) and name. */
18
+ export interface SelectedAgent {
19
+ id: string;
20
+ name: string;
21
+ }
22
+ /**
23
+ * Primitive id -> every agent an agent entry deploys to `env`, read the way
24
+ * `agents apply` reads the directory. An unreadable directory selects nothing.
25
+ */
26
+ export declare function agentSelections({ manifest, rootDir, env, }: {
27
+ manifest: AppManifest;
28
+ rootDir: string;
29
+ env: string;
30
+ }): Promise<Map<string, SelectedAgent[]>>;
31
+ /** The entries that deploy exactly one agent, and its id: those register as members. */
32
+ export declare function singleAgentRefs(selections: ReadonlyMap<string, readonly SelectedAgent[]>): Map<string, string>;
@@ -11,7 +11,14 @@ import { resolveContainedPrimitivePath } from './paths.js';
11
11
  * failed deploy.
12
12
  */
13
13
  export async function agentComponentRefs({ manifest, rootDir, env, }) {
14
- const refs = new Map();
14
+ return singleAgentRefs(await agentSelections({ manifest, rootDir, env }));
15
+ }
16
+ /**
17
+ * Primitive id -> every agent an agent entry deploys to `env`, read the way
18
+ * `agents apply` reads the directory. An unreadable directory selects nothing.
19
+ */
20
+ export async function agentSelections({ manifest, rootDir, env, }) {
21
+ const selections = new Map();
15
22
  for (const entry of manifest.primitives) {
16
23
  if (entry.kind !== 'agent')
17
24
  continue;
@@ -24,13 +31,18 @@ export async function agentComponentRefs({ manifest, rootDir, env, }) {
24
31
  deployEnvironments: [target],
25
32
  ...(entry.only ? { onlyIds: entry.only } : {}),
26
33
  });
27
- const [only, ...more] = bundle.definitions;
28
- if (only && more.length === 0)
29
- refs.set(entry.id, only.id);
34
+ selections.set(entry.id, bundle.definitions.map((definition) => ({ id: definition.id, name: definition.name })));
30
35
  }
31
36
  catch {
32
- // No ref: the graph shows the agent without resolving it, as before.
37
+ // Nothing selected: the graph shows the agent without resolving it, as before.
33
38
  }
34
39
  }
35
- return refs;
40
+ return selections;
41
+ }
42
+ /** The entries that deploy exactly one agent, and its id: those register as members. */
43
+ export function singleAgentRefs(selections) {
44
+ return new Map([...selections].flatMap(([entryId, agents]) => {
45
+ const [only, ...more] = agents;
46
+ return only && more.length === 0 ? [[entryId, only.id]] : [];
47
+ }));
36
48
  }
@@ -11,10 +11,12 @@
11
11
  * are the artifact/function/ORM primitives, single-process entries and
12
12
  * pipelines, referenced by the stable names that resolve in every environment,
13
13
  * single-agent entries, referenced by the agent id they deploy to the target
14
- * environment (agent-refs.ts), the app's `secrets`, by name, and its
15
- * `service_accounts`, by slug.
14
+ * environment (agent-refs.ts), the app's `secrets`, by name, its
15
+ * `service_accounts`, by slug, and its `existing` members — deployed
16
+ * elsewhere, included here by ref without deploying them.
16
17
  */
17
18
  import { type ClientOptions } from '../atlas-client.js';
19
+ import { type ApplicationSuggestion, type SharedAgentEntry } from './application-suggestions.js';
18
20
  import { type AppManifest, type PrimitiveEntry } from './manifest.js';
19
21
  type MemberKind = 'artifact' | 'function' | 'orm' | 'lattice' | 'pipeline' | 'agent' | 'secret' | 'service_account';
20
22
  export interface ApplicationDeployMember {
@@ -103,6 +105,10 @@ export type ApplicationRegistration = {
103
105
  requested?: ApplicationConsentRequest[];
104
106
  /** The Application's Runtime access page, where access gaps are fixed. */
105
107
  accessUrl?: string;
108
+ /** What its members depend on that it doesn't include. Absent when Atlas couldn't say. */
109
+ suggestions?: ApplicationSuggestion[];
110
+ /** Its Members page, where suggestions are reviewed or marked not needed. */
111
+ membersUrl?: string;
106
112
  } | {
107
113
  status: 'failed';
108
114
  message: string;
@@ -124,9 +130,11 @@ export declare function putApplication({ client, manifest, agentRefs, }: {
124
130
  manifest: AppManifest;
125
131
  agentRefs?: ReadonlyMap<string, string>;
126
132
  }): Promise<ApplicationRegistration>;
127
- export declare function logApplicationRegistration({ appId, registration, }: {
133
+ export declare function logApplicationRegistration({ appId, registration, sharedAgentEntries, }: {
128
134
  appId: string;
129
135
  registration: ApplicationRegistration;
136
+ /** Agent entries that deploy several agents, so a suggested agent among them is fixed by splitting the entry. */
137
+ sharedAgentEntries?: readonly SharedAgentEntry[];
130
138
  }): void;
131
139
  /** Default registrar: authenticate against `env` the same way the primitive deployers do. */
132
140
  export declare const registerApplicationWithAtlas: RegisterApplication;
@@ -11,10 +11,12 @@
11
11
  * are the artifact/function/ORM primitives, single-process entries and
12
12
  * pipelines, referenced by the stable names that resolve in every environment,
13
13
  * single-agent entries, referenced by the agent id they deploy to the target
14
- * environment (agent-refs.ts), the app's `secrets`, by name, and its
15
- * `service_accounts`, by slug.
14
+ * environment (agent-refs.ts), the app's `secrets`, by name, its
15
+ * `service_accounts`, by slug, and its `existing` members — deployed
16
+ * elsewhere, included here by ref without deploying them.
16
17
  */
17
18
  import { AtlasApiError, putJson } from '../atlas-client.js';
19
+ import { fetchApplicationSuggestions, logApplicationSuggestions } from './application-suggestions.js';
18
20
  import { buildContext, clientOptions } from '../functions/commands.js';
19
21
  import { pipelineReleaseUnit } from './adapters.js';
20
22
  import { isFloorRoleAlias } from './manifest.js';
@@ -43,6 +45,10 @@ function memberOf(entry, agentRefs) {
43
45
  return { key: entry.id, kind: 'lattice', ref: processId };
44
46
  return null;
45
47
  }
48
+ /** An `existing` entry's member kind: YAML says `process`, Atlas `lattice`. */
49
+ function existingKind(kind) {
50
+ return kind === 'process' ? 'lattice' : kind;
51
+ }
46
52
  function componentRef(entry, agentRefs) {
47
53
  switch (entry.kind) {
48
54
  case 'artifact': return entry.project_id;
@@ -95,6 +101,7 @@ export function buildApplicationDeployBody(manifest, { agentRefs = new Map() } =
95
101
  return member ? [member] : [];
96
102
  }),
97
103
  ...(manifest.secrets ?? []).map((secret) => ({ key: secret.id, kind: 'secret', ref: secret.name })),
104
+ ...(manifest.existing ?? []).map((entry) => ({ key: entry.id, kind: existingKind(entry.kind), ref: entry.ref })),
98
105
  ...(manifest.service_accounts ?? []).map((account) => ({ key: account.id, kind: 'service_account', ref: account.slug })),
99
106
  ],
100
107
  components: [
@@ -103,6 +110,7 @@ export function buildApplicationDeployBody(manifest, { agentRefs = new Map() } =
103
110
  return { key: entry.id, kind: entry.kind, ...(ref !== undefined ? { ref } : {}) };
104
111
  }),
105
112
  ...(manifest.secrets ?? []).map((secret) => ({ key: secret.id, kind: 'secret', ref: secret.name })),
113
+ ...(manifest.existing ?? []).map((entry) => ({ key: entry.id, kind: entry.kind, ref: entry.ref })),
106
114
  ...(manifest.service_accounts ?? []).map((account) => ({ key: account.id, kind: 'service_account', ref: account.slug })),
107
115
  ],
108
116
  edges: manifest.primitives.flatMap((entry) => entry.uses.map((use) => ({ from: entry.id, to: use.primitive, ...(use.as !== undefined ? { label: use.as } : {}) }))),
@@ -161,7 +169,7 @@ export async function putApplication({ client, manifest, agentRefs = new Map(),
161
169
  return {
162
170
  status: 'failed',
163
171
  message: `roles include agent entries that don't deploy exactly one agent here: ${unresolved.join(', ')}. ` +
164
- 'Set only: [<agent-id>] on each so its roles reach one agent.',
172
+ 'Give each agent its own entry with only: [<agent-id>] (entries may share the path) so its roles reach one agent.',
165
173
  };
166
174
  }
167
175
  const path = `/api/custom-roles/applications/${encodeURIComponent(manifest.app.id)}`;
@@ -190,8 +198,11 @@ export async function putApplication({ client, manifest, agentRefs = new Map(),
190
198
  }]
191
199
  : [];
192
200
  });
193
- const accessUrl = new URL(`/permissions/applications/application/${encodeURIComponent(manifest.app.id)}?tab=roles`, client.baseUrl).toString();
194
- return { status: 'registered', created: response.created === true, warnings, requested, accessUrl };
201
+ const pageUrl = (tab) => new URL(`/permissions/applications/application/${encodeURIComponent(manifest.app.id)}?tab=${tab}`, client.baseUrl).toString();
202
+ const suggestions = await fetchApplicationSuggestions({ client, appId: manifest.app.id });
203
+ const created = response.created === true;
204
+ const extra = suggestions ? { suggestions, membersUrl: pageUrl('members') } : {};
205
+ return { status: 'registered', created, warnings, requested, accessUrl: pageUrl('roles'), ...extra };
195
206
  }
196
207
  catch (error) {
197
208
  if (!(error instanceof AtlasApiError))
@@ -199,7 +210,7 @@ export async function putApplication({ client, manifest, agentRefs = new Map(),
199
210
  return { status: 'failed', message: [error.message, ...errorDetailLines(error)].join('\n') };
200
211
  }
201
212
  }
202
- export function logApplicationRegistration({ appId, registration, }) {
213
+ export function logApplicationRegistration({ appId, registration, sharedAgentEntries = [], }) {
203
214
  if (registration.status === 'failed') {
204
215
  console.error(`${LOG} ✗ Application "${appId}" registration failed: ${registration.message}`);
205
216
  return;
@@ -228,6 +239,9 @@ export function logApplicationRegistration({ appId, registration, }) {
228
239
  }
229
240
  console.warn(`${LOG} Admins approve from Permissions → the member → Applications, or by redeploying as someone who administers it.`);
230
241
  }
242
+ if (registration.suggestions && registration.membersUrl) {
243
+ logApplicationSuggestions({ appId, suggestions: registration.suggestions, membersUrl: registration.membersUrl, sharedAgentEntries });
244
+ }
231
245
  }
232
246
  /** Default registrar: authenticate against `env` the same way the primitive deployers do. */
233
247
  export const registerApplicationWithAtlas = async ({ manifest, env, agentRefs }) => {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Suggested members after a deploy: what the Application's members depend on
3
+ * that `sequence.app.yml` doesn't include, read from Atlas
4
+ * (`GET /api/custom-roles/applications/<id>/suggestions`) and printed with
5
+ * the lines that would include them. Best-effort: a deployer who can't read
6
+ * them, or an older Atlas, just sees none.
7
+ */
8
+ import { type ClientOptions } from '../atlas-client.js';
9
+ import type { SelectedAgent } from './agent-refs.js';
10
+ import type { AppManifest } from './manifest.js';
11
+ /** An agent entry that deploys several agents from one directory: none of them can be a member as it stands. */
12
+ export interface SharedAgentEntry {
13
+ id: string;
14
+ path: string;
15
+ /** The environment it deploys to, when not the CLI's: the split entries keep it so they select the same agents. */
16
+ target?: string;
17
+ /** Its prerequisites and runtime uses, which each split entry keeps. */
18
+ dependsOn?: string[];
19
+ uses?: Array<{
20
+ primitive: string;
21
+ as?: string;
22
+ }>;
23
+ /** Entries and roles that name it, and so need to name the split entries instead. */
24
+ referencedBy?: string[];
25
+ agents: SelectedAgent[];
26
+ }
27
+ /** The manifest's agent entries that deploy more than one agent. */
28
+ export declare function sharedAgentEntries(manifest: AppManifest, selections: ReadonlyMap<string, readonly SelectedAgent[]>): SharedAgentEntry[];
29
+ /** The entries that replace a shared one, one per agent, so each can be a member. */
30
+ export declare function splitAgentEntries(entry: SharedAgentEntry): Array<{
31
+ id: string;
32
+ line: string;
33
+ }>;
34
+ export interface ApplicationSuggestion {
35
+ kind: string;
36
+ name: string;
37
+ ref: string;
38
+ /** Why, in a few words: "read by fn", "run by a step in intake". */
39
+ reasons: string[];
40
+ declared: boolean;
41
+ yaml: {
42
+ block: string;
43
+ line: string;
44
+ };
45
+ }
46
+ /** The Application's open suggestions (dismissed ones left out), or null when they can't be read. */
47
+ export declare function fetchApplicationSuggestions({ client, appId, }: {
48
+ client: ClientOptions;
49
+ appId: string;
50
+ }): Promise<ApplicationSuggestion[] | null>;
51
+ /** Print what to add, grouped as it goes into `sequence.app.yml`. */
52
+ export declare function logApplicationSuggestions({ appId, suggestions, membersUrl, sharedAgentEntries, }: {
53
+ appId: string;
54
+ suggestions: readonly ApplicationSuggestion[];
55
+ membersUrl: string;
56
+ /** This repo's agent entries that deploy several agents. */
57
+ sharedAgentEntries?: readonly SharedAgentEntry[];
58
+ }): void;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Suggested members after a deploy: what the Application's members depend on
3
+ * that `sequence.app.yml` doesn't include, read from Atlas
4
+ * (`GET /api/custom-roles/applications/<id>/suggestions`) and printed with
5
+ * the lines that would include them. Best-effort: a deployer who can't read
6
+ * them, or an older Atlas, just sees none.
7
+ */
8
+ import { getJsonOr404 } from '../atlas-client.js';
9
+ const LOG = '[seq-studio]';
10
+ /** How many to print before pointing at Atlas for the rest. */
11
+ const PRINT_LIMIT = 8;
12
+ /** The manifest's agent entries that deploy more than one agent. */
13
+ export function sharedAgentEntries(manifest, selections) {
14
+ return manifest.primitives.flatMap((entry) => {
15
+ const agents = selections.get(entry.id) ?? [];
16
+ if (entry.kind !== 'agent' || agents.length <= 1)
17
+ return [];
18
+ return [{
19
+ id: entry.id,
20
+ path: entry.path,
21
+ ...(entry.target ? { target: entry.target } : {}),
22
+ dependsOn: entry.depends_on,
23
+ uses: entry.uses,
24
+ referencedBy: referencesTo(manifest, entry.id),
25
+ agents: [...agents],
26
+ }];
27
+ });
28
+ }
29
+ /** The entries (`depends_on`, `uses`) and roles that name `id`. */
30
+ function referencesTo(manifest, id) {
31
+ const entries = manifest.primitives
32
+ .filter((other) => other.depends_on.includes(id) || other.uses.some((use) => use.primitive === id))
33
+ .map((other) => other.id);
34
+ const roles = Object.entries(manifest.roles?.definitions ?? {}).flatMap(([key, definition]) => definition.includes.some((include) => include.primitive === id) ? [`roles.${key}`] : []);
35
+ const collaborators = Object.entries(manifest.collaborators?.definitions ?? {}).flatMap(([key, definition]) => definition.includes.some((include) => include.primitive === id) ? [`collaborators.${key}`] : []);
36
+ return [...entries, ...roles, ...collaborators];
37
+ }
38
+ /** Words YAML loads as booleans or null rather than strings. */
39
+ const YAML_RESERVED = new Set(['true', 'false', 'yes', 'no', 'on', 'off', 'y', 'n', 'null']);
40
+ /** A YAML flow value that loads as this string: plain when safe, quoted otherwise (as Atlas writes suggestions). */
41
+ function yamlValue(value) {
42
+ return /^[A-Za-z_][A-Za-z0-9_./-]*$/.test(value) && !YAML_RESERVED.has(value.toLowerCase()) ? value : JSON.stringify(value);
43
+ }
44
+ /** A manifest id from an agent's name. */
45
+ function entryId(name) {
46
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'agent';
47
+ }
48
+ /** The original entry's target, carried to each split entry. */
49
+ function splitExtras(entry) {
50
+ return entry.target ? `, target: ${yamlValue(entry.target)}` : '';
51
+ }
52
+ /** The original entry's prerequisites and uses, carried to each split entry. */
53
+ function dependencyExtras(entry) {
54
+ const dependsOn = entry.dependsOn?.length ? `, depends_on: [${entry.dependsOn.map(yamlValue).join(', ')}]` : '';
55
+ const uses = entry.uses?.length
56
+ ? `, uses: [${entry.uses.map((use) => `{ primitive: ${yamlValue(use.primitive)}${use.as ? `, as: ${yamlValue(use.as)}` : ''} }`).join(', ')}]`
57
+ : '';
58
+ return dependsOn + uses;
59
+ }
60
+ /** The entries that replace a shared one, one per agent, so each can be a member. */
61
+ export function splitAgentEntries(entry) {
62
+ const taken = new Set();
63
+ return entry.agents.map((agent) => {
64
+ let id = entryId(agent.name);
65
+ for (let suffix = 2; taken.has(id); suffix++)
66
+ id = `${entryId(agent.name)}-${suffix}`;
67
+ taken.add(id);
68
+ const line = `- { id: ${yamlValue(id)}, kind: agent, path: ${yamlValue(entry.path)}${splitExtras(entry)}, only: [${yamlValue(agent.id)}]${dependencyExtras(entry)} }`;
69
+ return { id, line };
70
+ });
71
+ }
72
+ /** Print the per-agent entries that replace a shared one, and what to repoint at them. */
73
+ function logAgentSplit(entry) {
74
+ console.warn(`${LOG} "${entry.id}" deploys ${entry.agents.length} agents from ${entry.path}, so none can be a member. Replace it with one entry per agent:`);
75
+ const split = splitAgentEntries(entry);
76
+ for (const { line } of split)
77
+ console.warn(` ${line}`);
78
+ if (entry.referencedBy?.length) {
79
+ console.warn(`${LOG} Then point ${entry.referencedBy.join(', ')} at ${split.map(({ id }) => id).join(', ')} instead of ${entry.id}.`);
80
+ }
81
+ }
82
+ const KIND_LABEL = {
83
+ artifact: 'artifact',
84
+ function: 'function',
85
+ orm: 'ORM namespace',
86
+ lattice: 'process',
87
+ agent: 'agent',
88
+ secret: 'secret',
89
+ service_account: 'service account',
90
+ };
91
+ const asRecord = (value) => typeof value === 'object' && value !== null ? value : {}; // narrowed: a non-null object
92
+ const isString = (value) => typeof value === 'string';
93
+ /** One reason, as a deploy log says it. */
94
+ function reasonOf(evidence) {
95
+ const member = isString(evidence.member) ? evidence.member : null;
96
+ if (!member)
97
+ return null;
98
+ switch (evidence.type) {
99
+ case 'reads_secret': return `read by ${member}`;
100
+ case 'runs_as': return `${member} runs as it`;
101
+ case 'runs_step': return `a step in ${member} runs it`;
102
+ case 'agent_uses': return `${member} uses it${evidence.required === true ? ' (required)' : ''}`;
103
+ case 'declares_data': return `${member} ${evidence.write === true ? 'writes' : 'reads'} its data`;
104
+ case 'invokes': return `${member} calls it`;
105
+ case 'calls': return typeof evidence.calls === 'number' ? `${member} called it ${evidence.calls.toLocaleString('en-US')} times` : null;
106
+ default: return null;
107
+ }
108
+ }
109
+ /** The Application's open suggestions (dismissed ones left out), or null when they can't be read. */
110
+ export async function fetchApplicationSuggestions({ client, appId, }) {
111
+ try {
112
+ const response = await getJsonOr404({
113
+ ...client,
114
+ path: `/api/custom-roles/applications/${encodeURIComponent(appId)}/suggestions`,
115
+ });
116
+ const list = asRecord(response?.suggestions).suggestions;
117
+ if (!Array.isArray(list))
118
+ return null;
119
+ return list.flatMap((entry) => {
120
+ const { kind, name, ref, evidence, declared, dismissed, yaml } = asRecord(entry);
121
+ const { block, line } = asRecord(yaml);
122
+ if (dismissed === true || !isString(kind) || !isString(name) || !isString(ref) || !isString(block) || !isString(line))
123
+ return [];
124
+ const reasons = (Array.isArray(evidence) ? evidence : []).flatMap((item) => reasonOf(asRecord(item)) ?? []);
125
+ return [{ kind, name, ref, reasons, declared: declared === true, yaml: { block, line } }];
126
+ });
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ /** Print what to add, grouped as it goes into `sequence.app.yml`. */
133
+ export function logApplicationSuggestions({ appId, suggestions, membersUrl, sharedAgentEntries = [], }) {
134
+ if (suggestions.length === 0)
135
+ return;
136
+ const shown = suggestions.slice(0, PRINT_LIMIT);
137
+ // A suggested agent this repo already deploys from a shared entry: split the entry, don't reference it.
138
+ const splitting = sharedAgentEntries.filter((entry) => entry.agents.some((agent) => shown.some((suggestion) => suggestion.kind === 'agent' && suggestion.ref === agent.id)));
139
+ const deployedHere = new Set(splitting.flatMap((entry) => entry.agents.map((agent) => agent.id)));
140
+ console.warn(`${LOG} Suggested members — "${appId}" doesn't include these, but its members depend on them:`);
141
+ for (const suggestion of shown) {
142
+ const label = KIND_LABEL[suggestion.kind] ?? suggestion.kind;
143
+ const named = suggestion.name === suggestion.ref ? suggestion.name : `${suggestion.name} (${suggestion.ref})`;
144
+ const why = suggestion.reasons.slice(0, 2).join('; ') + (suggestion.reasons.length > 2 ? `; +${suggestion.reasons.length - 2} more` : '');
145
+ console.warn(`${LOG} ${label} ${named}${why ? ` — ${why}` : ''}${suggestion.declared ? '' : ' (seen in traffic)'}`);
146
+ }
147
+ for (const entry of splitting)
148
+ logAgentSplit(entry);
149
+ const blocks = new Map();
150
+ for (const suggestion of shown) {
151
+ if (suggestion.kind === 'agent' && deployedHere.has(suggestion.ref))
152
+ continue;
153
+ blocks.set(suggestion.yaml.block, [...(blocks.get(suggestion.yaml.block) ?? []), suggestion.yaml.line]);
154
+ }
155
+ if (blocks.size > 0)
156
+ console.warn(`${LOG} Add ${splitting.length > 0 ? 'the rest' : 'them'} to sequence.app.yml:`);
157
+ for (const [block, lines] of blocks) {
158
+ console.warn(` ${block}:`);
159
+ for (const line of lines)
160
+ console.warn(` ${line}`);
161
+ }
162
+ const more = suggestions.length - shown.length;
163
+ console.warn(`${LOG} ${more > 0 ? `${more} more, and ` : ''}"Not needed" for any you mean to leave out: ${membersUrl}`);
164
+ }
@@ -9,7 +9,8 @@ import { randomUUID } from 'node:crypto';
9
9
  import { existsSync } from 'node:fs';
10
10
  import { join, resolve } from 'node:path';
11
11
  import { ensureAppOutputDirectory, resolveContainedPrimitivePath } from './paths.js';
12
- import { agentComponentRefs } from './agent-refs.js';
12
+ import { agentSelections, singleAgentRefs } from './agent-refs.js';
13
+ import { sharedAgentEntries } from './application-suggestions.js';
13
14
  export { resolveContainedPrimitivePath } from './paths.js';
14
15
  import { executeDeployment } from './run-deployment.js';
15
16
  import { buildApplicationDeployBody, logApplicationRegistration, registerApplicationWithAtlas, } from './application-registration.js';
@@ -39,12 +40,13 @@ async function registerApplicationStep({ manifest, options, result, rootDir, })
39
40
  return;
40
41
  }
41
42
  const register = options.registerApplication ?? registerApplicationWithAtlas;
42
- const agentRefs = await agentComponentRefs({ manifest, rootDir, env: options.env });
43
+ const selections = await agentSelections({ manifest, rootDir, env: options.env });
44
+ const agentRefs = singleAgentRefs(selections);
43
45
  const registration = await register({ manifest, env: options.env, agentRefs }).catch((error) => ({
44
46
  status: 'failed',
45
47
  message: error instanceof Error ? error.message : String(error),
46
48
  }));
47
- logApplicationRegistration({ appId: manifest.app.id, registration });
49
+ logApplicationRegistration({ appId: manifest.app.id, registration, sharedAgentEntries: sharedAgentEntries(manifest, selections) });
48
50
  result.application = registration;
49
51
  if (registration.status === 'failed')
50
52
  result.exitCode = 1;
@@ -145,7 +147,8 @@ export async function deployApp(options) {
145
147
  }
146
148
  if (options.dryRun) {
147
149
  if (manifest.schema_version === 3) {
148
- const body = buildApplicationDeployBody(manifest);
150
+ const agentRefs = singleAgentRefs(await agentSelections({ manifest, rootDir, env: options.env }));
151
+ const body = buildApplicationDeployBody(manifest, { agentRefs });
149
152
  console.log(`${LOG} dry-run: would register Application "${manifest.app.id}" ` +
150
153
  `(${body.members.length} member(s), ${Object.keys(body.capabilities).length} capability(ies), ` +
151
154
  `${Object.keys(body.roles).length} role(s) and ${Object.keys(body.collaborators).length} collaborator role(s) to seed)`);
@@ -121,11 +121,11 @@ function isBindingText(name) {
121
121
  return TEXT_EXTENSIONS.has(extension);
122
122
  }
123
123
  async function defaultBindingContext(envName) {
124
- const { readConfig, resolveEnvWithDiscovery } = await import('../config.js');
124
+ const { readConfig, resolveConfiguredEnv } = await import('../config.js');
125
125
  const { getAccessTokenWithMode } = await import('../auth.js');
126
126
  const { getJson, patchJson, postJson, putJson, deleteJson } = await import('../atlas-client.js');
127
127
  const { storageClient } = await import('@sequenceholdings/storage');
128
- const env = await resolveEnvWithDiscovery({ requested: envName });
128
+ const env = await resolveConfiguredEnv({ requested: envName });
129
129
  const deployOrigin = canonicalDeploymentOrigin(env.url);
130
130
  if (!deployOrigin)
131
131
  throw new Error(`Invalid deployment URL '${env.url}'.`);
@@ -19,6 +19,11 @@ type ManifestGraph = {
19
19
  id: string;
20
20
  slug: string;
21
21
  }[];
22
+ existing?: {
23
+ id: string;
24
+ kind: string;
25
+ ref: string;
26
+ }[];
22
27
  roles?: {
23
28
  definitions: Record<string, {
24
29
  inherits: string[];