Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/eval/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ pnpm run eval:drive -- run --base https://ENV --reps 3 --concurrency 4 --tokens
- 给每个 persona 分 AI 席位(没有席位的环境跳过,记警告);
- 先给 `setup` 登录的管理员授予「制度管理员」权限集(`brightrule_policy_admin`,可用 `--admin-permission-set` 换),再读写制度。brightrule#70 之后只有这个权限集读得到草稿和已废止制度,管理员没有它,重跑时会找不到这些制度、重复新建,挂在上面的链接和附件也会 404。`run` 用同一个管理员换算记录 id,所以要先跑过 `setup`;
- 制度按 `policy_no`(= 语料 `key`),再补「上级制度」链接,附件按(制度,序号)。试行和制度大类留给应用的钩子推导。
- 最后写「按所属单位共享」的规则(`brightrule_policy_unit_<单位>`,每个拥有制度的单位一条),调用的是应用自己的 `scripts/sharing/policy-unit-sharing.mjs`。brightrule#76 之后制度是私有的,员工靠这些规则才读得到本单位和上级单位的制度;没有它们,每个 persona 一份制度也读不到,检索结果在权限复核时全部被去掉(brightrule#93)。带 `--skip-policies` 时也会跑。规则写不进去时 `setup` 报错退出:登录的管理员要有 `manage_sharing`(平台管理员有;`brightrule_policy_admin` 不含它),并且读得到全部制度。结果里的 `sharingRules` 报出新建、改写、删除和不变的规则数。

环境里语料没有的制度不会删,会留在目录里当干扰项,所以要用专门的评测环境。

Expand Down
57 changes: 56 additions & 1 deletion scripts/eval/__tests__/driver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,8 @@ describe('setup on an environment where only the policy administrator reads unpu
};
let n = 0;
const log: string[] = [];
const rules = new Map<string, Record<string, unknown>>();
const sharing = { refuse: false };
const adminSees = () => tables.sys_user_permission_set!.some((g) => g.user_id === 'admin-1' && g.permission_set === 'brightrule_policy_admin');
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'set-cookie': 's=1; Path=/' } });
const fetchMock = vi.fn(async (url: string, init: { method?: string; body?: string } = {}) => {
Expand All @@ -310,6 +312,18 @@ describe('setup on an environment where only the policy administrator reads unpu
return json({ user: { id } });
}
if (p.startsWith('/api/v1/actions/')) return json({ ok: true });
if (p.startsWith('/api/v1/sharing/rules')) {
log.push(`${method} sharing/rules`);
if (sharing.refuse) return json({ error: 'manage_sharing required' }, 403);
if (method === 'GET') return json({ data: [...rules.values()] });
if (method === 'POST') {
// The row the API stores: snake_case columns, as `ruleMatches` reads them.
rules.set(body.name, { name: body.name, label: body.label, description: body.description, object_name: body.object, criteria: body.criteria, recipient_type: body.recipientType, recipient_id: body.recipientId, access_level: body.accessLevel, active: body.active });
return json({ data: body });
}
rules.delete(decodeURIComponent(p.split('/').pop()!));
return json({ ok: true });
}
const m = p.match(/^\/api\/v1\/data\/([a-z_]+)(?:\/([^/]+))?$/);
if (!m) return json({ error: `no route ${p}` }, 404);
const [, object, id] = m;
Expand All @@ -335,7 +349,7 @@ describe('setup on an environment where only the policy administrator reads unpu
return json({ id });
});
vi.stubGlobal('fetch', fetchMock);
return { tables, log };
return { tables, log, rules, sharing };
}

const small = {
Expand Down Expand Up @@ -366,6 +380,47 @@ describe('setup on an environment where only the policy administrator reads unpu
}
});

