Own passive source update checks in Python
Use the exact target root and profile for branch, release, and cache decisions. Keep the desktop as a transport and handoff adapter. Remove the competing TypeScript checker and switch the banner, dashboard, and updater count consumers. Preserve fork origins, unknown counts, publication checks, old-probe recovery, and official SSH branch healing through public HTTPS. Keep the historical unstamped-root policy unchanged.
This commit is contained in:
1 parent
03d3c46697
commit
cfebdfd466
33 files changed
+728
-1771
No files matched your search
@@ -411,7 +411,6 @@ import {
|
||||
} from './translucency'
|
||||
import { waitForUpdateClearance } from './update-gate'
|
||||
import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'
|
||||
import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from './update-remote'
|
||||
import {
|
||||
resolveUpdaterMechanism,
|
||||
type UpdaterApplyResultWire,
|
||||
@@ -2976,12 +2975,6 @@ function runGit(args, options: any = {}): Promise<{ code: number; stdout: string
|
||||
|
||||
const firstLine = text => (text || '').split('\n').find(Boolean) || ''
|
||||
|
||||
async function getOriginUrl(updateRoot) {
|
||||
const origin = await runGit(['remote', 'get-url', 'origin'], { cwd: updateRoot })
|
||||
|
||||
return origin.code === 0 ? origin.stdout.trim() : ''
|
||||
}
|
||||
|
||||
function emitUpdateProgress(payload) {
|
||||
const merged = { stage: 'idle', message: '', percent: null, error: null, ...payload, at: Date.now() }
|
||||
rememberLog(`[updates] ${merged.stage}: ${merged.message || merged.error || ''}`)
|
||||
@@ -2991,35 +2984,6 @@ function emitUpdateProgress(payload) {
|
||||
}
|
||||
}
|
||||
|
||||
// Self-heal the tracked update branch: if origin no longer publishes it (e.g.
|
||||
// bb/gui was merged into main and deleted), fall back to main and persist so
|
||||
// every later check/apply follows main — no manual flip, even for already-
|
||||
// installed clients. Read-only ls-remote probe; only flips on a definitive
|
||||
// "ref absent" (exit 2), never on a transient network error, so a flaky
|
||||
// connection can't strand a user on the wrong branch.
|
||||
async function resolveHealedBranch(updateRoot, branch) {
|
||||
if (!branch || branch === 'main') {
|
||||
return branch || 'main'
|
||||
}
|
||||
|
||||
const originUrl = await getOriginUrl(updateRoot)
|
||||
const remote = isOfficialSshRemote(originUrl) ? OFFICIAL_REPO_HTTPS_URL : 'origin'
|
||||
const probe = await runGit(['ls-remote', '--exit-code', '--heads', remote, branch], { cwd: updateRoot })
|
||||
|
||||
if (probe.code !== 2) {
|
||||
return branch
|
||||
}
|
||||
|
||||
rememberLog(`[updates] origin/${branch} is gone (merged?); falling back to main`)
|
||||
const config = readDesktopUpdateConfig()
|
||||
|
||||
if (config.branch !== 'main') {
|
||||
writeDesktopUpdateConfig({ ...config, branch: 'main' })
|
||||
}
|
||||
|
||||
return 'main'
|
||||
}
|
||||
|
||||
async function checkUpdates(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {
|
||||
// A packaged install delegates to the update owner named by its stamp.
|
||||
let strategy: UpdaterStrategy | null = null
|
||||
@@ -3044,19 +3008,6 @@ async function checkUpdates(opts: { force?: boolean } = {}): Promise<UpdaterStat
|
||||
return resolveCheckoutUpdateStrategy().check(opts)
|
||||
}
|
||||
|
||||
async function fetchGitHubApi(url: string, accept: string = 'application/vnd.github+json'): Promise<unknown> {
|
||||
const response = await fetch(url, {
|
||||
headers: { Accept: accept, 'User-Agent': 'hermes-desktop-update-check' },
|
||||
signal: AbortSignal.timeout(10_000)
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
return accept === 'application/vnd.github.sha' ? response.text() : response.json()
|
||||
}
|
||||
|
||||
let updateInFlight = false
|
||||
|
||||
// ── bundled / App Installer helpers ─────────────────────────────────────────
|
||||
@@ -3191,24 +3142,17 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
|
||||
defaultUpdateBranch: DEFAULT_UPDATE_BRANCH,
|
||||
updateHandoffDwellMs: UPDATE_HANDOFF_DWELL_MS,
|
||||
directoryExists,
|
||||
readCanonicalInstallStamp,
|
||||
readDesktopUpdateConfig,
|
||||
readSourceUpdate: (updateRoot: string): Promise<SourceUpdate | null> => readSourceUpdate({
|
||||
readSourceUpdate: (updateRoot: string, opts: { force?: boolean }): Promise<SourceUpdate | null> => readSourceUpdate({
|
||||
python: findPythonForRoot(updateRoot),
|
||||
git: resolveGitBinary(),
|
||||
updateRoot,
|
||||
hermesHome: HERMES_HOME
|
||||
hermesHome: HERMES_HOME,
|
||||
branchConfigPath: DESKTOP_UPDATE_CONFIG_PATH,
|
||||
force: opts.force
|
||||
}),
|
||||
resolveUpdateRoot,
|
||||
resolveUpdaterBinary,
|
||||
resolveHealedBranch,
|
||||
getOriginUrl,
|
||||
runGit,
|
||||
firstLine,
|
||||
fetchGitHubApi,
|
||||
isGitCheckout,
|
||||
updateCheckCachePath: path.join(app.getPath('userData'), 'update-check-cache.json'),
|
||||
writeFileAtomic,
|
||||
|
||||
emitUpdateProgress,
|
||||
rememberLog,
|
||||
@@ -3911,9 +3855,8 @@ async function handOffWindowsBootstrapRecovery(reason) {
|
||||
const updateRoot = resolveUpdateRoot()
|
||||
const { branch: configuredBranch } = readDesktopUpdateConfig()
|
||||
|
||||
const branch = isGitCheckout(updateRoot)
|
||||
? await resolveHealedBranch(updateRoot, configuredBranch || DEFAULT_UPDATE_BRANCH)
|
||||
: configuredBranch || DEFAULT_UPDATE_BRANCH
|
||||
// Recovery can run without Python. Keep the chosen branch; do not guess a replacement.
|
||||
const branch: string = configuredBranch || DEFAULT_UPDATE_BRANCH
|
||||
|
||||
const updaterArgs: string[] = chooseUpdaterArgs(
|
||||
{ runtimeUsable: isSourceRuntimeUsable(updateRoot) },
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
/**
|
||||
* Tests for electron/update-api-check.ts — the API-first passive update check.
|
||||
*
|
||||
* Why this exists: every desktop client used to `git fetch` twice every 30
|
||||
* minutes. GitHub measured tens of millions of fetch/clone requests per day
|
||||
* from the install base and asked us to poll via the API instead. These pin
|
||||
* the two load-bearing contracts: the cache answers passive checks for a full
|
||||
* day but invalidates the moment HEAD moves, and the compare payload maps to
|
||||
* an honest behind count (never a fabricated one).
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { test } from 'vitest'
|
||||
|
||||
import {
|
||||
branchTipApiUrl,
|
||||
cacheIsFresh,
|
||||
githubRepoSlug,
|
||||
parseCompare,
|
||||
UPDATE_CHECK_FAILURE_TTL_MS,
|
||||
UPDATE_CHECK_TTL_MS
|
||||
} from './update-api-check'
|
||||
|
||||
const SHA_A = 'a'.repeat(40)
|
||||
const SHA_B = 'b'.repeat(40)
|
||||
const HOUR = 60 * 60 * 1000
|
||||
|
||||
test('cache serves a passive check for 24h, but not once HEAD or the branch changes', () => {
|
||||
const cached = { fetchedAt: 0, currentSha: SHA_A, branch: 'main', status: { behind: 0 } }
|
||||
|
||||
assert.equal(cacheIsFresh(cached, { branch: 'main', currentSha: SHA_A, now: UPDATE_CHECK_TTL_MS - 1 }), true)
|
||||
assert.equal(cacheIsFresh(cached, { branch: 'main', currentSha: SHA_A, now: UPDATE_CHECK_TTL_MS }), false)
|
||||
// Applying an update moves HEAD: a stale "update available" must never survive it.
|
||||
assert.equal(cacheIsFresh(cached, { branch: 'main', currentSha: SHA_B, now: 1 }), false)
|
||||
assert.equal(cacheIsFresh(cached, { branch: 'bb/gui', currentSha: SHA_A, now: 1 }), false)
|
||||
|
||||
// Failures retry sooner than successes, but still not on every tick.
|
||||
const failed = { ...cached, status: { error: 'fetch-failed' } }
|
||||
assert.equal(cacheIsFresh(failed, { branch: 'main', currentSha: SHA_A, now: UPDATE_CHECK_FAILURE_TTL_MS - 1 }), true)
|
||||
assert.equal(cacheIsFresh(failed, { branch: 'main', currentSha: SHA_A, now: 2 * HOUR }), false)
|
||||
})
|
||||
|
||||
test('compare payload maps to the behind count and a newest-first commit list; malformed = null', () => {
|
||||
const payload = {
|
||||
ahead_by: 2,
|
||||
status: 'ahead',
|
||||
commits: [
|
||||
{
|
||||
sha: SHA_A,
|
||||
commit: { message: 'fix: older\n\nbody', author: { name: 'A' }, committer: { date: '2026-09-10T00:00:00Z' } }
|
||||
},
|
||||
{
|
||||
sha: SHA_B,
|
||||
commit: { message: 'feat: newer', author: { name: 'B' }, committer: { date: '2026-09-10T01:00:00Z' } }
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const parsed = parseCompare(payload)
|
||||
assert.equal(parsed?.behind, 2)
|
||||
assert.deepEqual(
|
||||
parsed?.commits.map(c => [c.sha, c.summary, c.author]),
|
||||
[
|
||||
[SHA_B, 'feat: newer', 'B'],
|
||||
[SHA_A, 'fix: older', 'A']
|
||||
]
|
||||
)
|
||||
|
||||
assert.equal(parseCompare({ ahead_by: -1 }), null)
|
||||
assert.equal(parseCompare({ status: 'ahead' }), null)
|
||||
assert.equal(parseCompare('nope'), null)
|
||||
|
||||
// Forks and SSH forms hit the API for their own repo; non-GitHub origins don't.
|
||||
assert.equal(githubRepoSlug('git@github.com:Someone/hermes-agent.git'), 'someone/hermes-agent')
|
||||
assert.equal(githubRepoSlug('https://gitlab.example/x/y.git'), null)
|
||||
assert.equal(
|
||||
branchTipApiUrl('nousresearch/hermes-agent', 'bb/gui'),
|
||||
'https://api.github.com/repos/nousresearch/hermes-agent/commits/bb%2Fgui'
|
||||
)
|
||||
})
|
||||
@@ -1,111 +0,0 @@
|
||||
/**
|
||||
* Passive update checks against the GitHub REST API instead of git.
|
||||
*
|
||||
* Every desktop client used to run `git fetch origin <branch>` (or `ls-remote`)
|
||||
* twice every 30 minutes, plus on each window focus. Multiplied across the
|
||||
* install base that is tens of millions of pack negotiations a day against one
|
||||
* repo — GitHub flagged it. A passive check only needs two facts the API gives
|
||||
* for free: the remote tip SHA (`GET /repos/{repo}/commits/{branch}` with the
|
||||
* `application/vnd.github.sha` media type — a 40-byte body) and, when the tips
|
||||
* differ, the compare endpoint's `ahead_by` + `commits[]`. `git fetch` now
|
||||
* runs only when the user actually applies an update.
|
||||
*
|
||||
* Pure helpers here (URL builders, cache policy, payload mapping) so they are
|
||||
* unit-testable without booting Electron; the bounded network call is injected.
|
||||
*/
|
||||
|
||||
import { canonicalGitHubRemote } from './update-remote'
|
||||
|
||||
export const UPDATE_CHECK_TTL_MS = 24 * 60 * 60 * 1000
|
||||
// A failed check (offline, 403 rate-limit) is retried sooner than a good one,
|
||||
// but never on every poller tick.
|
||||
export const UPDATE_CHECK_FAILURE_TTL_MS = 60 * 60 * 1000
|
||||
|
||||
export interface CachedUpdateCheck {
|
||||
fetchedAt: number
|
||||
currentSha: string
|
||||
branch: string
|
||||
status: Record<string, unknown> & { error?: string }
|
||||
}
|
||||
|
||||
/** `owner/repo` for any GitHub remote form; null for non-GitHub origins. */
|
||||
export function githubRepoSlug(originUrl: string): string | null {
|
||||
const canonical = canonicalGitHubRemote(originUrl)
|
||||
const match = /^github\.com\/([^/]+\/[^/]+)$/.exec(canonical)
|
||||
|
||||
return match ? match[1] : null
|
||||
}
|
||||
|
||||
export function branchTipApiUrl(slug: string, branch: string): string {
|
||||
return `https://api.github.com/repos/${slug}/commits/${encodeURIComponent(branch)}`
|
||||
}
|
||||
|
||||
export function compareApiUrl(slug: string, currentSha: string, targetSha: string): string {
|
||||
return `https://api.github.com/repos/${slug}/compare/${currentSha}...${targetSha}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a cached result still answers a passive check. The cache is keyed on
|
||||
* the local HEAD and branch: applying an update or switching branches changes
|
||||
* HEAD and invalidates it immediately, so a 24h TTL never shows a stale
|
||||
* "update available" after the user just updated.
|
||||
*/
|
||||
export function cacheIsFresh(
|
||||
cached: CachedUpdateCheck | null | undefined,
|
||||
{ branch, currentSha, now }: { branch: string; currentSha: string; now: number }
|
||||
): boolean {
|
||||
if (!cached || cached.branch !== branch || cached.currentSha !== currentSha) {
|
||||
return false
|
||||
}
|
||||
|
||||
const ttl = cached.status.error ? UPDATE_CHECK_FAILURE_TTL_MS : UPDATE_CHECK_TTL_MS
|
||||
|
||||
return now - cached.fetchedAt < ttl
|
||||
}
|
||||
|
||||
export interface CompareCommit {
|
||||
sha: string
|
||||
summary: string
|
||||
author: string
|
||||
at: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Map the compare payload to the shape the update overlay renders. `ahead_by`
|
||||
* is how far the remote tip is ahead of local HEAD, i.e. the behind count; 0
|
||||
* with differing tips means local carries commits on top of origin (not
|
||||
* behind). Any shape surprise returns null so callers keep the honest
|
||||
* "update available, count unknown" state instead of trusting a partial answer.
|
||||
*/
|
||||
export function parseCompare(payload: unknown): { behind: number; commits: CompareCommit[] } | null {
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return null
|
||||
}
|
||||
|
||||
const ahead = (payload as { ahead_by?: unknown }).ahead_by
|
||||
|
||||
if (typeof ahead !== 'number' || !Number.isInteger(ahead) || ahead < 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const raw = (payload as { commits?: unknown }).commits
|
||||
|
||||
const commits: CompareCommit[] = Array.isArray(raw)
|
||||
? raw
|
||||
.map(entry => {
|
||||
const sha = typeof entry?.sha === 'string' ? entry.sha : ''
|
||||
const message = typeof entry?.commit?.message === 'string' ? entry.commit.message : ''
|
||||
const author = typeof entry?.commit?.author?.name === 'string' ? entry.commit.author.name : ''
|
||||
|
||||
const date =
|
||||
typeof entry?.commit?.committer?.date === 'string' ? Date.parse(entry.commit.committer.date) : NaN
|
||||
|
||||
return { sha, summary: message.split('\n')[0], author, at: Number.isFinite(date) ? date : 0 }
|
||||
})
|
||||
.filter(commit => commit.sha)
|
||||
// The overlay lists newest first; compare returns oldest first.
|
||||
.reverse()
|
||||
: []
|
||||
|
||||
return { behind: ahead, commits }
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* Tests for electron/update-root-policy.ts — the pure classifier that decides
|
||||
* whether the desktop's git-based self-update may run against a resolved
|
||||
* update root. A checkout the install contract does not manage (steward-owned
|
||||
* `external`/`electron-updater` mechanisms) must be refused with a user-action
|
||||
* pointer instead of the desktop pulling into it.
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { test } from 'vitest'
|
||||
|
||||
import { classifyUpdateRoot } from './update-root-policy'
|
||||
|
||||
test('a non-git root is not updatable and carries no user advice', () => {
|
||||
const result = classifyUpdateRoot({ isGitTree: false, updateMechanism: null })
|
||||
|
||||
assert.equal(result.updatable, false)
|
||||
assert.equal(result.verdict, 'not-a-checkout')
|
||||
assert.equal(result.provenance, 'not-a-checkout')
|
||||
assert.equal(result.advice, null)
|
||||
assert.ok(result.message)
|
||||
})
|
||||
|
||||
test('a self-managed checkout is updatable', () => {
|
||||
const result = classifyUpdateRoot({ isGitTree: true, updateMechanism: 'self' })
|
||||
|
||||
assert.equal(result.updatable, true)
|
||||
assert.equal(result.verdict, 'updatable')
|
||||
assert.equal(result.provenance, 'managed-self')
|
||||
assert.equal(result.advice, null)
|
||||
assert.equal(result.message, null)
|
||||
})
|
||||
|
||||
test.each(['external', 'electron-updater', 'app-installer'] as const)('a %s-owned checkout is never git-updated by the desktop', updateMechanism => {
|
||||
const result = classifyUpdateRoot({ isGitTree: true, updateMechanism })
|
||||
|
||||
assert.equal(result.updatable, false)
|
||||
assert.equal(result.verdict, 'steward-owned-git-tree')
|
||||
assert.equal(result.provenance, 'steward-owned')
|
||||
assert.equal(result.advice, 'git pull')
|
||||
assert.ok(result.message?.includes(updateMechanism))
|
||||
})
|
||||
|
||||
test('an unstamped git tree (dev checkout) stays updatable with unknown provenance', () => {
|
||||
const result = classifyUpdateRoot({ isGitTree: true, updateMechanism: null })
|
||||
|
||||
assert.equal(result.updatable, true)
|
||||
assert.equal(result.verdict, 'updatable')
|
||||
assert.equal(result.provenance, 'unknown')
|
||||
assert.equal(result.advice, null)
|
||||
})
|
||||
|
||||
test('the classification is a pure function of its inputs', () => {
|
||||
const facts = { isGitTree: true, updateMechanism: 'external' as const }
|
||||
assert.deepEqual(classifyUpdateRoot(facts), classifyUpdateRoot({ ...facts }))
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
// update-root-policy.ts — pure classifier for the desktop self-update root.
|
||||
//
|
||||
// The desktop's git-based self-update arm runs `git fetch/merge` against a
|
||||
// checkout it resolved (resolveUpdateRoot in main.ts). That root is only
|
||||
// legitimate update territory when the install contract says so:
|
||||
//
|
||||
// - Not a `.git` tree → there is nothing to pull; the desktop cannot
|
||||
// self-update here (bundled installs use the OS App Installer arm and
|
||||
// never reach this classifier).
|
||||
// - A `.git` tree whose install stamp says `updateMechanism: "self"` → the
|
||||
// install is a managed self-updating checkout (e.g. the desktop
|
||||
// bootstrap's clone, which writes exactly that stamp) — updatable.
|
||||
// - A `.git` tree with any OTHER mechanism (`external`: the store/steward
|
||||
// owns updates; `electron-updater`: the desktop package does) → the tree
|
||||
// is managed by someone else. Pulling into it from the desktop would
|
||||
// stash-and-move a user's checkout out from under its steward.
|
||||
// - No stamp at all (null mechanism; a dev source checkout) → provenance
|
||||
// unknown. The classifier reports `updatable` with `provenance:
|
||||
// 'unknown'`: a developer's working tree keeps its existing update flow,
|
||||
// and callers log the ambiguity rather than silently widening the refusal.
|
||||
//
|
||||
// Pure and dependency-injected (same shape as update-gate.ts) so the policy
|
||||
// is unit-testable without booting Electron, and every caller gets the same
|
||||
// answer from one authority.
|
||||
|
||||
import type { InstallStamp } from './install-stamp'
|
||||
|
||||
export type UpdateRootProvenance = 'managed-self' | 'steward-owned' | 'unknown' | 'not-a-checkout'
|
||||
|
||||
export interface UpdateRootClassification {
|
||||
/** Whether the desktop's git-based self-update may run against this root. */
|
||||
updatable: boolean
|
||||
/** Machine-readable verdict for update-check results and logs. */
|
||||
verdict: 'updatable' | 'not-a-checkout' | 'steward-owned-git-tree' | 'unmanaged-git-tree'
|
||||
/** Why the root is (or is not) updatable, for user-facing messages. */
|
||||
message: string | null
|
||||
/** The command that fixes it, when the user (not the app) must act. */
|
||||
advice: 'git pull' | null
|
||||
provenance: UpdateRootProvenance
|
||||
}
|
||||
|
||||
export interface UpdateRootFacts {
|
||||
/** True when the resolved update root contains a `.git` entry. */
|
||||
isGitTree: boolean
|
||||
/** The install stamp's updateMechanism, or null when there is no stamp. */
|
||||
updateMechanism: InstallStamp['updateMechanism'] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify whether the desktop may self-update (git pull semantics) against
|
||||
* the resolved update root.
|
||||
*/
|
||||
export function classifyUpdateRoot(facts: UpdateRootFacts): UpdateRootClassification {
|
||||
if (!facts.isGitTree) {
|
||||
return {
|
||||
updatable: false,
|
||||
verdict: 'not-a-checkout',
|
||||
message: 'This install has no git checkout to update — the app or its steward owns the update loop.',
|
||||
advice: null,
|
||||
provenance: 'not-a-checkout'
|
||||
}
|
||||
}
|
||||
|
||||
if (facts.updateMechanism === 'self') {
|
||||
return {
|
||||
updatable: true,
|
||||
verdict: 'updatable',
|
||||
message: null,
|
||||
advice: null,
|
||||
provenance: 'managed-self'
|
||||
}
|
||||
}
|
||||
|
||||
if (facts.updateMechanism !== null) {
|
||||
return {
|
||||
updatable: false,
|
||||
verdict: 'steward-owned-git-tree',
|
||||
message:
|
||||
`This checkout is managed by its install method (${facts.updateMechanism}); ` +
|
||||
'the desktop will not run git updates against it.',
|
||||
advice: 'git pull',
|
||||
provenance: 'steward-owned'
|
||||
}
|
||||
}
|
||||
|
||||
// No stamp: unknown provenance (typically a developer source checkout).
|
||||
return {
|
||||
updatable: true,
|
||||
verdict: 'updatable',
|
||||
message: null,
|
||||
advice: null,
|
||||
provenance: 'unknown'
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import * as fs from 'node:fs'
|
||||
import * as http from 'node:http'
|
||||
import type { AddressInfo } from 'node:net'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
|
||||
import { expect, it } from 'vitest'
|
||||
|
||||
import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
|
||||
|
||||
it('checks a real linked worktree through HTTP and reuses the disk cache until forced or HEAD changes', async (): Promise<void> => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-update-worktree-'))
|
||||
const checkout = path.join(root, 'source')
|
||||
const worktree = path.join(root, 'worktree')
|
||||
const requests: string[] = []
|
||||
|
||||
const server = http.createServer((request: http.IncomingMessage, response: http.ServerResponse): void => {
|
||||
requests.push(request.url ?? '')
|
||||
response.end(targetSha)
|
||||
})
|
||||
|
||||
let targetSha = ''
|
||||
|
||||
function git(args: string[], cwd: string = checkout): string {
|
||||
return execFileSync('git', ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', ...args], {
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
}).trim()
|
||||
}
|
||||
|
||||
try {
|
||||
fs.mkdirSync(checkout)
|
||||
git(['init', '--initial-branch=main'])
|
||||
git(['commit', '--allow-empty', '-m', 'initial'])
|
||||
git(['remote', 'add', 'origin', 'https://github.com/example/test.git'])
|
||||
git(['worktree', 'add', '--detach', worktree])
|
||||
targetSha = git(['rev-parse', 'HEAD'])
|
||||
await new Promise<void>((resolve: () => void): void => { server.listen(0, '127.0.0.1', resolve) })
|
||||
const address = server.address() as AddressInfo
|
||||
|
||||
const deps: CheckoutCheckDeps = {
|
||||
updateCheckCachePath: path.join(root, 'cache.json'),
|
||||
writeFileAtomic: (filePath: string, contents: string): void => {
|
||||
fs.writeFileSync(`${filePath}.tmp`, contents)
|
||||
fs.renameSync(`${filePath}.tmp`, filePath)
|
||||
},
|
||||
isGitCheckout: (directory: string): boolean => fs.existsSync(path.join(directory, '.git')),
|
||||
readCanonicalInstallStamp: (): null => null,
|
||||
readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'main' }),
|
||||
resolveUpdateRoot: (): string => worktree,
|
||||
resolveHealedBranch: async (_directory: string, branch: string): Promise<string> => branch,
|
||||
getOriginUrl: async (directory: string): Promise<string> => git(['remote', 'get-url', 'origin'], directory),
|
||||
runGit: async (args: string[], options?: { cwd?: string }): Promise<{ code: number; stdout: string; stderr: string }> => {
|
||||
// A passive check must not use git to contact the configured remote.
|
||||
expect(['rev-parse', 'status']).toContain(args[0])
|
||||
|
||||
return { code: 0, stdout: git(args, options?.cwd), stderr: '' }
|
||||
},
|
||||
readSourceUpdate: async (): Promise<{ channel: 'main' }> => ({ channel: 'main' }),
|
||||
fetchGitHubApi: async (url: string, accept?: string): Promise<unknown> => {
|
||||
const parsed = new URL(url)
|
||||
expect(parsed.hostname).toBe('api.github.com')
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${address.port}${parsed.pathname}`, {
|
||||
headers: { Accept: accept ?? 'application/json' }
|
||||
})
|
||||
|
||||
return response.text()
|
||||
},
|
||||
rememberLog: (message: unknown): void => { throw new Error(String(message)) }
|
||||
}
|
||||
|
||||
expect(fs.statSync(path.join(worktree, '.git')).isFile()).toBe(true)
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({ supported: true, currentSha: targetSha, updateAvailable: false })
|
||||
expect(requests).toHaveLength(1)
|
||||
await checkCheckoutUpdates({ ...deps })
|
||||
expect(requests).toHaveLength(1)
|
||||
await checkCheckoutUpdates(deps, { force: true })
|
||||
expect(requests).toHaveLength(2)
|
||||
git(['commit', '--allow-empty', '-m', 'advance'], worktree)
|
||||
targetSha = git(['rev-parse', 'HEAD'], worktree)
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({ currentSha: targetSha, updateAvailable: false })
|
||||
expect(requests).toHaveLength(3)
|
||||
} finally {
|
||||
server.closeAllConnections()
|
||||
await new Promise<void>((resolve: () => void): void => { server.close((): void => resolve()) })
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -1,156 +0,0 @@
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
|
||||
|
||||
const roots: string[] = []
|
||||
afterEach((): void => {
|
||||
for (const root of roots.splice(0)) {
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function fixture(): CheckoutCheckDeps {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'checkout-check-'))
|
||||
roots.push(root)
|
||||
|
||||
return {
|
||||
writeFileAtomic: (filePath: string, contents: string): void => fs.writeFileSync(filePath, contents),
|
||||
updateCheckCachePath: path.join(root, 'cache.json'),
|
||||
isGitCheckout: (): boolean => true,
|
||||
readCanonicalInstallStamp: (): null => null,
|
||||
readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'main' }),
|
||||
resolveUpdateRoot: (): string => root,
|
||||
resolveHealedBranch: async (_root: string, branch: string): Promise<string> => branch,
|
||||
getOriginUrl: async (): Promise<string> => 'git@github.com:NousResearch/hermes-agent.git',
|
||||
runGit: vi.fn(async (args: string[]): Promise<{ code: number; stdout: string; stderr: string }> => {
|
||||
const key = args.join(' ')
|
||||
|
||||
if (key === 'rev-parse HEAD') {
|
||||
return { code: 0, stdout: 'a'.repeat(40), stderr: '' }
|
||||
}
|
||||
|
||||
if (key === 'rev-parse --abbrev-ref HEAD') {
|
||||
return { code: 0, stdout: 'main', stderr: '' }
|
||||
}
|
||||
|
||||
if (key === 'status --porcelain') {
|
||||
return { code: 0, stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected git operation: ${key}`)
|
||||
}),
|
||||
readSourceUpdate: async (): Promise<{ channel: 'main' }> => ({ channel: 'main' }),
|
||||
fetchGitHubApi: vi.fn(async (url: string): Promise<unknown> =>
|
||||
url.includes('/commits/') ? 'b'.repeat(40) : { ahead_by: 3, commits: [] }
|
||||
),
|
||||
rememberLog: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
it('uses API checks and a disk cache while a forced check bypasses the cache', async (): Promise<void> => {
|
||||
const deps = fixture()
|
||||
const first = await checkCheckoutUpdates(deps)
|
||||
expect(first.behind).toBe(3)
|
||||
expect(first.updateAvailable).toBe(true)
|
||||
expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(2)
|
||||
expect(await checkCheckoutUpdates(deps)).toEqual(first)
|
||||
expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(2)
|
||||
await checkCheckoutUpdates(deps, { force: true })
|
||||
expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('follows the current branch unless config explicitly overrides it, including cached checks', async (): Promise<void> => {
|
||||
const deps: CheckoutCheckDeps = fixture()
|
||||
const localGit: CheckoutCheckDeps['runGit'] = deps.runGit
|
||||
let currentBranch: string = 'feature/foo'
|
||||
let configuredBranch: string = 'main'
|
||||
let branchExplicit: boolean = false
|
||||
deps.readDesktopUpdateConfig = (): { branch: string; branchExplicit: boolean } => ({
|
||||
branch: configuredBranch,
|
||||
branchExplicit
|
||||
})
|
||||
deps.runGit = async (
|
||||
args: string[],
|
||||
options?: { cwd?: string }
|
||||
): Promise<{ code: number; stdout: string; stderr: string }> =>
|
||||
args.join(' ') === 'rev-parse --abbrev-ref HEAD'
|
||||
? { code: 0, stdout: currentBranch, stderr: '' }
|
||||
: localGit(args, options)
|
||||
|
||||
for (const scenario of [
|
||||
{ current: 'feature/foo', configured: 'main', explicit: false, target: 'feature/foo' },
|
||||
{ current: 'feature/foo', configured: 'main', explicit: true, target: 'main' },
|
||||
{ current: 'feature/foo', configured: 'release/next', explicit: true, target: 'release/next' },
|
||||
{ current: 'feature/foo', configured: 'main', explicit: false, target: 'feature/foo' },
|
||||
{ current: 'feature/bar', configured: 'main', explicit: false, target: 'feature/bar' },
|
||||
{ current: 'HEAD', configured: 'main', explicit: false, target: 'main' },
|
||||
{ current: '', configured: 'main', explicit: false, target: 'main' }
|
||||
]) {
|
||||
currentBranch = scenario.current
|
||||
configuredBranch = scenario.configured
|
||||
branchExplicit = scenario.explicit
|
||||
vi.mocked(deps.fetchGitHubApi).mockClear()
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({
|
||||
branch: scenario.target,
|
||||
currentBranch,
|
||||
targetSha: 'b'.repeat(40)
|
||||
})
|
||||
|
||||
if (currentBranch) {
|
||||
expect(deps.fetchGitHubApi).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`/commits/${encodeURIComponent(scenario.target)}`),
|
||||
'application/vnd.github.sha'
|
||||
)
|
||||
}
|
||||
|
||||
vi.mocked(deps.fetchGitHubApi).mockClear()
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({ branch: scenario.target, currentBranch })
|
||||
expect(deps.fetchGitHubApi).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not report locally ahead commits as an update', async (): Promise<void> => {
|
||||
const deps = fixture()
|
||||
deps.fetchGitHubApi = async (url: string): Promise<unknown> =>
|
||||
url.includes('/commits/') ? 'b'.repeat(40) : { ahead_by: 0 }
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({ behind: 0, updateAvailable: false, commits: [] })
|
||||
})
|
||||
|
||||
it('keeps an unknown count when the compare API fails', async (): Promise<void> => {
|
||||
const deps = fixture()
|
||||
|
||||
deps.fetchGitHubApi = async (url: string): Promise<unknown> => {
|
||||
if (url.includes('/commits/')) {
|
||||
return 'b'.repeat(40)
|
||||
}
|
||||
|
||||
throw new Error('rate limited')
|
||||
}
|
||||
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({ behind: null, updateAvailable: true })
|
||||
})
|
||||
|
||||
it('uses only ls-remote for non-GitHub network checks', async (): Promise<void> => {
|
||||
const deps = fixture()
|
||||
const localGit = deps.runGit
|
||||
deps.getOriginUrl = async (): Promise<string> => 'https://git.example/repo.git'
|
||||
deps.runGit = vi.fn(
|
||||
async (args: string[], options: { cwd?: string }): Promise<{ code: number; stdout: string; stderr: string }> => {
|
||||
if (args[0] === 'ls-remote') {
|
||||
return { code: 0, stdout: `${'b'.repeat(40)}\trefs/heads/main`, stderr: '' }
|
||||
}
|
||||
|
||||
if (args[0] === 'cat-file') {
|
||||
return { code: 1, stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
return localGit(args, options)
|
||||
}
|
||||
)
|
||||
expect(await checkCheckoutUpdates(deps)).toMatchObject({ behind: null, updateAvailable: true })
|
||||
expect(deps.fetchGitHubApi).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -1,207 +0,0 @@
|
||||
import * as fs from 'node:fs'
|
||||
import * as path from 'node:path'
|
||||
|
||||
import type { InstallStamp } from '../install-stamp'
|
||||
import { branchTipApiUrl, cacheIsFresh, compareApiUrl, githubRepoSlug, parseCompare } from '../update-api-check'
|
||||
import { classifyUpdateRoot } from '../update-root-policy'
|
||||
|
||||
import { SOURCE_PROBE_RECOVERY, type SourceUpdate } from './checkout-source'
|
||||
|
||||
import type { UpdaterStatusWire } from './index'
|
||||
|
||||
export interface CheckoutCheckDeps {
|
||||
writeFileAtomic: (filePath: string, contents: string) => void
|
||||
updateCheckCachePath: string
|
||||
isGitCheckout: (root: string) => boolean
|
||||
readCanonicalInstallStamp: () => { updateMechanism?: InstallStamp['updateMechanism'] } | null
|
||||
readDesktopUpdateConfig: () => { branch: string; branchExplicit?: boolean }
|
||||
readSourceUpdate: (root: string) => Promise<SourceUpdate | null>
|
||||
resolveUpdateRoot: () => string
|
||||
resolveHealedBranch: (root: string, branch: string) => Promise<string>
|
||||
getOriginUrl: (root: string) => Promise<string>
|
||||
runGit: (args: string[], options?: { cwd?: string }) => Promise<{ code: number; stdout: string; stderr: string }>
|
||||
fetchGitHubApi: (url: string, accept?: string) => Promise<unknown>
|
||||
rememberLog: (chunk: unknown) => void
|
||||
}
|
||||
|
||||
interface CachedCheckoutCheck {
|
||||
fetchedAt: number
|
||||
currentSha: string
|
||||
branch: string
|
||||
originUrl: string
|
||||
updateRoot: string
|
||||
status: UpdaterStatusWire & Record<string, unknown>
|
||||
}
|
||||
|
||||
function readCache(filePath: string): CachedCheckoutCheck | null {
|
||||
try {
|
||||
const cached: CachedCheckoutCheck = JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
||||
|
||||
return cached?.status?.supported === true ? cached : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function checkApi(
|
||||
deps: CheckoutCheckDeps,
|
||||
slug: string,
|
||||
branch: string,
|
||||
currentSha: string
|
||||
): Promise<Partial<UpdaterStatusWire>> {
|
||||
let targetSha: string
|
||||
|
||||
try {
|
||||
targetSha = String(await deps.fetchGitHubApi(branchTipApiUrl(slug, branch), 'application/vnd.github.sha')).trim()
|
||||
} catch (error: unknown) {
|
||||
return { error: 'fetch-failed', message: `GitHub API: ${error instanceof Error ? error.message : String(error)}` }
|
||||
}
|
||||
|
||||
if (!/^[0-9a-f]{40}$/i.test(targetSha)) {
|
||||
return { error: 'fetch-failed', message: 'GitHub API returned no tip SHA.' }
|
||||
}
|
||||
|
||||
if (targetSha === currentSha) {
|
||||
return { behind: 0, updateAvailable: false, targetSha, commits: [] }
|
||||
}
|
||||
|
||||
const compared = await deps
|
||||
.fetchGitHubApi(compareApiUrl(slug, currentSha, targetSha))
|
||||
.then(parseCompare)
|
||||
.catch((): null => null)
|
||||
|
||||
return {
|
||||
behind: compared?.behind ?? null,
|
||||
updateAvailable: compared?.behind !== 0,
|
||||
targetSha,
|
||||
commits: compared?.behind === 0 ? [] : (compared?.commits ?? [])
|
||||
}
|
||||
}
|
||||
|
||||
async function checkLsRemote(
|
||||
deps: CheckoutCheckDeps,
|
||||
updateRoot: string,
|
||||
branch: string,
|
||||
currentSha: string
|
||||
): Promise<Partial<UpdaterStatusWire>> {
|
||||
const target = await deps.runGit(['ls-remote', 'origin', `refs/heads/${branch}`], { cwd: updateRoot })
|
||||
const targetSha = target.stdout.trim().split(/\s+/)[0] || ''
|
||||
|
||||
if (target.code !== 0 || !targetSha) {
|
||||
return { error: 'fetch-failed', message: target.stderr.split('\n')[0] || 'git ls-remote failed.' }
|
||||
}
|
||||
|
||||
if (targetSha === currentSha) {
|
||||
return { behind: 0, updateAvailable: false, targetSha, commits: [] }
|
||||
}
|
||||
|
||||
const known = (await deps.runGit(['cat-file', '-e', `${targetSha}^{commit}`], { cwd: updateRoot })).code === 0
|
||||
|
||||
const isAncestor =
|
||||
known && (await deps.runGit(['merge-base', '--is-ancestor', targetSha, 'HEAD'], { cwd: updateRoot })).code === 0
|
||||
|
||||
return { behind: isAncestor ? 0 : null, updateAvailable: !isAncestor, targetSha, commits: [] }
|
||||
}
|
||||
|
||||
/** Passive checks must not fetch packs or mutate a steward-owned checkout. */
|
||||
export async function checkCheckoutUpdates(
|
||||
deps: CheckoutCheckDeps,
|
||||
{ force = false }: { force?: boolean } = {}
|
||||
): Promise<UpdaterStatusWire> {
|
||||
const updateRoot: string = deps.resolveUpdateRoot()
|
||||
const config: ReturnType<CheckoutCheckDeps['readDesktopUpdateConfig']> = deps.readDesktopUpdateConfig()
|
||||
let branch: string = config.branch
|
||||
|
||||
const policy = classifyUpdateRoot({
|
||||
isGitTree: deps.isGitCheckout(updateRoot),
|
||||
updateMechanism: deps.readCanonicalInstallStamp()?.updateMechanism ?? null
|
||||
})
|
||||
|
||||
if (!policy.updatable) {
|
||||
return {
|
||||
supported: false,
|
||||
reason: policy.verdict === 'not-a-checkout' ? 'not-a-git-checkout' : `update-root-${policy.verdict}`,
|
||||
message: policy.message,
|
||||
advice: policy.advice,
|
||||
hermesRoot: updateRoot,
|
||||
branch
|
||||
}
|
||||
}
|
||||
|
||||
const git = async (args: string[]): Promise<string> => (await deps.runGit(args, { cwd: updateRoot })).stdout.trim()
|
||||
|
||||
const [currentSha, dirty, currentBranch, originUrl] = await Promise.all([
|
||||
git(['rev-parse', 'HEAD']),
|
||||
git(['status', '--porcelain']),
|
||||
git(['rev-parse', '--abbrev-ref', 'HEAD']),
|
||||
deps.getOriginUrl(updateRoot)
|
||||
])
|
||||
|
||||
if (config.branchExplicit === false && currentBranch && currentBranch !== 'HEAD') {
|
||||
branch = currentBranch
|
||||
}
|
||||
|
||||
const selection: SourceUpdate | null = await deps.readSourceUpdate(updateRoot)
|
||||
|
||||
if (selection === null) {
|
||||
return { supported: false, reason: 'source-probe-unavailable', message: SOURCE_PROBE_RECOVERY, hermesRoot: updateRoot }
|
||||
}
|
||||
|
||||
if (selection.channel !== 'main') {
|
||||
return {
|
||||
supported: true,
|
||||
...selection,
|
||||
channel: selection.channel,
|
||||
currentSha,
|
||||
currentBranch,
|
||||
dirty: dirty.length > 0,
|
||||
hermesRoot: updateRoot,
|
||||
fetchedAt: Date.now(),
|
||||
updateAvailable: !selection.error && selection.targetSha !== currentSha,
|
||||
behind: selection.targetSha === currentSha ? 0 : null,
|
||||
commits: []
|
||||
}
|
||||
}
|
||||
|
||||
const cached = readCache(deps.updateCheckCachePath)
|
||||
const now = Date.now()
|
||||
|
||||
if (
|
||||
!force &&
|
||||
cached?.updateRoot === updateRoot &&
|
||||
cached.originUrl === originUrl &&
|
||||
cacheIsFresh(cached, { branch, currentSha, now })
|
||||
) {
|
||||
return { ...cached.status, dirty: dirty.length > 0, currentBranch }
|
||||
}
|
||||
|
||||
branch = await deps.resolveHealedBranch(updateRoot, branch)
|
||||
const slug = githubRepoSlug(originUrl)
|
||||
|
||||
const status = slug
|
||||
? await checkApi(deps, slug, branch, currentSha)
|
||||
: await checkLsRemote(deps, updateRoot, branch, currentSha)
|
||||
|
||||
const result: UpdaterStatusWire & Record<string, unknown> = {
|
||||
supported: true,
|
||||
branch,
|
||||
currentBranch,
|
||||
currentSha,
|
||||
dirty: dirty.length > 0,
|
||||
hermesRoot: updateRoot,
|
||||
fetchedAt: now,
|
||||
...status
|
||||
}
|
||||
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(deps.updateCheckCachePath), { recursive: true })
|
||||
const entry: CachedCheckoutCheck = { fetchedAt: now, currentSha, branch, originUrl, updateRoot, status: result }
|
||||
deps.writeFileAtomic(deps.updateCheckCachePath, JSON.stringify(entry))
|
||||
} catch (error: unknown) {
|
||||
deps.rememberLog(
|
||||
`[updates] could not persist check cache: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { readSourceUpdate, type SourceUpdate } from './checkout-source'
|
||||
it('offers manual recovery only for a missing source probe, never for a broken probe', async (): Promise<void> => {
|
||||
const root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'legacy-channel-'))
|
||||
const home: string = path.join(root, 'profile')
|
||||
const modulePath: string = path.join(root, 'hermes_cli', 'source_releases.py')
|
||||
const modulePath: string = path.join(root, 'hermes_cli', 'source_check.py')
|
||||
fs.mkdirSync(path.dirname(modulePath))
|
||||
fs.mkdirSync(home)
|
||||
fs.writeFileSync(path.join(root, 'hermes_cli', '__init__.py'), '')
|
||||
@@ -20,19 +20,11 @@ it('offers manual recovery only for a missing source probe, never for a broken p
|
||||
})
|
||||
|
||||
const deps: CheckoutStrategyDeps = {
|
||||
isGitCheckout: (): boolean => true,
|
||||
updateCheckCachePath: path.join(root, 'cache.json'),
|
||||
writeFileAtomic: vi.fn(), readSourceUpdate: probe, fetchGitHubApi: vi.fn(),
|
||||
readSourceUpdate: probe,
|
||||
hermesHome: home, isWindows: process.platform === 'win32', isMac: process.platform === 'darwin',
|
||||
defaultUpdateBranch: 'main', updateHandoffDwellMs: 0,
|
||||
directoryExists: fs.existsSync, readCanonicalInstallStamp: (): null => null,
|
||||
readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'main' }),
|
||||
directoryExists: fs.existsSync,
|
||||
resolveUpdateRoot: (): string => root, resolveUpdaterBinary: vi.fn((): string => 'frozen-updater'),
|
||||
resolveHealedBranch: vi.fn(async (_root: string, branch: string): Promise<string> => branch),
|
||||
getOriginUrl: async (): Promise<string> => 'https://github.com/fixture/repo',
|
||||
runGit: async (args: string[]): Promise<{ code: number; stdout: string; stderr: string }> => ({
|
||||
code: 0, stdout: args.includes('--abbrev-ref') ? 'feature/work' : args.includes('HEAD') ? 'a'.repeat(40) : '', stderr: ''
|
||||
}),
|
||||
firstLine: (text: string): string => text.split('\n')[0], emitUpdateProgress: vi.fn(), rememberLog: vi.fn(),
|
||||
startHermes: vi.fn(async (): Promise<void> => {}),
|
||||
stopBackendsForUpdate: vi.fn(async (): Promise<void> => {}),
|
||||
@@ -54,7 +46,6 @@ it('offers manual recovery only for a missing source probe, never for a broken p
|
||||
expect(result.command).not.toContain('--branch')
|
||||
expect(deps.stopBackendsForUpdate).not.toHaveBeenCalled()
|
||||
expect(deps.resolveUpdaterBinary).not.toHaveBeenCalled()
|
||||
expect(deps.fetchGitHubApi).not.toHaveBeenCalled()
|
||||
expect(deps.quit).not.toHaveBeenCalled()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,62 +1,43 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
|
||||
import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'
|
||||
import type { SourceUpdate } from './checkout-source'
|
||||
|
||||
function dependencies(): CheckoutStrategyDeps {
|
||||
return {
|
||||
isGitCheckout: (): boolean => true,
|
||||
updateCheckCachePath: 'unused-cache.json',
|
||||
writeFileAtomic: vi.fn(),
|
||||
readSourceUpdate: vi.fn(async (): Promise<{ channel: 'main' }> => ({ channel: 'main' })),
|
||||
fetchGitHubApi: vi.fn(),
|
||||
hermesHome: 'home',
|
||||
isWindows: process.platform === 'win32',
|
||||
isMac: process.platform === 'darwin',
|
||||
defaultUpdateBranch: 'main',
|
||||
updateHandoffDwellMs: 0,
|
||||
directoryExists: () => true,
|
||||
readCanonicalInstallStamp: () => ({ updateMechanism: 'external' }),
|
||||
readDesktopUpdateConfig: () => ({ branch: 'main' }),
|
||||
resolveUpdateRoot: () => 'repo',
|
||||
resolveUpdaterBinary: () => null,
|
||||
resolveHealedBranch: async (_, branch) => branch,
|
||||
getOriginUrl: async () => '',
|
||||
runGit: vi.fn(async () => { throw new Error('unexpected git invocation') }),
|
||||
firstLine: text => text.split('\n')[0],
|
||||
emitUpdateProgress: vi.fn(),
|
||||
rememberLog: vi.fn(),
|
||||
startHermes: vi.fn(async () => {}),
|
||||
stopBackendsForUpdate: vi.fn(async (): Promise<void> => {}),
|
||||
repairMacUpdaterHelper: vi.fn(),
|
||||
preflightStateDb: vi.fn(),
|
||||
runningAppBundle: () => null,
|
||||
markQuittingForHandoff: vi.fn(),
|
||||
quit: vi.fn()
|
||||
}
|
||||
}
|
||||
it.each(['not-a-git-checkout', 'update-root-steward-owned-git-tree', 'fetch-failed'])(
|
||||
'preserves the Python refusal or error before handoff: %s',
|
||||
async (reason: string): Promise<void> => {
|
||||
const status: SourceUpdate = reason === 'fetch-failed'
|
||||
? { supported: true, error: reason }
|
||||
: { supported: false, reason }
|
||||
|
||||
describe('checkout update admission', () => {
|
||||
it.each(['external', 'app-installer', 'electron-updater'] as const)('refuses %s-owned code without fetching or stopping the backend', async updateMechanism => {
|
||||
const deps = dependencies()
|
||||
deps.readCanonicalInstallStamp = () => ({ updateMechanism })
|
||||
const strategy = createCheckoutStrategy(deps)
|
||||
const result = await strategy.check()
|
||||
const deps: CheckoutStrategyDeps = {
|
||||
readSourceUpdate: vi.fn(async (): Promise<SourceUpdate> => status),
|
||||
hermesHome: 'home',
|
||||
isWindows: process.platform === 'win32',
|
||||
isMac: process.platform === 'darwin',
|
||||
defaultUpdateBranch: 'main',
|
||||
updateHandoffDwellMs: 0,
|
||||
directoryExists: (): boolean => true,
|
||||
resolveUpdateRoot: (): string => 'repo',
|
||||
resolveUpdaterBinary: vi.fn((): null => null),
|
||||
firstLine: (text: string): string => text.split('\n')[0],
|
||||
emitUpdateProgress: vi.fn(),
|
||||
rememberLog: vi.fn(),
|
||||
startHermes: vi.fn(async (): Promise<void> => {}),
|
||||
stopBackendsForUpdate: vi.fn(async (): Promise<void> => {}),
|
||||
repairMacUpdaterHelper: vi.fn(),
|
||||
preflightStateDb: vi.fn(),
|
||||
runningAppBundle: (): null => null,
|
||||
markQuittingForHandoff: vi.fn(),
|
||||
quit: vi.fn()
|
||||
}
|
||||
|
||||
expect(result.supported).toBe(false)
|
||||
expect(await strategy.apply()).toMatchObject({ ok: false })
|
||||
expect(deps.readSourceUpdate).not.toHaveBeenCalled()
|
||||
expect(result.mechanism).toBe(strategy.mechanism)
|
||||
expect(deps.runGit).not.toHaveBeenCalled()
|
||||
const strategy: ReturnType<typeof createCheckoutStrategy> = createCheckoutStrategy(deps)
|
||||
expect(await strategy.check()).toMatchObject({ ...status, mechanism: strategy.mechanism })
|
||||
expect(await strategy.apply()).toMatchObject({ ok: false, error: reason })
|
||||
expect(deps.readSourceUpdate).toHaveBeenLastCalledWith('repo', { force: true })
|
||||
expect(deps.resolveUpdaterBinary).not.toHaveBeenCalled()
|
||||
expect(deps.stopBackendsForUpdate).not.toHaveBeenCalled()
|
||||
expect(deps.quit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a missing source checkout without attempting git', async () => {
|
||||
const deps = dependencies()
|
||||
deps.isGitCheckout = (): boolean => false
|
||||
const result = await createCheckoutStrategy(deps).check()
|
||||
|
||||
expect(result.reason).toBe('not-a-git-checkout')
|
||||
expect(deps.runGit).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
}
|
||||
)
|
||||
@@ -56,7 +56,7 @@ it('carries each install channel from Python publication checks into the source
|
||||
try {
|
||||
fs.mkdirSync(origin)
|
||||
fs.mkdirSync(home)
|
||||
git(['init', '-b', 'feature/gui'])
|
||||
git(['init', '-b', 'upstream-build'])
|
||||
const commits: string[] = []
|
||||
|
||||
for (const label of ['old', 'stable', 'canary', 'unpublished']) {
|
||||
@@ -80,7 +80,10 @@ it('carries each install channel from Python publication checks into the source
|
||||
|
||||
responses.set('/releases/stable/release-candidates.json', { tag: tags.stable, commit: commits[1] })
|
||||
git(['tag', 'v99.0.0'])
|
||||
git(['clone', origin, root], temporary)
|
||||
git(['worktree', 'add', '-b', 'feature/gui', root])
|
||||
git(['remote', 'add', 'origin', origin])
|
||||
fs.writeFileSync(path.join(origin, 'install-stamp.json'), JSON.stringify({ updateMechanism: 'external' }))
|
||||
fs.writeFileSync(path.join(root, 'install-stamp.json'), JSON.stringify({ updateMechanism: 'self' }))
|
||||
await new Promise<void>((resolve: () => void): void => {
|
||||
server.listen(0, '127.0.0.1', resolve)
|
||||
})
|
||||
@@ -122,48 +125,22 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requ
|
||||
)
|
||||
}
|
||||
|
||||
const checkerPath: string = path.join(root, 'hermes_cli', 'source_check.py')
|
||||
fs.writeFileSync(checkerPath, fs.readFileSync(checkerPath, 'utf8').replace(
|
||||
'from __future__ import annotations',
|
||||
`from __future__ import annotations\nimport runpy; runpy.run_path(${JSON.stringify(path.join(root, 'transport.py'))})`
|
||||
))
|
||||
|
||||
const deps: CheckoutStrategyDeps = {
|
||||
hermesHome: home,
|
||||
isWindows: process.platform === 'win32',
|
||||
isMac: process.platform === 'darwin',
|
||||
defaultUpdateBranch: 'main',
|
||||
updateHandoffDwellMs: 0,
|
||||
updateCheckCachePath: path.join(home, 'cache.json'),
|
||||
writeFileAtomic: (file: string, contents: string): void => fs.writeFileSync(file, contents),
|
||||
isGitCheckout: (): boolean => true,
|
||||
readCanonicalInstallStamp: (): null => null,
|
||||
readDesktopUpdateConfig: (): { branch: string; branchExplicit: boolean } => ({
|
||||
branch: 'main',
|
||||
branchExplicit: false
|
||||
}),
|
||||
resolveUpdateRoot: (): string => root,
|
||||
readSourceUpdate: async (install: string): Promise<SourceUpdate> => {
|
||||
const result: { stdout: string } = await execute(
|
||||
python,
|
||||
[
|
||||
'-c',
|
||||
"import runpy,sys; runpy.run_path(sys.argv.pop(1)); runpy.run_module('hermes_cli.source_releases', run_name='__main__')",
|
||||
path.join(root, 'transport.py'),
|
||||
'--install-root',
|
||||
install,
|
||||
'--git',
|
||||
'git'
|
||||
],
|
||||
{ cwd: root, env: environment }
|
||||
)
|
||||
|
||||
return JSON.parse(result.stdout) as SourceUpdate
|
||||
},
|
||||
resolveHealedBranch: async (_root: string, branch: string): Promise<string> => branch,
|
||||
getOriginUrl: async (): Promise<string> => origin,
|
||||
runGit: async (args: string[]): Promise<{ code: number; stdout: string; stderr: string }> => ({
|
||||
code: 0,
|
||||
stdout: git(args, root),
|
||||
stderr: ''
|
||||
readSourceUpdate: (install: string, opts: { force?: boolean }): Promise<SourceUpdate | null> => readSourceUpdate({
|
||||
python, git: 'git', updateRoot: install, hermesHome: home, force: opts.force
|
||||
}),
|
||||
fetchGitHubApi: async (): Promise<never> => {
|
||||
throw new Error('branch API must not resolve releases')
|
||||
},
|
||||
directoryExists: fs.existsSync,
|
||||
resolveUpdaterBinary: (): null => null,
|
||||
firstLine: (text: string): string => text.split('\n')[0],
|
||||
@@ -199,7 +176,6 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requ
|
||||
|
||||
for (const channel of ['stable', 'canary'] as const) {
|
||||
await setChannel(channel)
|
||||
await setChannel(channel === 'stable' ? 'canary' : 'stable', origin)
|
||||
const sha: string = commits[channel === 'stable' ? 1 : 2]
|
||||
const checked: unknown = await strategy.check()
|
||||
expect(checked, JSON.stringify({ checked, requests })).toMatchObject({
|
||||
@@ -246,8 +222,8 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requ
|
||||
expect(deps.stopBackendsForUpdate).not.toHaveBeenCalled()
|
||||
expect(spawned).toHaveLength(0)
|
||||
await setChannel('main')
|
||||
expect(await readSourceUpdate({ python, git: 'git', updateRoot: root, hermesHome: home })).toEqual({
|
||||
channel: 'main'
|
||||
expect(await readSourceUpdate({ python, git: 'git', updateRoot: root, hermesHome: home })).toMatchObject({
|
||||
supported: true, branch: 'feature/gui', targetSha: commits[3], updateAvailable: false
|
||||
})
|
||||
const count: number = requests.length
|
||||
expect(await strategy.check()).toMatchObject({
|
||||
|
||||
@@ -4,19 +4,20 @@ import { promisify } from 'node:util'
|
||||
import { buildDesktopBackendEnv } from '../backend-env'
|
||||
import { hiddenWindowsChildOptions } from '../windows-child-options'
|
||||
|
||||
export interface SourceUpdate {
|
||||
channel: 'main' | 'stable' | 'canary'
|
||||
latestTag?: string
|
||||
targetSha?: string
|
||||
error?: string
|
||||
message?: string
|
||||
}
|
||||
import type { UpdaterStatusWire } from './index'
|
||||
|
||||
export interface SourceUpdate extends UpdaterStatusWire {}
|
||||
|
||||
export interface SourceUpdateProbe {
|
||||
python: string | null
|
||||
git: string
|
||||
updateRoot: string
|
||||
hermesHome: string
|
||||
branch?: string
|
||||
channel?: 'main' | 'stable' | 'canary'
|
||||
force?: boolean
|
||||
cachePath?: string
|
||||
branchConfigPath?: string
|
||||
}
|
||||
|
||||
const execute: typeof execFile.__promisify__ = promisify(execFile)
|
||||
@@ -48,8 +49,13 @@ export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<Source
|
||||
'-c',
|
||||
// Inspect the target checkout's callable, not stderr strings or an editable
|
||||
// install elsewhere on sys.path. Exceptions inside a present probe propagate.
|
||||
'from pathlib import Path; import runpy; p = Path("hermes_cli/source_releases.py"); entry = runpy.run_path(str(p)).get("main") if p.is_file() else None; entry() if callable(entry) else print("null")',
|
||||
'--install-root', probe.updateRoot, '--git', probe.git
|
||||
'from pathlib import Path; import runpy; p = Path("hermes_cli/source_check.py"); entry = runpy.run_path(str(p)).get("main") if p.is_file() else None; entry() if callable(entry) else print("null")',
|
||||
'--install-root', probe.updateRoot, '--home', probe.hermesHome, '--git', probe.git,
|
||||
...(probe.branch ? ['--branch', probe.branch] : []),
|
||||
...(probe.channel ? ['--channel', probe.channel] : []),
|
||||
...(probe.force ? ['--force'] : []),
|
||||
...(probe.cachePath ? ['--cache-path', probe.cachePath] : []),
|
||||
...(probe.branchConfigPath ? ['--branch-config-path', probe.branchConfigPath] : [])
|
||||
],
|
||||
hiddenWindowsChildOptions({
|
||||
cwd: probe.updateRoot,
|
||||
@@ -66,17 +72,12 @@ export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<Source
|
||||
return null
|
||||
}
|
||||
|
||||
if (!['main', 'stable', 'canary'].includes(selection.channel)) {
|
||||
throw new Error('The source update check returned an invalid channel.')
|
||||
if (typeof selection.supported !== 'boolean') {
|
||||
throw new Error('The source update check returned an invalid status.')
|
||||
}
|
||||
|
||||
if (
|
||||
selection.channel !== 'main' &&
|
||||
!selection.error &&
|
||||
(!selection.latestTag || !/^[0-9a-f]{40}$/.test(selection.targetSha ?? ''))
|
||||
) {
|
||||
throw new Error('The source update check returned no release commit.')
|
||||
}
|
||||
// The Python banner uses -1 for an available update with no exact count.
|
||||
if (selection.behind === -1) { selection.behind = null }
|
||||
|
||||
return selection
|
||||
}
|
||||
@@ -17,8 +17,7 @@ import {
|
||||
wrapHandoffForDetachedConsole
|
||||
} from '../updater-process'
|
||||
|
||||
import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
|
||||
import { sourceUpdateEnvironment } from './checkout-source'
|
||||
import { SOURCE_PROBE_RECOVERY, type SourceUpdate, sourceUpdateEnvironment } from './checkout-source'
|
||||
|
||||
import type { UpdaterApplyResultWire, UpdaterMechanism, UpdaterStatusWire, UpdaterStrategy } from './index'
|
||||
|
||||
@@ -26,7 +25,9 @@ import type { UpdaterApplyResultWire, UpdaterMechanism, UpdaterStatusWire, Updat
|
||||
* Everything the checkout flow needs from the app shell. These are the
|
||||
* impure edges only — all update logic lives here.
|
||||
*/
|
||||
export interface CheckoutStrategyDeps extends CheckoutCheckDeps {
|
||||
export interface CheckoutStrategyDeps {
|
||||
resolveUpdateRoot: () => string
|
||||
readSourceUpdate: (root: string, opts: { force?: boolean }) => Promise<SourceUpdate | null>
|
||||
hermesHome: string
|
||||
isWindows: boolean
|
||||
isMac: boolean
|
||||
@@ -68,7 +69,12 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
|
||||
const mechanism: UpdaterMechanism = deps.isWindows ? 'windows-handoff' : 'posix-handoff'
|
||||
|
||||
async function check(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {
|
||||
const status = await checkCheckoutUpdates(deps, opts)
|
||||
const root: string = deps.resolveUpdateRoot()
|
||||
|
||||
const status: UpdaterStatusWire = await deps.readSourceUpdate(root, opts) ?? {
|
||||
supported: false, reason: 'source-probe-unavailable', message: SOURCE_PROBE_RECOVERY, hermesRoot: root
|
||||
}
|
||||
|
||||
status.mechanism = mechanism
|
||||
|
||||
return status
|
||||
@@ -84,7 +90,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
|
||||
return { mechanism, check, apply }
|
||||
|
||||
async function applyBody(): Promise<UpdaterApplyResultWire> {
|
||||
const status: UpdaterStatusWire = await checkCheckoutUpdates(deps, { force: true })
|
||||
const status: UpdaterStatusWire = await check({ force: true })
|
||||
|
||||
if (status.reason === 'source-probe-unavailable') {
|
||||
return { ok: true, manual: true, command: 'hermes update --help', message: status.message, hermesRoot: status.hermesRoot }
|
||||
|
||||
@@ -29,11 +29,9 @@ def run_case(root, output, name, behind, early=False, cancel=False):
|
||||
" base_url: http://127.0.0.1:9/v1\n"
|
||||
"display:\n interface: cli\n skip_banner: false\n"
|
||||
"memory:\n provider: ''\n", encoding="utf-8")
|
||||
cache = hh / ".update_check"
|
||||
# The version comes from the checkout, not an invented cache identity.
|
||||
from hermes_cli.banner import VERSION
|
||||
payload = json.dumps({"ts": time.time(), "behind": behind,
|
||||
"rev": None, "ver": VERSION}).encode()
|
||||
cache = hh / "notice-result.json"
|
||||
# This harness tests display timing, not source-check cache policy.
|
||||
payload = json.dumps({"behind": behind}).encode()
|
||||
if early:
|
||||
cache.write_bytes(payload)
|
||||
else:
|
||||
@@ -44,7 +42,9 @@ def run_case(root, output, name, behind, early=False, cancel=False):
|
||||
"OPENAI_API_KEY": "local-not-used", "PROMPT_TOOLKIT_NO_CPR": "1"}
|
||||
master, slave = pty.openpty()
|
||||
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 120, 0, 0))
|
||||
bootstrap = ("import hermes_cli.main as m; import hermes_cli.banner as b; "
|
||||
bootstrap = ("import json; from pathlib import Path; import hermes_cli.main as m; "
|
||||
"import hermes_cli.banner as b; from hermes_cli import source_check; "
|
||||
f"source_check.check_for_updates = lambda **kw: json.loads(Path({str(cache)!r}).read_text()); "
|
||||
"print('LOADED', m.__file__, b.__file__, flush=True); m.main()")
|
||||
proc = subprocess.Popen([sys.executable, "-c", bootstrap, "chat"], cwd=root,
|
||||
env=env, stdin=slave, stdout=slave, stderr=slave,
|
||||
|
||||
@@ -20,7 +20,7 @@ env = {'PATH': f'{BASE}/bin:/usr/bin:/bin', 'HOME': str(BASE/'home'),
|
||||
for name in ('home', 'hermes', 'bin'):
|
||||
(BASE/name).mkdir(exist_ok=True)
|
||||
sys.path.insert(0, str(REPO))
|
||||
from hermes_cli import banner
|
||||
from hermes_cli import source_check
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
os.environ.clear()
|
||||
@@ -28,7 +28,7 @@ if len(sys.argv) > 1:
|
||||
case = json.loads((BASE/'case.json').read_text())
|
||||
os.environ.update(case['env'])
|
||||
start = time.monotonic()
|
||||
result = banner._check_via_local_git(BASE/'checkout')
|
||||
result = source_check.check_for_updates(install_root=BASE/'checkout').get('behind')
|
||||
print('PRODUCTION_RETURN '+json.dumps({'result': result, 'elapsed': time.monotonic()-start}), flush=True)
|
||||
time.sleep(2)
|
||||
sys.exit(0)
|
||||
@@ -146,7 +146,7 @@ finally:
|
||||
os.killpg(proc.pid, signal.SIGTERM)
|
||||
proc.wait(timeout=5)
|
||||
log.close()
|
||||
result = {'platform': sys.platform, 'production': banner.__file__, 'rows': rows,
|
||||
result = {'platform': sys.platform, 'production': source_check.__file__, 'rows': rows,
|
||||
'isolation': 'PATH ssh adapter only adds -F fixture config; execs real /usr/bin/ssh; loopback sshd and disposable git repos',
|
||||
'server_stopped': server.poll() is not None, 'agent_stopped': agent is None or agent.poll() is not None}
|
||||
(BASE/'result.json').write_text(json.dumps(result, indent=2))
|
||||
|
||||
@@ -175,10 +175,10 @@ def print_fast_version_info(*, check_updates: bool = True) -> None:
|
||||
# Synchronous update status — bounded by check_for_updates' own subprocess/network timeouts
|
||||
# and its 6-hour cache; any failure prints nothing.
|
||||
try:
|
||||
from hermes_cli.banner import UPDATE_AVAILABLE_NO_COUNT, check_for_updates
|
||||
from hermes_cli.source_check import UPDATE_AVAILABLE_NO_COUNT, check_for_updates
|
||||
from hermes_cli.config import recommended_update_command
|
||||
|
||||
behind = check_for_updates(passive=True)
|
||||
behind = check_for_updates(passive=True).get("behind")
|
||||
if behind == UPDATE_AVAILABLE_NO_COUNT:
|
||||
print(f"Update available — run '{recommended_update_command()}'")
|
||||
elif behind and behind > 0:
|
||||
|
||||
+10
-325
@@ -3,11 +3,11 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from hermes_cli import source_check
|
||||
# Historical updater import (tests/compat/old_updater_surface.json). In-tree callers use the owner.
|
||||
from hermes_cli.source_check import _github_compare_behind
|
||||
from hermes_constants import get_hermes_home
|
||||
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
||||
|
||||
@@ -140,321 +140,6 @@ def get_available_skills() -> Dict[str, List[str]]:
|
||||
return {} if result is _UNCACHED else result
|
||||
|
||||
|
||||
# === Update check ===
|
||||
|
||||
# Passive checks hit GitHub at most once a day per install; a failed check retries after an hour
|
||||
# so a flaky line can't turn every startup into a request (nor stay wrong for a day).
|
||||
_UPDATE_CHECK_CACHE_SECONDS = 24 * 3600
|
||||
_UPDATE_CHECK_FAILURE_CACHE_SECONDS = 3600
|
||||
# Upstream tip seen by the most recent check; recorded in the cache file for the changelog.
|
||||
_last_target_rev: Optional[str] = None
|
||||
|
||||
# Returned when an update is known to exist but commits can't be counted (e.g. nix builds).
|
||||
UPDATE_AVAILABLE_NO_COUNT = -1
|
||||
|
||||
_UPSTREAM_REPO_URL = "https://github.com/NousResearch/hermes-agent.git"
|
||||
_OFFICIAL_REPO_CANONICAL = "github.com/nousresearch/hermes-agent"
|
||||
|
||||
|
||||
def _canonical_github_remote(url: str | None) -> str:
|
||||
"""Return ``host/owner/repo`` for common GitHub remote URL forms."""
|
||||
if not url:
|
||||
return ""
|
||||
value = url.strip()
|
||||
for ssh_prefix in ("git@github.com:", "ssh://git@github.com/"):
|
||||
if value.startswith(ssh_prefix):
|
||||
value = "github.com/" + value[len(ssh_prefix):]
|
||||
break
|
||||
else:
|
||||
parsed = urlparse(value)
|
||||
if parsed.netloc and parsed.path:
|
||||
value = f"{parsed.netloc}{parsed.path}"
|
||||
return value.strip().rstrip("/").removesuffix(".git").lower()
|
||||
|
||||
|
||||
def _is_official_ssh_remote(url: str | None) -> bool:
|
||||
return bool(url) and url.strip().lower().startswith(("git@", "ssh://")) and (
|
||||
_canonical_github_remote(url) == _OFFICIAL_REPO_CANONICAL)
|
||||
|
||||
|
||||
_GIT_TEXT_KW = {"text": True, "encoding": "utf-8", "errors": "replace"}
|
||||
|
||||
|
||||
def _git_run(args: list[str], *, cwd: Optional[Path] = None, timeout: int = 5, text: bool = True,
|
||||
network: bool = False):
|
||||
"""Run ``git <args>`` with the shared subprocess boilerplate; None on any exception.
|
||||
|
||||
git output is UTF-8; on Windows ``text=True`` defaults to the ANSI code page and a byte like the
|
||||
3rd of 🐛 in a commit subject crashes the stdlib reader thread (#52649), hence the explicit
|
||||
encoding. ``network=True`` (ls-remote/fetch) detaches stdin and disables git/GCM prompts so a
|
||||
passive update check can never hang on a ``Username for 'https://github.com':`` prompt.
|
||||
"""
|
||||
from hermes_cli._subprocess_compat import noninteractive_git_env, windows_hide_flags
|
||||
|
||||
# The banner/update probes run from GUI-hosted backends too (desktop-spawned
|
||||
# ``hermes serve``), where a bare git child flashes a console window.
|
||||
kwargs: dict = {"creationflags": windows_hide_flags()}
|
||||
if network:
|
||||
kwargs.update({"stdin": subprocess.DEVNULL, "env": noninteractive_git_env()})
|
||||
try:
|
||||
return subprocess.run(
|
||||
["git", *args], capture_output=True, timeout=timeout, cwd=str(cwd) if cwd is not None else None,
|
||||
**(_GIT_TEXT_KW if text else {}), **kwargs)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _git_stdout(args: list[str], *, cwd: Path, timeout: int = 5, network: bool = False) -> Optional[str]:
|
||||
result = _git_run(args, cwd=cwd, timeout=timeout, network=network)
|
||||
if result is None or result.returncode != 0:
|
||||
return None
|
||||
return (result.stdout or "").strip()
|
||||
|
||||
|
||||
def _git_ok(args: list[str], **kw) -> bool:
|
||||
"""True when ``git <args>`` ran and exited 0 (output discarded)."""
|
||||
result = _git_run(args, text=False, **kw)
|
||||
return result is not None and result.returncode == 0
|
||||
|
||||
|
||||
def _git_count(args: list[str], *, cwd: Path) -> Optional[int]:
|
||||
"""``int`` of a successful ``git rev-list --count``-style command, else None."""
|
||||
result = _git_run(args, cwd=cwd)
|
||||
if result is not None and result.returncode == 0:
|
||||
return _quiet(lambda: int(result.stdout.strip()))
|
||||
return None
|
||||
|
||||
|
||||
def _is_full_sha(value: Optional[str]) -> bool:
|
||||
return isinstance(value, str) and len(value) == 40 and all(c in "0123456789abcdefABCDEF" for c in value)
|
||||
|
||||
|
||||
_compare_payload_cache: Dict[tuple, dict] = {}
|
||||
|
||||
|
||||
def _github_compare(current_rev: str, target_rev: str) -> Optional[dict]:
|
||||
"""Compare payload for ``current...target`` from the GitHub API; memoized per process.
|
||||
|
||||
Shallow installer clones and API-only probes know the two tip SHAs but have no local history
|
||||
to run ``rev-list --count`` or ``git log`` across; the payload carries both the count
|
||||
(``ahead_by``) and the commit list the dashboard/desktop render as "what's changed".
|
||||
"""
|
||||
if not (_is_full_sha(current_rev) and _is_full_sha(target_rev)):
|
||||
return None
|
||||
key = (current_rev, target_rev)
|
||||
if key in _compare_payload_cache:
|
||||
return _compare_payload_cache[key]
|
||||
url = f"https://api.github.com/repos/nousresearch/hermes-agent/compare/{current_rev}...{target_rev}"
|
||||
|
||||
def _fetch():
|
||||
import urllib.request
|
||||
# api.github.com 403s requests without a User-Agent.
|
||||
req = urllib.request.Request(
|
||||
url, headers={"Accept": "application/vnd.github+json", "User-Agent": "hermes-cli-update-check"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
payload = _quiet(_fetch)
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
_compare_payload_cache[key] = payload
|
||||
return payload
|
||||
|
||||
|
||||
def _github_compare_behind(current_rev: str, target_rev: str) -> Optional[int]:
|
||||
"""Exact behind-count via the GitHub compare API for uncountable graphs."""
|
||||
payload = _github_compare(current_rev, target_rev)
|
||||
ahead = payload.get("ahead_by") if payload else None
|
||||
return ahead if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0 else None
|
||||
|
||||
|
||||
def upstream_commits_behind(n: int = 20) -> List[Dict[str, Any]]:
|
||||
"""Commits between the last checked HEAD and upstream tip, newest first; [] when unknown.
|
||||
|
||||
Reads the tips recorded by ``check_for_updates`` so it costs no extra request when the
|
||||
compare payload is already memoized for this process.
|
||||
"""
|
||||
cached = _read_json(get_hermes_home() / ".update_check") or {}
|
||||
head_rev, target_rev = cached.get("head"), cached.get("target")
|
||||
if not head_rev or not target_rev or head_rev == target_rev:
|
||||
return []
|
||||
payload = _github_compare(head_rev, target_rev)
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for entry in (payload or {}).get("commits", []) if isinstance(payload, dict) else []:
|
||||
commit = entry.get("commit") or {}
|
||||
when = ((commit.get("committer") or {}).get("date") or "")
|
||||
try:
|
||||
from datetime import datetime
|
||||
at = int(datetime.fromisoformat(when.replace("Z", "+00:00")).timestamp()) if when else 0
|
||||
except ValueError:
|
||||
at = 0
|
||||
rows.append({
|
||||
"sha": str(entry.get("sha", ""))[:7],
|
||||
"summary": str(commit.get("message", "")).split("\n", 1)[0],
|
||||
"author": str((commit.get("author") or {}).get("name", "")),
|
||||
"at": at,
|
||||
})
|
||||
rows.reverse() # compare returns oldest first
|
||||
return rows[:n]
|
||||
|
||||
|
||||
def _tips_behind(head_rev: Optional[str], target_rev: Optional[str], repo_dir: Optional[Path] = None) -> Optional[int]:
|
||||
"""Behind-count from two tip SHAs: None if either is unknown, 0 when equal, else count/sentinel.
|
||||
|
||||
With ``repo_dir``, a target that is already an ancestor of HEAD (local-ahead checkout) is 0 too.
|
||||
``ahead_by == 0`` with differing tips means the remote tip is reachable from our HEAD — NOT
|
||||
behind. A local-only HEAD 404s on the API, which degrades to ``UPDATE_AVAILABLE_NO_COUNT`` —
|
||||
never a fabricated 1.
|
||||
"""
|
||||
if not head_rev or not target_rev:
|
||||
return None
|
||||
if head_rev == target_rev or (repo_dir is not None and _git_ok(
|
||||
["merge-base", "--is-ancestor", target_rev, "HEAD"], cwd=repo_dir)):
|
||||
return 0
|
||||
counted = _github_compare_behind(head_rev, target_rev)
|
||||
return counted if counted is not None else UPDATE_AVAILABLE_NO_COUNT
|
||||
|
||||
|
||||
def _github_branch_tip(repo_slug: str, branch: str) -> Optional[str]:
|
||||
"""Tip SHA of ``branch`` on GitHub via the REST API (40-byte body, no git, no auth)."""
|
||||
from urllib.parse import quote
|
||||
|
||||
url = f"https://api.github.com/repos/{repo_slug}/commits/{quote(branch, safe='')}"
|
||||
|
||||
def _fetch():
|
||||
import urllib.request
|
||||
req = urllib.request.Request(
|
||||
url, headers={"Accept": "application/vnd.github.sha", "User-Agent": "hermes-cli-update-check"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.read().decode("utf-8").strip()
|
||||
sha = _quiet(_fetch)
|
||||
return sha if _is_full_sha(sha) else None
|
||||
|
||||
|
||||
def _upstream_main_sha() -> Optional[str]:
|
||||
"""Tip SHA of upstream main; API first, HTTPS ``ls-remote`` (no auth, no prompts) as fallback."""
|
||||
sha = _github_branch_tip(_OFFICIAL_REPO_CANONICAL.removeprefix("github.com/"), "main")
|
||||
if sha:
|
||||
return sha
|
||||
result = _git_run(["ls-remote", _UPSTREAM_REPO_URL, "refs/heads/main"], timeout=10, network=True)
|
||||
if result is None or result.returncode != 0 or not result.stdout:
|
||||
return None
|
||||
return result.stdout.split()[0] or None
|
||||
|
||||
|
||||
def _check_via_rev(local_rev: str) -> Optional[int]:
|
||||
"""Compare an embedded git revision to upstream main via the API (see ``_tips_behind``)."""
|
||||
global _last_target_rev
|
||||
_last_target_rev = _upstream_main_sha()
|
||||
return _tips_behind(local_rev, _last_target_rev)
|
||||
|
||||
|
||||
def _check_via_local_git(repo_dir: Path) -> Optional[int]:
|
||||
"""Count commits behind origin/main in a local checkout.
|
||||
|
||||
Passive checks never run ``git fetch``: every CLI/TUI/gateway start used to negotiate a pack
|
||||
with GitHub, and across the install base that was tens of millions of fetch requests a day
|
||||
(GitHub asked us to poll the API instead). Two tip SHAs are enough — the remote one from the
|
||||
API, the local one from ``rev-parse`` — and ``_tips_behind`` recovers the exact count through
|
||||
the compare API when they differ. ``git fetch`` happens only inside ``hermes update``.
|
||||
"""
|
||||
# Probe the origin URL under the config-isolated env: a global url.<https>.insteadOf rewrite
|
||||
# otherwise makes an SSH origin masquerade as HTTPS (#104591).
|
||||
origin_url = _git_stdout(["remote", "get-url", "origin"], cwd=repo_dir, network=True)
|
||||
head_rev = _git_stdout(["rev-parse", "HEAD"], cwd=repo_dir)
|
||||
if not head_rev:
|
||||
return None
|
||||
canonical = _canonical_github_remote(origin_url)
|
||||
if canonical.startswith("github.com/"):
|
||||
target_rev = _github_branch_tip(canonical.removeprefix("github.com/"), "main")
|
||||
else:
|
||||
# Non-GitHub origin: one ls-remote for the tip (ref advertisement only, no pack transfer).
|
||||
result = _git_run(["ls-remote", "origin", "refs/heads/main"], cwd=repo_dir, timeout=10, network=True)
|
||||
target_rev = result.stdout.split()[0] if result is not None and result.returncode == 0 and result.stdout else None
|
||||
global _last_target_rev
|
||||
_last_target_rev = target_rev
|
||||
# Tip SHAs alone can't distinguish "behind" from a local commit AHEAD of origin/main, and
|
||||
# misreporting an ahead checkout nudges the user into `hermes update`, which can wipe carried
|
||||
# work — hence the ancestor check inside _tips_behind, against the FRESH upstream SHA.
|
||||
return _tips_behind(head_rev, target_rev, repo_dir)
|
||||
|
||||
|
||||
def _read_json(path: Path) -> Optional[dict]:
|
||||
"""Parse ``path`` as a JSON object; None when missing, unreadable, or not a dict."""
|
||||
blob = _quiet(lambda: json.loads(path.read_text(encoding="utf-8")))
|
||||
return blob if isinstance(blob, dict) else None
|
||||
|
||||
|
||||
def check_for_updates(*, passive: bool = False) -> Optional[int]:
|
||||
"""Check whether a Hermes update is available.
|
||||
|
||||
If ``HERMES_REVISION`` is set (nix builds embed it), compare it to upstream main; otherwise
|
||||
compare the local checkout's HEAD. Both go through the GitHub API, never ``git fetch``.
|
||||
"""
|
||||
from hermes_cli.config import get_project_root
|
||||
from hermes_cli.update_contract import is_commit_build
|
||||
from hermes_cli.steward import is_bundled_payload
|
||||
|
||||
if is_commit_build(get_project_root()) or is_bundled_payload(get_project_root()):
|
||||
return None
|
||||
|
||||
def _read_config_opt_out():
|
||||
from hermes_cli.config import load_config
|
||||
return load_config().get("updates", {}).get("check", True) is False
|
||||
|
||||
if passive and _quiet(_read_config_opt_out) is True:
|
||||
return None
|
||||
|
||||
cache_file = get_hermes_home() / ".update_check"
|
||||
embedded_rev = os.environ.get("HERMES_REVISION") or None
|
||||
# Docker images have no working tree (the image excludes `.git`) and set no HERMES_REVISION.
|
||||
# None makes both the Rich banner and the Ink badge show nothing, mirroring the dashboard's
|
||||
# `/api/hermes/update/check` short-circuit so the surfaces agree.
|
||||
def _install_method():
|
||||
from hermes_cli.config import detect_install_method, get_project_root
|
||||
return detect_install_method(get_project_root())
|
||||
|
||||
if _quiet(_install_method) in {"docker", "apt"}:
|
||||
return None
|
||||
from hermes_cli.config import load_config
|
||||
from hermes_cli.update_channel import resolve_update_channel
|
||||
|
||||
channel = resolve_update_channel(_quiet(load_config), get_project_root())
|
||||
# Cache is invalidated when the embedded rev OR installed version changed since the last check.
|
||||
# For a git checkout the local HEAD is part of the key too: `hermes update` moves HEAD, and a
|
||||
# stale "3 behind" must not survive the update it just prompted.
|
||||
now = time.time()
|
||||
repo_dir = None if embedded_rev else _resolve_repo_dir()
|
||||
head_rev = _git_stdout(["rev-parse", "HEAD"], cwd=repo_dir) if repo_dir is not None else None
|
||||
cached = _read_json(cache_file)
|
||||
if cached is not None and cached.get("rev") == embedded_rev and cached.get("ver") == VERSION \
|
||||
and cached.get("head") == head_rev and cached.get("channel", "main") == channel:
|
||||
ttl = _UPDATE_CHECK_CACHE_SECONDS if cached.get("behind") is not None else _UPDATE_CHECK_FAILURE_CACHE_SECONDS
|
||||
if now - cached.get("ts", 0) < ttl:
|
||||
return cached.get("behind")
|
||||
if channel in {"stable", "canary"}:
|
||||
from hermes_cli.source_releases import resolve_source_release, source_repository
|
||||
|
||||
global _last_target_rev
|
||||
repository = source_repository(["git"] if repo_dir else None, repo_dir)
|
||||
_, _last_target_rev = resolve_source_release(channel, repository=repository)
|
||||
current = head_rev or embedded_rev
|
||||
# A selected release can be an ancestor after a channel switch.
|
||||
# Equality, not ancestry, means this install runs that release.
|
||||
behind = None if not current or not _last_target_rev else (
|
||||
0 if current == _last_target_rev else UPDATE_AVAILABLE_NO_COUNT
|
||||
)
|
||||
elif embedded_rev:
|
||||
behind = _check_via_rev(embedded_rev)
|
||||
else:
|
||||
# No checkout and no embedded revision — status can't be determined.
|
||||
behind = _check_via_local_git(repo_dir) if repo_dir is not None else None
|
||||
_quiet(lambda: cache_file.write_text(
|
||||
json.dumps({"ts": now, "behind": behind, "rev": embedded_rev, "ver": VERSION,
|
||||
"head": head_rev or embedded_rev, "target": _last_target_rev, "channel": channel}),
|
||||
encoding="utf-8"))
|
||||
return behind
|
||||
|
||||
|
||||
def _resolve_repo_dir() -> Optional[Path]:
|
||||
"""The active Hermes git checkout, or None if this isn't a git install.
|
||||
|
||||
@@ -491,11 +176,11 @@ def _compute_git_banner_state(repo_dir: Optional[Path] = None) -> Optional[dict]
|
||||
repo_dir = repo_dir or _resolve_repo_dir()
|
||||
if repo_dir is None:
|
||||
return _baked_banner_state()
|
||||
upstream, local = (_git_stdout(["rev-parse", "--short=8", rev], cwd=repo_dir) for rev in ("origin/main", "HEAD"))
|
||||
upstream, local = (source_check._git_stdout(["rev-parse", "--short=8", rev], cwd=repo_dir) for rev in ("origin/main", "HEAD"))
|
||||
if not upstream or not local:
|
||||
# Live-git lookup failed (e.g. shallow clone without origin/main).
|
||||
return _baked_banner_state()
|
||||
ahead = _git_count(["rev-list", "--count", "origin/main..HEAD"], cwd=repo_dir) or 0
|
||||
ahead = source_check._git_count(["rev-list", "--count", "origin/main..HEAD"], cwd=repo_dir) or 0
|
||||
return {"upstream": upstream, "local": local, "ahead": max(ahead, 0)}
|
||||
|
||||
|
||||
@@ -509,7 +194,7 @@ def get_latest_release_tag(repo_dir: Optional[Path] = None) -> Optional[tuple]:
|
||||
"""
|
||||
def _compute():
|
||||
rd = repo_dir or _resolve_repo_dir()
|
||||
tag = _git_stdout(["describe", "--tags", "--abbrev=0"], cwd=rd, timeout=3) if rd else None
|
||||
tag = source_check._git_stdout(["describe", "--tags", "--abbrev=0"], cwd=rd, timeout=3) if rd else None
|
||||
return (tag, f"{_RELEASE_URL_BASE}/{tag}") if tag else None
|
||||
return _memo("_latest_release_cache", _compute)
|
||||
|
||||
@@ -537,7 +222,7 @@ def format_banner_version_label() -> str:
|
||||
|
||||
channel = resolve_update_channel(_quiet(load_config), get_project_root())
|
||||
if channel in {"stable", "canary"}:
|
||||
head = _git_stdout(["rev-parse", "HEAD"], cwd=get_project_root())
|
||||
head = source_check._git_stdout(["rev-parse", "HEAD"], cwd=get_project_root())
|
||||
return f"{base} · {channel}" + (f" · local {head[:12]}" if head else "")
|
||||
state = get_git_banner_state()
|
||||
if not state:
|
||||
@@ -564,7 +249,7 @@ def prefetch_update_check():
|
||||
"""Kick off update check in a background daemon thread."""
|
||||
def _run():
|
||||
global _update_result
|
||||
_update_result = check_for_updates(passive=True)
|
||||
_update_result = source_check.check_for_updates(passive=True).get("behind")
|
||||
_update_check_done.set()
|
||||
_daemon(None, _run)
|
||||
|
||||
@@ -704,8 +389,8 @@ def banner_snapshot_fingerprint() -> Optional[str]:
|
||||
|
||||
def load_banner_snapshot(enabled_toolsets: List[str] = None) -> Optional[Dict[str, Any]]:
|
||||
"""Return the stored banner snapshot when its fingerprint is current."""
|
||||
blob = _read_json(_banner_snapshot_path())
|
||||
if blob is None:
|
||||
blob = _quiet(lambda: json.loads(_banner_snapshot_path().read_text(encoding="utf-8")))
|
||||
if not isinstance(blob, dict):
|
||||
return None
|
||||
fp = banner_snapshot_fingerprint()
|
||||
if (not fp or blob.get("fingerprint") != fp
|
||||
|
||||
@@ -131,7 +131,7 @@ _DEFAULT_EXPORT_EXCLUDE_ROOT = DEFAULT_EXPORT_EXCLUDE_ROOT = frozenset({
|
||||
"gateway.pid", "gateway_state.json", "processes.json",
|
||||
"auth.json", # API keys, OAuth tokens, credential pools
|
||||
".env", # API keys (dotenv)
|
||||
"auth.lock", "active_profile", ".update_check",
|
||||
"auth.lock", "active_profile", ".update_check", "source-checks",
|
||||
"errors.log",
|
||||
".hermes_history",
|
||||
# Caches (regenerated on use)
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Passive source update decisions for one exact installation and profile.
|
||||
|
||||
No fetch, lock repair, or Git writes. Desktop, CLI, and dashboard share this owner.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
import urllib.request
|
||||
|
||||
from hermes_constants import get_hermes_home
|
||||
from hermes_cli.source_releases import OFFICIAL_REPOSITORY, _GITHUB_ORIGIN, resolve_source_release
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
UPDATE_AVAILABLE_NO_COUNT = -1
|
||||
_UPDATE_CHECK_CACHE_SECONDS = 24 * 3600
|
||||
_UPDATE_CHECK_FAILURE_CACHE_SECONDS = 3600
|
||||
|
||||
|
||||
def _quiet(fn, default=None):
|
||||
try:
|
||||
return fn()
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def source_git_env() -> dict[str, str]:
|
||||
"""Keep read-only Git probes in their explicit cwd, not an inherited worktree."""
|
||||
from hermes_cli._subprocess_compat import noninteractive_git_env
|
||||
|
||||
env = noninteractive_git_env()
|
||||
for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE",
|
||||
"GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_SHALLOW_FILE", "GIT_NAMESPACE"):
|
||||
env.pop(key, None)
|
||||
env["GIT_OPTIONAL_LOCKS"] = "0"
|
||||
return env
|
||||
|
||||
|
||||
_GIT_TEXT_KW = {"text": True, "encoding": "utf-8", "errors": "replace"}
|
||||
|
||||
|
||||
def _git_run(args: list[str], *, cwd: Optional[Path] = None, timeout: int = 5, text: bool = True,
|
||||
git: str = "git"):
|
||||
"""Read Git state without prompts, optional index writes, or inherited targeting."""
|
||||
from hermes_cli._subprocess_compat import windows_hide_flags
|
||||
|
||||
kwargs: dict = {"creationflags": windows_hide_flags(), "env": source_git_env(), "stdin": subprocess.DEVNULL}
|
||||
try:
|
||||
return subprocess.run(
|
||||
[git, *args], capture_output=True, timeout=timeout, cwd=str(cwd) if cwd is not None else None,
|
||||
**(_GIT_TEXT_KW if text else {}), **kwargs)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _git_stdout(args: list[str], *, cwd: Path, timeout: int = 5, git: str = "git") -> Optional[str]:
|
||||
result = _git_run(args, cwd=cwd, timeout=timeout, git=git)
|
||||
if result is None or result.returncode != 0:
|
||||
return None
|
||||
return (result.stdout or "").strip()
|
||||
|
||||
|
||||
def _git_ok(args: list[str], **kw) -> bool:
|
||||
"""True when ``git <args>`` ran and exited 0 (output discarded)."""
|
||||
result = _git_run(args, text=False, **kw)
|
||||
return result is not None and result.returncode == 0
|
||||
|
||||
|
||||
def _git_count(args: list[str], *, cwd: Path) -> Optional[int]:
|
||||
"""``int`` of a successful ``git rev-list --count``-style command, else None."""
|
||||
result = _git_run(args, cwd=cwd)
|
||||
if result is not None and result.returncode == 0:
|
||||
return _quiet(lambda: int(result.stdout.strip()))
|
||||
return None
|
||||
|
||||
|
||||
def _is_full_sha(value: Optional[str]) -> bool:
|
||||
return isinstance(value, str) and len(value) == 40 and all(c in "0123456789abcdefABCDEF" for c in value)
|
||||
|
||||
|
||||
def _github_compare(current_rev: str, target_rev: str, repository: str = OFFICIAL_REPOSITORY) -> Optional[dict]:
|
||||
# Do not memoize this separately: force must bypass failed AND successful network results.
|
||||
if not (_is_full_sha(current_rev) and _is_full_sha(target_rev)):
|
||||
return None
|
||||
payload = _quiet(lambda: json.loads(_request(
|
||||
f"https://api.github.com/repos/{repository}/compare/{current_rev}...{target_rev}")))
|
||||
return payload if isinstance(payload, dict) else None
|
||||
|
||||
|
||||
def _github_compare_behind(current_rev: str, target_rev: str, repository: str = OFFICIAL_REPOSITORY) -> Optional[int]:
|
||||
payload = _github_compare(current_rev, target_rev, repository)
|
||||
ahead = payload.get("ahead_by") if payload else None
|
||||
return ahead if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0 else None
|
||||
|
||||
|
||||
def _request(url: str, accept: str = "application/vnd.github+json") -> str:
|
||||
req = urllib.request.Request(url, headers={"Accept": accept, "User-Agent": "hermes-update-check"})
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.read(2 * 1024 * 1024).decode("utf-8").strip()
|
||||
|
||||
|
||||
def _branch_tip(repository: str | None, branch: str, root: Path, git: str, remote: str = "origin") -> tuple[str | None, bool]:
|
||||
# A successful empty ref advertisement alone proves a branch was deleted.
|
||||
# GitHub 404 can also mean a private repository: it must not heal a branch.
|
||||
if repository:
|
||||
sha = _quiet(lambda: _request(
|
||||
f"https://api.github.com/repos/{repository}/commits/{quote(branch, safe='')}",
|
||||
"application/vnd.github.sha"))
|
||||
if _is_full_sha(sha):
|
||||
return sha, False
|
||||
if branch == "main" and remote == "origin":
|
||||
return None, False
|
||||
result = _git_run(["ls-remote", "--exit-code", "--heads", remote, f"refs/heads/{branch}"],
|
||||
cwd=root, git=git, timeout=10)
|
||||
if result is None:
|
||||
return None, False
|
||||
sha = result.stdout.split()[0] if result.returncode == 0 and result.stdout else None
|
||||
return (sha if _is_full_sha(sha) else None), result.returncode == 2
|
||||
|
||||
|
||||
def _commits(payload: dict | None) -> list[dict]:
|
||||
from datetime import datetime
|
||||
rows = []
|
||||
entries = (payload or {}).get("commits", [])
|
||||
for entry in entries if isinstance(entries, list) else []:
|
||||
if not isinstance(entry, dict) or not isinstance(entry.get("sha"), str):
|
||||
continue
|
||||
commit = entry.get("commit") or {}
|
||||
when = (commit.get("committer") or {}).get("date") or ""
|
||||
at = _quiet(lambda: int(datetime.fromisoformat(when.replace("Z", "+00:00")).timestamp() * 1000), 0)
|
||||
rows.append({"sha": entry["sha"], "summary": str(commit.get("message", "")).split("\n", 1)[0],
|
||||
"author": str((commit.get("author") or {}).get("name", "")), "at": at})
|
||||
return rows[::-1]
|
||||
|
||||
|
||||
def check_for_updates(*, install_root: Path | None = None, home: Path | None = None,
|
||||
branch: str | None = None, channel: str | None = None,
|
||||
cache_path: Path | None = None, branch_config_path: Path | None = None,
|
||||
force: bool = False,
|
||||
passive: bool = False, git: str = "git") -> dict:
|
||||
"""Return a presentation-ready status. Omitted branch follows the current checkout.
|
||||
|
||||
Only the default (running installation) may use HERMES_REVISION. An explicit
|
||||
target must never inherit the host process's embedded revision or stamp.
|
||||
"""
|
||||
from hermes_cli.config import detect_install_method, get_project_root, require_readable_config_before_write
|
||||
from hermes_cli.steward import read_install_stamp
|
||||
from hermes_cli.update_channel import install_id, resolve_update_channel
|
||||
from hermes_cli.update_contract import COMMIT_BUILD_UPDATE_MESSAGE
|
||||
|
||||
embedded = (os.environ.get("HERMES_REVISION") or None) if install_root is None else None
|
||||
root = Path(install_root if install_root is not None else get_project_root()).resolve()
|
||||
home = Path(home if home is not None else get_hermes_home()).resolve()
|
||||
stamp = read_install_stamp(root)
|
||||
result = {"supported": False, "hermesRoot": str(root), "behind": None, "commits": []}
|
||||
if stamp.get("source") == "commit-build":
|
||||
return {**result, "reason": "commit-build", "message": COMMIT_BUILD_UPDATE_MESSAGE}
|
||||
if stamp.get("payload") in {"bundled", "light"} or (install_root is None and detect_install_method(root) in {"docker", "apt"}):
|
||||
return {**result, "reason": "not-a-git-checkout"}
|
||||
if not embedded and not (root / ".git").exists():
|
||||
return {**result, "reason": "not-a-git-checkout",
|
||||
"message": "This install has no git checkout to update."}
|
||||
if stamp.get("updateMechanism") not in (None, "self") and not embedded:
|
||||
return {**result, "reason": "update-root-steward-owned-git-tree",
|
||||
"message": "This installation is managed by its install method; use its updater.", "advice": "git pull"}
|
||||
config = require_readable_config_before_write(home / "config.yaml")
|
||||
if passive and (config.get("updates") or {}).get("check") is False:
|
||||
return {**result, "reason": "disabled"}
|
||||
channel = channel or resolve_update_channel(config, root)
|
||||
if channel not in {"main", "stable", "canary"}:
|
||||
raise ValueError(f"Invalid update channel: {channel}")
|
||||
head = embedded or _git_stdout(["rev-parse", "HEAD"], cwd=root, git=git)
|
||||
current_branch = None if embedded else _git_stdout(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root, git=git)
|
||||
desktop_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8"))) if branch_config_path else None
|
||||
configured_branch = desktop_config.get("branch") if isinstance(desktop_config, dict) else None
|
||||
if isinstance(configured_branch, str):
|
||||
configured_branch = configured_branch.strip() or None
|
||||
else:
|
||||
configured_branch = None
|
||||
selected_branch = branch or configured_branch or (current_branch if current_branch and current_branch != "HEAD" else "main")
|
||||
origin = "" if embedded else (_git_stdout(["remote", "get-url", "origin"], cwd=root, git=git) or "")
|
||||
match = _GITHUB_ORIGIN.fullmatch(origin)
|
||||
repository = OFFICIAL_REPOSITORY if embedded else (match[1] if match else None)
|
||||
dirty = False if embedded else bool(_git_stdout(["status", "--porcelain"], cwd=root, git=git))
|
||||
result.update(supported=True, currentSha=head, currentBranch=current_branch, dirty=dirty)
|
||||
if channel != "main":
|
||||
result["channel"] = channel
|
||||
else:
|
||||
result["branch"] = selected_branch
|
||||
identity = {"root": str(root), "home": str(home), "head": head, "origin": origin, "branch": selected_branch,
|
||||
"channel": channel, "embedded": embedded}
|
||||
cache_file = Path(cache_path) if cache_path is not None else home / "source-checks" / f"{install_id(root)}.json"
|
||||
cached = _quiet(lambda: json.loads(cache_file.read_text(encoding="utf-8")))
|
||||
now = time.time()
|
||||
if (not force and isinstance(cached, dict) and cached.get("identity") == identity
|
||||
and isinstance(cached.get("status"), dict) and cached["status"].get("supported") is True):
|
||||
status = cached.get("status", {})
|
||||
ttl = _UPDATE_CHECK_FAILURE_CACHE_SECONDS if status.get("error") else _UPDATE_CHECK_CACHE_SECONDS
|
||||
ts = cached.get("ts")
|
||||
if isinstance(ts, (float, int)) and 0 <= now - ts < ttl:
|
||||
return {**status, "dirty": dirty, "currentBranch": current_branch}
|
||||
result["fetchedAt"] = int(now * 1000)
|
||||
if not _is_full_sha(head):
|
||||
result.update(error="head-unavailable", message="Could not read the installed revision.")
|
||||
elif channel in {"stable", "canary"}:
|
||||
tag, target = resolve_source_release(channel, [git] if not embedded else None, root,
|
||||
repository=repository or OFFICIAL_REPOSITORY)
|
||||
if not tag or not target:
|
||||
result.update(error="release-unavailable", message=f"Could not resolve the {channel} release commit.")
|
||||
else:
|
||||
result.update(latestTag=tag, targetSha=target, updateAvailable=head != target,
|
||||
behind=0 if head == target else UPDATE_AVAILABLE_NO_COUNT)
|
||||
else:
|
||||
official_ssh = (repository and repository.lower() == OFFICIAL_REPOSITORY.lower()
|
||||
and origin.lower().startswith(("git@", "ssh://")))
|
||||
# The public official repo does not require the user's SSH credentials.
|
||||
# Forks must keep their own origin, including its authentication.
|
||||
remote = (f"https://github.com/{OFFICIAL_REPOSITORY}.git"
|
||||
if embedded or (official_ssh and selected_branch != "main") else "origin")
|
||||
target, missing = _branch_tip(repository, selected_branch, root, git, remote)
|
||||
if missing and selected_branch != "main":
|
||||
result["branch"] = "main"
|
||||
if branch_config_path and not branch and configured_branch == selected_branch:
|
||||
# Do not overwrite a concurrent choice made while the network probe ran.
|
||||
current_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8")))
|
||||
if current_config == desktop_config:
|
||||
from utils import atomic_json_write
|
||||
atomic_json_write(branch_config_path, {**desktop_config, "branch": "main"})
|
||||
target, _ = _branch_tip(repository, "main", root, git, remote if embedded else "origin")
|
||||
if target is None:
|
||||
result.update(error="fetch-failed", message="Could not resolve the remote branch tip.")
|
||||
else:
|
||||
behind = UPDATE_AVAILABLE_NO_COUNT
|
||||
if head == target or (not embedded and _git_ok(
|
||||
["merge-base", "--is-ancestor", target, head], cwd=root, git=git)):
|
||||
behind = 0
|
||||
elif repository:
|
||||
payload = _github_compare(head, target, repository)
|
||||
ahead = (payload or {}).get("ahead_by")
|
||||
if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0:
|
||||
behind = ahead
|
||||
result["commits"] = _quiet(lambda: _commits(payload), []) if behind else []
|
||||
result.update(targetSha=target, behind=behind, updateAvailable=behind != 0)
|
||||
try:
|
||||
from utils import atomic_json_write
|
||||
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
atomic_json_write(cache_file, {"identity": identity, "ts": now, "status": result})
|
||||
except OSError as exc:
|
||||
logger.debug("Could not cache source check: %s", exc)
|
||||
return result
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import argparse
|
||||
import contextlib
|
||||
import sys
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--install-root", type=Path, required=True)
|
||||
parser.add_argument("--home", type=Path, required=True)
|
||||
parser.add_argument("--git", default="git")
|
||||
parser.add_argument("--branch")
|
||||
parser.add_argument("--channel", choices=("main", "stable", "canary"))
|
||||
parser.add_argument("--cache-path", type=Path)
|
||||
parser.add_argument("--branch-config-path", type=Path)
|
||||
parser.add_argument("--force", action="store_true")
|
||||
args = parser.parse_args()
|
||||
with contextlib.redirect_stdout(sys.stderr):
|
||||
result = check_for_updates(**vars(args))
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
from html.parser import HTMLParser
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import urllib.error
|
||||
@@ -26,9 +25,12 @@ _SHA = re.compile(r"[0-9a-f]{40}")
|
||||
def source_repository(git_cmd=None, cwd=None) -> str:
|
||||
"""GitHub forks own their releases; other origins must mirror official tags."""
|
||||
if git_cmd is not None:
|
||||
from hermes_cli.source_check import source_git_env
|
||||
|
||||
result = subprocess.run(
|
||||
[*git_cmd, "config", "--get", "remote.origin.url"], cwd=cwd,
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
|
||||
stdin=subprocess.DEVNULL, env=source_git_env(),
|
||||
)
|
||||
match = _GITHUB_ORIGIN.fullmatch(result.stdout.strip())
|
||||
if result.returncode == 0 and match:
|
||||
@@ -149,12 +151,14 @@ def resolve_source_release(channel: str, git_cmd=None, cwd=None, *, repository=N
|
||||
if not isinstance(sha, str) or not _SHA.fullmatch(sha):
|
||||
raise ValueError(f"No published commit for release {tag}")
|
||||
if git_cmd is not None:
|
||||
from hermes_cli.source_check import source_git_env
|
||||
|
||||
ref = f"refs/tags/{tag}"
|
||||
result = subprocess.run(
|
||||
[*git_cmd, "ls-remote", "--tags", "origin", ref, ref + "^{}"],
|
||||
cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
||||
check=True, timeout=60, stdin=subprocess.DEVNULL,
|
||||
env={**os.environ, "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"},
|
||||
env=source_git_env(),
|
||||
)
|
||||
refs = dict((parts[1], parts[0]) for line in result.stdout.splitlines()
|
||||
if len(parts := line.split()) == 2)
|
||||
@@ -166,36 +170,3 @@ def resolve_source_release(channel: str, git_cmd=None, cwd=None, *, repository=N
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
logger.warning("Could not resolve the %s source release: %s", channel, exc)
|
||||
return None, None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Read-only JSON probe for the desktop, using the CLI's channel authority."""
|
||||
import argparse
|
||||
import contextlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from hermes_cli.config import load_config, require_parseable_user_config
|
||||
from hermes_cli.update_channel import resolve_update_channel
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--install-root", type=Path, required=True)
|
||||
parser.add_argument("--git", default="git")
|
||||
args = parser.parse_args()
|
||||
# Config diagnostics must not corrupt the JSON transport.
|
||||
with contextlib.redirect_stdout(sys.stderr):
|
||||
# Recovery defaults are safe for repair UI, not for choosing an update target.
|
||||
require_parseable_user_config()
|
||||
channel = resolve_update_channel(load_config(), args.install_root)
|
||||
result = {"channel": channel}
|
||||
if channel in ("stable", "canary"):
|
||||
tag, sha = resolve_source_release(channel, [args.git], args.install_root)
|
||||
if tag is None or sha is None:
|
||||
result.update(error="release-unavailable", message=f"Could not resolve the {channel} release commit.")
|
||||
else:
|
||||
result.update(latestTag=tag, targetSha=sha)
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -439,35 +439,6 @@ def _print_called_process_error_tail(
|
||||
# scripts/write_install_stamp.py.
|
||||
|
||||
|
||||
def _invalidate_update_cache():
|
||||
"""Delete the update-check cache for ALL profiles so no banner
|
||||
reports a stale "commits behind" count after a successful update.
|
||||
|
||||
The git repo is shared across profiles — when one profile runs
|
||||
``hermes update``, every profile is now current.
|
||||
"""
|
||||
homes = []
|
||||
# Default profile home (Docker-aware — uses /opt/data in Docker)
|
||||
from hermes_constants import get_default_hermes_root
|
||||
|
||||
default_home = get_default_hermes_root()
|
||||
homes.append(default_home)
|
||||
# Named profiles under <root>/profiles/
|
||||
profiles_root = default_home / "profiles"
|
||||
if profiles_root.is_dir():
|
||||
for entry in profiles_root.iterdir():
|
||||
if entry.is_dir():
|
||||
homes.append(entry)
|
||||
for home in homes:
|
||||
try:
|
||||
cache_file = home / ".update_check"
|
||||
if cache_file.exists():
|
||||
cache_file.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
def _write_update_incomplete_marker() -> None:
|
||||
# Historical updater hook. PM's successful facts determine completion.
|
||||
stop_for_relaunch()
|
||||
@@ -752,7 +723,7 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False, ch
|
||||
if head_sha and target_sha and head_sha == target_sha:
|
||||
print("✓ Already up to date.")
|
||||
else:
|
||||
from hermes_cli.banner import _github_compare_behind
|
||||
from hermes_cli.source_check import _github_compare_behind
|
||||
from hermes_cli.config import recommended_update_command
|
||||
|
||||
counted = _github_compare_behind(head_sha, target_sha)
|
||||
@@ -1071,7 +1042,7 @@ def _prepare_checkout_for_update(
|
||||
|
||||
apply_is_shallow = _is_shallow_checkout(git_cmd)
|
||||
if commit_count > 0 and apply_is_shallow:
|
||||
from hermes_cli.banner import _github_compare_behind
|
||||
from hermes_cli.source_check import _github_compare_behind
|
||||
counted = _github_compare_behind(*_tip_shas(git_cmd, target_ref))
|
||||
# counted == 0 means local-ahead: falls through to the up-to-date path.
|
||||
commit_count = counted if counted is not None else -1
|
||||
@@ -1303,7 +1274,6 @@ def _finish_already_up_to_date(
|
||||
_windows_gateway_resume) -> None:
|
||||
""""Already up to date" path: restore stash/branch, repair the checkout, catch up the fleet.
|
||||
``sys.exit(1)`` when the repair is incomplete (after gateway exit code + partial receipt)."""
|
||||
_invalidate_update_cache()
|
||||
|
||||
# Restore stash and switch back if we moved. EXCEPTION: a parked branch verified clean +
|
||||
# fully merged stays on the target — re-parking on the stale branch recreates the incident.
|
||||
@@ -1347,7 +1317,6 @@ def _apply_pulled_update(
|
||||
had_desktop_app_before_update, pre_update_snapshot_id, _pre_update_plan,
|
||||
_windows_gateway_resume) -> None:
|
||||
"""Post-pull phase: verify HEAD, sync Python/Node/web/Desktop, maintenance, fleet restart."""
|
||||
_invalidate_update_cache()
|
||||
post_pull_sha = _verify_head_after_pull(
|
||||
git_cmd, branch, pre_pull_sha, in_place_update=_plan.in_place_update,
|
||||
_windows_gateway_resume=_windows_gateway_resume)
|
||||
|
||||
@@ -297,15 +297,13 @@ async def check_hermes_update(force: bool = False):
|
||||
payload["message"] = non_applyable()
|
||||
return payload
|
||||
|
||||
# banner.check_for_updates() handles git / nix-revision paths through the GitHub API and
|
||||
# source_check.check_for_updates() handles git / nix-revision paths through the GitHub API and
|
||||
# caches the result for 24h. ``force`` busts the cache so "Check now" reflects reality.
|
||||
try:
|
||||
from hermes_cli.banner import check_for_updates, upstream_commits_behind
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
|
||||
if force:
|
||||
with contextlib.suppress(OSError):
|
||||
(get_hermes_home() / ".update_check").unlink()
|
||||
behind = await asyncio.to_thread(check_for_updates)
|
||||
status = await asyncio.to_thread(check_for_updates, force=force)
|
||||
behind = status.get("behind")
|
||||
except Exception:
|
||||
_log.exception("Update check failed")
|
||||
behind = None
|
||||
@@ -319,7 +317,8 @@ async def check_hermes_update(force: bool = False):
|
||||
payload["update_available"] = True
|
||||
# "What's changed" for the desktop's remote update overlay; best-effort
|
||||
# (empty list on any failure).
|
||||
payload["commits"] = await asyncio.to_thread(upstream_commits_behind)
|
||||
payload["commits"] = [{**row, "sha": row["sha"][:7], "at": row["at"] // 1000}
|
||||
for row in status.get("commits", [])[:20]]
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
@@ -35,99 +35,12 @@ def test_get_git_banner_state_reads_origin_and_head(tmp_path):
|
||||
raise AssertionError(f"unexpected command: {cmd}")
|
||||
return results[key]
|
||||
|
||||
with patch("hermes_cli.banner.subprocess.run", side_effect=fake_run):
|
||||
with patch("hermes_cli.source_check.subprocess.run", side_effect=fake_run):
|
||||
state = banner.get_git_banner_state(repo_dir)
|
||||
|
||||
assert state == {"upstream": "b2f477a3", "local": "af8aad31", "ahead": 3}
|
||||
|
||||
|
||||
def test_check_via_local_git_ssh_fastpath_ahead_not_behind(tmp_path):
|
||||
"""SSH fast path must not report an ahead (carried) HEAD as behind.
|
||||
|
||||
A carried local commit means tip SHAs differ, but the fresh upstream tip
|
||||
is an ancestor of HEAD — that is "ahead", and reporting it as behind
|
||||
nudges the user into `hermes update`, which can wipe the carried work.
|
||||
"""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from hermes_cli import banner
|
||||
|
||||
repo_dir = tmp_path / "repo"
|
||||
(repo_dir / ".git").mkdir(parents=True)
|
||||
|
||||
def fake_git_stdout(args, *, cwd, timeout=5, network=False):
|
||||
if args == ["remote", "get-url", "origin"]:
|
||||
return "git@github.com:NousResearch/hermes-agent.git"
|
||||
if args == ["rev-parse", "HEAD"]:
|
||||
return "b" * 40 # carried commit, differs from upstream tip
|
||||
raise AssertionError(f"unexpected git call: {args}")
|
||||
|
||||
with (
|
||||
patch.object(banner, "_git_stdout", side_effect=fake_git_stdout),
|
||||
patch.object(banner, "_github_branch_tip", return_value="a" * 40),
|
||||
# merge-base --is-ancestor exits 0: upstream tip IS an ancestor of HEAD
|
||||
patch.object(banner.subprocess, "run", return_value=MagicMock(returncode=0)),
|
||||
):
|
||||
behind = banner._check_via_local_git(repo_dir)
|
||||
|
||||
assert behind == 0
|
||||
|
||||
|
||||
def test_check_via_local_git_ssh_fastpath_genuinely_behind(tmp_path):
|
||||
"""SSH fast path reports the exact count (compare API) when behind."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from hermes_cli import banner
|
||||
|
||||
repo_dir = tmp_path / "repo"
|
||||
(repo_dir / ".git").mkdir(parents=True)
|
||||
|
||||
def fake_git_stdout(args, *, cwd, timeout=5, network=False):
|
||||
if args == ["remote", "get-url", "origin"]:
|
||||
return "git@github.com:NousResearch/hermes-agent.git"
|
||||
if args == ["rev-parse", "HEAD"]:
|
||||
return "b" * 40
|
||||
raise AssertionError(f"unexpected git call: {args}")
|
||||
|
||||
with (
|
||||
patch.object(banner, "_git_stdout", side_effect=fake_git_stdout),
|
||||
patch.object(banner, "_github_branch_tip", return_value="a" * 40),
|
||||
# merge-base --is-ancestor exits 1: not an ancestor -> genuinely behind
|
||||
patch.object(banner.subprocess, "run", return_value=MagicMock(returncode=1)),
|
||||
patch.object(banner, "_github_compare_behind", return_value=3),
|
||||
):
|
||||
behind = banner._check_via_local_git(repo_dir)
|
||||
|
||||
assert behind == 3
|
||||
|
||||
|
||||
def test_check_via_local_git_ssh_fastpath_offline_keeps_sentinel(tmp_path):
|
||||
"""Behind + compare API unreachable = honest no-count sentinel, never 1."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from hermes_cli import banner
|
||||
|
||||
repo_dir = tmp_path / "repo"
|
||||
(repo_dir / ".git").mkdir(parents=True)
|
||||
|
||||
def fake_git_stdout(args, *, cwd, timeout=5, network=False):
|
||||
if args == ["remote", "get-url", "origin"]:
|
||||
return "git@github.com:NousResearch/hermes-agent.git"
|
||||
if args == ["rev-parse", "HEAD"]:
|
||||
return "b" * 40
|
||||
raise AssertionError(f"unexpected git call: {args}")
|
||||
|
||||
with (
|
||||
patch.object(banner, "_git_stdout", side_effect=fake_git_stdout),
|
||||
patch.object(banner, "_github_branch_tip", return_value="a" * 40),
|
||||
patch.object(banner.subprocess, "run", return_value=MagicMock(returncode=1)),
|
||||
patch.object(banner, "_github_compare_behind", return_value=None),
|
||||
):
|
||||
behind = banner._check_via_local_git(repo_dir)
|
||||
|
||||
assert behind == banner.UPDATE_AVAILABLE_NO_COUNT
|
||||
|
||||
|
||||
def test_check_via_local_git_insteadof_rewrite_routes_to_ssh_fastpath(tmp_path, monkeypatch):
|
||||
"""#104591: the origin-URL probe must run under the fetch's config-isolated env.
|
||||
|
||||
@@ -173,7 +86,8 @@ def test_check_via_local_git_insteadof_rewrite_routes_to_ssh_fastpath(tmp_path,
|
||||
monkeypatch.setenv("USERPROFILE", str(home)) # Git for Windows resolves global config here too
|
||||
|
||||
calls = []
|
||||
real_run = banner.subprocess.run
|
||||
from hermes_cli import source_check
|
||||
real_run = source_check.subprocess.run
|
||||
|
||||
def spy_run(args, **kwargs):
|
||||
calls.append((list(args), kwargs))
|
||||
@@ -181,10 +95,10 @@ def test_check_via_local_git_insteadof_rewrite_routes_to_ssh_fastpath(tmp_path,
|
||||
raise AssertionError(f"a GitHub origin must be probed via the API, not git {args[1]}")
|
||||
return real_run(args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(banner.subprocess, "run", spy_run)
|
||||
monkeypatch.setattr(banner, "_github_branch_tip", lambda slug, branch: head_sha)
|
||||
monkeypatch.setattr(source_check.subprocess, "run", spy_run)
|
||||
monkeypatch.setattr(source_check, "_branch_tip", lambda *args: (head_sha, False))
|
||||
|
||||
behind = banner._check_via_local_git(repo_dir)
|
||||
behind = source_check.check_for_updates(install_root=repo_dir, branch="main").get("behind")
|
||||
|
||||
# Same upstream tip as HEAD: the SSH fast path concludes "not behind".
|
||||
assert behind == 0
|
||||
|
||||
@@ -5,7 +5,7 @@ from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import banner
|
||||
from hermes_cli import banner, source_check
|
||||
from hermes_cli.update_channel import install_id
|
||||
|
||||
|
||||
@@ -19,10 +19,9 @@ def test_release_channel_never_compares_main_or_reuses_main_cache(tmp_path, monk
|
||||
monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))
|
||||
monkeypatch.delenv("HERMES_REVISION", raising=False)
|
||||
monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: root)
|
||||
monkeypatch.setattr(banner, "_resolve_repo_dir", lambda: root)
|
||||
head = "a" * 40
|
||||
target = "b" * 40
|
||||
monkeypatch.setattr(banner, "_git_stdout", lambda args, **kw: head if args == ["rev-parse", "HEAD"] else "https://github.com/NousResearch/hermes-agent.git")
|
||||
monkeypatch.setattr(source_check, "_git_stdout", lambda args, **kw: head if args == ["rev-parse", "HEAD"] else "https://github.com/example/fork.git")
|
||||
(get_hermes_home() / "config.yaml").write_text(json.dumps({
|
||||
"update": {"installs": {install_id(root): {"path": str(root), "channel": channel}}}
|
||||
}))
|
||||
@@ -30,22 +29,15 @@ def test_release_channel_never_compares_main_or_reuses_main_cache(tmp_path, monk
|
||||
"rev": None, "ver": banner.VERSION, "head": head, "behind": 99, "ts": 10**12,
|
||||
}))
|
||||
resolve = Mock(return_value=("v1.2.3" if channel == "stable" else "v1.2.4-canary.20260911", target))
|
||||
monkeypatch.setattr("hermes_cli.source_releases.resolve_source_release", resolve)
|
||||
repository = Mock(return_value="example/fork")
|
||||
monkeypatch.setattr("hermes_cli.source_releases.source_repository", repository)
|
||||
main = Mock(return_value="c" * 40)
|
||||
monkeypatch.setattr(banner, "_github_branch_tip", main)
|
||||
compare = Mock(return_value=2)
|
||||
monkeypatch.setattr(banner, "_tips_behind", compare)
|
||||
|
||||
assert banner.check_for_updates(passive=True) == banner.UPDATE_AVAILABLE_NO_COUNT
|
||||
repository.assert_called_once_with(["git"], root)
|
||||
resolve.assert_called_once_with(channel, repository="example/fork")
|
||||
compare.assert_not_called()
|
||||
monkeypatch.setattr(source_check, "resolve_source_release", resolve)
|
||||
main = Mock(side_effect=AssertionError("release must not check a branch"))
|
||||
monkeypatch.setattr(source_check, "_branch_tip", main)
|
||||
status = source_check.check_for_updates(passive=True)
|
||||
assert status["behind"] == source_check.UPDATE_AVAILABLE_NO_COUNT
|
||||
resolve.assert_called_once_with(channel, ["git"], root, repository="example/fork")
|
||||
main.assert_not_called()
|
||||
cache = json.loads((get_hermes_home() / ".update_check").read_text())
|
||||
assert cache["channel"] == channel
|
||||
assert cache["target"] == target
|
||||
assert status["channel"] == channel
|
||||
assert status["targetSha"] == target
|
||||
# The selected release may be an ancestor (a requested canary → stable switch).
|
||||
# That is still a different release, not "already current" or "behind main".
|
||||
label = banner.format_banner_version_label()
|
||||
|
||||
@@ -42,21 +42,18 @@ def test_commit_build_refuses_without_gui_advice(commit_build, git_present):
|
||||
|
||||
@pytest.mark.parametrize("passive", [False, True])
|
||||
def test_commit_build_never_checks_upstream_or_reuses_source_cache(commit_build, monkeypatch, passive):
|
||||
from hermes_cli import banner
|
||||
from hermes_cli import banner, source_check
|
||||
|
||||
# Even a shared home's source-checkout cache and an embedded SHA cannot turn this into an update.
|
||||
monkeypatch.setenv("HERMES_REVISION", "b" * 40)
|
||||
check = Mock(return_value=5)
|
||||
monkeypatch.setattr(banner, "_check_via_rev", check)
|
||||
cache = Mock(return_value={"behind": 5})
|
||||
monkeypatch.setattr(banner, "_read_json", cache)
|
||||
assert banner.check_for_updates(passive=passive) is None
|
||||
check = Mock(side_effect=AssertionError("must not probe"))
|
||||
monkeypatch.setattr(source_check, "_branch_tip", check)
|
||||
assert source_check.check_for_updates(passive=passive)["behind"] is None
|
||||
check.assert_not_called()
|
||||
cache.assert_not_called()
|
||||
|
||||
|
||||
def test_commit_version_banner_uses_stamp_not_shared_checkout(commit_build, monkeypatch):
|
||||
from hermes_cli import banner
|
||||
from hermes_cli import banner, source_check
|
||||
from hermes_cli.version_info import get_version_info
|
||||
|
||||
git = Mock(side_effect=AssertionError("version must not inspect another checkout"))
|
||||
@@ -73,7 +70,7 @@ def test_commit_backend_update_routes_refuse_before_checks_or_spawns(commit_buil
|
||||
from starlette.testclient import TestClient
|
||||
import hermes_cli.web_server as server
|
||||
import hermes_cli.web_server_gateway as gateway
|
||||
from hermes_cli import banner
|
||||
from hermes_cli import banner, source_check
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
monkeypatch.setattr(server, "PROJECT_ROOT", commit_build)
|
||||
@@ -82,7 +79,7 @@ def test_commit_backend_update_routes_refuse_before_checks_or_spawns(commit_buil
|
||||
spawn = Mock(side_effect=AssertionError("no updater process"))
|
||||
monkeypatch.setattr(gateway, "_spawn_hermes_action", spawn)
|
||||
check = Mock(side_effect=AssertionError("no update check"))
|
||||
monkeypatch.setattr(banner, "check_for_updates", check)
|
||||
monkeypatch.setattr(source_check, "check_for_updates", check)
|
||||
cache = get_hermes_home() / ".update_check"
|
||||
cache.write_text("source checkout cache")
|
||||
client = TestClient(server.app)
|
||||
|
||||
@@ -848,7 +848,7 @@ class TestUpdateCheckEndpoint:
|
||||
# Stub the shared checker so the contract is deterministic (no network).
|
||||
import hermes_cli.banner as banner
|
||||
|
||||
monkeypatch.setattr(banner, "check_for_updates", lambda: 5)
|
||||
monkeypatch.setattr("hermes_cli.source_check.check_for_updates", lambda **kw: {"behind": 5, "commits": []})
|
||||
|
||||
r = self.client.get("/api/hermes/update/check")
|
||||
assert r.status_code == 200
|
||||
|
||||
@@ -1,30 +1,9 @@
|
||||
"""Passive opt-out keeps explicit update checks available."""
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
|
||||
def test_passive_check_obeys_config_before_using_cached_notice(monkeypatch):
|
||||
from hermes_cli import banner
|
||||
|
||||
home = get_hermes_home()
|
||||
# The cache is keyed on the checkout's HEAD (an update moving HEAD invalidates it).
|
||||
repo_dir = banner._resolve_repo_dir()
|
||||
head = banner._git_stdout(["rev-parse", "HEAD"], cwd=repo_dir) if repo_dir else None
|
||||
(home / ".update_check").write_text(json.dumps({
|
||||
"ts": time.time(), "behind": 17, "rev": None, "ver": banner.VERSION, "head": head,
|
||||
}), encoding="utf-8")
|
||||
monkeypatch.delenv("HERMES_REVISION", raising=False)
|
||||
config = home / "config.yaml"
|
||||
config.write_text("updates:\n check: true\n", encoding="utf-8")
|
||||
assert banner.check_for_updates(passive=True) == 17
|
||||
config.write_text("updates:\n check: false\n", encoding="utf-8")
|
||||
assert banner.check_for_updates(passive=True) is None
|
||||
assert banner.check_for_updates() == 17
|
||||
|
||||
|
||||
def test_explicit_check_fetches_local_origin_despite_passive_opt_out(tmp_path, monkeypatch, capsys):
|
||||
from hermes_cli import main
|
||||
from hermes_cli.update_cmd import _cmd_update_check
|
||||
|
||||
@@ -113,7 +113,7 @@ def test_update_check_prunes_and_reports_count(tmp_path, monkeypatch, capsys):
|
||||
|
||||
monkeypatch.setattr(update_cmd, "_git_run", fake_git_run)
|
||||
monkeypatch.setattr(update_cmd, "_base_git_cmd", lambda: ["git"])
|
||||
monkeypatch.setattr("hermes_cli.banner._github_compare_behind", lambda *a, **k: 0)
|
||||
monkeypatch.setattr("hermes_cli.source_check._github_compare_behind", lambda *a, **k: 0)
|
||||
prune_calls = []
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.gitlock.prune_stale_shallow_grafts",
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Exercise the passive checker with real linked worktrees and loopback HTTP."""
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def installation(tmp_path, monkeypatch):
|
||||
root = tmp_path / "checkout"
|
||||
root.mkdir()
|
||||
home = tmp_path / "profile"
|
||||
home.mkdir()
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.delenv("HERMES_REVISION", raising=False)
|
||||
monkeypatch.delenv("HERMES_MANAGED", raising=False)
|
||||
|
||||
def git(*args, cwd=root):
|
||||
return subprocess.check_output([
|
||||
"git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid",
|
||||
"-c", "commit.gpgsign=false", *args,
|
||||
], cwd=cwd, text=True).strip()
|
||||
|
||||
git("init", "-b", "main")
|
||||
git("commit", "--allow-empty", "-m", "base")
|
||||
base = git("rev-parse", "HEAD")
|
||||
git("commit", "--allow-empty", "-m", "local")
|
||||
head = git("rev-parse", "HEAD")
|
||||
git("remote", "add", "origin", "https://github.com/fixture/fork.git")
|
||||
linked = tmp_path / "linked"
|
||||
git("worktree", "add", "-b", "feature/gui", str(linked))
|
||||
responses = {}
|
||||
requests = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
requests.append(self.path)
|
||||
code, body = responses.get(self.path, (404, {}))
|
||||
self.send_response(code)
|
||||
self.end_headers()
|
||||
self.wfile.write((body if isinstance(body, str) else json.dumps(body)).encode())
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
original = urllib.request.urlopen
|
||||
|
||||
def local(request, *args, **kwargs):
|
||||
url = urlsplit(request.full_url)
|
||||
assert url.hostname in {"api.github.com", "hermes-assets.nousresearch.com"}
|
||||
return original(f"http://127.0.0.1:{server.server_port}{url.path}" + (f"?{url.query}" if url.query else ""), *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(urllib.request, "urlopen", local)
|
||||
yield root, linked, home, base, head, responses, requests, git
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_target_worktree_owns_admission_and_fork_comparison(installation, monkeypatch):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
(root / "install-stamp.json").write_text(json.dumps({"updateMechanism": "external"}))
|
||||
(linked / "install-stamp.json").write_text(json.dumps({"updateMechanism": "self"}))
|
||||
cache = home / "shared-cache.json"
|
||||
target = "a" * 40
|
||||
responses["/repos/fixture/fork/commits/feature%2Fgui"] = (200, target)
|
||||
responses[f"/repos/fixture/fork/compare/{head}...{target}"] = (200, {"ahead_by": 3, "commits": []})
|
||||
commands = []
|
||||
original = subprocess.run
|
||||
|
||||
def record(args, **kwargs):
|
||||
commands.append(args)
|
||||
return original(args, **kwargs)
|
||||
|
||||
before = {str(p.relative_to(root)): p.read_bytes() for p in (root / ".git").rglob("*") if p.is_file()}
|
||||
monkeypatch.setattr(subprocess, "run", record)
|
||||
status = check_for_updates(install_root=linked, home=home, cache_path=cache)
|
||||
assert status["supported"] is True
|
||||
assert status["branch"] == "feature/gui"
|
||||
assert status["behind"] == 3
|
||||
assert status["hermesRoot"] == str(linked)
|
||||
assert check_for_updates(install_root=root, home=home, cache_path=cache)["supported"] is False
|
||||
assert len(requests) == 2
|
||||
assert all(not any(arg in {"fetch", "checkout", "reset", "update-ref", "stash"} for arg in cmd) for cmd in commands)
|
||||
assert git("rev-parse", "HEAD", cwd=linked) == head
|
||||
assert {str(p.relative_to(root)): p.read_bytes() for p in (root / ".git").rglob("*") if p.is_file()} == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tip_kind,compare,expected", [
|
||||
("head", None, 0), ("base", None, 0),
|
||||
("unknown", {"ahead_by": 61}, 61), ("unknown", {"ahead_by": 0}, 0),
|
||||
("unknown", None, -1), ("unknown", {"ahead_by": True}, -1),
|
||||
])
|
||||
def test_counts_are_honest_without_fetch(installation, tip_kind, compare, expected):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
target = {"head": head, "base": base, "unknown": "a" * 40}[tip_kind]
|
||||
responses["/repos/fixture/fork/commits/main"] = (200, target)
|
||||
if compare is not None:
|
||||
responses[f"/repos/fixture/fork/compare/{head}...{target}"] = (200, compare)
|
||||
status = check_for_updates(install_root=root, home=home)
|
||||
assert status["behind"] == expected
|
||||
assert status["updateAvailable"] is (expected != 0)
|
||||
if tip_kind != "unknown":
|
||||
assert len(requests) == 1
|
||||
|
||||
|
||||
def test_cache_force_expiry_and_passive_opt_out(installation, monkeypatch):
|
||||
from hermes_cli import source_check
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
clock = [1000000.0]
|
||||
monkeypatch.setattr(source_check.time, "time", lambda: clock[0])
|
||||
url = "/repos/fixture/fork/commits/main"
|
||||
responses[url] = (200, head)
|
||||
check = lambda **kw: source_check.check_for_updates(install_root=root, home=home, **kw)
|
||||
assert check()["behind"] == 0
|
||||
responses[url] = (503, {})
|
||||
(root / "dirty.txt").write_text("carried work")
|
||||
assert check()["dirty"] is True
|
||||
assert len(requests) == 1
|
||||
assert check(force=True)["error"] == "fetch-failed"
|
||||
clock[0] += 3599
|
||||
assert check()["error"] == "fetch-failed"
|
||||
assert len(requests) == 2
|
||||
clock[0] += 2
|
||||
responses[url] = (200, head)
|
||||
assert check()["behind"] == 0
|
||||
assert len(requests) == 3
|
||||
clock[0] += 86401
|
||||
assert check()["behind"] == 0
|
||||
assert len(requests) == 4
|
||||
(home / "config.yaml").write_text("updates: {check: false}")
|
||||
assert check(passive=True)["behind"] is None
|
||||
assert check()["behind"] == 0
|
||||
assert len(requests) == 4
|
||||
git("commit", "--allow-empty", "-m", "moved")
|
||||
responses[url] = (200, git("rev-parse", "HEAD"))
|
||||
assert check()["behind"] == 0
|
||||
assert len(requests) == 5
|
||||
|
||||
|
||||
def test_explicit_and_current_branch_heal_only_after_confirmed_absence(installation, monkeypatch):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
git("remote", "set-url", "origin", str(root))
|
||||
# Use the same real linked worktree with a local origin. No GitHub fallback is involved.
|
||||
assert check_for_updates(install_root=linked, home=home)["branch"] == "feature/gui"
|
||||
assert check_for_updates(install_root=linked, home=home, branch="main")["branch"] == "main"
|
||||
assert check_for_updates(install_root=linked, home=home, branch="deleted")["branch"] == "main"
|
||||
git("remote", "set-url", "origin", str(home / "unreachable"))
|
||||
failed = check_for_updates(install_root=linked, home=home, branch="deleted", force=True)
|
||||
assert failed["branch"] == "deleted"
|
||||
assert failed["error"] == "fetch-failed"
|
||||
assert git("branch", "--show-current", cwd=linked) == "feature/gui"
|
||||
assert requests == []
|
||||
|
||||
|
||||
def test_running_revision_is_not_applied_to_an_explicit_target(installation, monkeypatch):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
monkeypatch.setenv("HERMES_REVISION", "e" * 40)
|
||||
monkeypatch.setenv("HERMES_INSTALL_ROOT", str(root))
|
||||
responses["/repos/fixture/fork/commits/feature%2Fgui"] = (200, head)
|
||||
assert check_for_updates(install_root=linked, home=home)["currentSha"] == head
|
||||
# Default invocation retains the Nix revision probe even without a Git checkout.
|
||||
monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: home)
|
||||
responses["/repos/NousResearch/hermes-agent/commits/main"] = (200, "e" * 40)
|
||||
assert check_for_updates(home=home)["behind"] == 0
|
||||
|
||||
|
||||
def test_deleted_desktop_branch_is_persisted_only_after_definitive_probe(installation):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
branch_file = home / "desktop-update.json"
|
||||
branch_file.write_text(json.dumps({"branch": "deleted", "other": "preserved"}))
|
||||
git("remote", "set-url", "origin", str(home / "unreachable"))
|
||||
status = check_for_updates(install_root=linked, home=home, branch_config_path=branch_file)
|
||||
assert status["branch"] == "deleted"
|
||||
assert json.loads(branch_file.read_text())["branch"] == "deleted"
|
||||
git("remote", "set-url", "origin", str(root))
|
||||
status = check_for_updates(install_root=linked, home=home, branch_config_path=branch_file)
|
||||
assert status["branch"] == "main"
|
||||
assert json.loads(branch_file.read_text()) == {"branch": "main", "other": "preserved"}
|
||||
|
||||
|
||||
def test_inherited_git_target_cannot_redirect_an_explicit_install(installation, monkeypatch):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
responses["/repos/fixture/fork/commits/feature%2Fgui"] = (200, head)
|
||||
monkeypatch.setenv("GIT_DIR", str(root / ".git"))
|
||||
monkeypatch.setenv("GIT_WORK_TREE", str(root))
|
||||
status = check_for_updates(install_root=linked, home=home)
|
||||
assert status["currentBranch"] == "feature/gui"
|
||||
assert status["behind"] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mechanism", ["external", "electron-updater", "app-installer", "microsoft-store", "self", None])
|
||||
def test_source_admission_is_stamp_owned_not_path_owned(installation, mechanism):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
if mechanism:
|
||||
(linked / "install-stamp.json").write_text(json.dumps({"updateMechanism": mechanism, "distribution": "nix" if mechanism == "external" else "source"}))
|
||||
responses["/repos/fixture/fork/commits/feature%2Fgui"] = (200, head)
|
||||
status = check_for_updates(install_root=linked, home=home)
|
||||
assert status["supported"] is (mechanism in ("self", None))
|
||||
assert len(requests) == (1 if status["supported"] else 0)
|
||||
empty = home / "no-source"
|
||||
empty.mkdir()
|
||||
(empty / "install-stamp.json").write_text(json.dumps({"updateMechanism": mechanism, "distribution": "nix" if mechanism == "external" else "source"}))
|
||||
assert check_for_updates(install_root=empty, home=home)["reason"] == "not-a-git-checkout"
|
||||
|
||||
|
||||
def test_embedded_revision_keeps_https_ref_advertisement_recovery(installation, monkeypatch):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
monkeypatch.setenv("HERMES_REVISION", head)
|
||||
monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: home)
|
||||
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda root: "nix")
|
||||
original = subprocess.run
|
||||
probes = []
|
||||
|
||||
def advertise(args, **kwargs):
|
||||
if "ls-remote" in args:
|
||||
probes.append((args, kwargs))
|
||||
return subprocess.CompletedProcess(args, 0, head + "\trefs/heads/main\n", "")
|
||||
return original(args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", advertise)
|
||||
assert check_for_updates(home=home)["behind"] == 0
|
||||
assert len(probes) == 1
|
||||
assert "https://github.com/NousResearch/hermes-agent.git" in probes[0][0]
|
||||
assert probes[0][1]["stdin"] == subprocess.DEVNULL
|
||||
assert probes[0][1]["env"]["GIT_TERMINAL_PROMPT"] == "0"
|
||||
|
||||
|
||||
def test_malformed_optional_changelog_and_cache_do_not_hide_the_update(installation):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
cache = home / "cache.json"
|
||||
responses["/repos/fixture/fork/commits/main"] = (200, "a" * 40)
|
||||
responses[f"/repos/fixture/fork/compare/{head}...{'a' * 40}"] = (200, {
|
||||
"ahead_by": 2, "commits": [{"sha": "b" * 40, "commit": 42}],
|
||||
})
|
||||
status = check_for_updates(install_root=root, home=home, cache_path=cache)
|
||||
assert status["behind"] == 2
|
||||
assert status["updateAvailable"] is True
|
||||
data = json.loads(cache.read_text())
|
||||
data["status"] = None
|
||||
cache.write_text(json.dumps(data))
|
||||
assert check_for_updates(install_root=root, home=home, cache_path=cache)["behind"] == 2
|
||||
assert len(requests) == 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize("repository,heals", [("NousResearch/hermes-agent", True), ("fixture/fork", False)])
|
||||
def test_official_ssh_healing_uses_public_https_without_retargeting_forks(installation, monkeypatch, repository, heals):
|
||||
from hermes_cli.source_check import check_for_updates
|
||||
root, linked, home, base, head, responses, requests, git = installation
|
||||
git("remote", "set-url", "origin", f"git@github.com:{repository}.git")
|
||||
git("config", f"url.{root.as_uri()}.insteadOf", "https://github.com/NousResearch/hermes-agent.git")
|
||||
monkeypatch.setenv("GIT_SSH_COMMAND", "false")
|
||||
branch_file = home / "desktop-update.json"
|
||||
branch_file.write_text(json.dumps({"branch": "deleted"}))
|
||||
responses[f"/repos/{repository}/commits/main"] = (200, head)
|
||||
status = check_for_updates(install_root=linked, home=home, branch_config_path=branch_file)
|
||||
assert status["branch"] == ("main" if heals else "deleted")
|
||||
assert json.loads(branch_file.read_text())["branch"] == status["branch"]
|
||||
if heals:
|
||||
assert status["behind"] == 0
|
||||
else:
|
||||
assert status["error"] == "fetch-failed"
|
||||
@@ -15,11 +15,11 @@ def test_invalid_config_refuses_desktop_channel_probe(tmp_path, content):
|
||||
config.write_bytes(content.encode() if isinstance(content, str) else content)
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "hermes_cli.source_releases", "--install-root", str(root)],
|
||||
[sys.executable, "-m", "hermes_cli.source_check", "--install-root", str(root), "--home", str(home)],
|
||||
cwd=root, env={**os.environ, "HERMES_HOME": str(home), "HERMES_IGNORE_USER_CONFIG": "0"},
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
assert result.returncode != 0, result.stdout + result.stderr
|
||||
assert '"channel": "main"' not in result.stdout
|
||||
assert "invalid" in result.stderr
|
||||
assert "config" in result.stderr
|
||||
assert config.read_bytes() == (content.encode() if isinstance(content, str) else content)
|
||||
@@ -47,7 +47,7 @@ def _run_count_block(*, shallow: bool, raw_count: str, api_count):
|
||||
with patch.object(update_cmd, "subprocess") as sub:
|
||||
sub.run = MagicMock(side_effect=fake)
|
||||
sub.CalledProcessError = real_subprocess.CalledProcessError
|
||||
with patch("hermes_cli.banner._github_compare_behind", return_value=api_count):
|
||||
with patch("hermes_cli.source_check._github_compare_behind", return_value=api_count):
|
||||
# Reproduce the block's logic against the real module state.
|
||||
git_cmd = ["git"]
|
||||
result = sub.run(
|
||||
@@ -63,7 +63,7 @@ def _run_count_block(*, shallow: bool, raw_count: str, api_count):
|
||||
== "true"
|
||||
)
|
||||
if commit_count > 0 and apply_is_shallow:
|
||||
from hermes_cli.banner import _github_compare_behind
|
||||
from hermes_cli.source_check import _github_compare_behind
|
||||
|
||||
head_sha = sub.run(git_cmd + ["rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
|
||||
target_sha = sub.run(
|
||||
@@ -109,7 +109,7 @@ def test_shallow_local_ahead_treated_as_up_to_date():
|
||||
|
||||
|
||||
def test_shallow_zero_count_short_circuits_without_api():
|
||||
with patch("hermes_cli.banner._github_compare_behind") as api:
|
||||
with patch("hermes_cli.source_check._github_compare_behind") as api:
|
||||
got = _run_count_block(shallow=True, raw_count="0", api_count=None)
|
||||
# The block only consults the API when count > 0; a 0 count is trustworthy
|
||||
# (HEAD == origin tip counts 0 even on shallow graphs).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Behind-count recovery via the GitHub compare API (banner.py).
|
||||
"""Behind-count recovery via the GitHub compare API (source_check.py).
|
||||
|
||||
The class of bug: any code path that knows two tip SHAs but has no local
|
||||
history to count across (shallow installer clones, ls-remote-only probes)
|
||||
@@ -12,28 +12,22 @@ indicator said 1). The fix has two halves:
|
||||
the full graph regardless of local clone depth.
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
import hermes_cli.banner as banner
|
||||
import hermes_cli.source_check as source_check
|
||||
|
||||
SHA_A = "a" * 40
|
||||
SHA_B = "b" * 40
|
||||
|
||||
|
||||
def _compare_payload(ahead):
|
||||
return io.BytesIO(json.dumps({"ahead_by": ahead, "status": "ahead"}).encode())
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload: bytes):
|
||||
self._payload = payload
|
||||
|
||||
def read(self):
|
||||
def read(self, limit=None):
|
||||
return self._payload
|
||||
|
||||
def __enter__(self):
|
||||
@@ -44,20 +38,12 @@ class _FakeResponse:
|
||||
|
||||
|
||||
def _patch_urlopen(payload):
|
||||
banner._compare_payload_cache.clear()
|
||||
return patch(
|
||||
"urllib.request.urlopen",
|
||||
return_value=_FakeResponse(json.dumps(payload).encode()),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_compare_cache():
|
||||
banner._compare_payload_cache.clear()
|
||||
yield
|
||||
banner._compare_payload_cache.clear()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _github_compare_behind
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -65,25 +51,25 @@ def _fresh_compare_cache():
|
||||
|
||||
def test_compare_behind_returns_ahead_by():
|
||||
with _patch_urlopen({"ahead_by": 61, "status": "ahead"}):
|
||||
assert banner._github_compare_behind(SHA_A, SHA_B) == 61
|
||||
assert source_check._github_compare_behind(SHA_A, SHA_B) == 61
|
||||
|
||||
|
||||
def test_compare_behind_zero_means_local_ahead():
|
||||
with _patch_urlopen({"ahead_by": 0, "status": "behind"}):
|
||||
assert banner._github_compare_behind(SHA_A, SHA_B) == 0
|
||||
assert source_check._github_compare_behind(SHA_A, SHA_B) == 0
|
||||
|
||||
|
||||
def test_compare_behind_rejects_short_shas_without_network():
|
||||
with patch("urllib.request.urlopen") as mock_open:
|
||||
assert banner._github_compare_behind("abc123", SHA_B) is None
|
||||
assert banner._github_compare_behind(SHA_A, "") is None
|
||||
assert banner._github_compare_behind(None, SHA_B) is None
|
||||
assert source_check._github_compare_behind("abc123", SHA_B) is None
|
||||
assert source_check._github_compare_behind(SHA_A, "") is None
|
||||
assert source_check._github_compare_behind(None, SHA_B) is None
|
||||
mock_open.assert_not_called()
|
||||
|
||||
|
||||
def test_compare_behind_network_failure_returns_none():
|
||||
with patch("urllib.request.urlopen", side_effect=OSError("offline")):
|
||||
assert banner._github_compare_behind(SHA_A, SHA_B) is None
|
||||
assert source_check._github_compare_behind(SHA_A, SHA_B) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -98,91 +84,4 @@ def test_compare_behind_network_failure_returns_none():
|
||||
)
|
||||
def test_compare_behind_rejects_malformed_payloads(payload):
|
||||
with _patch_urlopen(payload):
|
||||
assert banner._github_compare_behind(SHA_A, SHA_B) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _check_via_rev: sentinel replaced by exact count when compare API answers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _upstream_tip(sha):
|
||||
return patch.object(banner, "_github_branch_tip", return_value=sha)
|
||||
|
||||
|
||||
def test_check_via_rev_recovers_exact_count():
|
||||
with _upstream_tip(SHA_B), patch.object(banner, "_github_compare_behind", return_value=61) as compare:
|
||||
assert banner._check_via_rev(SHA_A) == 61
|
||||
compare.assert_called_once_with(SHA_A, SHA_B)
|
||||
|
||||
|
||||
def test_check_via_rev_falls_back_to_sentinel_offline():
|
||||
"""FAIL-BEFORE (class): this path returned a fabricated 1 via callers."""
|
||||
with _upstream_tip(SHA_B), patch.object(banner, "_github_compare_behind", return_value=None):
|
||||
assert banner._check_via_rev(SHA_A) == banner.UPDATE_AVAILABLE_NO_COUNT
|
||||
|
||||
|
||||
def test_check_via_rev_up_to_date_short_circuits_compare():
|
||||
with _upstream_tip(SHA_A), patch.object(banner, "_github_compare_behind") as compare:
|
||||
assert banner._check_via_rev(SHA_A) == 0
|
||||
compare.assert_not_called()
|
||||
|
||||
|
||||
def test_check_via_rev_local_ahead_reports_up_to_date():
|
||||
"""ahead_by == 0 with differing tips = local commits on top, not behind."""
|
||||
with _upstream_tip(SHA_B), patch.object(banner, "_github_compare_behind", return_value=0):
|
||||
assert banner._check_via_rev(SHA_A) == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _check_via_local_git: tips from the API, exact count via compare, no fetch
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _local_git(head_sha):
|
||||
def fake_run(cmd, **kwargs):
|
||||
if cmd[:4] == ["git", "remote", "get-url", "origin"]:
|
||||
return MagicMock(returncode=0, stdout="https://github.com/NousResearch/hermes-agent.git\n")
|
||||
if cmd[:3] == ["git", "rev-parse", "HEAD"]:
|
||||
return MagicMock(returncode=0, stdout=f"{head_sha}\n")
|
||||
if cmd[:3] == ["git", "merge-base", "--is-ancestor"]:
|
||||
return MagicMock(returncode=1, stdout="")
|
||||
raise AssertionError(f"unexpected git command: {cmd!r}")
|
||||
|
||||
return fake_run
|
||||
|
||||
|
||||
def test_local_checkout_recovers_exact_count(tmp_path):
|
||||
"""The #84591 shape: no local history across the tips (shallow clone), tips differ.
|
||||
|
||||
FAIL-BEFORE (class): reported UPDATE_AVAILABLE_NO_COUNT (or, further back,
|
||||
a fabricated 1) even though the compare API could count exactly.
|
||||
"""
|
||||
repo_dir = tmp_path / "hermes-agent"
|
||||
repo_dir.mkdir()
|
||||
|
||||
with patch("hermes_cli.banner.subprocess.run", side_effect=_local_git(SHA_A)), \
|
||||
patch.object(banner, "_github_branch_tip", return_value=SHA_B), \
|
||||
patch.object(banner, "_github_compare_behind", return_value=61):
|
||||
assert banner._check_via_local_git(repo_dir) == 61
|
||||
|
||||
|
||||
def test_local_checkout_offline_compare_keeps_honest_sentinel(tmp_path):
|
||||
repo_dir = tmp_path / "hermes-agent"
|
||||
repo_dir.mkdir()
|
||||
|
||||
with patch("hermes_cli.banner.subprocess.run", side_effect=_local_git(SHA_A)), \
|
||||
patch.object(banner, "_github_branch_tip", return_value=SHA_B), \
|
||||
patch.object(banner, "_github_compare_behind", return_value=None):
|
||||
assert banner._check_via_local_git(repo_dir) == banner.UPDATE_AVAILABLE_NO_COUNT
|
||||
|
||||
|
||||
def test_local_checkout_equal_tips_up_to_date_without_compare(tmp_path):
|
||||
repo_dir = tmp_path / "hermes-agent"
|
||||
repo_dir.mkdir()
|
||||
|
||||
with patch("hermes_cli.banner.subprocess.run", side_effect=_local_git(SHA_A)), \
|
||||
patch.object(banner, "_github_branch_tip", return_value=SHA_A), \
|
||||
patch.object(banner, "_github_compare_behind") as compare:
|
||||
assert banner._check_via_local_git(repo_dir) == 0
|
||||
compare.assert_not_called()
|
||||
assert source_check._github_compare_behind(SHA_A, SHA_B) is None
|
||||
@@ -1,101 +1,8 @@
|
||||
"""Tests for the update check mechanism in hermes_cli.banner.
|
||||
|
||||
Passive checks go through the GitHub REST API — never ``git fetch``. Every CLI, TUI and desktop
|
||||
start used to fetch; across the install base that was tens of millions of fetch requests a day
|
||||
and GitHub asked us to poll the API instead. These tests pin that contract plus the cache
|
||||
policy that keeps the API traffic to one request a day per install.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
import hermes_cli.banner as banner
|
||||
|
||||
SHA_A = "a" * 40
|
||||
SHA_B = "b" * 40
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def git_repo(tmp_path, monkeypatch):
|
||||
"""A fake checkout the update check resolves to, with git calls stubbed out."""
|
||||
repo_dir = tmp_path / "hermes-agent"
|
||||
repo_dir.mkdir()
|
||||
(repo_dir / ".git").mkdir()
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
monkeypatch.delenv("HERMES_REVISION", raising=False)
|
||||
monkeypatch.setattr(banner, "_resolve_repo_dir", lambda: repo_dir)
|
||||
monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda root: "git")
|
||||
monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: repo_dir)
|
||||
return repo_dir
|
||||
|
||||
|
||||
def _stub_git(monkeypatch, *, head=SHA_A, origin="https://github.com/NousResearch/hermes-agent.git"):
|
||||
calls = []
|
||||
|
||||
def fake_run(args, **kwargs):
|
||||
calls.append(list(args))
|
||||
sub = args[1]
|
||||
if sub == "rev-parse":
|
||||
return MagicMock(returncode=0, stdout=f"{head}\n")
|
||||
if sub == "remote":
|
||||
return MagicMock(returncode=0, stdout=f"{origin}\n")
|
||||
if sub == "merge-base":
|
||||
return MagicMock(returncode=1, stdout="")
|
||||
raise AssertionError(f"passive check must not run git {sub}: {args}")
|
||||
|
||||
monkeypatch.setattr(banner.subprocess, "run", fake_run)
|
||||
return calls
|
||||
|
||||
|
||||
def test_passive_check_uses_the_api_and_never_fetches(git_repo, monkeypatch):
|
||||
"""The whole point: no ``git fetch`` / ``ls-remote`` for a GitHub origin, exact count via compare."""
|
||||
calls = _stub_git(monkeypatch, head=SHA_A)
|
||||
tip = MagicMock(return_value=SHA_B)
|
||||
monkeypatch.setattr(banner, "_github_branch_tip", tip)
|
||||
monkeypatch.setattr(banner, "_github_compare_behind", lambda cur, tgt: 61)
|
||||
|
||||
assert banner.check_for_updates() == 61
|
||||
tip.assert_called_once_with("nousresearch/hermes-agent", "main")
|
||||
assert not any(c[1] in {"fetch", "ls-remote"} for c in calls)
|
||||
|
||||
cached = json.loads((git_repo.parent / ".update_check").read_text())
|
||||
assert (cached["head"], cached["target"], cached["behind"]) == (SHA_A, SHA_B, 61)
|
||||
|
||||
|
||||
def test_cache_is_daily_but_invalidated_when_head_moves(git_repo, monkeypatch):
|
||||
"""A fresh cache answers without any network; ``hermes update`` moving HEAD busts it at once;
|
||||
an inconclusive (None) result is retried after the shorter failure window, not never."""
|
||||
from hermes_cli import __version__
|
||||
|
||||
cache_file = git_repo.parent / ".update_check"
|
||||
_stub_git(monkeypatch, head=SHA_A)
|
||||
tip = MagicMock(return_value=None)
|
||||
monkeypatch.setattr(banner, "_github_branch_tip", tip)
|
||||
|
||||
def write_cache(*, ts, head, behind):
|
||||
cache_file.write_text(json.dumps(
|
||||
{"ts": ts, "behind": behind, "rev": None, "ver": __version__, "head": head}))
|
||||
|
||||
write_cache(ts=time.time() - banner._UPDATE_CHECK_CACHE_SECONDS + 60, head=SHA_A, behind=3)
|
||||
assert banner.check_for_updates() == 3
|
||||
tip.assert_not_called()
|
||||
|
||||
write_cache(ts=time.time(), head=SHA_B, behind=3) # cached for a different HEAD
|
||||
assert banner.check_for_updates() is None # API unreachable → inconclusive, re-asked
|
||||
tip.assert_called_once()
|
||||
|
||||
tip.reset_mock()
|
||||
write_cache(ts=time.time() - banner._UPDATE_CHECK_FAILURE_CACHE_SECONDS + 60, head=SHA_A, behind=None)
|
||||
assert banner.check_for_updates() is None
|
||||
tip.assert_not_called()
|
||||
|
||||
write_cache(ts=time.time() - banner._UPDATE_CHECK_FAILURE_CACHE_SECONDS - 1, head=SHA_A, behind=None)
|
||||
banner.check_for_updates()
|
||||
tip.assert_called_once()
|
||||
from hermes_cli import banner, source_check
|
||||
|
||||
|
||||
def test_prefetch_non_blocking():
|
||||
@@ -103,23 +10,9 @@ def test_prefetch_non_blocking():
|
||||
banner._update_result = None
|
||||
banner._update_check_done = threading.Event()
|
||||
|
||||
with patch.object(banner, "check_for_updates", return_value=5):
|
||||
with patch.object(source_check, "check_for_updates", return_value={"behind": 5}):
|
||||
start = time.monotonic()
|
||||
banner.prefetch_update_check()
|
||||
assert time.monotonic() - start < 1.0
|
||||
banner._update_check_done.wait(timeout=5)
|
||||
assert banner._update_result == 5
|
||||
|
||||
|
||||
def test_upstream_main_sha_ls_remote_fallback_disables_git_prompts(monkeypatch):
|
||||
"""When the API is unreachable the HTTPS ls-remote fallback must never inherit the terminal."""
|
||||
monkeypatch.setattr(banner, "_github_branch_tip", lambda slug, branch: None)
|
||||
completed = MagicMock(returncode=1, stdout="", stderr="auth required")
|
||||
run = MagicMock(return_value=completed)
|
||||
monkeypatch.setattr(banner.subprocess, "run", run)
|
||||
|
||||
assert banner._upstream_main_sha() is None
|
||||
kwargs = run.call_args.kwargs
|
||||
assert kwargs["stdin"] is banner.subprocess.DEVNULL
|
||||
assert kwargs["env"]["GIT_TERMINAL_PROMPT"] == "0"
|
||||
assert kwargs["env"]["GCM_INTERACTIVE"] == "Never"
|
||||
Reference in new issue
Block a user