pi-spine 2.12.3 → 2.14.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/package.json +1 -1
- package/skills/spine-release-operator/SKILL.md +15 -2
- package/src/batch/journal-checksum.mjs +84 -0
- package/src/batch/journal.mjs +33 -19
- package/src/batch/review-shared.mjs +7 -0
- package/src/doctor/quota-risk.mjs +229 -0
- package/src/doctor/run-doctor-checks.mjs +18 -0
- package/src/metrics/quota-probes.mjs +171 -9
- package/src/metrics/quota-snapshot.mjs +1 -1
package/package.json
CHANGED
|
@@ -55,6 +55,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
|
|
|
55
55
|
- **Do not** execute tasks outside the approved manifest scope
|
|
56
56
|
- **Never** start Phase 4 (execute) without **recorded scope approval** — the release manifest must show `Operator approved scope: yes` from the Phase 2 gate. Refuse the first wave when approval is missing or `no` (F1, [#249](https://github.com/beettlle/pi-spine/issues/249))
|
|
57
57
|
- **Never** mid-release-edit `.spine/spine-config.json` agent pins (`agents.worker.model` / `agents.reviewer.model`) while a batch is running or integrated work is still unpublished. Pin **one worker** per release; escalate models **only** on content/contract failure — never on quota/403 or launch storms, which make releases worse (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). To override mid-release, first record the reason and date in the release manifest
|
|
58
|
+
- **Heed** the doctor/preflight **quota-risk advisory** ([#251](https://github.com/beettlle/pi-spine/issues/251)): `spine doctor` surfaces `ok: true, warning: true` when escalate/hard worker pins target quota-constrained pools without headroom evidence, or recent run-metrics show launch-storm / quota-abort patterns. It is advisory only — never fails preflight — and does not change the mid-release pin-thrash ban above
|
|
58
59
|
- **Always** push/sync `main` to `origin` after each land loop once the post-integrate regression gate is green — do not let `main` drift far ahead of `origin` during a release (F8, [#249](https://github.com/beettlle/pi-spine/issues/249))
|
|
59
60
|
- **Do not** start a second batch while another batch is **running** on this repo
|
|
60
61
|
- **Never** background `spine batch resume --attached` or `resume --attached --force` ([#163](https://github.com/beettlle/pi-spine/issues/163))
|
|
@@ -435,13 +436,25 @@ COMMIT=$(git rev-parse HEAD)
|
|
|
435
436
|
gh run list --workflow ci.yml --commit "$COMMIT" --json databaseId,conclusion,status --limit 5
|
|
436
437
|
```
|
|
437
438
|
|
|
438
|
-
**Fail closed** when no run has `conclusion: success`.
|
|
439
|
+
**Fail closed** when no run has `conclusion: success`. **Cancelled or absent CI is no signal** — neither green nor red (post-mortem v2.12.3 F-C). Branch by run state:
|
|
440
|
+
|
|
441
|
+
- **`in_progress` / `queued`:** wait:
|
|
442
|
+
|
|
443
|
+
```bash
|
|
444
|
+
gh run watch --exit-status <run-id>
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
- **`cancelled` or no run exists for `HEAD`:** re-run **CI** via `workflow_dispatch` (trigger added in `edb7919d`), then wait for `conclusion: success` on current `HEAD`:
|
|
439
448
|
|
|
440
449
|
```bash
|
|
450
|
+
gh workflow run ci.yml
|
|
451
|
+
gh run list --workflow ci.yml --commit "$COMMIT" --json databaseId,conclusion,status --limit 5
|
|
441
452
|
gh run watch --exit-status <run-id>
|
|
442
453
|
```
|
|
443
454
|
|
|
444
|
-
|
|
455
|
+
Never treat a cancelled run as green or as a reason to skip this gate.
|
|
456
|
+
|
|
457
|
+
If CI **failed**, **STOP** — fix CI on `main`, re-run Phase 5, then re-attempt this gate. Do not `npm version` or `git push --tags` until a green CI run exists on `HEAD`.
|
|
445
458
|
|
|
446
459
|
Only after Phase 5 **and** pre-tag CI gate pass:
|
|
447
460
|
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Journal event checksums and bounded jsonl append (extracted from journal.mjs
|
|
3
|
+
* so the facade stays under the Phase 23 500 LOC cap).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
/** Bounded retry policy for transient append failures (EBUSY/ENOENT). */
|
|
11
|
+
const APPEND_RETRY_ATTEMPTS = 3;
|
|
12
|
+
const APPEND_RETRY_DELAY_MS = 25;
|
|
13
|
+
const RETRYABLE_APPEND_CODES = new Set(["EBUSY", "ENOENT"]);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Synchronous sleep for retry backoff. Atomics.wait is permitted on the Node
|
|
17
|
+
* main thread (unlike browsers), so this works in the sync append path.
|
|
18
|
+
* @param {number} ms
|
|
19
|
+
*/
|
|
20
|
+
function sleepSync(ms) {
|
|
21
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* SHA-256 integrity checksum for new journal events. Computed over the
|
|
26
|
+
* canonical JSON of the entry without the checksum field; the field is
|
|
27
|
+
* appended last so JSON.parse preserves key order and readers can recompute
|
|
28
|
+
* by stripping `checksum` and re-stringifying. Legacy lines without the
|
|
29
|
+
* field remain valid.
|
|
30
|
+
* @param {Record<string, unknown>} entry Entry without a checksum field.
|
|
31
|
+
* @returns {string} Hex digest.
|
|
32
|
+
*/
|
|
33
|
+
export function computeJournalChecksum(entry) {
|
|
34
|
+
return crypto.createHash("sha256").update(JSON.stringify(entry), "utf-8").digest("hex");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Verify a parsed journal line's checksum when present.
|
|
39
|
+
* @param {Record<string, unknown>} event
|
|
40
|
+
* @returns {boolean} True when checksum is absent (legacy) or matches.
|
|
41
|
+
*/
|
|
42
|
+
export function verifyJournalChecksum(event) {
|
|
43
|
+
if (!event || typeof event !== "object") return false;
|
|
44
|
+
const { checksum, ...rest } = event;
|
|
45
|
+
if (typeof checksum !== "string" || !checksum) return true;
|
|
46
|
+
return computeJournalChecksum(rest) === checksum;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Append one jsonl line with fsync and bounded EBUSY/ENOENT retry.
|
|
51
|
+
* Does not rewrite the journal file. In-process callers remain serialized
|
|
52
|
+
* because this function is fully synchronous.
|
|
53
|
+
* @param {string} filePath
|
|
54
|
+
* @param {string} line
|
|
55
|
+
*/
|
|
56
|
+
export function appendJsonlLineSync(filePath, line) {
|
|
57
|
+
let lastError;
|
|
58
|
+
let appended = false;
|
|
59
|
+
for (let attempt = 1; attempt <= APPEND_RETRY_ATTEMPTS; attempt += 1) {
|
|
60
|
+
try {
|
|
61
|
+
if (!appended) {
|
|
62
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
63
|
+
fs.appendFileSync(filePath, line, "utf-8");
|
|
64
|
+
appended = true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const fd = fs.openSync(filePath, "r+");
|
|
68
|
+
try {
|
|
69
|
+
fs.fsyncSync(fd);
|
|
70
|
+
} finally {
|
|
71
|
+
fs.closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
return;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
lastError = error;
|
|
76
|
+
const code = error && /** @type {NodeJS.ErrnoException} */ (error).code;
|
|
77
|
+
if (typeof code !== "string" || !RETRYABLE_APPEND_CODES.has(code) || attempt === APPEND_RETRY_ATTEMPTS) {
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
sleepSync(APPEND_RETRY_DELAY_MS);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
throw lastError;
|
|
84
|
+
}
|
package/src/batch/journal.mjs
CHANGED
|
@@ -6,6 +6,13 @@
|
|
|
6
6
|
import crypto from "node:crypto";
|
|
7
7
|
import fs from "node:fs";
|
|
8
8
|
import path from "node:path";
|
|
9
|
+
import {
|
|
10
|
+
appendJsonlLineSync,
|
|
11
|
+
computeJournalChecksum,
|
|
12
|
+
verifyJournalChecksum,
|
|
13
|
+
} from "./journal-checksum.mjs";
|
|
14
|
+
|
|
15
|
+
export { verifyJournalChecksum };
|
|
9
16
|
|
|
10
17
|
export const JOURNAL_SCHEMA_VERSION = 1;
|
|
11
18
|
export const MAX_PAYLOAD_BYTES = 32 * 1024;
|
|
@@ -169,7 +176,6 @@ export function normalizeJournalEvent(line) {
|
|
|
169
176
|
*/
|
|
170
177
|
export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
|
|
171
178
|
const filePath = journalPath(projectRoot, batchId);
|
|
172
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
173
179
|
|
|
174
180
|
const rawPayload = extractPayload(options);
|
|
175
181
|
const payload = capPayloadSize(redactSecrets(rawPayload));
|
|
@@ -194,16 +200,16 @@ export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
|
|
|
194
200
|
const taskId = options.taskId;
|
|
195
201
|
if (typeof taskId === "string" && taskId) entry.taskId = taskId;
|
|
196
202
|
|
|
197
|
-
|
|
198
|
-
|
|
203
|
+
// checksum: SHA-256 hex of the canonical JSON of the entry without this
|
|
204
|
+
// field. Added last so readers recompute by stripping `checksum` and
|
|
205
|
+
// re-stringifying; absent on legacy lines.
|
|
206
|
+
entry.checksum = computeJournalChecksum(entry);
|
|
199
207
|
|
|
200
|
-
const
|
|
201
|
-
try {
|
|
202
|
-
fs.fsyncSync(fd);
|
|
203
|
-
} finally {
|
|
204
|
-
fs.closeSync(fd);
|
|
205
|
-
}
|
|
208
|
+
const line = `${JSON.stringify(entry)}\n`;
|
|
206
209
|
|
|
210
|
+
// In-process serialization: appendJsonlLineSync is fully synchronous, so
|
|
211
|
+
// concurrent event-loop callers cannot interleave partial jsonl lines.
|
|
212
|
+
appendJsonlLineSync(filePath, line);
|
|
207
213
|
return entry;
|
|
208
214
|
}
|
|
209
215
|
|
|
@@ -227,6 +233,22 @@ export function exportJournalJsonl(projectRoot, batchId) {
|
|
|
227
233
|
return fs.readFileSync(filePath, "utf-8");
|
|
228
234
|
}
|
|
229
235
|
|
|
236
|
+
/**
|
|
237
|
+
* Parse jsonl journal content into normalized events. Lines whose checksum is
|
|
238
|
+
* present but mismatches are skipped (fail-closed per-line) without
|
|
239
|
+
* discarding the rest of the file; legacy lines without checksum load as-is.
|
|
240
|
+
* @param {string} content Raw jsonl content.
|
|
241
|
+
* @returns {object[]}
|
|
242
|
+
*/
|
|
243
|
+
function parseJournalLines(content) {
|
|
244
|
+
return content
|
|
245
|
+
.split("\n")
|
|
246
|
+
.filter(Boolean)
|
|
247
|
+
.map((line) => JSON.parse(line))
|
|
248
|
+
.filter((parsed) => verifyJournalChecksum(parsed))
|
|
249
|
+
.map((parsed) => normalizeJournalEvent(parsed));
|
|
250
|
+
}
|
|
251
|
+
|
|
230
252
|
/**
|
|
231
253
|
* @param {string} projectRoot
|
|
232
254
|
* @param {string} batchId
|
|
@@ -236,11 +258,7 @@ export function readJournalEvents(projectRoot, batchId) {
|
|
|
236
258
|
const filePath = journalPath(projectRoot, batchId);
|
|
237
259
|
if (!fs.existsSync(filePath)) return [];
|
|
238
260
|
|
|
239
|
-
return fs
|
|
240
|
-
.readFileSync(filePath, "utf-8")
|
|
241
|
-
.split("\n")
|
|
242
|
-
.filter(Boolean)
|
|
243
|
-
.map((line) => normalizeJournalEvent(JSON.parse(line)));
|
|
261
|
+
return parseJournalLines(fs.readFileSync(filePath, "utf-8"));
|
|
244
262
|
}
|
|
245
263
|
|
|
246
264
|
/**
|
|
@@ -273,11 +291,7 @@ export function readJournalEventsCached(projectRoot, batchId) {
|
|
|
273
291
|
return _journalCache.events;
|
|
274
292
|
}
|
|
275
293
|
|
|
276
|
-
const events = fs
|
|
277
|
-
.readFileSync(filePath, "utf-8")
|
|
278
|
-
.split("\n")
|
|
279
|
-
.filter(Boolean)
|
|
280
|
-
.map((line) => normalizeJournalEvent(JSON.parse(line)));
|
|
294
|
+
const events = parseJournalLines(fs.readFileSync(filePath, "utf-8"));
|
|
281
295
|
|
|
282
296
|
_journalCache.filePath = filePath;
|
|
283
297
|
_journalCache.mtimeMs = stat.mtimeMs;
|
|
@@ -98,6 +98,9 @@ function extractSummary(reviewContent) {
|
|
|
98
98
|
export function parseReviewVerdict(reviewContent, options = {}) {
|
|
99
99
|
const reviewType = options.reviewType ?? "code";
|
|
100
100
|
const isFinal = reviewType === "final";
|
|
101
|
+
// A json fence signals structured-output intent; if it cannot yield a valid
|
|
102
|
+
// verdict, fail closed instead of salvaging a verdict from prose heuristics.
|
|
103
|
+
const hasJsonFence = /```json/i.test(reviewContent);
|
|
101
104
|
|
|
102
105
|
const jsonMatch = reviewContent.match(/```json\s*\n([\s\S]*?)\n```/i);
|
|
103
106
|
if (jsonMatch) {
|
|
@@ -126,6 +129,10 @@ export function parseReviewVerdict(reviewContent, options = {}) {
|
|
|
126
129
|
};
|
|
127
130
|
}
|
|
128
131
|
|
|
132
|
+
if (hasJsonFence) {
|
|
133
|
+
return { verdict: null, feedback: extractSummary(reviewContent) };
|
|
134
|
+
}
|
|
135
|
+
|
|
129
136
|
const lower = reviewContent.toLowerCase();
|
|
130
137
|
if (
|
|
131
138
|
lower.includes("changes requested") ||
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Quota-risk advisory doctor check (GitHub #251, SP-700).
|
|
4
|
+
*
|
|
5
|
+
* Warns when worker pins that matter for escalation (base worker, active
|
|
6
|
+
* profile worker, or the `escalatePolicy.toProfile` target worker) point at
|
|
7
|
+
* known quota-constrained provider pools without live/estimate headroom
|
|
8
|
+
* evidence. Optionally surfaces recent launch-storm / quota-abort patterns
|
|
9
|
+
* from run-metrics when metrics lines are supplied.
|
|
10
|
+
*
|
|
11
|
+
* This check is advisory only: it always returns `ok: true` (with
|
|
12
|
+
* `warning: true` when risk is detected) so doctor/preflight stay
|
|
13
|
+
* non-blocking. Live probes are never run from doctor — probe results are an
|
|
14
|
+
* injectable input; when probes/auth are absent the check degrades closed
|
|
15
|
+
* (warns) instead of claiming headroom it cannot prove.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
19
|
+
|
|
20
|
+
/** Default window for launch-storm / quota-abort signal detection. */
|
|
21
|
+
const DEFAULT_SIGNAL_WINDOW_MS = 60 * 60 * 1000;
|
|
22
|
+
/** Failed tasks under this duration count toward a launch storm. */
|
|
23
|
+
const LAUNCH_STORM_MAX_DURATION_MS = 5 * 60 * 1000;
|
|
24
|
+
/** Minimum failed short tasks inside the window to flag a launch storm. */
|
|
25
|
+
const LAUNCH_STORM_MIN_FAILURES = 3;
|
|
26
|
+
|
|
27
|
+
export const QUOTA_RISK_CHECK_LABEL = "quota risk: escalate/hard worker pins (#251)";
|
|
28
|
+
export const QUOTA_RISK_SUGGESTED_COMMAND = "spine metrics quota";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {object} QuotaPinTarget
|
|
32
|
+
* @property {string} model
|
|
33
|
+
* @property {string} poolId
|
|
34
|
+
* @property {string} source Human-readable origin of the pin.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Collect worker model pins that matter for escalation risk: the base
|
|
39
|
+
* worker pin, the active-profile worker pin, and the escalate-policy target
|
|
40
|
+
* profile worker pin. Only pins resolving to a known quota pool are kept.
|
|
41
|
+
*
|
|
42
|
+
* @param {object} [config]
|
|
43
|
+
* @returns {QuotaPinTarget[]}
|
|
44
|
+
*/
|
|
45
|
+
export function collectQuotaPinTargets(config = {}) {
|
|
46
|
+
const agents = config?.agents;
|
|
47
|
+
if (!agents || typeof agents !== "object") return [];
|
|
48
|
+
|
|
49
|
+
/** @type {Array<{ model: unknown, source: string }>} */
|
|
50
|
+
const candidates = [
|
|
51
|
+
{ model: agents.worker?.model, source: "agents.worker.model" },
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
const activeProfile = typeof agents.activeProfile === "string" ? agents.activeProfile.trim() : "";
|
|
55
|
+
if (activeProfile && agents.profiles?.[activeProfile]) {
|
|
56
|
+
candidates.push({
|
|
57
|
+
model: agents.profiles[activeProfile]?.worker?.model,
|
|
58
|
+
source: `agents.profiles.${activeProfile}.worker.model (active profile)`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const escalate = agents.escalatePolicy;
|
|
63
|
+
const escalateTarget =
|
|
64
|
+
escalate && typeof escalate === "object" && escalate.enabled !== false
|
|
65
|
+
? String(escalate.toProfile ?? "").trim()
|
|
66
|
+
: "";
|
|
67
|
+
if (escalateTarget && agents.profiles?.[escalateTarget]) {
|
|
68
|
+
candidates.push({
|
|
69
|
+
model: agents.profiles[escalateTarget]?.worker?.model,
|
|
70
|
+
source: `agents.profiles.${escalateTarget}.worker.model (escalate target)`,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @type {QuotaPinTarget[]} */
|
|
75
|
+
const targets = [];
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
for (const candidate of candidates) {
|
|
78
|
+
if (typeof candidate.model !== "string") continue;
|
|
79
|
+
const model = candidate.model.trim();
|
|
80
|
+
if (!model || model === "inherit") continue;
|
|
81
|
+
const poolId = resolvePoolId(model);
|
|
82
|
+
if (poolId === "unknown") continue;
|
|
83
|
+
const key = `${poolId}::${model}`;
|
|
84
|
+
if (seen.has(key)) continue;
|
|
85
|
+
seen.add(key);
|
|
86
|
+
targets.push({ model, poolId, source: candidate.source });
|
|
87
|
+
}
|
|
88
|
+
return targets;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Evaluate headroom evidence for one pool from an optional probe result.
|
|
93
|
+
* Degrades closed: absent probes/auth mean "no headroom evidence", never an
|
|
94
|
+
* invented remaining percentage.
|
|
95
|
+
*
|
|
96
|
+
* @param {QuotaPinTarget} target
|
|
97
|
+
* @param {import("../metrics/quota-probes.mjs").ProbeResult | undefined} probe
|
|
98
|
+
* @returns {{ hasHeadroom: boolean, reason: string }}
|
|
99
|
+
*/
|
|
100
|
+
function evaluateHeadroom(target, probe) {
|
|
101
|
+
const pin = `${target.source} → ${target.model} (pool: ${target.poolId})`;
|
|
102
|
+
|
|
103
|
+
if (probe?.source === "live") {
|
|
104
|
+
const usage = probe.usage && typeof probe.usage === "object" ? probe.usage : {};
|
|
105
|
+
if (Number.isFinite(probe.limit) && Number.isFinite(usage.tokensOut)) {
|
|
106
|
+
const headroom = probe.limit - usage.tokensOut;
|
|
107
|
+
if (headroom > 0) {
|
|
108
|
+
return { hasHeadroom: true, reason: `${pin} — live probe reports headroom` };
|
|
109
|
+
}
|
|
110
|
+
return { hasHeadroom: false, reason: `${pin} — live probe reports quota exhausted` };
|
|
111
|
+
}
|
|
112
|
+
if (Number.isFinite(usage.estimatedUsd)) {
|
|
113
|
+
if (usage.estimatedUsd > 0) {
|
|
114
|
+
return { hasHeadroom: true, reason: `${pin} — live probe reports positive balance` };
|
|
115
|
+
}
|
|
116
|
+
return { hasHeadroom: false, reason: `${pin} — live probe reports zero/negative balance` };
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
hasHeadroom: true,
|
|
120
|
+
reason: `${pin} — live probe reachable, provider reported no explicit limit`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
hasHeadroom: false,
|
|
126
|
+
reason: `${pin} — quota-constrained pool with no live/estimate headroom evidence (probe/auth absent)`,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Detect recent launch-storm and quota-abort signals in task metric records.
|
|
132
|
+
* Pure heuristic over injected records; nothing is fabricated when fields are
|
|
133
|
+
* missing.
|
|
134
|
+
*
|
|
135
|
+
* @param {object[]} [metricsLines]
|
|
136
|
+
* @param {object} [options]
|
|
137
|
+
* @param {number | string | Date} [options.now]
|
|
138
|
+
* @param {number} [options.windowMs]
|
|
139
|
+
* @returns {string[]}
|
|
140
|
+
*/
|
|
141
|
+
export function detectQuotaRiskSignals(metricsLines, { now = Date.now(), windowMs = DEFAULT_SIGNAL_WINDOW_MS } = {}) {
|
|
142
|
+
if (!Array.isArray(metricsLines) || metricsLines.length === 0) return [];
|
|
143
|
+
|
|
144
|
+
const nowMs = new Date(now).getTime();
|
|
145
|
+
if (!Number.isFinite(nowMs)) return [];
|
|
146
|
+
|
|
147
|
+
const windowStart = nowMs - windowMs;
|
|
148
|
+
const records = metricsLines.filter(
|
|
149
|
+
(line) => line && typeof line === "object" && line.recordType === "task",
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
let shortFailures = 0;
|
|
153
|
+
let quotaAborts = 0;
|
|
154
|
+
for (const record of records) {
|
|
155
|
+
if (record.outcome !== "failed") continue;
|
|
156
|
+
const startedMs = new Date(record.startedAt ?? 0).getTime();
|
|
157
|
+
if (!Number.isFinite(startedMs) || startedMs < windowStart) continue;
|
|
158
|
+
|
|
159
|
+
const haystack = [record.diagnosis, record.failureKind, record.exitReason]
|
|
160
|
+
.filter((value) => typeof value === "string")
|
|
161
|
+
.join(" ")
|
|
162
|
+
.toLowerCase();
|
|
163
|
+
if (haystack.includes("quota") || haystack.includes("rate limit") || haystack.includes("429")) {
|
|
164
|
+
quotaAborts += 1;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (Number.isFinite(record.durationMs) && record.durationMs <= LAUNCH_STORM_MAX_DURATION_MS) {
|
|
168
|
+
shortFailures += 1;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** @type {string[]} */
|
|
173
|
+
const signals = [];
|
|
174
|
+
if (quotaAborts > 0) {
|
|
175
|
+
signals.push(`${quotaAborts} recent quota-abort task failure(s) in run-metrics`);
|
|
176
|
+
}
|
|
177
|
+
if (shortFailures >= LAUNCH_STORM_MIN_FAILURES) {
|
|
178
|
+
signals.push(
|
|
179
|
+
`${shortFailures} short-lived task failure(s) in the last hour — possible launch storm`,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
return signals;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Build the advisory quota-risk doctor check.
|
|
187
|
+
*
|
|
188
|
+
* @param {object} [options]
|
|
189
|
+
* @param {object} [options.config] Resolved spine config.
|
|
190
|
+
* @param {Record<string, import("../metrics/quota-probes.mjs").ProbeResult>} [options.probeResults]
|
|
191
|
+
* Optional live probe results keyed by pool id; doctor never runs probes itself.
|
|
192
|
+
* @param {object[]} [options.metricsLines] Optional parsed run-metrics records.
|
|
193
|
+
* @param {number | string | Date} [options.now]
|
|
194
|
+
* @returns {{ label: string, ok: true, warning?: boolean, detail: string, suggestedCommand?: string }}
|
|
195
|
+
*/
|
|
196
|
+
export function buildQuotaRiskDoctorCheck({ config = {}, probeResults, metricsLines, now } = {}) {
|
|
197
|
+
const targets = collectQuotaPinTargets(config);
|
|
198
|
+
const probes = probeResults && typeof probeResults === "object" ? probeResults : {};
|
|
199
|
+
|
|
200
|
+
/** @type {string[]} */
|
|
201
|
+
const risks = [];
|
|
202
|
+
for (const target of targets) {
|
|
203
|
+
const { hasHeadroom, reason } = evaluateHeadroom(target, probes[target.poolId]);
|
|
204
|
+
if (!hasHeadroom) risks.push(reason);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const signals = detectQuotaRiskSignals(metricsLines, { now });
|
|
208
|
+
risks.push(...signals);
|
|
209
|
+
|
|
210
|
+
if (risks.length === 0) {
|
|
211
|
+
const detail =
|
|
212
|
+
targets.length === 0
|
|
213
|
+
? "no escalate/hard worker pins on quota-constrained pools"
|
|
214
|
+
: `${targets.length} quota-pool pin(s) with headroom evidence`;
|
|
215
|
+
return {
|
|
216
|
+
label: QUOTA_RISK_CHECK_LABEL,
|
|
217
|
+
ok: true,
|
|
218
|
+
detail,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
label: QUOTA_RISK_CHECK_LABEL,
|
|
224
|
+
ok: true,
|
|
225
|
+
warning: true,
|
|
226
|
+
detail: risks.join("; "),
|
|
227
|
+
suggestedCommand: QUOTA_RISK_SUGGESTED_COMMAND,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
@@ -33,6 +33,8 @@ import { buildAgentModelIdsDoctorCheck } from "./agent-models.mjs";
|
|
|
33
33
|
import { buildPiExtensionConflictDoctorCheck } from "./pi-extension-conflict.mjs";
|
|
34
34
|
import { buildSupervisorConfigDoctorCheck } from "./supervisor.mjs";
|
|
35
35
|
import { buildAttachedOrphanRiskDoctorCheck } from "./attached-orphan-risk.mjs";
|
|
36
|
+
import { buildQuotaRiskDoctorCheck } from "./quota-risk.mjs";
|
|
37
|
+
import { metricsFilePath, readMetricsLines } from "../batch/metrics.mjs";
|
|
36
38
|
import {
|
|
37
39
|
buildCheckoutVersionSkewDoctorCheck,
|
|
38
40
|
buildDuplicateInstallDoctorCheck,
|
|
@@ -408,6 +410,22 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
|
|
|
408
410
|
for (const testingCheck of buildTestingEvidenceDoctorChecks(configResult.config)) {
|
|
409
411
|
checks.push(testingCheck);
|
|
410
412
|
}
|
|
413
|
+
let quotaMetricsLines;
|
|
414
|
+
try {
|
|
415
|
+
quotaMetricsLines = readMetricsLines(
|
|
416
|
+
metricsFilePath(projectRoot, configResult.config),
|
|
417
|
+
{ skipInvalid: true },
|
|
418
|
+
);
|
|
419
|
+
} catch {
|
|
420
|
+
// Unreadable metrics degrade to pin-only evaluation; the check still warns on absent headroom.
|
|
421
|
+
quotaMetricsLines = undefined;
|
|
422
|
+
}
|
|
423
|
+
checks.push(
|
|
424
|
+
buildQuotaRiskDoctorCheck({
|
|
425
|
+
config: configResult.config,
|
|
426
|
+
metricsLines: quotaMetricsLines,
|
|
427
|
+
}),
|
|
428
|
+
);
|
|
411
429
|
const concurrentDevCheck = buildConcurrentDevDoctorCheck({
|
|
412
430
|
projectRoot,
|
|
413
431
|
config: configResult.config,
|
|
@@ -14,6 +14,12 @@
|
|
|
14
14
|
* Cursor is only probed when the auth file contains an explicit admin key
|
|
15
15
|
* (`type: "admin_key"` or a dedicated `adminKey` field). Regular Cursor API
|
|
16
16
|
* keys are not used and no undocumented dashboard HTML is scraped.
|
|
17
|
+
*
|
|
18
|
+
* Anthropic is only probed with an explicit Admin key (`type: "admin_key"`
|
|
19
|
+
* or a dedicated `adminKey` field). Regular inference keys
|
|
20
|
+
* (`sk-ant-api...`) are never sent to the Admin API. GitHub Copilot is only
|
|
21
|
+
* probed when the auth entry carries a PAT plus an explicit org or enterprise
|
|
22
|
+
* context; user-level entries without that scope degrade to `absent`.
|
|
17
23
|
*/
|
|
18
24
|
|
|
19
25
|
import fs from "node:fs";
|
|
@@ -26,12 +32,17 @@ const PROBE_URLS = {
|
|
|
26
32
|
zai: "https://api.z.ai/api/monitor/usage/quota/limit",
|
|
27
33
|
"kimi-coding": "https://api.moonshot.ai/v1/users/me/balance",
|
|
28
34
|
cursor: "https://api.cursor.com/teams/daily-usage-data",
|
|
35
|
+
anthropic: "https://api.anthropic.com/v1/organizations/usage_report/messages",
|
|
29
36
|
};
|
|
30
37
|
|
|
38
|
+
const GITHUB_API_BASE = "https://api.github.com";
|
|
39
|
+
|
|
31
40
|
export const PROBE_POOLS = {
|
|
32
41
|
zai: "zai",
|
|
33
42
|
kimiCoding: "kimi-coding",
|
|
34
43
|
cursor: "cursor",
|
|
44
|
+
anthropic: "anthropic",
|
|
45
|
+
githubCopilot: "github-copilot",
|
|
35
46
|
};
|
|
36
47
|
|
|
37
48
|
/**
|
|
@@ -103,21 +114,59 @@ function hasCursorAdminKey(auth) {
|
|
|
103
114
|
}
|
|
104
115
|
|
|
105
116
|
/**
|
|
106
|
-
*
|
|
107
|
-
*
|
|
117
|
+
* Return the explicit Anthropic Admin key from the auth file, or `undefined`
|
|
118
|
+
* when only a regular inference key is present. The Admin API rejects
|
|
119
|
+
* inference keys, so they are never used for the probe.
|
|
120
|
+
*
|
|
121
|
+
* @param {object | null} auth
|
|
122
|
+
* @returns {string | undefined}
|
|
123
|
+
*/
|
|
124
|
+
function getAnthropicAdminKey(auth) {
|
|
125
|
+
const entry = auth?.anthropic;
|
|
126
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
127
|
+
if (entry.type === "admin_key" && typeof entry.key === "string" && entry.key.length > 0) {
|
|
128
|
+
return entry.key;
|
|
129
|
+
}
|
|
130
|
+
if (typeof entry.adminKey === "string" && entry.adminKey.length > 0) return entry.adminKey;
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Return the GitHub Copilot billing probe context (PAT plus an explicit org
|
|
136
|
+
* or enterprise scope), or `undefined` when either is missing. The billing
|
|
137
|
+
* endpoints are only exposed at org/enterprise level, so user-level entries
|
|
138
|
+
* without that context fail closed.
|
|
139
|
+
*
|
|
140
|
+
* @param {object | null} auth
|
|
141
|
+
* @returns {{ key: string, url: string } | undefined}
|
|
142
|
+
*/
|
|
143
|
+
function getCopilotBillingContext(auth) {
|
|
144
|
+
const entry = auth?.["github-copilot"];
|
|
145
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
146
|
+
const key = typeof entry.key === "string" && entry.key.length > 0 ? entry.key : undefined;
|
|
147
|
+
if (!key) return undefined;
|
|
148
|
+
if (typeof entry.org === "string" && entry.org.length > 0) {
|
|
149
|
+
return { key, url: `${GITHUB_API_BASE}/orgs/${encodeURIComponent(entry.org)}/copilot/billing` };
|
|
150
|
+
}
|
|
151
|
+
if (typeof entry.enterprise === "string" && entry.enterprise.length > 0) {
|
|
152
|
+
return { key, url: `${GITHUB_API_BASE}/enterprises/${encodeURIComponent(entry.enterprise)}/copilot/billing` };
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Make a JSON GET request with arbitrary headers, returning `null` on any
|
|
159
|
+
* failure so adapters remain fail-closed.
|
|
108
160
|
*
|
|
109
161
|
* @param {string} url
|
|
110
|
-
* @param {string}
|
|
162
|
+
* @param {Record<string, string>} headers
|
|
111
163
|
* @param {typeof globalThis.fetch} fetch
|
|
112
164
|
* @returns {Promise<object | null>}
|
|
113
165
|
*/
|
|
114
|
-
async function
|
|
166
|
+
async function fetchJsonWithHeaders(url, headers, fetch) {
|
|
115
167
|
const response = await fetch(url, {
|
|
116
168
|
method: "GET",
|
|
117
|
-
headers: {
|
|
118
|
-
Authorization: `Bearer ${key}`,
|
|
119
|
-
Accept: "application/json",
|
|
120
|
-
},
|
|
169
|
+
headers: { Accept: "application/json", ...headers },
|
|
121
170
|
});
|
|
122
171
|
if (!response.ok) return null;
|
|
123
172
|
const text = await response.text();
|
|
@@ -129,6 +178,19 @@ async function fetchJsonWithBearer(url, key, fetch) {
|
|
|
129
178
|
}
|
|
130
179
|
}
|
|
131
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Make a JSON GET request with a Bearer token, returning `null` on any failure
|
|
183
|
+
* so adapters remain fail-closed.
|
|
184
|
+
*
|
|
185
|
+
* @param {string} url
|
|
186
|
+
* @param {string} key
|
|
187
|
+
* @param {typeof globalThis.fetch} fetch
|
|
188
|
+
* @returns {Promise<object | null>}
|
|
189
|
+
*/
|
|
190
|
+
async function fetchJsonWithBearer(url, key, fetch) {
|
|
191
|
+
return fetchJsonWithHeaders(url, { Authorization: `Bearer ${key}` }, fetch);
|
|
192
|
+
}
|
|
193
|
+
|
|
132
194
|
/**
|
|
133
195
|
* Extract a numeric limit from a provider response when it is explicitly
|
|
134
196
|
* present; otherwise return `undefined` so the snapshot does not invent one.
|
|
@@ -280,6 +342,96 @@ async function probeCursor(auth, fetch) {
|
|
|
280
342
|
}
|
|
281
343
|
}
|
|
282
344
|
|
|
345
|
+
/**
|
|
346
|
+
* Anthropic probe — only runs when an explicit Admin key is present in
|
|
347
|
+
* `auth.json`. Regular inference keys (`type: "api_key"`, `sk-ant-api...`)
|
|
348
|
+
* are never sent to the Admin API.
|
|
349
|
+
*
|
|
350
|
+
* Expected shape (used by mocked tests): `{ used: number }` or a `data`
|
|
351
|
+
* array whose entries carry `tokens` fields. A numeric limit is only
|
|
352
|
+
* attached when the response explicitly includes one.
|
|
353
|
+
*
|
|
354
|
+
* @param {object | null} auth
|
|
355
|
+
* @param {typeof globalThis.fetch} fetch
|
|
356
|
+
* @returns {Promise<ProbeResult>}
|
|
357
|
+
*/
|
|
358
|
+
async function probeAnthropic(auth, fetch) {
|
|
359
|
+
const key = getAnthropicAdminKey(auth);
|
|
360
|
+
if (!key) return { poolId: "anthropic", source: "absent" };
|
|
361
|
+
|
|
362
|
+
try {
|
|
363
|
+
const data = await fetchJsonWithHeaders(
|
|
364
|
+
PROBE_URLS.anthropic,
|
|
365
|
+
{ "x-api-key": key, "anthropic-version": "2023-06-01" },
|
|
366
|
+
fetch,
|
|
367
|
+
);
|
|
368
|
+
if (!data) return { poolId: "anthropic", source: "absent" };
|
|
369
|
+
|
|
370
|
+
/** @type {PoolUsage} */
|
|
371
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
372
|
+
const used = extractNumber(data, ["used", "used_tokens", "total_tokens"])
|
|
373
|
+
?? extractNumber(data.data, ["used", "used_tokens", "total_tokens"]);
|
|
374
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
375
|
+
|
|
376
|
+
const limit =
|
|
377
|
+
extractLimit(data, ["total", "limit"]) ??
|
|
378
|
+
extractLimit(data.data, ["total", "limit"]);
|
|
379
|
+
|
|
380
|
+
const result = { poolId: "anthropic", source: "live", usage };
|
|
381
|
+
if (limit !== undefined) result.limit = limit;
|
|
382
|
+
return result;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return { poolId: "anthropic", source: "absent", error };
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* GitHub Copilot probe — only runs when the auth entry carries a PAT plus
|
|
390
|
+
* an explicit org or enterprise context. User-level entries without that
|
|
391
|
+
* scope fail closed because the billing endpoints are org/enterprise-only.
|
|
392
|
+
*
|
|
393
|
+
* Expected shape (used by mocked tests): `{ used: number }` or
|
|
394
|
+
* `{ usage: { used: number } }`. Seat-only billing payloads still count as
|
|
395
|
+
* live but contribute no usage numbers. A numeric limit is only attached
|
|
396
|
+
* when the response explicitly includes one.
|
|
397
|
+
*
|
|
398
|
+
* @param {object | null} auth
|
|
399
|
+
* @param {typeof globalThis.fetch} fetch
|
|
400
|
+
* @returns {Promise<ProbeResult>}
|
|
401
|
+
*/
|
|
402
|
+
async function probeGitHubCopilot(auth, fetch) {
|
|
403
|
+
const context = getCopilotBillingContext(auth);
|
|
404
|
+
if (!context) return { poolId: "github-copilot", source: "absent" };
|
|
405
|
+
|
|
406
|
+
try {
|
|
407
|
+
const data = await fetchJsonWithHeaders(
|
|
408
|
+
context.url,
|
|
409
|
+
{
|
|
410
|
+
Authorization: `Bearer ${context.key}`,
|
|
411
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
412
|
+
},
|
|
413
|
+
fetch,
|
|
414
|
+
);
|
|
415
|
+
if (!data) return { poolId: "github-copilot", source: "absent" };
|
|
416
|
+
|
|
417
|
+
/** @type {PoolUsage} */
|
|
418
|
+
const usage = { taskCount: 0, durationMs: 0 };
|
|
419
|
+
// Seat counts are deliberately not mapped into taskCount: seats are not
|
|
420
|
+
// tasks and conflating them would invent usage the API never reported.
|
|
421
|
+
const used = extractNumber(data, ["used", "used_premium_requests", "total_used"])
|
|
422
|
+
?? extractNumber(data.usage, ["used", "total"]);
|
|
423
|
+
if (used !== undefined) usage.tokensOut = used;
|
|
424
|
+
|
|
425
|
+
const limit = extractLimit(data, ["limit", "seat_limit"]);
|
|
426
|
+
|
|
427
|
+
const result = { poolId: "github-copilot", source: "live", usage };
|
|
428
|
+
if (limit !== undefined) result.limit = limit;
|
|
429
|
+
return result;
|
|
430
|
+
} catch (error) {
|
|
431
|
+
return { poolId: "github-copilot", source: "absent", error };
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
283
435
|
/**
|
|
284
436
|
* Run the optional provider probes and return a map keyed by pool id.
|
|
285
437
|
*
|
|
@@ -292,7 +444,13 @@ async function probeCursor(auth, fetch) {
|
|
|
292
444
|
export async function runQuotaProbes({
|
|
293
445
|
authPath = DEFAULT_AUTH_PATH,
|
|
294
446
|
fetch = globalThis.fetch,
|
|
295
|
-
providers = [
|
|
447
|
+
providers = [
|
|
448
|
+
PROBE_POOLS.zai,
|
|
449
|
+
PROBE_POOLS.kimiCoding,
|
|
450
|
+
PROBE_POOLS.cursor,
|
|
451
|
+
PROBE_POOLS.anthropic,
|
|
452
|
+
PROBE_POOLS.githubCopilot,
|
|
453
|
+
],
|
|
296
454
|
} = {}) {
|
|
297
455
|
const auth = loadAuthCredentials(authPath);
|
|
298
456
|
/** @type {Record<string, ProbeResult>} */
|
|
@@ -305,6 +463,10 @@ export async function runQuotaProbes({
|
|
|
305
463
|
results["kimi-coding"] = await probeKimi(auth, fetch);
|
|
306
464
|
} else if (provider === PROBE_POOLS.cursor) {
|
|
307
465
|
results.cursor = await probeCursor(auth, fetch);
|
|
466
|
+
} else if (provider === PROBE_POOLS.anthropic) {
|
|
467
|
+
results.anthropic = await probeAnthropic(auth, fetch);
|
|
468
|
+
} else if (provider === PROBE_POOLS.githubCopilot) {
|
|
469
|
+
results["github-copilot"] = await probeGitHubCopilot(auth, fetch);
|
|
308
470
|
}
|
|
309
471
|
}
|
|
310
472
|
|
|
@@ -26,7 +26,7 @@ import { metricsFilePath, readMetricsLines } from "../batch/metrics.mjs";
|
|
|
26
26
|
* pool because provider-level quotas (e.g. Z.ai, Google, Kimi) are typically
|
|
27
27
|
* account- or key-wide, not model-wide.
|
|
28
28
|
*/
|
|
29
|
-
const POOL_PREFIXES = new Set(["zai", "kimi-coding", "google", "cursor"]);
|
|
29
|
+
const POOL_PREFIXES = new Set(["zai", "kimi-coding", "google", "cursor", "anthropic", "github-copilot"]);
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* Resolves a model identifier to a shared quota pool id.
|