it('writes one sharing rule per unit that owns a policy, after the policies, and a rerun writes none (brightrule#93)', async () => {
const env = fakeEnvironment();
try {
const first = await setupEnvironment(small, opts());
const owners = new Set(env.tables.brightrule_policy!.map((r) => r.owning_unit));
expect(owners.size).toBeGreaterThan(0);
expect(first.sharingRules).toEqual({ created: owners.size, updated: 0, removed: 0, unchanged: 0 });
expect([...env.rules.values()].map((r) => (r.criteria as { owning_unit: string }).owning_unit).sort()).toEqual([...owners].sort());
expect(env.log.indexOf('POST sharing/rules')).toBeGreaterThan(env.log.lastIndexOf('POST brightrule_policy'));

const second = await setupEnvironment(small, opts());
expect(second.sharingRules).toEqual({ created: 0, updated: 0, removed: 0, unchanged: owners.size });
} finally {
vi.unstubAllGlobals();
}
});

it('writes the sharing rules with --skip-policies too, for policies loaded earlier', async () => {
const env = fakeEnvironment();
try {
await setupEnvironment(small, opts());
env.rules.clear();
const again = await setupEnvironment(small, { ...opts(), skipPolicies: true });
expect(again.policies).toEqual({ created: 0, updated: 0 });
expect(again.sharingRules.created).toBe(env.rules.size);
expect(env.rules.size).toBeGreaterThan(0);
} finally {
vi.unstubAllGlobals();
}
});

it('fails setup when the sharing rules cannot be written, naming manage_sharing', async () => {
const env = fakeEnvironment();
try {
env.sharing.refuse = true;
await expect(setupEnvironment(small, opts())).rejects.toThrow(/sharing rules: .*403.*manage_sharing/s);
} finally {
vi.unstubAllGlobals();
}
});

