@copado/agentia-cli 1.0.0-beta.1 → 1.0.0-beta.4

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 (70) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +648 -370
  3. package/dist/commands/cicd/cloud/commit.js +252 -0
  4. package/dist/commands/cicd/cloud/promote.js +139 -0
  5. package/dist/commands/cicd/data/template/save-detail.js +2 -2
  6. package/dist/commands/cicd/health-check.js +77 -0
  7. package/dist/commands/cicd/repository/auth/https/configure.js +21 -0
  8. package/dist/commands/cicd/repository/auth/oauth/login.js +56 -0
  9. package/dist/commands/cicd/repository/auth/setup.js +28 -0
  10. package/dist/commands/cicd/repository/auth/ssh/configure.js +22 -0
  11. package/dist/commands/cicd/repository/create.js +2 -2
  12. package/dist/commands/cicd/repository/reset.js +17 -5
  13. package/dist/commands/cicd/repository/update.js +6 -14
  14. package/dist/commands/cicd/work/commit.js +10 -324
  15. package/dist/commands/cicd/work/environment-sync.js +125 -0
  16. package/dist/commands/cicd/work/get.js +29 -12
  17. package/dist/commands/cicd/work/promote.js +93 -97
  18. package/dist/commands/cicd/work/set.js +4 -2
  19. package/dist/commands/cicd/work/submit.js +7 -0
  20. package/dist/commands/runtime.js +26 -0
  21. package/dist/hooks/finally/ide-command-event.js +1 -1
  22. package/dist/hooks/init/plugin-host.js +6 -0
  23. package/dist/lib/agentia-command.js +16 -0
  24. package/dist/lib/cursor-mcp-config.js +3 -1
  25. package/dist/lib/data-types.js +3 -1
  26. package/dist/lib/defaults-store.js +2 -1
  27. package/dist/lib/git-sizer.js +5 -0
  28. package/dist/lib/git-worktree.js +17 -1
  29. package/dist/lib/health-check.js +3 -0
  30. package/dist/lib/mcp/command-id.js +1 -0
  31. package/dist/lib/mcp/data-tools.js +2 -2
  32. package/dist/lib/mcp/health-check-tools.js +16 -0
  33. package/dist/lib/mcp/server.js +35 -8
  34. package/dist/lib/mcp/tool-annotations.js +268 -0
  35. package/dist/lib/mcp/tools.js +58 -12
  36. package/dist/lib/mcp/work-tools.js +98 -83
  37. package/dist/lib/metadata-pathspecs.js +4 -0
  38. package/dist/lib/metadataRegistry.json +5427 -0
  39. package/dist/lib/plugin-host/auth.js +4 -0
  40. package/dist/lib/plugin-host/format.js +3 -0
  41. package/dist/lib/plugin-host/index.js +7 -0
  42. package/dist/lib/plugin-host/organization.js +4 -0
  43. package/dist/lib/plugin-host/projection-utils.js +6 -0
  44. package/dist/lib/plugin-host/registry.js +6 -0
  45. package/dist/lib/plugin-host/request-scope.js +4 -0
  46. package/dist/lib/plugin-host/work.js +4 -0
  47. package/dist/lib/project-root.js +3 -1
  48. package/dist/lib/promotion-types.js +4 -1
  49. package/dist/lib/repository-auth.js +8 -0
  50. package/dist/lib/repository-flags.js +2 -2
  51. package/dist/lib/repository-types.js +6 -1
  52. package/dist/lib/repository-url-prefill.js +4 -0
  53. package/dist/lib/runtime-invoke-context.js +6 -0
  54. package/dist/lib/runtime-rpc.js +14 -0
  55. package/dist/lib/runtime.js +1 -1
  56. package/dist/lib/work-environment-sync-errors.js +4 -0
  57. package/dist/lib/work-environment-sync-ready.js +18 -0
  58. package/dist/lib/work-environment-sync.js +41 -0
  59. package/dist/lib/work-get.js +3 -0
  60. package/dist/lib/work-promote-deploy.js +13 -0
  61. package/dist/lib/work-promote-errors.js +5 -0
  62. package/dist/lib/work-promote.js +12 -0
  63. package/dist/lib/work-set-selection.js +2 -1
  64. package/dist/lib/work-submit-ahead-behind.js +8 -0
  65. package/dist/lib/work-types.js +2 -1
  66. package/oclif.manifest.json +1166 -605
  67. package/package.json +8 -4
  68. package/templates/skills/agentia-cicd/SKILL.md +2 -2
  69. package/templates/skills/agentia-cicd/references/promotions.md +8 -8
  70. package/templates/skills/agentia-cicd/references/work.md +16 -14
