Commit Graph
211 Commits
Author SHA1 Message Date
inference-admin d941961549 portal: stop telling stray-credit buyers the floor is $10
ci/woodpecker/push/woodpecker Pipeline was canceled
mmoya traced the false '$10 floor' to the stray-credit email: it said '($10-20/month,
sliding scale)' when Open Collective's flexible tier starts at $5 (suggested $10).
Copy now says 'from $5/month, suggested $10 — sliding scale'.
2026-11-17 08:07:01 +00:00
inference-admin ea0f728af2 portal: member_aliases — credit a purchase made from a member's second OC profile
ci/woodpecker/push/woodpecker Pipeline was canceled
A person can hold two Open Collective profiles, one hiding its email. Purchases from
the hidden one have no email to match and no primary slug, so they land in held
credits. member_aliases maps extra slugs to a member email; the sweep's held-credit
pass resolves email -> slug -> alias before holding anything. Admin GET/POST
/admin/aliases manages rows; test covers grant and idempotency.
2026-11-17 05:11:16 +00:00
inference-admin ffe62d3c78 portal: derive source from OC email visibility instead of trusting a stale flag
ci/woodpecker/push/woodpecker Pipeline was canceled
oc-incognito disables email matching by design, so a profile that later shows an
email leaves the member silently unmatched. The sweep now flips those to oc and
records oc_email; profiles still hiding an email are untouched. Test covers both.
2026-11-17 05:04:50 +00:00
inference-admin 85e8e62e5b portal: membership-status reports the computed allowance, not members.balance (often NULL)
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-17 04:56:58 +00:00
inference-admin 27b0ea564a portal: answer for a lapsed membership instead of leaving the dashboard blank
ci/woodpecker/push/woodpecker Pipeline was canceled
New read-only /broker/membership-status, authenticated by the broker secret with a
verifier that admits a member row in ANY state (usage and keys still require active).
Returns active/state, the latest allowance_log decision with its evidence, the OC
minimum contribution (MIN_CONTRIBUTION, copy-only — OC stays the authority), credits,
allowance and the contribute URL.

