@sequenceholdings/studio-cli 0.2.2 → 0.4.1

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 (128) hide show
  1. package/README.md +616 -78
  2. package/dist/access/commands.d.ts +3 -0
  3. package/dist/access/commands.js +91 -0
  4. package/dist/agents/commands.d.ts +1 -1
  5. package/dist/agents/commands.js +5 -0
  6. package/dist/agents/scaffold.js +5 -7
  7. package/dist/agents/voice-authoring.d.ts +5 -0
  8. package/dist/agents/voice-authoring.js +75 -0
  9. package/dist/agents/voice-publication.d.ts +5 -0
  10. package/dist/agents/voice-publication.js +63 -0
  11. package/dist/agents/voice-shared.d.ts +20 -0
  12. package/dist/agents/voice-shared.js +112 -0
  13. package/dist/agents/voice.d.ts +3 -0
  14. package/dist/agents/voice.js +57 -0
  15. package/dist/app/adapters.d.ts +6 -0
  16. package/dist/app/adapters.js +17 -2
  17. package/dist/app/agent-refs.d.ts +16 -0
  18. package/dist/app/agent-refs.js +36 -0
  19. package/dist/app/application-registration.d.ts +36 -6
  20. package/dist/app/application-registration.js +60 -15
  21. package/dist/app/commands.js +19 -2
  22. package/dist/app/deploy.d.ts +3 -0
  23. package/dist/app/deploy.js +22 -6
  24. package/dist/app/env-bindings.d.ts +21 -0
  25. package/dist/app/env-bindings.js +184 -0
  26. package/dist/app/manifest-validation.js +8 -0
  27. package/dist/app/manifest.d.ts +32 -14
  28. package/dist/app/manifest.js +16 -6
  29. package/dist/app/primitive-scaffold.d.ts +4 -1
  30. package/dist/app/primitive-scaffold.js +4 -4
  31. package/dist/app/readme.js +1 -0
  32. package/dist/app/scaffold-files.js +1 -1
  33. package/dist/app/scaffold.d.ts +6 -4
  34. package/dist/app/scaffold.js +7 -4
  35. package/dist/app/workspace-scaffold.js +12 -7
  36. package/dist/argv.d.ts +7 -0
  37. package/dist/argv.js +56 -0
  38. package/dist/artifact/delegate.js +8 -4
  39. package/dist/atlas-client.d.ts +6 -0
  40. package/dist/atlas-client.js +39 -2
  41. package/dist/auth-cmds/commands.d.ts +1 -1
  42. package/dist/auth-cmds/commands.js +16 -0
  43. package/dist/auth.d.ts +32 -0
  44. package/dist/auth.js +170 -33
  45. package/dist/bin.js +23 -4
  46. package/dist/command-contract.d.ts +137 -0
  47. package/dist/command-contract.js +43 -0
  48. package/dist/command-help.d.ts +8 -0
  49. package/dist/command-help.js +71 -0
  50. package/dist/command-input.d.ts +15 -0
  51. package/dist/command-input.js +33 -0
  52. package/dist/functions/commands.d.ts +2 -1
  53. package/dist/functions/commands.js +78 -33
  54. package/dist/functions/deploy-preflight.d.ts +21 -0
  55. package/dist/functions/deploy-preflight.js +58 -0
  56. package/dist/functions/egress-postgres.d.ts +7 -0
  57. package/dist/functions/egress-postgres.js +36 -0
  58. package/dist/functions/manifest.d.ts +15 -1
  59. package/dist/functions/manifest.js +49 -12
  60. package/dist/functions/secret-reconcile.d.ts +3 -3
  61. package/dist/functions/secret-reconcile.js +5 -7
  62. package/dist/functions/source-selection.js +4 -1
  63. package/dist/main.d.ts +2 -0
  64. package/dist/main.js +75 -25
  65. package/dist/manifest-roles-notice.d.ts +33 -0
  66. package/dist/manifest-roles-notice.js +75 -0
  67. package/dist/orm/delegate.d.ts +16 -0
  68. package/dist/orm/delegate.js +142 -7
  69. package/dist/pipeline/clone-deploy.d.ts +37 -0
  70. package/dist/pipeline/clone-deploy.js +125 -0
  71. package/dist/pipeline/codegen.js +6 -2
  72. package/dist/pipeline/commands.js +21 -5
  73. package/dist/pipeline/lifecycle.d.ts +1 -0
  74. package/dist/pipeline/lifecycle.js +95 -44
  75. package/dist/pipeline/repin-orm.js +6 -2
  76. package/dist/pipeline/stage-secrets.d.ts +4 -1
  77. package/dist/pipeline/stage-secrets.js +7 -3
  78. package/dist/process/build.js +17 -0
  79. package/dist/process/codegen.js +16 -0
  80. package/dist/process/commands.d.ts +15 -7
  81. package/dist/process/commands.js +294 -98
  82. package/dist/process/lint.js +35 -0
  83. package/dist/process/plan-diff.js +9 -0
  84. package/dist/process/simulate.js +8 -0
  85. package/dist/release-age.d.ts +12 -0
  86. package/dist/release-age.js +24 -0
  87. package/dist/repos/commands.d.ts +10 -1
  88. package/dist/repos/commands.js +42 -8
  89. package/dist/repos/pulls.d.ts +3 -0
  90. package/dist/repos/pulls.js +131 -0
  91. package/dist/scaffold-guidance.d.ts +4 -0
  92. package/dist/scaffold-guidance.js +15 -0
  93. package/dist/secrets/commands.d.ts +1 -1
  94. package/dist/secrets/commands.js +97 -16
  95. package/dist/service-accounts/commands.d.ts +3 -0
  96. package/dist/service-accounts/commands.js +50 -0
  97. package/dist/storage/commands.js +23 -1
  98. package/dist/storage/gcs-download.d.ts +13 -0
  99. package/dist/storage/gcs-download.js +41 -0
  100. package/dist/storage/import-cycle.d.ts +41 -0
  101. package/dist/storage/import-cycle.js +123 -0
  102. package/dist/storage/import-files.d.ts +30 -0
  103. package/dist/storage/import-files.js +133 -0
  104. package/dist/storage/import-gcloud.d.ts +12 -0
  105. package/dist/storage/import-gcloud.js +54 -0
  106. package/dist/storage/import-identity.d.ts +12 -0
  107. package/dist/storage/import-identity.js +15 -0
  108. package/dist/storage/import-plan.d.ts +120 -0
  109. package/dist/storage/import-plan.js +189 -0
  110. package/dist/storage/import-preflight.d.ts +36 -0
  111. package/dist/storage/import-preflight.js +62 -0
  112. package/dist/storage/import-progress-map.d.ts +5 -0
  113. package/dist/storage/import-progress-map.js +22 -0
  114. package/dist/storage/import-recover.d.ts +97 -0
  115. package/dist/storage/import-recover.js +186 -0
  116. package/dist/storage/import-run.d.ts +14 -0
  117. package/dist/storage/import-run.js +140 -0
  118. package/dist/templates/guidance/AGENTS.md +10 -0
  119. package/dist/templates/guidance/CLAUDE.md +1 -0
  120. package/dist/templates/process/package.json +2 -2
  121. package/dist/templates/process/pnpm-workspace.yaml +7 -4
  122. package/dist/validation-detail.d.ts +2 -0
  123. package/dist/validation-detail.js +20 -0
  124. package/package.json +9 -9
  125. package/templates/guidance/AGENTS.md +10 -0
  126. package/templates/guidance/CLAUDE.md +1 -0
  127. package/templates/process/package.json +2 -2
  128. package/templates/process/pnpm-workspace.yaml +7 -4
