@outputai/cli 0.17.1-next.b47353f.0 → 0.18.1-dev.72b80da.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/assets/docker/docker-compose-dev.yml +1 -1
  2. package/dist/commands/workflow/dataset/generate.d.ts +8 -6
  3. package/dist/commands/workflow/dataset/generate.js +46 -80
  4. package/dist/commands/workflow/dataset/generate.spec.js +154 -83
  5. package/dist/commands/workflow/debug.d.ts +8 -3
  6. package/dist/commands/workflow/debug.js +35 -25
  7. package/dist/commands/workflow/debug.spec.js +76 -22
  8. package/dist/commands/workflow/test.js +0 -3
  9. package/dist/commands/workflow/test.spec.js +19 -0
  10. package/dist/generated/framework_version.json +1 -1
  11. package/dist/services/datasets.d.ts +1 -3
  12. package/dist/services/datasets.js +1 -19
  13. package/dist/services/datasets.test.js +45 -3
  14. package/dist/services/temporal_client.d.ts +50 -0
  15. package/dist/services/temporal_client.js +84 -0
  16. package/dist/services/temporal_client.spec.d.ts +1 -0
  17. package/dist/services/temporal_client.spec.js +129 -0
  18. package/dist/services/workflow_debug.d.ts +68 -0
  19. package/dist/services/workflow_debug.js +273 -0
  20. package/dist/services/workflow_debug.spec.d.ts +1 -0
  21. package/dist/services/workflow_debug.spec.js +363 -0
  22. package/dist/services/workflow_run_data.d.ts +26 -0
  23. package/dist/services/workflow_run_data.js +67 -0
  24. package/dist/services/workflow_run_data.spec.d.ts +1 -0
  25. package/dist/services/workflow_run_data.spec.js +190 -0
  26. package/dist/types/trace.d.ts +1 -73
  27. package/dist/types/trace.js +1 -12
  28. package/dist/utils/payload_truncator.d.ts +23 -0
  29. package/dist/utils/payload_truncator.js +92 -0
  30. package/dist/utils/payload_truncator.spec.d.ts +1 -0
  31. package/dist/utils/payload_truncator.spec.js +51 -0
  32. package/dist/utils/temporal_flags.d.ts +14 -0
  33. package/dist/utils/temporal_flags.js +16 -0
  34. package/oclif.manifest.json +80 -36
  35. package/package.json +10 -2
  36. package/dist/utils/trace_extractor.d.ts +0 -27
  37. package/dist/utils/trace_extractor.js +0 -53
  38. package/dist/utils/trace_formatter.d.ts +0 -11
  39. package/dist/utils/trace_formatter.js +0 -401
@@ -80,7 +80,7 @@ services:
80
80
  condition: service_healthy
81
81
  worker:
82
82
  condition: service_healthy
83
- image: outputai/api:${OUTPUT_API_VERSION:-0.17.1-next.b47353f.0}
83
+ image: outputai/api:${OUTPUT_API_VERSION:-0.18.1-dev.72b80da.0}
84
84
  init: true
85
85
  networks:
86
86
  - main
@@ -7,18 +7,20 @@ export default class DatasetGenerate extends Command {
7
7
  scenario: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
8
8
  };
9
9
  static flags: {
10
+ profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ address: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ namespace: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
13
  catalog: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
- trace: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
14
  name: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
- download: import("@oclif/core/interfaces").BooleanFlag<boolean>;
14
- limit: import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
15
15
  input: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
+ 'workflow-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ 'run-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
18
  };
17
19
  run(): Promise<void>;
18
20
  private generateFromScenario;
19
- private generateFromTrace;
20
- private generateFromRuns;
21
- private generateFromRun;
21
+ private generateFromWorkflowRun;
22
+ /** Reads the run from Temporal and reports any failure by its message alone, as `workflow debug` does */
23
+ private readWorkflowRun;
22
24
  private resolveScenarioInput;
23
25
  catch(error: Error): Promise<void>;
24
26
  }
@@ -1,19 +1,19 @@
1
- import { readFile } from 'node:fs/promises';
2
1
  import { Args, Command, Flags, ux } from '@oclif/core';
3
2
  import { postWorkflowRun } from '#api/generated/api.js';
4
- import { writeDataset, resolveDefaultDatasetsDir, buildDataset, getExecutionTime, extractDatasetName, datasetFilePath } from '#services/datasets.js';
5
- import { fetchWorkflowRuns } from '#services/workflow_runs.js';
6
- import { getTrace } from '#services/trace_reader.js';
7
- import { extractDatasetFromTrace } from '#utils/trace_extractor.js';
3
+ import { writeDataset, resolveDefaultDatasetsDir, buildDataset, datasetFilePath } from '#services/datasets.js';
4
+ import { createTemporalClient, formatTemporalError } from '#services/temporal_client.js';
5
+ import { collectWorkflowRunData } from '#services/workflow_run_data.js';
6
+ import { temporalFlags } from '#utils/temporal_flags.js';
8
7
  import { resolveScenarioPath, getScenarioNotFoundMessage } from '#utils/scenario_resolver.js';
9
8
  import { parseInputFlag } from '#utils/input_parser.js';
10
- import { createErrorFn, handleApiError } from '#utils/error_handler.js';
9
+ import { createErrorFn, handleCommandError } from '#utils/error_handler.js';
11
10
  export default class DatasetGenerate extends Command {
12
- static description = 'Generate a dataset for a workflow from a scenario, trace file, or recent runs';
11
+ static description = 'Generate a dataset case for a workflow from a scenario, an input, or a completed run read from Temporal';
13
12
  static examples = [
14
13
  '<%= config.bin %> <%= command.id %> simple basic_input',
15
- '<%= config.bin %> <%= command.id %> simple --trace logs/runs/simple/trace.json --name edge_case',
16
- '<%= config.bin %> <%= command.id %> simple --download --limit 5'
14
+ '<%= config.bin %> <%= command.id %> simple --input \'{"values":[1,2,3]}\' --name edge_case',
15
+ '<%= config.bin %> <%= command.id %> simple --workflow-id wf-12345 --name edge_case',
16
+ '<%= config.bin %> <%= command.id %> simple --workflow-id wf-12345 --run-id 11111111-2222-4333-8444-555555555555 --profile prod'
17
17
  ];
18
18
  static args = {
19
19
  workflowName: Args.string({
@@ -34,39 +34,36 @@ export default class DatasetGenerate extends Command {
34
34
  description: 'Catalog name for workflow execution (defaults to OUTPUT_CATALOG_ID)',
35
35
  env: 'OUTPUT_CATALOG_ID'
36
36
  }),
37
- trace: Flags.string({
38
- char: 't',
39
- description: 'Path to a local trace file to extract dataset from',
40
- exclusive: ['download']
41
- }),
42
37
  name: Flags.string({
43
38
  char: 'n',
44
- description: 'Dataset name (defaults to scenario name or trace filename)'
45
- }),
46
- download: Flags.boolean({
47
- char: 'd',
48
- description: 'Generate datasets from recent workflow runs fetched via the Output API',
49
- default: false,
50
- exclusive: ['trace']
51
- }),
52
- limit: Flags.integer({
53
- char: 'l',
54
- description: 'Maximum number of recent runs to fetch',
55
- default: 5
39
+ description: 'Dataset name (defaults to the scenario name, or the workflow id with --workflow-id)'
56
40
  }),
57
41
  input: Flags.string({
58
42
  char: 'i',
59
43
  description: 'Workflow input as JSON string or file path (overrides scenario)'
60
- })
44
+ }),
45
+ 'workflow-id': Flags.string({
46
+ description: 'Workflow id of a completed run to read from Temporal (not the workflow type)',
47
+ exclusive: ['input']
48
+ }),
49
+ 'run-id': Flags.string({
50
+ char: 'r',
51
+ description: 'Run to read (defaults to the latest run of the workflow id)',
52
+ dependsOn: ['workflow-id']
53
+ }),
54
+ ...temporalFlags
61
55
  };