MIN_CONTRIBUTION is deliberately NOT wired into deactivation: a number we half-know
should not cost anyone access.
2026-11-17 04:55:34 +00:00
inference-admin e9d0fd259a portal: settle held credits in the sweep, and report the ones nobody can be credited for
ci/woodpecker/push/woodpecker Pipeline was canceled
A credit pack bought while the buyer's membership was inactive is held — correctly,
we must never mint credits for a non-member. The gap was what happened next: the hold
sat until a human noticed (mmoya's $10 waited from 01:45 until they wrote in).

Every sweep now grants any hold that resolves to an ACTIVE member (by email first, then
slug), reusing grant_held_credits() so held:<id> keeps it idempotent; holds with no
active member older than HELD_ALERT_HOURS are emailed to info@. Tests cover grant/hold/
no-double-apply.
2026-11-17 04:51:40 +00:00
inference-admin bed7f03063 rate limits: one bucket per ROUTE, not one per proxy address
ci/woodpecker/push/woodpecker Pipeline was canceled
Every request arrives through Cloudrons
2026-11-13 22:45:48 +00:00
inference-admin 0a6939fe07 retire the Open WebUI integration
ci/woodpecker/push/woodpecker Pipeline was canceled
The app is stopped (`com.openwebui.cloudronapp`, installed|stopped), so every call
to it failed with "Temporary failure in name resolution" — a stopped container has
no DNS entry. Four of the last four provisions logged exactly that; no new member
ever reached the group.

Its "members group" was never a Cloudron group: the id pointed at a group inside
Open WebUI's own database, which is why it appears nowhere in Cloudron's UI.

Removed: owui_add_to_members_group, both call sites (provision_member and guest
convert), the OWUI_* constants, and the signed-JWT identity path in inject_key.
That last one is the part that matters beyond tidiness: it accepted a
shared-secret-signed token as proof of identity for an integration nobody runs.
inject_key keeps its one live path (LibreChat: X-User-Email + X-Portal-Secret,
still verified).

First attempt at this cut too much — a greedy splice off the guest-convert call
took listmonk_sync and the held-credit grant with it, and test_guest_lifecycle.py
caught it before anything shipped. Redone with exact anchors.
2026-11-13 22:33:10 +00:00
inference-admin b1022eb02a oc-incognito: take the slug from the member's own row
ci/woodpecker/push/woodpecker Pipeline was canceled
Setting the source was not enough, and verification is what caught it: mmoya still
produced no allowance decision at all.

The reconciler gets a member's OC slug from the member INDEX — which is keyed by
email, and DROPS anyone whose profile hides its email. So `oc_slug` came back
empty, the member fell into "not in the live Open Collective member list — cannot
verify payment", and was counted as skipped. An oc-incognito member would have
been "not manual" and still not reconciled: a nicer label over the same hole.

For source oc-incognito the slug now comes from the member's own row, which is
the same key fetch_member_orders() groups orders by — the whole reason matching
can work for these people. The test pins the fallback, not just the source.
2026-11-13 22:27:55 +00:00
inference-admin 64d1ea5093 members: an explicit SOURCE, so 'oc-incognito' stops being 'manual'
ci/woodpecker/push/woodpecker Pipeline was canceled
mmoya@mmoya.org sat in MANUAL_MEMBERS because OC hides the address on their
profile (incognito-5ad60182, email null since 2023), so email matching can never
find them. But "manual" means hand-provisioned, and the sweep SKIPS manual
members entirely: a paying subscriber had no lapse logic, no dues tracking and no
order attribution. Two different facts were sharing one word.

members.source now carries which one it is:
  oc            — OC-backed, matched by email (the default; NULL means this)
  oc-incognito  — OC-backed, profile hides the email, matched by the stored OC
                  SLUG — which the reconciliation already uses, since
                  fetch_member_orders() groups orders by the payer's slug and
                  members.slug holds exactly that for these people
  manual        — hand-provisioned; no contribution expected, nothing reconciles,
                  nobody lapses

So an oc-incognito member needs no exemption from reconciliation — they need to
stop being skipped, and the existing slug path does the rest.

Every decision that keyed on the raw MANUAL_MEMBERS list now keys on the source:
the reconciliation skip, the sweep's deactivation guard, and the shortfall-credit
exemption. An explicit source beats the list, so a member can be moved without
editing the env — and the env list can shrink toward deprecation. An
unrecognised or unreadable source falls back to 'oc', the direction that keeps
reconciling someone rather than quietly exempting them.

anchor_day_for_member also resolves by slug now: an incognito member is absent
from the member index (it drops anyone without an email), and falling back to
"today" would silently move their renewal day.

tests/test_oc_incognito.py pins all of it, including that the column is optional
(NULL = not stated) so this ships without a data migration.
2026-11-13 22:24:46 +00:00
inference-admin 2cde368c1e resolve payer: authenticate the lookup — without the token OC hides the email
ci/woodpecker/push/woodpecker Pipeline was canceled
Second live-only bug in the same helper. Sent unauthenticated, OC answers the
public view of an account: name comes back, email does not. A hand query with the
Personal-Token header returned conor.canaday@gmail.com for the very slug the
helper reported as email=None — so the fix would have resolved nobody, silently,
while looking like it worked.

The test now pins the header (the stub records what it was called with), because
the failure mode here is an absence, and an absence is exactly what a stub
forgets to check.
2026-11-13 22:14:36 +00:00
inference-admin 9c10e627fc resolve payer: read the response's JSON (the stub hid this)
ci/woodpecker/push/woodpecker Pipeline was canceled
_oc_graphql_post returns the RESPONSE — it is a retrying wrapper around
client.post — so fetch_account_by_slug has to call .json() on it. My unit test
stubbed it as a dict, so the test passed and the first live call in the container
died with "Response object has no attribute get".

The test now stubs the real shape (a response wrapper with .json()). Folding it
in here rather than hiding it: a stub that does not match the real return shape
certifies nothing.
2026-11-13 22:13:22 +00:00
inference-admin 5a7380686c webhook: a first-time contributor's order must not vanish in silence
ci/woodpecker/push/woodpecker Pipeline was canceled
On 2026-11-13 21:59:43 Open Collective delivered order.processed for a live
$5/month membership (Conor W, conor.canaday@gmail.com, order
or_eU8gRkrPCvFsaYHrgiCfz). The portal answered 200 and did nothing.

The membership branch resolves the payer by SLUG against the collective's
members list:

    members = await fetch_members()
    member = next((m for m in members if m["slug"] == slug), None)

and a first-time contributor's account is not in that list yet — OC reports the
payer as guest-…/incognito-…. So `member` was None, the branch fell through, and
because the delivery had SUCCEEDED there was no error to record either: no
account, no welcome email, no credit, no log line. The sweep's unmapped-backers
check found it hours later, which is the wrong place to find it.

Now an unknown payer is resolved from the order's account slug
(`Individual.email`, which OC exposes for an ordinary guest checkout) and handed
to the same provisioning path a known member gets. When even that yields no
email — an incognito profile, hidden on purpose — the webhook logs at ERROR that
nobody was provisioned or credited, instead of shrugging.

The defect worth naming is the SHAPE: an `if` with no `else` on a money path,
where doing nothing leaves no trace. tests/test_resolve_payer.py pins the
resolution cases (guest with email, incognito, unknown account, read failure, no
token) and the fact that the branch can no longer fall through quietly.
2026-11-13 22:12:02 +00:00
inference-admin 241ac800c6 panel state: a reminder is history, not a state — renewals clear grace, grace expires
ci/woodpecker/push/woodpecker Pipeline was canceled
mark@ofosos.org showed as in grace while his contribution was live. The sweep's
own trail says it plainly: reminded 2026-11-04 for the cycle that looked unpaid,
grace elapsed 2026-11-11, and `renewed` logged at 19:02 on 2026-11-13 (last
charge 2026-11-11, next reset 2026-11-26). The panel said grace anyway, because
member_membership_state() asked only "is there a row in payment_reminders?".

That table is a HISTORY — kept so the sweep does not re-remind inside a cycle. It
is not a state, and treating it as one broke two things: a reminder never
expired (grace is PAYMENT_GRACE_DAYS long), and a renewal never cleared it.

Now the LATEST reconciliation decision decides:
  renewed / would_renew            -> active (they are paying)
  reminder inside the window       -> in_grace
  reminder past the window         -> awaiting_contribution, saying grace elapsed
  would_deactivate / deactivated   -> awaiting_contribution
Ordered by decided_at, not id: the same member had id 2296 dated 2026-11-11 next
to id 2286 dated 2026-11-13, so "latest by id" reads the wrong decision.

Reads still fail safe: an unreadable DB reports active, never a payment problem.

tests/test_membership_state.py pins all of it, including the ordering trap.
2026-11-13 21:53:27 +00:00
inference-admin 2a77b0c988 spend: ONE all-time figure, computed once, for every surface that shows it
ci/woodpecker/push/woodpecker Pipeline was canceled
The panel's card said $941.37 and the member dashboard's said $900.51 for the
same claim. The panel used its own per-team query; the dashboard summed the
chart series IN THE BROWSER, which disagrees with the server whenever a row is
null, capped or stale.

coop_spend_totals() is now the definition: one GROUP BY over SpendLogs joined to
the team table, so
  spend_all_time      = every row (members, operators, agent teams, sandboxes) —
                        the same universe litellm_spend_by_day() sums, so the
                        cards and the money chart agree by construction
  own_all_time_spend  = the part that is the co-op's own (non-member teams, plus
                        rows with no team)
