Skip to content
Merged
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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## [0.9.1] - 2026-11-10

### Fixed

- **Paid features are unlocked on the first paint.** A signed-in page now reads the plan's features, the billing state and the flag definitions before Angular renders it (each read capped at 1.5 seconds), so a paying user no longer sees "Upgrade to use this" flash on a plan-gated feature. Flags also re-check when the plan, its features or a plan limit change, so a feature unlocks straight after an upgrade and locks after a downgrade, with no reload.
- **Billing screens stay current.** The plan picker, the subscription badge and the billing notice re-read when the sign-in renews, when a plan or subscription changes in Bridge, and when the tab regains focus after 30 seconds. A plan added or changed in Bridge shows without a reload, and the current plan stays on screen while it re-reads. A plan list that comes back empty or fails to load now offers **Try again** instead of "No plans available."
- **A flag on a route is a live kill switch.** Switching off the flag a route rule names now moves someone already on that page to the rule's `redirectTo` within about a second, without a click. A flag that changed while live updates were down is picked up when they reconnect.

### Changed

- **Guides follow "every gate is a flag".** The billing and feature-flags guides open with the rule and end with `npx @nebulr-group/bridge-cli check gates`. A paid feature is taught as a flag ruled on the plan's feature, with direct plan checks kept as the exception. The guides name the MCP tools next to the CLI commands, the team guide teaches seat limits with `seatsMetric`, and the live-updates page explains each status reason and links the troubleshooting page.
- **The guides are checked against the package.** A test now fails if a guide imports, renders or configures something the package does not have.

## [0.9.0] - 2026-11-10

### Changed
Expand Down
2 changes: 1 addition & 1 deletion bridge-angular/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nebulr-group/bridge-angular",
"version": "0.9.0",
"version": "0.9.1",
"description": "The Bridge for Angular: sign-in, workspaces and roles, feature flags, Stripe subscriptions and plan limits with providers and route helpers.",
"author": "Iman Pouya",
"license": "MIT",
Expand Down
269 changes: 269 additions & 0 deletions bridge-angular/src/doc-currency.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
// TBP-705 — the guides this repo serves to AI agents (mcp/, learning/, README.md,
// read from GitHub main by the Bridge MCP server) must not teach what the rule
// forbids. The owner's rule (2026-09-29): every gate in app code is a flag, and
// its rule says why — a privilege, a plan feature
// (`bridge:billing.entitlement.<key> eq true`) or a rollout. App code never reads
// a role, a privilege list, the plan or a plan feature to decide what someone may
// see or do. Browser-only counting is a complete, first-class way to run limits.
//
// A sentence that tells the reader NOT to do it is allowed, and so is anything
// in the one section a guide may have whose heading says "Exceptions".
//
// The pattern list, the negation list and the Exceptions scoping MIRROR
// bridge-cli `src/gate-rules.ts` (DOC_FORBIDDEN / docGateViolations), which is
// the source of truth and also drives `bridge check gates`. Keep them the same:
// change it there first, then copy it here.
//
// Angular port (TBP-705 parity): the same patterns, plus the Angular spellings
// of a direct plan-feature check (`*bridgeEntitled`, `injectEntitlements()`).
// Lives in src/ (not src/lib) and is a .spec.ts, so the library build never
// includes it.

import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

// ── Mirror of bridge-cli src/gate-rules.ts (docs part) ──────────────────────

