Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
python -m coverage report --include=src/capkit/apr.py,src/capkit/disclosures.py --fail-under=94
- name: Rebuild workbook and verify it against the engine (fuzzed)
run: |
PYTHONPATH=src python -m capkit workbook '{"path": "workbook/CapKit.xlsx"}'
PYTHONPATH=src python -m capkit workbook '{"path": "workbook/CapKit.xlsx", "force": true}'
python scripts/verify_workbook.py workbook/CapKit.xlsx --fuzz 10
- name: Skills are valid and in sync with src/
run: python scripts/build_skills.py --check
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
- run: python scripts/build_skills.py
- name: Regenerate and verify the workbook that ships
run: |
PYTHONPATH=src python -m capkit workbook '{"path": "workbook/CapKit.xlsx"}'
PYTHONPATH=src python -m capkit workbook '{"path": "workbook/CapKit.xlsx", "force": true}'
python scripts/verify_workbook.py workbook/CapKit.xlsx --fuzz 10
- name: Checksums
run: |
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@

## Unreleased

- Audit low findings (experimental optimizer and workbook command):
- `optimize_mix` refuses `time_limit` above 300 seconds (per solve) or not above 0, and `horizon_weeks`
outside 1 to 520, with an error that names the argument.
- `optimize_mix` results now have a `warnings` list. A solve that stops at its time limit is named there
(plan, baseline or floor-sensitivity row), the first `summary` line starts with "CAUTION", and each
sensitivity row carries `optimal`. Before, only `status` and `optimal` showed it.
- `workbook` refuses a directory and refuses to overwrite the workbook or its `.cells.json` unless
`force` is true. The CI and release workflows pass `"force": true` to rebuild the committed file.
- `workbook` no longer has a check-then-write race: files are built in a scratch folder beside the target,
then placed with an exclusive create (no `force`) or an atomic replace (`force`). A symbolic link as
the file is still refused. A symbolic link as the containing folder is allowed on purpose (macOS
`/tmp` is one) and writes into the folder it points to; this is now documented.
- `optimize_mix` accepts any real `time_limit` (numpy integers and floats as well as int and float);
true/false, strings and None are still refused.
- `test_long_schedules_solve_quickly` measures CPU time instead of wall-clock time. It failed on a busy
machine (10 to 13 s wall); the same solve is about 1 s of CPU and 0.6 s wall when the machine is idle,
so no code speed-up was made.

- California SB 362: the disclosure rules now cover Fin. Code 22806, in force January 1, 2026. Any rate or
charge a provider states must come with the APR, and "interest" and "rate" must not mislead. The CA citation
is now 22800-22807.
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ PYTHONPATH=src python -m capkit true_cost '{"offer": {"type": "mca_fixed", "adva
| [`workbook/CapKit.xlsx`](workbook/CapKit.xlsx) | The core calculations as portable spreadsheet formulas (Excel, Google Sheets) |

A merchant-side remittance and reconciliation audit for MCAs is in development. A funding-mix
optimizer (`src/capkit/optimize`) is experimental and not included in releases.
optimizer (`src/capkit/optimize`) is experimental and not included in releases. Its result carries a
`warnings` list: if any solve stopped at its time limit (`time_limit` is capped at 300 seconds per solve,
`horizon_weeks` at 520), the plan is labelled "NOT proven optimal" and the warnings name which one. The
`workbook` command refuses a directory and will not overwrite an existing file unless `"force": true`.

Skills install by uploading the zip in Claude (Settings → Capabilities → Skills) or unzipping into
`~/.claude/skills/`. They need Python 3.9+.
Expand Down
5 changes: 4 additions & 1 deletion docs/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ The model maximizes:
## How a plan is checked

- **Solver.** HiGHS, through `scipy.optimize.milp`, with a relative gap of 1e-9. If the time limit is
hit, the result is labelled "not proven optimal".
hit, the result is labelled "not proven optimal": `status` says so, `optimal` is false, the first
line of `summary` starts with "CAUTION", and the top-level `warnings` list names every solve (plan,
baseline, floor sensitivity) that was stopped. `time_limit` is per solve, above 0 and at most 300
seconds; `horizon_weeks` is at most 520.
- **Re-pricing check** (`capkit.verify.reprice`). It rebuilds every cash flow from the offer
terms without reading the matrix. It does share the offer-expansion and invoice code with the
model, so it is a cross-check, not a fully independent implementation:
Expand Down
2 changes: 1 addition & 1 deletion docs/scenario.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ SBA 7(a) proceeds generally cannot refinance it.

