kibi-agent-core 0.7.0 → 0.8.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # kibi-agent-core
2
2
 
3
+ ## 0.8.1
4
+
5
+ ### Patch Changes
6
+
7
+ - f4c5822: After a migration, the `kb_apply_plan` digest of the remaining plan now says when an automatic action in it is blocked: it waits for the actions in its `dependsOn` and needs no approval until a later plan shows it ready. Before, a blocked automatic action looked like something left to approve. The Claude hook's firm-edit question no longer prints a double full stop after a requirement title that ends in one.
8
+
9
+ The digest's `next` text appends a count of blocked automatic actions when there are any. `firmEditConfirmation` in `kibi-agent-core/decision-guard` trims a trailing full stop from the named requirements before closing the sentence.
10
+
11
+ ## 0.8.0
12
+
13
+ ### Minor Changes
14
+
15
+ - 00d2871: The Codex, Cursor and ZCode hooks now act on recorded decisions while the work happens, as the Claude Code hooks do.
16
+ - **Firm requirements before the edit.** When an edit changes code that implements a current firm requirement, the pre-edit hook tells the agent to ask the person before an edit that breaks that rule, naming the rule; once per requirement per session. These hosts cannot put the question to the person from a hook (Codex has no "ask", Cursor does not enforce one, and the ZCode adapter stays advisory), so this is a notice to the agent. Set `KIBI_CONFIRM_FIRM_EDITS=0` to turn it off.
17
+ - **Stated rules are captured.** A prompt that reads as a rule ("must", "never", "from now on") gets the note that recording it with `kb_upsert` is part of the change: through a new `UserPromptSubmit` hook in Codex and ZCode, and in Cursor through a new `beforeSubmitPrompt` hook whose note arrives with the next pre-edit message. When a session changed source files and wrote nothing with `kb_upsert`, the stop hook asks once for the decision to be recorded (Codex continues the turn with it; Cursor adds it to the stop follow-up; ZCode adds it to the Stop context).
18
+ - **Codex unlinked-file candidates** are ranked by the latest prompt's words as well as the path's.
19
+
20
+ `kibi-agent-core`: new `kibi-agent-core/decision-guard` entry with the host-neutral pieces (`firmRequirementsTouched`, `firmEditNotice`, `confirmFirmEdits`, the prompt and stop notes, and per-session markers). `kibi-claude` now imports its firm-edit and capture texts from it; behavior is unchanged.
21
+
3
22
  ## 0.7.0
4
23
 
5
24
  ### Minor Changes
