@agentbadge/database 0.6.22 → 0.6.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/database.d.ts +6 -0
- package/dist/database.js +7 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/prisma/contract.json +4453 -3034
- package/dist/repositories/knowledge-repository.d.ts +83 -0
- package/dist/repositories/knowledge-repository.js +181 -0
- package/dist/repositories/knowledge-taxonomy-repository.d.ts +106 -0
- package/dist/repositories/knowledge-taxonomy-repository.js +285 -0
- package/package.json +1 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { Models } from "../prisma/contract.d.js";
|
|
2
|
+
import type { PrismaDb } from "./event-repository.js";
|
|
3
|
+
type ItemRow = Models.public_KnowledgeItem;
|
|
4
|
+
type VersionRow = Models.public_KnowledgeVersion;
|
|
5
|
+
type EventRow = Models.public_KnowledgeStatusEvent;
|
|
6
|
+
export interface KnowledgeItemInsert {
|
|
7
|
+
id: string;
|
|
8
|
+
slug: string;
|
|
9
|
+
kind: string;
|
|
10
|
+
status?: string;
|
|
11
|
+
createdBy: string;
|
|
12
|
+
}
|
|
13
|
+
export interface KnowledgeVersionInsert {
|
|
14
|
+
id: string;
|
|
15
|
+
itemId: string;
|
|
16
|
+
seq: number;
|
|
17
|
+
title: string;
|
|
18
|
+
body: string;
|
|
19
|
+
summary?: string | null;
|
|
20
|
+
restoredFromVersionId?: string | null;
|
|
21
|
+
createdBy: string;
|
|
22
|
+
}
|
|
23
|
+
export interface KnowledgeStatusEventInsert {
|
|
24
|
+
id: string;
|
|
25
|
+
itemId: string;
|
|
26
|
+
from: string | null;
|
|
27
|
+
to: string;
|
|
28
|
+
actor: string;
|
|
29
|
+
reason?: string | null;
|
|
30
|
+
}
|
|
31
|
+
export interface KnowledgeTransitionResult {
|
|
32
|
+
item: ItemRow | null;
|
|
33
|
+
event: EventRow | null;
|
|
34
|
+
transitioned: boolean;
|
|
35
|
+
reason?: "missing" | "status_mismatch";
|
|
36
|
+
}
|
|
37
|
+
export interface KnowledgeSearchHit {
|
|
38
|
+
itemId: string;
|
|
39
|
+
slug: string;
|
|
40
|
+
kind: string;
|
|
41
|
+
versionId: string;
|
|
42
|
+
title: string;
|
|
43
|
+
summary: string | null;
|
|
44
|
+
snippet: string;
|
|
45
|
+
rank: number;
|
|
46
|
+
}
|
|
47
|
+
export declare class KnowledgeRepository {
|
|
48
|
+
private readonly db;
|
|
49
|
+
constructor(db: PrismaDb);
|
|
50
|
+
getItem(id: string): Promise<ItemRow | null>;
|
|
51
|
+
getItemBySlug(slug: string): Promise<ItemRow | null>;
|
|
52
|
+
listItems(opts?: {
|
|
53
|
+
status?: string;
|
|
54
|
+
kind?: string;
|
|
55
|
+
limit?: number;
|
|
56
|
+
}): Promise<ItemRow[]>;
|
|
57
|
+
createItemWithVersion(item: KnowledgeItemInsert, version: KnowledgeVersionInsert, event: KnowledgeStatusEventInsert): Promise<{
|
|
58
|
+
item: ItemRow;
|
|
59
|
+
version: VersionRow;
|
|
60
|
+
}>;
|
|
61
|
+
addVersion(version: KnowledgeVersionInsert): Promise<VersionRow>;
|
|
62
|
+
getVersion(id: string): Promise<VersionRow | null>;
|
|
63
|
+
getVersionBySeq(itemId: string, seq: number): Promise<VersionRow | null>;
|
|
64
|
+
listVersions(itemId: string): Promise<VersionRow[]>;
|
|
65
|
+
transitionItem(id: string, input: {
|
|
66
|
+
from: string;
|
|
67
|
+
to: string;
|
|
68
|
+
actor: string;
|
|
69
|
+
reason?: string | null;
|
|
70
|
+
publish?: boolean;
|
|
71
|
+
unpublish?: boolean;
|
|
72
|
+
eventId?: string;
|
|
73
|
+
}): Promise<KnowledgeTransitionResult>;
|
|
74
|
+
listStatusEvents(itemId: string): Promise<EventRow[]>;
|
|
75
|
+
searchItems(opts: {
|
|
76
|
+
query: string;
|
|
77
|
+
status?: string;
|
|
78
|
+
kind?: string | null;
|
|
79
|
+
capabilityRef?: string | null;
|
|
80
|
+
limit?: number;
|
|
81
|
+
}): Promise<KnowledgeSearchHit[]>;
|
|
82
|
+
}
|
|
83
|
+
export {};
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { param } from "@prisma/orm-postgres/relational-core/expression";
|
|
2
|
+
const txt = (v) => param(v ?? null, { codecId: "pg/text@1" });
|
|
3
|
+
export class KnowledgeRepository {
|
|
4
|
+
db;
|
|
5
|
+
constructor(db) {
|
|
6
|
+
this.db = db;
|
|
7
|
+
}
|
|
8
|
+
async getItem(id) {
|
|
9
|
+
return this.db.orm.public.KnowledgeItem.where({ id }).first();
|
|
10
|
+
}
|
|
11
|
+
async getItemBySlug(slug) {
|
|
12
|
+
return this.db.orm.public.KnowledgeItem.where({ slug }).first();
|
|
13
|
+
}
|
|
14
|
+
async listItems(opts) {
|
|
15
|
+
let q = this.db.orm.public.KnowledgeItem.orderBy((r) => r.updatedAt.desc());
|
|
16
|
+
if (opts?.status !== undefined)
|
|
17
|
+
q = q.where({ status: opts.status });
|
|
18
|
+
if (opts?.kind !== undefined)
|
|
19
|
+
q = q.where({ kind: opts.kind });
|
|
20
|
+
return q.limit(opts?.limit ?? 500).all();
|
|
21
|
+
}
|
|
22
|
+
async createItemWithVersion(item, version, event) {
|
|
23
|
+
return this.db.transaction(async (tx) => {
|
|
24
|
+
const it = await tx.orm.public.KnowledgeItem.create({
|
|
25
|
+
id: item.id,
|
|
26
|
+
slug: item.slug,
|
|
27
|
+
kind: item.kind,
|
|
28
|
+
status: item.status ?? "DRAFT",
|
|
29
|
+
latestVersionId: version.id,
|
|
30
|
+
publishedVersionId: null,
|
|
31
|
+
createdBy: item.createdBy,
|
|
32
|
+
});
|
|
33
|
+
const v = await tx.orm.public.KnowledgeVersion.create({
|
|
34
|
+
id: version.id,
|
|
35
|
+
itemId: version.itemId,
|
|
36
|
+
seq: version.seq,
|
|
37
|
+
title: version.title,
|
|
38
|
+
body: version.body,
|
|
39
|
+
summary: version.summary ?? null,
|
|
40
|
+
restoredFromVersionId: version.restoredFromVersionId ?? null,
|
|
41
|
+
createdBy: version.createdBy,
|
|
42
|
+
});
|
|
43
|
+
await tx.orm.public.KnowledgeStatusEvent.create({
|
|
44
|
+
id: event.id,
|
|
45
|
+
itemId: event.itemId,
|
|
46
|
+
from: event.from,
|
|
47
|
+
to: event.to,
|
|
48
|
+
actor: event.actor,
|
|
49
|
+
reason: event.reason ?? null,
|
|
50
|
+
});
|
|
51
|
+
return { item: it, version: v };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
async addVersion(version) {
|
|
55
|
+
return this.db.transaction(async (tx) => {
|
|
56
|
+
const v = await tx.orm.public.KnowledgeVersion.create({
|
|
57
|
+
id: version.id,
|
|
58
|
+
itemId: version.itemId,
|
|
59
|
+
seq: version.seq,
|
|
60
|
+
title: version.title,
|
|
61
|
+
body: version.body,
|
|
62
|
+
summary: version.summary ?? null,
|
|
63
|
+
restoredFromVersionId: version.restoredFromVersionId ?? null,
|
|
64
|
+
createdBy: version.createdBy,
|
|
65
|
+
});
|
|
66
|
+
await tx.orm.public.KnowledgeItem.where({
|
|
67
|
+
id: version.itemId,
|
|
68
|
+
}).update({ latestVersionId: v.id });
|
|
69
|
+
return v;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async getVersion(id) {
|
|
73
|
+
return this.db.orm.public.KnowledgeVersion.where({ id }).first();
|
|
74
|
+
}
|
|
75
|
+
async getVersionBySeq(itemId, seq) {
|
|
76
|
+
return this.db.orm.public.KnowledgeVersion.where({
|
|
77
|
+
itemId,
|
|
78
|
+
seq,
|
|
79
|
+
}).first();
|
|
80
|
+
}
|
|
81
|
+
async listVersions(itemId) {
|
|
82
|
+
return this.db.orm.public.KnowledgeVersion.where({ itemId })
|
|
83
|
+
.orderBy((r) => r.seq.desc())
|
|
84
|
+
.all();
|
|
85
|
+
}
|
|
86
|
+
async transitionItem(id, input) {
|
|
87
|
+
return this.db.transaction(async (tx) => {
|
|
88
|
+
const cur = await tx.orm.public.KnowledgeItem.where({ id }).first();
|
|
89
|
+
if (!cur) {
|
|
90
|
+
return { item: null, event: null, transitioned: false, reason: "missing" };
|
|
91
|
+
}
|
|
92
|
+
const plan = input.publish === true
|
|
93
|
+
? this.db.raw
|
|
94
|
+
.sql `UPDATE "knowledgeItem" SET "status" = ${txt(input.to)}, "publishedVersionId" = "latestVersionId" WHERE "id" = ${txt(id)} AND "status" = ${txt(input.from)}`
|
|
95
|
+
.affectedCount()
|
|
96
|
+
.build()
|
|
97
|
+
: input.unpublish === true
|
|
98
|
+
? this.db.raw
|
|
99
|
+
.sql `UPDATE "knowledgeItem" SET "status" = ${txt(input.to)}, "publishedVersionId" = NULL WHERE "id" = ${txt(id)} AND "status" = ${txt(input.from)}`
|
|
100
|
+
.affectedCount()
|
|
101
|
+
.build()
|
|
102
|
+
: this.db.raw
|
|
103
|
+
.sql `UPDATE "knowledgeItem" SET "status" = ${txt(input.to)} WHERE "id" = ${txt(id)} AND "status" = ${txt(input.from)}`
|
|
104
|
+
.affectedCount()
|
|
105
|
+
.build();
|
|
106
|
+
const stats = await tx.execute(plan);
|
|
107
|
+
if (stats.affectedRows === 0) {
|
|
108
|
+
return {
|
|
109
|
+
item: cur,
|
|
110
|
+
event: null,
|
|
111
|
+
transitioned: false,
|
|
112
|
+
reason: "status_mismatch",
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const event = await tx.orm.public.KnowledgeStatusEvent.create({
|
|
116
|
+
id: input.eventId ?? crypto.randomUUID(),
|
|
117
|
+
itemId: id,
|
|
118
|
+
from: input.from,
|
|
119
|
+
to: input.to,
|
|
120
|
+
actor: input.actor,
|
|
121
|
+
reason: input.reason ?? null,
|
|
122
|
+
});
|
|
123
|
+
const item = await tx.orm.public.KnowledgeItem.where({ id }).first();
|
|
124
|
+
return { item, event, transitioned: true };
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
async listStatusEvents(itemId) {
|
|
128
|
+
return this.db.orm.public.KnowledgeStatusEvent.where({ itemId })
|
|
129
|
+
.orderBy((r) => r.createdAt.asc())
|
|
130
|
+
.all();
|
|
131
|
+
}
|
|
132
|
+
async searchItems(opts) {
|
|
133
|
+
const limit = opts.limit ?? 20;
|
|
134
|
+
const status = opts.status ?? "PUBLISHED";
|
|
135
|
+
const plan = this.db.raw.sql `
|
|
136
|
+
SELECT i."id" AS "itemId", i."slug" AS "slug", i."kind" AS "kind",
|
|
137
|
+
v."id" AS "versionId", v."title" AS "title", v."summary" AS "summary",
|
|
138
|
+
ts_headline('simple', v."title" || ' ' || v."body", q,
|
|
139
|
+
'MaxWords=32, MinWords=10, ShortWord=2, HighlightAll=FALSE') AS "snippet",
|
|
140
|
+
ts_rank(to_tsvector('simple', v."title" || ' ' || v."body"), q) AS "rank"
|
|
141
|
+
FROM "knowledgeItem" i
|
|
142
|
+
JOIN "knowledgeVersion" v ON v."id" = i."publishedVersionId"
|
|
143
|
+
CROSS JOIN plainto_tsquery('simple', ${txt(opts.query)}) q
|
|
144
|
+
WHERE i."status" = ${txt(status)}
|
|
145
|
+
AND to_tsvector('simple', v."title" || ' ' || v."body") @@ q
|
|
146
|
+
AND (${txt(opts.kind)}::text IS NULL OR i."kind" = ${txt(opts.kind)})
|
|
147
|
+
AND (${txt(opts.capabilityRef)}::text IS NULL OR EXISTS (
|
|
148
|
+
SELECT 1 FROM "knowledgeItemCapability" ic
|
|
149
|
+
JOIN "knowledgeCapability" cp
|
|
150
|
+
ON cp."id" = ic."capabilityId"
|
|
151
|
+
WHERE ic."itemId" = i."id" AND cp."name" = ${txt(opts.capabilityRef)}))
|
|
152
|
+
ORDER BY "rank" DESC
|
|
153
|
+
LIMIT ${param(limit, { codecId: "pg/int4@1" })}`
|
|
154
|
+
.returnsRow({
|
|
155
|
+
itemId: "pg/text@1",
|
|
156
|
+
slug: "pg/text@1",
|
|
157
|
+
kind: "pg/text@1",
|
|
158
|
+
versionId: "pg/text@1",
|
|
159
|
+
title: "pg/text@1",
|
|
160
|
+
summary: "pg/text@1",
|
|
161
|
+
snippet: "pg/text@1",
|
|
162
|
+
rank: "pg/float4@1",
|
|
163
|
+
})
|
|
164
|
+
.build();
|
|
165
|
+
const rows = await this.db.runtime().query(plan);
|
|
166
|
+
const out = [];
|
|
167
|
+
for await (const r of rows) {
|
|
168
|
+
out.push({
|
|
169
|
+
itemId: r.itemId,
|
|
170
|
+
slug: r.slug,
|
|
171
|
+
kind: r.kind,
|
|
172
|
+
versionId: r.versionId,
|
|
173
|
+
title: r.title,
|
|
174
|
+
summary: r.summary,
|
|
175
|
+
snippet: r.snippet,
|
|
176
|
+
rank: r.rank,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { Models } from "../prisma/contract.d.js";
|
|
2
|
+
import type { PrismaDb } from "./event-repository.js";
|
|
3
|
+
type CapabilityRow = Models.public_KnowledgeCapability;
|
|
4
|
+
type RelationRow = Models.public_KnowledgeRelation;
|
|
5
|
+
type EvidenceRow = Models.public_KnowledgeEvidence;
|
|
6
|
+
type GapRow = Models.public_KnowledgeGap;
|
|
7
|
+
export interface KnowledgeCapabilityUpsert {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
kind: string;
|
|
11
|
+
description?: string | null;
|
|
12
|
+
source: string;
|
|
13
|
+
verified: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface KnowledgeRelationInsert {
|
|
16
|
+
id: string;
|
|
17
|
+
fromItemId: string;
|
|
18
|
+
toItemId: string;
|
|
19
|
+
type: string;
|
|
20
|
+
createdBy: string;
|
|
21
|
+
}
|
|
22
|
+
export interface KnowledgeEvidenceInsert {
|
|
23
|
+
id: string;
|
|
24
|
+
versionId: string;
|
|
25
|
+
type: string;
|
|
26
|
+
uri: string;
|
|
27
|
+
label?: string | null;
|
|
28
|
+
addedBy: string;
|
|
29
|
+
}
|
|
30
|
+
export interface KnowledgeGapRecord {
|
|
31
|
+
id: string;
|
|
32
|
+
normalizedQuery: string;
|
|
33
|
+
sampleQuery: string;
|
|
34
|
+
source: string;
|
|
35
|
+
sourceRef?: string | null;
|
|
36
|
+
capabilityRef?: string | null;
|
|
37
|
+
intent?: string | null;
|
|
38
|
+
}
|
|
39
|
+
export declare const KNOWLEDGE_EVIDENCE_CAP = 50;
|
|
40
|
+
export declare const KNOWLEDGE_GAP_SAMPLES_CAP = 10;
|
|
41
|
+
export declare class KnowledgeTaxonomyRepository {
|
|
42
|
+
private readonly db;
|
|
43
|
+
constructor(db: PrismaDb);
|
|
44
|
+
upsertCapability(input: KnowledgeCapabilityUpsert): Promise<{
|
|
45
|
+
row: CapabilityRow;
|
|
46
|
+
created: boolean;
|
|
47
|
+
}>;
|
|
48
|
+
getCapability(id: string): Promise<CapabilityRow | null>;
|
|
49
|
+
getCapabilityByName(name: string): Promise<CapabilityRow | null>;
|
|
50
|
+
listCapabilities(opts?: {
|
|
51
|
+
verified?: boolean;
|
|
52
|
+
kind?: string;
|
|
53
|
+
limit?: number;
|
|
54
|
+
}): Promise<CapabilityRow[]>;
|
|
55
|
+
linkCapability(itemId: string, capabilityId: string): Promise<{
|
|
56
|
+
created: boolean;
|
|
57
|
+
}>;
|
|
58
|
+
unlinkCapability(itemId: string, capabilityId: string): Promise<{
|
|
59
|
+
removed: boolean;
|
|
60
|
+
}>;
|
|
61
|
+
capabilitiesForItem(itemId: string): Promise<CapabilityRow[]>;
|
|
62
|
+
itemsForCapability(name: string): Promise<string[]>;
|
|
63
|
+
addRelation(input: KnowledgeRelationInsert): Promise<{
|
|
64
|
+
row: RelationRow | null;
|
|
65
|
+
created: boolean;
|
|
66
|
+
}>;
|
|
67
|
+
removeRelation(id: string): Promise<{
|
|
68
|
+
removed: boolean;
|
|
69
|
+
}>;
|
|
70
|
+
relationsFor(itemId: string): Promise<{
|
|
71
|
+
outgoing: RelationRow[];
|
|
72
|
+
incoming: RelationRow[];
|
|
73
|
+
}>;
|
|
74
|
+
addEvidence(input: KnowledgeEvidenceInsert, cap?: number): Promise<{
|
|
75
|
+
row: EvidenceRow;
|
|
76
|
+
ok: true;
|
|
77
|
+
} | {
|
|
78
|
+
ok: false;
|
|
79
|
+
reason: string;
|
|
80
|
+
}>;
|
|
81
|
+
listEvidence(versionId: string): Promise<EvidenceRow[]>;
|
|
82
|
+
removeEvidence(id: string): Promise<{
|
|
83
|
+
removed: boolean;
|
|
84
|
+
}>;
|
|
85
|
+
itemsCiting(uri: string): Promise<EvidenceRow[]>;
|
|
86
|
+
recordGap(input: KnowledgeGapRecord, cap?: number): Promise<{
|
|
87
|
+
row: GapRow;
|
|
88
|
+
created: boolean;
|
|
89
|
+
}>;
|
|
90
|
+
getGap(id: string): Promise<GapRow | null>;
|
|
91
|
+
listGaps(opts?: {
|
|
92
|
+
status?: string;
|
|
93
|
+
orderBy?: "count" | "lastSeen";
|
|
94
|
+
limit?: number;
|
|
95
|
+
}): Promise<GapRow[]>;
|
|
96
|
+
transitionGap(id: string, input: {
|
|
97
|
+
from: string;
|
|
98
|
+
to: string;
|
|
99
|
+
linkedItemId?: string | null;
|
|
100
|
+
}): Promise<{
|
|
101
|
+
gap: GapRow | null;
|
|
102
|
+
transitioned: boolean;
|
|
103
|
+
reason?: string;
|
|
104
|
+
}>;
|
|
105
|
+
}
|
|
106
|
+
export {};
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { param } from "@prisma/orm-postgres/relational-core/expression";
|
|
2
|
+
const txt = (v) => param(v ?? null, { codecId: "pg/text@1" });
|
|
3
|
+
function isUniqueViolation(err) {
|
|
4
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
5
|
+
return /unique|duplicate/i.test(m);
|
|
6
|
+
}
|
|
7
|
+
export const KNOWLEDGE_EVIDENCE_CAP = 50;
|
|
8
|
+
export const KNOWLEDGE_GAP_SAMPLES_CAP = 10;
|
|
9
|
+
export class KnowledgeTaxonomyRepository {
|
|
10
|
+
db;
|
|
11
|
+
constructor(db) {
|
|
12
|
+
this.db = db;
|
|
13
|
+
}
|
|
14
|
+
async upsertCapability(input) {
|
|
15
|
+
const plan = this.db.raw.sql `
|
|
16
|
+
INSERT INTO "knowledgeCapability"
|
|
17
|
+
("id","name","kind","description","source","verified","createdAt","updatedAt")
|
|
18
|
+
VALUES (${txt(input.id)}, ${txt(input.name)}, ${txt(input.kind)},
|
|
19
|
+
${txt(input.description)}, ${txt(input.source)}, ${param(input.verified, { codecId: "pg/bool@1" })},
|
|
20
|
+
now(), now())
|
|
21
|
+
ON CONFLICT ("name") DO UPDATE SET
|
|
22
|
+
"kind" = EXCLUDED."kind",
|
|
23
|
+
"description" = EXCLUDED."description",
|
|
24
|
+
"verified" = EXCLUDED."verified",
|
|
25
|
+
"updatedAt" = now()
|
|
26
|
+
RETURNING "id","name","kind","description","source","verified","createdAt","updatedAt",
|
|
27
|
+
(xmax = 0) AS "created"`
|
|
28
|
+
.returnsRow({
|
|
29
|
+
id: "pg/text@1",
|
|
30
|
+
name: "pg/text@1",
|
|
31
|
+
kind: "pg/text@1",
|
|
32
|
+
description: "pg/text@1",
|
|
33
|
+
source: "pg/text@1",
|
|
34
|
+
verified: "pg/bool@1",
|
|
35
|
+
createdAt: "pg/timestamptz-string@1",
|
|
36
|
+
updatedAt: "pg/timestamptz-string@1",
|
|
37
|
+
created: "pg/bool@1",
|
|
38
|
+
})
|
|
39
|
+
.build();
|
|
40
|
+
const rows = await this.db.runtime().query(plan);
|
|
41
|
+
for await (const r of rows) {
|
|
42
|
+
return {
|
|
43
|
+
row: {
|
|
44
|
+
id: r.id,
|
|
45
|
+
name: r.name,
|
|
46
|
+
kind: r.kind,
|
|
47
|
+
description: r.description,
|
|
48
|
+
source: r.source,
|
|
49
|
+
verified: r.verified,
|
|
50
|
+
createdAt: r.createdAt,
|
|
51
|
+
updatedAt: r.updatedAt,
|
|
52
|
+
},
|
|
53
|
+
created: r.created,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
throw new Error("upsertCapability: empty result");
|
|
57
|
+
}
|
|
58
|
+
async getCapability(id) {
|
|
59
|
+
return this.db.orm.public.KnowledgeCapability.where({ id }).first();
|
|
60
|
+
}
|
|
61
|
+
async getCapabilityByName(name) {
|
|
62
|
+
return this.db.orm.public.KnowledgeCapability.where({ name }).first();
|
|
63
|
+
}
|
|
64
|
+
async listCapabilities(opts) {
|
|
65
|
+
let q = this.db.orm.public.KnowledgeCapability.orderBy((r) => r.name.asc());
|
|
66
|
+
if (opts?.verified !== undefined)
|
|
67
|
+
q = q.where({ verified: opts.verified });
|
|
68
|
+
if (opts?.kind !== undefined)
|
|
69
|
+
q = q.where({ kind: opts.kind });
|
|
70
|
+
return q.limit(opts?.limit ?? 1000).all();
|
|
71
|
+
}
|
|
72
|
+
async linkCapability(itemId, capabilityId) {
|
|
73
|
+
const plan = this.db.raw.sql `
|
|
74
|
+
INSERT INTO "knowledgeItemCapability" ("itemId","capabilityId")
|
|
75
|
+
VALUES (${txt(itemId)}, ${txt(capabilityId)})
|
|
76
|
+
ON CONFLICT ("itemId","capabilityId") DO NOTHING`
|
|
77
|
+
.affectedCount()
|
|
78
|
+
.build();
|
|
79
|
+
const stats = await this.db.runtime().execute(plan);
|
|
80
|
+
return { created: stats.affectedRows > 0 };
|
|
81
|
+
}
|
|
82
|
+
async unlinkCapability(itemId, capabilityId) {
|
|
83
|
+
const plan = this.db.raw.sql `
|
|
84
|
+
DELETE FROM "knowledgeItemCapability"
|
|
85
|
+
WHERE "itemId" = ${txt(itemId)} AND "capabilityId" = ${txt(capabilityId)}`
|
|
86
|
+
.affectedCount()
|
|
87
|
+
.build();
|
|
88
|
+
const stats = await this.db.runtime().execute(plan);
|
|
89
|
+
return { removed: stats.affectedRows > 0 };
|
|
90
|
+
}
|
|
91
|
+
async capabilitiesForItem(itemId) {
|
|
92
|
+
const plan = this.db.raw.sql `
|
|
93
|
+
SELECT cp."id","name","kind","description","source","verified","createdAt","updatedAt"
|
|
94
|
+
FROM "knowledgeCapability" cp
|
|
95
|
+
JOIN "knowledgeItemCapability" ic ON ic."capabilityId" = cp."id"
|
|
96
|
+
WHERE ic."itemId" = ${txt(itemId)}
|
|
97
|
+
ORDER BY cp."name"`
|
|
98
|
+
.returnsRow({
|
|
99
|
+
id: "pg/text@1",
|
|
100
|
+
name: "pg/text@1",
|
|
101
|
+
kind: "pg/text@1",
|
|
102
|
+
description: "pg/text@1",
|
|
103
|
+
source: "pg/text@1",
|
|
104
|
+
verified: "pg/bool@1",
|
|
105
|
+
createdAt: "pg/timestamptz-string@1",
|
|
106
|
+
updatedAt: "pg/timestamptz-string@1",
|
|
107
|
+
})
|
|
108
|
+
.build();
|
|
109
|
+
const rows = await this.db.runtime().query(plan);
|
|
110
|
+
const out = [];
|
|
111
|
+
for await (const r of rows)
|
|
112
|
+
out.push(r);
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
async itemsForCapability(name) {
|
|
116
|
+
const plan = this.db.raw.sql `
|
|
117
|
+
SELECT ic."itemId" AS "itemId"
|
|
118
|
+
FROM "knowledgeItemCapability" ic
|
|
119
|
+
JOIN "knowledgeCapability" cp ON cp."id" = ic."capabilityId"
|
|
120
|
+
WHERE cp."name" = ${txt(name)}`
|
|
121
|
+
.returnsRow({ itemId: "pg/text@1" })
|
|
122
|
+
.build();
|
|
123
|
+
const rows = await this.db.runtime().query(plan);
|
|
124
|
+
const out = [];
|
|
125
|
+
for await (const r of rows)
|
|
126
|
+
out.push(r.itemId);
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
async addRelation(input) {
|
|
130
|
+
try {
|
|
131
|
+
const row = await this.db.orm.public.KnowledgeRelation.create({
|
|
132
|
+
id: input.id,
|
|
133
|
+
fromItemId: input.fromItemId,
|
|
134
|
+
toItemId: input.toItemId,
|
|
135
|
+
type: input.type,
|
|
136
|
+
createdBy: input.createdBy,
|
|
137
|
+
});
|
|
138
|
+
return { row, created: true };
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
if (isUniqueViolation(err))
|
|
142
|
+
return { row: null, created: false };
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async removeRelation(id) {
|
|
147
|
+
const plan = this.db.raw.sql `
|
|
148
|
+
DELETE FROM "knowledgeRelation" WHERE "id" = ${txt(id)}`
|
|
149
|
+
.affectedCount()
|
|
150
|
+
.build();
|
|
151
|
+
const stats = await this.db.runtime().execute(plan);
|
|
152
|
+
return { removed: stats.affectedRows > 0 };
|
|
153
|
+
}
|
|
154
|
+
async relationsFor(itemId) {
|
|
155
|
+
const orm = this.db.orm.public.KnowledgeRelation;
|
|
156
|
+
const outgoing = await orm.where({ fromItemId: itemId }).all();
|
|
157
|
+
const incoming = await orm.where({ toItemId: itemId }).all();
|
|
158
|
+
return { outgoing, incoming };
|
|
159
|
+
}
|
|
160
|
+
async addEvidence(input, cap = KNOWLEDGE_EVIDENCE_CAP) {
|
|
161
|
+
return this.db.transaction(async (tx) => {
|
|
162
|
+
const v = await tx.orm.public.KnowledgeVersion.where({
|
|
163
|
+
id: input.versionId,
|
|
164
|
+
}).first();
|
|
165
|
+
if (!v)
|
|
166
|
+
return { ok: false, reason: "missing_version" };
|
|
167
|
+
const plan = this.db.raw.sql `
|
|
168
|
+
SELECT count(*)::int AS "n" FROM "knowledgeEvidence"
|
|
169
|
+
WHERE "versionId" = ${txt(input.versionId)}`
|
|
170
|
+
.returnsRow({ n: "pg/int4@1" })
|
|
171
|
+
.build();
|
|
172
|
+
const counted = await tx.query(plan);
|
|
173
|
+
let n = 0;
|
|
174
|
+
for await (const r of counted)
|
|
175
|
+
n = r.n;
|
|
176
|
+
if (n >= cap)
|
|
177
|
+
return { ok: false, reason: "cap_exceeded" };
|
|
178
|
+
const row = await tx.orm.public.KnowledgeEvidence.create({
|
|
179
|
+
id: input.id,
|
|
180
|
+
versionId: input.versionId,
|
|
181
|
+
type: input.type,
|
|
182
|
+
uri: input.uri,
|
|
183
|
+
label: input.label ?? null,
|
|
184
|
+
addedBy: input.addedBy,
|
|
185
|
+
});
|
|
186
|
+
return { ok: true, row };
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
async listEvidence(versionId) {
|
|
190
|
+
return this.db.orm.public.KnowledgeEvidence.where({ versionId })
|
|
191
|
+
.orderBy((r) => r.createdAt.asc())
|
|
192
|
+
.all();
|
|
193
|
+
}
|
|
194
|
+
async removeEvidence(id) {
|
|
195
|
+
const plan = this.db.raw.sql `
|
|
196
|
+
DELETE FROM "knowledgeEvidence" WHERE "id" = ${txt(id)}`
|
|
197
|
+
.affectedCount()
|
|
198
|
+
.build();
|
|
199
|
+
const stats = await this.db.runtime().execute(plan);
|
|
200
|
+
return { removed: stats.affectedRows > 0 };
|
|
201
|
+
}
|
|
202
|
+
async itemsCiting(uri) {
|
|
203
|
+
return this.db.orm.public.KnowledgeEvidence.where({ uri }).all();
|
|
204
|
+
}
|
|
205
|
+
async recordGap(input, cap = KNOWLEDGE_GAP_SAMPLES_CAP) {
|
|
206
|
+
const samples = JSON.stringify([input.sampleQuery]);
|
|
207
|
+
const plan = this.db.raw.sql `
|
|
208
|
+
INSERT INTO "knowledgeGap"
|
|
209
|
+
("id","normalizedQuery","sampleQueries","count","capabilityRef","intent","source","sourceRef","status","linkedItemId","firstSeenAt","lastSeenAt")
|
|
210
|
+
VALUES (${txt(input.id)}, ${txt(input.normalizedQuery)},
|
|
211
|
+
to_jsonb(ARRAY[${txt(input.sampleQuery)}::text])::json, 1,
|
|
212
|
+
${txt(input.capabilityRef)}, ${txt(input.intent)},
|
|
213
|
+
${txt(input.source)}, ${txt(input.sourceRef)},
|
|
214
|
+
'OPEN', NULL, now(), now())
|
|
215
|
+
ON CONFLICT ("normalizedQuery") DO UPDATE SET
|
|
216
|
+
"count" = "knowledgeGap"."count" + 1,
|
|
217
|
+
"lastSeenAt" = now(),
|
|
218
|
+
"capabilityRef" = COALESCE("knowledgeGap"."capabilityRef", EXCLUDED."capabilityRef"),
|
|
219
|
+
"intent" = COALESCE("knowledgeGap"."intent", EXCLUDED."intent"),
|
|
220
|
+
"sampleQueries" = CASE
|
|
221
|
+
WHEN jsonb_array_length("knowledgeGap"."sampleQueries"::jsonb) < ${param(cap, { codecId: "pg/int4@1" })}
|
|
222
|
+
AND NOT ("knowledgeGap"."sampleQueries"::jsonb ? ${txt(input.sampleQuery)})
|
|
223
|
+
THEN ("knowledgeGap"."sampleQueries"::jsonb || to_jsonb(ARRAY[${txt(input.sampleQuery)}::text]))::json
|
|
224
|
+
ELSE "knowledgeGap"."sampleQueries"
|
|
225
|
+
END
|
|
226
|
+
RETURNING "id","normalizedQuery","sampleQueries","count","capabilityRef",
|
|
227
|
+
"intent","source","sourceRef","status","linkedItemId","firstSeenAt","lastSeenAt",
|
|
228
|
+
(xmax = 0) AS "created"`
|
|
229
|
+
.returnsRow({
|
|
230
|
+
id: "pg/text@1",
|
|
231
|
+
normalizedQuery: "pg/text@1",
|
|
232
|
+
sampleQueries: "pg/json@1",
|
|
233
|
+
count: "pg/int4@1",
|
|
234
|
+
capabilityRef: "pg/text@1",
|
|
235
|
+
intent: "pg/text@1",
|
|
236
|
+
source: "pg/text@1",
|
|
237
|
+
sourceRef: "pg/text@1",
|
|
238
|
+
status: "pg/text@1",
|
|
239
|
+
linkedItemId: "pg/text@1",
|
|
240
|
+
firstSeenAt: "pg/timestamptz-string@1",
|
|
241
|
+
lastSeenAt: "pg/timestamptz-string@1",
|
|
242
|
+
created: "pg/bool@1",
|
|
243
|
+
})
|
|
244
|
+
.build();
|
|
245
|
+
const rows = await this.db.runtime().query(plan);
|
|
246
|
+
for await (const r of rows) {
|
|
247
|
+
const { created, ...rest } = r;
|
|
248
|
+
return {
|
|
249
|
+
row: { ...rest, sampleQueries: rest.sampleQueries },
|
|
250
|
+
created,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
throw new Error("recordGap: empty result");
|
|
254
|
+
}
|
|
255
|
+
async getGap(id) {
|
|
256
|
+
return this.db.orm.public.KnowledgeGap.where({ id }).first();
|
|
257
|
+
}
|
|
258
|
+
async listGaps(opts) {
|
|
259
|
+
const base = this.db.orm.public.KnowledgeGap;
|
|
260
|
+
const ordered = opts?.orderBy === "lastSeen"
|
|
261
|
+
? base.orderBy((r) => r.lastSeenAt.desc())
|
|
262
|
+
: base.orderBy((r) => r.count.desc());
|
|
263
|
+
const q = opts?.status !== undefined ? ordered.where({ status: opts.status }) : ordered;
|
|
264
|
+
return q.limit(opts?.limit ?? 500).all();
|
|
265
|
+
}
|
|
266
|
+
async transitionGap(id, input) {
|
|
267
|
+
const cur = await this.getGap(id);
|
|
268
|
+
if (!cur)
|
|
269
|
+
return { gap: null, transitioned: false, reason: "missing" };
|
|
270
|
+
const plan = input.linkedItemId !== undefined
|
|
271
|
+
? this.db.raw
|
|
272
|
+
.sql `UPDATE "knowledgeGap" SET "status" = ${txt(input.to)}, "linkedItemId" = ${txt(input.linkedItemId)} WHERE "id" = ${txt(id)} AND "status" = ${txt(input.from)}`
|
|
273
|
+
.affectedCount()
|
|
274
|
+
.build()
|
|
275
|
+
: this.db.raw
|
|
276
|
+
.sql `UPDATE "knowledgeGap" SET "status" = ${txt(input.to)} WHERE "id" = ${txt(id)} AND "status" = ${txt(input.from)}`
|
|
277
|
+
.affectedCount()
|
|
278
|
+
.build();
|
|
279
|
+
const stats = await this.db.runtime().execute(plan);
|
|
280
|
+
if (stats.affectedRows === 0) {
|
|
281
|
+
return { gap: cur, transitioned: false, reason: "status_mismatch" };
|
|
282
|
+
}
|
|
283
|
+
return { gap: await this.getGap(id), transitioned: true };
|
|
284
|
+
}
|
|
285
|
+
}
|
package/package.json
CHANGED