@@ -226,6 +226,22 @@ function emitNode(node, ctx) {
226
226
  ];
227
227
  return call('defineManagedFunctionNode', fields);
228
228
  }
229
+ case 'managed_server': {
230
+ ctx.used.add('defineManagedServerNode');
231
+ const fields = [
232
+ ...head,
233
+ ` server: ${lit(String(m.server_id))},`,
234
+ ` path: ${lit(String(m.path))},`,
235
+ m.limits !== undefined ? ` limits: ${pretty(m.limits, 1)},` : null,
236
+ runAsField(m.run_as),
237
+ bindings(m.bindings),
238
+ middleware(m.middleware, ctx),
239
+ mapper('input', m.input_mapper_source, m.input_mapper_expr, ctx),
240
+ mapper('output', undefined, m.output_mapper_expr, ctx),
241
+ tail,
242
+ ];
243
+ return call('defineManagedServerNode', fields);
244
+ }
229
245
  default:
230
246
  throw new Error(`codegen: unsupported node kind "${node.kind}" (node "${node.id}")`);
231
247
  }
@@ -4,13 +4,9 @@
4
4
  * happens through `atlas-client.ts` and `getAccessToken()`; commands
5
5
  * themselves do not know about the token file or config TOML.
6
6
  */
7
- export interface ParsedArgs {
8
- positional: string[];
9
- flags: Record<string, string | true>;
10
- /** All string values for flags supplied more than once; `flags` keeps the last value. */
11
- repeatedFlags?: Record<string, string[]>;
12
- }
13
- export declare function parseArgs(rest: string[]): ParsedArgs;
7
+ import { type ParsedArgs } from '../argv.js';
8
+ export { parseArgs } from '../argv.js';
9
+ export type { ParsedArgs } from '../argv.js';
14
10
  export type ProcessSourceSpec = {
15
11
  kind: 'local';
16
12
  } | {
@@ -65,4 +61,16 @@ export declare function pullCommand(args: ParsedArgs): Promise<number>;
65
61
  export declare function promoteCommand(args: ParsedArgs): Promise<number>;
66
62
  export declare function bundleCommand(args: ParsedArgs): Promise<number>;
67
63
  export declare function simulateCommand(args: ParsedArgs): Promise<number>;
64
+ interface RuntimePackageDiagnostic {
65
+ status: 'resolved' | 'unavailable';
66
+ version?: string;
67
+ path?: string;
68
+ packagePath?: string;
69
+ entrypointExists?: boolean;
70
+ configuredOverride?: string;
71
+ overrideExists?: boolean;
72
+ detail?: string;
73
+ }
74
+ /** Resolve this source module's owning package metadata without following its `exports` entry. */
75
+ export declare function runtimePackageMetadataDiagnostic(name: string, modulePath: string): Promise<RuntimePackageDiagnostic>;
68
76
  export declare function doctorCommand(args: ParsedArgs): Promise<number>;
@@ -7,12 +7,14 @@
7
7
  import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
8
8
  import { existsSync } from 'node:fs';
9
9
  import { dirname, join, relative, resolve } from 'node:path';
10
+ import { createRequire } from 'node:module';
10
11
  import { fileURLToPath } from 'node:url';
11
12
  import { forEachSerializedNode, } from '@sequenceholdings/lattice/bundle';
12
13
  import { getJson, getJsonOr404, postJson, AtlasApiError } from '../atlas-client.js';
13
14
  import { generateProcessFiles } from './codegen.js';
14
- import { getAccessToken, getAccessTokenWithMode, NotLoggedInError, } from '../auth.js';
15
- import { readConfig, resolveEnvWithDiscovery } from '../config.js';
15
+ import { getAccessToken, getAccessTokenWithMode, inspectAuthPreflight, AuthTokenStoreError, NotLoggedInError, } from '../auth.js';
16
+ import { readConfig, resolveEnv, resolveEnvWithDiscovery } from '../config.js';
17
+ import { writeScaffoldGuidance } from '../scaffold-guidance.js';
16
18
  import { finalizeCompiledBundle, summarizeBundle } from './build.js';
17
19
  import { buildResolveProcessPinFromEnv } from './resolve-process-pin.js';
18
20
  import { loadBundleForPublish } from './local-bundle.js';
@@ -24,89 +26,7 @@ import { buildAgentSchemaLoader } from './agent-loader.js';
24
26
  import { localGitMetadata, resolveArtifactSource, } from '@sequenceholdings/artifact-studio/source-resolver';
25
27
  import { prepareProcessBuildRoot } from './repo-install.js';
26
28
  import { compileProcessSourceIsolated, simulateProcessIsolated, } from './compiler-subprocess.js';
27
- export function parseArgs(rest) {
28
- const positional = [];
29
- const flags = {};
30
- const repeatedFlags = {};
31
- const setFlag = (key, value) => {
32
- flags[key] = value;
33
- if (typeof value === 'string') {
34
- const values = repeatedFlags[key] ?? [];
35
- values.push(value);
36
- repeatedFlags[key] = values;
37
- }
38
- };
39
- for (let i = 0; i < rest.length; i++) {
40
- const arg = rest[i];
41
- if (arg === '--') {
42
- positional.push(...rest.slice(i + 1));
43
- break;
44
- }
45
- if (arg.startsWith('--')) {
46
- const body = arg.slice(2);
47
- // Accept `--key=value` (POSIX-style). Without this, `--env=staging`
48
- // would land in flags as `env=staging` → true and resolveEnv
49
- // would fall back to default_env, silently deploying to the
50
- // wrong target.
51
- const eqIdx = body.indexOf('=');
52
- if (eqIdx >= 0) {
53
- setFlag(body.slice(0, eqIdx), body.slice(eqIdx + 1));
54
- continue;
55
- }
56
- const key = body;
57
- const next = rest[i + 1];
58
- // Same sentinel as the short-flag branch below: any leading `-`
59
- // is another flag, not a value. Without this `--out -e staging`
60
- // would consume `-e` as the value of `--out` and silently swallow
61
- // the `-e` flag.
62
- if (next && !next.startsWith('-')) {
63
- setFlag(key, next);
64
- i += 1;
65
- }
66
- else {
67
- setFlag(key, true);
68
- }
69
- }
70
- else if (arg.startsWith('-') && arg.length >= 2 && !arg.startsWith('--')) {
71
- // single-letter shorthand: -e, -o, -e=foo, -o=path/to/file
72
- // Without supporting the `-e=value` form, a user running
73
- // `seq-studio process apply -e=production` would silently fall
74
- // back to the configured default env and deploy to local.
75
- const eqIdx = arg.indexOf('=');
76
- const shortName = eqIdx >= 0 ? arg.slice(0, eqIdx) : arg;
77
- const longName = SHORT_FLAG_ALIASES[shortName];
78
- if (!longName || shortName.length !== 2) {
79
- positional.push(arg);
80
- continue;
81
- }
82
- if (eqIdx >= 0) {
83
- setFlag(longName, arg.slice(eqIdx + 1));
84
- continue;
85
- }
86
- const next = rest[i + 1];
87
- if (next && !next.startsWith('-')) {
88
- setFlag(longName, next);
89
- i += 1;
90
- }
91
- else {
92
- setFlag(longName, true);
93
- }
94
- }
95
- else {
96
- positional.push(arg);
97
- }
98
- }
99
- return {
100
- positional,
101
- flags,
102
- ...(Object.keys(repeatedFlags).length > 0 ? { repeatedFlags } : {}),
103
- };
104
- }
105
- const SHORT_FLAG_ALIASES = {
106
- '-e': 'env',
107
- '-m': 'message',
108
- '-o': 'out',
109
- };
29
+ export { parseArgs } from '../argv.js';
110
30
  async function getEnvAndToken(args) {
111
31
  const requested = typeof args.flags.env === 'string' ? args.flags.env : undefined;
112
32
  const env = await resolveEnvWithDiscovery({ requested });
@@ -213,6 +133,7 @@ export async function initCommand(args) {
213
133
  await writeFile(path, body, 'utf8');
214
134
  }
215
135
  }
136
+ await writeScaffoldGuidance({ directory: dir });
216
137
  console.log(`[seq-studio] scaffolded process repo at ${relative(process.cwd(), dir)}`);
217
138
  console.log('Next:');
218
139
  // pnpm is recommended over npm so the scaffolded
@@ -494,6 +415,7 @@ async function registerAndPromote({ args, env, token, compiled, }) {
494
415
  return 1;
495
416
  }
496
417
  const onlyIds = onlyResult.ids;
418
+ const platformManaged = args.flags['platform-managed'] === true;
497
419
  // Layer-3 lint before touching the registry. Server-side lint runs
498
420
  // again on POST /bundles; this is a local fast-fail so we don't ship
499
421
  // a bundle that will be rejected.
@@ -535,7 +457,10 @@ async function registerAndPromote({ args, env, token, compiled, }) {
535
457
  baseUrl: env.url,
536
458
  token,
537
459
  path: `/api/lattice/processes/${encodeURIComponent(pv.processId)}/promote`,
538
- body: { version: pv.version },
460
+ body: {
461
+ version: pv.version,
462
+ ...(platformManaged ? { platform_managed: true } : {}),
463
+ },
539
464
  });