and member_all_time_spend = the rest. Exposed through /admin/overview (the
panel's boot payload), the money payload, and /broker/metrics (the dashboard's).
_coop_spend_totals_safe() returns {} rather than a zero: a failed computation
must never read as "the co-op has spent nothing".

tests/test_coop_spend_totals.py pins the arithmetic (total == member + own ==
every row) and the no-fake-zero rule.
2026-11-13 21:44:13 +00:00
inference-admin 9af0604f47 portal: /broker/money-series, so members chart the co-op's money beside its other charts
ci/woodpecker/push/woodpecker Pipeline was successful
The member dashboard could not show the money chart because the broker exposed no
money series — the same payload /admin/money-series serves the panel is aggregate
and carries no member identities (cumulative revenue, cumulative token spend, the
OC balance), so it goes through the broker for the same reason /broker/metrics
does. One chart definition, drawn identically for members and stewards.
2026-11-13 21:01:38 +00:00
inference-admin c92d8979eb spend check: compare like for like (same window, same kind of number)
ci/woodpecker/push/woodpecker Pipeline was canceled
The second live run FAILED again, correctly and informatively: portal $935.52
all-time vs LiteLLM $827.89 — and the $107.63 'drift' was the WINDOW. LiteLLM's
per-day view reaches back a fixed number of days (31 on 2026-11-13); our table
holds 69. Over the days both sides cover the two agree to $0.07, with no day
differing by more than $0.022 (the API rounds to cents).

So the check now compares DAY BY DAY over the shared window, which localises drift
instead of hiding it in a sum, with a per-day tolerance ($0.10) plus a window-total
tolerance ($5). It reads /global/spend/teams rather than /global/spend/keys: the
per-key figure follows each key's own budget cycle, so summing it is not an all-time
number at all (and /global/spend/report, the all-time one, is Enterprise-gated).

Degenerate reads are judged BEFORE the window overlap, because in the failure this
check exists for the portal's aggregate comes back EMPTY — there would be no shared
days to compare, and the overlap logic would report 'cannot compare' instead of the
stale-credential signature. All failure reporting goes through one helper that mails
info@ once per episode and advances the marker only after a notice is sent.

23 checks; all 20 suites green.
2026-11-13 20:46:50 +00:00
inference-admin c0ef046b0d spend check: read the field LiteLLM actually sends (total_spend), and fail loudly either way
ci/woodpecker/push/woodpecker Pipeline was canceled
The first live run FAILED with api $0.00 over 306 keys against the portal's $935.35.
The disagreement was real, the verdict was right, and the cause was mine: LiteLLM's
/global/spend/keys returns each key's all-time spend as `total_spend`, not `spend`.
A checker that trusts its own parse then reports "the portal is wrong" — the exact
mirror of the failure this check exists to catch, which is why the guard now names
both possibilities when the independent side reads zero against real portal spend.

Parser accepts either field name; a regression test exercises the real function
against a stubbed httpx (the module attribute is stubbed for the other checks, so
the real one is captured at import). 24 checks; all 20 suites green.
2026-11-13 20:43:41 +00:00
inference-admin e2eaa7ae40 spend consistency: the check moves into the portal's sweep
ci/woodpecker/push/woodpecker Pipeline was canceled
The failure this exists for (2026-11-05): the portal's own all-time-spend aggregate
failed SOFT when its copy of the gateway's LiteLLM DB credential went stale — the
query returned nothing, every surface showed $0, and nothing looked wrong, because
the portal WAS the thing that was wrong. The guard ran as a daily script on the
bot's host.

It now runs in the portal, and keeps two genuinely independent reads: the portal's
SpendLogs aggregate over its own DB credential, and LiteLLM's own HTTP API
(/global/spend/keys) over the master key — a different transport AND a different
credential, which is the point, since the DB copy is what goes stale.

It adds the signature guard the host script could only infer from outside: an
EMPTY//usr/bin/bash portal aggregate while LiteLLM reports real spend is a FAILURE, named as
the stale-credential case; an API side that returns no keys is a failure too, not
agreement. A read that cannot be made is skipped — never a clean bill. Silent when
they agree; info@ once per failing episode, marker cleared on recovery.
POST /admin/spend-check runs it on demand. 23 checks; all 20 suites green.
2026-11-13 20:41:27 +00:00
inference-admin bf1e5f013b unmapped backers: stop the phantom finding (the members query had no createdAt)
ci/woodpecker/push/woodpecker Pipeline was canceled
The first production run reported a null-account node as an uncredited payer. The
cause was in my port, not the data: the members query selected id-less,
date-less nodes, so every null-account node fell into the date "" bucket, matched
no same-day order, and was reported as unattributable — while the host-side script
(correctly) said clean.