@@ -0,0 +1,90 @@
1
+ import type { EntitySummary, IndexedSymbol } from "./knowledge-index.js";
2
+ import { type LineRange, type Summarize } from "./snippets.js";
3
+ /**
4
+ * Host-neutral pieces of the hooks that act on recorded decisions while the
5
+ * work happens: which firm requirements an edit changes, the confirmation and
6
+ * agent texts for it, and the prompt-time and stop-time capture notes. Each
7
+ * host adapter decides how to put the confirmation to the person.
8
+ */
9
+ /** Set to `0`, `false` or `off` to stop asking before edits of firm requirements. */
10
+ export declare const CONFIRM_FIRM_EDITS_ENV = "KIBI_CONFIRM_FIRM_EDITS";
11
+ /** False when the operator turned the firm-edit confirmation off. */
12
+ export declare function confirmFirmEdits(env: NodeJS.ProcessEnv): boolean;
13
+ /**
14
+ * The current firm requirements an edit changes that are not in `confirmed`:
15
+ * those implemented by the symbols the edit lands in, or by every symbol of
16
+ * the file for a whole-file write. An edit whose location is unknown, or
17
+ * outside every symbol, changes none.
18
+ */
19
+ export declare function firmRequirementsTouched(input: {
20
+ symbols: readonly IndexedSymbol[];
21
+ focus: readonly LineRange[] | undefined;
22
+ wholeFile: boolean;
23
+ summarize: Summarize;
24
+ confirmed?: ReadonlySet<string>;
25
+ }): {
26
+ ids: string[];
27
+ symbol: IndexedSymbol | undefined;
28
+ };
29
+ /**
30
+ * The permission-prompt text for an edit of a firm requirement's code: what
31
+ * the edit changes, the requirements, and what allowing it means. The person
32
+ * reads it, so it names the rule rather than the mechanism.
33
+ */
34
+ export declare function firmEditConfirmation(where: string, requirements: readonly EntitySummary[]): string;
35
+ /** What the agent is told when its edit was put to the person. */
36
+ export declare function firmEditContext(ids: readonly string[]): string;
37
+ /** The phrase that makes `prompt` read as a rule, or undefined. */
38
+ export declare function statedRule(prompt: string): string | undefined;
39
+ /** Prompt-time note for a request that reads as a rule or decision. */
40
+ export declare function rulePromptNote(phrase: string): string;
41
+ /**
42
+ * Stop-time note for a session that changed source files and wrote nothing
43
+ * to the knowledge base.
44
+ */
45
+ export declare function captureReminder(rulePrompt: boolean): string;
46
+ /**
47
+ * Pre-edit context for hosts whose pre-tool hook cannot put a call to the
48
+ * person: the edit is named as a change to the person's rule, and the agent
49
+ * is told to ask before making it unless it keeps the rule.
50
+ */
51
+ export declare function firmEditNotice(where: string, requirements: readonly EntitySummary[]): string;
52
+ /** Where one host session's decision-guard markers live. */
53
+ export type DecisionSession = {
54
+ stateDir: string | undefined;
55
+ sessionId: string | undefined;
56
+ };
57
+ /** Session markers the decision guard keeps. */
58
+ export type DecisionFlag = "source-edited" | "kb-recorded" | "rule-prompt" | "capture-asked";
59
+ /** Set a session marker; best effort. */
60
+ export declare function markDecisionFlag(session: DecisionSession, flag: DecisionFlag): void;
61
+ export declare function hasDecisionFlag(session: DecisionSession, flag: DecisionFlag): boolean;
62
+ /**
63
+ * True the first time `flag` is claimed in the session. Without a state
64
+ * directory nothing can be remembered, so nothing is claimed.
65
+ */
66
+ export declare function claimDecisionFlag(session: DecisionSession, flag: DecisionFlag): boolean;
67
+ /**
68
+ * Remember a submitted prompt's topic words (for unlinked-file candidates)
69
+ * and whether it read as a rule. Returns the rule phrase, if any.
70
+ */
71
+ export declare function recordRequest(session: DecisionSession, prompt: string): string | undefined;
72
+ /** Topic words of the session's latest prompt, or none. */
73
+ export declare function requestWords(session: DecisionSession): string[];
74
+ /**
75
+ * Whether the stop should ask for the session's decision to be recorded:
76
+ * source changed, nothing was written with kb_upsert, and the session has
77
+ * not been asked yet (claiming the ask).
78
+ */
79
+ export declare function claimCaptureReminder(session: DecisionSession): boolean;
80
+ /** Firm requirements the agent was already told about this session. */
81
+ export declare function settledFirmRequirements(session: DecisionSession): Set<string>;
82
+ /** Remember that the agent was told about these firm requirements. */
83
+ export declare function settleFirmRequirements(session: DecisionSession, ids: readonly string[]): void;
84
+ /**
85
+ * Keep a prompt's rule note for a host whose prompt hook cannot add context,
86
+ * so the next hook that can speak to the agent delivers it.
87
+ */
88
+ export declare function holdRuleNote(session: DecisionSession, phrase: string): void;
89
+ /** The held rule note, removed so it is delivered once; or undefined. */
90
+ export declare function takeRuleNote(session: DecisionSession): string | undefined;
@@ -0,0 +1,276 @@
1
+ // implements REQ-claude-firm-edit-confirmation, REQ-claude-decision-capture-nudges, REQ-agent-hosts-decision-guard
2
+ import { createHash } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { requestTopicWords } from "./requirement-candidates.js";
6
+ import { focusedSymbols, implementedRequirementIds, isRetiredStatus, } from "./snippets.js";
7
+ /**
8
+ * Host-neutral pieces of the hooks that act on recorded decisions while the
9
+ * work happens: which firm requirements an edit changes, the confirmation and
10
+ * agent texts for it, and the prompt-time and stop-time capture notes. Each
11
+ * host adapter decides how to put the confirmation to the person.
12
+ */
13
+ /** Set to `0`, `false` or `off` to stop asking before edits of firm requirements. */
14
+ export const CONFIRM_FIRM_EDITS_ENV = "KIBI_CONFIRM_FIRM_EDITS";
15
+ // implements REQ-claude-firm-edit-confirmation, REQ-agent-hosts-decision-guard
16
+ /** False when the operator turned the firm-edit confirmation off. */
17
+ export function confirmFirmEdits(env) {
18
+ const value = env[CONFIRM_FIRM_EDITS_ENV]?.trim().toLowerCase();
19
+ return !(value === "0" || value === "false" || value === "off");
20
+ }
21
+ // implements REQ-claude-firm-edit-confirmation, REQ-agent-hosts-decision-guard
22
+ /**
23
+ * The current firm requirements an edit changes that are not in `confirmed`:
24
+ * those implemented by the symbols the edit lands in, or by every symbol of
25
+ * the file for a whole-file write. An edit whose location is unknown, or
26
+ * outside every symbol, changes none.
27
+ */
28
+ export function firmRequirementsTouched(input) {
29
+ const touched = input.wholeFile
30
+ ? input.symbols
31
+ : focusedSymbols(input.symbols, input.focus);
32
+ const ids = implementedRequirementIds(touched).filter((id) => {
33
+ if (input.confirmed?.has(id))
34
+ return false;
35
+ const summary = input.summarize(id);
36
+ return summary.firmness === "firm" && !isRetiredStatus(summary.status);
37
+ });
38
+ return { ids, symbol: input.wholeFile ? undefined : touched[0] };
39
+ }
40
+ // implements REQ-claude-firm-edit-confirmation
41
+ /**
42
+ * The permission-prompt text for an edit of a firm requirement's code: what
43
+ * the edit changes, the requirements, and what allowing it means. The person
44
+ * reads it, so it names the rule rather than the mechanism.
45
+ */
46
+ export function firmEditConfirmation(where, requirements) {
47
+ // Every one is firm, so each is named by id and title only.
48
+ const shown = requirements
49
+ .slice(0, 2)
50
+ .map((summary) => summary.title ? `${summary.id}: ${summary.title}` : summary.id);
51
+ const more = requirements.length > shown.length
52
+ ? ` (+${requirements.length - shown.length} more)`
53
+ : "";
54
+ const noun = requirements.length === 1 ? "a firm requirement" : "firm requirements";
55
+ // A title that ends in a full stop would read "preference.. Allow".
56
+ const named = `${shown.join("; ")}${more}`.replace(/\.+$/, "");
57
+ return `Kibi: this edit changes ${where}, which implements ${noun} recorded in the knowledge base: ${named}. Allow it if the change keeps ${requirements.length === 1 ? "that requirement" : "them"}, or if you mean to change ${requirements.length === 1 ? "the requirement" : "them"} too.`;
58
+ }
59
+ // implements REQ-claude-firm-edit-confirmation
60
+ /** What the agent is told when its edit was put to the person. */
61
+ export function firmEditContext(ids) {
62
+ const named = ids.slice(0, 2).join(", ");
63
+ return [
64
+ `Kibi asked the person to confirm this edit because it changes code that implements firm ${ids.length === 1 ? "requirement" : "requirements"} ${named}.`,
65
+ "If the edit was declined or could not be confirmed, the requirement stands: name it and ask the person how to proceed, rather than reaching the same change another way. If it was allowed and the change alters what the requirement says, the requirement is updated with kb_upsert in this change.",
66
+ ].join("\n");
67
+ }
68
+ /**
69
+ * Phrases that make a request read as a rule or decision. Matching is
70
+ * deliberately loose: the note it triggers only asks whether there is
71
+ * something to record.
72
+ */
73
+ const RULE_PHRASES = /\b(?:from now on|going forward|must(?:n['’]t| not)?|should (?:always|never)|never|always|is not allowed|are not allowed|not be allowed|only (?:allow|admins?|owners?)|is required|are required|has to|have to)\b/i;
74
+ // implements REQ-claude-decision-capture-nudges, REQ-agent-hosts-decision-guard
75
+ /** The phrase that makes `prompt` read as a rule, or undefined. */
76
+ export function statedRule(prompt) {
77
+ const match = RULE_PHRASES.exec(prompt);
78
+ return match ? match[0].toLowerCase() : undefined;
79
+ }
80
+ // implements REQ-claude-decision-capture-nudges, REQ-agent-hosts-decision-guard
81
+ /** Prompt-time note for a request that reads as a rule or decision. */
82
+ export function rulePromptNote(phrase) {
83
+ return [
84
+ `Kibi: this request reads as a rule or decision (it says "${phrase}").`,
85
+ "A rule the person states is project knowledge: kb_search shows whether a recorded requirement already says something about it (changing a firm one is a question for the person first), and a new or changed rule is recorded with kb_upsert (a requirement, firm because the person stated it, with the implements link from the code that enforces it) as part of this change, not after it.",
86
+ ].join("\n");
87
+ }
88
+ // implements REQ-claude-decision-capture-nudges, REQ-agent-hosts-decision-guard
89
+ /**
90
+ * Stop-time note for a session that changed source files and wrote nothing
91
+ * to the knowledge base.
92
+ */
93
+ export function captureReminder(rulePrompt) {
94
+ return [
95
+ rulePrompt
96
+ ? "Kibi: a request this session read as a rule or decision, the session changed source files, and nothing was recorded in the knowledge base."
97
+ : "Kibi: this session changed source files and recorded nothing in the knowledge base.",
98
+ "A decision the person stated or this change made (a rule, a limit, a default, who may do what) is recorded with kb_upsert as a requirement linked to the code that implements it before the work is reported done; when there was none, the final report says so in one line.",
99
+ ].join("\n");
100
+ }
101
+ // implements REQ-agent-hosts-decision-guard
102
+ /**
103
+ * Pre-edit context for hosts whose pre-tool hook cannot put a call to the
104
+ * person: the edit is named as a change to the person's rule, and the agent
105
+ * is told to ask before making it unless it keeps the rule.
106
+ */
107
+ export function firmEditNotice(where, requirements) {
108
+ const shown = requirements
109
+ .slice(0, 2)
110
+ .map((summary) => summary.title ? `${summary.id}: ${summary.title}` : summary.id);
111
+ const more = requirements.length > shown.length
112
+ ? ` (+${requirements.length - shown.length} more)`
113
+ : "";
114
+ const one = requirements.length === 1;
115
+ return [
116
+ `Kibi: this edit changes ${where}, which implements ${one ? "a firm requirement" : "firm requirements"}, a rule the person set: ${shown.join("; ")}${more}.`,
117
+ `Unless the edit keeps ${one ? "that rule" : "those rules"}, ask the person before making it and name the rule; change the requirement with kb_upsert in this change only when they say so.`,
118
+ ].join("\n");
119
+ }
120
+ function sessionPath(session, name) {
121
+ if (!session.stateDir)
122
+ return undefined;
123
+ const key = createHash("sha256")
124
+ .update(session.sessionId?.trim() || "unattributed")
125
+ .digest("hex")
126
+ .slice(0, 32);
127
+ return path.join(session.stateDir, "decision-guard", key, name);
128
+ }
129
+ function writeMarker(file, content, flag) {
130
+ fs.mkdirSync(path.dirname(file), { recursive: true });
131
+ fs.writeFileSync(file, content, { flag });
132
+ }
133
+ // implements REQ-agent-hosts-decision-guard
134
+ /** Set a session marker; best effort. */
135
+ export function markDecisionFlag(session, flag) {
136
+ const file = sessionPath(session, flag);
137
+ if (!file)
138
+ return;
139
+ try {
140
+ writeMarker(file, "", "w");
141
+ }
142
+ catch {
143
+ // Markers are best effort; a lost one means a note may repeat or skip.
144
+ }
145
+ }
146
+ // implements REQ-agent-hosts-decision-guard
147
+ export function hasDecisionFlag(session, flag) {
148
+ const file = sessionPath(session, flag);
149
+ return file !== undefined && fs.existsSync(file);
150
+ }
151
+ // implements REQ-agent-hosts-decision-guard
152
+ /**
153
+ * True the first time `flag` is claimed in the session. Without a state
154
+ * directory nothing can be remembered, so nothing is claimed.
155
+ */
156
+ export function claimDecisionFlag(session, flag) {
157
+ const file = sessionPath(session, flag);
158
+ if (!file)
159
+ return false;
160
+ try {
161
+ writeMarker(file, "", "wx");
162
+ return true;
163
+ }
164
+ catch {
165
+ return false;
166
+ }
167
+ }
168
+ // implements REQ-agent-hosts-decision-guard
169
+ /**
170
+ * Remember a submitted prompt's topic words (for unlinked-file candidates)
171
+ * and whether it read as a rule. Returns the rule phrase, if any.
172
+ */
173
+ export function recordRequest(session, prompt) {
174
+ const rule = statedRule(prompt);
175
+ const file = sessionPath(session, "request-words.json");
176
+ if (file) {
177
+ try {
178
+ writeMarker(file, JSON.stringify(requestTopicWords(prompt)), "w");
179
+ }
180
+ catch {
181
+ // Best effort.
182
+ }
183
+ }
184
+ if (rule !== undefined)
185
+ markDecisionFlag(session, "rule-prompt");
186
+ return rule;
187
+ }
188
+ // implements REQ-agent-hosts-decision-guard
189
+ /** Topic words of the session's latest prompt, or none. */
190
+ export function requestWords(session) {
191
+ const file = sessionPath(session, "request-words.json");
192
+ if (!file)
193
+ return [];
194
+ try {
195
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
196
+ return Array.isArray(parsed)
197
+ ? parsed.filter((word) => typeof word === "string")
198
+ : [];
199
+ }
200
+ catch {
201
+ return [];
202
+ }
203
+ }
204
+ // implements REQ-agent-hosts-decision-guard
205
+ /**
206
+ * Whether the stop should ask for the session's decision to be recorded:
207
+ * source changed, nothing was written with kb_upsert, and the session has
208
+ * not been asked yet (claiming the ask).
209
+ */
210
+ export function claimCaptureReminder(session) {
211
+ return (hasDecisionFlag(session, "source-edited") &&
212
+ !hasDecisionFlag(session, "kb-recorded") &&
213
+ claimDecisionFlag(session, "capture-asked"));
214
+ }
215
+ function readSettled(file) {
216
+ if (!file)
217
+ return [];
218
+ try {
219
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
220
+ return Array.isArray(parsed)
221
+ ? parsed.filter((id) => typeof id === "string")
222
+ : [];
223
+ }
224
+ catch {
225
+ return [];
226
+ }
227
+ }
228
+ // implements REQ-agent-hosts-decision-guard
229
+ /** Firm requirements the agent was already told about this session. */
230
+ export function settledFirmRequirements(session) {
231
+ return new Set(readSettled(sessionPath(session, "firm-settled.json")));
232
+ }
233
+ // implements REQ-agent-hosts-decision-guard
234
+ /** Remember that the agent was told about these firm requirements. */
235
+ export function settleFirmRequirements(session, ids) {
236
+ const file = sessionPath(session, "firm-settled.json");
237
+ if (!file)
238
+ return;
239
+ try {
240
+ writeMarker(file, JSON.stringify([...new Set([...readSettled(file), ...ids])]), "w");
241
+ }
242
+ catch {
243
+ // Best effort: a lost write means the notice may repeat.
244
+ }
245
+ }
246
+ // implements REQ-agent-hosts-decision-guard
247
+ /**
248
+ * Keep a prompt's rule note for a host whose prompt hook cannot add context,
249
+ * so the next hook that can speak to the agent delivers it.
250
+ */
251
+ export function holdRuleNote(session, phrase) {
252
+ const file = sessionPath(session, "rule-note");
253
+ if (!file)
254
+ return;
255
+ try {
256
+ writeMarker(file, rulePromptNote(phrase), "w");
257
+ }
258
+ catch {
259
+ // Best effort.
260
+ }
261
+ }
262
+ // implements REQ-agent-hosts-decision-guard
263
+ /** The held rule note, removed so it is delivered once; or undefined. */
264
+ export function takeRuleNote(session) {
265
+ const file = sessionPath(session, "rule-note");
266
+ if (!file)
267
+ return undefined;
268
+ try {
269
+ const note = fs.readFileSync(file, "utf8");
270
+ fs.rmSync(file, { force: true });
271
+ return note || undefined;
272
+ }
273
+ catch {
274
+ return undefined;
275
+ }
276
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./decision-guard.js";
1
2
  export * from "./hook-usage-log.js";
2
3
  export * from "./kb-mcp-tools.js";
3
4
  export * from "./knowledge-index.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./decision-guard.js";
1
2
  export * from "./hook-usage-log.js";
2
3
  export * from "./kb-mcp-tools.js";
3
4
  export * from "./knowledge-index.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kibi-agent-core",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Shared low-latency hook helpers for Kibi agent adapters",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -10,6 +10,10 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "default": "./dist/index.js"
12
12
  },
13
+ "./decision-guard": {
14
+ "types": "./dist/decision-guard.d.ts",
15
+ "default": "./dist/decision-guard.js"
16
+ },
13
17
  "./hook-usage-log": {
14
18
  "types": "./dist/hook-usage-log.d.ts",
15
19
  "default": "./dist/hook-usage-log.js"