@mnemom/mnemom 0.17.38-next.1 → 0.17.38-next.2

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.
Files changed (66) hide show
  1. package/dist/commands/agent-run.d.ts +10 -2
  2. package/dist/commands/agent-run.js +12 -6
  3. package/dist/commands/scan.d.ts +1 -1
  4. package/dist/commands/scan.js +7 -14
  5. package/dist/lib/runner/executor-client.d.ts +6 -0
  6. package/dist/lib/runner/executor-client.js +6 -0
  7. package/dist/lib/runner/job.d.ts +12 -3
  8. package/dist/lib/runner/job.js +30 -2
  9. package/dist/lib/scan/caps.d.ts +1 -35
  10. package/dist/lib/scan/caps.js +2 -67
  11. package/dist/lib/scan/cost-per-pr.d.ts +1 -93
  12. package/dist/lib/scan/cost-per-pr.js +2 -101
  13. package/dist/lib/scan/credential.d.ts +2 -26
  14. package/dist/lib/scan/credential.js +5 -58
  15. package/dist/lib/scan/failure.d.ts +1 -10
  16. package/dist/lib/scan/failure.js +2 -43
  17. package/dist/lib/scan/pr-source.d.ts +1 -57
  18. package/dist/lib/scan/pr-source.js +2 -132
  19. package/dist/lib/scan/report-email.d.ts +7 -104
  20. package/dist/lib/scan/report-email.js +25 -97
  21. package/dist/lib/scan/scan.d.ts +1 -69
  22. package/dist/lib/scan/scan.js +2 -195
  23. package/dist/lib/scan/share.d.ts +3 -1
  24. package/dist/lib/scan/spend/ai-tool-detect.d.ts +1 -6
  25. package/dist/lib/scan/spend/ai-tool-detect.js +2 -18
  26. package/dist/lib/scan/spend/anthropic-usage.d.ts +1 -76
  27. package/dist/lib/scan/spend/anthropic-usage.js +2 -269
  28. package/dist/lib/scan/spend/prices.d.ts +1 -33
  29. package/dist/lib/scan/spend/prices.js +2 -57
  30. package/dist/lib/scan/spend/spend-estimate.d.ts +1 -30
  31. package/dist/lib/scan/spend/spend-estimate.js +2 -70
  32. package/dist/lib/scan/spend/spend-tiers.d.ts +1 -16
  33. package/dist/lib/scan/spend/spend-tiers.js +6 -26
  34. package/dist/lib/scan/spend/token-rate.d.ts +1 -30
  35. package/dist/lib/scan/spend/token-rate.js +2 -54
  36. package/dist/vendor/shared/org-scan-core/caps.d.ts +35 -0
  37. package/dist/vendor/shared/org-scan-core/caps.js +68 -0
  38. package/dist/vendor/shared/org-scan-core/cost-per-pr.d.ts +93 -0
  39. package/dist/vendor/shared/org-scan-core/cost-per-pr.js +101 -0
  40. package/dist/vendor/shared/org-scan-core/credential.d.ts +43 -0
  41. package/dist/vendor/shared/org-scan-core/credential.js +74 -0
  42. package/dist/vendor/shared/org-scan-core/failure.d.ts +10 -0
  43. package/dist/vendor/shared/org-scan-core/failure.js +43 -0
  44. package/dist/vendor/shared/org-scan-core/index.d.ts +18 -0
  45. package/dist/vendor/shared/org-scan-core/index.js +19 -0
  46. package/dist/vendor/shared/org-scan-core/pr-source.d.ts +61 -0
  47. package/dist/vendor/shared/org-scan-core/pr-source.js +138 -0
  48. package/dist/vendor/shared/org-scan-core/report-build.d.ts +120 -0
  49. package/dist/vendor/shared/org-scan-core/report-build.js +119 -0
  50. package/dist/vendor/shared/org-scan-core/scan.d.ts +75 -0
  51. package/dist/vendor/shared/org-scan-core/scan.js +202 -0
  52. package/dist/vendor/shared/org-scan-core/spend/ai-tool-detect.d.ts +6 -0
  53. package/dist/vendor/shared/org-scan-core/spend/ai-tool-detect.js +18 -0
  54. package/dist/vendor/shared/org-scan-core/spend/anthropic-usage.d.ts +76 -0
  55. package/dist/vendor/shared/org-scan-core/spend/anthropic-usage.js +270 -0
  56. package/dist/{lib/scan → vendor/shared/org-scan-core}/spend/cost-corpus.v1.js +1 -0
  57. package/dist/vendor/shared/org-scan-core/spend/prices.d.ts +33 -0
  58. package/dist/vendor/shared/org-scan-core/spend/prices.js +58 -0
  59. package/dist/vendor/shared/org-scan-core/spend/spend-estimate.d.ts +30 -0
  60. package/dist/vendor/shared/org-scan-core/spend/spend-estimate.js +71 -0
  61. package/dist/vendor/shared/org-scan-core/spend/spend-select.d.ts +16 -0
  62. package/dist/vendor/shared/org-scan-core/spend/spend-select.js +26 -0
  63. package/dist/vendor/shared/org-scan-core/spend/token-rate.d.ts +30 -0
  64. package/dist/vendor/shared/org-scan-core/spend/token-rate.js +55 -0
  65. package/package.json +1 -1
  66. /package/dist/{lib/scan → vendor/shared/org-scan-core}/spend/cost-corpus.v1.d.ts +0 -0