Two fixes: select id + createdAt in fetch_all_member_nodes, and never emit a
null-account finding when the node carries no date — there is nothing to attribute
it against, and guessing is what produced the phantom. 27 checks in the suite.
2026-11-13 20:35:28 +00:00
inference-admin 13b6131652 notices: tell a human about what is NEW, and only when a notice actually went out
ci/woodpecker/push/woodpecker Pipeline was successful
Three fixes to the 'email only when there is a problem' rule, found by testing it:

1. The marker recorded the CURRENT set, so a set that SHRANK looked changed — one
   purchase granted dropped out, the remaining hold looked new, and it was mailed
   about twice. What a human has been TOLD is now a growing SET of keys
   (order:grant / order:hold, slug:class for backers): only keys not in it are
   mailed, and the union is stored.
2. A notify=False run advanced the marker, so a verification look CONSUMED the
   only alert a finding gets. The marker now advances only when the notice was
   actually sent (a failed send retries next sweep), and a clean pass clears it so
   a recurrence is news again.
3. The credit reconcile had the same shape of bug.

Tests updated to pin the new semantics: a smaller set re-mails nobody, a silent
look does not swallow the alert, a clean run clears the marker and a recurrence
speaks. 26 + 40 checks in those suites; all 19 suites green.
2026-11-13 20:34:24 +00:00
inference-admin eaaabf3763 unmapped backers: the paid-but-unprovisioned net moves into the portal
ci/woodpecker/push/woodpecker Pipeline was canceled
A contributor who pays and never gets an account is invisible to the sweep —
fetch_members() drops every member node with no email, and an OC Organization
never exposes one — so they wait until they ask (the mmoya case). The net for them
was a daily script on the bot's host driving `cloudron exec` from outside. The
portal holds both sides of that comparison, so it now owns it.

reconcile_unmapped_backers() runs in the sweep and reports three classes, because
each needs a different human action: an org account (link it), a VISIBLE email
(the sweep should have provisioned this — check the token/sweep), and a hidden
email (fetch it out-of-band). A node with no account object is attributed through
same-day current orders, and stays silent when every same-day payer is mapped.

MAIL POLICY (ntnsndr, 2026-11-13): only when there is a problem — and only when
the finding SET changes, fingerprinted in portal_state (slug+class only, never an
email), so a stuck finding does not mail three times a day while a fresh one
always speaks. A clean run clears the marker. A failed read returns skipped,
never a clean bill.

POST /admin/unmapped-check (X-Admin-Token, ?notify=0 to stay quiet). The
credit-pack reconcile now mails on the same rule. 25 checks; all 19 suites green.
2026-11-13 20:30:46 +00:00
inference-admin 2e40387245 webhook failures: the portal records and reports its own, not a scraper on my host
ci/woodpecker/push/woodpecker Pipeline was successful
The alert for a failed Open Collective delivery lived in portal_webhook_watch.py on
the operator's machine, polling this app's log through the Cloudron API. That put a
money-critical signal outside the system, and on a log buffer with only hours of
memory — during the 2026-11-13 investigation whole hours (06:00-13:00, 15:00) were
simply absent, so 'no failed delivery in the log' could not be distinguished from
'no delivery at all'.

The portal handles every delivery, so the portal now knows: a new webhook_failures
table records every non-2xx (including the 401 that means the URL and WEBHOOK_TOKEN
disagree, whose event type is read from a body cached before the token check), and
webhook_failure_report() in the sweep emails info@ ONCE per new batch via a marker
in the new portal_state table, so a wrong token does not mail every sweep while the
rows stay queryable. The delivery path is unchanged: bookkeeping failures are
logged, never raised, and the response stays 401/503.

