Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(edge-proposals): list reads --limit and --status in both spellings; a bad --limit is a usage error before any query (#6249)
time-attack9a51769be3c7
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 7aaa55bc29..d5b1347abc 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`. 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`).- `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.tsindex 48acc565b6..a18b267d37 100644--- a/src/commands/edge-proposals.ts+++ b/src/commands/edge-proposals.ts@@ -17,6 +17,7 @@ import type { BrainEngine } from '../core/engine.ts';import { applyEdgeProposal, rejectEdgeProposal, undoEdgeProposal, DREAM_TIMELINE_SOURCE } from '../core/cycle/edge-contradictions.ts';import { isCalendarDate, dateKey } from '../core/link-validity.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { intFlagValue } from '../cli/flag-values.ts';import { EDGE_PROPOSALS_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';import { bigintToStringReplacer } from '../core/utils.ts';@@ -75,7 +76,11 @@ export async function runEdgeProposals(engine: BrainEngine, args: string[]): Proif (subcommandHelpRequested(args, ROUTERS['edge-proposals'])) { printUsage(); return; }const [sub, ...rest] = args as [(typeof EDGE_PROPOSALS_SUBCOMMANDS)[number] | undefined, ...string[]];const json = rest.includes('--json');- const flag = (name: string) => { const i = rest.indexOf(name); return i >= 0 ? rest[i + 1] : undefined; };+ const flag = (name: string) => {+ const at = rest.findIndex(a => a === name || a.startsWith(`${name}=`));+ if (at < 0) return undefined;+ return rest[at] === name ? rest[at + 1] ?? '' : rest[at]!.slice(name.length + 1);+ };const id = Number(rest.find(a => /^\d+$/.test(a)));const out = (value: unknown, text: string) => console.log(json ? JSON.stringify(value, bigintToStringReplacer, 2) : text);@@ -83,8 +88,10 @@ export async function runEdgeProposals(engine: BrainEngine, args: string[]): Proif (sub === 'list') {const status = flag('--status');if (status && status !== 'all' && !STATUSES.includes(status)) { console.error(`Unknown status ${status}. One of: ${STATUSES.join(', ')}, all`); setCliExitVerdict(2); return; }- const list = status === 'all' ? await rows(engine, 'TRUE', [], Number(flag('--limit') ?? 50))- : await rows(engine, 'p.status = ANY($1::text[])', [status ? [status] : ['proposed', 'undated_unresolved']], Number(flag('--limit') ?? 50));+ const rawLimit = flag('--limit');+ const limit = rawLimit === undefined ? 50 : intFlagValue(rawLimit, '--limit', { min: 1, example: 50 });+ const list = status === 'all' ? await rows(engine, 'TRUE', [], limit)+ : await rows(engine, 'p.status = ANY($1::text[])', [status ? [status] : ['proposed', 'undated_unresolved']], limit);out(list, list.length ? list.map(describe).join('\n') + '\n\nNext: gbrain edge-proposals accept <id> | reject <id>' : 'No open relationship proposals.');return;}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 273df8fcbd..34632c3eaa 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -290,6 +290,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.103.0', text: 'Filtered vector search on Postgres runs pgvector iterative scans in relaxed_order, which keeps closer in-filter matches strict order dropped; `gbrain config set search.hnsw_iterative_scan strict_order` and a restart of serve and autopilot restore the old mode.' },{ since: '0.60.103.0', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },{ since: '0.60.103.0', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },+ { since: 'WAVE12', text: '`gbrain edge-proposals list` now reads `--limit=N` and `--status=X` (they were ignored), and a `--limit` that is not a whole number from 1 up exits 2 instead of failing in the database or silently becoming 1.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/test/edge-proposals-list-flags.test.ts b/test/edge-proposals-list-flags.test.tsnew file mode 100644index 0000000000..dea4ca7400--- /dev/null+++ b/test/edge-proposals-list-flags.test.ts@@ -0,0 +1,96 @@+/**+ * #6249: `edge-proposals list` reads `--limit` and `--status` in both the+ * `--flag value` and `--flag=value` spellings. A malformed, missing or+ * out-of-range `--limit` is a usage error (`invalid_params`) before any query,+ * instead of reaching the database as `LIMIT NaN`; a valid value above 1000 is+ * still capped. `--status=applied` lists applied proposals instead of the+ * default set.+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { runEdgeProposals } from '../src/commands/edge-proposals.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import type { BrainEngine } from '../src/core/engine.ts';++interface Recorded { sql: string; params: unknown[] }++function recordingEngine(): { engine: BrainEngine; calls: Recorded[] } {+ const calls: Recorded[] = [];+ const engine = {+ kind: 'pglite',+ executeRaw: async (sql: string, params: unknown[] = []) => { calls.push({ sql, params }); return []; },+ } as unknown as BrainEngine;+ return { engine, calls };+}++async function run(args: string[]): Promise<{ calls: Recorded[]; error: unknown }> {+ const { engine, calls } = recordingEngine();+ const log = spyOn(console, 'log').mockImplementation(() => {});+ const err = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runEdgeProposals(engine, args);+ return { calls, error: undefined };+ } catch (error) {+ return { calls, error };+ } finally {+ log.mockRestore();+ err.mockRestore();+ }+}++afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });++describe('#6249 edge-proposals list --limit', () => {+ const bad: Array<[string, string | undefined]> = [+ ['abc', 'abc'], ['12abc', '12abc'], ['1.5', '1.5'], ['0', '0'], ['-2', '-2'],+ ['an unsafe integer', '9007199254740992'], ['a missing value', undefined], ['the next flag', '--json'],+ ];+ for (const [name, value] of bad) {+ test(`refuses ${name} in both spellings, on both query branches, before any query`, async () => {+ const spellings = [['--limit', ...(value === undefined ? [] : [value])], [`--limit=${value ?? ''}`]];+ for (const status of [[], ['--status', 'all']]) {+ for (const limit of spellings) {+ const { calls, error } = await run(['list', ...status, ...limit]);+ expect(error).toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--limit') });+ expect(calls).toEqual([]);+ }+ }+ });+ }++ const good: Array<[string[], number]> = [+ [[], 50], [['--limit', '5'], 5], [['--limit=7'], 7], [['--limit', '1000'], 1000],+ [['--limit', '5000'], 1000], [['--status', 'all', '--limit=7'], 7],+ ];+ for (const [args, limit] of good) {+ test(`${JSON.stringify(args)} queries with LIMIT ${limit}`, async () => {+ const { calls, error } = await run(['list', ...args]);+ expect(error).toBeUndefined();+ expect(calls).toHaveLength(1);+ expect(calls[0]!.sql).toEndWith(`LIMIT ${limit}`);+ });+ }+});++describe('#6249 edge-proposals list --status', () => {+ test('--status=applied lists applied proposals', async () => {+ const { calls } = await run(['list', '--status=applied']);+ expect(calls).toHaveLength(1);+ expect(calls[0]!.params).toEqual([['applied']]);+ });++ test('--status applied (separate value) still works', async () => {+ const { calls } = await run(['list', '--status', 'applied']);+ expect(calls[0]!.params).toEqual([['applied']]);+ });++ test('--status=all lists every status', async () => {+ const { calls } = await run(['list', '--status=all']);+ expect(calls[0]!.params).toEqual([]);+ });++ test('--status=bogus is refused before any query', async () => {+ const { calls } = await run(['list', '--status=bogus']);+ expect(calls).toEqual([]);+ expect(process.exitCode).toBe(2);+ });+});