it('grantSelf writes nothing when the account already holds the set', async () => {
const env = fakeEnvironment();
try {
Expand Down
47 changes: 46 additions & 1 deletion scripts/eval/driver/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,22 @@
* again and fail on their links and attachments. `run` reads the same
* account's view to map record ids to keys, so it needs the set too;
* - policies (`brightrule_policy`, by `policy_no` = corpus key), then their
* 上级制度 links, then attachments (by policy and `sort_no`).
* 上级制度 links, then attachments (by policy and `sort_no`);
* - the per-unit sharing rules (`brightrule_policy_unit_<unit>`), last, by the
* app's own reconciler (scripts/sharing/policy-unit-sharing.mjs). Policies
* are private since brightrule#76 and an employee reads the ones of their
* unit and its parents only through these rules; without them every persona
* reads no policy and every search comes back empty (brightrule#93). It runs
* with `--skip-policies` too, since the policies may be from an earlier
* load, and a failure stops setup: an environment without the rules gives
* numbers that mean nothing.
*
* Use an environment kept for evaluation: policies already there that the
* corpus does not name are left as they are and crowd the catalog.
*/
import { textStats } from '../../../src/data/document-text.js';
import type { Corpus, CorpusPolicy, Unit } from '../schema.js';
import { reconcilePolicyUnitRules, type ApiRequest } from '../../sharing/policy-unit-sharing.mjs';
import { call, failure, idOf, listAll, pool, signIn, type Session } from './http.js';

export interface SetupOptions {
Expand All @@ -51,6 +60,8 @@ export interface SetupResult {
personas: number;
policies: { created: number; updated: number };
attachments: number;
/** The per-unit sharing rules after this run: how many were written, removed, or already right. */
sharingRules: { created: number; updated: number; removed: number; unchanged: number };
warnings: string[];
}

Expand Down Expand Up @@ -248,6 +259,38 @@ export async function grantSelf(s: Session, set: string): Promise<boolean> {
return true;
}

/** One call relative to `/api/v1` as the signed-in session, in the shape the sharing reconciler takes. */
export function apiRequest(s: Session): ApiRequest {
const origin = new URL(s.baseUrl).origin;
return (method, path, body) =>
fetch(`${s.baseUrl}/api/v1${path}`, {
method,
headers: { 'content-type': 'application/json', accept: 'application/json', origin, cookie: s.cookie },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
}

/**
* Write the per-unit sharing rules the policies in the environment need, as
* the administrator. Throws when a rule cannot be written: the usual cause is
* an administrator without `manage_sharing`, which `brightrule_policy_admin`
* does not grant.
*/
export async function reconcileSharing(s: Session, o: Pick<SetupOptions, 'log'>): Promise<SetupResult['sharingRules']> {
let r;
try {
r = await reconcilePolicyUnitRules(apiRequest(s), { log: (line) => o.log(`sharing rules: ${line}`) });
} catch (e) {
throw new Error(
`sharing rules: ${e instanceof Error ? e.message : String(e)}. Without them no persona reads any policy. `
+ 'The administrator setup signs in as needs `manage_sharing` (a platform administrator has it) and must see every policy.',
);
}
const counts = { created: r.created.length, updated: r.updated.length, removed: r.removed.length, unchanged: r.unchanged.length };
o.log(`sharing rules: ${r.units} unit(s) own ${r.policies} policies; ${counts.created} created, ${counts.updated} updated, ${counts.removed} removed, ${counts.unchanged} unchanged`);
return counts;
}

export async function setupEnvironment(corpus: Corpus, o: SetupOptions): Promise<SetupResult> {
const warnings: string[] = [];
const adminSet = o.adminPermissionSet ?? 'brightrule_policy_admin';
Expand All @@ -256,11 +299,13 @@ export async function setupEnvironment(corpus: Corpus, o: SetupOptions): Promise
const unitIds = await upsertUnits(o.admin, corpus, o);
await setupPersonas(o.admin, corpus, unitIds, o, warnings);
const loaded = o.skipPolicies ? { created: 0, updated: 0, attachments: 0 } : await loadPolicies(o.admin, corpus, unitIds, o);
const sharingRules = await reconcileSharing(o.admin, o);
return {
units: corpus.units.length,
personas: corpus.personas.length,
policies: { created: loaded.created, updated: loaded.updated },
attachments: loaded.attachments,
sharingRules,
warnings,
};
}
Expand Down
7 changes: 6 additions & 1 deletion src/skills/policy-inquiry.skill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ import { defineSkill } from '@objectstack/spec';
* policy whose text the asker's unit also carries is cited from the unit's
* copy, so the source does not depend on which copy the search ranked.
*
* A search hit already carries `metadata` (policy, owning_unit, clause_hash:
* the source's `metadataFields`), so the skill reads those from the hit and
* no longer re-queries the clause table for them (brightrule#97). `section_key`
* is not indexed with the passage; it is read only when neighbours are wanted.
*
* Phase one has no hand-off to a person (maintainer, 2026-11-24): with no
* basis the answer says so; the escalation action stays for the form path.
*/
Expand Down Expand Up @@ -73,7 +78,7 @@ export const PolicyInquirySkill = defineSkill({
- 只给了名称:query_records 对象 brightrule_policy,条件 title 包含名称中的关键词,找到后再读正文;找到多份同名或相近的,按 display_name 列出来请员工确认。
- 这份制度回答不了时,先说明「本制度中未找到相关规定」,再说明你另外查了哪份制度,引用时写清是哪份。
- 员工问「这个制度讲了什么」:读正文后按章概括要点,列出章节和主要条款号,不要只复述目录字段。
2. **没有指定制度**:先用 search_knowledge 检索制度条款(按条切分,每条开头写着【单位|制度名|附件】章 > 节 > 条):query 写问题要点,topK 8,groupBy: "clause_hash",granularity: "record"(同一条文只出一次;带 groupBy 时 granularity 只能是 "record" 或不传,传 "chunk" 会被拒绝);问题有几个要点时在同一步同时发几次检索,一轮合计最多 3 次。系统提示的「主单位链」列出了单位 id 时,加 scope: [{ object: "sys_business_unit", ids: [链上全部 id] }];员工明确问另一家单位、或没有单位链时不加。命中结果的 record.id 是条款 id:用一次 query_records 对象 brightrule_policy_clause,where { id: { $in: [这些 id] } },取 id、policy、owning_unit、section_key、clause_hash,得到所属制度;命中条款不属于本公司时,再 query_records 同一对象 where { clause_hash: { $in: [这些 clause_hash] }, owning_unit: 本公司 id },有同文条款的,以本公司那份制度为出处。条文完整时可直接据以引用作答;要看同一节的前后条或整张表时,query_records 对象 brightrule_policy_clause,where { policy: 制度 id, section_key: 命中条款的 section_key },按 seq 排序取 content;要通读时才按上一节 get_record 读那份制度,一轮最多读 2 份全文,同一份不重复读。写出处前,用 query_records 取所引制度的 id、display_name、doc_no、issuance_type、issued_date(结果带 __link)。锁定制度后还缺数字,或准备答「未找到」之前,必须再检一次:scope 改为 [{ object: "brightrule_policy", ids: [候选制度 id] }];仍没有,去掉 scope 再检一次,命中内容写明适用于提问人所属公司的,按本公司规定作答。片段只覆盖问题一部分时不得只凭片段作答。检索不到相关条款时,再按下面查目录。
2. **没有指定制度**:先用 search_knowledge 检索制度条款(按条切分,每条开头写着【单位|制度名|附件】章 > 节 > 条):query 写问题要点,topK 8,groupBy: "clause_hash",granularity: "record"(同一条文只出一次;带 groupBy 时 granularity 只能是 "record" 或不传,传 "chunk" 会被拒绝);问题有几个要点时在同一步同时发几次检索,一轮合计最多 3 次。系统提示的「主单位链」列出了单位 id 时,加 scope: [{ object: "sys_business_unit", ids: [链上全部 id] }];员工明确问另一家单位、或没有单位链时不加。命中的 record.id 是条款 id,metadata 有 policy(制度 id)、owning_unit、clause_hash,直接用;没有 metadata 时才按 id 查 brightrule_policy_clause 取这三项。命中条款不属于本公司时,查该对象 where { clause_hash: { $in: [这些 clause_hash] }, owning_unit: 本公司 id },有同文的,以本公司那份制度为出处。条文完整时可直接引用作答;要看同节前后条或整张表时,先按条款 id 取 section_key,再查该对象 where { policy: 制度 id, section_key },按 seq 取 content;要通读时才按上一节 get_record 读那份制度,一轮最多读 2 份全文,同一份不重复读。写出处前,用 query_records 取所引制度的 id、display_name、doc_no、issuance_type、issued_date(结果带 __link)。锁定制度后还缺数字,或准备答「未找到」之前,必须再检一次:scope 改为 [{ object: "brightrule_policy", ids: [候选制度 id] }];仍没有,去掉 scope 再检一次,命中内容写明适用于提问人所属公司的,按本公司规定作答。片段只覆盖问题一部分时不得只凭片段作答。检索不到相关条款时,再按下面查目录。
查目录:query_records 查制度目录,先缩小范围再挑,不要逐页读完整个目录。每次都带 status = "published",limit 200,再加:
- 单位:系统提示的「主单位链」列出了单位 id 时,只查链上单位(本公司及上级)和没填所属单位的制度:{ "$or": [{ "owning_unit": { "$in": [链上全部 id] } }, { "owning_unit": { "$null": true } }] }。员工明确问另一家单位时,改为 display_name 包含那家单位的名称。没有单位链(未分配单位、系统提示里没有提问人)时不加单位条件。
- 关键词:用 $contains 在 title、summary、body_md 上筛,fields 不带 body_md。与单位条件同用时都放进 $and:{ "status": "published", "$and": [单位条件, { "$or": [关键词条件] }] }。
Expand Down