@@ -1,57 +1,2 @@
1
- // MNE-9268: public list prices for the AI coding tools the Tier-3 spend estimator can name.
2
- // Constants, not magic numbers: every row carries its source page and the date it was read.
3
- // USD per million tokens (input / output), standard (non-batch) list price. A band is the cheapest
4
- // and the dearest model a tool's coding agent plausibly runs on, so the estimate is a RANGE.
5
- // Re-read the pages and bump PRICES_AS_OF when they move; a stale price widens nothing silently,
6
- // it just shifts the range, which is why the date ships with the estimate's method text.
7
- export const PRICES_AS_OF = "2026-10-28";
8
- export const TOOL_PRICES = {
9
- claude_code: {
10
- source: "https://platform.claude.com/docs/en/about-claude/pricing",
11
- low: { model: "Claude Sonnet 5.5", inputPerMTok: 2, outputPerMTok: 10 },
12
- high: { model: "Claude Opus 5", inputPerMTok: 5, outputPerMTok: 25 },
13
- },
14
- codex: {
15
- source: "https://developers.openai.com/api/docs/pricing",
16
- low: { model: "gpt-5.3-codex (standard)", inputPerMTok: 1.75, outputPerMTok: 14 },
17
- high: { model: "gpt-5.3-codex (fast)", inputPerMTok: 3.5, outputPerMTok: 28 },
18
- },
19
- gemini: {
20
- source: "https://ai.google.dev/gemini-api/docs/pricing",
21
- // Gemini 3.8 Flash is $0.75/$3.75 through 2026-12-31 and $1.50/$7.50 from 2027-01-01; the
22
- // post-promotion price is used so the lower bound does not expire in two months.
23
- low: { model: "Gemini 3.8 Flash (from 2027-01-01)", inputPerMTok: 1.5, outputPerMTok: 7.5 },
24
- high: { model: "Gemini 3.1 Pro (prompts up to 200k)", inputPerMTok: 2, outputPerMTok: 12 },
25
- },
26
- };
27
- /**
28
- * GitHub Copilot bills per premium request, not per token
29
- * (https://docs.github.com/en/copilot/concepts/billing/copilot-requests),
30
- * so it has no token price of its own. Its agent routes to the other vendors' models, so its band is
31
- * the union of the other three: cheapest low to dearest high. An assumption, stated here once.
32
- */
33
- export function copilotBand() {
34
- const bands = Object.values(TOOL_PRICES);
35
- const blend = (p) => p.inputPerMTok * INPUT_SHARE + p.outputPerMTok * (1 - INPUT_SHARE);
36
- const low = bands.map((b) => b.low).sort((a, b) => blend(a) - blend(b))[0];
37
- const high = bands.map((b) => b.high).sort((a, b) => blend(b) - blend(a))[0];
38
- return {
39
- low,
40
- high,
41
- source: "union of the claude_code, codex and gemini bands (per-request billing)",
42
- };
43
- }
44
- /**
45
- * Share of billed tokens that are input (the rest output). Agent loops re-read large context and
46
- * write little, so input dominates. An ASSUMPTION used both to turn our known run cost into
47
- * tokens-per-line and to price those tokens for each tool; it cancels to first order when the
48
- * tool's input/output price ratio matches ours, and is the main source of the range's width.
49
- */
50
- export const INPUT_SHARE = 0.9;
51
- export function bandFor(tool) {
52
- return tool === "copilot" ? copilotBand() : TOOL_PRICES[tool];
53
- }
54
- /** USD per token at the assumed input/output mix. */
55
- export function blendedUsdPerToken(p) {
56
- return (p.inputPerMTok * INPUT_SHARE + p.outputPerMTok * (1 - INPUT_SHARE)) / 1_000_000;
57
- }
1
+ // Moved to shared/org-scan-core (MNE-9752); vendored at cli/src/vendor/shared/org-scan-core. Re-exported so CLI imports stay put.
2
+ export * from "../../../vendor/shared/org-scan-core/spend/prices.js";
@@ -1,30 +1 @@
1
- import { type AiTool } from "./prices.js";
2
- import { type TokenRate } from "./token-rate.js";
3
- /** AI-assisted PRs needed before a range is worth printing. */
4
- export declare const MIN_AI_PRS = 10;
5
- /** Per-PR input. `markText` is commit messages / PR body, read for tool marks and dropped. */
6
- export interface SpendPrInput {
7
- additions: number;
8
- deletions: number;
9
- markText: string;
10
- /** Tools already detected inside the PR source (so the body never leaves it). Wins over markText. */
11
- tools?: AiTool[];
12
- }
13
- export type NoSpendReason = "too_few_ai_prs" | "no_rate" | "invalid_input";
14
- export type SpendEstimate = {
15
- kind: "range";
16
- lowUsd: number;
17
- highUsd: number;
18
- aiPrs: number;
19
- scannedPrs: number;
20
- byTool: Partial<Record<AiTool, number>>;
21
- /** One line, labelled estimate, passes claim-lint. */
22
- line: string;
23
- } | {
24
- kind: "none";
25
- reason: NoSpendReason;
26
- aiPrs: number;
27
- scannedPrs: number;
28
- line: string;
29
- };
30
- export declare function estimateSpend(prs: unknown, rate?: TokenRate | null): SpendEstimate;
1
+ export * from "../../../vendor/shared/org-scan-core/spend/spend-estimate.js";
@@ -1,70 +1,2 @@
1
- // MNE-9268: Tier-3 spend RANGE estimator. Pure and in-memory: takes per-PR counts and mark text, returns
2
- // one labelled estimate line or an explicit "no estimate". Nothing is stored, fetched or logged.
3
- //
4
- // No line is produced when there are too few AI-assisted PRs to price (MIN_AI_PRS). That is a
5
- // data-sufficiency threshold on the evidence behind the range, nothing to do with how large a
6
- // reporting cohort is. Default-OFF behind ORG_SCAN_MODE via estimateSpendIfEnabled.
7
- import { AI_TOOLS, detectAiTools } from "./ai-tool-detect.js";
8
- import { PRICES_AS_OF, bandFor, blendedUsdPerToken } from "./prices.js";
9
- import { DERIVED_TOKEN_RATE } from "./token-rate.js";
10
- /** AI-assisted PRs needed before a range is worth printing. */
11
- export const MIN_AI_PRS = 10;
12
- /** Fixed strings only: a failure never carries input or an error message into the output. */
13
- const NONE_LINES = {
14
- too_few_ai_prs: "No spend estimate: too few AI-assisted PRs in this scan to price a range.",
15
- no_rate: "No spend estimate: the cost reference data is not sufficient to price a range.",
16
- invalid_input: "No spend estimate: the PR counts could not be read.",
17
- };
18
- const isCount = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
19
- function none(reason, aiPrs, scannedPrs) {
20
- return { kind: "none", reason, aiPrs, scannedPrs, line: NONE_LINES[reason] };
21
- }
22
- function validPr(p) {
23
- if (typeof p !== "object" || p === null)
24
- return false;
25
- const o = p;
26
- return (isCount(o.additions) &&
27
- isCount(o.deletions) &&
28
- typeof o.markText === "string" &&
29
- (o.tools === undefined ||
30
- (Array.isArray(o.tools) && o.tools.every((t) => AI_TOOLS.includes(t)))));
31
- }
32
- /** Two significant figures so the range does not claim precision it lacks ($2.4, not $2; 0 stays $0). */
33
- function usd(n) {
34
- return `$${n.toLocaleString("en-US", { maximumSignificantDigits: 2 })}`;
35
- }
36
- export function estimateSpend(prs, rate = DERIVED_TOKEN_RATE) {
37
- if (!Array.isArray(prs))
38
- return none("invalid_input", 0, 0);
39
- const scanned = prs.length;
40
- if (!prs.every(validPr))
41
- return none("invalid_input", 0, scanned);
42
- let aiPrs = 0;
43
- let low = 0;
44
- let high = 0;
45
- const byTool = {};
46
- for (const p of prs) {
47
- const tools = p.tools ?? detectAiTools(p.markText);
48
- if (tools.length === 0)
49
- continue;
50
- aiPrs += 1;
51
- for (const t of tools)
52
- byTool[t] = (byTool[t] ?? 0) + 1;
53
- if (!rate)
54
- continue;
55
- const lines = p.additions + p.deletions;
56
- // A PR carrying several marks is priced once, across the widest band of the tools named.
57
- const bands = tools.map(bandFor);
58
- const lo = Math.min(...bands.map((b) => blendedUsdPerToken(b.low)));
59
- const hi = Math.max(...bands.map((b) => blendedUsdPerToken(b.high)));
60
- low += lines * rate.low * lo;
61
- high += lines * rate.high * hi;
62
- }
63
- if (aiPrs < MIN_AI_PRS)
64
- return none("too_few_ai_prs", aiPrs, scanned);
65
- if (!rate)
66
- return none("no_rate", aiPrs, scanned);
67
- const line = `Estimate, AI tool spend: ${usd(low)} to ${usd(high)} across ${aiPrs} AI-assisted PRs ` +
68
- `(public list prices as of ${PRICES_AS_OF} times a tokens-per-line rate from our own agents' PRs; not billing data).`;
69
- return { kind: "range", lowUsd: low, highUsd: high, aiPrs, scannedPrs: scanned, byTool, line };
70
- }
1
+ // Moved to shared/org-scan-core (MNE-9752); vendored at cli/src/vendor/shared/org-scan-core. Re-exported so CLI imports stay put.
2
+ export * from "../../../vendor/shared/org-scan-core/spend/spend-estimate.js";
@@ -1,4 +1,3 @@
1
- import type { SpendEstimate } from "./spend-estimate.js";
2
1
  export declare const ORG_SCAN_ENV = "MNEMOM_ORG_SCAN_MODE";
