kibi-cli 2.10.0 → 2.12.0

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.
Files changed (57) hide show
  1. package/dist/operations/bootstrap/candidates.d.ts +2 -1
  2. package/dist/operations/bootstrap/candidates.d.ts.map +1 -1
  3. package/dist/operations/bootstrap/candidates.js +2 -2
  4. package/dist/operations/bootstrap/generate.d.ts.map +1 -1
  5. package/dist/operations/bootstrap/generate.js +10 -3
  6. package/dist/operations/bootstrap/intent-claims.d.ts +2 -1
  7. package/dist/operations/bootstrap/intent-claims.d.ts.map +1 -1
  8. package/dist/operations/bootstrap/intent-claims.js +6 -4
  9. package/dist/operations/bootstrap/markdown-candidates.d.ts +2 -1
  10. package/dist/operations/bootstrap/markdown-candidates.d.ts.map +1 -1
  11. package/dist/operations/bootstrap/markdown-candidates.js +7 -5
  12. package/dist/operations/bootstrap/requirement-claims.d.ts +60 -2
  13. package/dist/operations/bootstrap/requirement-claims.d.ts.map +1 -1
  14. package/dist/operations/bootstrap/requirement-claims.js +324 -20
  15. package/dist/operations/modeling/predicate-applyplan.d.ts +13 -0
  16. package/dist/operations/modeling/predicate-applyplan.d.ts.map +1 -1
  17. package/dist/operations/modeling/predicate-applyplan.js +56 -18
  18. package/dist/operations/modeling/predicate-binding-hints.d.ts +11 -0
  19. package/dist/operations/modeling/predicate-binding-hints.d.ts.map +1 -0
  20. package/dist/operations/modeling/predicate-binding-hints.js +97 -0
  21. package/dist/operations/modeling/predicate-bindings.d.ts +24 -1
  22. package/dist/operations/modeling/predicate-bindings.d.ts.map +1 -1
  23. package/dist/operations/modeling/predicate-bindings.js +129 -4
  24. package/dist/operations/modeling/predicate-catalog-1.d.ts.map +1 -1
  25. package/dist/operations/modeling/predicate-catalog-1.js +3 -0
  26. package/dist/operations/modeling/predicate-catalog-2.d.ts.map +1 -1
  27. package/dist/operations/modeling/predicate-catalog-2.js +3 -0
  28. package/dist/operations/modeling/predicate-catalog-3.d.ts.map +1 -1
  29. package/dist/operations/modeling/predicate-catalog-3.js +7 -0
  30. package/dist/operations/modeling/predicate-catalog-4.d.ts.map +1 -1
  31. package/dist/operations/modeling/predicate-catalog-4.js +2 -0
  32. package/dist/operations/modeling/predicate-closed-vocabularies.d.ts +104 -0
  33. package/dist/operations/modeling/predicate-closed-vocabularies.d.ts.map +1 -0
  34. package/dist/operations/modeling/predicate-closed-vocabularies.js +104 -0
  35. package/dist/operations/modeling/predicate-types.d.ts +19 -1
  36. package/dist/operations/modeling/predicate-types.d.ts.map +1 -1
  37. package/dist/operations/modeling/predicate-utils.d.ts +11 -1
  38. package/dist/operations/modeling/predicate-utils.d.ts.map +1 -1
  39. package/dist/operations/modeling/predicate-utils.js +19 -3
  40. package/dist/operations/modeling/suggest-predicates.d.ts.map +1 -1
  41. package/dist/operations/modeling/suggest-predicates.js +112 -16
  42. package/dist/operations/semantic-advisor/observation-plan.d.ts +7 -0
  43. package/dist/operations/semantic-advisor/observation-plan.d.ts.map +1 -1
  44. package/dist/operations/semantic-advisor/observation-plan.js +13 -14
  45. package/dist/public/operations/contracts.d.ts.map +1 -1
  46. package/dist/public/operations/contracts.js +4 -0
  47. package/dist/public/skills/kibi-bootstrap/SKILL.md +2 -2
  48. package/dist/public/skills/kibi-usage/SKILL.md +20 -7
  49. package/dist/public/skills/kibi-usage/resources/workflows.md +2 -2
  50. package/dist/utils/strict-modeling.d.ts +1 -0
  51. package/dist/utils/strict-modeling.d.ts.map +1 -1
  52. package/dist/utils/strict-modeling.js +1 -1
  53. package/package.json +2 -2
  54. package/src/public/operations/contracts.ts +5 -0
  55. package/src/public/skills/kibi-bootstrap/SKILL.md +2 -2
  56. package/src/public/skills/kibi-usage/SKILL.md +20 -7
  57. package/src/public/skills/kibi-usage/resources/workflows.md +2 -2
