Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): one unbuildable page no longer wedges v0.60.31 (GBRA-130 A-27)

garrytan4085a1dd3348
diff --git a/skills/migrations/v0.60.31.0.md b/skills/migrations/v0.60.31.0.md
index 93f8a5c690..1b5decdc4b 100644
--- a/skills/migrations/v0.60.31.0.md
+++ b/skills/migrations/v0.60.31.0.md
@@ -35,6 +35,11 @@ add an allowlist entry on the user's behalf without asking.
`credential_projection_pending`. When it is ok, every page is searchable
again. If it names code pages without a recorded source path, they stay
withheld until their source is synced again: `gbrain sync --source <id>`.
+ If it says some pages failed their re-chunk and are held, the migration
+ completed without them and they stay withheld. `gbrain doctor --only
+ text_projection_readiness` lists each with its error code; preview the
+ retry with `gbrain repair safe-chunks --source <id>` and apply the
+ command it prints (no provider calls).
3. **Ask before embedding the new chunks.** Re-chunked pages have no vectors
until they are embedded, so keyword search finds them and vector search
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 3128a29ccc..9163578242 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -165,7 +165,7 @@
"migrations/v0.60.28.0.md": "f7fa936066fb188f6f3f54bb6c720f57743792e4371d0b98dd3cb5a57d1bd9c9",
"migrations/v0.60.284.0.md": "f42776fd15f0b8da1132646d671b45e110289e75261b44841f788775d1028ec9",
"migrations/v0.60.30.0.md": "2dd24bb319cad80ae15c52fb163c704fc3adfc1182d44ab563f636f07434a9e0",
- "migrations/v0.60.31.0.md": "fb8c0a98451a6f7826413ee7463421612511986252f6b803d91a26da94d378bf",
+ "migrations/v0.60.31.0.md": "0c3f3790ac9d86e4ab7c2373eea7e929ba98800e404191ba2c5bbc1480b6e8ca",
"migrations/v0.60.36.0.md": "8ce9aba221d24dec7f354b41c04d59fcbe947e9302a038e87e0ba807086c7ed7",
"migrations/v0.60.37.0.md": "e0e9d8ab0adb14cfb55d67f821614f25e0ab2f6281a1a1bfc10faefc95312015",
"migrations/v0.60.44.0.md": "415d05b4587e49c7bdad40b55878b0b50f5330915a5e49065638fb6680ced3fe",
diff --git a/src/commands/doctor/checks/credential-projection.ts b/src/commands/doctor/checks/credential-projection.ts
index 2f4c2b4194..9d02a3680a 100644
--- a/src/commands/doctor/checks/credential-projection.ts
+++ b/src/commands/doctor/checks/credential-projection.ts
@@ -2,22 +2,28 @@
* credential_projection_pending doctor check (security wave ENG-2): pages whose
* canonical body holds a private-key marker and whose chunks are withheld from
* every search path until the provider-free credential-safe re-chunk seals
- * them. Counts the pages the v0.60.31 migration can re-chunk and, separately,
- * code pages without a recorded source path that wait for their importer.
+ * them. Counts the pages the v0.60.31 migration can re-chunk, the ones it held
+ * after a failed re-chunk (retried by `gbrain repair safe-chunks`) and,
+ * separately, code pages without a recorded source path that wait for their
+ * importer.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { credentialProjectionPending } from '../../../core/page-state/credential-reseal.ts';
+import { credentialProjectionPending, readCredentialResealHolds } from '../../../core/page-state/credential-reseal.ts';
export async function credentialProjectionPendingCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
const name = 'credential_projection_pending';
try {
const { rebuildable, kept } = await credentialProjectionPending(engine, sourceIds);
- const details = { pages_pending: rebuildable, kept_pages: kept, count: 'exact', truncated: false };
+ // GBRA-130 A-27: pages whose re-chunk failed are held; the migration completed, so they are retried by repair safe-chunks.
+ const held = await readCredentialResealHolds(engine, sourceIds);
+ const details = { pages_pending: rebuildable, kept_pages: kept, ...(held.length ? { held_pages: held.length } : {}), count: 'exact', truncated: false };
const keptNote = kept ? ` ${kept} code page(s) without a recorded source path stay withheld until re-imported (gbrain sync --source <id>).` : '';
+ const heldNote = held.length ? ` ${held.length} of them failed their re-chunk and are held; retry with ${[...new Set(held.map(hold => `\`${hold.fix.argv!.join(' ')}\``))].join(', ')} `
+ + '(gbrain doctor --only text_projection_readiness lists them).' : '';
if (rebuildable === 0) return { name, status: kept ? 'warn' : 'ok', details, message: `No page waits for the credential-safe re-chunk.${keptNote}` };
return { name, status: 'warn', details, message: `${rebuildable} page(s) holding a private key are withheld from search until re-chunked without provider calls. `
- + `Run \`gbrain apply-migrations --yes --no-autopilot-install\`, then \`gbrain embed --stale\` when ready.${keptNote}` };
+ + `Run \`gbrain apply-migrations --yes --no-autopilot-install\`, then \`gbrain embed --stale\` when ready.${heldNote}${keptNote}` };
} catch (error) {
return { name, status: 'warn', message: `Credential-safe re-chunk state could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
details: { count: 'unknown', truncated: true, health: 'unknown' } };
diff --git a/src/commands/doctor/checks/projection-readiness.ts b/src/commands/doctor/checks/projection-readiness.ts
index 1691daa7db..26ef7db35f 100644
--- a/src/commands/doctor/checks/projection-readiness.ts
+++ b/src/commands/doctor/checks/projection-readiness.ts
@@ -6,6 +6,7 @@ import { projectionBacklog, type ProjectionBacklog } from '../../../core/page-st
import { projectionDrainLimit } from '../../../core/page-state/image-seal.ts';
import type { PersistenceProjectionStatus } from '../../../core/persistence/ipc.ts';
import { isMultimodalEnabled } from '../../../core/sync.ts';
+import { readCredentialResealHolds } from '../../../core/page-state/credential-reseal.ts';
import type { Check } from '../../doctor.ts';
import type { DoctorContext, DoctorEntry } from '../context.ts';
@@ -84,25 +85,33 @@ export async function checkProjectionReadiness(engine: BrainEngine, scope: PageR
WHERE deleted_at IS NULL AND body_storage='segmented' AND text_projection_revision IS DISTINCT FROM knowledge_revision`).catch(() => []))[0]?.n ?? 0) : 0;
const segmentedNote = segmented ? ` ${segmented} page(s) stored in segments are not searchable yet; ${opts.resident
? 'the resident builds them too.' : '`gbrain projections drain` builds them as well.'}` : '';
- const details = { readiness: readiness.status, ready: readiness.ready, ...classDetails(backlog), ...(segmented ? { segmented_pending: segmented } : {}) };
+ // GBRA-130 A-27: pages the v0.60.31 credential re-chunk held; remote callers get the count only.
+ const held = await readCredentialResealHolds(engine, scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined)).catch(() => []);
+ const details = { readiness: readiness.status, ready: readiness.ready, ...classDetails(backlog), ...(segmented ? { segmented_pending: segmented } : {}),
+ ...(held.length ? { credential_reseal_held: held.length, ...(opts.remote ? {} : { held_pages: held.slice(0, 20).map(hold => ({ source_id: hold.source_id, slug: hold.slug,
+ code: hold.code, attempts: hold.attempts, fix: hold.fix.argv })) }) } : {}) };
const work = backlog.pending + backlog.sealable + backlog.reimport;
- if (work === 0 && readiness.status !== 'projection_pending') {
+ if (work === 0 && readiness.status !== 'projection_pending' && !held.length) {
const byDesign = classSentences(backlog, false);
return byDesign.length
? { name: 'text_projection_readiness', status: 'ok', severity: 'info', fix_unavailable_reason: 'operator_judgement', details,
message: `No queued projection needs work. ${byDesign.join(' ')}` }
: { name: 'text_projection_readiness', status: 'ok', message: 'Visible text projections match their canonical revisions.', details };
}
- const text = backlog.pending || work === 0
+ const heldText = held.length ? `${held.length} page(s) holding a private key failed their credential-safe re-chunk and stay withheld from search${opts.remote ? '' : ` (${held.slice(0, 3)
+ .map(hold => `${hold.source_id}:${hold.slug} ${hold.code}`).join(', ')}${held.length > 3 ? ', ...' : ''})`}; retry them with ${[...new Set(held.map(hold => `\`${hold.fix.argv!.join(' ')}\``))].join(', ')}.` : '';
+ const text = backlog.pending || (work === 0 && readiness.status === 'projection_pending')
? `Visible pages have missing or stale text projections${backlog.pending ? ` (${backlog.pending} queued Markdown/code page(s)${backlog.failed ? `, ${backlog.failed} last failed` : ''})` : ''}; search and code results may be incomplete. ${opts.resident
? 'The resident gbrain process that holds this PGLite brain is rebuilding queued Markdown and code projections (up to 100 pages per pass, fewer while writes wait). On the brain host, `gbrain doctor --only text_projection_readiness --json` shows the counts and how to drain faster.'
: 'Run `gbrain projections drain` to rebuild queued Markdown and code projections now; it is safe while `gbrain serve` runs on Postgres.'}${segmentedNote} ${CODE_REPAIR}`
: '';
- const { fix, blocked } = opts.resident ? {} : projectionFix(backlog, opts);
+ const projection = opts.resident ? {} : projectionFix(backlog, opts);
+ const blocked = projection.blocked;
+ const fix = projection.fix ?? (held.length && !opts.resident ? { ...held[0]!.fix, actor: opts.remote ? 'host_admin' as const : 'agent' as const } : undefined);
const unavailable = blocked ? ` Re-importing images needs multimodal embeddings, which are off (set ${blocked}=true on the brain host, then preview with \`gbrain embed --stale --images --dry-run\`).` : '';
return {
name: 'text_projection_readiness', status: 'warn',
- message: [text, ...classSentences(backlog, opts.resident === true)].filter(Boolean).join(' ') + unavailable + ` ${UNCHANGED}`,
+ message: [text, heldText, ...classSentences(backlog, opts.resident === true)].filter(Boolean).join(' ') + unavailable + ` ${UNCHANGED}`,
details: blocked ? { ...details, reimport_blocked_by: blocked } : details,
...(fix ? { fix } : { fix_unavailable_reason: 'operator_judgement' as const }),
};
diff --git a/src/commands/migrations/v0_60_31.ts b/src/commands/migrations/v0_60_31.ts
index 3e154fa744..2d56c087f0 100644
--- a/src/commands/migrations/v0_60_31.ts
+++ b/src/commands/migrations/v0_60_31.ts
@@ -14,8 +14,11 @@
*
* Idempotent: each page re-seals in its own transaction and a re-sealed page
* is no longer pending, so a rerun after an interruption resumes with the
- * pages still withheld. A failed page records the run as partial so the next
- * `gbrain apply-migrations --yes` retries it.
+ * pages still withheld. A page whose re-chunk fails item-scoped is held (its
+ * chunks stay withheld, doctor lists it, `gbrain repair safe-chunks --source
+ * <id> --apply` retries it) and the phase completes with `held: N` in its
+ * detail. A run-scoped failure, or most pages failing, fails the phase so the
+ * next `gbrain apply-migrations --yes` retries it.
*/
import type { Migration, OrchestratorOpts, OrchestratorPhaseResult, OrchestratorResult } from './types.ts';
import type { BrainEngine } from '../../core/engine.ts';
@@ -24,6 +27,8 @@ import { createEngine } from '../../core/engine-factory.ts';
import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';
import { credentialProjectionPending, resealCredentialProjections } from '../../core/page-state/credential-reseal.ts';
import { runMigrateOnlyCore } from './in-process.ts';
+import { classifyItemFailure } from '../../core/item-failure.ts';
+import { redactConnectionInfo } from '../../core/audit/redact-connection-info.ts';
import { googleFileModesNoticePhase } from './v0_60_31-google-file-modes.ts';
let testEngineOverride: BrainEngine | null = null;
@@ -37,12 +42,21 @@ async function credentialProjectionPhase(engine: BrainEngine, opts: Orchestrator
const pending = await credentialProjectionPending(engine);
return { name, status: 'skipped', detail: `dry-run: ${pending.rebuildable} page(s) would be re-chunked without provider calls` };
}
- const result = await resealCredentialProjections(engine);
+ let result: Awaited<ReturnType<typeof resealCredentialProjections>>;
+ try {
+ result = await resealCredentialProjections(engine);
+ } catch (error) {
+ // A run-scoped failure (connection, schema, abort) or a systemic one: the phase fails and the next run resumes; no page was held.
+ const failure = classifyItemFailure(error);
+ return { name, status: 'failed', detail: `The credential-safe re-chunk stopped (${failure.code}): ${redactConnectionInfo(failure.message).slice(0, 500)} `
+ + 'Pages it did not reach stay withheld; fix the cause, then rerun: gbrain apply-migrations --yes --no-autopilot-install' };
+ }
const kept = result.kept ? `; ${result.kept} code page(s) without a recorded source path stay withheld until re-imported` : '';
- const detail = `${result.resealed} page(s) re-chunked without provider calls, ${result.superseded} superseded by newer writes${kept}. `
- + 'Embed the re-chunked text when ready: gbrain embed --stale';
- if (result.failed) return { name, status: 'failed', detail: `${result.failed} page(s) failed to re-chunk and stay withheld; ${detail}` };
- return { name, status: 'complete', detail };
+ const codes = [...new Set(result.held.map(hold => hold.code))].join(', ');
+ const held = result.held.length ? `; held: ${result.held.length} page(s) whose re-chunk failed (${codes}) stay withheld; gbrain doctor --only text_projection_readiness lists them `
+ + 'and gbrain repair safe-chunks --source <id> --apply retries them' : '';
+ return { name, status: 'complete', detail: `${result.resealed} page(s) re-chunked without provider calls, ${result.superseded} superseded by newer writes${kept}${held}. `
+ + 'Embed the re-chunked text when ready: gbrain embed --stale' };
}
async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult> {
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index c9fe68794a..22cfdfebf5 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -30,6 +30,7 @@ export const ISOLATE_SITES = {
'repair.apply_items': 'A-9',
'repair.all_kinds': 'A-45',
'repair.content_lane_kinds': 'A-46',
+ 'migration.credential_reseal': 'A-27',
} as const satisfies Record<string, string>;
export type IsolateSite = keyof typeof ISOLATE_SITES;
diff --git a/src/core/page-state/credential-reseal.ts b/src/core/page-state/credential-reseal.ts
index bc89038dfd..2c92ed5455 100644
--- a/src/core/page-state/credential-reseal.ts
+++ b/src/core/page-state/credential-reseal.ts
@@ -6,11 +6,23 @@
* unchanged canonical body through the projection installer: no page write,
* no journal admission and no provider call. Vectors of chunks whose text is
* unchanged are kept; re-chunked key chunks wait for `gbrain embed --stale`.
+ *
+ * A page whose re-chunk fails item-scoped is held under op_checkpoints
+ * `credential-reseal-hold` (page id, revision, chunker generation, error code,
+ * consecutive attempts): its chunks stay withheld, doctor
+ * text_projection_readiness lists it, and `gbrain repair safe-chunks --source
+ * <id> --apply` retries it. A hold never blocks a retry and stops applying when
+ * the page changes, seals or the chunker generation moves.
*/
import type { BrainEngine } from '../engine.ts';
import { resealSafeChunks } from './projections.ts';
import { buildSegmentedProjection } from '../page-body/projection.ts';
import { PageRevisionConflictError } from './types.ts';
+import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';
+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
+import type { Action } from '../agent-output.ts';
+import { ItemRun } from '../item-failure.ts';
+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
const KEY_MARKER = `'-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----'`;
const REBUILDABLE = `(p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL))`;
@@ -33,29 +45,100 @@ export async function credentialProjectionPending(engine: Pick<BrainEngine, 'exe
return { rebuildable: Number(row?.rebuildable ?? 0), kept: Number(row?.kept ?? 0) };
}
-export interface CredentialResealResult { resealed: number; superseded: number; failed: number; kept: number }
+/** GBRA-130 A-27: one page whose re-chunk failed item-scoped, recorded under op_checkpoints `credential-reseal-hold` keyed by page id. */
+export interface CredentialResealHold {
+ page_id: number; source_id: string; slug: string;
+ /** The page's knowledge_revision when it failed: a new revision is a new item and the hold no longer applies. */
+ revision: string;
+ /** The chunker generation that failed it: a chunker change retries every page. */
+ producer: string;
+ code: string; message: string;
+ /** Consecutive failing runs at this revision, producer and code. */
+ attempts: number;
+ at: string;
+}
+
+const HOLD_OP = 'credential-reseal-hold';
+const PRODUCER = `chunker-v${MARKDOWN_CHUNKER_VERSION}.fence-v${SAFE_FENCE_CHUNKER_VERSION}`;
+/** A hold applies while its page is live, still at the held revision and producer, and still unsealed. */
+const LIVE_HOLD = `p.deleted_at IS NULL AND p.knowledge_revision::text = h.completed_keys->0->>'revision'
+ AND h.completed_keys->0->>'producer' = '${PRODUCER}' AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision`;
+const HOLD_PAGES = `op_checkpoints h JOIN pages p ON p.id = (h.completed_keys->0->>'page_id')::int`;
+
+/** SQL predicate over `pages p`: the page has a live credential re-chunk hold (`gbrain repair safe-chunks` retries it). */
+export const CREDENTIAL_RESEAL_HELD = `(p.text_projection_revision IS DISTINCT FROM p.knowledge_revision AND EXISTS (SELECT 1 FROM op_checkpoints h
+ WHERE h.op='${HOLD_OP}' AND h.fingerprint = p.id::text AND p.knowledge_revision::text = h.completed_keys->0->>'revision'
+ AND h.completed_keys->0->>'producer' = '${PRODUCER}'))`;
+
+/** The command that retries a held page: `gbrain repair safe-chunks` for its source (a segmented page is rebuilt by the projection drain). */
+function holdFix(hold: Pick<CredentialResealHold, 'source_id'>, segmented: boolean): Action {
+ return segmented
+ ? { argv: ['gbrain', 'projections', 'drain'], preview_argv: ['gbrain', 'projections', 'drain', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Rebuilds the segmented page\'s projection from its stored regions and seals it; no provider call.' }
+ : { argv: ['gbrain', 'repair', 'safe-chunks', '--source', hold.source_id, '--apply'], preview_argv: ['gbrain', 'repair', 'safe-chunks', '--source', hold.source_id],
+ consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-chunks the held page from its unchanged body without provider calls; its key chunks stay withheld until it seals.' };
+}
+
+/** Live holds (optionally for some sources), oldest page first, each with the command that retries it. */
+export async function readCredentialResealHolds(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<Array<CredentialResealHold & { fix: Action }>> {
+ const rows = await engine.executeRaw<{ hold: CredentialResealHold; segmented: boolean }>(`SELECT h.completed_keys->0 AS hold, p.body_storage IS NOT DISTINCT FROM 'segmented' AS segmented
+ FROM ${HOLD_PAGES} WHERE h.op='${HOLD_OP}' AND ${LIVE_HOLD} ${sourceIds ? 'AND p.source_id=ANY($1::text[])' : ''} ORDER BY p.id`, sourceIds ? [sourceIds] : []);
+ return rows.map(row => ({ ...row.hold, fix: holdFix(row.hold, row.segmented === true) }));
+}
-/** Re-seal every rebuildable pending page, one page per transaction, so an interrupted run resumes where it stopped. */
+/**
+ * Records this run's failed pages (attempts count consecutive runs at the same revision, producer and code) and drops
+ * every hold that no longer applies. Called only for a run that finished: a run-scoped or systemic stop records nothing.
+ */
+async function recordCredentialResealHolds(engine: BrainEngine, failed: Array<Omit<CredentialResealHold, 'producer' | 'attempts' | 'at'>>): Promise<CredentialResealHold[]> {
+ await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op='${HOLD_OP}' AND fingerprint NOT IN (SELECT h.fingerprint FROM ${HOLD_PAGES} WHERE h.op='${HOLD_OP}' AND ${LIVE_HOLD})`);
+ const holds: CredentialResealHold[] = [];
+ for (const item of failed) {
+ const [prior] = await engine.executeRaw<{ hold: CredentialResealHold }>(`SELECT completed_keys->0 AS hold FROM op_checkpoints WHERE op='${HOLD_OP}' AND fingerprint=$1`, [String(item.page_id)]);
+ const same = prior?.hold && prior.hold.revision === item.revision && prior.hold.producer === PRODUCER && prior.hold.code === item.code;
+ const hold: CredentialResealHold = { ...item, producer: PRODUCER, attempts: same ? prior.hold.attempts + 1 : 1, at: new Date().toISOString() };
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('${HOLD_OP}',$1,$2::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [String(item.page_id), JSON.stringify([hold])]);
+ holds.push(hold);
+ }
+ return holds;
+}
+
+export interface CredentialResealResult { resealed: number; superseded: number; failed: number; kept: number; held: CredentialResealHold[] }
+
+/**
+ * Re-seal every rebuildable pending page, one page per transaction, so an interrupted run resumes where it stopped.
+ * GBRA-130 A-27: a page whose re-chunk fails item-scoped is held (`readCredentialResealHolds`) with its revision and
+ * code and its chunks stay withheld; the run goes on. A run-scoped failure, or most pages failing
+ * (`item_failures_systemic`), is thrown and records no hold.
+ */
export async function resealCredentialProjections(engine: BrainEngine): Promise<CredentialResealResult> {
- const rows = await engine.executeRaw<{ source_id: string; slug: string; body_storage: string }>(`SELECT p.source_id,p.slug,p.body_storage
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; body_storage: string; revision: string }>(`SELECT p.id,p.source_id,p.slug,p.body_storage,
+ p.knowledge_revision::text AS revision
FROM pages p JOIN sources s ON s.id=p.source_id AND s.archived IS NOT TRUE
WHERE ${PENDING} AND ${REBUILDABLE} ORDER BY p.id`);
- const result: CredentialResealResult = { resealed: 0, superseded: 0, failed: 0, kept: 0 };
+ const result: CredentialResealResult = { resealed: 0, superseded: 0, failed: 0, kept: 0, held: [] };
+ const run = new ItemRun('migration.credential_reseal');
+ const failed: Array<Omit<CredentialResealHold, 'producer' | 'attempts' | 'at'>> = [];
for (const row of rows) {
try {
// A segmented page's chunks are built from its stored pem regions; its projection rebuild re-seals it.
const resealed = row.body_storage === 'segmented'
? (await buildSegmentedProjection(engine, { sourceId: row.source_id, slug: row.slug })).sealed
: await resealSafeChunks(engine, row.slug, row.source_id);
+ run.succeed();
if (resealed) result.resealed++;
else result.superseded++;
} catch (error) {
- if (error instanceof PageRevisionConflictError) { result.superseded++; continue; }
- result.failed++;
- process.stderr.write(`[gbrain] Credential-safe re-chunk failed for ${row.source_id}:${row.slug}; its chunks stay withheld. `
- + `Re-run: gbrain apply-migrations --yes --no-autopilot-install\n`);
+ if (error instanceof PageRevisionConflictError) { run.succeed(); result.superseded++; continue; }
+ const failure = run.fail(`${row.source_id}:${row.slug}`, error);
+ failed.push({ page_id: Number(row.id), source_id: row.source_id, slug: row.slug, revision: row.revision, code: failure.code, message: redactConnectionInfo(failure.message) });
+ process.stderr.write(`[gbrain] Credential-safe re-chunk failed for ${row.source_id}:${row.slug} (${failure.code}); its chunks stay withheld. `
+ + `Retry: gbrain repair safe-chunks --source ${row.source_id} --apply\n`);
}
}
+ result.held = await recordCredentialResealHolds(engine, failed);
+ result.failed = failed.length;
result.kept = (await credentialProjectionPending(engine)).kept;
return result;
}
diff --git a/src/core/repair/safe-chunks.ts b/src/core/repair/safe-chunks.ts
index d80e011374..1e0a096d64 100644
--- a/src/core/repair/safe-chunks.ts
+++ b/src/core/repair/safe-chunks.ts
@@ -7,6 +7,9 @@
* Vectors of unchanged embedding inputs are kept; the rest are embedded after
* the re-seal unless --no-embed is passed (then `gbrain embed --stale` does it).
*
+ * It also retries the pages the v0.60.31 credential re-chunk held
+ * (page-state/credential-reseal.ts, GBRA-130 A-27), whatever their chunker.
+ *
* Code pages need their recorded source path to re-chunk; pages without one,
* and page kinds the projection installer cannot rebuild (images), are counted
* as residuals and left for their importer.
@@ -16,6 +19,7 @@ import { resealSafeChunks } from '../page-state/projections.ts';
import { PageRevisionConflictError } from '../page-state/types.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
import { embedStalePages } from '../embed-stale.ts';
+import { CREDENTIAL_RESEAL_HELD } from '../page-state/credential-reseal.ts';
import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';
interface PendingRow { id: number; source_id: string; slug: string; page_kind: string; rebuildable: boolean; chars: number }
@@ -27,7 +31,8 @@ export const safeChunksRepair: RepairHandler = {
const rows = await engine.executeRaw<PendingRow>(`SELECT p.id,p.source_id,p.slug,p.page_kind,
(p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL)) AS rebuildable,
length(p.compiled_truth)+length(COALESCE(p.timeline,'')) AS chars
- FROM pages p WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}
+ FROM pages p WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL
+ AND (p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} OR (${CREDENTIAL_RESEAL_HELD} AND p.body_storage IS DISTINCT FROM 'segmented'))
ORDER BY p.id`, [scope.source_ids]);
const items: RepairItem[] = rows.filter(row => row.rebuildable)
.map(row => ({ cursor: { phase: 0, id: Number(row.id) }, source_id: row.source_id, slug: row.slug, chars: Number(row.chars),
diff --git a/test/pathological/a27-credential-reseal.test.ts b/test/pathological/a27-credential-reseal.test.ts
new file mode 100644
index 0000000000..2a7707d413
--- /dev/null
+++ b/test/pathological/a27-credential-reseal.test.ts
@@ -0,0 +1,156 @@
+/**
+ * GBRA-130 A-27: the v0.60.31 orchestrated migration re-chunks every page whose
+ * body holds a private key (src/core/page-state/credential-reseal.ts,
+ * src/commands/migrations/v0_60_31.ts).
+ *
+ * Protects: one page whose credential-safe re-chunk throws item-scoped no
+ * longer fails the phase (three partial runs wedge every apply-migrations and
+ * upgrade): the page is recorded durably with its revision and error code, its
+ * chunks stay withheld, every other page is re-chunked, the phase completes
+ * with \`held: N\` in its detail, doctor text_projection_readiness lists the held
+ * page with \`gbrain repair safe-chunks --source <id> --apply\`, that command
+ * retries and seals it, and the record clears when the page changes. A
+ * run-scoped failure still fails the phase, and so does a systemic run
+ * (\`item_failures_systemic\`), recording nothing.
+ * Fails when: one page's failure marks the phase failed again, the record
+ * blocks or outlives its revision, or a run-scoped error is recorded as a hold.
+ * Why new: test/e2e/credential-projection-repair.test.ts covers healthy pages.
+ * Seams: __setTestEngineOverride (existing); a test-only trigger on
+ * content_chunks builds the unbuildable page; run-scoped errors are injected at
+ * the engine's transaction.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomBytes } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { readCredentialResealHolds } from '../../src/core/page-state/credential-reseal.ts';
+import { v0_60_31, __setTestEngineOverride } from '../../src/commands/migrations/v0_60_31.ts';
+import { checkProjectionReadiness } from '../../src/commands/doctor/checks/projection-readiness.ts';
+import { credentialProjectionPendingCheck } from '../../src/commands/doctor/checks/credential-projection.ts';
+import { resolveRepairScope, runRepair } from '../../src/core/repair/core.ts';
+import { safeChunksRepair } from '../../src/core/repair/safe-chunks.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const SOURCE = 'default';
+const SLUGS = ['ops/k1', 'ops/k2', 'ops/k3', 'ops/k4', 'ops/k5', 'ops/k6'];
+const POISON = 'ops/k2';
+const quiet = { info() {}, warn() {}, error() {} };
+// Built at runtime so no key-shaped literal sits in the repository.
+const pem = () => ['-----BEGIN', 'PRIVATE', 'KEY-----'].join(' ') + '\n' + randomBytes(48).toString('base64') + '\n' + ['-----END', 'PRIVATE', 'KEY-----'].join(' ');
+const body = (slug: string) => '---\ntitle: ' + slug + '\ntype: note\n---\n\nDeploy notes for ' + slug + '.\n\n' + pem() + '\n\nRotation steps follow.\n';
+
+async function refuseChunks(engine: BrainEngine, slugs: string[]) {
+ const ids = (await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=ANY($2::text[])', [SOURCE, slugs])).map(row => Number(row.id));
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION pathological_refuse_chunk() RETURNS trigger LANGUAGE plpgsql AS $fn$
+ BEGIN IF NEW.page_id = ANY(ARRAY[${ids.join(',')}]::int[]) THEN RAISE EXCEPTION 'pathological: chunk refused for this page' USING ERRCODE = 'check_violation'; END IF; RETURN NEW; END $fn$`);
+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_chunk ON content_chunks');
+ await engine.executeRaw('CREATE TRIGGER pathological_refuse_chunk BEFORE INSERT OR UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION pathological_refuse_chunk()');
+}
+
+function failingAt(engine: BrainEngine, injected: unknown): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ const value = Reflect.get(target, prop);
+ if (prop === 'transaction' && typeof value === 'function') {
+ return (...args: unknown[]) => new Error().stack?.includes('resealSafeChunks') ? Promise.reject(injected) : (value as Function).apply(target, args);
+ }
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+}
+
+const migrate = () => v0_60_31.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe('A-27 v0.60.31 credential re-chunk: one unbuildable page never fails the migration (' + backend + ')', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); }, 120_000);
+ afterAll(async () => { await close(); });
+ afterEach(() => { __setTestEngineOverride(null); });
+ beforeEach(async () => {
+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_chunk ON content_chunks');
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='credential-reseal-hold' OR op='repair'");
+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [SOURCE]);
+ for (const slug of SLUGS) await importFromContent(engine, slug, body(slug), { noEmbed: true, sourceId: SOURCE });
+ // Schema migration v189's state: the pages' old chunks are withheld until the re-chunk seals them.
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1', [SOURCE]);
+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)', [SOURCE]);
+ __setTestEngineOverride(engine);
+ });
+
+ test('item case: the unbuildable page is held with its code and the migration completes; doctor lists it with the retry command', async () => {
+ await refuseChunks(engine, [POISON]);
+ const before = await snapshotItems(engine, SOURCE);
+ const result = await expectUnitNotAborted(migrate);
+ expect(result.status).toBe('complete');
+ expect(result.phases[0]).toMatchObject({ name: 'credential_projection', status: 'complete' });
+ expect(result.phases[0]!.detail).toContain('held: 1');
+ expect(result.phases[0]!.detail).toContain('invalid_data');
+ const holds = await readCredentialResealHolds(engine);
+ expect(holds.length).toBe(1);
+ expectItemFailure({ key: holds[0]!.source_id + ':' + holds[0]!.slug, code: holds[0]!.code, fix: holds[0]!.fix }, { key: SOURCE + ':' + POISON, code: 'invalid_data', fix: /"gbrain","repair","safe-chunks","--source","default","--apply"/ });
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: SLUGS.filter(s => s !== POISON), progressFields: ['chunks'] });
+ const check = await checkProjectionReadiness(engine);
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ credential_reseal_held: 1, held_pages: [{ source_id: SOURCE, slug: POISON, code: 'invalid_data' }] });
+ expect(check.message).toContain('gbrain repair safe-chunks --source default --apply');
+ expect(check.fix?.argv).toEqual(['gbrain', 'repair', 'safe-chunks', '--source', SOURCE, '--apply']);
+ const pending = await credentialProjectionPendingCheck(engine, [SOURCE]);
+ expect(pending.details).toMatchObject({ pages_pending: 1, held_pages: 1 });
+ expect(pending.message).toContain('gbrain repair safe-chunks --source default --apply');
+ const remote = await checkProjectionReadiness(engine, {}, { remote: true });
+ expect(JSON.stringify(remote)).not.toContain(POISON);
+ });
+
+ test('three consecutive runs on the same page all complete (never partial, so never wedged) and count the attempts', async () => {
+ await refuseChunks(engine, [POISON]);
+ for (let run = 1; run <= 3; run++) {
+ const result = await expectUnitNotAborted(migrate);
+ expect({ run, status: result.status, phase: result.phases[0]!.status }).toEqual({ run, status: 'complete', phase: 'complete' });
+ }
+ expect((await readCredentialResealHolds(engine)).map(h => [h.slug, h.attempts])).toEqual([[POISON, 3]]);
+ });
+
+ test('recovery case: once the page can be built, the doctor fix re-chunks it and the hold clears', async () => {
+ await refuseChunks(engine, [POISON]);
+ await expectUnitNotAborted(migrate);
+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_chunk ON content_chunks');
+ const before = await snapshotItems(engine, SOURCE);
+ const repair = await expectUnitNotAborted(async () => runRepair({ engine, sourceId: SOURCE, remote: false, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: quiet } as never,
+ safeChunksRepair, await resolveRepairScope(engine, SOURCE), { apply: true, embed: false }));
+ expect(repair).toMatchObject({ applied: 1, complete: true });
+ expect(await readCredentialResealHolds(engine)).toEqual([]);
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: [POISON], progressFields: ['chunks'] });
+ expect((await checkProjectionReadiness(engine)).details).not.toHaveProperty('credential_reseal_held');
+ });
+
+ test('the hold clears when the page changes (a new revision is a new item)', async () => {
+ await refuseChunks(engine, [POISON]);
+ await expectUnitNotAborted(migrate);
+ expect((await readCredentialResealHolds(engine)).length).toBe(1);
+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [SOURCE, POISON]);
+ expect(await readCredentialResealHolds(engine)).toEqual([]);
+ });
+
+ for (const { name, error } of runScopedErrors()) {
+ test('run case: a run-scoped ' + name + ' fails the phase and records no hold', async () => {
+ __setTestEngineOverride(failingAt(engine, error()));
+ const before = await snapshotItems(engine, SOURCE);
+ const result = await migrate();
+ expect(result.status).toBe('partial');
+ expect(result.phases[0]!.status).toBe('failed');
+ expect(await readCredentialResealHolds(engine)).toEqual([]);
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE));
+ });
+ }
+
+ test('breaker case: when every page fails the phase fails item_failures_systemic and records no hold', async () => {
+ await refuseChunks(engine, SLUGS);
+ const result = await migrate();
+ expect(result.status).toBe('partial');
+ expect(result.phases[0]!.status).toBe('failed');
+ expect(result.phases[0]!.detail).toContain('item_failures_systemic');
+ expect(await readCredentialResealHolds(engine)).toEqual([]);
+ });
+ });
+}
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index ac589e7120..34c5ed9c55 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -21,4 +21,5 @@ export const CATALOGUE: Record<IsolateSite, SiteCases> = {
'repair.apply_items': { file: 'test/pathological/a9-repair-core.test.ts', item: 'item case: an item whose apply throws', run: 'run case: a run-scoped' },
'repair.all_kinds': { file: 'test/pathological/a45-repair-all-kinds.test.ts', item: 'item case: a kind whose plan throws', run: 'run case: a run-scoped' },
'repair.content_lane_kinds': { file: 'test/pathological/a46-content-lane-kinds.test.ts', item: 'item case: fences throwing is recorded', run: 'run case: a run-scoped' },
+ 'migration.credential_reseal': { file: 'test/pathological/a27-credential-reseal.test.ts', item: 'item case: the unbuildable page is held', run: 'run case: a run-scoped' },
};
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 5af32080a8..41e6d74f07 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -218,6 +218,7 @@ test/page-prepare-shared-origin-6517.test.ts
test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
+test/pathological/a27-credential-reseal.test.ts
test/pathological/a45-repair-all-kinds.test.ts
test/pathological/a46-content-lane-kinds.test.ts
test/pathological/a9-repair-core.test.ts