@assemblyline/al-orc 0.0.0-stage → 0.2.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 (66) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +5 -0
  4. package/README.md +98 -2
  5. package/bin/cli.js +5 -0
  6. package/package.json +59 -4
  7. package/src/cli/_helpers.js +68 -0
  8. package/src/cli/config/add.js +11 -0
  9. package/src/cli/config/current.js +21 -0
  10. package/src/cli/config/index.js +64 -0
  11. package/src/cli/config/list.js +23 -0
  12. package/src/cli/config/remove.js +7 -0
  13. package/src/cli/config/use.js +7 -0
  14. package/src/cli/config-store.js +128 -0
  15. package/src/cli/factory-sessions/index.js +36 -0
  16. package/src/cli/factory-sessions/list.js +94 -0
  17. package/src/cli/factory-sessions/show.js +84 -0
  18. package/src/cli/index.js +62 -0
  19. package/src/cli/lines/index.js +54 -0
  20. package/src/cli/lines/list.js +40 -0
  21. package/src/cli/lines/pull.js +47 -0
  22. package/src/cli/lines/push.js +83 -0
  23. package/src/cli/lines/show.js +37 -0
  24. package/src/cli/shared/edit-tags.js +44 -0
  25. package/src/cli/stations/archive.js +25 -0
  26. package/src/cli/stations/delete.js +9 -0
  27. package/src/cli/stations/edit.js +31 -0
  28. package/src/cli/stations/index.js +105 -0
  29. package/src/cli/stations/list.js +38 -0
  30. package/src/cli/stations/pull.js +74 -0
  31. package/src/cli/stations/push.js +213 -0
  32. package/src/cli/stations/run.js +94 -0
  33. package/src/cli/stations/show.js +75 -0
  34. package/src/cli/status.js +24 -0
  35. package/src/cli/supporting-docs/index.js +22 -0
  36. package/src/cli/supporting-docs/show.js +50 -0
  37. package/src/cli/tags/create.js +22 -0
  38. package/src/cli/tags/delete.js +9 -0
  39. package/src/cli/tags/edit.js +28 -0
  40. package/src/cli/tags/index.js +50 -0
  41. package/src/cli/tags/list.js +25 -0
  42. package/src/cli/utils/format.js +171 -0
  43. package/src/cli/utils/line-files.js +85 -0
  44. package/src/cli/utils/station-files.js +152 -0
  45. package/src/cli/utils/station-labels.js +49 -0
  46. package/src/cli/work-records/cancel.js +25 -0
  47. package/src/cli/work-records/edit.js +23 -0
  48. package/src/cli/work-records/index.js +61 -0
  49. package/src/cli/work-records/list.js +49 -0
  50. package/src/cli/work-records/show.js +104 -0
  51. package/src/http.js +254 -0
  52. package/src/index.js +104 -0
  53. package/src/resources/factory-sessions.js +86 -0
  54. package/src/resources/lines.js +57 -0
  55. package/src/resources/stations.js +90 -0
  56. package/src/resources/supporting-docs.js +37 -0
  57. package/src/resources/tags.js +68 -0
  58. package/src/resources/work-records.js +78 -0
  59. package/src/types/api/Line.types.js +23 -0
  60. package/src/types/api/Station.types.js +36 -0
  61. package/src/types/api/SupportingDoc.types.js +20 -0
  62. package/src/types/api/Tag.types.js +12 -0
  63. package/src/types/api/WorkRecord.types.js +34 -0
  64. package/src/types/general/Credentials.types.js +18 -0
  65. package/src/types/general/Transport.types.js +22 -0
  66. package/src/types/general/index.js +9 -0
