Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Record rows: keep amends/supersedes targets inside the caller's sources; trim core-search-1 under the 60 KB cap

garrytan65825a876b8c
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 821b662710..2080ec38cd 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -75,6 +75,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.
-- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults. Backlink counts, adjacency, relational fanout, chain hops and chain degree skip non-ranking link types (`rankingLinkSql`, `src/core/link-ranking-policy.ts`). `readChainHop` (behind `BrainEngine.relationalChainHop`) is one oriented, authorized, bounded expansion step of a multi-hop chain: fenced LATERAL link scans and primary-key page lookups (a statistics-less planner otherwise joins pages on source_id quadratically), relationship page-type signatures (`stored` / `flipped` / `uncertain`; frontmatter, manual and attendance-section links keep stored direction), logical-edge collapse, `neighborCap` per frontier page, degree saturating at `CHAIN_DEGREE_SATURATION` (300) link rows, and edge context only from pages whose text the caller may read. Pinned by `test/relational-chain.test.ts`, `test/relational-chain-hub.slow.test.ts` and the engine-parity chain case.
+- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults. Link reads skip non-ranking link types (`rankingLinkSql`). `readChainHop` (behind `BrainEngine.relationalChainHop`) is one oriented, authorized, bounded expansion step of a multi-hop chain: fenced LATERAL link scans and primary-key page lookups (a statistics-less planner otherwise joins pages on source_id quadratically), relationship page-type signatures (`stored` / `flipped` / `uncertain`; frontmatter, manual and attendance-section links keep stored direction), logical-edge collapse, `neighborCap` per frontier page, degree saturating at `CHAIN_DEGREE_SATURATION` (300) link rows, and edge context only from pages whose text the caller may read. Pinned by `test/relational-chain.test.ts`, `test/relational-chain-hub.slow.test.ts` and the engine-parity chain case.
- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.
diff --git a/src/core/mentions/referrers.ts b/src/core/mentions/referrers.ts
index 7f8bba773c..0ff3b78938 100644
--- a/src/core/mentions/referrers.ts
+++ b/src/core/mentions/referrers.ts
@@ -373,14 +373,15 @@ export async function readPageStatusByRef(engine: BrainEngine, refs: Array<{ sou
/**
* The record metadata of referring pages: `page_status` from frontmatter,
- * `amends` and `supersedes` links to pages the caller can see (link origins
- * under the same privacy rule as the referrer read), and each amends link's
+ * `amends` and `supersedes` links to pages the caller can see (targets in the
+ * caller's referrer sources, link origins under the same privacy rule as the
+ * referrer read), and each amends link's
* `since` from the temporal relationship state for the caller's scope
* (`world` for untrusted callers, so a date whose only evidence is private
* stays hidden).
*/
export async function readRecordMetadata(engine: BrainEngine, pageIds: number[],
- scope: Pick<ReferrerScope, 'excludePrivate' | 'includeQuarantined'>): Promise<Map<number, RecordMetadata>> {
+ scope: Pick<ReferrerScope, 'referrerSources' | 'excludePrivate' | 'includeQuarantined'>): Promise<Map<number, RecordMetadata>> {
const out = new Map<number, RecordMetadata>();
if (!pageIds.length) return out;
const linkPriv = scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '';
@@ -391,11 +392,11 @@ export async function readRecordMetadata(engine: BrainEngine, pageIds: number[],
engine.executeRaw<{ from_id: number; slug: string; link_type: string; since: string | null }>(
`SELECT DISTINCT l.from_page_id AS from_id, t.slug, l.link_type,
CASE WHEN l.link_type = 'amends' THEN to_char(r.first_start, 'YYYY-MM-DD') END AS since
- FROM links l JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL${targetPriv}${targetQuarantine}
+ FROM links l JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL AND t.source_id = ANY($3::text[])${targetPriv}${targetQuarantine}
LEFT JOIN link_relationships r ON r.from_page_id = l.from_page_id AND r.to_page_id = l.to_page_id
AND r.link_type = l.link_type AND r.scope = $2
WHERE l.from_page_id = ANY($1::int[]) AND l.link_type IN ('amends', 'supersedes')${linkPriv}
- ORDER BY l.from_page_id, t.slug`, [pageIds, scope.excludePrivate ? 'world' : 'all']).catch(() => []),
+ ORDER BY l.from_page_id, t.slug`, [pageIds, scope.excludePrivate ? 'world' : 'all', scope.referrerSources]).catch(() => []),
]);
for (const row of status) {
const value = pageStatusValue(row.status);
@@ -500,7 +501,7 @@ export async function readTargetReferences(engine: BrainEngine,
}
async function hydrateRecords(engine: BrainEngine, rows: RecordCandidate[],
- scope: Pick<ReferrerScope, 'excludePrivate' | 'includeQuarantined'>): Promise<RecordRow[]> {
+ scope: Pick<ReferrerScope, 'referrerSources' | 'excludePrivate' | 'includeQuarantined'>): Promise<RecordRow[]> {
if (!rows.length) return [];
const ids = [...new Set(rows.map(r => Number(r.id)))];
const [pages, meta] = await Promise.all([
diff --git a/test/e2e/entity-records-postgres.test.ts b/test/e2e/entity-records-postgres.test.ts
index 633a4a87cf..aee1ec67d6 100644
--- a/test/e2e/entity-records-postgres.test.ts
+++ b/test/e2e/entity-records-postgres.test.ts
@@ -32,4 +32,5 @@ d('entity records (Postgres)', () => {
test('records pack last under 1,500 and 2,000 token budgets; newer mentions unaffected', () => S.recordsPackLast(engine), 60_000);
test('F3 page_status on get_backlinks and context_pack rows: additive, bounded, hidden pages none; its key removes it there', () => S.pageStatusOnRows(engine), 60_000);
test('F1 on, F3 off: record rows keep page_status on initial and continued outputs; other rows have none', () => S.recordsKeepPageStatusWithRowKeyOff(engine), 60_000);
+ test('amends and supersedes targets outside the caller\'s sources never reach record rows', () => S.recordLinksStayInSources(engine), 60_000);
});
diff --git a/test/entity-records.test.ts b/test/entity-records.test.ts
index fc46b24c5e..f393c611c2 100644
--- a/test/entity-records.test.ts
+++ b/test/entity-records.test.ts
@@ -32,4 +32,5 @@ describe('entity records (PGLite)', () => {
test('records pack last under 1,500 and 2,000 token budgets; newer mentions unaffected', () => S.recordsPackLast(engine), 60_000);
test('F3 page_status on get_backlinks and context_pack rows: additive, bounded, hidden pages none; its key removes it there', () => S.pageStatusOnRows(engine), 60_000);
test('F1 on, F3 off: record rows keep page_status on initial and continued outputs; other rows have none', () => S.recordsKeepPageStatusWithRowKeyOff(engine), 60_000);
+ test('amends and supersedes targets outside the caller\'s sources never reach record rows', () => S.recordLinksStayInSources(engine), 60_000);
});
diff --git a/test/helpers/entity-records-scenarios.ts b/test/helpers/entity-records-scenarios.ts
index 0deb6d094e..57e3333166 100644
--- a/test/helpers/entity-records-scenarios.ts
+++ b/test/helpers/entity-records-scenarios.ts
@@ -449,3 +449,32 @@ export async function recordsKeepPageStatusWithRowKeyOff(engine: BrainEngine): P
await engine.unsetConfig('entity.row_page_status');
}
}
+
+/** An `amends` or `supersedes` target outside the caller's sources never reaches a record row (names, card, context_pack, continuation). */
+export async function recordLinksStayInSources(engine: BrainEngine): Promise<void> {
+ await seedRecordsWorld(engine);
+ const OTHER = 'restricted-example';
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [OTHER]);
+ await engine.putPage('contracts/restricted-original', { type: 'contract' as never, title: 'Restricted original', compiled_truth: 'Restricted original.', timeline: '', frontmatter: {} }, { sourceId: OTHER });
+ for (const [from, type] of [['contracts/acme-amend-1', 'amends'], ['contracts/acme-msa-v2', 'supersedes']] as const) {
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, link_source, origin_page_id)
+ SELECT f.id, t.id, $3, 'markdown', f.id FROM pages f JOIN pages t ON t.slug = 'contracts/restricted-original' AND t.source_id = $4
+ WHERE f.slug = $1 AND f.source_id = $2`, [from, SRC, type, OTHER]);
+ }
+ await engine.setConfig('entity.record_types', 'contract');
+ for (const remote of [true, false]) {
+ const names = (await call(engine, 'entity', { names: ['CRM record: Acme Example'] }, remote)).body.results[0];
+ const card = (await call(engine, 'entity', { name: 'crm/acme-example' }, remote)).body.card;
+ const pack = (await call(engine, 'context_pack', { entities: 'crm/acme-example' }, remote)).body;
+ const continued = (await call(engine, 'get_backlinks', { slug: 'crm/acme-example', type: 'contract', group: 'page', limit: 50 }, remote)).body;
+ for (const out of [names.records, card.records, pack.cards[0].records, continued.rows]) {
+ expect(JSON.stringify(out)).toContain('contracts/acme-msa');
+ expect(JSON.stringify(out)).not.toContain('restricted-original');
+ }
+ const amend1 = continued.rows.find((r: { slug: string }) => r.slug === 'contracts/acme-amend-1');
+ expect(amend1.amends).toEqual([{ slug: 'contracts/acme-msa', since: '2025-07-01' }]);
+ const v2 = continued.rows.find((r: { slug: string }) => r.slug === 'contracts/acme-msa-v2');
+ expect(v2.supersedes).toEqual([{ slug: 'contracts/acme-msa' }]);
+ }
+}