runspec-node 0.24.0 → 0.26.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/cli.ts CHANGED
@@ -2,6 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import * as readline from 'readline';
4
4
  import { findConfig } from './finder';
5
+ import * as logs from './logs';
5
6
  import { loadRaw } from './loader';
6
7
  import { inferScript } from './inference';
7
8
  import { parse } from './parser';
@@ -33,6 +34,7 @@ export function main(): void {
33
34
  init: cmdInit,
34
35
  local: cmdLocal,
35
36
  bin: cmdBin,
37
+ logs: cmdLogs,
36
38
  jump: cmdJump,
37
39
  serve: cmdServe,
38
40
  };
@@ -124,7 +126,7 @@ function cmdBin(_args: string[]): void {
124
126
  const projectRoot = path.dirname(configPath);
125
127
  const result = scaffoldBin(projectRoot);
126
128
 
127
- console.log(`Wrote ${result.written.length} shim(s) to ${path.join(projectRoot, 'bin')}/:\n`);
129
+ console.log(`Wrote ${result.written.length} shim(s) (POSIX + .cmd) to ${path.join(projectRoot, 'bin')}/:\n`);
128
130
  for (const w of result.written) console.log(` ✓ bin/${w.name}${w.target ? ` → ${w.target}` : ''}`);
129
131
  if (result.warnings.length) {
130
132
  console.log('\nIssues:\n');
@@ -221,15 +223,88 @@ export function shimContent(relPath: string): string {
221
223
  return ['#!/bin/sh', '# Generated by `runspec bin` — do not edit.', 'DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)', `exec node "$DIR/${relPath}" "$@"`, ''].join('\n');
222
224
  }
223
225
 
226
+ /** Windows batch shim. `%~dp0` is the bin/ dir (trailing `\`), so `%~dp0..\<rel>`
227
+ * resolves the target relative to the folder; `%*` forwards args and node's exit
228
+ * code propagates as the script's. CRLF line endings per Windows convention. */
229
+ export function cmdShimContent(relPath: string): string {
230
+ const relWin = relPath.split('/').join('\\');
231
+ return ['@echo off', 'REM Generated by `runspec bin` — do not edit.', `node "%~dp0..\\${relWin}" %*`, ''].join('\r\n');
232
+ }
233
+
234
+ /** Write a POSIX shim plus a Windows `.cmd` alongside it, so one folder runs on both. */
224
235
  function writeShim(shimPath: string, relPath: string): void {
225
236
  fs.writeFileSync(shimPath, shimContent(relPath), 'utf-8');
226
237
  fs.chmodSync(shimPath, 0o755);
238
+ fs.writeFileSync(shimPath + '.cmd', cmdShimContent(relPath), 'utf-8');
227
239
  }
228
240
 
229
241
  function toPosix(p: string): string {
230
242
  return p.split(path.sep).join('/');
231
243
  }
232
244
 
245
+ function cmdLogs(args: string[]): void {
246
+ const has = (name: string): boolean => args.includes(name);
247
+ const valueFlags = new Set(['--since', '--user', '--run', '--older-than', '--max-files', '--max-total-size']);
248
+ const val = (name: string): string | undefined => {
249
+ const i = args.indexOf(name);
250
+ return i >= 0 && i + 1 < args.length ? args[i + 1] : undefined;
251
+ };
252
+ // Positionals are tokens that aren't flags or flag-values.
253
+ const positionals: string[] = [];
254
+ for (let i = 0; i < args.length; i++) {
255
+ const a = args[i];
256
+ if (a.startsWith('-')) {
257
+ if (valueFlags.has(a)) i++; // skip its value
258
+ continue;
259
+ }
260
+ positionals.push(a);
261
+ }
262
+
263
+ // `runspec logs status|prune|compact [runnable]` vs `runspec logs <runnable>`.
264
+ const target = positionals[0];
265
+ const verb = target === 'status' || target === 'prune' || target === 'compact' ? target : 'view';
266
+ const runnable = verb === 'view' ? target : positionals[1] ?? null;
267
+
268
+ try {
269
+ if (verb === 'view') {
270
+ if (!runnable) {
271
+ console.log('✗ A runnable is required: runspec logs <runnable>');
272
+ process.exit(1);
273
+ }
274
+ logs.view(runnable, {
275
+ since: val('--since') ? logs.parseDuration(val('--since')!) : null,
276
+ run: val('--run') ?? null,
277
+ user: val('--user') ?? null,
278
+ asJson: has('--json'),
279
+ follow: has('--follow'),
280
+ });
281
+ } else if (verb === 'status') {
282
+ logs.status(runnable, { asJson: has('--json') });
283
+ } else if (verb === 'prune') {
284
+ logs.prune(runnable, {
285
+ olderThan: val('--older-than') ? logs.parseDuration(val('--older-than')!) : null,
286
+ maxFiles: val('--max-files') ? parseInt(val('--max-files')!, 10) : null,
287
+ maxTotalSize: val('--max-total-size') ? logs.parseSize(val('--max-total-size')!) : null,
288
+ dryRun: has('--dry-run'),
289
+ asJson: has('--json'),
290
+ });
291
+ } else if (verb === 'compact') {
292
+ if (!val('--older-than')) {
293
+ console.log('✗ compact requires --older-than (e.g. --older-than 7d)');
294
+ process.exit(1);
295
+ }
296
+ logs.compact(runnable, logs.parseDuration(val('--older-than')!), {
297
+ gzip: has('--gzip'),
298
+ dryRun: has('--dry-run'),
299
+ asJson: has('--json'),
300
+ });
301
+ }
302
+ } catch (err) {
303
+ console.log(`✗ ${(err as Error).message}`);
304
+ process.exit(1);
305
+ }
306
+ }
307
+
233
308
  async function cmdJump(args: string[]): Promise<void> {
234
309
  const parsed = parse({ scriptName: 'runspec', argv: ['jump', ...args], configPath: _CLI_CONFIG });
235
310
  const fmt = String(parsed['format'] ?? 'text');
@@ -751,6 +826,7 @@ Commands:
751
826
  init Create runspec.toml and a code stub
752
827
  local List runnables and emit tool schemas
753
828
  bin Generate a venv-shaped bin/ so a controller can run this folder
829
+ logs View, status, prune, or compact per-invocation audit logs
754
830
  jump Execute a runnable on a remote host via SSH
755
831
  serve Start the MCP stdio server for local runnables
756
832
 
@@ -762,6 +838,7 @@ Examples:
762
838
  runspec local
763
839
  runspec local --format mcp
764
840
  runspec bin
841
+ runspec logs deploy
765
842
  runspec serve`);
766
843
  }
767
844
 
@@ -800,12 +877,32 @@ Examples:
800
877
 
801
878
  Each runnable's script is resolved from package.json "bin", falling back to
802
879
  ./<runnable>.js | .cjs | .mjs next to runspec.toml. Re-run after adding a
803
- runnable or 'npm install'. (POSIX shims; Windows support is a follow-up.)
880
+ runnable or 'npm install'. Writes both a POSIX shim and a Windows .cmd per
881
+ runnable, so one folder runs on either OS.
804
882
 
805
883
  Examples:
806
884
  npm install runspec-node
807
885
  runspec bin`,
808
886
 
887
+ logs: `runspec logs — View, status, prune, or compact per-invocation audit logs
888
+
889
+ For runnables using [config.logging] store = "per-run" (one file per
890
+ invocation, no in-process rotation). Reads/maintains the project's logs/.
891
+
892
+ View (default):
893
+ runspec logs <runnable> merged, timestamp-sorted stream
894
+ runspec logs <runnable> --follow live tail across invocations
895
+ runspec logs <runnable> --since 1h --user alice --run <id>
896
+ runspec logs <runnable> --json raw JSON lines
897
+
898
+ Status / retention (default to all runnables):
899
+ runspec logs status [runnable] [--json] per-runnable file + disk inventory
900
+ runspec logs compact [runnable] --older-than 7d [--gzip] [--dry-run]
901
+ runspec logs prune [runnable] --older-than 90d | --max-files N | --max-total-size 5GB [--dry-run]
902
+
903
+ prune/compact never touch a single-mode {runnable}.log — only per-run files
904
+ and archives. Add --json to any verb for machine-readable output.`,
905
+
809
906
  jump: `runspec jump — Execute a runnable on a remote host via SSH
810
907
 
811
908
  Not yet implemented in the Node package.
@@ -22,6 +22,16 @@ const _handlers: Handler[] = [];
22
22
  let _runId: string | null = null;
23
23
 
24
24
  const RUN_SUMMARY_LOGGER = 'runspec.runsummary';
25
+ // Captured-stdout records are logged under this name (mirrors Python's
26
+ // `runspec.print`). Used only for clarity in the audit file.
27
+ const PRINT_LOGGER = 'runspec.print';
28
+
29
+ // The real `process.stdout.write`, captured before we tee it. The stdout
30
+ // handler writes through this so its own output isn't re-captured (mirrors
31
+ // Python capturing the real sys.stdout reference before the tee swap).
32
+ let _rawStdoutWrite: typeof process.stdout.write | null = null;
33
+ let _stdoutBuf = '';
34
+ let _captureInstalled = false;
25
35
  // Uncaught exceptions are emitted on this dedicated logger so the file handler
26
36
  // records them while the console handlers drop them by name — console display is
27
37
  // handled explicitly in _handleUncaught (debug-gated).
@@ -114,6 +124,10 @@ interface LogRecord {
114
124
  error?: Error;
115
125
  extra?: Record<string, unknown>;
116
126
  excStructured?: Record<string, unknown>;
127
+ // Set on records synthesised from captured stdout (print-capture). Console +
128
+ // counter handlers skip these (the real stdout write already happened, and
129
+ // printed lines aren't log "events"); only file handlers persist them.
130
+ fromPrint?: boolean;
117
131
  }
118
132
 
119
133
  interface Handler {
@@ -220,8 +234,11 @@ class StdoutHandler implements Handler {
220
234
  emit(record: LogRecord): void {
221
235
  if (record.levelNum >= 30) return; // WARNING+ belongs on stderr
222
236
  if (record.loggerName === RUN_SUMMARY_LOGGER || record.loggerName === EXCEPTION_LOGGER) return;
237
+ if (record.fromPrint) return; // the real stdout write already emitted this
223
238
  try {
224
- process.stdout.write(formatConsole(record, this.showTracebacks) + '\n');
239
+ // Write through the *raw* stream so this output isn't re-captured by the
240
+ // print-capture tee (would double it in the audit file).
241
+ (_rawStdoutWrite ?? process.stdout.write.bind(process.stdout))(formatConsole(record, this.showTracebacks) + '\n');
225
242
  } catch {
226
243
  // never disrupt
227
244
  }
@@ -262,8 +279,9 @@ class RunSummaryCounter implements Handler {
262
279
  };
263
280
 
264
281
  emit(record: LogRecord): void {
265
- // Don't count runspec's own bookkeeping records (summary + uncaught-exception).
266
- if (record.loggerName === RUN_SUMMARY_LOGGER || record.loggerName === EXCEPTION_LOGGER) return;
282
+ // Don't count runspec's own bookkeeping records (summary + uncaught-exception)
283
+ // or captured stdout lines only genuine logger events.
284
+ if (record.loggerName === RUN_SUMMARY_LOGGER || record.loggerName === EXCEPTION_LOGGER || record.fromPrint) return;
267
285
  const label = LEVEL_LABEL[record.levelNum];
268
286
  if (label && label in this.counts) {
269
287
  this.counts[label]++;
@@ -617,6 +635,61 @@ export function _handleUncaught(err: Error): void {
617
635
  }
618
636
  }
619
637
 
638
+ // ── stdout capture (print → audit log) ─────────────────────────────────────────
639
+
640
+ /** Emit one captured stdout line as a file-only record (skipped by console + counter). */
641
+ function emitPrintLine(line: string): void {
642
+ if (_handlers.length === 0) return;
643
+ const record: LogRecord = { ts: new Date(), levelNum: 20, loggerName: PRINT_LOGGER, message: redact(line), fromPrint: true };
644
+ for (const h of _handlers) {
645
+ try {
646
+ if (record.levelNum >= h.level) h.emit(record);
647
+ } catch {
648
+ // never disrupt
649
+ }
650
+ }
651
+ }
652
+
653
+ /**
654
+ * Tee `process.stdout.write`: output still reaches the real stream unchanged
655
+ * (so pipes / `runspec serve` capture are untouched), and each complete line is
656
+ * also written to the audit file as a `fromPrint` record. Mirrors Python's
657
+ * `_StdoutTee`, so a runnable's `console.log` output is preserved in the
658
+ * per-invocation log — not just the run summary.
659
+ */
660
+ function installStdoutCapture(): void {
661
+ if (_captureInstalled) return;
662
+ _captureInstalled = true;
663
+ _rawStdoutWrite = process.stdout.write.bind(process.stdout);
664
+ const patched = function (chunk: unknown, encoding?: unknown, cb?: unknown): boolean {
665
+ const result = (_rawStdoutWrite as (...a: unknown[]) => boolean)(chunk, encoding, cb);
666
+ try {
667
+ const s = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString(typeof encoding === 'string' ? (encoding as BufferEncoding) : 'utf8') : '';
668
+ if (s) {
669
+ _stdoutBuf += s;
670
+ let idx: number;
671
+ while ((idx = _stdoutBuf.indexOf('\n')) !== -1) {
672
+ const line = _stdoutBuf.slice(0, idx);
673
+ _stdoutBuf = _stdoutBuf.slice(idx + 1);
674
+ if (line) emitPrintLine(line);
675
+ }
676
+ }
677
+ } catch {
678
+ // never disrupt
679
+ }
680
+ return result;
681
+ };
682
+ process.stdout.write = patched as typeof process.stdout.write;
683
+ // Flush a trailing partial line at exit. Registered before installExitHooks so
684
+ // it runs before the run-summary record (FIFO exit handlers).
685
+ process.on('exit', () => {
686
+ if (_stdoutBuf) {
687
+ emitPrintLine(_stdoutBuf);
688
+ _stdoutBuf = '';
689
+ }
690
+ });
691
+ }
692
+
620
693
  function installExitHooks(): void {
621
694
  if (_exitHooksInstalled) return;
622
695
  _exitHooksInstalled = true;
@@ -740,6 +813,10 @@ export function configureLogging(opts: ConfigureLoggingOptions): void {
740
813
  };
741
814
  }
742
815
 
816
+ // Tee stdout into the audit log so printed output (not just the run summary)
817
+ // is preserved. Installed before the exit hooks so its flush runs first.
818
+ installStdoutCapture();
819
+
743
820
  // Uncaught-exception handling is always installed (independent of the summary
744
821
  // toggle) so the structured exception record reaches the audit file even when
745
822
  // summary is off. The exit hook only flushes a summary when _summaryState is set.
@@ -757,8 +834,15 @@ export function _resetForTest(): void {
757
834
  _loggers.clear();
758
835
  _handlers.length = 0;
759
836
  _summaryState = null;
837
+ // Un-tee stdout so the patch doesn't leak across tests.
838
+ if (_rawStdoutWrite) {
839
+ process.stdout.write = _rawStdoutWrite;
840
+ _rawStdoutWrite = null;
841
+ }
842
+ _stdoutBuf = '';
843
+ _captureInstalled = false;
760
844
  // Note: process event listeners installed by installExitHooks() stay —
761
845
  // they no-op when _summaryState is null, which is the test-time state.
762
846
  }
763
847
 
764
- export { _periodForDate, RUN_SUMMARY_LOGGER, EXCEPTION_LOGGER, buildExcStructured, formatCompactTrace };
848
+ export { _periodForDate, RUN_SUMMARY_LOGGER, EXCEPTION_LOGGER, buildExcStructured, formatCompactTrace, findProjectRoot };