| Field | Meaning |
|---|---|
| `horizon_weeks` | T, from 4 to 52 (13 is typical) |
| `horizon_weeks` | T, a whole number of weeks from 1 to 520 (13 is typical) |
| `starting_cash` | Cash today (week 0) |
| `cash_floor` | Minimum cash every week: one number, or a list of T values |
| `revenue` | Weekly revenue used by the affordability limit: one number or T values |
Expand Down
68 changes: 64 additions & 4 deletions skills/commercial-financing-disclosure/scripts/capkit/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import inspect
import json
import math
import numbers
import sys
from datetime import date
from typing import Any, Callable, Dict, Optional, Sequence
Expand All @@ -26,6 +27,8 @@

MAX_FLOWS = 25_000 # room for products.MAX_PERIODS payments plus advances
MAX_OFFERS = 25
MAX_TIME_LIMIT = 300.0 # seconds per solve; one optimize_mix runs up to len(carries) + baselines + 4 solves
MAX_HORIZON_WEEKS = 520 # ten years of weekly columns
MAX_ERROR = 300 # characters of an error message echoed back (inputs can be hostile)


Expand Down Expand Up @@ -163,7 +166,19 @@ def check_disclosure(disclosed_apr: float, funding_provided: float, total_owed:
def optimize_mix(scenario: dict, carries: Sequence[int] = (0, 52), sensitivity: bool = True, time_limit: float = 60.0):
"""Cheapest funding mix for a weekly cash forecast (needs scipy >= 1.9). See examples/bakery.json for
the scenario format. Reports the plan at post-horizon carries H=0 and H=52, the saving versus the
scenario's baseline, floor sensitivity, and an independent re-pricing check of every plan."""
scenario's baseline, floor sensitivity, and an independent re-pricing check of every plan.
``time_limit`` is seconds per solve, above 0 and at most 300. ``scenario.horizon_weeks`` is at most 520.
If any solve stops at its time limit, the result's ``warnings`` say so and the plan is labelled
"NOT proven optimal"."""
if not _is_real(time_limit): # any real number (int, float, numpy int/float), never true/false
raise ValueError(f"time_limit must be a number of seconds, got {_kind(time_limit)}")
time_limit = float(time_limit)
if not 0 < time_limit <= MAX_TIME_LIMIT:
raise ValueError(f"time_limit must be above 0 and at most {MAX_TIME_LIMIT:g} seconds (per solve), got {time_limit!r}")
weeks = scenario.get("horizon_weeks") if isinstance(scenario, dict) else None
if weeks is not None and not (_is_num(weeks) and float(weeks).is_integer() and 1 <= weeks <= MAX_HORIZON_WEEKS):
raise ValueError(f"scenario.horizon_weeks must be a whole number from 1 to {MAX_HORIZON_WEEKS}, got {_kind(weeks)}"
+ (f" {weeks}" if _is_num(weeks) else ""))
from .optimize.report import run
return run(scenario, tuple(carries), sensitivity, time_limit)

Expand Down Expand Up @@ -226,10 +241,51 @@ def prime_rate():
return pr()


def workbook(path: str = "CapKit.xlsx"):
"""Generate the formula-driven Excel / Google Sheets workbook."""
def workbook(path: str = "CapKit.xlsx", force: bool = False):
"""Generate the formula-driven Excel / Google Sheets workbook (and a .cells.json map beside it).
Refuses a directory or a symbolic link (even a dangling one), and refuses to replace an existing file
unless ``force`` is true. The files are built in a scratch folder beside the target and then placed with
an exclusive create (no ``force``) or an atomic replace (``force``), neither of which follows a link
planted after the checks. A symbolic link as the directory *containing* the file is allowed and writes
into the directory it points to: system paths such as macOS /tmp -> /private/tmp are links, and a
directory link is the caller's own choice. Only the file itself is protected."""
import os
import shutil
import tempfile
from pathlib import Path

from .excel.builder import build_workbook
build_workbook(path)
target = Path(path)
cells = target.with_suffix(".cells.json")

def check(p: Path):
if p.is_symlink():
raise ValueError(f"path must be a regular file, but {str(p)!r} is a symbolic link")
if p.is_dir():
raise ValueError(f"path must be a file, but {str(p)!r} is a directory")
if p.exists() and not force:
raise ValueError(f"{str(p)!r} already exists; pass force: true to overwrite it")

for p in (target, cells):
check(p)
target.parent.mkdir(parents=True, exist_ok=True)
scratch = Path(tempfile.mkdtemp(prefix=".capkit-wb-", dir=target.parent))
try:
built = scratch / target.name
build_workbook(built)
for src, dest in ((built, target), (built.with_suffix(".cells.json"), cells)):
if force:
check(dest) # a link may only be refused, never replaced through
os.replace(src, dest) # atomic; replaces the name itself, never a link's target
else:
try:
with open(src, "rb") as fin, open(dest, "xb") as fout: # O_CREAT|O_EXCL: fails on any
shutil.copyfileobj(fin, fout) # existing name, link included
except FileExistsError:
check(dest)
raise ValueError(f"{str(dest)!r} already exists; pass force: true to overwrite it") from None
finally:
shutil.rmtree(scratch, ignore_errors=True)
return {"wrote": path}


Expand Down Expand Up @@ -294,6 +350,10 @@ def _kind(v) -> str:
return names.get(type(v), type(v).__name__)


def _is_real(v) -> bool:
return isinstance(v, numbers.Real) and not isinstance(v, bool)


def _is_num(v) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool)

