Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): one failing page no longer stops managed link extraction; content failures are held after 3 runs, --retry-held retries them (GBRA-130 A-1)

garrytan6e3c40d31547
diff --git a/src/commands/extract-stale-delegate.ts b/src/commands/extract-stale-delegate.ts
index eb7b7d5421..5ca26937cf 100644
--- a/src/commands/extract-stale-delegate.ts
+++ b/src/commands/extract-stale-delegate.ts
@@ -44,9 +44,10 @@ export async function maybeDelegateExtractStale(hostConfig: GBrainConfig | null,
if (arg === '--source') i++;
params.source_mode = selection.mode;
} else if (arg === '--catch-up') params.catch_up = true;
+ else if (arg === '--retry-held') params.retry_held = true;
else if (!['--stale', '--json', '--include-frontmatter', 'all'].includes(arg)) {
throw invalid(`Unsupported owner-delegated extract --stale option: ${arg.split('=')[0]}.`,
- `Remove ${arg.split('=')[0]}; while the running serve holds the brain, extract --stale accepts --source-id, --dry-run, --json, --include-frontmatter and --catch-up. Stop the serve to use other extract options.`);
+ `Remove ${arg.split('=')[0]}; while the running serve holds the brain, extract --stale accepts --source-id, --dry-run, --json, --include-frontmatter, --catch-up and --retry-held. Stop the serve to use other extract options.`);
}
}
const delegated = await maybeDelegateLocalAdministration('writer_extract_stale', params, config, { timeoutMs: 86_400_000 });
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 7a94a5d9d2..bac8268f44 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -87,6 +87,7 @@ export { withRetry };
export type { WithRetryOpts } from '../core/retry.ts';
import { buildGazetteer, findMentionedEntities, hashGazetteer } from '../core/by-mention.ts';
import { pageMentions, runMentionPass, type MentionPassResult } from '../core/mentions/pass.ts';
+import type { LinkExtractionFailure, LinkExtractionSystemic } from '../core/persistence/links-maintenance.ts';
import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../core/mentions/stale.ts';
// #4611: the cross-source link fallback follows the configured
// `sources.default` (validated shape) instead of the literal 'default'.
@@ -880,12 +881,15 @@ Extraction:
Incremental sweep:
${ATTENDANCE_REPAIR_HELP}
gbrain extract --stale [--source-id <id>] [--include-frontmatter]
- [--catch-up] [--dry-run] [--json]
+ [--catch-up] [--retry-held] [--dry-run] [--json]
Re-extract links + timeline for stale pages, then the mention pass (entity
aliases and title subjects; link_source='mentions'; off: gbrain config set
mentions.auto_link false). DB-source; safe to cron; 30 min per run, the next
resumes; --catch-up runs until none remain. Scope with --source-id (--source
is fs|db). Done when --dry-run --json reports actionable 0 and mention_due 0.
+ On a managed brain a page whose extraction fails is reported and skipped;
+ after 3 runs failing it the same way it is held until it is edited, the
+ extractor changes, or --retry-held clears the holds and retries it now.
Inspection:
gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]
@@ -976,6 +980,7 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?
includeFrontmatter: args.includes('--include-frontmatter') || undefined,
sourceIdFilter: staleSourceId,
catchUp: args.includes('--catch-up'),
+ retryHeld: args.includes('--retry-held'),
});
return;
}
@@ -2097,8 +2102,10 @@ export async function extractStaleFromDB(
* explicit `gbrain extract --stale` command. Ignored when catchUp.
*/
timeBudgetMs?: number;
+ /** GBRA-130 A-1 (managed brains): clear held link-extraction failures first. */ retryHeld?: boolean;
},
-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; mentions?: MentionPassResult }> {
+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; mentions?: MentionPassResult;
+ linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[] }> {
const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;
const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
@@ -2122,11 +2129,12 @@ export async function extractStaleFromDB(
// (the mention pass runs inside it).
if (await managedPersistenceEnabled(engine)) {
const { runManagedStaleExtraction, formatManagedStaleExtraction } = await import('../core/persistence/links-maintenance.ts');
- const r = await runManagedStaleExtraction(engine, { sourceId: sourceIdFilter, catchUp, timeBudgetMs, counts: !opts.quiet });
+ const r = await runManagedStaleExtraction(engine, { sourceId: sourceIdFilter, catchUp, timeBudgetMs, counts: !opts.quiet, retryHeld: opts.retryHeld });
if (!jsonMode) log(formatManagedStaleExtraction(r, false, false));
else if (!opts.quiet) process.stdout.write(formatManagedStaleExtraction(r, false, true) + '\n');
return { linksCreated: r.created, timelineCreated: r.timeline, pagesProcessed: r.pages, staleRemaining: r.remaining + (r.mentions?.remaining ?? 0),
- ...(r.skipped ? { skippedChanged: r.skipped } : {}), ...(r.mentions ? { mentions: r.mentions } : {}) };
+ ...(r.skipped ? { skippedChanged: r.skipped } : {}), ...(r.mentions ? { mentions: r.mentions } : {}),
+ ...(r.failed ? { linkFailed: r.failed, linkFailures: r.failures } : {}), ...(r.systemic?.length ? { linkSystemic: r.systemic } : {}) };
}
// Resolver + cross-source resolution map built ONCE before the loop (the
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e2ba0efb62..99172b34a2 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -59,10 +59,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
- 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
+ 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--retry-held', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--conversation', '--dry-run', '--entity', '--examples', '--expected-state', '--force', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--slugs', '--source', '--source-id'],
- 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--retry-held', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],
'forget': ['--all-subjects', '--brain', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--request-id', '--source', '--status', '--vacuum', '--yes'],
@@ -81,7 +81,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index eb88e02358..241a75f998 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -171,7 +171,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
...(waitDrainMs !== undefined ? { waitDrainMs } : {}), ...(fetchTimeoutMs !== undefined ? { fetchTimeoutMs } : {}) }) };
}
if (operation === 'writer_extract_stale') {
- keys(params, ['source_id', 'dry_run', 'catch_up', 'source_mode']);
+ keys(params, ['source_id', 'dry_run', 'catch_up', 'source_mode', 'retry_held']);
const writer = currentVerifiedLocalWriter();
if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Stale extraction requires a trusted CLI registration.');
const { managedPersistenceEnabled } = await import('./ownership.ts');
@@ -180,7 +180,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
// #6803 (D2): the CLI validated --source before the hand-off; only the owner can see whether a source is named db.
if (params.source_mode === 'db') await (await import('../../commands/extract-stale-options.ts')).assertStaleSourceModeUnambiguous(engine, ['--stale', '--source', 'db', ...(sourceId ? ['--source-id', sourceId] : [])]);
return { ...await (await import('./links-maintenance.ts')).runManagedStaleExtraction(engine,
- { sourceId, dryRun: params.dry_run === true, catchUp: params.catch_up === true }) };
+ { sourceId, dryRun: params.dry_run === true, catchUp: params.catch_up === true, retryHeld: params.retry_held === true }) };
}
if (operation === 'writer_reindex_code') return (await import('./reindex-administration.ts')).runAuthenticatedCodeReindex(engine, params);
if (operation === 'writer_embed_facts') return (await import('./embed-facts-administration.ts')).runAuthenticatedFactEmbedding(engine, params, config);
diff --git a/src/core/persistence/links-extraction-holds.ts b/src/core/persistence/links-extraction-holds.ts
new file mode 100644
index 0000000000..520bd01285
--- /dev/null
+++ b/src/core/persistence/links-extraction-holds.ts
@@ -0,0 +1,75 @@
+/**
+ * GBRA-130 A-1: the per-page failure record of managed link extraction (`pages.links_extract_failure`, migration v257).
+ *
+ * Only content-class failures are recorded (a transient one is retried on the next run and never counts). A page that
+ * fails with the same code at the same knowledge revision and extractor generation in `LINK_HOLD_THRESHOLD_RUNS`
+ * consecutive runs is held: stale extraction skips it (`stalePagesWhere` `held: 'exclude'`) and doctor's
+ * `links_extraction_lag` reports it. A held page is retried when it is edited (new revision), when the extractor
+ * generation changes, or after `gbrain extract --stale --retry-held` clears the records; publishing its links clears
+ * its record with the watermark (`markPagesExtractedBatch`). The counting mirrors connectors/item-holds.ts. The
+ * record is a derived column outside the managed writer guard's tracked set, so it is written without coordination.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import type { ItemFailureClass } from '../item-failure.ts';
+import { sanitizeForJsonb } from '../batch-rows.ts';
+
+/** Consecutive runs failing one page the same way before it is held (as connectors/item-holds.ts HOLD_THRESHOLD_RUNS). */
+export const LINK_HOLD_THRESHOLD_RUNS = 3;
+
+export interface LinkExtractionFailure {
+ slug: string;
+ source_id: string;
+ code: string;
+ class: ItemFailureClass;
+ message: string;
+ /** Consecutive runs that failed this page at its revision and generation; 0 for a transient failure (never counted). */
+ attempts: number;
+ held: boolean;
+ fix: Action;
+}
+
+/** The command that retries a page: the next plain run for a page not held, `--retry-held` for a held one. */
+export function linkExtractionRetryFix(sourceId: string | undefined, held: boolean): Action {
+ const scope = sourceId ? ['--source-id', sourceId] : [];
+ const which = sourceId ? `source ${sourceId}'s` : 'every source\'s';
+ return {
+ argv: ['gbrain', 'extract', '--stale', ...scope, ...(held ? ['--retry-held'] : [])], consent: [], actor: 'agent', requires_exclusive: false,
+ why: held
+ ? `Clears ${which} held link-extraction failures and retries those pages now; it changes no page content. A page that fails the same way again is held again after ${LINK_HOLD_THRESHOLD_RUNS} runs.`
+ : `Retries link extraction for ${which} stale pages, the failed ones included; it changes no page content.`,
+ verify: { argv: ['gbrain', 'extract', '--stale', '--dry-run', '--json', ...scope] },
+ docs: 'docs/guides/troubleshooting.md#symptom-table',
+ };
+}
+
+/**
+ * Counts one run's content failures. `revision` is the knowledge revision the run read (null when the failure came
+ * before the read: the page's current revision is used). A page edited since is not recorded. Returns each recorded
+ * page's run count and whether it is now held, keyed `source_id\0slug`.
+ */
+export async function recordLinkExtractionFailures(engine: BrainEngine, generation: string,
+ failures: ReadonlyArray<{ slug: string; source_id: string; revision: string | null; code: string; message: string }>): Promise<Map<string, { attempts: number; held: boolean }>> {
+ if (!failures.length) return new Map();
+ const rows = await engine.executeRaw<{ slug: string; source_id: string; attempts: number; state: string }>(
+ `UPDATE pages p SET links_extract_failure = (
+ SELECT jsonb_build_object('state', CASE WHEN n.attempts >= $7 THEN 'held' ELSE 'failing' END, 'code', v.code, 'message', v.message,
+ 'revision', p.knowledge_revision::text, 'generation', $6::text, 'attempts', n.attempts,
+ 'first_failed_at', CASE WHEN n.attempts > 1 THEN COALESCE(p.links_extract_failure->>'first_failed_at', $8) ELSE $8 END, 'last_failed_at', $8,
+ 'held_at', CASE WHEN n.attempts >= $7 THEN COALESCE(p.links_extract_failure->>'held_at', $8) END)
+ FROM (SELECT CASE WHEN p.links_extract_failure->>'revision' = p.knowledge_revision::text AND p.links_extract_failure->>'generation' = $6::text
+ AND p.links_extract_failure->>'code' = v.code THEN COALESCE((p.links_extract_failure->>'attempts')::int, 0) + 1 ELSE 1 END AS attempts) n)
+ FROM unnest($1::text[], $2::text[], $3::text[], $4::text[], $5::text[]) AS v(slug, source_id, revision, code, message)
+ WHERE p.slug = v.slug AND p.source_id = v.source_id AND p.deleted_at IS NULL AND p.knowledge_revision::text = COALESCE(v.revision, p.knowledge_revision::text)
+ RETURNING p.slug, p.source_id, (p.links_extract_failure->>'attempts')::int AS attempts, p.links_extract_failure->>'state' AS state`,
+ [failures.map(f => f.slug), failures.map(f => f.source_id), failures.map(f => f.revision), failures.map(f => f.code),
+ failures.map(f => sanitizeForJsonb(f.message)), generation, LINK_HOLD_THRESHOLD_RUNS, new Date().toISOString()]);
+ return new Map(rows.map(row => [`${row.source_id}\0${row.slug}`, { attempts: Number(row.attempts), held: row.state === 'held' }]));
+}
+
+/** `--retry-held`: drops the failure records (held or still counting) of one source, or of every source. Returns the pages cleared. */
+export async function clearLinkExtractionHolds(engine: BrainEngine, sourceId?: string): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ 'UPDATE pages SET links_extract_failure = NULL WHERE links_extract_failure IS NOT NULL AND ($1::text IS NULL OR source_id = $1::text) RETURNING id', [sourceId ?? null]);
+ return rows.length;
+}
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index b64a4dc587..2eaa42a5bc 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -10,25 +10,39 @@ import { runMentionPass, type MentionPassResult } from '../mentions/pass.ts';
import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../mentions/stale.ts';
import { plannerStatsForLinkDrain } from '../planner-stats.ts';
import { STALE_TIME_BUDGET_MS, formatStaleCounts, staleExtractionCounts, type StaleExtractionCounts } from '../extraction-lag.ts';
+import { ItemRun, type ItemFailure } from '../item-failure.ts';
+import type { OperationError } from '../ops/contract.ts';
+import { clearLinkExtractionHolds, linkExtractionRetryFix, recordLinkExtractionFailures, type LinkExtractionFailure } from './links-extraction-holds.ts';
+export type { LinkExtractionFailure };
export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number;
/** The mention pass (absent when the caller ran links only, as sync does). */
mentions?: MentionPassResult; mention_due?: number; mention_last_pass_at?: string | null;
/** #6803 (D3): the terminal counts (`gbrain extract --stale` only; sync's tail does not read them). */
- counts?: StaleExtractionCounts; }
+ counts?: StaleExtractionCounts;
+ /** GBRA-130 A-1 (present when a page failed): pages whose derivation failed this run; the first `LINK_FAILURE_REPORT_LIMIT` are listed. */
+ failed?: number; failures?: LinkExtractionFailure[];
+ /** Sources an unscoped run stopped because most of their pages failed (the breaker): nothing of theirs was held. */
+ systemic?: LinkExtractionSystemic[]; }
+
+export interface LinkExtractionSystemic { source_id: string; code: string; reason: string | null; message: string; fix: OperationError['fix'] }
+
+/** Failures a result lists in full; `failed` counts all of them. */
+export const LINK_FAILURE_REPORT_LIMIT = 50;
/**
* `gbrain extract --stale` on a managed brain, locally or inside the PGLite owner: a plain run stops at the
* `STALE_TIME_BUDGET_MS` budget and the next resumes, `catchUp` runs until nothing is stale (#6803 D2).
*/
export async function runManagedStaleExtraction(engine: BrainEngine,
- opts: { sourceId?: string; dryRun?: boolean; catchUp?: boolean; timeBudgetMs?: number; counts?: boolean }): Promise<ManagedLinkExtraction> {
+ opts: { sourceId?: string; dryRun?: boolean; catchUp?: boolean; timeBudgetMs?: number; counts?: boolean; retryHeld?: boolean }): Promise<ManagedLinkExtraction> {
const counts = async () => opts.counts === false ? {} : { counts: await staleExtractionCounts(engine, opts.sourceId) };
if (!opts.dryRun) {
+ if (opts.retryHeld) await clearLinkExtractionHolds(engine, opts.sourceId);
const result = await extractManagedStaleLinks(engine, { sourceId: opts.sourceId, ...(opts.catchUp ? {} : { timeBudgetMs: opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS }) });
return { ...result, ...await counts() };
}
- const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: await effectiveLinkExtractorWatermark(engine) });
+ const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: await effectiveLinkExtractorWatermark(engine), held: 'exclude' });
const m = await previewMentionPass(engine, opts.sourceId);
return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining, mention_due: m.due, mention_last_pass_at: m.last_pass_at, ...await counts() };
}
@@ -42,6 +56,7 @@ export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryR
action: 'extract_stale_done', links_created: result.created, links_removed: result.removed, timeline_created: result.timeline,
pages_processed: result.pages, stale_remaining: result.remaining + (result.mentions?.remaining ?? 0),
...(result.skipped ? { skipped_changed: result.skipped } : {}), ...(result.mentions ? mentionJsonFields(result.mentions) : {}),
+ ...(result.failed ? { failed: result.failed, failures: result.failures } : {}), ...(result.systemic?.length ? { systemic: result.systemic } : {}),
}), ...(counts ?? {}) });
}
const countsLine = counts ? `\n${formatStaleCounts(counts)}` : '';
@@ -52,7 +67,15 @@ export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryR
const mentionLine = result.mentions ? formatMentionSummary(result.mentions) : null;
return `Extract --stale: ${result.created} link(s) created, ${result.removed} removed, ${result.timeline} timeline entr(ies) from ${result.pages} page(s).` +
(result.skipped ? ` Skipped ${result.skipped} page(s) edited during extraction or with unresolved attendance; they stay stale.` : '') +
- (result.remaining ? ` ${result.remaining} page(s) remain stale (raw total).` : '') + (mentionLine ? `\n${mentionLine}` : '') + countsLine;
+ (result.remaining ? ` ${result.remaining} page(s) remain stale (raw total).` : '') + formatLinkFailures(result) + (mentionLine ? `\n${mentionLine}` : '') + countsLine;
+}
+
+/** The failure lines of a run: each listed page with its code and state, then each source the breaker stopped, each with its fix. */
+function formatLinkFailures(result: ManagedLinkExtraction): string {
+ const lines = (result.failures ?? []).map(f => `\n ${f.source_id}:${f.slug}: ${f.code} (${f.held ? 'held; fix the page, then run' : f.class === 'content' ? `failed ${f.attempts} run(s); retried by` : 'transient; retried by'} ${f.fix.argv!.join(' ')}): ${f.message}`);
+ const head = result.failed ? `\n${result.failed} page(s) failed link extraction and stay stale${result.failed > lines.length ? ` (first ${lines.length} listed)` : ''}; the other pages were derived:` : '';
+ const systemic = (result.systemic ?? []).map(s => `\nSource ${s.source_id} stopped (${s.code}, most often ${s.reason}): ${s.message}`);
+ return head + lines.join('') + systemic.join('');
}
/** #5984: pages a managed link extraction derives at once on Postgres. */
@@ -93,12 +116,12 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
// publication refuses it if the generation moved since (derived-links.ts), and it stays stale.
const settings = await preparationConfigView(engine);
const versionTs = await effectiveLinkExtractorWatermark(settings);
- const derive = async (slug: string, sourceId: string, stamp?: string) => {
- opts.signal?.throwIfAborted();
+ const derive = async (slug: string, sourceId: string, stamp: string | undefined, read: { revision: string | null }) => {
done.add(`${sourceId}\0${slug}`);
// A segmented body stays unread: links and the canonical timeline read it block by block, before the transaction.
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot || isQuarantined(snapshot.page.frontmatter)) return;
+ read.revision = snapshot.revision;
const prepared = await prepareAutomaticLinks(settings, slug, snapshot.page, sourceId);
const canonical = await storedCanonicalTimeline(engine, snapshot.page, slug);
const outcome = await engine.transaction(async tx => withCoordinatedWrite(tx, [sourceId], async () => {
@@ -127,31 +150,67 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
let started = 0;
const budget = () => started < maxPages && Date.now() < deadline;
// #5984: on Postgres several pages derive at once, each in its own transaction (page guards lock in sorted
- // order, so they cannot deadlock); a page's links depend only on committed pages. The first failure stops the rest.
+ // order, so they cannot deadlock); a page's links depend only on committed pages.
+ // GBRA-130 A-1: a page whose derivation fails is recorded (one ItemRun per source) and the cursor moves past it; a
+ // run-scoped failure stops every worker and is rethrown once they settle. When most of a source's pages fail, its
+ // breaker trips: a run scoped to that source stops with `item_failures_systemic`, a brain-wide run skips the rest of
+ // that source and reports it in `systemic`. Nothing of a tripped source is recorded.
const width = engine.kind === 'postgres' ? MANAGED_LINK_EXTRACTION_WIDTH : 1;
- const each = async <T>(items: readonly T[], run: (item: T) => Promise<void>) => {
- let next = 0, failed = false;
- await Promise.all(Array.from({ length: Math.min(width, items.length) }, async () => {
- while (!failed && next < items.length && budget()) {
- const item = items[next++]!;
+ const runs = new Map<string, ItemRun>();
+ const failed: Array<ItemFailure & { slug: string; source_id: string; revision: string | null }> = [];
+ const tripped = new Map<string, OperationError>();
+ let stop: { error: unknown } | null = null;
+ const each = async (items: ReadonlyArray<{ slug: string; sourceId: string; stamp?: string }>) => {
+ let next = 0;
+ const settled = await Promise.allSettled(Array.from({ length: Math.min(width, items.length) }, async () => {
+ while (!stop && next < items.length && budget()) {
+ const { slug, sourceId, stamp } = items[next++]!;
+ if (tripped.has(sourceId)) continue;
+ try { opts.signal?.throwIfAborted(); } catch (error) { stop ??= { error }; break; }
started++;
await plannerTick(started);
- try { await run(item); } catch (error) { failed = true; throw error; }
+ const run = runs.get(sourceId) ?? runs.set(sourceId, new ItemRun('links.extract_stale')).get(sourceId)!;
+ const read = { revision: null as string | null };
+ try {
+ await derive(slug, sourceId, stamp, read);
+ run.succeed();
+ } catch (error) {
+ try { failed.push({ ...run.fail(`${sourceId}:${slug}`, error), slug, source_id: sourceId, revision: read.revision }); } catch (stopped) {
+ if (stopped !== error && !opts.sourceId) tripped.set(sourceId, stopped as OperationError);
+ else stop ??= { error: stopped };
+ }
+ }
}
}));
+ const rejected = settled.find(outcome => outcome.status === 'rejected');
+ if (rejected) throw (rejected as PromiseRejectedResult).reason;
+ if (stop) throw stop.error;
};
const plannerTick = await plannerStatsForLinkDrain(engine, async () =>
- Math.min(maxPages, await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs })));
- if (opts.slugs?.length && opts.sourceId) await each([...new Set(opts.slugs)], slug => derive(slug, opts.sourceId!));
+ Math.min(maxPages, await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs, held: 'exclude' })));
+ if (opts.slugs?.length && opts.sourceId) await each([...new Set(opts.slugs)].map(slug => ({ slug, sourceId: opts.sourceId! })));
let afterPageId = 0;
while (budget()) {
- const rows = await engine.listStalePagesForExtraction({ batchSize: 25, afterPageId, sourceId: opts.sourceId, versionTs });
+ const rows = await engine.listStalePagesForExtraction({ batchSize: 25, afterPageId, sourceId: opts.sourceId, versionTs, held: 'exclude' });
if (!rows.length) break;
afterPageId = rows[rows.length - 1]!.id;
- await each(rows.filter(row => !done.has(`${row.source_id}\0${row.slug}`)),
- row => derive(row.slug, row.source_id, row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs));
+ await each(rows.filter(row => !done.has(`${row.source_id}\0${row.slug}`)).map(row => ({ slug: row.slug, sourceId: row.source_id,
+ stamp: row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs })));
+ }
+ // Holds are counted only for sources whose failures look like their pages' own (ItemRun.systemic).
+ const recorded = await recordLinkExtractionFailures(engine, versionTs,
+ failed.filter(f => f.class === 'content' && !tripped.has(f.source_id) && !runs.get(f.source_id)!.systemic()));
+ if (failed.length) {
+ result.failed = failed.length;
+ result.failures = failed.slice(0, LINK_FAILURE_REPORT_LIMIT).map(f => {
+ const count = recorded.get(`${f.source_id}\0${f.slug}`);
+ return { slug: f.slug, source_id: f.source_id, code: f.code, class: f.class, message: f.message, attempts: count?.attempts ?? 0,
+ held: count?.held ?? false, fix: linkExtractionRetryFix(f.source_id, count?.held ?? false) };
+ });
}
- result.remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs });
+ if (tripped.size) result.systemic = [...tripped].map(([sourceId, error]) => ({ source_id: sourceId, code: error.code, reason: error.reason ?? null,
+ message: error.message, fix: linkExtractionRetryFix(sourceId, false) }));
+ result.remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs, held: 'exclude' });
if (withMentions) {
result.mentions = await runMentionPass(engine, { sourceId: opts.sourceId, signal: opts.signal,
...(opts.timeBudgetMs === undefined ? {} : { deadline: startMs + opts.timeBudgetMs }) });
diff --git a/test/pathological/a1-links-extract.test.ts b/test/pathological/a1-links-extract.test.ts
index 3abc29f30c..ebe9799fca 100644
--- a/test/pathological/a1-links-extract.test.ts
+++ b/test/pathological/a1-links-extract.test.ts
@@ -14,12 +14,12 @@
* transaction (no production seam); the #6808 cases build the real orphan-source state.
*/
import { describe, expect, test } from 'bun:test';
-import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../../src/core/engine.ts';
import { extractManagedStaleLinks, runManagedStaleExtraction } from '../../src/core/persistence/links-maintenance.ts';
import { runPhaseExtractDatabaseOnly } from '../../src/core/cycle/connector-extract.ts';
import { checkLinksExtractionLag } from '../../src/commands/doctor.ts';
-import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { maintenanceAttribution } from '../../src/core/persistence/attribution.ts';
import { effectiveLinkExtractorWatermark } from '../../src/core/link-extraction-watermark.ts';
import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
@@ -79,10 +79,11 @@ async function stamped(engine: BrainEngine, slug: string, sourceId = 'default')
const run = (engine: BrainEngine) => extractManagedStaleLinks(engine, { sourceId: 'default', mentions: false });
const runAll = (engine: BrainEngine) => extractManagedStaleLinks(engine, { mentions: false });
-async function edit(ctx: Parameters<typeof submitPageMutation>[0], engine: BrainEngine, body: string) {
- const expected = (await engine.readPageSnapshot(BAD, { sourceId: 'default' }))!.revision;
- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: BAD, content: `---\ntitle: p-03\ntype: note\n---\n${body}`,
- request_id: randomUUID(), expected_revision: expected } });
+/** An edit of the bad page: a coordinated content write, so the page gets a new knowledge revision. */
+async function edit(engine: BrainEngine, body: string) {
+ const attribution = await maintenanceAttribution(engine);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'],
+ () => tx.executeRaw('UPDATE pages SET compiled_truth=$1, updated_at=now() WHERE source_id=$2 AND slug=$3', [body, 'default', BAD]), attribution));
}
for (const { backend, databaseUrl } of pathologicalArms()) {
@@ -93,7 +94,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
try {
const before = await snapshotItems(engine, 'default');
const first = await expectUnitNotAborted(() => run(engine));
- expect(first.pages).toBe(healthy.length);
+ expect(first.pages).toBe(healthy.length + 1);
expectItemFailure(first.failures?.[0], { key: BAD, code: 'invalid_data', fix: /extract.*--stale.*--source-id.*default/ });
expect({ held: first.failures?.[0]?.held, attempts: first.failures?.[0]?.attempts }).toEqual({ held: false, attempts: 1 });
expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { changed: [BAD], expectProgress: healthy, progressFields: ['links'] });
@@ -163,13 +164,13 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
}, 120_000);
test('A-1 recovery: a held page is retried and lands after --retry-held, an edit or an extractor generation change', async () => {
- await managedBrain(async ({ engine, ctx }) => {
+ await managedBrain(async ({ engine }) => {
const restore = failDerive(engine, new Set([BAD]), contentError);
try { for (let i = 0; i < 3; i++) await run(engine); } finally { restore(); }
expect((await holds(engine)).map(h => h.state)).toEqual(['held']);
const versionTs = await effectiveLinkExtractorWatermark(engine);
expect(await engine.countStalePagesForExtraction({ sourceId: 'default', versionTs, held: 'exclude' })).toBe(0);
- const bumped = new Date(Date.parse(versionTs) + 1000).toISOString();
+ const bumped = new Date(Date.now() + 86_400_000).toISOString();
expect(await engine.countStalePagesForExtraction({ sourceId: 'default', versionTs: bumped, held: 'exclude' })).toBe(PAGES.length + 1);
const retried = await runManagedStaleExtraction(engine, { sourceId: 'default', retryHeld: true, counts: false });
@@ -177,11 +178,11 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
expect(await stamped(engine, BAD)).toBe(true);
expect(await holds(engine)).toEqual([]);
- await edit(ctx, engine, `See [[${TARGET}]] again.`);
+ await edit(engine, `See [[${TARGET}]] again.`);
const again = failDerive(engine, new Set([BAD]), contentError);
try { for (let i = 0; i < 3; i++) await run(engine); } finally { again(); }
expect((await holds(engine)).map(h => h.state)).toEqual(['held']);
- await edit(ctx, engine, `See [[${TARGET}]], edited.`);
+ await edit(engine, `See [[${TARGET}]], edited.`);
const edited = await run(engine);
expect({ pages: edited.pages, failures: edited.failures ?? [] }).toEqual({ pages: 1, failures: [] });
expect(await holds(engine)).toEqual([]);
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index 038e54eda2..aa1c5793be 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -18,4 +18,6 @@ export interface SiteCases {
}
export const CATALOGUE: Record<IsolateSite, SiteCases> = {
+ 'links.extract_stale': { file: 'test/pathological/a1-links-extract.test.ts',
+ item: 'A-1 item: a page whose derive throws is reported', run: 'A-1 run: a run-scoped error at one page stops the unit' },
};
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 12e8291655..d1a4780029 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/a1-links-extract.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts