Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): sync_freshness exempts read-only skill-pack catalogs (#6076)
garrytanf20c3872f66a
diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.mdindex ed4cf18042..d68aba978e 100644--- a/docs/architecture/key-files/shared-skills.md+++ b/docs/architecture/key-files/shared-skills.md@@ -6,7 +6,7 @@- `src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts` implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed. The adapter's leave treats a server `membership_inactive` (its own enrollment epoch was left or re-enrolled past) as remote cleanup complete (`remote_membership_reason: superseded`), so harness rotation converges; `gbrain bootstrap harness --refresh-skills` re-runs `join` to adopt the current epoch.- `src/core/harness/{shared-skills,native-router}.ts` connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.- `src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts` owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. `src/commands/migrations/shared-content.ts` integrates previews and recurring pending-stage reconciliation into the migration runner. The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), refuses at inventory a pack whose adoption would exceed `packFiles` (A-NEW-4), and accepts a post-inventory change only through `--accept-reviewed-inventory <source>=<inventoryDigest>` printed in the conflict reason (#5476).-- `src/core/shared-skills/{setup-source-policy,content-freshness}.ts` excludes external, connector, company and opted-out (`config.shared_skills=false`) sources from owned-root scaffolding and freshness exemptions. A completed content receipt must match the current brain, incarnation, source root and active owner binding. `src/commands/doctor/checks/canonical-content.ts` reports pending publication and recovery separately; it never invents an upstream sync timestamp.+- `src/core/shared-skills/{setup-source-policy,content-freshness}.ts` excludes external, connector, company and opted-out (`config.shared_skills=false`) sources from owned-root scaffolding and freshness exemptions. A completed content receipt must match the current brain, incarnation, source root and active owner binding. `src/commands/doctor/checks/canonical-content.ts` reports pending publication and recovery separately; it never invents an upstream sync timestamp. `src/core/shared-skills/adopted-packs.ts` names the sources holding an adopted pack (`source_routing_health` skips their zero-page warning) and, of those, the read-only catalogs (no commit, no `.git` when the checkout is readable) that `sync_freshness` exempts; a failing read exempts nothing and is a note.- `src/core/shared-skills/{source-opt-out,inventory-limits}.ts` and `src/commands/sources-shared-skills.ts` implement `gbrain sources shared-skills <id> on|off|status`: `off` writes `config.shared_skills=false`, `on` deletes it and releases a parked inventory, and every form reports the configured value and the effective policy mode with its reason. Trusted local only; a remote attempt gets `trusted_local_only` with a `host_admin` fix and a read-only verify. `inventorySkillpack` reads its file-count, total-byte, per-file and entry bounds from the capped `shared_skills.inventory.*` keys; confinement checks are fixed. An overflow (`payload_too_large`) parks the source in its per-source migration record, so the 0.53.0 orchestrator completes and later runs skip it until the bounds change, it opts out, or it is released. `src/commands/doctor/checks/shared-skills.ts` (`shared_skills_sources`) lists opted-out and parked sources. Operator recipe: `docs/guides/shared-brain-skills.md#choose-which-sources-adopt-shared-skills`.- `src/core/shared-skills/optimizer.ts` stages opt-in optimization outside canonical roots with the original grants, immutable approved closure and protected metadata. Publication rechecks authority and the original revision through the coordinator; provider evaluation cannot write canonical skill files directly.- `src/core/persistence/{import-mutations,import-prepare}.ts` routes managed Markdown, code and image import through prepared canonical publication. Source, input, target, owner and revision checks run before apply; derived content retains the source-scoped skill-path guard. `importManagedFiles` takes a batch (at most `IMPORT_BATCH_MAX_PAGES` files and `IMPORT_BATCH_MAX_BYTES`, cut by `nextImportBatch`): each file keeps its own durable intent (`op_checkpoints` `managed-file-import`, written and cleared in one statement per batch), request id, receipt and result; the new requests are admitted in one transaction (`page-batch.ts` `admitBatch`, with its connection-loss re-run and `write_outcome_unknown`) and carry one `intent.import_batch`, so the owner publishes them as independent groups. A file refused before admission settles only that file; a slug the batch already holds ends the batch there, and that file and the rest import after it, as they would one by one. GBRA-75 wave 7: the no-op screen (`unchangedManagedImport`) calls `prepareManagedImportMutation` with `screen: { snapshot }`, the snapshot it just read: the preparer then skips its first path check, the input re-normalization and the snapshot re-read, because the screen just made them, `validate` re-runs every path and byte check last and the no-op kernel re-checks the page revision; a skipped file reads its snapshot once. A canonical input reuses its input hash as the target hash. The plan and screen loops run inside `withScreeningPaths` (`screening-paths.ts`). The preparer imports with `coordinated: true`: publication proves the base revision under its page guard, and the apply reads the page once after its write for the read-back check, the projection target, the text seal and the receipt's postimage. Pinned by `test/persistence-import-batch.test.ts` (row-by-row state against one-by-one imports on PGLite and Postgres, resume, lost commit acknowledgment).diff --git a/docs/guides/shared-brain-skills.md b/docs/guides/shared-brain-skills.mdindex a2f45991cc..9ea326dce8 100644--- a/docs/guides/shared-brain-skills.md+++ b/docs/guides/shared-brain-skills.md@@ -56,7 +56,12 @@ canonical-owner binding.The source must have no Git sync commit, external repository, connector, orcompany-ingestion policy. Existing external roots and incomplete or mismatchedreceipts retain the ordinary never-synced/stale checks; managed persistence alone-does not exempt a source. No `last_sync_at` timestamp is fabricated. The separate+does not exempt a source. No `last_sync_at` timestamp is fabricated. A dedicated+skills source is the other exemption: a source holding an adopted skill pack+(live heads on its current incarnation) whose content is a read-only catalog, with+no Git commit recorded and, when doctor may read the checkout, no `.git` under+its root, counts as `read_only_pack_count` in `sync_freshness`. A git-backed pack+is still judged stale. The separate`canonical_content_writes` check reports queued publication and required recoveryfor these roots. Both checks classify ownership from database records; remotedoctor does not inspect or execute commands against stored filesystem paths.diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 8cb223362b..f16e74a374 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -31,6 +31,7 @@ import { persistenceEnabledForHealth } from '../../../core/persistence/ownershipimport { upstreamFreshness } from '../../../core/sync-upstream.ts';import type { Check } from '../../doctor.ts';import { isOwnedContentSchemaMissing, ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';+import { readOnlyCatalogPackSourceIds } from '../../../core/shared-skills/adopted-packs.ts';import { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';import { parseSourceConfig } from '../../../core/sources-load.ts';import { checkError } from '../check-fix.ts';@@ -1256,10 +1257,13 @@ export async function checkSyncFreshness(let ownedContent = new Set<string>();try { ownedContent = new Set((await ownedContentFreshness(engine)).map(source => source.sourceId)); }catch (error) { if (!isOwnedContentSchemaMissing(error)) throw error; }+ // #6076: an adopted read-only catalog pack (no commit history) has nothing to sync.+ const catalogPacks = await readOnlyCatalogPackSourceIds(engine, sources, localOnly);let writer_owned_count = 0;+ let read_only_pack_count = 0;// v0.41.27.0: D6 count math. Every source falls into// EXACTLY ONE bucket per iteration. Invariant pinned by unit test:- // unchanged_count + synced_recently_count + stale_count + writer_owned_count === sources.length+ // unchanged + synced_recently + stale + writer_owned + read_only_pack counts === sources.length// Stale subsumes warn + fail + never-synced + future-timestamp; we keep// hasWarnings/hasFailures for the existing return-status logic.let unchanged_count = 0;@@ -1312,6 +1316,7 @@ export async function checkSyncFreshness(let upstream_behind_count = 0;for (const source of sources) {if (ownedContent.has(source.id)) { writer_owned_count++; continue; }+ if (catalogPacks.ids.has(source.id)) { read_only_pack_count++; continue; }// Embed source.id in user-visible messages so `gbrain sync --source <id>`// matches what the user copy-pastes. Show display name in parens when set.const display = source.name && source.name !== source.id@@ -1474,12 +1479,14 @@ export async function checkSyncFreshness(// D6 invariant: every source incremented exactly one bucket.const details = { unchanged_count, synced_recently_count, stale_count, ...(writer_owned_count ? { writer_owned_count } : {}),+ ...(read_only_pack_count ? { read_only_pack_count } : {}), ...(catalogPacks.note ? { read_only_pack_note: catalogPacks.note } : {}),...(outcomes.length ? { code: outcomes[0]!.code, no_successful_sync: outcomes } : {}),...(upstream_unknown_count ? { upstream_unknown_count } : {}), ...(upstream_behind_count ? { upstream_behind_count } : {}) };// BUG 4: append in-progress context when any source is actively syncing.// Empty otherwise, so steady-state messages are byte-for-byte unchanged.const inProgressNote = (inProgress.length ? `. ${inProgress.join('; ')}` : '')- + (writer_owned_count ? `. ${writer_owned_count} writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status` : '');+ + (writer_owned_count ? `. ${writer_owned_count} writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status` : '')+ + (read_only_pack_count ? `. ${read_only_pack_count} read-only skill-pack source(s): no commits to sync` : '') + (catalogPacks.note ? `. ${catalogPacks.note}` : '');const remedy = issues.length > outcomes.length;const outcomeFix = outcomes.find(o => o.code === 'sync_no_successful_sync')?.fix ?? outcomes[0]?.fix;@@ -1503,7 +1510,8 @@ export async function checkSyncFreshness(name: 'sync_freshness', status: 'ok',message: `${writer_owned_count} writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status.`, details,};- const upstreamCount = sources.length - writer_owned_count;+ const upstreamCount = sources.length - writer_owned_count - read_only_pack_count;+ if (upstreamCount === 0) return { name: 'sync_freshness', status: 'ok', message: `No upstream-synced sources${inProgressNote}.`, details };// v0.41.27.0: D2 ok-message reshape. Three branches surface what the// git short-circuit actually did so operators understand "unchanged// since last sync" vs "synced recently".diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.tsindex d023c76271..4ed1e5d441 100644--- a/src/commands/doctor/checks/routing-federation.ts+++ b/src/commands/doctor/checks/routing-federation.ts@@ -9,6 +9,7 @@ import type { BrainEngine } from '../../../core/engine.ts';import { gbrainPath } from '../../../core/config.ts';import { embedBackfillWorkerSurface } from '../../../core/minions/embed-backfill-admission.ts';import { isMissingSchemaObject } from '../../../core/utils.ts';+import { adoptedSkillPackSourceIds } from '../../../core/shared-skills/adopted-packs.ts';import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../../../core/scope.ts';import type { Check } from '../../doctor.ts';@@ -85,30 +86,6 @@ export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Che}}-/**- * Non-default sources holding an adopted skill pack: a `shared_skill_packs`- * row for the source's current incarnation with at least one live- * (`NOT deleted`) `shared_skill_heads` row. A pack left behind by an earlier- * incarnation does not count. A schema without the shared-skills tables (or- * `sources.incarnation`) has no adopted packs.- */-async function adoptedSkillPackSourceIds(engine: BrainEngine): Promise<Set<string>> {- try {- const rows = await engine.executeRaw<{ id: string }>(- `SELECT s.id FROM sources s- WHERE s.id <> 'default' AND EXISTS (- SELECT 1 FROM shared_skill_packs p- JOIN shared_skill_heads h ON h.source_id = p.source_id AND h.source_incarnation = p.source_incarnation- AND h.pack_id = p.pack_id AND NOT h.deleted- WHERE p.source_id = s.id AND p.source_incarnation = s.incarnation)`,- );- return new Set(rows.map((r) => r.id));- } catch (e) {- if (isMissingSchemaObject(e, 'table', ['shared_skill_packs', 'shared_skill_heads']) || isMissingSchemaObject(e, 'column', 'incarnation')) return new Set();- throw e;- }-}-/*** v0.40 Federated Sync v2 (T12) — federation_health.*diff --git a/src/core/shared-skills/adopted-packs.ts b/src/core/shared-skills/adopted-packs.tsnew file mode 100644index 0000000000..f1704d4a90--- /dev/null+++ b/src/core/shared-skills/adopted-packs.ts@@ -0,0 +1,60 @@+/**+ * Sources holding an adopted skill pack (#6076), shared by doctor+ * `source_routing_health` (a skills source has no pages by design) and+ * `sync_freshness` (a read-only catalog pack has no commits to sync).+ */+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { isMissingSchemaObject } from '../utils.ts';++/**+ * Non-default sources holding an adopted skill pack: a `shared_skill_packs`+ * row for the source's current incarnation with at least one live+ * (`NOT deleted`) `shared_skill_heads` row. A pack left behind by an earlier+ * incarnation does not count. A schema without the shared-skills tables (or+ * `sources.incarnation`) has no adopted packs; any other error throws.+ */+export async function adoptedSkillPackSourceIds(engine: BrainEngine): Promise<Set<string>> {+ try {+ const rows = await engine.executeRaw<{ id: string }>(+ `SELECT s.id FROM sources s+ WHERE s.id <> 'default' AND EXISTS (+ SELECT 1 FROM shared_skill_packs p+ JOIN shared_skill_heads h ON h.source_id = p.source_id AND h.source_incarnation = p.source_incarnation+ AND h.pack_id = p.pack_id AND NOT h.deleted+ WHERE p.source_id = s.id AND p.source_incarnation = s.incarnation)`,+ );+ return new Set(rows.map((r) => r.id));+ } catch (e) {+ if (isMissingSchemaObject(e, 'table', ['shared_skill_packs', 'shared_skill_heads']) || isMissingSchemaObject(e, 'column', 'incarnation')) return new Set();+ throw e;+ }+}++/**+ * The adopted-pack sources whose content is a read-only catalog: no commit+ * history recorded (`last_commit` NULL) and, when the caller may read the local+ * checkout (`localOnly`), no `.git` under its root. A git-backed pack is not+ * one: its commits can move, so its freshness is still judged. Errors never+ * escape: the adopted-pack read failing exempts nothing and returns a `note`,+ * and a source whose checkout cannot be probed is judged normally.+ */+export async function readOnlyCatalogPackSourceIds(+ engine: BrainEngine,+ sources: ReadonlyArray<{ id: string; local_path: string | null; last_commit: string | null }>,+ localOnly: boolean,+): Promise<{ ids: Set<string>; note: string | null }> {+ let adopted: Set<string>;+ try { adopted = await adoptedSkillPackSourceIds(engine); }+ catch (e) { return { ids: new Set(), note: `read-only skill-pack exemption unavailable (${e instanceof Error ? e.message : String(e)}); those sources were judged as git sources` }; }+ const ids = new Set<string>();+ for (const source of sources) {+ if (!adopted.has(source.id) || source.last_commit) continue;+ try {+ if (localOnly && source.local_path && existsSync(join(source.local_path, '.git'))) continue;+ } catch { continue; }+ ids.add(source.id);+ }+ return { ids, note: null };+}diff --git a/test/doctor-sync-freshness-skill-pack-6076.test.ts b/test/doctor-sync-freshness-skill-pack-6076.test.tsnew file mode 100644index 0000000000..59457a4609--- /dev/null+++ b/test/doctor-sync-freshness-skill-pack-6076.test.ts@@ -0,0 +1,129 @@+/**+ * sync_freshness and read-only skill-pack sources (#6076, wave 18b 1.3).+ *+ * Protects: a source holding an adopted skill pack whose content is a+ * read-only catalog (no commit history: `last_commit` NULL, and no `.git`+ * under its root when doctor may read the checkout) is exempt from freshness,+ * next to writer-owned content, while a git-backed pack or a source with no+ * pack is still judged stale. A failing adopted-pack read exempts nothing and+ * leaves a note instead of failing the whole check.+ * Fails when: the exemption is dropped (the catalog fails freshness after 3+ * days) or widened (a git-backed pack hides staleness).+ * Seams: real PGLite (and Postgres through test/postgres-unit-arms.txt) with+ * the pack rows written directly (publication triggers suppressed), plus an+ * engine proxy whose adopted-pack read throws.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++async function withoutTriggers(engine: BrainEngine, run: (tx: BrainEngine) => Promise<void>): Promise<void> {+ await engine.transaction(async (tx) => {+ await tx.executeRaw('SET LOCAL session_replication_role = replica');+ await run(tx);+ });+}++const FIVE_DAYS_AGO = new Date(Date.now() - 5 * 24 * 3600_000);++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`${backend}: sync_freshness and read-only skill-pack sources (#6076)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl));+ }, 120_000);+ afterAll(async () => { await close(); });+ beforeEach(async () => {+ await withoutTriggers(engine, async (tx) => {+ await tx.executeRaw('DELETE FROM shared_skill_heads');+ await tx.executeRaw('DELETE FROM shared_skill_packs');+ await tx.executeRaw("DELETE FROM pages WHERE source_id <> 'default'");+ await tx.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ });+ });++ async function addSource(id: string, opts: { lastCommit?: string | null; localPath?: string } = {}): Promise<string> {+ const [row] = await engine.executeRaw<{ incarnation: string }>(+ `INSERT INTO sources (id, name, local_path, last_sync_at, last_commit, config)+ VALUES ($1, $1, $2, $3, $4, '{"federated":false}'::jsonb) RETURNING incarnation::text AS incarnation`,+ [id, opts.localPath ?? `/tmp/gbrain-test-${id}`, FIVE_DAYS_AGO, opts.lastCommit ?? null]);+ return row!.incarnation;+ }++ async function adoptPack(sourceId: string, incarnation: string): Promise<void> {+ await withoutTriggers(engine, async (tx) => {+ await tx.executeRaw(+ `INSERT INTO shared_skill_packs (source_id, source_incarnation, pack_id, revision, manifest, manifest_hash)+ VALUES ($1, $2::uuid, 'pack-example', $3::uuid, '{}'::jsonb, 'hash-example')`,+ [sourceId, incarnation, randomUUID()]);+ await tx.executeRaw(+ `INSERT INTO shared_skill_heads (source_id, source_incarnation, pack_id, name, revision, metadata, deleted, policy_epoch)+ VALUES ($1, $2::uuid, 'pack-example', 'example-skill', $3::uuid, '{}'::jsonb, false, 'epoch-example')`,+ [sourceId, incarnation, randomUUID()]);+ });+ }++ test('an adopted catalog pack synced 5 days ago is ok, counted as read-only', async () => {+ await adoptPack('shared-skills', await addSource('shared-skills'));+ const result = await checkSyncFreshness(engine);+ expect(result.status).toBe('ok');+ expect(result.details).toMatchObject({ read_only_pack_count: 1, stale_count: 0 });+ expect(result.message).toContain('1 read-only skill-pack source(s): no commits to sync');+ });++ test('a git-backed pack (commit history) still reports staleness', async () => {+ await adoptPack('pack-git', await addSource('pack-git', { lastCommit: 'a'.repeat(40) }));+ const result = await checkSyncFreshness(engine);+ expect(result.status).toBe('fail');+ expect(result.message).toContain("Source 'pack-git' last synced 5d ago");+ expect(result.details?.read_only_pack_count).toBeUndefined();+ });++ test('a pack root that is a Git checkout is judged when doctor may read it (localOnly)', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-pack-git-'));+ mkdirSync(join(root, '.git'));+ await adoptPack('pack-root', await addSource('pack-root', { localPath: root }));+ const result = await checkSyncFreshness(engine, { localOnly: true });+ expect(result.status).toBe('fail');+ expect(result.message).toContain("Source 'pack-root' last synced 5d ago");+ });++ test('a source with no pack and no commits is still stale', async () => {+ await adoptPack('shared-skills', await addSource('shared-skills'));+ await addSource('plain');+ const result = await checkSyncFreshness(engine);+ expect(result.status).toBe('fail');+ expect(result.message).toContain("Source 'plain' last synced 5d ago");+ expect(result.details).toMatchObject({ read_only_pack_count: 1, stale_count: 1 });+ });++ test('a failing adopted-pack read exempts nothing and is a note, not a check error', async () => {+ await adoptPack('shared-skills', await addSource('shared-skills'));+ const failing = new Proxy(engine, {+ get(target, prop, receiver) {+ const value = Reflect.get(target, prop, receiver);+ if (prop !== 'executeRaw') return typeof value === 'function' ? value.bind(target) : value;+ return async (sql: string, params?: unknown[]) => {+ if (sql.includes('FROM shared_skill_packs')) throw Object.assign(new Error('permission denied for table shared_skill_packs'), { code: '42501' });+ return (value as BrainEngine['executeRaw']).call(target, sql, params);+ };+ },+ }) as BrainEngine;+ const result = await checkSyncFreshness(failing);+ expect(result.status).toBe('fail');+ expect(result.message).toContain("Source 'shared-skills' last synced 5d ago");+ expect(result.message).toContain('read-only skill-pack exemption unavailable (permission denied for table shared_skill_packs)');+ expect(result.details?.read_only_pack_note).toContain('permission denied');+ });+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 453df02aff..b3cd2b5ad1 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -32,6 +32,7 @@ test/doctor-frontmatter-holds.test.tstest/doctor-image-embedding-coverage.test.tstest/doctor-keyword-plan-6495.test.tstest/doctor-routing-skill-pack-source.test.ts+test/doctor-sync-freshness-skill-pack-6076.test.tstest/embed-stale-images-managed-6529.test.tstest/embedding-completion-atomic.serial.test.tstest/engine-sql-facts-keyset.test.ts