mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-30 19:49:14 +00:00
* feat(progress): step 1 - shared ProgressReporter + CliOptions Adds the foundation for v0.14.2's bulk-action progress streaming work: - src/core/progress.ts: dependency-free reporter with auto/human/json/quiet modes, TTY-aware rendering, time+item rate gating, heartbeat helper for slow single queries, dot-composed child phases, EPIPE defense (both sync throw and async 'error' event), and a singleton module-level signal coordinator so SIGINT/SIGTERM emits abort events for all live phases without leaking per-instance listeners. - src/core/cli-options.ts: parseGlobalFlags() for --quiet / --progress-json / --progress-interval=<ms> (both space and = forms), plus cliOptsToProgressOptions() that resolves to the right mode. Non-TTY default is human-plain one-line-per-event; JSON is explicit opt-in so shell pipelines don't suddenly see structured noise. - test/progress.test.ts (17 cases): mode resolution, rate gating, no-fake- totals on heartbeat paths, EPIPE paths, SIGINT singleton, child phase composition. - test/cli-options.test.ts (14 cases): flag parsing, invalid values, interleaved flags, mode resolution. Follow-ups wire doctor/embed/files/export/extract/import/sync/migrate/ repair-jsonb/backlinks/orphans/lint/integrity/eval/autopilot/jobs plus the apply-migrations orchestrators through this reporter, and route Minion handlers to job.updateProgress instead of stderr. See the plan in ~/.claude/plans/. 1682 unit tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 2 - wire global flags into cli.ts Parse --quiet / --progress-json / --progress-interval from argv BEFORE command dispatch, strip them, stash resolved CliOptions on a module-level singleton (same pattern as Commander's program.opts()) and on every OperationContext created for shared-op dispatch. - src/cli.ts: parseGlobalFlags(rawArgs) at the top of main(); setCliOptions once; dispatch sees only the stripped argv. Fixes the "gbrain --progress-json doctor" unknown-command case that Codex flagged. - src/core/cli-options.ts: expose setCliOptions/getCliOptions/ _resetCliOptionsForTest singleton. Commands that want progress call getCliOptions() to construct their reporter. - src/core/operations.ts: OperationContext gains optional cliOpts field so shared-op handlers (and MCP-invoked ops that need a reporter) can read the same settings. MCP callers leave it undefined and consumers default to quiet. - test/cli-options.test.ts: +4 cases covering singleton round-trip and an integration smoke spawning `bun src/cli.ts --progress-json --version` to prove the global flag survives dispatch. 45 relevant unit tests pass (progress + cli-options + cli.test.ts). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 3a - doctor + orphans heartbeat streaming Doctor on a 52K-page brain used to sit silent for 10+ minutes while the DB checks ran, then get killed by an agent timeout. Wired through the new reporter so agents see which check is running and the slow ones heartbeat every second. doctor.ts: - Start a single `doctor.db_checks` phase around the DB section, with a per-check heartbeat before each step (connection, pgvector, rls, schema_version, embeddings, graph_coverage, integrity, jsonb_integrity, markdown_body_completeness). - jsonb_integrity now scans 5 targets, not 4: added page_versions. frontmatter so the check surface matches `repair-jsonb` (per Codex review of the plan — the old 4-target scan missed a known repair site). Per-target heartbeat so 50K-row scans show incremental progress. - markdown_body_completeness: wrap the existing query in a 1s heartbeat timer. The regex scan over rd.data ->> 'content' can't be paginated usefully; this just lets agents see life during the sequential scan. No fake totals — the LIMIT 100 query has no meaningful total count. - integrity sample: same heartbeat pattern around the 500-page scan. orphans.ts: - findOrphans() wraps the NOT EXISTS anti-join in a 1s heartbeat. Keyset pagination was considered and rejected: without an index on links.to_page_id it's no faster than the full scan, and may re-plan the anti-join per batch. A schema migration adding that index is the right fix and is queued for v0.14.3. Follow-ups: - Step 3b: wire embed/files/export (the \r-only stdout offenders). - Step 5: end-to-end progress test spawning `gbrain doctor --progress-json` against a fixture brain, asserting stderr events and clean stdout. All existing unit tests continue to pass (76/76 in doctor + orphans + progress + cli-options). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 3b - embed + files + export stderr progress Replaces the \r-on-stdout progress pattern in the three worst offenders (embed, files sync, export) with the shared reporter on stderr. Stdout now carries only final summaries, so scripts and tests that grep for counts ("Embedded N chunks", "Files sync complete", "Exported N pages") still work when output is piped. - embed.ts: runEmbedCore accepts an optional onProgress callback. The CLI wrapper builds a reporter and passes reporter.tick(); Minion handlers will pass job.updateProgress in Step 4. Worker-pool is single-threaded JS so no rate-gate race (per Codex review #18). - files.ts syncFiles(): tick per file; summary preserved on stdout. - export.ts: tick per page; summary preserved on stdout. Also fixes a --quiet flag collision. `skillpack-check` has its own --quiet mode (suppress all stdout). parseGlobalFlags strips --quiet globally now, and skillpack-check reads the resolved CliOptions singleton via getCliOptions() instead of re-parsing argv. Test updated to match the stripping behavior. 1686 unit tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 3c - extract + import + sync reporter streaming Extract, import, and sync now stream per-file progress to stderr through the shared reporter. All three kept their stdout summaries + JSON action-events intact so existing tests + agent scripts are unaffected. - extract.ts (4 paths: links/timeline × fs/db): replaced the ad-hoc `process.stderr.write({event:"progress"...})` lines with reporter ticks. Same channel (stderr), canonical schema now, visible in both text and --json modes. Stdout action-events (`add_link` / `add_timeline`) untouched — tests grep them. - import.ts: the logProgress() function that printed every 100 files to stdout is now a progress.tick() call per file. Rate-gated by the reporter. Stdout still gets the final "Import complete (Xs)" summary and the --json payload. - sync.ts: three new phases (`sync.deletes`, `sync.renames`, `sync.imports`) tick per file, so big syncs show each step rather than a single end-of-run summary. Phase hierarchy ready to be child()-chained into runImport / runEmbed later, per Codex review #26. Updated the #132 nested-transaction regression test in test/sync.test.ts to also accept the new hoisted-loop shape — the guarantee (this loop is not wrapped in engine.transaction) still holds. 1686 unit tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 3d - migrate/repair/backlinks/lint/integrity/eval Wires the remaining bulk commands through the reporter: - migrate-engine: phase starts (migrate.copy_pages, migrate.copy_links), per-page tick. Old \"Progress: N/total\" stdout logs replaced by stderr ticks; final stdout summary preserved. - repair-jsonb: per-column start + a heartbeat timer while each UPDATE runs (minutes on 50K-row tables). CRITICAL: stdout stays clean so migrations/v0_12_2.ts's JSON.parse(child.stdout) still works. Per Codex review #12. - backlinks: 1s heartbeat around findBacklinkGaps() (sync double-walk of the brain dir). - lint: tick per page; per-issue stdout output preserved. - integrity auto: tick per page in the main resolver loop. The separate ~/.gbrain/integrity-progress.jsonl resume marker is untouched (its role shifts from live progress reporting to resume-only). - eval: add an onProgress option to core's runEval(), CLI wraps with a reporter. Phases: eval.single / eval.ab. Tick per query. core/search/eval.ts gains a RunEvalOptions type so future callers (MCP eval op, Minion handlers) can also hook in without the reporter. 1686 unit tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 3e - onProgress callbacks on core libs - src/core/embedding.ts: embedBatch() gains an optional EmbedBatchOptions.onBatchComplete callback, fired after each 100-item sub-batch. CLI wrappers pass reporter.tick; Minion handlers can pass job.updateProgress. - src/core/enrichment-service.ts: enrichEntities() config gains onProgress(done, total, name) fired after each entity. Same split: CLI -> reporter, Minion -> DB-backed progress. No CLI behavior change on its own. Wiring these callbacks into the Minion handlers is Step 4. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 4 - orchestrators + upgrade + minion handlers - cli-options.ts: childGlobalFlags() returns the flag suffix to append to child gbrain subprocesses. Empty string by default, " --quiet --progress-json" when the parent has them set, so child behavior inherits the parent's progress-mode without scattering string-concat logic across every execSync site. - migrations/v0_12_2.ts: each execSync inherits the parent's global flags. Phase C (repair-jsonb --dry-run --json) pins explicit stdio to ['ignore','pipe','inherit'] so child stderr streams straight through while stdout stays captured for JSON.parse. Per Codex review #12. - migrations/v0_12_0.ts + v0_11_0.ts: same childGlobalFlags wiring at each gbrain-subcommand execSync. - upgrade.ts: post-upgrade timeout bumped 300s → 30min (1_800_000 ms) with GBRAIN_POST_UPGRADE_TIMEOUT_MS override. The old 300s cap killed v0.12.0 graph-backfill migrations on 50K+ brains; the heartbeat wiring added in v0.14.2 makes long waits observable, so a generous ceiling no longer means users stare at a silent terminal. - jobs.ts: the embed Minion handler passes job.updateProgress as the onProgress callback, so per-job progress is durable in minion_jobs and readable via `gbrain jobs get <id>`. Primary Minion progress channel is DB-backed — stderr from `jobs work` stays coarse for daemon liveness only. Per Codex review #20. 1686 unit tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 5 - E2E doctor-progress test + CI guard scripts/check-progress-to-stdout.sh greps src/ for the banned `process.stdout.write('\r…')` pattern that v0.14.2 removed from the bulk-action codepaths. Wired into the `bun run test` script so any future regression that puts progress back on stdout fails fast. An empty allowlist documents the position: every known call site was migrated; new exceptions need a rationale in the allowlist. test/e2e/doctor-progress.test.ts (Tier 1, needs Postgres + pgvector): - `gbrain --progress-json doctor --json`: stderr carries JSONL progress events with the canonical {event, phase, ts} shape, starts + finishes for `doctor.db_checks`. Stdout stays parseable JSON — no progress pollution. - `gbrain doctor` (no flag): human-plain progress goes to stderr only, stdout stays free of `[doctor.db_checks]`. - `gbrain --quiet doctor`: reporter emits nothing; doctor still runs to completion. test/cli-options.test.ts: +2 spawning integration tests. One verifies `gbrain --progress-json --version` keeps stdout clean of progress events (single-shot commands that don't use a reporter aren't affected). One guards the skillpack-check --quiet regression — --quiet suppresses stdout by reading the resolved CliOptions singleton, not re-parsing argv. Full test matrix: bun run test -> 1726 pass / 184 skipped (no DB) / 0 fail bun run test:e2e -> 136 pass / 13 skipped / 0 fail Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(progress): step 6 - docs + v0.14.2 release bump - VERSION + package.json bumped to 0.14.2. - docs/progress-events.md (new): canonical JSON event schema reference. Stable from v0.14.2, additive only. Lists every phase name shipped in this release, the five event types (start/tick/heartbeat/finish/ abort), the TTY/non-TTY rendering rules, subprocess inheritance semantics, and the Minion DB-backed progress model. - CLAUDE.md: "Bulk-action progress reporting" section under the build instructions; Key files entries for src/core/progress.ts, src/core/cli-options.ts, scripts/check-progress-to-stdout.sh, and docs/progress-events.md; doctor.ts entry updated to note the v0.14.2 5-target jsonb_integrity scan + heartbeat wiring. - CHANGELOG.md v0.14.2: full release summary per project voice rules. The "numbers that matter" table, per-command before/after grid, backward-compat warnings for stdout→stderr moves, and an itemized changes section covering reporter/CLI plumbing/schema/Minion handlers/doctor fixes/upgrade timeout/CI guard/tests. No em dashes. Real file paths, real commands, real numbers. - skills/migrations/v0.14.2.md (new): agent migration note. Mechanical step is "nothing" since v0.14.2 is purely additive. Walks agents through the three new global flags, the 14 wired commands, the event schema cheat sheet, Minion progress via job.updateProgress, and scripts/verification commands. Full test matrix: bun run test (unit + guards) -> 1726 pass / 184 skipped / 0 fail bun run test:e2e (Postgres) -> 141 pass / 8 skipped / 0 fail Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version to 0.15.2, restore master's [0.14.2] CHANGELOG entry Master sits at 0.14.2 (reliability wave). This PR lands on top as 0.15.2 (progress streaming wave). Splits the merge-time combined CHANGELOG entry back into two discrete release sections so history stays honest: - [0.15.2] = progress reporter, CliOptions, 14 wired commands, Minion embed handler, doctor jsonb_integrity 5-target fix, upgrade timeout bump, CI guard, progress unit+E2E tests. - [0.14.2] = master's eight root-cause bug fixes, restored verbatim from origin/master. Touched files: - VERSION + package.json: 0.14.2 -> 0.15.2 (next patch off master). - skills/migrations/v0.14.2.md -> skills/migrations/v0.15.2.md (rename + rewrite frontmatter + body to v0.15.2). - CHANGELOG.md: split into two entries; progress-wave refs renamed v0.14.2 -> v0.15.2; reliability-wave entry restored from master. - src/core/progress.ts, src/commands/doctor.ts, src/commands/sync.ts, src/commands/upgrade.ts, docs/progress-events.md, test/sync.test.ts: progress-wave v0.14.2 references -> v0.15.2. The remaining v0.14.2 references in test/e2e/migration-flow.test.ts (Bug 3 context) and CLAUDE.md (reliability-wave key commands, Bug 3 ledger move) correctly point at master's 0.14.2 release. Test matrix after version bump: bun run test -> 1780 pass / 179 skipped / 0 fail Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
478 lines
15 KiB
TypeScript
478 lines
15 KiB
TypeScript
/**
|
|
* Bulk-action progress reporter.
|
|
*
|
|
* Single source of truth for per-object progress on long-running binaries
|
|
* (doctor, embed, sync, extract, etc.). Writes to stderr so stdout stays
|
|
* clean for data / JSON output that agents parse.
|
|
*
|
|
* Modes:
|
|
* auto (default): isTTY ? human-\r : human-plain one-line-per-event
|
|
* human: force human rendering
|
|
* json: emit one JSON object per line (see schema below)
|
|
* quiet: no output
|
|
*
|
|
* JSON event schema (stable from v0.15.2, additive only):
|
|
* {"event":"start","phase":"<snake.dot.path>","total"?:N,"ts":"<iso>"}
|
|
* {"event":"tick","phase":"...","done":N,"total"?:N,"pct"?:F,"elapsed_ms":N,"eta_ms"?:N,"ts":"..."}
|
|
* {"event":"heartbeat","phase":"...","note":"<str>","elapsed_ms":N,"ts":"..."}
|
|
* {"event":"finish","phase":"...","done"?:N,"total"?:N,"elapsed_ms":N,"ts":"..."}
|
|
* {"event":"abort","phase":"...","reason":"<SIGINT|SIGTERM>","elapsed_ms":N,"ts":"..."}
|
|
*
|
|
* Rules:
|
|
* - phase uses snake_case dot-separated machine-stable names.
|
|
* - total/pct/eta_ms are omitted when total is unknown (no fake totals).
|
|
* - stdout is NEVER written to. Data output stays a separate concern.
|
|
*
|
|
* See docs/progress-events.md for the full reference.
|
|
*/
|
|
|
|
export type ProgressMode = 'auto' | 'human' | 'json' | 'quiet';
|
|
|
|
export interface ProgressOptions {
|
|
mode?: ProgressMode;
|
|
stream?: NodeJS.WritableStream; // default process.stderr
|
|
minIntervalMs?: number; // default 1000
|
|
minItems?: number; // default: max(10, Math.ceil((total||1000)/100))
|
|
}
|
|
|
|
export interface ProgressReporter {
|
|
start(phase: string, total?: number): void;
|
|
tick(n?: number, note?: string): void;
|
|
heartbeat(note: string): void;
|
|
finish(note?: string): void;
|
|
child(phase: string, total?: number): ProgressReporter;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Singleton signal coordinator
|
|
// ---------------------------------------------------------------------------
|
|
// Per Codex review #28/#29: one process-level SIGINT/SIGTERM handler, tracking
|
|
// every live reporter. Per-instance handlers would leak listeners and interfere
|
|
// with command-level handlers (e.g. shell-handler abort in jobs.ts).
|
|
//
|
|
// We never call process.exit() or swallow the signal — we just emit abort
|
|
// events for live phases, then remove ourselves so the user's own handlers
|
|
// (or the default Node behavior) run as usual.
|
|
|
|
interface LivePhase {
|
|
reporter: PhaseState;
|
|
abort: (reason: string) => void;
|
|
}
|
|
|
|
const liveReporters = new Set<LivePhase>();
|
|
let signalHandlerInstalled = false;
|
|
|
|
function installSignalHandler(): void {
|
|
if (signalHandlerInstalled) return;
|
|
signalHandlerInstalled = true;
|
|
|
|
const onSignal = (reason: 'SIGINT' | 'SIGTERM') => {
|
|
// Copy to array so abort() can mutate liveReporters during iteration.
|
|
const snapshot = Array.from(liveReporters);
|
|
for (const entry of snapshot) {
|
|
try {
|
|
entry.abort(reason);
|
|
} catch {
|
|
/* best-effort */
|
|
}
|
|
}
|
|
};
|
|
|
|
// once() so we don't block user handlers or double-fire.
|
|
process.once('SIGINT', () => onSignal('SIGINT'));
|
|
process.once('SIGTERM', () => onSignal('SIGTERM'));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Mode resolution
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function resolveMode(mode: ProgressMode, stream: NodeJS.WritableStream): 'human-tty' | 'human-plain' | 'json' | 'quiet' {
|
|
if (mode === 'quiet') return 'quiet';
|
|
if (mode === 'json') return 'json';
|
|
const isTty = (stream as { isTTY?: boolean }).isTTY === true;
|
|
if (mode === 'human') return isTty ? 'human-tty' : 'human-plain';
|
|
// auto
|
|
return isTty ? 'human-tty' : 'human-plain';
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Stream write with EPIPE defense (sync throw path AND 'error' event path).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const brokenStreams = new WeakSet<NodeJS.WritableStream>();
|
|
|
|
function safeWrite(stream: NodeJS.WritableStream, chunk: string): void {
|
|
if (brokenStreams.has(stream)) return;
|
|
try {
|
|
stream.write(chunk, (err) => {
|
|
if (err) brokenStreams.add(stream);
|
|
});
|
|
} catch {
|
|
brokenStreams.add(stream);
|
|
}
|
|
}
|
|
|
|
// Attach one 'error' listener per stream so async EPIPE marks it broken.
|
|
const errorListenersAttached = new WeakSet<NodeJS.WritableStream>();
|
|
function attachErrorListener(stream: NodeJS.WritableStream): void {
|
|
if (errorListenersAttached.has(stream)) return;
|
|
errorListenersAttached.add(stream);
|
|
// 'error' on a raw tty/pipe is rare, but EPIPE can surface this way.
|
|
(stream as NodeJS.EventEmitter).on?.('error', () => {
|
|
brokenStreams.add(stream);
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Rendering helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function renderHumanLine(phase: string, done: number | undefined, total: number | undefined, note: string | undefined): string {
|
|
const parts: string[] = [`[${phase}]`];
|
|
if (typeof done === 'number') {
|
|
if (typeof total === 'number' && total > 0) {
|
|
const pct = Math.floor((done / total) * 100);
|
|
parts.push(`${done}/${total} (${pct}%)`);
|
|
} else {
|
|
parts.push(`${done}`);
|
|
}
|
|
}
|
|
if (note) parts.push(note);
|
|
return parts.join(' ');
|
|
}
|
|
|
|
function nowIso(): string {
|
|
return new Date().toISOString();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase state (per start/finish lifecycle of one reporter instance)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface PhaseState {
|
|
phase: string;
|
|
total?: number;
|
|
done: number;
|
|
startedAt: number;
|
|
lastEmitMs: number;
|
|
lastDoneEmitted: number;
|
|
heartbeatTimer?: ReturnType<typeof setInterval>;
|
|
live: LivePhase | null; // membership in liveReporters for signal cleanup
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Reporter factory
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface ReporterInternal extends ProgressReporter {
|
|
_phasePath: string[]; // for child phase path composition
|
|
}
|
|
|
|
class Reporter implements ReporterInternal {
|
|
_phasePath: string[];
|
|
private stream: NodeJS.WritableStream;
|
|
private renderMode: 'human-tty' | 'human-plain' | 'json' | 'quiet';
|
|
private minIntervalMs: number;
|
|
private minItemsOverride?: number;
|
|
private state: PhaseState | null = null;
|
|
|
|
constructor(parentPath: string[], opts: Required<Omit<ProgressOptions, 'stream' | 'minIntervalMs' | 'minItems'>> & {
|
|
stream: NodeJS.WritableStream;
|
|
minIntervalMs: number;
|
|
minItems?: number;
|
|
}) {
|
|
this._phasePath = parentPath;
|
|
this.stream = opts.stream;
|
|
this.renderMode = resolveMode(opts.mode, opts.stream);
|
|
this.minIntervalMs = opts.minIntervalMs;
|
|
this.minItemsOverride = opts.minItems;
|
|
if (this.renderMode !== 'quiet') {
|
|
attachErrorListener(this.stream);
|
|
installSignalHandler();
|
|
}
|
|
}
|
|
|
|
private defaultMinItems(total?: number): number {
|
|
if (this.minItemsOverride !== undefined) return this.minItemsOverride;
|
|
const base = total && total > 0 ? total : 1000;
|
|
return Math.max(10, Math.ceil(base / 100));
|
|
}
|
|
|
|
private emitJson(obj: Record<string, unknown>): void {
|
|
safeWrite(this.stream, JSON.stringify(obj) + '\n');
|
|
}
|
|
|
|
private emitHumanLine(line: string): void {
|
|
if (this.renderMode === 'human-tty') {
|
|
// \r rewrite: clear-to-EOL then carriage-return-positioned line.
|
|
safeWrite(this.stream, `\r\x1b[2K${line}`);
|
|
} else {
|
|
safeWrite(this.stream, line + '\n');
|
|
}
|
|
}
|
|
|
|
private finalizeHumanLine(): void {
|
|
// When a TTY phase ends, move to a new line so subsequent output doesn't overwrite.
|
|
if (this.renderMode === 'human-tty') safeWrite(this.stream, '\n');
|
|
}
|
|
|
|
private phaseName(localPhase: string): string {
|
|
return [...this._phasePath, localPhase].join('.');
|
|
}
|
|
|
|
start(localPhase: string, total?: number): void {
|
|
// Auto-finish prior phase if caller forgot.
|
|
if (this.state) this.finish();
|
|
|
|
const phase = this.phaseName(localPhase);
|
|
const now = Date.now();
|
|
const s: PhaseState = {
|
|
phase,
|
|
total,
|
|
done: 0,
|
|
startedAt: now,
|
|
lastEmitMs: now,
|
|
lastDoneEmitted: 0,
|
|
live: null,
|
|
};
|
|
this.state = s;
|
|
|
|
// Register with signal coordinator.
|
|
const live: LivePhase = {
|
|
reporter: s,
|
|
abort: (reason) => this.abortFromSignal(reason),
|
|
};
|
|
liveReporters.add(live);
|
|
s.live = live;
|
|
|
|
if (this.renderMode === 'quiet') return;
|
|
|
|
if (this.renderMode === 'json') {
|
|
const obj: Record<string, unknown> = { event: 'start', phase, ts: nowIso() };
|
|
if (typeof total === 'number') obj.total = total;
|
|
this.emitJson(obj);
|
|
} else {
|
|
this.emitHumanLine(renderHumanLine(phase, undefined, total, 'start'));
|
|
}
|
|
}
|
|
|
|
tick(n: number = 1, note?: string): void {
|
|
const s = this.state;
|
|
if (!s) return;
|
|
s.done += n;
|
|
|
|
if (this.renderMode === 'quiet') return;
|
|
|
|
const now = Date.now();
|
|
const sinceEmit = now - s.lastEmitMs;
|
|
const itemsSinceEmit = s.done - s.lastDoneEmitted;
|
|
const minItems = this.defaultMinItems(s.total);
|
|
const isFinalTick = s.total !== undefined && s.done >= s.total;
|
|
|
|
// Emit if: time-gate passed, OR enough items since last emit, OR this is the final tick.
|
|
const shouldEmit = sinceEmit >= this.minIntervalMs || itemsSinceEmit >= minItems || isFinalTick;
|
|
if (!shouldEmit) return;
|
|
|
|
s.lastEmitMs = now;
|
|
s.lastDoneEmitted = s.done;
|
|
|
|
const elapsedMs = now - s.startedAt;
|
|
if (this.renderMode === 'json') {
|
|
const obj: Record<string, unknown> = {
|
|
event: 'tick',
|
|
phase: s.phase,
|
|
done: s.done,
|
|
elapsed_ms: elapsedMs,
|
|
ts: nowIso(),
|
|
};
|
|
if (typeof s.total === 'number' && s.total > 0) {
|
|
obj.total = s.total;
|
|
obj.pct = Math.round((s.done / s.total) * 1000) / 10; // one decimal
|
|
if (s.done > 0) {
|
|
const msPerItem = elapsedMs / s.done;
|
|
const remaining = Math.max(0, s.total - s.done);
|
|
obj.eta_ms = Math.round(msPerItem * remaining);
|
|
}
|
|
}
|
|
if (note) obj.note = note;
|
|
this.emitJson(obj);
|
|
} else {
|
|
this.emitHumanLine(renderHumanLine(s.phase, s.done, s.total, note));
|
|
}
|
|
}
|
|
|
|
heartbeat(note: string): void {
|
|
const s = this.state;
|
|
if (!s) return;
|
|
if (this.renderMode === 'quiet') return;
|
|
|
|
const now = Date.now();
|
|
const elapsedMs = now - s.startedAt;
|
|
|
|
if (this.renderMode === 'json') {
|
|
this.emitJson({
|
|
event: 'heartbeat',
|
|
phase: s.phase,
|
|
note,
|
|
elapsed_ms: elapsedMs,
|
|
ts: nowIso(),
|
|
});
|
|
} else {
|
|
this.emitHumanLine(renderHumanLine(s.phase, undefined, undefined, note));
|
|
}
|
|
}
|
|
|
|
finish(note?: string): void {
|
|
const s = this.state;
|
|
if (!s) return;
|
|
|
|
if (s.heartbeatTimer) {
|
|
clearInterval(s.heartbeatTimer);
|
|
s.heartbeatTimer = undefined;
|
|
}
|
|
if (s.live) {
|
|
liveReporters.delete(s.live);
|
|
s.live = null;
|
|
}
|
|
|
|
if (this.renderMode !== 'quiet') {
|
|
const elapsedMs = Date.now() - s.startedAt;
|
|
if (this.renderMode === 'json') {
|
|
const obj: Record<string, unknown> = {
|
|
event: 'finish',
|
|
phase: s.phase,
|
|
elapsed_ms: elapsedMs,
|
|
ts: nowIso(),
|
|
};
|
|
if (s.done > 0) obj.done = s.done;
|
|
if (typeof s.total === 'number') obj.total = s.total;
|
|
if (note) obj.note = note;
|
|
this.emitJson(obj);
|
|
} else {
|
|
this.emitHumanLine(renderHumanLine(s.phase, s.done > 0 ? s.done : undefined, s.total, note ?? 'done'));
|
|
this.finalizeHumanLine();
|
|
}
|
|
}
|
|
|
|
this.state = null;
|
|
}
|
|
|
|
private abortFromSignal(reason: string): void {
|
|
const s = this.state;
|
|
if (!s) return;
|
|
if (s.heartbeatTimer) {
|
|
clearInterval(s.heartbeatTimer);
|
|
s.heartbeatTimer = undefined;
|
|
}
|
|
if (this.renderMode !== 'quiet') {
|
|
const elapsedMs = Date.now() - s.startedAt;
|
|
if (this.renderMode === 'json') {
|
|
this.emitJson({
|
|
event: 'abort',
|
|
phase: s.phase,
|
|
reason,
|
|
elapsed_ms: elapsedMs,
|
|
ts: nowIso(),
|
|
});
|
|
} else {
|
|
this.emitHumanLine(renderHumanLine(s.phase, s.done > 0 ? s.done : undefined, s.total, `aborted (${reason})`));
|
|
this.finalizeHumanLine();
|
|
}
|
|
}
|
|
if (s.live) {
|
|
liveReporters.delete(s.live);
|
|
s.live = null;
|
|
}
|
|
this.state = null;
|
|
}
|
|
|
|
child(localPhase: string, _total?: number): ProgressReporter {
|
|
// Children inherit mode, stream, rate settings. The child's prefix path
|
|
// is the parent's currently-active FULL phase (if any) plus the local
|
|
// child-name passed here, so child.start('file1') renders as
|
|
// '<parent-phase>.<child-name>.file1'. If parent has no active phase,
|
|
// fall back to parent's own prefix.
|
|
const childPath = this.state
|
|
? [this.state.phase, localPhase]
|
|
: [...this._phasePath, localPhase];
|
|
const child = new Reporter(childPath, {
|
|
mode: this.modeForChildren(),
|
|
stream: this.stream,
|
|
minIntervalMs: this.minIntervalMs,
|
|
minItems: this.minItemsOverride,
|
|
});
|
|
return child;
|
|
}
|
|
|
|
/**
|
|
* Expose a heartbeat timer to external callers. The reporter owns the timer
|
|
* so we can guarantee cleanup on finish/abort. Caller uses the returned
|
|
* stopper in a try/finally. Internal helper — the canonical user API is:
|
|
*
|
|
* p.start('phase');
|
|
* const stop = startHeartbeat(p, 'still scanning…');
|
|
* try { await slowWork(); } finally { stop(); p.finish(); }
|
|
*/
|
|
|
|
// modeForChildren preserves the fully-resolved mode (so a parent in 'json'
|
|
// doesn't re-evaluate TTY for children — they inherit the explicit mode).
|
|
private modeForChildren(): ProgressMode {
|
|
switch (this.renderMode) {
|
|
case 'human-tty':
|
|
case 'human-plain':
|
|
return 'human';
|
|
case 'json':
|
|
return 'json';
|
|
case 'quiet':
|
|
return 'quiet';
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Public API
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export function createProgress(opts: ProgressOptions = {}): ProgressReporter {
|
|
const stream = opts.stream ?? process.stderr;
|
|
return new Reporter([], {
|
|
mode: opts.mode ?? 'auto',
|
|
stream,
|
|
minIntervalMs: opts.minIntervalMs ?? 1000,
|
|
minItems: opts.minItems,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Starts a 1000ms interval that fires p.heartbeat(note). Returns a stop
|
|
* function to call in finally. Safe to stop twice.
|
|
*
|
|
* Use for single long-running queries where there's no iteration to tick.
|
|
*/
|
|
export function startHeartbeat(p: ProgressReporter, note: string, intervalMs = 1000): () => void {
|
|
const timer = setInterval(() => {
|
|
try {
|
|
p.heartbeat(note);
|
|
} catch {
|
|
/* reporter may be finished; ignore */
|
|
}
|
|
}, intervalMs);
|
|
let stopped = false;
|
|
return () => {
|
|
if (stopped) return;
|
|
stopped = true;
|
|
clearInterval(timer);
|
|
};
|
|
}
|
|
|
|
// Test-only hook so we can assert one signal handler across many reporters.
|
|
// Not part of the public API; used by test/progress.test.ts.
|
|
export function __liveReporterCountForTest(): number {
|
|
return liveReporters.size;
|
|
}
|
|
|
|
export function __signalHandlerInstalledForTest(): boolean {
|
|
return signalHandlerInstalled;
|
|
}
|