const DOC_FORBIDDEN: Array<[string, RegExp]> = [
['a role compared in code', /\b(?:user|session|claims|token|me|currentUser|profile|locals\.user|req\.user|\$user|\$profile)\??\.role\s*(?:===|!==|==|!=)/],
['a role compared in code', /\brole\s*(?:===|!==|==|!=)\s*['"`]/i],
['a role list checked in code', /\[\s*['"][A-Z_]+['"](?:\s*,\s*['"][A-Z_]+['"])*\s*\]\s*\.includes\(/],
['a role checked in code', /\bhasRole\s*\(/],
['a role decorator on a handler', /@RequireRole\s*\(/],
['a role check on the page', /\brole check\b[^.\n]{0,30}\b(?:in|on) (?:the |your )?(?:page|component|code|handler|layout|controller)/i],
['a role check on the page', /\bcheck\w*\b[^.\n]{0,30}\brole\b[^.\n]{0,30}\b(?:in|on) (?:the |your )?(?:page|component|code|layout)\b/i],
['"target a role instead"', /target a role instead/i],
['privileges read in code', /\bprivileges\s*\??\.\s*(?:includes|some|indexOf|has)\s*\(/],
['a direct plan-feature check', /<Entitled\b/],
['a direct plan-feature check', /\*bridgeEntitled\b/],
['a direct plan-feature check', /\binjectEntitlements\s*\(\s*\)\s*\(\s*\)\s*\.\s*can\s*\(/],
['a direct plan-feature check', /\bentitlements\s*\??\.\s*can\s*\(/],
['a direct plan-feature check', /@RequireEntitlement\s*\(/],
['a plan name compared in code', /\.plan(?:Key|Name|Slug)?\s*(?:===|!==|==|!=)\s*['"`]/],
['a plan name compared in code', /\bplan(?:Key|Name|Slug)?\s*(?:===|!==|==|!=)\s*['"`]/i],
['a plan-name helper', /\bis(?:Pro|Free|Enterprise|Team|Business)(?:Plan|User)?\b\s*[(=]/],
['a route rule on plans', /\bplans\s*:\s*\[/],
['a route rule on a role', /\{[^}\n]*\b(?:match|path)\s*:[^}\n]*\brole\s*:\s*['"`]/],
['a route rule on a privilege', /\bprivilege\s*:\s*['"`](?!ANONYMOUS|AUTHENTICATED)[A-Z_]+['"`]/],
['a flag rule that names plans', /"attribute"\s*:\s*"(?:tenant\.plan|bridge:billing\.plan)"/],
['browser counting called demo-grade', /demo[- ]grade/i],
['browser counting called display only', /display,? not enforcement/i],
['browser counting said unable to refuse', /only (?:a|the|your) backend can (?:refuse|enforce|stop)/i],
[
'browser counting said not to work',
/\b(?:browser|frontend|client)(?:[- ](?:only|side))?\b[^.\n]{0,40}\b(?:won't|will not|does not|doesn't|cannot|can't|can not) (?:work|enforce|be trusted)/i,
],
['browser counting said not production-ready', /\b(?:browser|frontend|client)\b[^.\n]{0,60}\bnot (?:production|prod)[- ](?:ready|grade)/i],
['privileges said to match as text', /\b(?:matched|matches|match) (?:privilege keys )?as text\b|\bno other (?:privilege )?key contains\b/i],
];

/** A sentence that tells the reader NOT to do the forbidden thing. */
const NEGATED = /\b(?:never|instead of|rather than|do not|don't|not a|is gone|no longer)\b/i;

const HEADING = /^(#{1,6})\s+(.*)$/;

type DocViolation = { line: number; rule: string; text: string };

function docGateViolations(markdown: string): DocViolation[] {
const out: DocViolation[] = [];
let exceptionLevel = 0;
let inFence = false;
markdown.split('\n').forEach((line, i) => {
if (/^\s*(?:```|~~~)/.test(line)) inFence = !inFence;
const heading = inFence ? null : HEADING.exec(line);
if (heading) {
const level = heading[1].length;
if (exceptionLevel && level <= exceptionLevel) exceptionLevel = 0;
if (/exception/i.test(heading[2])) exceptionLevel = level;
return;
}
if (exceptionLevel) return;
for (const sentence of line.split(/(?<=[.!?])\s+/)) {
if (NEGATED.test(sentence)) continue;
for (const [rule, pattern] of DOC_FORBIDDEN) {
if (pattern.test(sentence)) out.push({ line: i + 1, rule, text: sentence.trim() });
}
}
});
return out;
}

// ── This repo's agent-facing docs ───────────────────────────────────────────

const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
// (this file is bridge-angular/src/doc-currency.spec.ts; REPO is the repo root)

function markdownFiles(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name);
if (statSync(path).isDirectory()) return markdownFiles(path);
return name.endsWith('.md') ? [path] : [];
});
}

const read = (file: string) => readFileSync(file, 'utf8');
const agentDocs = [...markdownFiles(join(REPO, 'mcp')), ...markdownFiles(join(REPO, 'learning')), join(REPO, 'README.md')];

describe('no agent-facing guide teaches a direct role, privilege or plan check, or talks browser counting down — TBP-705', () => {
it('finds the guides (guards against scanning nothing)', () => {
expect(agentDocs.length).toBeGreaterThan(10);
expect(agentDocs).toContain(join(REPO, 'mcp', 'billing-prompt.md'));
});

it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => {
expect(docGateViolations(read(file))).toEqual([]);
});

// Owner 2026-09-29: the trust trade-off of browser counting belongs to human
// docs only. mcp/ and learning/ are served to agents; the README may say it once.
it('the browser-counting trust trade-off is not in mcp/ or learning/, and at most once in the README', () => {
const TRADE_OFF = /trusts the browser|could report less than/i;
const inAgentGuides = agentDocs
.filter((f) => f !== join(REPO, 'README.md'))
.filter((f) => TRADE_OFF.test(read(f)))
.map((f) => relative(REPO, f));
expect(inAgentGuides).toEqual([]);
expect(read(join(REPO, 'README.md')).match(new RegExp(TRADE_OFF.source, 'gi'))?.length ?? 0).toBeLessThanOrEqual(1);
});

describe('goes red on a planted bad line', () => {
it.each([
'For admin-only pages, add a role check on the page: `if (user.role === "ADMIN")`.',
"Gate the page with `{#if $auth.user.role == 'ADMIN'}`.",
"Gate the link with `@if (profile()?.role === 'ADMIN')`.",
'Wrap the chart in `<app-chart *bridgeEntitled="\'analytics\'" />`.',
"Show it when `this.bridge.tenant.entitlements.can('exports')`.",
"Put `@RequireRole('ADMIN')` on the handler.",
'Check the role in the component before rendering the button.',
"Show analytics when `tenant.plan === 'pro'`.",
"if (plan === 'pro') showAnalytics();",
'const isPro = subscription.plan.key === "pro";',
'{ "conditions": [{ "attribute": "tenant.plan", "operator": "eq", "values": ["pro"] }] }',
'Wrap the chart in `<Entitled to="analytics">`.',
"Show the button when `$entitlements.can('exports')`.",
"Put `@RequireEntitlement('analytics')` on the handler.",
"const canManageTeam = ['OWNER', 'ADMIN'].includes(role);",
"Show the link when `privileges.includes('USER_WRITE')`.",
"{ path: '/reports/*', privilege: 'REPORTS_VIEW' }",
"{ path: '/reports/*', privilege: 'AUTHENTICATED', plans: ['pro'] }",
'Browser counting is display, not enforcement.',
'Only a backend can refuse a click over the limit.',
'Offer "Browser only (demo-grade)" as the last option.',
'A frontend-only app cannot enforce a limit.',
'Counting in the browser is not production-ready.',
])('%s', (bad) => {
expect(docGateViolations(bad)).not.toEqual([]);
});

it('and in a real guide file, not only in isolation', () => {
const planted = `${read(join(REPO, 'mcp', 'team-prompt.md'))}\nShow the Team link when \`['OWNER','ADMIN'].includes(role)\`.\n`;
const found = docGateViolations(planted);
expect(found.length).toBeGreaterThan(0);
for (const v of found) expect(v.text).toContain("['OWNER','ADMIN'].includes(role)");
});
});

describe("stays green on the rule's own sentences", () => {
it.each([
'**Every gate in app code is a flag.** A link, a page, a button, an endpoint: if some people get it and others do not, the code asks a flag, and the flag\'s rule says why: a privilege (`privileges contains "USER_WRITE"`), a plan feature (`bridge:billing.entitlement.analytics eq true`) or a rollout.',
'App code never reads a role, a privilege list, the plan or a plan feature to decide what someone may see or do.',
'Control it with a flag rule, never with a role check written into the app\'s code.',
'Never gate the Team link with `[\'OWNER\',\'ADMIN\'].includes(role)`.',
'A role rule (`user.role eq "ADMIN"`) is fine when the developer means the role itself.',
"{ match: '/admin/*', featureFlag: 'admin-area', redirectTo: '/' }",
"{ path: '/health', privilege: 'ANONYMOUS' }",
'Browser-only counting is a first-class, complete way to run limits.',
'Never describe browser counting as demo-grade.',
])('%s', (good) => {
expect(docGateViolations(good)).toEqual([]);
});

it('a direct plan-feature check inside the Exceptions section, and only there', () => {
const guide = [
'## Gating',
'Use `<bridge-feature-flag key="analytics">`.',
'## Exceptions',
'When the developer asks for no flag, `*bridgeEntitled="\'analytics\'"` reads the plan directly.',
'### Details',
"`$entitlements.can('analytics')` is the same check in script.",
'## Next',
'Wrap it in `<app-x *bridgeEntitled="\'analytics\'" />`.',
].join('\n');
expect(docGateViolations(guide).map((v) => v.line)).toEqual([8]);
});
});
});

// ── TBP-763 — seats ─────────────────────────────────────────────────────────
//
// Owner decisions 2026-09-29: seats are a plan limit the app names (e.g.
// `seats`), kind gauge, counted by Bridge from membership (`--source
// membership`). There is no built-in `users` seat metric. The limit is enforced
// where invites start — `seatsMetric="seats"` on the built-in team page, or
// `@RequireQuota('seats')` on the app's own invite handler — because Bridge's
// invite API does not refuse at the limit. Never a flag or an entitlement.

const SEAT_FORBIDDEN: Array<[string, RegExp]> = [
['`users` as the built-in seat metric', /\bseats?\b\**\s*\(\s*`(?:metric:\s*)?["']?users["']?`\s*\)/i],
['`users` as the built-in seat metric', /@RequireQuota\(\s*['"]users['"]/],
['`users` as the built-in seat metric', /--metric\s+users\b|"metric"\s*:\s*"users"|\bmetric:\s*["']users["']/],
['seats gated with a flag or an entitlement', /\bseats?\b[^.\n]{0,60}(?:<FeatureFlag|<Entitled|<bridge-feature-flag|\*bridgeEntitled|@RequireEntitlement|\bentitlement\b|\bflag\b)/i],
];

function seatViolations(markdown: string): DocViolation[] {
const out: DocViolation[] = [];
markdown.split('\n').forEach((line, i) => {
for (const sentence of line.split(/(?<=[.!?])\s+/)) {
if (NEGATED.test(sentence) || /\bno built-in\b/i.test(sentence)) continue;
for (const [rule, pattern] of SEAT_FORBIDDEN) {
if (pattern.test(sentence)) out.push({ line: i + 1, rule, text: sentence.trim() });
}
}
});
return out;
}

const SEATS_CLI = 'bridge plan quota set <plan> --metric seats --limit N --policy hard --kind gauge --source membership';

describe('seats are a plan limit the app names, counted from membership — TBP-763', () => {
it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => {
expect(seatViolations(read(file))).toEqual([]);
});

it.each([['mcp/team-prompt.md'], ['mcp/billing-prompt.md']])('%s teaches the seat setup and both enforcement points', (file) => {
const guide = read(join(REPO, file));
expect(guide).toContain(SEATS_CLI);
expect(guide).toContain('seatsMetric="seats"');
expect(guide).toContain("@RequireQuota('seats')");
expect(guide).toMatch(/invite API does not refuse at the limit/i);
expect(guide).toMatch(/built-in team page or the app's own invite handler|built-in team page, or the app's own invite handler/i);
expect(guide).toMatch(/never gate seats with a flag or an entitlement/i);
});

describe('goes red on a planted bad line', () => {
it.each([
'Seats (`metric: "users"`) are counted by Bridge from workspace members.',
'**Seats** (`users`) are a gauge Bridge keeps itself.',
"Put `@RequireQuota('users')` on your invite handler.",
'bridge plan quota set free --metric users --limit 2 --policy hard',
'Gate the invite button on seats with a flag rule.',
'Gate seats with `<bridge-feature-flag>` around Invite.',
'Put the seat count behind an entitlement.',
])('%s', (bad) => {
expect(seatViolations(bad)).not.toEqual([]);
});
});

describe('stays green on the guides’ own sentences', () => {
it.each([
'There is no built-in `users` metric.',
'Never gate seats with a flag or an entitlement: a seat count is a limit.',
SEATS_CLI,
"`@RequireQuota('seats')` on that backend handler.",
])('%s', (good) => {
expect(seatViolations(good)).toEqual([]);
});
});
});
Loading
Loading