Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(test): root-cause the two flakes the PR stress lane found
garrytanc02fe160fca7
diff --git a/src/core/line-grammar.ts b/src/core/line-grammar.tsindex a757445b1f..7a09258962 100644--- a/src/core/line-grammar.ts+++ b/src/core/line-grammar.ts@@ -94,7 +94,32 @@ const LINE_TEXT_MAX = 160;// A trailing `[Source: ...]` citation (plain or wrapping a markdown link) is// part of the brain's quality convention, not of the grammar: it is set aside// before a line is read.-const TRAILING_CITATION_RE = /\[Source:(?:[^\][]|\[[^\]]*\]\([^)]*\))*\]\s*$/i;+// Same language as /\[Source:(?:[^\][]|\[[^\]]*\]\([^)]*\))*\]\s*$/i, scanned by hand: on a long+// unclosed body the regex left JSC's JIT for its backtracking interpreter, a 20x cost step at ~100k chars.+function citationBodyEnd(text: string, from: number): number {+ let i = from;+ while (i < text.length) {+ const c = text[i];+ if (c === ']') return i;+ if (c !== '[') { i++; continue; }+ const close = text.indexOf(']', i + 1);+ if (close < 0 || text[close + 1] !== '(') return -1;+ const paren = text.indexOf(')', close + 2);+ if (paren < 0) return -1;+ i = paren + 1;+ }+ return -1;+}++/** `text` without a trailing `[Source: ...]` citation (plain or wrapping a markdown link). */+export function stripTrailingCitation(text: string): string {+ const lower = text.toLowerCase();+ for (let at = lower.indexOf('[source:'); at >= 0; at = lower.indexOf('[source:', at + 1)) {+ const end = citationBodyEnd(text, at + 8);+ if (end >= 0 && text.slice(end + 1).trim() === '') return text.slice(0, at);+ }+ return text;+}/** Index of the first char at or after each position that is in `stops`, or `text.length`. */function nextStop(text: string, stops: string): Int32Array {@@ -256,8 +281,8 @@ export function parseLineGrammar(text: string, opts: { declaredTypes?: ReadonlyS// Masking keeps offsets, so the item's content sits at the same place in// the original line; structure is read from the masked text (links inside// code are not links), the fact text from the original.- const visibleContent = item[2].replace(TRAILING_CITATION_RE, '').trim();- const content = line.slice(line.length - item[2].length).replace(TRAILING_CITATION_RE, '').trim();+ const visibleContent = stripTrailingCitation(item[2]).trim();+ const content = stripTrailingCitation(line.slice(line.length - item[2].length)).trim();if (!visibleContent || visibleContent.startsWith('\\')) continue;const note = (reason: GrammarReason, message: string) => result.diagnostics.push({ line: lineNo, reason, text: lineText(line), message });if (visibleContent.startsWith('[')) {diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 30c5d26b96..11c85739a6 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -114,7 +114,9 @@ export class PersistenceConsumer {constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number;/** Claim renewal cadence (default 10 s); each renewal runs under the `phaseMs` deadline. */- renewalIntervalMs?: number; onError?: (error: unknown) => void;+ renewalIntervalMs?: number;+ /** Claim lease length for single-request claims (default 30 s). A test seam, like the timings above. */+ claimLeaseMs?: number; onError?: (error: unknown) => void;onSettled?: (row: WriteRequest) => void;/** Engine graduation drain: claim, recover and publish requests only; effect, projection, topology and maintenance workers never start. */requestsOnly?: boolean } = {}) {@@ -374,7 +376,7 @@ export class PersistenceConsumer {while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {const claimed = laneClaim();try {- const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, 30_000, [...attemptedRoots]));+ const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, this.opts.claimLeaseMs ?? 30_000, [...attemptedRoots]));if (!row) break;if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }const key = row.worktree_id ?? `db:${row.source_incarnation}`;@@ -541,7 +543,7 @@ export class PersistenceConsumer {}, budget) : undefined;const clock = startClaimPhase();const lease = startClaimLease(- signal => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,+ signal => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, this.opts.claimLeaseMs ?? 30_000,this.engine.kind === 'postgres' ? signal : undefined, claimPhaseStamp(clock, row.execution_token)),this.leaseTiming(), () => abort.abort({ code: 'claim_lost' }));const releaseReason = () => !lease.held ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping';diff --git a/test/line-grammar.test.ts b/test/line-grammar.test.tsindex fcd5ba070d..6dfa4cb2ee 100644--- a/test/line-grammar.test.ts+++ b/test/line-grammar.test.ts@@ -195,13 +195,16 @@ test('long comma, bracket and space runs are parsed in linear time (#6186)', ()'- [idea] a' + ' '.repeat(n) + 'b', '- [idea] a [Source:' + ' '.repeat(n) + 'b'].join('\\n');const time = (n) => { const text = lines(n); const t = performance.now(); parseLineGrammar(text); return performance.now() - t; };time(1000);- const small = Math.min(time(100_000), time(100_000)); const large = Math.min(time(200_000), time(200_000));- console.log(JSON.stringify({ small, large }));`;+ // Interleaved samples so CPU contention hits both sizes alike; n vs 4n so linear (x4) and quadratic (x16)+ // sit a factor of 2 either side of the bound.+ const smalls = [], larges = [];+ for (let i = 0; i < 5; i++) { smalls.push(time(50_000)); larges.push(time(200_000)); }+ console.log(JSON.stringify({ small: Math.min(...smalls), large: Math.min(...larges) }));`;const run = spawnSync(process.execPath, ['-e', script], { timeout: 5_000, encoding: 'utf-8' });expect(run.error?.message ?? '', 'the 200k-character lines did not finish within 5 s').toBe('');expect(run.status, run.stderr).toBe(0);const { small, large } = JSON.parse(run.stdout.trim()) as { small: number; large: number };- expect(large / Math.max(small, 1)).toBeLessThan(3);+ expect(large / Math.max(small, 1)).toBeLessThan(8);}, 30_000);test('a qualifier with more than one comma is refused as a range (#6186)', () => {diff --git a/test/persistence-write-stall.test.ts b/test/persistence-write-stall.test.tsindex b831c9e8b4..5fb42515f8 100644--- a/test/persistence-write-stall.test.ts+++ b/test/persistence-write-stall.test.ts@@ -50,7 +50,11 @@ async function scenario(engine: BrainEngine, config: HarnessConfig) {installFaultHook(async (point, detail) => { if (point === 'consumer:prepared' && detail.requestId === stuck.request_id) await hang.promise; });const errors: unknown[] = [];const consumer = new PersistenceConsumer(engine, { engine: engine.kind }, async (_engine, row) => prepared(row, sources),- { hostId: config.hostId, concurrency: 1, pollMs: 20, renewalIntervalMs: 20, phaseMs: 2_000, onError: error => errors.push(error) });+ { hostId: config.hostId, concurrency: 1, pollMs: 20, renewalIntervalMs: 20, phaseMs: 2_000, onError: error => errors.push(error),+ // The test moves the clock 11 minutes ahead. A 30 s lease would let the consumer's own expired-claims sweep requeue the+ // stuck claim before the next renewal (a race that hangs the frozen-clock waitFor); a day-long lease keeps it live, as+ // an owner renewing for 11 real minutes would.+ claimLeaseMs: 86_400_000 });try {consumer.start();await waitFor(async () => (await engine.executeRaw<{ p: string | null }>("SELECT claim_phase->>'phase' AS p FROM persistence_requests WHERE id=$1::uuid", [stuck.id]))[0]?.p === 'publishing',