Expand Down
68 changes: 64 additions & 4 deletions skills/financing-true-cost/scripts/capkit/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import inspect
import json
import math
import numbers
import sys
from datetime import date
from typing import Any, Callable, Dict, Optional, Sequence
Expand All @@ -26,6 +27,8 @@

MAX_FLOWS = 25_000 # room for products.MAX_PERIODS payments plus advances
MAX_OFFERS = 25
MAX_TIME_LIMIT = 300.0 # seconds per solve; one optimize_mix runs up to len(carries) + baselines + 4 solves
MAX_HORIZON_WEEKS = 520 # ten years of weekly columns
MAX_ERROR = 300 # characters of an error message echoed back (inputs can be hostile)


Expand Down Expand Up @@ -163,7 +166,19 @@ def check_disclosure(disclosed_apr: float, funding_provided: float, total_owed:
def optimize_mix(scenario: dict, carries: Sequence[int] = (0, 52), sensitivity: bool = True, time_limit: float = 60.0):
"""Cheapest funding mix for a weekly cash forecast (needs scipy >= 1.9). See examples/bakery.json for
the scenario format. Reports the plan at post-horizon carries H=0 and H=52, the saving versus the
scenario's baseline, floor sensitivity, and an independent re-pricing check of every plan."""
scenario's baseline, floor sensitivity, and an independent re-pricing check of every plan.
``time_limit`` is seconds per solve, above 0 and at most 300. ``scenario.horizon_weeks`` is at most 520.
If any solve stops at its time limit, the result's ``warnings`` say so and the plan is labelled
"NOT proven optimal"."""
if not _is_real(time_limit): # any real number (int, float, numpy int/float), never true/false
raise ValueError(f"time_limit must be a number of seconds, got {_kind(time_limit)}")
time_limit = float(time_limit)
if not 0 < time_limit <= MAX_TIME_LIMIT:
raise ValueError(f"time_limit must be above 0 and at most {MAX_TIME_LIMIT:g} seconds (per solve), got {time_limit!r}")
weeks = scenario.get("horizon_weeks") if isinstance(scenario, dict) else None
if weeks is not None and not (_is_num(weeks) and float(weeks).is_integer() and 1 <= weeks <= MAX_HORIZON_WEEKS):
raise ValueError(f"scenario.horizon_weeks must be a whole number from 1 to {MAX_HORIZON_WEEKS}, got {_kind(weeks)}"
+ (f" {weeks}" if _is_num(weeks) else ""))
from .optimize.report import run
return run(scenario, tuple(carries), sensitivity, time_limit)

Expand Down Expand Up @@ -226,10 +241,51 @@ def prime_rate():
return pr()


def workbook(path: str = "CapKit.xlsx"):
"""Generate the formula-driven Excel / Google Sheets workbook."""
def workbook(path: str = "CapKit.xlsx", force: bool = False):
"""Generate the formula-driven Excel / Google Sheets workbook (and a .cells.json map beside it).
Refuses a directory or a symbolic link (even a dangling one), and refuses to replace an existing file
unless ``force`` is true. The files are built in a scratch folder beside the target and then placed with
an exclusive create (no ``force``) or an atomic replace (``force``), neither of which follows a link
planted after the checks. A symbolic link as the directory *containing* the file is allowed and writes
into the directory it points to: system paths such as macOS /tmp -> /private/tmp are links, and a
directory link is the caller's own choice. Only the file itself is protected."""
import os
import shutil
import tempfile
from pathlib import Path

from .excel.builder import build_workbook
build_workbook(path)
target = Path(path)
cells = target.with_suffix(".cells.json")

def check(p: Path):
if p.is_symlink():
raise ValueError(f"path must be a regular file, but {str(p)!r} is a symbolic link")
if p.is_dir():
raise ValueError(f"path must be a file, but {str(p)!r} is a directory")
if p.exists() and not force:
raise ValueError(f"{str(p)!r} already exists; pass force: true to overwrite it")

for p in (target, cells):
check(p)
target.parent.mkdir(parents=True, exist_ok=True)
scratch = Path(tempfile.mkdtemp(prefix=".capkit-wb-", dir=target.parent))
try:
built = scratch / target.name
build_workbook(built)
for src, dest in ((built, target), (built.with_suffix(".cells.json"), cells)):
if force:
check(dest) # a link may only be refused, never replaced through
os.replace(src, dest) # atomic; replaces the name itself, never a link's target
else:
try:
with open(src, "rb") as fin, open(dest, "xb") as fout: # O_CREAT|O_EXCL: fails on any
shutil.copyfileobj(fin, fout) # existing name, link included
except FileExistsError:
check(dest)
raise ValueError(f"{str(dest)!r} already exists; pass force: true to overwrite it") from None
finally:
shutil.rmtree(scratch, ignore_errors=True)
return {"wrote": path}


Expand Down Expand Up @@ -294,6 +350,10 @@ def _kind(v) -> str:
return names.get(type(v), type(v).__name__)


def _is_real(v) -> bool:
return isinstance(v, numbers.Real) and not isinstance(v, bool)


def _is_num(v) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool)

