runspec-node 0.8.0 → 0.9.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.
package/src/loader.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import { parse as parseTOML } from 'smol-toml';
3
- import type { RawConfig, RawSpec, ScriptSpec, ArgSpec, GroupSpec, JumpHostConfig } from './models';
3
+ import type { RawConfig, RawSpec, ScriptSpec, ArgSpec, GroupSpec, JumpHostConfig, LoggingConfig } from './models';
4
4
 
5
5
  export function loadRaw(configPath: string): RawSpec {
6
6
  const content = fs.readFileSync(configPath, 'utf-8');
@@ -30,6 +30,23 @@ function normaliseConfig(raw: Record<string, unknown>): RawConfig {
30
30
  lang: raw['lang'] as string | undefined,
31
31
  version: String(raw['version'] ?? '1'),
32
32
  jumpHosts,
33
+ logging: normaliseLogging(raw['logging'] as Record<string, unknown> | undefined),
34
+ };
35
+ }
36
+
37
+ const VALID_LOG_LEVELS = new Set(['debug', 'info', 'warning', 'error', 'critical']);
38
+
39
+ function normaliseLogging(raw: Record<string, unknown> | undefined): LoggingConfig | undefined {
40
+ if (raw === undefined) return undefined;
41
+ const level = String(raw['level'] ?? 'info').toLowerCase();
42
+ if (!VALID_LOG_LEVELS.has(level)) {
43
+ const sorted = [...VALID_LOG_LEVELS].sort().join(', ');
44
+ throw new Error(`✗ [config.logging] level must be one of: ${sorted}. Got: ${JSON.stringify(level)}`);
45
+ }
46
+ return {
47
+ level,
48
+ rotate: String(raw['rotate'] ?? 'midnight'),
49
+ keep: Number(raw['keep'] ?? 7),
33
50
  };
34
51
  }
