Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(edge-proposals): normalize BigInt ids so list/show --json work on Postgres (#6193)

garrytan9b0ffe7ea596
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index da8def9a43..683f0e3971 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`. Budget through the cycle `BudgetMeter`. Pinned by `test/cycle-edge-contradictions.test.ts` and the managed phase matrix. `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`. 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/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/src/commands/edge-proposals.ts b/src/commands/edge-proposals.ts
index c63e8bac27..48acc565b6 100644
--- a/src/commands/edge-proposals.ts
+++ b/src/commands/edge-proposals.ts
@@ -18,11 +18,12 @@ import { applyEdgeProposal, rejectEdgeProposal, undoEdgeProposal, DREAM_TIMELINE
import { isCalendarDate, dateKey } from '../core/link-validity.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { EDGE_PROPOSALS_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';
+import { bigintToStringReplacer } from '../core/utils.ts';
const STATUSES = ['proposed', 'applied', 'rejected', 'undone', 'stale', 'reverted_by_user', 'undated_unresolved', 'ambiguous_same_date', 'compatible', 'error'];
interface Row {
- id: number; status: string; link_type: string; subject: string; a_target: string; b_target: string; ending: string | null;
+ id: number | string; status: string; link_type: string; subject: string; a_target: string; b_target: string; ending: string | null;
close_date: unknown; born_closed: boolean; model: string | null; confidence: number | null; generated_line: string | null; created_at: unknown;
}
@@ -38,14 +39,21 @@ function usage(): string {
].join('\n');
}
+/** Postgres returns `bigint` ids as BigInt (#6193): a safe integer stays a number, anything larger an exact string. */
+function normalizeId(id: unknown): number | string {
+ const n = Number(id);
+ return Number.isSafeInteger(n) ? n : String(id);
+}
+
async function rows(engine: BrainEngine, where: string, params: unknown[], limit = 50): Promise<Row[]> {
- return engine.executeRaw<Row>(
+ const raw = await engine.executeRaw<Row>(
`SELECT p.id, p.status, p.link_type, f.slug AS subject, ta.slug AS a_target, tb.slug AS b_target, te.slug AS ending,
p.close_date::text AS close_date, p.born_closed, p.model, p.confidence, p.generated_line, p.created_at
FROM link_edge_proposals p
JOIN pages f ON f.id = p.from_page_id JOIN pages ta ON ta.id = p.a_to_page_id JOIN pages tb ON tb.id = p.b_to_page_id
LEFT JOIN pages te ON te.id = p.ending_to_page_id
WHERE ${where} ORDER BY p.created_at DESC, p.id DESC LIMIT ${Math.max(1, Math.min(1000, limit))}`, params);
+ return raw.map(r => ({ ...r, id: normalizeId(r.id) }));
}
function describe(r: Row): string {
@@ -69,7 +77,7 @@ export async function runEdgeProposals(engine: BrainEngine, args: string[]): Pro
const json = rest.includes('--json');
const flag = (name: string) => { const i = rest.indexOf(name); return i >= 0 ? rest[i + 1] : undefined; };
const id = Number(rest.find(a => /^\d+$/.test(a)));
- const out = (value: unknown, text: string) => console.log(json ? JSON.stringify(value, null, 2) : text);
+ const out = (value: unknown, text: string) => console.log(json ? JSON.stringify(value, bigintToStringReplacer, 2) : text);
if (!sub) { printUsage(); return; }
if (sub === 'list') {
diff --git a/test/e2e/edge-proposals-json-postgres.test.ts b/test/e2e/edge-proposals-json-postgres.test.ts
new file mode 100644
index 0000000000..06fe9145a8
--- /dev/null
+++ b/test/e2e/edge-proposals-json-postgres.test.ts
@@ -0,0 +1,60 @@
+/**
+ * #6193: on Postgres `link_edge_proposals.id` is BIGSERIAL and the driver
+ * returns it as BigInt; `edge-proposals list --json` and `show <id> --json`
+ * must print one parseable document with a numeric id (the form `show` takes).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from '../helpers/cli-spawn.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+
+const describeDatabase = hasDatabase() ? describe : describe.skip;
+
+describeDatabase('#6193 edge-proposals --json on Postgres BigInt ids', () => {
+ let engine: PostgresEngine;
+ let home: string;
+ let proposalId: number;
+
+ beforeAll(async () => {
+ engine = await setupDB();
+ await engine.executeRaw('DELETE FROM link_edge_proposals');
+ for (const slug of ['people/alice-example', 'companies/acme-example', 'companies/widget-example']) {
+ await engine.putPage(slug, { type: slug.startsWith('people/') ? 'person' : 'company', title: slug, compiled_truth: 'Fixture page.' });
+ }
+ const ids = await engine.executeRaw<{ slug: string; id: number }>(
+ `SELECT slug, id FROM pages WHERE slug IN ('people/alice-example','companies/acme-example','companies/widget-example')`);
+ const id = (slug: string) => ids.find(r => r.slug === slug)!.id;
+ const [row] = await engine.executeRaw<{ id: unknown }>(
+ `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)
+ VALUES ('default', $1, $2, $3, 'works_at', 'e2e-6193', 'proposed', $2, '2024-05-01') RETURNING id`,
+ [id('people/alice-example'), id('companies/acme-example'), id('companies/widget-example')]);
+ expect(typeof row.id).toBe('bigint');
+ proposalId = Number(row.id);
+ home = mkdtempSync(join(tmpdir(), 'gbrain-edge-proposals-pg-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: process.env.DATABASE_URL }));
+ }, 60_000);
+
+ afterAll(async () => {
+ await engine.executeRaw('DELETE FROM link_edge_proposals');
+ await teardownDB();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('list --json prints parseable rows with a numeric id', async () => {
+ const r = await runCli(['edge-proposals', 'list', '--json'], { home, cwd: home, timeoutMs: 60_000 });
+ expect(r.exitCode, r.stderr).toBe(0);
+ const rows = JSON.parse(r.stdout) as Array<Record<string, unknown>>;
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ id: proposalId, status: 'proposed', subject: 'people/alice-example', ending: 'companies/acme-example' });
+ }, 90_000);
+
+ test('show <id> --json prints one parseable document with a numeric id', async () => {
+ const r = await runCli(['edge-proposals', 'show', String(proposalId), '--json'], { home, cwd: home, timeoutMs: 60_000 });
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout)).toMatchObject({ id: proposalId, close_date: '2024-05-01' });
+ }, 90_000);
+});
diff --git a/test/edge-proposals-json-bigint.test.ts b/test/edge-proposals-json-bigint.test.ts
new file mode 100644
index 0000000000..a18ea94779
--- /dev/null
+++ b/test/edge-proposals-json-bigint.test.ts
@@ -0,0 +1,62 @@
+/**
+ * #6193: `edge-proposals list/show --json` must not crash when the driver
+ * returns BigInt ids (Postgres `bigint` columns). The CLI normalizes ids at
+ * the row boundary: a safe integer becomes a number, anything larger a string.
+ */
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { runEdgeProposals } from '../src/commands/edge-proposals.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+function row(id: bigint) {
+ return {
+ id, status: 'proposed', link_type: 'works_at', subject: 'people/alice-example',
+ a_target: 'companies/acme-example', b_target: 'companies/widget-example', ending: 'companies/acme-example',
+ close_date: '2024-05-01', born_closed: false, model: 'test-model', confidence: 0.9,
+ generated_line: 'left [Acme](companies/acme-example)', created_at: new Date('2026-10-01T00:00:00Z'),
+ };
+}
+
+function fakeEngine(rows: Array<ReturnType<typeof row>>): BrainEngine {
+ return { kind: 'postgres', executeRaw: async () => rows } as unknown as BrainEngine;
+}
+
+async function capture(engine: BrainEngine, args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ const err = spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ await runEdgeProposals(engine, args);
+ } finally {
+ log.mockRestore();
+ err.mockRestore();
+ }
+ return lines.join('\n');
+}
+
+afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });
+
+describe('#6193 edge-proposals --json with BigInt ids', () => {
+ test('list --json parses and keeps a safe id numeric', async () => {
+ const out = await capture(fakeEngine([row(1n)]), ['list', '--json']);
+ const parsed = JSON.parse(out);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0].id).toBe(1);
+ expect(currentExitCode()).toBe(0);
+ });
+
+ test('show <id> --json parses and keeps a safe id numeric', async () => {
+ const out = await capture(fakeEngine([row(1n)]), ['show', '1', '--json']);
+ expect(JSON.parse(out).id).toBe(1);
+ });
+
+ test('an id beyond the safe integer range becomes an exact string', async () => {
+ const out = await capture(fakeEngine([row(9007199254740993n)]), ['list', '--json']);
+ expect(JSON.parse(out)[0].id).toBe('9007199254740993');
+ });
+
+ test('text mode prints the normalized id', async () => {
+ const out = await capture(fakeEngine([row(7n)]), ['list']);
+ expect(out).toContain('#7 [proposed]');
+ });
+});