Exported functions in state/lib/freshbooks.ts. .md file to compare - side-by-side diff against freshbooks
freshbooks
description: "Triggers on prompt mention of 'freshbooks'."
What it does for you
Connects your assistant to your FreshBooks invoices and bookkeeping.
What it produces
A recent result, so you can see the kind of work it returns.
loading…
How to get it
These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.
For developers how this skill is built, graded, and how it runs
at a glance- the short version
what's inside - the parts that make up a skill 3/4 present
A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.
state/skills/freshbooks/SKILL.md
present
state/lib/freshbooks.ts
present
state/bin/freshbooks/
not present
state/skills/freshbooks/AGENTS.md
present
how it's graded - what counts as a good run 4 criteria · 3 deterministic · 1 judge
Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.
how it runs - the shared frame every skill uses 5/5 present
Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.
state/log/pending-eval.ndjson what it has learned - fixes written back in over time sample
When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.
- Loading feedback rows…
how the work flows- who makes it, who checks it
import from `state/lib/freshbooks.ts` — read: `listClients`, `listInvoices`, `getOpenDraftsForClient`, `listOpenDrafts`, `getLastPaidInvoice`, `listTimeEntries`, `listExpenses`; write: `getOrCreateClient`, `draftCatchupInvoice`, `createInvoice`, `updateInvoice`, `sendInvoice`, `markPaid`, `createTimeEntry`, `createExpense
listOpenDrafts()` before any `createInvoice` to avoid duplicate drafts for the same client/period
SKILL.md- the skill, written out in plain English
freshbooks
FreshBooks operations via direct API for all snappy-* skills.
Ported from kernel snappy-freshbooks in Phase 0.5. See state/lib/freshbooks.ts for the full API surface.
Steps
listClients()- seestate/lib/freshbooks.tsgetOrCreateClient()- seestate/lib/freshbooks.tslistInvoices()- seestate/lib/freshbooks.tsgetOpenDraftsForClient()- seestate/lib/freshbooks.tslistOpenDrafts()- seestate/lib/freshbooks.tsgetLastPaidInvoice()- seestate/lib/freshbooks.tsdraftCatchupInvoice()- seestate/lib/freshbooks.tscreateInvoice()- seestate/lib/freshbooks.tsupdateInvoice()- seestate/lib/freshbooks.tssendInvoice()- seestate/lib/freshbooks.tsmarkPaid()- seestate/lib/freshbooks.tslistTimeEntries()- seestate/lib/freshbooks.tscreateTimeEntry()- seestate/lib/freshbooks.tslistExpenses()- seestate/lib/freshbooks.tscreateExpense()- seestate/lib/freshbooks.tscomputeFreshbooksMetric()- seestate/lib/freshbooks.ts
Eval
Actor: the exported functions in state/lib/freshbooks.ts. Auditor: none wired yet - eval is manual (Robert review). File a state/log/pending-eval.ndjson row on each run.
Score convention:
| Outcome | Score |
|---|---|
| Pass on first try | 1.0 |
| Failed first, auto-fix applied, re-check passed | 0.5 |
| Still failing or unrecoverable | 0.0 |
Gotchas
via the Phase 0.5 driver. Only these rewrites were applied: already in state/lib/)
realpathSync(process.argv[1])CLI guard wrapped in try/catch
- See the kernel SKILL.md for the original long-form guidance if you need it
(read-only reference at the kernel path above).
Graduation
This skill is prose. Graduate by defining a deterministic auditor and flipping eval: auto.
Rubric
criteria:
- name: api_surface_completeness
kind: deterministic
check: "The `state/lib/freshbooks.ts` file exports all specified functions: `listClients`, `getOrCreateClient`, `listInvoices`, `getOpenDraftsForClient`, `listOpenDrafts`, `getLastPaidInvoice`, `draftCatchupInvoice`, `createInvoice`, `updateInvoice`, `sendInvoice`, `markPaid`, `listTimeEntries`, `createTimeEntry`, `listExpenses`, `createExpense`, and `computeFreshbooksMetric`."
- name: input_schema_adherence
kind: deterministic
check: "The skill definition's `inputs` section accurately reflects the types required by the specified functions (e.g., `listClients_input`, `getOrCreateClient_input`, etc.) from `state/lib/freshbooks.ts`."
- name: freshbooks_api_connectivity
kind: judge
check: "Executing a basic query (e.g., `listClients()`) via the skill successfully connects to and retrieves data from the FreshBooks API without errors, indicating correct API key configuration and network access."
- name: deterministic_eval_readiness
kind: deterministic
check: "The skill has a defined `state/log/pending-eval.ndjson` row on execution, indicating activity that can be manually reviewed for graduation to a 'deterministic' eval."AGENTS.md- what the AI loads when this skill comes up
freshbooks - loader
Per-turn rules for the freshbooks skill. Full reference: state/skills/freshbooks/SKILL.md. Do not skip these.
Critical Rules
_(no failures recorded yet - this skill is a Phase 0.5 prose port from kernel snappy-freshbooks. No hard-won rules have surfaced yet. Read state/skills/freshbooks/SKILL.md and state/lib/freshbooks.ts before invoking.)_
Commands
| ui dashboard | state/skills/freshbooks/resources/ui.openui | |invoke: import from state/lib/freshbooks.ts - read: listClients, listInvoices, getOpenDraftsForClient, listOpenDrafts, getLastPaidInvoice, listTimeEntries, listExpenses; write: getOrCreateClient, draftCatchupInvoice, createInvoice, updateInvoice, sendInvoice, markPaid, createTimeEntry, createExpense |cli: npx tsx state/lib/freshbooks.ts <subcommand> - subcommands are clients|invoices|time-entries|expenses|create-invoice|send-invoice|mark-paid|log-time|log-expense. Note: it's invoices not listInvoices at the CLI; the TS function is listInvoices. Output is the raw FreshBooks JSON array. Invoice line items / descriptions are NOT in the response - pipe through python3 -c "import json,sys; ..." to get a flat summary, but to characterize what work an invoice covers, cross-reference Krisp meetings or local notes from that period. |verify: listOpenDrafts() before any createInvoice to avoid duplicate drafts for the same client/period |eval log: state/log/pending-eval.ndjson (manual eval - skill: "freshbooks")
OpenUI Resource
- Skill-owned OpenUI Lang resource:
state/skills/freshbooks/resources/ui.openui. Read it before rendering or editing this skill's generated component surface. - Treat this resource as a first-class artifact of the skill, not a generic chat response. Improve it when the skill's user-facing output needs to become richer.
- System resources compose OpenUI primitives and inherit SnappyChat tokens. Use
ui_contract: brandedin SKILL.md only for deliberate platform or client visuals.
Known Pitfalls
sendInvoiceandmarkPaidare irreversible side-effects - keep behind scope-only defaultgetOrCreateClientis idempotent but checklistClientsif naming is fuzzy - duplicates are painful to clean updraftCatchupInvoiceis the convenience fn for "client owes us catchup time" - prefer it over hand-stitchingcreateInvoice
Self-Test
An agent reading this should correctly:
- [ ] Check
listOpenDraftsbefore drafting a new invoice - [ ] Default
sendInvoiceandmarkPaidto scope-only - [ ] Use
draftCatchupInvoicefor catchup billing instead of rawcreateInvoice
Self-report
If this loader fell short, append a line:
echo "[$(date -u +%FT%TZ)] freshbooks: <what was missing>" >> state/log/loader-feedback.log
<!-- kernel-ok: historical attribution for the PID-loader pattern. -->
Self-correcting loader (PID feedback)
This is the rule that makes loaders learn. Ported from snappy-kernel, where it demonstrably worked: the snappy-dom-cartographer skill mapped Skool admin UI once, every later ship-agent inherited the full map for free.
Before you finish, do two things:
1. Fix gaps (P - proportional). MANDATORY. If this loader didn't cover your case - if you had to read another file, run an undocumented command, work around a wrong selector, or discover a quirk - you MUST attempt an Edit to this AGENTS.md before you log.
- Default action: edit this file. Surgical. Add the missing line, table
row, or code example where it belongs. No restructuring.
- Only
LOGGEDis allowed when: the fix needs >10 lines, spans multiple
files, or requires a structural rewrite. In that case the state/regen/drain.sh queue picks it up asynchronously.
- "I didn't have time" / "it's minor" / "the next agent will figure it out"
are NOT valid reasons. Minor gaps compound - that's the whole point of this loop.
- Concrete example of a valid P-fix: discover
agent-browser screenshot
takes path positionally not as --output <path>. One line in a table. Edit it in. Do not just log it.
- The goal: the next agent never has to leave the loader.
2. Log the result.
echo "[$(date -u +%FT%TZ)] freshbooks: <what was missing or fixed> [FIXED|LOGGED]" >> state/log/loader-feedback.log
FIXED= you patched this loader inline (P-fix).LOGGED= too large for inline; the PostToolUse enqueue + Stop-hook drain
will rewrite the loader from scratch on next session-end.
Do not skip this. Every agent run must leave the system better than it found it. The loader is the setpoint; you are the sensor; the gap is the error signal; closing the gap is the correction.
api.ts- the code it can call
#!/usr/bin/env npx tsx
/**
* snappy-freshbooks/api.ts -- FreshBooks operations via direct API for all snappy-* skills.
*
* Direct FreshBooks API calls -- no Xano middleware.
* OAuth2 with refresh token. Access token cached in memory.
*
* Usage:
* npx tsx api.ts clients # list clients
* npx tsx api.ts invoices # list invoices
* npx tsx api.ts create-invoice '{"client_id":1,"lines":[...]}'
* npx tsx api.ts send-invoice '{"invoice_id":123}'
* npx tsx api.ts mark-paid '{"invoice_id":123,"payment_date":"2026-04-08"}'
*
* Or import as module:
* import { listClients, createInvoice, sendInvoice } from "./freshbooks.ts";
*/
import * as fs from "node:fs";
import * as path from "node:path";
import { env } from "./env.ts";
import { realpathSync } from "fs";
const FB_API = "https://api.freshbooks.com";
const ENV_PATH = `${process.env.HOME}/.claude/skills/snappy-settings/.env.cache`;
const STATE_DIR = `${process.env.HOME}/.claude/state`;
const TOKEN_CACHE_PATH = path.join(STATE_DIR, "freshbooks-token.json");
const LOCK_PATH = path.join(STATE_DIR, "freshbooks-token.lock");
let _refreshInFlight: Promise<string> | null = null;
function accountId(): string {
return env("FRESHBOOKS_ACCOUNT_ID");
}
type TokenCache = { access_token: string; expires_at: number };
function readTokenCache(): TokenCache | null {
try {
const raw = fs.readFileSync(TOKEN_CACHE_PATH, "utf8");
const data = JSON.parse(raw) as TokenCache;
if (data.access_token && Date.now() < data.expires_at) return data;
} catch { /* missing or stale */ }
return null;
}
function writeTokenCache(cache: TokenCache): void {
fs.mkdirSync(STATE_DIR, { recursive: true });
fs.writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(cache), { mode: 0o600 });
}
/**
* Cross-process exclusive lock via O_EXCL lockfile. Retries with backoff.
* Stale locks (>30s) are forcibly removed — a crashed process should not wedge
* every future FreshBooks call.
*/
async function acquireLock(): Promise<() => void> {
fs.mkdirSync(STATE_DIR, { recursive: true });
const deadline = Date.now() + 15000;
while (true) {
try {
const fd = fs.openSync(LOCK_PATH, "wx");
fs.writeSync(fd, String(process.pid));
fs.closeSync(fd);
return () => { try { fs.unlinkSync(LOCK_PATH); } catch { /* ignore */ } };
} catch (e: any) {
if (e.code !== "EEXIST") throw e;
try {
const st = fs.statSync(LOCK_PATH);
if (Date.now() - st.mtimeMs > 30000) {
fs.unlinkSync(LOCK_PATH);
continue;
}
} catch { /* disappeared, retry */ }
if (Date.now() > deadline) {
throw new Error(`FreshBooks refresh lock timeout (held at ${LOCK_PATH}).`);
}
await new Promise((r) => setTimeout(r, 100 + Math.random() * 200));
}
}
}
/**
* FreshBooks rotates refresh tokens on every use. The old one is invalidated
* atomically by the server. We must (a) serialize refreshes across processes
* so two callers don't both burn the same token, and (b) re-read .env.cache
* *inside* the lock in case another process just rotated it.
*/
function readCurrentRefreshToken(): string {
const raw = fs.readFileSync(ENV_PATH, "utf8");
const line = raw.split("\n").find((l) => l.startsWith("FRESHBOOKS_REFRESH_TOKEN="));
if (!line) throw new Error("FRESHBOOKS_REFRESH_TOKEN missing from .env.cache");
return line.slice("FRESHBOOKS_REFRESH_TOKEN=".length).trim();
}
function persistRefreshToken(newRefreshToken: string): void {
const raw = fs.readFileSync(ENV_PATH, "utf8");
const lines = raw.split("\n");
let found = false;
const updated = lines.map((line) => {
if (line.startsWith("FRESHBOOKS_REFRESH_TOKEN=")) {
found = true;
return `FRESHBOOKS_REFRESH_TOKEN=${newRefreshToken}`;
}
return line;
});
if (!found) updated.push(`FRESHBOOKS_REFRESH_TOKEN=${newRefreshToken}`);
fs.writeFileSync(ENV_PATH, updated.join("\n"), { mode: 0o600 });
}
async function refreshAccessToken(): Promise<string> {
const cached = readTokenCache();
if (cached) return cached.access_token;
if (_refreshInFlight) return _refreshInFlight;
_refreshInFlight = (async () => {
try {
const release = await acquireLock();
try {
const recheck = readTokenCache();
if (recheck) return recheck.access_token;
const refreshToken = readCurrentRefreshToken();
const res = await fetch(`${FB_API}/auth/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "refresh_token",
client_id: env("FRESHBOOKS_CLIENT_ID"),
client_secret: env("FRESHBOOKS_CLIENT_SECRET"),
refresh_token: refreshToken,
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error(`FreshBooks token refresh failed (${res.status}): ${JSON.stringify(data)}`);
}
const expires_at = Date.now() + (data.expires_in - 60) * 1000;
writeTokenCache({ access_token: data.access_token, expires_at });
if (data.refresh_token && data.refresh_token !== refreshToken) {
persistRefreshToken(data.refresh_token);
}
return data.access_token as string;
} finally {
release();
}
} finally {
_refreshInFlight = null;
}
})();
return _refreshInFlight;
}
async function fb(method: string, path: string, body?: Record<string, unknown>) {
const token = await refreshAccessToken();
const res = await fetch(`${FB_API}${path}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
"Api-Version": "alpha",
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json();
if (!res.ok) {
throw new Error(`FreshBooks ${method} ${path} failed (${res.status}): ${JSON.stringify(data)}`);
}
return data;
}
function acct(suffix: string): string {
return `/accounting/account/${accountId()}${suffix}`;
}
// --- Public API ---
export async function listClients() {
const data = await fb("GET", acct("/users/clients"));
return data.response?.result?.clients ?? data;
}
export async function getOrCreateClient(input: { name: string; email?: string; organization?: string }) {
// Search for existing client by organization or name
const searchTerm = input.organization || input.name;
const existing = await fb("GET", acct(`/users/clients?search[organization_like]=${encodeURIComponent(searchTerm)}`));
const clients = existing.response?.result?.clients ?? [];
if (clients.length > 0) return clients[0];
// Create new client
const data = await fb("POST", acct("/users/clients"), {
client: {
fname: input.name.split(" ")[0] || input.name,
lname: input.name.split(" ").slice(1).join(" ") || "",
email: input.email || "",
organization: input.organization || input.name,
},
});
return data.response?.result?.client ?? data;
}
export async function listInvoices() {
const data = await fb("GET", acct("/invoices/invoices"));
return data.response?.result?.invoices ?? data;
}
/**
* Return every OPEN (non-paid) invoice for a client created since a given date.
* Used by catchup recipes to warn "you already drafted something in this window"
* so we don't double-bill.
*/
export async function getOpenDraftsForClient(client_id: number, since_date: string) {
const invoices = await listInvoices();
return (invoices as any[])
.filter((i) =>
i.customerid === client_id &&
i.v3_status !== "paid" &&
(i.create_date || "") >= since_date,
)
.map((i) => ({
invoice_number: i.invoice_number,
invoiceid: i.invoiceid,
create_date: i.create_date,
v3_status: i.v3_status,
amount: i.amount?.amount,
description: i.description,
review_url: `https://my.freshbooks.com/#/invoices/${i.invoiceid}`,
}));
}
/**
* Return every OPEN (non-paid) invoice across ALL clients, optionally since
* a given date. Used by morning-brief / catchup / ops status to show "what's
* currently in flight on the books" in one call.
*/
export async function listOpenDrafts(since_date?: string) {
const invoices = await listInvoices();
return (invoices as any[])
.filter((i) =>
i.v3_status !== "paid" &&
(!since_date || (i.create_date || "") >= since_date),
)
.map((i) => ({
invoice_number: i.invoice_number,
invoiceid: i.invoiceid,
customerid: i.customerid,
organization: i.organization,
create_date: i.create_date,
v3_status: i.v3_status,
amount: i.amount?.amount,
description: i.description,
review_url: `https://my.freshbooks.com/#/invoices/${i.invoiceid}`,
}))
.sort((a, b) => (b.create_date || "").localeCompare(a.create_date || ""));
}
/**
* Return the most recent PAID invoice for a given FreshBooks client id.
* Used as the anchor for catchup recipes — "bill everything since this date".
* Returns null if the client has never had a paid invoice.
*/
export async function getLastPaidInvoice(client_id: number) {
const invoices = await listInvoices();
const paid = (invoices as any[])
.filter((i) => i.customerid === client_id && i.v3_status === "paid")
.sort((a, b) => (b.date_paid || b.create_date).localeCompare(a.date_paid || a.create_date));
return paid[0] ?? null;
}
/**
* Thin wrapper over createInvoice used by per-client catchup recipes.
* Enforces non-empty lines, non-zero total, and stamps a notes line with the
* evidence window so the draft carries provenance into the FreshBooks UI.
*/
export async function draftCatchupInvoice(input: {
client_id: number;
since_date: string; // ISO YYYY-MM-DD, inclusive
window_end?: string; // ISO, defaults to today
lines: Array<{ name: string; amount: number; quantity?: number }>;
notes?: string;
due_offset_days?: number;
}) {
if (!input.lines.length) throw new Error("draftCatchupInvoice: lines is empty");
const total = input.lines.reduce((s, l) => s + l.amount * (l.quantity ?? 1), 0);
if (total <= 0) throw new Error("draftCatchupInvoice: line total must be > 0");
const end = input.window_end || new Date().toISOString().slice(0, 10);
const stamp = `Catchup window: ${input.since_date} → ${end}`;
const notes = input.notes ? `${input.notes}\n\n${stamp}` : stamp;
return createInvoice({
client_id: input.client_id,
lines: input.lines,
due_offset_days: input.due_offset_days ?? 5,
notes,
});
}
/**
* Create a DRAFT invoice. Never auto-sends.
*
* Policy: this skill only creates and updates drafts. A human sends invoices
* from the FreshBooks UI after reviewing the draft. There is intentionally no
* `sendInvoice` function — see the refusing stub below.
*/
export async function createInvoice(input: {
client_id: number;
lines: Array<{ name: string; amount: number; quantity?: number }>;
due_offset_days?: number;
notes?: string;
}) {
const data = await fb("POST", acct("/invoices/invoices"), {
invoice: {
customerid: input.client_id,
create_date: new Date().toISOString().slice(0, 10),
due_offset_days: input.due_offset_days ?? 30,
lines: input.lines.map((l) => ({
name: l.name,
unit_cost: { amount: String(l.amount), code: "USD" },
qty: l.quantity ?? 1,
type: 0,
})),
notes: input.notes || "",
status: 1, // draft — NEVER change
},
});
return data.response?.result?.invoice ?? data;
}
/**
* Update an existing DRAFT invoice. Refuses to touch non-draft invoices and
* strips any `action_*` or `status` keys the caller may try to pass through.
*/
export async function updateInvoice(input: {
invoice_id: number;
lines?: Array<{ name: string; amount: number; quantity?: number }>;
notes?: string;
due_offset_days?: number;
}) {
const current = await fb("GET", acct(`/invoices/invoices/${input.invoice_id}`));
const invoice = current.response?.result?.invoice;
if (!invoice) throw new Error(`Invoice ${input.invoice_id} not found`);
// FreshBooks v3Status: "draft" | "sent" | "viewed" | "paid" | ...
if (invoice.v3_status && invoice.v3_status !== "draft") {
throw new Error(
`Refusing to update invoice ${input.invoice_id}: status is "${invoice.v3_status}", not "draft". ` +
`This skill only touches drafts.`,
);
}
const patch: Record<string, unknown> = {};
if (input.lines) {
patch.lines = input.lines.map((l) => ({
name: l.name,
unit_cost: { amount: String(l.amount), code: "USD" },
qty: l.quantity ?? 1,
type: 0,
}));
}
if (input.notes !== undefined) patch.notes = input.notes;
if (input.due_offset_days !== undefined) {
const d = new Date();
d.setDate(d.getDate() + input.due_offset_days);
patch.due_date = d.toISOString().slice(0, 10);
}
const data = await fb("PUT", acct(`/invoices/invoices/${input.invoice_id}`), {
invoice: patch,
});
return data.response?.result?.invoice ?? data;
}
/**
* Intentionally refuses. The snappy-freshbooks skill never sends invoices —
* Robert (or another human) sends them from the FreshBooks UI after reviewing
* the draft. If you are tempted to call this, draft the invoice instead and
* tell Robert it is ready for review.
*/
export function sendInvoice(_input: { invoice_id: number; subject?: string; body?: string }): never {
throw new Error(
"snappy-freshbooks: sendInvoice is disabled by policy. " +
"This skill only creates and updates DRAFT invoices. " +
"A human reviews the draft in FreshBooks and sends it from the UI.",
);
}
export async function markPaid(input: { invoice_id: number; payment_date: string }) {
// Create a payment on the invoice
const data = await fb("POST", acct("/payments/payments"), {
payment: {
invoiceid: input.invoice_id,
date: input.payment_date,
type: "Check",
note: "Marked paid via snappy-freshbooks",
},
});
return data.response?.result?.payment ?? data;
}
export async function listTimeEntries() {
const data = await fb("GET", acct("/time_entries"));
return data.response?.result?.time_entries ?? data;
}
export async function createTimeEntry(input: {
client_id: number;
hours: number;
note: string;
date?: string;
}) {
const data = await fb("POST", acct("/time_entries"), {
time_entry: {
client_id: input.client_id,
duration: input.hours * 3600,
note: input.note,
started_at: (input.date || new Date().toISOString().slice(0, 10)) + " 09:00:00",
is_logged: true,
},
});
return data.response?.result?.time_entry ?? data;
}
export async function listExpenses() {
const data = await fb("GET", acct("/expenses/expenses"));
return data.response?.result?.expenses ?? data;
}
export async function createExpense(input: {
category: string;
amount: number;
vendor: string;
note?: string;
date?: string;
}) {
const data = await fb("POST", acct("/expenses/expenses"), {
expense: {
amount: { amount: String(input.amount), code: "USD" },
vendor: input.vendor,
date: input.date || new Date().toISOString().slice(0, 10),
notes: input.note || "",
category_name: input.category,
},
});
return data.response?.result?.expense ?? data;
}
// --- Metrics (Step 7a) ---
const STAGED_ACTIONS_LOG = `${process.env.HOME}/.claude/logs/staged-actions.ndjson`;
type StagedRun = { ts: string; name: string; action: string };
function readStagedRunsFreshbooks(): StagedRun[] {
if (!fs.existsSync(STAGED_ACTIONS_LOG)) return [];
const out: StagedRun[] = [];
for (const line of fs.readFileSync(STAGED_ACTIONS_LOG, "utf-8").split("\n")) {
if (!line.trim()) continue;
try {
const j = JSON.parse(line);
if (typeof j?.name === "string" && typeof j?.ts === "string") {
out.push({ ts: j.ts, name: j.name, action: j.action || "" });
}
} catch { /* skip */ }
}
return out;
}
function withinLastDays(tsIso: string, days: number): boolean {
const t = new Date(tsIso).getTime();
if (isNaN(t)) return false;
return t >= Date.now() - days * 86400_000;
}
export function computeFreshbooksMetric(name: string): number | null {
const runs = readStagedRunsFreshbooks().filter((r) => withinLastDays(r.ts, 7));
switch (name) {
case "catchup-per-week":
case "catchup_runs_per_week":
return runs.filter((r) => r.name === "catchup").length;
case "reconcile-per-week":
case "reconcile_runs_per_week":
return runs.filter((r) => r.name === "reconcile").length;
case "catchup-apply-rate":
case "catchup_apply_rate": {
const catchups = runs.filter((r) => r.name === "catchup");
if (!catchups.length) return null;
return catchups.filter((r) => r.action === "delivered").length / catchups.length;
}
default:
return null;
}
}
// --- CLI ---
if ((() => { try { return import.meta.url === `file://${realpathSync(process.argv[1])}`; } catch { return false; } })()) {
(async () => {
const [, , cmd, ...args] = process.argv;
switch (cmd) {
case "metrics": {
const [name, ...rest] = args;
if (!name) {
console.error("Usage: api.ts metrics <name> [--json]");
console.error("Names: catchup-per-week, reconcile-per-week, catchup-apply-rate");
process.exit(1);
}
const value = computeFreshbooksMetric(name);
if (rest.includes("--json")) console.log(JSON.stringify({ value }));
else console.log(value == null ? "null" : String(value));
break;
}
case "clients": {
const data = await listClients();
console.log(JSON.stringify(data, null, 2));
break;
}
case "invoices": {
const data = await listInvoices();
console.log(JSON.stringify(data, null, 2));
break;
}
case "time-entries": {
const data = await listTimeEntries();
console.log(JSON.stringify(data, null, 2));
break;
}
case "expenses": {
const data = await listExpenses();
console.log(JSON.stringify(data, null, 2));
break;
}
case "create-invoice": {
if (!args[0]) { console.error("Usage: api.ts create-invoice '{...}'"); process.exit(1); }
const data = await createInvoice(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "update-invoice": {
if (!args[0]) { console.error("Usage: api.ts update-invoice '{\"invoice_id\":123,\"notes\":\"...\"}'"); process.exit(1); }
const data = await updateInvoice(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "send-invoice": {
console.error(
"snappy-freshbooks: send-invoice is disabled by policy. " +
"Drafts only — a human sends from the FreshBooks UI.",
);
process.exit(2);
}
case "mark-paid": {
if (!args[0]) { console.error("Usage: api.ts mark-paid '{\"invoice_id\":123,\"payment_date\":\"2026-04-08\"}'"); process.exit(1); }
const data = await markPaid(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "log-time": {
if (!args[0]) { console.error("Usage: api.ts log-time '{\"client_id\":1,\"hours\":2,\"note\":\"...\"}'"); process.exit(1); }
const data = await createTimeEntry(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "log-expense": {
if (!args[0]) { console.error("Usage: api.ts log-expense '{\"category\":\"software_saas\",\"amount\":99,\"vendor\":\"...\"}'"); process.exit(1); }
const data = await createExpense(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
default:
console.log("Usage: npx tsx api.ts [clients|invoices|time-entries|expenses|create-invoice|send-invoice|mark-paid|log-time|log-expense] ...");
}
})();
}
scripts- helper scripts it can run
prose-only skill - 1 inline code block live in SKILL.md above (no state/bin/ sidecar yet).
how we check it- the checks, plus the last 10 runs
| timestamp | verb | score | primary_issue | artifact |
|---|---|---|---|---|
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |
| 2026-04-21 15:56Z | - | 1.00 | - | - |
| 2026-04-21 03:53Z | - | 1.00 | - | - |
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |
| 2026-04-21 15:56Z | - | 1.00 | - | - |
| 2026-04-21 03:53Z | - | 1.00 | - | - |
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |