From 0fdb5e870e97e2658e68177c4569cd91c8933f41 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:08:26 +0000 Subject: [PATCH 1/2] =?UTF-8?q?=E5=88=B6=E5=BA=A6=E9=97=AE=E8=AF=A2?= =?UTF-8?q?=EF=BC=9A=E6=A3=80=E7=B4=A2=E5=91=BD=E4=B8=AD=E5=90=8E=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E7=94=A8=E5=91=BD=E4=B8=AD=E8=87=AA=E5=B8=A6=E7=9A=84?= =?UTF-8?q?=20metadata=EF=BC=8C=E4=B8=8D=E5=86=8D=E5=9B=9E=E6=9F=A5?= =?UTF-8?q?=E6=9D=A1=E6=AC=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 命中已带 policy、owning_unit、clause_hash(知识源的 metadataFields), 技能不再为这三项按条款 id 查一次 brightrule_policy_clause;命中没有 metadata 时保留回查作为退路。section_key 不随条文入索引,只在要看 同节前后条时才按条款 id 取。 技能文字由 5677 降到 5590,policy-inquiry-length 测试恢复通过 (main 上此前为 5677 > 5600)。 Refs #97 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012dn2Af3j32UkLgdzhb7Zu3 --- src/skills/policy-inquiry.skill.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/skills/policy-inquiry.skill.ts b/src/skills/policy-inquiry.skill.ts index cf81855..004aa3d 100644 --- a/src/skills/policy-inquiry.skill.ts +++ b/src/skills/policy-inquiry.skill.ts @@ -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. */ @@ -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": [关键词条件] }] }。 From 01ba22388560c4c3f6cc6ec109d5c13a4dbdf630 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:28:18 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=E8=AF=84=E6=B5=8B=20setup=20=E5=86=99?= =?UTF-8?q?=E5=85=A5=E5=88=B6=E5=BA=A6=E7=9A=84=E6=8C=89=E5=8D=95=E4=BD=8D?= =?UTF-8?q?=E5=85=B1=E4=BA=AB=E8=A7=84=E5=88=99=EF=BC=8C=E5=86=99=E4=B8=8D?= =?UTF-8?q?=E8=BF=9B=E5=8E=BB=E5=B0=B1=E6=8A=A5=E9=94=99=E9=80=80=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit brightrule#76 之后制度是私有的,员工靠 brightrule_policy_unit_<单位> 规则读本单位和上级单位的制度。drive.ts setup 从不写这些规则,所以 评测环境里每个员工身份读到的制度是 0 份,检索全部 0 命中。 setupEnvironment 在载入制度之后调用应用自己的 reconcilePolicyUnitRules(scripts/sharing/policy-unit-sharing.mjs), 用 setup 已登录的管理员会话;--skip-policies 时同样跑。结果里新增 sharingRules(新建、改写、删除、不变的规则数)。规则写入失败时 setup 报错并点名 manage_sharing,不再静默产出 0 命中的评测。 Refs #93 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012dn2Af3j32UkLgdzhb7Zu3 --- scripts/eval/README.md | 1 + scripts/eval/__tests__/driver.test.ts | 57 ++++++++++++++++++++++++++- scripts/eval/driver/setup.ts | 47 +++++++++++++++++++++- 3 files changed, 103 insertions(+), 2 deletions(-) diff --git a/scripts/eval/README.md b/scripts/eval/README.md index fa6b432..12bc681 100644 --- a/scripts/eval/README.md +++ b/scripts/eval/README.md @@ -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` 报出新建、改写、删除和不变的规则数。 环境里语料没有的制度不会删,会留在目录里当干扰项,所以要用专门的评测环境。 diff --git a/scripts/eval/__tests__/driver.test.ts b/scripts/eval/__tests__/driver.test.ts index cf687f6..ec23538 100644 --- a/scripts/eval/__tests__/driver.test.ts +++ b/scripts/eval/__tests__/driver.test.ts @@ -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>(); + 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 } = {}) => { @@ -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; @@ -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 = { @@ -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 { diff --git a/scripts/eval/driver/setup.ts b/scripts/eval/driver/setup.ts index 2116bb9..95f1713 100644 --- a/scripts/eval/driver/setup.ts +++ b/scripts/eval/driver/setup.ts @@ -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_`), 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 { @@ -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[]; } @@ -248,6 +259,38 @@ export async function grantSelf(s: Session, set: string): Promise { 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): Promise { + 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 { const warnings: string[] = []; const adminSet = o.adminPermissionSet ?? 'brightrule_policy_admin'; @@ -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, }; }