diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e79eb0..ee53f54 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ba30ca7..d8496e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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: | diff --git a/CHANGELOG.md b/CHANGELOG.md index e653717..c0da3e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 9fc58a4..f876208 100644 --- a/README.md +++ b/README.md @@ -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+. diff --git a/docs/model.md b/docs/model.md index 8310aa5..13f74da 100644 --- a/docs/model.md +++ b/docs/model.md @@ -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: diff --git a/docs/scenario.md b/docs/scenario.md index 2899919..cd35b43 100644 --- a/docs/scenario.md +++ b/docs/scenario.md @@ -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 | diff --git a/skills/commercial-financing-disclosure/scripts/capkit/api.py b/skills/commercial-financing-disclosure/scripts/capkit/api.py index 9263dae..82992a3 100644 --- a/skills/commercial-financing-disclosure/scripts/capkit/api.py +++ b/skills/commercial-financing-disclosure/scripts/capkit/api.py @@ -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 @@ -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) @@ -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) @@ -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} @@ -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) diff --git a/skills/financing-true-cost/scripts/capkit/api.py b/skills/financing-true-cost/scripts/capkit/api.py index 9263dae..82992a3 100644 --- a/skills/financing-true-cost/scripts/capkit/api.py +++ b/skills/financing-true-cost/scripts/capkit/api.py @@ -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 @@ -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) @@ -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) @@ -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} @@ -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) diff --git a/skills/funding-mix-optimizer/SKILL.md b/skills/funding-mix-optimizer/SKILL.md index 4ddac9d..701146f 100644 --- a/skills/funding-mix-optimizer/SKILL.md +++ b/skills/funding-mix-optimizer/SKILL.md @@ -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. diff --git a/skills/funding-mix-optimizer/references/commands.md b/skills/funding-mix-optimizer/references/commands.md index 344c2cd..fc60d8e 100644 --- a/skills/funding-mix-optimizer/references/commands.md +++ b/skills/funding-mix-optimizer/references/commands.md @@ -7,6 +7,9 @@ Write the arguments to a JSON file, then run `python scripts/capkit_cli.py = 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 @@ -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` diff --git a/skills/funding-mix-optimizer/references/model.md b/skills/funding-mix-optimizer/references/model.md index 8310aa5..13f74da 100644 --- a/skills/funding-mix-optimizer/references/model.md +++ b/skills/funding-mix-optimizer/references/model.md @@ -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: diff --git a/skills/funding-mix-optimizer/references/scenario.md b/skills/funding-mix-optimizer/references/scenario.md index 2899919..cd35b43 100644 --- a/skills/funding-mix-optimizer/references/scenario.md +++ b/skills/funding-mix-optimizer/references/scenario.md @@ -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 | diff --git a/skills/funding-mix-optimizer/scripts/capkit/api.py b/skills/funding-mix-optimizer/scripts/capkit/api.py index 9263dae..82992a3 100644 --- a/skills/funding-mix-optimizer/scripts/capkit/api.py +++ b/skills/funding-mix-optimizer/scripts/capkit/api.py @@ -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 @@ -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) @@ -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) @@ -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} @@ -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) diff --git a/skills/funding-mix-optimizer/scripts/capkit/optimize/report.py b/skills/funding-mix-optimizer/scripts/capkit/optimize/report.py index 8961c3a..21a68bd 100644 --- a/skills/funding-mix-optimizer/scripts/capkit/optimize/report.py +++ b/skills/funding-mix-optimizer/scripts/capkit/optimize/report.py @@ -66,19 +66,30 @@ def _describe(plan, info_offers=None): return lines +def _warn(warnings: list, what: str, r: dict) -> None: + """Record every solve that is not proven optimal (infeasible is a finding, not a stopped solve).""" + if not r.get("optimal") and r.get("status") != "infeasible": + warnings.append(f"{what}: {r.get('status')}") + + def run(scenario: dict, carries=(0, 52), sensitivity: bool = True, time_limit: float = 60.0) -> dict: """Full report: optimal plan at each post-horizon carry H, the baseline, savings, and the effect of moving the cash floor (parametric re-solves, not shadow prices).""" out: Dict[str, Any] = {"scenario": scenario.get("name"), "results": {}} + warnings: list = [] base_force = (scenario.get("baseline") or {}).get("force") for H in carries: best = optimize(scenario, H=H, time_limit=time_limit) - entry = {"optimal": best} + _warn(warnings, f"plan at H={H}", best) + entry: Dict[str, Any] = {"optimal": best} if best.get("objective") is not None: entry["summary"] = _describe(best["plan"]) + if not best["optimal"]: + entry["summary"].insert(0, f"CAUTION, {best['status']}.") if base_force and best.get("objective") is not None: base = optimize(scenario, H=H, force=base_force, time_limit=time_limit) entry["baseline"] = base + _warn(warnings, f"baseline at H={H}", base) if base.get("objective") is not None: entry["saving_vs_baseline"] = best["objective"] - base["objective"] out["results"][f"H={H}"] = entry @@ -93,11 +104,13 @@ def run(scenario: dict, carries=(0, 52), sensitivity: bool = True, time_limit: f else: sc["cash_floor"] = max(0.0, float(fl) + delta) r = optimize(sc, H=0, time_limit=time_limit) - sens.append({"cash_floor_change": delta, + _warn(warnings, f"floor sensitivity {delta:+d}", r) + sens.append({"cash_floor_change": delta, "optimal": r.get("optimal", False), "terminal_change": None if r.get("objective") is None else r["objective"] - base_obj}) out["sensitivity"] = {"what": "re-solve with the cash floor moved; actual change in terminal net " "position (captures jumps when the set of offers changes)", "rows": sens} + out["warnings"] = warnings out["assumptions"] = [ "Terminal net position values every balance still open at the horizon at its payoff amount (H=0); " "H=52 also carries each open balance one more year at its own rate.", diff --git a/src/capkit/api.py b/src/capkit/api.py index 9263dae..82992a3 100644 --- a/src/capkit/api.py +++ b/src/capkit/api.py @@ -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 @@ -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) @@ -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) @@ -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} @@ -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) diff --git a/src/capkit/optimize/report.py b/src/capkit/optimize/report.py index 8961c3a..21a68bd 100644 --- a/src/capkit/optimize/report.py +++ b/src/capkit/optimize/report.py @@ -66,19 +66,30 @@ def _describe(plan, info_offers=None): return lines +def _warn(warnings: list, what: str, r: dict) -> None: + """Record every solve that is not proven optimal (infeasible is a finding, not a stopped solve).""" + if not r.get("optimal") and r.get("status") != "infeasible": + warnings.append(f"{what}: {r.get('status')}") + + def run(scenario: dict, carries=(0, 52), sensitivity: bool = True, time_limit: float = 60.0) -> dict: """Full report: optimal plan at each post-horizon carry H, the baseline, savings, and the effect of moving the cash floor (parametric re-solves, not shadow prices).""" out: Dict[str, Any] = {"scenario": scenario.get("name"), "results": {}} + warnings: list = [] base_force = (scenario.get("baseline") or {}).get("force") for H in carries: best = optimize(scenario, H=H, time_limit=time_limit) - entry = {"optimal": best} + _warn(warnings, f"plan at H={H}", best) + entry: Dict[str, Any] = {"optimal": best} if best.get("objective") is not None: entry["summary"] = _describe(best["plan"]) + if not best["optimal"]: + entry["summary"].insert(0, f"CAUTION, {best['status']}.") if base_force and best.get("objective") is not None: base = optimize(scenario, H=H, force=base_force, time_limit=time_limit) entry["baseline"] = base + _warn(warnings, f"baseline at H={H}", base) if base.get("objective") is not None: entry["saving_vs_baseline"] = best["objective"] - base["objective"] out["results"][f"H={H}"] = entry @@ -93,11 +104,13 @@ def run(scenario: dict, carries=(0, 52), sensitivity: bool = True, time_limit: f else: sc["cash_floor"] = max(0.0, float(fl) + delta) r = optimize(sc, H=0, time_limit=time_limit) - sens.append({"cash_floor_change": delta, + _warn(warnings, f"floor sensitivity {delta:+d}", r) + sens.append({"cash_floor_change": delta, "optimal": r.get("optimal", False), "terminal_change": None if r.get("objective") is None else r["objective"] - base_obj}) out["sensitivity"] = {"what": "re-solve with the cash floor moved; actual change in terminal net " "position (captures jumps when the set of offers changes)", "rows": sens} + out["warnings"] = warnings out["assumptions"] = [ "Terminal net position values every balance still open at the horizon at its payoff amount (H=0); " "H=52 also carries each open balance one more year at its own rate.", diff --git a/tests/test_api.py b/tests/test_api.py index 4918242..fa1856e 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -173,3 +173,109 @@ def test_after_tax_characters(): for bad in (-0.1, 1.0, float("nan"), "0.3"): with pytest.raises(ValueError): compare.after_tax_cost(1000, "interest", bad) + + +def test_workbook_command_refuses_a_directory_and_an_existing_file_unless_forced(tmp_path): + assert "is a directory" in err("workbook", json.dumps({"path": str(tmp_path)})) + p = tmp_path / "w.xlsx" + ok("workbook", json.dumps({"path": str(p)})) + first = p.read_bytes() + p.write_bytes(b"keep me") + assert "already exists" in err("workbook", json.dumps({"path": str(p)})) + assert p.read_bytes() == b"keep me" + assert ok("workbook", json.dumps({"path": str(p), "force": True}))["wrote"] == str(p) + assert p.read_bytes()[:2] == first[:2] and p.stat().st_size > 10000 + # an existing map file beside a new workbook is protected too + q = tmp_path / "x.xlsx" + (tmp_path / "x.cells.json").write_text("{}") + assert "x.cells.json" in err("workbook", json.dumps({"path": str(q)})) and not q.exists() + + +def test_workbook_command_refuses_a_symbolic_link_even_a_dangling_one(tmp_path): + victim = tmp_path / "victim.xlsx" + link = tmp_path / "link.xlsx" + link.symlink_to(victim) # dangling: the target does not exist yet + for force in (False, True): + assert "symbolic link" in err("workbook", json.dumps({"path": str(link), "force": force})) + assert not victim.exists() + victim.write_bytes(b"keep me") # a link to an existing file is refused too + assert "symbolic link" in err("workbook", json.dumps({"path": str(link), "force": True})) + assert victim.read_bytes() == b"keep me" + cells = tmp_path / "c.cells.json" # and so is a symlinked map file beside a new workbook + cells.symlink_to(tmp_path / "gone.json") + assert "symbolic link" in err("workbook", json.dumps({"path": str(tmp_path / "c.xlsx")})) + assert not (tmp_path / "gone.json").exists() + + +def test_optimize_mix_time_limit_error_shows_the_real_value_and_direct_calls_reject_non_numbers(): + sc = {"horizon_weeks": 4, "starting_cash": 0, "operating_cash_flow": [0, 0, 0, 0]} + assert "300.0001" in err("optimize_mix", json.dumps({"scenario": sc, "time_limit": 300.0001})) + for bad in (True, False, "5", None, [1]): + with pytest.raises(ValueError, match="time_limit must be a number"): + api.optimize_mix(sc, time_limit=bad) + + +def test_optimize_mix_refuses_out_of_range_time_limit_and_horizon(): + sc = {"horizon_weeks": 4, "starting_cash": 0, "operating_cash_flow": [0, 0, 0, 0]} + for bad in (0, -1, 300.5, 1e9): + assert "time_limit" in err("optimize_mix", json.dumps({"scenario": sc, "time_limit": bad})) + for bad in (0, -3, 521, 1e6, 2.5, "10"): + out = err("optimize_mix", json.dumps({"scenario": dict(sc, horizon_weeks=bad)})) + assert "horizon_weeks" in out + + +def test_workbook_exclusive_create_loses_a_race_without_overwriting(tmp_path, monkeypatch): + """A file that appears after the pre-check (the check-then-write race) is never overwritten without force.""" + p = tmp_path / "r.xlsx" + real_open = open + + def racing_open(file, mode="r", *a, **k): # the rival creates the file just before our exclusive create + if str(file) == str(p) and "x" in mode: + p.write_bytes(b"rival") + return real_open(file, mode, *a, **k) + monkeypatch.setattr("builtins.open", racing_open) + with pytest.raises(ValueError, match="already exists"): + api.workbook(str(p)) + monkeypatch.undo() + assert p.read_bytes() == b"rival" + assert [x.name for x in tmp_path.iterdir()] == ["r.xlsx"] # scratch folder cleaned up + + +def test_workbook_force_replaces_atomically_and_never_writes_through_a_link_planted_late(tmp_path, monkeypatch): + p, victim = tmp_path / "f.xlsx", tmp_path / "victim.bin" + victim.write_bytes(b"keep me") + api.workbook(str(p)) + p.unlink() + p.symlink_to(victim) # a link in place of the file: refused, victim untouched + with pytest.raises(ValueError, match="symbolic link"): + api.workbook(str(p), force=True) + assert victim.read_bytes() == b"keep me" and p.is_symlink() + p.unlink() + (tmp_path / "f.cells.json").unlink() + api.workbook(str(p)) + assert api.workbook(str(p), force=True)["wrote"] == str(p) and not p.is_symlink() + assert sorted(x.name for x in tmp_path.iterdir()) == ["f.cells.json", "f.xlsx", "victim.bin"] + + +def test_workbook_allows_a_symlinked_parent_directory_on_purpose(tmp_path): + """Documented rule: only the file is protected; a link as the containing folder (macOS /tmp) is followed.""" + real = tmp_path / "real" + real.mkdir() + (tmp_path / "linkdir").symlink_to(real, target_is_directory=True) + api.workbook(str(tmp_path / "linkdir" / "w.xlsx")) + assert (real / "w.xlsx").stat().st_size > 10000 and (real / "w.cells.json").exists() + link_file = real / "l.xlsx" # but a link as the file itself is still refused + link_file.symlink_to(real / "gone.xlsx") + assert "symbolic link" in err("workbook", json.dumps({"path": str(tmp_path / "linkdir" / "l.xlsx"), "force": True})) + + +def test_optimize_mix_time_limit_accepts_numpy_numbers_and_still_rejects_bool_str_none(): + np = pytest.importorskip("numpy") + sc = {"horizon_weeks": 4, "starting_cash": 0, "operating_cash_flow": [0, 0, 0, 0]} + for ok_val in (np.int64(5), np.float64(5.0), np.float32(5.0), np.int32(5), 5, 5.0): + assert api.optimize_mix(sc, carries=(0,), sensitivity=False, time_limit=ok_val) + for bad in (np.bool_(True), True, "5", None): + with pytest.raises(ValueError, match="time_limit must be a number"): + api.optimize_mix(sc, time_limit=bad) + with pytest.raises(ValueError, match="at most 300"): + api.optimize_mix(sc, time_limit=np.int64(301)) diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 5269726..594388e 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -205,18 +205,20 @@ def test_semimonthly_fifteenth_and_month_end_measures_the_same_in_30_and_31_day_ # ---------------------------------------------------------------- skill red-team (overnight) def test_long_schedules_solve_quickly(): + # CPU time, not wall clock: the solve is ~1 s of CPU on an idle machine, but wall time stretches 10x or + # more when other jobs share the machine. A real slowdown still shows up as CPU time. import time from capkit import api - t = time.perf_counter() + t = time.process_time() r = api.true_cost({"type": "mca_fixed", "advance": 50000, "factor_rate": 1.0001, "payment": 2.6, "frequency": "business_day", "funding_date": "2027-01-04"}) - assert len(r["schedule"]) > 19000 and time.perf_counter() - t < 8 - t = time.perf_counter() + assert len(r["schedule"]) > 19000 and time.process_time() - t < 8 + t = time.process_time() with pytest.raises(ValueError, match="does not repay"): api.true_cost({"type": "mca_split", "advance": 50000, "factor_rate": 1.3, "holdback": 0.1, "sales": [3.4], "frequency": "month"}) - assert time.perf_counter() - t < 3 + assert time.process_time() - t < 3 def test_hostile_sizes_are_refused_and_errors_are_truncated(capsys): diff --git a/tests/test_optimize.py b/tests/test_optimize.py index cba6211..ea91db8 100644 --- a/tests/test_optimize.py +++ b/tests/test_optimize.py @@ -181,3 +181,28 @@ def test_infeasible_reported_cleanly(): sc = variant(cash_floor=1_000_000) r = optimize(sc) assert not r["optimal"] and "floor" in r["message"] + + +def test_a_solve_stopped_at_the_time_limit_is_flagged_everywhere(monkeypatch): + import capkit.optimize.report as rep + real = rep.solve + + def stopped(m, time_limit=60.0, **kw): + r = real(m, time_limit=time_limit, **kw) + if r["x"] is None: + return r + return dict(r, status=1, optimal=False, label="time limit reached: best plan found, NOT proven optimal") + + monkeypatch.setattr(rep, "solve", stopped) + out = run(SAFE, carries=(0,), sensitivity=True, time_limit=5) + assert out["results"]["H=0"]["optimal"]["optimal"] is False + assert out["results"]["H=0"]["summary"][0].startswith("CAUTION") and "NOT proven optimal" in out["results"]["H=0"]["summary"][0] + assert out["warnings"] and all("NOT proven optimal" in w for w in out["warnings"]) + assert any(w.startswith("plan at H=0") for w in out["warnings"]) + assert all(r["optimal"] is False for r in out["sensitivity"]["rows"]) + + +def test_a_proven_optimal_run_has_no_warnings(): + out = run(SAFE, carries=(0,), sensitivity=False) + assert out["warnings"] == [] and out["results"]["H=0"]["optimal"]["optimal"] is True + assert not out["results"]["H=0"]["summary"][0].startswith("CAUTION")