fix(skills): trust the updater's lock when a run installs content newer than the bundle (#11220)

skills update installs source-repo HEAD, which routinely runs ahead of the
revisions a shipped build bundles. The post-run re-scan hashed that content
'unrecognized' (the registry has never seen it) and the verdict counted it as
a failure — so a clean update reported "The update didn't finish / Updated 0
of N", and Retry repeated the false failure forever because the CLI now
no-ops (lock == source). The 'newer-known' escape hatch never fires: the
generator always points the manifest at the registry's newest snapshot, so no
observed content can hash to a revision newer than the bundle.

The verdict now computes the git tree sha of the observed bytes (a port of
the generator's hashing, verified byte-for-byte against git write-tree and
against every shipped skill's manifest gitTreeSha) and accepts an
unrecognized placement when that sha equals the lock's skillFolderHash: the
lock is the CLI's own record of what it installed, so disk matching lock
means the command did its job — the bundled registry simply has not seen
that revision yet.

Half-written bundles (sha mismatch), unreadable copies, removed skills,
degraded aliases, and outdated copies at the lock hash all still fail.
This commit is contained in:
Brennan Benson
2026-07-28 14:37:31 -07:00
committed by GitHub
parent 2b88931b93
commit a81f17c189
8 changed files with 383 additions and 29 deletions
+8 -2
View File
@@ -13,6 +13,7 @@ import type {
import { inventorySkillFreshness } from '../skills/skill-freshness-inventory'
import { SkillUpdateRunner } from '../skills/skill-update-run'
import { skillUpdateFailedNames } from '../skills/skill-update-outcome'
import { readGloballyUpdatableSkillLocks } from '../skills/skill-update-registration'
import {
discoverSkillsOnTarget,
resolveSkillDiscoveryTarget
@@ -31,8 +32,13 @@ export function registerSkillsHandlers(store: Store): void {
// Why: per-skill outcomes come from re-hashing what is actually on disk, not
// from scraping stdout.
rescanOutdatedNames: async (names) => {
const inventory = await scanInventory()
return skillUpdateFailedNames(names, inventory.installations)
// The lock read is fresh on purpose: the run just rewrote it, and the
// verdict accepts unrecognized content only when disk matches that record.
const [inventory, globalSkillLocks] = await Promise.all([
scanInventory(),
readGloballyUpdatableSkillLocks()
])
return skillUpdateFailedNames(names, inventory.installations, globalSkillLocks)
},
onState: (run: SkillUpdateRun) => {
for (const window of BrowserWindow.getAllWindows()) {
@@ -88,7 +88,8 @@ export async function observeSkillFreshnessInstallation(args: {
status: 'inaccessible',
installedReleaseRevision: null,
installedAppVersion: null,
observedPackageDigest: null
observedPackageDigest: null,
observedGitTreeSha: null
}
}
@@ -115,7 +116,8 @@ export async function observeSkillFreshnessInstallation(args: {
: (args.artifacts.releasedAppVersions[args.current.name]?.[snapshot.releaseRevision] ??
null)
: null,
observedPackageDigest: observed.observedDigest
observedPackageDigest: observed.observedDigest,
observedGitTreeSha: observed.observedGitTreeSha
}
} catch (error) {
return {
@@ -124,6 +126,7 @@ export async function observeSkillFreshnessInstallation(args: {
installedReleaseRevision: null,
installedAppVersion: null,
observedPackageDigest: null,
observedGitTreeSha: null,
errorCategory: errorCategory(error, 'skill-package-read-failed')
}
}
@@ -0,0 +1,69 @@
import { execFileSync } from 'node:child_process'
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { devNull, tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import type { SkillBundleManifest } from '../../shared/skill-freshness'
import { observeSkillPackage } from './skill-package-identity'
const REPO_ROOT = resolve(__dirname, '..', '..', '..')
const temporaryDirectories: string[] = []
afterEach(async () => {
await Promise.all(
temporaryDirectories.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
)
})
describe('observed skill git tree identity', () => {
// The decisive check: the runtime port must reproduce the generator's tree
// sha bit-for-bit, or the lock comparison never matches and the verdict fix
// is a silent no-op. The manifest's gitTreeSha values are generated from
// these same working-tree bytes.
it('matches the gitTreeSha the bundled manifest records for every shipped skill', async () => {
const manifest = JSON.parse(
await readFile(join(REPO_ROOT, 'resources', 'skills', 'current-manifest.json'), 'utf8')
) as SkillBundleManifest
expect(manifest.skills.length).toBeGreaterThan(0)
for (const skill of manifest.skills) {
const observed = await observeSkillPackage(join(REPO_ROOT, 'skills', skill.name))
expect(observed.observedGitTreeSha, skill.name).toBe(skill.gitTreeSha)
}
})
// Shipped skills are flat today, so this covers what they do not: nested
// directories, an executable, binary bytes, and the `z.txt` vs `z/` edge where
// git's slash-append ordering diverges from a plain name sort.
it('matches git write-tree over nesting, executables and the directory sort edge', async () => {
const base = await mkdtemp(join(tmpdir(), 'orca-skill-tree-sha-'))
temporaryDirectories.push(base)
const work = join(base, 'work')
const repoShell = join(base, 'repo')
await mkdir(join(work, 'z'), { recursive: true })
await mkdir(join(work, 'nested', 'deep'), { recursive: true })
await mkdir(repoShell, { recursive: true })
await writeFile(join(work, 'SKILL.md'), '---\nname: fixture\n---\n')
await writeFile(join(work, 'z.txt'), 'sorts before the z directory\n')
await writeFile(join(work, 'z', 'inner.md'), 'directory entry\n')
await writeFile(join(work, 'nested', 'deep', 'tool.sh'), '#!/bin/sh\nexit 0\n')
await chmod(join(work, 'nested', 'deep', 'tool.sh'), 0o755)
await writeFile(join(work, 'blob.bin'), Buffer.from([0, 1, 2, 253, 254, 255]))
const env = { ...process.env, GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_SYSTEM: devNull }
execFileSync('git', ['init', '--quiet', repoShell], { env })
const gitDirArgs = ['--git-dir', join(repoShell, '.git'), '--work-tree', work]
execFileSync('git', [...gitDirArgs, '-c', 'core.autocrlf=false', 'add', '-A'], {
env,
cwd: work
})
const expected = execFileSync('git', [...gitDirArgs, 'write-tree'], {
env,
cwd: work,
encoding: 'utf8'
}).trim()
const observed = await observeSkillPackage(work)
expect(observed.observedGitTreeSha).toBe(expected)
})
})
@@ -0,0 +1,82 @@
import { createHash } from 'node:crypto'
/**
* Git object identity for an observed skill package.
*
* The updater's lock records the git tree sha of the skill folder it installed,
* so hashing the observed bytes the same way lets the post-run verdict recognise
* content the bundled registry has never seen. The algorithm is a port of
* `gitTreeSha` in config/scripts/generate-skill-bundle-manifest.mjs and must
* match it exactly — a near-miss never matches anything and silently disables
* the verdict's lock check.
*
* Hashes are over RAW bytes deliberately: a CRLF materialization (Windows
* checkout) hashes differently from the source tree, so it fails closed to the
* pre-lock-check behavior rather than misidentifying content.
*/
export type SkillGitTreeFileEntry = {
/** Slash-separated path relative to the package root. */
path: string
executable: boolean
blobSha: Buffer
}
type SkillGitTreeDirectory = {
directories: Map<string, SkillGitTreeDirectory>
files: { filename: string; executable: boolean; blobSha: Buffer }[]
}
function gitObjectSha(kind: 'blob' | 'tree', bytes: Buffer): Buffer {
return createHash('sha1').update(`${kind} ${bytes.length}\0`).update(bytes).digest()
}
export function gitBlobSha(bytes: Buffer): Buffer {
return gitObjectSha('blob', bytes)
}
export function skillPackageGitTreeSha(entries: readonly SkillGitTreeFileEntry[]): string {
const root: SkillGitTreeDirectory = { directories: new Map(), files: [] }
for (const entry of entries) {
const parts = entry.path.split('/')
const filename = parts.pop() as string
let directory = root
for (const part of parts) {
let child = directory.directories.get(part)
if (!child) {
child = { directories: new Map(), files: [] }
directory.directories.set(part, child)
}
directory = child
}
directory.files.push({ filename, executable: entry.executable, blobSha: entry.blobSha })
}
function hashDirectory(directory: SkillGitTreeDirectory): Buffer {
const children = [
...[...directory.directories].map(([name, child]) => ({
mode: '40000',
name,
hash: hashDirectory(child)
})),
...directory.files.map((file) => ({
mode: file.executable ? '100755' : '100644',
name: file.filename,
hash: file.blobSha
}))
].sort((left, right) => {
// Git orders tree entries as raw bytes with directory names read as `name/`.
const leftName = left.mode === '40000' ? `${left.name}/` : left.name
const rightName = right.mode === '40000' ? `${right.name}/` : right.name
return Buffer.from(leftName).compare(Buffer.from(rightName))
})
const body = Buffer.concat(
children.map(({ mode, name, hash }) =>
Buffer.concat([Buffer.from(`${mode} ${name}\0`, 'utf8'), hash])
)
)
return gitObjectSha('tree', body)
}
return hashDirectory(root).toString('hex')
}
+16 -2
View File
@@ -3,12 +3,19 @@ import type { Dirent } from 'node:fs'
import { lstat, open, opendir } from 'node:fs/promises'
import { isAbsolute, join, relative, sep } from 'node:path'
import type { SkillBundleFileIdentity, SkillKnownSnapshot } from '../../shared/skill-freshness'
import {
gitBlobSha,
skillPackageGitTreeSha,
type SkillGitTreeFileEntry
} from './skill-git-tree-identity'
type ObservedSkillFile = SkillBundleFileIdentity
export type ObservedSkillPackage = {
files: ObservedSkillFile[]
observedDigest: string
/** Git tree sha of the raw bytes — comparable against the updater lock's skillFolderHash. */
observedGitTreeSha: string
}
export const SKILL_PACKAGE_OBSERVATION_LIMITS = {
@@ -136,6 +143,7 @@ export async function observeSkillPackage(
limits: SkillPackageObservationLimits = SKILL_PACKAGE_OBSERVATION_LIMITS
): Promise<ObservedSkillPackage> {
const files: ObservedSkillFile[] = []
const treeEntries: SkillGitTreeFileEntry[] = []
const caseFoldedPaths = new Map<string, string>()
let entryCount = 0
let totalBytes = 0
@@ -197,7 +205,9 @@ export async function observeSkillPackage(
limits.maximumSingleFileBytes
)
totalBytes += bytes.length
files.push(describeObservedSkillFile(manifestPath, bytes, (fileStat.mode & 0o111) !== 0))
const executable = (fileStat.mode & 0o111) !== 0
files.push(describeObservedSkillFile(manifestPath, bytes, executable))
treeEntries.push({ path: manifestPath, executable, blobSha: gitBlobSha(bytes) })
} else {
throw new Error('skill-package-special-file')
}
@@ -205,7 +215,11 @@ export async function observeSkillPackage(
}
await visit(packageRoot, 0)
return { files, observedDigest: skillPackageDigest(files) }
return {
files,
observedDigest: skillPackageDigest(files),
observedGitTreeSha: skillPackageGitTreeSha(treeEntries)
}
}
export function matchingKnownSnapshot(
+173 -17
View File
@@ -1,15 +1,24 @@
import { describe, expect, it } from 'vitest'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import type {
SkillFreshnessInstallation,
SkillFreshnessStatus,
SkillInstallationTopology
} from '../../shared/skill-freshness'
import { inventorySkillFreshness } from './skill-freshness-inventory'
import { observeSkillPackage } from './skill-package-identity'
import { readGloballyUpdatableSkillLocks } from './skill-update-registration'
import { skillUpdateFailedNames } from './skill-update-outcome'
const noLocks = new Map<string, string>()
function placement(
name: string,
status: SkillFreshnessStatus,
topology: SkillInstallationTopology = 'canonical-copy'
topology: SkillInstallationTopology = 'canonical-copy',
observedGitTreeSha: string | null = null
): SkillFreshnessInstallation {
return {
id: `${name}-${topology}-${status}`,
@@ -29,49 +38,55 @@ function placement(
currentPackageDigest: 'current',
currentAppVersion: '2.0.0',
observedPackageDigest: 'current',
observedGitTreeSha,
errorCategory: null
}
}
describe('skillUpdateFailedNames', () => {
it('treats a convergent copy that is now current as landed', () => {
expect(skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'current')])).toEqual([])
expect(
skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'current')], noLocks)
).toEqual([])
})
it('reports a copy the run left outdated', () => {
expect(skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'outdated')])).toEqual([
'orca-cli'
])
expect(
skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'outdated')], noLocks)
).toEqual(['orca-cli'])
})
it('reports a half-written bundle instead of reading it as success', () => {
// The old "still eligible?" test passed here: an unrecognized copy is not
// eligible either, so a corrupt write looked identical to a clean update.
expect(skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'unrecognized')])).toEqual([
'orca-cli'
])
expect(
skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'unrecognized')], noLocks)
).toEqual(['orca-cli'])
})
it('reports an unreadable copy', () => {
expect(skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'inaccessible')])).toEqual([
'orca-cli'
])
expect(
skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'inaccessible')], noLocks)
).toEqual(['orca-cli'])
})
it('reports a skill the run removed outright', () => {
expect(skillUpdateFailedNames(['orca-cli'], [])).toEqual(['orca-cli'])
expect(skillUpdateFailedNames(['orca-cli'], [], noLocks)).toEqual(['orca-cli'])
})
it('accepts a revision newer than this build ships', () => {
// The CLI pulls from the source repo, which runs ahead of the bundled manifest.
expect(skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'newer-known')])).toEqual([])
expect(
skillUpdateFailedNames(['orca-cli'], [placement('orca-cli', 'newer-known')], noLocks)
).toEqual([])
})
it('ignores placements the update command never writes to', () => {
expect(
skillUpdateFailedNames(
['orca-cli'],
[placement('orca-cli', 'current'), placement('orca-cli', 'outdated', 'plugin-cache')]
[placement('orca-cli', 'current'), placement('orca-cli', 'outdated', 'plugin-cache')],
noLocks
)
).toEqual([])
})
@@ -80,7 +95,8 @@ describe('skillUpdateFailedNames', () => {
expect(
skillUpdateFailedNames(
['orca-cli'],
[placement('orca-cli', 'current'), placement('orca-cli', 'outdated', 'provider-alias')]
[placement('orca-cli', 'current'), placement('orca-cli', 'outdated', 'provider-alias')],
noLocks
)
).toEqual(['orca-cli'])
})
@@ -89,8 +105,148 @@ describe('skillUpdateFailedNames', () => {
expect(
skillUpdateFailedNames(
['orca-cli', 'orchestration'],
[placement('orca-cli', 'current'), placement('orchestration', 'outdated')]
[placement('orca-cli', 'current'), placement('orchestration', 'outdated')],
noLocks
)
).toEqual(['orchestration'])
})
it('treats unrecognized content whose tree sha matches the lock as landed', () => {
// Source-repo HEAD routinely runs ahead of the bundled registry; the lock is
// the CLI's own record of what it wrote.
expect(
skillUpdateFailedNames(
['orca-cli'],
[placement('orca-cli', 'unrecognized', 'canonical-copy', 'ahead-of-bundle')],
new Map([['orca-cli', 'ahead-of-bundle']])
)
).toEqual([])
})
it('still reports unrecognized content whose bytes do not match the lock', () => {
expect(
skillUpdateFailedNames(
['orca-cli'],
[placement('orca-cli', 'unrecognized', 'canonical-copy', 'half-written-bytes')],
new Map([['orca-cli', 'ahead-of-bundle']])
)
).toEqual(['orca-cli'])
})
it('still reports unrecognized content when the skill has no lock entry', () => {
expect(
skillUpdateFailedNames(
['orca-cli'],
[placement('orca-cli', 'unrecognized', 'canonical-copy', 'ahead-of-bundle')],
noLocks
)
).toEqual(['orca-cli'])
})
it('never forgives an outdated copy, even at the lock hash', () => {
// Lock == disk on an outdated copy means the command provably wrote nothing.
expect(
skillUpdateFailedNames(
['orca-cli'],
[placement('orca-cli', 'outdated', 'canonical-copy', 'locked-revision')],
new Map([['orca-cli', 'locked-revision']])
)
).toEqual(['orca-cli'])
})
it('does not let a lock-matching canonical copy excuse a degraded alias', () => {
expect(
skillUpdateFailedNames(
['orca-cli'],
[
placement('orca-cli', 'unrecognized', 'canonical-copy', 'ahead-of-bundle'),
placement('orca-cli', 'inaccessible', 'provider-alias')
],
new Map([['orca-cli', 'ahead-of-bundle']])
)
).toEqual(['orca-cli'])
})
})
describe('skillUpdateFailedNames over a real inventory', () => {
const repoRoot = resolve(__dirname, '..', '..', '..')
const temporaryDirectories: string[] = []
afterEach(async () => {
await Promise.all(
temporaryDirectories.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
)
})
async function postCutFixture(): Promise<{ homeDir: string; installedTreeSha: string }> {
const root = await mkdtemp(join(tmpdir(), 'orca-skill-outcome-'))
temporaryDirectories.push(root)
const homeDir = join(root, 'home')
const skillDir = join(homeDir, '.agents', 'skills', 'orca-cli')
await mkdir(skillDir, { recursive: true })
// Current bytes plus one upstream edit: content no snapshot in this build's
// registry has ever seen, exactly what `skills update` installs after the
// source repo moves past the release cut.
const current = await readFile(join(repoRoot, 'skills', 'orca-cli', 'SKILL.md'))
await writeFile(
join(skillDir, 'SKILL.md'),
Buffer.concat([current, Buffer.from('\nUpstream edit published after this build.\n')])
)
return { homeDir, installedTreeSha: (await observeSkillPackage(skillDir)).observedGitTreeSha }
}
async function writeLock(homeDir: string, skillFolderHash: string): Promise<void> {
await writeFile(
join(homeDir, '.agents', '.skill-lock.json'),
JSON.stringify({
version: 3,
skills: {
'orca-cli': {
skillFolderHash,
skillPath: 'skills/orca-cli',
source: 'github.com/stablyai/orca'
}
}
})
)
}
it('accepts post-cut source content when the lock records exactly those bytes', async () => {
const { homeDir, installedTreeSha } = await postCutFixture()
await writeLock(homeDir, installedTreeSha)
const inventory = await inventorySkillFreshness({
currentAppVersion: 'test',
homeDir,
resourceRoot: join(repoRoot, 'resources'),
repos: []
})
const locks = await readGloballyUpdatableSkillLocks({ homeDir })
// Guard the premise: this is the unrecognized path, not an accidental match.
const canonical = inventory.installations.filter(
(entry) => entry.name === 'orca-cli' && entry.topology === 'canonical-copy'
)
expect(canonical).toHaveLength(1)
expect(canonical[0].status).toBe('unrecognized')
expect(skillUpdateFailedNames(['orca-cli'], inventory.installations, locks)).toEqual([])
})
it('keeps failing the same content when the lock names different bytes', async () => {
const { homeDir } = await postCutFixture()
await writeLock(homeDir, 'f'.repeat(40))
const inventory = await inventorySkillFreshness({
currentAppVersion: 'test',
homeDir,
resourceRoot: join(repoRoot, 'resources'),
repos: []
})
const locks = await readGloballyUpdatableSkillLocks({ homeDir })
expect(skillUpdateFailedNames(['orca-cli'], inventory.installations, locks)).toEqual([
'orca-cli'
])
})
})
+28 -6
View File
@@ -11,8 +11,9 @@ import {
* `unrecognized`, a failed write can leave the directory unreadable, and a
* removed skill has no convergent placement at all — each would read as
* "updated" and show a green check over a broken skill. So demand a positive
* signal instead: every placement the command writes to has to come back as a
* revision we recognise.
* signal instead: every placement the command writes to has to come back as
* either a revision we recognise or the exact bytes the updater's lock says it
* installed.
*
* Known limit: the topology filter runs before the status check, so a placement
* that degrades OUT of the convergent set is dropped from the judgment rather
@@ -23,17 +24,38 @@ import {
*/
export function skillUpdateFailedNames(
names: readonly string[],
installations: readonly SkillFreshnessInstallation[]
installations: readonly SkillFreshnessInstallation[],
globalSkillLocks: ReadonlyMap<string, string>
): string[] {
return names.filter((name) => {
const lockHash = globalSkillLocks.get(name)
const convergent = installations.filter(
(entry) => entry.name === name && SUPPORTED_GLOBAL_SKILL_TOPOLOGIES.has(entry.topology)
)
if (convergent.length === 0) {
return true
}
// `newer-known` counts as landed: the CLI pulls from the source repo, which
// can be ahead of the revision this build ships in its manifest.
return convergent.some((entry) => entry.status !== 'current' && entry.status !== 'newer-known')
return convergent.some((entry) => !skillPlacementLanded(entry, lockHash))
})
}
function skillPlacementLanded(
entry: SkillFreshnessInstallation,
lockHash: string | undefined
): boolean {
if (entry.status === 'current' || entry.status === 'newer-known') {
return true
}
// Why: the CLI installs source-repo HEAD, which runs ahead of the revisions this
// build bundles, so a clean update routinely hashes `unrecognized`. The lock is
// the CLI's own record of what it installed — disk matching lock means the
// command did its job and the bundled registry simply has not seen that revision
// yet. Everything else unrecognized (half-written, no lock entry, mismatch)
// still fails, and `outdated` is never forgiven: lock == disk there means the
// command provably wrote nothing.
return (
entry.status === 'unrecognized' &&
lockHash !== undefined &&
entry.observedGitTreeSha === lockHash
)
}
+2
View File
@@ -81,6 +81,8 @@ export type SkillFreshnessInstallation = {
currentPackageDigest: string
currentAppVersion: string
observedPackageDigest: string | null
/** Git tree sha of the observed bytes; lets the post-run verdict match disk against the updater's lock. */
observedGitTreeSha?: string | null
errorCategory: string | null
}