@@ -0,0 +1,252 @@
1
+ import { Args, Flags } from '@oclif/core';
2
+ import { readFileSync } from 'node:fs';
3
+ import { AgentiaCommand } from '../../../lib/agentia-command.js';
4
+ import { resolveWorkItemId, WorkActiveResolutionError } from '../../../lib/work-active.js';
5
+ import { buildWorkCommitRequest, formatWorkCommitResult, normalizeWorkCommitInput, performWorkCommit, resolveWorkCommitPlatformExperience, WORK_COMMIT_ACTIONS, WORK_COMMIT_DEFAULT_TIMEOUT_SECONDS, WORK_COMMIT_METADATA_CATEGORY_HELP, WorkCommitJobFailedError, WorkCommitTimeoutError, WorkCommitValidationError, } from '../../../lib/work-commit.js';
6
+ function readStdin() {
7
+ if (process.stdin.isTTY) {
8
+ throw new WorkCommitValidationError('Cannot read --stdin from an interactive terminal. Pipe JSON input or use --file <path>.');
9
+ }
10
+ return new Promise((resolve, reject) => {
11
+ let data = '';
12
+ process.stdin.setEncoding('utf8');
13
+ process.stdin.on('data', (chunk) => {
14
+ data += chunk;
15
+ });
16
+ process.stdin.on('end', () => resolve(data));
17
+ process.stdin.on('error', reject);
18
+ });
19
+ }
20
+ function readJsonFile(path) {
21
+ try {
22
+ return readFileSync(path, 'utf8');
23
+ }
24
+ catch (error) {
25
+ throw new WorkCommitValidationError(`Cannot read JSON request file ${path}: ${error.message}`);
26
+ }
27
+ }
28
+ function parseJsonValue(raw, label) {
29
+ try {
30
+ return JSON.parse(raw);
31
+ }
32
+ catch (error) {
33
+ throw new WorkCommitValidationError(`${label} must contain valid JSON: ${error.message}`);
34
+ }
35
+ }
36
+ function hasSimpleChangeFlags(flags) {
37
+ return (flags.action !== undefined ||
38
+ flags['metadata-category'] !== undefined ||
39
+ flags['metadata-message'] !== undefined ||
40
+ flags['metadata-name'] !== undefined ||
41
+ flags['metadata-raw-json'] !== undefined ||
42
+ flags['metadata-type'] !== undefined ||
43
+ flags.selection !== undefined);
44
+ }
45
+ function simpleInputFromFlags(flags) {
46
+ const rawJson = flags['metadata-raw-json'] === undefined
47
+ ? undefined
48
+ : parseJsonValue(flags['metadata-raw-json'], '--metadata-raw-json');
49
+ return {
50
+ baseBranch: flags['base-branch'] ?? null,
51
+ changes: [
52
+ {
53
+ ...(flags.action === undefined ? {} : { a: flags.action }),
54
+ ...(flags['metadata-category'] === undefined ? {} : { c: flags['metadata-category'] }),
55
+ ...(rawJson === undefined ? {} : { j: rawJson }),
56
+ ...(flags['metadata-message'] === undefined ? {} : { m: flags['metadata-message'] }),
57
+ n: flags['metadata-name'],
58
+ ...(flags.selection === undefined ? {} : { selections: flags.selection }),
59
+ t: flags['metadata-type'],
60
+ },
61
+ ],
62
+ commitId: flags['commit-id'],
63
+ executeCommit: flags['execute-commit'],
64
+ message: flags.message,
65
+ recreateFeatureBranch: flags['recreate-feature-branch'],
66
+ };
67
+ }
68
+ async function jsonInputFromFlags(flags) {
69
+ const raw = flags.file === undefined ? await readStdin() : readJsonFile(flags.file);
70
+ const input = normalizeWorkCommitInput(parseJsonValue(raw, flags.file === undefined ? 'stdin' : flags.file));
71
+ return {
72
+ ...input,
73
+ ...(flags['base-branch'] === undefined ? {} : { baseBranch: flags['base-branch'] }),
74
+ ...(flags['commit-id'] === undefined ? {} : { commitId: flags['commit-id'] }),
75
+ ...(flags['execute-commit'] ? {} : { executeCommit: false }),
76
+ ...(flags.message === undefined ? {} : { message: flags.message }),
77
+ ...(flags['recreate-feature-branch'] ? { recreateFeatureBranch: true } : {}),
78
+ };
79
+ }
80
+ async function commitInputFromFlags(flags) {
81
+ const jsonModes = [flags.file !== undefined, flags.stdin].filter(Boolean).length;
82
+ const simpleMode = hasSimpleChangeFlags(flags);
83
+ if (jsonModes > 1) {
84
+ throw new WorkCommitValidationError('Use only one JSON input mode: --file or --stdin.');
85
+ }
86
+ if (jsonModes > 0 && simpleMode) {
87
+ throw new WorkCommitValidationError('Use JSON input or simple metadata flags, not both.');
88
+ }
89
+ if (jsonModes > 0) {
90
+ return jsonInputFromFlags(flags);
91
+ }
92
+ if (!simpleMode) {
93
+ throw new WorkCommitValidationError('Requires simple metadata flags such as --metadata-name and --metadata-type, or JSON input with --file/--stdin.');
94
+ }
95
+ return simpleInputFromFlags(flags);
96
+ }
97
+ export default class CloudCommit extends AgentiaCommand {
98
+ static args = {
99
+ id: Args.string({
100
+ description: 'User story ID (defaults to the active work item from `work set`)',
101
+ required: false,
102
+ }),
103
+ };
104
+ static description = [
105
+ 'Create a Copado cloud metadata commit for a user story.',
106
+ 'Preflights the story, submits POST /release/commit, and polls the job monitor by default.',
107
+ 'For local Git work, use git add/commit then `cicd work publish`. Permission and full-metadata selections belong on `cicd work publish`.',
108
+ ].join(' ');
109
+ static examples = [
110
+ '<%= config.bin %> <%= command.id %> --message "Commit AccountService" --metadata-name AccountService --metadata-type ApexClass --metadata-category SFDX --action Add',
111
+ '<%= config.bin %> <%= command.id %> a07XXXXXXXXXXXXXXX --message "Update Aura files" --metadata-name accountEditor --metadata-type AuraDefinitionBundle --metadata-category SFDX --action SelectiveCommit --selection accountEditor/accountEditor.cmp --selection accountEditor/accountEditorController.js',
112
+ '<%= config.bin %> <%= command.id %> --file commit-request.json # {"message":"Commit AccountService","changes":[{"a":"Add","c":"SFDX","n":"AccountService","t":"ApexClass"}]}',
113
+ 'cat commit-request.json | <%= config.bin %> <%= command.id %> --stdin --json',
114
+ ];
115
+ static flags = {
116
+ action: Flags.string({
117
+ description: 'Metadata action for simple flag input. Defaults to Add.',
118
+ options: [...WORK_COMMIT_ACTIONS],
119
+ }),
120
+ 'base-branch': Flags.string({
121
+ description: 'Optional base branch to include in the commit request.',
122
+ }),
123
+ cloud: Flags.boolean({
124
+ default: false,
125
+ description: 'Ignored. Cloud is implied by cicd cloud commit.',
126
+ hidden: true,
127
+ }),
128
+ 'commit-id': Flags.string({
129
+ description: 'Existing local Git commit identifier to register when --no-execute-commit is used.',
130
+ }),
131
+ 'execute-commit': Flags.boolean({
132
+ allowNo: true,
133
+ default: true,
134
+ description: 'Execute the Copado commit job. Use --no-execute-commit only with --commit-id.',
135
+ }),
136
+ file: Flags.string({
137
+ char: 'f',
138
+ description: 'Path to a JSON commit request body.',
139
+ }),
140
+ message: Flags.string({
141
+ char: 'm',
142
+ description: 'Commit message. Required unless provided by JSON input.',
143
+ }),
144
+ 'metadata-category': Flags.string({
145
+ description: WORK_COMMIT_METADATA_CATEGORY_HELP,
146
+ }),
147
+ 'metadata-message': Flags.string({
148
+ description: 'Optional per-change message for simple flag input.',
149
+ }),
150
+ 'metadata-name': Flags.string({
151
+ description: 'Metadata full name for simple flag input.',
152
+ }),
153
+ 'metadata-raw-json': Flags.string({
154
+ description: 'Optional raw metadata JSON value for simple flag input.',
155
+ }),
156
+ 'metadata-type': Flags.string({
157
+ description: 'Metadata type for simple flag input, for example ApexClass.',
158
+ }),
159
+ 'recreate-feature-branch': Flags.boolean({
160
+ default: false,
161
+ description: 'Ask Copado to recreate the feature branch before committing.',
162
+ }),
163
+ selection: Flags.string({
164
+ description: 'Selected file inside a bundle for SelectiveCommit. Can be provided multiple times.',
165
+ multiple: true,
166
+ }),
167
+ stdin: Flags.boolean({
168
+ default: false,
169
+ description: 'Read a JSON commit request body from stdin.',
170
+ }),
171
+ wait: Flags.boolean({
172
+ allowNo: true,
173
+ default: true,
174
+ description: 'Poll the commit job to a terminal status when a jobExecution Id is returned.',
175
+ }),
176
+ 'wait-timeout': Flags.integer({
177
+ default: WORK_COMMIT_DEFAULT_TIMEOUT_SECONDS,
178
+ description: 'Maximum seconds to wait for the commit job.',
179
+ }),
180
+ };
181
+ async run() {
182
+ const { args, flags } = await this.parse(CloudCommit);
183
+ const commitFlags = flags;
184
+ if (!Number.isInteger(commitFlags['wait-timeout']) || commitFlags['wait-timeout'] <= 0) {
185
+ this.error('--wait-timeout must be a positive integer.', { exit: 2 });
186
+ }
187
+ let workItemId;
188
+ try {
189
+ workItemId = await resolveWorkItemId(args.id);
190
+ }
191
+ catch (error) {
192
+ if (error instanceof WorkActiveResolutionError) {
193
+ this.error(error.message, {
194
+ exit: 1,
195
+ suggestions: [`${this.config.bin} cicd work set <id>`],
196
+ });
197
+ }
198
+ throw error;
199
+ }
200
+ try {
201
+ const input = await commitInputFromFlags(commitFlags);
202
+ const request = buildWorkCommitRequest(input, { message: commitFlags.message, userStoryId: workItemId });
203
+ const initialPlatformExperience = await resolveWorkCommitPlatformExperience({
204
+ userStoryId: workItemId,
205
+ });
206
+ const result = await performWorkCommit({
207
+ hooks: {
208
+ log: (message) => this.display(() => this.log(message)),
209
+ withSpinner: (message, action) => this.withSpinner(message, action),
210
+ },
211
+ initialPlatformExperience,
212
+ request,
213
+ timeoutSeconds: commitFlags['wait-timeout'],
214
+ wait: commitFlags.wait,
215
+ });
216
+ this.display(() => {
217
+ this.log(formatWorkCommitResult(result));
218
+ });
219
+ return result;
220
+ }
221
+ catch (error) {
222
+ if (error instanceof WorkCommitValidationError) {
223
+ this.error(error.message, { exit: 2 });
224
+ }
225
+ if (error instanceof WorkCommitJobFailedError || error instanceof WorkCommitTimeoutError) {
226
+ this.display(() => {
227
+ if (error.result !== undefined) {
228
+ this.log(formatWorkCommitResult(error.result));
229
+ }
230
+ });
231
+ error.oclif = { exit: 1 };
232
+ throw error;
233
+ }
234
+ throw error;
235
+ }
236
+ }
237
+ toErrorJson(err) {
238
+ const base = super.toErrorJson(err);
239
+ if (err instanceof WorkCommitJobFailedError || err instanceof WorkCommitTimeoutError) {
240
+ return {
241
+ ...base,
242
+ error: {
243
+ ...(base.error && typeof base.error === 'object' ? base.error : {}),
244
+ ...(err.jobMonitor === undefined ? {} : { jobMonitor: err.jobMonitor }),
245
+ ...(err.result === undefined ? {} : { result: err.result }),
246
+ },
247
+ };
248
+ }
249
+ return base;
250
+ }
251
+ }
252
+ //# sourceMappingURL=commit.js.map
@@ -0,0 +1,139 @@
1
+ import { confirm } from '@inquirer/prompts';
2
+ import { Args, Flags } from '@oclif/core';
3
+ import { AgentiaCommand } from '../../../lib/agentia-command.js';
4
+ import { formatPromotionRunResult, isPromotionRunExecutionError, parseIgnoredMetadataJson, performPromotionRun, PROMOTION_RUN_DEFAULT_TIMEOUT_SECONDS, promotionRunErrorJson, PromotionRunValidationError, resolvePromotionIdForWorkItem, } from '../../../lib/promotion-run.js';
5
+ import { resolveWorkItemId, WorkActiveResolutionError } from '../../../lib/work-active.js';
6
+ export default class CloudPromote extends AgentiaCommand {
7
+ static args = {
8
+ id: Args.string({
9
+ description: 'User Story ID (defaults to the active work item from `work set`)',
10
+ required: false,
11
+ }),
12
+ };
13
+ static description = [
14
+ 'Promote the explicit or active User Story through its Copado Promotion.',
15
+ 'Selects promote-only unless --deploy is passed.',
16
+ ].join(' ');
17
+ static examples = [
18
+ '<%= config.bin %> <%= command.id %>',
19
+ '<%= config.bin %> <%= command.id %> a07XXXXXXXXXXXXXXX --promotion-id a0BXXXXXXXXXXXXXXX',
20
+ '<%= config.bin %> <%= command.id %> --deploy --json',
21
+ ];
22
+ static flags = {
23
+ cloud: Flags.boolean({
24
+ default: false,
25
+ description: 'Ignored. Cloud is implied by cicd cloud promote.',
26
+ hidden: true,
27
+ }),
28
+ deploy: Flags.boolean({
29
+ default: false,
30
+ description: 'Use merge_and_deploy instead of promote-only merge.',
31
+ }),
32
+ 'deployment-step-id': Flags.string({
33
+ description: 'Ordered deployment-step Salesforce ID. Can be provided multiple times with --deploy.',
34
+ multiple: true,
35
+ }),
36
+ 'ignored-metadata-json': Flags.string({
37
+ description: 'JSON array to persist through ignored-metadata before starting the promotion.',
38
+ }),
39
+ 'promotion-id': Flags.string({
40
+ description: 'Explicit 18-character Promotion ID when the User Story belongs to multiple promotions.',
41
+ }),
42
+ 'recreate-promotion-branch': Flags.boolean({
43
+ description: 'Recreate the promotion branch before execution. Requires confirmation or --yes.',
44
+ }),
45
+ wait: Flags.boolean({
46
+ allowNo: true,
47
+ default: true,
48
+ description: 'Poll promotion and deployment executions to terminal status.',
49
+ }),
50
+ 'wait-timeout': Flags.integer({
51
+ default: PROMOTION_RUN_DEFAULT_TIMEOUT_SECONDS,
52
+ description: 'Maximum total seconds to wait for promotion and deployment executions.',
53
+ }),
54
+ yes: Flags.boolean({
55
+ char: 'y',
56
+ default: false,
57
+ description: 'Confirm promotion branch recreation without prompting.',
58
+ }),
59
+ };
60
+ async run() {
61
+ const { args, flags } = await this.parse(CloudPromote);
62
+ const promoteFlags = flags;
63
+ if (!Number.isInteger(promoteFlags['wait-timeout']) || promoteFlags['wait-timeout'] <= 0) {
64
+ this.error('--wait-timeout must be a positive integer.', { exit: 2 });
65
+ }
66
+ if (!promoteFlags.deploy && promoteFlags['deployment-step-id'] !== undefined) {
67
+ this.error('--deployment-step-id requires --deploy.', { exit: 2 });
68
+ }
69
+ let workItemId;
70
+ try {
71
+ workItemId = await resolveWorkItemId(args.id);
72
+ }
73
+ catch (error) {
74
+ if (error instanceof WorkActiveResolutionError) {
75
+ this.error(error.message, {
76
+ exit: 1,
77
+ suggestions: [`${this.config.bin} cicd work set <id>`],
78
+ });
79
+ }
80
+ throw error;
81
+ }
82
+ try {
83
+ const promotionId = await this.withSpinner('Resolving User Story promotion', () => resolvePromotionIdForWorkItem(workItemId, promoteFlags['promotion-id']));
84
+ if (promoteFlags['recreate-promotion-branch'] === true && !promoteFlags.yes) {
85
+ if (this.jsonEnabled() || !process.stdin.isTTY) {
86
+ this.error('Promotion branch recreation requires confirmation. Pass --yes for headless or JSON execution.', {
87
+ exit: 2,
88
+ });
89
+ }
90
+ const confirmed = await confirm({
91
+ default: false,
92
+ message: `Recreate the promotion branch for ${promotionId}? Existing promotion branch changes may be replaced.`,
93
+ });
94
+ if (!confirmed) {
95
+ this.error('Promotion canceled.', { exit: 1 });
96
+ }
97
+ }
98
+ const result = await performPromotionRun({
99
+ deploymentStepIds: promoteFlags['deployment-step-id'],
100
+ hooks: {
101
+ log: (message) => this.display(() => this.log(message)),
102
+ withSpinner: (message, action) => this.withSpinner(message, action),
103
+ },
104
+ ignoredMetadata: parseIgnoredMetadataJson(promoteFlags['ignored-metadata-json']),
105
+ operation: promoteFlags.deploy ? 'merge_and_deploy' : 'merge',
106
+ promotionId,
107
+ recreatePromotionBranch: promoteFlags['recreate-promotion-branch'],
108
+ timeoutSeconds: promoteFlags['wait-timeout'],
109
+ wait: promoteFlags.wait,
110
+ });
111
+ const workResult = { ...result, workItemId };
112
+ this.display(() => {
113
+ this.log(`User Story: ${workItemId}`);
114
+ this.log(formatPromotionRunResult(result));
115
+ });
116
+ return workResult;
117
+ }
118
+ catch (error) {
119
+ if (error instanceof PromotionRunValidationError) {
120
+ this.error(error.message, { exit: 2 });
121
+ }
122
+ if (isPromotionRunExecutionError(error)) {
123
+ this.display(() => {
124
+ if (error.result !== undefined) {
125
+ this.log(`User Story: ${workItemId}`);
126
+ this.log(formatPromotionRunResult(error.result));
127
+ }
128
+ });
129
+ error.oclif = { exit: 1 };
130
+ }
131
+ throw error;
132
+ }
133
+ }
134
+ toErrorJson(err) {
135
+ const base = super.toErrorJson(err);
136
+ return promotionRunErrorJson(base, err);
137
+ }
138
+ }
139
+ //# sourceMappingURL=promote.js.map
@@ -2,7 +2,7 @@ import { Args } from '@oclif/core';
2
2
  import { AgentiaCommand } from '../../../../lib/agentia-command.js';
