mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
* fix(ruflo-console): Plugin Catalog reads a Windows marketplace clone (0.47.1)
Claude Code records the ruflo marketplace clone's installLocation as a drive
path (C:\Users\...\marketplaces\ruflo). readCatalog refused any location not
starting with "/", so the catalog showed "the clone's marketplace.json is not
readable" with the file in place.
- readCatalog uses isAbsolutePath / hasParentSegment from paths.ts.
- The catalog's plugin folders, manifests, skill/agent/command reads and the
snapshot's marketplace.json read (freshness row) build paths with joinPath
instead of a hardcoded "/".
- tests/windows-drive-path-sites.spec.ts: a Windows clone lists its plugins,
reads a skill file, and still refuses a relative or climbing location. The
new tests fail without the fix.
- Version 0.47.0 -> 0.47.1 in plugin.json, hooks/version.ts, scripts/smoke.sh
and CHANGELOG.md.
The other ruflo-console specs fail the same 12 tests with and without this
change on this machine (mission-cost, menu-entry, tui-ai-page, write-argv).
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): forget-history actions and TUI colour work on Windows
- Events "forget history" and Workflows "forget saved views" ran `rm -f`, which
Windows does not have (write-flavor.ts: no delete on host-fs). On host-fs they
now empty the file(s) through the host file API (new emptyFiles in
write-via.ts; forgetSpec carries a `write` op like event-export does). The
saved-views file is rewritten as a valid empty document, and the forget is
verified by what the file holds. Linux/macOS keep the rm argv.
- depthOf returned "none" whenever TERM was unset. Windows Terminal, PowerShell
and cmd leave TERM unset (COLORTERM=truecolor, OS=Windows_NT), so the
standalone TUI drew without colour. On Windows only an explicit TERM=dumb or
NO_COLOR turns colour off.
Tests: both forget actions in host-fs flavor (files emptied, no rm run, refusal
reported, missing file left alone), forgetSpec verification, depthOf on Windows.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): ADR status edits on CRLF records, and codex detection, on Windows
- withStatus / withSupersedes compared whole lines ("---") and checked
startsWith("---\n"), so a MADR record checked out with CRLF (git autocrlf is on
by default on Windows) failed with "the front matter is not closed", and other
formats got mixed line endings. Records with CRLF are now edited as LF text and
written back with CRLF.
- The Conversation board looked for codex with `which`, which Windows lacks, so
codex was never offered there. A Windows home (drive path or share) uses
`where`.
Tests: CRLF records for all three ADR formats (same edit as LF, CRLF kept, MADR
front matter found, supersede link), and the finder per platform. The ADR tests
fail without the fix.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): keep the Windows fixes under the size rule, skip POSIX-only specs on Windows (0.47.2)
- Move the forget-history spec out of events-ui.ts into events-forget.ts: the
Windows branch had taken events-ui.ts to 521 lines (smoke step 11 caps files at
500). Move the codex-finder test out of wf-control-views.spec.ts (514 lines)
into wf-convo-finder.spec.ts.
- wf-replay-views: the Forget button asks one tick later now that it awaits the
write flavor; the spec waits for it.
- write-argv.spec.ts: the real-disk POSIX script specs check Unix mode bits and
FIFOs, which NTFS has not; Windows writes through the host file API. Skipped
there. tui-ai-page.spec.ts: the --plain spec needs a runnable fake codex (a
shebang script), which Windows cannot run; it asserts the codex line exists.
- Version 0.47.1 -> 0.47.2 in plugin.json, hooks/version.ts, scripts/smoke.sh and
CHANGELOG.md (the entry lists every Windows fix of this branch).
Verified: the specs of the changed areas pass; the remaining failures in a full
run are menu-entry (a circular import, not Windows-specific, fails on the
baseline), the *.test.ts kit files (need claude-code/testing), and two
timing-sensitive specs that pass alone.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-cost-tracker): the ledger scripts run on Windows (0.28.3)
ledger.mjs, advise.mjs and local-cost.mjs ran only when
import.meta.url === `file://${process.argv[1]}`. On Windows that is
file:///C:/... against C:\..., never equal, so every call exited 0 with no
output and the plugin's own test-ledger.mjs failed 7 tests. They compare against
pathToFileURL(process.argv[1]).href now.
Two more breaks sat behind it for the ruflo console's mission spend:
- ledger.mjs --project required a leading "/", so a Windows project exited 2.
- inProject matched with "/" and exact case; transcripts record C:\Users\x\proj.
A drive-lettered path now compares with either separator and any letter case;
POSIX matching is unchanged (exact, directory boundary).
Tests: test-ledger.mjs gains Windows rows and cases (drive path in both
separator styles and letter cases, relative or climbing drive paths still exit 2,
POSIX rule stays exact). Version 0.28.2 -> 0.28.3 in plugin.json, smoke.sh and
CHANGELOG.md. smoke.sh still fails 5 steps on a Windows Git Bash for a reason
that predates this (it hands /c/... paths to a Windows node), unchanged here.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): the autopilot's text checks know Windows paths, commands and shells
Groundwork for the Windows-aware path checks that ap-windows-gate.spec.ts names as
the follow-up (an autopilot start is still refused on Windows). Each rule only
parks or refuses more; none allows anything that was refused before.
- classifyTask read only POSIX paths from a task's text, so a task naming
C:\Windows\..., \\srv\share\..., ..\..\x, ~\x, %USERPROFILE%\x or
$env:USERPROFILE\x was not checked against the envelope folders. It is now.
- delete-outside-worktree knew the POSIX recursive-delete forms but not the
Windows ones: rmdir /s, del on a drive, the drive-format command,
Remove-Item -Recurse, or a recursive rm on a drive or a variable.
- verifyProblem took the program name by splitting on "/" only, so
C:\Windows\System32\cmd.exe, bash.exe or powershell passed the banned-program
check. It uses either separator, drops .exe/.cmd/.bat/.ps1, and a second set
bans the Windows shells, script hosts and destructive or system tools.
Tests (ap-windows-guard.spec.ts): path extraction and the envelope check, the deny
forms and ordinary text that must not match, verify programs allowed and refused.
Four of them fail without the change; the POSIX behaviour is asserted unchanged.
CHANGELOG: added to the unreleased 0.47.2 entry.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): the Overview heading shortens a Windows project path
"ruflo state in <last two folders>" split the cwd on "/" only, so a Windows cwd
(C:\Users\x\proj) printed whole. tailOf in paths.ts splits on either separator;
the overview uses it. Test in paths.spec.ts. CHANGELOG: added to the unreleased
0.47.2 entry.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): transcript search, model keys and peer sends on Windows; smoke under Git Bash
The last Windows gaps of the sweep, each tested.
- Stopping or messaging a workflow run reads the run's task id from the session
transcript; over 2 MB that was `grep -o`, which Windows lacks. Windows now runs
PowerShell's Select-String (windowsSearchArgv in data/wf-control.ts). The path
and the pattern ride inside the script as base64, so a path with a space, a
quote, $, & or ; is only data and the script holds no double quote. Tested
against a real PowerShell on a 5 MB-class file through such a path.
- taskIdOf returned the FIRST launch when a search printed two launches of one
run (a resume), because the pattern's `[^}]` ran across both matches (nothing
prints a closing brace between them). It takes the last task id in the match.
This also affected `grep -o` on Linux and macOS.
- A model key for an HTTP endpoint was read with `printenv`, which Windows lacks.
Host gains an optional `env` (register.ts: $.env.get, already used for other
names) and SendDeps an optional `readEnv`, set only for a Windows home; elsewhere
`printenv` is unchanged.
- A send to a federation peer runs `bash <helper>`. On a Windows PATH `bash` is
the WSL launcher (System32\bash.exe), which cannot open a C:\ script path, so
the send failed obscurely. On a Windows home it now refuses, running nothing,
and says why.
- ruflo-cost-tracker scripts/smoke.sh builds ROOT with `pwd -W` under Git Bash:
a Windows node could not open /c/... paths, which failed 5 steps (now 66/0).
Checked and left alone: the npx launcher. The installed Claude Code (a native
binary with the host code inside it) runs $.process.run through a bundled execa
on cross-spawn, which finds `npx` as npx.cmd through PATHEXT and runs it via
cmd.exe /d /s /c with its own argument escaping, so ['npx', ...] works on
Windows. The same lookup is why `bash` there is the first bash.exe on the PATH
(the WSL launcher on this machine), which the peer refusal above relies on.
CHANGELOG: both plugins' unreleased entries (0.47.2, 0.28.3) list these.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): what running every view on a real Windows machine turned up
The previous commits came from pattern scans. This one comes from running the
console's own readers against a real Windows machine (every view through the
standalone terminal; the plugin catalog, ADR loader and workflow reader called
directly), plus a complete triage of the path-handling patterns in hooks/.
Found by the real run:
- The standalone terminal left state.configDir null when CLAUDE_CONFIG_DIR was
unset (the usual case), so the installed plugins, the marketplaces and the
workflow runs were all "unreadable". It now falls back to <home>/.claude, as
register.ts does in the engine. Not Windows-specific.
- research.ts kept its own POSIX-only safeInstallPath, so ruflo-goals was never
found on Windows. It uses the Windows-aware one in cost-ledger.ts (same
character set on POSIX); on this machine goalsOf now answers ready with the
real C:\ root.
Found by triaging every `split('/')`, `lastIndexOf('/')` and `startsWith('/')`:
- isRunPath, isRunFile and isUnder checked for ".." only between slashes, so a
segment written with a backslash passed on Windows; a config folder ending in
a backslash did not match. They use hasParentSegment / trimTrailing, as does
under().
- The menu and the boot screen named the project by splitting cwd on "/", which
printed a whole C:\ path. baseOf in paths.ts.
Test-suite and cycle fixes so the smoke's own command passes here:
- views/pane built BODIES = { menu: menuView, ... } at load time, but
views/menu reaches pane through mission-control > mission-claude > model-tools,
so loading menu first left menuView undefined under the test runner (native
ESM hoists the function; the app loads pane first). It is read at call time.
- tui-actions waited a fixed 1.2 s for a 1 s retry plus a redraw, and failed
under CPU contention in a full run (also on the baseline). It waits for the
outcome it asserts, up to 10 s.
Verified: the smoke's exact command (every spec, 30 s timeout) is 239 files
passed, 0 failed, 3486 tests; the console smoke is 20 passed, 0 failed; all 34
views render with exit 0 and no stderr; an ADR project with a space in its path
and CRLF records loads and plans a status change keeping its CRLF.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): the install record of a plugin that applies to this project, compared the Windows way
installed_plugins.json holds one record per install of a plugin, and a project-scope
record names the project it was made for. The snapshot took entries[0], so a plugin
installed for several projects showed another project's version and install folder.
On a real Windows machine ruflo-console@ruflo has five records (four project, one
user) and the first is a different project's 0.44.7; everything derived from it,
the version shown and the installPath used to find a plugin's scripts, could point
at the wrong copy.
- parseInstalled(text, cwd) picks the project or local record whose projectPath is
the session folder or holds it, else the user record, else the first.
- insideOrSame in paths.ts is that comparison, Windows-aware (case, either
separator, a folder inside the project); hooks/updates.ts decides which installs
to update with it too. It compared with === and startsWith(path + "/"), so on
Windows a session in a subfolder of the project, or with a different drive-letter
case, did not count the project's own install and left it stale.
tui-actions: "a read runs at once" waited a fixed 500 ms for a stand-in CLI process
to start; it waits for the run it asserts, and its neighbour, which failed only
because that run landed late in the shared log, no longer does.
Tests (windows-path-guards.spec.ts): the record chosen for the project under both
separators, other letter case, a subfolder, a sibling sharing the prefix, no match,
no user record, no cwd; the updater's rule; insideOrSame. Verified: the smoke's
exact command (every spec, 30 s timeout) is 239 files passed, 0 failed, 3491 tests.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the focus-lost spec waits for the output to go quiet before it asserts silence
"stops drawing while the terminal reports focus lost" marked the output length 60 ms
after the focus-lost report and then expected no growth. A frame already in flight
when focus was lost lands after that mark on a busy machine, which reads as the page
still drawing; the smoke's first vitest pass failed on it and only the retry passed.
It now waits until the output stops changing before it marks, still asserts 500 ms of
silence after that, and waits for the redraw on focus regained instead of a fixed
300 ms. Passes 4 of 4 isolated runs.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the hostile-regex spec bounds the scan's CPU time, not the wall clock
"a slow pattern over ten thousand 200-character events stops at its budget" asserted
that the scan finished in under 2500 ms of wall-clock time. The scan is CPU-bound, and
the wall clock also counts every other worker of a parallel run, so the spec passed
alone (all 12 specs of the file in 316 ms) and failed in full runs, including both
tries of the smoke's step 14 on the previous HEAD. It now bounds the scan's CPU time
(process.cpuUsage) at the same 2500 ms and keeps a 30 s wall-clock bound as a guard
against a hang. The product code is untouched.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the host-boundary spec does not scan the mutation specs' temporary files
tui-boundary.spec.ts reads every .ts under hooks/ when it loads. adr-mutation and
mission-advisor-mutation make temporary .mut-N-*.ts copies of hooks modules inside
hooks/ and delete them, in other workers of the same run. Two ways that disturbs this
spec: a copy that is still there is checked as if it were a hooks module (shown with a
throwaway .mut- file that imports a Node module: the spec failed before this change,
passes after), and a copy listed and then deleted can throw at load, which fails the
whole file (the smoke's step 14 showed one such file-level failure that did not repeat;
six runs of the three specs together did not reproduce it, so that part is the likely
cause, not a demonstrated one).
The walk skips .mut- names and tolerates a file that vanishes. A real violation in
hooks/ is still caught (checked with a throwaway file).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): the mod loads again: $.env.get takes a literal name
An earlier commit on this branch (f54772424) gave the host an `env` read that was
`async name => $.env.get(name)`. The engine lists the variables a module reads, so
`claude plugin validate` refuses a computed name:
$.env.get takes a literal name as its first argument ...
and when it refuses register.ts the mod does not load at all: no /ruflo command, no
pane. Vitest never runs the engine's validator, so no test caught it; it showed up
when the branch was installed into a real Claude Code.
- register.ts reads only the one key it can name literally,
$.env.get('OPENROUTER_API_KEY'); any other name answers undefined.
- wf-send says, for a custom endpoint key on Windows, that it cannot be read here and
that only $OPENROUTER_API_KEY can, instead of claiming the variable is unset. The
OpenRouter key keeps the "is not set" wording.
- tui-boundary.spec.ts: no $.env.get/set in hooks/ may take a non-literal name (fails on
the old line, passes on the fix).
- smoke.sh step 21 runs `claude plugin validate` on the plugin when the CLI is present
(passes now; reports "Validation failed" against the old line).
- CHANGELOG corrected: it described the broken behaviour.
Verified with the real validator: before, "Found 1 error"; after, "Validation passed",
and the hook list shows command.run{command=ruflo}. The 9 "gating hook without .catch"
notes it prints are identical on upstream/main.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): specs remove their temp folder with a retry, so a still-exiting child does not fail the file on Windows
After the merge, tui-actions.spec.ts was reported as a failed FILE with all 8 of its
tests passing:
EBUSY: resource busy or locked, rmdir '...\tui-actions-XXXX\project'
On Windows a folder cannot be deleted while a process started in it is still running,
and these specs start the stand-in CLI and terminal sessions with the project folder as
their working directory. force: true does not cover EBUSY, and neither does maxRetries
on rmSync: measured on Node 22 with a child holding the folder for 1.2 s, rmSync fails
in 3 ms with or without maxRetries, while fs.promises.rm with maxRetries (and a manual
loop) removes it after about a second.
- tests/fixtures/rm-tree.ts: removeTree(), the async rm with up to ~5 s of retries.
- The ten specs that start processes or sessions in their temp folder (tui-actions,
tui-ai-host, tui-ai-page, tui-host, tui-nav, tui-pagebar, tui-parity, tui-pictures,
tui-session, wf-control-windows) use it in afterAll.
- tests/rm-tree.spec.ts: removes a tree and an already-gone one; on Windows, a real child
holding the folder makes rmSync fail with EBUSY and removeTree wait it out.
All eleven files pass.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
---------
Co-authored-by: RuFlo <ruv@ruv.net>
114 lines
7.2 KiB
JavaScript
114 lines
7.2 KiB
JavaScript
#!/usr/bin/env node
|
|
// cost-ledger — one cost view across Claude Code, Codex and Grok logs on this machine.
|
|
//
|
|
// node ledger.mjs [--since 7d|24h|all] [--provider claude|codex|grok|all] [--format json|markdown] [--advise]
|
|
// --advise adds the optimisation findings (advise.mjs) from the same single pass over the logs.
|
|
// --from <ISO> --to <ISO> --project </abs/path> narrow the rows to a time window (inclusive) and to one project
|
|
// (row.project is the path or inside it); JSON then carries `window`. A bad ISO time or a relative path exits 2.
|
|
//
|
|
// Reads local logs only; sends nothing anywhere. Prices come from data/prices.json
|
|
// (dated). USD and Codex credits are NEVER added together, and an unpriced model
|
|
// is listed, not counted as $0.
|
|
|
|
import { collect } from './_ledger.mjs';
|
|
import { priceUsage, bookDate } from './_pricebook.mjs';
|
|
import { parseDurationMs } from './_sessions.mjs';
|
|
import { advise } from './advise.mjs';
|
|
import { pathToFileURL } from 'node:url';
|
|
|
|
const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : fallback; };
|
|
|
|
/** Aggregate priced rows. Exported so advise.mjs and tests share one definition. */
|
|
export function summarise(rows) {
|
|
const out = { totals: {}, byProvider: {}, byModel: {}, byDay: {}, unpriced: {}, approx: [], cache: {}, rows: rows.length };
|
|
const add = (bucket, key, unit, cost) => { bucket[key] ??= {}; bucket[key][unit] = (bucket[key][unit] ?? 0) + cost; };
|
|
const tok = (bucket, key, row) => {
|
|
const t = (bucket[key] ??= { input: 0, cache_read: 0, cache_write: 0, output: 0, messages: 0 });
|
|
t.input += row.input; t.cache_read += row.cache_read; t.cache_write += row.cache_write_5m + row.cache_write_1h; t.output += row.output; t.messages += 1;
|
|
};
|
|
const tokens = {};
|
|
const approx = new Set();
|
|
for (const row of rows) {
|
|
const p = priceUsage(row.model, row, row.provider);
|
|
const day = new Date(row.ts).toISOString().slice(0, 10);
|
|
tok(tokens, `${row.provider}|${row.model}`, row);
|
|
if (!p.priced) { const u = (out.unpriced[row.model] ??= { provider: row.provider, messages: 0, tokens: 0 }); u.messages += 1; u.tokens += row.input + row.cache_read + row.output; continue; }
|
|
if (p.approx) approx.add(row.model);
|
|
add(out.byProvider, row.provider, p.unit, p.cost);
|
|
add(out.byModel, `${row.provider}|${row.model}`, p.unit, p.cost);
|
|
add(out.byDay, day, p.unit, p.cost);
|
|
out.totals[p.unit] = (out.totals[p.unit] ?? 0) + p.cost;
|
|
}
|
|
out.approx = [...approx];
|
|
out.tokens = tokens;
|
|
for (const provider of new Set(rows.map(row => row.provider))) {
|
|
const mine = rows.filter(row => row.provider === provider);
|
|
const read = mine.reduce((sum, row) => sum + row.cache_read, 0);
|
|
const fresh = mine.reduce((sum, row) => sum + row.input + row.cache_write_5m + row.cache_write_1h, 0);
|
|
out.cache[provider] = { hitRatio: read + fresh > 0 ? read / (read + fresh) : null, read, fresh };
|
|
}
|
|
|
|
return out;
|
|
}
|
|
|
|
const money = (value, unit) => (unit === 'usd' ? `$${value.toFixed(2)}` : `${value.toFixed(0)} credits`);
|
|
|
|
function markdown(summary, meta) {
|
|
const lines = [`# Cost ledger (${meta.since}, prices as of ${meta.priceDate})`, ''];
|
|
lines.push(`Totals: ${Object.entries(summary.totals).map(([unit, value]) => money(value, unit)).join(' + ') || 'n/a'} · ${summary.rows} messages · estimates at list price, not bills`, '');
|
|
lines.push('| Provider · model | Cost | Msgs | Input | Cache read | Cache write | Output |', '|---|---|---|---|---|---|---|');
|
|
for (const [key, cost] of Object.entries(summary.byModel).sort((a, b) => Object.values(b[1])[0] - Object.values(a[1])[0])) {
|
|
const t = summary.tokens[key];
|
|
lines.push(`| ${key.replaceAll('|', ' · ')} | ${Object.entries(cost).map(([unit, value]) => money(value, unit)).join(', ')} | ${t.messages} | ${t.input} | ${t.cache_read} | ${t.cache_write} | ${t.output} |`);
|
|
}
|
|
for (const [provider, cache] of Object.entries(summary.cache)) lines.push('', `Cache hit ratio · ${provider}: ${cache.hitRatio === null ? 'n/a' : `${(cache.hitRatio * 100).toFixed(1)}%`}`);
|
|
const dark = Object.entries(summary.unpriced);
|
|
if (dark.length > 0) lines.push('', `Unpriced (NOT counted as $0): ${dark.map(([model, u]) => `${model} (${u.messages} msgs)`).join(', ')} — add them to data/prices.json`);
|
|
if (summary.approx.length > 0) lines.push('', `Approximate (family fallback or list price; Grok subscription billing may differ): ${summary.approx.join(', ')}`);
|
|
lines.push('', 'Claude output tokens come from the transcript, which can under-count streamed output; /usage is authoritative for the live session.');
|
|
|
|
return lines.join('\n');
|
|
}
|
|
|
|
const bad = message => { console.error(`ledger: ${message}`); process.exit(2); };
|
|
|
|
/** An ISO time as epoch ms; anything else (relative words, bare numbers, a missing value) exits 2. */
|
|
function isoMs(name) {
|
|
const value = arg(name);
|
|
if (value === undefined || !/^\d{4}-\d{2}-\d{2}/.test(value) || !Number.isFinite(Date.parse(value))) bad(`--${name} needs an ISO time such as 2026-10-04T09:30:00Z`);
|
|
|
|
return Date.parse(value);
|
|
}
|
|
|
|
/** An absolute path (POSIX, or drive-lettered on Windows) with no control characters or `..`; anything else exits 2. */
|
|
function absolutePath(name) {
|
|
const value = arg(name);
|
|
const isWindows = typeof value === 'string' && /^[A-Za-z]:[\\/]/.test(value);
|
|
if (typeof value !== 'string' || !(value.startsWith('/') || isWindows) || /[\u0000-\u001f\u007f]/.test(value) || value.split(isWindows ? /[\\/]/ : '/').includes('..')) bad(`--${name} needs an absolute path with no '..'`);
|
|
|
|
return value;
|
|
}
|
|
|
|
// pathToFileURL, not `file://${argv[1]}`: on Windows import.meta.url is file:///C:/... and argv[1] is C:..., so the string never matched and the script printed nothing.
|
|
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
const given = name => process.argv.includes(`--${name}`);
|
|
const fromMs = given('from') ? isoMs('from') : null;
|
|
const toMs = given('to') ? isoMs('to') : null;
|
|
const project = given('project') ? absolutePath('project') : null;
|
|
if (fromMs !== null && toMs !== null && fromMs > toMs) bad('--from is after --to');
|
|
const windowed = fromMs !== null || toMs !== null || project !== null;
|
|
|
|
// An explicit window replaces the default 7-day look-back; an explicit --since still narrows it.
|
|
const sinceSpec = given('since') || !windowed ? arg('since', '7d') : 'window';
|
|
const spanMs = sinceSpec === 'all' || sinceSpec === 'window' ? 0 : Date.now() - (parseDurationMs(sinceSpec) ?? 7 * 86_400_000);
|
|
const sinceMs = Math.max(spanMs, fromMs ?? 0);
|
|
const providers = arg('provider', 'all') === 'all' ? undefined : [arg('provider')];
|
|
const rows = collect({ providers, sinceMs, ...(toMs !== null && { untilMs: toMs }), ...(project !== null && { project }) });
|
|
const summary = summarise(rows);
|
|
const meta = { since: sinceSpec, priceDate: bookDate() };
|
|
const findings = process.argv.includes('--advise') ? advise(rows) : undefined;
|
|
const window = windowed ? { window: { from: fromMs === null ? null : new Date(fromMs).toISOString(), to: toMs === null ? null : new Date(toMs).toISOString(), project } } : {};
|
|
|
|
console.log(arg('format', 'markdown') === 'json' ? JSON.stringify({ ...meta, ...summary, ...window, ...(findings && { findings }) }, null, 2) : markdown(summary, meta));
|
|
}
|