benignswarm 0.12.167 → 0.12.168
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/dist/antigravity.js +10 -6
- package/dist/client.js +10 -7
- package/dist/commands/machine-admin.js +9 -0
- package/dist/commands/machine.js +71 -0
- package/dist/commands/watch.js +44 -10
- package/dist/commands/worktrees.js +9 -3
- package/dist/commands/wu.js +12 -5
- package/dist/gate-test-reports.js +6 -1
- package/dist/git.js +47 -1
- package/dist/harnesses.js +22 -2
- package/dist/heartbeat.js +11 -1
- package/dist/jsonl.js +113 -0
- package/dist/macos-readiness.js +128 -0
- package/dist/merge-train.js +16 -76
- package/dist/scoped-gate.js +3 -0
- package/dist/state.js +9 -0
- package/dist/usage.js +88 -56
- package/dist/ux-jobs.js +27 -12
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/antigravity.js
CHANGED
|
@@ -6,6 +6,7 @@ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "no
|
|
|
6
6
|
import { configRoot } from "./config.js";
|
|
7
7
|
import { repoDirectory } from "./directories.js";
|
|
8
8
|
import { CliError } from "./errors.js";
|
|
9
|
+
import { readJsonlRecords } from "./jsonl.js";
|
|
9
10
|
import { gitSandboxDeniedPaths, gitSandboxReadablePaths, gitSandboxWorktreeMetadataPath, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
|
|
10
11
|
export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
|
|
11
12
|
export function isAntigravityWorkspaceWrite(env = process.env) {
|
|
@@ -294,12 +295,15 @@ export function antigravityProbe(session, ref, logPath = antigravityLog(ref), co
|
|
|
294
295
|
}
|
|
295
296
|
export function antigravityUsage(path, since, until) {
|
|
296
297
|
const from = Date.parse(since), to = Date.parse(until);
|
|
297
|
-
const rows = agyRecords(path).filter((record) => Date.parse(record.started_at) >= from && Date.parse(record.started_at) <= to && record.result?.usage);
|
|
298
|
-
if (!rows.length)
|
|
299
|
-
return null;
|
|
300
298
|
const totals = { input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 };
|
|
301
|
-
|
|
302
|
-
|
|
299
|
+
let found = false;
|
|
300
|
+
for (const row of readJsonlRecords(path)) {
|
|
301
|
+
const record = row;
|
|
302
|
+
const at = Date.parse(record.started_at);
|
|
303
|
+
const usage = record.result?.usage;
|
|
304
|
+
if (!Number.isFinite(at) || at < from || at > to || !usage)
|
|
305
|
+
continue;
|
|
306
|
+
found = true;
|
|
303
307
|
const cached = usage.cache_read_tokens ?? 0;
|
|
304
308
|
totals.input += (usage.input_tokens ?? 0) + cached;
|
|
305
309
|
totals.cached_input += cached;
|
|
@@ -307,7 +311,7 @@ export function antigravityUsage(path, since, until) {
|
|
|
307
311
|
totals.reasoning += usage.thinking_tokens ?? 0;
|
|
308
312
|
totals.total += antigravityTotalTokens(usage) ?? 0;
|
|
309
313
|
}
|
|
310
|
-
return totals;
|
|
314
|
+
return found ? totals : null;
|
|
311
315
|
}
|
|
312
316
|
export function appendAntigravityRawResult(path, output, exitCode, expectedConversation) {
|
|
313
317
|
const result = parseAntigravityJson(output);
|
package/dist/client.js
CHANGED
|
@@ -537,14 +537,17 @@ export class Client {
|
|
|
537
537
|
throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint, res.status);
|
|
538
538
|
}
|
|
539
539
|
const allowsRedactedExcerpt = upperMethod === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
540
|
+
const isScopedGateReceipt = upperMethod === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/scoped-gate-receipts(?:\?|$)/.test(path);
|
|
541
|
+
if (!isScopedGateReceipt) {
|
|
542
|
+
try {
|
|
543
|
+
verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : [], expectedStoredText(method, path, body, json));
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
if (res.status >= 200 && res.status < 300 && error instanceof CliError && !isRead) {
|
|
547
|
+
throw new WrittenReceiptMismatchError(json, error);
|
|
548
|
+
}
|
|
549
|
+
throw error;
|
|
546
550
|
}
|
|
547
|
-
throw error;
|
|
548
551
|
}
|
|
549
552
|
return json;
|
|
550
553
|
}
|
|
@@ -97,6 +97,15 @@ export function machineMacLines(macos) {
|
|
|
97
97
|
lines.push(` Xcode readiness: ${macos.xcode?.error ?? "not ready"}`);
|
|
98
98
|
if (!macos.simulators?.probe_ok)
|
|
99
99
|
lines.push(` simulator probe: ${macos.simulators?.error ?? "not ready"}`);
|
|
100
|
+
if (macos.signing_identity && typeof macos.signing_identity === "object") {
|
|
101
|
+
const s = macos.signing_identity;
|
|
102
|
+
if (s.status === "available") {
|
|
103
|
+
lines.push(` signing identity: ${s.name}${s.team_id ? ` (team ${s.team_id})` : ""}, certificate ${s.expires_at ? `expires ${s.expires_at}` : `expiry unavailable (${s.expiry_reason ?? "unknown"})`}`);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
lines.push(` signing identity: unavailable (${s.reason ?? "not reported"})`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
100
109
|
return lines;
|
|
101
110
|
}
|
|
102
111
|
export function machineGitLines(gitFacts) {
|
package/dist/commands/machine.js
CHANGED
|
@@ -145,6 +145,7 @@ export function startArgs(s, thread, writable = [], startupJitterSeconds) {
|
|
|
145
145
|
const KEY_CHECK_MS = 10 * 60_000;
|
|
146
146
|
const CAPABILITY_PROBE_MS = 60 * 60_000;
|
|
147
147
|
const lastCapabilityProbe = new Map();
|
|
148
|
+
const lastMacCapabilityReportHash = new Map();
|
|
148
149
|
const WORKTREE_PRUNE_INTERVAL_MS = 60 * 60_000;
|
|
149
150
|
const WORKTREE_PRUNE_PRESSURE_INTERVAL_MS = 15 * 60_000;
|
|
150
151
|
const WORKTREE_PRUNE_TIMEOUT_MS = 2 * 60_000;
|
|
@@ -2244,6 +2245,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
2244
2245
|
for (const item of probedProjects) {
|
|
2245
2246
|
lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
|
|
2246
2247
|
}
|
|
2248
|
+
const macosFacts = facts.macos;
|
|
2249
|
+
if (macosFacts) {
|
|
2250
|
+
await maybeReportMacCapabilities(client, m.name, macosFacts, log);
|
|
2251
|
+
}
|
|
2247
2252
|
const warning = diskSpaceNotice(homeSpace, workSpace);
|
|
2248
2253
|
if (warning !== undefined)
|
|
2249
2254
|
await client.call("PUT", "/machines/me/notices/disk", { text: warning });
|
|
@@ -2290,6 +2295,72 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
2290
2295
|
await resumePromise;
|
|
2291
2296
|
return { sessions: out, report };
|
|
2292
2297
|
}
|
|
2298
|
+
/** Build the strict allowlisted PUT /machines/me/mac-capabilities payload from a MacReadiness probe. */
|
|
2299
|
+
export function buildMacCapabilityReportPayload(macos, probeVersion = CLI_VERSION) {
|
|
2300
|
+
if (!macos.product_version ||
|
|
2301
|
+
!macos.product_build ||
|
|
2302
|
+
(macos.architecture !== "arm64" && macos.architecture !== "x86_64") ||
|
|
2303
|
+
!macos.model ||
|
|
2304
|
+
!macos.xcode?.version ||
|
|
2305
|
+
!macos.xcode?.build) {
|
|
2306
|
+
return null;
|
|
2307
|
+
}
|
|
2308
|
+
const disk = {};
|
|
2309
|
+
if (typeof macos.disk?.home?.free_bytes === "number")
|
|
2310
|
+
disk.home_free_bytes = Math.floor(macos.disk.home.free_bytes);
|
|
2311
|
+
if (typeof macos.disk?.checkout_build?.free_bytes === "number")
|
|
2312
|
+
disk.worktree_free_bytes = Math.floor(macos.disk.checkout_build.free_bytes);
|
|
2313
|
+
if (typeof macos.disk?.checkout_build?.total_bytes === "number")
|
|
2314
|
+
disk.total_bytes = Math.floor(macos.disk.checkout_build.total_bytes);
|
|
2315
|
+
const simulatorFree = macos.simulators?.runtimes.find((r) => typeof r.disk?.free_bytes === "number")?.disk?.free_bytes;
|
|
2316
|
+
if (typeof simulatorFree === "number")
|
|
2317
|
+
disk.simulator_free_bytes = Math.floor(simulatorFree);
|
|
2318
|
+
const capabilities = {
|
|
2319
|
+
macos_product_version: macos.product_version,
|
|
2320
|
+
macos_build: macos.product_build,
|
|
2321
|
+
architecture: macos.architecture,
|
|
2322
|
+
model: macos.model,
|
|
2323
|
+
...(macos.developer_directory ? { developer_directory: macos.developer_directory } : {}),
|
|
2324
|
+
xcode_version: macos.xcode.version,
|
|
2325
|
+
xcode_build: macos.xcode.build,
|
|
2326
|
+
license_accepted: macos.xcode.license_accepted === true,
|
|
2327
|
+
sdks: macos.xcode.sdks.slice(0, 100),
|
|
2328
|
+
simulator_runtimes: macos.simulators.runtimes
|
|
2329
|
+
.map((runtime) => `${runtime.platform} ${runtime.version ?? "unknown"}${runtime.build ? ` (${runtime.build})` : ""}`.slice(0, 200))
|
|
2330
|
+
.slice(0, 100),
|
|
2331
|
+
...(Object.keys(disk).length ? { disk } : {}),
|
|
2332
|
+
checks: {
|
|
2333
|
+
developer_directory_selected: macos.developer_directory_ok,
|
|
2334
|
+
xcode_license_accepted: macos.xcode.license_accepted === true,
|
|
2335
|
+
disk_ready: macos.readiness_refusals.build.length === 0,
|
|
2336
|
+
},
|
|
2337
|
+
signing_identity: macos.signing_identity,
|
|
2338
|
+
};
|
|
2339
|
+
return { probe_version: `cli-${probeVersion}`.slice(0, 100), capabilities };
|
|
2340
|
+
}
|
|
2341
|
+
/** Submit PUT /machines/me/mac-capabilities from a Mac daemon whenever its probe output changes. */
|
|
2342
|
+
export async function maybeReportMacCapabilities(client, machineKey, macos, log, probeVersion = CLI_VERSION) {
|
|
2343
|
+
const payload = buildMacCapabilityReportPayload(macos, probeVersion);
|
|
2344
|
+
if (!payload)
|
|
2345
|
+
return false;
|
|
2346
|
+
const serialized = JSON.stringify(payload);
|
|
2347
|
+
const digest = createHash("sha256").update(serialized).digest("hex");
|
|
2348
|
+
if (lastMacCapabilityReportHash.get(machineKey) === digest)
|
|
2349
|
+
return false;
|
|
2350
|
+
try {
|
|
2351
|
+
await client.call("PUT", "/machines/me/mac-capabilities", payload, { retryForMs: MACHINE_NETWORK_RETRY_MS });
|
|
2352
|
+
lastMacCapabilityReportHash.set(machineKey, digest);
|
|
2353
|
+
const idSummary = macos.signing_identity.status === "available"
|
|
2354
|
+
? `${macos.signing_identity.name}${macos.signing_identity.expires_at ? ` (expires ${macos.signing_identity.expires_at})` : ""}`
|
|
2355
|
+
: `unavailable (${macos.signing_identity.reason ?? "unknown"})`;
|
|
2356
|
+
log(`reported Mac capabilities (${macos.xcode.version}; signing identity ${idSummary})`);
|
|
2357
|
+
return true;
|
|
2358
|
+
}
|
|
2359
|
+
catch (error) {
|
|
2360
|
+
log(`Mac capability report upload failed safely: ${error.message}`);
|
|
2361
|
+
return false;
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2293
2364
|
export async function answerWorktreeProcessQueries(client, desired, queries, log, scan = scanWorktreeProcesses) {
|
|
2294
2365
|
for (const query of queries) {
|
|
2295
2366
|
try {
|
package/dist/commands/watch.js
CHANGED
|
@@ -16,7 +16,7 @@ import { basename, dirname, join } from "node:path";
|
|
|
16
16
|
import { bool, str } from "../args.js";
|
|
17
17
|
import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js";
|
|
18
18
|
import { Client } from "../client.js";
|
|
19
|
-
import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
|
|
19
|
+
import { heartbeatIfActive, reportWakeOutcomeChange, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
|
|
20
20
|
import { cleanupDeferredUnitWorktree, scanProject, unitWorktrees } from "./worktrees.js";
|
|
21
21
|
import { branchAndHead, formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
|
|
22
22
|
import { CliError } from "../errors.js";
|
|
@@ -25,7 +25,7 @@ import { acquireWatchLock } from "../lock.js";
|
|
|
25
25
|
import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
|
|
26
26
|
import { currentAssignmentEvent, deliveredAssignmentBinding } from "../turn-binding.js";
|
|
27
27
|
import { writeFileAtomic } from "../shared-file.js";
|
|
28
|
-
import { readState, updateState } from "../state.js";
|
|
28
|
+
import { readState, updateState, recordWakeAttempt } from "../state.js";
|
|
29
29
|
import { probeCapabilities } from "../capabilities.js";
|
|
30
30
|
import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
|
|
31
31
|
import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS, markTurnUnverified, unverifiedTurn } from "../turn-guard.js";
|
|
@@ -244,7 +244,7 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
244
244
|
// The watcher sits in a checkout on the machine, so it keeps the worktree registry current: a
|
|
245
245
|
// scan on start and then hourly reports worktrees nobody is touching, which agent calls never would.
|
|
246
246
|
const scanCreds = loadAgent(name);
|
|
247
|
-
const watcherClient = once ? null : Client.forAgent(scanCreds, undefined, { presence: false });
|
|
247
|
+
const watcherClient = once ? null : Client.forAgent(scanCreds, undefined, { presence: false, machineIdentity: true });
|
|
248
248
|
let lastScan = 0;
|
|
249
249
|
let lastCapabilities = 0;
|
|
250
250
|
// A watcher holding a pending wake-up makes no server call, so a revoked key (the agent moved to
|
|
@@ -258,12 +258,13 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
258
258
|
if (watcherClient) {
|
|
259
259
|
try {
|
|
260
260
|
const phase = turnMode && probe ? probe.phase() : null;
|
|
261
|
-
const
|
|
261
|
+
const reportState = readState(name);
|
|
262
|
+
const saved = turnMode ? reportState.watch_turn_binding : undefined;
|
|
262
263
|
const observed = phase && !("missing" in phase) && phase.running && phase.startedAt && saved?.started_at === phase.startedAt ? saved : null;
|
|
263
264
|
const binding = observed?.work_unit_number && observed.assignment_event_id
|
|
264
265
|
? { work_unit_number: observed.work_unit_number, assignment_event_id: observed.assignment_event_id }
|
|
265
266
|
: null;
|
|
266
|
-
await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue", { startedAt: observed?.started_at ?? null, binding });
|
|
267
|
+
await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue", { startedAt: observed?.started_at ?? null, binding }, readState(name).wake_attempt);
|
|
267
268
|
}
|
|
268
269
|
catch (e) {
|
|
269
270
|
log(`watcher heartbeat failed: ${e.message}`);
|
|
@@ -386,8 +387,18 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
386
387
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
387
388
|
}, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness, currentWatcherOomKillCount, turn?.antigravityRuntime?.sandbox);
|
|
388
389
|
else {
|
|
390
|
+
const previousWakeAttempts = JSON.stringify(readState(name).wake_attempts ?? null);
|
|
389
391
|
const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered, undefined, false, undefined, undefined, undefined, 0, dependencies.wakeOnceDependencies);
|
|
390
392
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
393
|
+
const updatedState = readState(name);
|
|
394
|
+
if (!turnMode && watcherClient && JSON.stringify(updatedState.wake_attempts ?? null) !== previousWakeAttempts) {
|
|
395
|
+
try {
|
|
396
|
+
await reportWakeOutcomeChange(watcherClient, interval, JSON.parse(previousWakeAttempts), updatedState.wake_attempts, dependencies.reportWatcher ?? reportWatcherHeartbeat);
|
|
397
|
+
}
|
|
398
|
+
catch (e) {
|
|
399
|
+
log(`watcher wake outcome report failed: ${e.message}`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
391
402
|
}
|
|
392
403
|
}
|
|
393
404
|
catch (e) {
|
|
@@ -447,7 +458,7 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
447
458
|
if (exec) {
|
|
448
459
|
const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", shellQuote(update.text));
|
|
449
460
|
log(`new activity (${summary}); running: ${cmd}`);
|
|
450
|
-
const code = await
|
|
461
|
+
const { code } = await runCommand(cmd, update.text, { BSCHAT_TEXT: update.text, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) });
|
|
451
462
|
if (code !== 0) {
|
|
452
463
|
log(`command exited ${code}`);
|
|
453
464
|
delivered = false;
|
|
@@ -1190,15 +1201,28 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
|
|
|
1190
1201
|
return { ...onDisk, watch_turn_binding: { ...pending, launched_at: startedAt } };
|
|
1191
1202
|
});
|
|
1192
1203
|
turnSink(startedTurn);
|
|
1204
|
+
recordWakeAttempt(name, { success: true });
|
|
1193
1205
|
}
|
|
1194
1206
|
else {
|
|
1195
1207
|
log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
|
|
1196
|
-
const code = await
|
|
1208
|
+
const { code, error: launchError } = await runCommand(cmd, wake, env);
|
|
1209
|
+
const attemptedAt = new Date().toISOString();
|
|
1210
|
+
updateState(name, (onDisk) => {
|
|
1211
|
+
const previous = onDisk.wake_attempts ?? { consecutive_failures: 0, last_failure_at: null, last_failure_exit_code: null, last_failure_message: null, last_success_at: null };
|
|
1212
|
+
return {
|
|
1213
|
+
...onDisk,
|
|
1214
|
+
wake_attempts: code === 0
|
|
1215
|
+
? { ...previous, consecutive_failures: 0, last_success_at: attemptedAt }
|
|
1216
|
+
: { ...previous, consecutive_failures: Math.min(previous.consecutive_failures + 1, Number.MAX_SAFE_INTEGER), last_failure_at: attemptedAt, last_failure_exit_code: code, last_failure_message: (launchError ?? `Wake command exited with code ${code}`).slice(0, 300) },
|
|
1217
|
+
};
|
|
1218
|
+
});
|
|
1197
1219
|
if (code !== 0) {
|
|
1220
|
+
recordWakeAttempt(name, { success: false, exitCode: code, message: `wake command exited ${code}` });
|
|
1198
1221
|
// The agent was NOT woken. Leave nothing pending so the next poll tries again.
|
|
1199
1222
|
log(`wake command exited ${code}; will retry next poll. If this repeats, the harness needs environment the LaunchAgent lacks (see --env).`);
|
|
1200
1223
|
return false;
|
|
1201
1224
|
}
|
|
1225
|
+
recordWakeAttempt(name, { success: true });
|
|
1202
1226
|
}
|
|
1203
1227
|
// Tell the server a wake-up was queued, so it can tell a busy agent from a broken wake path
|
|
1204
1228
|
// (no harness activity long after). A failure here is logged; the agent was woken regardless.
|
|
@@ -2014,12 +2038,22 @@ async function processLag(name, st, fresh, log) {
|
|
|
2014
2038
|
function shellQuote(s) {
|
|
2015
2039
|
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
2016
2040
|
}
|
|
2017
|
-
function
|
|
2041
|
+
export function runCommand(cmd, stdin, env) {
|
|
2018
2042
|
return new Promise((resolve) => {
|
|
2019
2043
|
const child = spawn("/bin/sh", ["-c", cmd], { stdio: ["pipe", "inherit", "inherit"], env: { ...process.env, ...env } });
|
|
2044
|
+
let stdinError;
|
|
2045
|
+
let stdinClosedEarly = false;
|
|
2046
|
+
child.stdin.on("error", (error) => {
|
|
2047
|
+
// A short-lived command may close stdin before the wake payload is written. EPIPE means
|
|
2048
|
+
// the child chose not to read the payload; it is not an unhandled watcher failure.
|
|
2049
|
+
if (error.code === "EPIPE")
|
|
2050
|
+
stdinClosedEarly = true;
|
|
2051
|
+
else
|
|
2052
|
+
stdinError = error;
|
|
2053
|
+
});
|
|
2020
2054
|
child.stdin.end(stdin);
|
|
2021
|
-
child.on("close", (code) => resolve(code ?? 1));
|
|
2022
|
-
child.on("error", () => resolve(1));
|
|
2055
|
+
child.on("close", (code) => resolve({ code: code ?? 1, ...(stdinError ? { error: stdinError.message } : {}), ...(stdinClosedEarly ? { stdinClosedEarly: true } : {}) }));
|
|
2056
|
+
child.on("error", (error) => resolve({ code: 1, error: error.message }));
|
|
2023
2057
|
});
|
|
2024
2058
|
}
|
|
2025
2059
|
/**
|
|
@@ -245,12 +245,18 @@ export async function worktrees(p, out, timeouts = {}) {
|
|
|
245
245
|
}
|
|
246
246
|
/** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
|
|
247
247
|
export async function scanProject(creds, project, options = {}) {
|
|
248
|
-
const
|
|
248
|
+
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
249
|
+
const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
|
|
250
|
+
const targets = await timedClientCall(client, "GET", `/projects/${project}/worktrees/scan-targets`, undefined, timeoutMs, `worktree target for project ${project}`);
|
|
251
|
+
const originTargetsByBranch = new Map();
|
|
252
|
+
for (const row of targets.unit_targets) {
|
|
253
|
+
if (!originTargetsByBranch.has(row.branch))
|
|
254
|
+
originTargetsByBranch.set(row.branch, row.target);
|
|
255
|
+
}
|
|
256
|
+
const scan = scanWorktrees(options.cwd ?? process.cwd(), { ...options, measureDisk: true, originTarget: targets.default_target, originTargetsByBranch });
|
|
249
257
|
if (!scan)
|
|
250
258
|
throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
|
|
251
259
|
const machine = defaultMachine();
|
|
252
|
-
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
253
|
-
const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
|
|
254
260
|
options.onProgress?.(`Reporting worktrees for project ${project} (timeout ${timeoutMs} ms)`);
|
|
255
261
|
const r = await timedClientCall(client, "POST", `/projects/${project}/worktrees/scan`, { machine, repo: scan.repo, worktrees: scan.worktrees }, timeoutMs, `worktree registry scan for project ${project}`);
|
|
256
262
|
return { machine, repo: scan.repo, recorded: r.recorded, missing: r.missing };
|
package/dist/commands/wu.js
CHANGED
|
@@ -2680,19 +2680,26 @@ async function reviewUsage(client, project, name) {
|
|
|
2680
2680
|
const until = new Date().toISOString();
|
|
2681
2681
|
const session = measurableSession(name);
|
|
2682
2682
|
let since;
|
|
2683
|
+
let cursor;
|
|
2683
2684
|
try {
|
|
2684
2685
|
const result = await client.call("GET", `/projects/${project}/agents/me/usage-cursor`);
|
|
2685
|
-
|
|
2686
|
+
cursor = result.since;
|
|
2687
|
+
}
|
|
2688
|
+
catch (error) {
|
|
2689
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session usage cursor: ${error.message}` };
|
|
2690
|
+
}
|
|
2691
|
+
try {
|
|
2692
|
+
if (cursor === null)
|
|
2686
2693
|
since = sessionStart(session);
|
|
2687
2694
|
else {
|
|
2688
|
-
const
|
|
2689
|
-
if (!Number.isFinite(
|
|
2695
|
+
const cursorAt = typeof cursor === "string" ? Date.parse(cursor) : NaN;
|
|
2696
|
+
if (!Number.isFinite(cursorAt))
|
|
2690
2697
|
throw new Error("invalid session usage cursor");
|
|
2691
|
-
since = new Date(
|
|
2698
|
+
since = new Date(cursorAt + 1).toISOString();
|
|
2692
2699
|
}
|
|
2693
2700
|
}
|
|
2694
2701
|
catch (error) {
|
|
2695
|
-
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session
|
|
2702
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session timestamp: ${error.message}` };
|
|
2696
2703
|
}
|
|
2697
2704
|
if (!since)
|
|
2698
2705
|
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: "no earlier usage boundary or timestamped session is available" };
|
|
@@ -9,6 +9,11 @@ const STAGES = [
|
|
|
9
9
|
{ stage: 'cli tests', engine: 'node', workspace: 'packages/cli', filename: 'cli.xml' },
|
|
10
10
|
{ stage: 'web tests', engine: 'node', workspace: 'apps/web', filename: 'web.xml' },
|
|
11
11
|
];
|
|
12
|
+
function machineAlias(machine) {
|
|
13
|
+
const segment = machine.split(/[\\/]/).at(-1) ?? "";
|
|
14
|
+
const alias = segment.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, "").slice(0, 64).replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, "");
|
|
15
|
+
return alias || "unknown-runner";
|
|
16
|
+
}
|
|
12
17
|
/** Import real failing Vitest reports as canonical test runs for later quarantine decisions. */
|
|
13
18
|
export async function importFailingGateReports(options) {
|
|
14
19
|
if (!/^[A-Za-z0-9-]{1,100}$/.test(options.trainRunId))
|
|
@@ -23,7 +28,7 @@ export async function importFailingGateReports(options) {
|
|
|
23
28
|
schema_version: 1,
|
|
24
29
|
source: { commit: options.candidate, target_commit: options.base, target_branch: options.branch, package: item.workspace, target_config: `merge-train-gate-${item.stage.replaceAll(" ", "-")}-${item.engine}` },
|
|
25
30
|
invocation: { argv: ['scripts/gate.sh', item.stage], cwd: '.' },
|
|
26
|
-
runner: { machine: options.creds.machine, os: platform() === 'darwin' ? 'macos' : platform() === 'win32' ? 'windows' : platform(), arch: arch(), runtime: `node-${process.versions.node}`, sandbox: 'unknown' },
|
|
31
|
+
runner: { machine: machineAlias(options.creds.machine), os: platform() === 'darwin' ? 'macos' : platform() === 'win32' ? 'windows' : platform(), arch: arch(), runtime: `node-${process.versions.node}`, sandbox: 'unknown' },
|
|
27
32
|
run: { started_at: options.startedAt, ended_at: options.endedAt, exit_status: 1, state: 'completed' },
|
|
28
33
|
};
|
|
29
34
|
const draft = parseTestRunReport(item.filename, bytes, Buffer.from(JSON.stringify(metadata)));
|
package/dist/git.js
CHANGED
|
@@ -169,6 +169,29 @@ export function mergeFacts(cwd, worktree, observedHead) {
|
|
|
169
169
|
const count = (range) => { const value = git(["rev-list", "--count", range], cwd); return value !== null && /^\d+$/.test(value) ? Number(value) : null; };
|
|
170
170
|
return { repo, base, merged, ahead: count(`${base_sha}..${head}`), behind: count(`${head}..${base_sha}`), base_sha };
|
|
171
171
|
}
|
|
172
|
+
/** Resolve the advertised target without updating the checkout's tracking refs. */
|
|
173
|
+
function scanOriginTip(cwd, target, deadline) {
|
|
174
|
+
const timeout = deadline - Date.now();
|
|
175
|
+
if (timeout <= 0)
|
|
176
|
+
return null;
|
|
177
|
+
const ref = `refs/heads/${target}`;
|
|
178
|
+
const env = { ...gitTransportEnv(), GIT_TERMINAL_PROMPT: "0" };
|
|
179
|
+
const listed = spawnSync("git", ["ls-remote", "--exit-code", "--heads", "origin", ref], { cwd, env, timeout, encoding: "utf8" });
|
|
180
|
+
if (listed.status !== 0)
|
|
181
|
+
return null;
|
|
182
|
+
const [sha, advertisedRef] = listed.stdout.trim().split("\t");
|
|
183
|
+
if (advertisedRef !== ref || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha))
|
|
184
|
+
return null;
|
|
185
|
+
if (fullSha(`${sha}^{commit}`, cwd) === sha)
|
|
186
|
+
return sha;
|
|
187
|
+
const remaining = deadline - Date.now();
|
|
188
|
+
if (remaining <= 0)
|
|
189
|
+
return null;
|
|
190
|
+
const fetched = spawnSync("git", ["fetch", "--no-tags", "--no-write-fetch-head", "origin", sha], {
|
|
191
|
+
cwd, env, timeout: remaining, encoding: "utf8",
|
|
192
|
+
});
|
|
193
|
+
return fetched.status === 0 && fullSha(`${sha}^{commit}`, cwd) === sha ? sha : null;
|
|
194
|
+
}
|
|
172
195
|
/** Every linked worktree of the repository at cwd, with the same facts an agent call reports. */
|
|
173
196
|
export function scanWorktrees(cwd = process.cwd(), options = {}) {
|
|
174
197
|
const list = git(["worktree", "list", "--porcelain"], cwd);
|
|
@@ -186,6 +209,11 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
|
|
|
186
209
|
return null;
|
|
187
210
|
const repo = entries[0].path;
|
|
188
211
|
options.onProgress?.(`Scanning repository ${repo}`);
|
|
212
|
+
// Apply one wall-clock budget across the repository. A timed-out observation is unknown.
|
|
213
|
+
const diskDeadline = Date.now() + 10_000;
|
|
214
|
+
const completeGraph = options.measureDisk && git(["rev-parse", "--is-shallow-repository"], cwd) === "false";
|
|
215
|
+
const originDeadline = Date.now() + 10_000;
|
|
216
|
+
const targetRevisions = new Map();
|
|
189
217
|
const worktrees = entries.map(({ path: p, locked }) => {
|
|
190
218
|
options.onProgress?.(`Scanning worktree ${p}`);
|
|
191
219
|
const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], p) ?? git(["rev-parse", "--short", "HEAD"], p);
|
|
@@ -193,7 +221,25 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
|
|
|
193
221
|
const worktreeStatus = status(p, options.statusTimeoutMs);
|
|
194
222
|
const f = head ? mergeFacts(p, p, head) : { base: null, merged: null, ahead: null, behind: null, base_sha: null };
|
|
195
223
|
const empty = existsSync(p) && readdirSync(p).every((e) => e === ".git");
|
|
196
|
-
|
|
224
|
+
let disk_bytes = null;
|
|
225
|
+
const remaining = diskDeadline - Date.now();
|
|
226
|
+
if (options.measureDisk && remaining > 0 && isAbsolute(p)) {
|
|
227
|
+
// -x stays on this volume, and excludes Git's shared object store from checkout usage.
|
|
228
|
+
const measurement = spawnSync("du", process.platform === "darwin" ? ["-skx", "-I", ".git", p] : ["-skx", "--exclude=.git", p], { timeout: remaining, encoding: "utf8" });
|
|
229
|
+
const line = measurement.status === 0 ? /^(\d+)\s/.exec(measurement.stdout ?? "") : null;
|
|
230
|
+
const bytes = line ? Number(line[1]) * 1024 : NaN;
|
|
231
|
+
if (Number.isSafeInteger(bytes))
|
|
232
|
+
disk_bytes = bytes;
|
|
233
|
+
}
|
|
234
|
+
const target = (branch ? options.originTargetsByBranch?.get(branch) : undefined) ?? options.originTarget;
|
|
235
|
+
const ref = completeGraph && target && /^[\w./-]{1,100}$/.test(target) ? `origin/${target}` : null;
|
|
236
|
+
if (ref && target && !targetRevisions.has(ref))
|
|
237
|
+
targetRevisions.set(ref, scanOriginTip(cwd, target, originDeadline));
|
|
238
|
+
const origin = ref ? targetRevisions.get(ref) : null;
|
|
239
|
+
const measuredHead = origin && head ? fullSha(head, p) : null;
|
|
240
|
+
const distance = measuredHead ? git(["rev-list", "--left-right", "--count", `${origin}...${measuredHead}`], p)?.match(/^(\d+)\s+(\d+)$/) : null;
|
|
241
|
+
const origin_distance = distance && ref && origin && head ? { ref, sha: origin, head, behind: Number(distance[1]), ahead: Number(distance[2]) } : null;
|
|
242
|
+
return { ...(options.measureDisk ? { disk_bytes, origin_distance } : {}), path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, behind: f.behind, base_sha: f.base_sha, empty, locked };
|
|
197
243
|
});
|
|
198
244
|
return { repo, worktrees };
|
|
199
245
|
}
|
package/dist/harnesses.js
CHANGED
|
@@ -230,11 +230,31 @@ export function dshResultError(text) {
|
|
|
230
230
|
}
|
|
231
231
|
/** DeepSeek emits per-step usage; sum it over the accumulated per-agent turn log. */
|
|
232
232
|
export function dshUsage(text, since, until) {
|
|
233
|
+
function* records() {
|
|
234
|
+
for (const line of text.split("\n")) {
|
|
235
|
+
try {
|
|
236
|
+
const value = JSON.parse(line);
|
|
237
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
238
|
+
yield value;
|
|
239
|
+
}
|
|
240
|
+
catch { /* a line may still be streaming */ }
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return dshUsageFromRecords(records(), since, until);
|
|
244
|
+
}
|
|
245
|
+
/** DeepSeek per-step usage over already parsed JSONL records. */
|
|
246
|
+
export function dshUsageFromRecords(records, since, until) {
|
|
247
|
+
return dshUsageFromRecordsDetailed(records, since, until).usage;
|
|
248
|
+
}
|
|
249
|
+
export function dshUsageFromRecordsDetailed(records, since, until) {
|
|
233
250
|
const result = { input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 };
|
|
234
251
|
const window = since !== undefined && until !== undefined ? { since: Date.parse(since), until: Date.parse(until) } : null;
|
|
235
252
|
let invocationAt = null;
|
|
236
|
-
|
|
253
|
+
let hasInvocationStart = false;
|
|
254
|
+
for (const row of records) {
|
|
255
|
+
const e = row;
|
|
237
256
|
if (e.type === "b9s_invocation_start") {
|
|
257
|
+
hasInvocationStart = true;
|
|
238
258
|
invocationAt = typeof e.at === "string" ? Date.parse(e.at) : null;
|
|
239
259
|
continue;
|
|
240
260
|
}
|
|
@@ -251,7 +271,7 @@ export function dshUsage(text, since, until) {
|
|
|
251
271
|
result.output += e.usage.outputTokens ?? 0;
|
|
252
272
|
}
|
|
253
273
|
result.total = result.input + result.output;
|
|
254
|
-
return result;
|
|
274
|
+
return { usage: result, hasInvocationStart };
|
|
255
275
|
}
|
|
256
276
|
/** Map the user's selected sandbox to dsh's native permission mode and writable roots. */
|
|
257
277
|
export function dshSettings(sandbox, cwd, b9sHome, extraWritable = []) {
|
package/dist/heartbeat.js
CHANGED
|
@@ -84,15 +84,25 @@ export async function heartbeatIfActive(client, src, prev, windowSeconds, log) {
|
|
|
84
84
|
return cur;
|
|
85
85
|
}
|
|
86
86
|
/** A persistent watcher proves its own wake path independently of harness file activity. */
|
|
87
|
-
export async function reportWatcherHeartbeat(client, intervalSeconds, mode, turn) {
|
|
87
|
+
export async function reportWatcherHeartbeat(client, intervalSeconds, mode, turn, wakeAttempt) {
|
|
88
88
|
await client.call("POST", "/agents/me/watcher/heartbeat", {
|
|
89
89
|
interval_seconds: intervalSeconds,
|
|
90
90
|
mode,
|
|
91
91
|
turn_started_at: mode === "turn" ? turn?.startedAt ?? null : null,
|
|
92
92
|
work_unit_number: mode === "turn" ? turn?.binding?.work_unit_number ?? null : null,
|
|
93
93
|
assignment_event_id: mode === "turn" ? turn?.binding?.assignment_event_id ?? null : null,
|
|
94
|
+
...(wakeAttempt ? { wake_attempt: wakeAttempt } : {}),
|
|
94
95
|
});
|
|
95
96
|
}
|
|
97
|
+
/** Immediately report a changed queue wake outcome instead of waiting for the next poll heartbeat. */
|
|
98
|
+
export async function reportWakeOutcomeChange(client, intervalSeconds, previous, current, report = reportWatcherHeartbeat) {
|
|
99
|
+
if (JSON.stringify(previous ?? null) === JSON.stringify(current ?? null))
|
|
100
|
+
return false;
|
|
101
|
+
if (!current)
|
|
102
|
+
throw new Error("changed watcher wake outcome is missing its current state");
|
|
103
|
+
await report(client, intervalSeconds, "queue", { startedAt: null, binding: null }, current);
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
96
106
|
/**
|
|
97
107
|
* The hook variant: the hook running is itself the evidence, so report now, throttled by the
|
|
98
108
|
* caller. `goal` undefined means "unknown, keep what you have"; null means "no goal is set".
|
package/dist/jsonl.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
import { constants as bufferConstants } from "node:buffer";
|
|
3
|
+
import { TextDecoder } from "node:util";
|
|
4
|
+
export const JSONL_CHUNK_BYTES = 64 * 1024;
|
|
5
|
+
// UTF-8 can use up to three bytes per UTF-16 code unit. This ceiling therefore accepts any
|
|
6
|
+
// valid UTF-8 record whose decoded string is within Node's maximum supported string length.
|
|
7
|
+
export const JSONL_MAX_RECORD_BYTES = bufferConstants.MAX_STRING_LENGTH * 3;
|
|
8
|
+
export class JsonlRecordTooLargeError extends Error {
|
|
9
|
+
constructor(path, line, limit) {
|
|
10
|
+
const label = limit >= 1024 * 1024 ? `${Math.round(limit / 1024 / 1024)} MB` : `${limit} units`;
|
|
11
|
+
super(`JSONL record ${line} in ${path} exceeds the supported ${label} telemetry record limit`);
|
|
12
|
+
this.name = "JsonlRecordTooLargeError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Decode failures are resource/input errors; only JSON syntax errors retain the historical skip behavior. */
|
|
16
|
+
export function parseJsonlRecord(bytes, path, line, decode = (input) => input.toString("utf8")) {
|
|
17
|
+
const text = decode(bytes);
|
|
18
|
+
let parsed;
|
|
19
|
+
try {
|
|
20
|
+
parsed = JSON.parse(text);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (error instanceof SyntaxError)
|
|
24
|
+
return null;
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
|
|
28
|
+
? parsed
|
|
29
|
+
: null;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Parse JSONL with memory bounded by one record plus a fixed read chunk. A record larger than the
|
|
33
|
+
* platform limit is reported as unreadable rather than truncated or partially counted. Newline is
|
|
34
|
+
* an ASCII byte and cannot occur inside a UTF-8 code point, so decoding each joined record is safe
|
|
35
|
+
* even when the input chunk boundary splits a multi-byte character.
|
|
36
|
+
*/
|
|
37
|
+
export function* readJsonlRecords(path, chunkBytes = JSONL_CHUNK_BYTES, maxRecordBytes = JSONL_MAX_RECORD_BYTES, maxDecodedStringLength = bufferConstants.MAX_STRING_LENGTH) {
|
|
38
|
+
const fd = openSync(path, "r");
|
|
39
|
+
try {
|
|
40
|
+
const size = fstatSync(fd).size;
|
|
41
|
+
const chunk = Buffer.allocUnsafe(chunkBytes);
|
|
42
|
+
let offset = 0;
|
|
43
|
+
let line = 0;
|
|
44
|
+
let parts = [];
|
|
45
|
+
let pendingBytes = 0;
|
|
46
|
+
let pendingStringLength = 0;
|
|
47
|
+
let decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
48
|
+
const account = (piece, final = false) => {
|
|
49
|
+
pendingStringLength += decoder.decode(piece, { stream: !final }).length;
|
|
50
|
+
if (pendingStringLength > maxDecodedStringLength) {
|
|
51
|
+
throw new JsonlRecordTooLargeError(path, line + 1, maxDecodedStringLength);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const record = (last) => {
|
|
55
|
+
const bytes = pendingBytes + last.length;
|
|
56
|
+
if (bytes > maxRecordBytes)
|
|
57
|
+
throw new JsonlRecordTooLargeError(path, line + 1, maxRecordBytes);
|
|
58
|
+
account(Buffer.alloc(0), true);
|
|
59
|
+
const joined = parts.length === 0 ? last : Buffer.concat([...parts, last], bytes);
|
|
60
|
+
parts = [];
|
|
61
|
+
pendingBytes = 0;
|
|
62
|
+
pendingStringLength = 0;
|
|
63
|
+
decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
64
|
+
line++;
|
|
65
|
+
if (joined.length === 0)
|
|
66
|
+
return null;
|
|
67
|
+
return parseJsonlRecord(joined, path, line);
|
|
68
|
+
};
|
|
69
|
+
while (offset < size) {
|
|
70
|
+
const wanted = Math.min(chunk.length, size - offset);
|
|
71
|
+
let got = 0;
|
|
72
|
+
while (got < wanted) {
|
|
73
|
+
const n = readSync(fd, chunk, got, wanted - got, offset + got);
|
|
74
|
+
if (n === 0)
|
|
75
|
+
break;
|
|
76
|
+
got += n;
|
|
77
|
+
}
|
|
78
|
+
if (got === 0)
|
|
79
|
+
break;
|
|
80
|
+
offset += got;
|
|
81
|
+
let start = 0;
|
|
82
|
+
for (let i = 0; i < got; i++) {
|
|
83
|
+
if (chunk[i] !== 0x0a)
|
|
84
|
+
continue;
|
|
85
|
+
const piece = chunk.subarray(start, i);
|
|
86
|
+
if (pendingBytes + piece.length > maxRecordBytes)
|
|
87
|
+
throw new JsonlRecordTooLargeError(path, line + 1, maxRecordBytes);
|
|
88
|
+
account(piece);
|
|
89
|
+
const parsed = record(piece);
|
|
90
|
+
if (parsed)
|
|
91
|
+
yield parsed;
|
|
92
|
+
start = i + 1;
|
|
93
|
+
}
|
|
94
|
+
const remainder = chunk.subarray(start, got);
|
|
95
|
+
if (pendingBytes + remainder.length > maxRecordBytes)
|
|
96
|
+
throw new JsonlRecordTooLargeError(path, line + 1, maxRecordBytes);
|
|
97
|
+
if (remainder.length) {
|
|
98
|
+
account(remainder);
|
|
99
|
+
parts.push(Buffer.from(remainder));
|
|
100
|
+
pendingBytes += remainder.length;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// The old full-file reader parsed a final valid record even when its writer had not appended a newline.
|
|
104
|
+
if (pendingBytes) {
|
|
105
|
+
const parsed = record(Buffer.alloc(0));
|
|
106
|
+
if (parsed)
|
|
107
|
+
yield parsed;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
closeSync(fd);
|
|
112
|
+
}
|
|
113
|
+
}
|
package/dist/macos-readiness.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { X509Certificate } from "node:crypto";
|
|
2
3
|
import { existsSync, statfsSync } from "node:fs";
|
|
3
4
|
import { arch, homedir } from "node:os";
|
|
4
5
|
import { dirname } from "node:path";
|
|
@@ -84,6 +85,131 @@ function runtimesFromJson(raw, devicesRaw, stat, floorPct) {
|
|
|
84
85
|
});
|
|
85
86
|
return { runtimes, error: devicesValid ? null : "simctl devices returned invalid JSON" };
|
|
86
87
|
}
|
|
88
|
+
function subjectField(subject, key) {
|
|
89
|
+
for (const line of subject.split(/\r?\n/)) {
|
|
90
|
+
const idx = line.indexOf("=");
|
|
91
|
+
if (idx <= 0)
|
|
92
|
+
continue;
|
|
93
|
+
if (line.slice(0, idx).trim() === key) {
|
|
94
|
+
const value = line.slice(idx + 1).trim();
|
|
95
|
+
if (value)
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
const IDENTITY_PRIORITY = [
|
|
102
|
+
/^Developer ID Application:/i,
|
|
103
|
+
/^Apple Distribution:/i,
|
|
104
|
+
/^iPhone Distribution:/i,
|
|
105
|
+
/^Mac App Distribution:/i,
|
|
106
|
+
/^Apple Development:/i,
|
|
107
|
+
/^iPhone Developer:/i,
|
|
108
|
+
];
|
|
109
|
+
function pickPreferredSigningIdentity(names) {
|
|
110
|
+
if (!names.length)
|
|
111
|
+
return null;
|
|
112
|
+
for (const pattern of IDENTITY_PRIORITY) {
|
|
113
|
+
const match = names.find((name) => pattern.test(name));
|
|
114
|
+
if (match)
|
|
115
|
+
return match;
|
|
116
|
+
}
|
|
117
|
+
return names[0] ?? null;
|
|
118
|
+
}
|
|
119
|
+
/** Read-only probe for macOS code-signing identity and X.509 certificate expiry; never accesses private keys. */
|
|
120
|
+
export function probeMacSigningIdentity(run) {
|
|
121
|
+
const identities = commandOutput(run, "security", ["find-identity", "-v", "-p", "codesigning"]);
|
|
122
|
+
if (!identities.ok) {
|
|
123
|
+
return {
|
|
124
|
+
status: "unavailable",
|
|
125
|
+
name: null,
|
|
126
|
+
team_id: null,
|
|
127
|
+
team_name: null,
|
|
128
|
+
expires_at: null,
|
|
129
|
+
reason: identities.error ?? "code-signing identity probe failed",
|
|
130
|
+
expiry_reason: null,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
const validNames = [];
|
|
134
|
+
for (const line of identities.output.split(/\r?\n/)) {
|
|
135
|
+
const match = /^\s*\d+\)\s+[0-9A-Fa-f]{40}\s+"([^"]+)"(?:\s+\(([^)]+)\))?/.exec(line);
|
|
136
|
+
if (!match)
|
|
137
|
+
continue;
|
|
138
|
+
const statusNote = match[2] ?? "";
|
|
139
|
+
if (/CSSMERR|REVOKED|EXPIRED|NOT TRUSTED/i.test(statusNote))
|
|
140
|
+
continue;
|
|
141
|
+
if (match[1]?.trim())
|
|
142
|
+
validNames.push(match[1].trim());
|
|
143
|
+
}
|
|
144
|
+
const selected = pickPreferredSigningIdentity(validNames);
|
|
145
|
+
if (!selected) {
|
|
146
|
+
return {
|
|
147
|
+
status: "unavailable",
|
|
148
|
+
name: null,
|
|
149
|
+
team_id: null,
|
|
150
|
+
team_name: null,
|
|
151
|
+
expires_at: null,
|
|
152
|
+
reason: "no valid code-signing identity installed in keychain",
|
|
153
|
+
expiry_reason: null,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
const trailingTeamMatch = /\(([A-Z0-9]{6,20})\)\s*$/.exec(selected);
|
|
157
|
+
const fallbackTeamId = trailingTeamMatch?.[1] ?? null;
|
|
158
|
+
// Query public certificates only (-p emits X.509 certificates, never private keys).
|
|
159
|
+
const certLookup = commandOutput(run, "security", ["find-certificate", "-a", "-c", selected, "-p"]);
|
|
160
|
+
if (!certLookup.ok) {
|
|
161
|
+
return {
|
|
162
|
+
status: "available",
|
|
163
|
+
name: selected,
|
|
164
|
+
team_id: fallbackTeamId,
|
|
165
|
+
team_name: null,
|
|
166
|
+
expires_at: null,
|
|
167
|
+
reason: null,
|
|
168
|
+
expiry_reason: certLookup.error ?? "certificate expiry lookup failed",
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
const pemBlocks = certLookup.output.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? [];
|
|
172
|
+
let bestCert = null;
|
|
173
|
+
for (const pem of pemBlocks) {
|
|
174
|
+
try {
|
|
175
|
+
const cert = new X509Certificate(pem);
|
|
176
|
+
const validToMs = Date.parse(cert.validTo);
|
|
177
|
+
if (!Number.isFinite(validToMs))
|
|
178
|
+
continue;
|
|
179
|
+
const cn = subjectField(cert.subject, "CN");
|
|
180
|
+
const ou = subjectField(cert.subject, "OU");
|
|
181
|
+
const org = subjectField(cert.subject, "O");
|
|
182
|
+
const exactMatch = cn === selected;
|
|
183
|
+
const bestExact = bestCert ? bestCert.cn === selected : false;
|
|
184
|
+
if (!bestCert || (exactMatch && !bestExact) || (exactMatch === bestExact && validToMs > bestCert.validToMs)) {
|
|
185
|
+
bestCert = { cn, ou, org, validToMs };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// Skip malformed certificate blocks safely without failing valid certificates.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (!bestCert) {
|
|
193
|
+
return {
|
|
194
|
+
status: "available",
|
|
195
|
+
name: selected,
|
|
196
|
+
team_id: fallbackTeamId,
|
|
197
|
+
team_name: null,
|
|
198
|
+
expires_at: null,
|
|
199
|
+
reason: null,
|
|
200
|
+
expiry_reason: "certificate expiry could not be parsed from keychain certificate",
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
status: "available",
|
|
205
|
+
name: selected,
|
|
206
|
+
team_id: bestCert.ou ?? fallbackTeamId,
|
|
207
|
+
team_name: bestCert.org,
|
|
208
|
+
expires_at: new Date(bestCert.validToMs).toISOString(),
|
|
209
|
+
reason: null,
|
|
210
|
+
expiry_reason: null,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
87
213
|
/** Read-only macOS/Xcode facts; probes never select Xcode, install runtimes, or accept licenses. */
|
|
88
214
|
export function macReadiness(options = {}) {
|
|
89
215
|
const run = options.run ?? runDefault(options.path);
|
|
@@ -127,6 +253,7 @@ export function macReadiness(options = {}) {
|
|
|
127
253
|
return [];
|
|
128
254
|
return [volumeRefusal(`${runtime.platform} ${runtime.version ?? runtime.identifier} simulator runtime`, runtime.disk)];
|
|
129
255
|
})];
|
|
256
|
+
const signingIdentity = probeMacSigningIdentity(run);
|
|
130
257
|
return {
|
|
131
258
|
product_version: macVersion,
|
|
132
259
|
product_build: build.ok ? firstLine(build.output) : null,
|
|
@@ -139,6 +266,7 @@ export function macReadiness(options = {}) {
|
|
|
139
266
|
disk: { home: homeDisk, checkout_build: checkoutDisk },
|
|
140
267
|
disk_policy: { floor_pct: floorPct, source: "machine cache floor" },
|
|
141
268
|
readiness_refusals: { build: buildRefusals, simulators: simulatorRefusals },
|
|
269
|
+
signing_identity: signingIdentity,
|
|
142
270
|
capabilities: {
|
|
143
271
|
mac: { ok: !!macVersion, version: macVersion },
|
|
144
272
|
architecture: { ok: !!machineArch, version: machineArch },
|
package/dist/merge-train.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { loadGateQuarantines } from "./gate-quarantines.js";
|
|
2
2
|
import { importFailingGateReports } from "./gate-test-reports.js";
|
|
3
|
-
import { existsSync, mkdirSync,
|
|
3
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { randomBytes } from "node:crypto";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
6
|
import { agentRef } from "./config.js";
|
|
@@ -14,10 +14,8 @@ export const CLI_VERSION_CONFLICT_FILES = [
|
|
|
14
14
|
"packages/cli/package.json",
|
|
15
15
|
"packages/cli/src/version.ts",
|
|
16
16
|
];
|
|
17
|
-
export const PG_BASELINE_CONFLICT_FILE = "apps/api/pg-migrations/0001_baseline.sql";
|
|
18
17
|
export const MECHANICALLY_RESOLVABLE_CONFLICT_FILES = [
|
|
19
18
|
...CLI_VERSION_CONFLICT_FILES,
|
|
20
|
-
PG_BASELINE_CONFLICT_FILE,
|
|
21
19
|
];
|
|
22
20
|
const MAX_RE_GATE_ATTEMPTS = 3;
|
|
23
21
|
const SHA_RE = /^[0-9a-f]{7,64}$/i;
|
|
@@ -354,25 +352,6 @@ async function tryResolveMechanicalMergeConflicts(worktreeDir, entry, conflictin
|
|
|
354
352
|
return false;
|
|
355
353
|
}
|
|
356
354
|
}
|
|
357
|
-
if (conflictingFiles.includes(PG_BASELINE_CONFLICT_FILE)) {
|
|
358
|
-
// This file is generated from the complete SQLite migration set. Keep the current
|
|
359
|
-
// accumulated baseline while merging each unit; the post-batch generator below writes
|
|
360
|
-
// the authoritative baseline after every included migration has landed.
|
|
361
|
-
const ours = await runner("git", ["-C", worktreeDir, "checkout", "--ours", "--", PG_BASELINE_CONFLICT_FILE], {
|
|
362
|
-
cwd: worktreeDir,
|
|
363
|
-
env,
|
|
364
|
-
timeoutMs: 30_000,
|
|
365
|
-
});
|
|
366
|
-
if (ours.status !== 0)
|
|
367
|
-
return false;
|
|
368
|
-
const add = await runner("git", ["-C", worktreeDir, "add", "--", PG_BASELINE_CONFLICT_FILE], {
|
|
369
|
-
cwd: worktreeDir,
|
|
370
|
-
env,
|
|
371
|
-
timeoutMs: 30_000,
|
|
372
|
-
});
|
|
373
|
-
if (add.status !== 0)
|
|
374
|
-
return false;
|
|
375
|
-
}
|
|
376
355
|
const remaining = await runner("git", ["-C", worktreeDir, "diff", "--name-only", "--diff-filter=U"], {
|
|
377
356
|
cwd: worktreeDir,
|
|
378
357
|
env,
|
|
@@ -430,9 +409,6 @@ async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeC
|
|
|
430
409
|
export function cliVersionBumpRequired(paths) {
|
|
431
410
|
return paths.some((path) => path.startsWith("packages/cli/") || path.startsWith("packages/skill"));
|
|
432
411
|
}
|
|
433
|
-
export function pgBaselineRefreshRequired(paths) {
|
|
434
|
-
return paths.some((path) => path.startsWith("apps/api/migrations/") && path.endsWith(".sql"));
|
|
435
|
-
}
|
|
436
412
|
/**
|
|
437
413
|
* Executes a claimed merge-train gate job: merges queued approved heads onto origin/<target>
|
|
438
414
|
* in order, leaves conflicting units out, runs the configured gate under complete-suite lock,
|
|
@@ -531,48 +507,6 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
|
531
507
|
},
|
|
532
508
|
};
|
|
533
509
|
}
|
|
534
|
-
// SQLite migrations from every included unit land together. Regenerate the PostgreSQL
|
|
535
|
-
// baseline once from that complete merged tree before running the gate, then commit the
|
|
536
|
-
// generated file into the exact candidate that the gate verifies.
|
|
537
|
-
await h.runStep("refresh merged PostgreSQL baseline", async () => {
|
|
538
|
-
const changed = await h.runner("git", ["-C", h.worktreeDir, "diff", "--name-only", baseSha, "HEAD"], {
|
|
539
|
-
cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
|
|
540
|
-
});
|
|
541
|
-
if (changed.status !== 0)
|
|
542
|
-
throw new Error(`could not inspect merged migration paths: ${(changed.stderr || changed.stdout).trim().slice(0, 300)}`);
|
|
543
|
-
if (!pgBaselineRefreshRequired(changed.stdout.split(/\r?\n/).filter(Boolean)))
|
|
544
|
-
return 0;
|
|
545
|
-
const apiPackage = JSON.parse(readFileSync(join(h.worktreeDir, "apps/api/package.json"), "utf8"));
|
|
546
|
-
const baselineGenerator = apiPackage.scripts?.["pg:generate-baseline"];
|
|
547
|
-
if (typeof baselineGenerator !== "string") {
|
|
548
|
-
h.onLogLine("no PostgreSQL baseline generator in this tree; skipping refresh");
|
|
549
|
-
return 0;
|
|
550
|
-
}
|
|
551
|
-
const generate = await h.runner("npm", ["run", "pg:generate-baseline", "-w", "apps/api"], {
|
|
552
|
-
cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
|
|
553
|
-
});
|
|
554
|
-
if (generate.status !== 0)
|
|
555
|
-
throw new Error(`PostgreSQL baseline generation failed: ${(generate.stderr || generate.stdout).trim().slice(0, 500)}`);
|
|
556
|
-
h.onLogLine(generate.stdout.trim());
|
|
557
|
-
const pending = await h.runner("git", ["-C", h.worktreeDir, "diff", "--quiet", "--", "apps/api/pg-migrations/0001_baseline.sql"], {
|
|
558
|
-
cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
|
|
559
|
-
});
|
|
560
|
-
if (pending.status === 1) {
|
|
561
|
-
const add = await h.runner("git", ["-C", h.worktreeDir, "add", "--", "apps/api/pg-migrations/0001_baseline.sql"], {
|
|
562
|
-
cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
|
|
563
|
-
});
|
|
564
|
-
if (add.status !== 0)
|
|
565
|
-
throw new Error(`could not stage generated PostgreSQL baseline: ${(add.stderr || add.stdout).trim().slice(0, 300)}`);
|
|
566
|
-
const commit = await h.runner("git", ["-C", h.worktreeDir, "commit", "-m", "chore(api): refresh PostgreSQL baseline after migration batch"], {
|
|
567
|
-
cwd: h.worktreeDir, env: gitEnv, timeoutMs: 30_000,
|
|
568
|
-
});
|
|
569
|
-
if (commit.status !== 0)
|
|
570
|
-
throw new Error(`could not commit generated PostgreSQL baseline: ${(commit.stderr || commit.stdout).trim().slice(0, 300)}`);
|
|
571
|
-
}
|
|
572
|
-
else if (pending.status !== 0)
|
|
573
|
-
throw new Error(`could not check generated PostgreSQL baseline changes: ${(pending.stderr || pending.stdout).trim().slice(0, 300)}`);
|
|
574
|
-
return 0;
|
|
575
|
-
}, () => 0);
|
|
576
510
|
// The published CLI version identifies an immutable source tree. When this train lands
|
|
577
511
|
// CLI or skill changes, bump the version before calculating the candidate head and gate.
|
|
578
512
|
await h.runStep("bump merged CLI version", async () => {
|
|
@@ -955,15 +889,21 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
|
955
889
|
const gateStartedAt = new Date().toISOString();
|
|
956
890
|
const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha, { scanReceipt: true, keepSuccessfulResultOnHeartbeatError: true });
|
|
957
891
|
if (mainRun.status !== 0) {
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
892
|
+
try {
|
|
893
|
+
const imported = await importFailingGateReports({
|
|
894
|
+
dir: join(gateArtifactDir, "test-reports"), project: job.project, trainRunId: trainRun.id, branch: trainRun.target_branch,
|
|
895
|
+
candidate: candidateSha, base: baseSha, startedAt: gateStartedAt, endedAt: new Date().toISOString(),
|
|
896
|
+
creds: h.agentCreds, client: h.agentClient,
|
|
897
|
+
});
|
|
898
|
+
for (const report of imported)
|
|
899
|
+
h.onLogLine(`merge-train ${trainRun.id}: imported ${report.stage} report ${report.runId}`);
|
|
900
|
+
if (!imported.length)
|
|
901
|
+
h.onLogLine(`merge-train ${trainRun.id}: failure has no importable individual test report`);
|
|
902
|
+
}
|
|
903
|
+
catch (error) {
|
|
904
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
905
|
+
h.onLogLine(`merge-train ${trainRun.id}: failed to import failing gate reports; continuing with failure attribution: ${detail}`);
|
|
906
|
+
}
|
|
967
907
|
}
|
|
968
908
|
scanner.push("", true);
|
|
969
909
|
const scanResult = scanner.result();
|
package/dist/scoped-gate.js
CHANGED
|
@@ -162,6 +162,9 @@ export function scopedGatePlan(changedPaths, merge) {
|
|
|
162
162
|
postgresRequiredReasons: [],
|
|
163
163
|
};
|
|
164
164
|
}
|
|
165
|
+
// CLI tests exercise the built entry points and need dist in a fresh checkout.
|
|
166
|
+
if (stageSet.has("cli tests"))
|
|
167
|
+
stageSet.add("cli build");
|
|
165
168
|
const orderedStages = SCOPED_GATE_STAGE_ORDER.filter((stage) => stageSet.has(stage));
|
|
166
169
|
return {
|
|
167
170
|
required: merge.require_gate_receipt && orderedStages.length > 0,
|
package/dist/state.js
CHANGED
|
@@ -64,6 +64,15 @@ export function updateState(agent, change, env = process.env) {
|
|
|
64
64
|
return next;
|
|
65
65
|
}, { busyCode: "state_busy" });
|
|
66
66
|
}
|
|
67
|
+
/** Persist wake-command outcomes across watcher restarts for the next heartbeat. */
|
|
68
|
+
export function recordWakeAttempt(agent, outcome, at = new Date().toISOString(), env = process.env) {
|
|
69
|
+
return updateState(agent, (state) => {
|
|
70
|
+
const prior = state.wake_attempt ?? { consecutive_failures: 0, last_failure_exit_code: null, last_failure_message: null, last_failure_at: null, last_success_at: null };
|
|
71
|
+
return { ...state, wake_attempt: outcome.success
|
|
72
|
+
? { ...prior, consecutive_failures: 0, last_success_at: at }
|
|
73
|
+
: { ...prior, consecutive_failures: prior.consecutive_failures + 1, last_failure_exit_code: outcome.exitCode, last_failure_message: outcome.message.slice(0, 300), last_failure_at: at } };
|
|
74
|
+
}, env);
|
|
75
|
+
}
|
|
67
76
|
/**
|
|
68
77
|
* Replaces the whole state file (first set-up, tests). Anything that changes a field of a state
|
|
69
78
|
* another process may also be writing uses updateState instead: a copy read earlier and written
|
package/dist/usage.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { existsSync
|
|
2
|
-
import { claudeTranscript,
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { claudeTranscript, dshUsageFromRecordsDetailed } from "./harnesses.js";
|
|
3
3
|
import { antigravityUsage } from "./antigravity.js";
|
|
4
4
|
import { scanLinesBackward, TAIL_CHUNK_BYTES } from "./tail-lines.js";
|
|
5
|
+
import { JsonlRecordTooLargeError, readJsonlRecords } from "./jsonl.js";
|
|
5
6
|
/**
|
|
6
7
|
* How far back a usage window may be read. The watcher measures every completed turn, so this is read
|
|
7
8
|
* once per turn rather than per pass, and a turn rarely writes more than a few MB; past the cap the
|
|
@@ -14,15 +15,10 @@ export function claudeSessionWithHookMetadata(sessionId, transcript, provider, r
|
|
|
14
15
|
return { harness: "claude-code", transcript, session_id: sessionId, provider, ...(sameSession && remembered.compactions?.length ? { compactions: remembered.compactions } : {}) };
|
|
15
16
|
}
|
|
16
17
|
const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
|
|
17
|
-
function lines(path) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
catch {
|
|
23
|
-
return [];
|
|
24
|
-
}
|
|
25
|
-
});
|
|
18
|
+
function* lines(path) { yield* readJsonlRecords(path); }
|
|
19
|
+
function transcriptReadReason(error) {
|
|
20
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
21
|
+
return error instanceof JsonlRecordTooLargeError ? message : `could not read session telemetry: ${message}`;
|
|
26
22
|
}
|
|
27
23
|
/** Earliest timestamp actually present in this session's supported metadata. */
|
|
28
24
|
export function sessionStart(session) {
|
|
@@ -61,15 +57,19 @@ export function sessionContext(session, until) {
|
|
|
61
57
|
: session.transcript;
|
|
62
58
|
if (!transcript || !existsSync(transcript))
|
|
63
59
|
return unknownContext(`the session file ${transcript || session.session_id || "(unknown)"} is gone`);
|
|
64
|
-
const rows = lines(transcript);
|
|
65
60
|
if (session.harness === "codex") {
|
|
66
61
|
let latest;
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
62
|
+
try {
|
|
63
|
+
for (const row of lines(transcript)) {
|
|
64
|
+
const p = row.payload;
|
|
65
|
+
const at = typeof row.timestamp === "string" ? row.timestamp : "";
|
|
66
|
+
const tokens = p?.info?.last_token_usage?.total_tokens, window = p?.info?.model_context_window;
|
|
67
|
+
if (row.type === "event_msg" && p?.type === "token_count" && at && Number.isFinite(epoch(at)) && epoch(at) <= epoch(until) && positiveInt(tokens) && positiveInt(window) && (!latest || epoch(at) > epoch(latest.at)))
|
|
68
|
+
latest = { at, tokens, window };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
return unknownContext(transcriptReadReason(error));
|
|
73
73
|
}
|
|
74
74
|
if (!latest)
|
|
75
75
|
return unknownContext("no Codex token_count with a model_context_window is available yet");
|
|
@@ -77,17 +77,22 @@ export function sessionContext(session, until) {
|
|
|
77
77
|
}
|
|
78
78
|
if (session.harness === "claude-code") {
|
|
79
79
|
let latest;
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
latest
|
|
80
|
+
try {
|
|
81
|
+
for (const row of lines(transcript)) {
|
|
82
|
+
const msg = row.message;
|
|
83
|
+
const at = typeof row.timestamp === "string" ? row.timestamp : "";
|
|
84
|
+
if (row.type !== "assistant" || !at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until) || !msg?.usage)
|
|
85
|
+
continue;
|
|
86
|
+
const model = msg.model;
|
|
87
|
+
const window = claudeContextWindow(model);
|
|
88
|
+
const usage = msg.usage;
|
|
89
|
+
const tokens = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.output_tokens ?? 0);
|
|
90
|
+
if (window && positiveInt(tokens) && (!latest || epoch(at) > epoch(latest.at)))
|
|
91
|
+
latest = { at, tokens, window };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
return unknownContext(transcriptReadReason(error));
|
|
91
96
|
}
|
|
92
97
|
if (!latest)
|
|
93
98
|
return unknownContext("no Claude assistant usage for a model with a confirmed context window is available yet");
|
|
@@ -95,16 +100,21 @@ export function sessionContext(session, until) {
|
|
|
95
100
|
}
|
|
96
101
|
if (session.harness === "antigravity") {
|
|
97
102
|
let latest;
|
|
98
|
-
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
103
|
+
try {
|
|
104
|
+
for (const row of lines(transcript)) {
|
|
105
|
+
const at = typeof row.finished_at === "string" ? row.finished_at : "";
|
|
106
|
+
if (!at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until))
|
|
107
|
+
continue;
|
|
108
|
+
const result = row.result;
|
|
109
|
+
const u = result?.usage;
|
|
110
|
+
const tokens = typeof u?.total_tokens === "number" ? u.total_tokens : u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.thinking_tokens ?? 0) + (u.cache_read_tokens ?? 0) : null;
|
|
111
|
+
const window = row.model_context_window ?? row.context_window;
|
|
112
|
+
if (tokens !== null && positiveInt(tokens) && (!latest || at > latest.at))
|
|
113
|
+
latest = { at, tokens, ...(positiveInt(window) ? { window } : {}) };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
return unknownContext(transcriptReadReason(error));
|
|
108
118
|
}
|
|
109
119
|
if (!latest?.window)
|
|
110
120
|
return unknownContext(latest ? "Antigravity model context window has not been confirmed on a real run" : "no Antigravity per-turn usage record is available yet");
|
|
@@ -132,30 +142,41 @@ export function sessionCompactions(session, since, until) {
|
|
|
132
142
|
: session.transcript;
|
|
133
143
|
if (!transcript || !existsSync(transcript))
|
|
134
144
|
return unknownCompactions(`the session file ${transcript || session.session_id || "(unknown)"} is gone`);
|
|
135
|
-
|
|
145
|
+
let boundaryCount = 0;
|
|
146
|
+
const pairedHooks = new Set();
|
|
147
|
+
const hookCompactions = [];
|
|
136
148
|
const sinceAt = epoch(since), untilAt = epoch(until);
|
|
137
149
|
if (!Number.isFinite(sinceAt) || !Number.isFinite(untilAt))
|
|
138
150
|
return unknownCompactions("the unit event time range is invalid");
|
|
139
|
-
for (const row of lines(transcript)) {
|
|
140
|
-
let at;
|
|
141
|
-
if (session.harness === "codex" && row.type === "response_item" && row.payload?.type === "compaction")
|
|
142
|
-
at = typeof row.timestamp === "string" ? row.timestamp : undefined;
|
|
143
|
-
if (session.harness === "claude-code" && row.type === "system" && row.subtype === "compact_boundary")
|
|
144
|
-
at = typeof row.timestamp === "string" ? row.timestamp : undefined;
|
|
145
|
-
const eventAt = at ? epoch(at) : NaN;
|
|
146
|
-
if (Number.isFinite(eventAt) && eventAt >= sinceAt && eventAt < untilAt)
|
|
147
|
-
boundaries.push(eventAt);
|
|
148
|
-
}
|
|
149
151
|
if (session.harness === "claude-code")
|
|
150
152
|
for (const at of session.compactions ?? [])
|
|
151
153
|
if (Number.isFinite(at) && at >= sinceAt && at < untilAt)
|
|
152
154
|
hookCompactions.push(at);
|
|
155
|
+
try {
|
|
156
|
+
for (const row of lines(transcript)) {
|
|
157
|
+
let at;
|
|
158
|
+
if (session.harness === "codex" && row.type === "response_item" && row.payload?.type === "compaction")
|
|
159
|
+
at = typeof row.timestamp === "string" ? row.timestamp : undefined;
|
|
160
|
+
if (session.harness === "claude-code" && row.type === "system" && row.subtype === "compact_boundary")
|
|
161
|
+
at = typeof row.timestamp === "string" ? row.timestamp : undefined;
|
|
162
|
+
const eventAt = at ? epoch(at) : NaN;
|
|
163
|
+
if (Number.isFinite(eventAt) && eventAt >= sinceAt && eventAt < untilAt) {
|
|
164
|
+
boundaryCount++;
|
|
165
|
+
hookCompactions.forEach((hookAt, index) => { if (Math.abs(eventAt - hookAt) <= 30_000)
|
|
166
|
+
pairedHooks.add(index); });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
return unknownCompactions(transcriptReadReason(error));
|
|
172
|
+
}
|
|
153
173
|
if (session.harness !== "codex" && session.harness !== "claude-code")
|
|
154
174
|
return unknownCompactions(`${session.harness} does not expose compaction events in a supported local session format`);
|
|
155
175
|
// Claude's hook and transcript can report the same compaction. Deduplicate only across those
|
|
156
176
|
// two sources so two real transcript boundaries close together are still counted separately.
|
|
157
|
-
|
|
158
|
-
|
|
177
|
+
// Hook metadata is known before scanning the transcript; pair it with transcript boundaries
|
|
178
|
+
// while streaming so memory use does not grow with the full session history.
|
|
179
|
+
return { count: boundaryCount + hookCompactions.filter((_hookAt, index) => !pairedHooks.has(index)).length, reason: null };
|
|
159
180
|
}
|
|
160
181
|
/**
|
|
161
182
|
* Codex rollout: `event_msg` `token_count` events carry running totals, so the window's use is the
|
|
@@ -258,15 +279,26 @@ export function sessionUsage(session, since, until) {
|
|
|
258
279
|
if (session.harness === "claude-code")
|
|
259
280
|
return withProvider(claudeUsage(transcript, since, until));
|
|
260
281
|
if (session.harness === "dsh") {
|
|
261
|
-
|
|
262
|
-
|
|
282
|
+
let tokens, hasInvocationStart;
|
|
283
|
+
try {
|
|
284
|
+
({ usage: tokens, hasInvocationStart } = dshUsageFromRecordsDetailed(lines(session.transcript), since, until));
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
return none(session.harness, transcriptReadReason(error));
|
|
288
|
+
}
|
|
289
|
+
if (!hasInvocationStart)
|
|
263
290
|
return none(session.harness, "DeepSeek Harness events have no local invocation timing, so usage cannot be attributed to this work-unit window");
|
|
264
|
-
const tokens = dshUsage(text, since, until);
|
|
265
291
|
const base = { harness: "dsh", source: "dsh-step-end-events", scope: "session", since, until, tokens: null };
|
|
266
292
|
return tokens.total ? { ...base, tokens } : { ...base, reason: "no step_end usage events in the DeepSeek Harness turn log during this window" };
|
|
267
293
|
}
|
|
268
294
|
if (session.harness === "antigravity") {
|
|
269
|
-
|
|
295
|
+
let tokens;
|
|
296
|
+
try {
|
|
297
|
+
tokens = antigravityUsage(session.transcript, since, until);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
return none(session.harness, transcriptReadReason(error));
|
|
301
|
+
}
|
|
270
302
|
const base = { harness: "antigravity", source: "agy-json-turn-records", scope: "session", since, until, tokens };
|
|
271
303
|
return tokens ? base : { ...base, reason: "no Antigravity usage records in the window" };
|
|
272
304
|
}
|
package/dist/ux-jobs.js
CHANGED
|
@@ -1543,20 +1543,35 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}, resume, c
|
|
|
1543
1543
|
}
|
|
1544
1544
|
}
|
|
1545
1545
|
}
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1546
|
+
try {
|
|
1547
|
+
const { res: seedRes } = await runLockedStep("seed", npmBin, ["run", "ux:seed"], { timeoutMs: 300_000 });
|
|
1548
|
+
if (seedRes.status !== 0)
|
|
1549
|
+
return seedRes.status ?? 1;
|
|
1550
|
+
if (job.task) {
|
|
1551
|
+
const { res: taskRes } = await runLockedStep("task", npmBin, ["run", "ux:task", "--", job.task], { timeoutMs: 600_000 });
|
|
1552
|
+
if (taskRes.status !== 0)
|
|
1553
|
+
return taskRes.status ?? 1;
|
|
1554
|
+
}
|
|
1555
|
+
if (job.compare_screen) {
|
|
1556
|
+
const { res: compareRes } = await runLockedStep("compare", npmBin, ["run", "ux:compare", "--", job.compare_screen, "--unit", String(job.work_unit_number), "--widths", "1440,375"], { timeoutMs: 600_000 });
|
|
1557
|
+
if (compareRes.status !== 0)
|
|
1558
|
+
return compareRes.status ?? 1;
|
|
1559
|
+
}
|
|
1560
|
+
return 0;
|
|
1553
1561
|
}
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
if (
|
|
1557
|
-
|
|
1562
|
+
finally {
|
|
1563
|
+
// Older historical checkouts used D1 and have no PostgreSQL fixture to drop.
|
|
1564
|
+
if (existsSync(join(jobWorktreeDir, "scripts", "ux-postgres.mjs"))) {
|
|
1565
|
+
// Cleanup is job-scoped and must still run after cancellation or lease loss.
|
|
1566
|
+
const res = await diagnosticRunner("node", ["scripts/ux-console.mjs", "cleanup"], {
|
|
1567
|
+
cwd: jobWorktreeDir, env: lockedEnv, timeoutMs: 60_000, signal: new AbortController().signal,
|
|
1568
|
+
onStdoutChunk: chunk => lockContext?.onOutput?.(chunk),
|
|
1569
|
+
onStderrChunk: chunk => lockContext?.onOutput?.(chunk),
|
|
1570
|
+
});
|
|
1571
|
+
if (res.status !== 0)
|
|
1572
|
+
throw stepFailure("UX PostgreSQL fixture cleanup", res);
|
|
1573
|
+
}
|
|
1558
1574
|
}
|
|
1559
|
-
return 0;
|
|
1560
1575
|
}
|
|
1561
1576
|
finally {
|
|
1562
1577
|
if (heartbeatTimer)
|
package/dist/version.js
CHANGED