@@ -1,4 +1,5 @@
1
- import { isConventionalSubjectKey, normalizeSubjectKey, } from "../../utils/strict-modeling.js";
1
+ import { createHash } from "node:crypto";
2
+ import { isConventionalSubjectKey, normalizeSourceKey, normalizeSubjectKey, } from "../../utils/strict-modeling.js";
2
3
  // implements REQ-KIBI-BOOTSTRAP-PLAN
3
4
  export function normalizeClaimStatement(statement) {
4
5
  return statement
@@ -67,16 +68,164 @@ function snakeSegment(value) {
67
68
  .replace(/[^a-z0-9]+/g, "_")
68
69
  .replace(/^_+|_+$/g, "");
69
70
  }
71
+ /** The longest aspect a bootstrap key keeps as derived. */
72
+ export const MAX_ASPECT_WORDS = 4;
73
+ export const MAX_ASPECT_CHARS = 40;
74
+ /** Words that start a dependent clause or a second item: the aspect ends before them. */
75
+ const ASPECT_BOUNDARY_WORDS = new Set([
76
+ "when",
77
+ "whenever",
78
+ "while",
79
+ "if",
80
+ "unless",
81
+ "without",
82
+ "after",
83
+ "before",
84
+ "until",
85
+ "because",
86
+ "once",
87
+ "as",
88
+ "by",
89
+ "via",
90
+ "during",
91
+ "except",
92
+ "so",
93
+ "that",
94
+ "which",
95
+ "who",
96
+ "where",
97
+ "since",
98
+ "for",
99
+ "and",
100
+ "or",
101
+ ]);
102
+ /** Words that carry no meaning in a key on their own. */
103
+ const ASPECT_STOP_WORDS = new Set([
104
+ "a",
105
+ "an",
106
+ "the",
107
+ "be",
108
+ "is",
109
+ "are",
110
+ "was",
111
+ "were",
112
+ "been",
113
+ "being",
114
+ "to",
115
+ "of",
116
+ "in",
117
+ "on",
118
+ "at",
119
+ "with",
120
+ "from",
121
+ "into",
122
+ "its",
123
+ "it",
124
+ "their",
125
+ "they",
126
+ "them",
127
+ "this",
128
+ "these",
129
+ "those",
130
+ "can",
131
+ "could",
132
+ "will",
133
+ "would",
134
+ "may",
135
+ "might",
136
+ "must",
137
+ "shall",
138
+ "should",
139
+ "do",
140
+ "does",
141
+ "has",
142
+ "have",
143
+ "had",
144
+ "any",
145
+ "all",
146
+ "each",
147
+ "every",
148
+ "some",
149
+ "only",
150
+ "also",
151
+ "then",
152
+ "than",
153
+ "not",
154
+ "no",
155
+ ]);
156
+ function fitsAspect(words) {
157
+ return (words.length > 0 &&
158
+ words.length <= MAX_ASPECT_WORDS &&
159
+ words.join("_").length <= MAX_ASPECT_CHARS);
160
+ }
161
+ function trimStopWords(words) {
162
+ let start = 0;
163
+ let end = words.length;
164
+ while (start < end && ASPECT_STOP_WORDS.has(words[start] ?? ""))
165
+ start += 1;
166
+ while (end > start && ASPECT_STOP_WORDS.has(words[end - 1] ?? ""))
167
+ end -= 1;
168
+ return words.slice(start, end);
169
+ }
170
+ /**
171
+ * A short noun-phrase aspect for a long one, deterministically: the words
172
+ * before the first clause boundary (when, while, for, and, ...), without
173
+ * leading or trailing stop words; if that is still longer than four words or
174
+ * forty characters, its content words (no stop words or -ly adverbs); if
175
+ * those are still too long, the first content word and the last two, where a
176
+ * noun phrase keeps its head noun. An aspect that already fits is returned
177
+ * unchanged.
178
+ */
179
+ // implements REQ-bootstrap-claim-name-length
180
+ export function shortenSubjectAspect(aspect) {
181
+ const words = aspect.split("_").filter(Boolean);
182
+ if (fitsAspect(words))
183
+ return aspect;
184
+ const boundary = words.findIndex((word, index) => index > 0 &&
185
+ ASPECT_BOUNDARY_WORDS.has(word) &&
186
+ trimStopWords(words.slice(0, index)).length > 0);
187
+ const head = trimStopWords(boundary < 0 ? words : words.slice(0, boundary));
188
+ if (fitsAspect(head))
189
+ return head.join("_");
190
+ // Content words only: no stop words, no -ly adverbs.
191
+ const content = head.filter((word) => !ASPECT_STOP_WORDS.has(word) && !(word.length > 4 && word.endsWith("ly")));
192
+ if (fitsAspect(content))
193
+ return content.join("_");
194
+ // The leading word (the action or state) and the closing words, where an
195
+ // English noun phrase keeps its head noun.
196
+ const picked = Array.from(new Set([content[0], ...content.slice(-(MAX_ASPECT_WORDS - 2))])).filter((word) => typeof word === "string");
197
+ while (picked.length > 1 && picked.join("_").length > MAX_ASPECT_CHARS)
198
+ picked.splice(1, 1);
199
+ const short = picked.join("_");
200
+ return short.length > 0
201
+ ? short.slice(0, MAX_ASPECT_CHARS).replace(/_+$/, "")
202
+ : (words[0] ?? aspect).slice(0, MAX_ASPECT_CHARS);
203
+ }
204
+ function withShortAspect(component, aspect) {
205
+ const full = `${component}.${aspect}`;
206
+ const short = shortenSubjectAspect(aspect);
207
+ const candidate = `${component}.${short}`;
208
+ if (!isConventionalSubjectKey(candidate))
209
+ return {
210
+ ok: false,
211
+ reason: `subject key "${candidate}" does not follow component.aspect[.sub]`,
212
+ };
213
+ return short === aspect
214
+ ? { ok: true, subjectKey: candidate }
215
+ : { ok: true, subjectKey: candidate, shortenedFrom: full };
216
+ }
70
217
  /**
71
218
  * The bootstrap subject key in the component.aspect[.sub] shape that
72
219
  * subject-key-shape checks. A subject that already has that shape is kept.
73
220
  * Otherwise the component comes from the declared `component` (claim or
74
221
  * knowledge source) and the aspect from the claim's subject; a one-word
75
222
  * subject is itself the component and the constrained property becomes the
76
- * aspect. When no component can be named the claim is not resolved, so the
77
- * caller reports it instead of writing a malformed key.
223
+ * aspect. An aspect longer than four words or forty characters is shortened
224
+ * to a noun phrase and the original key is returned in `shortenedFrom`. When
225
+ * no component can be named the claim is not resolved, so the caller reports
226
+ * it instead of writing a malformed key.
78
227
  */
79
- // implements REQ-bootstrap-subject-key-shape
228
+ // implements REQ-bootstrap-subject-key-shape, REQ-bootstrap-claim-name-length
80
229
  export function resolveBootstrapSubjectKey(subject, propertyKey, component) {
81
230
  const stripped = subject.trim().replace(/^(?:the|a|an)\s+/i, "");
82
231
  let key;
@@ -91,28 +240,183 @@ export function resolveBootstrapSubjectKey(subject, propertyKey, component) {
91
240
  const flat = key.replace(/\./g, "_");
92
241
  const comp = component === undefined ? "" : snakeSegment(component);
93
242
  const property = snakeSegment(propertyKey);
94
- let candidate;
95
243
  if (comp) {
96
244
  const aspect = flat === comp
97
245
  ? property
98
246
  : flat.startsWith(`${comp}_`)
99
247
  ? flat.slice(comp.length + 1)
100
248
  : flat;
101
- candidate = `${comp}.${aspect}`;
102
- }
103
- else if (/^[a-z][a-z0-9]*$/.test(flat) && property) {
104
- candidate = `${flat}.${property}`;
249
+ return withShortAspect(comp, aspect);
105
250
  }
106
- else {
107
- return {
108
- ok: false,
109
- reason: `subject key "${flat}" names no component, so it would violate component.aspect[.sub]`,
110
- };
251
+ if (/^[a-z][a-z0-9]*$/.test(flat) && property)
252
+ return withShortAspect(flat, property);
253
+ return {
254
+ ok: false,
255
+ reason: `subject key "${flat}" names no component, so it would violate component.aspect[.sub]`,
256
+ };
257
+ }
258
+ /**
259
+ * Keeps the subject keys of one bootstrap plan distinct. Claims about the
260
+ * same subject (the same full key) share a key; when shortening collapses two
261
+ * different subjects onto one key, the later one gets a third segment from
262
+ * its own wording (or a short digest) instead of colliding.
263
+ */
264
+ // implements REQ-bootstrap-claim-name-length
265
+ export class SubjectKeyRegistry {
266
+ owners = new Map();
267
+ assigned = new Map();
268
+ /** The plan-wide key for a resolution, and the key it collided with, if any. */
269
+ assign(resolution) {
270
+ const identity = resolution.shortenedFrom ?? resolution.subjectKey;
271
+ const known = this.assigned.get(identity);
272
+ if (known !== undefined)
273
+ return { subjectKey: known };
274
+ const owner = this.owners.get(resolution.subjectKey);
275
+ if (owner === undefined || owner === identity) {
276
+ this.owners.set(resolution.subjectKey, identity);
277
+ this.assigned.set(identity, resolution.subjectKey);
278
+ return { subjectKey: resolution.subjectKey };
279
+ }
280
+ const used = new Set(resolution.subjectKey.split(/[._]/));
281
+ const fullWords = identity.split(".").slice(1).join("_").split("_");
282
+ const qualifier = fullWords.find((word) => /^[a-z][a-z0-9]*$/.test(word) &&
283
+ !used.has(word) &&
284
+ !ASPECT_STOP_WORDS.has(word) &&
285
+ !ASPECT_BOUNDARY_WORDS.has(word) &&
286
+ !this.owners.has(`${resolution.subjectKey}.${word}`));
287
+ const subjectKey = `${resolution.subjectKey}.${qualifier ?? `k${digest(identity)}`}`;
288
+ this.owners.set(subjectKey, identity);
289
+ this.assigned.set(identity, subjectKey);
290
+ return { subjectKey, collidedWith: resolution.subjectKey };
111
291
  }
112
- return isConventionalSubjectKey(candidate)
113
- ? { ok: true, subjectKey: candidate }
114
- : {
115
- ok: false,
116
- reason: `subject key "${candidate}" does not follow component.aspect[.sub]`,
117
- };
292
+ }
293
+ function digest(value) {
294
+ return createHash("sha256").update(value).digest("hex").slice(0, 6);
295
+ }
296
+ /**
297
+ * Resolve a claim's subject key for a plan and describe any renaming as a
298
+ * plan diagnostic, so the operator can pick a better name before applying.
299
+ */
300
+ // implements REQ-bootstrap-claim-name-length
301
+ export function planSubjectKey(subject, propertyKey, component, registry, location) {
302
+ const resolved = resolveBootstrapSubjectKey(subject, propertyKey, component);
303
+ if (!resolved.ok)
304
+ return { resolution: resolved, diagnostics: [] };
305
+ const diagnostics = [];
306
+ const assigned = registry?.assign(resolved) ?? {
307
+ subjectKey: resolved.subjectKey,
308
+ };
309
+ if (resolved.shortenedFrom)
310
+ diagnostics.push(`subject-key-shortened: claim at ${location} would have the subject key ${resolved.shortenedFrom}; its aspect is longer than ${MAX_ASPECT_WORDS} words or ${MAX_ASPECT_CHARS} characters, so the plan uses ${assigned.subjectKey}. Rename the subject after apply if another noun phrase fits better.`);
311
+ if (assigned.collidedWith)
312
+ diagnostics.push(`subject-key-disambiguated: claim at ${location} names a different subject than an earlier claim keyed ${assigned.collidedWith}, so the plan uses ${assigned.subjectKey} instead of reusing that key.`);
313
+ return {
314
+ resolution: {
315
+ ok: true,
316
+ subjectKey: assigned.subjectKey,
317
+ ...(resolved.shortenedFrom
318
+ ? { shortenedFrom: resolved.shortenedFrom }
319
+ : {}),
320
+ },
321
+ diagnostics,
322
+ };
323
+ }
324
+ function stepProperties(step) {
325
+ return step.properties !== null && typeof step.properties === "object"
326
+ ? step.properties
327
+ : {};
328
+ }
329
+ function subjectStepKey(step) {
330
+ const properties = stepProperties(step);
331
+ return step.type === "fact" &&
332
+ properties.fact_kind === "subject" &&
333
+ typeof properties.subject_key === "string" &&
334
+ typeof step.id === "string"
335
+ ? properties.subject_key
336
+ : null;
337
+ }
338
+ function retarget(relationships, renamed) {
339
+ return relationships.map((relationship) => {
340
+ const to = renamed.get(relationship.to);
341
+ return to === undefined ? relationship : { ...relationship, to };
342
+ });
343
+ }
344
+ function retargetStep(step, renamed) {
345
+ if (!Array.isArray(step.relationships))
346
+ return step;
347
+ const relationships = step.relationships;
348
+ return { ...step, relationships: retarget(relationships, renamed) };
349
+ }
350
+ /**
351
+ * One subject fact per subject_key in a bootstrap plan. The registry keeps
352
+ * different subjects on different keys, so claims that share a key name the
353
+ * same subject: the first selected claim's subject fact is kept, every later
354
+ * requirement links to it through constrains instead of minting another
355
+ * subject fact (which subject-key-identity would report), and the later
356
+ * sources' provenance is added to the kept fact's tags and body. Each shared
357
+ * key is reported as a subject-key-shared diagnostic. The result depends only
358
+ * on the candidate order, so the plan hash stays deterministic.
359
+ */
360
+ // implements REQ-bootstrap-subject-fact-shared
361
+ export function shareSubjectFacts(candidates) {
362
+ const owners = new Map();
363
+ const renamed = new Map();
364
+ candidates.forEach((candidate, candidateIndex) => {
365
+ for (const step of candidate.applyPlan) {
366
+ const key = subjectStepKey(step);
367
+ if (key === null)
368
+ continue;
369
+ const factId = String(step.id);
370
+ const source = String(stepProperties(step).text_ref ?? candidate.sourcePath);
371
+ const owner = owners.get(key);
372
+ if (owner === undefined) {
373
+ owners.set(key, { factId, candidateIndex, sources: [source] });
374
+ continue;
375
+ }
376
+ if (owner.factId === factId)
377
+ continue;
378
+ renamed.set(factId, owner.factId);
379
+ if (!owner.sources.includes(source))
380
+ owner.sources.push(source);
381
+ }
382
+ });
383
+ if (renamed.size === 0)
384
+ return { candidates: [...candidates], diagnostics: [] };
385
+ const shared = [...owners.entries()].filter(([, owner]) => owner.sources.length > 1);
386
+ const sharedFacts = new Map(shared.map(([key, owner]) => [owner.factId, { key, owner }]));
387
+ const result = candidates.map((candidate) => ({
388
+ ...candidate,
389
+ relationships: retarget(candidate.relationships, renamed),
390
+ applyPlan: candidate.applyPlan
391
+ .filter((step) => !renamed.has(String(step.id)))
392
+ .map((step) => {
393
+ const sharing = sharedFacts.get(String(step.id));
394
+ const retargeted = retargetStep(step, renamed);
395
+ if (sharing === undefined || subjectStepKey(step) === null)
396
+ return retargeted;
397
+ const properties = stepProperties(step);
398
+ const tags = Array.isArray(properties.tags)
399
+ ? properties.tags.map(String)
400
+ : [];
401
+ return {
402
+ ...retargeted,
403
+ properties: {
404
+ ...properties,
405
+ tags: [
406
+ ...new Set([
407
+ ...tags,
408
+ ...sharing.owner.sources.map((source) => `provenance:${normalizeSourceKey(source)}`),
409
+ ]),
410
+ ],
411
+ },
412
+ document: {
413
+ body: `Subject ${sharing.key}, shared by the requirements bootstrap planned from ${sharing.owner.sources.join(", ")}. Each of them links to this fact through constrains.\n`,
414
+ },
415
+ };
416
+ }),
417
+ }));
418
+ return {
419
+ candidates: result,
420
+ diagnostics: shared.map(([key, owner]) => `subject-key-shared: claims at ${owner.sources.join(", ")} name the same subject ${key}, so the plan writes one subject fact ${owner.factId} and links every requirement to it through constrains.`),
421
+ };
118
422
  }
@@ -5,9 +5,22 @@ export declare function buildSuggestion(schema: PredicateSchemaCandidate, text:
5
5
  applicabilityScore?: number;
6
6
  scoreComponents?: PredicateScoreComponents;
7
7
  explicitSubject?: boolean;
8
+ /**
9
+ * The subject_key of the subject fact the requirement constrains. It
10
+ * binds the schema's `subject` argument (provenance `requirement`) unless
11
+ * the caller bound that argument or passed subjectHint.
12
+ */
13
+ requirementSubject?: string;
8
14
  }): PredicateSuggestion;
9
15
  export declare function buildPredicateApplyPlan(suggestion: PredicateSuggestion, args: SuggestPredicatesArgs): Array<Record<string, unknown>>;
10
16
  export declare function buildRelationshipPlan(factId: string | undefined, requirementId: string | undefined, claimText?: string, existingLogicClaims?: readonly string[]): Record<string, unknown> | null;
17
+ /**
18
+ * The ontology-gap observation plan. It is a review note, not a semantic
19
+ * claim: it quotes the claim in claim_text without a claim_key, carries the
20
+ * review tags in `tags` only (a tag is not an entity, so no relationship
21
+ * targets it) and explains itself in `document.body`, so kb_upsert accepts
22
+ * it unchanged.
23
+ */
11
24
  export declare function buildGapApplyPlan(text: string, args: SuggestPredicatesArgs): Array<Record<string, unknown>>;
12
25
  /**
13
26
  * Build a review-only schema draft when retrieval found no eligible schema.
@@ -1 +1 @@
1
- {"version":3,"file":"predicate-applyplan.d.ts","sourceRoot":"","sources":["../../../src/operations/modeling/predicate-applyplan.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAEV,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,EACtB,MAAM,sBAAsB,CAAC;AAQ9B,wBAAgB,eAAe,CAC7B,MAAM,EAAE,wBAAwB,EAChC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,gBAAgB,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM,EACvD,YAAY,CAAC,EAAE,QAAQ,GAAG,MAAM,EAChC,WAAW,CAAC,EAAE;IACZ,WAAW,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IACtC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,eAAe,CAAC,EAAE,wBAAwB,CAAC;IAC3C,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,GACA,mBAAmB,CA8FrB;AAGD,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,mBAAmB,EAC/B,IAAI,EAAE,qBAAqB,GAC1B,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAqChC;AAGD,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,SAAS,CAAC,EAAE,MAAM,EAClB,mBAAmB,GAAE,SAAS,MAAM,EAAO,GAC1C,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAuBhC;AAGD,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,qBAAqB,GAC1B,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CA+BhC;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,GACd,0BAA0B,CAoE5B"}
1
+ {"version":3,"file":"predicate-applyplan.d.ts","sourceRoot":"","sources":["../../../src/operations/modeling/predicate-applyplan.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAEV,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,EACtB,MAAM,sBAAsB,CAAC;AAQ9B,wBAAgB,eAAe,CAC7B,MAAM,EAAE,wBAAwB,EAChC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,gBAAgB,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM,EACvD,YAAY,CAAC,EAAE,QAAQ,GAAG,MAAM,EAChC,WAAW,CAAC,EAAE;IACZ,WAAW,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IACtC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,eAAe,CAAC,EAAE,wBAAwB,CAAC;IAC3C,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B,GACA,mBAAmB,CAsHrB;AAGD,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,mBAAmB,EAC/B,IAAI,EAAE,qBAAqB,GAC1B,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAqChC;AAGD,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,SAAS,CAAC,EAAE,MAAM,EAClB,mBAAmB,GAAE,SAAS,MAAM,EAAO,GAC1C,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAuBhC;AAoBD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,qBAAqB,GAC1B,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAwBhC;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,GACd,0BAA0B,CAoE5B"}
@@ -9,8 +9,17 @@ import { applyArgumentRewrites, predicateArgumentConformance, } from "./predicat
9
9
  export function buildSuggestion(schema, text, subject, score, argumentBindings = {}, polarityHint, diagnostics) {
10
10
  const inferredArgs = inferArgs(schema, text, subject);
11
11
  const canonicalLauncherArgs = exactLauncherPredicateArgs(schema.predicate_name, text);
12
+ const hasExactBinding = (name) => typeof argumentBindings[name] === "string" &&
13
+ argumentBindings[name].trim().length > 0;
14
+ const requirementSubjectArgument = diagnostics?.requirementSubject &&
15
+ diagnostics.explicitSubject !== true &&
16
+ !hasExactBinding("subject")
17
+ ? schema.argument_names.indexOf("subject")
18
+ : -1;
12
19
  const boundArgs = schema.argument_names.map((name, index) => {
13
20
  const exactBinding = argumentBindings[name];
21
+ if (index === requirementSubjectArgument)
22
+ return diagnostics?.requirementSubject ?? "unknown";
14
23
  return typeof exactBinding === "string" && exactBinding.trim().length > 0
15
24
  ? exactBinding.trim()
16
25
  : (inferredArgs[index] ?? "unknown");
@@ -27,13 +36,26 @@ export function buildSuggestion(schema, text, subject, score, argumentBindings =
27
36
  const undeclaredArguments = new Set(conformance.undeclared.map((value) => value.argumentName));
28
37
  const bindingProvenanceByArgument = Object.fromEntries(schema.argument_names.map((name, index) => [
29
38
  name,
30
- classifyBinding(predicateArgs[index] ?? "unknown", text, (typeof argumentBindings[name] === "string" &&
31
- argumentBindings[name].trim().length > 0) ||
32
- (diagnostics?.explicitSubject === true && index === 0), canonicalLauncherArgs?.[index] === predicateArgs[index] &&
33
- !(index === 0 &&
34
- predicateArgs[index] === "launcher" &&
35
- diagnostics?.explicitSubject !== true &&
36
- typeof argumentBindings[name] !== "string")),
39
+ index === requirementSubjectArgument && !undeclaredArguments.has(name)
40
+ ? "requirement"
41
+ : classifyBinding(predicateArgs[index] ?? "unknown", text, (typeof argumentBindings[name] === "string" &&
42
+ argumentBindings[name].trim().length > 0) ||
43
+ (diagnostics?.explicitSubject === true && index === 0), canonicalLauncherArgs?.[index] === predicateArgs[index] &&
44
+ !(index === 0 &&
45
+ predicateArgs[index] === "launcher" &&
46
+ diagnostics?.explicitSubject !== true &&
47
+ typeof argumentBindings[name] !== "string"),
48
+ // A subject named through subjectHint is the agent's reviewed
49
+ // subject, even when the schema names its first argument after it.
50
+ index === 0 &&
51
+ diagnostics?.explicitSubject === true &&
52
+ typeof argumentBindings[name] !== "string"
53
+ ? { constants: schema.argument_constants?.[name] }
54
+ : {
55
+ argumentName: name,
56
+ argumentNames: schema.argument_names,
57
+ constants: schema.argument_constants?.[name],
58
+ }),
37
59
  ]));
38
60
  const bindingProvenance = aggregateBindingProvenance(Object.values(bindingProvenanceByArgument));
39
61
  const unboundArguments = schema.argument_names.filter((name) => undeclaredArguments.has(name) ||
@@ -136,9 +158,31 @@ export function buildRelationshipPlan(factId, requirementId, claimText, existing
136
158
  instructions: `Apply the predicate fact ${factId} first, update the requirement with the returned merged logicClaims manifest, then attach this relationship without overwriting other requirement metadata. The relationship target is the planned fact id ${factId}, never a candidates[].id (SUGGEST-...).`,
137
159
  };
138
160
  }
139
- // implements REQ-mcp-suggest-predicates
161
+ /**
162
+ * The prose an ontology-gap observation carries in `document.body`. Schema 8
163
+ * blocks an observation without body context (entity-context-missing), so the
164
+ * body says why the note exists and quotes the claim it is about.
165
+ */
166
+ function gapObservationBody(text, args) {
167
+ const origin = [
168
+ args.requirementId ? `requirement ${args.requirementId}` : null,
169
+ args.source ? `source ${args.source}` : null,
170
+ ].filter((value) => value !== null);
171
+ return [
172
+ "No available predicate schema fits this claim, so kb_model mode predicates recorded it as an open ontology gap. The observation does not ground the claim; it stays visible for review until a reviewed predicate_schema covers this kind of statement.",
173
+ ...(origin.length > 0 ? [`Claim from ${origin.join(", ")}:`] : ["Claim:"]),
174
+ `> ${text.trim().replace(/\n/g, "\n> ")}`,
175
+ ].join("\n\n");
176
+ }
177
+ // implements REQ-mcp-suggest-predicates, REQ-model-predicates-plan-roundtrip
178
+ /**
179
+ * The ontology-gap observation plan. It is a review note, not a semantic
180
+ * claim: it quotes the claim in claim_text without a claim_key, carries the
181
+ * review tags in `tags` only (a tag is not an entity, so no relationship
182
+ * targets it) and explains itself in `document.body`, so kb_upsert accepts
183
+ * it unchanged.
184
+ */
140
185
  export function buildGapApplyPlan(text, args) {
141
- const claimKey = semanticClaimKey(text);
142
186
  const factId = hashId("FACT-ONTOLOGY-GAP", [
143
187
  args.requirementId ?? "",
144
188
  args.source ?? "",
@@ -152,20 +196,14 @@ export function buildGapApplyPlan(text, args) {
152
196
  title: "Ontology gap: predicate schema needed",
153
197
  status: "active",
154
198
  source: args.source ?? "mcp://kibi/suggest-predicates",
155
- text_ref: args.source,
199
+ ...(args.source ? { text_ref: args.source } : {}),
156
200
  tags: ["review:ontology-gap", "needs_schema_extension"],
157
201
  fact_kind: "observation",
158
202
  value_string: text,
159
- claim_key: claimKey,
160
203
  claim_text: text,
161
204
  },
162
- relationships: [
163
- {
164
- type: "relates_to",
165
- from: factId,
166
- to: "review:ontology-gap",
167
- },
168
- ],
205
+ document: { body: gapObservationBody(text, args) },
206
+ relationships: [],
169
207
  },
170
208
  ];
171
209
  }
@@ -0,0 +1,11 @@
1
+ import type { BindingHint, PredicateSuggestion } from "./predicate-types.js";
2
+ /**
3
+ * For each unbound argument of a candidate: its type, its declared constants
4
+ * when the vocabulary is closed, example values from the schema, and why the
5
+ * current value was not accepted, so the agent binds from the claim text
6
+ * instead of guessing.
7
+ */
8
+ export declare function buildBindingHints(candidate: PredicateSuggestion, text: string, requirementSubjects?: readonly string[]): BindingHint[];
9
+ /** One line per hint for the text summary: `name (type, e.g. a, b)`. */
10
+ export declare function describeBindingHints(hints: readonly BindingHint[]): string;
11
+ //# sourceMappingURL=predicate-binding-hints.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"predicate-binding-hints.d.ts","sourceRoot":"","sources":["../../../src/operations/modeling/predicate-binding-hints.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAoD7E;;;;;GAKG;AAEH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,mBAAmB,EAC9B,IAAI,EAAE,MAAM,EACZ,mBAAmB,GAAE,SAAS,MAAM,EAAO,GAC1C,WAAW,EAAE,CAiCf;AAED,wEAAwE;AACxE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,MAAM,CAW1E"}
@@ -0,0 +1,97 @@
1
+ import { isGenericPlaceholder, nameOrStopWordReason, } from "./predicate-bindings.js";
2
+ const MAX_EXAMPLES = 5;
3
+ /** Split `name(a, b(c), d)` into its top-level arguments, or [] when it is not a call. */
4
+ function exampleArguments(example) {
5
+ const open = example.indexOf("(");
6
+ const close = example.lastIndexOf(")");
7
+ if (open < 0 || close <= open)
8
+ return [];
9
+ const inner = example.slice(open + 1, close);
10
+ const args = [];
11
+ let depth = 0;
12
+ let current = "";
13
+ for (const char of inner) {
14
+ if (char === "(" || char === "[")
15
+ depth += 1;
16
+ if (char === ")" || char === "]")
17
+ depth -= 1;
18
+ if (char === "," && depth === 0) {
19
+ args.push(current.trim());
20
+ current = "";
21
+ continue;
22
+ }
23
+ current += char;
24
+ }
25
+ args.push(current.trim());
26
+ return args.filter(Boolean);
27
+ }
28
+ function unboundReason(candidate, name, value, text) {
29
+ const schema = candidate.schema;
30
+ const provenance = candidate.binding_provenance_by_argument[name];
31
+ const nameReason = nameOrStopWordReason(value, {
32
+ argumentName: name,
33
+ argumentNames: schema.argument_names,
34
+ constants: schema.argument_constants?.[name],
35
+ text,
36
+ });
37
+ if (nameReason !== null)
38
+ return `The value "${value}" is not a binding: ${nameReason}.`;
39
+ if (!value.trim() || isGenericPlaceholder(value))
40
+ return "The claim text names no value for this argument.";
41
+ if (provenance === "inferred")
42
+ return `The value "${value}" was inferred and does not appear in the claim text; confirm it or pass the exact value.`;
43
+ if (schema.argument_constants?.[name])
44
+ return `The value "${value}" is not one of this argument's declared constants.`;
45
+ return `The value "${value}" needs review.`;
46
+ }
47
+ /**
48
+ * For each unbound argument of a candidate: its type, its declared constants
49
+ * when the vocabulary is closed, example values from the schema, and why the
50
+ * current value was not accepted, so the agent binds from the claim text
51
+ * instead of guessing.
52
+ */
53
+ // implements REQ-model-predicates-binding-placeholders, REQ-model-predicates-requirement-subject
54
+ export function buildBindingHints(candidate, text, requirementSubjects = []) {
55
+ const schema = candidate.schema;
56
+ const parsedExamples = schema.examples.map(exampleArguments);
57
+ return candidate.unbound_arguments.map((name) => {
58
+ const position = schema.argument_names.indexOf(name);
59
+ const constants = schema.argument_constants?.[name];
60
+ const exampleValues = parsedExamples
61
+ .map((args) => args[position])
62
+ .filter((value) => typeof value === "string");
63
+ // The subject keys the requirement already constrains come first, so
64
+ // the predicate and the subject fact use one identifier for the subject.
65
+ const examples = Array.from(new Set([
66
+ ...(name === "subject" ? requirementSubjects : []),
67
+ ...(constants ?? []),
68
+ ...exampleValues,
69
+ ])).slice(0, MAX_EXAMPLES);
70
+ const current = candidate.predicate_args[position] ?? "";
71
+ const description = schema.argument_descriptions?.[position];
72
+ return {
73
+ argument: name,
74
+ position,
75
+ type: schema.argument_types[position] ?? "unknown",
76
+ ...(description ? { description } : {}),
77
+ ...(constants ? { allowedValues: [...constants] } : {}),
78
+ examples,
79
+ currentValue: current,
80
+ provenance: candidate.binding_provenance_by_argument[name] ?? "placeholder",
81
+ reason: unboundReason(candidate, name, current, text),
82
+ };
83
+ });
84
+ }
85
+ /** One line per hint for the text summary: `name (type, e.g. a, b)`. */
86
+ export function describeBindingHints(hints) {
87
+ return hints
88
+ .map((hint) => {
89
+ const values = hint.allowedValues
90
+ ? `one of ${hint.allowedValues.join(", ")}`
91
+ : hint.examples.length > 0
92
+ ? `e.g. ${hint.examples.join(", ")}`
93
+ : "no example in the schema";
94
+ return `${hint.argument} (${hint.type}, ${values})`;
95
+ })
96
+ .join("; ");
97
+ }
@@ -1,6 +1,29 @@
1
1
  import type { BindingProvenance } from "./predicate-types.js";
2
2
  export declare function isGenericPlaceholder(value: string): boolean;
3
- export declare function classifyBinding(value: string, text: string, explicit: boolean, canonical?: boolean): BindingProvenance;
3
+ /** A binding value in the snake_case form argument names use. */
4
+ export declare function bindingToken(value: string): string;
5
+ /** The schema context a binding is judged against. */
6
+ export type BindingContext = Readonly<{
7
+ /** The argument this value binds. */
8
+ argumentName?: string;
9
+ /** Every argument name of the schema. */
10
+ argumentNames?: readonly string[];
11
+ /** Declared constants of this argument: always valid when matched. */
12
+ constants?: readonly string[] | undefined;
13
+ /**
14
+ * The claim text. A value that repeats an argument name is still a real
15
+ * binding when the claim itself names it (a `launcher` argument bound to
16
+ * "launcher" in "The launcher must ...").
17
+ */
18
+ text?: string | undefined;
19
+ }>;
20
+ /**
21
+ * Why a value only stands in for a binding, or null when it can be a reviewed
22
+ * value: it repeats its own or another argument's name, or it is a bare stop
23
+ * word. Declared constants and the booleans `true`/`false` always pass.
24
+ */
25
+ export declare function nameOrStopWordReason(value: string, context?: BindingContext): string | null;
26
+ export declare function classifyBinding(value: string, text: string, explicit: boolean, canonical?: boolean, context?: BindingContext): BindingProvenance;
4
27
  export declare function aggregateBindingProvenance(values: readonly BindingProvenance[]): BindingProvenance;
5
28
  export declare function bindingCanBeApplied(value: BindingProvenance): boolean;
6
29
  //# sourceMappingURL=predicate-bindings.d.ts.map