@indigoai-us/hq-cli 5.345.220 → 5.345.221
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/CHANGELOG.md +118 -0
- package/dist/command-catalog.generated.d.ts +144 -2
- package/dist/command-catalog.generated.js +175 -2
- package/dist/commands/auth.js +4 -1
- package/dist/commands/bot-runtime.d.ts +18 -5
- package/dist/commands/bot-runtime.js +29 -12
- package/dist/commands/bot.d.ts +39 -2
- package/dist/commands/bot.js +140 -11
- package/dist/commands/core-stop-autosave.d.ts +21 -0
- package/dist/commands/core-stop-autosave.js +300 -0
- package/dist/commands/core.js +2 -0
- package/dist/commands/daemon.d.ts +5 -0
- package/dist/commands/daemon.js +31 -7
- package/dist/commands/doctor-usage.d.ts +5 -0
- package/dist/commands/doctor-usage.js +25 -0
- package/dist/commands/env.d.ts +49 -4
- package/dist/commands/env.js +355 -5
- package/dist/commands/lanes-shared.d.ts +3 -0
- package/dist/commands/lanes.d.ts +3 -0
- package/dist/commands/lanes.js +87 -3
- package/dist/commands/sources.js +3 -3
- package/dist/commands/sync-core.d.ts +1 -0
- package/dist/commands/sync-core.js +77 -3
- package/dist/commands/whoami.js +96 -80
- package/dist/lib/bot/config.d.ts +17 -0
- package/dist/lib/bot/config.js +13 -0
- package/dist/lib/bot/fleet-cron.js +24 -2
- package/dist/lib/bot/fleet-local.d.ts +30 -2
- package/dist/lib/bot/fleet-local.js +60 -1
- package/dist/lib/bot/grok-login-scope.d.ts +36 -0
- package/dist/lib/bot/grok-login-scope.js +93 -0
- package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
- package/dist/lib/bot/legacy-provider-login.js +28 -22
- package/dist/lib/bot/runtime-sign-in-check.js +6 -1
- package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
- package/dist/lib/core-utils/sentry-report.js +2 -0
- package/dist/lib/daemon/machine-checks.d.ts +22 -1
- package/dist/lib/daemon/machine-checks.js +54 -12
- package/dist/lib/daemon/run.js +66 -8
- package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
- package/dist/lib/daemon/stop-autosave-lock.js +166 -0
- package/dist/lib/daemon/stop-autosave.d.ts +28 -0
- package/dist/lib/daemon/stop-autosave.js +111 -0
- package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
- package/dist/lib/daemon/stop-diagnostics.js +136 -0
- package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
- package/dist/lib/daemon/stop-job-executor.js +126 -0
- package/dist/lib/daemon/stop-jobs.d.ts +93 -0
- package/dist/lib/daemon/stop-jobs.js +599 -0
- package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
- package/dist/lib/doctor/checks/host-core.js +1 -1
- package/dist/lib/environment/access-probes.d.ts +234 -0
- package/dist/lib/environment/access-probes.js +918 -0
- package/dist/lib/environment/profile.d.ts +15 -2
- package/dist/lib/environment/profile.js +55 -20
- package/dist/lib/environment/rfc3339.d.ts +8 -0
- package/dist/lib/environment/rfc3339.js +26 -0
- package/dist/lib/environment/work-requirements.d.ts +169 -0
- package/dist/lib/environment/work-requirements.js +389 -0
- package/dist/lib/hook-engine/coverage.d.ts +137 -7
- package/dist/lib/hook-engine/coverage.js +1424 -4
- package/dist/lib/hook-engine/fleet-registration.js +2 -2
- package/dist/lib/hook-engine/git-stop-config.json +513 -0
- package/dist/lib/hook-engine/native-stop-compatibility.json +311 -0
- package/dist/lib/hook-engine/reconcile.js +2 -2
- package/dist/lib/hot-channels/alert.d.ts +2 -2
- package/dist/lib/hot-channels/alert.js +8 -5
- package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
- package/dist/lib/hot-channels/signals-pass.js +296 -17
- package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
- package/dist/lib/hot-channels/signals-runtime.js +82 -0
- package/dist/lib/install/hook-target.js +1 -1
- package/dist/lib/lanes/host-capacity.d.ts +26 -2
- package/dist/lib/lanes/host-capacity.js +17 -2
- package/dist/lib/lanes/host-compute.d.ts +90 -0
- package/dist/lib/lanes/host-compute.js +185 -0
- package/dist/lib/lanes/index.d.ts +2 -0
- package/dist/lib/lanes/index.js +1 -0
- package/dist/lib/lanes/reconcile.js +22 -1
- package/dist/lib/lanes/resource-usage.d.ts +155 -0
- package/dist/lib/lanes/resource-usage.js +589 -0
- package/dist/lib/lanes/run-size.d.ts +46 -0
- package/dist/lib/lanes/run-size.js +197 -0
- package/dist/lib/lanes/store.js +27 -0
- package/dist/lib/lanes/throttle.d.ts +36 -1
- package/dist/lib/lanes/throttle.js +47 -10
- package/dist/lib/lanes/types.d.ts +40 -0
- package/dist/lib/lanes/types.js +2 -2
- package/dist/lib/lanes/watcher.js +13 -4
- package/dist/lib/lanes/worker-process.d.ts +25 -2
- package/dist/lib/lanes/worker-process.js +71 -19
- package/dist/lib/placement/match.d.ts +192 -0
- package/dist/lib/placement/match.js +667 -0
- package/dist/lib/safe-store.d.ts +14 -0
- package/dist/lib/safe-store.js +77 -4
- package/dist/lib/search-index/index.d.ts +88 -4
- package/dist/lib/search-index/index.js +288 -24
- package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
- package/dist/lib/search-index/max-doc-bytes.js +48 -23
- package/dist/lib/signals/codex-lockdown.d.ts +79 -0
- package/dist/lib/signals/codex-lockdown.js +271 -0
- package/dist/lib/signals/codex-login.d.ts +37 -0
- package/dist/lib/signals/codex-login.js +83 -0
- package/dist/lib/signals/engine.d.ts +27 -0
- package/dist/lib/signals/engine.js +70 -0
- package/dist/lib/signals/reply.js +22 -1
- package/dist/lib/signals/run-record.js +6 -1
- package/dist/lib/signals/settings.d.ts +5 -0
- package/dist/lib/signals/settings.js +2 -0
- package/dist/lib/signals/steps/extract.d.ts +85 -9
- package/dist/lib/signals/steps/extract.js +317 -68
- package/dist/lib/signals/steps/types.d.ts +2 -0
- package/dist/lib/sync-core/engine-home.d.ts +35 -1
- package/dist/lib/sync-core/engine-home.js +119 -16
- package/dist/lib/sync-core/rollout-state.d.ts +2 -1
- package/dist/lib/sync-core/rollout-state.js +5 -2
- package/dist/lib/sync-core/vault-uid.d.ts +2 -0
- package/dist/lib/sync-core/vault-uid.js +4 -0
- package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
- package/dist/utils/auth-session-check.d.ts +16 -0
- package/dist/utils/auth-session-check.js +16 -0
- package/dist/utils/client-health-contract.d.ts +6 -0
- package/dist/utils/client-health-contract.js +13 -0
- package/dist/utils/client-health.d.ts +7 -0
- package/dist/utils/client-health.js +22 -1
- package/dist/utils/command-usage.d.ts +40 -0
- package/dist/utils/command-usage.js +61 -0
- package/dist/utils/duplicate-command-usage.d.ts +72 -0
- package/dist/utils/duplicate-command-usage.js +125 -0
- package/dist/utils/host-registration.js +2 -1
- package/dist/utils/resident-package-preload.js +4 -0
- package/dist/utils/sentry-fingerprint.js +9 -0
- package/dist/utils/windows-bash.d.ts +2 -0
- package/dist/utils/windows-bash.js +2 -1
- package/package.json +9 -8
- package/scripts/bench-core-compare.mjs +313 -0
- package/scripts/bench-core.mjs +399 -12
- package/scripts/check-function-manifest.mjs +116 -3
package/dist/commands/bot.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { withLocalJobs } from "../lib/bot/local-jobs.js";
|
|
2
2
|
import { clearFleetMoveRecords, fleetMoveHoldPath, fleetMoveRecentlyFailed, holdReportDue, legacyConversionDecision, legacyHoldFailureReport, legacyHoldNotice, legacyHoldNotifiesOwner, legacyMoveState, ownerHoldNoticeDue, readFleetMoveFailure, readFleetMoveHold, writeFleetMoveFailure, writeFleetMoveHold, } from "../lib/bot/legacy-convert.js";
|
|
3
|
-
import { legacyProviderLoginProbe } from "../lib/bot/legacy-provider-login.js";
|
|
3
|
+
import { legacyProviderLoginProbe, newBotLoginScope } from "../lib/bot/legacy-provider-login.js";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { CLI_VERSION } from "../cli-version.js";
|
|
6
|
+
import { BOT_SIGNALS_RUNTIME_SETTINGS, signalsPassRuntime } from "../lib/bot/config.js";
|
|
6
7
|
import { runSignals } from "../lib/signals/engine.js";
|
|
7
8
|
// The main bot's runtime, the same one the signals engine's extract step uses.
|
|
8
|
-
import { defaultResolveBotRuntime } from "../lib/signals/steps/extract.js";
|
|
9
9
|
import { BOT_SIGNALS_ENGINE_JOB_FLAG, signalsEngineForJob } from "../lib/bot/signals-engine-flag.js";
|
|
10
10
|
import { resolveProcessFlagGate } from "../lib/flag-registry.js";
|
|
11
11
|
import { currentHotSignalSyncCompany, hasScheduledBriefJob, hotSignalSyncJobCompanies, readActiveCompanySlug, registerHotSignalSyncOnStart, runHotSignalSyncJob } from "../lib/bot/jobs/hot-signal-sync.js";
|
|
12
|
-
import { CLAUDE_SIGN_IN_STEPS, createClaudeSignalsPass } from "../lib/hot-channels/signals-pass.js";
|
|
12
|
+
import { CLAUDE_SIGN_IN_STEPS, CODEX_SIGN_IN_STEPS, codexBotSignalsOptInCommand, createClaudeSignalsPass } from "../lib/hot-channels/signals-pass.js";
|
|
13
|
+
import { executiveSignalsRuntimeOptions, signalsPassCodexLogin } from "../lib/hot-channels/signals-runtime.js";
|
|
13
14
|
import { checkClaudeLoginNow, readSignalsClaudeLogin, recordSignalsPassClaudeLogin } from "../lib/hot-channels/signals-claude-login.js";
|
|
14
15
|
import { machineTimeZone } from "../lib/bot/job-run.js";
|
|
15
16
|
import { runCompanyHotChannelSync } from "./sources.js";
|
|
@@ -82,7 +83,7 @@ import { clearPendingSwitch, recoverPendingSwitchSafely, writePendingSwitch } fr
|
|
|
82
83
|
import { classifyRuntimeFailure, isRuntimeUsageLimit, runtimeFailureReason, usageLimitResetsAt } from "../lib/bot/runtime-failure.js";
|
|
83
84
|
import { PROBE_DEFAULT_TIMEOUT_MS, probeBotRuntime } from "../lib/bot/probe.js";
|
|
84
85
|
import { BOT_LOGIN_RUNTIMES, botAuthEnv, botRuntimeAuth, capacityAccountHome, defaultSpawnBrowserSignIn, describeBotAuth, formatBotAuth, isBotLoginRuntime, restoreBotSessions, setAsideBotSessions, discardHeldBotLogin, holdPreviousBotLogin, restoreHeldBotLogin, signInBotRuntime, signOutBotRuntime, withRuntimeAuth, } from "../lib/bot/runtime-auth.js";
|
|
85
|
-
import { BotApi, BotApiError, BOT_RESTORE_DEFAULTS, buildBotLocalConfig, describeBotLocalConfig, orphanBotRunMessage, parseBotLocalConfig, removeOrphanBotDaemon, botDaemonStatus, botDir, botCredsPath, botLogPath, botsRoot, botTokenStateDir, botWorkerRelDir, buildBotDaemonPaths, createBotLogger, deleteBotCreds, installBotDaemon, repairBotDaemonIfStale, healBotDaemonNodeFromJob, introDmText, isBotMemoryMode, botLocalMemoryDir, botMemoryMode, resolveBotMemoryDir, validateBotIntro, validateBotDisplayName, validateBotKickoff, validateBotEffort, validateBotModel, effectiveBotEffort, BOT_EFFORT_LEVELS, DEFAULT_BOT_EFFORT, BOT_MEMORY_MODES, BOT_KINDS, isBotKind, effectiveBotKind, effectiveBotCompanies, normalizeBotCompanies, SETUP_BOT_WORKER_ID, isBotRuntimeId, botRuntimeFromBrainName, localNameForRemoteBot, remoteBotRunnability, isPidAlive, listBotWorkerOptions, patchBotConfig, readBotConfig, readBotCredsIdentity, readBotStatus, patchBotStatus, runtimeCrashSinceStart, resolveBotWorker, runBot, runtimeFor, scaffoldBotMemory, scaffoldBotWorker, startBotDaemon, stopBotDaemon, uninstallBotDaemon, validateBotName, writeBotConfig, writeBotCreds, BOT_RUNTIMES, BOT_INTRO_MAX_CHARS, BOT_DISPLAY_NAME_MAX_CHARS, BOT_KICKOFF_MAX_CHARS, detectBotPlatform, withBotLock, localBotRole, remoteBotRole, remoteBotDisplayName, personFacingName, writeCloudDisplayName, setupSlugFor, ASSISTANT_ROLE, HQ_FLEET_RUNTIME_ENGINE_ID, HQ_FLEET_LOCAL_RELEASE, authenticateFleetLocalBot, bootstrapFleetLocalBot, buildSystemPrompt, controlFleetBot as controlFleetLocalBot, ensureFleetBotDaemon, FleetDaemonStoppedError, fleetBotUnitId, fleetBotsManagedByDaemon, fleetLocalGatewayPid, fleetLocalProfileNeedsAdoption, fleetLocalServiceInstalled, fleetProviderForRuntime, importFleetLocalMachineCredential, importFleetLocalProviderLogin, fleetProviderNeedsSignIn, fleetOwnerCompanies, refreshFleetLocalInstructions, fleetLocalPromotionRuntime, installPinnedFleetLocalDistribution, installTargetFleetLocalDistribution, resolveFleetLocalPointerTarget, resolveFleetLocalTargetRelease, fleetLocalProfileDir, fleetProfileOwnerCompanies, fleetLocalChannels, readFleetLocalGatewayState, readFleetLocalIntroSentAt, readFleetLocalSignInNeeded, readPromptSources, removeFleetLocalBot, } from "../lib/bot/index.js";
|
|
86
|
+
import { BotApi, BotApiError, BOT_RESTORE_DEFAULTS, buildBotLocalConfig, describeBotLocalConfig, orphanBotRunMessage, parseBotLocalConfig, removeOrphanBotDaemon, botDaemonStatus, botDir, botCredsPath, botLogPath, botsRoot, botTokenStateDir, botWorkerRelDir, buildBotDaemonPaths, createBotLogger, deleteBotCreds, installBotDaemon, repairBotDaemonIfStale, healBotDaemonNodeFromJob, introDmText, isBotMemoryMode, botLocalMemoryDir, botMemoryMode, resolveBotMemoryDir, validateBotIntro, validateBotDisplayName, validateBotKickoff, validateBotEffort, validateBotModel, effectiveBotEffort, BOT_EFFORT_LEVELS, DEFAULT_BOT_EFFORT, BOT_MEMORY_MODES, BOT_KINDS, isBotKind, effectiveBotKind, effectiveBotCompanies, normalizeBotCompanies, SETUP_BOT_WORKER_ID, isBotRuntimeId, botRuntimeFromBrainName, localNameForRemoteBot, remoteBotRunnability, isPidAlive, listBotWorkerOptions, patchBotConfig, readBotConfig, readBotCredsIdentity, readBotStatus, patchBotStatus, runtimeCrashSinceStart, resolveBotWorker, runBot, runtimeFor, scaffoldBotMemory, scaffoldBotWorker, startBotDaemon, stopBotDaemon, uninstallBotDaemon, validateBotName, writeBotConfig, writeBotCreds, BOT_RUNTIMES, BOT_INTRO_MAX_CHARS, BOT_DISPLAY_NAME_MAX_CHARS, BOT_KICKOFF_MAX_CHARS, detectBotPlatform, withBotLock, localBotRole, remoteBotRole, remoteBotDisplayName, personFacingName, writeCloudDisplayName, setupSlugFor, ASSISTANT_ROLE, HQ_FLEET_RUNTIME_ENGINE_ID, HQ_FLEET_LOCAL_RELEASE, authenticateFleetLocalBot, bootstrapFleetLocalBot, buildSystemPrompt, controlFleetBot as controlFleetLocalBot, ensureFleetBotDaemon, FleetDaemonStoppedError, fleetBotUnitId, fleetBotsManagedByDaemon, fleetLocalGatewayPid, fleetLocalProfileNeedsAdoption, fleetLocalServiceInstalled, fleetProviderForRuntime, importFleetLocalMachineCredential, importFleetLocalProviderLogin, fleetAuthUsesXaiOauthLogin, xaiOauthLoginHeldBack, xaiOauthLoginRefusal, fleetProviderNeedsSignIn, fleetOwnerCompanies, refreshFleetLocalInstructions, fleetLocalPromotionRuntime, installPinnedFleetLocalDistribution, installTargetFleetLocalDistribution, resolveFleetLocalPointerTarget, resolveFleetLocalTargetRelease, fleetLocalProfileDir, fleetProfileOwnerCompanies, fleetLocalChannels, readFleetLocalGatewayState, readFleetLocalIntroSentAt, readFleetLocalSignInNeeded, readPromptSources, removeFleetLocalBot, } from "../lib/bot/index.js";
|
|
86
87
|
import { gatedInteractiveLogin } from "../utils/interactive-caller.js";
|
|
87
88
|
import { brainSignInStatus, fleetInstallProgressReporter, fleetRuntimeStatus, runBotAuthStatus, runBotRuntimeInstall, runBotRuntimeStatus, runBotSignIn } from "./bot-runtime.js";
|
|
88
89
|
import { ensureFleetRuntimeInstalled } from "../lib/bot/fleet-local.js";
|
|
@@ -524,6 +525,14 @@ export function signalsClaudeSignInFor(dir, fleet, record = readSignalsClaudeLog
|
|
|
524
525
|
const companies = hotSignalSyncJobCompanies(dir, { fleet });
|
|
525
526
|
if (companies.length === 0)
|
|
526
527
|
return null;
|
|
528
|
+
// Signals take their runtime from the Executive bot, as the pass does
|
|
529
|
+
// (signals-runtime.ts). When that is a Codex bot that opted in, no Claude
|
|
530
|
+
// Code login is needed; the Codex line stands in (signalsCodexRuntimeLine).
|
|
531
|
+
const executiveBot = resolveExecutiveBot();
|
|
532
|
+
const source = executiveBot?.config ?? null;
|
|
533
|
+
const executiveDir = executiveBot?.dir ?? null;
|
|
534
|
+
if (signalsPassRuntime(source) === "codex")
|
|
535
|
+
return null;
|
|
527
536
|
const signedOutSince = record && !record.signedIn ? (record.signedOutSince ?? record.checkedAt) : null;
|
|
528
537
|
const liveAnswer = live && live.signedIn !== null ? live.signedIn : null;
|
|
529
538
|
const signedIn = liveAnswer ?? record?.signedIn ?? null;
|
|
@@ -541,7 +550,15 @@ export function signalsClaudeSignInFor(dir, fleet, record = readSignalsClaudeLog
|
|
|
541
550
|
source: record?.source ?? null,
|
|
542
551
|
signedOutSince,
|
|
543
552
|
queuedDocsHint,
|
|
544
|
-
|
|
553
|
+
// A Codex Executive bot's owner hears about switching signals to that bot
|
|
554
|
+
// first, with the Claude sign-in as the alternative. `command` stays the
|
|
555
|
+
// Claude sign-in command it always was, for readers of the JSON.
|
|
556
|
+
// The switch is offered only when the Executive bot qualifies (a Codex bot
|
|
557
|
+
// with its own Codex login, not on the Fleet runtime: signalsCodexLogin);
|
|
558
|
+
// the Claude sign-in comes first, as the fix that works now.
|
|
559
|
+
fix: source && executiveDir && signalsPassCodexLogin(executiveDir, source).ok
|
|
560
|
+
? `${CLAUDE_SIGN_IN_STEPS} Or run signals on ${source.name}'s own Codex: \`${codexBotSignalsOptInCommand(source.name)}\`.`
|
|
561
|
+
: CLAUDE_SIGN_IN_STEPS,
|
|
545
562
|
command: signInCommand("claude"),
|
|
546
563
|
};
|
|
547
564
|
}
|
|
@@ -590,6 +607,44 @@ export function signalsClaudeSignInLines(s) {
|
|
|
590
607
|
lines.push(s.queuedDocsHint);
|
|
591
608
|
return lines;
|
|
592
609
|
}
|
|
610
|
+
/**
|
|
611
|
+
* The tool the signals pass runs on for a bot with the hot-signal-sync job
|
|
612
|
+
* (null without the job): the Executive bot's choice, as in the pass.
|
|
613
|
+
*/
|
|
614
|
+
export function signalsRuntimeFor(dir, fleet) {
|
|
615
|
+
if (hotSignalSyncJobCompanies(dir, { fleet }).length === 0)
|
|
616
|
+
return null;
|
|
617
|
+
return signalsPassRuntime(resolveExecutiveBot()?.config ?? null);
|
|
618
|
+
}
|
|
619
|
+
/** The Codex login the pass uses when signals run on Codex (signalsCodexLogin), else null. */
|
|
620
|
+
export function signalsCodexHomeFor(dir, fleet) {
|
|
621
|
+
if (signalsRuntimeFor(dir, fleet) !== "codex")
|
|
622
|
+
return null;
|
|
623
|
+
const executive = resolveExecutiveBot();
|
|
624
|
+
if (!executive)
|
|
625
|
+
return null;
|
|
626
|
+
const login = signalsPassCodexLogin(executive.dir, executive.config);
|
|
627
|
+
return login.ok && "codexHome" in login ? login.codexHome : null;
|
|
628
|
+
}
|
|
629
|
+
/** Why the Executive bot's Codex login cannot run signals, when signals are set to run on it; else null. */
|
|
630
|
+
export function signalsCodexRefusalFor(dir, fleet) {
|
|
631
|
+
if (signalsRuntimeFor(dir, fleet) !== "codex")
|
|
632
|
+
return null;
|
|
633
|
+
const executive = resolveExecutiveBot();
|
|
634
|
+
if (!executive)
|
|
635
|
+
return null;
|
|
636
|
+
const login = signalsPassCodexLogin(executive.dir, executive.config);
|
|
637
|
+
return login.ok ? null : login.reason;
|
|
638
|
+
}
|
|
639
|
+
/** The status line for a bot whose signals run on its own Codex: the bot's own sign-in answer. */
|
|
640
|
+
export function signalsCodexRuntimeLine(companies, runtimeSignedIn) {
|
|
641
|
+
const forWhat = `(hot-channel signals for ${companies.join(", ")}, on the bot's own runtime)`;
|
|
642
|
+
if (runtimeSignedIn === true)
|
|
643
|
+
return `${chalk.green("Codex signed in")} ${forWhat}`;
|
|
644
|
+
if (runtimeSignedIn === false)
|
|
645
|
+
return `${chalk.yellow("Codex signed out")} ${forWhat} - ${CODEX_SIGN_IN_STEPS}`;
|
|
646
|
+
return `${chalk.gray("Codex sign-in unknown")} ${forWhat} ${chalk.dim("the running bot checks it")}`;
|
|
647
|
+
}
|
|
593
648
|
/**
|
|
594
649
|
* `brainUsage` for a row. A model-CLI bot records it itself (status.brainUsage);
|
|
595
650
|
* a Fleet bot's last failure carries the runtime's `brain_usage`, and an older
|
|
@@ -716,6 +771,8 @@ function rowFor(name, opts = {}) {
|
|
|
716
771
|
...(fleet && config.fleetServiceInstallPending === true ? { needsSignIn: false, serviceInstallPending: true } : {}),
|
|
717
772
|
signInCommand: fleet ? fleetAuthCommand(name, config) : signInCommand(config.runtime),
|
|
718
773
|
signalsClaudeSignIn: signalsClaudeSignInFor(dir, fleet),
|
|
774
|
+
signalsRuntime: signalsRuntimeFor(dir, fleet),
|
|
775
|
+
signalsCodexHome: signalsCodexHomeFor(dir, fleet),
|
|
719
776
|
brainSignIn: brainSignInFor(name, config, status, legacy),
|
|
720
777
|
brainUsage: brainUsageFor(config, status),
|
|
721
778
|
...(legacy ? { legacy: legacyStatusJson(legacy) } : {}),
|
|
@@ -1237,6 +1294,8 @@ export const botCreateSeams = {
|
|
|
1237
1294
|
importBrainLogin: (agentUid, runtime) => {
|
|
1238
1295
|
importFleetLocalProviderLogin(agentUid, runtime);
|
|
1239
1296
|
},
|
|
1297
|
+
/** The same question the helper call asks itself: would a Grok account sign-in for this bot copy a login it may not share? */
|
|
1298
|
+
grokSiblingLogin: (config) => xaiOauthLoginHeldBack(config.agentUid),
|
|
1240
1299
|
runtimeStatus: fleetRuntimeStatus,
|
|
1241
1300
|
installRuntime: ensureFleetRuntimeInstalled,
|
|
1242
1301
|
waitForReady: waitForGatewayReady,
|
|
@@ -1747,7 +1806,7 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1747
1806
|
const steps = createSetupStepReporter(opts.json ? (opts.progress ? "json" : "silent") : "text");
|
|
1748
1807
|
const fleetTarget = await resolveFleetLocalTargetRelease();
|
|
1749
1808
|
const brainLogin = fleetProviderNeedsSignIn(fleetProvider)
|
|
1750
|
-
? await botCreateSeams.brainSignIn(runtime === "grok" ? "grok" : "chatgpt", { target: async () => fleetTarget })
|
|
1809
|
+
? await botCreateSeams.brainSignIn(runtime === "grok" ? "grok" : "chatgpt", { target: async () => fleetTarget, scope: newBotLoginScope(kind, companies) })
|
|
1751
1810
|
: null;
|
|
1752
1811
|
const fleetAuthPending = brainLogin !== null && !brainLogin.signedIn;
|
|
1753
1812
|
if (opts.start !== false && brainLogin?.signedIn === true)
|
|
@@ -2009,6 +2068,7 @@ async function runBotCreateLocked(name, opts) {
|
|
|
2009
2068
|
effort: null,
|
|
2010
2069
|
provider: fleetProvider.id,
|
|
2011
2070
|
needsSignIn: fleetAuthPending,
|
|
2071
|
+
...(fleetAuthPending && brainLogin?.blocked ? { signInBlocked: brainLogin.blocked } : {}),
|
|
2012
2072
|
...(fleetAuthPending ? { authCommand: fleetAuthCommand(name, config) } : {}),
|
|
2013
2073
|
};
|
|
2014
2074
|
if (!opts.json) {
|
|
@@ -2021,7 +2081,11 @@ async function runBotCreateLocked(name, opts) {
|
|
|
2021
2081
|
console.log(chalk.dim(` memory: ${scaffold.memoryDir} (${memoryMode})`));
|
|
2022
2082
|
console.log(chalk.dim(` state: ${dir}`));
|
|
2023
2083
|
console.log(chalk.dim(` profile: ${fleetProfile}`));
|
|
2024
|
-
if (fleetAuthPending) {
|
|
2084
|
+
if (fleetAuthPending && brainLogin?.blocked) {
|
|
2085
|
+
console.log(chalk.yellow(` no Grok sign-in was reused: ${brainLogin.blocked}.`));
|
|
2086
|
+
console.log(chalk.yellow(` sign it in with an xAI API key before it can answer: hq bot auth ${name} --provider grok --api-key (reads the key from stdin: paste it and press Ctrl-D, or pipe it in)`));
|
|
2087
|
+
}
|
|
2088
|
+
else if (fleetAuthPending) {
|
|
2025
2089
|
console.log(chalk.yellow(` sign it in before it can answer: hq bot auth ${name} --provider ${runtime === "grok" ? "grok" : "chatgpt"}`));
|
|
2026
2090
|
}
|
|
2027
2091
|
if (daemonStopped)
|
|
@@ -2195,7 +2259,10 @@ async function runBotResident(nameArg) {
|
|
|
2195
2259
|
...(signals ? { signals } : {}),
|
|
2196
2260
|
sync: (syncInput) => runCompanyHotChannelSync({ hqRoot: config.hqRoot, ...syncInput }),
|
|
2197
2261
|
// A new pass per run: the login preflight and the 20-document cap are per run.
|
|
2198
|
-
|
|
2262
|
+
// The runtime comes from the Executive bot, as on main for the wording
|
|
2263
|
+
// (defaultResolveBotRuntime) and as in `hq sources sync`: Claude Code
|
|
2264
|
+
// unless that bot is a Codex bot with signalsRuntime "bot".
|
|
2265
|
+
signalsPass: createClaudeSignalsPass({ hqRoot: config.hqRoot, company: input.company, ...executiveSignalsRuntimeOptions(), onClaudeLogin: recordSignalsPassClaudeLogin }),
|
|
2199
2266
|
});
|
|
2200
2267
|
// The engine is gated default-off (cli.bot-signals-engine-job); with the
|
|
2201
2268
|
// flag off the job runs the hot-channel sync alone, as before US-006.
|
|
@@ -2438,6 +2505,14 @@ async function runBotStatus(nameArg, opts) {
|
|
|
2438
2505
|
if (row.signalsClaudeSignIn) {
|
|
2439
2506
|
signalsClaudeSignInLines(row.signalsClaudeSignIn).forEach((line, i) => console.log(` ${i === 0 ? "signals: " : " "}${line}`));
|
|
2440
2507
|
}
|
|
2508
|
+
else if (row.signalsRuntime === "codex") {
|
|
2509
|
+
// The Executive bot's own check answers for its Codex; for any other bot it is not known here.
|
|
2510
|
+
const own = resolveExecutiveBot()?.name === name;
|
|
2511
|
+
const refusal = signalsCodexRefusalFor(dir, fleet);
|
|
2512
|
+
console.log(refusal
|
|
2513
|
+
? ` signals: ${chalk.yellow("set to run on Codex, but that login cannot be used")} - ${refusal}. Signals fail until it is fixed, or run \`hq bot set ${resolveExecutiveBot()?.name ?? name} --signals-runtime claude\`.`
|
|
2514
|
+
: ` signals: ${signalsCodexRuntimeLine(hotSignalSyncJobCompanies(dir, { fleet }), own ? row.runtimeSignedIn : null)}`);
|
|
2515
|
+
}
|
|
2441
2516
|
if (row.brainUsage.state === "exhausted") {
|
|
2442
2517
|
console.log(` usage: ${chalk.yellow(`out of usage${row.brainUsage.resetsAt ? `, resets ${row.brainUsage.resetsAt}` : ""}`)} — switch account: hq bot switch-account ${name} --runtime <claude|codex|grok>`);
|
|
2443
2518
|
}
|
|
@@ -2849,8 +2924,21 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2849
2924
|
const { name, dir, config } = requireBot(nameArg);
|
|
2850
2925
|
if (hasPromotionHold(dir))
|
|
2851
2926
|
throw new Error("This bot is held for cloud promotion. Continue its promotion before changing local settings or lifecycle.");
|
|
2852
|
-
if (opts.runtime === undefined && opts.account === undefined && opts.model === undefined && opts.effort === undefined && opts.displayName === undefined) {
|
|
2853
|
-
throw Object.assign(new Error("Nothing to change: pass --runtime <runtime>, --account <id|default>, --model <id|default>, --effort <level|default> and/or --
|
|
2927
|
+
if (opts.runtime === undefined && opts.account === undefined && opts.model === undefined && opts.effort === undefined && opts.displayName === undefined && opts.signalsRuntime === undefined) {
|
|
2928
|
+
throw Object.assign(new Error("Nothing to change: pass --runtime <runtime>, --account <id|default>, --model <id|default>, --effort <level|default>, --display-name <name> and/or --signals-runtime <bot|claude>."), { expected: true });
|
|
2929
|
+
}
|
|
2930
|
+
const signalsRuntime = opts.signalsRuntime !== undefined ? validateSignalsRuntimeSetting(config.runtime, opts.signalsRuntime) : undefined;
|
|
2931
|
+
if (signalsRuntime === "bot") {
|
|
2932
|
+
// The pass reads the opt-in from the Executive bot only (signals-runtime.ts),
|
|
2933
|
+
// and uses the login signalsCodexLogin names, which must exist.
|
|
2934
|
+
const login = signalsPassCodexLogin(dir, config);
|
|
2935
|
+
if (!login.ok)
|
|
2936
|
+
throw Object.assign(new Error(`Signals cannot run on ${name}'s Codex: ${login.reason}`), { expected: true });
|
|
2937
|
+
const executive = resolveExecutiveBot();
|
|
2938
|
+
if (executive?.name !== name) {
|
|
2939
|
+
throw Object.assign(new Error(`Signals take their runtime from the Executive bot${executive ? ` (${executive.name})` : ""}. ` +
|
|
2940
|
+
`Make ${name} the Executive bot with \`hq bot eb ${name}\` first, or set this on the Executive bot.`), { expected: true });
|
|
2941
|
+
}
|
|
2854
2942
|
}
|
|
2855
2943
|
if (opts.runtime !== undefined && !isBotRuntimeId(opts.runtime)) {
|
|
2856
2944
|
throw Object.assign(new Error(`--runtime must be one of ${BOT_RUNTIMES.join(", ")}`), { expected: true });
|
|
@@ -2860,6 +2948,9 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2860
2948
|
if ((switching || opts.account !== undefined) && opts.displayName !== undefined) {
|
|
2861
2949
|
throw Object.assign(new Error("Change --display-name on its own, not together with --runtime or --account."), { expected: true });
|
|
2862
2950
|
}
|
|
2951
|
+
if ((switching || opts.account !== undefined) && signalsRuntime !== undefined) {
|
|
2952
|
+
throw Object.assign(new Error("Change --signals-runtime on its own, not together with --runtime or --account."), { expected: true });
|
|
2953
|
+
}
|
|
2863
2954
|
let runtimeAuth = config.runtimeAuth;
|
|
2864
2955
|
if (opts.account !== undefined) {
|
|
2865
2956
|
const id = opts.account.trim();
|
|
@@ -2882,6 +2973,9 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2882
2973
|
patch.model = validateBotModel(opts.model) || undefined;
|
|
2883
2974
|
if (opts.effort !== undefined)
|
|
2884
2975
|
patch.effort = validateBotEffort(config.runtime, opts.effort) || undefined;
|
|
2976
|
+
// "claude" is the default, so it is stored as no key at all.
|
|
2977
|
+
if (signalsRuntime !== undefined)
|
|
2978
|
+
patch.signalsRuntime = signalsRuntime === "bot" ? "bot" : undefined;
|
|
2885
2979
|
const displayName = opts.displayName !== undefined ? validateBotDisplayName(opts.displayName) : undefined;
|
|
2886
2980
|
let nameSaved = null;
|
|
2887
2981
|
if (displayName !== undefined) {
|
|
@@ -2898,7 +2992,7 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2898
2992
|
patch.displayName = displayName;
|
|
2899
2993
|
}
|
|
2900
2994
|
const next = patchBotConfig(dir, patch);
|
|
2901
|
-
createBotLogger(dir)("info", `settings: model=${next.model ?? "default"} effort=${effectiveBotEffort(next)}${next.effort ? "" : " (default)"}${displayName !== undefined ? ` name="${displayName}"` : ""}`);
|
|
2995
|
+
createBotLogger(dir)("info", `settings: model=${next.model ?? "default"} effort=${effectiveBotEffort(next)}${next.effort ? "" : " (default)"}${displayName !== undefined ? ` name="${displayName}"` : ""}${signalsRuntime !== undefined ? ` signals=${signalsPassRuntime(next)}` : ""}`);
|
|
2902
2996
|
const status = readBotStatus(dir);
|
|
2903
2997
|
let running = !!status && isPidAlive(status.pid) && status.state === "running";
|
|
2904
2998
|
let restarted = false;
|
|
@@ -2921,6 +3015,7 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2921
3015
|
effortIsDefault: !next.effort,
|
|
2922
3016
|
effortLevels: BOT_EFFORT_LEVELS[config.runtime],
|
|
2923
3017
|
displayName: next.displayName ?? null,
|
|
3018
|
+
signalsRuntime: signalsPassRuntime(next),
|
|
2924
3019
|
role: localBotRole(next),
|
|
2925
3020
|
nameSaved,
|
|
2926
3021
|
running,
|
|
@@ -2937,6 +3032,11 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2937
3032
|
if (opts.model !== undefined || opts.effort !== undefined) {
|
|
2938
3033
|
console.log(chalk.green(`${name} now thinks with ${result.model ?? "the default model"} at ${result.effort} effort (from its next message).`));
|
|
2939
3034
|
}
|
|
3035
|
+
if (signalsRuntime !== undefined) {
|
|
3036
|
+
console.log(chalk.green(signalsPassRuntime(next) === "codex"
|
|
3037
|
+
? `${name}'s hot-channel signals now run on its own Codex (from the next sync).`
|
|
3038
|
+
: `${name}'s hot-channel signals run on Claude Code (from the next sync).`));
|
|
3039
|
+
}
|
|
2940
3040
|
if (displayName !== undefined) {
|
|
2941
3041
|
const where = nameSaved === "local-only" ? " (kept on this computer; HQ does not take names yet)" : "";
|
|
2942
3042
|
const how = restarted
|
|
@@ -2949,6 +3049,23 @@ async function runBotSetLocked(nameArg, opts, deps = {}) {
|
|
|
2949
3049
|
console.log(chalk.green(`${name} is now called ${displayName}`) + chalk.dim(`${where}${how}`));
|
|
2950
3050
|
}
|
|
2951
3051
|
}
|
|
3052
|
+
/**
|
|
3053
|
+
* `--signals-runtime`: "bot" only for a Codex bot (a Claude bot already runs
|
|
3054
|
+
* signals on Claude Code, and Grok has no isolated signals call yet);
|
|
3055
|
+
* "claude" for any bot.
|
|
3056
|
+
*/
|
|
3057
|
+
export function validateSignalsRuntimeSetting(runtime, value) {
|
|
3058
|
+
const v = value.trim().toLowerCase();
|
|
3059
|
+
if (!BOT_SIGNALS_RUNTIME_SETTINGS.includes(v)) {
|
|
3060
|
+
throw Object.assign(new Error(`--signals-runtime must be one of ${BOT_SIGNALS_RUNTIME_SETTINGS.join(", ")}`), { expected: true });
|
|
3061
|
+
}
|
|
3062
|
+
if (v === "bot" && runtime !== "codex") {
|
|
3063
|
+
throw Object.assign(new Error(runtime === "claude"
|
|
3064
|
+
? "This bot runs on Claude Code, so its signals already run on its own runtime. Nothing to change."
|
|
3065
|
+
: `--signals-runtime bot is only for Codex bots; this bot runs on ${runtime}, so its signals stay on Claude Code.`), { expected: true });
|
|
3066
|
+
}
|
|
3067
|
+
return v;
|
|
3068
|
+
}
|
|
2952
3069
|
/**
|
|
2953
3070
|
* `hq bot set --runtime/--account`: probe the new setup first (nothing changes
|
|
2954
3071
|
* when it cannot answer), stop a running bot, back up bot.json and set the
|
|
@@ -3366,6 +3483,13 @@ export async function runBotAuth(nameArg, opts) {
|
|
|
3366
3483
|
if (opts.apiKey && !apiKey) {
|
|
3367
3484
|
throw Object.assign(new Error("No API key was received on stdin."), { expected: true });
|
|
3368
3485
|
}
|
|
3486
|
+
// Decided on the provider the name resolves to (grok, xai, xai-oauth, any case), before the profile
|
|
3487
|
+
// install and the stop below. authenticateFleetLocalBot asks again right before the helper call.
|
|
3488
|
+
if (fleetAuthUsesXaiOauthLogin(opts.provider, apiKey)) {
|
|
3489
|
+
const held = botCreateSeams.grokSiblingLogin(b.config);
|
|
3490
|
+
if (held.blocked)
|
|
3491
|
+
throw Object.assign(new Error(xaiOauthLoginRefusal(held, { name: b.name })), { expected: true });
|
|
3492
|
+
}
|
|
3369
3493
|
if (!apiKey && botRuntimeFromBrainName(opts.provider) === "claude" && !botCreateSeams.claudeLogin().signedIn) {
|
|
3370
3494
|
const reason = `Claude Code is not signed in on this computer, so ${b.name} cannot answer.`;
|
|
3371
3495
|
const brainSignIn = { provider: "claude", needed: true, reason, command: "claude /login" };
|
|
@@ -4205,12 +4329,16 @@ export function registerBotCommand(program) {
|
|
|
4205
4329
|
.command("auth-status")
|
|
4206
4330
|
.description("Say whether a bot created now with this brain starts without a sign-in step, reusing a login already on this computer")
|
|
4207
4331
|
.requiredOption("--provider <provider>", "Brain: claude, codex (or chatgpt) or grok")
|
|
4332
|
+
.option("--kind <kind>", "The bot the answer is for: personal (default) or company")
|
|
4333
|
+
.option("--company <slug>", "The company of a company bot (repeatable); a Grok login is reused only within one company", collectRepeated, [])
|
|
4208
4334
|
.option("--json", "Print machine-readable JSON: { provider, signedIn, source }")
|
|
4209
4335
|
.action((opts) => wrap(async () => { await runBotAuthStatus(opts); })());
|
|
4210
4336
|
bot
|
|
4211
4337
|
.command("sign-in")
|
|
4212
4338
|
.description("Sign this computer in to ChatGPT or Grok through its own CLI, so new bots with that brain start without a sign-in step")
|
|
4213
4339
|
.requiredOption("--provider <provider>", "Brain: codex (or chatgpt) or grok")
|
|
4340
|
+
.option("--kind <kind>", "The bot the sign-in is for: personal (default) or company")
|
|
4341
|
+
.option("--company <slug>", "The company of a company bot (repeatable)", collectRepeated, [])
|
|
4214
4342
|
.option("--json", "Print one JSON line per event (device code, messages) and a final result")
|
|
4215
4343
|
.option("--no-browser", "Use the CLI's device-code login instead of its browser login")
|
|
4216
4344
|
.action((opts) => wrap(async () => { await runBotSignIn(opts); })());
|
|
@@ -4239,6 +4367,7 @@ export function registerBotCommand(program) {
|
|
|
4239
4367
|
.option("--model <model>", "Model id for the runtime CLI, or default for the CLI's own default")
|
|
4240
4368
|
.option("--display-name <name>", `The name people see for the bot in HQ (up to ${BOT_DISPLAY_NAME_MAX_CHARS} chars). The handle stays <name>`)
|
|
4241
4369
|
.option("--effort <level>", `Thinking level (claude ${BOT_EFFORT_LEVELS.claude.join("|")}; codex ${BOT_EFFORT_LEVELS.codex.join("|")}; grok ${BOT_EFFORT_LEVELS.grok.join("|")}), or default (${DEFAULT_BOT_EFFORT})`)
|
|
4370
|
+
.option("--signals-runtime <bot|claude>", "Where hot-channel signals run: bot (the Executive Codex bot's own Codex) or claude (Claude Code, the default). Set on the Executive bot; local to this computer, from the next sync")
|
|
4242
4371
|
.option("--json", "Print machine-readable JSON")
|
|
4243
4372
|
.action((name, opts) => wrap(() => runBotSet(name, opts))());
|
|
4244
4373
|
bot
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Typed CLI boundary for Stop's Bash-file autosave job. */
|
|
2
|
+
import type { Command } from "commander";
|
|
3
|
+
/** The private folder, inside the HQ root, that holds the autosave lock. */
|
|
4
|
+
export declare const AUTOSAVE_LOCK_FOLDER = "workspace/.autocommit-lock";
|
|
5
|
+
/** The caller supplies only its root and session; every Git argument is built
|
|
6
|
+
* here. Tests replace the sweep dependencies and never invoke this mutation.
|
|
7
|
+
*/
|
|
8
|
+
export interface StopAutosaveDependencies {
|
|
9
|
+
git?: (root: string, args: string[]) => {
|
|
10
|
+
code: number;
|
|
11
|
+
stdout: string;
|
|
12
|
+
stderr: string;
|
|
13
|
+
};
|
|
14
|
+
enabled?: () => Promise<boolean>;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
/** A definite holder answer; unknown always retains an index lock. */
|
|
17
|
+
indexLockHeld?: (file: string) => boolean | undefined;
|
|
18
|
+
}
|
|
19
|
+
export declare function stopAutosave(root: string, session: string, env: NodeJS.ProcessEnv, deps?: StopAutosaveDependencies): Promise<number>;
|
|
20
|
+
export declare function registerCoreStopAutosave(core: Command): void;
|
|
21
|
+
//# sourceMappingURL=core-stop-autosave.d.ts.map
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { createFlagClient } from "@indigoai-us/hq-flags-client";
|
|
6
|
+
import { loadCachedTokens } from "@indigoai-us/hq-cloud";
|
|
7
|
+
import { resolveFlagRegistryEndpoint } from "../lib/flag-registry-endpoint.js";
|
|
8
|
+
import { executeHqSession } from "./core-hq-session-native.js";
|
|
9
|
+
import { runStopSweep, sweepFileSize } from "../lib/daemon/stop-autosave.js";
|
|
10
|
+
import { openStoreDir } from "../lib/safe-store.js";
|
|
11
|
+
import { describeCoreCommand } from "./core-command-catalog.js";
|
|
12
|
+
import { acquireAutosaveLock, lockParentRefusal } from "../lib/daemon/stop-autosave-lock.js";
|
|
13
|
+
/** The private folder, inside the HQ root, that holds the autosave lock. */
|
|
14
|
+
export const AUTOSAVE_LOCK_FOLDER = "workspace/.autocommit-lock";
|
|
15
|
+
/** Fresh, explicit-company flag read. A missing row or any error stays off. */
|
|
16
|
+
async function sweepEnabled(root, env) {
|
|
17
|
+
let uid = env.HQ_COMPANY_UID?.trim();
|
|
18
|
+
let slug = env.HQ_COMPANY_SLUG?.trim();
|
|
19
|
+
if (!uid || !/^cmp_[A-Za-z0-9]{3,128}$/.test(uid)) {
|
|
20
|
+
const resolved = executeHqSession(["get", "company_slug"], { cwd: root, hqRoot: root }, { env });
|
|
21
|
+
if (resolved.code !== 0)
|
|
22
|
+
return false;
|
|
23
|
+
slug = resolved.stdout.trim();
|
|
24
|
+
if (!slug || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(slug))
|
|
25
|
+
return false;
|
|
26
|
+
try {
|
|
27
|
+
uid = JSON.parse(fs.readFileSync(path.join(root, "companies", slug, ".company.json"), "utf8")).cloud_uid;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!uid || !/^cmp_[A-Za-z0-9]{3,128}$/.test(uid))
|
|
34
|
+
return false;
|
|
35
|
+
const token = loadCachedTokens()?.idToken;
|
|
36
|
+
if (!token)
|
|
37
|
+
return false;
|
|
38
|
+
let failed = false;
|
|
39
|
+
const client = createFlagClient({ endpoint: resolveFlagRegistryEndpoint(undefined, env), companyUid: uid,
|
|
40
|
+
...(slug ? { companyIdentifiers: [slug] } : {}), env: {}, getToken: () => token,
|
|
41
|
+
refreshIntervalMs: 0, requestTimeoutMs: 150, onError: () => { failed = true; } });
|
|
42
|
+
try {
|
|
43
|
+
await client.ready();
|
|
44
|
+
return !failed && client.snapshot()?.flags["hooks.hq-autocommit-bash-sweep"] === true;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
client.close();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function indexLockHeld(file, env) {
|
|
54
|
+
// An arbitrary legacy probe cannot be reinterpreted as a native operation.
|
|
55
|
+
if (env.HQ_AUTOCOMMIT_LOCK_PROBE)
|
|
56
|
+
return undefined;
|
|
57
|
+
for (const command of ["/usr/sbin/lsof", "/usr/bin/lsof", "/usr/bin/fuser"]) {
|
|
58
|
+
if (!fs.existsSync(command))
|
|
59
|
+
continue;
|
|
60
|
+
const result = spawnSync(command, [file], { env, timeout: 1000, stdio: "ignore" });
|
|
61
|
+
if (result.error || result.signal)
|
|
62
|
+
return undefined;
|
|
63
|
+
return result.status === 0 ? true : result.status === 1 ? false : undefined;
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
export async function stopAutosave(root, session, env, deps = {}) {
|
|
68
|
+
root = fs.realpathSync(root);
|
|
69
|
+
const now = deps.now ?? Date.now;
|
|
70
|
+
const key = (session || `pid-${process.ppid}`).replace(/[^A-Za-z0-9._-]/g, "_");
|
|
71
|
+
const warnMessage = (marker, message) => {
|
|
72
|
+
const opened = openStoreDir(path.join(root, "workspace/.autocommit-warnings"), { create: true });
|
|
73
|
+
if (!opened.ok)
|
|
74
|
+
return;
|
|
75
|
+
try {
|
|
76
|
+
const name = `${key}.keys`;
|
|
77
|
+
const existing = opened.value.read(name);
|
|
78
|
+
if (existing.ok && existing.value.toString().split("\n").includes(marker))
|
|
79
|
+
return;
|
|
80
|
+
if (!opened.value.appendLine(name, marker).ok)
|
|
81
|
+
return;
|
|
82
|
+
process.stdout.write(message + "\n");
|
|
83
|
+
process.stderr.write(message + "\n");
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
opened.value.close();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const warn = (stage, code, relative) => warnMessage(`autocommit|${stage}|${code}`, `WARNING: HQ autosave failed — git ${stage} exited ${code} for '${relative}'. Local HQ edits are NOT being committed until this is resolved. Details: workspace/logs/hq-autocommit.log`);
|
|
90
|
+
const log = (message) => {
|
|
91
|
+
const opened = openStoreDir(path.join(root, "workspace/logs"), { create: true });
|
|
92
|
+
if (!opened.ok)
|
|
93
|
+
return;
|
|
94
|
+
try {
|
|
95
|
+
const configured = Number(env.HQ_AUTOCOMMIT_LOG_MAX_BYTES ?? 1_048_576);
|
|
96
|
+
const limit = Number.isSafeInteger(configured) && configured >= 0 ? configured : 1_048_576;
|
|
97
|
+
const facts = opened.value.stat("hq-autocommit.log");
|
|
98
|
+
if (facts.ok && facts.value.size > limit)
|
|
99
|
+
opened.value.rename("hq-autocommit.log", "hq-autocommit.log.1");
|
|
100
|
+
opened.value.appendLine("hq-autocommit.log", `[${new Date(now()).toISOString().slice(0, 19)}Z] ${message} session=${key}`);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
opened.value.close();
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const git = (args) => {
|
|
107
|
+
if (deps.git)
|
|
108
|
+
return deps.git(root, args);
|
|
109
|
+
const result = spawnSync("git", ["-C", root, ...args], {
|
|
110
|
+
env: { ...env, GIT_OPTIONAL_LOCKS: "0" }, encoding: "utf8", timeout: 30_000, maxBuffer: 8 * 1024 * 1024,
|
|
111
|
+
});
|
|
112
|
+
return { code: result.error ? 1 : result.status ?? 1, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
|
|
113
|
+
};
|
|
114
|
+
const failure = (stage, result, relative) => {
|
|
115
|
+
log(`FAIL stage=${stage} exit=${result.code} path=${relative}`);
|
|
116
|
+
const output = (result.stdout + result.stderr).replace(/\n+$/, "");
|
|
117
|
+
if (output) {
|
|
118
|
+
const opened = openStoreDir(path.join(root, "workspace/logs"), { create: true });
|
|
119
|
+
if (opened.ok) {
|
|
120
|
+
try {
|
|
121
|
+
opened.value.appendLine("hq-autocommit.log", output.split("\n").map(line => ` git: ${line}`).join("\n"));
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
opened.value.close();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
warn(stage, result.code, relative);
|
|
129
|
+
return env.HQ_AUTOCOMMIT_STRICT === "1" ? 1 : 0;
|
|
130
|
+
};
|
|
131
|
+
const rawMinimum = Number(env.HQ_OFFLOAD_MIN_BYTES);
|
|
132
|
+
const minimum = Number.isSafeInteger(rawMinimum) && rawMinimum > 0 ? rawMinimum : 52_428_800;
|
|
133
|
+
return runStopSweep(root, minimum, {
|
|
134
|
+
git, enabled: deps.enabled ?? (() => sweepEnabled(root, env)), exists: fs.existsSync, size: sweepFileSize, log,
|
|
135
|
+
save: async (relative, hqTop) => {
|
|
136
|
+
if (env.HQ_AUTOCOMMIT === "0")
|
|
137
|
+
return 0;
|
|
138
|
+
const absolute = path.join(root, relative);
|
|
139
|
+
let parent;
|
|
140
|
+
try {
|
|
141
|
+
parent = fs.realpathSync(path.dirname(absolute));
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
const relativeParent = path.relative(root, parent);
|
|
147
|
+
if (relativeParent === ".." || relativeParent.startsWith(`..${path.sep}`) || path.isAbsolute(relativeParent))
|
|
148
|
+
return 0;
|
|
149
|
+
const nested = deps.git ? deps.git(parent, ["rev-parse", "--show-toplevel"])
|
|
150
|
+
: (() => { const r = spawnSync("git", ["-C", parent, "rev-parse", "--show-toplevel"], { env, encoding: "utf8", timeout: 5000 }); return { code: r.status ?? 1, stdout: r.stdout ?? "" }; })();
|
|
151
|
+
// Two git outputs, as hq-autocommit.sh compares PATH_TOP with HQ_TOP:
|
|
152
|
+
// a git path is never compared with a Node path (they differ on Windows).
|
|
153
|
+
if (nested.code !== 0 || !nested.stdout.trim() || nested.stdout.trim() !== hqTop)
|
|
154
|
+
return 0;
|
|
155
|
+
const staged = git(["diff", "--cached", "--name-only"]);
|
|
156
|
+
if (staged.code !== 0)
|
|
157
|
+
return failure("diff-cached", staged, relative);
|
|
158
|
+
const warningStore = openStoreDir(path.join(root, "workspace/.autocommit-warnings"), { create: true });
|
|
159
|
+
if (staged.stdout.trim()) {
|
|
160
|
+
const count = staged.stdout.trim().split("\n").length;
|
|
161
|
+
log(`SKIP stage=prestaged staged=${count} path=${relative}`);
|
|
162
|
+
if (warningStore.ok) {
|
|
163
|
+
try {
|
|
164
|
+
const current = warningStore.value.read("prestaged-since", { maxBytes: 32 });
|
|
165
|
+
let since = current.ok ? Number(current.value.toString().trim()) : NaN;
|
|
166
|
+
if (!Number.isSafeInteger(since) || since < 0) {
|
|
167
|
+
since = Math.floor(now() / 1000);
|
|
168
|
+
warningStore.value.writeAtomic("prestaged-since", `${since}\n`);
|
|
169
|
+
}
|
|
170
|
+
const raw = env.HQ_AUTOCOMMIT_PRESTAGED_STALE_MINUTES ?? "10";
|
|
171
|
+
const minutes = /^\d+$/.test(raw) ? Number(raw) : 10;
|
|
172
|
+
if (Math.floor(now() / 1000) - since >= minutes * 60)
|
|
173
|
+
warnMessage("autocommit|prestaged", `WARNING: HQ autosave is skipping edits because the HQ git index already has ${count} staged path(s) that nobody has committed. Local HQ edits are NOT being committed until those paths are committed or unstaged (see: git diff --cached --name-only). Details: workspace/logs/hq-autocommit.log`);
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
warningStore.value.close();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return 0;
|
|
180
|
+
}
|
|
181
|
+
if (warningStore.ok) {
|
|
182
|
+
warningStore.value.remove("prestaged-since");
|
|
183
|
+
warningStore.value.close();
|
|
184
|
+
}
|
|
185
|
+
const rawStale = Number(env.HQ_AUTOCOMMIT_STALE_LOCK_MINUTES ?? 5);
|
|
186
|
+
const staleMinutes = Number.isFinite(rawStale) && rawStale >= 0 ? rawStale : 5;
|
|
187
|
+
// A refused lock folder is said where it is seen: the daemon runs this
|
|
188
|
+
// job with its output discarded, so the log is the durable record.
|
|
189
|
+
const refusedLock = (what) => {
|
|
190
|
+
log(`SKIP stage=lock reason=${JSON.stringify(what)} path=${relative}`);
|
|
191
|
+
process.stderr.write(`HQ autosave: ${what}\n`);
|
|
192
|
+
};
|
|
193
|
+
// The autosave lock lives in a private folder of this HQ root, never
|
|
194
|
+
// in a shared temporary folder that the store checks would refuse.
|
|
195
|
+
const lockFolder = openStoreDir(path.join(root, AUTOSAVE_LOCK_FOLDER), { create: true });
|
|
196
|
+
if (!lockFolder.ok) {
|
|
197
|
+
refusedLock(`autosave lock folder refused (${lockFolder.code}); local HQ edits are not being committed`);
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
lockFolder.value.close();
|
|
201
|
+
const held = acquireAutosaveLock(path.join(root, AUTOSAVE_LOCK_FOLDER, "hq-autocommit.lock"), now(), staleMinutes);
|
|
202
|
+
if (!held)
|
|
203
|
+
return 0;
|
|
204
|
+
if (held.recovered)
|
|
205
|
+
log(`RECOVER stage=lock path=${relative}`);
|
|
206
|
+
// The shell autosave (hq-autocommit.sh) still takes
|
|
207
|
+
// ${TMPDIR:-/tmp}/hq-autocommit.lock; this job holds that lock too
|
|
208
|
+
// while it can, so the two never commit at once. A shared folder that
|
|
209
|
+
// cannot hold it safely is reported, and the private lock alone runs.
|
|
210
|
+
const sharedLock = path.join(env.TMPDIR || os.tmpdir(), "hq-autocommit.lock");
|
|
211
|
+
const sharedRefusal = lockParentRefusal(sharedLock);
|
|
212
|
+
let shared;
|
|
213
|
+
if (sharedRefusal)
|
|
214
|
+
refusedLock(`shared autosave ${sharedRefusal}; continuing with the private lock only`);
|
|
215
|
+
else {
|
|
216
|
+
shared = acquireAutosaveLock(sharedLock, now(), staleMinutes);
|
|
217
|
+
if (!shared) {
|
|
218
|
+
held.release();
|
|
219
|
+
return 0;
|
|
220
|
+
}
|
|
221
|
+
if (shared.recovered)
|
|
222
|
+
log(`RECOVER stage=lock path=${relative}`);
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
const lockPath = git(["rev-parse", "--git-path", "index.lock"]);
|
|
226
|
+
if (lockPath.code === 0 && lockPath.stdout.trim()) {
|
|
227
|
+
const indexLock = path.resolve(root, lockPath.stdout.trim());
|
|
228
|
+
const within = path.relative(root, indexLock);
|
|
229
|
+
if (within !== ".." && !within.startsWith(`..${path.sep}`) && !path.isAbsolute(within)) {
|
|
230
|
+
const indexStore = openStoreDir(path.dirname(indexLock));
|
|
231
|
+
if (indexStore.ok) {
|
|
232
|
+
try {
|
|
233
|
+
const facts = indexStore.value.stat(path.basename(indexLock));
|
|
234
|
+
if (facts.ok && now() - facts.value.mtimeMs > (Number.isFinite(rawStale) && rawStale >= 0 ? rawStale : 5) * 60_000
|
|
235
|
+
&& (deps.indexLockHeld ?? (file => indexLockHeld(file, env)))(indexLock) === false) {
|
|
236
|
+
const removed = indexStore.value.remove(path.basename(indexLock));
|
|
237
|
+
if (removed.ok && removed.value)
|
|
238
|
+
log(`RECOVER stage=index-lock path=${relative}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
indexStore.value.close();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// Recheck after acquiring the shared autosave lock. A user's staged
|
|
248
|
+
// work must never be included in this commit.
|
|
249
|
+
const before = git(["diff", "--cached", "--name-only", "-z"]);
|
|
250
|
+
if (before.code !== 0 || before.stdout)
|
|
251
|
+
return 0;
|
|
252
|
+
let add = git(["add", "--", relative]);
|
|
253
|
+
for (let retry = 0; add.code !== 0 && retry < 3 && add.stderr.includes("index.lock") && add.stderr.includes("File exists"); retry++) {
|
|
254
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
255
|
+
add = git(["add", "--", relative]);
|
|
256
|
+
}
|
|
257
|
+
if (add.code !== 0)
|
|
258
|
+
return failure("add", add, relative);
|
|
259
|
+
const after = git(["diff", "--cached", "--name-only", "-z"]);
|
|
260
|
+
if (after.code !== 0)
|
|
261
|
+
return 0;
|
|
262
|
+
const paths = after.stdout.split("\0").filter(Boolean);
|
|
263
|
+
if (paths.some(name => name !== relative)) {
|
|
264
|
+
git(["reset", "-q", "--", relative]);
|
|
265
|
+
log(`SKIP stage=foreign-staged path=${relative}`);
|
|
266
|
+
return 0;
|
|
267
|
+
}
|
|
268
|
+
const mode = git(["ls-files", "--stage", "--", relative]);
|
|
269
|
+
if (mode.code !== 0 || /^160000 /m.test(mode.stdout)) {
|
|
270
|
+
git(["reset", "-q", "--", relative]);
|
|
271
|
+
return 0;
|
|
272
|
+
}
|
|
273
|
+
const changed = git(["diff", "--cached", "--quiet", "--", relative]);
|
|
274
|
+
if (changed.code !== 1)
|
|
275
|
+
return 0;
|
|
276
|
+
const display = relative.length > 72 ? relative.slice(0, 69) + "..." : relative;
|
|
277
|
+
const commit = git(["-c", "gc.auto=0", "-c", "maintenance.auto=false", "commit", "--no-verify", "-m", `autosave(hq): ${display}`]);
|
|
278
|
+
if (commit.code !== 0)
|
|
279
|
+
return failure("commit", commit, relative);
|
|
280
|
+
return 0;
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
shared?.release();
|
|
284
|
+
held.release();
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
export function registerCoreStopAutosave(core) {
|
|
290
|
+
const command = core.command("stop-autosave").description("Drain the typed Stop autosave job")
|
|
291
|
+
.requiredOption("--session-id <id>")
|
|
292
|
+
.action(async (options) => {
|
|
293
|
+
const root = core.opts().hqRoot || process.env.CLAUDE_PROJECT_DIR || process.env.HQ_ROOT;
|
|
294
|
+
if (!root)
|
|
295
|
+
throw new Error("Stop autosave requires an HQ root");
|
|
296
|
+
process.exitCode = await stopAutosave(root, options.sessionId, process.env);
|
|
297
|
+
});
|
|
298
|
+
describeCoreCommand(command, { execution: "native", root: "live" });
|
|
299
|
+
}
|
|
300
|
+
//# sourceMappingURL=core-stop-autosave.js.map
|