35
52
 
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Configure a lightweight logger from [config.logging]. Zero new deps — uses
3
+ * only Node stdlib (fs, path, os). Call configureLogging() once from parse();
4
+ * runnables call getLogger(name) to obtain a named Logger.
5
+ */
6
+
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+ import * as os from 'os';
10
+ import type { LoggingConfig } from './models';
11
+
12
+ // ── internal state ────────────────────────────────────────────────────────────
13
+
14
+ let _configured = false;
15
+ const _loggers = new Map<string, Logger>();
16
+ const _handlers: Handler[] = [];
17
+
18
+ // ── level map ─────────────────────────────────────────────────────────────────
19
+
20
+ const LEVEL_NUM: Record<string, number> = {
21
+ debug: 10, info: 20, warning: 30, error: 40, critical: 50,
22
+ };
23
+
24
+ const LEVEL_LABEL: Record<number, string> = {
25
+ 10: 'DEBUG', 20: 'INFO', 30: 'WARNING', 40: 'ERROR', 50: 'CRITICAL',
26
+ };
27
+
28
+ // ── sensitive data redaction ──────────────────────────────────────────────────
29
+
30
+ const SENSITIVE: Array<[RegExp, string]> = [
31
+ [/(password|passwd|pwd)\s*[=:]\s*\S+/gi, '$1=[REDACTED]'],
32
+ [/(token|api[_-]?key|secret)\s*[=:]\s*\S+/gi, '$1=[REDACTED]'],
33
+ [/Authorization:\s*(Bearer|Basic)\s+\S+/gi, 'Authorization: $1 [REDACTED]'],
34
+ [/https?:\/\/[^:@\s]+:[^@\s]+@/g, 'https://[REDACTED]@'],
35
+ [/"(password|token|api_key|secret)"\s*:\s*"[^"]*"/gi, '"$1": "[REDACTED]"'],
36
+ [/(password|passwd|token)=([^&\s"]+)/gi, '$1=[REDACTED]'],
37
+ ];
38
+
39
+ function redact(msg: string): string {
40
+ try {
41
+ for (const [pattern, replacement] of SENSITIVE) {
42
+ msg = msg.replace(pattern, replacement);
43
+ }
44
+ } catch {
45
+ // never disrupt logging on redaction errors
46
+ }
47
+ return msg;
48
+ }
49
+
50
+ // ── log record & handler ──────────────────────────────────────────────────────
51
+
52
+ interface LogRecord {
53
+ ts: Date;
54
+ levelNum: number;
55
+ loggerName: string;
56
+ message: string;
57
+ error?: Error;
58
+ }
59
+
60
+ interface Handler {
61
+ level: number;
62
+ emit(record: LogRecord): void;
63
+ }
64
+
65
+ // ── Logger ────────────────────────────────────────────────────────────────────
66
+
67
+ export class Logger {
68
+ constructor(private readonly name: string) {}
69
+
70
+ debug(msg: string, error?: Error): void { this._emit(10, msg, error); }
71
+ info(msg: string, error?: Error): void { this._emit(20, msg, error); }
72
+ warning(msg: string, error?: Error): void { this._emit(30, msg, error); }
73
+ warn(msg: string, error?: Error): void { this._emit(30, msg, error); }
74
+ error(msg: string, error?: Error): void { this._emit(40, msg, error); }
75
+ critical(msg: string, error?: Error): void { this._emit(50, msg, error); }
76
+
77
+ private _emit(levelNum: number, message: string, error?: Error): void {
78
+ if (_handlers.length === 0) return;
79
+ const record: LogRecord = { ts: new Date(), levelNum, loggerName: this.name, message: redact(message), error };
80
+ for (const h of _handlers) {
81
+ if (levelNum >= h.level) h.emit(record);
82
+ }
83
+ }
84
+ }
85
+
86
+ export function getLogger(name: string): Logger {
87
+ let logger = _loggers.get(name);
88
+ if (!logger) {
89
+ logger = new Logger(name);
90
+ _loggers.set(name, logger);
91
+ }
92
+ return logger;
93
+ }
94
+
95
+ // ── formatters ────────────────────────────────────────────────────────────────
96
+
97
+ function formatJson(record: LogRecord): string {
98
+ const obj: Record<string, unknown> = {
99
+ ts: record.ts.toISOString(),
100
+ level: LEVEL_LABEL[record.levelNum] ?? String(record.levelNum),
101
+ logger: record.loggerName,
102
+ message: record.message,
103
+ };
104
+ if (record.error) obj['exc'] = record.error.stack ?? record.error.message;
105
+ return JSON.stringify(obj);
106
+ }
107
+
108
+ function formatHuman(record: LogRecord, showTracebacks: boolean): string {
109
+ const hh = String(record.ts.getHours()).padStart(2, '0');
110
+ const mm = String(record.ts.getMinutes()).padStart(2, '0');
111
+ const ss = String(record.ts.getSeconds()).padStart(2, '0');
112
+ const time = `${hh}:${mm}:${ss}`;
113
+ const label = (LEVEL_LABEL[record.levelNum] ?? String(record.levelNum)).padEnd(8);
114
+ let line = `${time} ${label} ${record.loggerName}: ${record.message}`;
115
+ if (showTracebacks && record.error) line += `\n${record.error.stack ?? record.error.message}`;
116
+ return line;
117
+ }
118
+
119
+ // ── console handler ───────────────────────────────────────────────────────────
120
+
121
+ class ConsoleHandler implements Handler {
122
+ constructor(public readonly level: number, private readonly showTracebacks: boolean) {}
123
+
124
+ emit(record: LogRecord): void {
125
+ try {
126
+ process.stderr.write(formatHuman(record, this.showTracebacks) + '\n');
127
+ } catch {
128
+ // never disrupt
129
+ }
130
+ }
131
+ }
132
+
133
+ // ── rotating file handlers ────────────────────────────────────────────────────
134
+
135
+ function doRotate(logPath: string, keep: number): void {
136
+ for (let i = keep; i >= 1; i--) {
137
+ const src = `${logPath}.${i}`;
138
+ if (i === keep) {
139
+ try { fs.unlinkSync(src); } catch { /* already gone */ }
140
+ } else {
141
+ try { fs.renameSync(src, `${logPath}.${i + 1}`); } catch { /* missing backup */ }
142
+ }
143
+ }
144
+ try { fs.renameSync(logPath, `${logPath}.1`); } catch { /* current file missing */ }
145
+ }
146
+
147
+ class SizeRotatingFileHandler implements Handler {
148
+ readonly level = 10; // always DEBUG
149
+
150
+ constructor(
151
+ private readonly logPath: string,
152
+ private readonly maxBytes: number,
153
+ private readonly keep: number,
154
+ ) {}
155
+
156
+ emit(record: LogRecord): void {
157
+ try {
158
+ this._rotateIfNeeded();
159
+ fs.appendFileSync(this.logPath, formatJson(record) + '\n', 'utf-8');
160
+ } catch {
161
+ // never disrupt
162
+ }
163
+ }
164
+
165
+ private _rotateIfNeeded(): void {
166
+ try {
167
+ if (fs.statSync(this.logPath).size < this.maxBytes) return;
168
+ } catch {
169
+ return; // file doesn't exist yet
170
+ }
171
+ doRotate(this.logPath, this.keep);
172
+ }
173
+ }
174
+
175
+ function _periodForDate(d: Date, when: 'daily' | 'midnight' | 'weekly'): string {
176
+ if (when === 'weekly') {
177
+ const tmp = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
178
+ const day = tmp.getUTCDay() || 7;
179
+ tmp.setUTCDate(tmp.getUTCDate() + 4 - day);
180
+ const yearStart = new Date(Date.UTC(tmp.getUTCFullYear(), 0, 1));
181
+ const week = Math.ceil(((tmp.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
182
+ return `${tmp.getUTCFullYear()}-W${week}`;
183
+ }
184
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
185
+ }
186
+
187
+ class TimedRotatingFileHandler implements Handler {
188
+ readonly level = 10;
189
+
190
+ constructor(
191
+ private readonly logPath: string,
192
+ private readonly when: 'daily' | 'midnight' | 'weekly',
193
+ private readonly keep: number,
194
+ ) {}
195
+
196
+ emit(record: LogRecord): void {
197
+ try {
198
+ this._rotateIfNeeded();
199
+ fs.appendFileSync(this.logPath, formatJson(record) + '\n', 'utf-8');
200
+ } catch {
201
+ // never disrupt
202
+ }
203
+ }
204
+
205
+ private _rotateIfNeeded(): void {
206
+ let filePeriod: string;
207
+ try {
208
+ filePeriod = _periodForDate(fs.statSync(this.logPath).mtime, this.when);
209
+ } catch {
210
+ return; // file doesn't exist yet
211
+ }
212
+ if (filePeriod === _periodForDate(new Date(), this.when)) return;
213
+ doRotate(this.logPath, this.keep);
214
+ }
215
+ }
216
+
217
+ // ── size/rotate parser ────────────────────────────────────────────────────────
218
+
219
+ const SIZE_RE = /^(\d+(?:\.\d+)?)\s*(KB|MB|GB)$/i;
220
+ const SIZE_MULT: Record<string, number> = { KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3 };
221
+ const TIMED_KEYS = new Set(['daily', 'midnight', 'weekly']);
222
+
223
+ function makeFileHandler(logPath: string, rotate: string, keep: number): Handler {
224
+ const sizeMatch = SIZE_RE.exec(rotate);
225
+ if (sizeMatch) {
226
+ const maxBytes = Math.round(parseFloat(sizeMatch[1]) * SIZE_MULT[sizeMatch[2].toUpperCase()]);
227
+ return new SizeRotatingFileHandler(logPath, maxBytes, keep);
228
+ }
229
+ const when = rotate.toLowerCase();
230
+ if (TIMED_KEYS.has(when)) {
231
+ return new TimedRotatingFileHandler(logPath, when as 'daily' | 'midnight' | 'weekly', keep);
232
+ }
233
+ throw new Error(
234
+ `✗ [config.logging] rotate ${JSON.stringify(rotate)} not recognised.\n` +
235
+ ` Valid: '10 MB', '100 KB', '1 GB', 'daily', 'midnight', 'weekly'`,
236
+ );
237
+ }
238
+
239
+ // ── log dir resolution ────────────────────────────────────────────────────────
240
+
241
+ function resolveLogDir(configPath: string): string {
242
+ const candidate = path.join(path.dirname(configPath), 'logs');
243
+ try {
244
+ fs.mkdirSync(candidate, { recursive: true });
245
+ const probe = path.join(candidate, '.wtest');
246
+ fs.writeFileSync(probe, '');
247
+ fs.unlinkSync(probe);
248
+ return candidate;
249
+ } catch {
250
+ const fallback = path.join(os.homedir(), 'logs');
251
+ fs.mkdirSync(fallback, { recursive: true });
252
+ return fallback;
253
+ }
254
+ }
255
+
256
+ // ── public: configureLogging ──────────────────────────────────────────────────
257
+
258
+ export interface ConfigureLoggingOptions {
259
+ logCfg: LoggingConfig | undefined;
260
+ agent: boolean;
261
+ runnableName: string;
262
+ configPath: string;
263
+ logLevelOverride?: string;
264
+ }
265
+
266
+ export function configureLogging(opts: ConfigureLoggingOptions): void {
267
+ if (!opts.logCfg || _configured) return;
268
+
269
+ const effectiveLevelName = opts.logLevelOverride ?? opts.logCfg.level;
270
+ const effectiveLevel = LEVEL_NUM[effectiveLevelName] ?? LEVEL_NUM['info'];
271
+
272
+ if (!opts.agent) {
273
+ _handlers.push(new ConsoleHandler(effectiveLevel, effectiveLevelName === 'debug'));
274
+ }
275
+
276
+ const logDir = resolveLogDir(opts.configPath);
277
+ const logPath = path.join(logDir, `${opts.runnableName}.log`);
278
+ _handlers.push(makeFileHandler(logPath, opts.logCfg.rotate, opts.logCfg.keep));
279
+
280
+ _configured = true;
281
+ }
282
+
283
+ // ── test helper ───────────────────────────────────────────────────────────────
284
+
285
+ export function _resetForTest(): void {
286
+ _configured = false;
287
+ _loggers.clear();
288
+ _handlers.length = 0;
289
+ }
290
+
291
+ export { _periodForDate };
package/src/models.ts CHANGED
@@ -8,11 +8,18 @@ export interface JumpHostConfig {
8
8
  sshOptions?: string[];
9
9
  }
10
10
 
11
+ export interface LoggingConfig {
12
+ level: string;
13
+ rotate: string;
14
+ keep: number;
15
+ }
16
+
11
17
  export interface RawConfig {
12
18
  autonomyDefault: string;
13
19
  lang?: string;
14
20
  version: string;
15
21
  jumpHosts: Record<string, JumpHostConfig>;
22
+ logging?: LoggingConfig;
16
23
  }
17
24
 
18
25
  export interface ArgSpec {
@@ -71,4 +78,5 @@ export interface ParsedArgs {
71
78
  readonly __runspec_spec__: ScriptSpec;
72
79
  readonly runspec_command: string | undefined;
73
80
  readonly runspec_command_path: string[];
81
+ readonly runspec_prefix: string;
74
82
  }
package/src/parser.ts CHANGED
@@ -5,6 +5,7 @@ import { inferScript, effectiveAutonomy } from './inference';
5
5
  import { coerce } from './types';
6
6
  import { validateArgs, validateGroups, raiseIfErrors } from './validator';
7
7
  import { RunSpecError } from './errors';
8
+ import { configureLogging } from './logging_setup';
8
9
  import type { ParsedArgs, ScriptSpec, ArgSpec } from './models';
9
10
 
10
11
  export interface ParseOptions {
@@ -30,7 +31,27 @@ export function parse(opts: ParseOptions = {}): ParsedArgs {
30
31
  throw new RunSpecError(`✗ Runnable '${name}' not found.\n Available: ${available}\n Config: ${configPath}`);
31
32
  }
32
33
 
33
- const rawScript = inferScript(raw.runnables[name], config.autonomyDefault);
34
+ let rawScript = inferScript(raw.runnables[name], config.autonomyDefault);
35
+
36
+ // Auto-inject --log-level when [config.logging] is present
37
+ if (config.logging && !('log-level' in rawScript.args)) {
38
+ rawScript = {
39
+ ...rawScript,
40
+ args: {
41
+ ...rawScript.args,
42
+ 'log-level': {
43
+ name: 'log-level',
44
+ type: 'choice',
45
+ options: ['debug', 'info', 'warning', 'error', 'critical'],
46
+ default: config.logging.level,
47
+ required: false,
48
+ description: 'Override the console log level for this invocation.',
49
+ multiple: false,
50
+ env: 'RUNSPEC_LOG_LEVEL',
51
+ },
52
+ },
53
+ };
54
+ }
34
55
 
35
56
  let argv = argvOverride ?? process.argv.slice(2);
36
57
  let activeScript = rawScript;
@@ -65,6 +86,22 @@ export function parse(opts: ParseOptions = {}): ParsedArgs {
65
86
 
66
87
  const agent = ['1', 'true', 'yes'].includes((process.env['RUNSPEC_AGENT'] ?? '').toLowerCase());
67
88
 
89
+ const logLevelOverride = config.logging
90
+ ? (coercedValues['log_level'] as string | undefined) ?? undefined
91
+ : undefined;
92
+
93
+ try {
94
+ configureLogging({
95
+ logCfg: config.logging,
96
+ agent,
97
+ runnableName: name,
98
+ configPath,
99
+ logLevelOverride,
100
+ });
101
+ } catch (e) {
102
+ throw new RunSpecError((e as Error).message);
103
+ }
104
+
68
105
  return {
69
106
  ...coercedValues,
70
107
  __runspec_agent__: agent,
@@ -75,6 +112,7 @@ export function parse(opts: ParseOptions = {}): ParsedArgs {
75
112
  __runspec_spec__: activeScript,
76
113
  get runspec_command() { return commandPath.length > 0 ? commandPath[commandPath.length - 1] : undefined; },
77
114
  get runspec_command_path() { return commandPath; },
115
+ get runspec_prefix() { return path.dirname(configPath); },
78
116
  } as ParsedArgs;
79
117
  }
80
118
 
@@ -132,3 +132,56 @@ test('autonomy-default falls back to confirm', () => {
132
132
  const raw = loadRaw(file);
133
133
  expect(raw.config.autonomyDefault).toBe('confirm');
134
134
  });
135
+
136
+ // ── [config.logging] ──────────────────────────────────────────────────────────
137
+
138
+ test('normalises [config.logging] with defaults', () => {
139
+ const dir = tmpDir();
140
+ const file = path.join(dir, 'runspec.toml');
141
+ fs.writeFileSync(file, `
142
+ [config.logging]
143
+ level = "info"
144
+
145
+ [greet]
146
+ description = "hi"
147
+ `);
148
+ const raw = loadRaw(file);
149
+ expect(raw.config.logging).toEqual({ level: 'info', rotate: 'midnight', keep: 7 });
150
+ });
151
+
152
+ test('normalises [config.logging] all fields', () => {
153
+ const dir = tmpDir();
154
+ const file = path.join(dir, 'runspec.toml');
155
+ fs.writeFileSync(file, `
156
+ [config.logging]
157
+ level = "debug"
158
+ rotate = "10 MB"
159
+ keep = 3
160
+
161
+ [greet]
162
+ description = "hi"
163
+ `);
164
+ const raw = loadRaw(file);
165
+ expect(raw.config.logging).toEqual({ level: 'debug', rotate: '10 MB', keep: 3 });
166
+ });
167
+
168
+ test('logging is undefined when section absent', () => {
169
+ const dir = tmpDir();
170
+ const file = path.join(dir, 'runspec.toml');
171
+ fs.writeFileSync(file, `[greet]\ndescription = "hi"\n`);
172
+ const raw = loadRaw(file);
173
+ expect(raw.config.logging).toBeUndefined();
174
+ });
175
+
176
+ test('throws on invalid log level', () => {
177
+ const dir = tmpDir();
178
+ const file = path.join(dir, 'runspec.toml');
179
+ fs.writeFileSync(file, `
180
+ [config.logging]
181
+ level = "verbose"
182
+
183
+ [greet]
184
+ description = "hi"
185
+ `);
186
+ expect(() => loadRaw(file)).toThrow('[config.logging]');
187
+ });