feat(graph): owner_id 寫入鏈必經(根治無主資料)——配合 base owner-mandatory(D28)
- kbdb-client requireOwner 守衛:漏 owner 插件端即 throw,不再靜默送 owner:'' - owner 一路 thread:persistNodes/ingestEnvelope/entity-crud/triplet-crud 全必填 - 病灶修:POST /triplets/ingest 原本沒傳 owner→加 owner_id query+400 - 寫入 route 缺 owner→400;vitest 23→27 - 註:gloss-bridge 分支的 backfill/gloss-entry 另需套 owner 必填(附說明),不跨支疊改
This commit is contained in:
@@ -13,12 +13,12 @@ const norm = (s: string): string => s.toLowerCase().trim();
|
||||
// ─── Entity ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/** 建立 Entity(canonical name)。底層 = 一筆 entity template record。 */
|
||||
export async function createEntity(client: KbdbClient, canonical: string, owner?: string): Promise<Entity> {
|
||||
export async function createEntity(client: KbdbClient, canonical: string, owner: string): Promise<Entity> {
|
||||
await ensurePluginTemplates(client);
|
||||
const id = await client.createRecord(
|
||||
TPL_ENTITY,
|
||||
{ canonical, aliases_json: '[]', entity_type: '', owner: owner ?? '' },
|
||||
owner,
|
||||
{ canonical, aliases_json: '[]', entity_type: '', owner }, // 真 owner 落 slot(不再 ?? '')
|
||||
owner, // 必經:createRecord 內 requireOwner 守衛
|
||||
);
|
||||
return { id, canonical, aliases: [] };
|
||||
}
|
||||
@@ -45,21 +45,23 @@ export async function listEntities(client: KbdbClient, limit = 100, owner?: stri
|
||||
* 新增 alias。base 無 PUT /records/:id → 改「重建一筆新 entity record」覆寫(含舊 canonical + 既有 aliases + 新 alias)。
|
||||
* [→arcrun] base 缺 PUT /records/:id:補上後改為原地 patch aliases_json,省一次重建。
|
||||
*/
|
||||
export async function addAlias(client: KbdbClient, entityId: string, alias: string, owner?: string): Promise<void> {
|
||||
export async function addAlias(client: KbdbClient, entityId: string, alias: string, owner: string): Promise<void> {
|
||||
const rec = await client.getRecord(entityId);
|
||||
if (!rec) throw new Error(`Entity ${entityId} not found`);
|
||||
const ent = recordToEntity(rec);
|
||||
if (ent.aliases.includes(alias)) return;
|
||||
const aliases = [...ent.aliases, alias];
|
||||
await ensurePluginTemplates(client);
|
||||
// 重建時沿用原 record 既有 owner;原 record 無主(舊資料 owner=None)才退回 caller 指定的 owner。
|
||||
const effectiveOwner = (rec.values.owner || '').trim() || owner;
|
||||
await client.createRecord(
|
||||
TPL_ENTITY,
|
||||
{
|
||||
canonical: ent.canonical,
|
||||
aliases_json: JSON.stringify(aliases),
|
||||
entity_type: rec.values.entity_type ?? '',
|
||||
owner: rec.values.owner ?? owner ?? '',
|
||||
owner: effectiveOwner,
|
||||
},
|
||||
owner,
|
||||
effectiveOwner, // 必經:createRecord 內 requireOwner 守衛
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import type { KbdbClient } from '../lib/kbdb-client';
|
||||
export async function normalizeEntity(
|
||||
client: KbdbClient,
|
||||
rawName: string,
|
||||
owner?: string,
|
||||
owner: string, // 必經:未命中會建新 entity,必帶 owner
|
||||
): Promise<string> {
|
||||
try {
|
||||
const exact = await findEntityByName(client, rawName, owner);
|
||||
|
||||
@@ -16,7 +16,7 @@ export async function createPendingAlias(
|
||||
candidateEntityId: string,
|
||||
candidateCanonical: string,
|
||||
similarity: number,
|
||||
owner?: string,
|
||||
owner: string, // 必經:pending record 也不可無主
|
||||
): Promise<PendingAlias> {
|
||||
await ensurePluginTemplates(client);
|
||||
const id = await client.createRecord(
|
||||
@@ -27,7 +27,7 @@ export async function createPendingAlias(
|
||||
candidate_canonical: candidateCanonical,
|
||||
similarity: String(similarity),
|
||||
},
|
||||
owner,
|
||||
owner, // 必經:createRecord 內 requireOwner 守衛
|
||||
);
|
||||
return {
|
||||
id,
|
||||
@@ -56,14 +56,14 @@ export async function getPendingAliases(client: KbdbClient, limit = 100, owner?:
|
||||
}
|
||||
|
||||
/** 確認 → addAlias 到候選 entity。pending soft 保留([→arcrun] base 缺 DELETE record)。 */
|
||||
export async function confirmPendingAlias(client: KbdbClient, pendingId: string, owner?: string): Promise<void> {
|
||||
export async function confirmPendingAlias(client: KbdbClient, pendingId: string, owner: string): Promise<void> {
|
||||
const rec = await client.getRecord(pendingId);
|
||||
if (!rec || !rec.values.raw_name) throw new Error(`Pending alias ${pendingId} not found`);
|
||||
await addAlias(client, rec.values.candidate_entity_id, rec.values.raw_name, owner);
|
||||
}
|
||||
|
||||
/** 拒絕 → 以 raw_name 建新 entity。pending soft 保留([→arcrun] base 缺 DELETE record)。 */
|
||||
export async function rejectPendingAlias(client: KbdbClient, pendingId: string, owner?: string): Promise<Entity> {
|
||||
export async function rejectPendingAlias(client: KbdbClient, pendingId: string, owner: string): Promise<Entity> {
|
||||
const rec = await client.getRecord(pendingId);
|
||||
if (!rec || !rec.values.raw_name) throw new Error(`Pending alias ${pendingId} not found`);
|
||||
return createEntity(client, rec.values.raw_name, owner);
|
||||
|
||||
@@ -22,7 +22,7 @@ export type IngestNode = {
|
||||
export async function persistNodes(
|
||||
client: KbdbClient,
|
||||
nodes: IngestNode[],
|
||||
owner_id?: string,
|
||||
owner_id: string, // 必經:owner 一路從 ingest envelope / route 帶到底,不得掉成空字串
|
||||
): Promise<void> {
|
||||
if (!nodes || nodes.length === 0) return;
|
||||
await ensurePluginTemplates(client);
|
||||
@@ -42,9 +42,9 @@ export async function persistNodes(
|
||||
gloss: n.gloss ?? '',
|
||||
// contract 預設 true;只在明確 false 時存標(base 看 'false' 跳過 embed)。
|
||||
embed: n.embed === false ? 'false' : 'true',
|
||||
owner: owner_id ?? '',
|
||||
owner: owner_id, // 真 owner 落 slot(不再 ?? '')
|
||||
},
|
||||
owner_id,
|
||||
owner_id, // createRecord 內 requireOwner 守衛:缺→throw
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export type CreateTripletData = {
|
||||
object: string;
|
||||
source_block_id?: string;
|
||||
confidence?: number;
|
||||
owner_id?: string;
|
||||
owner_id: string; // 必經:三元組寫入必帶 owner(createRecord 內 requireOwner 守衛)
|
||||
clusters?: string[];
|
||||
bridge_score?: number;
|
||||
subject_entity_type?: string;
|
||||
|
||||
@@ -55,7 +55,7 @@ export async function extractTripletsViaLLM(ai: Ai, chunks: string[]): Promise<L
|
||||
export async function writeTripletToDb(
|
||||
client: KbdbClient,
|
||||
t: { subject: string; predicate: string; object: string; confidence?: number },
|
||||
owner: string | null,
|
||||
owner: string, // 必經:萃取寫入必帶 owner(不再收 null → 不會 owner_id: undefined)
|
||||
): Promise<boolean> {
|
||||
// 查重:以 S-P-O 三欄精確比對(queryTriplets 取 template record 後在插件層 filter)
|
||||
const { count } = await queryTriplets(client, {
|
||||
@@ -71,7 +71,7 @@ export async function writeTripletToDb(
|
||||
predicate: t.predicate,
|
||||
object: t.object,
|
||||
confidence: t.confidence ?? 0.8,
|
||||
owner_id: owner ?? undefined,
|
||||
owner_id: owner,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ export type IngestResult = { skipped: boolean; ingested: number; deprecated: num
|
||||
export async function ingestEnvelope(
|
||||
client: KbdbClient,
|
||||
env: IngestEnvelope,
|
||||
owner_id?: string,
|
||||
owner_id: string, // 必經:owner 從 route 帶入,一路 thread 進 triplet + node 寫入,不得掉成空
|
||||
): Promise<IngestResult> {
|
||||
await ensurePluginTemplates(client);
|
||||
|
||||
|
||||
+24
-4
@@ -26,11 +26,29 @@ export type BaseRecord = {
|
||||
export type CreateEntryInput = {
|
||||
content: string | null;
|
||||
entry_type: string;
|
||||
owner_id?: string;
|
||||
// owner_id 必經(D27/D28):型別上必填、且執行期缺→throw。不再靜默送空 → 不寫出無主資料。
|
||||
owner_id: string;
|
||||
parent_id?: string;
|
||||
page_name?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* owner_id 必經守衛(D27/D28,2026-07-05)。
|
||||
* 病根:漏 owner → 靜默送 owner:'' → base 寫成 owner=None → mira owner 過濾濾掉 → 使用者查不到
|
||||
* (實測回填 16 筆 gloss entry owner=None)。base 即將把 owner 設必填(缺→400);插件端先擋,fail loud。
|
||||
* 任何寫入前呼叫此守衛:漏 owner 在插件端就爆、不會送到 base,錯誤訊息指名該從最外層 route/envelope 帶入。
|
||||
*/
|
||||
export function requireOwner(owner_id: string | null | undefined, op: string): string {
|
||||
const v = (owner_id ?? '').trim();
|
||||
if (!v) {
|
||||
throw new Error(
|
||||
`[kbdb-graph] ${op} 缺 owner_id:owner 為必經欄位,不可寫出無主資料。` +
|
||||
`請從最外層(route 參數 / ingest envelope)把真 owner thread 到底。`,
|
||||
);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/** 基本盤 API client。所有方法 = 一個 HTTP 呼叫,零 SQL。 */
|
||||
export class KbdbClient {
|
||||
constructor(
|
||||
@@ -70,7 +88,8 @@ export class KbdbClient {
|
||||
// --- entries ---
|
||||
|
||||
async createEntry(input: CreateEntryInput): Promise<BaseEntry> {
|
||||
const { entry } = await this.req<{ entry: BaseEntry }>('POST', '/entries', input);
|
||||
const owner_id = requireOwner(input.owner_id, 'createEntry');
|
||||
const { entry } = await this.req<{ entry: BaseEntry }>('POST', '/entries', { ...input, owner_id });
|
||||
return entry;
|
||||
}
|
||||
|
||||
@@ -154,11 +173,12 @@ export class KbdbClient {
|
||||
|
||||
// --- records(= template 實例,填 slot) ---
|
||||
|
||||
async createRecord(template: string, values: Record<string, string>, owner_id?: string): Promise<string> {
|
||||
async createRecord(template: string, values: Record<string, string>, owner_id: string): Promise<string> {
|
||||
const owner = requireOwner(owner_id, `createRecord(template=${template})`);
|
||||
const { record } = await this.req<{ record: { record_id: string } }>('POST', '/records', {
|
||||
template,
|
||||
values,
|
||||
owner_id,
|
||||
owner_id: owner,
|
||||
});
|
||||
return record.record_id;
|
||||
}
|
||||
|
||||
@@ -54,13 +54,19 @@ entityRoutes.openapi(listPendingRoute, async (c) => {
|
||||
|
||||
entityRoutes.post('/pending/:id/confirm', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
await confirmPendingAlias(makeKbdbClient(c.env), id);
|
||||
// owner 必經:confirm 會 addAlias(重建 entity record),缺 owner→400 不寫無主資料。
|
||||
const owner = c.req.query('owner_id')?.trim();
|
||||
if (!owner) return c.json({ error: 'owner_id query parameter required(資料不可無主)' }, 400);
|
||||
await confirmPendingAlias(makeKbdbClient(c.env), id, owner);
|
||||
return c.json({ success: true, action: 'confirmed', id });
|
||||
});
|
||||
|
||||
entityRoutes.post('/pending/:id/reject', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
const newEntity = await rejectPendingAlias(makeKbdbClient(c.env), id);
|
||||
// owner 必經:reject 會 createEntity,缺 owner→400 不寫無主資料。
|
||||
const owner = c.req.query('owner_id')?.trim();
|
||||
if (!owner) return c.json({ error: 'owner_id query parameter required(資料不可無主)' }, 400);
|
||||
const newEntity = await rejectPendingAlias(makeKbdbClient(c.env), id, owner);
|
||||
return c.json({ success: true, action: 'rejected', newEntity });
|
||||
});
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ const createRouteDefinition = createRoute({
|
||||
subject: z.string().min(1),
|
||||
predicate: z.string().min(1),
|
||||
object: z.string().min(1),
|
||||
owner_id: z.string().optional(),
|
||||
owner_id: z.string().min(1), // 必填:缺→400(資料不可無主)
|
||||
source_block_id: z.string().optional(),
|
||||
confidence: z.number().optional(),
|
||||
clusters: z.array(z.string()).optional(),
|
||||
@@ -103,10 +103,13 @@ const ingestRoute = createRoute({
|
||||
method: 'post',
|
||||
path: '/ingest',
|
||||
request: {
|
||||
// owner_id 走 route 參數(envelope 是 .strict() 凍結契約,不塞 owner 進去)。缺→400。
|
||||
query: z.object({ owner_id: z.string().optional().describe('資料所有者(必填,缺→400)') }),
|
||||
body: { content: { 'application/json': { schema: IngestEnvelopeSchema } } },
|
||||
},
|
||||
responses: {
|
||||
200: { description: 'Envelope ingested (or skipped if same content_hash)' },
|
||||
400: { description: 'Missing owner_id (資料不可無主)' },
|
||||
422: { description: 'Invalid envelope (forbidden field or shape mismatch)' },
|
||||
},
|
||||
tags: ['Triplets'],
|
||||
@@ -115,8 +118,11 @@ const ingestRoute = createRoute({
|
||||
tripletRoutes.openapi(
|
||||
ingestRoute,
|
||||
async (c) => {
|
||||
// owner 必經:缺→400(不寫出無主 triplet/node;避免再現 owner=None 被 mira 過濾)。
|
||||
const owner_id = c.req.query('owner_id')?.trim();
|
||||
if (!owner_id) return c.json({ error: 'owner_id query parameter required(資料不可無主)' }, 400);
|
||||
const env = c.req.valid('json');
|
||||
const result = await ingestEnvelope(makeKbdbClient(c.env), env);
|
||||
const result = await ingestEnvelope(makeKbdbClient(c.env), env, owner_id);
|
||||
return c.json(result, 200);
|
||||
},
|
||||
// strict() 驗證失敗(如送禁止欄位 bridge_score)→ 422,不是預設 400。
|
||||
|
||||
Reference in New Issue
Block a user