kibi-cli 2.22.1 → 2.24.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 (159) hide show
  1. package/dist/cli-operation-metadata.d.ts +1 -1
  2. package/dist/cli-operation-metadata.js +1 -1
  3. package/dist/cli-register-foundation.d.ts.map +1 -1
  4. package/dist/cli-register-foundation.js +1 -0
  5. package/dist/commands/check.d.ts.map +1 -1
  6. package/dist/commands/check.js +51 -3
  7. package/dist/commands/doctor.d.ts.map +1 -1
  8. package/dist/commands/doctor.js +28 -0
  9. package/dist/commands/migrate.d.ts +10 -0
  10. package/dist/commands/migrate.d.ts.map +1 -1
  11. package/dist/commands/migrate.js +81 -9
  12. package/dist/commands/sync.d.ts.map +1 -1
  13. package/dist/commands/sync.js +15 -1
  14. package/dist/decision-firmness.d.ts +16 -4
  15. package/dist/decision-firmness.d.ts.map +1 -1
  16. package/dist/decision-firmness.js +29 -6
  17. package/dist/extractors/markdown.d.ts.map +1 -1
  18. package/dist/extractors/markdown.js +39 -36
  19. package/dist/intent-search.d.ts +2 -0
  20. package/dist/intent-search.d.ts.map +1 -1
  21. package/dist/intent-search.js +43 -4
  22. package/dist/operations/bootstrap/activation.d.ts +7 -1
  23. package/dist/operations/bootstrap/activation.d.ts.map +1 -1
  24. package/dist/operations/bootstrap/activation.js +27 -2
  25. package/dist/operations/bootstrap/candidate-helpers.d.ts +6 -0
  26. package/dist/operations/bootstrap/candidate-helpers.d.ts.map +1 -1
  27. package/dist/operations/bootstrap/candidate-helpers.js +19 -0
  28. package/dist/operations/bootstrap/generate.d.ts.map +1 -1
  29. package/dist/operations/bootstrap/generate.js +56 -16
  30. package/dist/operations/bootstrap/guidance-actions.d.ts.map +1 -1
  31. package/dist/operations/bootstrap/guidance-actions.js +14 -2
  32. package/dist/operations/bootstrap/guidance.d.ts.map +1 -1
  33. package/dist/operations/bootstrap/guidance.js +6 -2
  34. package/dist/operations/bootstrap/intent-claims.d.ts.map +1 -1
  35. package/dist/operations/bootstrap/intent-claims.js +2 -2
  36. package/dist/operations/bootstrap/markdown-candidates.d.ts.map +1 -1
  37. package/dist/operations/bootstrap/markdown-candidates.js +2 -2
  38. package/dist/operations/bootstrap/presentation.d.ts.map +1 -1
  39. package/dist/operations/bootstrap/presentation.js +75 -9
  40. package/dist/operations/bootstrap/types.d.ts +6 -0
  41. package/dist/operations/bootstrap/types.d.ts.map +1 -1
  42. package/dist/operations/migration/firm-supersede.d.ts +19 -0
  43. package/dist/operations/migration/firm-supersede.d.ts.map +1 -0
  44. package/dist/operations/migration/firm-supersede.js +60 -0
  45. package/dist/operations/migration/kb-sources.d.ts +8 -5
  46. package/dist/operations/migration/kb-sources.d.ts.map +1 -1
  47. package/dist/operations/migration/kb-sources.js +50 -14
  48. package/dist/operations/migration/schema6.d.ts.map +1 -1
  49. package/dist/operations/migration/schema6.js +52 -2
  50. package/dist/operations/migration/source-paths.d.ts +18 -1
  51. package/dist/operations/migration/source-paths.d.ts.map +1 -1
  52. package/dist/operations/migration/source-paths.js +111 -16
  53. package/dist/operations/modeling/suggest-predicates.d.ts.map +1 -1
  54. package/dist/operations/modeling/suggest-predicates.js +22 -7
  55. package/dist/operations/mutation/requirement-semantics.d.ts +19 -1
  56. package/dist/operations/mutation/requirement-semantics.d.ts.map +1 -1
  57. package/dist/operations/mutation/requirement-semantics.js +63 -2
  58. package/dist/operations/mutation/strict-fact.js +1 -1
  59. package/dist/operations/mutation/upsert.d.ts.map +1 -1
  60. package/dist/operations/mutation/upsert.js +2 -1
  61. package/dist/operations/planning/apply-plan.d.ts.map +1 -1
  62. package/dist/operations/planning/apply-plan.js +22 -2
  63. package/dist/operations/semantic-advisor/analyze-prose.d.ts.map +1 -1
  64. package/dist/operations/semantic-advisor/analyze-prose.js +49 -17
  65. package/dist/public/impact/analyzer.d.ts.map +1 -1
  66. package/dist/public/impact/analyzer.js +7 -1
  67. package/dist/public/impact/diagnostics.d.ts.map +1 -1
  68. package/dist/public/impact/diagnostics.js +16 -3
  69. package/dist/public/impact/types.d.ts +2 -0
  70. package/dist/public/impact/types.d.ts.map +1 -1
  71. package/dist/public/operations/catalog.d.ts +8 -3
  72. package/dist/public/operations/catalog.d.ts.map +1 -1
  73. package/dist/public/operations/check-executor.d.ts.map +1 -1
  74. package/dist/public/operations/check-executor.js +10 -3
  75. package/dist/public/operations/check-helpers.d.ts +10 -0
  76. package/dist/public/operations/check-helpers.d.ts.map +1 -1
  77. package/dist/public/operations/check-helpers.js +54 -0
  78. package/dist/public/operations/contracts.d.ts.map +1 -1
  79. package/dist/public/operations/contracts.js +1 -0
  80. package/dist/public/operations/decision-firmness.d.ts +14 -0
  81. package/dist/public/operations/decision-firmness.d.ts.map +1 -1
  82. package/dist/public/operations/decision-firmness.js +60 -7
  83. package/dist/public/operations/discovery-executors.d.ts +18 -0
  84. package/dist/public/operations/discovery-executors.d.ts.map +1 -1
  85. package/dist/public/operations/discovery-executors.js +80 -8
  86. package/dist/public/operations/schema6-check-actions.d.ts +4 -0
  87. package/dist/public/operations/schema6-check-actions.d.ts.map +1 -1
  88. package/dist/public/operations/schema6-check-actions.js +39 -2
  89. package/dist/public/operations/source-path-dangling.d.ts +1 -1
  90. package/dist/public/operations/source-path-dangling.d.ts.map +1 -1
  91. package/dist/public/operations/source-path-dangling.js +11 -2
  92. package/dist/public/operations/specs/composite.d.ts +1 -1
  93. package/dist/public/operations/specs/discovery.d.ts +5 -0
  94. package/dist/public/operations/specs/discovery.d.ts.map +1 -1
  95. package/dist/public/operations/specs/discovery.js +5 -0
  96. package/dist/public/operations/specs/planning.d.ts +1 -1
  97. package/dist/public/operations/specs/planning.js +1 -1
  98. package/dist/public/operations/specs/reporting.d.ts.map +1 -1
  99. package/dist/public/operations/specs/reporting.js +6 -4
  100. package/dist/public/operations/specs/semantic.d.ts +1 -1
  101. package/dist/public/operations/specs/semantic.d.ts.map +1 -1
  102. package/dist/public/operations/specs/semantic.js +4 -2
  103. package/dist/public/operations/specs/upsert.d.ts +1 -1
  104. package/dist/public/operations/specs/upsert.js +1 -1
  105. package/dist/public/schemas/entity.js +1 -1
  106. package/dist/public/skills/kibi-bootstrap/SKILL.md +5 -4
  107. package/dist/public/skills/kibi-usage/SKILL.md +36 -16
  108. package/dist/public/skills/kibi-usage/resources/workflows.md +3 -1
  109. package/dist/schemas/entity.schema.json +1 -1
  110. package/dist/search-answer.d.ts +14 -0
  111. package/dist/search-answer.d.ts.map +1 -1
  112. package/dist/search-answer.js +51 -5
  113. package/dist/traceability/git-change-snapshot.d.ts +46 -0
  114. package/dist/traceability/git-change-snapshot.d.ts.map +1 -1
  115. package/dist/traceability/git-change-snapshot.js +187 -3
  116. package/dist/traceability/staged-diagnostics.d.ts.map +1 -1
  117. package/dist/traceability/staged-diagnostics.js +5 -6
  118. package/dist/traceability/staged-inventory-drift.d.ts +24 -0
  119. package/dist/traceability/staged-inventory-drift.d.ts.map +1 -0
  120. package/dist/traceability/staged-inventory-drift.js +84 -0
  121. package/dist/traceability/staged-symbols-manifest.d.ts.map +1 -1
  122. package/dist/traceability/staged-symbols-manifest.js +1 -2
  123. package/dist/types/entities.d.ts +2 -2
  124. package/dist/types/entities.d.ts.map +1 -1
  125. package/dist/utils/content-freshness.d.ts +9 -0
  126. package/dist/utils/content-freshness.d.ts.map +1 -1
  127. package/dist/utils/content-freshness.js +33 -0
  128. package/dist/utils/kb-manifest.d.ts +7 -0
  129. package/dist/utils/kb-manifest.d.ts.map +1 -1
  130. package/dist/utils/kb-manifest.js +6 -0
  131. package/dist/utils/merge-driver-setup.d.ts +10 -0
  132. package/dist/utils/merge-driver-setup.d.ts.map +1 -0
  133. package/dist/utils/merge-driver-setup.js +69 -0
  134. package/dist/utils/rule-registry.generated.d.ts +1 -1
  135. package/dist/utils/rule-registry.generated.js +1 -1
  136. package/dist/utils/schema-version.d.ts +1 -1
  137. package/dist/utils/schema-version.d.ts.map +1 -1
  138. package/dist/utils/schema-version.js +3 -1
  139. package/package.json +2 -2
  140. package/src/public/impact/analyzer.ts +13 -1
  141. package/src/public/impact/diagnostics.ts +20 -3
  142. package/src/public/impact/types.ts +2 -0
  143. package/src/public/operations/check-executor.ts +16 -4
  144. package/src/public/operations/check-helpers.ts +65 -0
  145. package/src/public/operations/contracts.ts +1 -0
  146. package/src/public/operations/decision-firmness.ts +83 -10
  147. package/src/public/operations/discovery-executors.ts +124 -7
  148. package/src/public/operations/schema6-check-actions.ts +43 -2
  149. package/src/public/operations/source-path-dangling.ts +12 -2
  150. package/src/public/operations/specs/discovery.ts +6 -0
  151. package/src/public/operations/specs/planning.ts +1 -1
  152. package/src/public/operations/specs/reporting.ts +6 -4
  153. package/src/public/operations/specs/semantic.ts +4 -2
  154. package/src/public/operations/specs/upsert.ts +1 -1
  155. package/src/public/schemas/entity.ts +1 -1
  156. package/src/public/skills/kibi-bootstrap/SKILL.md +5 -4
  157. package/src/public/skills/kibi-usage/SKILL.md +36 -16
  158. package/src/public/skills/kibi-usage/resources/workflows.md +3 -1
  159. package/src/schemas/entity.schema.json +1 -1
@@ -22,6 +22,7 @@ import {
22
22
  WHY_THIS_CHANGED_HEADING,
23
23
  carriesFirmness,
24
24
  effectiveFirmness,
25
+ firmnessIsImplicit,
25
26
  firmnessRef,
26
27
  supersedeAcknowledgement,
27
28
  whyThisChangedWords,
@@ -66,6 +67,21 @@ const DECISION_LANES = ["requirements", "adr"] as const;
66
67
  /** The schema version from which a supersede must explain itself. */
67
68
  const SUPERSEDES_REASON_SCHEMA_VERSION = 9;
68
69
 
70
+ /**
71
+ * The schema version from which a decision without `firmness` reads its
72
+ * firmness from its origin, so a person's or imported rule is firm.
73
+ */
74
+ // implements REQ-kb-decision-firmness-from-origin
75
+ export const FIRMNESS_FROM_ORIGIN_SCHEMA_VERSION = 10;
76
+
77
+ /**
78
+ * Told on a KB older than schema 10: the pending schema upgrade acknowledges
79
+ * supersedes of decisions that only became firm when firmness started to
80
+ * follow origin.
81
+ */
82
+ const PRE_SCHEMA10_FIRM_NOTE =
83
+ " This decision has no firmness and was not written by an agent, so it reads as firm from schema 10; supersedes recorded before schema 10 are acknowledged by the plan's schema-config-upgrade (kibi migrate --yes).";
84
+
69
85
  /**
70
86
  * Told on a KB older than schema 9: the pending schema upgrade acknowledges
71
87
  * supersedes recorded before the rule existed, so no edit is required now.
@@ -167,6 +183,43 @@ export function supersedeAcknowledgements(
167
183
  .map((target) => supersedeAcknowledgement(id, target));
168
184
  }
169
185
 
186
+ /**
187
+ * Supersede edges (`FROM -> TO`) whose target reads as firm only because
188
+ * firmness follows origin (it has no `firmness` and an agent did not write
189
+ * it) and whose superseder is not firm, retired entities included. These
190
+ * were allowed before schema 10; the migration acknowledges them once.
191
+ */
192
+ // implements REQ-kb-decision-firmness-from-origin
193
+ export function implicitFirmSupersedes(
194
+ entities: readonly AuthoredEntity[],
195
+ edges: ReadonlyMap<string, Set<string>>,
196
+ ): string[] {
197
+ const byId = new Map(entities.map((entity) => [entity.id, entity]));
198
+ const found: string[] = [];
199
+ for (const [from, targets] of edges) {
200
+ const source = byId.get(from);
201
+ if (
202
+ source === undefined ||
203
+ effectiveFirmness(
204
+ source.type,
205
+ source.data.firmness,
206
+ source.data.origin,
207
+ ) === "firm"
208
+ )
209
+ continue;
210
+ for (const to of targets) {
211
+ const target = byId.get(to);
212
+ if (
213
+ target !== undefined &&
214
+ firmnessIsImplicit(target.type, target.data.firmness) &&
215
+ effectiveFirmness(target.type, undefined, target.data.origin) === "firm"
216
+ )
217
+ found.push(supersedeAcknowledgement(from, to));
218
+ }
219
+ }
220
+ return found.sort();
221
+ }
222
+
170
223
  /** Evaluate the firmness rules over authored requirements and ADRs. */
171
224
  // implements REQ-kb-decision-firmness
172
225
  export function evaluateDecisionFirmness(
@@ -174,11 +227,19 @@ export function evaluateDecisionFirmness(
174
227
  edges: ReadonlyMap<string, Set<string>>,
175
228
  rules: ReadonlySet<string> = new Set(DECISION_FIRMNESS_RULES),
176
229
  acknowledged: ReadonlySet<string> = new Set(),
177
- options: Readonly<{ schemaVersion?: number | null }> = {},
230
+ options: Readonly<{
231
+ schemaVersion?: number | null;
232
+ /** Edges the schema 10 migration recorded (`FROM -> TO`). */
233
+ firmSupersedeAcknowledged?: ReadonlySet<string>;
234
+ }> = {},
178
235
  ): Violation[] {
179
236
  const preSchema9 =
180
237
  typeof options.schemaVersion === "number" &&
181
238
  options.schemaVersion < SUPERSEDES_REASON_SCHEMA_VERSION;
239
+ const preSchema10 =
240
+ typeof options.schemaVersion === "number" &&
241
+ options.schemaVersion < FIRMNESS_FROM_ORIGIN_SCHEMA_VERSION;
242
+ const firmAcknowledged = options.firmSupersedeAcknowledged ?? new Set();
182
243
  const findings: Violation[] = [];
183
244
  const superseded = supersededIds(edges);
184
245
  const byId = new Map(entities.map((entity) => [entity.id, entity]));
@@ -186,11 +247,13 @@ export function evaluateDecisionFirmness(
186
247
  .filter((entity) => isCurrentAuthoredEntity(entity, superseded))
187
248
  .sort((left, right) => left.id.localeCompare(right.id));
188
249
  const firmnessOf = (entity: AuthoredEntity) =>
189
- effectiveFirmness(entity.type, entity.data.firmness);
250
+ effectiveFirmness(entity.type, entity.data.firmness, entity.data.origin);
190
251
 
252
+ // Only an authored `firmness: firm` must cite the person's words: a
253
+ // decision that reads as firm from its origin already names its author.
191
254
  if (rules.has(DECISION_FIRM_UNREFERENCED_RULE)) {
192
255
  for (const entity of current) {
193
- if (firmnessOf(entity) !== "firm") continue;
256
+ if (entity.data.firmness !== "firm") continue;
194
257
  if (firmnessRef({ type: entity.type, ...entity.data }) !== undefined)
195
258
  continue;
196
259
  findings.push({
@@ -212,13 +275,19 @@ export function evaluateDecisionFirmness(
212
275
  left.id.localeCompare(right.id),
213
276
  )) {
214
277
  if (firmnessOf(entity) === "firm") continue;
278
+ const implicit = new Set<string>();
215
279
  const firmTargets = [...(edges.get(entity.id) ?? [])]
216
280
  .filter((id) => {
217
281
  const target = byId.get(id);
218
- return (
219
- target !== undefined &&
220
- effectiveFirmness(target.type, target.data.firmness) === "firm"
221
- );
282
+ if (target === undefined || firmnessOf(target) !== "firm")
283
+ return false;
284
+ if (!firmnessIsImplicit(target.type, target.data.firmness))
285
+ return true;
286
+ // Recorded before firmness followed origin: acknowledged once.
287
+ if (firmAcknowledged.has(supersedeAcknowledgement(entity.id, id)))
288
+ return false;
289
+ implicit.add(id);
290
+ return true;
222
291
  })
223
292
  .sort();
224
293
  if (firmTargets.length === 0) continue;
@@ -226,8 +295,7 @@ export function evaluateDecisionFirmness(
226
295
  rule: DECISION_FIRM_SUPERSEDED_RULE,
227
296
  entityId: entity.id,
228
297
  description: `${entity.id} (firmness: ${firmnessOf(entity)}) supersedes the firm decision${firmTargets.length === 1 ? "" : "s"} ${firmTargets.join(", ")}; only a human may change a firm decision`,
229
- suggestion:
230
- "Ask the person who stated the firm decision; if they agree, mark the replacement firmness: firm with origin.ref to their words, otherwise remove the supersedes link and propose the change instead",
298
+ suggestion: `Ask the person who stated the firm decision; if they agree, mark the replacement firmness: firm with origin.ref to their words, otherwise remove the supersedes link and propose the change instead${preSchema10 && implicit.size > 0 ? `.${PRE_SCHEMA10_FIRM_NOTE}` : ""}`,
231
299
  source: entity.path,
232
300
  evidence: { firmness: firmnessOf(entity), firmTargets },
233
301
  });
@@ -291,6 +359,11 @@ export function collectDecisionFirmnessViolations(
291
359
  authoredSupersedes(workspaceRoot, entities),
292
360
  rules,
293
361
  new Set(manifest?.supersedesReasonAcknowledged ?? []),
294
- { schemaVersion: manifest?.schemaVersion ?? null },
362
+ {
363
+ schemaVersion: manifest?.schemaVersion ?? null,
364
+ firmSupersedeAcknowledged: new Set(
365
+ manifest?.firmSupersedeAcknowledged ?? [],
366
+ ),
367
+ },
295
368
  );
296
369
  }
@@ -1,3 +1,4 @@
1
+ import { readFile } from "node:fs/promises";
1
2
  import path from "node:path";
2
3
  import { compilerFingerprintReason } from "../../commands/sync/cache.js";
3
4
  import { effectiveFirmness } from "../../decision-firmness.js";
@@ -8,6 +9,7 @@ import {
8
9
  type IntentSearchMatch,
9
10
  type SourceLocation,
10
11
  executeIntentSearch,
12
+ questionPaths,
11
13
  validateIntentSearchInput,
12
14
  } from "../../intent-search.js";
13
15
  import { classifyActivation } from "../../operations/bootstrap/activation.js";
@@ -34,6 +36,7 @@ import {
34
36
  reloadFullEntities,
35
37
  validateEntityType,
36
38
  } from "./discovery-entities.js";
39
+ import { readAuthoredEntity } from "./entity-context.js";
37
40
  import {
38
41
  type MigrationConfigStatus,
39
42
  type MigrationPlan,
@@ -67,6 +70,8 @@ export type QueryInput = {
67
70
  readonly distinct?: string;
68
71
  readonly subjectKey?: string;
69
72
  readonly propertyKey?: string;
73
+ /** With `id`: also return the entity's authored Markdown body. */
74
+ readonly includeBody?: boolean;
70
75
  };
71
76
 
72
77
  /** A ready-to-run follow-up call the query suggests. */
@@ -97,8 +102,26 @@ export type QueryPayload = {
97
102
  readonly factQuery?: FactQueryPayload;
98
103
  /** Present when an empty answer came from a store never compiled for this branch. */
99
104
  readonly branchStore?: SearchBranchStoreNotice;
105
+ /** Present when `includeBody` was requested for an `id`. */
106
+ readonly body?: QueryBody;
100
107
  };
101
108
 
109
+ /**
110
+ * The authored Markdown body of the entity a kb_query `id` names: the text
111
+ * after its front matter, which kb_upsert `document.body` replaces. `text` is
112
+ * null when the entity has no readable authored document (a symbol, or a
113
+ * source that is not a workspace Markdown file).
114
+ */
115
+ export type QueryBody = Readonly<{
116
+ id: string;
117
+ path: string | null;
118
+ text: string | null;
119
+ truncated?: boolean;
120
+ }>;
121
+
122
+ /** Bodies longer than this are cut; the file itself stays the full record. */
123
+ export const QUERY_BODY_MAX_CHARS = 32_000;
124
+
102
125
  export const FACT_KINDS = [
103
126
  "subject",
104
127
  "property_value",
@@ -684,6 +707,11 @@ export async function executeQuery(
684
707
  const { type, id, tags, sourceFile, limit = 100, offset = 0 } = input;
685
708
  try {
686
709
  validateEntityType(type);
710
+ if (input.includeBody === true && (id === undefined || id === "")) {
711
+ throw new Error(
712
+ "includeBody needs id: it returns the authored body of one entity. Pass the entity's id.",
713
+ );
714
+ }
687
715
  if (hasTypedFactFilters(input)) {
688
716
  return await executeFactQuery(input, context, limit, offset);
689
717
  }
@@ -704,11 +732,16 @@ export async function executeQuery(
704
732
  const indexedPage = prolog.queryEntities
705
733
  ? await prolog.queryEntities(pageInput, signal)
706
734
  : await queryEntitiesViaQuery(prolog, pageInput, signal);
707
- // A requirement or ADR without authored firmness reads as `default`;
708
- // the row says so, so a reader never has to know the default.
709
- // implements REQ-kb-decision-firmness
735
+ // A requirement or ADR without authored firmness reads as its origin
736
+ // implies (`default` when an agent wrote it, else `firm`); the row says
737
+ // so, so a reader never has to know the rule.
738
+ // implements REQ-kb-decision-firmness, REQ-kb-decision-firmness-from-origin
710
739
  const paginated = indexedPage.entities.map((entity) => {
711
- const firmness = effectiveFirmness(entity.type, entity.firmness);
740
+ const firmness = effectiveFirmness(
741
+ entity.type,
742
+ entity.firmness,
743
+ entity.origin,
744
+ );
712
745
  return firmness === undefined || entity.firmness === firmness
713
746
  ? entity
714
747
  : { ...entity, firmness };
@@ -729,12 +762,23 @@ export async function executeQuery(
729
762
  return `${entityId} (${String(entity.title ?? "")}, status=${String(entity.status ?? "")})`;
730
763
  })
731
764
  .join(", ")}`;
765
+ const body =
766
+ input.includeBody === true && id !== undefined
767
+ ? await readQueryBody(
768
+ id,
769
+ paginated.find((entity) => entity.id === id),
770
+ context,
771
+ )
772
+ : undefined;
732
773
  return {
733
- content: [{ type: "text", text }],
774
+ content: [
775
+ { type: "text", text: body ? `${text}\n${queryBodyText(body)}` : text },
776
+ ],
734
777
  structuredContent: {
735
778
  entities: paginated,
736
779
  count: indexedPage.count,
737
780
  ...(storeNotice ? { branchStore: storeNotice } : {}),
781
+ ...(body ? { body } : {}),
738
782
  },
739
783
  };
740
784
  } catch (error) {
@@ -743,6 +787,55 @@ export async function executeQuery(
743
787
  }
744
788
  }
745
789
 
790
+ // The body is read from the entity's authored document inside the
791
+ // workspace, the same file kb_upsert rewrites; nothing outside it is read.
792
+ // implements REQ-kibi-operation-interface-parity
793
+ async function readQueryBody(
794
+ id: string,
795
+ entity: Readonly<Record<string, unknown>> | undefined,
796
+ context: OperationContext,
797
+ ): Promise<QueryBody> {
798
+ const source = typeof entity?.source === "string" ? entity.source : "";
799
+ const relative = source.split("#", 1)[0]?.trim() ?? "";
800
+ const root = path.resolve(context.workspaceRoot);
801
+ const resolved = path.resolve(root, relative);
802
+ if (!relative.endsWith(".md") || !resolved.startsWith(root + path.sep)) {
803
+ return { id, path: null, text: null };
804
+ }
805
+ const bodyPath = path.relative(root, resolved).split(path.sep).join("/");
806
+ let raw: string;
807
+ try {
808
+ raw = String(
809
+ context.fs
810
+ ? await context.fs.readFile(resolved)
811
+ : await readFile(resolved, "utf8"),
812
+ );
813
+ } catch {
814
+ return { id, path: bodyPath, text: null };
815
+ }
816
+ const authored = readAuthoredEntity(raw, bodyPath)?.body;
817
+ if (authored === undefined || authored === null) {
818
+ return { id, path: bodyPath, text: null };
819
+ }
820
+ return authored.length > QUERY_BODY_MAX_CHARS
821
+ ? {
822
+ id,
823
+ path: bodyPath,
824
+ text: authored.slice(0, QUERY_BODY_MAX_CHARS),
825
+ truncated: true,
826
+ }
827
+ : { id, path: bodyPath, text: authored };
828
+ }
829
+
830
+ function queryBodyText(body: QueryBody): string {
831
+ if (body.text === null) {
832
+ return body.path === null
833
+ ? `No authored document for ${body.id}, so there is no body to return.`
834
+ : `The authored document ${body.path} of ${body.id} could not be read.`;
835
+ }
836
+ return `Body of ${body.id} (${body.path}${body.truncated ? `, first ${QUERY_BODY_MAX_CHARS} characters` : ""}; replace it with kb_upsert document.body):\n${body.text}`;
837
+ }
838
+
746
839
  /**
747
840
  * Identifying metadata a caller needs to decide which hits to open.
748
841
  *
@@ -792,6 +885,30 @@ async function projectMatches<
792
885
  : matches.map(summarizeMatch);
793
886
  }
794
887
 
888
+ // A question about contradictions is answered by the check, not by the
889
+ // entities that happen to mention the word.
890
+ const CONTRADICTION_QUESTION =
891
+ /\b(contradict\w*|conflict\w*|inconsisten\w*)\b/i;
892
+ const CONTRADICTION_HINT =
893
+ ' Search only finds entities that mention a conflict. Whether current requirements contradict each other is decided by kb_check with rules ["domain-contradictions"]; what a proposed rule would conflict with, by kb_model mode predicates (decisionConflicts) on its text or a kb_upsert dryRun.';
894
+
895
+ // A file path written in the question is left out of its topic. Passed as
896
+ // sourceLocations it also brings the requirements linked to that file.
897
+ function questionPathHint(
898
+ query: string,
899
+ locations: readonly SourceLocation[] | undefined,
900
+ ): string {
901
+ const located = new Set(
902
+ (locations ?? []).map((location) => location.path.replace(/^\.\//, "")),
903
+ );
904
+ const named = questionPaths(query).filter((file) => !located.has(file));
905
+ if (named.length === 0) return "";
906
+ const list = named.join(", ");
907
+ return named.length === 1
908
+ ? ` The question names ${list}; its words were left out of the topic. Pass it as sourceLocations to also see the requirements linked to that file.`
909
+ : ` The question names ${list}; their words were left out of the topic. Pass them as sourceLocations to also see the requirements linked to those files.`;
910
+ }
911
+
795
912
  export async function executeSearch(
796
913
  input: SearchInput,
797
914
  context: OperationContext,
@@ -864,14 +981,14 @@ export async function executeSearch(
864
981
  );
865
982
  const text = `${
866
983
  intentResult.matches.length === 0
867
- ? `No intent search results for '${trimmedQuery}' (abstained).`
984
+ ? `No intent search results for '${trimmedQuery}' (abstained). No entity shares enough of the question's words: ask again in the words and language the KB is written in, or pass sourceLocations.`
868
985
  : `Found ${intentResult.matches.length} intent search results for '${trimmedQuery}'${intentResult.analysis.ambiguous ? " (top matches are close; confirm before relying on one)" : ""}. Top: ${paginated
869
986
  .slice(0, 5)
870
987
  .map((match) => String(match.entity.id ?? ""))
871
988
  .join(
872
989
  ", ",
873
990
  )}${answerLayer ? `. Governing: ${answerLayer.governing.map((req) => req.id).join(", ") || "none found"}` : ""}${topUngoverned ? ` (the top match ${topUngoverned.id} is linked to no requirement)` : ""}.`
874
- }${storeNote}`;
991
+ }${questionPathHint(trimmedQuery, sourceLocations)}${CONTRADICTION_QUESTION.test(trimmedQuery) ? CONTRADICTION_HINT : ""}${storeNote}`;
875
992
  return {
876
993
  content: [{ type: "text", text }],
877
994
  structuredContent: {
@@ -208,6 +208,8 @@ export function supersessionCycleReviewActionInput(cycle: {
208
208
  export type SourcePathRewriteInput = Readonly<{
209
209
  entityId: string;
210
210
  file: string;
211
+ /** The field rewritten; absent means `source`. */
212
+ field?: "text_ref";
211
213
  from: string;
212
214
  to: string;
213
215
  }>;
@@ -260,7 +262,7 @@ export function sourcePathRewriteActionInput(
260
262
  ],
261
263
  evidence: {
262
264
  reason:
263
- "The authored source field is dead data: the compiled source is always the entity's own file, and Kibi ignores the field when compiling and never writes it. Each rewrite points a knowledge file named by its pre-canonical path (under documentation/, or relative to the knowledge root) at the same file under .kb/. Each removal deletes a value that names the entity's own file (reason self) or nothing Kibi can map (reason dangling). Only the source line changes.",
265
+ "The authored source field is dead data: the compiled source is always the entity's own file, and Kibi ignores the field when compiling and never writes it. Each rewrite points a knowledge file named by its pre-canonical path (under documentation/, or relative to the knowledge root) at the same file under .kb/; a rewrite with field text_ref does the same for a text_ref evidence path. Each removal deletes a source value that names the entity's own file (reason self) or nothing Kibi can map (reason dangling). Only the rewritten or removed line changes.",
264
266
  count: all.length,
265
267
  rewrites: rewrites.map((rewrite) => ({ ...rewrite })),
266
268
  removals: removals.map((removal) => ({ ...removal })),
@@ -275,6 +277,8 @@ export function sourcePathRewriteActionInput(
275
277
  // implements REQ-kibi-schema6-migration, REQ-core-validation-rules, REQ-kibi-kb-lifecycle-integrity
276
278
  export function sourcePathReviewActionInput(source: {
277
279
  entityId: string;
280
+ /** The field to repair; absent means `source`. */
281
+ field?: "text_ref";
278
282
  value: unknown;
279
283
  file?: string;
280
284
  reason?: string;
@@ -285,6 +289,32 @@ export function sourcePathReviewActionInput(source: {
285
289
  ? source.value
286
290
  : JSON.stringify(source.value);
287
291
  const where = source.file !== undefined ? ` in ${source.file}` : "";
292
+ if (source.field === "text_ref") {
293
+ const edit =
294
+ source.rewrite !== undefined
295
+ ? `replace the whole field with the single line 'text_ref: ${source.rewrite}'`
296
+ : "point text_ref at the evidence file's current path, or delete the field when that evidence is gone";
297
+ return {
298
+ id: `review-text-ref-dangling-${stableIdPart(source.entityId)}`,
299
+ code: SOURCE_PATH_REVIEW_CODE,
300
+ category: "quality",
301
+ safety: "review",
302
+ invocation: {
303
+ kind: "review",
304
+ instruction: `${source.entityId} has text_ref '${shown}'${where}, a file path that does not exist (${source.reason ?? "the edit would not read back as exactly that change"}). A person edits the frontmatter by hand: ${edit}. Then rerun kibi migrate.`,
305
+ },
306
+ affectedEntityIds: [source.entityId],
307
+ affectedFiles: source.file !== undefined ? [source.file] : [],
308
+ dispositionRequired: true,
309
+ evidence: {
310
+ entityId: source.entityId,
311
+ field: "text_ref",
312
+ text_ref: source.value,
313
+ ...(source.reason !== undefined ? { refused: source.reason } : {}),
314
+ ...(source.rewrite !== undefined ? { rewrite: source.rewrite } : {}),
315
+ },
316
+ };
317
+ }
288
318
  const edit =
289
319
  source.rewrite !== undefined
290
320
  ? `replace the whole field with the single line 'source: ${source.rewrite}'`
@@ -367,10 +397,12 @@ export function lifecycleActionsFromViolations(
367
397
  typeof evidence.value === "string"
368
398
  ? evidence.value
369
399
  : (JSON.stringify(evidence.value) ?? "");
400
+ const textRef = evidence.field === "text_ref";
370
401
  if (refused !== "" || file === "") {
371
402
  actions.push(
372
403
  sourcePathReviewActionInput({
373
404
  entityId,
405
+ ...(textRef ? { field: "text_ref" as const } : {}),
374
406
  value: evidence.value,
375
407
  ...(file !== "" ? { file } : {}),
376
408
  ...(refused !== "" ? { reason: refused } : {}),
@@ -378,7 +410,16 @@ export function lifecycleActionsFromViolations(
378
410
  }),
379
411
  );
380
412
  } else if (rewrite !== "") {
381
- rewrites.push({ entityId, file, from, to: rewrite });
413
+ rewrites.push({
414
+ entityId,
415
+ file,
416
+ ...(textRef ? { field: "text_ref" as const } : {}),
417
+ from,
418
+ to: rewrite,
419
+ });
420
+ } else if (textRef) {
421
+ // Kibi never removes evidence; an unmapped text_ref carries refused.
422
+ continue;
382
423
  } else {
383
424
  removals.push({
384
425
  entityId,
@@ -23,11 +23,17 @@ import {
23
23
  } from "../../operations/migration/source-paths.js";
24
24
  import type { Violation } from "../../utils/rule-registry.js";
25
25
 
26
- /** An authored source field that names no path, entity or URL. */
26
+ /** An authored source field that names no path, entity or URL, or a path-shaped text_ref that names no file. */
27
27
  // implements REQ-core-validation-rules, REQ-kibi-kb-lifecycle-integrity
28
28
  export const SOURCE_PATH_DANGLING_RULE = "source-path-dangling";
29
29
 
30
30
  function suggestion(source: SourceRepair): string {
31
+ if (source.field === "text_ref") {
32
+ if (source.refused !== undefined) {
33
+ return `kibi migrate cannot repair this text_ref (${source.refused}), so it plans a review_source_path_dangling action. Point text_ref at the evidence file's current path, or clear it when the evidence is gone: kb_upsert with the entity's title, status and text_ref "".`;
34
+ }
35
+ return `The file moved to ${source.fix.kind === "rewrite" ? source.fix.to : source.file}; kibi migrate rewrites the text_ref field there (source_path_rewrite).`;
36
+ }
31
37
  const compiled = `The compiled source is always the entity's own file (${source.file}), so the field carries nothing Kibi compiles.`;
32
38
  if (source.refused !== undefined) {
33
39
  return `kibi migrate cannot edit this source field safely (${source.refused}), so it plans a review_source_path_dangling action for a person. ${compiled}`;
@@ -54,10 +60,14 @@ export function sourcePathDanglingViolations(
54
60
  return dangling.map((source) => ({
55
61
  rule: SOURCE_PATH_DANGLING_RULE,
56
62
  entityId: source.entityId,
57
- description: `${source.entityId} names source '${shownSourceValue(source.value)}', which is not an existing workspace path, an entity id or an http(s) URL`,
63
+ description:
64
+ source.field === "text_ref"
65
+ ? `${source.entityId} names text_ref '${shownSourceValue(source.value)}', a file path that does not exist in the workspace`
66
+ : `${source.entityId} names source '${shownSourceValue(source.value)}', which is not an existing workspace path, an entity id or an http(s) URL`,
58
67
  suggestion: suggestion(source),
59
68
  source: source.file,
60
69
  evidence: {
70
+ ...(source.field === "text_ref" ? { field: "text_ref" } : {}),
61
71
  value: source.value,
62
72
  file: source.file,
63
73
  ...(source.fix.kind === "rewrite"
@@ -132,6 +132,12 @@ export const querySpec = {
132
132
  description:
133
133
  "Optional zero-based pagination offset. Default: 0. Example: 50 to skip first 50 rows.",
134
134
  },
135
+ includeBody: {
136
+ type: "boolean",
137
+ default: false,
138
+ description:
139
+ "With id only: also return the entity's authored Markdown body (the prose after its front matter) as body {id, path, text}, so a stale statement in it can be corrected; kb_upsert document.body replaces it. Default: false.",
140
+ },
135
141
  },
136
142
  },
137
143
  requiresProlog: true,
@@ -86,7 +86,7 @@ export const compileIntentSpec = {
86
86
  items: { type: "string", minLength: 1 },
87
87
  maxItems: 64,
88
88
  description:
89
- "Optional complete atomic clause decomposition. Each assertive clause receives independent proposition accounting.",
89
+ "Optional complete atomic clause decomposition. Each clause must be a verbatim fragment of intent (whitespace may differ); a clause that does not occur in intent fails the call with VALIDATION_FAILED naming it. Each assertive clause receives independent proposition accounting.",
90
90
  },
91
91
  semanticFacets: {
92
92
  type: "object",
@@ -1,3 +1,4 @@
1
+ import { confirmMetaFreshness } from "../../../utils/content-freshness.js";
1
2
  import { PROOF_RECEIPT_MAX_AGE_SECONDS } from "../../proof-receipt.js";
2
3
  import { executeStatus } from "../discovery-executors.js";
3
4
  import {
@@ -160,7 +161,7 @@ export async function executeFindGaps(
160
161
  : `Found ${payload.count ?? rows.length} gap rows. Showing ${rows.length}: ${rows.map((row) => row.id).join(", ")}.${stubNote}`,
161
162
  },
162
163
  ],
163
- structuredContent: payload,
164
+ structuredContent: confirmMetaFreshness(payload, context.workspaceRoot),
164
165
  };
165
166
  } catch (error) {
166
167
  const message = error instanceof Error ? error.message : String(error);
@@ -380,15 +381,16 @@ export async function executeCoverage(
380
381
  const migrationPlan = statusPlan
381
382
  ? mergeMigrationPlans([statusPlan, coveragePlan])
382
383
  : coveragePlan;
384
+ const confirmed = confirmMetaFreshness(payload, context.workspaceRoot);
383
385
  const enrichedPayload = {
384
- ...payload,
386
+ ...confirmed,
385
387
  rows,
386
388
  ...(repairPlan !== undefined ? { repairPlan } : {}),
387
389
  ...(legacyMigrationPlan !== undefined ? { legacyMigrationPlan } : {}),
388
390
  ...(symbolRepairPlan !== undefined ? { symbolRepairPlan } : {}),
389
391
  migrationPlan,
390
392
  meta: {
391
- ...(payload.meta ?? {}),
393
+ ...(confirmed.meta ?? {}),
392
394
  proofReceiptMaxAgeSeconds: PROOF_RECEIPT_MAX_AGE_SECONDS,
393
395
  proofSnapshot: codeSnapshot,
394
396
  proofSnapshotAvailable: snapshotEvidence.available,
@@ -512,7 +514,7 @@ export async function executeGraph(
512
514
  : `Graph traversal returned ${nodes.length} nodes and ${edges.length} edges from ${input.seedIds.join(", ")}.`,
513
515
  },
514
516
  ],
515
- structuredContent: payload,
517
+ structuredContent: confirmMetaFreshness(payload, context.workspaceRoot),
516
518
  };
517
519
  } catch (error) {
518
520
  const message = error instanceof Error ? error.message : String(error);
@@ -144,7 +144,9 @@ export async function executeSemanticAdvisor(
144
144
  content: [
145
145
  {
146
146
  type: "text",
147
- text: `kb_semantic_advisor: ${result.receipt.summary} Suggestions: ${result.receipt.suggestions.map(({ kind }) => kind).join(", ") || "none"}.`,
147
+ // A drift warning decides whether the analyzed ledger can be
148
+ // written at all, so the text says it too, not only the warnings.
149
+ text: `kb_semantic_advisor: ${result.receipt.summary} Suggestions: ${result.receipt.suggestions.map(({ kind }) => kind).join(", ") || "none"}.${ledgerWarnings.map((warning) => ` ${warning}`).join("")}`,
148
150
  },
149
151
  ],
150
152
  structuredContent: {
@@ -211,7 +213,7 @@ export const semanticAdvisorSpec = {
211
213
  type: "array",
212
214
  items: { type: "string" },
213
215
  description:
214
- "Optional complete list of atomic requirement clauses supplied by the caller. Use this for compound prose so every normative clause receives a stable claim key and independent grounding review.",
216
+ "Optional complete list of atomic requirement clauses supplied by the caller. Each clause must be a verbatim fragment of text (whitespace may differ); a clause that does not occur in text fails the call with VALIDATION_FAILED naming it. Use this for compound prose so every normative clause receives a stable claim key and independent grounding review.",
215
217
  },
216
218
  interpretations: {
217
219
  type: "array",
@@ -14,7 +14,7 @@ export const upsertSpec = {
14
14
  name: "kb_upsert",
15
15
  cliName: "upsert",
16
16
  description:
17
- "Create or update one entity and optional relationships. Use for KB mutations after validating intent; prefer a dryRun:true call first because it validates without writing and returns semantic advisor receipts for prose-heavy requirements. Use kb_model (mode requirement) before hand-writing strict property facts from prose, and kb_model (mode predicates) before hand-writing ontology predicate facts. Use the `relationships` array for batch creation of multiple links in a single call (e.g., linking a requirement to multiple tests or facts). Prefer modeling requirements as reusable fact links (`constrains`, `requires_property`, or `requires_predicate`) so consistency and contradiction checks remain queryable. Relationship endpoints must already exist in KB. For requirements, the write will be rejected if it contradicts existing current requirements that constrain the same subject with incompatible properties. To replace a conflicting requirement, include a `supersedes` relationship from the new requirement to the old one in the same request, then upsert the old requirement with status closed (kb_check blocks a superseded requirement that is not closed). Successful writes may return non-blocking semantic advisor warnings; inspect and repair those warnings before treating prose as contradiction-checkable. Pass a sectioned `document.body` when creating a requirement (the statement, then `## Context` stating why it exists, who asked and the source, then `## Source` with the verbatim excerpt) and a prose body for scenarios, tests, ADRs and observation facts; a result warning reports an entity whose body lacks context, and kb_check blocks it under entity-context-missing. Never invent a reason the requester did not give: write 'Reason not stated'. Do not use for read-only inspection. Side effects: writes KB, may refresh symbol coordinates; dryRun:true writes nothing.",
17
+ "Create or update one entity and optional relationships. Use for KB mutations after validating intent; prefer a dryRun:true call first because it validates without writing and returns semantic advisor receipts for prose-heavy requirements. Use kb_model (mode requirement) before hand-writing strict property facts from prose, and kb_model (mode predicates) before hand-writing ontology predicate facts. Use the `relationships` array for batch creation of multiple links in a single call (e.g., linking a requirement to multiple tests or facts). An update keeps the properties and relationships it leaves out: send the fields that change (with title and status) and only the links to add. Prefer modeling requirements as reusable fact links (`constrains`, `requires_property`, or `requires_predicate`) so consistency and contradiction checks remain queryable. Relationship endpoints must already exist in KB. For requirements, the write will be rejected if it contradicts existing current requirements that constrain the same subject with incompatible properties. To replace a conflicting requirement, include a `supersedes` relationship from the new requirement to the old one in the same request, then upsert the old requirement with status closed (kb_check blocks a superseded requirement that is not closed). Successful writes may return non-blocking semantic advisor warnings; inspect and repair those warnings before treating prose as contradiction-checkable. Pass a sectioned `document.body` when creating a requirement (the statement, then `## Context` stating why it exists, who asked and the source, then `## Source` with the verbatim excerpt) and a prose body for scenarios, tests, ADRs and observation facts; a result warning reports an entity whose body lacks context, and kb_check blocks it under entity-context-missing. Never invent a reason the requester did not give: write 'Reason not stated'. Do not use for read-only inspection. Side effects: writes KB, may refresh symbol coordinates; dryRun:true writes nothing.",
18
18
  businessInputSchema: {
19
19
  type: "object",
20
20
  required: ["type", "id", "properties"],
@@ -362,7 +362,7 @@ const entitySchema: Record<string, unknown> = {
362
362
  type: "string",
363
363
  enum: ["firm", "default", "exploratory"],
364
364
  description:
365
- "Requirement and ADR only. How firmly the decision was made. firm: a human stated it as a rule; it needs a ref (origin.ref, or approval_ref on a requirement) to their words, and only a human may change it. default (assumed when absent): a delegated or agent choice; a later agent may supersede it with evidence. exploratory: a flagged guess, expected to be revisited.",
365
+ "Requirement and ADR only. How firmly the decision was made. firm: a human stated it as a rule; it needs a ref (origin.ref, or approval_ref on a requirement) to their words, and only a human may change it. default: a delegated or agent choice; a later agent may supersede it with evidence. exploratory: a flagged guess, expected to be revisited. When absent, it reads as default if an agent wrote the entity (origin.kind agent) and as firm otherwise (a person's, imported or migrated decision); set it explicitly when recording a decision.",
366
366
  },
367
367
  expects: {
368
368
  type: "string",