pi-spine 2.10.0 → 2.12.0
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/bin/spine.mjs +50 -36
- package/package.json +1 -1
- package/skills/spine-orchestrate-waves/SKILL.md +2 -0
- package/skills/spine-release-operator/SKILL.md +2 -0
- package/src/batch/diagnosis.mjs +3 -3
- package/src/batch/gate-evidence-collect.mjs +6 -0
- package/src/batch/gate-evidence-read.mjs +2 -0
- package/src/batch/metrics-rollup.mjs +119 -0
- package/src/batch/metrics.mjs +6 -1
- package/src/batch/reconcile-diagnosis.mjs +15 -0
- package/src/metrics/quota-cli.mjs +123 -0
- package/src/metrics/quota-html.mjs +465 -0
- package/src/metrics/quota-probes.mjs +312 -0
- package/src/metrics/quota-snapshot.mjs +272 -0
- package/templates/spine-config.json +3 -2
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Optional provider quota probes.
|
|
4
|
+
*
|
|
5
|
+
* Reads API credentials from `~/.pi/agent/auth.json` and attempts to fetch live
|
|
6
|
+
* usage from providers that expose a usage endpoint. All adapters are optional
|
|
7
|
+
* and fail-closed: missing credentials, network errors, and non-ok responses
|
|
8
|
+
* degrade to `source: "absent"` so the caller can fall back to the offline
|
|
9
|
+
* estimate built from run metrics.
|
|
10
|
+
*
|
|
11
|
+
* No remaining percentage is ever invented. A numeric `limit` is only attached
|
|
12
|
+
* to a probe result when the provider response explicitly includes one.
|
|
13
|
+
*
|
|
14
|
+
* Cursor is only probed when the auth file contains an explicit admin key
|
|
15
|
+
* (`type: "admin_key"` or a dedicated `adminKey` field). Regular Cursor API
|
|
16
|
+
* keys are not used and no undocumented dashboard HTML is scraped.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from "node:fs";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import os from "node:os";
|
|
22
|
+
|
|
23
|
+
const DEFAULT_AUTH_PATH = path.join(os.homedir(), ".pi", "agent", "auth.json");
|
|
24
|
+
|
|
25
|
+
const PROBE_URLS = {
|
|
26
|
+
zai: "https://api.z.ai/api/monitor/usage/quota/limit",
|
|
27
|
+
"kimi-coding": "https://api.moonshot.ai/v1/users/me/balance",
|
|
28
|
+
cursor: "https://api.cursor.com/teams/daily-usage-data",
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const PROBE_POOLS = {
|
|
32
|
+
zai: "zai",
|
|
33
|
+
kimiCoding: "kimi-coding",
|
|
34
|
+
cursor: "cursor",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @typedef {object} PoolUsage
|
|
39
|
+
* @property {number} taskCount
|
|
40
|
+
* @property {number} durationMs
|
|
41
|
+
* @property {number} [tokensIn]
|
|
42
|
+
* @property {number} [tokensOut]
|
|
43
|
+
* @property {number} [estimatedUsd]
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {object} ProbeResult
|
|
48
|
+
* @property {string} poolId
|
|
49
|
+
* @property {"live" | "absent"} source
|
|
50
|
+
* @property {PoolUsage} [usage]
|
|
51
|
+
* @property {number} [limit]
|
|
52
|
+
* @property {Error} [error]
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read and parse the pi agent auth file, returning `null` when it is missing
|
|
57
|
+
* or unreadable so callers fail closed.
|
|
58
|
+
*
|
|
59
|
+
* @param {string} [authPath]
|
|
60
|
+
* @returns {object | null}
|
|
61
|
+
*/
|
|
62
|
+
export function loadAuthCredentials(authPath = DEFAULT_AUTH_PATH) {
|
|
63
|
+
try {
|
|
64
|
+
if (!fs.existsSync(authPath)) return null;
|
|
65
|
+
const text = fs.readFileSync(authPath, "utf-8");
|
|
66
|
+
const parsed = JSON.parse(text);
|
|
67
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
68
|
+
return parsed;
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Return the API key for a provider, or `undefined` when the credential is
|
|
76
|
+
* missing or malformed.
|
|
77
|
+
*
|
|
78
|
+
* @param {object | null} auth
|
|
79
|
+
* @param {string} poolId
|
|
80
|
+
* @returns {string | undefined}
|
|
81
|
+
*/
|
|
82
|
+
function getProviderKey(auth, poolId) {
|
|
83
|
+
const entry = auth?.[poolId];
|
|
84
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
85
|
+
if (typeof entry.key === "string" && entry.key.length > 0) return entry.key;
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* True when the auth file contains an explicit Cursor admin key.
|
|
91
|
+
*
|
|
92
|
+
* @param {object | null} auth
|
|
93
|
+
* @returns {boolean}
|
|
94
|
+
*/
|
|
95
|
+
function hasCursorAdminKey(auth) {
|
|
96
|
+
const entry = auth?.cursor;
|
|
97
|
+
if (!entry || typeof entry !== "object") return false;
|
|
98
|
+
if (entry.type === "admin_key" && typeof entry.key === "string" && entry.key.length > 0) {
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
if (typeof entry.adminKey === "string" && entry.adminKey.length > 0) return true;
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Make a JSON GET request with a Bearer token, returning `null` on any failure
|
|
107
|
+
* so adapters remain fail-closed.
|
|
108
|
+
*
|
|
109
|
+
* @param {string} url
|
|
110
|
+
* @param {string} key
|
|
111
|
+
* @param {typeof globalThis.fetch} fetch
|
|
112
|
+
* @returns {Promise<object | null>}
|
|
113
|
+
*/
|
|
114
|
+
async function fetchJsonWithBearer(url, key, fetch) {
|
|
115
|
+
const response = await fetch(url, {
|
|
116
|
+
method: "GET",
|
|
117
|
+
headers: {
|
|
118
|
+
Authorization: `Bearer ${key}`,
|
|
119
|
+
Accept: "application/json",
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
if (!response.ok) return null;
|
|
123
|
+
const text = await response.text();
|
|
124
|
+
if (!text) return null;
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(text);
|
|
127
|
+
} catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Extract a numeric limit from a provider response when it is explicitly
|
|
134
|
+
* present; otherwise return `undefined` so the snapshot does not invent one.
|
|
135
|
+
*
|
|
136
|
+
* @param {object | null} data
|
|
137
|
+
* @param {string[]} fields
|
|
138
|
+
* @returns {number | undefined}
|
|
139
|
+
*/
|
|
140
|
+
function extractLimit(data, fields) {
|
|
141
|
+
if (!data || typeof data !== "object") return undefined;
|
|
142
|
+
for (const field of fields) {
|
|
143
|
+
const value = data[field];
|
|
144
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
145
|
+
}
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Extract a numeric usage value from a provider response when it is explicitly
|
|
151
|
+
* present; otherwise return `undefined`.
|
|
152
|
+
*
|
|
153
|
+
* @param {object | null} data
|
|
154
|
+
* @param {string[]} fields
|
|
155
|
+
* @returns {number | undefined}
|
|
156
|
+
*/
|
|
157
|
+
function extractNumber(data, fields) {
|
|
158
|
+
if (!data || typeof data !== "object") return undefined;
|
|
159
|
+
for (const field of fields) {
|
|
160
|
+
const value = data[field];
|
|
161
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
162
|
+
}
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Z.ai probe — uses the bearer key from `auth.json` to request the quota
|
|
168
|
+
* monitor endpoint.
|
|
169
|
+
*
|
|
170
|
+
* Expected shape (used by mocked tests): `{ used: number, total: number }`.
|
|
171
|
+
*
|
|
172
|
+
* @param {object | null} auth
|
|
173
|
+
* @param {typeof globalThis.fetch} fetch
|
|
174
|
+
* @returns {Promise<ProbeResult>}
|
|
175
|
+
*/
|
|
176
|
+
async function probeZai(auth, fetch) {
|
|
177
|
+
const key = getProviderKey(auth, "zai");
|
|
178
|
+
if (!key) return { poolId: "zai", source: "absent" };
|
|
179
|
+
|
|
180
|
+
try {
|
|
181
|
+
const data = await fetchJsonWithBearer(PROBE_URLS.zai, key, fetch);
|
|
182
|
+
if (!data) return { poolId: "zai", source: "absent" };
|
|
183
|
+
|
|
184
|
+
/** @type {PoolUsage} */
|
|
185
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
186
|
+
const used = extractNumber(data, ["used", "used_tokens", "usage"])
|
|
187
|
+
?? extractNumber(data.data, ["used", "used_tokens", "usage"]);
|
|
188
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
189
|
+
|
|
190
|
+
const limit =
|
|
191
|
+
extractLimit(data, ["total", "total_tokens", "limit"]) ??
|
|
192
|
+
extractLimit(data.data, ["total", "total_tokens", "limit"]);
|
|
193
|
+
|
|
194
|
+
const result = { poolId: "zai", source: "live", usage };
|
|
195
|
+
if (limit !== undefined) result.limit = limit;
|
|
196
|
+
return result;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
return { poolId: "zai", source: "absent", error };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Kimi (Moonshot) probe — uses the bearer key from `auth.json` to request the
|
|
204
|
+
* balance endpoint.
|
|
205
|
+
*
|
|
206
|
+
* Expected shape (used by mocked tests): `{ used: number, total: number }`.
|
|
207
|
+
*
|
|
208
|
+
* @param {object | null} auth
|
|
209
|
+
* @param {typeof globalThis.fetch} fetch
|
|
210
|
+
* @returns {Promise<ProbeResult>}
|
|
211
|
+
*/
|
|
212
|
+
async function probeKimi(auth, fetch) {
|
|
213
|
+
const key = getProviderKey(auth, "kimi-coding");
|
|
214
|
+
if (!key) return { poolId: "kimi-coding", source: "absent" };
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
const data = await fetchJsonWithBearer(PROBE_URLS["kimi-coding"], key, fetch);
|
|
218
|
+
if (!data) return { poolId: "kimi-coding", source: "absent" };
|
|
219
|
+
|
|
220
|
+
/** @type {PoolUsage} */
|
|
221
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
222
|
+
const used = extractNumber(data, ["used", "used_tokens"])
|
|
223
|
+
?? extractNumber(data.data, ["used", "used_tokens"]);
|
|
224
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
225
|
+
|
|
226
|
+
const balance =
|
|
227
|
+
extractNumber(data, ["balance", "cash"]) ??
|
|
228
|
+
extractNumber(data.data, ["balance", "cash"]);
|
|
229
|
+
if (balance !== undefined) usage.estimatedUsd = balance;
|
|
230
|
+
|
|
231
|
+
const limit =
|
|
232
|
+
extractLimit(data, ["total", "total_tokens", "limit"]) ??
|
|
233
|
+
extractLimit(data.data, ["total", "total_tokens", "limit"]);
|
|
234
|
+
|
|
235
|
+
const result = { poolId: "kimi-coding", source: "live", usage };
|
|
236
|
+
if (limit !== undefined) result.limit = limit;
|
|
237
|
+
return result;
|
|
238
|
+
} catch (error) {
|
|
239
|
+
return { poolId: "kimi-coding", source: "absent", error };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Cursor probe — only runs when an explicit admin key is present in
|
|
245
|
+
* `auth.json`. Regular Cursor keys are not used and no dashboard HTML is
|
|
246
|
+
* scraped.
|
|
247
|
+
*
|
|
248
|
+
* Expected shape (used by mocked tests): `{ used_tokens: number }` or
|
|
249
|
+
* `{ total_tokens: number }`.
|
|
250
|
+
*
|
|
251
|
+
* @param {object | null} auth
|
|
252
|
+
* @param {typeof globalThis.fetch} fetch
|
|
253
|
+
* @returns {Promise<ProbeResult>}
|
|
254
|
+
*/
|
|
255
|
+
async function probeCursor(auth, fetch) {
|
|
256
|
+
if (!hasCursorAdminKey(auth)) {
|
|
257
|
+
return { poolId: "cursor", source: "absent" };
|
|
258
|
+
}
|
|
259
|
+
const key = auth.cursor.type === "admin_key" ? auth.cursor.key : auth.cursor.adminKey;
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
const data = await fetchJsonWithBearer(PROBE_URLS.cursor, key, fetch);
|
|
263
|
+
if (!data) return { poolId: "cursor", source: "absent" };
|
|
264
|
+
|
|
265
|
+
/** @type {PoolUsage} */
|
|
266
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
267
|
+
const used = extractNumber(data, ["used_tokens", "total_tokens", "usage"])
|
|
268
|
+
?? extractNumber(data.data, ["used_tokens", "total_tokens", "usage"]);
|
|
269
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
270
|
+
|
|
271
|
+
const limit =
|
|
272
|
+
extractLimit(data, ["total_tokens", "limit"]) ??
|
|
273
|
+
extractLimit(data.data, ["total_tokens", "limit"]);
|
|
274
|
+
|
|
275
|
+
const result = { poolId: "cursor", source: "live", usage };
|
|
276
|
+
if (limit !== undefined) result.limit = limit;
|
|
277
|
+
return result;
|
|
278
|
+
} catch (error) {
|
|
279
|
+
return { poolId: "cursor", source: "absent", error };
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Run the optional provider probes and return a map keyed by pool id.
|
|
285
|
+
*
|
|
286
|
+
* @param {object} [params]
|
|
287
|
+
* @param {string} [params.authPath]
|
|
288
|
+
* @param {typeof globalThis.fetch} [params.fetch]
|
|
289
|
+
* @param {string[]} [params.providers]
|
|
290
|
+
* @returns {Promise<Record<string, ProbeResult>>}
|
|
291
|
+
*/
|
|
292
|
+
export async function runQuotaProbes({
|
|
293
|
+
authPath = DEFAULT_AUTH_PATH,
|
|
294
|
+
fetch = globalThis.fetch,
|
|
295
|
+
providers = [PROBE_POOLS.zai, PROBE_POOLS.kimiCoding, PROBE_POOLS.cursor],
|
|
296
|
+
} = {}) {
|
|
297
|
+
const auth = loadAuthCredentials(authPath);
|
|
298
|
+
/** @type {Record<string, ProbeResult>} */
|
|
299
|
+
const results = {};
|
|
300
|
+
|
|
301
|
+
for (const provider of providers) {
|
|
302
|
+
if (provider === PROBE_POOLS.zai) {
|
|
303
|
+
results.zai = await probeZai(auth, fetch);
|
|
304
|
+
} else if (provider === PROBE_POOLS.kimiCoding) {
|
|
305
|
+
results["kimi-coding"] = await probeKimi(auth, fetch);
|
|
306
|
+
} else if (provider === PROBE_POOLS.cursor) {
|
|
307
|
+
results.cursor = await probeCursor(auth, fetch);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return results;
|
|
312
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Privacy-safe quota/headroom snapshot builder.
|
|
4
|
+
*
|
|
5
|
+
* Joins the expected role→model mapping from `spine-config.json` with observed
|
|
6
|
+
* burn from `.spine/run-metrics.jsonl`. Provider prefixes are mapped to shared
|
|
7
|
+
* quota pools. Usage is aggregated from task metric records, preferring
|
|
8
|
+
* explicit usage fields (`tokensIn`, `tokensOut`, `estimatedUsd`) when present and
|
|
9
|
+
* falling back to duration-based attribution when they are absent.
|
|
10
|
+
*
|
|
11
|
+
* Optional live provider probe results (SP-681) are merged in when supplied.
|
|
12
|
+
* Snapshots produced by this module report:
|
|
13
|
+
*
|
|
14
|
+
* - `source: "live"` when a probe successfully enriched the pool,
|
|
15
|
+
* - `source: "estimate"` when observed metrics exist but no live probe is present,
|
|
16
|
+
* - `source: "absent"` when a pool has no observed burn and no live probe.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { metricsFilePath, readMetricsLines } from "../batch/metrics.mjs";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Known provider prefixes that map to shared quota pools.
|
|
23
|
+
*
|
|
24
|
+
* The prefix is the segment before the first `/` in a model identifier. The
|
|
25
|
+
* mapping is intentionally simple: all models under the same provider share a
|
|
26
|
+
* pool because provider-level quotas (e.g. Z.ai, Google, Kimi) are typically
|
|
27
|
+
* account- or key-wide, not model-wide.
|
|
28
|
+
*/
|
|
29
|
+
const POOL_PREFIXES = new Set(["zai", "kimi-coding", "google", "cursor"]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Resolves a model identifier to a shared quota pool id.
|
|
33
|
+
*
|
|
34
|
+
* @param {string} [model]
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function resolvePoolId(model) {
|
|
38
|
+
if (typeof model !== "string" || !model.trim()) return "unknown";
|
|
39
|
+
if (model === "inherit") return "unknown";
|
|
40
|
+
|
|
41
|
+
const [provider] = model.split("/");
|
|
42
|
+
if (provider && POOL_PREFIXES.has(provider)) return provider;
|
|
43
|
+
if (provider) return "unknown";
|
|
44
|
+
|
|
45
|
+
// Cursor Admin/Enterprise quotas are not keyed by model name, so we keep a
|
|
46
|
+
// dedicated cursor pool even when no model slug is present.
|
|
47
|
+
if (model.toLowerCase().startsWith("cursor")) return "cursor";
|
|
48
|
+
|
|
49
|
+
return "unknown";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Extract agent model identifiers from a shallow agent config object (worker,
|
|
54
|
+
* reviewer and its sub-phases, supervisor). Nested profiles are handled by the
|
|
55
|
+
* caller.
|
|
56
|
+
*
|
|
57
|
+
* @param {object} agents
|
|
58
|
+
* @param {Set<string>} models
|
|
59
|
+
*/
|
|
60
|
+
function collectAgentModels(agents, models) {
|
|
61
|
+
if (!agents || typeof agents !== "object") return;
|
|
62
|
+
if (typeof agents.worker?.model === "string") models.add(agents.worker.model);
|
|
63
|
+
if (typeof agents.reviewer?.model === "string") models.add(agents.reviewer.model);
|
|
64
|
+
if (typeof agents.reviewer?.plan?.model === "string") models.add(agents.reviewer.plan.model);
|
|
65
|
+
if (typeof agents.reviewer?.code?.model === "string") models.add(agents.reviewer.code.model);
|
|
66
|
+
if (typeof agents.reviewer?.final?.model === "string") models.add(agents.reviewer.final.model);
|
|
67
|
+
if (typeof agents.supervisor?.model === "string") models.add(agents.supervisor.model);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Extract all expected model identifiers from the spine config, including the
|
|
72
|
+
* active profile if one is configured. Profiles that are not active are ignored
|
|
73
|
+
* so the snapshot reflects the configured runtime, not every possible profile.
|
|
74
|
+
*
|
|
75
|
+
* @param {object} config
|
|
76
|
+
* @returns {string[]}
|
|
77
|
+
*/
|
|
78
|
+
export function collectExpectedModels(config) {
|
|
79
|
+
const models = new Set();
|
|
80
|
+
const agents = config?.agents;
|
|
81
|
+
if (!agents || typeof agents !== "object") return [];
|
|
82
|
+
|
|
83
|
+
collectAgentModels(agents, models);
|
|
84
|
+
|
|
85
|
+
const activeProfile = typeof agents.activeProfile === "string" ? agents.activeProfile : "";
|
|
86
|
+
if (activeProfile && agents.profiles?.[activeProfile]) {
|
|
87
|
+
collectAgentModels(agents.profiles[activeProfile], models);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return [...models].filter((m) => m && m !== "inherit");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @typedef {object} PoolUsage
|
|
95
|
+
* @property {number} taskCount
|
|
96
|
+
* @property {number} durationMs
|
|
97
|
+
* @property {number} [tokensIn]
|
|
98
|
+
* @property {number} [tokensOut]
|
|
99
|
+
* @property {number} [estimatedUsd]
|
|
100
|
+
*/
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Aggregate usage for a list of task metric records. Fields are omitted when
|
|
104
|
+
* no record in the pool carries them, so callers never receive invented values.
|
|
105
|
+
*
|
|
106
|
+
* @param {object[]} records
|
|
107
|
+
* @returns {PoolUsage}
|
|
108
|
+
*/
|
|
109
|
+
export function aggregatePoolUsage(records) {
|
|
110
|
+
/** @type {PoolUsage} */
|
|
111
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
112
|
+
let tokensIn = 0;
|
|
113
|
+
let tokensOut = 0;
|
|
114
|
+
let estimatedUsd = 0;
|
|
115
|
+
let hasTokensIn = false;
|
|
116
|
+
let hasTokensOut = false;
|
|
117
|
+
let hasEstimatedUsd = false;
|
|
118
|
+
|
|
119
|
+
for (const record of records) {
|
|
120
|
+
if (!record || typeof record !== "object") continue;
|
|
121
|
+
usage.taskCount += 1;
|
|
122
|
+
if (Number.isFinite(record.durationMs)) {
|
|
123
|
+
usage.durationMs += Math.max(0, record.durationMs);
|
|
124
|
+
}
|
|
125
|
+
if (Number.isFinite(record.tokensIn)) {
|
|
126
|
+
tokensIn += Math.max(0, record.tokensIn);
|
|
127
|
+
hasTokensIn = true;
|
|
128
|
+
}
|
|
129
|
+
if (Number.isFinite(record.tokensOut)) {
|
|
130
|
+
tokensOut += Math.max(0, record.tokensOut);
|
|
131
|
+
hasTokensOut = true;
|
|
132
|
+
}
|
|
133
|
+
if (Number.isFinite(record.estimatedUsd)) {
|
|
134
|
+
estimatedUsd += Math.max(0, record.estimatedUsd);
|
|
135
|
+
hasEstimatedUsd = true;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (hasTokensIn) usage.tokensIn = tokensIn;
|
|
140
|
+
if (hasTokensOut) usage.tokensOut = tokensOut;
|
|
141
|
+
if (hasEstimatedUsd) usage.estimatedUsd = estimatedUsd;
|
|
142
|
+
|
|
143
|
+
return usage;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Build a drift report for a single pool from the expected and observed model
|
|
148
|
+
* sets.
|
|
149
|
+
*
|
|
150
|
+
* @param {string[]} expectedModels
|
|
151
|
+
* @param {string[]} observedModels
|
|
152
|
+
*/
|
|
153
|
+
function buildPoolDrift(expectedModels, observedModels) {
|
|
154
|
+
const expectedSet = new Set(expectedModels);
|
|
155
|
+
const observedSet = new Set(observedModels);
|
|
156
|
+
const unexpectedModels = observedModels.filter((m) => !expectedSet.has(m));
|
|
157
|
+
const missingModels = expectedModels.filter((m) => !observedSet.has(m));
|
|
158
|
+
return { unexpectedModels, missingModels };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* @typedef {object} PoolSnapshot
|
|
163
|
+
* @property {string} poolId
|
|
164
|
+
* @property {"live" | "estimate" | "absent"} source
|
|
165
|
+
* @property {string[]} expectedModels
|
|
166
|
+
* @property {string[]} observedModels
|
|
167
|
+
* @property {PoolUsage} usage
|
|
168
|
+
* @property {number} [limit]
|
|
169
|
+
* @property {{unexpectedModels: string[], missingModels: string[]}} drift
|
|
170
|
+
*/
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* @typedef {object} QuotaSnapshot
|
|
174
|
+
* @property {string} generatedAt
|
|
175
|
+
* @property {"live" | "estimate" | "absent"} snapshotSource
|
|
176
|
+
* @property {Record<string, PoolSnapshot>} pools
|
|
177
|
+
*/
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Build a privacy-safe quota snapshot from spine config and run metrics.
|
|
181
|
+
*
|
|
182
|
+
* @param {object} params
|
|
183
|
+
* @param {string} params.projectRoot
|
|
184
|
+
* @param {object} params.config
|
|
185
|
+
* @param {object[]} [params.metricsLines]
|
|
186
|
+
* @param {Record<string, import("./quota-probes.mjs").ProbeResult>} [params.probeResults]
|
|
187
|
+
* @param {number | string | Date} [params.now]
|
|
188
|
+
* @returns {QuotaSnapshot}
|
|
189
|
+
*/
|
|
190
|
+
export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeResults, now = Date.now() }) {
|
|
191
|
+
const resolvedNow = new Date(now).toISOString();
|
|
192
|
+
|
|
193
|
+
let lines = metricsLines;
|
|
194
|
+
if (lines == null) {
|
|
195
|
+
const filePath = metricsFilePath(projectRoot, config);
|
|
196
|
+
lines = readMetricsLines(filePath);
|
|
197
|
+
}
|
|
198
|
+
const taskRecords = (lines ?? []).filter(
|
|
199
|
+
(line) => line && typeof line === "object" && line.recordType === "task",
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
const expectedModels = collectExpectedModels(config);
|
|
203
|
+
const expectedByPool = new Map();
|
|
204
|
+
for (const model of expectedModels) {
|
|
205
|
+
const poolId = resolvePoolId(model);
|
|
206
|
+
if (!expectedByPool.has(poolId)) expectedByPool.set(poolId, new Set());
|
|
207
|
+
expectedByPool.get(poolId).add(model);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const observedByPool = new Map();
|
|
211
|
+
for (const record of taskRecords) {
|
|
212
|
+
const model =
|
|
213
|
+
typeof record.model === "string" && record.model !== "inherit"
|
|
214
|
+
? record.model
|
|
215
|
+
: "inherit";
|
|
216
|
+
const poolId = resolvePoolId(model);
|
|
217
|
+
if (!observedByPool.has(poolId)) observedByPool.set(poolId, { records: [], models: new Set() });
|
|
218
|
+
const entry = observedByPool.get(poolId);
|
|
219
|
+
entry.records.push(record);
|
|
220
|
+
entry.models.add(model);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const poolIds = new Set([...expectedByPool.keys(), ...observedByPool.keys()]);
|
|
224
|
+
let overallHasLive = false;
|
|
225
|
+
let overallHasEstimate = false;
|
|
226
|
+
|
|
227
|
+
const probeByPool = probeResults && typeof probeResults === "object" ? probeResults : {};
|
|
228
|
+
|
|
229
|
+
/** @type {Record<string, PoolSnapshot>} */
|
|
230
|
+
const pools = {};
|
|
231
|
+
for (const poolId of poolIds) {
|
|
232
|
+
const expectedSet = expectedByPool.get(poolId) ?? new Set();
|
|
233
|
+
const observedEntry = observedByPool.get(poolId);
|
|
234
|
+
const observedRecords = observedEntry?.records ?? [];
|
|
235
|
+
const observedSet = observedEntry?.models ?? new Set();
|
|
236
|
+
let source = observedRecords.length > 0 ? "estimate" : "absent";
|
|
237
|
+
|
|
238
|
+
const probe = probeByPool[poolId];
|
|
239
|
+
/** @type {PoolUsage} */
|
|
240
|
+
let usage = aggregatePoolUsage(observedRecords);
|
|
241
|
+
let limit;
|
|
242
|
+
|
|
243
|
+
if (probe?.source === "live") {
|
|
244
|
+
source = "live";
|
|
245
|
+
usage = probe.usage && typeof probe.usage === "object" ? probe.usage : usage;
|
|
246
|
+
if (Number.isFinite(probe.limit) && probe.limit >= 0) limit = probe.limit;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (source === "live") overallHasLive = true;
|
|
250
|
+
if (source === "estimate") overallHasEstimate = true;
|
|
251
|
+
|
|
252
|
+
/** @type {PoolSnapshot} */
|
|
253
|
+
const pool = {
|
|
254
|
+
poolId,
|
|
255
|
+
source,
|
|
256
|
+
expectedModels: [...expectedSet].sort(),
|
|
257
|
+
observedModels: [...observedSet].sort(),
|
|
258
|
+
usage,
|
|
259
|
+
drift: buildPoolDrift([...expectedSet], [...observedSet]),
|
|
260
|
+
};
|
|
261
|
+
if (limit !== undefined) pool.limit = limit;
|
|
262
|
+
pools[poolId] = pool;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const snapshotSource = overallHasLive ? "live" : overallHasEstimate ? "estimate" : "absent";
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
generatedAt: resolvedNow,
|
|
269
|
+
snapshotSource,
|
|
270
|
+
pools,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"testing": {
|
|
12
12
|
"build": "npm run typecheck",
|
|
13
13
|
"test": "npm test",
|
|
14
|
-
"testWithCoverage": "npm run coverage:check"
|
|
14
|
+
"testWithCoverage": "npm run coverage:check",
|
|
15
|
+
"review": ""
|
|
15
16
|
},
|
|
16
17
|
"agents": {
|
|
17
18
|
"worker": { "model": "cursor/auto", "thinking": "high" },
|
|
@@ -81,7 +82,7 @@
|
|
|
81
82
|
"_examples": {
|
|
82
83
|
"worktreeSetupHook": "scripts/spine-worktree-setup-flutter.sh",
|
|
83
84
|
"_worktreeSetupHookNote": "Optional Flutter: symlink gitignored pubspec assets from SPINE_PROJECT_ROOT into lane worktrees — see docs/adoption/flutter-worktree-guide.md",
|
|
84
|
-
"_testingScriptsNote": "testing.build/test/testWithCoverage may use a relative scripts/*.sh path (validated sandbox, no shell metacharacters); e.g. scripts/run-gate-evidence.sh"
|
|
85
|
+
"_testingScriptsNote": "testing.build/test/testWithCoverage/review may use a relative scripts/*.sh path (validated sandbox, no shell metacharacters); e.g. scripts/run-gate-evidence.sh. testing.review is optional and, when set, runs through the same validated executor and is included in the gate evidence bundle."
|
|
85
86
|
},
|
|
86
87
|
"worktreeSetupHook": "",
|
|
87
88
|
"worktreeSetupIgnorePaths": [".venv"],
|