@assemblyline/al-orc 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +56 -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 +67 -0
  8. package/src/cli/config/add.js +10 -0
  9. package/src/cli/config/current.js +20 -0
  10. package/src/cli/config/index.js +63 -0
  11. package/src/cli/config/list.js +22 -0
  12. package/src/cli/config/remove.js +6 -0
  13. package/src/cli/config/use.js +6 -0
  14. package/src/cli/config-store.js +127 -0
  15. package/src/cli/factory-sessions/index.js +35 -0
  16. package/src/cli/factory-sessions/list.js +93 -0
  17. package/src/cli/factory-sessions/show.js +83 -0
  18. package/src/cli/index.js +61 -0
  19. package/src/cli/lines/index.js +53 -0
  20. package/src/cli/lines/list.js +36 -0
  21. package/src/cli/lines/pull.js +46 -0
  22. package/src/cli/lines/push.js +82 -0
  23. package/src/cli/lines/show.js +36 -0
  24. package/src/cli/shared/edit-tags.js +43 -0
  25. package/src/cli/stations/archive.js +24 -0
  26. package/src/cli/stations/delete.js +8 -0
  27. package/src/cli/stations/edit.js +30 -0
  28. package/src/cli/stations/index.js +104 -0
  29. package/src/cli/stations/list.js +34 -0
  30. package/src/cli/stations/pull.js +73 -0
  31. package/src/cli/stations/push.js +212 -0
  32. package/src/cli/stations/run.js +87 -0
  33. package/src/cli/stations/show.js +74 -0
  34. package/src/cli/status.js +23 -0
  35. package/src/cli/supporting-docs/index.js +21 -0
  36. package/src/cli/supporting-docs/show.js +49 -0
  37. package/src/cli/tags/create.js +21 -0
  38. package/src/cli/tags/delete.js +8 -0
  39. package/src/cli/tags/edit.js +27 -0
  40. package/src/cli/tags/index.js +49 -0
  41. package/src/cli/tags/list.js +24 -0
  42. package/src/cli/utils/format.js +206 -0
  43. package/src/cli/utils/line-files.js +84 -0
  44. package/src/cli/utils/station-files.js +151 -0
  45. package/src/cli/utils/station-labels.js +48 -0
  46. package/src/cli/work-records/cancel.js +24 -0
  47. package/src/cli/work-records/edit.js +22 -0
  48. package/src/cli/work-records/index.js +59 -0
  49. package/src/cli/work-records/list.js +48 -0
  50. package/src/cli/work-records/show.js +103 -0
  51. package/src/http.js +255 -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 +77 -0
  59. package/src/types/api/Line.types.js +22 -0
  60. package/src/types/api/Station.types.js +34 -0
  61. package/src/types/api/SupportingDoc.types.js +14 -0
  62. package/src/types/api/Tag.types.js +10 -0
  63. package/src/types/api/WorkRecord.types.js +27 -0
  64. package/src/types/general/Credentials.types.js +18 -0
  65. package/src/types/general/Transport.types.js +21 -0
  66. package/src/types/general/index.js +8 -0
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Local station + station-scenario file cache — the bridge between the
3
+ * orchestrator (remote truth) and the working tree.
4
+ *
5
+ * Station files live in: .orchestrator/stations/<short_code>__<name>.json
6
+ * Station scenarios in: .orchestrator/scenarios/stations/<short_code>/<name>.json
7
+ *
8
+ * Line membership is encoded by the `line` field inside each JSON, not by folder
9
+ * hierarchy. (Ported from cli-fob for the al-orc pull/push/run bridges; the
10
+ * step-scenario + local run-state helpers stay in al-factory.)
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ const STATIONS_DIR = '.orchestrator/stations';
17
+ const SCENARIOS_DIR = '.orchestrator/scenarios';
18
+
19
+ /** All station JSON file paths under `.orchestrator/stations/`. */
20
+ function getAllStationFilePaths() {
21
+ if (!fs.existsSync(STATIONS_DIR)) return [];
22
+ const paths = [];
23
+ for (const f of fs.readdirSync(STATIONS_DIR)) {
24
+ if (f.endsWith('.json')) paths.push(path.join(STATIONS_DIR, f));
25
+ }
26
+ return paths;
27
+ }
28
+
29
+ /** "Update Rules" → "update_rules" */
30
+ function nameToSnakeCase(name) {
31
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
32
+ }
33
+
34
+ /** Filename: short_code (or id) prefix + snake_case name. */
35
+ function buildFilename(station) {
36
+ const snakeName = nameToSnakeCase(station.name || 'unnamed');
37
+ const prefix = station.short_code || station.id;
38
+ return `${prefix}__${snakeName}.json`;
39
+ }
40
+
41
+ /** Find a station file by ID or short_code (filename prefix, then JSON `id`). */
42
+ export function findStationFile(identifier) {
43
+ const all = getAllStationFilePaths();
44
+ for (const p of all) {
45
+ if (path.basename(p).startsWith(`${identifier}__`)) return p;
46
+ }
47
+ for (const p of all) {
48
+ try {
49
+ if (JSON.parse(fs.readFileSync(p, 'utf8')).id === identifier) return p;
50
+ } catch {
51
+ // skip malformed files
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /** Save a station locally, removing any existing file(s) for it first. */
58
+ export function saveStation(station) {
59
+ const toRemove = new Set();
60
+ const existingById = findStationFile(station.id);
61
+ if (existingById) toRemove.add(existingById);
62
+ if (station.short_code) {
63
+ const existingByCode = findStationFile(station.short_code);
64
+ if (existingByCode) toRemove.add(existingByCode);
65
+ }
66
+ for (const f of toRemove) fs.unlinkSync(f);
67
+
68
+ if (!fs.existsSync(STATIONS_DIR)) fs.mkdirSync(STATIONS_DIR, { recursive: true });
69
+
70
+ const filepath = path.join(STATIONS_DIR, buildFilename(station));
71
+ fs.writeFileSync(filepath, JSON.stringify(station, null, 2));
72
+ return filepath;
73
+ }
74
+
75
+ /** Load a station file by ID or short_code. */
76
+ export function loadStation(identifier) {
77
+ const filepath = findStationFile(identifier);
78
+ return filepath ? JSON.parse(fs.readFileSync(filepath, 'utf8')) : null;
79
+ }
80
+
81
+ /** All station JSON file paths. */
82
+ export function listAllStationFiles() {
83
+ return getAllStationFilePaths();
84
+ }
85
+
86
+ /** IDs from every local station file that carries one. */
87
+ export function listLocalStationIds() {
88
+ const ids = [];
89
+ for (const p of getAllStationFilePaths()) {
90
+ try {
91
+ const content = JSON.parse(fs.readFileSync(p, 'utf8'));
92
+ if (content.id) ids.push(content.id);
93
+ } catch {
94
+ // skip malformed files
95
+ }
96
+ }
97
+ return ids;
98
+ }
99
+
100
+ /** Load a station from a bare filename or a relative path. */
101
+ export function loadStationByFilename(arg) {
102
+ if (arg.includes(path.sep) || arg.includes('/')) {
103
+ return fs.existsSync(arg) ? JSON.parse(fs.readFileSync(arg, 'utf8')) : null;
104
+ }
105
+ for (const filepath of getAllStationFilePaths()) {
106
+ if (path.basename(filepath) === arg) return JSON.parse(fs.readFileSync(filepath, 'utf8'));
107
+ }
108
+ return null;
109
+ }
110
+
111
+ /** Write the server-assigned id into a new station file and rename to standard form. */
112
+ export function finalizeNewStationFile(originalArg, station) {
113
+ let originalPath;
114
+ if (originalArg.includes(path.sep) || originalArg.includes('/')) {
115
+ originalPath = originalArg;
116
+ } else {
117
+ originalPath =
118
+ getAllStationFilePaths().find((p) => path.basename(p) === originalArg) ||
119
+ path.join(STATIONS_DIR, originalArg);
120
+ }
121
+ if (fs.existsSync(originalPath)) fs.unlinkSync(originalPath);
122
+ if (!fs.existsSync(STATIONS_DIR)) fs.mkdirSync(STATIONS_DIR, { recursive: true });
123
+
124
+ const newPath = path.join(STATIONS_DIR, buildFilename(station));
125
+ fs.writeFileSync(newPath, JSON.stringify(station, null, 2));
126
+ return newPath;
127
+ }
128
+
129
+ /** Path of the local stations directory (shown in pull/push output). */
130
+ export function getStationsDir() {
131
+ return STATIONS_DIR;
132
+ }
133
+
134
+ // --- Station scenarios (flat key→value override maps applied to a whole run) ---
135
+
136
+ function getScenarioDirForStation(stationShortCode) {
137
+ return path.join(SCENARIOS_DIR, 'stations', stationShortCode);
138
+ }
139
+
140
+ /** Scenario names available for a station (without .json). */
141
+ export function listStationScenarios(stationShortCode) {
142
+ const dir = getScenarioDirForStation(stationShortCode);
143
+ if (!fs.existsSync(dir)) return [];
144
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => f.replace('.json', ''));
145
+ }
146
+
147
+ /** Load a station scenario (flat key→value map), or null. */
148
+ export function loadStationScenario(stationShortCode, scenarioName) {
149
+ const filepath = path.join(getScenarioDirForStation(stationShortCode), `${scenarioName}.json`);
150
+ return fs.existsSync(filepath) ? JSON.parse(fs.readFileSync(filepath, 'utf8')) : null;
151
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Station id → short_code labelling for commands that only get an id back.
3
+ *
4
+ * Work records carry the station as `process` — a bare id like `2XqwQGJuATJE`,
5
+ * which nobody recognises. The short_code (`EM3`) is only on the station record,
6
+ * so a lookup is needed. `stations.list()` returns every station with its
7
+ * short_code in ONE request, so the whole map costs a single call regardless of
8
+ * how many rows are being labelled — no per-row fetch.
9
+ *
10
+ * The map is deliberately not cached across calls: a CLI process is short-lived
11
+ * and each command builds it at most once.
12
+ */
13
+
14
+ /**
15
+ * Build an id → short_code map from every station.
16
+ *
17
+ * Resolution is best-effort: if the stations call fails (permissions, transport,
18
+ * an older orchestrator), an empty map comes back and callers fall through to
19
+ * printing the raw id. Losing the nicer label must never sink a `work-records
20
+ * list` that would otherwise have worked.
21
+ *
22
+ * @param {any} orc A credential-bound alOrc client.
23
+ * @returns {Promise<Map<string, string>>}
24
+ */
25
+ export async function buildStationLabelMap(orc) {
26
+ try {
27
+ // include_archived: a work record outlives the station being archived, and
28
+ // its rows should still resolve to a code rather than regressing to an id.
29
+ const stations = await orc.stations.getAll({ include_archived: true });
30
+ return new Map((stations || []).filter((s) => s?.id && s.short_code).map((s) => [s.id, s.short_code]));
31
+ } catch {
32
+ return new Map();
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Label a station id for display: its short_code if known, else the raw id
38
+ * (still useful — it's what `al-orc stations show <id>` takes), else the
39
+ * em-dash placeholder the other formatters use for absent values.
40
+ *
41
+ * @param {string|undefined|null} id
42
+ * @param {Map<string, string>} labels
43
+ * @returns {string}
44
+ */
45
+ export function stationLabel(id, labels) {
46
+ if (!id) return '—';
47
+ return labels.get(id) || id;
48
+ }
@@ -0,0 +1,24 @@
1
+ import { clientFor } from '../_helpers.js';
2
+ import { buildStationLabelMap, stationLabel } from '../utils/station-labels.js';
3
+
4
+ /** `al-orc work-records cancel <id>` — cancel a running or pending work record. */
5
+ export async function cancelWorkRecordHandler(argv) {
6
+ const { id, json } = argv;
7
+
8
+ const orc = clientFor();
9
+ const record = await orc.workRecords.cancel(id);
10
+
11
+ if (json) {
12
+ console.log(JSON.stringify(record, null, 2));
13
+ return;
14
+ }
15
+
16
+ console.log(`Cancelled work record ${record?.id ?? id}`);
17
+ if (record?.status) console.log(`Status: ${record.status}`);
18
+ if (record?.station) {
19
+ // `station` is the station id; show its short_code when it resolves —
20
+ // matches `work-records list` / `show` in this CLI.
21
+ const labels = await buildStationLabelMap(orc);
22
+ console.log(`Station: ${stationLabel(record.station, labels)}`);
23
+ }
24
+ }
@@ -0,0 +1,22 @@
1
+ import { clientFor } from '../_helpers.js';
2
+ import { editEntityTags } from '../shared/edit-tags.js';
3
+
4
+ /** `al-orc work-records edit <id>` — add/remove tags on a work record. */
5
+ export async function editWorkRecordHandler(argv) {
6
+ const { id, addTag, removeTag } = argv;
7
+
8
+ const addTags = addTag ? [].concat(addTag) : [];
9
+ const removeTags = removeTag ? [].concat(removeTag) : [];
10
+
11
+ if (addTags.length === 0 && removeTags.length === 0) {
12
+ console.error('Usage: al-orc work-records edit <id> --add-tag <name> [--remove-tag <name>]');
13
+ console.error('At least one --add-tag or --remove-tag is required');
14
+ process.exit(1);
15
+ }
16
+
17
+ console.log(`Work record: ${id}`);
18
+ const orc = clientFor();
19
+ await editEntityTags(orc.workRecords, orc.tags, id, addTags, removeTags);
20
+ console.log('');
21
+ console.log('Tags updated');
22
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Subtree builder for `al-orc work-records <action>`.
3
+ */
4
+
5
+ import { safe, localOptions } from '../_helpers.js';
6
+
7
+ import { listWorkRecordsHandler } from './list.js';
8
+ import { showWorkRecordHandler } from './show.js';
9
+ import { cancelWorkRecordHandler } from './cancel.js';
10
+ import { editWorkRecordHandler } from './edit.js';
11
+
12
+ export function buildWorkRecordsSubcommands(yargs) {
13
+ return yargs
14
+ .usage('$0 work-records <action> [options]')
15
+ .command(
16
+ 'list',
17
+ 'List work records',
18
+ (y) =>
19
+ localOptions(y)
20
+ .option('limit', { describe: 'Max records', type: 'number' })
21
+ .option('status', { describe: 'Filter by status', type: 'string' })
22
+ .option('station', { describe: 'Filter by station ID or short_code (e.g. EM0)', type: 'string' })
23
+ .option('line', { describe: 'Filter by line — every station on it (e.g. VM)', type: 'string' })
24
+ .option('tag', { describe: 'Filter by tag name', type: 'string' })
25
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' }),
26
+ safe(listWorkRecordsHandler),
27
+ )
28
+ .command(
29
+ 'show <id>',
30
+ 'Show a work record (--report/--steps/--supporting-docs/--activity/--all for detail)',
31
+ (y) =>
32
+ localOptions(y.positional('id', { describe: 'Work record ID', type: 'string' }))
33
+ .option('report', { describe: 'Include the report', type: 'boolean' })
34
+ .option('steps', { describe: 'Include step outputs', type: 'boolean' })
35
+ .option('supporting-docs', { describe: 'Include supporting documents', type: 'boolean' })
36
+ .option('activity', { describe: 'Include activity events', type: 'boolean' })
37
+ .option('all', { describe: 'Include every detail section', type: 'boolean' })
38
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' }),
39
+ safe(showWorkRecordHandler),
40
+ )
41
+ .command(
42
+ 'cancel <id>',
43
+ 'Cancel a running or pending work record',
44
+ (y) =>
45
+ localOptions(y.positional('id', { describe: 'Work record ID', type: 'string' }))
46
+ .option('json', { describe: 'Output raw JSON', type: 'boolean' }),
47
+ safe(cancelWorkRecordHandler),
48
+ )
49
+ .command(
50
+ 'edit <id>',
51
+ 'Add or remove tags on a work record',
52
+ (y) =>
53
+ localOptions(y.positional('id', { describe: 'Work record ID', type: 'string' }))
54
+ .option('add-tag', { describe: 'Tag name to add (repeatable)', type: 'string', array: true })
55
+ .option('remove-tag', { describe: 'Tag name to remove (repeatable)', type: 'string', array: true }),
56
+ safe(editWorkRecordHandler),
57
+ )
58
+ .demandCommand(1, 'Specify an action: list, show, cancel, edit');
59
+ }
@@ -0,0 +1,48 @@
1
+ import { clientFor } from '../_helpers.js';
2
+ import { formatTable, formatDate, formatDuration, localTzLabel, formatPaginationHint, truncate } from '../utils/format.js';
3
+ import { buildStationLabelMap, stationLabel } from '../utils/station-labels.js';
4
+
5
+ /** `al-orc work-records list` — work records from the orchestrator, filterable. */
6
+ export async function listWorkRecordsHandler(argv) {
7
+ const { limit, status, station, line, tag, json } = argv;
8
+
9
+ const orc = clientFor();
10
+ const { data, page_context } = await orc.workRecords.list({ limit, status, station, line, tag });
11
+ const records = data || [];
12
+
13
+ if (json) {
14
+ console.log(JSON.stringify(records, null, 2));
15
+ return;
16
+ }
17
+
18
+ if (records.length === 0) {
19
+ console.log('No work records found');
20
+ return;
21
+ }
22
+
23
+ // STATION shows the short_code (`EM3`), not the raw station id the API
24
+ // returns. One stations.getAll() builds the whole map, so the label costs a
25
+ // single request for the table rather than one per row. Unresolved ids print
26
+ // as-is — still what `al-orc stations show <id>` takes.
27
+ const labels = await buildStationLabelMap(orc);
28
+
29
+ const rows = records.map((r) => [
30
+ r.id,
31
+ stationLabel(r.station, labels),
32
+ r.status || '—',
33
+ formatDate(r.created_at),
34
+ formatDuration(r.started_at, r.completed_at),
35
+ r.performed_by || '—',
36
+ truncate(r.error, 40),
37
+ ]);
38
+
39
+ console.log(formatTable(
40
+ ['ID', 'STATION', 'STATUS', `CREATED (${localTzLabel()})`, 'TOOK', 'BY', 'ERROR'],
41
+ rows,
42
+ ));
43
+ console.log('');
44
+ console.log(`Total: ${records.length} records`);
45
+
46
+ const hint = formatPaginationHint(page_context);
47
+ if (hint) console.log(hint);
48
+ }
@@ -0,0 +1,103 @@
1
+ import { clientFor } from '../_helpers.js';
2
+ import { formatHeader, formatField, formatTable, formatSection, formatDate, formatDuration, localTzLabel } from '../utils/format.js';
3
+ import { buildStationLabelMap, stationLabel } from '../utils/station-labels.js';
4
+
5
+ /** `al-orc work-records show <id>` — one work record, with optional detail sections. */
6
+ export async function showWorkRecordHandler(argv) {
7
+ const { id, report, steps, supportingDocs, activity, all, json } = argv;
8
+
9
+ const orc = clientFor();
10
+
11
+ const include = [];
12
+ if (report || all) include.push('report');
13
+ if (steps || all) include.push('step_outputs');
14
+ if (supportingDocs || all) include.push('supporting_docs');
15
+
16
+ const record = await orc.workRecords.get(id, { include: include.length ? include : undefined });
17
+
18
+ if (json) {
19
+ if (activity || all) {
20
+ record.activity = await orc.workRecords.activity(id).catch(() => []);
21
+ }
22
+ console.log(JSON.stringify(record, null, 2));
23
+ return;
24
+ }
25
+
26
+ if (!record) {
27
+ console.error(`Work record not found: ${id}`);
28
+ process.exit(1);
29
+ }
30
+
31
+ console.log(formatHeader('Work Record', record.id, record.status));
32
+ console.log('');
33
+ const lw = 14;
34
+ // `station` is the station id; show its short_code when it resolves.
35
+ const labels = await buildStationLabelMap(orc);
36
+ console.log(formatField('Station', stationLabel(record.station, labels), lw));
37
+ console.log(formatField('Status', record.status, lw));
38
+ console.log(formatField('Duration', formatDuration(record.started_at, record.completed_at), lw));
39
+ console.log(formatField('Created', formatDate(record.created_at), lw));
40
+ if (record.started_at) console.log(formatField('Started', formatDate(record.started_at), lw));
41
+ if (record.completed_at) console.log(formatField('Completed', formatDate(record.completed_at), lw));
42
+
43
+ const tags = await orc.workRecords.getTags(id).catch(() => []);
44
+ console.log(formatField('Tags', tags.map((t) => t.name).join(', ') || '—', lw));
45
+
46
+ if (report || all) {
47
+ console.log(formatSection('Report'));
48
+ console.log(record.report ? (typeof record.report === 'string' ? record.report : JSON.stringify(record.report, null, 2)) : 'No report available.');
49
+ }
50
+
51
+ if (steps || all) {
52
+ console.log(formatSection('Step Outputs'));
53
+ const outputs = record.step_outputs || {};
54
+ const slugs = Object.keys(outputs);
55
+ if (slugs.length) {
56
+ for (const slug of slugs) {
57
+ console.log(`\n[${slug}]`);
58
+ const output = outputs[slug];
59
+ console.log(typeof output === 'object' ? JSON.stringify(output, null, 2) : String(output));
60
+ }
61
+ } else {
62
+ console.log('No step outputs.');
63
+ }
64
+ }
65
+
66
+ if (supportingDocs || all) {
67
+ const docs = record.supporting_docs || [];
68
+ console.log(formatSection(`Supporting Documents (${docs.length})`));
69
+ if (docs.length) {
70
+ const rows = docs.map((d) => [d.id, d.type || '—', d.title || '—', formatDate(d.created_at)]);
71
+ console.log(formatTable(['ID', 'TYPE', 'TITLE', `CREATED (${localTzLabel()})`], rows));
72
+ console.log('\nUse `al-orc supporting-docs show <id>` to view content.');
73
+ } else {
74
+ console.log('No supporting documents.');
75
+ }
76
+ }
77
+
78
+ if (activity || all) {
79
+ const events = await orc.workRecords.activity(id).catch(() => null);
80
+ console.log(formatSection(`Activity (${events?.length ?? 0})`));
81
+ if (events?.length) {
82
+ // Factory session attribution rides in `properties` on the claim/complete/fail
83
+ // events. It was being fetched and dropped, which is why diagnosing a
84
+ // bad factory session meant hand-querying the API. `al-orc factory-sessions show
85
+ // <session>` takes it from here.
86
+ const rows = events.map((e) => [
87
+ formatDate(e.created_at),
88
+ e.event || e.type || '—',
89
+ e.properties?.factory_name || '—',
90
+ e.properties?.factory_session_id || '—',
91
+ ]);
92
+ console.log(formatTable([`TIME (${localTzLabel()})`, 'EVENT', 'FACTORY', 'SESSION'], rows));
93
+ } else if (events) {
94
+ console.log('No activity events.');
95
+ } else {
96
+ console.log('Could not load activity.');
97
+ }
98
+ }
99
+
100
+ if (!report && !steps && !supportingDocs && !activity && !all) {
101
+ console.log('\nUse --report, --steps, --supporting-docs, --activity, or --all for details.');
102
+ }
103
+ }