3
2
  /** Default OFF: only the exact string "true" turns the tiers on. */
4
3
  export declare const isSpendTiersEnabled: (env?: NodeJS.ProcessEnv) => boolean;
@@ -8,18 +7,4 @@ export declare const SPEND_NO_TERMINAL_MSG = "Pass --monthly-spend <usd> (there
8
7
  export declare const MAX_MONTHLY_SPEND_USD = 10000000;
9
8
  /** Dollars, or null if the text is not a positive, plausible amount. */
10
9
  export declare function parseMonthlySpendUsd(raw: string): number | null;
11
- export type SpendTier = 1 | 2 | 3;
12
- export interface SpendSelection {
13
- /** null when the evidence is too thin: print nothing. */
14
- tier: SpendTier | null;
15
- line: string | null;
16
- /** May this line leave the machine in a share payload? Never for a self-reported figure. */
17
- shareable: boolean;
18
- }
19
- export declare function selectSpend(i: {
20
- measuredUsd?: number;
21
- /** Fraction of measured tokens from requests over 200k context; shown only with a measured figure. */
22
- over200kShare?: number | null;
23
- selfReportedUsd?: number | null;
24
- estimate: SpendEstimate;
25
- }): SpendSelection;
10
+ export { selectSpend, type SpendTier, type SpendSelection, } from "../../../vendor/shared/org-scan-core/spend/spend-select.js";
@@ -1,3 +1,8 @@
1
+ // MNE-9298: the CLI side of the spend tiers (env flag, typed figure). selectSpend is shared (MNE-9752).
2
+ // Tier 1 measured Anthropic usage the customer connected (a number handed in by the caller).
3
+ // Tier 2 a dollar figure the CTO gives; self-reported, labelled so, never sent or saved.
4
+ // Tier 3 the PR-size estimate range, only when the evidence behind it is enough.
5
+ // With none of the three there is NO line: a number is never invented to fill the gap.
1
6
  export const ORG_SCAN_ENV = "MNEMOM_ORG_SCAN_MODE";