62
56
  async run() {
63
57
  const { args, flags } = await this.parse(DatasetGenerate);
64
- if (flags.download) {
65
- await this.generateFromRuns(args.workflowName, flags.limit, flags.catalog);
66
- return;
67
- }
68
- if (flags.trace) {
69
- await this.generateFromTrace(args.workflowName, flags.trace, flags.name);
58
+ if (flags['workflow-id'] !== undefined) {
59
+ const workflowId = flags['workflow-id'].trim();
60
+ if (!workflowId) {
61
+ this.error('--workflow-id cannot be empty.', { exit: 1 });
62
+ }
63
+ if (args.scenario) {
64
+ this.error('Cannot use both scenario argument and --workflow-id flag. Choose one.', { exit: 1 });
65
+ }
66
+ await this.generateFromWorkflowRun(args.workflowName, workflowId, flags['run-id'], flags.name, flags);
70
67
  return;
71
68
  }
72
69
  await this.generateFromScenario(args.workflowName, args.scenario, flags.input, flags.name, flags.catalog);
@@ -85,65 +82,34 @@ export default class DatasetGenerate extends Command {
85
82
  if (!response?.data) {
86
83
  this.error('API returned invalid response', { exit: 1 });
87
84
  }
88
- const { workflowId, output } = response.data;
89
- const executionTimeMs = await getExecutionTime(workflowId);
90
- const dataset = buildDataset(datasetName, resolvedInput, output, executionTimeMs);
85
+ const { output } = response.data;
86
+ const dataset = buildDataset(datasetName, resolvedInput, output);
91
87
  const dir = await resolveDefaultDatasetsDir(workflowName);
92
88
  const filePath = datasetFilePath(dir, datasetName);
93
89
  await writeDataset(dataset, filePath);
94
90
  this.log(`Dataset saved: ${filePath}`);
95
91
  }
96
- async generateFromTrace(workflowName, tracePath, nameOverride) {
97
- this.log(`Reading trace: ${tracePath}`);
98
- const content = await readFile(tracePath, 'utf-8');
99
- const traceData = JSON.parse(content);
100
- const extracted = extractDatasetFromTrace(traceData);
101
- const datasetName = nameOverride ?? extractDatasetName(tracePath);
102
- const dataset = buildDataset(datasetName, extracted.input, extracted.output, extracted.executionTimeMs);
92
+ async generateFromWorkflowRun(workflowName, workflowId, runId, nameOverride, temporal) {
93
+ this.log(`Reading workflow "${workflowId}" from Temporal...`);
94
+ const data = await this.readWorkflowRun(workflowName, workflowId, runId, temporal);
95
+ if (data.inputRunId !== data.runId) {
96
+ this.log(`Run ${data.runId} is a continuation (continue-as-new) of workflow "${workflowId}". Using the input of its first run: ${data.inputRunId}.`);
97
+ }
98
+ const datasetName = nameOverride ?? workflowId;
99
+ const dataset = buildDataset(datasetName, data.input, data.output);
103
100
  const dir = await resolveDefaultDatasetsDir(workflowName);
104
101
  const filePath = datasetFilePath(dir, datasetName);
105
102
  await writeDataset(dataset, filePath);
106
103
  this.log(`Dataset saved: ${filePath}`);
107
104
  }
108
- async generateFromRuns(workflowName, limit, catalog) {
109
- this.log(`Fetching recent runs for "${workflowName}"...`);
110
- const { runs, skipped } = await fetchWorkflowRuns({ workflowType: workflowName, catalog, limit });
111
- if (runs.length === 0) {
112
- if (skipped > 0) {
113
- this.error(`Found ${skipped} run(s) but none had a workflow ID.`, { exit: 1 });
114
- }
115
- this.log('No recent runs found.');
116
- return;
117
- }
118
- if (skipped > 0) {
119
- this.warn(`Skipping ${skipped} run(s) with no workflow ID.`);
120
- }
121
- // The trace-log endpoint always targets a workflow's latest run, so distinct
122
- // runIds sharing one workflowId (continue-as-new, reset) collapse to one dataset.
123
- const workflowIds = [...new Set(runs.map(run => run.workflowId))];
124
- this.log(`Found ${workflowIds.length} run(s). Fetching traces...`);
125
- const dir = await resolveDefaultDatasetsDir(workflowName);
126
- const generated = (await Promise.all(workflowIds.map(id => this.generateFromRun(id, dir))))
127
- .filter(Boolean).length;
128
- this.log(`\nGenerated ${generated} dataset(s)`);
129
- if (generated === 0) {
130
- this.error(`Failed to generate any datasets from ${workflowIds.length} run(s).`, { exit: 1 });
131
- }
132
- }
133
- async generateFromRun(workflowId, dir) {
105
+ /** Reads the run from Temporal and reports any failure by its message alone, as `workflow debug` does */
106
+ async readWorkflowRun(workflowName, workflowId, runId, temporal) {
134
107
  try {
135
- const { data: traceData } = await getTrace(workflowId);
136
- const extracted = extractDatasetFromTrace(traceData);
137
- const dataset = buildDataset(workflowId, extracted.input, extracted.output, extracted.executionTimeMs);
138
- const filePath = datasetFilePath(dir, workflowId);
139
- await writeDataset(dataset, filePath);
140
- this.log(` Saved: ${filePath}`);
141
- return true;
108
+ const { client, close } = await createTemporalClient(temporal);
109
+ return await collectWorkflowRunData(client, { workflowName, workflowId, runId }).finally(close);
142
110
  }
143
111
  catch (error) {
144
- const message = error instanceof Error ? error.message : String(error);
145
- this.warn(` Skipped ${workflowId}: ${message}`);
146
- return false;
112
+ return this.error(formatTemporalError(error), { exit: 1 });
147
113
  }
148
114
  }
149
115
  async resolveScenarioInput(workflowName, scenario, inputFlag, catalog) {
@@ -165,7 +131,7 @@ export default class DatasetGenerate extends Command {
165
131
  ' - An input flag: output workflow dataset generate <workflow> --input <json>', { exit: 1 });
166
132
  }
167
133
  async catch(error) {
168
- return handleApiError(error, createErrorFn(this), {
134
+ return handleCommandError(error, createErrorFn(this), {
169
135
  404: 'Workflow not found. Check the workflow name.',
170
136
  500: 'Workflow execution failed.'
171
137
  });
@@ -1,16 +1,16 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import { describe, it, expect, vi, beforeEach } from 'vitest';
3
+ import { Parser } from '@oclif/core';
4
+ import { WorkflowNotFoundError } from '@temporalio/client';
3
5
  vi.mock('#api/generated/api.js', () => ({
4
6
  postWorkflowRun: vi.fn()
5
7
  }));
6
- vi.mock('#services/workflow_runs.js', () => ({
7
- fetchWorkflowRuns: vi.fn()
8
+ vi.mock('#services/temporal_client.js', async (importOriginal) => ({
9
+ ...await importOriginal(),
10
+ createTemporalClient: vi.fn()
8
11
  }));
9
- vi.mock('#services/trace_reader.js', () => ({
10
- getTrace: vi.fn()
11
- }));
12
- vi.mock('#utils/trace_extractor.js', () => ({
13
- extractDatasetFromTrace: vi.fn().mockReturnValue({ input: { a: 1 }, output: { ok: true }, executionTimeMs: 5 })
12
+ vi.mock('#services/workflow_run_data.js', () => ({
13
+ collectWorkflowRunData: vi.fn()
14
14
  }));
15
15
  vi.mock('#utils/scenario_resolver.js', () => ({
16
16
  resolveScenarioPath: vi.fn(),
@@ -23,8 +23,6 @@ vi.mock('#services/datasets.js', () => ({
23
23
  writeDataset: vi.fn(),
24
24
  resolveDefaultDatasetsDir: vi.fn().mockResolvedValue('/datasets'),
25
25
  buildDataset: vi.fn().mockReturnValue({ name: 'basic' }),
26
- getExecutionTime: vi.fn().mockResolvedValue(100),
27
- extractDatasetName: vi.fn(),
28
26
  datasetFilePath: vi.fn((dir, name) => `${dir}/${name.replace(/[^a-zA-Z0-9._-]/g, '_')}.yml`)
29
27
  }));
30
28
  describe('workflow dataset generate command', () => {
@@ -51,12 +49,46 @@ describe('workflow dataset generate command', () => {
51
49
  expect(DatasetGenerate.flags.catalog.char).toBe('c');
52
50
  });
53
51
  });
52
+ describe('command definition (flags)', () => {
53
+ it('no longer has the trace modes', async () => {
54
+ const DatasetGenerate = (await import('./generate.js')).default;
55
+ expect(DatasetGenerate.flags).not.toHaveProperty('trace');
56
+ expect(DatasetGenerate.flags).not.toHaveProperty('download');
57
+ expect(DatasetGenerate.flags).not.toHaveProperty('limit');
58
+ });
59
+ it('has the run flags and the shared Temporal flags', async () => {
60
+ const DatasetGenerate = (await import('./generate.js')).default;
61
+ expect(DatasetGenerate.flags).toHaveProperty('workflow-id');
62
+ expect(DatasetGenerate.flags).toHaveProperty('run-id');
63
+ expect(DatasetGenerate.flags).toHaveProperty('profile');
64
+ expect(DatasetGenerate.flags).toHaveProperty('address');
65
+ expect(DatasetGenerate.flags).toHaveProperty('namespace');
66
+ });
67
+ // Parser.parse needs no oclif Config, so what oclif does with the flag relations can be pinned directly
68
+ describe('flag parsing', () => {
69
+ const parse = async (argv) => {
70
+ const DatasetGenerate = (await import('./generate.js')).default;
71
+ return Parser.parse(argv, { flags: DatasetGenerate.flags, args: DatasetGenerate.args });
72
+ };
73
+ it('accepts --workflow-id alone, and with -r and --name', async () => {
74
+ await expect(parse(['my_workflow', '--workflow-id', 'wf-1'])).resolves.toMatchObject({ flags: { 'workflow-id': 'wf-1' } });
75
+ await expect(parse(['my_workflow', '--workflow-id', 'wf-1', '-r', 'run-1', '--name', 'case']))
76
+ .resolves.toMatchObject({ flags: { 'workflow-id': 'wf-1', 'run-id': 'run-1', name: 'case' } });
77
+ });
78
+ it('rejects --run-id without --workflow-id', async () => {
79
+ await expect(parse(['my_workflow', '--run-id', 'run-1'])).rejects.toThrow(/--workflow-id/);
80
+ });
81
+ it('rejects --workflow-id together with --input', async () => {
82
+ await expect(parse(['my_workflow', '--workflow-id', 'wf-1', '--input', '{}'])).rejects.toThrow(/--input/);
83
+ });
84
+ });
85
+ });
54
86
  describe('run()', () => {
55
87
  const createCommand = async (flagOverrides = {}) => {
56
88
  const { postWorkflowRun } = await import('#api/generated/api.js');
57
89
  const { resolveScenarioPath } = await import('#utils/scenario_resolver.js');
58
90
  const { parseInputFlag } = await import('#utils/input_parser.js');
59
- const cmd = await makeCmd({ workflowName: 'my_workflow', scenario: 'basic' }, { catalog: undefined, trace: undefined, name: undefined, download: false, limit: 5, input: undefined, ...flagOverrides });
91
+ const cmd = await makeCmd({ workflowName: 'my_workflow', scenario: 'basic' }, { catalog: undefined, name: undefined, input: undefined, ...flagOverrides });
60
92
  return {
61
93
  cmd,
62
94
  postWorkflowRun: vi.mocked(postWorkflowRun),
@@ -64,6 +96,24 @@ describe('workflow dataset generate command', () => {
64
96
  parseInputFlag: vi.mocked(parseInputFlag)
65
97
  };
66
98
  };
99
+ it('does not connect to Temporal in scenario mode', async () => {
100
+ const { createTemporalClient } = await import('#services/temporal_client.js');
101
+ const { cmd, postWorkflowRun, resolveScenarioPath, parseInputFlag } = await createCommand();
102
+ resolveScenarioPath.mockResolvedValue({ found: true, path: '/scenarios/basic.json', searchedPaths: [] });
103
+ parseInputFlag.mockResolvedValue({ foo: 'bar' });
104
+ postWorkflowRun.mockResolvedValue({ data: { workflowId: 'wf-1', output: { ok: true } }, status: 200, headers: new Headers() });
105
+ await cmd.run();
106
+ expect(createTemporalClient).not.toHaveBeenCalled();
107
+ });
108
+ it('saves the scenario output with only the output and the date', async () => {
109
+ const { buildDataset } = await import('#services/datasets.js');
110
+ const { cmd, postWorkflowRun, resolveScenarioPath, parseInputFlag } = await createCommand();
111
+ resolveScenarioPath.mockResolvedValue({ found: true, path: '/scenarios/basic.json', searchedPaths: [] });
112
+ parseInputFlag.mockResolvedValue({ foo: 'bar' });
113
+ postWorkflowRun.mockResolvedValue({ data: { workflowId: 'wf-1', output: { ok: true } }, status: 200, headers: new Headers() });
114
+ await cmd.run();
115
+ expect(buildDataset).toHaveBeenCalledWith('basic', { foo: 'bar' }, { ok: true });
116
+ });
67
117
  it('resolves the scenario and runs the workflow against the resolved catalog', async () => {
68
118
  const { cmd, postWorkflowRun, resolveScenarioPath, parseInputFlag } = await createCommand({ catalog: 'my-catalog' });
69
119
  resolveScenarioPath.mockResolvedValue({ found: true, path: '/scenarios/basic.json', searchedPaths: [] });
@@ -78,97 +128,118 @@ describe('workflow dataset generate command', () => {
78
128
  expect(postWorkflowRun).toHaveBeenCalledWith(expect.objectContaining({ workflowName: 'my_workflow', catalog: 'my-catalog' }), expect.anything());
79
129
  });
80
130
  });
81
- describe('run() --download', () => {
82
- const createDownloadCommand = async (flagOverrides = {}) => {
83
- const { fetchWorkflowRuns } = await import('#services/workflow_runs.js');
84
- const { getTrace } = await import('#services/trace_reader.js');
85
- const { writeDataset } = await import('#services/datasets.js');
86
- const cmd = await makeCmd({ workflowName: 'my_workflow', scenario: undefined }, { catalog: 'my-catalog', trace: undefined, name: undefined, download: true, limit: 5, input: undefined, ...flagOverrides });
131
+ describe('run() --workflow-id', () => {
132
+ const createWorkflowIdCommand = async (flagOverrides = {}, scenario) => {
133
+ const { createTemporalClient } = await import('#services/temporal_client.js');
134
+ const { collectWorkflowRunData } = await import('#services/workflow_run_data.js');
135
+ const { buildDataset, writeDataset } = await import('#services/datasets.js');
136
+ const close = vi.fn().mockResolvedValue(undefined);
137
+ const client = {};
138
+ vi.mocked(createTemporalClient).mockResolvedValue({ client, address: 'a:1', namespace: 'default', close });
139
+ const cmd = await makeCmd({ workflowName: 'my_workflow', scenario }, { name: undefined, input: undefined, 'workflow-id': 'wf-1', 'run-id': undefined, ...flagOverrides });
87
140
  return {
88
141
  cmd,
89
- fetchWorkflowRuns: vi.mocked(fetchWorkflowRuns),
90
- getTrace: vi.mocked(getTrace),
91
- writeDataset: vi.mocked(writeDataset)
142
+ client,
143
+ close,
144
+ collectWorkflowRunData: vi.mocked(collectWorkflowRunData),
145
+ buildDataset: vi.mocked(buildDataset),
146
+ writeDataset: vi.mocked(writeDataset),
147
+ createTemporalClient: vi.mocked(createTemporalClient)
92
148
  };
93
149
  };
94
- it('fetches recent runs scoped to the catalog and writes a dataset per run', async () => {
95
- const { cmd, fetchWorkflowRuns, getTrace, writeDataset } = await createDownloadCommand();
96
- fetchWorkflowRuns.mockResolvedValue({
97
- runs: [{ workflowId: 'wf-1' }, { workflowId: 'wf-2' }],
98
- skipped: 0,
99
- count: 2
150
+ it('reads the run from Temporal and writes a case named after the workflow id', async () => {
151
+ const { cmd, client, close, collectWorkflowRunData, buildDataset, writeDataset, createTemporalClient } = await createWorkflowIdCommand({
152
+ 'run-id': 'run-1',
153
+ profile: 'prod'
100
154
  });
101
- getTrace.mockResolvedValue({ data: {}, location: { path: 'remote', isRemote: true } });
155
+ collectWorkflowRunData.mockResolvedValue({ workflowId: 'wf-1', runId: 'run-1', inputRunId: 'run-1', input: { a: 1 }, output: { ok: true } });
102
156
  await cmd.run();
103
- expect(fetchWorkflowRuns).toHaveBeenCalledWith({ workflowType: 'my_workflow', catalog: 'my-catalog', limit: 5 });
104
- expect(getTrace).toHaveBeenCalledTimes(2);
105
- expect(getTrace).toHaveBeenCalledWith('wf-1');
106
- expect(getTrace).toHaveBeenCalledWith('wf-2');
107
- expect(writeDataset).toHaveBeenCalledTimes(2);
108
- });
109
- it('skips runs whose trace cannot be fetched and continues', async () => {
110
- const { cmd, fetchWorkflowRuns, getTrace, writeDataset } = await createDownloadCommand();
111
- fetchWorkflowRuns.mockResolvedValue({
112
- runs: [{ workflowId: 'wf-1' }, { workflowId: 'wf-2' }],
113
- skipped: 0,
114
- count: 2
115
- });
116
- getTrace
117
- .mockRejectedValueOnce(new Error('no trace available'))
118
- .mockResolvedValueOnce({ data: {}, location: { path: 'remote', isRemote: true } });
157
+ expect(createTemporalClient).toHaveBeenCalledWith(expect.objectContaining({ profile: 'prod' }));
158
+ expect(collectWorkflowRunData).toHaveBeenCalledWith(client, { workflowName: 'my_workflow', workflowId: 'wf-1', runId: 'run-1' });
159
+ expect(buildDataset).toHaveBeenCalledWith('wf-1', { a: 1 }, { ok: true });
160
+ expect(writeDataset).toHaveBeenCalledWith(expect.anything(), '/datasets/wf-1.yml');
161
+ expect(close).toHaveBeenCalledTimes(1);
162
+ });
163
+ it('says so when the run is a continuation and the input was read from the first run', async () => {
164
+ const { cmd, collectWorkflowRunData, buildDataset } = await createWorkflowIdCommand();
165
+ collectWorkflowRunData.mockResolvedValue({ workflowId: 'wf-1', runId: 'run-3', inputRunId: 'run-1', input: { a: 1 }, output: null });
166
+ await cmd.run();
167
+ expect(cmd.log).toHaveBeenCalledWith('Run run-3 is a continuation (continue-as-new) of workflow "wf-1". Using the input of its first run: run-1.');
168
+ expect(buildDataset).toHaveBeenCalledWith('wf-1', { a: 1 }, null);
169
+ });
170
+ it('does not mention a continuation for a run that did not continue', async () => {
171
+ const { cmd, collectWorkflowRunData } = await createWorkflowIdCommand();
172
+ collectWorkflowRunData.mockResolvedValue({ workflowId: 'wf-1', runId: 'run-1', inputRunId: 'run-1', input: {}, output: null });
173
+ await cmd.run();
174
+ expect(cmd.log).not.toHaveBeenCalledWith(expect.stringContaining('continuation'));
175
+ });
176
+ it('uses --name over the workflow id', async () => {
177
+ const { cmd, collectWorkflowRunData, buildDataset } = await createWorkflowIdCommand({ name: 'edge_case' });
178
+ collectWorkflowRunData.mockResolvedValue({ workflowId: 'wf-1', runId: 'run-1', inputRunId: 'run-1', input: {}, output: null });
119
179
  await cmd.run();
120
- expect(cmd.warn).toHaveBeenCalledWith(expect.stringContaining('wf-1'));
121
- expect(writeDataset).toHaveBeenCalledTimes(1);
180
+ expect(buildDataset).toHaveBeenCalledWith('edge_case', {}, null);
122
181
  });
123
- it('reports when no recent runs are found', async () => {
124
- const { cmd, fetchWorkflowRuns, getTrace, writeDataset } = await createDownloadCommand();
125
- fetchWorkflowRuns.mockResolvedValue({ runs: [], skipped: 0, count: 0 });
182
+ it('sanitizes path separators in the workflow id used for the filename', async () => {
183
+ const { cmd, collectWorkflowRunData, writeDataset } = await createWorkflowIdCommand({ 'workflow-id': '../../escape' });
184
+ collectWorkflowRunData.mockResolvedValue({ workflowId: '../../escape', runId: 'run-1', inputRunId: 'run-1', input: {}, output: null });
126
185
  await cmd.run();
127
- expect(getTrace).not.toHaveBeenCalled();
186
+ expect(writeDataset).toHaveBeenCalledWith(expect.anything(), '/datasets/.._.._escape.yml');
187
+ });
188
+ it('writes nothing and closes the connection when the run cannot be read', async () => {
189
+ const { cmd, close, collectWorkflowRunData, writeDataset } = await createWorkflowIdCommand();
190
+ collectWorkflowRunData.mockRejectedValue(new Error('not completed'));
191
+ await expect(cmd.run()).rejects.toThrow('error called');
192
+ expect(cmd.error).toHaveBeenCalledWith('not completed', { exit: 1 });
128
193
  expect(writeDataset).not.toHaveBeenCalled();
194
+ expect(close).toHaveBeenCalledTimes(1);
129
195
  });
130
- it('exits non-zero when every run fails to produce a dataset', async () => {
131
- const { cmd, fetchWorkflowRuns, getTrace } = await createDownloadCommand();
132
- fetchWorkflowRuns.mockResolvedValue({ runs: [{ workflowId: 'wf-1' }], skipped: 0, count: 1 });
133
- getTrace.mockRejectedValue(new Error('no trace available'));
196
+ it('writes nothing and reports the message when Temporal cannot be reached', async () => {
197
+ const { cmd, createTemporalClient, collectWorkflowRunData, writeDataset } = await createWorkflowIdCommand();
198
+ createTemporalClient.mockRejectedValue(new Error('Cannot connect to Temporal at localhost:1: refused'));
134
199
  await expect(cmd.run()).rejects.toThrow('error called');
135
- expect(cmd.error).toHaveBeenCalledWith(expect.stringContaining('Failed to generate'), { exit: 1 });
200
+ expect(cmd.error).toHaveBeenCalledWith('Cannot connect to Temporal at localhost:1: refused', { exit: 1 });
201
+ expect(collectWorkflowRunData).not.toHaveBeenCalled();
202
+ expect(writeDataset).not.toHaveBeenCalled();
136
203
  });
137
- it('warns about runs the service skipped for missing a workflow ID', async () => {
138
- const { cmd, fetchWorkflowRuns, getTrace, writeDataset } = await createDownloadCommand();
139
- fetchWorkflowRuns.mockResolvedValue({ runs: [{ workflowId: 'wf-1' }], skipped: 1, count: 2 });
140
- getTrace.mockResolvedValue({ data: {}, location: { path: 'remote', isRemote: true } });
204
+ it('reports the message of a run that cannot be turned into a case', async () => {
205
+ const { cmd, collectWorkflowRunData } = await createWorkflowIdCommand();
206
+ const message = 'Workflow wf-1 (run run-1) is running. Only completed runs can be turned into a dataset case.';
207
+ collectWorkflowRunData.mockRejectedValue(new Error(message));
208
+ await expect(cmd.run()).rejects.toThrow('error called');
209
+ expect(cmd.error).toHaveBeenCalledWith(message, { exit: 1 });
210
+ });
211
+ it('does not touch the API or the trace', async () => {
212
+ const { postWorkflowRun } = await import('#api/generated/api.js');
213
+ const { cmd, collectWorkflowRunData } = await createWorkflowIdCommand();
214
+ collectWorkflowRunData.mockResolvedValue({ workflowId: 'wf-1', runId: 'run-1', inputRunId: 'run-1', input: {}, output: null });
141
215
  await cmd.run();
142
- expect(cmd.warn).toHaveBeenCalledWith(expect.stringContaining('no workflow ID'));
143
- expect(getTrace).toHaveBeenCalledTimes(1);
144
- expect(writeDataset).toHaveBeenCalledTimes(1);
216
+ expect(postWorkflowRun).not.toHaveBeenCalled();
145
217
  });
146
- it('exits non-zero when every run was skipped for missing a workflow ID', async () => {
147
- const { cmd, fetchWorkflowRuns, getTrace } = await createDownloadCommand();
148
- fetchWorkflowRuns.mockResolvedValue({ runs: [], skipped: 2, count: 2 });
218
+ it('rejects an empty --workflow-id without touching Temporal', async () => {
219
+ const { cmd, createTemporalClient, collectWorkflowRunData } = await createWorkflowIdCommand({ 'workflow-id': ' ' });
149
220
  await expect(cmd.run()).rejects.toThrow('error called');
150
- expect(getTrace).not.toHaveBeenCalled();
151
- expect(cmd.error).toHaveBeenCalledWith(expect.stringContaining('none had a workflow ID'), { exit: 1 });
152
- });
153
- it('deduplicates runs that share a workflow ID', async () => {
154
- const { cmd, fetchWorkflowRuns, getTrace, writeDataset } = await createDownloadCommand();
155
- fetchWorkflowRuns.mockResolvedValue({
156
- runs: [{ workflowId: 'wf-1' }, { workflowId: 'wf-1' }],
157
- skipped: 0,
158
- count: 2
159
- });
160
- getTrace.mockResolvedValue({ data: {}, location: { path: 'remote', isRemote: true } });
161
- await cmd.run();
162
- expect(getTrace).toHaveBeenCalledTimes(1);
163
- expect(writeDataset).toHaveBeenCalledTimes(1);
221
+ expect(cmd.error).toHaveBeenCalledWith('--workflow-id cannot be empty.', { exit: 1 });
222
+ expect(createTemporalClient).not.toHaveBeenCalled();
223
+ expect(collectWorkflowRunData).not.toHaveBeenCalled();
164
224
  });
165
- it('sanitizes path separators in the workflow ID used for the filename', async () => {
166
- const { cmd, fetchWorkflowRuns, getTrace, writeDataset } = await createDownloadCommand();
167
- fetchWorkflowRuns.mockResolvedValue({ runs: [{ workflowId: '../../escape' }], skipped: 0, count: 1 });
168
- getTrace.mockResolvedValue({ data: {}, location: { path: 'remote', isRemote: true } });
225
+ it('trims the --workflow-id before reading Temporal and naming the case', async () => {
226
+ const { cmd, collectWorkflowRunData, buildDataset } = await createWorkflowIdCommand({ 'workflow-id': ' wf-1 ' });
227
+ collectWorkflowRunData.mockResolvedValue({ workflowId: 'wf-1', runId: 'run-1', inputRunId: 'run-1', input: {}, output: null });
169
228
  await cmd.run();
170
- const writtenPath = writeDataset.mock.calls[0][1];
171
- expect(writtenPath).toBe('/datasets/.._.._escape.yml');
229
+ expect(collectWorkflowRunData).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ workflowId: 'wf-1' }));
230
+ expect(buildDataset).toHaveBeenCalledWith('wf-1', {}, null);
231
+ });
232
+ it('explains a workflow or run that is not found', async () => {
233
+ const { cmd, collectWorkflowRunData, writeDataset } = await createWorkflowIdCommand();
234
+ collectWorkflowRunData.mockRejectedValue(new WorkflowNotFoundError('workflow not found for ID: wf-1', 'wf-1', undefined));
235
+ await expect(cmd.run()).rejects.toThrow('error called');
236
+ expect(cmd.error).toHaveBeenCalledWith('Workflow not found for ID: wf-1. Check the workflow id, the run id and the namespace.', { exit: 1 });
237
+ expect(writeDataset).not.toHaveBeenCalled();
238
+ });
239
+ it('rejects a scenario argument', async () => {
240
+ const { cmd, collectWorkflowRunData } = await createWorkflowIdCommand({}, 'basic');
241
+ await expect(cmd.run()).rejects.toThrow('error called');
242
+ expect(collectWorkflowRunData).not.toHaveBeenCalled();
172
243
  });
173
244
  });
174
245
  });
@@ -1,12 +1,17 @@
1
1
  import { Command } from '@oclif/core';
2
2
  export default class WorkflowDebug extends Command {
3
3
  static description: string;
4
- static enableJsonFlag: boolean;
5
4
  static examples: string[];
6
5
  static args: {
7
6
  workflowId: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
8
7
  };
9
- run(): Promise<unknown>;
10
- private displayTextTrace;
8
+ static flags: {
9
+ profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ address: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ namespace: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ 'run-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
14
+ };
15
+ run(): Promise<void>;
11
16
  catch(error: Error): Promise<void>;
12
17
  }
@@ -1,13 +1,16 @@
1
- import { Args, Command } from '@oclif/core';
2
- import { displayDebugTree } from '#utils/trace_formatter.js';
3
- import { getTrace } from '#services/trace_reader.js';
4
- import { createErrorFn, handleApiError } from '#utils/error_handler.js';
1
+ import { Args, Command, Flags } from '@oclif/core';
2
+ import { CLIError } from '@oclif/core/errors';
3
+ import { collectWorkflowDebug } from '#services/workflow_debug.js';
4
+ import { createTemporalClient, formatTemporalError } from '#services/temporal_client.js';
5
+ import { temporalFlags } from '#utils/temporal_flags.js';
6
+ import { createErrorFn, handleCommandError } from '#utils/error_handler.js';
5
7
  export default class WorkflowDebug extends Command {
6
- static description = 'Get and display workflow execution trace for debugging';
7
- static enableJsonFlag = true;
8
+ static description = 'Read a workflow run and its child workflows from Temporal as JSON, one entry per workflow, for debugging';
8
9
  static examples = [
9
10
  '<%= config.bin %> <%= command.id %> wf-12345',
10
- '<%= config.bin %> <%= command.id %> wf-12345 --json'
11
+ '<%= config.bin %> <%= command.id %> wf-12345 --run-id 11111111-2222-4333-8444-555555555555',
12
+ '<%= config.bin %> <%= command.id %> wf-12345 --profile prod',
13
+ '<%= config.bin %> <%= command.id %> wf-12345 --address temporal.internal:7233 --namespace staging'
11
14
  ];
12
15
  static args = {
13
16
  workflowId: Args.string({
@@ -15,27 +18,34 @@ export default class WorkflowDebug extends Command {
15
18
  required: true
16
19
  })
17
20
  };
21
+ static flags = {
22
+ 'run-id': Flags.string({
23
+ char: 'r',
24
+ description: 'Run to start from (defaults to the latest run); runs that continue from it are read too'
25
+ }),
26
+ // The output is always JSON; kept so scripts that pass --json keep working
27
+ json: Flags.boolean({
28
+ hidden: true,
29
+ description: 'Accepted and ignored: the output is always JSON'
30
+ }),
31
+ ...temporalFlags
32
+ };
18
33
  async run() {
19
- const { args } = await this.parse(WorkflowDebug);
20
- this.log(`Fetching debug information for workflow: ${args.workflowId}...`);
21
- const { data: traceData, location } = await getTrace(args.workflowId);
22
- const source = location.isRemote ? 'remote' : 'local';
23
- this.log(`Trace source: ${source}${!location.isRemote ? ` (${location.path})` : ''}`);
24
- if (!this.jsonEnabled()) {
25
- this.displayTextTrace(traceData);
34
+ const { args, flags } = await this.parse(WorkflowDebug);
35
+ const { client, address, namespace, close } = await createTemporalClient(flags);
36
+ try {
37
+ const result = await collectWorkflowDebug(client, { address, namespace, workflowId: args.workflowId, runId: flags['run-id'] });
38
+ this.log(JSON.stringify(result));
39
+ }
40
+ finally {
41
+ await close();
26
42
  }
27
- return traceData;
28
- }
29
- displayTextTrace(traceData) {
30
- this.log('\nTrace Log:');
31
- this.log('─'.repeat(80));
32
- this.log(displayDebugTree(traceData));
33
- this.log('\n' + '─'.repeat(80));
34
- this.log('Tip: Use --json for the full untruncated trace');
35
43
  }
36
44
  async catch(error) {
37
- return handleApiError(error, createErrorFn(this), {
38
- 404: 'Workflow not found or trace not available. Check the workflow ID.'
39
- });
45
+ const errorFn = createErrorFn(this);
46
+ if (error instanceof CLIError) {
47
+ return handleCommandError(error, errorFn);
48
+ }
49
+ return errorFn(formatTemporalError(error), { exit: 1 });
40
50
  }
41
51
  }