19 checks in test_webhook_resilience.py; all 18 suites green.
2026-11-13 20:23:33 +00:00
inference-admin c174fa2ffe reconcile: link a row to its member by slug OR email
ci/woodpecker/push/woodpecker Pipeline was successful
Both routes are needed. A manual grant often carries no reference at all, so the
row's EMAIL is the only link to its member — and the slug and email local part
routinely differ ('henry-smith' vs 'h.smith@x.org'). The membership test was
slug-first and, when the slug matched neither the reference nor the email, dropped
the row outright: a hand-credited purchase therefore reads as a gap (ntnsndr's
2026-09-28 packs, where the ledger carries +20.00, +5.75 and a -10.75 correction
with no references). _row_belongs_to() accepts either route, in both the
accounted-for test and the nearby-rows context. 38 checks; all 18 suites green.
2026-11-13 20:20:40 +00:00
inference-admin f2b6153aa6 reconcile: show a candidate's nearby ledger rows, so a manual grant isn't read as a gap
ci/woodpecker/push/woodpecker Pipeline was canceled
Widening the window to OC's whole order history found three $5 packs from
2026-09-28 reported as uncredited — ntnsndr's launch-day purchases, which WERE
credited by hand that morning: +20.00, +5.75, then a -10.75 correction ('true
contributions were 3 x $5.00'), netting exactly $15, with no per-order reference
on any row.

credit_pack_accounted() is right not to infer 'accounted for' from a nearby
amount — that would hide genuine gaps — but a reviewer could not tell the two
cases apart from the candidate alone. Each candidate now carries its nearby
ledger/held rows (7-day window, capped at 5) and the report-mode log line prints
them, so a manual grant explains itself. Nothing about the decision changes.

36 checks; all 18 suites green.
2026-11-13 20:18:44 +00:00
inference-admin 5868ca82e8 reconcile paid credit packs against the ledger, report-first (issue #7)
ci/woodpecker/push/woodpecker Pipeline was canceled
Credits have one path in: the OC order.processed webhook. On 2026-11-13 two paid
packs got nothing through it — a $50 whose delivery 500'd on httpx's 5s default,
and a $10 with no delivery in the retained log at all — and nothing on a
schedule noticed. This adds a pass that reads OC's own order list and compares it
with our books over a day-based window (not "whatever the log still holds": the
$10 gap was 11h old and the log had lost the whole morning).

Report-first: CREDIT_RECONCILE defaults to 'report' (log findings, change
nothing) and grants only when set to 'on'. Grants go through add_credits() with
credit_pack_reference(), the same per-order key the webhook writes, so a late
delivery and this pass are idempotent against each other in both directions. A
buyer with no active membership is reported, never credited — those keep the
hold-and-email path.

credit_pack_accounted() encodes what our own rows actually look like: a v2 id, a
hyphenated legacy id, an empty-suffix legacy reference, and held_credits rows. A
bare oc:<slug>:<order.id> match read 21 credited purchases as missing during
development, so the fallback demands a second signal (member + tip-free amount +
date) before calling an order credited.

POST /admin/credit-pack-reconcile (X-Admin-Token) runs it on demand, dry unless
?apply=1 and the policy is on. 33 new checks; all 18 suites green.
2026-11-13 20:16:24 +00:00
inference-admin f45e4ef305 webhook: stop a transient OC read failure from costing a member credits
On 2026-11-13 an `order.processed` delivery for a $50 credit pack returned 500.
fetch_members() -> fetch_all_member_nodes() used a bare httpx.AsyncClient(), so OC
was given httpx's DEFAULT 5-second timeout; the read timed out, httpx.ReadTimeout
escaped the handler as an unhandled ASGI exception, and the purchase was never
credited. The member paid and got nothing, and the log held a stack trace rather
than anything naming the member or the order.

Three changes, each aimed at a different failure:

* fetch_all_member_nodes: an EXPLICIT 30s timeout, and one retry per page on a
  transport error (`_oc_graphql_post`). Still RAISES when it cannot get the full
  list — the sweep's fail-safes depend on that.
* opencollective_webhook: the work moves to _process_opencollective_webhook and a
  thin wrapper answers 503 (retryable) with an ERROR line naming the exception if
  anything unexpected escapes. A 401 stays a 401; that status is the signal that
  the webhook URL and WEBHOOK_TOKEN disagree, and swallowing it would hide a
  misconfigured webhook.
* tests/test_webhook_resilience.py proves it: 401 preserved, 503 (not 500) on a
  simulated ReadTimeout, credits granted exactly once per OC order, an identical
  re-delivery answering already_credited with no money moved, and the retry/raise
  behaviour of the transport helper.
2026-11-13 20:04:09 +00:00
inference-admin 0e825e6d61 service invites: per-room Matrix gate, resumable rate limits, Loomio record heal, 5-min sync tick
A new member could end up with a Loomio account and a Matrix account and see
NOTHING: no forum group, no Space. Three defects:

* sync_matrix_space() gated each member on the SPACE's membership, so an
  account already joined/invited to the Space was skipped for EVERY room. A
  member whose invite pass was interrupted (or who predates a room added to
  MATRIX_INVITE_ROOMS later) never received that room — and a restricted child
  room is invisible until you are invited to it. The gate is now per room, from
  a single up-front membership snapshot; a room whose membership cannot be read
  is left alone rather than invited into blindly.
* a 429 slept for retry_after_ms (minutes) INSIDE the pass, so a scheduled run
  could outlive its own tick. A rate limit now ENDS the pass; the next run
  resumes (every invite is idempotent).
* a member sitting in the Loomio group with no loomio_invited_at stamp reads as
  'never invited' — the dedupe guard was only as good as the rows it had. The
  sync now heals the record from the live roster.

And the activation window itself: provisioning skips an unactivated account by
design, and activation happens later with nobody watching, so the 3x/day sweep
was the pickup. New /admin/service-sync + a 5-minute scheduler task fires the
same idempotent syncs while any member still awaits an invite (one SELECT when
none do), and deliberately is NOT /admin/sweep — it never touches Open
Collective, allowance logic or member mail.

tests/test_service_invites.py proves the per-room gate, resumable rate limits,
the unreadable-room skip, the record heal and the endpoint's idle/run paths.
2026-11-13 17:37:57 +00:00
inference-bot 3c64b150db broker: per-member daily usage series in /broker/usage (daily: day/spend/requests)
ci/woodpecker/push/woodpecker Pipeline was successful
The member dashboard's usage chart reads per-day spend + requests for the
signed-in member, bounded by the existing days param (0 = all time, the
unchanged default). Same source and day convention as the co-op daily series
(to_char(startTime)); interior zero days are explicit so chart spacing is
true; requests excludes failed attempts; spend sums every row. Additive and
backward compatible: every existing field untouched. Tested in
tests/test_broker_usage_daily.py (route table, SQL shape, fallback twin,
fail-soft degradation).
2026-11-13 16:11:16 +00:00
inference-bot 58214be0db Guest state: the overview payload carries the definitive display state
Single derivation point (tested once, here): 'invited' while the Cloudron
invite is unaccepted, else the guests-ledger status (the record of record),
membership state only as a no-ledger-row fallback. The panel and dashboard
become pure consumers of `state` — their local invited/active derivation
goes away in their own repos next. Live-behaviour note: today's four live
guests render byte-identically; the change only shows for ended guests
(ledger 'expired' instead of the bare inactive flag), which is what the
panel already displayed via its own guest_status preference.
2026-11-11 05:16:13 +00:00
inference-bot 2954fe609f Guest invite: serialize member invites — parallel direct calls can't slip two guests
The one-per-30-days rule is a READ of the guests ledger, provisioning
takes seconds of external calls, and the ledger row that closes the
window is written LAST — so two PARALLEL direct calls (curl, bypassing
the dashboard JS) could both pass guest_request_guard before either row
exists and slip two guests past the rule. The member invite path now
runs guard+provision under _GUEST_INVITE_LOCK (single-process uvicorn),
making check-and-send atomic: the second caller re-runs the guard after
the first caller's ledger row exists and is refused 429.

tests/test_guest_concurrency.py proves both halves on the fixture DB:
unguarded, two parallel invites both provision (the test has teeth);
with the lock, exactly one provisions, one is refused 429, one ledger
row, one account, one email; sequential semantics unchanged.
2026-11-08 20:53:54 +00:00
Inferencebot 88ca8bfe18 Guest state: provisioned-but-not-set-up reads 'invited', never 'active'
A guest invitation provisions immediately, but the Cloudron account is not
ACCEPTED until the guest clicks the setup link (inviteAccepted=false, no
username) — until then they cannot log in, so no surface may read them as
active. guest_invite_pending() derives it from the same Cloudron signal the
overview's activated flag uses; unseen-record (users fetch failed) is never
pending, so the state falls back instead of asserting what the data does
not show.

/admin/overview: guest rows report state='invited' with an 'awaiting
setup' reason (invite date named when the ledger has it); /broker/guests
trail entries carry state='invited' the same way, status stays the ledger
record of record. Display/state semantics only — access rules, the $2 cap
and the expiry box are unchanged.

Tests: new test_guest_invited_state.py (derivation, overview flip,
fetch-failure fallback, member rows untouched, trail state);
test_guest_requests.py gains the trail invited/accepted assertions and a
constructible-but-loud fake client so the stubbed users fetch runs.
2026-11-08 20:40:23 +00:00
inference-bot 285aa66525 Guest invites provision immediately: remove the member approval gate
Operator decision 2026-11-08: the remaining protections (active member,
1 guest per inviter per rolling 30 days, one guest per recipient ever,
no existing portal row, MANUAL_MEMBERS refusal, the $2 cap and the
GUEST_DAYS box) are sufficient without the approval step.

* POST /broker/guests provisions through provision_guest_member at once —
  no pending state; no guest_requests row is ever written.
* GUEST_AUTO_APPROVE flag removed (the live env never carried it).
* guest_request_guard keeps the member-path rules and drops the
  trial-era pending-request checks; the 30-day window is counted from
  the guests ledger.
* GET /admin/guest-requests + approve/reject removed; GET /admin/guest-ledger
  serves the panel's duplicate-send guard.
* The member trail keeps legacy rejected requests as history only.

Built on the sibling $2-cap commit 6be8e2d.
2026-11-08 20:20:30 +00:00
inference-bot 6be8e2d632 Guest cap $5 -> $2: GUEST_BUDGET default, emails, docs, tests 2026-11-08 20:12:47 +00:00
Inferencebot 6f5e479900 Guest invitation email: drop the renewable-energy claim, state sliding-scale pricing
Operator edits:
- The co-op is described only as a member-governed AI cooperative; the
  renewable-energy claim is removed (not all providers are renewable).
- Membership pitch now states the pricing exactly: pay on a sliding
  scale, $15/month allowance plus optional credit packs, plus a say in
  how it's run.
2026-11-08 05:13:52 +00:00
inference-bot ed50031663 Admin guest invites: admin inviter, no member cap, no name guessing
The admin panel's /admin/provision-guest now takes ONE field (the guest's
email): no name is collected and none is derived from the email — the
guest chooses their own display name and username during Cloudron account
setup, and the invitation email greets neutrally when no name is known.
The guests ledger records the co-op's ADMIN account (ADMIN_INVITER_EMAIL,
default info@inference.coop) as the inviter. Admin invites provision
immediately (the operator IS the approver) and are not bound by the
member's one-per-30-days cap; recipient-side guards (one guest per
recipient ever, no existing portal row) still run. The member paths
(broker invite, request approval) keep every protection and likewise pass
no derived name.
2026-11-08 02:55:10 +00:00
inference-bot 0293d66c1e Member self-serve guest invitations with a trial approval gate
POST /broker/guests (member broker identity — guests cannot reach it) creates
a guest REQUEST; GET /broker/guests returns the member's invitation allowance
(rolling one-per-30-days, counting pending + approved requests) and their own
guest trail. guest_request_guard enforces every existing protection plus the
member-side ones: recipient never an existing member, a prior guest, a pending
request, or a MANUAL_MEMBERS address; the inviter's window counts requests too.

