@bridge_gpt/mcp-server 0.2.72 → 0.2.73
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/README.md +5 -5
- package/build/agent-launchers/claude-executor-adapter.js +3 -0
- package/build/agents.generated.js +6 -6
- package/build/bridge-permissions.js +27 -0
- package/build/ci-system-detection.js +50 -0
- package/build/ci-trigger-adapters.js +631 -0
- package/build/ci-trigger-install.js +106 -0
- package/build/codex-launcher-pin.js +33 -2
- package/build/codex-skill-adapter.js +3 -1
- package/build/command-host.js +33 -0
- package/build/commands.generated.js +7 -6
- package/build/conductor/bridge-api-client.js +842 -35
- package/build/conductor/bring-up-facts.js +18 -5
- package/build/conductor/command-drift-production.js +42 -17
- package/build/conductor/command-drift.js +47 -0
- package/build/conductor/declare-blocked.js +554 -0
- package/build/conductor/doctor.js +106 -21
- package/build/conductor/driver-commands.js +141 -0
- package/build/conductor/driver-guard.js +277 -0
- package/build/conductor/driver-lapse.js +321 -0
- package/build/conductor/driver-register.js +176 -0
- package/build/conductor/driver-release.js +174 -0
- package/build/conductor/driver-session-state.js +315 -0
- package/build/conductor/epic-branch-ci-inspection.js +222 -29
- package/build/conductor/epic-implementer-cli.js +166 -15
- package/build/conductor/epic-server-database.js +162 -0
- package/build/conductor/epic-server-guidance.js +278 -0
- package/build/conductor/epic-server-journal.js +239 -0
- package/build/conductor/epic-server-processes.js +324 -0
- package/build/conductor/epic-server-recipe.js +397 -0
- package/build/conductor/epic-server-runtime.js +1207 -0
- package/build/conductor/epic-server-sfcc.js +107 -0
- package/build/conductor/epic-server-state.js +427 -0
- package/build/conductor/epic-server.js +594 -0
- package/build/conductor/gate-discovery.js +150 -5
- package/build/conductor/gate-settings-review.js +224 -4
- package/build/conductor/launch-need-probes.js +6 -53
- package/build/conductor/launch-plan.js +313 -156
- package/build/conductor/prerequisite-inputs.js +879 -45
- package/build/conductor/readiness-assessment.js +16 -1
- package/build/conductor/readiness-cli.js +20 -9
- package/build/conductor/readiness-prerequisites.js +28 -9
- package/build/conductor/readiness-sections.js +133 -126
- package/build/conductor/readiness.js +1 -1
- package/build/conductor/recovery-cli.js +13 -2
- package/build/conductor/tools.js +6 -5
- package/build/conductor/wait-run-attention.js +2 -2
- package/build/conductor/wait-run-cli.js +208 -22
- package/build/conductor/worker-database-doctor-inspector.js +33 -2
- package/build/conductor/worker-setup-tally.js +27 -0
- package/build/credential-store.js +71 -1
- package/build/dependency-install-declarations.js +55 -0
- package/build/docs.generated.js +2 -2
- package/build/doctor.js +54 -3
- package/build/drive-epic-help.js +21 -2
- package/build/drive-epic.js +1811 -351
- package/build/engine-paths.js +20 -0
- package/build/epic-branch-ci-summary.js +140 -0
- package/build/epic-capability-statement.js +107 -0
- package/build/epic-ci-workflow-drift.js +30 -15
- package/build/epic-ci-workflow-install.js +110 -42
- package/build/epic-ci-workflow-v2.js +274 -0
- package/build/epic-ci-workflow.js +38 -12
- package/build/epic-implementer-bin.js +2101 -44
- package/build/epic-launch-context.js +607 -0
- package/build/epic-server-record.js +273 -0
- package/build/epic-shared/bridge-client.js +11 -3
- package/build/escalation-reachability.js +43 -0
- package/build/executor/ci-fix-test-runs.js +334 -0
- package/build/executor/completion-contract.js +8 -1
- package/build/executor/env.js +59 -22
- package/build/executor/epic-server-context.js +141 -0
- package/build/executor/gate-qualification-job.js +127 -26
- package/build/executor/http-client.js +52 -5
- package/build/executor/job-runner.js +423 -69
- package/build/executor/observation.js +8 -0
- package/build/executor/pre-pr-checks.js +363 -0
- package/build/executor/prompt-spec.js +114 -2
- package/build/executor/reconcile-overlap-job.js +5 -3
- package/build/executor/required-work-diagnostics.js +4 -2
- package/build/executor/required-work-ledger.js +936 -38
- package/build/executor/results.js +58 -0
- package/build/executor/terminal-mutation.js +8 -0
- package/build/executor/worker-command.js +72 -3
- package/build/executor/worker-database-config.js +281 -0
- package/build/executor/worker-database-target.js +16 -12
- package/build/executor/worker-database.js +320 -101
- package/build/executor/worker-finalization.js +7 -1
- package/build/executor/worker-resources.js +25 -3
- package/build/executor/worker-verification-guidance.js +18 -3
- package/build/executor/worktree.js +20 -1
- package/build/executor-launch.js +54 -2
- package/build/generated-assets-catalog.js +2 -2
- package/build/index.js +664 -335
- package/build/init.js +26 -11
- package/build/install-bridge-conductor-answers.js +465 -0
- package/build/install-bridge-conductor-apply.js +259 -0
- package/build/install-bridge-conductor-assessment.js +895 -0
- package/build/install-bridge-conductor-compact.js +161 -0
- package/build/install-bridge-conductor-contracts.js +63 -0
- package/build/install-bridge-conductor-gate.js +1197 -196
- package/build/install-bridge-conductor-setup.js +535 -79
- package/build/install-bridge-conductor.js +2885 -560
- package/build/install-bridge.js +199 -21
- package/build/install-maintenance.js +26 -3
- package/build/launcher-config-inspection.js +162 -1
- package/build/mcp-grant-candidates.js +767 -0
- package/build/mcp-grant-doctor.js +63 -0
- package/build/mcp-grant.js +288 -0
- package/build/mcp-host-targets.js +8 -0
- package/build/mcp-identity.js +23 -0
- package/build/mcp-invoke.js +126 -13
- package/build/mcp-presets.js +107 -0
- package/build/mcp-provisioning.js +134 -2
- package/build/mcp-registration-doctor.js +31 -2
- package/build/mcp-server-invocation.js +6 -1
- package/build/merge-workflow-install.js +234 -109
- package/build/pipelines.generated.js +5 -5
- package/build/plan-discovery.js +97 -4
- package/build/plan-execution-ledger.js +100 -7
- package/build/plan-generation-io.js +262 -0
- package/build/plan-generation.js +424 -0
- package/build/plane/build-freshness.js +6 -1
- package/build/plane/cli.js +75 -9
- package/build/plane/plane-freshness.js +17 -0
- package/build/plane/preflight.js +50 -10
- package/build/plane/shutdown.js +19 -0
- package/build/plane/terminal-run-cleanup.js +18 -4
- package/build/printed-remedy-commands.js +206 -12
- package/build/readiness-check.js +77 -0
- package/build/readiness-prerequisites.generated.js +122 -14
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +38 -0
- package/build/run-unit-tests-launcher.js +8 -1
- package/build/setup-epic.js +1190 -196
- package/build/setup-progress.js +44 -0
- package/build/setup-question.js +122 -4
- package/build/third-party-mcp-targets.js +30 -0
- package/build/ticket-delivery-enrollment.js +9 -0
- package/build/upgrade-cli.js +85 -2
- package/build/v2-readiness-requirements.js +28 -1
- package/build/version.generated.js +3 -3
- package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
- package/docs/epic-implementer/getting-started.md +3 -1
- package/docs/epic-implementer/self-hosting.md +14 -1
- package/package.json +2 -2
|
@@ -261,40 +261,92 @@ function makeRow(id, label, state, detail) {
|
|
|
261
261
|
...(state === "healthy" ? {} : { runbook: WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION }),
|
|
262
262
|
};
|
|
263
263
|
}
|
|
264
|
-
|
|
264
|
+
/** The configured role, for technical details; a generic phrase when doctor was not told one. */
|
|
265
|
+
function configuredRole(config) {
|
|
266
|
+
// No declaration passed at all (the launch advisory, which still inspects the
|
|
267
|
+
// Bridge seed): keep the wording it always had. The inspector uses the same seed.
|
|
268
|
+
if (config === undefined)
|
|
269
|
+
return "bridge_epic_worker";
|
|
270
|
+
return config.status === "configured" && config.workerRole ? config.workerRole : "the worker role";
|
|
271
|
+
}
|
|
272
|
+
/** An informational row for a check that does not apply. Nothing was probed. */
|
|
273
|
+
function notConfiguredRow(id, label) {
|
|
274
|
+
return {
|
|
275
|
+
...makeRow(id, label, "healthy", "Not configured — no worker database is expected for this project"),
|
|
276
|
+
not_configured: true,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
/** A row for a declaration that could not be read. Warning treatment; nothing was probed. */
|
|
280
|
+
function unreadableConfigRow(id, label) {
|
|
281
|
+
return makeRow(id, label, "unknown", "Couldn't check — the worker database setting could not be read");
|
|
282
|
+
}
|
|
283
|
+
const NOT_CONFIGURED_LABELS = [
|
|
284
|
+
["worker-db-role", "worker role"],
|
|
285
|
+
["worker-db-boundary", "protected-database boundary"],
|
|
286
|
+
["worker-db-alembic", "operator-checkout Alembic"],
|
|
287
|
+
["worker-db-leftovers", "worker databases"],
|
|
288
|
+
["worker-db-unverifiable", "unverifiable worker databases"],
|
|
289
|
+
["worker-db-harness", "conductor_harness databases"],
|
|
290
|
+
];
|
|
291
|
+
/** True when the declaration says a disposable database is expected and was read. */
|
|
292
|
+
function isDisposableConfig(config) {
|
|
293
|
+
return config?.status === "configured" && config.mode === "disposable_postgres";
|
|
294
|
+
}
|
|
295
|
+
function roleRow(role, config) {
|
|
296
|
+
if (config?.status === "unreadable")
|
|
297
|
+
return unreadableConfigRow("worker-db-role", "worker role");
|
|
298
|
+
if (config !== undefined && !isDisposableConfig(config))
|
|
299
|
+
return notConfiguredRow("worker-db-role", "worker role");
|
|
300
|
+
const name = configuredRole(config);
|
|
265
301
|
const r = (role ?? {});
|
|
266
302
|
let state = safeState(r.state);
|
|
267
303
|
const category = safeCategory(r.category);
|
|
268
304
|
let detail;
|
|
269
305
|
if (state === "healthy") {
|
|
270
|
-
detail =
|
|
306
|
+
detail = `${name} exists with the expected attributes and no elevating memberships`;
|
|
271
307
|
}
|
|
272
308
|
else if (state === "unsafe") {
|
|
273
309
|
detail =
|
|
274
310
|
category === "role_missing"
|
|
275
|
-
?
|
|
276
|
-
:
|
|
311
|
+
? `${name} does not exist`
|
|
312
|
+
: `${name} attributes or memberships differ from the expected least-privilege set`;
|
|
277
313
|
}
|
|
278
314
|
else if (category === "role_missing") {
|
|
279
315
|
// A definitive "missing" answer is actionable, not unknown.
|
|
280
316
|
state = "unsafe";
|
|
281
|
-
detail =
|
|
317
|
+
detail = `${name} does not exist`;
|
|
282
318
|
}
|
|
283
319
|
else {
|
|
284
320
|
detail = `unknown — ${describeUnavailableCategory(category)}`;
|
|
285
321
|
}
|
|
286
322
|
return makeRow("worker-db-role", "worker role", state, detail);
|
|
287
323
|
}
|
|
288
|
-
function boundaryRow(boundary) {
|
|
324
|
+
function boundaryRow(boundary, config) {
|
|
325
|
+
const label = config === undefined ? "bridgeapi boundary" : "protected-database boundary";
|
|
326
|
+
if (config?.status === "unreadable")
|
|
327
|
+
return unreadableConfigRow("worker-db-boundary", label);
|
|
328
|
+
if (config !== undefined && !isDisposableConfig(config))
|
|
329
|
+
return notConfiguredRow("worker-db-boundary", label);
|
|
289
330
|
const b = (boundary ?? {});
|
|
290
331
|
const state = safeState(b.state);
|
|
291
332
|
const category = safeCategory(b.category);
|
|
333
|
+
if (config === undefined) {
|
|
334
|
+
// No declaration passed (the launch advisory still inspects the Bridge seed): the wording it always had.
|
|
335
|
+
const legacy = state === "healthy"
|
|
336
|
+
? "bridge_epic_worker is refused on bridgeapi"
|
|
337
|
+
: state === "unsafe"
|
|
338
|
+
? "UNSAFE — bridge_epic_worker can connect to bridgeapi"
|
|
339
|
+
: `unknown — ${category === "boundary_unknown" ? "the bridgeapi refusal could not be confirmed" : describeUnavailableCategory(category)}`;
|
|
340
|
+
return makeRow("worker-db-boundary", label, state, legacy);
|
|
341
|
+
}
|
|
342
|
+
const name = configuredRole(config);
|
|
343
|
+
const protectedNames = config.protectedDatabases.length > 0 ? config.protectedDatabases.join(", ") : "the protected databases";
|
|
292
344
|
const detail = state === "healthy"
|
|
293
|
-
?
|
|
345
|
+
? `${name} is refused on ${protectedNames}`
|
|
294
346
|
: state === "unsafe"
|
|
295
|
-
?
|
|
296
|
-
: `unknown — ${category === "boundary_unknown" ? "the
|
|
297
|
-
return makeRow("worker-db-boundary",
|
|
347
|
+
? `UNSAFE — ${name} can connect to a protected database (${protectedNames})`
|
|
348
|
+
: `unknown — ${category === "boundary_unknown" ? "the protected-database refusal could not be confirmed" : describeUnavailableCategory(category)}`;
|
|
349
|
+
return makeRow("worker-db-boundary", label, state, detail);
|
|
298
350
|
}
|
|
299
351
|
function alembicRow(alembic) {
|
|
300
352
|
const a = (alembic ?? {});
|
|
@@ -307,8 +359,8 @@ function alembicRow(alembic) {
|
|
|
307
359
|
: state === "unsafe"
|
|
308
360
|
? cause
|
|
309
361
|
? `the operator checkout's offline migration check failed: ${MIGRATION_CAUSE_LABELS[cause]} (cause: ${cause})`
|
|
310
|
-
: "the operator checkout's
|
|
311
|
-
: "unknown — the operator checkout's offline migration check could not be completed";
|
|
362
|
+
: "the operator checkout's migration launcher is missing"
|
|
363
|
+
: "unknown — the operator checkout's offline migration check is not declared or could not be completed";
|
|
312
364
|
return { ...makeRow("worker-db-alembic", "operator-checkout Alembic", state, detail), ...(cause ? { cause } : {}) };
|
|
313
365
|
}
|
|
314
366
|
function safeNameList(value, redacted) {
|
|
@@ -404,7 +456,22 @@ function inventoryRows(inventory) {
|
|
|
404
456
|
];
|
|
405
457
|
}
|
|
406
458
|
/** Project a (possibly hostile or malformed) inspection into the sanitized advisory section. */
|
|
407
|
-
export function buildWorkerDatabaseDoctorSection(inspection) {
|
|
459
|
+
export function buildWorkerDatabaseDoctorSection(inspection, config) {
|
|
460
|
+
// BAPI-1598: a declaration that says no database is expected, or that could not
|
|
461
|
+
// be read, never reaches an inspection — every row says so and nothing is probed.
|
|
462
|
+
if (config !== undefined && !isDisposableConfig(config)) {
|
|
463
|
+
const unreadable = config.status === "unreadable";
|
|
464
|
+
return {
|
|
465
|
+
advisory: true,
|
|
466
|
+
owner: WORKER_DATABASE_DOCTOR_OWNER,
|
|
467
|
+
runbook: WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION,
|
|
468
|
+
rows: NOT_CONFIGURED_LABELS.map(([id, label]) => ({
|
|
469
|
+
...(unreadable ? unreadableConfigRow(id, label) : notConfiguredRow(id, label)),
|
|
470
|
+
duration_ms: 0,
|
|
471
|
+
})),
|
|
472
|
+
inventory: { state: "unknown" },
|
|
473
|
+
};
|
|
474
|
+
}
|
|
408
475
|
const insp = (inspection ?? {});
|
|
409
476
|
const inventory = inspection ? sanitizeInventory(insp.inventory) : { state: "unknown" };
|
|
410
477
|
return {
|
|
@@ -412,8 +479,8 @@ export function buildWorkerDatabaseDoctorSection(inspection) {
|
|
|
412
479
|
owner: WORKER_DATABASE_DOCTOR_OWNER,
|
|
413
480
|
runbook: WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION,
|
|
414
481
|
rows: [
|
|
415
|
-
roleRow(insp.role),
|
|
416
|
-
boundaryRow(insp.boundary),
|
|
482
|
+
roleRow(insp.role, config),
|
|
483
|
+
boundaryRow(insp.boundary, config),
|
|
417
484
|
alembicRow(insp.alembic),
|
|
418
485
|
...inventoryRows(inventory),
|
|
419
486
|
].map((row) => ({ ...row, duration_ms: inspection?.timings?.[row.id] ?? elapsedMs(monotonicNow()) })),
|
|
@@ -429,10 +496,14 @@ export function buildWorkerDatabaseDoctorSection(inspection) {
|
|
|
429
496
|
* `timeout`/`error` classification — never the thrown value — so a caller can
|
|
430
497
|
* say that the inspection failed without echoing exception text.
|
|
431
498
|
*/
|
|
432
|
-
export async function collectWorkerDatabaseDoctorSection(inspect, timeoutMs = WORKER_DATABASE_DOCTOR_TIMEOUT_MS, onFailure) {
|
|
499
|
+
export async function collectWorkerDatabaseDoctorSection(inspect, timeoutMs = WORKER_DATABASE_DOCTOR_TIMEOUT_MS, onFailure, config) {
|
|
500
|
+
// BAPI-1598: nothing to inspect when no database is expected or the setting is unreadable.
|
|
501
|
+
if (config !== undefined && !isDisposableConfig(config)) {
|
|
502
|
+
return buildWorkerDatabaseDoctorSection(null, config);
|
|
503
|
+
}
|
|
433
504
|
const started = monotonicNow();
|
|
434
505
|
const failedSection = () => {
|
|
435
|
-
const section = buildWorkerDatabaseDoctorSection(null);
|
|
506
|
+
const section = buildWorkerDatabaseDoctorSection(null, config);
|
|
436
507
|
return { ...section, rows: section.rows.map((row) => ({ ...row, duration_ms: elapsedMs(started) })) };
|
|
437
508
|
};
|
|
438
509
|
let timer;
|
|
@@ -441,10 +512,10 @@ export async function collectWorkerDatabaseDoctorSection(inspect, timeoutMs = WO
|
|
|
441
512
|
timer = setTimeout(() => resolve(null), timeoutMs);
|
|
442
513
|
timer.unref?.();
|
|
443
514
|
});
|
|
444
|
-
const inspection = await Promise.race([Promise.resolve().then(inspect), timeout]);
|
|
515
|
+
const inspection = await Promise.race([Promise.resolve().then(() => inspect(config)), timeout]);
|
|
445
516
|
if (inspection === null)
|
|
446
517
|
onFailure?.("timeout");
|
|
447
|
-
return inspection === null ? failedSection() : buildWorkerDatabaseDoctorSection(inspection);
|
|
518
|
+
return inspection === null ? failedSection() : buildWorkerDatabaseDoctorSection(inspection, config);
|
|
448
519
|
}
|
|
449
520
|
catch {
|
|
450
521
|
onFailure?.("error");
|
|
@@ -477,6 +548,10 @@ export function formatWorkerDatabaseDoctorSection(section) {
|
|
|
477
548
|
lines.push("──────────────────────────────────────");
|
|
478
549
|
for (const row of section.rows) {
|
|
479
550
|
const state = safeState(row.state);
|
|
551
|
+
if (row.not_configured === true) {
|
|
552
|
+
lines.push(`${row.label.padEnd(30)} [INFO] ${row.detail}`);
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
480
555
|
lines.push(`${row.label.padEnd(30)} ${WORKER_DB_STATE_TAG[state]} ${state} — ${row.detail}`);
|
|
481
556
|
if (state !== "healthy") {
|
|
482
557
|
lines.push(` → ${WORKER_DATABASE_DOCTOR_OWNER}: see ${WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION}`);
|
|
@@ -501,7 +576,8 @@ export function formatWorkerDatabaseDoctorSection(section) {
|
|
|
501
576
|
* therefore resolve credentials themselves (CLAUDE.md "Shell-Spawned Credential
|
|
502
577
|
* Resolution"): the four BAPI-872 recovery verbs, the six run-addressed repair
|
|
503
578
|
* verbs (BAPI-1154's three and BAPI-1176's three), and BAPI-1300's parked-child
|
|
504
|
-
* continuation pair,
|
|
579
|
+
* continuation pair, BAPI-1557's `prerequisite-inputs`, and BAPI-1642's driver-supervision
|
|
580
|
+
* commands. `.mcp.json` env is invisible to
|
|
505
581
|
* them — only `BAPI_API_KEY` in the parent env and the user-scoped credential
|
|
506
582
|
* store count.
|
|
507
583
|
*/
|
|
@@ -523,6 +599,11 @@ export const CREDENTIALED_RECOVERY_COMMANDS = [
|
|
|
523
599
|
"wait-run",
|
|
524
600
|
// BAPI-1557: reads stored tickets and writes private local scanner inputs.
|
|
525
601
|
"prerequisite-inputs",
|
|
602
|
+
// BAPI-1642: driver supervision. The Stop-hook guard itself resolves nothing;
|
|
603
|
+
// its detached lapse FYI goes through `escalate`.
|
|
604
|
+
"driver-register",
|
|
605
|
+
"driver-release",
|
|
606
|
+
"declare-blocked",
|
|
526
607
|
];
|
|
527
608
|
/** Remediation for recovery/repair verbs that cannot resolve Bridge credentials. */
|
|
528
609
|
export const REPAIR_CREDENTIAL_REMEDIATION = "export BAPI_API_KEY in the shell that runs `conductor`, or store a credential for this " +
|
|
@@ -1204,8 +1285,12 @@ export async function buildConductorDoctorReport(deps = {}) {
|
|
|
1204
1285
|
const command_drift = deps.inspectCommandDrift
|
|
1205
1286
|
? await inspectCommandDriftSafe(deps.inspectCommandDrift)
|
|
1206
1287
|
: undefined;
|
|
1288
|
+
let workerDatabaseConfig;
|
|
1289
|
+
if (deps.inspectWorkerDatabase && deps.readWorkerDatabaseConfig) {
|
|
1290
|
+
workerDatabaseConfig = await deps.readWorkerDatabaseConfig().catch(() => ({ status: "unreadable" }));
|
|
1291
|
+
}
|
|
1207
1292
|
const worker_database = deps.inspectWorkerDatabase
|
|
1208
|
-
? await collectWorkerDatabaseDoctorSection(deps.inspectWorkerDatabase, deps.workerDatabaseTimeoutMs ?? WORKER_DATABASE_DOCTOR_TIMEOUT_MS)
|
|
1293
|
+
? await collectWorkerDatabaseDoctorSection(deps.inspectWorkerDatabase, deps.workerDatabaseTimeoutMs ?? WORKER_DATABASE_DOCTOR_TIMEOUT_MS, undefined, workerDatabaseConfig)
|
|
1209
1294
|
: undefined;
|
|
1210
1295
|
return {
|
|
1211
1296
|
ledger,
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one rendering of every command the driver guard prints or recognizes
|
|
3
|
+
* (BAPI-1642): the registered waiter, the `declare-blocked` template, and the
|
|
4
|
+
* `driver-release` exits.
|
|
5
|
+
*
|
|
6
|
+
* The launcher prefix is the same value the project permission rules are
|
|
7
|
+
* written for ({@link resolvePermissionLauncher}): `npx -y @bridge_gpt/mcp-server`
|
|
8
|
+
* by default, or a validated `BAPI_MCP_CLI`. The prefix stays unquoted so the
|
|
9
|
+
* printed command matches those exact-prefix rules; every argument value is
|
|
10
|
+
* single-quoted.
|
|
11
|
+
*
|
|
12
|
+
* RECOGNITION. The Stop hook compares a running task's `command` with the
|
|
13
|
+
* registered waiter byte for byte (`waiter_verified`). Investigation 4 found that
|
|
14
|
+
* Claude Code 2.1.312 reports the command exactly as the agent ran it, quotes
|
|
15
|
+
* included. {@link parseWaiterInvocation} is a deliberately small tokenizer for
|
|
16
|
+
* the near-miss case (`waiter_unrecognized`): plain words and single- or
|
|
17
|
+
* double-quoted words only. Anything with shell operators, substitutions, or
|
|
18
|
+
* escapes is not parsed, never guessed at.
|
|
19
|
+
*/
|
|
20
|
+
import { resolvePermissionLauncher } from "../bridge-permissions.js";
|
|
21
|
+
/** The `--max-minutes` every registered waiter uses. */
|
|
22
|
+
export const DRIVER_WAITER_MAX_MINUTES = 20;
|
|
23
|
+
/** Quote one argument value for a POSIX shell. Values here never contain `'`. */
|
|
24
|
+
export function shellQuote(value) {
|
|
25
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The launcher prefix, or `null` when `BAPI_MCP_CLI` is set but unusable (a
|
|
29
|
+
* quote, a shell operator, or a credential-like value). A null launcher means no
|
|
30
|
+
* waiter can be printed, so registration refuses to arm.
|
|
31
|
+
*/
|
|
32
|
+
export function resolveDriverLauncher(env) {
|
|
33
|
+
const resolved = resolvePermissionLauncher(env);
|
|
34
|
+
return resolved.ok ? resolved.prefix : null;
|
|
35
|
+
}
|
|
36
|
+
/** The exact registered waiter command. */
|
|
37
|
+
export function renderWaiterCommand(launcher, epicRunId, generation) {
|
|
38
|
+
return `${launcher} epic-implementer wait-run --epic-run-id ${shellQuote(epicRunId)} --watch ` +
|
|
39
|
+
`--max-minutes ${DRIVER_WAITER_MAX_MINUTES} --driver-generation ${shellQuote(generation)} --json`;
|
|
40
|
+
}
|
|
41
|
+
/** The unregistered watch waiter, for a host or session with no registration. */
|
|
42
|
+
export function renderPlainWaiterCommand(launcher, epicRunId) {
|
|
43
|
+
return `${launcher} epic-implementer wait-run --epic-run-id ${shellQuote(epicRunId)} --watch ` +
|
|
44
|
+
`--max-minutes ${DRIVER_WAITER_MAX_MINUTES} --json`;
|
|
45
|
+
}
|
|
46
|
+
/** The `declare-blocked` template the block message names; `<…>` are the driver's inputs. */
|
|
47
|
+
export function renderDeclareBlockedTemplate(launcher, epicRunId) {
|
|
48
|
+
return `${launcher} epic-implementer declare-blocked --epic-run-id ${shellQuote(epicRunId)} ` +
|
|
49
|
+
"--ticket-key <TICKET> --entry <1|2|3|4|5|wedge> --requirement '<what is needed>' " +
|
|
50
|
+
"--evidence '<current evidence>' --tried '<verbs already run>'";
|
|
51
|
+
}
|
|
52
|
+
/** One `driver-release` exit. `--reason` comes first so permission rules can tell them apart. */
|
|
53
|
+
export function renderReleaseCommand(launcher, reason, epicRunId) {
|
|
54
|
+
return `${launcher} epic-implementer driver-release --reason ${reason} --epic-run-id ${shellQuote(epicRunId)}`;
|
|
55
|
+
}
|
|
56
|
+
/** A `wait-run` result token (change mode `v1:`, attention mode `a1:`). */
|
|
57
|
+
const WAITER_SINCE_TOKEN = /^(?:v1|a1):[0-9a-f]{16}$/;
|
|
58
|
+
/**
|
|
59
|
+
* True when `command` is the registered waiter exactly, or exactly the
|
|
60
|
+
* registered waiter followed by ` --since '<token>'` with a valid token. The
|
|
61
|
+
* prompt passes the previous result's token on every re-arm, so this is the one
|
|
62
|
+
* structured variant the exact match accepts; nothing else is loosened.
|
|
63
|
+
*/
|
|
64
|
+
export function isRegisteredWaiterCommand(command, waiterCommand) {
|
|
65
|
+
if (command === waiterCommand)
|
|
66
|
+
return true;
|
|
67
|
+
const prefix = `${waiterCommand} --since `;
|
|
68
|
+
if (!command.startsWith(prefix))
|
|
69
|
+
return false;
|
|
70
|
+
const rest = command.slice(prefix.length);
|
|
71
|
+
const token = rest.startsWith("'") && rest.endsWith("'") && rest.length > 2 ? rest.slice(1, -1) : rest;
|
|
72
|
+
return WAITER_SINCE_TOKEN.test(token);
|
|
73
|
+
}
|
|
74
|
+
/** At most this many characters of a task command are parsed. */
|
|
75
|
+
const MAX_PARSED_COMMAND_CHARS = 1000;
|
|
76
|
+
/** A word that needs no quoting and carries no shell meaning. */
|
|
77
|
+
const PLAIN_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
|
|
78
|
+
/**
|
|
79
|
+
* Split a command into words, accepting only plain words and whole single- or
|
|
80
|
+
* double-quoted words with no escapes, expansions or operators inside. Returns
|
|
81
|
+
* `null` for anything else.
|
|
82
|
+
*/
|
|
83
|
+
export function tokenizeSimpleCommand(command) {
|
|
84
|
+
if (command.length === 0 || command.length > MAX_PARSED_COMMAND_CHARS)
|
|
85
|
+
return null;
|
|
86
|
+
const words = [];
|
|
87
|
+
for (const raw of command.trim().split(/[ \t]+/)) {
|
|
88
|
+
if (raw.length === 0)
|
|
89
|
+
continue;
|
|
90
|
+
if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
|
|
91
|
+
const inner = raw.slice(1, -1);
|
|
92
|
+
if (inner.includes("'"))
|
|
93
|
+
return null;
|
|
94
|
+
words.push(inner);
|
|
95
|
+
}
|
|
96
|
+
else if (raw.length >= 2 && raw.startsWith("\"") && raw.endsWith("\"")) {
|
|
97
|
+
const inner = raw.slice(1, -1);
|
|
98
|
+
if (/["$`\\]/.test(inner))
|
|
99
|
+
return null;
|
|
100
|
+
words.push(inner);
|
|
101
|
+
}
|
|
102
|
+
else if (PLAIN_WORD.test(raw)) {
|
|
103
|
+
words.push(raw);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return words.length > 0 ? words : null;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Parse a task command as a `wait-run` invocation and return the run id and
|
|
113
|
+
* generation it names, or `null` when it is not a parseable `epic-implementer
|
|
114
|
+
* wait-run` call carrying both `--epic-run-id` and `--driver-generation`.
|
|
115
|
+
*/
|
|
116
|
+
export function parseWaiterInvocation(command) {
|
|
117
|
+
const words = tokenizeSimpleCommand(command);
|
|
118
|
+
if (!words)
|
|
119
|
+
return null;
|
|
120
|
+
const at = words.indexOf("epic-implementer");
|
|
121
|
+
if (at < 0 || words[at + 1] !== "wait-run")
|
|
122
|
+
return null;
|
|
123
|
+
let epicRunId;
|
|
124
|
+
let generation;
|
|
125
|
+
for (let i = at + 2; i < words.length; i += 1) {
|
|
126
|
+
const word = words[i];
|
|
127
|
+
const [name, inline] = word.includes("=") ? [word.slice(0, word.indexOf("=")), word.slice(word.indexOf("=") + 1)] : [word, undefined];
|
|
128
|
+
if (name !== "--epic-run-id" && name !== "--driver-generation")
|
|
129
|
+
continue;
|
|
130
|
+
const value = inline ?? words[i + 1];
|
|
131
|
+
if (inline === undefined)
|
|
132
|
+
i += 1;
|
|
133
|
+
if (value === undefined)
|
|
134
|
+
return null;
|
|
135
|
+
if (name === "--epic-run-id")
|
|
136
|
+
epicRunId = value;
|
|
137
|
+
else
|
|
138
|
+
generation = value;
|
|
139
|
+
}
|
|
140
|
+
return epicRunId !== undefined && generation !== undefined ? { epicRunId, generation } : null;
|
|
141
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `epic-implementer driver-guard` — the `/drive-epic-run` Stop hook (BAPI-1642).
|
|
3
|
+
*
|
|
4
|
+
* Claude Code runs it at every turn end of a session that invoked
|
|
5
|
+
* `/drive-epic-run` (the hook is declared in that command's frontmatter, so it
|
|
6
|
+
* never runs in any other session). It reads the hook JSON on stdin and decides,
|
|
7
|
+
* locally and within a few seconds, whether the driving session may stop.
|
|
8
|
+
*
|
|
9
|
+
* ALWAYS EXITS 0. Stdout is empty to allow, and exactly
|
|
10
|
+
* `{"decision":"block","reason":"..."}` to block. Any error, timeout, missing
|
|
11
|
+
* field, or unreadable state allows the stop and records why when it safely can.
|
|
12
|
+
* It makes no network call and runs no LLM, git read, or `explain_run`.
|
|
13
|
+
*
|
|
14
|
+
* DECISION ORDER.
|
|
15
|
+
* 1. `BRIDGE_EI_DRIVER_GUARD=off`: allow.
|
|
16
|
+
* 2. No registration for this session: allow, no record, nothing written.
|
|
17
|
+
* 3. Malformed registration: allow (uncertainty). Generation differs from the
|
|
18
|
+
* run's `driver-current.json`: allow, the registration is stale.
|
|
19
|
+
* 4. This generation is released: allow.
|
|
20
|
+
* 5. `background_tasks` missing or malformed: allow, `supervision_unknown`.
|
|
21
|
+
* An older Claude Code without the field is unknown, never "nothing running".
|
|
22
|
+
* 6. A running shell task whose command equals the registered waiter
|
|
23
|
+
* (optionally followed by `--since '<token>'`): allow, `waiter_verified`.
|
|
24
|
+
* The only thing that re-arms the cap.
|
|
25
|
+
* 7. A running task naming `wait-run` with this run and generation but not an
|
|
26
|
+
* exact match: allow, `waiter_unrecognized`. No re-arm.
|
|
27
|
+
* 8. Otherwise block, at most three times per episode. The fourth attempt
|
|
28
|
+
* allows, records `supervision_lapse`, and starts the detached owner FYI;
|
|
29
|
+
* the episode then stays allowed until a verified waiter or a new
|
|
30
|
+
* generation. `stop_hook_active` is never permission on its own.
|
|
31
|
+
*
|
|
32
|
+
* The worker lifecycle hook (`claude-hook.ts`) is separate and unchanged.
|
|
33
|
+
*/
|
|
34
|
+
import { appendFile } from "node:fs/promises";
|
|
35
|
+
import path from "node:path";
|
|
36
|
+
import { BRIDGE_DEFAULT_LAUNCHER } from "../bridge-permissions.js";
|
|
37
|
+
import { isRegisteredWaiterCommand, renderDeclareBlockedTemplate, renderReleaseCommand, parseWaiterInvocation, } from "./driver-commands.js";
|
|
38
|
+
import { closeLapseEpisode, launchLapseFyi, transcribeLapseResult } from "./driver-lapse.js";
|
|
39
|
+
import { DRIVER_GUARD_BLOCK_CAP, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, currentPointerPath, ensurePrivateDir, formatDriverTallyLine, generationFilePath, generationLabel, parseCapState, parseCurrentPointer, parseRegistration, parseReleaseMarker, readDriverJson, registrationPath, resolveDriverStateRoots, withDriverLock, writeDriverJsonAtomic, } from "./driver-session-state.js";
|
|
40
|
+
/** The off switch. `off` (any case) disables the guard; anything else leaves it on. */
|
|
41
|
+
export const DRIVER_GUARD_OFF_ENV = "BRIDGE_EI_DRIVER_GUARD";
|
|
42
|
+
/** The guard's own deadline, under the hook's timeout. Past it, the stop is allowed. */
|
|
43
|
+
export const DRIVER_GUARD_DEADLINE_MS = 4_000;
|
|
44
|
+
/** Hook stdin larger than this is not parsed. */
|
|
45
|
+
export const DRIVER_GUARD_MAX_STDIN_BYTES = 256 * 1024;
|
|
46
|
+
/** How long the runner waits for its own guard_error line after a crash or the deadline. */
|
|
47
|
+
const DRIVER_GUARD_RECORD_GRACE_MS = 500;
|
|
48
|
+
function isRecord(value) {
|
|
49
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
50
|
+
}
|
|
51
|
+
/** The launcher prefix the registered waiter was rendered with. */
|
|
52
|
+
function launcherFromWaiter(waiter) {
|
|
53
|
+
const at = waiter.indexOf(" epic-implementer wait-run ");
|
|
54
|
+
return at > 0 ? waiter.slice(0, at) : BRIDGE_DEFAULT_LAUNCHER;
|
|
55
|
+
}
|
|
56
|
+
/** The corrective message: what is wrong, the exact waiter, then the only other exits. */
|
|
57
|
+
export function renderBlockMessage(registration, attempt) {
|
|
58
|
+
const launcher = launcherFromWaiter(registration.waiter_command);
|
|
59
|
+
return [
|
|
60
|
+
`Supervision is not armed: run ${registration.epic_key} is still active and no waiter is running for ` +
|
|
61
|
+
`this session (guard block ${attempt} of ${DRIVER_GUARD_BLOCK_CAP}).`,
|
|
62
|
+
"Start this exact command as a background task (append --since '<token>' when you have one), then end the turn:",
|
|
63
|
+
registration.waiter_command,
|
|
64
|
+
"If a real stop-list blocker (entries 1-5) or a wedge stops progress, check it first with:",
|
|
65
|
+
renderDeclareBlockedTemplate(launcher, registration.epic_run_id),
|
|
66
|
+
"Filing a blocker never releases the session; keep the waiter running afterwards.",
|
|
67
|
+
"This session may stop without a waiter only after one of:",
|
|
68
|
+
`${renderReleaseCommand(launcher, "done", registration.epic_run_id)} (the run is done or abandoned)`,
|
|
69
|
+
`${renderReleaseCommand(launcher, "handoff", registration.epic_run_id)} (the hand-off report is published)`,
|
|
70
|
+
`${renderReleaseCommand(launcher, "owner", registration.epic_run_id)} (only when the owner explicitly says to stop driving)`,
|
|
71
|
+
].join("\n");
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Classify `background_tasks` against the registration. Never throws. A list
|
|
75
|
+
* that is missing, not an array, or holds an entry whose shape cannot be read is
|
|
76
|
+
* `unknown`: an unreadable entry might be the waiter, so it is never read as
|
|
77
|
+
* "nothing running".
|
|
78
|
+
*/
|
|
79
|
+
export function classifyBackgroundTasks(tasks, registration) {
|
|
80
|
+
if (!Array.isArray(tasks))
|
|
81
|
+
return "unknown";
|
|
82
|
+
let unrecognized = false;
|
|
83
|
+
let unreadable = false;
|
|
84
|
+
for (const task of tasks) {
|
|
85
|
+
if (!isRecord(task) || typeof task.type !== "string" || typeof task.status !== "string" ||
|
|
86
|
+
(task.type === "shell" && typeof task.command !== "string")) {
|
|
87
|
+
unreadable = true;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (task.type !== "shell" || task.status !== "running")
|
|
91
|
+
continue;
|
|
92
|
+
const command = task.command;
|
|
93
|
+
if (isRegisteredWaiterCommand(command, registration.waiter_command))
|
|
94
|
+
return "verified";
|
|
95
|
+
const named = parseWaiterInvocation(command);
|
|
96
|
+
if (named && named.generation === registration.generation &&
|
|
97
|
+
(named.epicRunId === registration.epic_run_id || named.epicRunId === registration.epic_key)) {
|
|
98
|
+
unrecognized = true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return unrecognized ? "unrecognized" : unreadable ? "unknown" : "none";
|
|
102
|
+
}
|
|
103
|
+
async function recordDecision(roots, registration, outcome, now) {
|
|
104
|
+
const fields = {
|
|
105
|
+
decision: outcome.decision, reason: outcome.reason, generation: generationLabel(registration.generation),
|
|
106
|
+
};
|
|
107
|
+
if (outcome.decision === "block")
|
|
108
|
+
fields.attempt = outcome.attempt;
|
|
109
|
+
if (outcome.decision === "allow" && outcome.detail)
|
|
110
|
+
fields.detail = outcome.detail;
|
|
111
|
+
await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", fields, now));
|
|
112
|
+
}
|
|
113
|
+
/** A bounded uncertainty line kept beside the session's guard state when no tally can be trusted. */
|
|
114
|
+
async function recordUncertainty(roots, sessionId, detail, now) {
|
|
115
|
+
const dir = path.join(roots.guardRoot, sessionId);
|
|
116
|
+
await ensurePrivateDir(dir);
|
|
117
|
+
await appendFile(path.join(dir, "guard-uncertain.log"), formatDriverTallyLine("driver-guard", { decision: "allow", reason: "guard_error", detail }, now), { encoding: "utf-8", mode: 0o600 });
|
|
118
|
+
}
|
|
119
|
+
/** Steps 6-8 under the generation's lock: re-arm, or count a block, or lapse. */
|
|
120
|
+
async function decideUnderCap(roots, registration, match, deps, now) {
|
|
121
|
+
const capPath = generationFilePath(roots, registration.session_id, registration.generation, "cap.json");
|
|
122
|
+
const lockPath = generationFilePath(roots, registration.session_id, registration.generation, "lock");
|
|
123
|
+
const locked = await withDriverLock(lockPath, async () => {
|
|
124
|
+
const read = await readDriverJson(capPath);
|
|
125
|
+
const cap = read.state === "ok" ? parseCapState(read.value) : null;
|
|
126
|
+
// A missing or corrupt counter for a registered generation is never a fresh zero.
|
|
127
|
+
if (!cap || cap.generation !== registration.generation) {
|
|
128
|
+
return { decision: "allow", reason: "guard_error", detail: "cap_unreadable" };
|
|
129
|
+
}
|
|
130
|
+
if (match === "verified") {
|
|
131
|
+
if (cap.blocks !== 0 || cap.lapsed) {
|
|
132
|
+
const rearmed = { version: DRIVER_STATE_VERSION, generation: cap.generation, blocks: 0, lapsed: false };
|
|
133
|
+
await writeDriverJsonAtomic(capPath, rearmed);
|
|
134
|
+
}
|
|
135
|
+
// A new episode starts here: a later lapse must send its own FYI.
|
|
136
|
+
if (cap.lapsed)
|
|
137
|
+
await closeLapseEpisode(roots, registration, now).catch(() => undefined);
|
|
138
|
+
return { decision: "allow", reason: "waiter_verified" };
|
|
139
|
+
}
|
|
140
|
+
if (cap.lapsed)
|
|
141
|
+
return { decision: "allow", reason: "lapse_open" };
|
|
142
|
+
if (cap.blocks < DRIVER_GUARD_BLOCK_CAP) {
|
|
143
|
+
const attempt = cap.blocks + 1;
|
|
144
|
+
// Persisted before the block is returned, so a crash cannot hand out a free block.
|
|
145
|
+
await writeDriverJsonAtomic(capPath, { ...cap, blocks: attempt });
|
|
146
|
+
return { decision: "block", reason: "no_waiter", attempt, message: renderBlockMessage(registration, attempt) };
|
|
147
|
+
}
|
|
148
|
+
await writeDriverJsonAtomic(capPath, { ...cap, lapsed: true });
|
|
149
|
+
const launch = await launchLapseFyi(roots, registration, { now, ...deps.lapse }).catch(() => "launch_failed");
|
|
150
|
+
return { decision: "allow", reason: "supervision_lapse", detail: `fyi_${launch}` };
|
|
151
|
+
});
|
|
152
|
+
return locked.state === "held" ? locked.value : { decision: "allow", reason: "guard_error", detail: "lock_contended" };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Decide one Stop event. Pure of process I/O: reads and writes only the
|
|
156
|
+
* driver state files. Errors propagate to {@link runDriverGuardCommand}, which
|
|
157
|
+
* turns every one of them into an allow.
|
|
158
|
+
*/
|
|
159
|
+
export async function evaluateDriverGuard(payload, deps = {}, context = {}) {
|
|
160
|
+
const env = deps.env ?? process.env;
|
|
161
|
+
const now = deps.now ?? (() => new Date());
|
|
162
|
+
if ((env[DRIVER_GUARD_OFF_ENV] ?? "").trim().toLowerCase() === "off")
|
|
163
|
+
return { decision: "allow", reason: "off" };
|
|
164
|
+
if (!isRecord(payload))
|
|
165
|
+
return { decision: "allow", reason: "unregistered" };
|
|
166
|
+
if (payload.hook_event_name !== undefined && payload.hook_event_name !== "Stop") {
|
|
167
|
+
return { decision: "allow", reason: "not_stop" };
|
|
168
|
+
}
|
|
169
|
+
const sessionId = payload.session_id;
|
|
170
|
+
if (typeof sessionId !== "string" || !DRIVER_SESSION_ID_PATTERN.test(sessionId)) {
|
|
171
|
+
return { decision: "allow", reason: "unregistered" };
|
|
172
|
+
}
|
|
173
|
+
// The hook's own session must be the process's session when the host says so.
|
|
174
|
+
const processSession = env.CLAUDE_CODE_SESSION_ID?.trim();
|
|
175
|
+
if (processSession && processSession !== sessionId)
|
|
176
|
+
return { decision: "allow", reason: "unregistered" };
|
|
177
|
+
const roots = resolveDriverStateRoots(deps.homeDir);
|
|
178
|
+
const regRead = await readDriverJson(registrationPath(roots, sessionId));
|
|
179
|
+
if (regRead.state === "absent")
|
|
180
|
+
return { decision: "allow", reason: "unregistered" };
|
|
181
|
+
const registration = regRead.state === "ok" ? parseRegistration(regRead.value) : null;
|
|
182
|
+
if (!registration || registration.session_id !== sessionId) {
|
|
183
|
+
await recordUncertainty(roots, sessionId, "registration_unreadable", now()).catch(() => undefined);
|
|
184
|
+
return { decision: "allow", reason: "guard_error", detail: "registration_unreadable" };
|
|
185
|
+
}
|
|
186
|
+
context.roots = roots;
|
|
187
|
+
context.registration = registration;
|
|
188
|
+
const pointerRead = await readDriverJson(currentPointerPath(roots, registration.epic_key));
|
|
189
|
+
const pointer = pointerRead.state === "ok" ? parseCurrentPointer(pointerRead.value) : null;
|
|
190
|
+
let outcome;
|
|
191
|
+
if (!pointer) {
|
|
192
|
+
outcome = { decision: "allow", reason: "guard_error", detail: "pointer_unreadable" };
|
|
193
|
+
}
|
|
194
|
+
else if (pointer.generation !== registration.generation || pointer.session_id !== sessionId) {
|
|
195
|
+
outcome = { decision: "allow", reason: "stale_registration" };
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
await transcribeLapseResult(roots, registration, now).catch(() => undefined);
|
|
199
|
+
const releaseRead = await readDriverJson(generationFilePath(roots, sessionId, registration.generation, "release.json"));
|
|
200
|
+
const release = releaseRead.state === "ok" ? parseReleaseMarker(releaseRead.value) : null;
|
|
201
|
+
if (release && release.generation === registration.generation) {
|
|
202
|
+
outcome = { decision: "allow", reason: "released", detail: release.reason };
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
const match = classifyBackgroundTasks(payload.background_tasks, registration);
|
|
206
|
+
if (match === "unknown")
|
|
207
|
+
outcome = { decision: "allow", reason: "supervision_unknown" };
|
|
208
|
+
else if (match === "unrecognized")
|
|
209
|
+
outcome = { decision: "allow", reason: "waiter_unrecognized" };
|
|
210
|
+
else
|
|
211
|
+
outcome = await decideUnderCap(roots, registration, match, deps, now);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
context.recorded = true;
|
|
215
|
+
await recordDecision(roots, registration, outcome, now()).catch(() => undefined);
|
|
216
|
+
return outcome;
|
|
217
|
+
}
|
|
218
|
+
/** Read hook stdin, bounded in bytes. */
|
|
219
|
+
async function readProcessStdin(maxBytes) {
|
|
220
|
+
if (process.stdin.isTTY)
|
|
221
|
+
return "";
|
|
222
|
+
const chunks = [];
|
|
223
|
+
let total = 0;
|
|
224
|
+
for await (const chunk of process.stdin) {
|
|
225
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
226
|
+
total += buffer.length;
|
|
227
|
+
if (total > maxBytes)
|
|
228
|
+
throw new Error("stdin too large");
|
|
229
|
+
chunks.push(buffer);
|
|
230
|
+
}
|
|
231
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Run the Stop hook. Always resolves 0. Prints the block JSON only for an
|
|
235
|
+
* intentional block; every failure, and the deadline, allow silently.
|
|
236
|
+
*/
|
|
237
|
+
export async function runDriverGuardCommand(_argv = [], deps = {}) {
|
|
238
|
+
const write = deps.writeStdout ?? ((text) => process.stdout.write(text));
|
|
239
|
+
const now = deps.now ?? (() => new Date());
|
|
240
|
+
const context = {};
|
|
241
|
+
let timer;
|
|
242
|
+
const deadline = new Promise((resolve) => {
|
|
243
|
+
timer = setTimeout(() => resolve("deadline"), deps.deadlineMs ?? DRIVER_GUARD_DEADLINE_MS);
|
|
244
|
+
timer.unref?.();
|
|
245
|
+
});
|
|
246
|
+
const work = (async () => {
|
|
247
|
+
const raw = await (deps.readStdin ?? readProcessStdin)(DRIVER_GUARD_MAX_STDIN_BYTES);
|
|
248
|
+
let payload;
|
|
249
|
+
try {
|
|
250
|
+
payload = JSON.parse(raw);
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return (deps.evaluate ?? evaluateDriverGuard)(payload, deps, context);
|
|
256
|
+
})().catch(() => "exception");
|
|
257
|
+
try {
|
|
258
|
+
const outcome = await Promise.race([work, deadline]);
|
|
259
|
+
if (outcome !== null && typeof outcome === "object" && outcome.decision === "block") {
|
|
260
|
+
write(`${JSON.stringify({ decision: "block", reason: outcome.message })}\n`);
|
|
261
|
+
}
|
|
262
|
+
else if ((outcome === "deadline" || outcome === "exception") && context.registration && context.roots &&
|
|
263
|
+
!context.recorded) {
|
|
264
|
+
// Allow, and record why, without waiting past a short grace period.
|
|
265
|
+
const line = recordDecision(context.roots, context.registration, { decision: "allow", reason: "guard_error", detail: outcome }, now()).catch(() => undefined);
|
|
266
|
+
await Promise.race([line, new Promise((resolve) => setTimeout(resolve, DRIVER_GUARD_RECORD_GRACE_MS).unref?.())]);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// Allow.
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
if (timer)
|
|
274
|
+
clearTimeout(timer);
|
|
275
|
+
}
|
|
276
|
+
return 0;
|
|
277
|
+
}
|