Expand Down
2 changes: 1 addition & 1 deletion skills/funding-mix-optimizer/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ python scripts/capkit_cli.py evaluate_mix '{"scenario": {...}, "plan": {...}}'
Use the `sensitivity` rows, which are actual re-solves with the floor moved, not shadow prices.
4. **The APR of each chosen source**, from the financing-true-cost skill's `true_cost` command.
5. **Checks:** confirm `check.feasible` is true and that the re-priced terminal value equals the
objective. If the status is not `optimal`, say "best plan found, not proven optimal".
objective. If the status is not `optimal`, or `warnings` is not empty, say "best plan found, not proven optimal".
6. **Assumptions** (from the output): weekly grid, one prepayment per offer, fixed MCA debits. For a
split-percentage MCA, stress-test the sales.

Expand Down
13 changes: 11 additions & 2 deletions skills/funding-mix-optimizer/references/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ Write the arguments to a JSON file, then run `python scripts/capkit_cli.py <comm
Cheapest funding mix for a weekly cash forecast (needs scipy >= 1.9). See examples/bakery.json for
the scenario format. Reports the plan at post-horizon carries H=0 and H=52, the saving versus the
scenario's baseline, floor sensitivity, and an independent re-pricing check of every plan.
``time_limit`` is seconds per solve, above 0 and at most 300. ``scenario.horizon_weeks`` is at most 520.
If any solve stops at its time limit, the result's ``warnings`` say so and the plan is labelled
"NOT proven optimal".

Args: `scenario`=**required**, `carries`=[0, 52], `sensitivity`=True, `time_limit`=60.0

Expand Down Expand Up @@ -46,9 +49,15 @@ Args: `discount`=0.02, `discount_days`=10, `net_days`=30

## `workbook`

Generate the formula-driven Excel / Google Sheets workbook.
Generate the formula-driven Excel / Google Sheets workbook (and a .cells.json map beside it).
Refuses a directory or a symbolic link (even a dangling one), and refuses to replace an existing file
unless ``force`` is true. The files are built in a scratch folder beside the target and then placed with
an exclusive create (no ``force``) or an atomic replace (``force``), neither of which follows a link
planted after the checks. A symbolic link as the directory *containing* the file is allowed and writes
into the directory it points to: system paths such as macOS /tmp -> /private/tmp are links, and a
directory link is the caller's own choice. Only the file itself is protected.

Args: `path`="CapKit.xlsx"
Args: `path`="CapKit.xlsx", `force`=False

## `params`

Expand Down
5 changes: 4 additions & 1 deletion skills/funding-mix-optimizer/references/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ The model maximizes:
## How a plan is checked

- **Solver.** HiGHS, through `scipy.optimize.milp`, with a relative gap of 1e-9. If the time limit is
hit, the result is labelled "not proven optimal".
hit, the result is labelled "not proven optimal": `status` says so, `optimal` is false, the first
line of `summary` starts with "CAUTION", and the top-level `warnings` list names every solve (plan,
baseline, floor sensitivity) that was stopped. `time_limit` is per solve, above 0 and at most 300
seconds; `horizon_weeks` is at most 520.
- **Re-pricing check** (`capkit.verify.reprice`). It rebuilds every cash flow from the offer
terms without reading the matrix. It does share the offer-expansion and invoice code with the
model, so it is a cross-check, not a fully independent implementation:
Expand Down
2 changes: 1 addition & 1 deletion skills/funding-mix-optimizer/references/scenario.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ SBA 7(a) proceeds generally cannot refinance it.

| Field | Meaning |
|---|---|
| `horizon_weeks` | T, from 4 to 52 (13 is typical) |
| `horizon_weeks` | T, a whole number of weeks from 1 to 520 (13 is typical) |
| `starting_cash` | Cash today (week 0) |
| `cash_floor` | Minimum cash every week: one number, or a list of T values |
| `revenue` | Weekly revenue used by the affordability limit: one number or T values |
Expand Down
Loading
Loading