🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-console): mission spend (ledger --from/--to/--project, mission-cost module and rows)
ruv718ab608b432
diff --git a/plugins/ruflo-console/hooks/data/mission-cost.ts b/plugins/ruflo-console/hooks/data/mission-cost.tsnew file mode 100644index 0000000000..62594a7606--- /dev/null+++ b/plugins/ruflo-console/hooks/data/mission-cost.ts@@ -0,0 +1,74 @@+/**+ * Mission spend (ADR-443 §2.3). The console asks the ruflo-cost-tracker plugin's `ledger.mjs` for the spend inside a+ * mission's time window and project, and compares it with an optional USD cap on the ADR-437 ladder (50, 75, 90, 100+ * percent of the cap). Pure: it builds the command and reads the answer; the probe runner does the running. Local only,+ * and USD and Codex credits are never added together; a model without a price is listed, never counted as $0.+ */+import { budgetAmount, ladderDollars } from '../cost'+import { jsonAfter } from './cli'+import { safeInstallPath } from './cost-ledger'+import { numberOf, plain, recordOf } from './parse'++export type MissionCost = { usd: number | null; credits: number | null; unpriced: string[]; rows: number }+export type CapLevel = 'none' | 'OK' | 'INFO' | 'WARNING' | 'CRITICAL' | 'HARD_STOP'+export type CapState = { level: CapLevel; percent: number | null }++/** An absolute POSIX path: no control characters, no `..` segment. It is one argv element, never part of a shell line. */+const safeProject = (value: unknown): string | undefined => {+ const path = typeof value === 'string' ? value : ''++ return path.startsWith('/') && path.length <= 500 && !/[\u0000-\u001f\u007f-\u009f]/.test(path) && !path.split('/').includes('..') ? path : undefined+}++/**+ * The ledger command for one mission: its window (`fromMs`, and `toMs` once it has ended) in its `project`. `null` when+ * the plugin root or the project fails the path checks, or a time is not a real instant. A mission still running has+ * `toMs === null`, so no `--to` is sent and the window stays open at the right.+ */+export function missionCostArgv(root: string, fromMs: number, toMs: number | null, project: string): readonly string[] | null {+ const base = safeInstallPath(root)+ const where = safeProject(project)+ const iso = (ms: number): string | undefined => (Number.isFinite(ms) && Math.abs(ms) < 8.64e15 ? new Date(ms).toISOString() : undefined)+ const from = iso(fromMs)+ const to = toMs === null ? null : iso(toMs)++ if (base === undefined || where === undefined || from === undefined || to === undefined) return null+ if (to !== null && Date.parse(to) < Date.parse(from)) return null++ return ['node', `${base}/scripts/ledger.mjs`, '--format', 'json', '--from', from, ...(to === null ? [] : ['--to', to]), '--project', where]+}++/** What `ledger.mjs --format json` printed for the window. A total that is missing is `null` (unknown), not zero. */+export function parseMissionCost(stdout: string): MissionCost | null {+ const value = recordOf(jsonAfter(stdout))+ const totals = recordOf(value?.totals)++ if (value === null || totals === null) return null++ const rows = Math.max(0, Math.floor(numberOf(value.rows) ?? 0))+ const usd = numberOf(totals.usd)+ const credits = numberOf(totals.credits)++ return {+ // No rows at all is a true $0; rows that are all unpriced leave the total unknown, which is not the same thing.+ usd: usd !== undefined && usd >= 0 ? usd : rows === 0 ? 0 : null,+ credits: credits !== undefined && credits >= 0 ? credits : null,+ unpriced: Object.keys(recordOf(value.unpriced) ?? {}).slice(0, 10).map(name => plain(name, 50)),+ rows,+ }+}++/** Where `spendUsd` sits on the ladder of `cap`; `none` without a spend or a cap. `percent` is the share of the cap used. */+export function capState(spendUsd: number | null, cap: number | null): CapState {+ if (spendUsd === null || cap === null || !Number.isFinite(spendUsd) || !Number.isFinite(cap) || cap <= 0 || spendUsd < 0) return { level: 'none', percent: null }++ const reached = ladderDollars(cap).filter(rung => rung.usd !== null && spendUsd >= rung.usd).at(-1)++ return { level: (reached?.level as CapLevel | undefined) ?? 'OK', percent: spendUsd / cap * 100 }+}++/** Auto-run stops at the cap, and only when auto-run is on: a warning level never pauses anything. */+export const shouldPause = (state: CapState, autoRun: boolean): boolean => autoRun && state.level === 'HARD_STOP'++/** A cap typed by the person: 0.01 to 10000 dollars, decimal digits only (same rule as the budget setter). */+export const capUsd = (text: string): number | null => budgetAmount(text)diff --git a/plugins/ruflo-console/hooks/views/mission-cost.ts b/plugins/ruflo-console/hooks/views/mission-cost.tsnew file mode 100644index 0000000000..034fb7641a--- /dev/null+++ b/plugins/ruflo-console/hooks/views/mission-cost.ts@@ -0,0 +1,38 @@+import type { RenderElement } from 'claude-code'++import type { MissionCost } from '../data/mission-cost'+import { capState } from '../data/mission-cost'+import { kv, rule, text, THEME, type Ctx } from './common'+import { ladder } from './cost'+import { moneyText } from './cost-providers'++/** The host clips a line at 60 columns; these notes stay shorter so nothing is cut mid-word. */+const LINE = 49+const short = (value: string): string => (value.length > LINE ? `${value.slice(0, LINE - 1)}…` : value)++const COLOR = { none: undefined, OK: THEME.ok, INFO: THEME.info, WARNING: THEME.warn, CRITICAL: THEME.warn, HARD_STOP: THEME.bad } as const++/** What the mission has spent, against its cap when it has one. `n/a` when the ledger did not answer. */+export function missionCostRows(ctx: Ctx, cost: MissionCost | null, cap: number | null, sourceNote: string): RenderElement[] {+ const rows = [rule(ctx, 'Mission spend', 'list-price estimate')]++ rows.push(kv(ctx, 'spend', cost === null || cost.usd === null ? 'n/a' : moneyText({ usd: cost.usd })))+ if (cost !== null && cost.credits !== null) rows.push(kv(ctx, 'Codex', moneyText({ credits: cost.credits })))+ rows.push(kv(ctx, 'cap', cap === null ? 'none set' : `$${cap.toFixed(2)}`))++ const state = capState(cost?.usd ?? null, cap)++ if (cap !== null && cost !== null && cost.usd !== null) {+ rows.push(text(ctx, ` ${ladder(cost.usd, cap, Math.min(30, Math.max(10, ctx.columns - 24)))} ${state.level} ${Math.round(state.percent ?? 0)}%`, { color: COLOR[state.level] }))+ rows.push(text(ctx, ' Marks: 50, 75, 90, 100% of the cap.', { dimColor: true }))+ }++ if (cost !== null && cost.unpriced.length > 0) rows.push(text(ctx, short(` Unpriced, not $0: ${cost.unpriced.join(', ')}`), { color: THEME.warn }))+ if (cost !== null && cost.usd === null && cost.rows > 0) rows.push(text(ctx, ' Every model here is unpriced.', { dimColor: true }))++ rows.push(text(ctx, short(` ${sourceNote}`), { dimColor: true }))+ rows.push(text(ctx, ' A list-price estimate, not a bill.', { dimColor: true }))+ rows.push(text(ctx, ' USD and credits are never added together.', { dimColor: true }))++ return rows+}diff --git a/plugins/ruflo-console/tests/mission-cost.spec.ts b/plugins/ruflo-console/tests/mission-cost.spec.tsnew file mode 100644index 0000000000..be1e0e2c2f--- /dev/null+++ b/plugins/ruflo-console/tests/mission-cost.spec.ts@@ -0,0 +1,186 @@+import { spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++import { describe, expect, it } from 'vitest'++import { capState, capUsd, missionCostArgv, parseMissionCost, shouldPause } from '../hooks/data/mission-cost'+import { newState } from '../hooks/state'+import { missionCostRows } from '../hooks/views/mission-cost'+import type { Ctx } from '../hooks/views/common'++const ROOT = '/p/ruflo-cost-tracker/0.28.0'+const FROM = Date.parse('2026-10-02T00:00:00Z')+const TO = Date.parse('2026-10-03T00:00:00Z')++const LEDGER = (extra: Record<string, unknown> = {}): string => JSON.stringify({ since: 'window', priceDate: '2026-10-03', rows: 4, totals: { usd: 12.5, credits: 300 }, byProvider: {}, unpriced: {}, window: { from: null, to: null, project: '/p' }, ...extra })++describe('missionCostArgv', () => {+ it('builds the fixed ledger command with an ISO window and the project', () => {+ expect(missionCostArgv(ROOT, FROM, TO, '/home/u/proj')).toEqual(['node', `${ROOT}/scripts/ledger.mjs`, '--format', 'json', '--from', '2026-10-02T00:00:00.000Z', '--to', '2026-10-03T00:00:00.000Z', '--project', '/home/u/proj'])+ })++ it('leaves the window open on the right while the mission runs', () => {+ const argv = missionCostArgv(ROOT, FROM, null, '/home/u/proj')++ expect(argv).not.toContain('--to')+ expect(argv).toContain('--from')+ })++ it('is null for a hostile plugin root, a relative or traversing project, control characters, or a bad window', () => {+ for (const root of ['relative', '/a/../b', '/x; rm -rf', '']) expect(missionCostArgv(root, FROM, TO, '/p')).toBeNull()+ for (const project of ['proj', '', '/a/../etc', '/a\nb', '/a\u0000b', '/a\u001b[31m', `/${'a'.repeat(600)}`]) expect(missionCostArgv(ROOT, FROM, TO, project)).toBeNull()+ expect(missionCostArgv(ROOT, Number.NaN, TO, '/p')).toBeNull()+ expect(missionCostArgv(ROOT, FROM, Number.POSITIVE_INFINITY, '/p')).toBeNull()+ expect(missionCostArgv(ROOT, TO, FROM, '/p')).toBeNull()+ })+})++describe('parseMissionCost', () => {+ it('keeps USD and credits apart and lists unpriced models', () => {+ expect(parseMissionCost(LEDGER({ unpriced: { 'gpt-5.6-sol': { messages: 3 } } }))).toEqual({ usd: 12.5, credits: 300, unpriced: ['gpt-5.6-sol'], rows: 4 })+ })++ it('treats a window with no rows as a real zero, but all-unpriced rows as unknown', () => {+ expect(parseMissionCost(LEDGER({ rows: 0, totals: {} }))).toMatchObject({ usd: 0, credits: null, rows: 0 })+ expect(parseMissionCost(LEDGER({ rows: 2, totals: {}, unpriced: { 'mystery-9': {} } }))).toMatchObject({ usd: null, unpriced: ['mystery-9'] })+ })++ it('is null for anything that is not the ledger, and strips control text from model names', () => {+ for (const bad of ['', 'nope', '{"a":1}', '[]', '{"totals":1}']) expect(parseMissionCost(bad)).toBeNull()+ expect(parseMissionCost(LEDGER({ unpriced: { 'm\u001b[31mx\nmodel': {} } }))?.unpriced[0]).toBe('mx model')+ })++ it('ignores negative or non-numeric totals', () => {+ expect(parseMissionCost(LEDGER({ totals: { usd: -4, credits: 'x' } }))).toMatchObject({ usd: null, credits: null })+ })+})++describe('capState and shouldPause', () => {+ it('follows the 50/75/90/100 ladder', () => {+ const at = (spend: number) => capState(spend, 10).level++ expect([at(0), at(4.99), at(5), at(7.49), at(7.5), at(8.99), at(9), at(9.99), at(10), at(25)]).toEqual(['OK', 'OK', 'INFO', 'INFO', 'WARNING', 'WARNING', 'CRITICAL', 'CRITICAL', 'HARD_STOP', 'HARD_STOP'])+ expect(capState(2.5, 10).percent).toBe(25)+ expect(capState(25, 10).percent).toBe(250)+ })++ it('is none without a spend or a usable cap', () => {+ for (const [spend, cap] of [[null, 10], [3, null], [null, null], [3, 0], [3, -1], [Number.NaN, 10], [-1, 10], [3, Number.POSITIVE_INFINITY]] as const) expect(capState(spend, cap)).toEqual({ level: 'none', percent: null })+ })++ it('pauses only at the hard stop with auto-run on', () => {+ expect(shouldPause(capState(10, 10), true)).toBe(true)+ expect(shouldPause(capState(10, 10), false)).toBe(false)+ expect(shouldPause(capState(9.5, 10), true)).toBe(false)+ expect(shouldPause(capState(null, 10), true)).toBe(false)+ expect(shouldPause(capState(10, null), true)).toBe(false)+ })+})++describe('capUsd', () => {+ it('accepts 0.01 to 10000 as plain decimals and nothing else', () => {+ expect([capUsd('0.01'), capUsd(' 25 '), capUsd('.5'), capUsd('10000')]).toEqual([0.01, 25, 0.5, 10_000])+ for (const bad of ['', '0', '0.009', '10000.01', '-5', '1e3', '$5', '5usd', '0x10', 'NaN', 'Infinity', '1,5']) expect(capUsd(bad)).toBeNull()+ })+})++type Node = { type: string; props: { children?: unknown } }+const kit = (): Ctx['kit'] => {+ const element = (type: string) => (props: Record<string, unknown>) => ({ type, props }) as never++ return { Box: element('Box'), Text: element('Text'), Button: element('Button') }+}+const flat = (node: unknown): string => {+ if (typeof node === 'string' || typeof node === 'number') return String(node)+ if (node === null || node === undefined || typeof node === 'boolean') return ''+ if (Array.isArray(node)) return node.map(flat).join('')++ return flat((node as Node).props.children)+}+const shown = (cost: ReturnType<typeof parseMissionCost>, cap: number | null, note = 'ledger: cost-tracker plugin'): string[] => missionCostRows({ kit: kit(), state: newState({}), nowMs: 5, columns: 110, pictures: new Map(), act: {} } as unknown as Ctx, cost, cap, note).map(flat)++describe('missionCostRows', () => {+ it('shows spend, cap and the ladder, and says it is an estimate', () => {+ const lines = shown({ usd: 8, credits: null, unpriced: [], rows: 3 }, 10)+ const all = lines.join('\n')++ expect(all).toContain('Mission spend')+ expect(all).toContain('$8.00')+ expect(all).toContain('$10.00')+ expect(all).toContain('WARNING')+ expect(all).toContain('80%')+ expect(all).toContain('list-price')+ expect(all).toMatch(/not a bill/)+ })++ it('is n/a when the ledger did not answer, and never draws a bar', () => {+ const all = shown(null, 10).join('\n')++ expect(all).toMatch(/spend\s*n\/a/)+ expect(all).not.toContain('WARNING')+ expect(all).not.toContain('█')+ })++ it('shows no bar without a cap, lists unpriced models and keeps credits separate', () => {+ const all = shown({ usd: 1, credits: 40, unpriced: ['mystery-9'], rows: 2 }, null).join('\n')++ expect(all).toMatch(/cap\s*none set/)+ expect(all).toContain('mystery-9')+ expect(all).toContain('40 credits')+ expect(all).not.toContain('█')+ })++ it('keeps every note and disclaimer under 50 characters, even for a long source note or model list', () => {+ const lines = shown({ usd: 1, credits: null, unpriced: ['m'.repeat(50), 'n'.repeat(50)], rows: 1 }, null, 'x'.repeat(200))+ const notes = lines.filter(line => /^ (?!Marks)/.test(line) && !line.includes('Mission spend'))++ expect(notes.length).toBeGreaterThan(2)+ for (const line of notes) expect(line.length, line).toBeLessThan(50)+ })+})++describe('the ledger filters, through the real script', () => {+ const win = mkdtempSync(join(tmpdir(), 'mission-cost-'))+ const logs = join(win, 'claude', 'projects', 'q')++ mkdirSync(logs, { recursive: true })+ mkdirSync(join(win, 'codex'), { recursive: true })++ const at = (iso: string, id: string, cwd: string) => ({ type: 'assistant', sessionId: `s-${id}`, cwd, requestId: `r-${id}`, timestamp: iso, message: { id, role: 'assistant', model: 'claude-opus-5-5', usage: { input_tokens: 1_000_000, output_tokens: 0 } } })++ writeFileSync(join(logs, 'w.jsonl'), [+ at('2026-10-01T00:00:00.000Z', 'before', '/proj/a'),+ at('2026-10-02T06:00:00.000Z', 'in-a', '/proj/a'),+ at('2026-10-02T07:00:00.000Z', 'in-sub', '/proj/a/sub'),+ at('2026-10-02T08:00:00.000Z', 'sibling', '/proj/ab'),+ at('2026-10-02T09:00:00.000Z', 'in-b', '/proj/b'),+ at('2026-10-04T00:00:00.000Z', 'after', '/proj/a'),+ ].map(item => JSON.stringify(item)).join('\n') + '\n')++ const ledgerRoot = resolve(__dirname, '../../ruflo-cost-tracker')+ const run = (project: string, toMs: number | null) => {+ const argv = missionCostArgv(ledgerRoot, FROM, toMs, project)++ if (argv === null) return null++ const out = spawnSync(process.execPath, argv.slice(1), { encoding: 'utf-8', env: { PATH: process.env.PATH ?? '', CLAUDE_CONFIG_DIR: join(win, 'claude'), CODEX_HOME: join(win, 'codex') } })++ return { status: out.status, cost: parseMissionCost(out.stdout) }+ }++ it('counts only the project and its subdirectories inside the window', () => {+ const result = run('/proj/a', TO)++ expect(result?.status).toBe(0)+ expect(result?.cost?.rows).toBe(2) // in-a and in-sub; not before, not /proj/ab, not /proj/b+ expect(result?.cost?.usd).toBeGreaterThan(0)+ })++ it('leaves the window open when the mission has not ended, and a different project gets its own spend', () => {+ expect(run('/proj/a', null)?.cost?.rows).toBe(3) // adds the row after the old end+ expect(run('/proj/b', TO)?.cost?.rows).toBe(1)+ expect(run('/proj/none', TO)?.cost).toMatchObject({ rows: 0, usd: 0 })+ })+})diff --git a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs b/plugins/ruflo-cost-tracker/scripts/_ledger.mjsindex cb569e4f4a..693ed06b82 100644--- a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs+++ b/plugins/ruflo-cost-tracker/scripts/_ledger.mjs@@ -133,10 +133,22 @@ export function* codexRows({ sinceMs = 0 } = {}) {export const READERS = { claude: claudeRows, codex: codexRows };-/** Rows for the chosen providers (default all), oldest first. */-export function collect({ providers = Object.keys(READERS), sinceMs = 0 } = {}) {+/** True when `row.project` is `project` itself or a directory inside it (a trailing slash on `project` is ignored). */+export function inProject(row, project) {+ const root = project.length > 1 ? project.replace(/\/+$/, '') : project;+ const at = typeof row.project === 'string' ? row.project : '';++ return at === root || at.startsWith(`${root}/`);+}++/**+ * Rows for the chosen providers (default all), oldest first. `untilMs` (inclusive) and `project` narrow the window;+ * with neither, the result is exactly what it was before they existed.+ */+export function collect({ providers = Object.keys(READERS), sinceMs = 0, untilMs = Infinity, project = '' } = {}) {const rows = [];for (const name of providers) if (READERS[name]) rows.push(...READERS[name]({ sinceMs }));+ const kept = untilMs === Infinity && project === '' ? rows : rows.filter(row => row.ts <= untilMs && (project === '' || inProject(row, project)));- return rows.sort((a, b) => a.ts - b.ts);+ return kept.sort((a, b) => a.ts - b.ts);}diff --git a/plugins/ruflo-cost-tracker/scripts/ledger.mjs b/plugins/ruflo-cost-tracker/scripts/ledger.mjsindex e8f03c7143..52d0e84b5e 100644--- a/plugins/ruflo-cost-tracker/scripts/ledger.mjs+++ b/plugins/ruflo-cost-tracker/scripts/ledger.mjs@@ -3,6 +3,8 @@//// node ledger.mjs [--since 7d|24h|all] [--provider claude|codex|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@@ -67,14 +69,42 @@ function markdown(summary, meta) {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 POSIX path with no control characters or `..`; anything else exits 2. */+function absolutePath(name) {+ const value = arg(name);+ if (typeof value !== 'string' || !value.startsWith('/') || /[\u0000-\u001f\u007f]/.test(value) || value.split('/').includes('..')) bad(`--${name} needs an absolute path with no '..'`);++ return value;+}+if (import.meta.url === `file://${process.argv[1]}`) {- const sinceSpec = arg('since', '7d');- const sinceMs = sinceSpec === 'all' ? 0 : Date.now() - (parseDurationMs(sinceSpec) ?? 7 * 86_400_000);+ 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 });+ 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, ...(findings && { findings }) }, null, 2) : markdown(summary, meta));+ console.log(arg('format', 'markdown') === 'json' ? JSON.stringify({ ...meta, ...summary, ...window, ...(findings && { findings }) }, null, 2) : markdown(summary, meta));}diff --git a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjsindex 91c5d4ba0b..6300da9618 100644--- a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs+++ b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs@@ -95,5 +95,59 @@ test('openrouter: a key in the environment is never echoed', () => {assert.ok(!(r.stdout + r.stderr).includes('SECRET123'));});+// ── Window and project filters, through the real script, on their own fixture logs.+const win = mkdtempSync(join(tmpdir(), 'ledger-window-'));+mkdirSync(join(win, 'claude', 'projects', 'q'), { recursive: true });+mkdirSync(join(win, 'codex'), { recursive: true });+const at = (iso, id, cwd) => ({ type: 'assistant', sessionId: `s-${id}`, cwd, requestId: `r-${id}`, timestamp: iso, message: { id, role: 'assistant', model: 'claude-opus-5-5', usage: { input_tokens: 1000, output_tokens: 0 } } });+jsonl(join(win, 'claude', 'projects', 'q', 'w.jsonl'), [+ at('2026-10-01T00:00:00.000Z', 'before', '/proj/a'),+ at('2026-10-02T00:00:00.000Z', 'start', '/proj/a'), // exactly on --from: inclusive+ at('2026-10-02T12:00:00.000Z', 'sub', '/proj/a/sub'),+ at('2026-10-02T13:00:00.000Z', 'sibling', '/proj/ab'), // shares the prefix text, not the directory+ at('2026-10-02T14:00:00.000Z', 'other', '/proj/b'),+ at('2026-10-03T00:00:00.000Z', 'end', '/proj/a'), // exactly on --to: inclusive+ at('2026-10-04T00:00:00.000Z', 'after', '/proj/a'),+]);+const ledger = (...flags) => {+ const r = spawnSync(process.execPath, [join(HERE, 'ledger.mjs'), '--format', 'json', ...flags], { encoding: 'utf-8', env: { PATH: process.env.PATH, CLAUDE_CONFIG_DIR: join(win, 'claude'), CODEX_HOME: join(win, 'codex') } });++ return { ...r, json: r.status === 0 ? JSON.parse(r.stdout) : null };+};+const FROM = '2026-10-02T00:00:00Z';+const TO = '2026-10-03T00:00:00Z';++test('window: --from/--to keep rows inside the window, both ends inclusive, in every project', () => {+ const r = ledger('--from', FROM, '--to', TO);+ assert.equal(r.json.rows, 5);+ assert.deepEqual(r.json.window, { from: '2026-10-02T00:00:00.000Z', to: '2026-10-03T00:00:00.000Z', project: null });+});+test('window: a --from older than 7 days is honoured (it replaces the default look-back)', () => assert.equal(ledger('--from', '2026-10-01T00:00:00Z').json.rows, 7));+test('window: --project matches the path and its subdirectories, not a sibling sharing the prefix', () => {+ const r = ledger('--from', FROM, '--to', TO, '--project', '/proj/a');+ assert.equal(r.json.rows, 3); // start, sub, end — not /proj/ab, not /proj/b+ assert.equal(r.json.window.project, '/proj/a');+});+test('window: a trailing slash on --project is ignored; --project alone has no time limit', () => {+ assert.equal(ledger('--project', '/proj/a/').json.rows, 5);+ assert.equal(ledger('--project', '/proj/b').json.rows, 1);+});+test('window: the JSON keeps every existing field', () => {+ const r = ledger('--from', FROM, '--project', '/proj/a');+ for (const key of ['since', 'priceDate', 'totals', 'byProvider', 'byModel', 'byDay', 'unpriced', 'approx', 'cache', 'rows', 'tokens']) assert.ok(key in r.json, key);+});+test('window: without the flags the output has no window and counts every row', () => {+ const r = ledger('--since', 'all');+ assert.equal(r.json.rows, 7);+ assert.ok(!('window' in r.json));+});+test('window: an invalid ISO time, a missing value, or a relative path exits 2 with a message', () => {+ for (const flags of [['--from', 'yesterday'], ['--to', '5'], ['--from'], ['--project', 'proj/a'], ['--project', '/proj/../etc'], ['--from', TO, '--to', FROM]]) {+ const r = ledger(...flags);+ assert.equal(r.status, 2, flags.join(' '));+ assert.match(r.stderr, /^ledger: /, flags.join(' '));+ }+});+if (failed > 0) { console.log(`\n${failed} failed`); process.exit(1); }console.log('\nall passed');