540
465
  console.log(`[seq-studio] promoted ${pv.processId} → ${pv.version}`);
541
466
  }
@@ -806,12 +731,229 @@ export async function simulateCommand(args) {
806
731
  console.log(formatSimulateResult(result));
807
732
  return result.status === 'failed' ? 1 : 0;
808
733
  }
809
- // ---------------------------------------------------------------------------
810
- // doctor (token + env + FGA gate)
811
- // ---------------------------------------------------------------------------
734
+ async function runtimePackageDiagnostic(name) {
735
+ const require = createRequire(import.meta.url);
736
+ let resolved;
737
+ try {
738
+ resolved = require.resolve(name);
739
+ }
740
+ catch (error) {
741
+ return {
742
+ status: 'unavailable',
743
+ detail: error instanceof Error ? error.message : String(error),
744
+ };
745
+ }
746
+ let directory = dirname(resolved);
747
+ while (true) {
748
+ const packagePath = join(directory, 'package.json');
749
+ try {
750
+ const parsed = JSON.parse(await readFile(packagePath, 'utf8'));
751
+ if (typeof parsed === 'object' &&
752
+ parsed !== null &&
753
+ Reflect.get(parsed, 'name') === name &&
754
+ typeof Reflect.get(parsed, 'version') === 'string') {
755
+ return {
756
+ status: 'resolved',
757
+ version: Reflect.get(parsed, 'version'),
758
+ path: resolved,
759
+ };
760
+ }
761
+ }
762
+ catch {
763
+ // Continue upward: the resolved entry can be nested under dist/ or src/.
764
+ }
765
+ const parent = dirname(directory);
766
+ if (parent === directory)
767
+ break;
768
+ directory = parent;
769
+ }
770
+ return { status: 'resolved', path: resolved, detail: 'package version unavailable' };
771
+ }
772
+ /** Resolve this source module's owning package metadata without following its `exports` entry. */
773
+ export async function runtimePackageMetadataDiagnostic(name, modulePath) {
774
+ let directory = dirname(modulePath);
775
+ while (true) {
776
+ const packagePath = join(directory, 'package.json');
777
+ try {
778
+ const parsed = JSON.parse(await readFile(packagePath, 'utf8'));
779
+ if (typeof parsed === 'object' &&
780
+ parsed !== null &&
781
+ Reflect.get(parsed, 'name') === name &&
782
+ typeof Reflect.get(parsed, 'version') === 'string') {
783
+ const bin = Reflect.get(parsed, 'bin');
784
+ const binPath = typeof bin === 'string'
785
+ ? bin
786
+ : typeof bin === 'object' && bin !== null
787
+ ? Reflect.get(bin, 'seq-studio')
788
+ : undefined;
789
+ const entrypoint = typeof binPath === 'string' ? resolve(directory, binPath) : undefined;
790
+ return {
791
+ status: 'resolved',
792
+ version: Reflect.get(parsed, 'version'),
793
+ path: entrypoint ?? modulePath,
794
+ packagePath,
795
+ ...(entrypoint ? { entrypointExists: existsSync(entrypoint) } : {}),
796
+ ...(!entrypoint
797
+ ? { detail: 'package metadata resolved, but no seq-studio executable is declared' }
798
+ : !existsSync(entrypoint)
799
+ ? { detail: 'package metadata resolved; declared executable is missing from this checkout' }
800
+ : {}),
801
+ };
802
+ }
803
+ }
804
+ catch {
805
+ // Continue upward until the module's owning package is found.
806
+ }
807
+ const parent = dirname(directory);
808
+ if (parent === directory)
809
+ break;
810
+ directory = parent;
811
+ }
812
+ return { status: 'unavailable', detail: `could not find ${name} package metadata from ${modulePath}` };
813
+ }
814
+ async function runtimeDiagnostics() {
815
+ const [cli, artifactStudio, lattice, orm, pipelineSpec] = await Promise.all([
816
+ runtimePackageMetadataDiagnostic('@sequenceholdings/studio-cli', fileURLToPath(import.meta.url)),
817
+ runtimePackageDiagnostic('@sequenceholdings/artifact-studio'),
818
+ runtimePackageDiagnostic('@sequenceholdings/lattice'),
819
+ runtimePackageDiagnostic('@sequenceholdings/orm'),
820
+ runtimePackageDiagnostic('@sequenceholdings/pipeline-spec'),
821
+ ]);
822
+ const ormOverride = process.env.SEQUENCE_ORM_MODULE_PATH?.trim();
823
+ const effectiveOrm = ormOverride ? resolve(process.cwd(), ormOverride) : undefined;
824
+ const ormDiagnostic = effectiveOrm
825
+ ? {
826
+ ...orm,
827
+ configuredOverride: effectiveOrm,
828
+ overrideExists: existsSync(effectiveOrm),
829
+ detail: existsSync(effectiveOrm)
830
+ ? 'ORM authoring imports may use this override; package resolution above shows the installed package.'
831
+ : 'ORM authoring override does not exist; authoring imports may fail.',
832
+ }
833
+ : orm;
834
+ return {
835
+ cwd: process.cwd(),
836
+ executable: process.argv[1] ?? null,
837
+ sourceFreshness: 'unknown',
838
+ node: {
839
+ version: process.version,
840
+ path: process.execPath,
841
+ platform: process.platform,
842
+ arch: process.arch,
843
+ },
844
+ cli,
845
+ sdk: {
846
+ '@sequenceholdings/artifact-studio': artifactStudio,
847
+ '@sequenceholdings/lattice': lattice,
848
+ '@sequenceholdings/orm': ormDiagnostic,
849
+ '@sequenceholdings/pipeline-spec': pipelineSpec,
850
+ },
851
+ };
852
+ }
853
+ function isLoopbackUrl(value) {
854
+ try {
855
+ const hostname = new URL(value).hostname.toLowerCase().replace(/^\[|\]$/g, '');
856
+ return ['localhost', '127.0.0.1', '::1'].includes(hostname);
857
+ }
858
+ catch {
859
+ return false;
860
+ }
861
+ }
862
+ function networkErrorCode(error) {
863
+ let current = error;
864
+ for (let depth = 0; depth < 4 && current instanceof Error; depth += 1) {
865
+ const code = Reflect.get(current, 'code');
866
+ if (typeof code === 'string')
867
+ return code;
868
+ current = Reflect.get(current, 'cause');
869
+ }
870
+ return undefined;
871
+ }
872
+ async function localServiceDiagnostic(url) {
873
+ if (!isLoopbackUrl(url))
874
+ return { status: 'available', detail: 'remote environment; not probed' };
875
+ try {
876
+ const response = await fetch(`${url.replace(/\/$/, '')}/api/auth/cli-config`, {
877
+ redirect: 'error',
878
+ signal: AbortSignal.timeout(1_500),
879
+ });
880
+ if (response.ok)
881
+ return { status: 'available' };
882
+ return { status: 'unavailable', detail: `local Atlas returned HTTP ${response.status}` };
883
+ }
884
+ catch (error) {
885
+ const code = networkErrorCode(error);
886
+ const reason = code === 'ECONNREFUSED'
887
+ ? 'connection refused; start the local Atlas server and check its configured port'
888
+ : code === 'ETIMEDOUT' || error instanceof Error && error.name === 'TimeoutError'
889
+ ? 'connection timed out; check that the local Atlas server is running'
890
+ : error instanceof Error
891
+ ? error.message
892
+ : String(error);
893
+ return { status: 'unavailable', detail: reason };
894
+ }
895
+ }
896
+ function doctorBooleanFlag({ key, value }) {
897
+ if (value === undefined || value === 'false')
898
+ return false;
899
+ if (value === true || value === 'true')
900
+ return true;
901
+ throw new Error(`--${key} accepts only true or false.`);
902
+ }
812
903
  export async function doctorCommand(args) {
904
+ if (args.flags.help || args.positional.includes('-h') || args.positional[0] === 'help') {
905
+ console.log('usage: seq-studio doctor [-e <env>] [--json] [--offline]\n\nDiagnose configuration, authentication, local service availability, CLI/SDK resolution, and deployment access. Does not open a browser. --offline reads only local config and token metadata; it performs no discovery or HTTP requests.');
906
+ return 0;
907
+ }
908
+ for (const key of Object.keys(args.flags)) {
909
+ if (!['env', 'e', 'json', 'offline'].includes(key)) {
910
+ throw new Error(`Unknown doctor flag --${key}. See seq-studio doctor --help.`);
911
+ }
912
+ }
913
+ const requestedEnv = args.flags.env ?? args.flags.e;
914
+ if (args.flags.env !== undefined && args.flags.e !== undefined) {
915
+ throw new Error('Specify only one of --env or -e.');
916
+ }
917
+ if (requestedEnv !== undefined && (typeof requestedEnv !== 'string' || !requestedEnv.trim())) {
918
+ throw new Error('doctor --env requires a non-empty environment name.');
919
+ }
920
+ if (args.positional.length > 0) {
921
+ throw new Error('doctor takes no positional arguments. See `seq-studio doctor --help`.');
922
+ }
923
+ const offline = doctorBooleanFlag({ key: 'offline', value: args.flags.offline });
924
+ const emitJson = doctorBooleanFlag({ key: 'json', value: args.flags.json });
813
925
  const lines = [];
814
926
  let ok = true;
927
+ const runtime = await runtimeDiagnostics();
928
+ const authMode = process.env.SEQAPI_AUTH_MODE?.trim().toLowerCase() === 'm2m' ? 'm2m' : 'auto';
929
+ const diagnostics = {
930
+ schemaVersion: 1,
931
+ runtime,
932
+ authMode,
933
+ offline,
934
+ checks: lines,
935
+ };
936
+ const emit = () => {
937
+ if (emitJson) {
938
+ console.log(JSON.stringify({ ...diagnostics, ok }, null, 2));
939
+ return;
940
+ }
941
+ console.log(`cwd: ${runtime.cwd}`);
942
+ console.log(`runtime: CLI ${runtime.cli.version ?? 'unknown'} (${runtime.executable ?? 'unknown'}); Node ${runtime.node.version} at ${runtime.node.path}`);
943
+ if (runtime.cli.entrypointExists === false) {
944
+ console.log(`cli entrypoint: missing (${runtime.cli.path}); package metadata: ${runtime.cli.packagePath}`);
945
+ }
946
+ for (const [name, pkg] of Object.entries(runtime.sdk)) {
947
+ console.log(`sdk: ${name} ${pkg.version ?? pkg.status}${pkg.path ? ` (${pkg.path})` : ''}`);
948
+ if (pkg.configuredOverride) {
949
+ console.log(`sdk override: ${name} ${pkg.configuredOverride} (${pkg.overrideExists ? 'exists' : 'missing'})`);
950
+ }
951
+ }
952
+ console.log('source/build freshness: unknown (doctor reports resolved runtime paths, not source timestamps)');
953
+ console.log(`auth mode: ${authMode}`);
954
+ for (const line of lines)
955
+ console.log(line);
956
+ };
815
957
  const config = await readConfig().catch(() => null);
816
958
  if (!config) {
817
959
  lines.push('config: FAIL — could not read ~/.config/lattice/config.toml');
@@ -828,7 +970,9 @@ export async function doctorCommand(args) {
828
970
  let env = null;
829
971
  if (config) {
830
972
  try {
831
- env = await resolveEnvWithDiscovery({ requested });
973
+ env = offline
974
+ ? resolveEnv({ config, requested })
975
+ : await resolveEnvWithDiscovery({ requested });
832
976
  lines.push(`env: ok — ${env.name} (${env.url})`);
833
977
  }
834
978
  catch (err) {
@@ -837,15 +981,66 @@ export async function doctorCommand(args) {
837
981
  }
838
982
  }
839
983
  let token = null;
984
+ let authPreflight = null;
985
+ if (env) {
986
+ const localService = offline
987
+ ? { status: 'not-checked', detail: 'not checked (offline)' }
988
+ : await localServiceDiagnostic(env.url);
989
+ diagnostics.environment = {
990
+ name: env.name,
991
+ url: env.url,
992
+ localService,
993
+ };
994
+ if (!offline && localService.status === 'unavailable') {
995
+ lines.push(`local service: FAIL — ${localService.detail ?? 'unavailable'}`);
996
+ ok = false;
997
+ }
998
+ else if (!offline && isLoopbackUrl(env.url)) {
999
+ lines.push(`local service: ok — ${env.url}`);
1000
+ }
1001
+ try {
1002
+ authPreflight = await inspectAuthPreflight({
1003
+ env: env.name,
1004
+ offline,
1005
+ ...(offline ? {} : { targetUrl: env.url }),
1006
+ });
1007
+ diagnostics.auth = authPreflight;
1008
+ lines.push(`auth cache: ${authPreflight.tokenCache}; user token ${authPreflight.cachedUserToken}; ` +
1009
+ `M2M credential ${authPreflight.m2mCredentialConfigured ? 'configured' : 'not configured'} ` +
1010
+ `(mode=${authPreflight.authMode}, realm=${authPreflight.realm}${authPreflight.realmVerified ? '' : ', unverified offline'})`);
1011
+ }
1012
+ catch (err) {
1013
+ diagnostics.auth = {
1014
+ status: 'unavailable',
1015
+ detail: err instanceof Error ? err.message : String(err),
1016
+ };
1017
+ lines.push(`auth preflight: FAIL — ${err instanceof Error ? err.message : String(err)}`);
1018
+ ok = false;
1019
+ }
1020
+ }
840
1021
  try {
841
- token = await getAccessToken({ env: env?.name, targetUrl: env?.url });
842
- lines.push('auth: ok — seqapi token present and not expired');
1022
+ if (authPreflight?.tokenCache === 'permission-denied' || authPreflight?.tokenCache === 'invalid-json' || authPreflight?.tokenCache === 'io-error') {
1023
+ throw new AuthTokenStoreError(authPreflight.detail ?? `Cannot read token cache at ${authPreflight.tokenCachePath}.`, authPreflight.tokenCache === 'permission-denied' ? 'permission' : authPreflight.tokenCache === 'invalid-json' ? 'invalid' : 'io', authPreflight.tokenCachePath);
1024
+ }
1025
+ if (offline) {
1026
+ lines.push('auth: not validated (offline); cache and configured credential metadata only');
1027
+ }
1028
+ else {
1029
+ const auth = await getAccessTokenWithMode({
1030
+ allowInteractiveLogin: false,
1031
+ env: env?.name,
1032
+ targetUrl: env?.url,
1033
+ });
1034
+ token = auth.token;
1035
+ diagnostics.authMode = auth.authMode;
1036
+ lines.push(`auth: ok — ${auth.authMode} credential available for Atlas APIs`);
1037
+ }
843
1038
  }
844
1039
  catch (err) {
845
- lines.push(`auth: FAIL — ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`);
1040
+ lines.push(`auth: FAIL — ${err instanceof Error ? err.message.replace(/\n/g, ' ') : String(err)}`);
846
1041
  ok = false;
847
1042
  }
848
- if (env && token) {
1043
+ if (!offline && env && token) {
849
1044
  // Hit a writer-gated endpoint with a fake hash so the request
850
1045
  // either:
851
1046
  // - 404 NOT_FOUND → writer gate passed (we're a Sequence-org
@@ -903,13 +1098,14 @@ export async function doctorCommand(args) {
903
1098
  if (currentTotal === 0 && env.name !== 'staging' && config?.envs.staging?.url) {
904
1099
  try {
905
1100
  const stagingUrl = config.envs.staging.url;
906
- const stagingToken = await getAccessToken({
1101
+ const stagingAuth = await getAccessTokenWithMode({
1102
+ allowInteractiveLogin: false,
907
1103
  env: 'staging',
908
1104
  targetUrl: stagingUrl,
909
1105
  });
910
1106
  const staging = await getJson({
911
1107
  baseUrl: stagingUrl,
912
- token: stagingToken,
1108
+ token: stagingAuth.token,
913
1109
  path: '/api/git-service/repos?limit=1&offset=0',
914
1110
  });
915
1111
  const stagingTotal = staging.total ?? staging.items.length;
@@ -937,7 +1133,7 @@ export async function doctorCommand(args) {
937
1133
  }
938
1134
  }
939
1135
  }
940
- for (const l of lines)
941
- console.log(l);
1136
+ diagnostics.checks = lines;
1137
+ emit();
942
1138
  return ok ? 0 : 1;
943
1139
  }
@@ -140,6 +140,9 @@ function lintJsonataExpressions(processId, node, errors) {
140
140
  case 'managed_function':
141
141
  add('output', node.output);
142
142
  break;
143
+ case 'managed_server':
144
+ add('output', node.output);
145
+ break;
143
146
  }
144
147
  const middleware = 'middleware' in node ? node.middleware : undefined;
145
148
  if (Array.isArray(middleware)) {
@@ -333,6 +336,10 @@ async function lintNodeContract(processId, node, errors, warnings, loadAgentSche
333
336
  lintManagedFunctionNode(processId, node, errors);
334
337
  break;
335
338
  }
339
+ case 'managed_server': {
340
+ lintManagedServerNode(processId, node, errors);
341
+ break;
342
+ }
336
343
  case 'automation': {
337
344
  lintRouteRulesEdges(processId, node, errors);
338
345
  break;
@@ -384,6 +391,34 @@ function lintRouteRulesEdges(processId, node, errors) {
384
391
  }
385
392
  }
386
393
  }
394
+ function lintManagedServerNode(processId, node, errors) {
395
+ const edgeIds = new Set(node.outgoing_edges.map((e) => e.id));
396
+ if (node.output === undefined) {
397
+ for (const required of ['success', 'error']) {
398
+ if (!edgeIds.has(required)) {
399
+ errors.push({
400
+ process_id: processId,
401
+ node_id: node.id,
402
+ message: `managed_server node must declare outgoing edge "${required}"`,
403
+ });
404
+ }
405
+ }
406
+ }
407
+ if (!node.server?.trim()) {
408
+ errors.push({
409
+ process_id: processId,
410
+ node_id: node.id,
411
+ message: 'managed_server node must declare a non-empty `server` ref',
412
+ });
413
+ }
414
+ if (!node.path?.startsWith('/') || node.path.includes('?') || node.path.includes('..')) {
415
+ errors.push({
416
+ process_id: processId,
417
+ node_id: node.id,
418
+ message: 'managed_server node `path` must be an exact origin-relative path',
419
+ });
420
+ }
421
+ }
387
422
  function lintManagedFunctionNode(processId, node, errors) {
388
423
  const edgeIds = new Set(node.outgoing_edges.map((e) => e.id));
389
424
  if (node.output === undefined) {
@@ -193,6 +193,15 @@ const BEHAVIORAL_METADATA_FIELDS = {
193
193
  'output_mapper_expr',
194
194
  'middleware',
195
195
  ],
196
+ managed_server: [
197
+ 'server_id',
198
+ 'path',
199
+ 'limits',
200
+ 'input_mapper_source',
201
+ 'input_mapper_expr',
202
+ 'output_mapper_expr',
203
+ 'middleware',
204
+ ],
196
205
  human: [
197
206
  'artifact_refs',
198
207
  'artifact_refs_mapper_source',
@@ -203,6 +203,14 @@ async function dispatchInProcess(args) {
203
203
  payload: { _simulated: true, kind: 'managed_function' },
204
204
  };
205
205
  }
206
+ case 'managed_server': {
207
+ return {
208
+ edge_id: args.node.output === undefined
209
+ ? 'success'
210
+ : args.node.outgoing_edges[0]?.id,
211
+ payload: { _simulated: true, kind: 'managed_server' },
212
+ };
213
+ }
206
214
  default: {
207
215
  const _exhaustive = args.node;
208
216
  void _exhaustive;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * First-party packages a scaffolded project may resolve, directly or
3
+ * transitively (studio-cli → managed-functions → storage, artifact-studio →
4
+ * custom-roles-manifest, …). Scaffolds exempt exactly these from pnpm's
5
+ * seven-day `minimumReleaseAge` gate: they ship from the Studio repo's audited
6
+ * release pipeline, so a fresh scaffold must install the day they publish.
7
+ * A missing entry fails `pnpm install` for a week after every release.
8
+ *
9
+ * The YAML templates under templates/ carry the same list; a test keeps them
10
+ * in sync with this one.
11
+ */
12
+ export declare const FIRST_PARTY_RELEASE_AGE_EXCLUDE: readonly ["@sequenceholdings/agent-spec", "@sequenceholdings/artifact-studio", "@sequenceholdings/atlas-ui", "@sequenceholdings/custom-roles-manifest", "@sequenceholdings/lattice", "@sequenceholdings/lattice-form-renderer", "@sequenceholdings/managed-functions", "@sequenceholdings/orm", "@sequenceholdings/pipeline-spec", "@sequenceholdings/storage", "@sequenceholdings/studio-cli"];
@@ -0,0 +1,24 @@
1
+ /**
2
+ * First-party packages a scaffolded project may resolve, directly or
3
+ * transitively (studio-cli → managed-functions → storage, artifact-studio →
4
+ * custom-roles-manifest, …). Scaffolds exempt exactly these from pnpm's
5
+ * seven-day `minimumReleaseAge` gate: they ship from the Studio repo's audited
6
+ * release pipeline, so a fresh scaffold must install the day they publish.
7
+ * A missing entry fails `pnpm install` for a week after every release.
8
+ *
9
+ * The YAML templates under templates/ carry the same list; a test keeps them
10
+ * in sync with this one.
11
+ */
12
+ export const FIRST_PARTY_RELEASE_AGE_EXCLUDE = [
13
+ '@sequenceholdings/agent-spec',
14
+ '@sequenceholdings/artifact-studio',
15
+ '@sequenceholdings/atlas-ui',
16
+ '@sequenceholdings/custom-roles-manifest',
17
+ '@sequenceholdings/lattice',
18
+ '@sequenceholdings/lattice-form-renderer',
19
+ '@sequenceholdings/managed-functions',
20
+ '@sequenceholdings/orm',
21
+ '@sequenceholdings/pipeline-spec',
22
+ '@sequenceholdings/storage',
23
+ '@sequenceholdings/studio-cli',
24
+ ];