2
7
  /** Default OFF: only the exact string "true" turns the tiers on. */
3
8
  export const isSpendTiersEnabled = (env = process.env) => env[ORG_SCAN_ENV] === "true";
@@ -14,29 +19,4 @@ export function parseMonthlySpendUsd(raw) {
14
19
  const n = Number(t.replace(/[$,\s]/g, ""));
15
20
  return Number.isFinite(n) && n > 0 && n <= MAX_MONTHLY_SPEND_USD ? n : null;
16
21
  }
17
- const usd = (n) => `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
18
- const isUsd = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
19
- const pct = (f) => `${Math.round(f * 100)}%`;
20
- const isShare = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1;
21
- export function selectSpend(i) {
22
- if (isUsd(i.measuredUsd)) {
23
- return {
24
- tier: 1,
25
- line: `Tier 1, measured: ${usd(i.measuredUsd)} of Anthropic usage over the period${isShare(i.over200kShare)
26
- ? ` (${pct(i.over200kShare)} of tokens in requests over 200k context)`
27
- : ""}.`,
28
- shareable: true,
29
- };
30
- }
31
- if (isUsd(i.selfReportedUsd)) {
32
- return {
33
- tier: 2,
34
- line: `Tier 2, self-reported: about ${usd(i.selfReportedUsd)} a month (given by you; not verified, not sent, not saved).`,
35
- shareable: false,
36
- };
37
- }
38
- if (i.estimate.kind === "range") {
39
- return { tier: 3, line: `Tier 3, ${i.estimate.line}`, shareable: true };
40
- }
41
- return { tier: null, line: null, shareable: false };
42
- }
22
+ export { selectSpend, } from "../../../vendor/shared/org-scan-core/spend/spend-select.js";
@@ -1,30 +1 @@
1
- /** Rows needed before the rate is trusted at all (data sufficiency, not a group size). */
2
- export declare const MIN_CORPUS_ROWS = 5;
3
- export interface CostRowShape {
4
- repo: string;
5
- pr: number;
6
- additions: number;
7
- deletions: number;
8
- cost_usd: number;
9
- runs: number;
10
- models: string[];
11
- }
12
- export interface TokenRate {
13
- /** Price-equivalent tokens per changed (added + deleted) line: 25th percentile. */
14
- low: number;
15
- median: number;
16
- /** 75th percentile. */
17
- high: number;
18
- rows: number;
19
- }
20
- /** Linear-interpolated quantile of a sorted array. */
21
- export declare function quantile(sorted: number[], q: number): number;
22
- /**
23
- * Derive the rate from corpus rows: per-row tokens/line, then the 25th, 50th and 75th percentile.
24
- * Rows that fail validation are dropped (not repaired); fewer than MIN_CORPUS_ROWS valid rows
25
- * returns null, never a rate built on a handful.
26
- */
27
- export declare function deriveTokenRate(rows: unknown): TokenRate | null;
28
- export declare const CORPUS_AS_OF: string;
29
- /** The shipped rate: derived once from the committed fixture. */
30
- export declare const DERIVED_TOKEN_RATE: TokenRate | null;
1
+ export * from "../../../vendor/shared/org-scan-core/spend/token-rate.js";
@@ -1,54 +1,2 @@
1
- // MNE-9268: tokens-per-changed-line and its spread, DERIVED from our own agents' PRs whose run cost is
2
- // known (cost-corpus.v1.json, built by build-cost-corpus.mjs from the ADW "Run cost" PR comments).
3
- // Nothing here is a typed-in rate: change the fixture and the rate moves, and token-rate.test.ts pins
4
- // the derivation. Tokens are price-equivalent: cost / (our model's blended list price per token).
5
- import rawCorpus from "./cost-corpus.v1.js";
6
- import { TOOL_PRICES, blendedUsdPerToken } from "./prices.js";
7
- /** Rows needed before the rate is trusted at all (data sufficiency, not a group size). */
8
- export const MIN_CORPUS_ROWS = 5;
9
- /** Our agents ran on Sonnet-family models in every corpus row; price their tokens as that. */
10
- const BASIS_USD_PER_TOKEN = blendedUsdPerToken(TOOL_PRICES.claude_code.low);
11
- const isCount = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
12
- function validRow(r) {
13
- if (typeof r !== "object" || r === null)
14
- return false;
15
- const o = r;
16
- return (isCount(o.additions) &&
17
- isCount(o.deletions) &&
18
- o.additions + o.deletions > 0 &&
19
- isCount(o.cost_usd) &&
20
- o.cost_usd > 0);
21
- }
22
- /** Linear-interpolated quantile of a sorted array. */
23
- export function quantile(sorted, q) {
24
- if (sorted.length === 0)
25
- return NaN;
26
- const pos = (sorted.length - 1) * q;
27
- const lo = Math.floor(pos);
28
- const hi = Math.ceil(pos);
29
- return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
30
- }
31
- /**
32
- * Derive the rate from corpus rows: per-row tokens/line, then the 25th, 50th and 75th percentile.
33
- * Rows that fail validation are dropped (not repaired); fewer than MIN_CORPUS_ROWS valid rows
34
- * returns null, never a rate built on a handful.
35
- */
36
- export function deriveTokenRate(rows) {
37
- if (!Array.isArray(rows))
38
- return null;
39
- const per = rows
40
- .filter(validRow)
41
- .map((r) => r.cost_usd / (r.additions + r.deletions) / BASIS_USD_PER_TOKEN)
42
- .sort((a, b) => a - b);
43
- if (per.length < MIN_CORPUS_ROWS)
44
- return null;
45
- return {
46
- low: quantile(per, 0.25),
47
- median: quantile(per, 0.5),
48
- high: quantile(per, 0.75),
49
- rows: per.length,
50
- };
51
- }
52
- export const CORPUS_AS_OF = rawCorpus.as_of;
53
- /** The shipped rate: derived once from the committed fixture. */
54
- export const DERIVED_TOKEN_RATE = deriveTokenRate(rawCorpus.rows);
1
+ // Moved to shared/org-scan-core (MNE-9752); vendored at cli/src/vendor/shared/org-scan-core. Re-exported so CLI imports stay put.
2
+ export * from "../../../vendor/shared/org-scan-core/spend/token-rate.js";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Coverage caps and sampling. Port of mnemom-api src/org-scan/scan/capped-scan.ts (PR #4208).
3
+ *
4
+ * Coverage decision (Shraddha, 2026-10-28): each scan covers the last 3 months OR the last 2,000 merged
5
+ * PRs, whichever is MORE; above 2,000 in the window, an even deterministic sample of 2,000.
6
+ */
7
+ export declare const COVERAGE_MONTHS = 3;
8
+ export interface ScanCaps {
9
+ maxPrs: number;
10
+ /** A PR with more additions+deletions than this is skipped, never read in full. */
11
+ maxPrSizeLines: number;
12
+ /** Upstream read calls. */
13
+ maxReads: number;
14
+ /** Wall-clock budget. */
15
+ maxMillis: number;
16
+ }
17
+ export declare const DEFAULT_SCAN_CAPS: ScanCaps;
18
+ export type StopReason = "pr-cap" | "read-cap" | "time-cap";
19
+ /** The day `months` calendar months before `end` (YYYY-MM-DD, UTC), clamped to the month's last day. */
20
+ export declare function monthsBefore(end: string, months: number): string;
21
+ /** `k` items spread evenly across `items` (order kept): index floor(i*n/k). Deterministic; n <= k returns all. */
22
+ export declare function evenSample<T>(items: readonly T[], k: number): T[];
23
+ export declare function sanitiseCaps(c: Partial<ScanCaps>): ScanCaps;
24
+ /** Running read budget. Every call is told how many reads it may spend (`room`). */
25
+ export declare class Budget {
26
+ private caps;
27
+ private now;
28
+ private startedAt;
29
+ reads: number;
30
+ constructor(caps: ScanCaps, now: () => number, startedAt: number);
31
+ block(n?: number): StopReason | null;
32
+ room(): number;
33
+ overrun(): StopReason | null;
34
+ charge(n: number): void;
35
+ }
@@ -0,0 +1,68 @@
1
+ // GENERATED from shared/org-scan-core/src/caps.ts by cli/scripts/sync-org-scan-core.mjs; do not edit.
2
+ /**
3
+ * Coverage caps and sampling. Port of mnemom-api src/org-scan/scan/capped-scan.ts (PR #4208).
4
+ *
5
+ * Coverage decision (Shraddha, 2026-10-28): each scan covers the last 3 months OR the last 2,000 merged
6
+ * PRs, whichever is MORE; above 2,000 in the window, an even deterministic sample of 2,000.
7
+ */
8
+ export const COVERAGE_MONTHS = 3;
9
+ export const DEFAULT_SCAN_CAPS = {
10
+ maxPrs: 2_000,
11
+ maxPrSizeLines: 20_000,
12
+ maxReads: 4_500,
13
+ maxMillis: 15 * 60_000,
14
+ };
15
+ /** The day `months` calendar months before `end` (YYYY-MM-DD, UTC), clamped to the month's last day. */
16
+ export function monthsBefore(end, months) {
17
+ const [y, m, d] = end.split("-").map(Number);
18
+ const target = new Date(Date.UTC(y, m - 1 - months, 1));
19
+ const last = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
20
+ target.setUTCDate(Math.min(d, last));
21
+ return target.toISOString().slice(0, 10);
22
+ }
23
+ /** `k` items spread evenly across `items` (order kept): index floor(i*n/k). Deterministic; n <= k returns all. */
24
+ export function evenSample(items, k) {
25
+ const n = items.length;
26
+ if (n <= k)
27
+ return [...items];
28
+ return Array.from({ length: k }, (_, i) => items[Math.floor((i * n) / k)]);
29
+ }
30
+ export function sanitiseCaps(c) {
31
+ const pos = (n, d) => typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : d;
32
+ return {
33
+ maxPrs: pos(c.maxPrs, DEFAULT_SCAN_CAPS.maxPrs),
34
+ maxPrSizeLines: pos(c.maxPrSizeLines, DEFAULT_SCAN_CAPS.maxPrSizeLines),
35
+ maxReads: pos(c.maxReads, DEFAULT_SCAN_CAPS.maxReads),
36
+ maxMillis: pos(c.maxMillis, DEFAULT_SCAN_CAPS.maxMillis),
37
+ };
38
+ }
39
+ /** Running read budget. Every call is told how many reads it may spend (`room`). */
40
+ export class Budget {
41
+ caps;
42
+ now;
43
+ startedAt;
44
+ reads = 0;
45
+ constructor(caps, now, startedAt) {
46
+ this.caps = caps;
47
+ this.now = now;
48
+ this.startedAt = startedAt;
49
+ }
50
+ block(n = 1) {
51
+ if (this.now() - this.startedAt >= this.caps.maxMillis)
52
+ return "time-cap";
53
+ if (this.reads + n > this.caps.maxReads)
54
+ return "read-cap";
55
+ return null;
56
+ }
57
+ room() {
58
+ if (this.now() - this.startedAt >= this.caps.maxMillis)
59
+ return 0;
60
+ return Math.max(0, this.caps.maxReads - this.reads);
61
+ }
62
+ overrun() {
63
+ return this.reads > this.caps.maxReads ? "read-cap" : null;
64
+ }
65
+ charge(n) {
66
+ this.reads += n;
67
+ }
68
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Cost per merged PR and cost by PR size, for the Org Scan report. Pure: numbers in, numbers out.
3
+ *
4
+ * Source of the spend. Measured per-request cost cannot be tied to a PR with the data the scan has:
5
+ * the Anthropic usage reads return one whole-org total (no per-request or per-PR rows) and the Mnemom
6
+ * Record totals are one window sum (model cost and a request count, no PR key). So every figure here is
7
+ * `label: "estimate"`: the period's spend split across the merged PRs in proportion to lines changed.
8
+ * Each figure names the spend it was split from (`spend_source`); sources are never mixed in one report.
9
+ *
10
+ * anthropic_usage the whole-org Anthropic cost for the period (the CTO's admin key)
11
+ * modelled_range our modelled estimate (a low to high range, so the figures are ranges)
12
+ *
13
+ * Size is per PR, in lines changed = additions + deletions, exactly as GitHub reports them. Lockfiles and
14
+ * generated files are NOT excluded. small < 50; medium 50..500 inclusive; large > 500.
15
+ *
16
+ * Each size figure is the average cost of ONE PR of that size: spend * (mean lines of the bucket) /
17
+ * (total lines of the PRs in scope). Scope: the modelled estimate prices AI-assisted PRs only, so it is
18
+ * split across those only (`pr_scope: "ai_assisted"`, buckets too); the others use every merged PR
19
+ * (`pr_scope: "all_merged"`). `pr_count` counts PRs in that scope. Usage-key figures also carry
20
+ * `spend_scope: "whole_org"` (the key covers the whole organization, not just the scanned repos). The cost per merged PR is the spend over the count of merged PRs.
21
+ *
22
+ * Missing data is an absent field, never 0 or NaN: no usable spend, zero merged PRs in the period, an
23
+ * empty bucket, a scan that did not read every merged PR in the period, or a result past safe-integer
24
+ * range. Reverts are listed without sizes, so they are not counted as merged PRs here.
25
+ */
26
+ import type { SpendEstimate } from "./spend/spend-estimate.js";
27
+ /** Strictly below this is small. 50 is medium. */
28
+ export declare const SMALL_MAX_EXCLUSIVE = 50;
29
+ /** At or below this (and not small) is medium. 500 is medium; 501 is large. */
30
+ export declare const MEDIUM_MAX_INCLUSIVE = 500;
31
+ export type SizeBucket = "small" | "medium" | "large";
32
+ export type CostSpendSourceName = "anthropic_usage" | "modelled_range";
33
+ export interface PrSize {
34
+ /** YYYY-MM-DD, UTC. */
35
+ mergedDay: string;
36
+ /** additions + deletions. */
37
+ lines: number;
38
+ /** The PR carries an AI-tool mark (the same rule the modelled spend uses to count AI-assisted PRs). */
39
+ aiAssisted: boolean;
40
+ }
41
+ /** Where the spend comes from. USD, never cents. */
42
+ export type CostSpend = {
43
+ source: "anthropic_usage";
44
+ usd: number;
45
+ } | {
46
+ source: "modelled_range";
47
+ lowUsd: number;
48
+ highUsd: number;
49
+ };
50
+ /** One figure: a single value, or a low to high range for the modelled source. Integer cents. */
51
+ export type PrScope = "ai_assisted" | "all_merged";
52
+ export type CostFigure = {
53
+ /** "measured" is not possible with current data (see header); every figure is an estimate. */
54
+ label: "estimate";
55
+ spend_source: CostSpendSourceName;
56
+ /**
57
+ * Which PRs the average is over. The modelled estimate prices AI-assisted PRs only, so it is split
58
+ * across those only ("ai_assisted"); the usage key covers all spend, so they use "all_merged".
59
+ */
60
+ pr_scope: PrScope;
61
+ /** PRs in that scope. */
62
+ pr_count: number;
63
+ /** Present on anthropic_usage only: the key's usage is the whole organization's, not just these PRs'. */
64
+ spend_scope?: "whole_org";
65
+ } & ({
66
+ value_cents: number;
67
+ } | {
68
+ low_cents: number;
69
+ high_cents: number;
70
+ });
71
+ export interface CostPerPr {
72
+ cost_per_merged_pr?: CostFigure;
73
+ cost_by_pr_size?: Partial<Record<SizeBucket, CostFigure>>;
74
+ }
75
+ export declare const sizeBucket: (lines: number) => SizeBucket;
76
+ /** Inclusive day count of YYYY-MM-DD..YYYY-MM-DD, or null if unparsable or reversed. */
77
+ export declare function periodDays(p: {
78
+ start: string;
79
+ end: string;
80
+ }): number | null;
81
+ /** The period's spend in USD as [low, high]; null when there is no usable spend. */
82
+ export declare function spendForPeriod(spend: CostSpend): [number, number] | null;
83
+ /** The modelled estimate as a spend source, or null when the estimate is "none". */
84
+ export declare const modelledSpend: (e: SpendEstimate) => CostSpend | null;
85
+ /**
86
+ * @param prs every merged PR the scan read, with merge day and size
87
+ * @param exhaustive true only if the scan read EVERY merged PR in the period (no sample, no skipped
88
+ * large PR, none unreadable, no cap hit). Otherwise the average is not defined.
89
+ */
90
+ export declare function buildCostPerPr(prs: readonly PrSize[] | undefined, period: {
91
+ start: string;
92
+ end: string;
93
+ }, spend: CostSpend | null, exhaustive: boolean): CostPerPr;
@@ -0,0 +1,101 @@
1
+ /** Strictly below this is small. 50 is medium. */
2
+ export const SMALL_MAX_EXCLUSIVE = 50;
3
+ /** At or below this (and not small) is medium. 500 is medium; 501 is large. */
4
+ export const MEDIUM_MAX_INCLUSIVE = 500;
5
+ export const sizeBucket = (lines) => lines < SMALL_MAX_EXCLUSIVE ? "small" : lines <= MEDIUM_MAX_INCLUSIVE ? "medium" : "large";
6
+ const DAY_MS = 86_400_000;
7
+ /** Inclusive day count of YYYY-MM-DD..YYYY-MM-DD, or null if unparsable or reversed. */
8
+ export function periodDays(p) {
9
+ const s = Date.parse(`${p.start}T00:00:00Z`);
10
+ const e = Date.parse(`${p.end}T00:00:00Z`);
11
+ if (!Number.isFinite(s) || !Number.isFinite(e) || e < s)
12
+ return null;
13
+ return Math.round((e - s) / DAY_MS) + 1;
14
+ }
15
+ const pos = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
16
+ /** The period's spend in USD as [low, high]; null when there is no usable spend. */
17
+ export function spendForPeriod(spend) {
18
+ let r;
19
+ if (spend.source === "anthropic_usage") {
20
+ if (!pos(spend.usd))
21
+ return null;
22
+ r = [spend.usd, spend.usd];
23
+ }
24
+ else {
25
+ if (!pos(spend.highUsd) || !(spend.lowUsd >= 0) || spend.lowUsd > spend.highUsd)
26
+ return null;
27
+ r = [spend.lowUsd, spend.highUsd];
28
+ }
29
+ return r.every((x) => Number.isFinite(x) && x * 100 <= Number.MAX_SAFE_INTEGER) ? r : null;
30
+ }
31
+ /** The modelled estimate as a spend source, or null when the estimate is "none". */
32
+ export const modelledSpend = (e) => e.kind === "range" ? { source: "modelled_range", lowUsd: e.lowUsd, highUsd: e.highUsd } : null;
33
+ /**
34
+ * `share` is the fraction of the period's spend one average PR here carries: always in (0, 1] by
35
+ * construction, and the spend is already bounded to safe-integer cents by spendForPeriod, so the
36
+ * rounded cents are finite safe integers without a further guard.
37
+ */
38
+ function figure(spend, [low, high], count, share, scope) {
39
+ const c = (usd) => Math.round(usd * share * 100);
40
+ const base = {
41
+ label: "estimate",
42
+ spend_source: spend.source,
43
+ pr_scope: scope,
44
+ pr_count: count,
45
+ ...(spend.source === "anthropic_usage" ? { spend_scope: "whole_org" } : {}),
46
+ };
47
+ return spend.source === "modelled_range"
48
+ ? { ...base, low_cents: c(low), high_cents: c(high) }
49
+ : { ...base, value_cents: c(low) };
50
+ }
51
+ /**
52
+ * @param prs every merged PR the scan read, with merge day and size
53
+ * @param exhaustive true only if the scan read EVERY merged PR in the period (no sample, no skipped
54
+ * large PR, none unreadable, no cap hit). Otherwise the average is not defined.
55
+ */
56
+ export function buildCostPerPr(prs, period, spend, exhaustive) {
57
+ if (!exhaustive || !spend || !Array.isArray(prs))
58
+ return {};
59
+ if (periodDays(period) === null)
60
+ return {};
61
+ const total = spendForPeriod(spend);
62
+ if (!total)
63
+ return {};
64
+ const inPeriod = prs.filter((p) => p.mergedDay >= period.start &&
65
+ p.mergedDay <= period.end &&
66
+ Number.isSafeInteger(p.lines) &&
67
+ p.lines >= 0);
68
+ // The modelled estimate is AI-tool spend, so it is split across AI-assisted PRs only; the usage key is
69
+ // the whole spend, so it is split across every merged PR.
70
+ const scope = spend.source === "modelled_range" ? "ai_assisted" : "all_merged";
71
+ const scoped = scope === "ai_assisted" ? inPeriod.filter((p) => p.aiAssisted) : inPeriod;
72
+ const n = scoped.length;
73
+ if (n === 0)
74
+ return {};
75
+ const out = {};
76
+ out.cost_per_merged_pr = figure(spend, total, n, 1 / n, scope);
77
+ let allLines = 0;
78
+ const agg = {
79
+ small: { n: 0, lines: 0 },
80
+ medium: { n: 0, lines: 0 },
81
+ large: { n: 0, lines: 0 },
82
+ };
83
+ for (const p of scoped) {
84
+ allLines += p.lines;
85
+ const a = agg[sizeBucket(p.lines)];
86
+ a.n += 1;
87
+ a.lines += p.lines;
88
+ }
89
+ // Splitting by lines needs lines: with none (or a sum past safe range) there is no size figure.
90
+ if (allLines <= 0 || !Number.isSafeInteger(allLines))
91
+ return out;
92
+ const bySize = {};
93
+ for (const b of ["small", "medium", "large"]) {
94
+ const a = agg[b];
95
+ if (a.n === 0)
96
+ continue;
97
+ bySize[b] = figure(spend, total, a.n, a.lines / a.n / allLines, scope);
98
+ }
99
+ out.cost_by_pr_size = bySize;
100
+ return out;
101
+ }