agy-family 0.6.4 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.6.4",
3
+ "version": "0.6.5",
4
4
  "description": "Zero-privacy-leak transparent usage dashboard, /family slash command, and fair-use budget guardrail for Google One / Antigravity family groups.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -71,7 +71,7 @@ import {
71
71
  upsertHostEntry,
72
72
  } from '../src/host.mjs';
73
73
 
74
- const CLI_VERSION = '0.6.4';
74
+ const CLI_VERSION = '0.6.5';
75
75
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
76
76
  const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
77
77
 
@@ -382,6 +382,32 @@ async function runHookCommand(eventArg) {
382
382
  child.unref();
383
383
  }
384
384
  } catch {}
385
+ } else if (capturedRes.captured) {
386
+ // Collaborative family quota sync: verified members passively help keep the shared family pool up to date!
387
+ try {
388
+ const clientCfg = readJsonSafe(clientConfigPath(home));
389
+ const expectedHash = String(clientCfg?.expectedEmailHash || '').trim().toLowerCase();
390
+ const capturedHash = String(capturedRes.emailHash || '').trim().toLowerCase();
391
+ const memberMatches = Boolean(
392
+ clientCfg?.url &&
393
+ clientCfg?.token &&
394
+ (!expectedHash || (capturedHash && capturedHash === expectedHash)),
395
+ );
396
+ if (memberMatches) {
397
+ const throttlePath = join(configBaseDir(home), 'last-member-quota-push.json');
398
+ const prev = readJsonSafe(throttlePath);
399
+ const now = Date.now();
400
+ if (!prev?.ts || now - Number(prev.ts) >= 60_000) {
401
+ writePrivateJson(throttlePath, { ts: now });
402
+ const child = spawn(process.execPath, [THIS_CLI_PATH, 'sync', '--quiet'], {
403
+ detached: true,
404
+ stdio: 'ignore',
405
+ windowsHide: true,
406
+ });
407
+ child.unref();
408
+ }
409
+ }
410
+ } catch {}
385
411
  }
386
412
 
387
413
  const chain = readJsonSafe(statusLineChainPath(home));
@@ -451,6 +477,13 @@ async function performJoin({ rawInvite, noHook = false, withDaemon = false }) {
451
477
  cliPath: THIS_CLI_PATH,
452
478
  });
453
479
  console.log(`✓ Installed /family zero-token command & auto-sync hook (${info.hooksFile})`);
480
+ const tap = installStatusLineTap({
481
+ executable: process.execPath,
482
+ cliPath: THIS_CLI_PATH,
483
+ });
484
+ console.log(
485
+ `✓ Enabled zero-secret statusLine quota capture (${tap.chained ? 'chained seamlessly with your existing statusLine' : 'standalone'})`,
486
+ );
454
487
  }
455
488
  if (withDaemon) {
456
489
  const d = installBackgroundDaemon({
@@ -553,18 +586,31 @@ async function main() {
553
586
  executable: process.execPath,
554
587
  cliPath: THIS_CLI_PATH,
555
588
  });
556
- console.log(`✓ Enabled /family slash command & Stop auto-sync hook:\n Skill: ${info.skillFile}\n Hooks: ${info.hooksFile}`);
589
+ const tap = installStatusLineTap({
590
+ executable: process.execPath,
591
+ cliPath: THIS_CLI_PATH,
592
+ });
593
+ console.log(
594
+ `✓ Enabled /family slash command, Stop auto-sync & zero-secret statusLine quota capture:\n Skill : ${info.skillFile}\n Hooks : ${info.hooksFile}\n statusLine : active (${tap.chained ? 'chained with existing statusLine' : 'standalone'})`,
595
+ );
557
596
  return;
558
597
  }
559
598
  if (action === 'off' || action === 'uninstall' || action === 'remove') {
560
599
  const info = uninstallAntigravityIntegration();
561
- console.log(`✓ Removed agy-family hook (${info.removedHook ? 'deleted' : 'not present'}) and /family skill (${info.removedSkill ? 'deleted' : 'not present'}).`);
600
+ const sl = !readMasterConfig() ? uninstallStatusLineTap() : { restored: false };
601
+ console.log(
602
+ `✓ Removed agy-family hook (${info.removedHook ? 'deleted' : 'not present'}) and /family skill (${info.removedSkill ? 'deleted' : 'not present'})${sl.restored ? '; restored previous statusLine' : ''}.`,
603
+ );
562
604
  return;
563
605
  }
564
606
  const status = inspectAntigravityIntegration();
607
+ const tapStatus = inspectStatusLineTap();
565
608
  console.log(`Antigravity /family Integration:`);
566
- console.log(` Hook : ${status.hookInstalled ? (status.hookEnabled ? 'enabled' : 'disabled') : 'not installed'} (${status.hooksFile})`);
567
- console.log(` Skill : ${status.skillInstalled ? 'installed' : 'not installed'} (${status.skillFile})`);
609
+ console.log(` Hook : ${status.hookInstalled ? (status.hookEnabled ? 'enabled' : 'disabled') : 'not installed'} (${status.hooksFile})`);
610
+ console.log(` Skill : ${status.skillInstalled ? 'installed' : 'not installed'} (${status.skillFile})`);
611
+ console.log(
612
+ ` statusLine : ${tapStatus.installed ? `active (${tapStatus.chained ? 'chained' : 'standalone'})` : 'not installed'}`,
613
+ );
568
614
  return;
569
615
  }
