@krisada-m/ksd-intelligence 0.0.0-stage → 1.1.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.
- package/.antigravity-plugin/plugin.json +20 -0
- package/LICENSE +21 -0
- package/README.md +195 -2
- package/agy-skills/erosiano-review/SKILL.md +17 -0
- package/dist/adapters/agy/skills.js +252 -0
- package/dist/adapters/cli/check-changed.js +3 -0
- package/dist/adapters/cli/main.js +1013 -0
- package/dist/adapters/cli/policy-bin.js +10 -0
- package/dist/adapters/cli/review-verdict.js +3 -0
- package/dist/adapters/omp/extension.js +884 -0
- package/dist/adapters/omp/skills.js +130 -0
- package/dist/adapters/ui/hud.js +389 -0
- package/dist/adapters/ui/tree.js +471 -0
- package/dist/core/audit/index.js +2 -0
- package/dist/core/audit/log.js +505 -0
- package/dist/core/audit/summary.js +188 -0
- package/dist/core/changes/changes.js +591 -0
- package/dist/core/changes/git.js +266 -0
- package/dist/core/changes/plan.js +109 -0
- package/dist/core/changes/render.js +356 -0
- package/dist/core/engine/build.js +178 -0
- package/dist/core/engine/child.js +389 -0
- package/dist/core/engine/host.js +206 -0
- package/dist/core/engine/lock.js +133 -0
- package/dist/core/engine/protocol.js +43 -0
- package/dist/core/engine/runtime.js +44 -0
- package/dist/core/engine/status.js +452 -0
- package/dist/core/engine/typescript.js +194 -0
- package/dist/core/engine/workspace.js +72 -0
- package/dist/core/graph/graph.js +127 -0
- package/dist/core/graph/limits.js +16 -0
- package/dist/core/impact/query.js +1292 -0
- package/dist/core/impact/render.js +590 -0
- package/dist/core/impact/session.js +694 -0
- package/dist/core/indexing/declarations.js +455 -0
- package/dist/core/indexing/differential.js +345 -0
- package/dist/core/indexing/doctor.js +120 -0
- package/dist/core/indexing/indexer.js +811 -0
- package/dist/core/indexing/keys.js +451 -0
- package/dist/core/indexing/lexical.js +212 -0
- package/dist/core/indexing/packages.js +57 -0
- package/dist/core/indexing/program.js +171 -0
- package/dist/core/indexing/resolve.js +1004 -0
- package/dist/core/indexing/stamp.js +52 -0
- package/dist/core/indexing/surface.js +335 -0
- package/dist/core/indexing/ui-progress.js +37 -0
- package/dist/core/indexing/verify.js +76 -0
- package/dist/core/kernel/config.js +383 -0
- package/dist/core/kernel/glob.js +105 -0
- package/dist/core/kernel/guards.js +4 -0
- package/dist/core/kernel/types.js +3 -0
- package/dist/core/kernel/verdict.js +142 -0
- package/dist/core/knowledge/anchors.js +139 -0
- package/dist/core/knowledge/knowledge.js +95 -0
- package/dist/core/knowledge/learning.js +102 -0
- package/dist/core/knowledge/render.js +76 -0
- package/dist/core/knowledge/store.js +109 -0
- package/dist/core/knowledge/yaml.js +87 -0
- package/dist/core/search/lexical.js +382 -0
- package/dist/core/search/render.js +98 -0
- package/dist/core/search/segments.js +118 -0
- package/dist/core/verify/parse.js +127 -0
- package/dist/core/verify/render.js +67 -0
- package/dist/core/verify/report.js +40 -0
- package/dist/core/verify/revision.js +79 -0
- package/dist/core/verify/run.js +117 -0
- package/dist/core/verify/store.js +66 -0
- package/dist/core/verify/verify.js +173 -0
- package/dist/core/workspace/init.js +267 -0
- package/dist/core/workspace/probe.js +56 -0
- package/dist/core/workspace/scan.js +420 -0
- package/dist/engineering/baseline.js +337 -0
- package/dist/engineering/change-scope.js +500 -0
- package/dist/engineering/check-changed.js +40 -0
- package/dist/engineering/config.js +129 -0
- package/dist/engineering/dist/policy.d.ts +17 -0
- package/dist/engineering/dist/policy.js +150 -0
- package/dist/engineering/dist/runtime.d.ts +40 -0
- package/dist/engineering/dist/runtime.js +77 -0
- package/dist/engineering/dist/sdlc.d.ts +7 -0
- package/dist/engineering/dist/sdlc.js +27 -0
- package/dist/engineering/eslint-rules/index.js +107 -0
- package/dist/engineering/index.d.ts +7 -0
- package/dist/engineering/index.js +319 -0
- package/dist/engineering/intelligence.js +44 -0
- package/dist/engineering/package.json +36 -0
- package/dist/engineering/policy.js +2 -0
- package/dist/engineering/practice-tool.js +72 -0
- package/dist/engineering/practices.js +283 -0
- package/dist/engineering/practices.json +2453 -0
- package/dist/engineering/review-verdict.js +262 -0
- package/dist/engineering/sdlc.js +2 -0
- package/dist/index.js +20 -0
- package/dist/storage/records.js +245 -0
- package/dist/storage/sqlite.js +314 -0
- package/dist/workflow/catalog.js +69 -0
- package/dist/workflow/classify.js +55 -0
- package/dist/workflow/loader.js +140 -0
- package/dist/workflow/packs.js +469 -0
- package/dist/workflow/registry.js +359 -0
- package/dist/workflow/render.js +61 -0
- package/dist/workflow/router.js +141 -0
- package/dist/workflow/sources.js +229 -0
- package/dist/workflow/types.js +44 -0
- package/dist/workflow/updates.js +532 -0
- package/engineering.lock.json +94 -0
- package/package.json +81 -4
- package/rules/engineering.md +20 -0
- package/scripts/agy-mcp.mjs +27 -0
- package/scripts/mcp/engineering.mjs +91 -0
- package/scripts/mcp/stdio.mjs +304 -0
- package/scripts/mcp/tools.mjs +491 -0
- package/skills/ksd-intelligence/SKILL.md +54 -0
- package/skills/matt-sdlc/SKILL.md +42 -0
- package/skills/osmani-quality/SKILL.md +38 -0
- package/skills/poteto-mode/SKILL.md +40 -0
- package/skills/pstack-analysis/SKILL.md +36 -0
- package/skills.lock.json +71 -0
- package/skills.registry.json +181 -0
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single OMP composition root: pinned erosiano-dev engineering policy and native ei_* tools.
|
|
3
|
+
* Registration failures are isolated. EI_DISABLED affects intelligence only; the engineering
|
|
4
|
+
* library owns its config, commands, lifecycle and disable flags.
|
|
5
|
+
*/
|
|
6
|
+
import { auditFieldsForChanges, auditFieldsForImpact, auditFieldsForSearch, auditFieldsForWorkflow, consumeAuditWarning, recordAudit, } from '../../core/audit/index.js';
|
|
7
|
+
import { runChanges } from '../../core/changes/changes.js';
|
|
8
|
+
import { renderChangesOutcome } from '../../core/changes/render.js';
|
|
9
|
+
import { renderStatus, workspaceStatus } from '../../core/engine/status.js';
|
|
10
|
+
import { engineVersion } from '../../core/engine/typescript.js';
|
|
11
|
+
import { loadWorkspace, readProjectConfigSync, resolveWorkspaceCache, } from '../../core/engine/workspace.js';
|
|
12
|
+
import { impactDetails, renderImpact } from '../../core/impact/render.js';
|
|
13
|
+
import { ImpactSession } from '../../core/impact/session.js';
|
|
14
|
+
import { isRecord } from '../../core/kernel/guards.js';
|
|
15
|
+
import { impactLearningsLine, proposeLearning, snapshot, withAnchorIndex, } from '../../core/knowledge/knowledge.js';
|
|
16
|
+
import { learningsFor, quoteClaim, renderLearningList, PROPOSAL_LABEL, } from '../../core/knowledge/render.js';
|
|
17
|
+
import { runSearch, validateSearchInput } from '../../core/search/lexical.js';
|
|
18
|
+
import { renderSearchOutcome } from '../../core/search/render.js';
|
|
19
|
+
import { changesVerificationNote, renderVerifyOutcome } from '../../core/verify/render.js';
|
|
20
|
+
import { loadVerificationState, runVerification, validateVerifyInput, } from '../../core/verify/verify.js';
|
|
21
|
+
import { rootsFromEnv } from '../../workflow/catalog.js';
|
|
22
|
+
import { prepareWorkflow } from '../../workflow/loader.js';
|
|
23
|
+
import { renderWorkflow } from '../../workflow/render.js';
|
|
24
|
+
import { defaultLockPath, readLock } from '../../workflow/sources.js';
|
|
25
|
+
import { RISKS, STAGES, TASK_TYPES, WorkflowError } from '../../workflow/types.js';
|
|
26
|
+
import { createExtension as createPolicyExtension } from '../../engineering/index.js';
|
|
27
|
+
import { SECTION_KEY } from '../../engineering/dist/policy.js';
|
|
28
|
+
import { renderResultView } from '../ui/tree.js';
|
|
29
|
+
function isImpactResult(value) {
|
|
30
|
+
return (isRecord(value) &&
|
|
31
|
+
typeof value.target === 'string' &&
|
|
32
|
+
isRecord(value.verdict) &&
|
|
33
|
+
isRecord(value.reach) &&
|
|
34
|
+
isRecord(value.completeness) &&
|
|
35
|
+
Array.isArray(value.byDepth) &&
|
|
36
|
+
Array.isArray(value.bridged) &&
|
|
37
|
+
Array.isArray(value.tests) &&
|
|
38
|
+
Array.isArray(value.factors) &&
|
|
39
|
+
isRecord(value.engine));
|
|
40
|
+
}
|
|
41
|
+
function isWorkspaceStatus(value) {
|
|
42
|
+
return (isRecord(value) &&
|
|
43
|
+
(value.state === 'ready' || value.state === 'degraded') &&
|
|
44
|
+
isRecord(value.runtime) &&
|
|
45
|
+
isRecord(value.typescript) &&
|
|
46
|
+
isRecord(value.config));
|
|
47
|
+
}
|
|
48
|
+
function isChangesResult(value) {
|
|
49
|
+
return (isRecord(value) &&
|
|
50
|
+
Array.isArray(value.changedSymbols) &&
|
|
51
|
+
Array.isArray(value.changedFiles) &&
|
|
52
|
+
isRecord(value.impact) &&
|
|
53
|
+
isRecord(value.verdict) &&
|
|
54
|
+
isRecord(value.engine));
|
|
55
|
+
}
|
|
56
|
+
function isSearchResult(value) {
|
|
57
|
+
return (isRecord(value) &&
|
|
58
|
+
typeof value.query === 'string' &&
|
|
59
|
+
Array.isArray(value.hits) &&
|
|
60
|
+
typeof value.totalMatches === 'number' &&
|
|
61
|
+
isRecord(value.engine));
|
|
62
|
+
}
|
|
63
|
+
function impactView(details) {
|
|
64
|
+
if (!Array.isArray(details) || details.length === 0)
|
|
65
|
+
return undefined;
|
|
66
|
+
const first = details[0];
|
|
67
|
+
if (!isRecord(first) || !isRecord(first.presentationIndex))
|
|
68
|
+
return undefined;
|
|
69
|
+
const index = first.presentationIndex;
|
|
70
|
+
if (index.state !== 'fresh' &&
|
|
71
|
+
index.state !== 'updated' &&
|
|
72
|
+
index.state !== 'stale' &&
|
|
73
|
+
index.state !== 'building')
|
|
74
|
+
return undefined;
|
|
75
|
+
if (typeof index.updatedFiles !== 'number' || !Array.isArray(index.driftedFiles))
|
|
76
|
+
return undefined;
|
|
77
|
+
if (!details.every(isImpactResult))
|
|
78
|
+
return undefined;
|
|
79
|
+
const answers = details.map((value) => ({
|
|
80
|
+
kind: 'result',
|
|
81
|
+
input: value.target,
|
|
82
|
+
value,
|
|
83
|
+
}));
|
|
84
|
+
return {
|
|
85
|
+
kind: 'impact',
|
|
86
|
+
learningsLine: typeof first.learningsLine === 'string' ? first.learningsLine : undefined,
|
|
87
|
+
value: {
|
|
88
|
+
answers,
|
|
89
|
+
index: {
|
|
90
|
+
state: index.state,
|
|
91
|
+
updatedFiles: index.updatedFiles,
|
|
92
|
+
driftedFiles: index.driftedFiles,
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function resultView(kind, details) {
|
|
98
|
+
if (kind === 'impact')
|
|
99
|
+
return impactView(details);
|
|
100
|
+
if (kind === 'status' && isWorkspaceStatus(details))
|
|
101
|
+
return { kind: 'status', value: details };
|
|
102
|
+
if (kind === 'changes' && isChangesResult(details)) {
|
|
103
|
+
const note = 'verificationNote' in details ? details.verificationNote : undefined;
|
|
104
|
+
const verificationNote = isRecord(note)
|
|
105
|
+
? {
|
|
106
|
+
line: typeof note.line === 'string' ? note.line : undefined,
|
|
107
|
+
nextHint: typeof note.nextHint === 'string' ? note.nextHint : undefined,
|
|
108
|
+
}
|
|
109
|
+
: undefined;
|
|
110
|
+
return { kind: 'changes', value: { kind: 'result', value: details }, verificationNote };
|
|
111
|
+
}
|
|
112
|
+
if (kind === 'search' && isSearchResult(details))
|
|
113
|
+
return { kind: 'search', value: { kind: 'result', value: details } };
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
function displayText(text) {
|
|
117
|
+
return text.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g, '?').split('\n');
|
|
118
|
+
}
|
|
119
|
+
function renderToolResult(kind, result, options) {
|
|
120
|
+
return {
|
|
121
|
+
render(width) {
|
|
122
|
+
const view = !options.isPartial && !result.isError ? resultView(kind, result.details) : undefined;
|
|
123
|
+
if (view) {
|
|
124
|
+
try {
|
|
125
|
+
return renderResultView(view, {
|
|
126
|
+
columns: width,
|
|
127
|
+
color: process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb',
|
|
128
|
+
ascii: process.env.EI_ASCII === '1' ||
|
|
129
|
+
!/utf-?8/i.test(process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? 'UTF-8'),
|
|
130
|
+
collapsed: !options.expanded,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
// Replayed results may have details from an older adapter.
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
let state = 'partial · details unavailable';
|
|
138
|
+
if (result.isError)
|
|
139
|
+
state = 'failed';
|
|
140
|
+
else if (options.isPartial)
|
|
141
|
+
state = 'in progress · partial';
|
|
142
|
+
const heading = `${result.isError ? '✗' : '?'} ${kind} ${state}`;
|
|
143
|
+
if (!options.expanded)
|
|
144
|
+
return [heading];
|
|
145
|
+
return [heading, ...result.content.flatMap((part) => displayText(part.text))];
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function renderToolCall(kind, args, options) {
|
|
150
|
+
if (!options.expanded && !options.isPartial)
|
|
151
|
+
return undefined;
|
|
152
|
+
return {
|
|
153
|
+
render() {
|
|
154
|
+
if (!isRecord(args))
|
|
155
|
+
return [`ei_${kind}`];
|
|
156
|
+
let target = '';
|
|
157
|
+
if (kind === 'impact' && Array.isArray(args.targets))
|
|
158
|
+
target = args.targets
|
|
159
|
+
.filter((value) => typeof value === 'string')
|
|
160
|
+
.join(', ');
|
|
161
|
+
if (kind === 'search' && typeof args.query === 'string')
|
|
162
|
+
target = args.query;
|
|
163
|
+
if (kind === 'changes' && typeof args.base === 'string')
|
|
164
|
+
target = `vs ${args.base}`;
|
|
165
|
+
return [`ei_${kind}${target ? ` ${displayText(target).join(' ')}` : ''}`];
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function errorResult(message) {
|
|
170
|
+
return { isError: true, content: [{ type: 'text', text: message }] };
|
|
171
|
+
}
|
|
172
|
+
// Load-time errors have no ctx.ui yet; console.error with KSD's SECTION_KEY tag is
|
|
173
|
+
// the closest equivalent of KSD's own warning channel (`ctx.ui.notify(msg, "warning")`).
|
|
174
|
+
function warnLoad(stage, error) {
|
|
175
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
176
|
+
console.error(`ksd-intelligence: ${stage} failed to register (${SECTION_KEY}): ${message}`);
|
|
177
|
+
}
|
|
178
|
+
async function tryResolveCache(cwd, cacheHome) {
|
|
179
|
+
try {
|
|
180
|
+
const info = await resolveWorkspaceCache(cwd ?? process.cwd(), cacheHome);
|
|
181
|
+
return { root: info.root, cacheDir: info.cacheDir };
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function registerEiWorkflow(pi, env, lockPath, skillsDir, cacheHome) {
|
|
188
|
+
const z = pi.zod;
|
|
189
|
+
const shape = {
|
|
190
|
+
task: z.string(),
|
|
191
|
+
stage: z.enum(STAGES),
|
|
192
|
+
risk: z.enum(RISKS).optional(),
|
|
193
|
+
type: z
|
|
194
|
+
.enum(TASK_TYPES)
|
|
195
|
+
.optional()
|
|
196
|
+
.describe('Caller-asserted task type; overrides the keyword classifier'),
|
|
197
|
+
};
|
|
198
|
+
if (z.boolean) {
|
|
199
|
+
shape.potetoMode = z
|
|
200
|
+
.boolean()
|
|
201
|
+
.optional()
|
|
202
|
+
.describe('Explicit opt-in for poteto-mode multi-phase workflow; never enabled automatically');
|
|
203
|
+
}
|
|
204
|
+
pi.registerTool({
|
|
205
|
+
name: 'ei_workflow',
|
|
206
|
+
label: 'KSD Skills Workflow',
|
|
207
|
+
description: 'Choose and read allowlisted Matt Pocock, poteto/pstack and Addy Osmani skills for an engineering task and stage. ' +
|
|
208
|
+
'Pass `type` when you can classify the task yourself (including non-English text); otherwise a keyword guess is used and reported. ' +
|
|
209
|
+
'Set `potetoMode: true` only when the user explicitly opts into poteto-mode.',
|
|
210
|
+
parameters: z.object(shape),
|
|
211
|
+
approval: 'read',
|
|
212
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
213
|
+
if (signal?.aborted)
|
|
214
|
+
return errorResult('Cancelled');
|
|
215
|
+
const started = performance.now();
|
|
216
|
+
try {
|
|
217
|
+
const workflow = await prepareWorkflow({
|
|
218
|
+
...params,
|
|
219
|
+
strict: true,
|
|
220
|
+
roots: rootsFromEnv(env),
|
|
221
|
+
lock: await readLock(lockPath),
|
|
222
|
+
skillsDir,
|
|
223
|
+
});
|
|
224
|
+
const cache = await tryResolveCache(ctx?.cwd, cacheHome);
|
|
225
|
+
if (cache !== null) {
|
|
226
|
+
recordAudit(cache.cacheDir, {
|
|
227
|
+
ts: new Date().toISOString(),
|
|
228
|
+
tool: 'ei_workflow',
|
|
229
|
+
adapter: 'omp',
|
|
230
|
+
outcome: 'result',
|
|
231
|
+
ms: performance.now() - started,
|
|
232
|
+
engine: engineVersion(),
|
|
233
|
+
...auditFieldsForWorkflow(workflow),
|
|
234
|
+
}, { env, root: cache.root });
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
content: [{ type: 'text', text: renderWorkflow(workflow) }],
|
|
238
|
+
details: {
|
|
239
|
+
type: workflow.type,
|
|
240
|
+
classifiedBy: workflow.classifiedBy,
|
|
241
|
+
stage: workflow.stage,
|
|
242
|
+
skillIds: workflow.skillIds,
|
|
243
|
+
ready: workflow.ready,
|
|
244
|
+
...(workflow.optInPacks.length > 0 ? { optInPacks: workflow.optInPacks } : {}),
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
const cache = await tryResolveCache(ctx?.cwd, cacheHome);
|
|
250
|
+
if (cache !== null) {
|
|
251
|
+
const task = isRecord(params) && typeof params.task === 'string' ? params.task : undefined;
|
|
252
|
+
const stage = isRecord(params) && typeof params.stage === 'string' ? params.stage : undefined;
|
|
253
|
+
recordAudit(cache.cacheDir, {
|
|
254
|
+
ts: new Date().toISOString(),
|
|
255
|
+
tool: 'ei_workflow',
|
|
256
|
+
adapter: 'omp',
|
|
257
|
+
outcome: 'error',
|
|
258
|
+
ms: performance.now() - started,
|
|
259
|
+
engine: engineVersion(),
|
|
260
|
+
code: error instanceof WorkflowError ? error.code : 'WORKFLOW_ERROR',
|
|
261
|
+
...(task !== undefined ? { task } : {}),
|
|
262
|
+
...(stage !== undefined ? { stage } : {}),
|
|
263
|
+
}, { env, root: cache.root });
|
|
264
|
+
}
|
|
265
|
+
return errorResult(error instanceof Error ? error.message : String(error));
|
|
266
|
+
}
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
function registerEiStatus(pi, deps, env) {
|
|
271
|
+
pi.registerTool({
|
|
272
|
+
name: 'ei_status',
|
|
273
|
+
label: 'KSD Index Status',
|
|
274
|
+
description: 'Shows whether the code index is ready and how much of the repository it covers. ' +
|
|
275
|
+
'Call this if an ei_ result looks empty, stale or wrong.',
|
|
276
|
+
// No input: nothing the agent passes can reach the engine or its environment.
|
|
277
|
+
parameters: pi.zod.object({}),
|
|
278
|
+
approval: 'read',
|
|
279
|
+
renderCall: (args, options) => renderToolCall('status', args, options),
|
|
280
|
+
renderResult: (result, options) => renderToolResult('status', result, options),
|
|
281
|
+
async execute(_toolCallId, _params, signal, _onUpdate, ctx) {
|
|
282
|
+
if (signal?.aborted)
|
|
283
|
+
return errorResult('Cancelled');
|
|
284
|
+
const started = performance.now();
|
|
285
|
+
try {
|
|
286
|
+
const status = await workspaceStatus(ctx?.cwd ?? process.cwd(), {
|
|
287
|
+
cacheHome: deps.cacheHome,
|
|
288
|
+
env,
|
|
289
|
+
});
|
|
290
|
+
recordAudit(status.cacheDir, {
|
|
291
|
+
ts: new Date().toISOString(),
|
|
292
|
+
tool: 'ei_status',
|
|
293
|
+
adapter: 'omp',
|
|
294
|
+
outcome: 'result',
|
|
295
|
+
ms: performance.now() - started,
|
|
296
|
+
engine: engineVersion(),
|
|
297
|
+
...(status.typescript.ok ? { ts_version: status.typescript.runtime.version } : {}),
|
|
298
|
+
statusState: status.state,
|
|
299
|
+
}, { env, root: status.root });
|
|
300
|
+
const extraWarning = consumeAuditWarning(status.cacheDir);
|
|
301
|
+
if (extraWarning !== null)
|
|
302
|
+
status.auditWarning = extraWarning;
|
|
303
|
+
return { content: [{ type: 'text', text: renderStatus(status) }], details: status };
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
307
|
+
if (cache !== null) {
|
|
308
|
+
recordAudit(cache.cacheDir, {
|
|
309
|
+
ts: new Date().toISOString(),
|
|
310
|
+
tool: 'ei_status',
|
|
311
|
+
adapter: 'omp',
|
|
312
|
+
outcome: 'error',
|
|
313
|
+
ms: performance.now() - started,
|
|
314
|
+
engine: engineVersion(),
|
|
315
|
+
code: 'index-failed',
|
|
316
|
+
}, { env, root: cache.root });
|
|
317
|
+
}
|
|
318
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
319
|
+
return errorResult(`index-failed: ${message}. Retry once; if it fails again, continue without ei_status and say so in your report.`);
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
function registerEiImpact(pi, deps, env, sessions) {
|
|
325
|
+
const z = pi.zod;
|
|
326
|
+
const targetsSchema = (() => {
|
|
327
|
+
const base = z.array ? z.array(z.string()) : z.string();
|
|
328
|
+
const min = base.min ? base.min(1) : base;
|
|
329
|
+
const max = min.max ? min.max(5) : min;
|
|
330
|
+
return max.describe('1–5 targets: bare name, Class.member, path#name, path:line, or file path');
|
|
331
|
+
})();
|
|
332
|
+
const depthSchema = (() => {
|
|
333
|
+
const base = z.number ? z.number() : z.string();
|
|
334
|
+
const int = base.int ? base.int() : base;
|
|
335
|
+
const min = int.min ? int.min(1) : int;
|
|
336
|
+
const max = min.max ? min.max(10) : min;
|
|
337
|
+
return max.optional().describe('How many caller levels to list (1–10, default 2)');
|
|
338
|
+
})();
|
|
339
|
+
pi.registerTool({
|
|
340
|
+
name: 'ei_impact',
|
|
341
|
+
label: 'KSD Code Impact',
|
|
342
|
+
description: 'Before editing a function, method, class, type or exported constant, call this even for comment-only edits. It shows callers by depth with file:line, how far the change reaches, the tests that reach it, and whether the picture is complete. Accepts up to 5 targets as names (`calculateFee`, `PaymentService.charge`), `path#name`, `path:line`, or a file path. Read-only.',
|
|
343
|
+
parameters: z.object({
|
|
344
|
+
targets: targetsSchema,
|
|
345
|
+
depth: depthSchema,
|
|
346
|
+
}),
|
|
347
|
+
approval: 'read',
|
|
348
|
+
renderCall: (args, options) => renderToolCall('impact', args, options),
|
|
349
|
+
renderResult: (result, options) => renderToolResult('impact', result, options),
|
|
350
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
351
|
+
if (signal?.aborted)
|
|
352
|
+
return errorResult('Cancelled');
|
|
353
|
+
const started = performance.now();
|
|
354
|
+
const recordInvalid = async (targets) => {
|
|
355
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
356
|
+
if (cache === null)
|
|
357
|
+
return;
|
|
358
|
+
recordAudit(cache.cacheDir, {
|
|
359
|
+
ts: new Date().toISOString(),
|
|
360
|
+
tool: 'ei_impact',
|
|
361
|
+
adapter: 'omp',
|
|
362
|
+
outcome: 'failure',
|
|
363
|
+
ms: performance.now() - started,
|
|
364
|
+
engine: engineVersion(),
|
|
365
|
+
code: 'INVALID_INPUT',
|
|
366
|
+
codes: ['INVALID_INPUT'],
|
|
367
|
+
...(targets && targets.length > 0 ? { targets: [...targets] } : {}),
|
|
368
|
+
}, { env, root: cache.root });
|
|
369
|
+
};
|
|
370
|
+
try {
|
|
371
|
+
const rawTargets = isRecord(params) ? params.targets : undefined;
|
|
372
|
+
const rawDepth = isRecord(params) ? params.depth : undefined;
|
|
373
|
+
if (!Array.isArray(rawTargets) ||
|
|
374
|
+
rawTargets.length < 1 ||
|
|
375
|
+
rawTargets.length > 5 ||
|
|
376
|
+
rawTargets.some((target) => typeof target !== 'string' || target.trim() === '')) {
|
|
377
|
+
await recordInvalid();
|
|
378
|
+
return errorResult('INVALID_INPUT: provide 1–5 non-empty string targets');
|
|
379
|
+
}
|
|
380
|
+
if (rawDepth !== undefined &&
|
|
381
|
+
(typeof rawDepth !== 'number' ||
|
|
382
|
+
!Number.isInteger(rawDepth) ||
|
|
383
|
+
rawDepth < 1 ||
|
|
384
|
+
rawDepth > 10)) {
|
|
385
|
+
await recordInvalid(rawTargets);
|
|
386
|
+
return errorResult('INVALID_INPUT: depth must be an integer 1–10');
|
|
387
|
+
}
|
|
388
|
+
const workspace = await loadWorkspace(ctx?.cwd ?? process.cwd(), deps.cacheHome);
|
|
389
|
+
let session = sessions.get(workspace.cacheDir);
|
|
390
|
+
if (session === undefined) {
|
|
391
|
+
session = new ImpactSession(workspace, deps.impactSession);
|
|
392
|
+
sessions.set(workspace.cacheDir, session);
|
|
393
|
+
}
|
|
394
|
+
const batch = await session.query(rawTargets, rawDepth, {
|
|
395
|
+
signal,
|
|
396
|
+
onProgress: (message, data) => {
|
|
397
|
+
onUpdate?.({ content: [{ type: 'text', text: message }], details: data });
|
|
398
|
+
},
|
|
399
|
+
});
|
|
400
|
+
if (signal?.aborted)
|
|
401
|
+
return errorResult('Cancelled');
|
|
402
|
+
const keys = impactDetails(batch).flatMap((item) => 'target' in item && typeof item.target === 'string' ? [item.target] : []);
|
|
403
|
+
const learningsLine = await impactLearningsLine(workspace, session, keys, signal);
|
|
404
|
+
const impactText = renderImpact(batch);
|
|
405
|
+
// Appended after the V1 block, never inside it; absent when knowledge is off or empty.
|
|
406
|
+
const text = learningsLine === undefined || impactText === 'Cancelled'
|
|
407
|
+
? impactText
|
|
408
|
+
: `${impactText}\n${learningsLine}`;
|
|
409
|
+
if (text === 'Cancelled')
|
|
410
|
+
return errorResult('Cancelled');
|
|
411
|
+
recordAudit(workspace.cacheDir, {
|
|
412
|
+
ts: new Date().toISOString(),
|
|
413
|
+
tool: 'ei_impact',
|
|
414
|
+
adapter: 'omp',
|
|
415
|
+
outcome: 'result',
|
|
416
|
+
ms: performance.now() - started,
|
|
417
|
+
engine: engineVersion(),
|
|
418
|
+
...auditFieldsForImpact(batch, engineVersion()),
|
|
419
|
+
}, { env, root: workspace.root });
|
|
420
|
+
const details = impactDetails(batch);
|
|
421
|
+
const first = details[0];
|
|
422
|
+
if (first !== undefined) {
|
|
423
|
+
const presented = { ...first, presentationIndex: batch.index, learningsLine };
|
|
424
|
+
details[0] = presented;
|
|
425
|
+
}
|
|
426
|
+
const failed = batch.answers.some((answer) => answer.kind === 'failure');
|
|
427
|
+
if (failed) {
|
|
428
|
+
return { isError: true, content: [{ type: 'text', text }], details };
|
|
429
|
+
}
|
|
430
|
+
return { content: [{ type: 'text', text }], details };
|
|
431
|
+
}
|
|
432
|
+
catch (error) {
|
|
433
|
+
if (signal?.aborted)
|
|
434
|
+
return errorResult('Cancelled');
|
|
435
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
436
|
+
if (cache !== null) {
|
|
437
|
+
recordAudit(cache.cacheDir, {
|
|
438
|
+
ts: new Date().toISOString(),
|
|
439
|
+
tool: 'ei_impact',
|
|
440
|
+
adapter: 'omp',
|
|
441
|
+
outcome: 'error',
|
|
442
|
+
ms: performance.now() - started,
|
|
443
|
+
engine: engineVersion(),
|
|
444
|
+
code: 'index-failed',
|
|
445
|
+
}, { env, root: cache.root });
|
|
446
|
+
}
|
|
447
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
448
|
+
return errorResult(`index-failed: ${message}. Retry once; if it fails again, continue without ei_impact and say so in your report.`);
|
|
449
|
+
}
|
|
450
|
+
},
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
function registerEiChanges(pi, deps, env, sessions) {
|
|
454
|
+
const z = pi.zod;
|
|
455
|
+
const baseSchema = z
|
|
456
|
+
.string()
|
|
457
|
+
.optional()
|
|
458
|
+
.describe('Git ref to compare against (default: merge-base with the default branch)');
|
|
459
|
+
const depthSchema = (() => {
|
|
460
|
+
const base = z.number ? z.number() : z.string();
|
|
461
|
+
const int = base.int ? base.int() : base;
|
|
462
|
+
const min = int.min ? int.min(1) : int;
|
|
463
|
+
const max = min.max ? min.max(10) : min;
|
|
464
|
+
return max.optional().describe('Levels of callers to list (1–10, default 1)');
|
|
465
|
+
})();
|
|
466
|
+
const plannedSchema = (z.array ? z.array(z.string()) : z.string())
|
|
467
|
+
.optional()
|
|
468
|
+
.describe('Planned symbol targets or file paths; unmentioned changes appear under Not in plan');
|
|
469
|
+
pi.registerTool({
|
|
470
|
+
name: 'ei_changes',
|
|
471
|
+
label: 'KSD Changed Code Impact',
|
|
472
|
+
description: 'Call with no arguments when asked to review the current diff, even if you did not edit or the working tree is clean. Also call after editing code, before reporting the work done. It reads uncommitted changes and lists changed symbols, their impact, tests to run, and files it cannot analyse. A post-edit result with no tests does not waive an earlier ei_impact run-tests verdict. Read-only.',
|
|
473
|
+
parameters: z.object({
|
|
474
|
+
base: baseSchema,
|
|
475
|
+
depth: depthSchema,
|
|
476
|
+
planned: plannedSchema,
|
|
477
|
+
}),
|
|
478
|
+
approval: 'read',
|
|
479
|
+
renderCall: (args, options) => renderToolCall('changes', args, options),
|
|
480
|
+
renderResult: (result, options) => renderToolResult('changes', result, options),
|
|
481
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
482
|
+
if (signal?.aborted)
|
|
483
|
+
return errorResult('Cancelled');
|
|
484
|
+
const started = performance.now();
|
|
485
|
+
const recordInvalid = async () => {
|
|
486
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
487
|
+
if (cache === null)
|
|
488
|
+
return;
|
|
489
|
+
recordAudit(cache.cacheDir, {
|
|
490
|
+
ts: new Date().toISOString(),
|
|
491
|
+
tool: 'ei_changes',
|
|
492
|
+
adapter: 'omp',
|
|
493
|
+
outcome: 'failure',
|
|
494
|
+
ms: performance.now() - started,
|
|
495
|
+
engine: engineVersion(),
|
|
496
|
+
code: 'INVALID_INPUT',
|
|
497
|
+
codes: ['INVALID_INPUT'],
|
|
498
|
+
}, { env, root: cache.root });
|
|
499
|
+
};
|
|
500
|
+
try {
|
|
501
|
+
const rawBase = isRecord(params) ? params.base : undefined;
|
|
502
|
+
const rawDepth = isRecord(params) ? params.depth : undefined;
|
|
503
|
+
const rawPlanned = isRecord(params) ? params.planned : undefined;
|
|
504
|
+
if (rawBase !== undefined && typeof rawBase !== 'string') {
|
|
505
|
+
await recordInvalid();
|
|
506
|
+
return errorResult('INVALID_INPUT: base must be a string');
|
|
507
|
+
}
|
|
508
|
+
if (rawDepth !== undefined &&
|
|
509
|
+
(typeof rawDepth !== 'number' ||
|
|
510
|
+
!Number.isInteger(rawDepth) ||
|
|
511
|
+
rawDepth < 1 ||
|
|
512
|
+
rawDepth > 10)) {
|
|
513
|
+
await recordInvalid();
|
|
514
|
+
return errorResult('INVALID_INPUT: depth must be an integer 1–10');
|
|
515
|
+
}
|
|
516
|
+
if (rawPlanned !== undefined &&
|
|
517
|
+
(!Array.isArray(rawPlanned) ||
|
|
518
|
+
rawPlanned.some((target) => typeof target !== 'string' || target.trim() === ''))) {
|
|
519
|
+
await recordInvalid();
|
|
520
|
+
return errorResult('INVALID_INPUT: planned must be an array of non-empty strings');
|
|
521
|
+
}
|
|
522
|
+
const workspace = await loadWorkspace(ctx?.cwd ?? process.cwd(), deps.cacheHome);
|
|
523
|
+
let session = sessions.get(workspace.cacheDir);
|
|
524
|
+
if (session === undefined) {
|
|
525
|
+
session = new ImpactSession(workspace, deps.impactSession);
|
|
526
|
+
sessions.set(workspace.cacheDir, session);
|
|
527
|
+
}
|
|
528
|
+
const outcome = await runChanges(session, {
|
|
529
|
+
base: rawBase,
|
|
530
|
+
depth: rawDepth,
|
|
531
|
+
planned: rawPlanned,
|
|
532
|
+
signal,
|
|
533
|
+
onProgress: (message, data) => {
|
|
534
|
+
onUpdate?.({ content: [{ type: 'text', text: message }], details: data });
|
|
535
|
+
},
|
|
536
|
+
});
|
|
537
|
+
if (signal?.aborted)
|
|
538
|
+
return errorResult('Cancelled');
|
|
539
|
+
const verification = await loadVerificationState(workspace);
|
|
540
|
+
const verificationNote = verification &&
|
|
541
|
+
changesVerificationNote(verification.reports, verification.revision, verification.checkNames);
|
|
542
|
+
const text = renderChangesOutcome(outcome, undefined, verificationNote);
|
|
543
|
+
if (text === 'Cancelled')
|
|
544
|
+
return errorResult('Cancelled');
|
|
545
|
+
recordAudit(workspace.cacheDir, {
|
|
546
|
+
ts: new Date().toISOString(),
|
|
547
|
+
tool: 'ei_changes',
|
|
548
|
+
adapter: 'omp',
|
|
549
|
+
outcome: outcome.kind,
|
|
550
|
+
ms: performance.now() - started,
|
|
551
|
+
engine: engineVersion(),
|
|
552
|
+
...auditFieldsForChanges(outcome, engineVersion()),
|
|
553
|
+
}, { env, root: workspace.root });
|
|
554
|
+
if (outcome.kind === 'failure') {
|
|
555
|
+
return { isError: true, content: [{ type: 'text', text }], details: outcome };
|
|
556
|
+
}
|
|
557
|
+
if (outcome.kind === 'guidance') {
|
|
558
|
+
return { content: [{ type: 'text', text }], details: outcome };
|
|
559
|
+
}
|
|
560
|
+
return {
|
|
561
|
+
content: [{ type: 'text', text }],
|
|
562
|
+
details: verificationNote === undefined ? outcome.value : { ...outcome.value, verificationNote },
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
if (signal?.aborted)
|
|
567
|
+
return errorResult('Cancelled');
|
|
568
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
569
|
+
if (cache !== null) {
|
|
570
|
+
recordAudit(cache.cacheDir, {
|
|
571
|
+
ts: new Date().toISOString(),
|
|
572
|
+
tool: 'ei_changes',
|
|
573
|
+
adapter: 'omp',
|
|
574
|
+
outcome: 'error',
|
|
575
|
+
ms: performance.now() - started,
|
|
576
|
+
engine: engineVersion(),
|
|
577
|
+
code: 'index-failed',
|
|
578
|
+
}, { env, root: cache.root });
|
|
579
|
+
}
|
|
580
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
581
|
+
return errorResult(`index-failed: ${message}. Retry once; if it fails again, continue without ei_changes and say so in your report.`);
|
|
582
|
+
}
|
|
583
|
+
},
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
function registerEiSearch(pi, deps, env, sessions) {
|
|
587
|
+
const z = pi.zod;
|
|
588
|
+
const limitSchema = (() => {
|
|
589
|
+
const base = z.number ? z.number() : z.string();
|
|
590
|
+
const int = base.int ? base.int() : base;
|
|
591
|
+
const min = int.min ? int.min(1) : int;
|
|
592
|
+
const max = min.max ? min.max(20) : min;
|
|
593
|
+
return max.optional().describe('Maximum matches to return (1–20, default 8)');
|
|
594
|
+
})();
|
|
595
|
+
pi.registerTool({
|
|
596
|
+
name: 'ei_search',
|
|
597
|
+
label: 'KSD Code Search',
|
|
598
|
+
description: 'Find where something is implemented when you do not know the symbol name. Give a few words or identifiers ("retry payment webhook", "session cookie parse"). Returns ranked declarations with file:line. For a symbol you can already name, call ei_impact directly.',
|
|
599
|
+
parameters: z.object({
|
|
600
|
+
query: z.string().describe('1–200 characters of words or identifiers to search for'),
|
|
601
|
+
limit: limitSchema,
|
|
602
|
+
}),
|
|
603
|
+
approval: 'read',
|
|
604
|
+
renderCall: (args, options) => renderToolCall('search', args, options),
|
|
605
|
+
renderResult: (result, options) => renderToolResult('search', result, options),
|
|
606
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
607
|
+
if (signal?.aborted)
|
|
608
|
+
return errorResult('Cancelled');
|
|
609
|
+
const started = performance.now();
|
|
610
|
+
const rawQuery = isRecord(params) ? params.query : undefined;
|
|
611
|
+
const rawLimit = isRecord(params) ? params.limit : undefined;
|
|
612
|
+
const recordInvalid = async (queryText, limitVal) => {
|
|
613
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
614
|
+
if (cache === null)
|
|
615
|
+
return;
|
|
616
|
+
recordAudit(cache.cacheDir, {
|
|
617
|
+
ts: new Date().toISOString(),
|
|
618
|
+
tool: 'ei_search',
|
|
619
|
+
adapter: 'omp',
|
|
620
|
+
outcome: 'failure',
|
|
621
|
+
ms: performance.now() - started,
|
|
622
|
+
engine: engineVersion(),
|
|
623
|
+
code: 'INVALID_INPUT',
|
|
624
|
+
codes: ['INVALID_INPUT'],
|
|
625
|
+
...(queryText !== undefined ? { query: queryText } : {}),
|
|
626
|
+
...(limitVal !== undefined && Number.isInteger(limitVal) ? { limit: limitVal } : {}),
|
|
627
|
+
}, { env, root: cache.root });
|
|
628
|
+
};
|
|
629
|
+
try {
|
|
630
|
+
const valid = validateSearchInput(rawQuery, rawLimit);
|
|
631
|
+
if (!valid.ok) {
|
|
632
|
+
await recordInvalid(typeof rawQuery === 'string' ? rawQuery : undefined, typeof rawLimit === 'number' ? rawLimit : undefined);
|
|
633
|
+
return errorResult(`INVALID_INPUT: ${valid.message}`);
|
|
634
|
+
}
|
|
635
|
+
const workspace = await loadWorkspace(ctx?.cwd ?? process.cwd(), deps.cacheHome);
|
|
636
|
+
let session = sessions.get(workspace.cacheDir);
|
|
637
|
+
if (session === undefined) {
|
|
638
|
+
session = new ImpactSession(workspace, deps.impactSession);
|
|
639
|
+
sessions.set(workspace.cacheDir, session);
|
|
640
|
+
}
|
|
641
|
+
const outcome = await runSearch(session, {
|
|
642
|
+
query: valid.query,
|
|
643
|
+
limit: valid.limit,
|
|
644
|
+
signal,
|
|
645
|
+
onProgress: (message, data) => {
|
|
646
|
+
onUpdate?.({ content: [{ type: 'text', text: message }], details: data });
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
if (signal?.aborted)
|
|
650
|
+
return errorResult('Cancelled');
|
|
651
|
+
const text = renderSearchOutcome(outcome);
|
|
652
|
+
if (text === 'Cancelled')
|
|
653
|
+
return errorResult('Cancelled');
|
|
654
|
+
recordAudit(workspace.cacheDir, {
|
|
655
|
+
ts: new Date().toISOString(),
|
|
656
|
+
tool: 'ei_search',
|
|
657
|
+
adapter: 'omp',
|
|
658
|
+
outcome: outcome.kind,
|
|
659
|
+
ms: performance.now() - started,
|
|
660
|
+
engine: engineVersion(),
|
|
661
|
+
...auditFieldsForSearch(outcome, engineVersion(), valid.query, valid.limit),
|
|
662
|
+
}, { env, root: workspace.root });
|
|
663
|
+
if (outcome.kind === 'failure') {
|
|
664
|
+
return { isError: true, content: [{ type: 'text', text }], details: outcome };
|
|
665
|
+
}
|
|
666
|
+
if (outcome.kind === 'guidance') {
|
|
667
|
+
return { content: [{ type: 'text', text }], details: outcome };
|
|
668
|
+
}
|
|
669
|
+
return { content: [{ type: 'text', text }], details: outcome.value };
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
if (signal?.aborted)
|
|
673
|
+
return errorResult('Cancelled');
|
|
674
|
+
const cache = await tryResolveCache(ctx?.cwd, deps.cacheHome);
|
|
675
|
+
if (cache !== null) {
|
|
676
|
+
recordAudit(cache.cacheDir, {
|
|
677
|
+
ts: new Date().toISOString(),
|
|
678
|
+
tool: 'ei_search',
|
|
679
|
+
adapter: 'omp',
|
|
680
|
+
outcome: 'error',
|
|
681
|
+
ms: performance.now() - started,
|
|
682
|
+
engine: engineVersion(),
|
|
683
|
+
code: 'index-failed',
|
|
684
|
+
...(typeof rawQuery === 'string' ? { query: rawQuery } : {}),
|
|
685
|
+
}, { env, root: cache.root });
|
|
686
|
+
}
|
|
687
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
688
|
+
return errorResult(`index-failed: ${message}. Retry once; if it fails again, continue without ei_search and say so in your report.`);
|
|
689
|
+
}
|
|
690
|
+
},
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
const LEARNING_DESCRIPTION = 'Read the project decisions recorded for code you are about to change, or propose one. `action: "list"` with an optional `target` (path#name or a file path) returns recorded learnings as quoted data with their source and status; only an unchanged owner-confirmed or test-verified learning is a decision, everything else is an unconfirmed note. `action: "propose"` with `claim`, `target` and `source` ("model-inferred" or "code-observed") stores a proposal for the owner to approve; it never writes to the repository.';
|
|
694
|
+
function registerEiLearning(pi, deps, sessions) {
|
|
695
|
+
const z = pi.zod;
|
|
696
|
+
pi.registerTool({
|
|
697
|
+
name: 'ei_learning',
|
|
698
|
+
label: 'KSD Project Learnings',
|
|
699
|
+
description: LEARNING_DESCRIPTION,
|
|
700
|
+
parameters: z.object({
|
|
701
|
+
action: z.enum(['list', 'propose']),
|
|
702
|
+
target: z.string().optional().describe('path#name or a repository file path'),
|
|
703
|
+
claim: z
|
|
704
|
+
.string()
|
|
705
|
+
.optional()
|
|
706
|
+
.describe('propose: the decision in one or two sentences (max 1,000 characters)'),
|
|
707
|
+
source: z.enum(['model-inferred', 'code-observed']).optional(),
|
|
708
|
+
}),
|
|
709
|
+
approval: 'read',
|
|
710
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
711
|
+
if (signal?.aborted)
|
|
712
|
+
return errorResult('Cancelled');
|
|
713
|
+
try {
|
|
714
|
+
const action = isRecord(params) ? params.action : undefined;
|
|
715
|
+
if (action !== 'list' && action !== 'propose') {
|
|
716
|
+
return errorResult('INVALID_INPUT: action must be "list" or "propose"');
|
|
717
|
+
}
|
|
718
|
+
const workspace = await loadWorkspace(ctx?.cwd ?? process.cwd(), deps.cacheHome);
|
|
719
|
+
let session = sessions.get(workspace.cacheDir);
|
|
720
|
+
if (session === undefined) {
|
|
721
|
+
session = new ImpactSession(workspace, deps.impactSession);
|
|
722
|
+
sessions.set(workspace.cacheDir, session);
|
|
723
|
+
}
|
|
724
|
+
if (action === 'propose') {
|
|
725
|
+
const outcome = await withAnchorIndex(session, (index) => proposeLearning(workspace, index, params), signal);
|
|
726
|
+
if (outcome.kind === 'failure')
|
|
727
|
+
return errorResult(`${outcome.code}: ${outcome.message}`);
|
|
728
|
+
const text = [
|
|
729
|
+
`PROPOSED ${outcome.value.id} — ${PROPOSAL_LABEL}; stored outside the repository`,
|
|
730
|
+
` > ${quoteClaim(outcome.value.claim)}`,
|
|
731
|
+
'Next: tell the owner; it takes effect only after `ei learning approve`.',
|
|
732
|
+
].join('\n');
|
|
733
|
+
return { content: [{ type: 'text', text }], details: outcome.value };
|
|
734
|
+
}
|
|
735
|
+
const target = isRecord(params) && typeof params.target === 'string' ? params.target.trim() : '';
|
|
736
|
+
const snap = await withAnchorIndex(session, (index) => snapshot(workspace, index), signal);
|
|
737
|
+
const scoped = target === ''
|
|
738
|
+
? snap
|
|
739
|
+
: {
|
|
740
|
+
...snap,
|
|
741
|
+
learnings: learningsFor(snap.learnings, [target]),
|
|
742
|
+
proposals: learningsFor(snap.proposals, [target]),
|
|
743
|
+
};
|
|
744
|
+
const text = renderLearningList({ scope: target === '' ? 'all' : target, ...scoped });
|
|
745
|
+
return { content: [{ type: 'text', text }], details: scoped };
|
|
746
|
+
}
|
|
747
|
+
catch (error) {
|
|
748
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
749
|
+
return errorResult(`ei_learning failed: ${message}. Continue without learnings and say so.`);
|
|
750
|
+
}
|
|
751
|
+
},
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
// A call naming a check runs a process, so it asks at OMP's `exec` tier; reading a file is `read`.
|
|
755
|
+
function verifyApproval(args) {
|
|
756
|
+
if (isRecord(args) && typeof args.report === 'string' && args.check === undefined)
|
|
757
|
+
return 'read';
|
|
758
|
+
return 'exec';
|
|
759
|
+
}
|
|
760
|
+
function registerEiVerify(pi, deps, env, loadConfig) {
|
|
761
|
+
const z = pi.zod;
|
|
762
|
+
const checkNames = (loadConfig.verification.checks ?? []).map((check) => check.name);
|
|
763
|
+
const reportNames = (loadConfig.verification.reports ?? []).map((report) => report.name);
|
|
764
|
+
const configured = [
|
|
765
|
+
checkNames.length > 0 ? `Checks: ${checkNames.join(', ')}.` : 'No checks configured.',
|
|
766
|
+
reportNames.length > 0 ? `Result files: ${reportNames.join(', ')}.` : '',
|
|
767
|
+
]
|
|
768
|
+
.filter((part) => part !== '')
|
|
769
|
+
.join(' ');
|
|
770
|
+
pi.registerTool({
|
|
771
|
+
name: 'ei_verify',
|
|
772
|
+
label: 'KSD Verification Evidence',
|
|
773
|
+
description: `Before you say tests, typecheck or lint pass, call this to get a recorded result. Pass \`check\` with a name the owner configured; it runs that exact command and returns PASS, FAIL, SKIPPED, ERROR or NOT_VERIFIED with the git revision. Pass \`report\` instead to read a configured JUnit/TAP file. Only a PASS result supports a claim that tests pass. Running a check asks for approval. ${configured}`.trim(),
|
|
774
|
+
parameters: z.object({
|
|
775
|
+
check: z.string().optional().describe('Name of an owner-configured check, e.g. "test"'),
|
|
776
|
+
report: z.string().optional().describe('Name of an owner-configured result file'),
|
|
777
|
+
}),
|
|
778
|
+
approval: verifyApproval,
|
|
779
|
+
formatApprovalDetails: (args) => {
|
|
780
|
+
if (!isRecord(args) || typeof args.check !== 'string')
|
|
781
|
+
return undefined;
|
|
782
|
+
const name = args.check;
|
|
783
|
+
// Show the argv that will run, read fresh from the committed config.
|
|
784
|
+
const config = readProjectConfigSync(deps.cwd ?? process.cwd());
|
|
785
|
+
const check = config?.verification.checks?.find((entry) => entry.name === name);
|
|
786
|
+
return check === undefined
|
|
787
|
+
? [`Check "${name}" is not configured; nothing will run`]
|
|
788
|
+
: [`Command: ${check.command.join(' ')}`, `Timeout: ${check.timeoutSec} s`];
|
|
789
|
+
},
|
|
790
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
791
|
+
if (signal?.aborted)
|
|
792
|
+
return errorResult('Cancelled');
|
|
793
|
+
try {
|
|
794
|
+
const valid = validateVerifyInput(params);
|
|
795
|
+
if (!valid.ok)
|
|
796
|
+
return errorResult(`INVALID_INPUT: ${valid.message}`);
|
|
797
|
+
const workspace = await loadWorkspace(ctx?.cwd ?? process.cwd(), deps.cacheHome);
|
|
798
|
+
const outcome = await runVerification(workspace, valid.request, {
|
|
799
|
+
env,
|
|
800
|
+
signal,
|
|
801
|
+
...(deps.verifyRunner === undefined ? {} : { runner: deps.verifyRunner }),
|
|
802
|
+
});
|
|
803
|
+
const text = renderVerifyOutcome(outcome, engineVersion());
|
|
804
|
+
if (outcome.kind === 'failure')
|
|
805
|
+
return errorResult(text);
|
|
806
|
+
return { content: [{ type: 'text', text }], details: outcome.value };
|
|
807
|
+
}
|
|
808
|
+
catch (error) {
|
|
809
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
810
|
+
return errorResult(`NOT_VERIFIED: ei_verify could not complete (${message}). Do not claim tests pass.`);
|
|
811
|
+
}
|
|
812
|
+
},
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
// Advisory tool: every failure becomes an error result for the agent, never a crashed session.
|
|
816
|
+
export default function ksdIntelligenceExtension(pi, deps = {}) {
|
|
817
|
+
const env = deps.env ?? process.env;
|
|
818
|
+
const startPolicy = deps.createPolicyExtension ??
|
|
819
|
+
((api) => createPolicyExtension(api, { defaultIntelligenceMode: 'native', label: 'ksd-intelligence' }));
|
|
820
|
+
try {
|
|
821
|
+
startPolicy(pi);
|
|
822
|
+
}
|
|
823
|
+
catch (error) {
|
|
824
|
+
warnLoad('KSD policy module', error);
|
|
825
|
+
}
|
|
826
|
+
if (env.EI_DISABLED === '1')
|
|
827
|
+
return;
|
|
828
|
+
const sessions = new Map();
|
|
829
|
+
try {
|
|
830
|
+
registerEiWorkflow(pi, env, deps.lockPath ?? defaultLockPath(), deps.skillsDir, deps.cacheHome);
|
|
831
|
+
}
|
|
832
|
+
catch (error) {
|
|
833
|
+
warnLoad('ei_workflow tool', error);
|
|
834
|
+
}
|
|
835
|
+
try {
|
|
836
|
+
registerEiStatus(pi, deps, env);
|
|
837
|
+
}
|
|
838
|
+
catch (error) {
|
|
839
|
+
warnLoad('ei_status tool', error);
|
|
840
|
+
}
|
|
841
|
+
try {
|
|
842
|
+
registerEiImpact(pi, deps, env, sessions);
|
|
843
|
+
}
|
|
844
|
+
catch (error) {
|
|
845
|
+
warnLoad('ei_impact tool', error);
|
|
846
|
+
}
|
|
847
|
+
try {
|
|
848
|
+
registerEiChanges(pi, deps, env, sessions);
|
|
849
|
+
}
|
|
850
|
+
catch (error) {
|
|
851
|
+
warnLoad('ei_changes tool', error);
|
|
852
|
+
}
|
|
853
|
+
try {
|
|
854
|
+
registerEiSearch(pi, deps, env, sessions);
|
|
855
|
+
}
|
|
856
|
+
catch (error) {
|
|
857
|
+
warnLoad('ei_search tool', error);
|
|
858
|
+
}
|
|
859
|
+
let config;
|
|
860
|
+
try {
|
|
861
|
+
config = readProjectConfigSync(deps.cwd ?? process.cwd());
|
|
862
|
+
}
|
|
863
|
+
catch (error) {
|
|
864
|
+
warnLoad('V2 tool configuration', error);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
if (config === null)
|
|
868
|
+
return;
|
|
869
|
+
// Keep registration failures isolated so one module cannot hide the other.
|
|
870
|
+
try {
|
|
871
|
+
if (config.knowledge.enabled)
|
|
872
|
+
registerEiLearning(pi, deps, sessions);
|
|
873
|
+
}
|
|
874
|
+
catch (error) {
|
|
875
|
+
warnLoad('ei_learning tool', error);
|
|
876
|
+
}
|
|
877
|
+
try {
|
|
878
|
+
if (config.verification.enabled)
|
|
879
|
+
registerEiVerify(pi, deps, env, config);
|
|
880
|
+
}
|
|
881
|
+
catch (error) {
|
|
882
|
+
warnLoad('ei_verify tool', error);
|
|
883
|
+
}
|
|
884
|
+
}
|