Trial gate (GUEST_AUTO_APPROVE, default off): requests land PENDING in the new
guest_requests table; the operator approves or rejects them via
GET/POST /admin/guest-requests (X-Admin-Token). Approval fires the full
provision_guest_member pipeline (Cloudron user, $5 credit, GUEST_DAYS box,
invitation email naming the inviter, newsletter, ledger row); a guard refusal
at approve-time is recorded on the request and surfaced. The member sees
pending/not-approved status in their own trail — the recipient is contacted
only on approval. With the flag on, a member's request provisions
immediately, no code change needed.

38-check fixture suite (tests/test_guest_requests.py) proves the gate, every
refusal path, the approve/reject actions and auto-approve with the network
replaced by a raising guard.
2026-11-08 02:42:56 +00:00
inference-bot 93184b6011 Fix the gift→guest rename migration for legacy databases
Two defects found by booting the renamed app against a fixture of the
pre-rename database (the live portal's exact state):

1. members.gift_expires_at: the RENAME above uses the stale
   snapshot, so the plain
   below fired right after a successful rename and crashed boot with
   'duplicate column name' — the portal would have failed its deploy
   health check on the live database. Make the two branches exclusive.

2. The ledger's own expiry column: ALTER TABLE guests RENAME moved the
   table but kept its legacy gift_expires_at column, which the provision
   INSERT (writing guest_expires_at) would fail on at first use. Rename
   the column with the table.

Also moves the credit-ledger dedupe references ('gift:<email>' /
'gift-return:<email>') to their guest prefixes at boot — returns first,
since 'gift-return:…' also matches 'gift:%' — so a re-grant after the
rename cannot double-credit.

Verified: migration harness 10/10 on a legacy-state fixture (renames,
value conversion, ref migration, idempotent second boot, readback
helpers); full portal suite 9/9 files green.
2026-11-08 02:42:53 +00:00
inference-bot 27f9cc06b2 Rename gift to guest throughout: routes, ledger table, account_type values, env names, emails, tests
Pure rename, no behaviour change, matching the renamed panel and dashboard
builds. Includes one-time idempotent migrations for existing databases
(gifts->guests table, gift_expires_at->guest_expires_at column,
account_type 'gift'->'guest' values, gift_lapse_notices->guest_lapse_notices)
and four transitional alias routes (admin/provision-gift, admin/gift-convert,
broker/gift-status, broker/cancel-gift) so pre-rename dashboard/panel builds
keep working until they are redeployed.
2026-11-08 02:41:05 +00:00
inference-bot 40fb75a34b gift cancel: self-service cancellation with credit return and full audit trail
POST /broker/cancel-gift (dashboard broker identity, gift accounts only,
idempotent) + GET /broker/gift-status for the ended-state view. Semantics
match the gift lapse: row deactivated, account kept for a clean resume,
gateway budget zeroed, newsletter off — plus the return a lapse does not
do: unspent credit back to the co-op as a NEGATIVE credit_ledger row whose
reason names the cancellation and the original gift reference, deduped on
its own reference. Gifts ledger records inviter → recipient → 'cancelled
by recipient'. The user leaves the guests group for GUESTS_ENDED_GROUP_ID
(dashboard-only visibility for the ended state); the reaching-limits
notice is pre-marked so a self-cancelled guest is never told their
credits were spent. Tests: tests/test_gift_cancel.py (19 fixture checks,
network-guarded).
2026-11-08 02:28:45 +00:00
inference-bot 0b0bdaab6f gift emails: invitation at gift time + once-only reaching-limits notice
- gift_welcome_email becomes gift_invitation_email: the ONE email a gift
  sends (the invitation and the guest welcome merged, not two mails at
  once). Subject 'You've been invited to the Inference Cooperative'; names
  the inviter (member slug), the $5 credits, the setup link, the
  Become-a-member button on BECOME_MEMBER_URL. Uses the shared
  PINE_LOGO_SVG instead of an inline copy.
- reaching-limits email (gift_limits_email, 'Your guest access has ended —
  become a member to continue') wired into the sweep's gift deactivation:
  sent once per guest, gated by a gift_lapse_notices sent-state row (same
  pattern as mark_shortfall_notice_sent). Says the access ended, the
  account and data are kept, and membership ($15/mo via Open Collective)
  restores a full monthly allowance + community spaces.
- catch-up pass in reconcile_gift_lifecycles: guests deactivated before the
  email shipped (or a failed send) get exactly one notice on a later sweep;
  converted guests are excluded by account_type.
- sweep summary now reports gift_lapse_notices.
- test_gift_lifecycle: invitation-subject assertion; send_email stub
  returns True (the bool is the gate's contract); new once-only + catch-up
  + healthy-untouched checks. 43/43.
2026-11-08 02:22:59 +00:00
inference-bot c6eb2b44e8 overview: guests are their own list, excluded from member counts
/admin/overview now returns gift (guest) accounts in a separate guests[]
list instead of inside members[], and excludes them from totals.members,
totals.active and the member spend totals. Guests get their own totals
breakout (guests, guests_active, guest_spend, guest_all_time_spend) so
their spend stays visible without ever reading as member activity — the
same reasoning as the operator (admins) and agent categories.

Builds on the gift feature's account_type marker: a guest is any row with
account_type='gift'. The panel reads guests[] and ignores gift rows in
its member count either way.
2026-11-08 02:09:28 +00:00
inference-bot 6d9074eefe gift accounts: $5 guest passes with time box, inviter ledger, auto member conversion
Operator feature: a member gives a friend access with $5 of credits, no OC
membership. Cloudron user lands in the guests group (chat + dashboard only),
LiteLLM team capped at GIFT_BUDGET with NO monthly reset, portal row marked
account_type='gift' with gift_expires_at set, gift welcome email, newsletter
subscription, and a gifts ledger recording inviter -> recipient (one gift per
inviter per 30 days, one per recipient ever).

Sweep safety: reconcile_memberships never deactivates a gift for lacking an
OC contribution; reconcile_gift_lifecycles lapses gifts by their own rules
(credits spent out, or the GIFT_DAYS time box) with member-deactivation
semantics. Guests are excluded from Loomio/Matrix invite lists, the reinvite
path, budget notices, the allowance reconciliation and the metrics member
counts.

Conversion: a gift whose OC identity appears under its own email converts
automatically (webhook + sweep + /admin/provision all funnel through
provision_member): group guests->members, cap lifted to allowance + carried
credits, anchor day kept, congrats email, full member onboarding.
/admin/gift-convert links a membership paid under a different OC email
(members.oc_email, matched by the sweep and webhook).

Fixture test: tests/test_gift_lifecycle.py (37 checks, network replaced by
a raising guard).
2026-11-08 02:05:37 +00:00
inference-bot 2d2d191e11 money-series: drop the caveat field from the payload
The operator removed all caveats from the finance chart; the balance-history
note is gone from the API payload too so it cannot reappear anywhere.
balance_history_start, the series, totals, sources and errors are unchanged.
2026-11-08 01:55:23 +00:00
inference-bot dcce9fcb35 money series: /admin/money-series (revenue/spend/OC balance) + daily OC balance snapshot
- /admin/money-series (X-Admin-Token, 30/min): three series for the admin
  panel's Money chart, hourly in-memory cache with stale-on-error fallback.
  revenue = OC contribution transactions (CREDIT/CONTRIBUTION/non-refund,
  monthly + one-time, org-backed included), cumulative from 2026-09-06;
  spend = one GROUP BY day pass over the full LiteLLM SpendLogs (no team
  filter, same definition as metrics_snapshot.spend_by_day); balance = OC
  current balance + daily snapshots.
- OC exposes only the CURRENT balance — no historical series exists — so
  metrics_snapshot.py now writes oc_balance_usd into metrics_daily daily
  (from 2026-11-08 onward; balance history cannot be backfilled). The
  endpoint seeds an existing row's balance with the live value without
  touching the snapshot's other columns.
- Aggregate totals only: no member emails or names selected or returned.
2026-11-08 01:50:17 +00:00
inference-bot ed66d73327 activation hook: fire Loomio+Matrix syncs at first broker login
New members were skipped by the syncs until their Cloudron account was
activated (deliberately - never invite a half-created account), but nothing
fired the syncs at the moment they DID activate: the 3x/day sweep was the
only pickup, so a newly-activated member could wait hours for forum/space
access (limdingwen waited ~5h on 2026-11-06).

Hook the broker identity path (_verify_broker_secret): after an active
member resolves, if loomio_invited_at is still null, confirm their Cloudron
account is activated (inviteAccepted, fail-CLOSED - an unreadable user list
never fires) and run the same idempotent syncs the sweep runs, as a
background task off the response. Established members pay one indexed
SELECT; concurrent first-logins collapse into one run via an inflight flag;
each service is independently best-effort so a Loomio outage cannot block
the Matrix invite or the response.

Tests: tests/test_first_login_sync.py (18 checks, fixture db + stubbed
network). Also fix test_allowance_shortfall, whose expected exclusion
reference still asserted the pre-a88ca86 placeholder.

Sweep, provisioning and deactivation paths are untouched.
2026-11-06 19:51:12 +00:00
inference-bot a88ca860d4 fix: restore the real OC tx reference in SHORTFALL_REMEDIATED (repo must match the deployed image)
The deployed portal image (20261105-ca3b8db) was built from a working tree
carrying the real transaction id; commit 22c0167 over-redacted it to a
placeholder that matches nothing, so the next build would lose the exclusion
that prevents double-crediting the manually-remediated 2026-11-04 shortfall
charge. Sync HEAD to the deployed bytes (md5-identical to the running
container). The tx id alone is the H2-approved form: it identifies the OC
transaction, carries no member email.
2026-11-05 18:55:15 +00:00
inference-bot 00f60f1374 ops: bound allowance_log growth; correct stale README claims (audit L4+L5)
allowance_log: the sweep and every report-mode run used to append a row
per member per run (~500/day measured). The insert is now an upsert per
(member, cycle, decision) — a re-derived decision updates the row's
evidence and timestamp; a decision CHANGE still gets its own row. No
index or migration; the latest-decision readers are unaffected; history
is not rewritten.

README: scheduler runs 3x/day (0 3,11,19 UTC), not nightly-3am; the
sweep's auth is the ADMIN_TOKEN X-Admin-Token header, not WEBHOOK_TOKEN;
the retired free/member/supporter tier budgets replaced by the actual
single MEMBER_BUDGET model; the unread OPENCOLLECTIVE_WEBHOOK_SECRET env
row removed.
2026-11-05 16:26:16 +00:00
inference-bot ce1bc7bee6 security: log every key-feed fetch (audit M2)
/admin/librechat/keys deliberately serves every member's chat key on one
sync token (the LibreChat sandbox seeds from it; a per-member fetch would
require changing the sandbox's identity model — decision recorded in
ops-docs maintenance/librechat-key-feed.md). Every fetch now logs a
count-only WARNING (no key material; the email redactor strips addresses)
with caller + user-agent, and the daily digest watches the rate against
the sandbox's ~10-min poll cadence.
2026-11-05 16:21:51 +00:00
inference-bot d63f702ec3 privacy: redact member emails from portal logs (audit M1)
The _RedactWebhookPath filter now also strips email-shaped strings from
every log record — messages, %-format args (recursing into tuple/list/
dict args), and any exception text already attached to the record — the
same retention discipline the webhook token got in ops/security#2.
_send_email recipients, listmonk failures, Loomio invite lists and
provisioning/credit lines carry member addresses into container logs,
which persist on the host and ride the backups. MXIDs, counts, slugs and
amounts stay readable; the daily digest's own sanitisation is unchanged.
Filter keeps its never-break-logging guarantee (all redaction inside
try/except; non-string args untouched).

Live pre-state measured: 99 email-bearing lines in the current app log.
2026-11-05 16:17:21 +00:00