570
616
 
@@ -890,7 +890,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
890
890
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
891
891
  deviceId,
892
892
  clientKind: 'cli',
893
- clientVersion: '0.6.4',
893
+ clientVersion: '0.6.5',
894
894
  home,
895
895
  fileCache: cache,
896
896
  syncedHashes: prevHashes,
@@ -83,7 +83,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
83
83
  export async function buildSyncPayload({
84
84
  deviceId,
85
85
  clientKind = 'cli',
86
- clientVersion = '0.6.4',
86
+ clientVersion = '0.6.5',
87
87
  home,
88
88
  roots = null,
89
89
  sourceFilter = 'all',
@@ -164,7 +164,7 @@ export async function buildSyncPayload({
164
164
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
165
165
  client: {
166
166
  kind: clientKind === 'extension' ? 'extension' : 'cli',
167
- version: String(clientVersion || '0.6.4').slice(0, 24),
167
+ version: String(clientVersion || '0.6.5').slice(0, 24),
168
168
  ...(platformLabel ? { platform: platformLabel } : {}),
169
169
  },
170
170
  account: {
@@ -26,7 +26,7 @@ import {
26
26
  import { FAVICON_SVG, renderDashboardHtml } from './ui.mjs';
27
27
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
28
28
 
29
- export const SERVER_VERSION = '0.6.4';
29
+ export const SERVER_VERSION = '0.6.5';
30
30
  const MAX_BUCKETS_PER_SYNC = 1000;
31
31
  const MAX_DEVICES_PER_MEMBER = 8;
32
32
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -1202,19 +1202,22 @@ export function createApp({
1202
1202
  const isExplicitMaster = Boolean(body.subscriptionQuota?.isMasterExplicit);
1203
1203
  const incomingQuotaHash = String(body.subscriptionQuota?.emailHash || '').trim().toLowerCase();
1204
1204
  const validIncomingHash = /^[a-f0-9]{64}$/.test(incomingQuotaHash) ? incomingQuotaHash : '';
1205
- const mgrBoundHash = String(member.expected_email_hash || '').trim().toLowerCase();
1206
- const quotaHashMatchesManager = mgrBoundHash
1207
- ? (validIncomingHash ? validIncomingHash === mgrBoundHash : !isMismatch)
1205
+ const boundHash = String(member.expected_email_hash || '').trim().toLowerCase();
1206
+ const quotaHashMatchesMember = boundHash
1207
+ ? (validIncomingHash ? validIncomingHash === boundHash : !isMismatch)
1208
1208
  : (!isMismatch || isExplicitMaster);
1209
1209
  const safeLabel = normSubQuota.accountLabel || member.email_address || member.email_hint || member.name || '';
1210
1210
  const normWithLabel = { ...normSubQuota, accountLabel: safeLabel };
1211
- if (!isMismatch) {
1211
+ if (!isMismatch && quotaHashMatchesMember) {
1212
1212
  writeStmts.push({
1213
1213
  sql: UPSERT_SUBSCRIPTION_QUOTA_SQL,
1214
1214
  params: buildSubscriptionQuotaParams(`member:${member.id}`, member.id, normWithLabel, now),
1215
1215
  });
1216
+ if (member.role === 'member' && boundHash && accountStatus === 'verified') {
1217
+ masterQuotaUpdated = true;
1218
+ }
1216
1219
  }
1217
- if (member.role === 'manager' && quotaHashMatchesManager) {
1220
+ if (member.role === 'manager' && quotaHashMatchesMember) {
1218
1221
  writeStmts.push({
1219
1222
  sql: UPSERT_SUBSCRIPTION_QUOTA_SQL,
1220
1223
  params: buildSubscriptionQuotaParams('master', member.id, normWithLabel, now),
@@ -1765,7 +1768,7 @@ export function createApp({
1765
1768
  }
1766
1769
 
1767
1770
  if (request.method === 'DELETE' && path === '/api/admin/master-quota') {
1768
- await db.run('DELETE FROM subscription_quotas WHERE scope = ?', ['master']);
1771
+ await db.run('DELETE FROM subscription_quotas');
1769
1772
  const masterSubscriptionQuota = await loadMasterSubscriptionQuota(db, now);
1770
1773
  return adminJsonRes({ ok: true, masterSubscriptionQuota });
1771
1774
  }
@@ -378,15 +378,287 @@ export function evaluateSubscriptionQuotaRow(row, now = Date.now()) {
378
378
  };
379
379
  }
380
380
 
381
- export async function loadMasterSubscriptionQuota(db, now = Date.now()) {
381
+ const TIER_RANK = Object.freeze({
382
+ 'Google AI Ultra': 3,
383
+ 'Google AI Pro': 2,
384
+ Free: 1,
385
+ });
386
+
387
+ function pickConsensusPlanTier(masterRow, memberEntries) {
388
+ if (masterRow?.plan_tier) return normalizePlanTierLabel(masterRow.plan_tier);
389
+ const votes = new Map();
390
+ for (const e of memberEntries) {
391
+ const tier = normalizePlanTierLabel(e.row?.plan_tier || '');
392
+ if (!tier) continue;
393
+ const prev = votes.get(tier) || { count: 0, latestObserved: 0 };
394
+ prev.count += 1;
395
+ prev.latestObserved = Math.max(prev.latestObserved, e.observedAt);
396
+ votes.set(tier, prev);
397
+ }
398
+ let best = '';
399
+ let bestScore = null;
400
+ for (const [tier, info] of votes.entries()) {
401
+ const rank = TIER_RANK[tier] || 0;
402
+ if (
403
+ !bestScore ||
404
+ info.count > bestScore.count ||
405
+ (info.count === bestScore.count && rank > bestScore.rank) ||
406
+ (info.count === bestScore.count && rank === bestScore.rank && info.latestObserved > bestScore.latestObserved)
407
+ ) {
408
+ best = tier;
409
+ bestScore = { count: info.count, rank, latestObserved: info.latestObserved };
410
+ }
411
+ }
412
+ return best;
413
+ }
414
+
415
+ function reconcileQuotaBucket(candidates, { now, maxAgeMs }) {
416
+ const valid = candidates.filter((c) => c.pct !== null && c.pct !== undefined && Number.isFinite(Number(c.pct)));
417
+ if (valid.length === 0) return { pct: null, resetAt: null, winner: null };
418
+
419
+ const fresh = valid.filter((c) => c.observedAt > 0 && now - c.observedAt <= maxAgeMs);
420
+ const pool = fresh.length > 0 ? fresh : valid;
421
+
422
+ const annotated = pool.map((c) => {
423
+ const rawReset = c.resetAt && Number(c.resetAt) > QUOTA_EPOCH_SENTINEL_MS ? Number(c.resetAt) : null;
424
+ const isActiveFuture = Boolean(rawReset && rawReset > now);
425
+ const isExpired = Boolean(rawReset && rawReset <= now);
426
+ return {
427
+ ...c,
428
+ rawReset,
429
+ isActiveFuture,
430
+ isExpired,
431
+ effPct: isExpired ? 100 : Math.max(0, Math.min(100, Number(c.pct))),
432
+ };
433
+ });
434
+
435
+ const activeFuture = annotated.filter((c) => c.isActiveFuture);
436
+ if (activeFuture.length > 0) {
437
+ // Pick the active window observed most recently (breaking ties by master priority then later reset),
438
+ // then reconcile monotonically (minimum remaining %) across all observations in that same reset window (±10 min).
439
+ const newest = [...activeFuture].sort((a, b) => {
440
+ if (b.observedAt !== a.observedAt) return b.observedAt - a.observedAt;
441
+ if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
442
+ return b.rawReset - a.rawReset;
443
+ })[0];
444
+ const sameWindow = activeFuture.filter((c) => Math.abs(c.rawReset - newest.rawReset) <= 10 * 60_000);
445
+ sameWindow.sort((a, b) => {
446
+ if (Math.abs(a.effPct - b.effPct) > 0.5) return a.effPct - b.effPct;
447
+ if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
448
+ return b.observedAt - a.observedAt;
449
+ });
450
+ const winner = sameWindow[0];
451
+ return { pct: winner.effPct, resetAt: winner.rawReset, winner };
452
+ }
453
+
454
+ annotated.sort((a, b) => {
455
+ const dt = Math.abs(b.observedAt - a.observedAt);
456
+ if (dt <= 15 * 60_000 && Math.abs(a.effPct - b.effPct) > 0.5) return a.effPct - b.effPct;
457
+ if (b.observedAt !== a.observedAt) return b.observedAt - a.observedAt;
458
+ if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
459
+ return a.effPct - b.effPct;
460
+ });
461
+ const winner = annotated[0];
462
+ return { pct: winner.effPct, resetAt: winner.rawReset, winner };
463
+ }
464
+
465
+ export function reconcileFamilySubscriptionQuota(allRows = [], membersRaw = [], now = Date.now()) {
466
+ const rows = Array.isArray(allRows) ? allRows : [];
467
+ const activeMembers = (membersRaw || []).filter((m) => m && (m.active === undefined || Boolean(m.active)));
468
+ const memberById = new Map(activeMembers.map((m) => [m.id, m]));
469
+ const mgrRow = activeMembers.find((m) => m.role === 'manager') || null;
470
+
471
+ const masterRow = rows.find((r) => r && r.scope === 'master') || null;
472
+ const memberQuotasById = new Map();
473
+ const eligibleMembers = [];
474
+
475
+ for (const r of rows) {
476
+ if (!r || typeof r.scope !== 'string' || !r.scope.startsWith('member:')) continue;
477
+ const mid = r.scope.slice(7);
478
+ const m = memberById.get(mid);
479
+ if (!m || m.last_account_status === 'mismatch') continue;
480
+ const ev = evaluateSubscriptionQuotaRow(r, now);
481
+ if (!ev.configured) continue;
482
+ memberQuotasById.set(mid, ev);
483
+
484
+ const isEligible =
485
+ m.role === 'manager' ||
486
+ (Boolean(m.expected_email_hash) && m.last_account_status === 'verified');
487
+ if (isEligible) {
488
+ eligibleMembers.push({
489
+ row: r,
490
+ member: m,
491
+ observedAt: Number(r.observed_at || r.updated_at) || 0,
492
+ updatedAt: Number(r.updated_at || r.observed_at) || 0,
493
+ isMaster: m.role === 'manager',
494
+ });
495
+ }
496
+ }
497
+
498
+ const isManualMaster = Boolean(masterRow && masterRow.source === 'manual');
499
+ const manualCutoffMs = isManualMaster ? Number(masterRow.updated_at || masterRow.observed_at || 0) : 0;
500
+ const postManualMembers = isManualMaster
501
+ ? eligibleMembers.filter((e) => e.observedAt > manualCutoffMs)
502
+ : eligibleMembers;
503
+
504
+ const authPlanTier = pickConsensusPlanTier(masterRow, postManualMembers);
505
+ const tierAlignedMembers = authPlanTier
506
+ ? postManualMembers.filter((e) => {
507
+ if (e.isMaster) return true;
508
+ const mt = normalizePlanTierLabel(e.row?.plan_tier || '');
509
+ return !mt || mt === authPlanTier;
510
+ })
511
+ : postManualMembers;
512
+
513
+ const allSources = [];
514
+ if (masterRow) {
515
+ allSources.push({
516
+ row: masterRow,
517
+ isMaster: true,
518
+ memberId: masterRow.member_id || mgrRow?.id || null,
519
+ memberName: mgrRow?.name || 'Master',
520
+ role: 'manager',
521
+ observedAt: Number(masterRow.observed_at || masterRow.updated_at) || 0,
522
+ updatedAt: Number(masterRow.updated_at || masterRow.observed_at) || 0,
523
+ source: masterRow.source || 'sync',
524
+ });
525
+ }
526
+ for (const e of tierAlignedMembers) {
527
+ // Avoid double-counting the manager's own older `member:<mgr>` row when `scope='master'` is already newer.
528
+ if (masterRow && (e.isMaster || e.member.id === masterRow.member_id) && e.observedAt <= Number(masterRow.observed_at || masterRow.updated_at || 0)) {
529
+ continue;
530
+ }
531
+ allSources.push({
532
+ row: e.row,
533
+ isMaster: e.isMaster,
534
+ memberId: e.member.id,
535
+ memberName: e.member.name,
536
+ role: e.member.role === 'manager' ? 'manager' : 'member',
537
+ observedAt: e.observedAt,
538
+ updatedAt: e.updatedAt,
539
+ source: e.row.source || 'sync',
540
+ });
541
+ }
542
+
543
+ if (allSources.length === 0) {
544
+ return {
545
+ masterSubscriptionQuota: evaluateSubscriptionQuotaRow(null, now),
546
+ memberQuotasById,
547
+ };
548
+ }
549
+
550
+ const buildCands = (pctField, resetField) =>
551
+ allSources.map((s) => ({
552
+ pct: s.row[pctField],
553
+ resetAt: s.row[resetField],
554
+ observedAt: s.observedAt,
555
+ updatedAt: s.updatedAt,
556
+ isMaster: s.isMaster,
557
+ memberId: s.memberId,
558
+ memberName: s.memberName,
559
+ role: s.role,
560
+ source: s.source,
561
+ }));
562
+
563
+ const g5 = reconcileQuotaBucket(buildCands('gemini_5h_pct', 'gemini_5h_reset_at'), { now, maxAgeMs: 12 * HOUR_MS });
564
+ const gw = reconcileQuotaBucket(buildCands('gemini_weekly_pct', 'gemini_weekly_reset_at'), { now, maxAgeMs: 7 * DAY_MS });
565
+ const c5 = reconcileQuotaBucket(buildCands('third_party_5h_pct', 'third_party_5h_reset_at'), { now, maxAgeMs: 12 * HOUR_MS });
566
+ const cw = reconcileQuotaBucket(buildCands('third_party_weekly_pct', 'third_party_weekly_reset_at'), { now, maxAgeMs: 7 * DAY_MS });
567
+
568
+ const winners = [g5.winner, gw.winner, c5.winner, cw.winner].filter(Boolean);
569
+ const latestObservedAt = winners.length > 0
570
+ ? Math.max(...winners.map((w) => w.observedAt || 0))
571
+ : Math.max(...allSources.map((s) => s.observedAt || 0));
572
+ const latestUpdatedAt = winners.length > 0
573
+ ? Math.max(...winners.map((w) => w.updatedAt || 0))
574
+ : Math.max(...allSources.map((s) => s.updatedAt || 0));
575
+
576
+ const freshContributorsMap = new Map();
577
+ for (const s of allSources) {
578
+ const isFresh = s.observedAt > 0 && now - s.observedAt <= 12 * HOUR_MS;
579
+ if (!isFresh && !winners.some((w) => w.memberId === s.memberId && w.isMaster === s.isMaster)) continue;
580
+ const key = s.memberId || (s.isMaster ? '__master__' : s.memberName);
581
+ const prev = freshContributorsMap.get(key);
582
+ if (!prev || s.observedAt > prev.observedAt) {
583
+ freshContributorsMap.set(key, {
584
+ id: s.memberId || null,
585
+ name: s.memberName,
586
+ role: s.role,
587
+ isMaster: s.isMaster,
588
+ observedAt: s.observedAt,
589
+ });
590
+ }
591
+ }
592
+ const contributors = Array.from(freshContributorsMap.values()).sort((a, b) => b.observedAt - a.observedAt);
593
+ const hasMasterContrib = Boolean(masterRow) || contributors.some((c) => c.isMaster);
594
+ const hasMemberContrib = contributors.some((c) => !c.isMaster);
595
+ const syncMode = hasMemberContrib ? (hasMasterContrib ? 'reconciled' : 'collaborative') : 'master';
596
+ const primaryWinner = g5.winner || gw.winner || c5.winner || cw.winner || allSources[0];
597
+
598
+ const mergedRow = {
599
+ scope: 'master',
600
+ member_id: masterRow?.member_id || mgrRow?.id || primaryWinner?.memberId || null,
601
+ account_label: masterRow?.account_label || mgrRow?.email_address || mgrRow?.email_hint || mgrRow?.name || '',
602
+ plan_tier: authPlanTier || masterRow?.plan_tier || '',
603
+ gemini_5h_pct: g5.pct,
604
+ gemini_5h_reset_at: g5.resetAt,
605
+ gemini_weekly_pct: gw.pct,
606
+ gemini_weekly_reset_at: gw.resetAt,
607
+ third_party_5h_pct: c5.pct,
608
+ third_party_5h_reset_at: c5.resetAt,
609
+ third_party_weekly_pct: cw.pct,
610
+ third_party_weekly_reset_at: cw.resetAt,
611
+ source: syncMode === 'master' ? (masterRow?.source || primaryWinner?.source || 'sync') : `family-${syncMode}`,
612
+ observed_at: latestObservedAt || now,
613
+ updated_at: latestUpdatedAt || now,
614
+ };
615
+
616
+ const evaluated = evaluateSubscriptionQuotaRow(mergedRow, now);
617
+ return {
618
+ masterSubscriptionQuota: {
619
+ ...evaluated,
620
+ syncMode,
621
+ contributorCount: contributors.length,
622
+ contributors: contributors.map((c) => ({ name: c.name, role: c.role, observedAt: c.observedAt })),
623
+ latestContributorName: contributors[0]?.name || '',
624
+ },
625
+ memberQuotasById,
626
+ };
627
+ }
628
+
629
+ export async function loadMasterSubscriptionQuota(db, now = Date.now(), membersRaw = null) {
382
630
  try {
383
- const row = await db.get('SELECT * FROM subscription_quotas WHERE scope = ?', ['master']);
384
- return evaluateSubscriptionQuotaRow(row || null, now);
631
+ const rows = await db.all('SELECT * FROM subscription_quotas');
632
+ const members =
633
+ Array.isArray(membersRaw)
634
+ ? membersRaw
635
+ : await db.all(
636
+ 'SELECT id, name, role, expected_email_hash, email_address, email_hint, last_account_status, active FROM members WHERE active = 1',
637
+ );
638
+ return reconcileFamilySubscriptionQuota(rows || [], members || [], now).masterSubscriptionQuota;
385
639
  } catch {
386
640
  return evaluateSubscriptionQuotaRow(null, now);
387
641
  }
388
642
  }
389
643
 
644
+ export async function loadAllSubscriptionQuotas(db, now = Date.now(), membersRaw = null) {
645
+ try {
646
+ const rows = await db.all('SELECT * FROM subscription_quotas');
647
+ const members =
648
+ Array.isArray(membersRaw)
649
+ ? membersRaw
650
+ : await db.all(
651
+ 'SELECT id, name, role, expected_email_hash, email_address, email_hint, last_account_status, active FROM members WHERE active = 1',
652
+ );
653
+ return reconcileFamilySubscriptionQuota(rows || [], members || [], now);
654
+ } catch {
655
+ return {
656
+ masterSubscriptionQuota: evaluateSubscriptionQuotaRow(null, now),
657
+ memberQuotasById: new Map(),
658
+ };
659
+ }
660
+ }
661
+
390
662
  /**
391
663
  * Resolve per-member percentage quota allocation across active family members.
392
664
  * - Members with explicit `quota_pct > 0` keep their pinned percentage.
@@ -1283,6 +1555,7 @@ export async function buildBoardPayload(
1283
1555
  const activeMemberCount = (membersRaw || []).length;
1284
1556
  const maskPublicEmail = Boolean(settings.maskPublicEmail);
1285
1557
  const maskPublicIp = Boolean(settings.maskPublicIp);
1558
+ const { masterSubscriptionQuota, memberQuotasById } = await loadAllSubscriptionQuotas(db, now, membersRaw);
1286
1559
 
1287
1560
  const members = (membersRaw || []).map((raw) => {
1288
1561
  const agg = byMember.get(raw.id);
@@ -1375,6 +1648,18 @@ export async function buildBoardPayload(
1375
1648
  emailHint: formatBoardEmail(raw.email_address, raw.email_hint, maskPublicEmail),
1376
1649
  accountStatus: raw.expected_email_hash ? raw.last_account_status || 'unknown' : 'unbound',
1377
1650
  integrityFlags7d: integrityByMember.get(raw.id) || 0,
1651
+ subscriptionQuota: (() => {
1652
+ const mq = memberQuotasById.get(raw.id);
1653
+ if (!mq || !mq.configured) return null;
1654
+ return {
1655
+ planTier: mq.planTier || '',
1656
+ status: mq.status,
1657
+ observedAt: mq.observedAt,
1658
+ stale: mq.stale,
1659
+ gemini: mq.gemini,
1660
+ thirdParty: mq.thirdParty,
1661
+ };
1662
+ })(),
1378
1663
  };
1379
1664
  });
1380
1665
 
@@ -1415,7 +1700,6 @@ export async function buildBoardPayload(
1415
1700
  poolTotalCredits > 0 ? roundPct(((projectedCycleUsd * creditsPerUsd) / poolTotalCredits) * 100) : null;
1416
1701
 
1417
1702
  const creditsReconciliation = await computeCreditsReconciliation(db, membersRaw, settings, cycleInfo);
1418
- const masterSubscriptionQuota = await loadMasterSubscriptionQuota(db, now);
1419
1703
 
1420
1704
  const estUsedCredits = Math.round(totalUsd * creditsPerUsd);
1421
1705
  const poolUsedPct = poolTotalCredits > 0 ? roundPct((estUsedCredits / poolTotalCredits) * 100) : null;
@@ -1924,7 +1924,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
1924
1924
 
1925
1925
  <footer class="foot">
1926
1926
  <span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
1927
- <span class="mono">agy-family v0.6.4 · MIT</span>
1927
+ <span class="mono">agy-family v0.6.5 · MIT</span>
1928
1928
  </footer>
1929
1929
  </main>
1930
1930
 
@@ -3182,6 +3182,30 @@ function renderMemberRows(d) {
3182
3182
  const emailHintHtml = m.emailHint
3183
3183
  ? '<span class="mono" style="color:var(--body)">· ' + esc(m.emailHint) + '</span>'
3184
3184
  : '';
3185
+ const mqMem = m.subscriptionQuota || null;
3186
+ let memQuotaTag = '';
3187
+ if (mqMem && mqMem.gemini) {
3188
+ const g5 = mqMem.gemini.fiveHourPct;
3189
+ const gw = mqMem.gemini.weeklyPct;
3190
+ const qBits = [];
3191
+ if (g5 !== null && g5 !== undefined) qBits.push('5h ' + Math.round(Number(g5)) + '%');
3192
+ if (gw !== null && gw !== undefined) qBits.push((lang === 'zh' ? '周 ' : 'wk ') + Math.round(Number(gw)) + '%');
3193
+ if (qBits.length) {
3194
+ const qCls = mqMem.status === 'limited' ? 'ntag-over' : (mqMem.status === 'low' ? 'ntag-warn' : 'ntag-gray');
3195
+ const tipParts = [];
3196
+ if (mqMem.planTier) tipParts.push(mqMem.planTier);
3197
+ if (g5 !== null && g5 !== undefined) tipParts.push('Gemini 5h: ' + g5 + '%');
3198
+ if (gw !== null && gw !== undefined) tipParts.push('Gemini wk: ' + gw + '%');
3199
+ if (mqMem.thirdParty?.fiveHourPct !== null && mqMem.thirdParty?.fiveHourPct !== undefined) {
3200
+ tipParts.push('3P 5h: ' + mqMem.thirdParty.fiveHourPct + '%');
3201
+ }
3202
+ if (mqMem.thirdParty?.weeklyPct !== null && mqMem.thirdParty?.weeklyPct !== undefined) {
3203
+ tipParts.push('3P wk: ' + mqMem.thirdParty.weeklyPct + '%');
3204
+ }
3205
+ if (mqMem.observedAt) tipParts.push(fmtAgo(mqMem.observedAt));
3206
+ memQuotaTag = '<span class="ntag ' + qCls + ' mono" title="' + esc(tipParts.join(' · ')) + '">' + esc(qBits.join(' · ')) + '</span>';
3207
+ }
3208
+ }
3185
3209
  const devMetaBits = [];
3186
3210
  if (m.lastPlatform) devMetaBits.push(m.lastPlatform);
3187
3211
  if (m.lastMaskedIp && m.lastMaskedIp !== 'local') {
@@ -3201,7 +3225,7 @@ function renderMemberRows(d) {
3201
3225
  '<span class="toggle-tri' + (isExpanded ? ' open' : '') + '">' + triSvg + '</span>' +
3202
3226
  '<span class="dot" style="background:' + esc(m.color) + '"></span>' +
3203
3227
  '<div>' +
3204
- '<div class="member-name-row"><span class="member-name">' + esc(m.name) + '</span>' + roleTag + meTag + acctTag + statusTag + integrityTag + '</div>' +
3228
+ '<div class="member-name-row"><span class="member-name">' + esc(m.name) + '</span>' + roleTag + meTag + acctTag + memQuotaTag + statusTag + integrityTag + '</div>' +
3205
3229
  '<div class="member-sub"><span class="live-dot ' + (m.online ? 'on' : 'off') + '"></span><span>' + esc(m.online ? t('online') : t('offline')) + '</span><span>' + esc(fmtAgo(m.lastSeenAt)) + '</span>' + emailHintHtml + devMetaHtml + '</div>' +
3206
3230
  '</div>' +
3207
3231
  '</div></td>' +
@@ -3380,9 +3404,22 @@ function renderBoard(d) {
3380
3404
  if (k4Sub) {
3381
3405
  const subBits = [];
3382
3406
  if (mq.accountLabel) subBits.push(mq.accountLabel);
3407
+ if (mq.syncMode === 'collaborative' && mq.latestContributorName) {
3408
+ subBits.push(
3409
+ lang === 'zh'
3410
+ ? (mq.contributorCount > 1
3411
+ ? '成员 ' + mq.latestContributorName + ' 等 ' + mq.contributorCount + ' 人协同'
3412
+ : '成员 ' + mq.latestContributorName + ' 协同同步')
3413
+ : (mq.contributorCount > 1
3414
+ ? 'Synced by ' + mq.contributorCount + ' members'
3415
+ : 'Synced via ' + mq.latestContributorName),
3416
+ );
3417
+ } else if (mq.syncMode === 'reconciled' && mq.contributorCount > 1) {
3418
+ subBits.push(lang === 'zh' ? mq.contributorCount + ' 人协同校准' : mq.contributorCount + '-way reconciled');
3419
+ }
3383
3420
  if (mq.stale) subBits.push(lang === 'zh' ? '缓存偏旧 · 点击刷新指引' : 'Stale cache');
3384
3421
  else if (g.weeklyResetInMs) subBits.push((lang === 'zh' ? '周重置 ' : 'Wk reset ') + fmtResetCountdown(g.weeklyResetInMs));
3385
- else subBits.push(lang === 'zh' ? '主号实时同步' : 'Synced from master');
3422
+ else if (!mq.syncMode || mq.syncMode === 'master') subBits.push(lang === 'zh' ? '主号实时同步' : 'Synced from master');
3386
3423
  k4Sub.style.color = mq.status === 'limited' ? 'var(--danger)' : (mq.status === 'low' || mq.stale ? 'var(--warn)' : 'var(--muted)');
3387
3424
  k4Sub.textContent = subBits.join(' · ');
3388
3425
  }
@@ -3392,11 +3429,11 @@ function renderBoard(d) {
3392
3429
  k4Meta.textContent = t('bindMasterLink');
3393
3430
  }
3394
3431
  if (k4Body) {
3395
- k4Body.innerHTML = '<div class="kpi-val-row"><div class="kpi-val" style="font-size:18px;color:var(--muted)">' + (lang === 'zh' ? '待绑定主号' : 'Not bound') + '</div></div>';
3432
+ k4Body.innerHTML = '<div class="kpi-val-row"><div class="kpi-val" style="font-size:18px;color:var(--muted)">' + (lang === 'zh' ? '待任意成员同步' : 'Awaiting sync') + '</div></div>';
3396
3433
  }
3397
3434
  if (k4Sub) {
3398
3435
  k4Sub.style.color = 'var(--muted)';
3399
- k4Sub.textContent = lang === 'zh' ? '运行 agy-family master bind 同步余量' : 'Run agy-family master bind to sync';
3436
+ k4Sub.textContent = lang === 'zh' ? '主号或任一已核验成员使用 agy 后自动捕获' : 'Auto-captured when master or any verified member uses agy';
3400
3437
  }
3401
3438
  }
3402
3439
 
@@ -3829,11 +3866,19 @@ async function loadAdmin() {
3829
3866
  '<div class="mq-track" style="height:5px"><div class="mq-fill ' + cls + '" style="width:' + (hasVal ? Math.max(0, Math.min(100, Number(pct))) : 0) + '%"></div></div>' +
3830
3867
  '</div>';
3831
3868
  };
3869
+ const contribNames = Array.isArray(mq.contributors) ? mq.contributors.map((c) => c.name).filter(Boolean) : [];
3870
+ const contribTag =
3871
+ mq.syncMode === 'collaborative' && contribNames.length
3872
+ ? '<span class="ntag ntag-good">' + esc((lang === 'zh' ? '成员协同:' : 'Via members: ') + contribNames.join(' / ')) + '</span>'
3873
+ : mq.syncMode === 'reconciled' && contribNames.length > 1
3874
+ ? '<span class="ntag ntag-good">' + esc((lang === 'zh' ? '多源综合校准:' : 'Reconciled: ') + contribNames.join(' + ')) + '</span>'
3875
+ : '';
3832
3876
  mqView.innerHTML =
3833
3877
  '<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;font-size:12px;flex-wrap:wrap">' +
3834
- '<div style="display:flex;align-items:center;gap:6px">' +
3878
+ '<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">' +
3835
3879
  (mq.planTier ? '<span class="mq-tier-pill">' + esc(mq.planTier) + '</span>' : '') +
3836
3880
  (mq.accountLabel ? '<span class="mono" style="color:var(--ink);font-weight:500">' + esc(mq.accountLabel) + '</span>' : '') +
3881
+ contribTag +
3837
3882
  '</div>' +
3838
3883
  '<span class="mono" style="font-size:11px;color:' + (mq.stale ? 'var(--warn)' : 'var(--muted)') + '">' +
3839
3884
  esc((mq.source || 'sync') + ' · ' + fmtAgo(mq.observedAt || mq.updatedAt)) +