Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(edge_contradictions): retry judge errors after a 24 h backoff, hold after 3 attempts (#6311)
time-attack6cacfbbbe568
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex dab22b8667..4c3c3330f9 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -120,5 +120,5 @@ rejection of serve-only flags before a brain opens.- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-semantics-pack.ts` installs pack-declared `link_types[].temporal` semantics (union of the active and per-source packs, `state` wins) over the built-in table; `replaceDerivedLinks`, `add_link`/`remove_link` and the extract sweep prime it before deriving or refreshing state (lint rule `link_types_temporal`; `test/link-semantics-pack.test.ts`). `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.-- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. `list` reads `--status` and `--limit` as `--flag value` or `--flag=value`; `--limit` is a positive integer (`intFlagValue`, a bad or missing value is `invalid_params` before any query) capped at 1000 (`test/edge-proposals-list-flags.test.ts`). Budget through the cycle `BudgetMeter`. The CLI's `rows()` normalizes proposal ids at the row boundary (Postgres returns `bigint` as BigInt: a safe integer becomes a number, anything larger an exact string) and `--json` output also passes `bigintToStringReplacer`, so `list/show --json` never crash on Postgres (#6193). Pinned by `test/cycle-edge-contradictions.test.ts`, the managed phase matrix, `test/edge-proposals-json-bigint.test.ts` and `test/e2e/edge-proposals-json-postgres.test.ts`. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`).+- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. `list` reads `--status` and `--limit` as `--flag value` or `--flag=value`; `--limit` is a positive integer (`intFlagValue`, a bad or missing value is `invalid_params` before any query) capped at 1000 (`test/edge-proposals-list-flags.test.ts`). Budget through the cycle `BudgetMeter`. The CLI's `rows()` normalizes proposal ids at the row boundary (Postgres returns `bigint` as BigInt: a safe integer becomes a number, anything larger an exact string) and `--json` output also passes `bigintToStringReplacer`, so `list/show --json` never crash on Postgres (#6193). Pinned by `test/cycle-edge-contradictions.test.ts`, the managed phase matrix, `test/edge-proposals-json-bigint.test.ts` and `test/e2e/edge-proposals-json-postgres.test.ts`. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`). #6311: a judge failure writes an `error` row whose detail is `attempt N/3; <class>: <message>` (provider keys, connection info and labeled credentials redacted, message ≤ 200 chars); skip-known treats it as known for 24 h (`updated_at`), then the pair is judged again and `recordProposal`'s upsert replaces only an `error` row; after `JUDGE_MAX_ATTEMPTS` (3) the detail reads `held after 3 attempts; …` and the pair is skipped until `gbrain edge-proposals retry <id> | --all-held` deletes the row (or the evidence hash changes). No migration. Pinned by `test/cycle-edge-contradictions.test.ts`.- `src/core/link-single-value.ts` — declared single-value relations ([guide](../../guides/temporal-edges.md#declared-single-value-relations)). A pack's `cardinality: one_per_from` on a state relation, built in or declared `temporal: state` (manifest-v1 `LinkTypeSchema`; lint rule `link_types_cardinality` rejects it elsewhere) makes `edge_contradictions` close that type's competing live relationships without a model: `planSingleValueClosures` orders members by latest dated start and applies `closeContradiction` to each consecutive pair (undated and same-date members stay open as proposals). `declaredSingleValueTypes` reads the source's resolved pack; `previewSingleValue` backs the read-only `gbrain schema cardinality-preview`. `dream.single_value.mode` propose (default) / apply / off. Pinned by `test/link-single-value.test.ts`.diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.mdindex d0142fefc4..a230b40590 100644--- a/docs/guides/temporal-edges.md+++ b/docs/guides/temporal-edges.md@@ -235,8 +235,17 @@ gbrain edge-proposals reject 12gbrain edge-proposals undo 12 # removes the line it wrotegbrain edge-proposals undo --all-appliedgbrain edge-proposals date 14 2024-05-01 # record when the newer relationship started+gbrain edge-proposals list --status error # pairs the judge failed on+gbrain edge-proposals retry --all-held # judge held pairs again on the next cycle```+When the judge call fails or its answer is unreadable, the pair gets an `error` row+with the error class and a redacted message (at most 200 characters). The next cycle+skips it for 24 hours, then judges it again; the first readable verdict replaces the+error row. After 3 failed attempts on the same evidence the pair is held: no cycle+pays for it again until `gbrain edge-proposals retry <id>` (or `--all-held`), or until+its evidence changes.+An applied proposal is one timeline line on the subject page:```diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.tsindex 2b7069d9b9..bf440905f5 100644--- a/src/cli/subcommands.ts+++ b/src/cli/subcommands.ts@@ -22,7 +22,7 @@ export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as const;-export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date'] as const;+export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date', 'retry'] as const;export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;export const QUARANTINE_SUBCOMMANDS = ['list', 'clear', 'scan', 'release', 'drop'] as const;export const SCHEMA_SUBCOMMANDS = [diff --git a/src/commands/edge-proposals.ts b/src/commands/edge-proposals.tsindex a18b267d37..9342a204e9 100644--- a/src/commands/edge-proposals.ts+++ b/src/commands/edge-proposals.ts@@ -8,6 +8,7 @@* gbrain edge-proposals reject <id>* gbrain edge-proposals undo <id> | --all-applied* gbrain edge-proposals date <id> <YYYY-MM-DD> date an undated pair: writes "Started <type> [[target]]"+ * gbrain edge-proposals retry <id> | --all-held clear a judge error so the next cycle judges the pair again** Every proposal names the subject page, the relationship that ends, the close* date (from relationship-specific evidence) and why. gbrain never invents a@@ -30,13 +31,14 @@ interface Row {function usage(): string {return [- 'Usage: gbrain edge-proposals <list|show|accept|reject|undo|date> [args]',+ 'Usage: gbrain edge-proposals <list|show|accept|reject|undo|date|retry> [args]',' list [--status <status|all>] [--limit N] [--json] default status: proposed + undated_unresolved',' show <id> [--json]',' accept <id> write the closure line on the subject page and re-derive its links',' reject <id> keep both relationships',' undo <id> | --all-applied remove the closure line(s) this phase wrote',' date <id> <YYYY-MM-DD> record when the newer relationship started (undated pairs), then re-run the dream cycle',+ ' retry <id> | --all-held clear a judge error (held after 3 attempts) so the next dream cycle judges the pair again',].join('\n');}@@ -95,6 +97,11 @@ export async function runEdgeProposals(engine: BrainEngine, args: string[]): Proout(list, list.length ? list.map(describe).join('\n') + '\n\nNext: gbrain edge-proposals accept <id> | reject <id>' : 'No open relationship proposals.');return;}+ if (sub === 'retry' && rest.includes('--all-held')) {+ const cleared = await engine.executeRaw<{ id: number }>(`DELETE FROM link_edge_proposals WHERE status = 'error' AND detail LIKE 'held after %' RETURNING id`);+ out({ cleared: cleared.map(r => normalizeId(r.id)) }, `${cleared.length} held judge error(s) cleared; the next dream cycle judges those pairs again.`);+ return;+ }if (!Number.isSafeInteger(id) || id <= 0) { console.error(`${usage()}\n\nA proposal id is required (gbrain edge-proposals list shows them).`); setCliExitVerdict(2); return; }if (sub === 'show') {const [r] = await rows(engine, 'p.id = $1', [id]);@@ -115,6 +122,12 @@ export async function runEdgeProposals(engine: BrainEngine, args: string[]): Proif (!['applied', 'rejected', 'undone'].includes(result.status)) setCliExitVerdict(1);return;}+ if (sub === 'retry') {+ const cleared = await engine.executeRaw<{ id: number }>(`DELETE FROM link_edge_proposals WHERE id = $1 AND status = 'error' RETURNING id`, [id]);+ if (!cleared.length) { console.error(`No judge error #${id}.`); setCliExitVerdict(1); return; }+ out({ id, status: 'cleared' }, `#${id}: cleared; the next dream cycle judges the pair again.`);+ return;+ }if (sub === 'date') {const date = rest.find(a => /^\d{4}-\d{2}-\d{2}$/.test(a));if (!isCalendarDate(date)) { console.error('date needs a calendar date YYYY-MM-DD: when the newer relationship started.'); setCliExitVerdict(2); return; }diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.tsindex 687f714a38..470438d937 100644--- a/src/core/cycle/edge-contradictions.ts+++ b/src/core/cycle/edge-contradictions.ts@@ -21,6 +21,9 @@* different targets whose combined evidence hash has no proposal yet.* Bounded by max_subjects and the cycle budget meter (max_usd).*/+import { redactProviderKeys } from '../ai/key-redact.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';+import { applyRedaction, planRedaction } from '../secret-scan.ts';import { LINK_EXTRACTION_GENERATION_KEY } from '../line-grammar.ts';import { linkExtractorWatermarkFor } from '../link-extraction-watermark.ts';import { createHash } from 'node:crypto';@@ -266,10 +269,18 @@ export async function runPhaseEdgeContradictions(engine: BrainEngine, opts: Edge// Skip subjects whose every pair already has a proposal for this evidence.const pairs: Array<[CandidateRow, CandidateRow]> = [];for (let i = 0; i < g.rels.length; i++) for (let j = i + 1; j < g.rels.length; j++) pairs.push(ordered(g.rels[i], g.rels[j]));- const known = new Set((await engine.executeRaw<{ a: number; b: number }>(- `SELECT a_to_page_id AS a, b_to_page_id AS b FROM link_edge_proposals+ // #6311: an error row is known while it is in its 24 h backoff or held after JUDGE_MAX_ATTEMPTS.+ const known = new Set<string>();+ const priorAttempts = new Map<string, number>();+ for (const r of await engine.executeRaw<{ a: number; b: number; status: string; detail: string | null; recent: boolean }>(+ `SELECT a_to_page_id AS a, b_to_page_id AS b, status, detail, updated_at > now() - interval '24 hours' AS recent FROM link_edge_proposalsWHERE from_page_id = $1 AND link_type = $2 AND evidence_hash = ANY($3::text[])`,- [g.fromId, g.linkType, pairs.map(([a, b]) => pairHash(a, b))])).map(r => `${r.a}:${r.b}`));+ [g.fromId, g.linkType, pairs.map(([a, b]) => pairHash(a, b))])) {+ const key = `${r.a}:${r.b}`;+ const attempts = r.status === 'error' ? judgeAttempts(r.detail) : 0;+ if (r.status !== 'error' || r.recent || attempts >= JUDGE_MAX_ATTEMPTS) known.add(key);+ else priorAttempts.set(key, attempts);+ }const fresh = pairs.filter(([a, b]) => !known.has(`${a.to_page_id}:${b.to_page_id}`));if (fresh.length === 0) { totals.skipped_known++; continue; }@@ -285,14 +296,22 @@ export async function runPhaseEdgeContradictions(engine: BrainEngine, opts: Edgeif (!check.allowed) { budgetExhausted = true; break; }let verdict: JudgePair[] | null = null;+ let failure = 'malformed: judge output missing or malformed';try { verdict = await judge({ subject: g, relationships, modelHint: model, maxOutputTokens: JUDGE_MAX_OUTPUT_TOKENS }); }- catch (e) { process.stderr.write(`[edge_contradictions] judge failed for ${g.slug}: ${(e as Error).message}\n`); }+ catch (e) {+ failure = judgeFailureDetail(e);+ process.stderr.write(`[edge_contradictions] judge failed for ${g.slug}: ${failure}\n`);+ }totals.judged++;for (const [a, b] of fresh) {const hash = pairHash(a, b);const ia = g.rels.indexOf(a) + 1, ib = g.rels.indexOf(b) + 1;if (!verdict) {- await recordProposal(engine, g, a, b, hash, { status: 'error', model, detail: 'judge output missing or malformed' });+ const attempt = (priorAttempts.get(`${a.to_page_id}:${b.to_page_id}`) ?? 0) + 1;+ const detail = attempt >= JUDGE_MAX_ATTEMPTS+ ? `held after ${attempt} attempts; ${failure}; reset: gbrain edge-proposals retry --all-held`+ : `attempt ${attempt}/${JUDGE_MAX_ATTEMPTS}; ${failure}`;+ await recordProposal(engine, g, a, b, hash, { status: 'error', model, detail });totals.errors++;continue;}@@ -392,6 +411,23 @@ async function runDeclaredSingleValue(return { handled, totals };}+/** #6311: judge attempts per evidence key; the 24 h backoff spaces them, then the pair is held until `edge-proposals retry`. */+export const JUDGE_MAX_ATTEMPTS = 3;++/** Attempts an error row records (`attempt N/3; …` or `held after N attempts; …`); a legacy row counts as one. */+function judgeAttempts(detail: string | null): number {+ const m = /^(?:attempt (\d+)\/\d+|held after (\d+) attempts);/.exec(detail ?? '');+ return m ? Number(m[1] ?? m[2]) : 1;+}++/** The stored failure: error class plus a redacted message of at most 200 characters. */+function judgeFailureDetail(e: unknown): string {+ const name = e instanceof Error ? e.name || 'Error' : 'Error';+ const raw = redactConnectionInfo(redactProviderKeys(e instanceof Error ? e.message : String(e), process.env));+ const message = applyRedaction(planRedaction(raw, { labeledCredentials: true })).replace(/\s+/g, ' ').trim();+ return `${name}: ${message.length > 200 ? `${message.slice(0, 199)}…` : message}`;+}+async function recordProposal(engine: BrainEngine, g: SubjectGroup, a: CandidateRow, b: CandidateRow, hash: string,p: { status: string; model: string; confidence?: number | null; endingTo?: number; closeDate?: string; bornClosed?: boolean; line?: string; detail?: string },@@ -400,7 +436,11 @@ async function recordProposal(`INSERT INTO link_edge_proposals (source_id, from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash, status,ending_to_page_id, close_date, born_closed, model, confidence, generated_line, detail)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::date, $10, $11, $12, $13, $14)- ON CONFLICT (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash) DO NOTHING+ ON CONFLICT (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash) DO UPDATE SET+ status = EXCLUDED.status, ending_to_page_id = EXCLUDED.ending_to_page_id, close_date = EXCLUDED.close_date,+ born_closed = EXCLUDED.born_closed, model = EXCLUDED.model, confidence = EXCLUDED.confidence,+ generated_line = EXCLUDED.generated_line, detail = EXCLUDED.detail, updated_at = now()+ WHERE link_edge_proposals.status = 'error'RETURNING id`,[g.sourceId, g.fromId, Number(a.to_page_id), Number(b.to_page_id), g.linkType, hash, p.status,p.endingTo ?? null, p.closeDate ?? null, p.bornClosed ?? false, p.model, p.confidence ?? null, p.line ?? null, p.detail ?? null]);diff --git a/test/cycle-edge-contradictions.test.ts b/test/cycle-edge-contradictions.test.tsindex ca916175c8..27f791ac26 100644--- a/test/cycle-edge-contradictions.test.ts+++ b/test/cycle-edge-contradictions.test.ts@@ -111,6 +111,64 @@ describe('edge_contradictions', () => {expect(parseEdgeJudgeOutput('{"pairs":[{"a":1,"b":2,"conflict":true,"confidence":2}]}', 2)).toEqual([{ a: 1, b: 2, conflict: true, confidence: 1 }]);});+ describe('judge errors retry with a bounded backoff (#6311)', () => {+ const age = () => engine.executeRaw(`UPDATE link_edge_proposals SET updated_at = now() - interval '25 hours' WHERE status = 'error'`);+ const errorRows = () => engine.executeRaw<{ status: string; detail: string }>(`SELECT status, detail FROM link_edge_proposals ORDER BY id`);++ test('a transient error is skipped inside the backoff, then the next verdict replaces it', async () => {+ await engine.setConfig('dream.edge_contradictions.mode', 'propose');+ await seed(DATED);+ calls = 0;+ await runPhaseEdgeContradictions(engine, { judge: counting(async () => { throw new Error('upstream 529 overloaded'); }) });+ expect((await errorRows())[0]).toMatchObject({ status: 'error', detail: 'attempt 1/3; Error: upstream 529 overloaded' });+ await runPhaseEdgeContradictions(engine, { judge: counting(conflict) });+ expect(calls).toBe(1);+ await age();+ const r = await runPhaseEdgeContradictions(engine, { judge: counting(conflict) });+ expect(calls).toBe(2);+ expect(r.totals).toMatchObject({ proposed: 1 });+ expect((await proposals()).map(p => p.status)).toEqual(['proposed']);+ });++ test('three failed attempts hold the pair; no fourth call until retry --all-held', async () => {+ await engine.setConfig('dream.edge_contradictions.mode', 'propose');+ await seed(DATED);+ calls = 0;+ const failing = counting(async () => null);+ for (let i = 0; i < 3; i++) { await runPhaseEdgeContradictions(engine, { judge: failing }); await age(); }+ expect(calls).toBe(3);+ expect((await errorRows())[0].detail).toStartWith('held after 3 attempts; malformed');+ await runPhaseEdgeContradictions(engine, { judge: failing });+ expect(calls).toBe(3);+ const { runEdgeProposals } = await import('../src/commands/edge-proposals.ts');+ const log = console.log; console.log = () => {};+ try { await runEdgeProposals(engine, ['retry', '--all-held']); } finally { console.log = log; }+ await runPhaseEdgeContradictions(engine, { judge: counting(conflict) });+ expect(calls).toBe(4);+ expect((await proposals()).map(p => p.status)).toEqual(['proposed']);+ });++ test('a non-error row is never replaced', async () => {+ await seed(DATED);+ await runPhaseEdgeContradictions(engine, { judge: async () => [{ a: 1, b: 2, conflict: false, confidence: 0.9 }] });+ await engine.executeRaw(`UPDATE link_edge_proposals SET updated_at = now() - interval '25 hours'`);+ calls = 0;+ await runPhaseEdgeContradictions(engine, { judge: counting(conflict) });+ expect(calls).toBe(0);+ expect((await proposals()).map(p => p.status)).toEqual(['compatible']);+ });++ test('the stored detail is the error class and a redacted message of at most 200 characters', async () => {+ await seed(DATED);+ const key = 'sk-ant-api03-' + 'Ab1Cd2Ef3Gh4'.repeat(8) + 'AA';+ await runPhaseEdgeContradictions(engine, { judge: async () => { throw new TypeError(`bad key ${key} ` + 'x'.repeat(400)); } });+ const [row] = await errorRows();+ expect(row.detail).toStartWith('attempt 1/3; TypeError: ');+ expect(row.detail).not.toContain(key);+ expect(row.detail.length).toBeLessThanOrEqual('attempt 1/3; TypeError: '.length + 200);+ });+ });+test('zero budget spends nothing', async () => {await seed(DATED);await engine.setConfig('dream.edge_contradictions.max_usd', '0');