thumbgate 1.40.12 → 1.40.14
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/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/adapters/claude/.mcp.json +3 -3
- package/adapters/forge/forge.yaml +3 -3
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +18 -5
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +6 -7
- package/config/unit-costs.json +47 -0
- package/package.json +16 -9
- package/public/admin.html +58 -3
- package/public/index.html +2 -2
- package/public/install.html +8 -8
- package/public/learn.html +8 -0
- package/public/numbers.html +2 -2
- package/public/project-switcher.js +10 -3
- package/scripts/activation-tracker.js +106 -5
- package/scripts/check-update.js +116 -1
- package/scripts/cli-feedback.js +8 -7
- package/scripts/cost-meter.js +161 -0
- package/scripts/first-block-upsell.js +30 -6
- package/scripts/mailer/resend-mailer.js +2 -0
- package/scripts/owner-admin.js +136 -13
- package/scripts/owner-alerts.js +6 -1
- package/scripts/owner-telemetry.js +22 -2
- package/scripts/pr-manager.js +156 -41
- package/scripts/project-identity.js +6 -1
- package/scripts/statusline-human-counts.js +52 -7
- package/scripts/unit-economics.js +138 -0
- package/server.json +2 -2
- package/src/api/server.js +43 -3
- package/src/mcp-writeguard.js +2 -2
package/scripts/pr-manager.js
CHANGED
|
@@ -482,12 +482,41 @@ async function managePrs(prNumber = '', runner = runGh, options = {}) {
|
|
|
482
482
|
return { status: 'ok', prs: results };
|
|
483
483
|
}
|
|
484
484
|
|
|
485
|
-
|
|
485
|
+
// Stale-PR steward. It never closes a PR. Claude Ship's PR Steward fixes PRs
|
|
486
|
+
// instead of closing them; the free version here does the mechanical part
|
|
487
|
+
// (rebase a branch that fell behind main) and labels the rest so the daily
|
|
488
|
+
// steward agent session (docs/ops/ship-pipeline.md) can fix the code.
|
|
489
|
+
// History: the old sweeper closed #5131 after 3 days as a draft.
|
|
490
|
+
const SWEEP_PR_FIELDS = 'number,state,isDraft,title,url,headRefName,headRefOid,baseRefName,updatedAt,createdAt,author,statusCheckRollup,mergeStateStatus,mergeable,labels';
|
|
491
|
+
// main has no "require up to date" rule, so GitHub never reports BEHIND here.
|
|
492
|
+
// The steward asks the compare API instead and updates a branch this far back.
|
|
493
|
+
const SWEEP_BEHIND_THRESHOLD = 10;
|
|
486
494
|
const SWEEP_LIST_LIMIT = '1000';
|
|
487
495
|
const SWEEP_REQUIRED_CHECKS_BASE = 'main';
|
|
488
496
|
const DEFAULT_RED_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
489
497
|
const DEFAULT_DRAFT_IDLE_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
|
|
490
498
|
const REQUIRED_CHECK_SET = new Set(MERGE_QUALITY_CHECKS.requiredStatusCheckContexts || []);
|
|
499
|
+
const STEWARD_LABELS = {
|
|
500
|
+
stale: 'stale',
|
|
501
|
+
needsFix: 'needs-fix',
|
|
502
|
+
needsRebase: 'needs-rebase',
|
|
503
|
+
};
|
|
504
|
+
const STEWARD_LABEL_STYLE = {
|
|
505
|
+
stale: ['C5DEF5', 'Steward: draft idle over 3 days'],
|
|
506
|
+
'needs-fix': ['D93F0B', 'Ship gate: red checks or open review threads'],
|
|
507
|
+
'needs-rebase': ['FBCA04', 'Steward: conflicts with main'],
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
/** Add a label, creating it first if the repo does not have it yet. */
|
|
511
|
+
function addStewardLabel(number, label, runner) {
|
|
512
|
+
let res = runner(['pr', 'edit', String(number), '--add-label', label]);
|
|
513
|
+
if (res.status !== 0 && /not found/i.test(formatGhError(res))) {
|
|
514
|
+
const [color, description] = STEWARD_LABEL_STYLE[label] || ['EDEDED', 'Steward'];
|
|
515
|
+
runner(['label', 'create', label, '--color', color, '--description', description]);
|
|
516
|
+
res = runner(['pr', 'edit', String(number), '--add-label', label]);
|
|
517
|
+
}
|
|
518
|
+
return res;
|
|
519
|
+
}
|
|
491
520
|
|
|
492
521
|
function isProtectedSweepBranch(pr = {}) {
|
|
493
522
|
const headRef = String(pr.headRefName || '').trim();
|
|
@@ -514,30 +543,60 @@ function isRequiredCheckFailing(check = {}) {
|
|
|
514
543
|
return FAILING_CHECK_CONCLUSIONS.has(conclusion) || conclusion === 'ERROR';
|
|
515
544
|
}
|
|
516
545
|
|
|
546
|
+
function prLabels(pr = {}) {
|
|
547
|
+
return new Set((pr.labels || []).map((l) => (typeof l === 'string' ? l : l.name)));
|
|
548
|
+
}
|
|
549
|
+
|
|
517
550
|
function classifyStalePr(pr = {}, options = {}) {
|
|
518
551
|
const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
|
|
519
552
|
const redMaxAgeMs = Number.isFinite(options.redMaxAgeMs) ? options.redMaxAgeMs : DEFAULT_RED_MAX_AGE_MS;
|
|
520
553
|
const draftIdleMaxAgeMs = Number.isFinite(options.draftIdleMaxAgeMs)
|
|
521
554
|
? options.draftIdleMaxAgeMs
|
|
522
555
|
: DEFAULT_DRAFT_IDLE_MAX_AGE_MS;
|
|
556
|
+
const labels = prLabels(pr);
|
|
523
557
|
|
|
524
558
|
if (isProtectedSweepBranch(pr)) {
|
|
525
|
-
return {
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
559
|
+
return { action: 'skip', reason: 'protected_branch', headRefName: pr.headRefName || '' };
|
|
560
|
+
}
|
|
561
|
+
if (labels.has('do-not-merge')) {
|
|
562
|
+
return { action: 'skip', reason: 'on_hold' };
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// A branch behind main is rebased whatever else is going on: that alone
|
|
566
|
+
// often turns red checks green, and it keeps drafts mergeable.
|
|
567
|
+
if (String(pr.mergeStateStatus || '').toUpperCase() === 'BEHIND') {
|
|
568
|
+
return { action: 'update_branch', reason: 'behind_main' };
|
|
569
|
+
}
|
|
570
|
+
const behindThreshold = Number.isFinite(options.behindThreshold) ? options.behindThreshold : SWEEP_BEHIND_THRESHOLD;
|
|
571
|
+
if (Number.isFinite(pr.behindBy) && pr.behindBy >= behindThreshold
|
|
572
|
+
&& String(pr.mergeStateStatus || '').toUpperCase() !== 'DIRTY') {
|
|
573
|
+
// A merge update, not a rebase: it never rewrites a branch an agent may be working on.
|
|
574
|
+
return { action: 'update_branch', reason: 'behind_main_by_commits', behindBy: pr.behindBy, rebase: false };
|
|
575
|
+
}
|
|
576
|
+
if (String(pr.mergeStateStatus || '').toUpperCase() === 'DIRTY' || String(pr.mergeable || '').toUpperCase() === 'CONFLICTING') {
|
|
577
|
+
return labels.has(STEWARD_LABELS.needsRebase)
|
|
578
|
+
? { action: 'keep', reason: 'conflict_already_flagged' }
|
|
579
|
+
: {
|
|
580
|
+
action: 'label',
|
|
581
|
+
label: STEWARD_LABELS.needsRebase,
|
|
582
|
+
reason: 'merge_conflict',
|
|
583
|
+
comment: `PR #${pr.number} has a merge conflict with \`main\`. Labelled \`${STEWARD_LABELS.needsRebase}\`; the steward session rebases it and resolves the conflict. Nothing was closed.`,
|
|
584
|
+
};
|
|
530
585
|
}
|
|
531
586
|
|
|
532
587
|
if (pr.isDraft) {
|
|
533
588
|
const updatedMs = Date.parse(pr.updatedAt || pr.createdAt || '');
|
|
534
589
|
if (Number.isFinite(updatedMs) && (nowMs - updatedMs) > draftIdleMaxAgeMs) {
|
|
535
590
|
const idleDays = Math.floor((nowMs - updatedMs) / (24 * 60 * 60 * 1000));
|
|
591
|
+
if (labels.has(STEWARD_LABELS.stale)) {
|
|
592
|
+
return { action: 'keep', reason: 'draft_idle_already_flagged', idleDays };
|
|
593
|
+
}
|
|
536
594
|
return {
|
|
537
|
-
action: '
|
|
595
|
+
action: 'label',
|
|
596
|
+
label: STEWARD_LABELS.stale,
|
|
538
597
|
reason: 'draft_idle_over_3d',
|
|
539
598
|
idleDays,
|
|
540
|
-
comment: `
|
|
599
|
+
comment: `Draft PR #${pr.number} has been idle ${idleDays}d. Labelled \`${STEWARD_LABELS.stale}\` so the steward session finishes it (tests, then ready for review). It stays open.`,
|
|
541
600
|
};
|
|
542
601
|
}
|
|
543
602
|
return { action: 'keep', reason: 'draft_active' };
|
|
@@ -546,8 +605,6 @@ function classifyStalePr(pr = {}, options = {}) {
|
|
|
546
605
|
const checks = Array.isArray(pr.statusCheckRollup) ? pr.statusCheckRollup : [];
|
|
547
606
|
const failingRequired = checks.filter((check) => isRequiredCheckFailing(check));
|
|
548
607
|
if (failingRequired.length > 0 && String(pr.baseRefName || '') !== SWEEP_REQUIRED_CHECKS_BASE) {
|
|
549
|
-
// The required-check set is only known for main. For any other base
|
|
550
|
-
// (or an unknown one) we cannot tell which red checks matter, so never close.
|
|
551
608
|
return { action: 'keep', reason: 'required_checks_unknown_for_base', baseRefName: pr.baseRefName || '' };
|
|
552
609
|
}
|
|
553
610
|
if (failingRequired.length > 0) {
|
|
@@ -555,19 +612,20 @@ function classifyStalePr(pr = {}, options = {}) {
|
|
|
555
612
|
.map((check) => Date.parse(check.completedAt || check.startedAt || ''))
|
|
556
613
|
.filter((ts) => Number.isFinite(ts));
|
|
557
614
|
const fallbackMs = Date.parse(pr.updatedAt || pr.createdAt || '');
|
|
558
|
-
const redSinceMs = checkTimestamps.length > 0
|
|
559
|
-
? Math.max(...checkTimestamps)
|
|
560
|
-
: fallbackMs;
|
|
561
|
-
|
|
615
|
+
const redSinceMs = checkTimestamps.length > 0 ? Math.max(...checkTimestamps) : fallbackMs;
|
|
562
616
|
if (Number.isFinite(redSinceMs) && (nowMs - redSinceMs) > redMaxAgeMs) {
|
|
563
617
|
const redHours = Math.floor((nowMs - redSinceMs) / (60 * 60 * 1000));
|
|
564
618
|
const failingNames = [...new Set(failingRequired.map((c) => c.name || c.context))];
|
|
619
|
+
if (labels.has(STEWARD_LABELS.needsFix)) {
|
|
620
|
+
return { action: 'keep', reason: 'red_already_flagged', redHours, failingChecks: failingNames };
|
|
621
|
+
}
|
|
565
622
|
return {
|
|
566
|
-
action: '
|
|
623
|
+
action: 'label',
|
|
624
|
+
label: STEWARD_LABELS.needsFix,
|
|
567
625
|
reason: 'red_checks_over_24h',
|
|
568
626
|
redHours,
|
|
569
627
|
failingChecks: failingNames,
|
|
570
|
-
comment: `
|
|
628
|
+
comment: `Required check(s) ${failingNames.join(', ')} on PR #${pr.number} have been red for ${redHours}h. Labelled \`${STEWARD_LABELS.needsFix}\`; the steward session fixes the failure and pushes. It stays open.`,
|
|
571
629
|
};
|
|
572
630
|
}
|
|
573
631
|
}
|
|
@@ -575,22 +633,77 @@ function classifyStalePr(pr = {}, options = {}) {
|
|
|
575
633
|
return { action: 'keep', reason: 'active' };
|
|
576
634
|
}
|
|
577
635
|
|
|
578
|
-
|
|
636
|
+
/**
|
|
637
|
+
* gh pr list often reports mergeable/mergeStateStatus as UNKNOWN (GitHub
|
|
638
|
+
* computes them lazily), and never reports BEHIND without an up-to-date rule.
|
|
639
|
+
* Ask the REST API for the real merge state and how far behind the base the
|
|
640
|
+
* head is. Read-only; skipped when the list gave no head SHA.
|
|
641
|
+
*/
|
|
642
|
+
function enrichSweepPr(pr, runner) {
|
|
643
|
+
if (!pr || !pr.headRefOid || !pr.baseRefName || !pr.number) {
|
|
644
|
+
return pr;
|
|
645
|
+
}
|
|
646
|
+
const out = { ...pr };
|
|
647
|
+
const state = runner(['api', `repos/{owner}/{repo}/pulls/${pr.number}`, '--jq', '.mergeable_state']);
|
|
648
|
+
if (state.status === 0) {
|
|
649
|
+
const value = String(state.stdout || '').trim().toUpperCase();
|
|
650
|
+
if (value === 'DIRTY') out.mergeStateStatus = 'DIRTY';
|
|
651
|
+
else if (value === 'BEHIND') out.mergeStateStatus = 'BEHIND';
|
|
652
|
+
}
|
|
653
|
+
const compare = runner(['api', `repos/{owner}/{repo}/compare/${pr.baseRefName}...${pr.headRefOid}`, '--jq', '.behind_by']);
|
|
654
|
+
if (compare.status === 0) {
|
|
655
|
+
const behind = Number(String(compare.stdout || '').trim());
|
|
656
|
+
if (Number.isFinite(behind)) out.behindBy = behind;
|
|
657
|
+
}
|
|
658
|
+
return out;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function stillNeedsAction(number, verdict, options, runner) {
|
|
579
662
|
const viewResult = runner(['pr', 'view', String(number), '--json', SWEEP_PR_FIELDS]);
|
|
580
663
|
if (viewResult.status !== 0) {
|
|
581
664
|
return false;
|
|
582
665
|
}
|
|
583
666
|
try {
|
|
584
|
-
const fresh = JSON.parse(viewResult.stdout || '{}');
|
|
585
|
-
|
|
667
|
+
const fresh = enrichSweepPr(JSON.parse(viewResult.stdout || '{}'), runner);
|
|
668
|
+
const again = classifyStalePr(fresh, options);
|
|
669
|
+
return fresh.state === 'OPEN' && again.action === verdict.action && again.reason === verdict.reason;
|
|
586
670
|
} catch {
|
|
587
671
|
return false;
|
|
588
672
|
}
|
|
589
673
|
}
|
|
590
674
|
|
|
675
|
+
function applyStewardAction(pr, verdict, runner) {
|
|
676
|
+
if (verdict.action === 'update_branch') {
|
|
677
|
+
if (verdict.rebase !== false) {
|
|
678
|
+
const rebase = runner(['pr', 'update-branch', String(pr.number), '--rebase']);
|
|
679
|
+
if (rebase.status === 0) {
|
|
680
|
+
return { applied: true, via: 'rebase' };
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
// Rebase can fail on a conflict that a merge commit would not hit.
|
|
684
|
+
const merge = runner(['pr', 'update-branch', String(pr.number)]);
|
|
685
|
+
if (merge.status === 0) {
|
|
686
|
+
return { applied: true, via: 'merge' };
|
|
687
|
+
}
|
|
688
|
+
addStewardLabel(pr.number, STEWARD_LABELS.needsRebase, runner);
|
|
689
|
+
return { applied: false, via: 'flagged', error: formatGhError(merge) };
|
|
690
|
+
}
|
|
691
|
+
if (verdict.action === 'label') {
|
|
692
|
+
const labelRes = addStewardLabel(pr.number, verdict.label, runner);
|
|
693
|
+
if (labelRes.status !== 0) {
|
|
694
|
+
throw new Error(`Failed to label PR #${pr.number}: ${formatGhError(labelRes)}`);
|
|
695
|
+
}
|
|
696
|
+
const commentRes = runner(['pr', 'comment', String(pr.number), '--body', verdict.comment]);
|
|
697
|
+
if (commentRes.status !== 0) {
|
|
698
|
+
throw new Error(`Failed to comment on PR #${pr.number}: ${formatGhError(commentRes)}`);
|
|
699
|
+
}
|
|
700
|
+
return { applied: true };
|
|
701
|
+
}
|
|
702
|
+
return { applied: false };
|
|
703
|
+
}
|
|
704
|
+
|
|
591
705
|
function sweepStalePrs(options = {}, runner = runGh) {
|
|
592
706
|
const dryRun = Boolean(options.dryRun);
|
|
593
|
-
// A high limit makes gh paginate through every open PR, so none are silently skipped.
|
|
594
707
|
const listResult = runner(['pr', 'list', '--state', 'open', '--limit', SWEEP_LIST_LIMIT, '--json', SWEEP_PR_FIELDS]);
|
|
595
708
|
if (listResult.status !== 0) {
|
|
596
709
|
throw new Error(`Failed to list open PRs for sweep: ${formatGhError(listResult)}`);
|
|
@@ -598,11 +711,13 @@ function sweepStalePrs(options = {}, runner = runGh) {
|
|
|
598
711
|
|
|
599
712
|
const prs = JSON.parse(listResult.stdout || '[]');
|
|
600
713
|
const decisions = [];
|
|
601
|
-
let
|
|
714
|
+
let actedCount = 0;
|
|
602
715
|
let skippedCount = 0;
|
|
603
716
|
let keptCount = 0;
|
|
717
|
+
let errorCount = 0;
|
|
604
718
|
|
|
605
|
-
for (const
|
|
719
|
+
for (const listed of prs) {
|
|
720
|
+
const pr = isProtectedSweepBranch(listed) ? listed : enrichSweepPr(listed, runner);
|
|
606
721
|
const verdict = classifyStalePr(pr, options);
|
|
607
722
|
const record = {
|
|
608
723
|
number: pr.number,
|
|
@@ -612,45 +727,44 @@ function sweepStalePrs(options = {}, runner = runGh) {
|
|
|
612
727
|
...verdict,
|
|
613
728
|
applied: false,
|
|
614
729
|
};
|
|
730
|
+
delete record.comment;
|
|
615
731
|
|
|
616
732
|
if (verdict.action === 'skip') {
|
|
617
733
|
skippedCount += 1;
|
|
618
|
-
} else if (verdict.action === '
|
|
619
|
-
|
|
734
|
+
} else if (verdict.action === 'keep') {
|
|
735
|
+
keptCount += 1;
|
|
736
|
+
} else if (!dryRun && !stillNeedsAction(pr.number, verdict, options, runner)) {
|
|
620
737
|
record.action = 'keep';
|
|
621
738
|
record.reason = 'eligibility_changed';
|
|
622
739
|
keptCount += 1;
|
|
623
|
-
} else
|
|
624
|
-
|
|
740
|
+
} else {
|
|
741
|
+
actedCount += 1;
|
|
625
742
|
if (!dryRun) {
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
if (closeRes.status !== 0) {
|
|
633
|
-
throw new Error(`Failed to close PR #${pr.number}: ${formatGhError(closeRes)}`);
|
|
743
|
+
// One PR's failure must not stop the sweep for the rest.
|
|
744
|
+
try {
|
|
745
|
+
Object.assign(record, applyStewardAction(pr, verdict, runner));
|
|
746
|
+
} catch (err) {
|
|
747
|
+
record.error = err.message;
|
|
748
|
+
errorCount += 1;
|
|
634
749
|
}
|
|
635
|
-
record.applied = true;
|
|
636
750
|
}
|
|
637
|
-
} else {
|
|
638
|
-
keptCount += 1;
|
|
639
751
|
}
|
|
640
|
-
|
|
641
752
|
decisions.push(record);
|
|
642
753
|
}
|
|
643
754
|
|
|
644
755
|
return {
|
|
645
756
|
status: 'ok',
|
|
646
757
|
dryRun,
|
|
647
|
-
|
|
758
|
+
actedCount,
|
|
759
|
+
closedCount: 0,
|
|
648
760
|
skippedCount,
|
|
649
761
|
keptCount,
|
|
762
|
+
errorCount,
|
|
650
763
|
decisions,
|
|
651
764
|
};
|
|
652
765
|
}
|
|
653
766
|
|
|
767
|
+
|
|
654
768
|
if (require.main === module) {
|
|
655
769
|
const argv = process.argv.slice(2);
|
|
656
770
|
if (argv.includes('--sweep') || argv.includes('--sweep-stale')) {
|
|
@@ -662,10 +776,10 @@ if (require.main === module) {
|
|
|
662
776
|
console.log(JSON.stringify(summary, null, 2));
|
|
663
777
|
} else {
|
|
664
778
|
console.log(
|
|
665
|
-
`[PR
|
|
779
|
+
`[PR Steward] dryRun=${summary.dryRun} acted=${summary.actedCount} skipped=${summary.skippedCount} kept=${summary.keptCount} errors=${summary.errorCount} closed=0`,
|
|
666
780
|
);
|
|
667
781
|
}
|
|
668
|
-
process.exit(0);
|
|
782
|
+
process.exit(summary.errorCount > 0 ? 1 : 0);
|
|
669
783
|
} catch (err) {
|
|
670
784
|
console.error(err.message);
|
|
671
785
|
process.exit(1);
|
|
@@ -685,6 +799,7 @@ module.exports = {
|
|
|
685
799
|
assertSafeGhArgs,
|
|
686
800
|
buildGhEnv,
|
|
687
801
|
classifyStalePr,
|
|
802
|
+
enrichSweepPr,
|
|
688
803
|
getPrStatus,
|
|
689
804
|
getPrChecks,
|
|
690
805
|
isProtectedSweepBranch,
|
|
@@ -110,6 +110,11 @@ function resolveLocalProjectUncached(cwd = process.cwd(), options = {}) {
|
|
|
110
110
|
const projectName = homeFolder && root === homeFolder ? 'Home folder (no project)' : safeProjectName(path.basename(root), 'Local project');
|
|
111
111
|
return { projectKey: `local_${hash(`${machineIdentity(options)}\0${root}`)}`, projectName, identitySource: 'local' };
|
|
112
112
|
}
|
|
113
|
+
// A folder is a real project only when its git remote identifies it (the same rule as isRealProject in public/project-switcher.js).
|
|
114
|
+
function isProjectFolder(dir, options = {}) {
|
|
115
|
+
if (!dir || typeof dir !== 'string') return false;
|
|
116
|
+
try { return resolveLocalProject(dir, options).identitySource === 'remote'; } catch { return false; }
|
|
117
|
+
}
|
|
113
118
|
function legacyAlias(record = {}, options = {}) {
|
|
114
119
|
const registry = options.recordType === 'agent-registry.jsonl' || record.recordType === 'agent-registry.jsonl';
|
|
115
120
|
const value = record.scope?.projectId || record.metadata?.project || record.metadata?.repo || record.projectId || (registry ? record.registryProject || record.project : null);
|
|
@@ -182,4 +187,4 @@ function projectForCapture(input = {}, options = {}) {
|
|
|
182
187
|
if ((input.projectKey && input.projectKey !== descriptor.projectKey) || (remote && remote.projectKey !== descriptor.projectKey)) throw invalid('Project key does not match execution directory');
|
|
183
188
|
return descriptor;
|
|
184
189
|
}
|
|
185
|
-
module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
|
|
190
|
+
module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, isProjectFolder, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
|
|
@@ -36,6 +36,22 @@ function isScrapedHumanThumb(row) {
|
|
|
36
36
|
return tags.includes('claude-history-sync');
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
// "[Eci.Psn.StockService] Igor: thumbs up": the prefix names the project the thumb was given in.
|
|
40
|
+
function contextProjectPrefix(row) {
|
|
41
|
+
const match = String(row.context || '').match(/^\s*\[([^\]]{1,80})\]/);
|
|
42
|
+
return match ? match[1].trim().toLowerCase() : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Only a thumbs-up can be auto-made this way: "found a successful pattern" is the sync's own guess, and a
|
|
46
|
+
// positive row with no text that the system logged as no-action names nothing. A distilled failure quotes the
|
|
47
|
+
// person's own message, so it stays.
|
|
48
|
+
function isAutoGenerated(row) {
|
|
49
|
+
if (normalizeSignal(row) !== 'up') return false;
|
|
50
|
+
const context = String(row.context || '').trim();
|
|
51
|
+
if (!context) return String(row.actionType || '').toLowerCase() === 'no-action';
|
|
52
|
+
return /^history-aware distillation found a successful pattern/i.test(context);
|
|
53
|
+
}
|
|
54
|
+
|
|
39
55
|
function collectHumanRows(options = {}) {
|
|
40
56
|
const env = options.env || process.env;
|
|
41
57
|
const cwd = options.cwd || process.cwd();
|
|
@@ -49,6 +65,8 @@ function collectHumanRows(options = {}) {
|
|
|
49
65
|
|
|
50
66
|
const seen = new Set();
|
|
51
67
|
const mineRows = [];
|
|
68
|
+
// Rows read but kept out of the headline. Nothing is deleted or rewritten; they are only not counted.
|
|
69
|
+
const excluded = { otherProject: 0, unassignedNoEvidence: 0, autoGenerated: 0 };
|
|
52
70
|
const ownDir = path.resolve(feedbackDir);
|
|
53
71
|
// THUMBGATE_FEEDBACK_DIR can point the resolved dir at the shared store, which
|
|
54
72
|
// would hide this project's own log. The project's own .thumbgate folder is always read too.
|
|
@@ -66,7 +84,13 @@ function collectHumanRows(options = {}) {
|
|
|
66
84
|
if (seen.has(row.id)) continue;
|
|
67
85
|
seen.add(row.id);
|
|
68
86
|
}
|
|
69
|
-
|
|
87
|
+
// A thumb given in another project never counts here, whatever key it carries.
|
|
88
|
+
const prefix = contextProjectPrefix(row);
|
|
89
|
+
if (prefix && prefix !== projectName.toLowerCase()) {
|
|
90
|
+
if (normalizeSignal(row)) excluded.otherProject += 1;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
mineRows.push({ row, unassigned: row.projectKey === 'unassigned' });
|
|
70
94
|
}
|
|
71
95
|
}
|
|
72
96
|
|
|
@@ -75,7 +99,7 @@ function collectHumanRows(options = {}) {
|
|
|
75
99
|
// labelled automated counts when such evidence sits next to it; without it the
|
|
76
100
|
// row is a lesson the agent logged on its own judgment.
|
|
77
101
|
const scraped = { up: [], down: [] };
|
|
78
|
-
for (const row of mineRows) {
|
|
102
|
+
for (const { row } of mineRows) {
|
|
79
103
|
const signal = normalizeSignal(row);
|
|
80
104
|
const at = rowTime(row);
|
|
81
105
|
if (signal && at !== null && isScrapedHumanThumb(row)) scraped[signal].push(at);
|
|
@@ -86,13 +110,34 @@ function collectHumanRows(options = {}) {
|
|
|
86
110
|
return Boolean(signal) && at !== null && scraped[signal].some((t) => Math.abs(t - at) <= CORROBORATION_MS);
|
|
87
111
|
};
|
|
88
112
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
113
|
+
// A row written before project tracking carries no key, so it proves nothing about
|
|
114
|
+
// which project it belongs to. It counts only when the row itself shows the person
|
|
115
|
+
// typed the thumb (the user-prompt hook tag, or a history-sync scrape beside it).
|
|
116
|
+
// Text in the context ("Explicit user thumbs-up") is the agent's own wording and proves nothing.
|
|
117
|
+
const hasPersonEvidence = (row) => {
|
|
118
|
+
const tags = Array.isArray(row.tags) ? row.tags : [];
|
|
119
|
+
return tags.includes('user-prompt-thumbs') || corroborated(row);
|
|
120
|
+
};
|
|
121
|
+
const counted = [];
|
|
122
|
+
for (const { row, unassigned } of mineRows) {
|
|
123
|
+
if (!normalizeSignal(row)) continue;
|
|
124
|
+
if (!(isCountedHumanFeedback(row) || (isLegacyMcpCapture(row) && corroborated(row)))) continue;
|
|
125
|
+
// A learning the history sync distilled on its own, or a row with no text at all, is never a thumb.
|
|
126
|
+
if (isAutoGenerated(row)) {
|
|
127
|
+
excluded.autoGenerated += 1;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (unassigned && !hasPersonEvidence(row)) {
|
|
131
|
+
excluded.unassignedNoEvidence += 1;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
counted.push(row);
|
|
135
|
+
}
|
|
136
|
+
return { rows: counted, projectKey, projectName, projectDir, excluded };
|
|
92
137
|
}
|
|
93
138
|
|
|
94
139
|
function computeHumanCounts(options = {}) {
|
|
95
|
-
const { rows, projectName } = collectHumanRows(options);
|
|
140
|
+
const { rows, projectName, excluded } = collectHumanRows(options);
|
|
96
141
|
let up = 0;
|
|
97
142
|
let down = 0;
|
|
98
143
|
let latestDown = null;
|
|
@@ -105,7 +150,7 @@ function computeHumanCounts(options = {}) {
|
|
|
105
150
|
if (at !== null && (!latestDown || at > latestDown.at)) latestDown = { at, row };
|
|
106
151
|
}
|
|
107
152
|
}
|
|
108
|
-
return { up, down, label: 'this project', project: projectName, latestDown: describeLatestDown(latestDown) };
|
|
153
|
+
return { up, down, label: 'this project', project: projectName, latestDown: describeLatestDown(latestDown), notCounted: excluded.unassignedNoEvidence };
|
|
109
154
|
}
|
|
110
155
|
|
|
111
156
|
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Unit economics for the owner console: what it costs to deliver ThumbGate, per active install and per paying customer,
|
|
4
|
+
// and what each plan keeps after those costs. Pure arithmetic over numbers the app already has:
|
|
5
|
+
// - hosting: the container's own measured CPU and memory (scripts/cost-meter.js) at Railway's list rates
|
|
6
|
+
// - email: emails the mailer sent, at Resend's per-email rate
|
|
7
|
+
// - payment fees: Stripe's fee on each ThumbGate checkout when Stripe returned it, else the published card rate
|
|
8
|
+
// - revenue: Stripe checkouts and renewal invoices (US dollars only; other currencies are listed, never converted)
|
|
9
|
+
// Every figure carries its basis. A number that cannot be measured is null with a reason, never a guess.
|
|
10
|
+
|
|
11
|
+
const fs = require('node:fs');
|
|
12
|
+
const path = require('node:path');
|
|
13
|
+
|
|
14
|
+
const MONTH_SECONDS = 30 * 86400;
|
|
15
|
+
const cents = (usd) => (Number.isFinite(usd) ? Math.round(usd * 100) : null);
|
|
16
|
+
const round2 = (n) => (Number.isFinite(n) ? Math.round(n * 100) / 100 : null);
|
|
17
|
+
const round4 = (n) => (Number.isFinite(n) ? Math.round(n * 10000) / 10000 : null);
|
|
18
|
+
const usdCents = (byCurrency) => (byCurrency && Number.isSafeInteger(byCurrency.USD) ? byCurrency.USD : 0);
|
|
19
|
+
const sumList = (list) => (Array.isArray(list) ? list : []).filter((item) => item && Number.isFinite(item.usd) && item.usd >= 0).reduce((total, item) => total + item.usd, 0);
|
|
20
|
+
|
|
21
|
+
function loadUnitCosts(file = path.join(__dirname, '..', 'config', 'unit-costs.json')) {
|
|
22
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Hosting for the window: measured compute plus the configured volume and egress, scaled to 30 days when the meter
|
|
26
|
+
// covered only part of the window (for example the first days after this feature shipped).
|
|
27
|
+
function hostingCost(meter, rates) {
|
|
28
|
+
if (!meter || !rates || !(meter.sampledSeconds > 0)) return { usd: null, measuredUsd: null, coverage: meter ? meter.coverage || 0 : 0, basis: 'not_measured_yet', reason: 'The cost meter has no samples yet. It records once a minute after the server starts.' };
|
|
29
|
+
const cpuUsd = (meter.cpuSeconds / MONTH_SECONDS) * rates.vcpuMonthUsd;
|
|
30
|
+
const memoryUsd = (meter.memoryGbSeconds / MONTH_SECONDS) * rates.memoryGbMonthUsd;
|
|
31
|
+
const measuredUsd = cpuUsd + memoryUsd;
|
|
32
|
+
const scale = MONTH_SECONDS / meter.sampledSeconds;
|
|
33
|
+
const computeMonthUsd = measuredUsd * scale;
|
|
34
|
+
const volumeUsd = (Number(rates.volumeGb) || 0) * (Number(rates.volumeGbMonthUsd) || 0);
|
|
35
|
+
const egressUsd = (Number(rates.egressGbPerMonth) || 0) * (Number(rates.egressGbUsd) || 0);
|
|
36
|
+
const full = meter.coverage >= 0.95;
|
|
37
|
+
return {
|
|
38
|
+
usd: round4(computeMonthUsd + volumeUsd + egressUsd),
|
|
39
|
+
measuredUsd: round4(measuredUsd),
|
|
40
|
+
parts: { cpuUsd: round4(cpuUsd * scale), memoryUsd: round4(memoryUsd * scale), volumeUsd: round4(volumeUsd), egressUsd: round4(egressUsd) },
|
|
41
|
+
coverage: round4(meter.coverage),
|
|
42
|
+
sources: meter.sources || [],
|
|
43
|
+
basis: full ? 'measured_30d' : 'projected_from_partial_window',
|
|
44
|
+
reason: full ? null : `The meter covered ${Math.round(meter.coverage * 1000) / 10}% of the 30 days, so compute is projected to 30 days from what it saw.`,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Stripe fees in US dollars: the fees Stripe returned for ThumbGate checkouts, plus the published rate for what it did not
|
|
49
|
+
// return and for renewal invoices. Subscription money also pays the Stripe Billing percentage.
|
|
50
|
+
function paymentFees(money, rates) {
|
|
51
|
+
if (!money || !rates) return { usd: null, basis: 'unavailable', reason: 'Stripe numbers are not available right now.' };
|
|
52
|
+
const fees = money.paymentFees30d || {};
|
|
53
|
+
const reported = usdCents(fees.reportedFees) / 100;
|
|
54
|
+
const unreportedCharges = Number.isSafeInteger(fees.unreportedCharges) ? fees.unreportedCharges : 0;
|
|
55
|
+
const unreportedAmount = usdCents(fees.unreportedAmount) / 100;
|
|
56
|
+
const renewalCount = Number.isSafeInteger(money.recurring30d?.renewalInvoices) ? money.recurring30d.renewalInvoices : 0;
|
|
57
|
+
const renewalUsd = usdCents(money.recurring30d?.renewalRevenue) / 100;
|
|
58
|
+
const card = (count, amount) => count * rates.fixedUsd + amount * rates.percent;
|
|
59
|
+
const estimated = card(unreportedCharges, unreportedAmount) + card(renewalCount, renewalUsd) + renewalUsd * (rates.billingPercent || 0) + (usdCents(fees.subscriptionFirstCharges) / 100) * (rates.billingPercent || 0);
|
|
60
|
+
return { usd: round4(reported + estimated), reportedUsd: round4(reported), estimatedUsd: round4(estimated), basis: estimated > 0 ? (reported > 0 ? 'stripe_reported_plus_published_rate' : 'published_rate') : 'stripe_reported' };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function perUnit(totalUsd, count) {
|
|
64
|
+
return Number.isFinite(totalUsd) && Number.isInteger(count) && count > 0 ? round4(totalUsd / count) : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Contribution for one plan sale: price, minus the payment fee on that price, minus the delivery cost one customer adds.
|
|
68
|
+
function planContribution({ priceUsd, recurring, costPerCustomerUsd, rates, laborNote = null }) {
|
|
69
|
+
if (!Number.isFinite(priceUsd) || !rates) return null;
|
|
70
|
+
const feeUsd = priceUsd * rates.percent + rates.fixedUsd + (recurring ? priceUsd * (rates.billingPercent || 0) : 0);
|
|
71
|
+
const deliveryUsd = Number.isFinite(costPerCustomerUsd) ? costPerCustomerUsd : 0;
|
|
72
|
+
const contributionUsd = priceUsd - feeUsd - deliveryUsd;
|
|
73
|
+
return { priceUsd: round2(priceUsd), paymentFeeUsd: round2(feeUsd), deliveryCostUsd: round4(deliveryUsd), contributionUsd: round2(contributionUsd), marginPct: round4(contributionUsd / priceUsd), laborNote };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// The whole board. `money` is collectMoney's data, `usage` the 30-day CLI usage, `meter` cost-meter's 30-day window.
|
|
77
|
+
function computeUnitEconomics({ money = null, usage = null, meter = null, costs = loadUnitCosts() } = {}) {
|
|
78
|
+
if (!costs) return { status: 'unavailable', reason: 'config/unit-costs.json could not be read.' };
|
|
79
|
+
const hosting = hostingCost(meter, costs.hosting);
|
|
80
|
+
const emails = meter ? meter.emails : null;
|
|
81
|
+
const emailUsd = Number.isInteger(emails) ? round4(emails * costs.email.costPerEmailUsd) : null;
|
|
82
|
+
const fees = paymentFees(money, costs.payments);
|
|
83
|
+
const fixedUsd = round4(sumList(costs.fixedDeliveryMonthly));
|
|
84
|
+
const buildUsd = round4(sumList(costs.buildAndInternalMonthly));
|
|
85
|
+
const parts = [hosting.usd, emailUsd, fees.usd, fixedUsd];
|
|
86
|
+
const deliveryUsd = parts.every(Number.isFinite) ? round4(parts.reduce((a, b) => a + b, 0)) : null;
|
|
87
|
+
// Serving cost (hosting, email, fixed) is shared by every install; payment fees belong to paying customers only.
|
|
88
|
+
const servingUsd = [hosting.usd, emailUsd, fixedUsd].every(Number.isFinite) ? hosting.usd + emailUsd + fixedUsd : null;
|
|
89
|
+
|
|
90
|
+
const activeInstalls = Number.isInteger(usage?.activeInstalls30d) ? usage.activeInstalls30d : null;
|
|
91
|
+
const payingCustomers = Number.isInteger(money?.payingCustomers) ? money.payingCustomers : null;
|
|
92
|
+
const activePro = Number.isInteger(money?.activePro) ? money.activePro : null;
|
|
93
|
+
const servingPerInstall = perUnit(servingUsd, activeInstalls);
|
|
94
|
+
|
|
95
|
+
const oneTimeUsd = money ? usdCents(money.revenueLast30Days) / 100 : null;
|
|
96
|
+
const renewalsUsd = money ? usdCents(money.recurring30d?.renewalRevenue) / 100 : null;
|
|
97
|
+
const revenueUsd = money ? round2(oneTimeUsd + renewalsUsd) : null;
|
|
98
|
+
const otherCurrencies = money ? [...new Set([...Object.keys(money.revenueLast30Days || {}), ...Object.keys(money.recurring30d?.renewalRevenue || {}), ...Object.keys(money.mrr || {})])].filter((code) => code !== 'USD') : [];
|
|
99
|
+
const contribution = Number.isFinite(revenueUsd) && Number.isFinite(deliveryUsd)
|
|
100
|
+
? { revenueUsd, deliveryUsd, contributionUsd: round2(revenueUsd - deliveryUsd), marginPct: revenueUsd > 0 ? round4((revenueUsd - deliveryUsd) / revenueUsd) : null, afterBuildUsd: round2(revenueUsd - deliveryUsd - buildUsd) }
|
|
101
|
+
: null;
|
|
102
|
+
|
|
103
|
+
// Pro: the list price, or the average active subscription in dollars when Stripe has some.
|
|
104
|
+
const mrrUsd = money ? usdCents(money.mrr) / 100 : 0;
|
|
105
|
+
const proPrice = activePro > 0 && mrrUsd > 0 ? mrrUsd / activePro : costs.plans.pro.listMonthlyUsd;
|
|
106
|
+
const plans = {
|
|
107
|
+
pro: { name: costs.plans.pro.name, priceBasis: activePro > 0 && mrrUsd > 0 ? 'stripe_average_active_subscription' : 'list_price', ...planContribution({ priceUsd: proPrice, recurring: true, costPerCustomerUsd: servingPerInstall, rates: costs.payments }) },
|
|
108
|
+
setupSprint: { name: costs.plans.setupSprint.name, priceBasis: 'list_price', ...planContribution({ priceUsd: costs.plans.setupSprint.listUsd, recurring: false, costPerCustomerUsd: servingPerInstall, rates: costs.payments, laborNote: costs.plans.setupSprint.deliveryHoursNote }) },
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const reasons = {};
|
|
112
|
+
if (hosting.reason) reasons.hosting = hosting.reason;
|
|
113
|
+
if (fees.reason) reasons.paymentFees = fees.reason;
|
|
114
|
+
if (activeInstalls === null) reasons.activeInstalls = 'CLI usage telemetry is not available right now.';
|
|
115
|
+
else if (activeInstalls === 0) reasons.activeInstalls = 'No active installs in 30 days, so there is no cost per install.';
|
|
116
|
+
if (payingCustomers === 0) reasons.payingCustomers = 'No paying customers, so there is no cost per paying customer.';
|
|
117
|
+
if (!costs.fixedDeliveryMonthly.length) reasons.fixed = 'No fixed delivery costs are recorded in config/unit-costs.json.';
|
|
118
|
+
if (!costs.buildAndInternalMonthly.length) reasons.build = 'No build or internal costs are recorded in config/unit-costs.json, so "after build costs" equals contribution.';
|
|
119
|
+
if (otherCurrencies.length) reasons.currencies = `Revenue in ${otherCurrencies.join(', ')} is left out: only US dollars are added up, and nothing is converted.`;
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
status: deliveryUsd === null ? 'partial' : 'ok',
|
|
123
|
+
window: '30d',
|
|
124
|
+
ratesCheckedAt: costs.checkedAt,
|
|
125
|
+
delivery: { hostingUsd: hosting.usd, hosting, emails, emailUsd, emailBasis: costs.email.basis, paymentFeesUsd: fees.usd, paymentFees: fees, fixedUsd, totalUsd: deliveryUsd },
|
|
126
|
+
build: { totalUsd: buildUsd, items: costs.buildAndInternalMonthly },
|
|
127
|
+
denominators: { activeInstalls30d: activeInstalls, payingCustomers, activePro },
|
|
128
|
+
perActiveInstallUsd: servingPerInstall,
|
|
129
|
+
perPayingCustomerUsd: perUnit(deliveryUsd, payingCustomers),
|
|
130
|
+
revenue: { oneTimeUsd, renewalsUsd, totalUsd: revenueUsd, mrrUsd: money ? round2(mrrUsd) : null },
|
|
131
|
+
contribution,
|
|
132
|
+
plans,
|
|
133
|
+
reasons,
|
|
134
|
+
sources: { hosting: costs.hosting.source, email: costs.email.source, payments: costs.payments.source },
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = { computeUnitEconomics, hostingCost, paymentFees, planContribution, loadUnitCosts, cents };
|
package/server.json
CHANGED
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"source": "github",
|
|
9
9
|
"url": "https://github.com/IgorGanapolsky/ThumbGate"
|
|
10
10
|
},
|
|
11
|
-
"version": "1.40.
|
|
11
|
+
"version": "1.40.14",
|
|
12
12
|
"packages": [
|
|
13
13
|
{
|
|
14
14
|
"registryType": "npm",
|
|
15
15
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
16
16
|
"identifier": "thumbgate",
|
|
17
|
-
"version": "1.40.
|
|
17
|
+
"version": "1.40.14",
|
|
18
18
|
"runtimeHint": "npx",
|
|
19
19
|
"runtimeArguments": [
|
|
20
20
|
{
|