3
3
  import { CicdGateway } from '../../../../lib/cicd-gateway.js';
4
4
  import { assertJsonObject, jsonBodyFlags, readJsonBodyFromFileOrStdin, } from '../../../../lib/data-flags.js';
5
- import { dataTemplateDetailEndpoint } from '../../../../lib/data-types.js';
5
+ import { dataTemplateDetailEndpoint, normalizeDataTemplateSavePayload, } from '../../../../lib/data-types.js';
6
6
  export default class DataTemplateSaveDetail extends AgentiaCommand {
7
7
  static args = {
8
8
  id: Args.string({
@@ -26,7 +26,7 @@ export default class DataTemplateSaveDetail extends AgentiaCommand {
26
26
  required: true,
27
27
  stdin: flags.stdin,
28
28
  });
29
- const body = assertJsonObject(raw, 'template detail');
29
+ const body = normalizeDataTemplateSavePayload(assertJsonObject(raw, 'template detail'));
30
30
  const result = await this.withSpinner('Saving data template detail', () => CicdGateway.call({
31
31
  body,
32
32
  endpoint: dataTemplateDetailEndpoint(args.id),
@@ -0,0 +1,77 @@
1
+ import { Flags, ux } from '@oclif/core';
2
+ import { AgentiaCommand } from '../../lib/agentia-command.js';
3
+ import { table } from '../../lib/format.js';
4
+ import { analyzeGitRepository, gitSizerRows } from '../../lib/git-sizer.js';
5
+ import { runOrganizationHealthChecks, } from '../../lib/health-check.js';
6
+ function displayStatus(status) {
7
+ const label = status.toUpperCase();
8
+ switch (status) {
9
+ case 'fail': {
10
+ return ux.colorize('red', label);
11
+ }
12
+ case 'pass': {
13
+ return ux.colorize('green', label);
14
+ }
15
+ case 'warn': {
16
+ return ux.colorize('yellow', label);
17
+ }
18
+ default: {
19
+ return label;
20
+ }
21
+ }
22
+ }
23
+ export default class HealthCheck extends AgentiaCommand {
24
+ static description = 'Run organization-scoped governance health checks';
25
+ static examples = [
26
+ '<%= config.bin %> <%= command.id %>',
27
+ '<%= config.bin %> <%= command.id %> --json',
28
+ '<%= config.bin %> <%= command.id %> --git-sizer',
29
+ '<%= config.bin %> <%= command.id %> --git-sizer --path /path/to/clone',
30
+ ];
31
+ static flags = {
32
+ 'git-sizer': Flags.boolean({
33
+ default: false,
34
+ description: 'Also analyze a local Git clone with git-sizer',
35
+ }),
36
+ path: Flags.string({
37
+ dependsOn: ['git-sizer'],
38
+ description: 'Local Git clone for --git-sizer. Defaults to the current directory.',
39
+ }),
40
+ };
41
+ async run() {
42
+ const { flags } = await this.parse(HealthCheck);
43
+ const result = await this.withSpinner('Running organization health checks', runOrganizationHealthChecks);
44
+ if (flags['git-sizer']) {
45
+ result.gitSizer = await analyzeGitRepository({ repoPath: flags.path });
46
+ }
47
+ this.display(() => {
48
+ this.log(table([
49
+ { alias: 'Status', value: 'status' },
50
+ { alias: 'Check', value: 'name' },
51
+ { alias: 'Severity', value: 'severity' },
52
+ { alias: 'Impact', value: 'impact', wrap: true },
53
+ ], result.checks.map((check) => ({ ...check, status: displayStatus(check.status) }))));
54
+ this.log(`Summary: ${result.summary.total} total, ${result.summary.pass} pass, ` +
55
+ `${result.summary.warn} warn, ${result.summary.fail} fail`);
56
+ if (result.gitSizer) {
57
+ this.logGitSizer(result.gitSizer);
58
+ }
59
+ });
60
+ return result;
61
+ }
62
+ logGitSizer(report) {
63
+ this.log('');
64
+ this.log(`Git repository size (${report.path})`);
65
+ if (report.status !== 'ok' || !report.metrics) {
66
+ this.log(report.message ?? `git-sizer ${report.status}`);
67
+ return;
68
+ }
69
+ this.log(table([
70
+ { alias: 'Metric', value: 'description', wrap: true },
71
+ { alias: 'Value', value: 'value' },
72
+ { alias: 'Unit', value: 'unit' },
73
+ { alias: 'Concern', value: 'levelOfConcern' },
74
+ ], gitSizerRows(report.metrics)));
75
+ }
76
+ }
77
+ //# sourceMappingURL=health-check.js.map
@@ -0,0 +1,21 @@
1
+ import { Args, Flags } from '@oclif/core';
2
+ import { AgentiaCommand } from '../../../../../lib/agentia-command.js';
3
+ import { configureHttps, promptHttpsPayload, readHttpsAuthPayloadFromStdin } from '../../../../../lib/repository-auth.js';
4
+ export default class RepositoryAuthHttpsConfigure extends AgentiaCommand {
5
+ static args = { id: Args.string({ description: 'Copado Git repository ID', required: true }) };
6
+ static description = 'Configure HTTPS authentication. Use a personal access token as the password when required by the provider.';
7
+ static flags = {
8
+ 'input-stdin': Flags.boolean({ description: 'Read the complete HTTPS authentication JSON payload from stdin' }),
9
+ overwrite: Flags.boolean({ description: 'Replace an existing validated HTTPS credential' }),
10
+ };
11
+ async run() {
12
+ const { args, flags } = await this.parse(RepositoryAuthHttpsConfigure);
13
+ if (this.jsonEnabled() && !flags['input-stdin'])
14
+ this.error('--json requires --input-stdin so secrets cannot be prompted.', { exit: 2 });
15
+ const payload = flags['input-stdin'] ? await readHttpsAuthPayloadFromStdin() : await promptHttpsPayload(args.id);
16
+ await this.withSpinner('Configuring HTTPS authentication', () => configureHttps(args.id, payload, flags.overwrite, !flags['input-stdin']));
17
+ this.display(() => this.log(`Configured HTTPS authentication for repository ${args.id}.`));
18
+ return { id: args.id };
19
+ }
20
+ }
21
+ //# sourceMappingURL=configure.js.map
@@ -0,0 +1,56 @@
1
+ import { select } from '@inquirer/prompts';
2
+ import { Args, Flags } from '@oclif/core';
3
+ import { AgentiaCommand } from '../../../../../lib/agentia-command.js';
4
+ import { CicdGateway } from '../../../../../lib/cicd-gateway.js';
5
+ import { createLoopbackCallbackServer } from '../../../../../lib/loopback-callback-server.js';
6
+ import { isHeadlessEnvironment, openUrl } from '../../../../../lib/open-browser.js';
7
+ import { repositoryOAuthEndpoint, repositoryOAuthInitEndpoint, repositoryOAuthRepositoriesEndpoint, } from '../../../../../lib/repository-types.js';
8
+ export default class RepositoryAuthOAuthLogin extends AgentiaCommand {
9
+ static args = { id: Args.string({ description: 'Copado Git repository ID', required: true }) };
10
+ static description = 'Authenticate a repository through browser OAuth and select a remote repository';
11
+ static flags = {
12
+ port: Flags.integer({ description: 'Local callback port (default: scan 8080-8090)' }),
13
+ timeout: Flags.integer({ default: 300, description: 'Seconds to wait for browser authentication' }),
14
+ };
15
+ async run() {
16
+ const { args, flags } = await this.parse(RepositoryAuthOAuthLogin);
17
+ if (this.jsonEnabled())
18
+ this.error('OAuth login requires an interactive terminal to select a repository.', { exit: 2 });
19
+ const callback = await createLoopbackCallbackServer({ port: flags.port });
20
+ if (!callback)
21
+ this.error('Could not bind a local OAuth callback port.', { exit: 2 });
22
+ try {
23
+ const init = await this.withSpinner('Generating OAuth authorization URL', () => CicdGateway.call({
24
+ endpoint: repositoryOAuthInitEndpoint(args.id, callback.callbackUrl),
25
+ method: 'POST',
26
+ }));
27
+ if (isHeadlessEnvironment()) {
28
+ this.log(`Complete authentication in your browser by opening this URL:\n${init.authUrl}`);
29
+ }
30
+ else {
31
+ this.log('Complete authentication in the browser window that opens.');
32
+ await openUrl(init.authUrl);
33
+ }
34
+ const result = await callback.waitForCallback({ timeoutMs: flags.timeout * 1000 });
35
+ if (!result.ok)
36
+ this.error(result.errorDescription ?? result.errorCode ?? 'OAuth authentication failed.', { exit: 1 });
37
+ const available = await CicdGateway.call({ endpoint: repositoryOAuthRepositoriesEndpoint(args.id), method: 'GET' });
38
+ const remoteRepositoryId = await select({
39
+ choices: available.repositories.map((repository) => ({ name: repository.name, value: repository.id })),
40
+ message: `Select ${available.provider} repository`,
41
+ });
42
+ await this.withSpinner('Saving selected repository', () => CicdGateway.call({
43
+ body: { remoteRepositoryId },
44
+ endpoint: repositoryOAuthEndpoint(args.id),
45
+ headers: { 'Content-Type': 'application/json' },
46
+ method: 'POST',
47
+ }));
48
+ this.log(`Configured OAuth authentication for repository ${args.id}.`);
49
+ return { id: args.id, remoteRepositoryId };
50
+ }
51
+ finally {
52
+ await callback.close().catch(() => { });
53
+ }
54
+ }
55
+ }
56
+ //# sourceMappingURL=login.js.map
@@ -0,0 +1,28 @@
1
+ import { select } from '@inquirer/prompts';
2
+ import { Args, Flags } from '@oclif/core';
3
+ import { AgentiaCommand } from '../../../../lib/agentia-command.js';
4
+ export default class RepositoryAuthSetup extends AgentiaCommand {
5
+ static args = { id: Args.string({ description: 'Copado Git repository ID', required: true }) };
6
+ static description = 'Interactively configure repository authentication; OAuth is selected by default';
7
+ static flags = { overwrite: Flags.boolean({ description: 'Replace an existing HTTPS or SSH credential' }) };
8
+ async run() {
9
+ const { args, flags } = await this.parse(RepositoryAuthSetup);
10
+ if (this.jsonEnabled())
11
+ this.error('Repository auth setup requires an interactive terminal.', { exit: 2 });
12
+ const authType = await select({
13
+ choices: [
14
+ { name: 'OAuth (recommended)', value: 'oauth' },
15
+ { name: 'HTTPS', value: 'https' },
16
+ { name: 'SSH', value: 'ssh' },
17
+ ],
18
+ default: 'oauth',
19
+ message: 'Authentication type',
20
+ });
21
+ const command = authType === 'oauth'
22
+ ? 'cicd:repository:auth:oauth:login'
23
+ : `cicd:repository:auth:${authType}:configure`;
24
+ const argv = [args.id, ...(flags.overwrite && authType !== 'oauth' ? ['--overwrite'] : [])];
25
+ await this.config.runCommand(command, argv);
26
+ }
27
+ }
28
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1,22 @@
1
+ import { Args, Flags } from '@oclif/core';
2
+ import { AgentiaCommand } from '../../../../../lib/agentia-command.js';
3
+ import { configureSsh, promptConnection } from '../../../../../lib/repository-auth.js';
4
+ export default class RepositoryAuthSshConfigure extends AgentiaCommand {
5
+ static args = { id: Args.string({ description: 'Copado Git repository ID', required: true }) };
6
+ static description = 'Generate SSH authentication and a public key. Add the key to your Git provider as a deploy, access, or SSH key.';
7
+ static flags = {
8
+ overwrite: Flags.boolean({ description: 'Replace an existing SSH key after confirmation' }),
9
+ };
10
+ async run() {
11
+ const { args, flags } = await this.parse(RepositoryAuthSshConfigure);
12
+ if (this.jsonEnabled())
13
+ this.error('SSH authentication requires an interactive terminal to collect connection details.', { exit: 2 });
14
+ const payload = await promptConnection(args.id, 'SSH');
15
+ const publicKey = await this.withSpinner('Generating SSH key', () => configureSsh(args.id, payload, flags.overwrite));
16
+ this.display(() => {
17
+ this.log(`Add this public key to your Git provider's repository deploy/access/SSH keys, then retain it for this repository:\n${publicKey}`);
18
+ });
19
+ return { id: args.id, publicKey };
20
+ }
21
+ }
22
+ //# sourceMappingURL=configure.js.map
@@ -10,9 +10,9 @@ export default class RepositoryCreate extends AgentiaCommand {
10
10
  required: true,
11
11
  }),
12
12
  };
13
- static description = 'Create a Copado Git repository';
13
+ static description = 'Create a Copado Git repository shell';
14
14
  static examples = [
15
- '<%= config.bin %> <%= command.id %> my-repo --source-format DX --provider Github --uri https://github.com/org/repo.git',
15
+ '<%= config.bin %> <%= command.id %> my-repo --source-format DX --provider Github',
16
16
  '<%= config.bin %> <%= command.id %> my-repo --source-format DX --provider GitLab --json',
17
17
  ];
18
18
  static flags = repositoryCreateFlags;