@@ -0,0 +1,44 @@
1
+ // @ts-check
2
+ /**
3
+ * Shared --add-tag / --remove-tag flow for taggable entities (stations,
4
+ * work-records). Works against a resource namespace that exposes getTags/setTags
5
+ * plus the tags namespace (ensure/resolveNames), so the CLI holds no paths.
6
+ *
7
+ * @param {{ getTags: (id: string) => Promise<any[]>, setTags: (id: string, tagIds: string[]) => Promise<any> }} ns
8
+ * @param {{ ensure: (name: string) => Promise<{id: string, name: string}>, resolveNames: (names: string[]) => Promise<string[]> }} tags
9
+ * @param {string} id
10
+ * @param {string[]} addTags
11
+ * @param {string[]} removeTags
12
+ */
13
+ export async function editEntityTags(ns, tags, id, addTags, removeTags) {
14
+ const current = await ns.getTags(id);
15
+ let ids = current.map((t) => t.id);
16
+ const changes = [];
17
+
18
+ for (const name of addTags) {
19
+ const tag = await tags.ensure(name);
20
+ if (!ids.includes(tag.id)) {
21
+ ids.push(tag.id);
22
+ changes.push(` + ${name}`);
23
+ } else {
24
+ changes.push(` ${name} (already present)`);
25
+ }
26
+ }
27
+
28
+ for (const name of removeTags) {
29
+ const [resolvedId] = await tags.resolveNames([name]).catch(() => [null]);
30
+ if (!resolvedId) {
31
+ console.error(` Warning: tag "${name}" not found, skipping removal`);
32
+ continue;
33
+ }
34
+ if (ids.includes(resolvedId)) {
35
+ ids = ids.filter((x) => x !== resolvedId);
36
+ changes.push(` - ${name}`);
37
+ } else {
38
+ changes.push(` ${name} (not present)`);
39
+ }
40
+ }
41
+
42
+ await ns.setTags(id, ids);
43
+ for (const change of changes) console.log(change);
44
+ }
@@ -0,0 +1,25 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+
4
+ /** `al-orc stations archive <id>` — hide from default list, preserve history, block execution. */
5
+ export async function archiveStationHandler(argv) {
6
+ const { id, json } = argv;
7
+ const station = await clientFor().stations.archive(id);
8
+ if (json) {
9
+ console.log(JSON.stringify(station, null, 2));
10
+ return;
11
+ }
12
+ // The API response carries short_code; `id` is only what the user typed.
13
+ console.log(`Archived station ${station?.short_code || id}.`);
14
+ }
15
+
16
+ /** `al-orc stations unarchive <id>` — undo archive. */
17
+ export async function unarchiveStationHandler(argv) {
18
+ const { id, json } = argv;
19
+ const station = await clientFor().stations.unarchive(id);
20
+ if (json) {
21
+ console.log(JSON.stringify(station, null, 2));
22
+ return;
23
+ }
24
+ console.log(`Unarchived station ${station?.short_code || id}.`);
25
+ }
@@ -0,0 +1,9 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+
4
+ /** `al-orc stations delete <id>` — permanently delete a station. */
5
+ export async function deleteStationHandler(argv) {
6
+ const { id, cascade } = argv;
7
+ await clientFor().stations.delete(id, { cascade });
8
+ console.log(`Deleted station ${id}${cascade ? ' (cascade)' : ''}.`);
9
+ }
@@ -0,0 +1,31 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+ import { editEntityTags } from '../shared/edit-tags.js';
4
+
5
+ /** `al-orc stations edit <id>` — set short_code and/or add/remove tags. */
6
+ export async function editStationHandler(argv) {
7
+ const { id, shortCode, addTag, removeTag } = argv;
8
+
9
+ const addTags = addTag ? [].concat(addTag) : [];
10
+ const removeTags = removeTag ? [].concat(removeTag) : [];
11
+ const hasTagChanges = addTags.length > 0 || removeTags.length > 0;
12
+
13
+ if (!hasTagChanges && shortCode === undefined) {
14
+ console.error('Usage: al-orc stations edit <id|short_code> --short-code P1 --add-tag <name> [--remove-tag <name>]');
15
+ console.error('At least one of --short-code, --add-tag, or --remove-tag is required');
16
+ process.exit(1);
17
+ }
18
+
19
+ console.log(`Station: ${id}`);
20
+ const orc = clientFor();
21
+
22
+ if (shortCode !== undefined) {
23
+ await orc.stations.update(id, { short_code: shortCode || null });
24
+ console.log(`Short code set: ${shortCode || '(cleared)'}`);
25
+ }
26
+
27
+ if (hasTagChanges) {
28
+ await editEntityTags(orc.stations, orc.tags, id, addTags, removeTags);
29
+ console.log('Tags updated');
30
+ }
31
+ }
@@ -0,0 +1,105 @@
1
+ // @ts-check
2
+ /**
3
+ * Subtree builder for `al-orc stations <action>`.
4
+ *
5
+ * These are the CANONICAL definitions from the orchestrator (contrast `al-control stations status`, which reads the bins).
6
+ */
7
+
8
+ import { safe, paginationOptions, localOptions } from '../_helpers.js';
9
+
10
+ import { listStationsHandler } from './list.js';
11
+ import { showStationHandler } from './show.js';
12
+ import { runStationHandler } from './run.js';
13
+ import { archiveStationHandler, unarchiveStationHandler } from './archive.js';
14
+ import { deleteStationHandler } from './delete.js';
15
+ import { editStationHandler } from './edit.js';
16
+ import { pullStationsHandler } from './pull.js';
17
+ import { pushStationsHandler } from './push.js';
18
+
19
+ export function buildStationsSubcommands(yargs) {
20
+ return yargs
21
+ .usage('$0 stations <action> [options]')
22
+ .command(
23
+ 'list',
24
+ 'List stations from the orchestrator',
25
+ (y) =>
26
+ paginationOptions(y)
27
+ .option('tag', { describe: 'Filter by tag name', type: 'string' })
28
+ .option('line', { describe: 'Filter by line code or ID', type: 'string' })
29
+ .option('include-archived', { describe: 'Include archived stations', type: 'boolean' }),
30
+ safe(listStationsHandler),
31
+ )
32
+ .command(
33
+ 'show <id>',
34
+ 'Show a station by ID or short_code',
35
+ (y) =>
36
+ localOptions(y.positional('id', { describe: 'Station ID or short_code', type: 'string' }))
37
+ .option('work-records', { describe: 'Include recent work records', type: 'boolean' })
38
+ .option('all', { describe: 'Include all linked entities', type: 'boolean' })
39
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' }),
40
+ safe(showStationHandler),
41
+ )
42
+ .command(
43
+ 'run <id>',
44
+ 'Trigger an orchestrator run (--scenario <name> + extra --key=value flags become per-run step overrides)',
45
+ (y) =>
46
+ localOptions(y.positional('id', { describe: 'Station ID or short_code', type: 'string' }))
47
+ .option('scenario', { describe: 'Apply a local station scenario (.orchestrator/scenarios/stations/<code>/)', type: 'string' })
48
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' })
49
+ // Any other --key=value is a step override, so unknown flags are the point here.
50
+ .strict(false),
51
+ safe(runStationHandler),
52
+ )
53
+ .command(
54
+ 'edit <id>',
55
+ 'Set a station short_code and/or add/remove tags',
56
+ (y) =>
57
+ localOptions(y.positional('id', { describe: 'Station ID or short_code', type: 'string' }))
58
+ .option('short-code', { describe: 'Set the short_code (empty string clears it)', type: 'string' })
59
+ .option('add-tag', { describe: 'Tag name to add (repeatable)', type: 'string', array: true })
60
+ .option('remove-tag', { describe: 'Tag name to remove (repeatable)', type: 'string', array: true }),
61
+ safe(editStationHandler),
62
+ )
63
+ .command(
64
+ 'pull [id]',
65
+ 'Pull station definitions to .orchestrator/stations/ (--all for every station)',
66
+ (y) =>
67
+ localOptions(y.positional('id', { describe: 'Station ID or short_code (omit with --all)', type: 'string' }))
68
+ .option('all', { describe: 'Pull every station', type: 'boolean' }),
69
+ safe(pullStationsHandler),
70
+ )
71
+ .command(
72
+ 'push [id]',
73
+ 'Push local station files to the orchestrator (create/update; --all for every file)',
74
+ (y) =>
75
+ localOptions(y.positional('id', { describe: 'Filename, station ID, or short_code (omit with --all)', type: 'string' }))
76
+ .option('all', { describe: 'Push every local station file', type: 'boolean' })
77
+ .option('force', { describe: 'On a 404 update, create remotely with the same id', type: 'boolean' }),
78
+ safe(pushStationsHandler),
79
+ )
80
+ .command(
81
+ 'archive <id>',
82
+ 'Archive a station (preserve history, hide from default list, block execution)',
83
+ (y) =>
84
+ localOptions(y.positional('id', { describe: 'Station ID', type: 'string' }))
85
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' }),
86
+ safe(archiveStationHandler),
87
+ )
88
+ .command(
89
+ 'unarchive <id>',
90
+ 'Unarchive a station',
91
+ (y) =>
92
+ localOptions(y.positional('id', { describe: 'Station ID', type: 'string' }))
93
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' }),
94
+ safe(unarchiveStationHandler),
95
+ )
96
+ .command(
97
+ 'delete <id>',
98
+ 'Permanently delete a station',
99
+ (y) =>
100
+ localOptions(y.positional('id', { describe: 'Station ID', type: 'string' }))
101
+ .option('cascade', { describe: 'Also delete its work records (otherwise refused while any exist)', type: 'boolean' }),
102
+ safe(deleteStationHandler),
103
+ )
104
+ .demandCommand(1, 'Specify an action: list, show, run, edit, pull, push, archive, unarchive, delete');
105
+ }
@@ -0,0 +1,38 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+ import { formatTable, formatPaginationHint } from '../utils/format.js';
4
+
5
+ /** `al-orc stations list` — canonical station definitions from the orchestrator. */
6
+ export async function listStationsHandler(argv) {
7
+ const { tag, line, json, includeArchived, page, limit } = argv || {};
8
+
9
+ const orc = clientFor();
10
+ const { data, page_context } = await orc.stations.list({ tag, line, include_archived: includeArchived, page, limit });
11
+ const stations = data || [];
12
+
13
+ if (json) {
14
+ console.log(JSON.stringify(stations, null, 2));
15
+ return;
16
+ }
17
+
18
+ if (stations.length === 0) {
19
+ console.log('No stations found');
20
+ return;
21
+ }
22
+
23
+ const rows = stations.map((s) => [
24
+ s.short_code || '—',
25
+ s.id,
26
+ s.name || '—',
27
+ String(s.steps ? s.steps.length : 0),
28
+ ...(includeArchived ? [s.archived || s.archived_at ? 'yes' : '—'] : []),
29
+ ]);
30
+ const headers = ['CODE', 'ID', 'NAME', 'STEPS', ...(includeArchived ? ['ARCHIVED'] : [])];
31
+
32
+ console.log(formatTable(headers, rows));
33
+ console.log('');
34
+ console.log(`Total: ${stations.length} stations${includeArchived ? ' (including archived)' : ''}`);
35
+
36
+ const hint = formatPaginationHint(page_context);
37
+ if (hint) console.log(hint);
38
+ }
@@ -0,0 +1,74 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+ import { saveStation, getStationsDir } from '../utils/station-files.js';
4
+ import { pullAllLines } from '../lines/pull.js';
5
+ import { getLinesDir } from '../utils/line-files.js';
6
+
7
+ /**
8
+ * Convert dependency IDs to short_codes using an id→short_code map.
9
+ * Values without a match pass through unchanged.
10
+ */
11
+ function dependenciesToShortCodes(dependencies, idToShortCode) {
12
+ if (!dependencies?.length) return dependencies;
13
+ return dependencies.map((dep) => idToShortCode.get(dep) || dep);
14
+ }
15
+
16
+ /** Normalize a fetched station for local storage: tags → names, deps → short_codes. */
17
+ function normalizeForLocal(station, idToShortCode) {
18
+ if (station.tags) station.tags = station.tags.map((t) => (typeof t === 'string' ? t : t.name));
19
+ station.dependencies = dependenciesToShortCodes(station.dependencies, idToShortCode);
20
+ return station;
21
+ }
22
+
23
+ /** `al-orc stations pull` — write orchestrator station definitions to `.orchestrator/stations/`. */
24
+ export async function pullStationsHandler(argv) {
25
+ const { id, all } = argv;
26
+
27
+ if (!id && !all) {
28
+ console.error('Usage: al-orc stations pull <id|short_code>');
29
+ console.error(' al-orc stations pull --all');
30
+ console.error('');
31
+ console.error('Run "al-orc stations list" to see available stations');
32
+ process.exit(1);
33
+ }
34
+
35
+ const orc = clientFor();
36
+
37
+ if (id) {
38
+ console.log(`Saving to: ${getStationsDir()}/`);
39
+ // Single station — also fetch the list for dependency resolution.
40
+ const [station, allStations] = await Promise.all([orc.stations.get(id), orc.stations.getAll()]);
41
+ if (!station) {
42
+ console.error(`Station not found: ${id}`);
43
+ process.exit(1);
44
+ }
45
+ const idToShortCode = new Map(allStations.filter((s) => s.short_code).map((s) => [s.id, s.short_code]));
46
+ const filepath = saveStation(normalizeForLocal(station, idToShortCode));
47
+ console.log(`Saved: ${filepath}`);
48
+ return;
49
+ }
50
+
51
+ // All stations — lines first, so every station's `line` code resolves locally
52
+ // (the factory session refuses to start on a station whose line file is missing).
53
+ console.log(`Saving to: ${getLinesDir()}/`);
54
+ const line_count = await pullAllLines(orc);
55
+ console.log(`Total: ${line_count} lines pulled`);
56
+ console.log('');
57
+ console.log(`Saving to: ${getStationsDir()}/`);
58
+
59
+ const stations = await orc.stations.getAll();
60
+ if (stations.length === 0) {
61
+ console.log('No stations found');
62
+ return;
63
+ }
64
+ const idToShortCode = new Map(stations.filter((s) => s.short_code).map((s) => [s.id, s.short_code]));
65
+
66
+ for (const summary of stations) {
67
+ // Fetch full details (the list may omit fields).
68
+ const full = await orc.stations.get(summary.id);
69
+ const filepath = saveStation(normalizeForLocal(full, idToShortCode));
70
+ console.log(`Saved: ${filepath}`);
71
+ }
72
+ console.log('');
73
+ console.log(`Total: ${stations.length} stations pulled`);
74
+ }
@@ -0,0 +1,213 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+ import {
4
+ loadStation,
5
+ listLocalStationIds,
6
+ listAllStationFiles,
7
+ loadStationByFilename,
8
+ finalizeNewStationFile,
9
+ findStationFile,
10
+ getStationsDir,
11
+ } from '../utils/station-files.js';
12
+ import { pushAllLines } from '../lines/push.js';
13
+ import { listAllLineFiles } from '../utils/line-files.js';
14
+
15
+ /**
16
+ * Build a short_code → ID map from remote stations (once per push session),
17
+ * falling back to local files if the fetch fails. Cached on `cache`.
18
+ */
19
+ async function getShortCodeMap(orc, cache) {
20
+ if (cache.map) return cache.map;
21
+ cache.map = new Map();
22
+ try {
23
+ for (const s of await orc.stations.getAll()) {
24
+ if (s.short_code) cache.map.set(s.short_code, s.id);
25
+ }
26
+ } catch {
27
+ for (const id of listLocalStationIds()) {
28
+ const station = loadStation(id);
29
+ if (station?.short_code) cache.map.set(station.short_code, station.id);
30
+ }
31
+ }
32
+ return cache.map;
33
+ }
34
+
35
+ /** Resolve short_codes in a dependencies array to database IDs (unknown values pass through). */
36
+ async function resolveDependencies(orc, cache, dependencies) {
37
+ if (!dependencies?.length) return dependencies;
38
+ const map = await getShortCodeMap(orc, cache);
39
+ const resolved = dependencies.map((dep) => map.get(dep) || dep);
40
+ const changed = dependencies.filter((dep, i) => dep !== resolved[i]);
41
+ if (changed.length > 0) {
42
+ console.log(` Dependencies resolved: ${changed.map((dep) => `${dep} -> ${map.get(dep)}`).join(', ')}`);
43
+ }
44
+ return resolved;
45
+ }
46
+
47
+ /** Map tag names → ids, creating any that don't exist. Returns { ids, created }. */
48
+ async function resolveTagNamesCreating(orc, names) {
49
+ const { data = [] } = await orc.tags.list();
50
+ const byName = new Map(data.map((t) => [t.name, t.id]));
51
+ const ids = [];
52
+ const created = [];
53
+ for (const name of names) {
54
+ let id = byName.get(name);
55
+ if (!id) {
56
+ const tag = await orc.tags.create({ name });
57
+ id = tag.id;
58
+ byName.set(name, id);
59
+ created.push(name);
60
+ }
61
+ ids.push(id);
62
+ }
63
+ return { ids, created };
64
+ }
65
+
66
+ /**
67
+ * Sync tags after push. `undefined` = leave untouched; `[]` = clear all;
68
+ * otherwise resolve (auto-creating missing) and replace.
69
+ */
70
+ async function syncTags(orc, stationId, tags) {
71
+ if (tags === undefined) return;
72
+ if (tags.length === 0) {
73
+ await orc.stations.setTags(stationId, []);
74
+ console.log(' Tags cleared');
75
+ return;
76
+ }
77
+ const { ids, created } = await resolveTagNamesCreating(orc, tags);
78
+ await orc.stations.setTags(stationId, ids);
79
+ if (created.length > 0) console.log(` Auto-created tags: ${created.join(', ')}`);
80
+ console.log(` Tags synced: ${tags.join(', ')}`);
81
+ }
82
+
83
+ /**
84
+ * Push one station file — create (no `id`) or update (has `id`). With `force`, a
85
+ * 404 on update falls back to create-with-same-id (promoting across environments).
86
+ */
87
+ async function pushByFilename(orc, cache, filename, { force = false } = {}) {
88
+ const station = loadStationByFilename(filename);
89
+ if (!station) {
90
+ console.error(`Station file not found: ${filename}`);
91
+ process.exit(1);
92
+ }
93
+
94
+ // `location` moved to the line (orchestrator D3); the API rejects it on a
95
+ // station. Drop it here so an un-repulled file still pushes, and say so.
96
+ if (station.location !== undefined) {
97
+ console.log(` Ignoring "location" in ${filename} — location now lives on line "${station.line}" (.orchestrator/lines/)`);
98
+ delete station.location;
99
+ }
100
+ if (!station.line) {
101
+ throw new Error(`${filename}: station has no "line". Every station is on a line; add "line": "<CODE>" and push the line file first.`);
102
+ }
103
+
104
+ if (!station.id) {
105
+ const { created_at, org, tags, ...createData } = station;
106
+ createData.dependencies = await resolveDependencies(orc, cache, createData.dependencies);
107
+ const created = await orc.stations.create(createData);
108
+ const newPath = finalizeNewStationFile(filename, created);
109
+ console.log(`Created: ${created.id} -> ${newPath}`);
110
+ await syncTags(orc, created.id, tags);
111
+ return;
112
+ }
113
+
114
+ const { id, created_at, org, tags, ...updateData } = station;
115
+ updateData.dependencies = await resolveDependencies(orc, cache, updateData.dependencies);
116
+
117
+ try {
118
+ await orc.stations.update(id, updateData);
119
+ console.log(`Updated: ${id}`);
120
+ await syncTags(orc, id, tags);
121
+ } catch (err) {
122
+ if (err.status !== 404) throw err;
123
+ if (!force) {
124
+ const label = station.short_code ? `station "${station.short_code}" (id: ${id})` : `station with id "${id}"`;
125
+ throw new Error(
126
+ `${label} does not exist in the orchestrator. Re-run with --force to create it remotely with this id ` +
127
+ `(use this when promoting a config from one environment to another).`,
128
+ );
129
+ }
130
+ console.log(` Not visible to this org (${id}), creating with --force...`);
131
+ let created;
132
+ try {
133
+ created = await orc.stations.create({ id, ...updateData });
134
+ } catch (createErr) {
135
+ if (createErr.status === 409) {
136
+ const label = station.short_code ? `station "${station.short_code}"` : 'station';
137
+ throw new Error(
138
+ `Cannot create ${label} with id "${id}" — that id is already used by another org in the orchestrator ` +
139
+ `(ids are globally unique across the multi-tenant database). Either change the id in the local file to a ` +
140
+ `different alphanumeric (1-24 chars), or remove the "id" field entirely to let the orchestrator generate ` +
141
+ `a fresh one — the file will be rewritten with the new id after push.`,
142
+ );
143
+ }
144
+ throw createErr;
145
+ }
146
+ const newPath = finalizeNewStationFile(filename, created);
147
+ console.log(`Created: ${created.id} -> ${newPath}`);
148
+ await syncTags(orc, created.id, tags);
149
+ }
150
+ }
151
+
152
+ /** `al-orc stations push` — create/update orchestrator stations from local files. */
153
+ export async function pushStationsHandler(argv) {
154
+ const { id, all, force } = argv;
155
+
156
+ if (!id && !all) {
157
+ console.error('Usage: al-orc stations push <filename> (create or update based on content)');
158
+ console.error(' al-orc stations push <id|short_code> (update by station ID or short_code)');
159
+ console.error(' al-orc stations push --all');
160
+ console.error('');
161
+ console.error('Run "al-orc stations list" to see available stations');
162
+ process.exit(1);
163
+ }
164
+
165
+ const orc = clientFor();
166
+ const cache = {};
167
+ console.log(`Reading from: ${getStationsDir()}/`);
168
+
169
+ if (id) {
170
+ const filename = id.endsWith('.json') ? id : `${id}.json`;
171
+ if (loadStationByFilename(filename)) {
172
+ await pushByFilename(orc, cache, filename, { force });
173
+ } else {
174
+ const filepath = findStationFile(id);
175
+ if (!filepath) {
176
+ console.error(`station not found locally: ${id}`);
177
+ console.error('Use a filename (e.g. AP1__document_intake.json) or a station ID/short_code');
178
+ process.exit(1);
179
+ }
180
+ await pushByFilename(orc, cache, filepath, { force });
181
+ }
182
+ return;
183
+ }
184
+
185
+ // Lines first: a new station's `line` code must already exist server-side.
186
+ if (listAllLineFiles().length > 0) {
187
+ const { created, updated } = await pushAllLines(orc);
188
+ console.log(`Lines: ${updated} updated, ${created} created`);
189
+ console.log('');
190
+ }
191
+
192
+ const allPaths = listAllStationFiles();
193
+ if (allPaths.length === 0) {
194
+ console.log('No local stations found');
195
+ console.log('Run "al-orc stations pull --all" first, or create a new station file');
196
+ return;
197
+ }
198
+
199
+ let updatedCount = 0;
200
+ let createdCount = 0;
201
+ for (const filepath of allPaths) {
202
+ const hadId = !!loadStationByFilename(filepath).id;
203
+ await pushByFilename(orc, cache, filepath, { force });
204
+ if (hadId) updatedCount++;
205
+ else createdCount++;
206
+ }
207
+
208
+ console.log('');
209
+ const parts = [];
210
+ if (updatedCount > 0) parts.push(`${updatedCount} updated`);
211
+ if (createdCount > 0) parts.push(`${createdCount} created`);
212
+ console.log(`Total: ${parts.join(', ')}`);
213
+ }
@@ -0,0 +1,94 @@
1
+ // @ts-check
2
+ import { clientFor } from '../_helpers.js';
3
+ import { loadStation, loadStationScenario, listStationScenarios } from '../utils/station-files.js';
4
+
5
+ // yargs auto-fills these on every argv; everything else is a candidate override.
6
+ const YARGS_KEYS = new Set(['_', '$0', 'help', 'version', 'h', 'v', 'profile', 'org']);
7
+ // Flags this command owns explicitly — not treated as step overrides.
8
+ const COMMAND_KEYS = new Set(['id', 'scenario', 'json']);
9
+
10
+ /**
11
+ * Build the merged step-override map: a local scenario file (if any) applied
12
+ * first, then direct CLI flags (which win on conflict). Any flag that isn't a
13
+ * reserved/known key becomes a per-run override, shallow-merged into every
14
+ * step's config server-side.
15
+ */
16
+ export function buildStepOverrides(argv, station) {
17
+ const overrides = {};
18
+ const fromScenario = [];
19
+ const fromCli = [];
20
+
21
+ if (argv.scenario) {
22
+ const shortCode = station?.short_code || station?.id || argv.id;
23
+ const scenario = loadStationScenario(shortCode, argv.scenario);
24
+ if (scenario === null) {
25
+ const available = listStationScenarios(shortCode);
26
+ const hint = available.length
27
+ ? `Available scenarios for ${shortCode}: ${available.join(', ')}`
28
+ : `No scenarios defined under .orchestrator/scenarios/stations/${shortCode}/`;
29
+ throw new Error(`Scenario not found: ${argv.scenario}\n${hint}`);
30
+ }
31
+ for (const [k, v] of Object.entries(scenario)) {
32
+ overrides[k] = v;
33
+ fromScenario.push(k);
34
+ }
35
+ }
36
+
37
+ // yargs adds a camelCase copy of every kebab-case flag (--max-files → maxFiles).
38
+ // Step configs are snake_case, so a kebab flag becomes max_files and its
39
+ // camelCase copy is dropped.
40
+ const camel_copies = new Set(
41
+ Object.keys(argv).filter((k) => k.includes('-')).map((k) => k.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase())),
42
+ );
43
+ for (const [k, v] of Object.entries(argv)) {
44
+ if (YARGS_KEYS.has(k) || COMMAND_KEYS.has(k) || camel_copies.has(k)) continue;
45
+ const key = k.replace(/-/g, '_');
46
+ overrides[key] = v;
47
+ fromCli.push(key);
48
+ }
49
+
50
+ return { overrides, fromScenario, fromCli };
51
+ }
52
+
53
+ function formatOverridesLine(overrides, fromScenario, fromCli, scenarioName) {
54
+ return Object.entries(overrides)
55
+ .map(([k, v]) => {
56
+ const sources = [];
57
+ if (fromScenario.includes(k)) sources.push(`scenario ${scenarioName}`);
58
+ if (fromCli.includes(k)) sources.push('CLI');
59
+ return `${k}=${JSON.stringify(v)} (${sources.join(' + ')})`;
60
+ })
61
+ .join(', ');
62
+ }
63
+
64
+ /** `al-orc stations run <id>` — trigger an orchestrator run; returns a work record id. */
65
+ export async function runStationHandler(argv) {
66
+ const { id, scenario, json } = argv;
67
+
68
+ // A local station file is only needed to resolve short_code for scenario lookup.
69
+ const station = loadStation(id);
70
+ if (!station && scenario) {
71
+ console.error(`Error: --scenario requires a local station definition for ${id}.`);
72
+ console.error(`Run "al-orc stations pull ${id}" first.`);
73
+ process.exit(1);
74
+ }
75
+
76
+ const { overrides, fromScenario, fromCli } = buildStepOverrides(argv, station);
77
+ const hasOverrides = Object.keys(overrides).length > 0;
78
+
79
+ const orc = clientFor();
80
+ const result = await orc.stations.run(id, { overrides: hasOverrides ? overrides : undefined });
81
+
82
+ if (json) {
83
+ console.log(JSON.stringify(result, null, 2));
84
+ return;
85
+ }
86
+
87
+ if (hasOverrides) {
88
+ console.log(`Overrides: ${formatOverridesLine(overrides, fromScenario, fromCli, scenario)}`);
89
+ }
90
+ console.log(`Triggered: ${id}`);
91
+ console.log(`Work Record: ${result?.work_record_id ?? '—'}`);
92
+ console.log('');
93
+ console.log(`Use \`al-orc work-records show ${result?.work_record_id ?? '<id>'}\` to check status.`);
94
+ }